Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(swarm): key agent artifacts by (agent_id, task_id), not agent_id alone

Lanre Shittua77e573b35a6
diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.py
index 520d44e6b..b418ad354 100644
--- a/agent/src/swarm/runtime.py
+++ b/agent/src/swarm/runtime.py
@@ -1089,6 +1089,10 @@ class SwarmRuntime:
cumulative_output_tokens = 0
result: WorkerResult | None = None
+ # agent_artifact_dir is keyed by (agent_id, task_id), so this task's
+ # first attempt always starts from a directory no other task has
+ # ever written to. Nothing to clear before it; only a retry of this
+ # same task needs clearing, below.
for attempt in range(max_retries + 1):
if attempt > 0:
retry_delay_s = _worker_retry_delay_s(attempt)
@@ -1129,7 +1133,9 @@ class SwarmRuntime:
# there when the retried attempt reads the directory back,
# silently substituting stale content for the new attempt's
# real result.
- clear_agent_artifacts(agent_artifact_dir(run_dir, agent_spec.id))
+ clear_agent_artifacts(
+ agent_artifact_dir(run_dir, agent_spec.id, task.id)
+ )
result = run_worker(
agent_spec=agent_spec,
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index 909a31c5f..3d794d703 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -378,8 +378,8 @@ def build_worker_prompt(
return "\n\n".join(prompt_parts)
-def agent_artifact_dir(run_dir: Path, agent_id: str) -> Path:
- """Return the canonical artifacts directory for one agent within a run.
+def agent_artifact_dir(run_dir: Path, agent_id: str, task_id: str) -> Path:
+ """Return the canonical artifacts directory for one task within a run.
The single source of truth for this path — shared with the retry loop
in ``runtime.py`` so the two can never compute it differently and drift
@@ -388,41 +388,57 @@ def agent_artifact_dir(run_dir: Path, agent_id: str) -> Path:
for ``mkdir``; validating the shared constructor protects both directory
creation and recursive cleanup from the same path escape.
+ Keyed by ``(agent_id, task_id)`` rather than ``agent_id`` alone: a preset
+ where one agent handles multiple tasks (sequentially or, across workers,
+ concurrently) must not have those tasks share a directory. Sharing meant
+ a later task's read of the directory could pick up an earlier task's
+ still-there files, and clearing the shared directory before a later task
+ could delete an earlier, concurrently-running task's in-flight output.
+ A directory scoped to one task never has either problem, and earlier
+ tasks' artifacts simply stay in place under their own task_id once the
+ agent moves on, instead of being deleted.
+
Args:
run_dir: Root directory for the swarm run.
agent_id: Single safe path segment identifying the agent.
+ task_id: Single safe path segment identifying the task.
Raises:
- ValueError: If ``agent_id`` is not a single safe path segment or the
- resolved artifact directory is not exactly one level below the
- resolved ``run_dir/artifacts`` directory.
+ ValueError: If ``agent_id`` or ``task_id`` is not a single safe path
+ segment, or the resolved artifact directory is not exactly two
+ levels below the resolved ``run_dir/artifacts`` directory.
"""
artifact_root = run_dir / "artifacts"
- if (
- not isinstance(agent_id, str)
- or not agent_id
- or agent_id in {".", ".."}
- or "/" in agent_id
- or "\\" in agent_id
- ):
- raise ValueError(
- f"Invalid swarm agent id {agent_id!r}: expected one safe path segment"
- )
- artifact_dir = artifact_root / agent_id
+ def _check(label: str, value: str) -> None:
+ if (
+ not isinstance(value, str)
+ or not value
+ or value in {".", ".."}
+ or "/" in value
+ or "\\" in value
+ ):
+ raise ValueError(
+ f"Invalid swarm {label} {value!r}: expected one safe path segment"
+ )
+
+ _check("agent id", agent_id)
+ _check("task id", task_id)
+
+ artifact_dir = artifact_root / agent_id / task_id
resolved_root = artifact_root.resolve()
resolved_dir = artifact_dir.resolve()
try:
relative = resolved_dir.relative_to(resolved_root)
except ValueError as exc:
raise ValueError(
- f"Invalid swarm agent id {agent_id!r}: artifact path escapes "
- "the run artifacts directory"
+ f"Invalid swarm agent/task id {agent_id!r}/{task_id!r}: artifact "
+ "path escapes the run artifacts directory"
) from exc
- if len(relative.parts) != 1:
+ if len(relative.parts) != 2:
raise ValueError(
- f"Invalid swarm agent id {agent_id!r}: artifact path must be "
- "one level below the run artifacts directory"
+ f"Invalid swarm agent/task id {agent_id!r}/{task_id!r}: artifact "
+ "path must be two levels below the run artifacts directory"
)
return artifact_dir
@@ -617,7 +633,7 @@ def _run_worker_impl(
]
# 6. ReAct loop
- artifact_dir = agent_artifact_dir(run_dir, agent_id)
+ artifact_dir = agent_artifact_dir(run_dir, agent_id, task_id)
artifact_dir.mkdir(parents=True, exist_ok=True)
t0 = time.monotonic()
@@ -655,7 +671,7 @@ def _run_worker_impl(
return WorkerResult(
status="timeout",
summary=summary,
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
iterations=iteration,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
@@ -674,7 +690,7 @@ def _run_worker_impl(
return WorkerResult(
status="cancelled",
summary=summary,
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
iterations=iteration,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
@@ -693,7 +709,7 @@ def _run_worker_impl(
return WorkerResult(
status="token_limit",
summary=summary,
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
iterations=iteration,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
@@ -839,7 +855,7 @@ def _run_worker_impl(
return WorkerResult(
status="cancelled",
summary=summary,
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
iterations=iteration,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
@@ -854,7 +870,7 @@ def _run_worker_impl(
return WorkerResult(
status="failed",
summary=_resolve_summary(artifact_dir, last_assistant_content or ""),
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
iterations=iteration,
error=error_msg,
input_tokens=total_input_tokens,
@@ -891,7 +907,7 @@ def _run_worker_impl(
return WorkerResult(
status="failed",
summary=summary,
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
iterations=iteration + 1,
error=(
f"content_filter_circuit_breaker: "
@@ -936,7 +952,7 @@ def _run_worker_impl(
return WorkerResult(
status="incomplete",
summary=summary,
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
iterations=iteration + 1,
error=f"output contract not met: {reason}",
input_tokens=total_input_tokens,
@@ -949,7 +965,7 @@ def _run_worker_impl(
return WorkerResult(
status="completed",
summary=summary,
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
iterations=iteration + 1,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
@@ -1053,7 +1069,7 @@ def _run_worker_impl(
return WorkerResult(
status="incomplete",
summary=summary,
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
iterations=max_iterations,
error=f"hit iteration limit without a valid deliverable: {reason}",
input_tokens=total_input_tokens,
@@ -1064,7 +1080,7 @@ def _run_worker_impl(
return WorkerResult(
status="completed",
summary=summary,
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
iterations=max_iterations,
input_tokens=total_input_tokens,
output_tokens=total_output_tokens,
@@ -1350,11 +1366,12 @@ def _write_summary(artifact_dir: Path, summary: str) -> None:
logger.warning("Failed to write summary to %s", artifact_dir, exc_info=True)
-def _collect_artifacts(artifact_dir: Path) -> list[str]:
+def _collect_artifacts(run_dir: Path, artifact_dir: Path) -> list[str]:
"""Collect regular artifacts as deterministic run-relative paths.
Args:
- artifact_dir: Path to artifacts/{agent_id}/ directory.
+ run_dir: Root directory for the swarm run.
+ artifact_dir: Path to artifacts/{agent_id}/{task_id}/ directory.
Returns:
Sorted POSIX-style paths relative to the swarm run directory. Symlinks
@@ -1363,7 +1380,7 @@ def _collect_artifacts(artifact_dir: Path) -> list[str]:
if not artifact_dir.exists():
return []
- run_dir = artifact_dir.parent.parent.resolve()
+ run_dir = run_dir.resolve()
artifact_root = artifact_dir.resolve()
if not artifact_root.is_relative_to(run_dir):
return []
diff --git a/agent/tests/test_swarm_m4_e2e.py b/agent/tests/test_swarm_m4_e2e.py
index ac175bb9e..c0845cb8b 100644
--- a/agent/tests/test_swarm_m4_e2e.py
+++ b/agent/tests/test_swarm_m4_e2e.py
@@ -296,7 +296,7 @@ def test_run_worker_uses_remote_mcp_tool_and_report_cites_canned_data(
)
assert result.status == "completed"
- report_path = tmp_path / "artifacts" / "kb_analyst" / "report.md"
+ report_path = tmp_path / "artifacts" / "kb_analyst" / "t1" / "report.md"
assert report_path.is_file()
contents = report_path.read_text(encoding="utf-8")
assert canned_payload["answer"] in contents
diff --git a/agent/tests/test_swarm_output_contract.py b/agent/tests/test_swarm_output_contract.py
index 0e3a26f71..dcab18843 100644
--- a/agent/tests/test_swarm_output_contract.py
+++ b/agent/tests/test_swarm_output_contract.py
@@ -412,7 +412,7 @@ def test_collect_artifacts_recurses_and_returns_sorted_run_relative_paths(
(artifact_dir / "nested" / "report.json").write_text("{}", encoding="utf-8")
(artifact_dir / "other" / "report.json").write_text("{}", encoding="utf-8")
- assert _collect_artifacts(artifact_dir) == [
+ assert _collect_artifacts(tmp_path / "run", artifact_dir) == [
"artifacts/analyst/nested/report.json",
"artifacts/analyst/other/report.json",
"artifacts/analyst/summary.md",
@@ -430,7 +430,7 @@ def test_collect_artifacts_rejects_symlink_escape(tmp_path: Path) -> None:
except (OSError, NotImplementedError):
pytest.skip("symlinks are not available on this platform")
- assert _collect_artifacts(artifact_dir) == []
+ assert _collect_artifacts(tmp_path / "run", artifact_dir) == []
# ---------------------------------------------------------------------------
diff --git a/agent/tests/test_swarm_retry_artifact_isolation.py b/agent/tests/test_swarm_retry_artifact_isolation.py
index 63bb5a2c8..d7b37db5a 100644
--- a/agent/tests/test_swarm_retry_artifact_isolation.py
+++ b/agent/tests/test_swarm_retry_artifact_isolation.py
@@ -1,16 +1,27 @@
"""Regression tests: a retried worker attempt must not inherit stale
artifacts (report.md, or any other tool-written file) from a prior failed
-attempt for the same task.
+attempt for the same task, and two different tasks must never share an
+artifact directory.
``_run_worker_with_retries`` re-invokes ``run_worker`` against the *same*
-``artifact_dir`` on every attempt (``mkdir(parents=True, exist_ok=True)``,
-no cleanup). ``_resolve_summary``/``_report_written``/``_collect_artifacts``
-all read whatever is currently sitting in that directory, with no way to
-tell which attempt wrote it. Without isolation, a worker that fails after
-writing report.md, followed by a retry that fails immediately (a realistic
-sequence of two ordinary transient LLM/provider errors), silently returns
-the discarded first attempt's stale content as the retried attempt's real
-result.
+``artifact_dir`` on every retry of one task (``mkdir(parents=True,
+exist_ok=True)``, no cleanup in between). ``_resolve_summary``/
+``_report_written``/``_collect_artifacts`` all read whatever is currently
+sitting in that directory, with no way to tell which attempt wrote it.
+Without per-attempt isolation, a worker that fails after writing report.md,
+followed by a retry that fails immediately (a realistic sequence of two
+ordinary transient LLM/provider errors), silently returns the discarded
+first attempt's stale content as the retried attempt's real result.
+
+``agent_artifact_dir`` is keyed by ``(agent_id, task_id)``, not ``agent_id``
+alone: an earlier design cleared the agent's single shared directory before
+every fresh task dispatch, which fixed the sequential-task leak above but
+traded it for two worse failure modes a reviewer caught before merge: (1) a
+prior task's artifacts, needed after the agent moved on, were deleted
+outright instead of just not being reread, and (2) two tasks assigned to the
+same agent and dispatched concurrently would have one task's retry delete
+the other's in-flight output out from under it. Per-task directories have
+neither problem.
The real ``_resolve_summary``/``_report_written``/``_collect_artifacts``
are exercised for real inside the mocked ``run_worker`` below (only the
@@ -55,12 +66,12 @@ def _make_agent_spec(max_retries: int) -> SwarmAgentSpec:
)
-def _make_task() -> SwarmTask:
- return SwarmTask(id="task-1", agent_id="analyst", prompt_template="do x")
+def _make_task(task_id: str = "task-1") -> SwarmTask:
+ return SwarmTask(id=task_id, agent_id="analyst", prompt_template="do x")
# --------------------------------------------------------------------------- #
-# Unit tests: the two new helpers themselves
+# Unit tests: the two shared helpers themselves
# --------------------------------------------------------------------------- #
@@ -68,33 +79,41 @@ def test_agent_artifact_dir_matches_run_worker_construction(tmp_path: Path) -> N
"""The shared helper must resolve to the exact path run_worker() writes
to, or the retry loop would clear the wrong directory entirely."""
run_dir = tmp_path / "run-x"
- assert agent_artifact_dir(run_dir, "analyst") == run_dir / "artifacts" / "analyst"
+ assert agent_artifact_dir(run_dir, "analyst", "task-1") == (
+ run_dir / "artifacts" / "analyst" / "task-1"
+ )
- "agent_id", ["..", "/abs/path", "", ".", "a/b", r"a\\b"]
-)
-def test_agent_artifact_dir_rejects_path_shaped_ids(
[email protected]("agent_id", ["..", "/abs/path", "", ".", "a/b", r"a\\b"])
+def test_agent_artifact_dir_rejects_path_shaped_agent_ids(
tmp_path: Path, agent_id: str
) -> None:
with pytest.raises(ValueError, match="agent id"):
- agent_artifact_dir(tmp_path / "run-x", agent_id)
+ agent_artifact_dir(tmp_path / "run-x", agent_id, "task-1")
+
+
[email protected]("task_id", ["..", "/abs/path", "", ".", "a/b", r"a\\b"])
+def test_agent_artifact_dir_rejects_path_shaped_task_ids(
+ tmp_path: Path, task_id: str
+) -> None:
+ with pytest.raises(ValueError, match="task id"):
+ agent_artifact_dir(tmp_path / "run-x", "analyst", task_id)
def test_agent_artifact_dir_rejects_canonical_symlink_escape(tmp_path: Path) -> None:
run_dir = tmp_path / "run-x"
artifact_root = run_dir / "artifacts"
- artifact_root.mkdir(parents=True)
+ (artifact_root / "analyst").mkdir(parents=True)
outside = tmp_path / "outside"
outside.mkdir()
- (artifact_root / "analyst").symlink_to(outside, target_is_directory=True)
+ (artifact_root / "analyst" / "task-1").symlink_to(outside, target_is_directory=True)
- with pytest.raises(ValueError, match="agent id"):
- agent_artifact_dir(run_dir, "analyst")
+ with pytest.raises(ValueError, match="agent/task id"):
+ agent_artifact_dir(run_dir, "analyst", "task-1")
def test_clear_agent_artifacts_removes_nested_files_and_dirs(tmp_path: Path) -> None:
- artifact_dir = tmp_path / "artifacts" / "analyst"
+ artifact_dir = tmp_path / "artifacts" / "analyst" / "task-1"
(artifact_dir / "charts").mkdir(parents=True)
(artifact_dir / "report.md").write_text("stale", encoding="utf-8")
(artifact_dir / "charts" / "plot.png").write_text("stale-binary", encoding="utf-8")
@@ -106,7 +125,7 @@ def test_clear_agent_artifacts_removes_nested_files_and_dirs(tmp_path: Path) ->
def test_clear_agent_artifacts_is_noop_when_directory_absent(tmp_path: Path) -> None:
"""Nothing to clean up before the very first attempt — must not raise."""
- artifact_dir = tmp_path / "artifacts" / "analyst"
+ artifact_dir = tmp_path / "artifacts" / "analyst" / "task-1"
assert not artifact_dir.exists()
clear_agent_artifacts(artifact_dir) # must not raise
assert not artifact_dir.exists()
@@ -125,7 +144,7 @@ def test_stale_report_not_returned_after_retry(tmp_path: Path) -> None:
task = _make_task()
run_dir = tmp_path / "run-stale-report"
run_dir.mkdir()
- artifact_dir = agent_artifact_dir(run_dir, "analyst")
+ artifact_dir = agent_artifact_dir(run_dir, "analyst", task.id)
calls = {"n": 0}
@@ -178,7 +197,7 @@ def test_stale_non_report_artifact_not_leaked_after_retry(tmp_path: Path) -> Non
task = _make_task()
run_dir = tmp_path / "run-stale-artifact"
run_dir.mkdir()
- artifact_dir = agent_artifact_dir(run_dir, "analyst")
+ artifact_dir = agent_artifact_dir(run_dir, "analyst", task.id)
calls = {"n": 0}
@@ -192,13 +211,13 @@ def test_stale_non_report_artifact_not_leaked_after_retry(tmp_path: Path) -> Non
return WorkerResult(
status="failed",
summary="attempt 1 raw fallback",
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
error="attempt 1: tool error",
)
return WorkerResult(
status="failed",
summary="attempt 2 real fallback",
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
error="attempt 2: provider error",
)
@@ -232,7 +251,7 @@ def test_successful_retry_only_reflects_current_attempt_artifacts(
task = _make_task()
run_dir = tmp_path / "run-successful-retry"
run_dir.mkdir()
- artifact_dir = agent_artifact_dir(run_dir, "analyst")
+ artifact_dir = agent_artifact_dir(run_dir, "analyst", task.id)
calls = {"n": 0}
@@ -249,7 +268,7 @@ def test_successful_retry_only_reflects_current_attempt_artifacts(
return WorkerResult(
status="failed",
summary=_resolve_summary(artifact_dir, "attempt 1 raw fallback"),
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
error="attempt 1: provider error",
)
(artifact_dir / "report.md").write_text(
@@ -258,7 +277,7 @@ def test_successful_retry_only_reflects_current_attempt_artifacts(
return WorkerResult(
status="completed",
summary=_resolve_summary(artifact_dir, "attempt 2 raw fallback"),
- artifact_paths=_collect_artifacts(artifact_dir),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
)
with patch("src.swarm.runtime.run_worker", side_effect=fake_run_worker):
@@ -278,4 +297,124 @@ def test_successful_retry_only_reflects_current_attempt_artifacts(
assert result.status == "completed"
assert "Attempt 2" in result.summary
assert "Attempt 1" not in result.summary
- assert result.artifact_paths == ["artifacts/analyst/report.md"]
+ assert result.artifact_paths == ["artifacts/analyst/task-1/report.md"]
+
+
+def test_earlier_task_artifacts_survive_a_later_task_on_the_same_agent(
+ tmp_path: Path,
+) -> None:
+ """agent_artifact_dir is keyed by (agent_id, task_id): a preset where one
+ agent handles two sequential tasks (task-2 depends_on task-1) must give
+ each its own directory. task-1's report.md must still be there, readable
+ under its own task_id, after task-2 runs — not deleted, and not visible
+ to task-2 either."""
+ runtime = _make_runtime(tmp_path)
+ agent_spec = _make_agent_spec(max_retries=0)
+ run_dir = tmp_path / "run-shared-agent"
+ run_dir.mkdir()
+
+ def fake_run_worker(**kwargs):
+ task = kwargs["task"]
+ artifact_dir = agent_artifact_dir(run_dir, "analyst", task.id)
+ artifact_dir.mkdir(parents=True, exist_ok=True)
+ if task.id == "task-1":
+ (artifact_dir / "report.md").write_text(
+ "# Task 1 report\nTASK-1 CONTENT.", encoding="utf-8"
+ )
+ return WorkerResult(
+ status="completed",
+ summary=_resolve_summary(artifact_dir, f"{task.id} raw fallback"),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
+ )
+
+ task1 = SwarmTask(id="task-1", agent_id="analyst", prompt_template="do x")
+ task2 = SwarmTask(id="task-2", agent_id="analyst", prompt_template="do y")
+
+ with patch("src.swarm.runtime.run_worker", side_effect=fake_run_worker):
+ result1 = runtime._run_worker_with_retries(
+ agent_spec=agent_spec,
+ task=task1,
+ upstream_summaries={},
+ user_vars={},
+ run_dir=run_dir,
+ event_callback=None,
+ run_id="run-shared-agent",
+ include_shell_tools=False,
+ grounding_block="",
+ )
+ result2 = runtime._run_worker_with_retries(
+ agent_spec=agent_spec,
+ task=task2,
+ upstream_summaries={},
+ user_vars={},
+ run_dir=run_dir,
+ event_callback=None,
+ run_id="run-shared-agent",
+ include_shell_tools=False,
+ grounding_block="",
+ )
+
+ assert "Task 1 report" in result1.summary
+ assert result2.summary == "task-2 raw fallback"
+ assert "Task 1" not in result2.summary
+ assert result2.artifact_paths == []
+
+ # task-1's artifact is not just absent from task-2's result — it is
+ # still on disk, under its own task directory, after task-2 completed.
+ task1_dir = agent_artifact_dir(run_dir, "analyst", "task-1")
+ assert (task1_dir / "report.md").read_text(encoding="utf-8") == (
+ "# Task 1 report\nTASK-1 CONTENT."
+ )
+
+
+def test_retrying_one_task_does_not_touch_a_concurrent_sibling_tasks_output(
+ tmp_path: Path,
+) -> None:
+ """Two tasks assigned to the same agent, dispatched concurrently (e.g.
+ two branches of the DAG with no dependency between them): retrying one
+ must not delete the other's in-flight output, since a shared directory
+ would make a retry-triggered clear race with a sibling task's writes."""
+ runtime = _make_runtime(tmp_path)
+ agent_spec = _make_agent_spec(max_retries=1)
+ run_dir = tmp_path / "run-concurrent-siblings"
+ run_dir.mkdir()
+
+ task_a = SwarmTask(id="task-a", agent_id="analyst", prompt_template="do a")
+
+ # task-b's worker is "in flight": its directory already carries a
+ # partial write, as if a concurrent worker thread wrote it moments ago.
+ sibling_dir = agent_artifact_dir(run_dir, "analyst", "task-b")
+ sibling_dir.mkdir(parents=True)
+ (sibling_dir / "partial.csv").write_text("in-flight", encoding="utf-8")
+
+ calls = {"n": 0}
+
+ def fake_run_worker(**kwargs):
+ calls["n"] += 1
+ artifact_dir = agent_artifact_dir(run_dir, "analyst", "task-a")
+ artifact_dir.mkdir(parents=True, exist_ok=True)
+ if calls["n"] == 1:
+ return WorkerResult(status="failed", summary="", error="transient error")
+ (artifact_dir / "report.md").write_text("task-a result", encoding="utf-8")
+ return WorkerResult(
+ status="completed",
+ summary=_resolve_summary(artifact_dir, "task-a fallback"),
+ artifact_paths=_collect_artifacts(run_dir, artifact_dir),
+ )
+
+ with patch("src.swarm.runtime.run_worker", side_effect=fake_run_worker):
+ runtime._run_worker_with_retries(
+ agent_spec=agent_spec,
+ task=task_a,
+ upstream_summaries={},
+ user_vars={},
+ run_dir=run_dir,
+ event_callback=None,
+ run_id="run-concurrent-siblings",
+ include_shell_tools=False,
+ grounding_block="",
+ )
+
+ assert calls["n"] == 2
+ # task-a's own retry cleared task-a's own directory, never task-b's.
+ assert (sibling_dir / "partial.csv").read_text(encoding="utf-8") == "in-flight"
diff --git a/agent/tests/test_swarm_tool_run_dir.py b/agent/tests/test_swarm_tool_run_dir.py
index b0bbb3769..4b5146601 100644
--- a/agent/tests/test_swarm_tool_run_dir.py
+++ b/agent/tests/test_swarm_tool_run_dir.py
@@ -178,7 +178,7 @@ def test_worker_passes_a_relative_run_dir_through_to_the_tool(
_run_worker_with(tmp_path, monkeypatch, _DeclaredTool(), {"run_dir": "runs/demo"})
assert _DeclaredTool.received == [
- str(tmp_path / "artifacts" / "analyst" / "runs" / "demo")
+ str(tmp_path / "artifacts" / "analyst" / "task" / "runs" / "demo")
]