"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(swarm): surface errors, output contract, Windows-safe store, redact paths (#119)
Teerapat Vatpitak39aaa620085c
diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex ce2ba122b..2a1204ca0 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -371,15 +371,17 @@ def run_swarm(preset_name: str, variables: dict[str, str]) -> str:"""import timefrom src.swarm.runtime import SwarmRuntime- from src.swarm.store import SwarmStore+ from src.swarm.store import SwarmStore, swarm_runs_rootfrom src.swarm.models import RunStatus- swarm_dir = AGENT_DIR / ".swarm" / "runs"+ swarm_dir = swarm_runs_root()store = SwarmStore(base_dir=swarm_dir)runtime = SwarmRuntime(store=store)try:- run = runtime.start_run(preset_name, variables)+ run = runtime.start_run(+ preset_name, variables, include_shell_tools=_include_shell_tools+ )except FileNotFoundError as exc:return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)except ValueError as exc:@@ -392,16 +394,16 @@ def run_swarm(preset_name: str, variables: dict[str, str]) -> str:if current is None:return json.dumps({"status": "error", "error": "Run record lost"}, ensure_ascii=False)if current.status in (RunStatus.completed, RunStatus.failed, RunStatus.cancelled):- tasks = [- {"id": t.id, "agent_id": t.agent_id, "status": t.status.value, "summary": t.summary}- for t in current.tasks- ]+ from src.swarm.serialization import run_level_error, serialize_task++ tasks = [serialize_task(t) for t in current.tasks]return json.dumps({"status": current.status.value,"preset": preset_name,"run_id": current.id,"final_report": current.final_report,+ "error": run_level_error(current),"tasks": tasks,"total_input_tokens": current.total_input_tokens,"total_output_tokens": current.total_output_tokens,@@ -552,28 +554,23 @@ def get_market_data(def _get_swarm_store():- swarm_dir = AGENT_DIR / ".swarm" / "runs"- swarm_dir.mkdir(parents=True, exist_ok=True)- from src.swarm.store import SwarmStore+ from src.swarm.store import SwarmStore, swarm_runs_root+ swarm_dir = swarm_runs_root()+ swarm_dir.mkdir(parents=True, exist_ok=True)return SwarmStore(base_dir=swarm_dir)def _run_to_dict(run) -> dict:+ from src.swarm.serialization import run_level_error, serialize_task+return {"run_id": run.id,"status": run.status.value,"preset": run.preset_name,"created_at": run.created_at,- "tasks": [- {- "id": t.id,- "agent_id": t.agent_id,- "status": t.status.value,- "summary": t.summary,- }- for t in run.tasks- ],+ "error": run_level_error(run),+ "tasks": [serialize_task(t) for t in run.tasks],"final_report": run.final_report,"total_input_tokens": run.total_input_tokens,"total_output_tokens": run.total_output_tokens,diff --git a/agent/src/swarm/models.py b/agent/src/swarm/models.pyindex 707347812..b756e38d6 100644--- a/agent/src/swarm/models.py+++ b/agent/src/swarm/models.py@@ -40,6 +40,23 @@ class RunStatus(str, Enum):cancelled = "cancelled"+class WorkerStatus(str, Enum):+ """Terminal status a worker returns.++ ``incomplete`` is distinct from ``failed``: the worker ran without an+ exception but produced no substantive deliverable (plan-only stub,+ fabricated/mock numbers, unparsed tool markup, or a data agent that+ made no tool call and wrote no report). It must never be folded into+ ``completed`` (see P01/P03).+ """++ completed = "completed"+ failed = "failed"+ timeout = "timeout"+ token_limit = "token_limit"+ incomplete = "incomplete"++class SwarmAgentSpec(BaseModel):"""Role definition for a single agent in a Swarm.@@ -203,7 +220,7 @@ class WorkerResult(BaseModel):"""Return value after worker execution completes.Attributes:- status: "completed" or "failed".+ status: WorkerStatus — completed|failed|timeout|token_limit|incomplete.summary: Execution summary.artifact_paths: List of generated artifact file paths.iterations: Actual ReAct iterations executed.@@ -212,7 +229,7 @@ class WorkerResult(BaseModel):output_tokens: Cumulative output tokens (exact or estimated)."""- status: str+ status: WorkerStatussummary: strartifact_paths: list[str] = Field(default_factory=list)iterations: int = 0diff --git a/agent/src/swarm/presets.py b/agent/src/swarm/presets.pyindex 9820d0a00..e5ae7135d 100644--- a/agent/src/swarm/presets.py+++ b/agent/src/swarm/presets.py@@ -39,7 +39,7 @@ def load_preset(name: str) -> dict:if not path.exists():available = [p.stem for p in PRESETS_DIR.glob("*.yaml")] if PRESETS_DIR.exists() else []raise FileNotFoundError(- f"Preset '{name}' not found at {path}. Available: {available}"+ f"Preset {name!r} not found. Available: {available}")return yaml.safe_load(path.read_text(encoding="utf-8"))diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.pyindex 2f2aa8f33..56a9f6eb1 100644--- a/agent/src/swarm/runtime.py+++ b/agent/src/swarm/runtime.py@@ -21,7 +21,6 @@ from pathlib import Pathfrom typing import Callablefrom src.swarm import grounding-from src.swarm.mailbox import Mailboxfrom src.swarm.models import (RunStatus,SwarmAgentSpec,@@ -39,6 +38,7 @@ from src.swarm.task_store import (topological_layers,validate_dag,)+from src.tools.redaction import redact_internal_pathsfrom src.swarm.worker import run_workerlogger = logging.getLogger(__name__)@@ -269,11 +269,12 @@ class SwarmRuntime:run.total_input_tokens += result.input_tokensrun.total_output_tokens += result.output_tokens- if result.status in ("completed", "timeout", "token_limit"):+ if result.status == "completed":task_summaries[tid] = result.summarynow_iso = datetime.now(timezone.utc).isoformat()task_store.update_status(- tid, TaskStatus.completed,+ tid,+ TaskStatus.completed,summary=result.summary,completed_at=now_iso,artifacts=result.artifact_paths,@@ -282,26 +283,38 @@ class SwarmRuntime:resolve_dependencies(run_dir / "tasks", tid)self._emit_event(run_id,- self._make_event("task_completed", task_id=tid,- data={"status": result.status,- "iterations": result.iterations,- "input_tokens": result.input_tokens,- "output_tokens": result.output_tokens}),+ self._make_event(+ "task_completed",+ task_id=tid,+ data={+ "status": result.status,+ "iterations": result.iterations,+ "input_tokens": result.input_tokens,+ "output_tokens": result.output_tokens,+ },+ ),)else:all_succeeded = Falsetask_store.update_status(- tid, TaskStatus.failed,- error=result.error or "Unknown error",+ tid,+ TaskStatus.failed,+ error=redact_internal_paths(result.error)+ or f"worker did not complete (status={result.status})",completed_at=datetime.now(timezone.utc).isoformat(),worker_iterations=result.iterations,)self._emit_event(run_id,- self._make_event("task_failed", task_id=tid,- data={"error": result.error,- "input_tokens": result.input_tokens,- "output_tokens": result.output_tokens}),+ self._make_event(+ "task_failed",+ task_id=tid,+ data={+ "error": redact_internal_paths(result.error),+ "input_tokens": result.input_tokens,+ "output_tokens": result.output_tokens,+ },+ ),)except Exception as exc:@@ -309,14 +322,12 @@ class SwarmRuntime:all_succeeded = Falseself._emit_event(run_id,- self._make_event("run_error", data={"error": str(exc)}),+ self._make_event("run_error", data={"error": redact_internal_paths(str(exc))}),)# Finalize runfinal_status = (- RunStatus.cancelled if cancel_event.is_set()- else RunStatus.completed if all_succeeded- else RunStatus.failed+ RunStatus.cancelled if cancel_event.is_set() else RunStatus.completed if all_succeeded else RunStatus.failed)run.status = final_statusrun.completed_at = datetime.now(timezone.utc).isoformat()@@ -350,7 +361,9 @@ class SwarmRuntime:if len(symbols) > symbol_limit:logger.warning("grounding: limiting run %s symbols from %d to %d",- run.id, len(symbols), symbol_limit,+ run.id,+ len(symbols),+ symbol_limit,)symbols = symbols[:symbol_limit]@@ -359,7 +372,9 @@ class SwarmRuntime:except Exception:logger.warning("grounding: pre-fetch failed for run %s symbols=%s",- run.id, symbols, exc_info=True,+ run.id,+ symbols,+ exc_info=True,)return@@ -416,14 +431,16 @@ class SwarmRuntime:agent_spec = agent_map.get(task.agent_id)if agent_spec is None:results[tid] = WorkerResult(- status="failed", summary="",+ status="failed",+ summary="",error=f"Agent '{task.agent_id}' not found in preset",)continue# Mark task as in_progresstask_store.update_status(- tid, TaskStatus.in_progress,+ tid,+ TaskStatus.in_progress,started_at=datetime.now(timezone.utc).isoformat(),)self._emit_event(@@ -467,7 +484,8 @@ class SwarmRuntime:except Exception as exc:logger.error("Worker for task %s raised exception", tid, exc_info=True)results[tid] = WorkerResult(- status="failed", summary="",+ status="failed",+ summary="",error=str(exc),)except FuturesTimeoutError:@@ -477,10 +495,12 @@ class SwarmRuntime:pending.cancel()logger.error("Worker for task %s exceeded layer deadline (%ds)",- tid, layer_deadline,+ tid,+ layer_deadline,)results[tid] = WorkerResult(- status="timeout", summary="",+ status="timeout",+ summary="",error=f"Worker exceeded layer deadline of {layer_deadline}s",)except KeyboardInterrupt:@@ -539,13 +559,18 @@ class SwarmRuntime:"task_retry",agent_id=agent_spec.id,task_id=task.id,- data={"attempt": attempt + 1, "max_retries": max_retries,- "previous_error": result.error if result else None},+ data={+ "attempt": attempt + 1,+ "max_retries": max_retries,+ "previous_error": result.error if result else None,+ },),)logger.info("Retrying task %s (attempt %d/%d)",- task.id, attempt + 1, max_retries + 1,+ task.id,+ attempt + 1,+ max_retries + 1,)result = run_worker(@@ -564,18 +589,22 @@ class SwarmRuntime:if result.status != "failed":# Success (or timeout/token_limit/completed) — no more retries- result = result.model_copy(update={- "input_tokens": cumulative_input_tokens,- "output_tokens": cumulative_output_tokens,- })+ result = result.model_copy(+ update={+ "input_tokens": cumulative_input_tokens,+ "output_tokens": cumulative_output_tokens,+ }+ )return result# All retries exhausted, return the last failed result with cumulative tokensif result is not None:- result = result.model_copy(update={- "input_tokens": cumulative_input_tokens,- "output_tokens": cumulative_output_tokens,- })+ result = result.model_copy(+ update={+ "input_tokens": cumulative_input_tokens,+ "output_tokens": cumulative_output_tokens,+ }+ )return result # type: ignore[return-value]def _cancel_remaining_tasks(diff --git a/agent/src/swarm/serialization.py b/agent/src/swarm/serialization.pynew file mode 100644index 000000000..660d2e02d--- /dev/null+++ b/agent/src/swarm/serialization.py@@ -0,0 +1,47 @@+"""Shared serialization helpers for the swarm read boundaries.++Single source of truth for projecting a :class:`SwarmTask` into the per-task+JSON dict returned by the MCP tools (``run_swarm`` / ``get_swarm_status`` /+``get_run_result``) and the in-process ``run_swarm`` agent tool.++Before this module each boundary hand-maintained its own field allowlist and+all three silently omitted ``SwarmTask.error``: a misconfigured provider+produced ``status="failed"`` with no diagnosable reason anywhere the caller+could see, even though the error was captured on disk (see P04).+"""++from __future__ import annotations++from typing import Any++from src.tools.redaction import redact_internal_paths+++def serialize_task(task: Any) -> dict:+ """Project a SwarmTask into its public per-task dict.++ ``error`` and ``iterations`` are always included so a failed or degraded+ task is diagnosable from every read path, not only the on-disk artifacts.+ """+ status = task.status.value if hasattr(task.status, "value") else str(task.status)+ return {+ "id": task.id,+ "agent_id": task.agent_id,+ "status": status,+ "summary": task.summary,+ "iterations": getattr(task, "worker_iterations", 0),+ "error": redact_internal_paths(getattr(task, "error", None)) or None,+ }+++def run_level_error(run: Any) -> str | None:+ """First failed task's error, for a top-level ``error`` field.++ Returns ``None`` (an explicit null, not an absent key) when no task carries+ an error, so a caller that only reads the top level still gets a signal.+ """+ for task in getattr(run, "tasks", None) or []:+ err = getattr(task, "error", None)+ if err:+ return f"{task.id}/{task.agent_id}: {redact_internal_paths(err)}"+ return Nonediff --git a/agent/src/swarm/store.py b/agent/src/swarm/store.pyindex 303781d04..65ffc856a 100644--- a/agent/src/swarm/store.py+++ b/agent/src/swarm/store.py@@ -12,10 +12,62 @@ File-system-based persistence for SwarmRun. Directory structure:from __future__ import annotationsimport json+import osimport threading+import timefrom pathlib import Pathfrom src.swarm.models import SwarmEvent, SwarmRun+from src.tools.redaction import redact_internal_paths+++def swarm_runs_root() -> Path:+ """Single source of truth for where swarm runs are persisted.++ The swarm store (mcp_server) and the run-dir sandbox allow-list+ (src.tools.path_utils) must agree on this path. They previously each+ derived ``<agent_root>/.swarm/runs`` independently; a packaging layout+ where the two anchors resolved differently silently put every worker+ run_dir outside the allow-list (P03-A). Deriving it here once keeps+ the store location and the allow-list from drifting again.+ """+ return Path(__file__).resolve().parents[2] / ".swarm" / "runs"+++_TRANSIENT_WINERRORS = (5, 32) # ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION+_REPLACE_ATTEMPTS = 6+_REPLACE_BACKOFF = (0.025, 0.05, 0.1, 0.2, 0.4) # seconds; len == attempts - 1+++def _is_transient_windows_error(exc: OSError) -> bool:+ """True for the Windows access/sharing race on os.replace.++ ``winerror`` is only set on Windows; ``getattr`` keeps this a hard+ False on POSIX, so the retry path is Windows-only and POSIX behavior+ is unchanged.+ """+ return getattr(exc, "winerror", None) in _TRANSIENT_WINERRORS+++def _replace_with_retry(tmp: Path, target: Path) -> None:+ """``os.replace`` retried on the Windows concurrent-access race.++ A reader holding ``target`` open (e.g. ``load_run`` on the poll path)+ makes Windows fail the rename with WinError 5/32. POSIX ``os.replace``+ is atomic and never raises these, so off-Windows this loop runs+ exactly once — no behavior change. Non-transient errors re-raise+ immediately; the last transient error re-raises after the budget.+ """+ for attempt in range(_REPLACE_ATTEMPTS):+ try:+ os.replace(tmp, target)+ return+ except OSError as exc:+ if not _is_transient_windows_error(exc):+ raise+ if attempt == _REPLACE_ATTEMPTS - 1:+ raise+ time.sleep(_REPLACE_BACKOFF[attempt])class SwarmStore:@@ -81,7 +133,19 @@ class SwarmStore:run_file = self.run_dir(run_id) / "run.json"if not run_file.exists():return None- return SwarmRun.model_validate_json(run_file.read_text(encoding="utf-8"))+ # The file may be read mid-replace by a concurrent writer; retry a+ # transient read/parse failure before giving up (same race as+ # _replace_with_retry, reader side).+ last: Exception | None = None+ for attempt in range(_REPLACE_ATTEMPTS):+ try:+ return SwarmRun.model_validate_json(run_file.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ last = exc+ if attempt < len(_REPLACE_BACKOFF):+ time.sleep(_REPLACE_BACKOFF[attempt])+ assert last is not None # loop body sets `last` or returns+ raise type(last)(redact_internal_paths(str(last))) from Nonedef update_run(self, run: SwarmRun) -> None:"""Atomically update run state.@@ -94,7 +158,7 @@ class SwarmStore:"""rd = self.run_dir(run.id)if not rd.exists():- raise FileNotFoundError(f"Run directory not found: {rd}")+ raise FileNotFoundError(f"Run directory not found: {rd.name}")self._atomic_write(rd / "run.json", run.model_dump_json(indent=2))def list_runs(self, limit: int = 50) -> list[SwarmRun]:@@ -116,9 +180,7 @@ class SwarmStore:run_file = entry / "run.json"if run_file.exists():try:- run = SwarmRun.model_validate_json(- run_file.read_text(encoding="utf-8")- )+ run = SwarmRun.model_validate_json(run_file.read_text(encoding="utf-8"))runs.append(run)except (json.JSONDecodeError, ValueError):continue@@ -138,15 +200,13 @@ class SwarmStore:"""rd = self.run_dir(run_id)if not rd.exists():- raise FileNotFoundError(f"Run directory not found: {rd}")+ raise FileNotFoundError(f"Run directory not found: {rd.name}")events_file = rd / "events.jsonl"with self._write_lock:with events_file.open("a", encoding="utf-8") as f:f.write(event.model_dump_json() + "\n")- def read_events(- self, run_id: str, after_index: int = 0- ) -> list[SwarmEvent]:+ def read_events(self, run_id: str, after_index: int = 0) -> list[SwarmEvent]:"""Read the event log with optional offset for SSE incremental streaming.Args:@@ -178,4 +238,4 @@ class SwarmStore:tmp_path = path.with_suffix(".tmp")with self._write_lock:tmp_path.write_text(content, encoding="utf-8")- tmp_path.replace(path)+ _replace_with_retry(tmp_path, path)diff --git a/agent/src/swarm/task_store.py b/agent/src/swarm/task_store.pyindex 17c2ec004..70a38dd79 100644--- a/agent/src/swarm/task_store.py+++ b/agent/src/swarm/task_store.py@@ -70,7 +70,7 @@ class TaskStore:"""path = self._task_path(task_id)if not path.exists():- raise FileNotFoundError(f"Task not found: {path}")+ raise FileNotFoundError(f"Task not found: {path.name}")return SwarmTask.model_validate_json(path.read_text(encoding="utf-8"))def load_all(self) -> list[SwarmTask]:diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex a2477ca7d..ebd1269c3 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -347,6 +347,7 @@ def run_worker(last_assistant_content = ""_KEEP_RECENT_TOOLS = 3+ data_tool_calls = 0for iteration in range(max_iterations):# Microcompact: clear old tool results to prevent token bloat@@ -448,8 +449,26 @@ def run_worker(if not response.has_tool_calls:summary = response.content or last_assistant_content or "(no summary)"summary = _resolve_summary(artifact_dir, summary)- _emit(event_callback, "worker_completed", agent_id, task_id, {"iterations": iteration + 1})_write_summary(artifact_dir, summary)+ reason = _classify_deliverable(+ summary,+ is_data_agent=_is_data_agent(agent_spec),+ report_written=_report_written(artifact_dir),+ data_tool_calls=data_tool_calls,+ )+ if reason:+ _emit(event_callback, "worker_incomplete", agent_id, task_id,+ {"iterations": iteration + 1, "reason": reason})+ return WorkerResult(+ status="incomplete",+ summary=summary,+ artifact_paths=_collect_artifacts(artifact_dir),+ iterations=iteration + 1,+ error=f"output contract not met: {reason}",+ input_tokens=total_input_tokens,+ output_tokens=total_output_tokens,+ )+ _emit(event_callback, "worker_completed", agent_id, task_id, {"iterations": iteration + 1})return WorkerResult(status="completed",summary=summary,@@ -478,6 +497,8 @@ def run_worker(tc_start = time.monotonic()args = {**tc.arguments, "run_dir": str(artifact_dir)}result = registry.execute(tc.name, args)+ if tc.name != "load_skill" and not _is_error_result(result):+ data_tool_calls += 1tc_elapsed = time.monotonic() - tc_start_emit(event_callback, "tool_result", agent_id, task_id,@@ -492,9 +513,27 @@ def run_worker(# Hit iteration limit — use last meaningful content as summarysummary = _best_summary(messages, last_assistant_content) or f"Worker hit iteration limit ({max_iterations} iterations)"summary = _resolve_summary(artifact_dir, summary)- _emit(event_callback, "worker_iteration_limit", agent_id, task_id)_write_summary(artifact_dir, summary)_persist_messages(artifact_dir, messages)+ reason = _classify_deliverable(+ summary,+ is_data_agent=_is_data_agent(agent_spec),+ report_written=_report_written(artifact_dir),+ data_tool_calls=data_tool_calls,+ )+ if reason:+ _emit(event_callback, "worker_incomplete", agent_id, task_id,+ {"iterations": max_iterations, "reason": f"iteration limit; {reason}"})+ return WorkerResult(+ status="incomplete",+ summary=summary,+ artifact_paths=_collect_artifacts(artifact_dir),+ iterations=max_iterations,+ error=f"hit iteration limit without a valid deliverable: {reason}",+ input_tokens=total_input_tokens,+ output_tokens=total_output_tokens,+ )+ _emit(event_callback, "worker_iteration_limit", agent_id, task_id)return WorkerResult(status="completed",summary=summary,@@ -540,6 +579,90 @@ def _is_sensitive_tool_argument(key: str) -> bool:)+# Tools that do not themselves fetch/compute market data. An agent whose+# entire toolset is a subset of these is a synthesis/editor role (e.g. the+# research editor in equity_research_team) and may legitimately produce a+# text deliverable with no tool calls — it must NOT be failed for "no tool+# evidence" (that would regress correct runs; see #115 framing).+_GENERIC_TOOLS = {"bash", "read_file", "write_file", "load_skill", "edit_file"}++_UNPARSED_TOOL_MARKERS = (+ "<\uff5ctool\u2581calls\u2581begin\uff5c>",+ "<tool_calls_begin>",+ "<tool_call_begin>",+ "<tool_sep>",+ "tool\u2581sep",+)+_FABRICATION_MARKERS = ("mock data", "without actual data", "fabricated data", "placeholder data")+_PLAN_PREFIXES = (+ "# phase 1", "## phase 1", "### phase 1",+ "phase 1 \u2014 plan", "phase 1 - plan", "phase 1: plan",+ "# plan", "## plan", "### plan", "**plan**",+)+_HANDOFF_TAILS = (+ "execute", "execute.", "execute:", "skills.", "skills", "proceed?",+ "proceed.", "without writing files.", "let me adjust the approach",+ "let me adjust the approach.", "stand by for final synthesis.",+)+++def _report_written(artifact_dir: Path) -> bool:+ """True iff a non-empty report.md was actually produced by the worker."""+ try:+ p = artifact_dir / "report.md"+ return p.is_file() and bool(p.read_text(encoding="utf-8").strip())+ except Exception:+ return False+++def _is_data_agent(agent_spec: SwarmAgentSpec) -> bool:+ """An agent with at least one data/analysis tool beyond the generic kit."""+ return bool(set(agent_spec.tools or []) - _GENERIC_TOOLS)+++def _is_error_result(result: str) -> bool:+ """Heuristic: did a tool call return an error envelope?"""+ head = (result or "").strip()[:160].lower()+ return head.startswith("{") and ('"status": "error"' in head or '"status":"error"' in head)+++def _classify_deliverable(+ summary: str,+ *,+ is_data_agent: bool,+ report_written: bool,+ data_tool_calls: int,+) -> str | None:+ """Hybrid output contract. Return a short reason string when the worker+ did NOT produce a substantive deliverable, else ``None``.++ Content-sanity applies to every agent; the tool-evidence requirement+ applies ONLY to data agents so tool-less synthesis/editor roles are+ not false-rejected.+ """+ text = (summary or "").strip()+ if not text:+ return "empty deliverable"+ low = text.lower()+ if any(m in low for m in _UNPARSED_TOOL_MARKERS):+ return "unparsed tool-call markup (provider did not parse tool calls)"+ if any(m in low for m in _FABRICATION_MARKERS):+ return "explicitly fabricated / mock data"+ if text.startswith("{") and '"status"' in text[:40] and (+ '"content"' in text[:300] or '"ok"' in text[:40]+ ):+ return "raw tool-result envelope, not analysis"+ if low.startswith(_PLAN_PREFIXES):+ tail = low.rsplit("phase 2", 1)[-1].strip() if "phase 2" in low else ""+ if len(text) < 600 or low.rstrip().endswith(_HANDOFF_TAILS) or (+ "phase 2" in low and len(tail) < 80+ ):+ return "plan-only stub (no executed analysis / conclusion)"+ if is_data_agent and not report_written and data_tool_calls == 0:+ return "data agent produced no tool calls and no report.md"+ return None++def _resolve_summary(artifact_dir: Path, fallback: str) -> str:"""Return report.md content if it exists, otherwise fall back to text."""report_path = artifact_dir / "report.md"diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.pyindex 9b2d73f23..682794ba0 100644--- a/agent/src/tools/__init__.py+++ b/agent/src/tools/__init__.py@@ -171,6 +171,13 @@ def build_filtered_registry(tool_names: list[str], *, include_shell_tools: booltool = full.get(name)if tool:filtered.register(tool)+ else:+ logger.warning(+ "Requested tool %r is unavailable and was dropped from the "+ "filtered registry (include_shell_tools=%s); a preset that "+ "depends on it cannot execute it.",+ name, include_shell_tools,+ )return filtereddiff --git a/agent/src/tools/edit_file_tool.py b/agent/src/tools/edit_file_tool.pyindex 2ea2675ba..cf6ccb3b3 100644--- a/agent/src/tools/edit_file_tool.py+++ b/agent/src/tools/edit_file_tool.py@@ -9,6 +9,7 @@ from typing import Anyfrom src.agent.tools import BaseToolfrom src.tools.path_utils import safe_path as _safe_pathfrom src.tools.path_utils import safe_run_dir as _safe_run_dir+from src.tools.redaction import redact_internal_pathsclass EditFileTool(BaseTool):@@ -43,42 +44,60 @@ class EditFileTool(BaseTool):run_dir = kwargs.get("run_dir")if not run_dir:- return json.dumps({- "status": "error",- "error": "run_dir is required for edit_file",- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": "run_dir is required for edit_file",+ },+ ensure_ascii=False,+ )try:run_root = _safe_run_dir(str(run_dir))resolved = _safe_path(file_path, run_root)except ValueError as exc:- return json.dumps({- "status": "error",- "error": str(exc),- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": str(exc),+ },+ ensure_ascii=False,+ )if not resolved.exists():- return json.dumps({- "status": "error",- "error": f"File not found: {file_path}",- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": f"File not found: {file_path}",+ },+ ensure_ascii=False,+ )try:content = resolved.read_text(encoding="utf-8")if old_text not in content:- return json.dumps({- "status": "error",- "error": f"old_text not found in {file_path}",- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": f"old_text not found in {file_path}",+ },+ ensure_ascii=False,+ )new_content = content.replace(old_text, new_text, 1)resolved.write_text(new_content, encoding="utf-8")- return json.dumps({- "status": "ok",- "path": str(resolved),- "message": "Edit applied successfully",- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "ok",+ "path": str(resolved),+ "message": "Edit applied successfully",+ },+ ensure_ascii=False,+ )except Exception as exc:- return json.dumps({- "status": "error",- "error": str(exc),- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": redact_internal_paths(str(exc)),+ },+ ensure_ascii=False,+ )diff --git a/agent/src/tools/path_utils.py b/agent/src/tools/path_utils.pyindex 7680554d4..d3fa24d5c 100644--- a/agent/src/tools/path_utils.py+++ b/agent/src/tools/path_utils.py@@ -50,7 +50,7 @@ def safe_path(p: str, workdir: Path) -> Path:try:resolved.relative_to(base)except ValueError as exc:- raise ValueError(f"Path {p!r} escapes workspace {base}") from exc+ raise ValueError(f"Path {p!r} escapes the workspace root") from excreturn resolved@@ -89,12 +89,14 @@ def _default_file_roots() -> list[Path]:def _default_run_roots() -> list[Path]:"""Return default roots for generated backtest/tool run directories."""+ from src.swarm.store import swarm_runs_root+cwd = Path.cwd().resolve()home = Path.home().resolve()agent_root = _agent_root()return [agent_root / "runs",- agent_root / ".swarm" / "runs",+ swarm_runs_root(),cwd / "runs",home / ".vibe-trading" / "shadow_runs",]diff --git a/agent/src/tools/read_file_tool.py b/agent/src/tools/read_file_tool.pyindex 680aedf68..8882849ac 100644--- a/agent/src/tools/read_file_tool.py+++ b/agent/src/tools/read_file_tool.py@@ -9,6 +9,7 @@ from typing import Anyfrom src.agent.tools import BaseToolfrom src.tools.path_utils import safe_path as _safe_pathfrom src.tools.path_utils import safe_run_dir as _safe_run_dir+from src.tools.redaction import redact_internal_paths_OUTPUT_LIMIT = 50_000@@ -46,10 +47,13 @@ class ReadFileTool(BaseTool):try:allowed_roots.append(_safe_run_dir(str(run_dir)))except ValueError as exc:- return json.dumps({- "status": "error",- "error": str(exc),- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": str(exc),+ },+ ensure_ascii=False,+ )# Read-only access to skills/skills_dir = Path(__file__).resolve().parents[1] / "skills"if skills_dir.exists():@@ -58,7 +62,7 @@ class ReadFileTool(BaseTool):# Strip redundant "skills/" prefix that LLMs sometimes addpaths_to_try = [file_path]if file_path.startswith("skills/"):- paths_to_try.append(file_path[len("skills/"):])+ paths_to_try.append(file_path[len("skills/") :])resolved = Nonefor root in allowed_roots:@@ -74,10 +78,13 @@ class ReadFileTool(BaseTool):breakif resolved is None:- return json.dumps({- "status": "error",- "error": f"File not found or path escapes workspace: {file_path}",- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": f"File not found or path escapes workspace: {file_path}",+ },+ ensure_ascii=False,+ )try:text = resolved.read_text(encoding="utf-8")@@ -86,13 +93,19 @@ class ReadFileTool(BaseTool):text = "".join(lines[:limit])if len(text) > _OUTPUT_LIMIT:text = text[:_OUTPUT_LIMIT] + "\n... (truncated)"- return json.dumps({- "status": "ok",- "path": str(resolved),- "content": text,- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "ok",+ "path": str(resolved),+ "content": text,+ },+ ensure_ascii=False,+ )except Exception as exc:- return json.dumps({- "status": "error",- "error": str(exc),- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": redact_internal_paths(str(exc)),+ },+ ensure_ascii=False,+ )diff --git a/agent/src/tools/redaction.py b/agent/src/tools/redaction.pynew file mode 100644index 000000000..f5cb9a77b--- /dev/null+++ b/agent/src/tools/redaction.py@@ -0,0 +1,54 @@+"""Redact internal absolute paths from user-facing strings (CWE-209/497, P10).++Redacts ONLY known-internal root prefixes (anchored to the running env) and+keeps the relative tail — caller-supplied/external absolute paths stay intact+for diagnosability; only our own topology is hidden. Idempotent: each root is+replaced by the literal '<redacted>' sentinel, which is not itself a root, so+a second pass is a no-op. No regex (zero ReDoS surface).+"""++from __future__ import annotations++import sys+import sysconfig+from pathlib import Path++_SENTINEL = "<redacted>"+++def _internal_roots() -> list[str]:+ # AGENT_DIR derived like agent/src/providers/llm.py:90+ # (Path(__file__).resolve().parents[2]); redaction.py is agent/src/tools/+ # so parents[2] == the agent/ dir. Anchor tracks layout, not hardcoded.+ agent_dir = Path(__file__).resolve().parents[2]+ cands = [+ Path.home(),+ Path.cwd(),+ agent_dir,+ agent_dir.parent,+ Path(sys.prefix),+ Path(sys.base_prefix),+ Path(sysconfig.get_paths().get("purelib", "")),+ Path(sysconfig.get_paths().get("platlib", "")),+ ]+ roots: set[str] = set()+ for c in cands:+ s = str(c)+ if len(s) > 3 and s not in (".", "/", "\\"):+ roots.add(s)+ roots.add(s.replace("\\", "/"))+ roots.add(s.replace("/", "\\"))+ return sorted(roots, key=len, reverse=True)+++def redact_internal_paths(text: object) -> str:+ """Replace internal root prefixes with '<redacted>', keep relative tail."""+ if text is None:+ return ""+ s = text if isinstance(text, str) else str(text)+ if not s:+ return s+ for root in _internal_roots():+ if root in s:+ s = s.replace(root, _SENTINEL)+ return sdiff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.pyindex 624f18e73..ae8c91c57 100644--- a/agent/src/tools/swarm_tool.py+++ b/agent/src/tools/swarm_tool.py@@ -696,17 +696,9 @@ def _format_result(Returns:JSON string with run status, report, task summaries, and token usage."""- task_summaries = []- for task in run.tasks:- task_summaries.append(- {- "id": task.id,- "agent_id": task.agent_id,- "status": task.status.value if hasattr(task.status, "value") else str(task.status),- "summary": task.summary or "",- "iterations": task.worker_iterations,- }- )+ from src.swarm.serialization import run_level_error, serialize_task++ task_summaries = [serialize_task(task) for task in run.tasks]status = "timeout" if timed_out else run.status.value@@ -716,6 +708,7 @@ def _format_result("preset": preset,"auto_variables": variables,"final_report": run.final_report or "",+ "error": run_level_error(run),"tasks": task_summaries,"token_usage": {"total_input_tokens": run.total_input_tokens,diff --git a/agent/src/tools/write_file_tool.py b/agent/src/tools/write_file_tool.pyindex 7069865f4..9be109224 100644--- a/agent/src/tools/write_file_tool.py+++ b/agent/src/tools/write_file_tool.py@@ -9,6 +9,7 @@ from typing import Anyfrom src.agent.tools import BaseToolfrom src.tools.path_utils import safe_path as _safe_pathfrom src.tools.path_utils import safe_run_dir as _safe_run_dir+from src.tools.redaction import redact_internal_pathsclass WriteFileTool(BaseTool):@@ -41,30 +42,42 @@ class WriteFileTool(BaseTool):run_dir = kwargs.get("run_dir")if not run_dir:- return json.dumps({- "status": "error",- "error": "run_dir is required for write_file",- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": "run_dir is required for write_file",+ },+ ensure_ascii=False,+ )try:run_root = _safe_run_dir(str(run_dir))resolved = _safe_path(file_path, run_root)except ValueError as exc:- return json.dumps({- "status": "error",- "error": str(exc),- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": str(exc),+ },+ ensure_ascii=False,+ )try:resolved.parent.mkdir(parents=True, exist_ok=True)resolved.write_text(content, encoding="utf-8")- return json.dumps({- "status": "ok",- "path": str(resolved),- "bytes_written": len(content.encode("utf-8")),- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "ok",+ "path": str(resolved),+ "bytes_written": len(content.encode("utf-8")),+ },+ ensure_ascii=False,+ )except Exception as exc:- return json.dumps({- "status": "error",- "error": str(exc),- }, ensure_ascii=False)+ return json.dumps(+ {+ "status": "error",+ "error": redact_internal_paths(str(exc)),+ },+ ensure_ascii=False,+ )diff --git a/agent/tests/test_error_path_redaction.py b/agent/tests/test_error_path_redaction.pynew file mode 100644index 000000000..0102bd4d7--- /dev/null+++ b/agent/tests/test_error_path_redaction.py@@ -0,0 +1,124 @@+"""Regression tests for P10 — user-facing errors must not leak internal+absolute filesystem paths (CWE-209 / CWE-497).++Pre-fix: an unknown preset / workspace-escape / missing run dir embedded the+full install path (OS username, .venvs/site-packages topology). Post-fix the+message keeps the actionable bits (name, Available list, the boundary) but+not the absolute path.+"""++from __future__ import annotations++import threading+from pathlib import Path++import pytest++import src.swarm.runtime as rt+from src.swarm.presets import load_preset+from src.swarm.store import SwarmStore+from src.swarm.models import SwarmAgentSpec, SwarmRun, SwarmTask, WorkerResult+from src.tools.path_utils import safe_path++_LEAKS = (str(Path.home()), "site-packages", ".venvs", str(Path.cwd()))+++def _assert_no_abs(msg: str):+ for marker in _LEAKS:+ assert marker not in msg, f"leaked {marker!r} in: {msg}"+++def test_unknown_preset_does_not_leak_path():+ with pytest.raises(FileNotFoundError) as ei:+ load_preset("nope_xyz_not_a_preset")+ msg = str(ei.value)+ _assert_no_abs(msg)+ assert "nope_xyz_not_a_preset" in msg and "Available" in msg # still actionable+++def test_workspace_escape_does_not_leak_root(tmp_path):+ with pytest.raises(ValueError) as ei:+ safe_path("../../../../etc/passwd", workdir=tmp_path)+ msg = str(ei.value)+ _assert_no_abs(msg)+ assert "escapes the workspace root" in msg+++def test_missing_run_dir_does_not_leak_abs(tmp_path):+ store = SwarmStore(base_dir=tmp_path / "runs")+ with pytest.raises(FileNotFoundError) as ei:+ store.update_run(SwarmRun(id="swarm-rid-001", preset_name="demo", created_at="2026-01-01T00:00:00Z"))+ msg = str(ei.value)+ _assert_no_abs(msg)+ assert "swarm-rid-001" in msg # logical id retained, absolute path dropped+++# --- P10 residual: swarm EVENT payloads (read_events / SSE / get_swarm_status)+# also project the raw error. update_status was redacted by G1 but the+# task_failed / run_error events still emitted raw text. These drive the real+# runtime hermetically (no network, no .env) and read the events back.++_ABS_LEAK = str(Path.home()) # an internal root redact_internal_paths anchors on+++def _drive_run(tmp_path: Path) -> tuple[SwarmStore, SwarmRun]:+ store = SwarmStore(base_dir=tmp_path)+ runtime = rt.SwarmRuntime(store=store)+ agent = SwarmAgentSpec(id="analyst", role="Analyst", system_prompt="x", max_retries=0)+ task = SwarmTask(id="t1", agent_id="analyst", prompt_template="do x")+ run = SwarmRun(+ id="r",+ preset_name="demo",+ created_at="2026-01-01T00:00:00Z",+ agents=[agent],+ tasks=[task],+ )+ store.create_run(run)+ runtime._execute_run(run, threading.Event())+ return store, run+++def _event_data(store: SwarmStore, run_id: str, event_type: str) -> dict:+ matches = [e for e in store.read_events(run_id) if e.type == event_type]+ assert matches, f"no {event_type!r} event emitted"+ return matches[-1].data+++def test_task_failed_event_does_not_leak_abs_path(tmp_path, monkeypatch):+ """task_failed event payload (surfaced via read_events/SSE/get_swarm_status)+ must redact the internal absolute path. Pre-fix: raw result.error → FAIL."""++ def fake_worker(*a, **k):+ return WorkerResult(+ status="failed",+ summary="",+ error=f"worker blew up writing {_ABS_LEAK}/secret/topology.log",+ )++ monkeypatch.setattr(rt, "run_worker", fake_worker)+ store, run = _drive_run(tmp_path)++ err = _event_data(store, run.id, "task_failed")["error"]+ assert _ABS_LEAK not in err, f"leaked abs path in task_failed event: {err}"+ assert "<redacted>" in err # boundary still actionable (relative tail kept)+ assert "secret/topology.log" in err or "secret\\topology.log" in err+++def test_run_error_event_does_not_leak_abs_path(tmp_path, monkeypatch):+ """A run-level exception that escapes the per-layer worker containment+ (caught by the top-level ``except Exception`` in _execute_run) surfaces via+ the run_error event. Worker-raised exceptions are absorbed into a failed+ WorkerResult by _execute_layer, so the run_error branch is only reachable+ by a structural failure of the layer machinery itself — injected here by+ failing _execute_layer. Pre-fix: raw str(exc) → FAIL."""++ def boom(*a, **k):+ raise RuntimeError(f"fatal: config missing under {_ABS_LEAK}/.venvs/cfg")++ monkeypatch.setattr(rt.SwarmRuntime, "_execute_layer", boom)+ store, run = _drive_run(tmp_path)++ err = _event_data(store, run.id, "run_error")["error"]+ assert _ABS_LEAK not in err, f"leaked abs path in run_error event: {err}"+ assert "<redacted>" in err+ assert ".venvs/cfg" in err or ".venvs\\cfg" in errdiff --git a/agent/tests/test_path_safety.py b/agent/tests/test_path_safety.pyindex 57924a5b6..a6cdd42e3 100644--- a/agent/tests/test_path_safety.py+++ b/agent/tests/test_path_safety.py@@ -23,12 +23,12 @@ class TestSafePath:assert result == (tmp_path / "sub" / "dir" / "file.txt").resolve()def test_parent_traversal_rejected(self, tmp_path: Path):- with pytest.raises(ValueError, match="escapes workspace"):+ with pytest.raises(ValueError, match="escapes the workspace"):safe_path("../../etc/passwd", tmp_path)def test_absolute_path_outside_workdir_rejected(self, tmp_path: Path):outside = tmp_path.parent / "elsewhere.txt"- with pytest.raises(ValueError, match="escapes workspace"):+ with pytest.raises(ValueError, match="escapes the workspace"):safe_path(str(outside), tmp_path)def test_unc_path_rejected(self, tmp_path: Path):diff --git a/agent/tests/test_redaction.py b/agent/tests/test_redaction.pynew file mode 100644index 000000000..f51955fe8--- /dev/null+++ b/agent/tests/test_redaction.py@@ -0,0 +1,35 @@+"""G1 evidence: anchored redaction — no over-redaction, idempotent, None-safe."""++from __future__ import annotations++from pathlib import Path++from src.tools.redaction import _internal_roots, redact_internal_paths+++def test_none_and_empty_and_nonstr_safe():+ assert redact_internal_paths(None) == ""+ assert redact_internal_paths("") == ""+ assert redact_internal_paths(42) == "42"+++def test_internal_leak_is_redacted_but_tail_kept():+ leak = str(Path.cwd() / "agent" / "runs" / "RUN42" / "run.json")+ out = redact_internal_paths(leak)+ assert "<redacted>" in out+ assert str(Path.cwd()) not in out+ assert "RUN42" in out and "run.json" in out+++def test_no_over_redaction_of_external_or_caller_paths():+ roots = _internal_roots()+ for keep in ("/etc/passwd", "/api/v1/orders", "../../etc/shadow", "D:\\external\\report.csv"):+ assert not any(rt in keep for rt in roots)+ assert redact_internal_paths(f"err: {keep}") == f"err: {keep}"+++def test_idempotent():+ leak = str(Path.home() / "agent" / "x" / "run.json")+ once = redact_internal_paths(leak)+ assert redact_internal_paths(once) == once+ assert "<redacted>" in oncediff --git a/agent/tests/test_swarm_error_surfacing.py b/agent/tests/test_swarm_error_surfacing.pynew file mode 100644index 000000000..7622f89fa--- /dev/null+++ b/agent/tests/test_swarm_error_surfacing.py@@ -0,0 +1,93 @@+"""Regression tests for P04 — a misconfigured LLM provider must surface a+diagnosable error from the swarm read boundaries.++The swarm already captures ``SwarmTask.error`` on disk; the bug was that every+read-side projection hand-maintained a field allowlist that omitted it, so the+caller saw ``status="failed"`` with no reason. These tests drive the *real*+``SwarmRuntime`` / ``SwarmStore`` with an injected worker failure (no network,+no ``.env`` access) and assert the error is BOTH captured AND surfaced.++Pre-fix: ``test_error_captured_*`` passes (capture was never broken);+``test_*_surfaces_error`` FAIL (the swallow). Post-fix: all pass.+"""++from __future__ import annotations++import json+import threading+from pathlib import Path++import httpx+import pytest+from openai import AuthenticationError++import mcp_server+import src.swarm.runtime as rt+from src.swarm.models import SwarmAgentSpec, SwarmRun, SwarmTask, WorkerResult+from src.swarm.store import SwarmStore+from src.tools.swarm_tool import _format_result+++def _run(tmp_path: Path) -> SwarmRun:+ store = SwarmStore(base_dir=tmp_path)+ runtime = rt.SwarmRuntime(store=store)+ agent = SwarmAgentSpec(id="analyst", role="Analyst", system_prompt="x", max_retries=0)+ task = SwarmTask(id="t1", agent_id="analyst", prompt_template="do x")+ run = SwarmRun(+ id="r",+ preset_name="demo",+ created_at="2026-01-01T00:00:00Z",+ agents=[agent],+ tasks=[task],+ )+ store.create_run(run)+ runtime._execute_run(run, threading.Event())+ reloaded = store.load_run(run.id)+ assert reloaded is not None+ return reloaded+++def auth_failure(monkeypatch):+ def fake_worker(*a, **k):+ resp = httpx.Response(401, request=httpx.Request("POST", "https://x/v1"))+ exc = AuthenticationError("Error code: 401 - bad key", response=resp, body=None)+ return WorkerResult(+ status="failed",+ summary="",+ error=f"LLM call failed at iteration 0: {exc}",+ )++ monkeypatch.setattr(rt, "run_worker", fake_worker)+++def test_error_captured_in_run_json(tmp_path, auth_failure):+ """Capture path must keep working (guards against a future regression)."""+ run = _run(tmp_path)+ assert run.tasks[0].error and "401" in run.tasks[0].error+++def test_get_run_result_surfaces_error(tmp_path, auth_failure):+ """get_run_result / get_swarm_status (_run_to_dict) must expose the error."""+ run = _run(tmp_path)+ view = mcp_server._run_to_dict(run)+ assert view.get("error") and "401" in view["error"]+ assert "401" in (view["tasks"][0].get("error") or "")+++def test_in_process_tool_surfaces_error(tmp_path, auth_failure):+ """The in-process run_swarm agent tool (_format_result) must expose it too."""+ view = json.loads(_format_result(_run(tmp_path), "demo", {}))+ assert "401" in json.dumps(view)+ assert view.get("error") and "401" in view["error"]+++def test_unset_model_runtime_error_surfaces(tmp_path, monkeypatch):+ """A RuntimeError raised above the worker try/except must surface too."""++ def boom(*a, **k):+ raise RuntimeError("LANGCHAIN_MODEL_NAME is not set")++ monkeypatch.setattr(rt, "run_worker", boom)+ run = _run(tmp_path)+ assert "LANGCHAIN_MODEL_NAME" in json.dumps(mcp_server._run_to_dict(run))diff --git a/agent/tests/test_swarm_output_contract.py b/agent/tests/test_swarm_output_contract.pynew file mode 100644index 000000000..30af4ce49--- /dev/null+++ b/agent/tests/test_swarm_output_contract.py@@ -0,0 +1,155 @@+"""Regression tests for P01 + P03 — swarm output contract.++A worker that produced no substantive deliverable (plan-only stub, mock+data, unparsed tool markup, raw tool envelope, or a data agent that made no+tool call and wrote no report) must NOT be reported ``completed``, and the+runtime must not fold ``timeout`` / ``token_limit`` / ``incomplete`` into a+successful run.++The ``test_timeout_terminal_*`` runtime test is the fail-before / pass-after+anchor: on the pre-fix code ``timeout`` was mapped to ``completed`` so the run+reported success; post-fix it is a failure. The content-contract unit tests+pin the new ``_classify_deliverable`` policy (Hybrid: content-sanity for all+agents, tool-evidence only for data agents — tool-less synthesis/editor roles+are intentionally NOT failed).+"""++from __future__ import annotations++import threading+from pathlib import Path++from src.swarm.models import (+ RunStatus,+ SwarmAgentSpec,+ SwarmRun,+ SwarmTask,+ WorkerResult,+)+from src.swarm.store import SwarmStore+from src.swarm.worker import (+ _classify_deliverable,+ _is_data_agent,+ _report_written,+)+import src.swarm.runtime as rt++PLAN_STUB = (+ "### Phase 1 — Plan\n"+ "1. Load the asset-allocation skill\n"+ "2. Fetch data\n\n"+ "### Phase 2 — Execute\n"+ "First, I'll load the necessary skills."+)+REAL_REPORT = (+ "# BTC-USDT — Short-Term View\n\n"+ "Spot fetched via okx: 81,704.6 (2026-05-05). 7d range 77,750–82,842.\n\n"+ "**Recommendation: accumulate on dips to 79k; invalidation below 77.5k.**\n"+ "Position 3% NAV, stop 76,900, target 86,000. Funding 0.035%/8h is elevated\n"+ "but not extreme; on-chain exchange reserves declining (bullish)."+)+++# ---- content contract (Hybrid policy) -------------------------------------+def test_plan_only_is_rejected():+ assert _classify_deliverable(PLAN_STUB, is_data_agent=True, report_written=False, data_tool_calls=0)+++def test_unparsed_tool_markup_is_rejected():+ txt = "<|tool▁calls▁begin|>function<tool_sep>load_skill"+ assert _classify_deliverable(txt, is_data_agent=False, report_written=False, data_tool_calls=0)+++def test_mock_data_is_rejected():+ txt = "### Risk Audit (Mock Data)\nWorst Drawdown: -23.5% | 95% VaR: -4.2%"+ assert _classify_deliverable(txt, is_data_agent=True, report_written=True, data_tool_calls=3)+++def test_raw_tool_envelope_is_rejected():+ txt = '{"status": "ok", "content": "<skill name=technical-basic>...</skill>"}'+ assert _classify_deliverable(txt, is_data_agent=False, report_written=False, data_tool_calls=1)+++def test_data_agent_without_evidence_is_rejected():+ assert _classify_deliverable(REAL_REPORT, is_data_agent=True, report_written=False, data_tool_calls=0)+++def test_synthesis_agent_prose_is_accepted():+ """FALSE-REJECT GUARD: a tool-less synthesis/editor agent that produced+ real prose with no tool calls and no report.md must pass."""+ assert _classify_deliverable(REAL_REPORT, is_data_agent=False, report_written=False, data_tool_calls=0) is None+++def test_real_report_is_accepted():+ assert _classify_deliverable(REAL_REPORT, is_data_agent=True, report_written=True, data_tool_calls=5) is None+++def test_is_data_agent_classification():+ synth = SwarmAgentSpec(id="editor", role="Editor", system_prompt="x", tools=["bash", "read_file", "write_file"])+ analyst = SwarmAgentSpec(+ id="onchain", role="On-Chain", system_prompt="x", tools=["bash", "write_file", "get_market_data"]+ )+ assert _is_data_agent(synth) is False+ assert _is_data_agent(analyst) is True+++def test_report_written_detection(tmp_path: Path):+ assert _report_written(tmp_path) is False+ (tmp_path / "report.md").write_text(" \n ", encoding="utf-8")+ assert _report_written(tmp_path) is False+ (tmp_path / "report.md").write_text("# Real report\nbuy.", encoding="utf-8")+ assert _report_written(tmp_path) is True+++# ---- runtime integrity ----------------------------------------------------+def _run(tmp_path: Path, worker_result: WorkerResult) -> SwarmRun:+ store = SwarmStore(base_dir=tmp_path)+ runtime = rt.SwarmRuntime(store=store)+ agent = SwarmAgentSpec(id="analyst", role="Analyst", system_prompt="x", max_retries=0)+ task = SwarmTask(id="t1", agent_id="analyst", prompt_template="do x")+ run = SwarmRun(id="r", preset_name="demo", created_at="2026-01-01T00:00:00Z", agents=[agent], tasks=[task])+ store.create_run(run)+ runtime._execute_run(run, threading.Event())+ reloaded = store.load_run(run.id)+ assert reloaded is not None+ return reloaded+++def test_timeout_terminal_run_not_completed(tmp_path, monkeypatch):+ """fail-before / pass-after anchor: timeout terminal must not be a success."""+ monkeypatch.setattr(+ rt,+ "run_worker",+ lambda *a, **k: WorkerResult(status="timeout", summary="partial work"),+ )+ run = _run(tmp_path, None)+ assert run.status != RunStatus.completed+ assert run.final_report is None+++def test_incomplete_terminal_run_not_completed(tmp_path, monkeypatch):+ monkeypatch.setattr(+ rt,+ "run_worker",+ lambda *a, **k: WorkerResult(+ status="incomplete",+ summary=PLAN_STUB,+ error="output contract not met: plan-only stub",+ ),+ )+ run = _run(tmp_path, None)+ assert run.status != RunStatus.completed+ assert run.final_report is None+ assert run.tasks[0].error and "plan-only" in run.tasks[0].error+++def test_genuine_completion_still_succeeds(tmp_path, monkeypatch):+ """Guard: a real deliverable must still complete and become final_report."""+ monkeypatch.setattr(+ rt,+ "run_worker",+ lambda *a, **k: WorkerResult(status="completed", summary=REAL_REPORT, iterations=4),+ )+ run = _run(tmp_path, None)+ assert run.status == RunStatus.completed+ assert run.final_report == REAL_REPORTdiff --git a/agent/tests/test_swarm_runs_root_and_shell_tools.py b/agent/tests/test_swarm_runs_root_and_shell_tools.pynew file mode 100644index 000000000..89a06095a--- /dev/null+++ b/agent/tests/test_swarm_runs_root_and_shell_tools.py@@ -0,0 +1,79 @@+"""Regression tests for P03-A (run-root / store single source of truth) and+P03-B (MCP swarm wrapper must thread include_shell_tools; the filtered+registry must not silently drop a requested tool).++P03-A: the swarm store location and the run-dir sandbox allow-list were each+derived independently as ``<agent_root>/.swarm/runs``. A packaging layout+where the two anchors resolved differently put every worker run_dir outside+the allow-list with no error. They now share ``swarm_runs_root()``.++P03-B: ``mcp_server.run_swarm`` called ``start_run`` without+``include_shell_tools``, so stdio MCP swarm workers silently lost ``bash`` and+could not execute their own scripts.+"""++from __future__ import annotations++import logging+import threading++from src.swarm.models import SwarmAgentSpec, SwarmRun, SwarmTask, WorkerResult+from src.swarm.store import SwarmStore, swarm_runs_root+from src.tools import build_filtered_registry, path_utils+import src.swarm.runtime as rt+++# ---- P03-A: single source of truth -----------------------------------------+def test_swarm_runs_root_is_an_allowed_run_root():+ """Whatever swarm_runs_root() returns MUST be inside the sandbox+ allow-list, otherwise every worker run_dir is rejected."""+ allowed = {p.resolve() for p in path_utils._allowed_run_roots()}+ assert swarm_runs_root().resolve() in allowed+++def test_default_run_roots_uses_single_source():+ assert swarm_runs_root() in path_utils._default_run_roots()+++def test_swarm_runs_root_stable_and_swarm_scoped():+ root = swarm_runs_root()+ assert root == swarm_runs_root() # deterministic+ assert root.name == "runs" and root.parent.name == ".swarm"+++# ---- P03-B: filtered registry must keep / not silently drop tools ----------+def test_filtered_registry_keeps_bash_when_shell_enabled():+ reg = build_filtered_registry(["bash", "read_file", "write_file", "load_skill"], include_shell_tools=True)+ assert "bash" in reg.tool_names+++def test_filtered_registry_warns_when_requested_tool_dropped(caplog):+ with caplog.at_level(logging.WARNING):+ reg = build_filtered_registry(["bash", "read_file", "write_file"], include_shell_tools=False)+ assert "bash" not in reg.tool_names+ assert any("bash" in r.message and r.levelno >= logging.WARNING for r in caplog.records), (+ "dropping a requested tool must be logged, not silent"+ )+++# ---- P03-B: include_shell_tools propagates to the worker -------------------+def test_execute_run_propagates_include_shell_tools(tmp_path, monkeypatch):+ """mcp_server now passes include_shell_tools into start_run; pin that the+ runtime forwards it all the way to run_worker."""+ captured: dict[str, object] = {}++ def fake_worker(*args, **kwargs):+ captured["include_shell_tools"] = kwargs.get("include_shell_tools")+ return WorkerResult(status="completed", summary="real deliverable: ok")++ monkeypatch.setattr(rt, "run_worker", fake_worker)++ store = SwarmStore(base_dir=tmp_path)+ runtime = rt.SwarmRuntime(store=store)+ agent = SwarmAgentSpec(id="analyst", role="Analyst", system_prompt="x", max_retries=0)+ task = SwarmTask(id="t1", agent_id="analyst", prompt_template="do x")+ run = SwarmRun(id="r", preset_name="demo", created_at="2026-01-01T00:00:00Z", agents=[agent], tasks=[task])+ store.create_run(run)+ runtime._execute_run(run, threading.Event(), include_shell_tools=True)++ assert captured.get("include_shell_tools") is Truediff --git a/agent/tests/test_swarm_store_atomic_write.py b/agent/tests/test_swarm_store_atomic_write.pynew file mode 100644index 000000000..927c5c647--- /dev/null+++ b/agent/tests/test_swarm_store_atomic_write.py@@ -0,0 +1,133 @@+"""Regression tests for P13 — SwarmStore atomic write/read must survive the+Windows concurrent-access race (os.replace WinError 5/32) deterministically.++The behaviour tests drive the public ``SwarmStore`` API with a fake+``os.replace`` and therefore run on BOTH pre- and post-fix code:+- pre-fix ``_atomic_write`` calls replace once -> a single transient failure+ propagates and ``update_run`` raises (test FAILS).+- post-fix it retries the WinError-scoped transient -> ``update_run`` lands+ (test PASSES).++A non-transient error must still raise immediately (no masking), the budget+is bounded, and POSIX behaviour is unchanged (a plain OSError without+``winerror`` is never treated as transient).+"""++from __future__ import annotations++import os++import pytest++import src.swarm.store as store_mod+from src.swarm.models import SwarmRun+from src.swarm.store import SwarmStore+++def _winerr(code: int) -> PermissionError:+ e = PermissionError(f"simulated WinError {code}")+ e.winerror = code # set even off-Windows so the test is deterministic+ return e+++def _run(rid: str = "r") -> SwarmRun:+ return SwarmRun(id=rid, preset_name="demo", created_at="2026-01-01T00:00:00Z")++[email protected](autouse=True)+def _no_sleep(monkeypatch):+ # Keep retry tests instant + deterministic.+ monkeypatch.setattr(store_mod.time, "sleep", lambda *_a, **_k: None)+++def test_replace_retries_transient_winerror_then_succeeds(tmp_path, monkeypatch):+ store = SwarmStore(base_dir=tmp_path)+ store.create_run(_run())++ real = os.replace+ calls = {"n": 0}++ def flaky(src, dst, *a, **k):+ calls["n"] += 1+ if calls["n"] <= 3: # fail the first 3 attempts with WinError 5+ raise _winerr(5)+ return real(src, dst, *a, **k)++ monkeypatch.setattr(store_mod.os, "replace", flaky)++ upd = _run()+ upd.final_report = "RETRIED-OK"+ store.update_run(upd) # pre-fix: raises on first WinError; post-fix: retries++ assert calls["n"] >= 4+ assert store.load_run("r").final_report == "RETRIED-OK"+++def test_non_transient_error_reraises_immediately(tmp_path, monkeypatch):+ store = SwarmStore(base_dir=tmp_path)+ store.create_run(_run())+ calls = {"n": 0}++ def boom(src, dst, *a, **k):+ calls["n"] += 1+ raise _winerr(2) # ERROR_FILE_NOT_FOUND — NOT in the transient set++ monkeypatch.setattr(store_mod.os, "replace", boom)+ with pytest.raises(OSError):+ store.update_run(_run())+ assert calls["n"] == 1, "non-transient must not be retried (no masking)"+++def test_transient_budget_is_bounded(tmp_path, monkeypatch):+ store = SwarmStore(base_dir=tmp_path)+ store.create_run(_run())+ calls = {"n": 0}++ def always(src, dst, *a, **k):+ calls["n"] += 1+ raise _winerr(32) # ERROR_SHARING_VIOLATION, forever++ monkeypatch.setattr(store_mod.os, "replace", always)+ with pytest.raises(OSError):+ store.update_run(_run())+ assert calls["n"] == store_mod._REPLACE_ATTEMPTS+++def test_load_run_retries_transient_read_then_parses(tmp_path, monkeypatch):+ store = SwarmStore(base_dir=tmp_path)+ store.create_run(_run())++ real_validate = SwarmRun.model_validate_json+ calls = {"n": 0}++ def flaky_validate(data, *a, **k):+ calls["n"] += 1+ if calls["n"] <= 2:+ raise ValueError("simulated partial-read / parse mid-replace")+ return real_validate(data, *a, **k)++ monkeypatch.setattr(store_mod.SwarmRun, "model_validate_json", staticmethod(flaky_validate))+ got = store.load_run("r")+ assert got is not None and got.id == "r"+ assert calls["n"] >= 3+++def test_load_run_missing_is_fast_none(tmp_path, monkeypatch):+ """Fast not-found path must stay immediate (guards get_run_result(bogus))."""+ store = SwarmStore(base_dir=tmp_path)++ def fail_read(*a, **k):+ raise AssertionError("read_text must not be called for a missing run")++ monkeypatch.setattr(store_mod.SwarmRun, "model_validate_json", staticmethod(lambda *a, **k: fail_read()))+ assert store.load_run("does-not-exist") is None+++def test_posix_oserror_is_not_treated_transient():+ """POSIX no-op guard: a plain OSError (no winerror) is never transient,+ so off-Windows the retry loop runs exactly once — no behavior change."""+ from src.swarm.store import _is_transient_windows_error++ assert _is_transient_windows_error(OSError("posix")) is False+ assert _is_transient_windows_error(_winerr(13)) is False+ assert _is_transient_windows_error(_winerr(5)) is True