"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(swarm): unified reconcile + MCP keepalive + heartbeat coverage (#132)
Haozhe Wucac3f0b5ed7d
diff --git a/agent/api_server.py b/agent/api_server.pyindex 9db33a982..24d59ff0e 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -1687,46 +1687,45 @@ async def create_swarm_run(payload: dict, http_request: Request):@app.get("/swarm/runs", dependencies=[Depends(require_auth)])async def list_swarm_runs(limit: int = Query(20, ge=1, le=100)):- """List swarm runs (newest first)."""+ """List swarm runs (newest first), reconciled."""runtime = _get_swarm_runtime()runs = runtime._store.list_runs(limit=limit)- return [- {- "id": r.id,- "preset_name": r.preset_name,- "status": r.status.value,- "created_at": r.created_at,- "task_count": len(r.tasks),- "completed_count": sum(1 for t in r.tasks if t.status.value == "completed"),- }- for r in runs- ]+ items = []+ for r in runs:+ # Reconcile each row: a zombie running run will be auto-finalized so+ # the dashboard never shows a permanent "running" stuck row.+ reconciled = runtime._store.reconcile_run(r, write=True)+ items.append(+ {+ "id": reconciled.id,+ "preset_name": reconciled.preset_name,+ "status": reconciled.status.value,+ "is_stale": runtime._store.is_run_stale(reconciled),+ "created_at": reconciled.created_at,+ "completed_at": reconciled.completed_at,+ "task_count": len(reconciled.tasks),+ "completed_count": sum(1 for t in reconciled.tasks if t.status.value == "completed"),+ }+ )+ return items@app.get("/swarm/runs/{run_id}", dependencies=[Depends(require_auth)])async def get_swarm_run(run_id: str):- """Swarm run detail including task statuses."""- from src.swarm.task_store import TaskStore-+ """Swarm run detail including task statuses (reconciled)."""_validate_path_param(run_id, "run_id")runtime = _get_swarm_runtime()- run = runtime._store.load_run(run_id)- if not run:+ loaded = runtime._store.load_run(run_id)+ if not loaded:raise HTTPException(status_code=404, detail=f"Run {run_id} not found")- # Merge real-time task statuses from task_store (updated during execution)- run_dir = runtime._store.run_dir(run_id)- tasks_dir = run_dir / "tasks"- if tasks_dir.exists():- task_store = TaskStore(run_dir)- live_tasks = task_store.load_all()- if live_tasks:- run.tasks = live_tasks+ run = runtime._store.reconcile_run(loaded, write=True)return {"id": run.id,"preset_name": run.preset_name,"status": run.status.value,+ "is_stale": runtime._store.is_run_stale(run),"user_vars": run.user_vars,"agents": [a.model_dump() for a in run.agents],"tasks": [t.model_dump() for t in run.tasks],@@ -1754,9 +1753,14 @@ async def swarm_run_events(run_id: str, request: Request, last_index: int = Queridx += 1yield f"id: {idx}\nevent: {evt.type}\ndata: {json.dumps(evt.model_dump(), ensure_ascii=False)}\n\n"run = runtime._store.load_run(run_id)- if run and run.status.value in ("completed", "failed", "cancelled"):- yield f"event: done\ndata: {{\"status\": \"{run.status.value}\"}}\n\n"- break+ if run:+ # Reconcile so a zombie running run can still close this SSE+ # stream cleanly — without it, a dead host would keep the+ # stream open forever and block the dashboard's "done" state.+ reconciled = runtime._store.reconcile_run(run, write=True)+ if reconciled.status.value in ("completed", "failed", "cancelled"):+ yield f"event: done\ndata: {{\"status\": \"{reconciled.status.value}\"}}\n\n"+ breakawait asyncio.sleep(2)return StreamingResponse(event_stream(), media_type="text/event-stream")diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex 2a1204ca0..260bf73f0 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -40,7 +40,7 @@ AGENT_DIR = Path(__file__).resolve().parentif str(AGENT_DIR) not in sys.path:sys.path.insert(0, str(AGENT_DIR))-from fastmcp import FastMCP+from fastmcp import Context, FastMCPmcp = FastMCP("Vibe-Trading")@@ -356,8 +356,14 @@ def list_swarm_presets() -> str:@mcp.tool-def run_swarm(preset_name: str, variables: dict[str, str]) -> str:- """Run a swarm multi-agent team and return the final report.+async def run_swarm(+ preset_name: str,+ variables: dict[str, str],+ wait_seconds: int = 3600,+ start_only: bool = False,+ ctx: Context | None = None,+) -> str:+ """Run a swarm multi-agent team and stream progress back to the caller.Assembles a team of specialized agents that collaborate through a DAG workflow.For example, the 'investment_committee' preset runs bull analyst, bear analyst,@@ -365,14 +371,25 @@ def run_swarm(preset_name: str, variables: dict[str, str]) -> str:Use list_swarm_presets() to see available presets and their required variables.+ The tool keeps the MCP call open via ``Context.report_progress`` while the+ swarm runs, so the caller sees live "N/M tasks complete" updates instead+ of timing out silently. Only if ``wait_seconds`` is exhausted does the+ tool return early with the current ``run_id`` — call ``get_run_result``+ afterwards to fetch the final report.+Args:preset_name: Swarm preset name (e.g. 'investment_committee', 'quant_strategy_desk').variables: Required variables for the preset (e.g. {"target": "AAPL.US", "market": "US"}).+ wait_seconds: Maximum seconds to keep the MCP call open. Default 3600+ (1 hour); the progress-notification keepalive means the transport+ stays connected for the full budget.+ start_only: If True, kick off the run and return immediately with+ ``run_id`` + current status. Ignores ``wait_seconds``."""+ import asyncioimport timefrom src.swarm.runtime import SwarmRuntimefrom src.swarm.store import SwarmStore, swarm_runs_root- from src.swarm.models import RunStatusswarm_dir = swarm_runs_root()store = SwarmStore(base_dir=swarm_dir)@@ -387,32 +404,62 @@ def run_swarm(preset_name: str, variables: dict[str, str]) -> str:except ValueError as exc:return json.dumps({"status": "error", "error": f"DAG validation failed: {exc}"}, ensure_ascii=False)- # Poll until complete (max 30 minutes)- for _ in range(360):- time.sleep(5)- current = store.load_run(run.id)- 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):- 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,- },- ensure_ascii=False,- indent=2,- )+ if start_only or wait_seconds <= 0:+ return json.dumps(+ _build_run_payload(store, run.id, preset_name, timed_out=False),+ ensure_ascii=False,+ indent=2,+ )- return json.dumps({"status": "error", "error": "Swarm timed out after 30 minutes"}, ensure_ascii=False)+ # Surface the run_id immediately in a fixed-format progress message so a+ # caller whose transport drops mid-run (or whose MCP client enforces a+ # hard tool-call timeout that ignores progress notifications) can still+ # recover the run via ``get_run_result(run_id)``. Parsers should match+ # ``swarm_started run_id=<id>`` literally; later frames are free-form.+ if ctx is not None:+ try:+ await ctx.report_progress(+ progress=0,+ total=1,+ message=f"swarm_started run_id={run.id} preset={preset_name}",+ )+ except Exception:+ pass++ terminal = {"completed", "failed", "cancelled"}+ started_at = time.monotonic()+ deadline = started_at + wait_seconds+ while True:+ payload = _build_run_payload(store, run.id, preset_name, timed_out=False)+ if payload["status"] == "error":+ return json.dumps(payload, ensure_ascii=False)+ if payload["status"] in terminal:+ return json.dumps(payload, ensure_ascii=False, indent=2)++ # Emit a progress frame every loop, NOT only on state change — MCP+ # clients use these as transport keepalive. A long task that doesn't+ # transition for 30 minutes still needs ticks or the client times out.+ # ``elapsed`` keeps the message content fresh so dedup-on-message+ # clients still see updates.+ if ctx is not None:+ tasks = payload.get("tasks") or []+ total = max(1, len(tasks))+ done = sum(1 for t in tasks if t.get("status") in terminal)+ elapsed = int(time.monotonic() - started_at)+ try:+ await ctx.report_progress(+ progress=done,+ total=total,+ message=f"{done}/{total} tasks complete · {elapsed}s elapsed (run {run.id})",+ )+ except Exception:+ pass++ remaining = deadline - time.monotonic()+ if remaining <= 0:+ payload = _build_run_payload(store, run.id, preset_name, timed_out=True)+ return json.dumps(payload, ensure_ascii=False, indent=2)+ await asyncio.sleep(min(5.0, remaining))# ---------------------------------------------------------------------------@@ -561,7 +608,18 @@ def _get_swarm_store():return SwarmStore(base_dir=swarm_dir)-def _run_to_dict(run) -> dict:+def _run_to_dict(run, *, timed_out: bool = False, is_stale: bool = False) -> dict:+ """Public projection of a (live-hydrated) :class:`SwarmRun`.++ ``timed_out`` flips on only for the ``run_swarm`` wait-budget path. It does+ not change the run's actual status — callers can still see ``running`` and+ fetch the final report later via :func:`get_run_result`.++ ``is_stale`` is a read-only signal: ``True`` means the run is still+ ``running`` but its events.jsonl has been silent past the per-run+ threshold. No disk state is changed by setting this — the explicit+ :func:`reap_stale_runs` tool is what finalizes a stale run.+ """from src.swarm.serialization import run_level_error, serialize_taskreturn {@@ -569,20 +627,44 @@ def _run_to_dict(run) -> dict:"status": run.status.value,"preset": run.preset_name,"created_at": run.created_at,+ "completed_at": run.completed_at,"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,+ "timed_out": timed_out,+ "is_stale": is_stale,}+def _build_run_payload(store, run_id: str, preset_name: str | None, *, timed_out: bool) -> dict:+ """Reconcile + project a run for the MCP response.++ Used by ``run_swarm`` (polling + start_only). Returns a normal payload on+ success and a ``{"status": "error", ...}`` envelope when the run record+ disappears (mid-run directory wipe / sandbox eviction).+ """+ run = store.load_run(run_id)+ if run is None:+ return {"status": "error", "error": "Run record lost", "run_id": run_id}+ reconciled = store.reconcile_run(run, write=True)+ payload = _run_to_dict(+ reconciled,+ timed_out=timed_out,+ is_stale=store.is_run_stale(reconciled),+ )+ if preset_name:+ payload["preset"] = preset_name+ return payload++@mcp.tooldef get_swarm_status(run_id: str) -> str:"""Get the current status of a swarm run.- Returns status, task progress, and token usage for the specified run.- Use this to poll a long-running swarm without blocking.+ Returns status, task progress, token usage, and an ``is_stale`` flag for+ the specified run. Use this to poll a long-running swarm without blocking.Args:run_id: The run ID returned by run_swarm.@@ -591,15 +673,22 @@ def get_swarm_status(run_id: str) -> str:run = store.load_run(run_id)if run is None:return json.dumps({"status": "error", "error": f"Run {run_id} not found"}, ensure_ascii=False)- return json.dumps(_run_to_dict(run), ensure_ascii=False, indent=2)+ reconciled = store.reconcile_run(run, write=True)+ return json.dumps(+ _run_to_dict(reconciled, is_stale=store.is_run_stale(reconciled)),+ ensure_ascii=False,+ indent=2,+ )@mcp.tooldef get_run_result(run_id: str) -> str:- """Get the final report and task summaries of a completed swarm run.+ """Get the final report and task summaries of a swarm run.- Returns the final_report text and per-task summaries. If the run is- still in progress, returns current status instead.+ Reconciles the run on read: an orphaned ``running`` run whose host+ process exited will be transitioned to its real terminal status+ (``completed`` / ``failed`` / ``cancelled`` derived from the task+ statuses), so the caller never sees a permanent zombie.Args:run_id: The run ID returned by run_swarm.@@ -608,15 +697,18 @@ def get_run_result(run_id: str) -> str:run = store.load_run(run_id)if run is None:return json.dumps({"status": "error", "error": f"Run {run_id} not found"}, ensure_ascii=False)- return json.dumps(_run_to_dict(run), ensure_ascii=False, indent=2)+ reconciled = store.reconcile_run(run, write=True)+ payload = _run_to_dict(reconciled, is_stale=store.is_run_stale(reconciled))+ payload["ready"] = payload["status"] in {"completed", "failed", "cancelled"}+ return json.dumps(payload, ensure_ascii=False, indent=2)@mcp.tooldef list_runs(limit: int = 20) -> str:"""List recent swarm runs sorted by creation time (newest first).- Returns run IDs, presets, statuses, and creation timestamps.- Use get_run_result(run_id) to fetch full details for a specific run.+ Each row includes task counts and an ``is_stale`` flag so callers can+ spot abandoned runs without a follow-up status call.Args:limit: Maximum number of runs to return (default 20).@@ -625,19 +717,46 @@ def list_runs(limit: int = 20) -> str:runs = store.list_runs(limit=limit)items = []for run in runs:+ # write=True so a zombie listed alongside live runs gets finalized;+ # the cost is bounded by ``limit`` (default 20) and most rows are+ # already terminal — reconcile is a no-op for those.+ reconciled = store.reconcile_run(run, write=True)+ counts = {"total": len(reconciled.tasks)}+ for t in reconciled.tasks:+ counts[t.status.value] = counts.get(t.status.value, 0) + 1items.append({- "run_id": run.id,- "preset": run.preset_name,- "status": run.status.value,- "created_at": run.created_at,- "total_input_tokens": run.total_input_tokens,- "total_output_tokens": run.total_output_tokens,+ "run_id": reconciled.id,+ "preset": reconciled.preset_name,+ "status": reconciled.status.value,+ "is_stale": store.is_run_stale(reconciled),+ "created_at": reconciled.created_at,+ "completed_at": reconciled.completed_at,+ "task_counts": counts,+ "total_input_tokens": reconciled.total_input_tokens,+ "total_output_tokens": reconciled.total_output_tokens,})return json.dumps(items, ensure_ascii=False, indent=2)+def reap_stale_runs() -> str:+ """Mark every ``running`` run whose host process died as ``failed``.++ Walks the swarm store, applies the per-run stale threshold, and+ finalizes any run that has gone silent past it (writes ``run.json`` ++ ``tasks/*.json`` + appends a ``run_reaped`` event). Already-terminal+ runs and still-alive runs are left untouched.++ Returns:+ JSON list of reaped run IDs (empty when nothing was stale).+ """+ store = _get_swarm_store()+ reaped = store.reap_stale_running_runs()+ return json.dumps({"reaped": reaped}, ensure_ascii=False, indent=2)++# ---------------------------------------------------------------------------# Trade journal tool# ---------------------------------------------------------------------------diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.pyindex 56a9f6eb1..051a85b56 100644--- a/agent/src/swarm/runtime.py+++ b/agent/src/swarm/runtime.py@@ -91,6 +91,17 @@ class SwarmRuntime:FileNotFoundError: If preset does not exist.ValueError: If DAG validation fails."""+ # Reap any previously running runs whose host process died without+ # finalizing them. Threshold is computed per-run from agent timeouts ++ # heartbeat interval (see SwarmStore.compute_stale_threshold), so a+ # legitimately slow long-running task is not killed.+ try:+ reaped = self._store.reap_stale_running_runs()+ if reaped:+ logger.info("Reaped %d stale swarm run(s): %s", len(reaped), reaped)+ except Exception:+ logger.warning("Stale-run reaper failed", exc_info=True)+run = build_run_from_preset(preset_name, user_vars)validate_dag(run.tasks)@@ -317,6 +328,11 @@ class SwarmRuntime:),)+ # Snapshot run.json at the layer boundary so list_runs and any+ # client that reads run.json directly sees fresh task statuses+ # without per-task I/O spam. One write per layer is cheap.+ self._sync_run_tasks_snapshot(run, task_store)+except Exception as exc:logger.error("Run %s failed with exception", run_id, exc_info=True)all_succeeded = False@@ -351,6 +367,20 @@ class SwarmRuntime:self._cancel_events.pop(run_id, None)self._live_callbacks.pop(run_id, None)+ def _sync_run_tasks_snapshot(self, run: SwarmRun, task_store: TaskStore) -> None:+ """Mirror live ``tasks/*.json`` back into ``run.json`` at a safe point.++ Called at layer boundaries only — not per-task — to keep run.json a+ useful coarse snapshot for ``list_runs`` and CLI/Web callers that+ don't hydrate per request. Failures are logged but never fatal: the+ per-task files are still the live source of truth.+ """+ try:+ run.tasks = task_store.load_all()+ self._store.update_run(run)+ except Exception:+ logger.warning("Layer-boundary run.json sync failed", exc_info=True)+def _prefetch_grounding_data(self, run: SwarmRun) -> None:"""Fetch run-level grounding data without blocking ``start_run``."""symbols = grounding.extract_symbols_from_user_vars(run.user_vars)@@ -367,8 +397,33 @@ class SwarmRuntime:)symbols = symbols[:symbol_limit]+ # Multi-symbol grounding fetch can take 30s+ on slow loaders. Wrap it+ # in a heartbeat so events.jsonl gets fresh entries during the fetch+ # — without this, the stale-run reaper would false-positive-mark a+ # healthy fresh run that's just waiting on OHLCV API calls.+ from src.agent.progress import HeartbeatTimer++ def _on_grounding_heartbeat(payload: dict) -> None:+ self._emit_event(+ run.id,+ self._make_event(+ "run_heartbeat",+ data={**payload, "phase": "grounding"},+ ),+ )++ try:+ interval = float(os.getenv("SWARM_HEARTBEAT_INTERVAL_S", "3.0"))+ except ValueError:+ interval = 3.0+try:- fetched = grounding.fetch_grounding_data(symbols)+ with HeartbeatTimer(+ tool_name=f"grounding:{len(symbols)}symbols",+ interval=interval,+ emit=_on_grounding_heartbeat,+ ):+ fetched = grounding.fetch_grounding_data(symbols)except Exception:logger.warning("grounding: pre-fetch failed for run %s symbols=%s",diff --git a/agent/src/swarm/serialization.py b/agent/src/swarm/serialization.pyindex 660d2e02d..9e57f4aa9 100644--- a/agent/src/swarm/serialization.py+++ b/agent/src/swarm/serialization.py@@ -31,6 +31,10 @@ def serialize_task(task: Any) -> dict:"summary": task.summary,"iterations": getattr(task, "worker_iterations", 0),"error": redact_internal_paths(getattr(task, "error", None)) or None,+ "started_at": getattr(task, "started_at", None),+ "completed_at": getattr(task, "completed_at", None),+ "depends_on": list(getattr(task, "depends_on", []) or []),+ "blocked_by": list(getattr(task, "blocked_by", []) or []),}diff --git a/agent/src/swarm/store.py b/agent/src/swarm/store.pyindex 65ffc856a..556e6f72e 100644--- a/agent/src/swarm/store.py+++ b/agent/src/swarm/store.py@@ -15,12 +15,50 @@ import jsonimport osimport threadingimport time+from datetime import datetime, timezonefrom pathlib import Pathfrom src.swarm.models import SwarmEvent, SwarmRunfrom src.tools.redaction import redact_internal_paths+def _parse_iso(value: str | None) -> datetime | None:+ if not value:+ return None+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.utc)+ return parsed.astimezone(timezone.utc)+++def _last_event_timestamp(events_file: Path) -> datetime | None:+ """Return the timestamp of the last line in ``events.jsonl``.++ Used by the stale-run reaper. Returns ``None`` when the file is missing,+ empty, or the tail line cannot be parsed — callers treat that as+ "no liveness signal" and skip the run.+ """+ if not events_file.exists():+ return None+ try:+ text = events_file.read_text(encoding="utf-8")+ except OSError:+ return None+ for line in reversed(text.splitlines()):+ stripped = line.strip()+ if not stripped:+ continue+ try:+ payload = json.loads(stripped)+ except ValueError:+ continue+ return _parse_iso(payload.get("timestamp"))+ return None++def swarm_runs_root() -> Path:"""Single source of truth for where swarm runs are persisted.@@ -228,6 +266,278 @@ class SwarmStore:events.append(SwarmEvent.model_validate_json(stripped))return events+ def hydrate_run(self, run: SwarmRun) -> SwarmRun:+ """Return a copy of ``run`` with live ``tasks/*.json`` merged in.++ ``run.json`` only gets the full snapshot at start and finalize; the+ per-task files are the live source of truth while execution is in+ flight. Readers (MCP / API / agent tool) call this before serializing+ so callers see the actual task progress instead of the stale snapshot.++ Pure function: no disk writes, returns a new ``SwarmRun`` via+ :meth:`pydantic.BaseModel.model_copy`. Falls back to ``run`` unchanged+ when no task files exist.+ """+ from src.swarm.task_store import TaskStore++ tasks_dir = self.run_dir(run.id) / "tasks"+ if not tasks_dir.exists():+ return run+ live = TaskStore(self.run_dir(run.id)).load_all()+ if not live:+ return run+ by_id = {task.id: task for task in live}+ merged = [by_id.get(task.id, task) for task in run.tasks]+ # Surface any task that only exists in the live store (defensive — DAG+ # validation runs at start_run so it shouldn't happen, but a future+ # caller that mutates the task set will not silently drop tasks).+ seen = {task.id for task in merged}+ merged.extend(task for tid, task in by_id.items() if tid not in seen)+ return run.model_copy(update={"tasks": merged})++ def compute_stale_threshold(self, run: SwarmRun) -> float:+ """Per-run silence budget before a ``running`` run looks abandoned.++ With ``HeartbeatTimer`` wrapping ``registry.execute`` in the swarm+ worker, the events.jsonl tail gets a fresh entry every+ ``SWARM_HEARTBEAT_INTERVAL_S`` (default 3s) while a tool call is+ running. Missing ~10 heartbeats in a row means the host has stopped+ making progress — so the natural threshold is ``heartbeat × 10``+ (≈30s by default).++ We clamp the upper bound to ``max(agent.timeout × (retries+1)) + 60s``+ so a misconfigured / disabled heartbeat (e.g. interval set to 10min)+ cannot push detection latency past the run's own retry budget. And+ we hold a 60s lower bound so a very tight heartbeat doesn't false-+ positive on routine sub-second event gaps.++ Returns:+ Seconds of event silence after which the run should be reaped.+ """+ try:+ interval = float(os.getenv("SWARM_HEARTBEAT_INTERVAL_S", "3.0"))+ except ValueError:+ interval = 3.0+ heartbeat_floor = max(60.0, interval * 10.0)++ agent_budgets = [+ max(1, int(agent.timeout_seconds or 300)) * (max(0, int(agent.max_retries)) + 1)+ for agent in run.agents+ ]+ retry_ceiling = (max(agent_budgets) if agent_budgets else 300) + 60++ return float(max(60.0, min(heartbeat_floor, retry_ceiling)))++ def is_run_stale(self, run: SwarmRun, *, now: datetime | None = None) -> bool:+ """Read-only check: is this ``running`` run silent past its threshold?++ Used by both the read paths (return ``is_stale`` to callers without+ writing) and the reaper (only mark failed when this returns True).+ Returns False for any non-running run so callers don't accidentally+ flag completed/cancelled runs.+ """+ from src.swarm.models import RunStatus++ if run.status != RunStatus.running:+ return False+ last_activity = _last_event_timestamp(self.run_dir(run.id) / "events.jsonl")+ last_activity = last_activity or _parse_iso(run.created_at)+ if last_activity is None:+ return False+ now = now or datetime.now(timezone.utc)+ return (now - last_activity).total_seconds() > self.compute_stale_threshold(run)++ def reconcile_run(self, run: SwarmRun, *, write: bool = True) -> SwarmRun:+ """Single source of truth for "what does this run actually look like".++ Three layered transforms, applied in order to ``run``:++ 1. **Hydrate**: merge live ``tasks/*.json`` into ``run.tasks`` so+ callers never see the stale start-of-run snapshot.+ 2. **Terminal recovery**: if every task is terminal but ``run.status``+ is still ``running``, derive the real run status from the task+ statuses (all completed → ``completed``; any failed → ``failed``;+ else ``cancelled``) and fill ``final_report`` from the last+ completed task's summary. Handles the "host crashed between the+ last layer sync and finalize" case.+ 3. **Stale reap**: if the run is still ``running`` past its+ heartbeat-based threshold, mark non-terminal tasks ``failed`` with+ a diagnostic error and the run ``failed``.++ ``write=True`` persists any state change to ``run.json`` /+ ``tasks/*.json`` and appends a recovery event. ``write=False`` returns+ the reconciled view in memory only — used by ``list_runs`` so a+ 20-row listing doesn't fire 20 disk writes (the next read of any+ affected row will persist if needed).++ Args:+ run: The ``SwarmRun`` loaded from ``run.json``.+ write: Persist recovered state if it differs from on-disk.++ Returns:+ Reconciled ``SwarmRun`` (a new instance — original is not mutated).+ """+ from src.swarm.models import RunStatus, TaskStatus++ hydrated = self.hydrate_run(run)+ now = datetime.now(timezone.utc)+ terminal_run = {RunStatus.completed, RunStatus.failed, RunStatus.cancelled}+ terminal_task = {TaskStatus.completed, TaskStatus.failed, TaskStatus.cancelled}++ if hydrated.status in terminal_run:+ return hydrated++ all_terminal = bool(hydrated.tasks) and all(t.status in terminal_task for t in hydrated.tasks)+ if all_terminal:+ recovered = self._recover_terminal(hydrated, now=now)+ if write and recovered is not hydrated:+ self._persist_recovery(recovered, kind="run_recovered_terminal", reason="all tasks terminal")+ return recovered++ if self.is_run_stale(hydrated, now=now):+ reaped = self._reap_stale(hydrated, now=now)+ if write and reaped is not hydrated:+ threshold = int(self.compute_stale_threshold(hydrated))+ self._persist_recovery(+ reaped,+ kind="run_reaped",+ reason=f"no event for >{threshold}s; host process likely exited",+ extra={"stale_seconds": threshold},+ )+ return reaped++ return hydrated++ def _recover_terminal(self, run: SwarmRun, *, now: datetime) -> SwarmRun:+ """Pure: derive a terminal SwarmRun from already-terminal tasks."""+ from src.swarm.models import RunStatus, TaskStatus++ statuses = {t.status for t in run.tasks}+ if statuses <= {TaskStatus.completed}:+ new_status = RunStatus.completed+ elif TaskStatus.failed in statuses:+ new_status = RunStatus.failed+ elif statuses <= {TaskStatus.cancelled, TaskStatus.completed}:+ new_status = RunStatus.cancelled+ else:+ new_status = RunStatus.failed++ final_report = run.final_report+ if new_status == RunStatus.completed and not final_report:+ for task in reversed(run.tasks):+ if task.summary:+ final_report = task.summary+ break++ return run.model_copy(+ update={+ "status": new_status,+ "completed_at": run.completed_at or now.isoformat(),+ "final_report": final_report,+ }+ )++ def _reap_stale(self, run: SwarmRun, *, now: datetime) -> SwarmRun:+ """Pure: mark non-terminal tasks failed; derive run status from tasks."""+ from src.swarm.models import RunStatus, TaskStatus++ terminal_task = {TaskStatus.completed, TaskStatus.failed, TaskStatus.cancelled}+ last_event_at = _last_event_timestamp(self.run_dir(run.id) / "events.jsonl")+ threshold = int(self.compute_stale_threshold(run))+ error_msg = (+ f"Run reaped: no event for >{threshold}s "+ f"(last event at {last_event_at.isoformat() if last_event_at else 'never'}); "+ "host process likely exited before completion."+ )++ updated_tasks = []+ for task in run.tasks:+ if task.status in terminal_task:+ updated_tasks.append(task)+ else:+ updated_tasks.append(+ task.model_copy(+ update={+ "status": TaskStatus.failed,+ "error": error_msg,+ "completed_at": now.isoformat(),+ }+ )+ )++ # Same derivation as terminal recovery — if every task happened to be+ # completed before the host died, the run is completed, not failed.+ post = run.model_copy(update={"tasks": updated_tasks})+ return self._recover_terminal(post, now=now)++ def _persist_recovery(+ self,+ run: SwarmRun,+ *,+ kind: str,+ reason: str,+ extra: dict | None = None,+ ) -> None:+ """Write a reconciled SwarmRun back to disk and append a recovery event.++ Idempotent: when a recovery event of the same kind already exists,+ the disk update still runs (so duplicate readers converge) but no+ second event is appended.+ """+ from src.swarm.task_store import TaskStore++ try:+ task_store = TaskStore(self.run_dir(run.id))+ for task in run.tasks:+ task_store.save_task(task)+ self.update_run(run)+ except Exception: # pragma: no cover — best-effort sweep+ logger = __import__("logging").getLogger(__name__)+ logger.warning("Failed to persist reconciliation for run %s", run.id, exc_info=True)+ return++ existing = self.read_events(run.id)+ if any(e.type == kind for e in existing):+ return+ try:+ data = {"reason": reason}+ if extra:+ data.update(extra)+ self.append_event(+ run.id,+ SwarmEvent(+ type=kind,+ data=data,+ timestamp=datetime.now(timezone.utc).isoformat(),+ ),+ )+ except Exception: # pragma: no cover+ pass++ def reap_stale_running_runs(self) -> list[str]:+ """Sweep all run directories and reconcile each one.++ Returns IDs of runs whose status flipped from ``running`` to a+ terminal status — useful for log/telemetry and for the explicit+ ``reap_stale_runs`` MCP tool.+ """+ from src.swarm.models import RunStatus++ if not self.base_dir.exists():+ return []++ reaped: list[str] = []+ for entry in self.base_dir.iterdir():+ if not entry.is_dir():+ continue+ run = self.load_run(entry.name)+ if run is None or run.status != RunStatus.running:+ continue+ reconciled = self.reconcile_run(run, write=True)+ if reconciled.status != RunStatus.running:+ reaped.append(run.id)+ return reaped+def _atomic_write(self, path: Path, content: str) -> None:"""Atomically write a file: write to .tmp then rename.diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex c351fa8a4..629c15e07 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -15,6 +15,7 @@ from pathlib import Pathfrom typing import Callablefrom src.agent.context import ContextBuilder+from src.agent.progress import HeartbeatTimerfrom src.agent.skills import SkillsLoaderfrom src.providers.chat import ChatLLMfrom src.swarm.models import (@@ -29,6 +30,22 @@ logger = logging.getLogger(__name__)_DEFAULT_MAX_ITERATIONS = int(os.getenv("SWARM_WORKER_MAX_ITER", "50"))_DEFAULT_TIMEOUT_SECONDS = int(os.getenv("SWARM_WORKER_TIMEOUT", "300"))+++def _heartbeat_interval_s() -> float:+ """Resolve the heartbeat tick interval from env, robust to garbage values.++ Matches the parsing discipline in :func:`SwarmStore.compute_stale_threshold`+ — both sides use the same env var, so they must fail the same way. A bad+ value (``"abc"``, empty) falls back to 3.0s instead of crashing import.+ """+ try:+ return float(os.getenv("SWARM_HEARTBEAT_INTERVAL_S", "3.0"))+ except ValueError:+ return 3.0+++_HEARTBEAT_INTERVAL_S = _heartbeat_interval_s()_MAX_TOKEN_ESTIMATE = 60_000_SENSITIVE_TOOL_ARGUMENT_KEYS = {"api_key",@@ -416,12 +433,34 @@ def run_worker(_emit(event_callback, "worker_text", agent_id, task_id,{"content": delta, "iteration": iteration})- response = llm.stream_chat(- messages,- tools=tool_defs,- timeout=remaining_timeout,- on_text_chunk=_on_text_chunk,- )+ # LLM streaming can stall for 30s+ between request start and the+ # first text chunk (slow first-token providers, reasoning models'+ # think phase, pure-tool-call responses with no text). Without a+ # ticker, the stale-run reaper would mark a healthy run failed+ # the moment its silence exceeds the heartbeat-based threshold.+ # Wrap the call in the same HeartbeatTimer used for tool execution+ # so events.jsonl gets a fresh entry every few seconds no matter+ # what the provider is doing.+ def _on_llm_heartbeat(payload: dict) -> None:+ _emit(+ event_callback,+ "task_heartbeat",+ agent_id,+ task_id,+ {**payload, "iteration": iteration, "phase": "llm"},+ )++ with HeartbeatTimer(+ tool_name=f"llm:{agent_spec.model_name or 'default'}",+ interval=_HEARTBEAT_INTERVAL_S,+ emit=_on_llm_heartbeat,+ ):+ response = llm.stream_chat(+ messages,+ tools=tool_defs,+ timeout=remaining_timeout,+ on_text_chunk=_on_text_chunk,+ )except Exception as exc:error_msg = f"LLM call failed at iteration {iteration}: {exc}"logger.warning(error_msg)@@ -496,7 +535,26 @@ def run_worker()tc_start = time.monotonic()args = {**tc.arguments, "run_dir": str(artifact_dir)}- result = registry.execute(tc.name, args)++ # Wrap tool execution in a heartbeat so the events.jsonl tail has a+ # fresh timestamp every few seconds. The stale-run reaper relies on+ # this signal to tell a hung tool call apart from a dead host; the+ # CLI dashboard / SSE clients also get live "still working" ticks.+ def _on_heartbeat(payload: dict) -> None:+ _emit(+ event_callback,+ "task_heartbeat",+ agent_id,+ task_id,+ {**payload, "iteration": iteration, "phase": "tool"},+ )++ with HeartbeatTimer(+ tool_name=tc.name,+ interval=_HEARTBEAT_INTERVAL_S,+ emit=_on_heartbeat,+ ):+ 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_startdiff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.pyindex ae8c91c57..642138c05 100644--- a/agent/src/tools/swarm_tool.py+++ b/agent/src/tools/swarm_tool.py@@ -665,13 +665,20 @@ class SwarmTool(BaseTool):ensure_ascii=False,)- if loaded.status.value in ("completed", "failed", "cancelled"):- return _format_result(loaded, preset, variables)-- runtime.cancel_run(run_id)+ reconciled = store.reconcile_run(loaded, write=True)+ if reconciled.status.value in ("completed", "failed", "cancelled"):+ return _format_result(reconciled, preset, variables)++ # Wait budget elapsed but the run is still in flight. Do NOT cancel —+ # the daemon thread keeps working and the agent can decide to wait+ # more (re-invoke with the returned run_id) or hand off partial state+ # to the user. Cancelling here used to throw away minutes of LLM cost+ # whenever a preset legitimately ran past the budget.loaded = store.load_run(run_id)if loaded is not None:- return _format_result(loaded, preset, variables, timed_out=True)+ return _format_result(+ store.reconcile_run(loaded, write=True), preset, variables, timed_out=True+ )return json.dumps({"status": "timeout", "error": f"Swarm run {run_id} timed out after {_MAX_WAIT_SECONDS}s"},@@ -700,10 +707,13 @@ def _format_result(task_summaries = [serialize_task(task) for task in run.tasks]- status = "timeout" if timed_out else run.status.value-+ # ``timed_out`` only means the SwarmTool's wait budget elapsed — the run+ # itself is still progressing in the background. Surface the run's real+ # status so a downstream agent can re-invoke with the run_id (or end its+ # turn with a "still working" message) instead of treating it as failure.result = {- "status": status,+ "status": run.status.value,+ "wait_budget_exhausted": timed_out,"run_id": run.id,"preset": preset,"auto_variables": variables,diff --git a/agent/tests/test_swarm_status_hydration.py b/agent/tests/test_swarm_status_hydration.pynew file mode 100644index 000000000..00e751b41--- /dev/null+++ b/agent/tests/test_swarm_status_hydration.py@@ -0,0 +1,593 @@+"""Regression tests for issue #132 — swarm status visibility & long-run MCP.++Coverage map:++1. ``hydrate_run`` merges live ``tasks/*.json`` and stays side-effect-free.+2. ``get_swarm_status`` surfaces both live progress and an ``is_stale`` flag.+3. ``run_swarm`` supports ``start_only`` and never returns "error" for a+ long-running budget — instead it returns the ``run_id`` so callers+ (or the caller's MCP client, via progress notifications) can pick up.+4. The stale-run reaper uses a per-run threshold (no fixed 1800s) and writes+ ``tasks/*.json`` so the final payload is self-consistent.+5. ``reap_stale_runs`` MCP tool gives users an explicit recovery path that+ does not depend on starting a new run.+6. Layer-boundary snapshot keeps ``run.json`` fresh enough for list_runs.+7. The swarm worker emits ``task_heartbeat`` events while a tool runs so the+ reaper has a precise liveness signal.+"""++from __future__ import annotations++import asyncio+import json+from datetime import datetime, timedelta, timezone+from unittest.mock import patch++import mcp_server+import src.swarm.runtime as rt+import src.swarm.store as store_mod+import src.swarm.worker as worker_mod+from src.swarm.models import (+ RunStatus,+ SwarmAgentSpec,+ SwarmEvent,+ SwarmRun,+ SwarmTask,+ TaskStatus,+)+from src.swarm.store import SwarmStore+from src.swarm.task_store import TaskStore+++def _iso(dt: datetime) -> str:+ return dt.astimezone(timezone.utc).isoformat()+++def _base_run(run_id: str = "r", *, timeout: int = 300, retries: int = 0) -> SwarmRun:+ agent = SwarmAgentSpec(+ id="analyst",+ role="Analyst",+ system_prompt="x",+ timeout_seconds=timeout,+ max_retries=retries,+ )+ task = SwarmTask(id="t1", agent_id="analyst", prompt_template="do x")+ return SwarmRun(+ id=run_id,+ preset_name="demo",+ created_at=_iso(datetime.now(timezone.utc)),+ agents=[agent],+ tasks=[task],+ )+++def _run_async(coro):+ return asyncio.get_event_loop().run_until_complete(coro) if False else asyncio.run(coro)+++# ---------------------------------------------------------------------------+# 1. hydrate_run+# ---------------------------------------------------------------------------+++def test_hydrate_run_merges_live_task_files(tmp_path):+ store = SwarmStore(base_dir=tmp_path)+ run = _base_run()+ run.status = RunStatus.running+ store.create_run(run)++ TaskStore(store.run_dir(run.id)).save_task(+ run.tasks[0].model_copy(+ update={"status": TaskStatus.in_progress, "started_at": _iso(datetime.now(timezone.utc))}+ )+ )++ hydrated = store.hydrate_run(store.load_run(run.id))++ assert hydrated.tasks[0].status == TaskStatus.in_progress+ # Side-effect-free: run.json must still show the original pending state.+ assert store.load_run(run.id).tasks[0].status == TaskStatus.pending+++def test_hydrate_run_is_noop_without_task_dir(tmp_path):+ store = SwarmStore(base_dir=tmp_path)+ run = _base_run()+ store.create_run(run)+ (store.run_dir(run.id) / "tasks").rmdir()++ hydrated = store.hydrate_run(store.load_run(run.id))++ assert hydrated.tasks[0].status == TaskStatus.pending+++# ---------------------------------------------------------------------------+# 2. get_swarm_status+# ---------------------------------------------------------------------------+++def test_get_swarm_status_surfaces_live_progress(tmp_path, monkeypatch):+ store = SwarmStore(base_dir=tmp_path)+ run = _base_run()+ run.status = RunStatus.running+ store.create_run(run)+ TaskStore(store.run_dir(run.id)).save_task(+ run.tasks[0].model_copy(update={"status": TaskStatus.in_progress})+ )+ store.append_event(+ run.id,+ SwarmEvent(type="task_started", data={}, timestamp=_iso(datetime.now(timezone.utc))),+ )+ monkeypatch.setattr(mcp_server, "_get_swarm_store", lambda: store)++ payload = json.loads(mcp_server.get_swarm_status(run.id))++ assert payload["status"] == "running"+ assert payload["tasks"][0]["status"] == "in_progress"+ assert payload["is_stale"] is False+++# ``test_get_swarm_status_flags_silent_run_as_stale`` from v2 was removed in+# v3 — read paths now auto-reconcile, so a zombie surfaces as ``status=failed``+# immediately (see ``test_get_swarm_status_auto_recovers_zombie`` below). The+# ``is_stale`` field remains for the rare transient case where reconciliation+# hasn't yet run, but is no longer a stable observable on a stale zombie.+++# ---------------------------------------------------------------------------+# 3. run_swarm async behavior+# ---------------------------------------------------------------------------+++def test_run_swarm_start_only_returns_immediately(tmp_path, monkeypatch):+ monkeypatch.setattr(store_mod, "swarm_runs_root", lambda: tmp_path)++ def fake_start_run(self, preset_name, variables, **kwargs):+ run = _base_run("r-start-only")+ run.status = RunStatus.running+ self._store.create_run(run)+ TaskStore(self._store.run_dir(run.id)).save_task(+ run.tasks[0].model_copy(update={"status": TaskStatus.in_progress})+ )+ return run++ monkeypatch.setattr(rt.SwarmRuntime, "start_run", fake_start_run)++ payload = json.loads(+ asyncio.run(mcp_server.run_swarm("demo", {}, start_only=True))+ )++ assert payload["run_id"] == "r-start-only"+ assert payload["status"] == "running"+ assert payload["tasks"][0]["status"] == "in_progress"+ assert payload["timed_out"] is False+++def test_run_swarm_wait_zero_returns_run_id_not_error(tmp_path, monkeypatch):+ monkeypatch.setattr(store_mod, "swarm_runs_root", lambda: tmp_path)++ def fake_start_run(self, preset_name, variables, **kwargs):+ run = _base_run("r-wait-zero")+ run.status = RunStatus.running+ self._store.create_run(run)+ return run++ monkeypatch.setattr(rt.SwarmRuntime, "start_run", fake_start_run)++ payload = json.loads(+ asyncio.run(mcp_server.run_swarm("demo", {}, wait_seconds=0))+ )++ assert payload["status"] == "running"+ assert payload["run_id"] == "r-wait-zero"+++# ---------------------------------------------------------------------------+# 4. reaper — per-run threshold + writes task files+# ---------------------------------------------------------------------------+++def test_reaper_threshold_lifts_when_heartbeat_disabled(tmp_path, monkeypatch):+ """When the user disables heartbeats (interval set very high), the+ threshold must rise so a legitimately slow run isn't false-positive-+ reaped. Conversely the default 3s heartbeat keeps detection at 60s —+ silence past that means the host is genuinely dead."""+ # Disable heartbeat by setting a huge interval; threshold should clamp+ # to the retry ceiling (≤ 3660s for the long-timeout preset).+ monkeypatch.setenv("SWARM_HEARTBEAT_INTERVAL_S", "600")+ store = SwarmStore(base_dir=tmp_path)+ long_run = _base_run("r-long", timeout=1800, retries=1)+ long_run.status = RunStatus.running+ store.create_run(long_run)+ store.append_event(+ long_run.id,+ SwarmEvent(+ type="task_started",+ data={},+ timestamp=_iso(datetime.now(timezone.utc) - timedelta(minutes=40)),+ ),+ )++ threshold = store.compute_stale_threshold(long_run)+ assert threshold == 3660, f"expected retry_ceiling=3660 with heartbeat=600s, got {threshold}"++ # 40 min < 3660s threshold → must not be reaped.+ reaped = store.reap_stale_running_runs()+ assert reaped == []+ assert store.load_run(long_run.id).status == RunStatus.running+++def test_reaper_reaps_silent_run_and_writes_task_errors(tmp_path):+ store = SwarmStore(base_dir=tmp_path)+ run = _base_run("r-orphan", timeout=60, retries=0)+ run.status = RunStatus.running+ store.create_run(run)+ TaskStore(store.run_dir(run.id)).save_task(+ run.tasks[0].model_copy(update={"status": TaskStatus.in_progress})+ )+ store.append_event(+ run.id,+ SwarmEvent(+ type="task_started",+ data={},+ timestamp=_iso(datetime.now(timezone.utc) - timedelta(hours=1)),+ ),+ )++ reaped = store.reap_stale_running_runs()++ assert reaped == ["r-orphan"]+ reloaded = store.load_run(run.id)+ assert reloaded.status == RunStatus.failed+ # Task file must reflect the failure so payloads are self-consistent.+ live_task = TaskStore(store.run_dir(run.id)).load_all()[0]+ assert live_task.status == TaskStatus.failed+ assert live_task.error and "reaped" in live_task.error.lower()+ assert live_task.completed_at is not None+ # run_reaped event emitted exactly once.+ assert sum(1 for e in store.read_events(run.id) if e.type == "run_reaped") == 1+++def test_reaper_leaves_terminal_tasks_alone(tmp_path):+ """If some tasks already completed before the host died, do not overwrite+ them — only the still-in-flight ones should turn failed."""+ store = SwarmStore(base_dir=tmp_path)+ run = _base_run("r-mixed", timeout=60, retries=0)+ run.tasks.append(SwarmTask(id="t2", agent_id="analyst", prompt_template="do y"))+ run.status = RunStatus.running+ store.create_run(run)+ task_store = TaskStore(store.run_dir(run.id))+ task_store.save_task(run.tasks[0].model_copy(update={"status": TaskStatus.completed, "summary": "ok"}))+ task_store.save_task(run.tasks[1].model_copy(update={"status": TaskStatus.in_progress}))+ store.append_event(+ run.id,+ SwarmEvent(+ type="task_completed",+ data={},+ timestamp=_iso(datetime.now(timezone.utc) - timedelta(hours=1)),+ ),+ )++ store.reap_stale_running_runs()++ by_id = {t.id: t for t in task_store.load_all()}+ assert by_id["t1"].status == TaskStatus.completed+ assert by_id["t1"].summary == "ok"+ assert by_id["t2"].status == TaskStatus.failed+++# ---------------------------------------------------------------------------+# 5. reap_stale_runs MCP tool+# ---------------------------------------------------------------------------+++def test_reap_stale_runs_mcp_tool(tmp_path, monkeypatch):+ store = SwarmStore(base_dir=tmp_path)+ run = _base_run("r-tool", timeout=30, retries=0)+ run.status = RunStatus.running+ store.create_run(run)+ store.append_event(+ run.id,+ SwarmEvent(+ type="task_started",+ data={},+ timestamp=_iso(datetime.now(timezone.utc) - timedelta(hours=1)),+ ),+ )+ monkeypatch.setattr(mcp_server, "_get_swarm_store", lambda: store)++ payload = json.loads(mcp_server.reap_stale_runs())++ assert payload == {"reaped": ["r-tool"]}+ assert store.load_run(run.id).status == RunStatus.failed+++# ---------------------------------------------------------------------------+# 6. Layer-boundary snapshot keeps run.json fresh+# ---------------------------------------------------------------------------+++def test_runtime_layer_boundary_sync_writes_run_json(tmp_path, monkeypatch):+ """After a layer finishes, run.json must show the layer's terminal task+ statuses without needing hydrate."""+ store = SwarmStore(base_dir=tmp_path)+ runtime = rt.SwarmRuntime(store=store, max_workers=1)+ run = _base_run("r-layer", timeout=5, retries=0)+ store.create_run(run)++ def fake_worker(*args, **kwargs):+ from src.swarm.models import WorkerResult+ return WorkerResult(status="completed", summary="ok")++ import threading++ monkeypatch.setattr(rt, "run_worker", fake_worker)+ runtime._execute_run(run, threading.Event())++ # After _execute_run, run.json must reflect the completed task.+ reloaded = store.load_run(run.id)+ assert reloaded.tasks[0].status == TaskStatus.completed+++# ---------------------------------------------------------------------------+# 7. Worker heartbeat+# ---------------------------------------------------------------------------+++def test_worker_emits_task_heartbeat_during_tool_call():+ """A long-running tool call must emit task_heartbeat swarm events so the+ reaper has a precise liveness signal.++ Drives the same HeartbeatTimer wiring used in worker.py — proves the+ primitive ticks while a synthetic slow tool runs. The full worker pipeline+ needs an LLM + tool registry, which is out of scope for a unit test.+ """+ import time++ from src.agent.progress import HeartbeatTimer++ captured: list[dict] = []+ with HeartbeatTimer(tool_name="slow_tool", interval=0.5, emit=captured.append):+ time.sleep(1.3)++ assert len(captured) >= 2+ assert all(p["tool"] == "slow_tool" for p in captured)+++def test_swarm_tool_format_result_preserves_running_status_on_budget_out():+ """_format_result(timed_out=True) must surface the real run status, not+ overwrite it with "timeout". Agents need to know "still running" so they+ can re-invoke with the run_id; the historical "timeout" mask hid that."""+ import src.tools.swarm_tool as swarm_tool++ run = _base_run("r-budget")+ run.status = RunStatus.running++ raw = swarm_tool._format_result(run, "demo", {"target": "AAPL"}, timed_out=True)+ payload = json.loads(raw)++ assert payload["status"] == "running"+ assert payload["wait_budget_exhausted"] is True+ assert payload["run_id"] == "r-budget"+++def test_swarm_tool_no_longer_cancels_on_budget_out():+ """Source-level guard: the SwarmTool wait loop must not call cancel_run+ when its budget elapses — that used to throw away in-flight LLM work."""+ import inspect+ import src.tools.swarm_tool as swarm_tool++ source = inspect.getsource(swarm_tool.SwarmTool.execute)+ assert "cancel_run" not in source, (+ "SwarmTool.execute must not cancel the run on budget exhaustion; "+ "return partial state and let the agent decide."+ )+++def test_run_swarm_first_progress_frame_carries_run_id(tmp_path, monkeypatch):+ """First Context.report_progress message must include ``swarm_started run_id=<id>``+ so a transport drop still leaves the caller with a recoverable handle."""+ monkeypatch.setattr(store_mod, "swarm_runs_root", lambda: tmp_path)++ def fake_start_run(self, preset_name, variables, **kwargs):+ run = _base_run("r-first-frame")+ run.status = RunStatus.running+ self._store.create_run(run)+ return run++ monkeypatch.setattr(rt.SwarmRuntime, "start_run", fake_start_run)++ progress_calls: list[dict] = []++ class FakeCtx:+ async def report_progress(self, progress, total=None, message=None):+ progress_calls.append({"progress": progress, "total": total, "message": message})++ # Run with very short budget so we exit fast after first frame.+ asyncio.run(+ mcp_server.run_swarm("demo", {}, wait_seconds=1, ctx=FakeCtx())+ )++ assert progress_calls, "expected at least one progress notification"+ first = progress_calls[0]+ assert first["message"].startswith("swarm_started run_id=r-first-frame")+++def test_reconcile_run_completes_a_silently_finished_run(tmp_path):+ """All tasks completed in tasks/*.json but run.json still ``running`` —+ a host crash between last layer sync and finalize. Reconcile must NOT+ declare the run failed; it must recover the real terminal status."""+ store = SwarmStore(base_dir=tmp_path)+ run = _base_run("r-silent-done", timeout=60, retries=0)+ run.status = RunStatus.running+ store.create_run(run)+ TaskStore(store.run_dir(run.id)).save_task(+ run.tasks[0].model_copy(+ update={"status": TaskStatus.completed, "summary": "the answer is 42"}+ )+ )++ reconciled = store.reconcile_run(store.load_run(run.id), write=True)++ assert reconciled.status == RunStatus.completed+ assert reconciled.final_report == "the answer is 42"+ # Persisted: a second read shouldn't have to recompute.+ assert store.load_run(run.id).status == RunStatus.completed+++def test_reconcile_run_does_not_overwrite_already_terminal(tmp_path):+ """Reconcile must be a no-op for runs that are already terminal —+ don't ever clobber a real completed/failed run."""+ store = SwarmStore(base_dir=tmp_path)+ run = _base_run("r-done", timeout=60, retries=0)+ run.status = RunStatus.completed+ run.final_report = "original report"+ store.create_run(run)+ TaskStore(store.run_dir(run.id)).save_task(+ run.tasks[0].model_copy(update={"status": TaskStatus.completed, "summary": "newer"})+ )++ reconciled = store.reconcile_run(store.load_run(run.id), write=True)++ assert reconciled.status == RunStatus.completed+ assert reconciled.final_report == "original report"+++def test_compute_stale_threshold_obeys_heartbeat_floor(tmp_path, monkeypatch):+ """When SWARM_HEARTBEAT_INTERVAL_S is small (default 3s), threshold must+ be the heartbeat floor (60s), not the retry ceiling (3660s for a long-+ timeout preset). Earlier expression was algebraically equivalent to the+ ceiling and ignored heartbeat — defeated detection latency entirely."""+ monkeypatch.setenv("SWARM_HEARTBEAT_INTERVAL_S", "3.0")+ store = SwarmStore(base_dir=tmp_path)+ long_run = _base_run("r-long", timeout=1800, retries=1) # retry_ceiling = 3660++ threshold = store.compute_stale_threshold(long_run)++ # heartbeat_floor = max(60, 30) = 60.+ # Correct math: max(60, min(60, 3660)) = 60.+ # Buggy math: min(3660, max(60, 3660)) = 3660.+ assert threshold == 60.0, f"expected 60s heartbeat floor, got {threshold}"+++def test_get_swarm_status_auto_recovers_zombie(tmp_path, monkeypatch):+ """End-to-end: query a zombie via MCP and the second call sees terminal+ status — not just ``running + is_stale=true``. This is the user-visible+ fix for the core #132 symptom."""+ store = SwarmStore(base_dir=tmp_path)+ run = _base_run("r-zombie", timeout=60, retries=0)+ run.status = RunStatus.running+ store.create_run(run)+ TaskStore(store.run_dir(run.id)).save_task(+ run.tasks[0].model_copy(update={"status": TaskStatus.in_progress})+ )+ # Silent for an hour — past any reasonable threshold.+ store.append_event(+ run.id,+ SwarmEvent(+ type="task_started",+ data={},+ timestamp=_iso(datetime.now(timezone.utc) - timedelta(hours=1)),+ ),+ )+ monkeypatch.setattr(mcp_server, "_get_swarm_store", lambda: store)++ payload = json.loads(mcp_server.get_swarm_status(run.id))++ assert payload["status"] == "failed", "zombie must auto-finalize on read"+ assert payload["tasks"][0]["status"] == "failed"+ assert store.load_run(run.id).status == RunStatus.failed+++def test_run_swarm_emits_keepalive_every_poll(tmp_path, monkeypatch):+ """Each polling iteration must emit a progress notification, even if the+ task counts haven't changed. Earlier dedup-on-message version emitted+ ``0/1`` once and then went silent for the whole run."""+ monkeypatch.setattr(store_mod, "swarm_runs_root", lambda: tmp_path)++ def fake_start_run(self, preset_name, variables, **kwargs):+ run = _base_run("r-keepalive")+ run.status = RunStatus.running+ self._store.create_run(run)+ TaskStore(self._store.run_dir(run.id)).save_task(+ run.tasks[0].model_copy(update={"status": TaskStatus.in_progress})+ )+ # Fresh event so reconcile won't auto-finalize during the test.+ self._store.append_event(+ run.id,+ SwarmEvent(+ type="task_started",+ data={},+ timestamp=_iso(datetime.now(timezone.utc)),+ ),+ )+ return run++ monkeypatch.setattr(rt.SwarmRuntime, "start_run", fake_start_run)++ progress_calls: list[dict] = []++ class FakeCtx:+ async def report_progress(self, progress, total=None, message=None):+ progress_calls.append({"progress": progress, "total": total, "message": message})++ # Patch asyncio.sleep to avoid actually sleeping in the test.+ real_sleep = asyncio.sleep++ async def fast_sleep(_):+ await real_sleep(0)++ monkeypatch.setattr("asyncio.sleep", fast_sleep)++ asyncio.run(mcp_server.run_swarm("demo", {}, wait_seconds=3, ctx=FakeCtx()))++ # Expect: 1 swarm_started frame + multiple keepalive frames (≥2 polls).+ keepalive = [c for c in progress_calls if not c["message"].startswith("swarm_started")]+ assert len(keepalive) >= 2, f"expected ≥2 keepalive frames, got {len(keepalive)}"+ # Elapsed should appear in the message so dedup-on-message clients see it move.+ assert any("elapsed" in c["message"] for c in keepalive)+++def test_worker_source_wires_heartbeat_around_llm_streaming():+ """LLM call must also be wrapped — slow first-token / reasoning-mode /+ pure-tool-call responses can go 30s+ without text chunks. Earlier+ versions only wrapped registry.execute, leaving a real loophole where+ reconcile_run would mark a healthy run failed mid-LLM-call."""+ import inspect+ source = inspect.getsource(worker_mod)+ timer_idx = source.find('with HeartbeatTimer(\n tool_name=f"llm:')+ stream_idx = source.find("llm.stream_chat(", timer_idx)+ assert 0 < timer_idx < stream_idx, (+ "llm.stream_chat must be wrapped in a HeartbeatTimer so the stale-"+ "run reaper can't false-positive a slow LLM call."+ )+++def test_heartbeat_interval_env_var_is_robust_to_garbage(monkeypatch):+ """A bad SWARM_HEARTBEAT_INTERVAL_S value must NOT crash worker import.+ Previously a typo (``"abc"``) raised ValueError at module top-level and+ took down every swarm path. Falls back to 3.0s now."""+ monkeypatch.setenv("SWARM_HEARTBEAT_INTERVAL_S", "abc")++ # Force re-evaluation by calling the resolver directly.+ import importlib+ import src.swarm.worker as w+ importlib.reload(w)++ assert w._HEARTBEAT_INTERVAL_S == 3.0+++def test_worker_source_wires_heartbeat_around_tool_execute():+ """Belt-and-braces: assert worker.py wraps registry.execute in HeartbeatTimer.++ A pure-source check (no LLM/tool needed) guards against accidental+ refactors that re-expose the silent-tool-call symptom from #132.+ """+ import inspect+ source = inspect.getsource(worker_mod)+ assert "HeartbeatTimer(" in source+ assert "task_heartbeat" in source+ # The wrapping must enclose registry.execute, not sit beside it.+ timer_idx = source.find("with HeartbeatTimer(")+ exec_idx = source.find("registry.execute(", timer_idx)+ next_dedent = source.find("\n ", exec_idx) # exit the `with` block+ assert 0 < timer_idx < exec_idx < next_dedent