Cairn is a general-purpose AI state-space search engine, validated first on autonomous penetration testing. Sometimes misspelled as Carin.
Python aiai-agentai-cybersecurityai-hackerai-hackingblackbox-testingctfctf-toolsllmpenetration-testingpentestingred-teamingsecurity-automationsecurity-tools
feat: add local execution mode for host-run workers
leixiao233f5e8505b9
diff --git a/README.md b/README.mdindex f281d6e..9b69116 100644--- a/README.md+++ b/README.md@@ -103,6 +103,8 @@ System architecture:**Cairn Dispatcher** reads the graph, schedules tasks, spins up and tears down worker containers, and is the sole writer to the protocol. Each project gets its own Worker Container; multiple Agent Workers run concurrently inside it. Agent Workers only receive a prompt and return structured output.+Workers can also run directly on the dispatcher host instead of in per-project containers — **local mode**, no Docker required. See [Local mode](#local-mode-no-docker) below.+Supported worker backends: **Claude Code**, **Codex**, and **Pi**.## Results@@ -129,7 +131,7 @@ Supported worker backends: **Claude Code**, **Codex**, and **Pi**.- macOS or Linux- Python ≥ 3.12-- Docker+- Docker (container execution only — not needed for local mode)### Pull required images@@ -173,6 +175,22 @@ uv run --project cairn cairn dispatch --config dispatch.yamluv run --project cairn cairn dispatch --config dispatch.yaml --startup-healthcheck-only```+### Local mode (no Docker)++Instead of one container per project, workers can run directly on the dispatcher host, reusing the machine's already-configured `claude` / `codex` / `pi` CLIs — no Docker, and no API keys in the config.++```bash+cp dispatch.local.example.yaml dispatch.yaml++# Start the server+uv run --project cairn cairn serve++# Run the dispatcher on the same host, where the CLIs are installed and logged in+uv run --project cairn cairn dispatch --config dispatch.yaml+```++Local mode is selected by `runtime.execution: local` (see `dispatch.local.example.yaml`). On startup the dispatcher checks each configured worker CLI is installed and runnable, and reminds you they must already be logged in. Each project gets an isolated working directory under `local.workspace_root` (default: the dispatcher's current directory). Run the dispatcher directly on the host — not inside Docker — since the agents run with your user's permissions and no sandbox.+### TestsRun the fast regression suite without Docker or live model endpoints:diff --git a/cairn/src/cairn/dispatcher/config.py b/cairn/src/cairn/dispatcher/config.pyindex 7dc2540..ff76161 100644--- a/cairn/src/cairn/dispatcher/config.py+++ b/cairn/src/cairn/dispatcher/config.py@@ -14,6 +14,8 @@ TaskType = Literal["reason", "explore", "bootstrap"]WorkerType = Literal["claudecode", "codex", "pi", "mock"]CompletedAction = Literal["remove", "stop"]WorkerHealthcheckMode = Literal["startup_and_task", "startup_only", "disabled"]+ExecutionMode = Literal["container", "local"]+LocalCompletedAction = Literal["keep", "remove"]WORKER_ENV_KEYS: dict[WorkerType, tuple[str, ...]] = {"claudecode": (@@ -155,6 +157,11 @@ class ContainerConfig(BaseModel):cap_add: list[str] = Field(default_factory=list)+class LocalConfig(BaseModel):+ workspace_root: str | None = None+ completed_action: LocalCompletedAction = "keep"++class RuntimeConfig(BaseModel):max_workers: int = Field(gt=0)max_running_projects: int = Field(gt=0)@@ -162,6 +169,7 @@ class RuntimeConfig(BaseModel):interval: int = Field(gt=0)healthcheck_timeout: int = Field(gt=0)worker_healthcheck: WorkerHealthcheckMode = "startup_only"+ execution: ExecutionMode = "container"prompt_group: str = Field(min_length=1)@@ -186,10 +194,9 @@ class WorkerConfig(BaseModel):@model_validator(mode="after")def validate_env(self) -> "WorkerConfig":- required = WORKER_ENV_KEYS[self.type]- missing = [key for key in required if not self.env.get(key)]- if missing:- raise ValueError(f"worker {self.name} missing env keys: {', '.join(missing)}")+ # Required LLM env keys (base_url / key / model) are enforced per execution mode by+ # DispatchConfig: container mode needs them, local mode reuses the host CLI config.+ # The checks below are mode-independent and always apply.if self.type == "pi":_validate_optional_positive_int_env(self.name, self.env, "PI_MODEL_CONTEXT_WINDOW")if self.type == "mock":@@ -203,7 +210,8 @@ class DispatchConfig(BaseModel):server: strruntime: RuntimeConfigtasks: TasksConfig- container: ContainerConfig+ container: ContainerConfig | None = None+ local: LocalConfig | None = Nonecommon_env: dict[str, str] = Field(default_factory=dict)workers: list[WorkerConfig]@@ -248,6 +256,21 @@ class DispatchConfig(BaseModel):raise ValueError("max_project_workers cannot exceed max_workers")return self+ @model_validator(mode="after")+ def validate_execution_mode(self) -> "DispatchConfig":+ if self.runtime.execution == "container":+ if self.container is None:+ raise ValueError("container config is required when runtime.execution is container")+ for worker in self.workers:+ required = WORKER_ENV_KEYS[worker.type]+ missing = [key for key in required if not worker.env.get(key)]+ if missing:+ raise ValueError(f"worker {worker.name} missing env keys: {', '.join(missing)}")+ else: # local: workers reuse the host CLI config, so no LLM env keys are required+ if self.local is None:+ self.local = LocalConfig()+ return self+@classmethoddef load(cls, path: Path) -> "DispatchConfig":data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}diff --git a/cairn/src/cairn/dispatcher/runtime/backend.py b/cairn/src/cairn/dispatcher/runtime/backend.pynew file mode 100644index 0000000..d889984--- /dev/null+++ b/cairn/src/cairn/dispatcher/runtime/backend.py@@ -0,0 +1,45 @@+from __future__ import annotations++from typing import Protocol, runtime_checkable++from cairn.dispatcher.runtime.process import ExecProcess+++@runtime_checkable+class ExecutionBackend(Protocol):+ """The execution substrate for worker processes.++ Two implementations exist: ContainerManager (one Docker container per project) and+ LocalBackend (host subprocesses, one working directory per project). The scheduler,+ task runners and startup healthcheck only depend on this surface so the two backends+ are interchangeable behind a single ``runtime.execution`` switch.+ """++ def container_name(self, project_id: str) -> str: ...++ def ensure_running(self, project_id: str) -> str: ...++ def build_exec_process(+ self,+ container_name: str,+ env: dict[str, str],+ command: list[str],+ timeout_seconds: int | None = None,+ kill_after_seconds: int = 5,+ ) -> ExecProcess: ...++ def write_text_file(self, container_name: str, path: str, content: str) -> None: ...++ def create_startup_container(self) -> str: ...++ def remove_container(self, name: str, *, force: bool = True) -> None: ...++ def needs_completed_cleanup(self, project_id: str) -> bool: ...++ def needs_stopped_cleanup(self, project_id: str) -> bool: ...++ def cleanup_completed(self, project_id: str) -> bool: ...++ def cleanup_stopped(self, project_id: str) -> bool: ...++ def close(self) -> None: ...diff --git a/cairn/src/cairn/dispatcher/runtime/cancellation.py b/cairn/src/cairn/dispatcher/runtime/cancellation.pyindex 4c6aef0..4d208a8 100644--- a/cairn/src/cairn/dispatcher/runtime/cancellation.py+++ b/cairn/src/cairn/dispatcher/runtime/cancellation.py@@ -2,16 +2,16 @@ from __future__ import annotationsimport threading-from cairn.dispatcher.runtime.process import ManagedProcess+from cairn.dispatcher.runtime.process import ExecProcessclass TaskCancellation:def __init__(self) -> None:self._lock = threading.Lock()- self._process: ManagedProcess | None = None+ self._process: ExecProcess | None = Noneself._reason: str | None = None- def attach_process(self, process: ManagedProcess | None) -> None:+ def attach_process(self, process: ExecProcess | None) -> None:with self._lock:self._process = processreason = self._reasondiff --git a/cairn/src/cairn/dispatcher/runtime/heartbeat.py b/cairn/src/cairn/dispatcher/runtime/heartbeat.pyindex c31bb0b..2518dae 100644--- a/cairn/src/cairn/dispatcher/runtime/heartbeat.py+++ b/cairn/src/cairn/dispatcher/runtime/heartbeat.py@@ -7,7 +7,7 @@ from collections.abc import Callablefrom dataclasses import dataclassfrom cairn.dispatcher.protocol.client import ApiResult, CairnClient-from cairn.dispatcher.runtime.process import ManagedProcess+from cairn.dispatcher.runtime.process import ExecProcessLOG = logging.getLogger(__name__)@@ -32,7 +32,7 @@ class HeartbeatLease:self._scope = scopeself._worker_name = worker_nameself._interval = interval- self._process: ManagedProcess | None = None+ self._process: ExecProcess | None = Noneself._failure: HeartbeatFailure | None = Noneself._last_success_at = time.monotonic()self._stop = threading.Event()@@ -77,7 +77,7 @@ class HeartbeatLease:self._stop.set()self._thread.join(timeout=1)- def attach_process(self, process: ManagedProcess | None) -> None:+ def attach_process(self, process: ExecProcess | None) -> None:with self._lock:self._process = processdiff --git a/cairn/src/cairn/dispatcher/runtime/local_backend.py b/cairn/src/cairn/dispatcher/runtime/local_backend.pynew file mode 100644index 0000000..a25f9af--- /dev/null+++ b/cairn/src/cairn/dispatcher/runtime/local_backend.py@@ -0,0 +1,91 @@+from __future__ import annotations++import logging+import os+import shutil+from pathlib import Path++from cairn.dispatcher.config import LocalConfig+from cairn.dispatcher.runtime.local_process import LocalProcess++LOG = logging.getLogger(__name__)+++class LocalBackend:+ """Runs workers directly on the dispatcher host instead of in per-project containers.++ Each project gets an isolated working directory under ``workspace_root`` (defaulting+ to the directory the dispatcher was started in). Worker processes inherit the host+ environment so the pre-configured ``claude`` / ``codex`` / ``pi`` CLIs and their+ credentials are used as-is; no API keys are injected. There are no containers to+ build or tear down, so the container-lifecycle methods are inert.+ """++ def __init__(self, config: LocalConfig):+ self._config = config+ root = config.workspace_root+ self._root = Path(root).expanduser() if root else Path.cwd()++ def close(self) -> None:+ return None++ def container_name(self, project_id: str) -> str:+ return str(self._project_dir(project_id))++ def ensure_running(self, project_id: str) -> str:+ project_dir = self._project_dir(project_id)+ project_dir.mkdir(parents=True, exist_ok=True)+ LOG.debug("local project workdir ready project=%s dir=%s", project_id, project_dir)+ return str(project_dir)++ def build_exec_process(+ self,+ container_name: str,+ env: dict[str, str],+ command: list[str],+ timeout_seconds: int | None = None,+ kill_after_seconds: int = 5,+ ) -> LocalProcess:+ merged_env = {**os.environ, **(env or {})}+ return LocalProcess(+ command,+ cwd=container_name,+ env=merged_env,+ timeout_seconds=timeout_seconds,+ term_grace_seconds=kill_after_seconds,+ )++ def write_text_file(self, container_name: str, path: str, content: str) -> None:+ target = Path(path)+ if not target.is_absolute():+ raise ValueError(f"local file path must be absolute: {path}")+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_text(content, encoding="utf-8")++ def create_startup_container(self) -> str:+ raise RuntimeError("startup healthcheck container is not used in local execution mode")++ def remove_container(self, name: str, *, force: bool = True) -> None:+ return None++ def needs_completed_cleanup(self, project_id: str) -> bool:+ return self._config.completed_action == "remove" and self._project_dir(project_id).exists()++ def needs_stopped_cleanup(self, project_id: str) -> bool:+ return False++ def cleanup_completed(self, project_id: str) -> bool:+ if self._config.completed_action == "remove":+ project_dir = self._project_dir(project_id)+ LOG.info("removing completed project workdir project=%s dir=%s", project_id, project_dir)+ shutil.rmtree(project_dir, ignore_errors=True)+ return True++ def cleanup_stopped(self, project_id: str) -> bool:+ return True++ def managed_container_names(self) -> list[str]:+ return []++ def _project_dir(self, project_id: str) -> Path:+ return self._root / project_id.replace("/", "-")diff --git a/cairn/src/cairn/dispatcher/runtime/local_process.py b/cairn/src/cairn/dispatcher/runtime/local_process.pynew file mode 100644index 0000000..fa7ad36--- /dev/null+++ b/cairn/src/cairn/dispatcher/runtime/local_process.py@@ -0,0 +1,135 @@+from __future__ import annotations++import logging+import os+import signal+import subprocess+import threading+from contextlib import suppress++from cairn.dispatcher.runtime.process import ProcessResult++LOG = logging.getLogger(__name__)++READ_CHUNK_SIZE = 65536+STREAM_JOIN_TIMEOUT_SECONDS = 5.0+FORCE_KILL_REAP_TIMEOUT_SECONDS = 2.0+++class LocalProcess:+ """Runs a worker command as a host subprocess.++ Mirrors the container ManagedProcess surface (start/communicate/kill/cancel) but+ executes on the dispatcher host: its own process group so children are killed as a+ group, a Python-enforced timeout instead of the ``timeout`` coreutil, and a+ SIGTERM -> grace -> SIGKILL shutdown so the CLI can flush its session before dying.+ """++ def __init__(+ self,+ command: list[str],+ cwd: str,+ env: dict[str, str],+ timeout_seconds: int | None = None,+ term_grace_seconds: int = 5,+ ):+ self.command = command+ self.env = env+ self._cwd = cwd+ self._timeout_seconds = timeout_seconds+ self._term_grace = max(1.0, float(term_grace_seconds))+ self._process: subprocess.Popen[str] | None = None+ self._stdout_chunks: list[str] = []+ self._stderr_chunks: list[str] = []+ self._stdout_thread: threading.Thread | None = None+ self._stderr_thread: threading.Thread | None = None+ self._timed_out = False+ self._cancel_reason: str | None = None+ self._kill_lock = threading.Lock()++ def start(self) -> None:+ self._process = subprocess.Popen(+ self.command,+ cwd=self._cwd,+ env=self.env,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ encoding="utf-8",+ errors="replace",+ start_new_session=True,+ )+ self._stdout_thread = threading.Thread(+ target=self._drain, args=(self._process.stdout, self._stdout_chunks), daemon=True+ )+ self._stderr_thread = threading.Thread(+ target=self._drain, args=(self._process.stderr, self._stderr_chunks), daemon=True+ )+ self._stdout_thread.start()+ self._stderr_thread.start()++ def communicate(self, timeout: float | None) -> ProcessResult:+ assert self._process is not None+ wait_for = float(self._timeout_seconds) if self._timeout_seconds is not None else timeout+ try:+ self._process.wait(timeout=wait_for)+ except subprocess.TimeoutExpired:+ self._timed_out = True+ self._terminate()+ with suppress(subprocess.TimeoutExpired):+ self._process.wait(timeout=FORCE_KILL_REAP_TIMEOUT_SECONDS)+ if self._stdout_thread is not None:+ self._stdout_thread.join(timeout=STREAM_JOIN_TIMEOUT_SECONDS)+ if self._stderr_thread is not None:+ self._stderr_thread.join(timeout=STREAM_JOIN_TIMEOUT_SECONDS)+ returncode = self._process.returncode+ if returncode is None:+ returncode = 137 if self._timed_out else 1+ return ProcessResult(+ returncode=returncode,+ stdout="".join(self._stdout_chunks),+ stderr="".join(self._stderr_chunks),+ timed_out=self._timed_out,+ cancelled=self._cancel_reason is not None,+ cancel_reason=self._cancel_reason,+ )++ def kill(self) -> None:+ self._terminate()++ def cancel(self, reason: str) -> None:+ if self._cancel_reason is None:+ self._cancel_reason = reason+ self._terminate()++ def _terminate(self) -> None:+ with self._kill_lock:+ process = self._process+ if process is None or process.poll() is not None:+ return+ self._signal_group(process, signal.SIGTERM)+ try:+ process.wait(timeout=self._term_grace)+ return+ except subprocess.TimeoutExpired:+ pass+ self._signal_group(process, signal.SIGKILL)++ @staticmethod+ def _signal_group(process: subprocess.Popen[str], sig: int) -> None:+ try:+ os.killpg(os.getpgid(process.pid), sig)+ except (ProcessLookupError, PermissionError):+ with suppress(ProcessLookupError, PermissionError, ValueError):+ process.send_signal(sig)++ @staticmethod+ def _drain(pipe, sink: list[str]) -> None:+ try:+ for chunk in iter(lambda: pipe.read(READ_CHUNK_SIZE), ""):+ sink.append(chunk)+ except (ValueError, OSError):+ pass+ finally:+ with suppress(Exception):+ pipe.close()diff --git a/cairn/src/cairn/dispatcher/runtime/process.py b/cairn/src/cairn/dispatcher/runtime/process.pyindex b3af0d7..06c3d17 100644--- a/cairn/src/cairn/dispatcher/runtime/process.py+++ b/cairn/src/cairn/dispatcher/runtime/process.py@@ -5,7 +5,7 @@ from dataclasses import dataclassimport loggingimport threadingimport time-from typing import Any+from typing import Any, Protocol, runtime_checkablefrom docker.errors import APIError, DockerExceptionfrom docker.models.containers import Container@@ -24,6 +24,23 @@ class ProcessResult:cancel_reason: str | None = None+@runtime_checkable+class ExecProcess(Protocol):+ """A worker process, regardless of whether it runs inside a container or on the host.++ Container mode uses ManagedProcess; local mode uses LocalProcess. Both expose this+ surface so the task runners, heartbeat lease and cancellation stay backend-agnostic.+ """++ def start(self) -> None: ...++ def communicate(self, timeout: float | None) -> ProcessResult: ...++ def kill(self) -> None: ...++ def cancel(self, reason: str) -> None: ...++class ManagedProcess:def __init__(self, container: Container, command: list[str], env: dict[str, str]):self.command = commanddiff --git a/cairn/src/cairn/dispatcher/scheduler/loop.py b/cairn/src/cairn/dispatcher/scheduler/loop.pyindex 77eb546..3d33066 100644--- a/cairn/src/cairn/dispatcher/scheduler/loop.py+++ b/cairn/src/cairn/dispatcher/scheduler/loop.py@@ -1,6 +1,8 @@from __future__ import annotationsimport logging+import shutil+import subprocessimport timefrom concurrent.futures import Future, ThreadPoolExecutorfrom dataclasses import dataclass@@ -8,13 +10,15 @@ from pathlib import Pathimport requests-from cairn.dispatcher.config import DispatchConfig, WorkerConfig+from cairn.dispatcher.config import DispatchConfig, LocalConfig, WorkerConfigfrom cairn.dispatcher.models import ReasonCheckpoint, RunningTaskfrom cairn.dispatcher.protocol.client import CairnClientfrom cairn.dispatcher.runtime.cancellation import TaskCancellationfrom cairn.dispatcher.runtime.containers import ContainerManager+from cairn.dispatcher.runtime.local_backend import LocalBackendfrom cairn.dispatcher.runtime.startup_healthcheck import format_failure_summary, run_startup_healthchecksfrom cairn.dispatcher.scheduler.worker_select import choose_worker+from cairn.dispatcher.workers.registry import get_driverfrom cairn.dispatcher.tasks.bootstrap import run_bootstrap_taskfrom cairn.dispatcher.tasks.explore import run_explore_taskfrom cairn.dispatcher.tasks.reason import run_reason_task@@ -41,7 +45,11 @@ class DispatcherLoop:self.config_path = config_pathself.config = DispatchConfig.load(config_path)self.client = CairnClient(self.config.server)- self.container_manager = ContainerManager(self.config.container)+ if self.config.runtime.execution == "local":+ self.container_manager = LocalBackend(self.config.local or LocalConfig())+ else:+ assert self.config.container is not None+ self.container_manager = ContainerManager(self.config.container)self.executor = ThreadPoolExecutor(max_workers=self.config.runtime.max_workers)self.cleanup_executor = ThreadPoolExecutor(max_workers=max(1, min(8, self.config.runtime.max_workers)))self.futures: dict[Future[str], RunningTask] = {}@@ -110,6 +118,10 @@ class DispatcherLoop:def run_startup_healthchecks(self, *, show_commands: bool = False, force: bool = False) -> None:if self._startup_healthchecks_checked:return+ if self.config.runtime.execution == "local":+ self._run_local_binary_check()+ self._startup_healthchecks_checked = True+ returnif not force and self.config.runtime.worker_healthcheck == "disabled":LOG.info("skip startup worker healthchecks because runtime.worker_healthcheck=disabled")self._startup_healthchecks_checked = True@@ -117,6 +129,65 @@ class DispatcherLoop:self._run_startup_healthchecks(show_commands=show_commands)self._startup_healthchecks_checked = True+ def _run_local_binary_check(self) -> None:+ binaries: dict[str, list[str]] = {}+ for worker in self.config.workers:+ binary = get_driver(worker.type, "local").local_binary()+ if binary is None:+ continue+ binaries.setdefault(binary, []).append(worker.name)+ if not binaries:+ return++ LOG.info("[*] Local execution: checking %d worker CLI(s) on this host", len(binaries))+ available: list[str] = []+ missing: list[str] = []+ for binary in sorted(binaries):+ workers = ", ".join(sorted(binaries[binary]))+ path, runnable = self._probe_local_cli(binary)+ if path is None:+ missing.append(binary)+ LOG.error("[-] %-8s not found on PATH (workers: %s)", binary, workers)+ elif runnable:+ available.append(binary)+ LOG.info("[+] %-8s %s (workers: %s)", binary, path, workers)+ else:+ available.append(binary)+ LOG.warning("[!] %-8s %s found but `%s --help` failed (workers: %s)", binary, path, binary, workers)++ if not available:+ raise RuntimeError(+ "local execution: none of the configured worker CLIs are installed on PATH ("+ + ", ".join(sorted(binaries))+ + "). Install them and make sure each runs directly from your shell, then retry."+ )+ if missing:+ LOG.warning(+ "[!] Missing CLIs, their workers cannot run: %s. Install them or drop those workers.",+ ", ".join(sorted(missing)),+ )+ LOG.warning(+ "[!] Local mode uses each CLI's own host config: make sure %s already logged in / "+ "configured and usable directly (e.g. `claude -p ...` works) — Cairn injects no API keys.",+ ", ".join(sorted(available)),+ )++ @staticmethod+ def _probe_local_cli(binary: str) -> tuple[str | None, bool]:+ path = shutil.which(binary)+ if path is None:+ return None, False+ try:+ result = subprocess.run(+ [binary, "--help"],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ timeout=15,+ )+ except (OSError, subprocess.SubprocessError):+ return path, False+ return path, result.returncode == 0+def _dispatch_available(self, summaries: list[ProjectSummary]) -> None:if len(self.futures) >= self.config.runtime.max_workers:self._log_changed(diff --git a/cairn/src/cairn/dispatcher/tasks/bootstrap.py b/cairn/src/cairn/dispatcher/tasks/bootstrap.pyindex 568da24..cc6b060 100644--- a/cairn/src/cairn/dispatcher/tasks/bootstrap.py+++ b/cairn/src/cairn/dispatcher/tasks/bootstrap.py@@ -41,7 +41,7 @@ def run_bootstrap_task(worker: WorkerConfig,cancellation: TaskCancellation,) -> str:- driver = get_driver(worker.type)+ driver = get_driver(worker.type, config.runtime.execution)task_started = time.perf_counter()healthcheck_timeout = config.runtime.healthcheck_timeoutlease = HeartbeatLease.for_intent(client, project.project.id, intent.id, worker.name, config.runtime.interval)diff --git a/cairn/src/cairn/dispatcher/tasks/common.py b/cairn/src/cairn/dispatcher/tasks/common.pyindex c6d1126..c8f4571 100644--- a/cairn/src/cairn/dispatcher/tasks/common.py+++ b/cairn/src/cairn/dispatcher/tasks/common.py@@ -55,6 +55,8 @@ def communicate_timeout(timeout_seconds: int, grace_seconds: int = PROCESS_COMMUdef task_healthcheck_enabled(config: DispatchConfig) -> bool:+ if config.runtime.execution == "local":+ return Falsereturn config.runtime.worker_healthcheck == "startup_and_task"diff --git a/cairn/src/cairn/dispatcher/tasks/explore.py b/cairn/src/cairn/dispatcher/tasks/explore.pyindex fef8b8f..e065c79 100644--- a/cairn/src/cairn/dispatcher/tasks/explore.py+++ b/cairn/src/cairn/dispatcher/tasks/explore.py@@ -38,7 +38,7 @@ def run_explore_task(worker: WorkerConfig,cancellation: TaskCancellation,) -> str:- driver = get_driver(worker.type)+ driver = get_driver(worker.type, config.runtime.execution)task_started = time.perf_counter()healthcheck_timeout = config.runtime.healthcheck_timeoutlease = HeartbeatLease.for_intent(client, project.project.id, intent.id, worker.name, config.runtime.interval)diff --git a/cairn/src/cairn/dispatcher/tasks/reason.py b/cairn/src/cairn/dispatcher/tasks/reason.pyindex b67f0e9..2e14442 100644--- a/cairn/src/cairn/dispatcher/tasks/reason.py+++ b/cairn/src/cairn/dispatcher/tasks/reason.py@@ -40,7 +40,7 @@ def run_reason_task(worker: WorkerConfig,cancellation: TaskCancellation,) -> str:- driver = get_driver(worker.type)+ driver = get_driver(worker.type, config.runtime.execution)task_started = time.perf_counter()healthcheck_timeout = config.runtime.healthcheck_timeoutlease = HeartbeatLease.for_reason(client, project.project.id, worker.name, config.runtime.interval)diff --git a/cairn/src/cairn/dispatcher/workers/adapters/claudecode.py b/cairn/src/cairn/dispatcher/workers/adapters/claudecode.pyindex d384f7b..13495da 100644--- a/cairn/src/cairn/dispatcher/workers/adapters/claudecode.py+++ b/cairn/src/cairn/dispatcher/workers/adapters/claudecode.py@@ -11,6 +11,9 @@ ANTHROPIC_VERSION = "2023-06-01"class ClaudeCodeDriver(SeedSessionDriver):type_name = "claudecode"+ def local_binary(self) -> str | None:+ return "claude"+def build_healthcheck(self, worker: WorkerConfig) -> list[str]:env = worker.envreturn [diff --git a/cairn/src/cairn/dispatcher/workers/adapters/codex.py b/cairn/src/cairn/dispatcher/workers/adapters/codex.pyindex 166a4ef..a09d5f2 100644--- a/cairn/src/cairn/dispatcher/workers/adapters/codex.py+++ b/cairn/src/cairn/dispatcher/workers/adapters/codex.py@@ -8,6 +8,12 @@ from cairn.dispatcher.workers.base import DriverResult, RegexSessionDriverclass CodexDriver(RegexSessionDriver):type_name = "codex"+ def __init__(self, local: bool = False):+ self.local = local++ def local_binary(self) -> str | None:+ return "codex"+def build_healthcheck(self, worker: WorkerConfig) -> list[str]:return ["curl",@@ -41,6 +47,16 @@ class CodexDriver(RegexSessionDriver):)def build_execute(self, worker: WorkerConfig, prompt: str, session: str | None) -> DriverResult:+ if self.local:+ return DriverResult(+ argv=[+ "codex",+ "exec",+ "--dangerously-bypass-approvals-and-sandbox",+ "--",+ prompt,+ ]+ )env = worker.envreturn DriverResult(argv=[@@ -67,6 +83,16 @@ class CodexDriver(RegexSessionDriver):)def build_conclude(self, worker: WorkerConfig, prompt: str, session: str) -> list[str]:+ if self.local:+ return [+ "codex",+ "exec",+ "resume",+ session,+ "--dangerously-bypass-approvals-and-sandbox",+ "--",+ prompt,+ ]env = worker.envreturn ["codex",diff --git a/cairn/src/cairn/dispatcher/workers/adapters/mock.py b/cairn/src/cairn/dispatcher/workers/adapters/mock.pyindex d051f22..7ca368d 100644--- a/cairn/src/cairn/dispatcher/workers/adapters/mock.py+++ b/cairn/src/cairn/dispatcher/workers/adapters/mock.py@@ -123,6 +123,9 @@ else:class MockDriver(SeedSessionDriver):type_name = "mock"+ def local_binary(self) -> str | None:+ return "python3"+@staticmethoddef _argv(worker: WorkerConfig, prompt: str) -> list[str]:behavior = resolve_mock_behavior(worker.name, worker.env)diff --git a/cairn/src/cairn/dispatcher/workers/adapters/pi.py b/cairn/src/cairn/dispatcher/workers/adapters/pi.pyindex d3b50a7..49f35f6 100644--- a/cairn/src/cairn/dispatcher/workers/adapters/pi.py+++ b/cairn/src/cairn/dispatcher/workers/adapters/pi.py@@ -11,6 +11,12 @@ from cairn.dispatcher.workers.base import DriverResult, WorkerDriverclass PiDriver(WorkerDriver):type_name = "pi"+ def __init__(self, local: bool = False):+ self.local = local++ def local_binary(self) -> str | None:+ return "pi"+def build_healthcheck(self, worker: WorkerConfig) -> list[str]:env = worker.envreturn self._wrap_with_models(@@ -33,6 +39,8 @@ class PiDriver(WorkerDriver):)def build_execute(self, worker: WorkerConfig, prompt: str, session: str | None) -> DriverResult:+ if self.local:+ return DriverResult(argv=self._local_argv(worker, prompt, session), session=session)env = worker.envargv = ["--provider",@@ -50,6 +58,8 @@ class PiDriver(WorkerDriver):return DriverResult(argv=self._wrap_with_models(worker, argv), session=session)def build_conclude(self, worker: WorkerConfig, prompt: str, session: str) -> list[str]:+ if self.local:+ return self._local_argv(worker, prompt, session)env = worker.envargv = ["--provider",@@ -67,6 +77,29 @@ class PiDriver(WorkerDriver):]return self._wrap_with_models(worker, argv)+ def _local_argv(self, worker: WorkerConfig, prompt: str, session: str | None) -> list[str]:+ # Native pi: no models.json injection and no --provider/--model overrides, so pi uses+ # its own host configuration. A tiny sh wrapper just ensures the session dir exists.+ session_dir = self._session_dir(worker)+ pi_argv = [+ "--mode",+ "json",+ "--session-dir",+ session_dir,+ "--no-extensions",+ "--no-skills",+ "--no-prompt-templates",+ "--no-themes",+ "--no-context-files",+ "--tools",+ "read,write,edit,bash,grep,find,ls",+ ]+ if session:+ pi_argv.extend(["--session", session])+ pi_argv.extend(["-p", prompt])+ script = 'sdir="$1"\nshift\nmkdir -p "$sdir"\nexec pi "$@"\n'+ return ["/bin/sh", "-lc", script, "--", session_dir, *pi_argv]+def extract_session(self, session: str | None, stdout: str, stderr: str) -> str | None:if session:return sessiondiff --git a/cairn/src/cairn/dispatcher/workers/base.py b/cairn/src/cairn/dispatcher/workers/base.pyindex 7130bac..b000f0b 100644--- a/cairn/src/cairn/dispatcher/workers/base.py+++ b/cairn/src/cairn/dispatcher/workers/base.py@@ -21,6 +21,13 @@ class WorkerDriver(abc.ABC):def supports_conclude(self) -> bool:return True+ def local_binary(self) -> str | None:+ """Executable this driver invokes in local mode, checked on PATH at startup.++ None means the driver has no host binary to verify (or is not used locally).+ """+ return None+def prepare_session(self) -> str | None:return Nonediff --git a/cairn/src/cairn/dispatcher/workers/registry.py b/cairn/src/cairn/dispatcher/workers/registry.pyindex e0f8b5f..9d1f371 100644--- a/cairn/src/cairn/dispatcher/workers/registry.py+++ b/cairn/src/cairn/dispatcher/workers/registry.py@@ -4,13 +4,26 @@ from cairn.dispatcher.workers.adapters import ClaudeCodeDriver, CodexDriver, Mocfrom cairn.dispatcher.workers.base import WorkerDriver+_CLAUDE = ClaudeCodeDriver()+_MOCK = MockDriver()+DRIVERS: dict[str, WorkerDriver] = {- "claudecode": ClaudeCodeDriver(),+ "claudecode": _CLAUDE,"codex": CodexDriver(),"pi": PiDriver(),- "mock": MockDriver(),+ "mock": _MOCK,+}++# Local variants invoke the host CLIs in their native configuration (no cairn provider+# injection). claudecode and mock build identical commands in both modes, so they are shared.+LOCAL_DRIVERS: dict[str, WorkerDriver] = {+ "claudecode": _CLAUDE,+ "codex": CodexDriver(local=True),+ "pi": PiDriver(local=True),+ "mock": _MOCK,}-def get_driver(name: str) -> WorkerDriver:- return DRIVERS[name]+def get_driver(name: str, execution: str = "container") -> WorkerDriver:+ drivers = LOCAL_DRIVERS if execution == "local" else DRIVERS+ return drivers[name]diff --git a/cairn/tests/test_local_execution.py b/cairn/tests/test_local_execution.pynew file mode 100644index 0000000..372642d--- /dev/null+++ b/cairn/tests/test_local_execution.py@@ -0,0 +1,454 @@+from __future__ import annotations++import os+import time+from pathlib import Path++import pytest+from pydantic import ValidationError++from cairn.dispatcher.config import DispatchConfig, LocalConfig, WorkerConfig+from cairn.dispatcher.runtime.local_backend import LocalBackend+from cairn.dispatcher.runtime.local_process import LocalProcess+from cairn.dispatcher.scheduler import loop as loop_module+from cairn.dispatcher.tasks import common, explore+from cairn.dispatcher.runtime.cancellation import TaskCancellation+from cairn.dispatcher.workers.adapters.codex import CodexDriver+from cairn.dispatcher.workers.adapters.pi import PiDriver+from cairn.dispatcher.workers.registry import get_driver++from conftest import FakeClient, make_config, make_intent, make_project+++REPO_ROOT = Path(__file__).resolve().parents[2]+++# --------------------------------------------------------------------------- LocalProcess+++def test_local_process_captures_stdout_and_exit_code() -> None:+ process = LocalProcess(+ ["python3", "-c", "import sys; print('hello'); sys.exit(3)"],+ cwd=os.getcwd(),+ env=dict(os.environ),+ timeout_seconds=10,+ )+ process.start()+ result = process.communicate(timeout=20)++ assert result.stdout.strip() == "hello"+ assert result.returncode == 3+ assert not result.timed_out+++def test_local_process_inherits_cwd(tmp_path: Path) -> None:+ process = LocalProcess(+ ["python3", "-c", "import os; print(os.getcwd())"],+ cwd=str(tmp_path),+ env=dict(os.environ),+ timeout_seconds=10,+ )+ process.start()+ result = process.communicate(timeout=20)++ assert Path(result.stdout.strip()).resolve() == tmp_path.resolve()+++def test_local_process_times_out_and_kills_within_grace() -> None:+ process = LocalProcess(+ ["sh", "-c", "sleep 30"],+ cwd=os.getcwd(),+ env=dict(os.environ),+ timeout_seconds=1,+ term_grace_seconds=2,+ )+ process.start()+ started = time.monotonic()+ result = process.communicate(timeout=30)+ elapsed = time.monotonic() - started++ assert result.timed_out+ assert elapsed < 10 # killed on its own timeout, not the 30s outer backstop+++def test_local_process_kill_terminates_child_process_group(tmp_path: Path) -> None:+ pid_file = tmp_path / "child.pid"+ script = f"sleep 30 & echo $! > {pid_file}; wait"+ process = LocalProcess(+ ["sh", "-c", script],+ cwd=str(tmp_path),+ env=dict(os.environ),+ timeout_seconds=1,+ term_grace_seconds=2,+ )+ process.start()+ result = process.communicate(timeout=30)++ assert result.timed_out+ child_pid = int(pid_file.read_text().strip())+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ try:+ os.kill(child_pid, 0)+ except ProcessLookupError:+ break+ time.sleep(0.1)+ else:+ raise AssertionError(f"child process {child_pid} survived the group kill")+++def test_local_process_cancel_records_reason() -> None:+ process = LocalProcess(+ ["sh", "-c", "sleep 30"],+ cwd=os.getcwd(),+ env=dict(os.environ),+ timeout_seconds=30,+ term_grace_seconds=2,+ )+ process.start()+ process.cancel("project stopped")+ result = process.communicate(timeout=30)++ assert result.cancelled+ assert result.cancel_reason == "project stopped"+++# --------------------------------------------------------------------------- LocalBackend+++def test_local_backend_creates_isolated_project_dir(tmp_path: Path) -> None:+ backend = LocalBackend(LocalConfig(workspace_root=str(tmp_path)))+ handle = backend.ensure_running("proj_001")++ assert Path(handle) == tmp_path / "proj_001"+ assert Path(handle).is_dir()+ assert backend.container_name("proj_001") == str(tmp_path / "proj_001")+++def test_local_backend_merges_host_env_with_worker_env(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("CAIRN_HOST_VAR", "host")+ backend = LocalBackend(LocalConfig(workspace_root=str(tmp_path)))+ handle = backend.ensure_running("proj_001")++ process = backend.build_exec_process(+ handle,+ {"CAIRN_WORKER_VAR": "worker"},+ ["sh", "-c", 'printf "%s-%s" "$CAIRN_HOST_VAR" "$CAIRN_WORKER_VAR"'],+ timeout_seconds=10,+ )+ process.start()+ result = process.communicate(timeout=20)++ assert result.stdout == "host-worker"+++def test_local_common_env_reaches_worker_subprocess(tmp_path: Path, monkeypatch) -> None:+ # common_env (e.g. an outbound proxy) merges into every worker's env and must survive+ # all the way to the host subprocess in local mode.+ payload = _local_payload()+ payload["local"] = {"workspace_root": str(tmp_path)}+ payload["common_env"] = {+ "https_proxy": "http://127.0.0.1:7897",+ "http_proxy": "http://127.0.0.1:7897",+ "all_proxy": "http://127.0.0.1:7897",+ }+ config = DispatchConfig.model_validate(payload)+ worker = next(w for w in config.workers if w.type == "claudecode")+ assert worker.env["https_proxy"] == "http://127.0.0.1:7897"++ assert config.local is not None+ backend = LocalBackend(config.local)+ handle = backend.ensure_running("proj_001")+ process = backend.build_exec_process(+ handle,+ dict(worker.env),+ ["sh", "-c", 'printf "%s|%s|%s" "$https_proxy" "$http_proxy" "$all_proxy"'],+ timeout_seconds=10,+ )+ process.start()+ result = process.communicate(timeout=20)++ proxy = "http://127.0.0.1:7897"+ assert result.stdout == f"{proxy}|{proxy}|{proxy}"+++def test_local_backend_write_text_file_writes_to_host(tmp_path: Path) -> None:+ backend = LocalBackend(LocalConfig(workspace_root=str(tmp_path)))+ target = tmp_path / "snapshots" / "graph.yaml"++ backend.write_text_file("ignored", str(target), "facts: []\n")++ assert target.read_text() == "facts: []\n"+++def test_local_backend_keep_leaves_dir_and_reports_no_cleanup(tmp_path: Path) -> None:+ backend = LocalBackend(LocalConfig(workspace_root=str(tmp_path), completed_action="keep"))+ handle = backend.ensure_running("proj_001")++ assert backend.needs_completed_cleanup("proj_001") is False+ assert backend.cleanup_completed("proj_001") is True+ assert Path(handle).is_dir()+++def test_local_backend_remove_deletes_dir_on_completion(tmp_path: Path) -> None:+ backend = LocalBackend(LocalConfig(workspace_root=str(tmp_path), completed_action="remove"))+ handle = backend.ensure_running("proj_001")++ assert backend.needs_completed_cleanup("proj_001") is True+ assert backend.cleanup_completed("proj_001") is True+ assert not Path(handle).exists()+++def test_local_backend_stopped_cleanup_is_noop(tmp_path: Path) -> None:+ backend = LocalBackend(LocalConfig(workspace_root=str(tmp_path)))+ backend.ensure_running("proj_001")++ assert backend.needs_stopped_cleanup("proj_001") is False+ assert backend.cleanup_stopped("proj_001") is True+++# --------------------------------------------------------------------------- config+++def _local_payload() -> dict:+ return {+ "server": "http://127.0.0.1:8000",+ "runtime": {+ "execution": "local",+ "worker_healthcheck": "disabled",+ "interval": 3,+ "max_workers": 2,+ "max_running_projects": 1,+ "max_project_workers": 2,+ "healthcheck_timeout": 5,+ "prompt_group": "default",+ },+ "tasks": {+ "bootstrap": {"timeout": 10, "conclude_timeout": 5},+ "reason": {"timeout": 10, "max_intents": 3},+ "explore": {"timeout": 10, "conclude_timeout": 5},+ },+ "workers": [+ {"name": "local-claude", "type": "claudecode", "task_types": ["explore"], "max_running": 1, "priority": 0},+ {"name": "local-codex", "type": "codex", "task_types": ["explore"], "max_running": 1, "priority": 1},+ {"name": "local-pi", "type": "pi", "task_types": ["reason"], "max_running": 1, "priority": 2},+ ],+ }+++def test_local_execution_needs_no_container_or_worker_env() -> None:+ config = DispatchConfig.model_validate(_local_payload())++ assert config.container is None+ assert config.local is not None+ assert config.local.completed_action == "keep"+ assert all(worker.env == {} for worker in config.workers)+++def test_local_workspace_root_is_optional_and_defaults_null() -> None:+ payload = _local_payload()+ payload["local"] = {"completed_action": "remove"}+ config = DispatchConfig.model_validate(payload)++ assert config.local is not None+ assert config.local.workspace_root is None+ assert config.local.completed_action == "remove"+++def test_container_execution_requires_container_block() -> None:+ payload = make_config().model_dump()+ payload["container"] = None++ with pytest.raises(ValidationError, match="container config is required"):+ DispatchConfig.model_validate(payload)+++def test_container_execution_still_requires_worker_env() -> None:+ payload = _local_payload()+ payload["runtime"]["execution"] = "container"+ payload["runtime"]["worker_healthcheck"] = "startup_only"+ payload["container"] = {"image": "img", "network_mode": "host", "completed_action": "stop"}++ with pytest.raises(ValidationError, match="missing env keys"):+ DispatchConfig.model_validate(payload)+++def test_shipped_local_example_config_is_valid() -> None:+ config = DispatchConfig.load(REPO_ROOT / "dispatch.local.example.yaml")++ assert config.runtime.execution == "local"+ assert config.container is None+ assert config.local is not None+ assert config.local.completed_action == "keep"+++# --------------------------------------------------------------------------- startup CLI check+++def _bare_loop(config: DispatchConfig) -> loop_module.DispatcherLoop:+ loop = loop_module.DispatcherLoop.__new__(loop_module.DispatcherLoop)+ loop.config = config+ return loop+++def test_local_cli_check_passes_when_cli_present() -> None:+ payload = _local_payload()+ payload["workers"] = [{"name": "m", "type": "mock", "task_types": ["reason"], "max_running": 1, "priority": 0}]+ config = DispatchConfig.model_validate(payload)++ _bare_loop(config)._run_local_binary_check() # mock -> python3 --help runs; must not raise+++def test_local_cli_check_exits_when_no_cli_installed(monkeypatch) -> None:+ monkeypatch.setattr(loop_module.shutil, "which", lambda _binary: None)+ config = DispatchConfig.model_validate(_local_payload())++ with pytest.raises(RuntimeError, match="none of the configured worker CLIs"):+ _bare_loop(config)._run_local_binary_check()+++# --------------------------------------------------------------------------- drivers+++def _bare_worker(worker_type: str) -> WorkerConfig:+ return WorkerConfig.model_validate(+ {"name": worker_type, "type": worker_type, "task_types": ["explore"], "max_running": 1, "priority": 0}+ )+++def test_codex_local_driver_omits_provider_injection() -> None:+ worker = _bare_worker("codex")+ argv = CodexDriver(local=True).build_execute(worker, "PROMPT", None).argv++ assert argv == ["codex", "exec", "--dangerously-bypass-approvals-and-sandbox", "--", "PROMPT"]+ assert not any("model_providers" in part for part in argv)+ assert "--model" not in argv++ conclude = CodexDriver(local=True).build_conclude(worker, "PROMPT", "sess-1")+ assert conclude[:4] == ["codex", "exec", "resume", "sess-1"]+ assert conclude[-2:] == ["--", "PROMPT"]+ assert not any("model_providers" in part for part in conclude)+++def test_pi_local_driver_omits_models_json_and_provider() -> None:+ worker = _bare_worker("pi")+ argv = PiDriver(local=True).build_execute(worker, "PROMPT", None).argv++ assert argv[0] == "/bin/sh"+ assert "exec pi" in argv[2]+ assert "--provider" not in argv+ assert "--model" not in argv+ assert argv[-2:] == ["-p", "PROMPT"]+++def test_get_driver_selects_local_or_container_variant() -> None:+ assert get_driver("codex", "local").local is True+ assert get_driver("codex").local is False+ assert get_driver("pi", "local").local is True+ # claudecode and mock are shared instances across both modes+ assert get_driver("claudecode", "local") is get_driver("claudecode")+ assert get_driver("mock", "local") is get_driver("mock")+++# --------------------------------------------------------------------------- end to end+++def _local_config_for_worker(name: str, worker_type: str) -> DispatchConfig:+ return DispatchConfig.model_validate(+ {+ "server": "in-process",+ "runtime": {+ "execution": "local",+ "worker_healthcheck": "disabled",+ "interval": 60,+ "max_workers": 1,+ "max_running_projects": 1,+ "max_project_workers": 1,+ "healthcheck_timeout": 5,+ "prompt_group": "default",+ },+ "tasks": {+ "bootstrap": {"timeout": 30, "conclude_timeout": 10},+ "reason": {"timeout": 30, "max_intents": 3},+ "explore": {"timeout": 30, "conclude_timeout": 10},+ },+ "workers": [+ {"name": name, "type": worker_type, "task_types": ["explore"], "max_running": 1, "priority": 0}+ ],+ }+ )+++def _install_fake_cli(tmp_path: Path, monkeypatch, name: str, body: str) -> None:+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir(exist_ok=True)+ script = bin_dir / name+ script.write_text(f"#!/bin/sh\n{body}\n")+ script.chmod(0o755)+ monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}")+++def test_explore_runs_real_local_cli_end_to_end(tmp_path: Path, monkeypatch) -> None:+ # A fake `claude` on PATH stands in for the real CLI: the whole local path is exercised+ # for real — driver argv -> LocalBackend -> LocalProcess subprocess -> stdout parsing.+ _install_fake_cli(+ tmp_path,+ monkeypatch,+ "claude",+ "echo '{\"accepted\":true,\"data\":{\"description\":\"local fake fact\"}}'",+ )+ monkeypatch.setattr(common, "GRAPH_SNAPSHOT_ROOT", str(tmp_path / "prompts"))++ config = _local_config_for_worker("test-worker", "claudecode")+ backend = LocalBackend(LocalConfig(workspace_root=str(tmp_path / "work")))+ intent = make_intent()+ project = make_project(intents=[intent])+ client = FakeClient(project)++ outcome = explore.run_explore_task(+ config,+ client,+ backend,+ project,+ "facts:\n- id: f001\n",+ intent,+ config.workers[0],+ TaskCancellation(),+ )++ assert outcome == "success"+ assert client.concluded == [("proj_001", "i001", "test-worker", "local fake fact")]+ # graph snapshot was materialised on the host under the patched root+ snapshot_root = tmp_path / "prompts"+ assert any(p.name == "graph.yaml" for p in snapshot_root.rglob("*"))+++def test_explore_local_cli_rejection_releases_intent(tmp_path: Path, monkeypatch) -> None:+ _install_fake_cli(+ tmp_path,+ monkeypatch,+ "claude",+ "echo '{\"accepted\":false,\"reason\":\"policy_refusal\"}'",+ )+ monkeypatch.setattr(common, "GRAPH_SNAPSHOT_ROOT", str(tmp_path / "prompts"))++ config = _local_config_for_worker("test-worker", "claudecode")+ backend = LocalBackend(LocalConfig(workspace_root=str(tmp_path / "work")))+ intent = make_intent()+ project = make_project(intents=[intent])+ client = FakeClient(project)++ outcome = explore.run_explore_task(+ config,+ client,+ backend,+ project,+ "facts:\n- id: f001\n",+ intent,+ config.workers[0],+ TaskCancellation(),+ )++ assert outcome == "rejected"+ assert client.concluded == []+ assert client.released == [("proj_001", "i001", "test-worker")]diff --git a/cairn/tests/test_worker_tasks.py b/cairn/tests/test_worker_tasks.pyindex 4077664..4f2b127 100644--- a/cairn/tests/test_worker_tasks.py+++ b/cairn/tests/test_worker_tasks.py@@ -36,7 +36,7 @@ def test_reason_writes_graph_snapshot_and_creates_intent(monkeypatch) -> None:lease = FakeLease()graph_yaml = "project:\n title: huge\n" + ("x" * 100_000)- monkeypatch.setattr(reason, "get_driver", lambda _name: driver)+ monkeypatch.setattr(reason, "get_driver", lambda *_a, **_k: driver)monkeypatch.setattr(reason.HeartbeatLease, "for_reason", _lease_factory(lease))monkeypatch.setattr(reason, "run_healthcheck", _healthy)monkeypatch.setattr(@@ -88,7 +88,7 @@ def test_explore_early_plain_text_exit_uses_conclude_fallback(monkeypatch) -> No])- monkeypatch.setattr(explore, "get_driver", lambda _name: driver)+ monkeypatch.setattr(explore, "get_driver", lambda *_a, **_k: driver)monkeypatch.setattr(explore.HeartbeatLease, "for_intent", _lease_factory(lease))monkeypatch.setattr(explore, "run_healthcheck", _healthy)monkeypatch.setattr(explore, "_run_process", lambda *_args, **_kwargs: next(results))@@ -123,7 +123,7 @@ def test_explore_healthcheck_failure_releases_claim(monkeypatch) -> None:containers = FakeContainerManager()lease = FakeLease()- monkeypatch.setattr(explore, "get_driver", lambda _name: FakeDriver())+ monkeypatch.setattr(explore, "get_driver", lambda *_a, **_k: FakeDriver())monkeypatch.setattr(explore.HeartbeatLease, "for_intent", _lease_factory(lease))monkeypatch.setattr(explore,@@ -156,7 +156,7 @@ def test_bootstrap_success_concludes_fact_then_completes_project(monkeypatch) ->driver = FakeDriver()lease = FakeLease()- monkeypatch.setattr(bootstrap, "get_driver", lambda _name: driver)+ monkeypatch.setattr(bootstrap, "get_driver", lambda *_a, **_k: driver)monkeypatch.setattr(bootstrap.HeartbeatLease, "for_intent", _lease_factory(lease))monkeypatch.setattr(bootstrap, "run_healthcheck", _healthy)monkeypatch.setattr(@@ -197,7 +197,7 @@ def test_reason_complete_treats_inactive_project_as_success(monkeypatch) -> Nonereturn ApiResult(403, text="inactive")client.complete = complete # type: ignore[method-assign]- monkeypatch.setattr(reason, "get_driver", lambda _name: FakeDriver())+ monkeypatch.setattr(reason, "get_driver", lambda *_a, **_k: FakeDriver())monkeypatch.setattr(reason.HeartbeatLease, "for_reason", _lease_factory(lease))monkeypatch.setattr(reason, "run_healthcheck", _healthy)monkeypatch.setattr(@@ -232,7 +232,7 @@ def test_reason_startup_only_mode_skips_task_healthcheck(monkeypatch) -> None:containers = FakeContainerManager()lease = FakeLease()- monkeypatch.setattr(reason, "get_driver", lambda _name: FakeDriver())+ monkeypatch.setattr(reason, "get_driver", lambda *_a, **_k: FakeDriver())monkeypatch.setattr(reason.HeartbeatLease, "for_reason", _lease_factory(lease))monkeypatch.setattr(reason,diff --git a/dispatch.local.example.yaml b/dispatch.local.example.yamlnew file mode 100644index 0000000..75d3bce--- /dev/null+++ b/dispatch.local.example.yaml@@ -0,0 +1,71 @@+# Local execution example — workers run directly on the dispatcher host and reuse the+# machine's already-configured claude / codex / pi CLIs. No API keys, base URLs or models+# are configured here; each CLI uses its own host configuration and credentials.+#+# Usage:+# cp dispatch.local.example.yaml dispatch.yaml+# uv run --project cairn cairn serve # in one shell+# uv run --project cairn cairn dispatch --config dispatch.yaml+#+# Notes:+# - Do NOT run the dispatcher via docker-compose in local mode: it must run on the host+# where the CLIs are installed, logged in, and on PATH. The server may still run anywhere.+# - Local mode runs the agents with your user's permissions and no sandbox. Only use it in+# environments you are authorized to operate in.++server: "http://127.0.0.1:8000"++runtime:+ execution: local # run workers as host processes instead of per-project containers+ worker_healthcheck: disabled # no base_url to probe; startup instead checks the CLIs are on PATH+ max_workers: 3 # all workers share this host — size to the machine+ max_running_projects: 2+ max_project_workers: 2+ interval: 3+ healthcheck_timeout: 15+ prompt_group: "default"++tasks:+ bootstrap:+ timeout: 120+ conclude_timeout: 30+ reason:+ timeout: 45+ explore:+ timeout: 600+ conclude_timeout: 120++# Optional. If omitted: workspace_root defaults to the dispatcher's current directory,+# completed_action defaults to keep. Each project gets an isolated <workspace_root>/<project_id>/.+local:+ # workspace_root: "/data/cairn-runs"+ completed_action: keep # keep | remove++# Extra environment variables for every local worker process. These are merged over the+# dispatcher's own environment ({**os.environ, **common_env}), so use it for things the+# CLIs need at runtime, e.g. an outbound proxy. (Alternatively just `export` them in the+# shell that starts the dispatcher — local workers inherit that environment.)+# common_env:+# https_proxy: "http://127.0.0.1:7897"+# http_proxy: "http://127.0.0.1:7897"+# all_proxy: "http://127.0.0.1:7897"++# No API keys needed — the host CLIs are used as-is. Per-worker `env:` overrides common_env.+workers:+ - name: "local-claude"+ type: "claudecode"+ task_types: [bootstrap, reason, explore]+ max_running: 1+ priority: 0++ # - name: "local-codex"+ # type: "codex"+ # task_types: [explore]+ # max_running: 1+ # priority: 1++ # - name: "local-pi"+ # type: "pi"+ # task_types: [reason]+ # max_running: 1+ # priority: 2diff --git a/docs/specs/dispatcher-design.md b/docs/specs/dispatcher-design.mdindex bda448d..7863aa3 100644--- a/docs/specs/dispatcher-design.md+++ b/docs/specs/dispatcher-design.md@@ -165,6 +165,7 @@ Dispatcher 使用一个运行期配置文件:- 使用者只需要提供 `dispatch.yaml`- 任务 prompt 以 markdown 文件形式随代码分发,并通过 `runtime.prompt_group` 选择目录- Worker 的健康检查、命令模板、session 处理、二阶段收尾能力由对应 driver 实现+- `runtime.execution` 选择执行后端:默认 `container`(每项目一个容器),或 `local`(worker 直接在 dispatcher 宿主机上以子进程运行,复用本机已配置好的 CLI,无需 Docker 与 API key)代码目录可以采用类似组织:@@ -874,10 +875,13 @@ codex exec resume "{session}" --dangerously-bypass-approvals-and-sandbox --model| `runtime.interval` | 是 | 统一节拍配置;既是 Dispatcher 主循环间隔,也是带 claim 任务的 heartbeat 周期 || `runtime.healthcheck_timeout` | 是 | Worker 健康检查的统一外层 watchdog 超时 || `runtime.worker_healthcheck` | 否 | Worker 健康检查模式:`startup_and_task`、`startup_only` 或 `disabled`;默认 `startup_only` |+| `runtime.execution` | 否 | 执行后端:`container`(默认)或 `local`;`local` 时 worker 在 dispatcher 宿主机上以子进程运行,复用本机 CLI,启动时校验各 CLI 是否已安装可用 || `runtime.prompt_group` | 是 | 当前使用的 prompt 组目录名 |### `container.*`+仅 `runtime.execution: container`(默认)时必填。+| 字段 | 必填 | 含义 || --- | --- | --- || `container.image` | 是 | 项目容器镜像 |@@ -894,6 +898,15 @@ codex exec resume "{session}" --dangerously-bypass-approvals-and-sandbox --model- completed project 的容器 cleanup 可以异步并行进行,不要求阻塞主调度循环- 如果项目已从 Server 删除,Dispatcher 会把找不到对应项目的 `cairn-dispatch-*` 容器视为 orphan,并执行 stop 清理+### `local.*`++仅 `runtime.execution: local` 时生效,`container` 模式下忽略。此时无需 `container.*`,worker 也不需要任何 LLM 环境变量;启动时 Dispatcher 会对每个已配置 worker 的 CLI 执行 `--help` 探测,全部缺失则报错退出。++| 字段 | 必填 | 含义 |+| --- | --- | --- |+| `local.workspace_root` | 否 | 每项目工作目录的根;不填则取 dispatcher 启动时的当前目录,每项目分到隔离子目录 `<root>/<project_id>/` 作为 worker 进程的工作目录 |+| `local.completed_action` | 否 | 项目 completed 后对工作目录的处理:`keep`(默认,保留现场)或 `remove` |+### `tasks.*`| 字段 | 必填 | 含义 |