"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: complete eight maintenance fixes and task isolation
Haozhe Wu4dfdcbad720b
diff --git a/README.md b/README.mdindex 8ab651bde..476984839 100644--- a/README.md+++ b/README.md@@ -666,6 +666,11 @@ Detailed inventories are folded below to keep the main README scannable. Open thThe read-only `report_audit` tool preserves signed financial values in Markdowntables and `label: value` lines, so losses are checked as losses rather than profits.+Backtest reports ground their figures in the engine's own output for that call.+For list results, equivalent references such as `data.positions[0].contribution_pct`+and `data.positions.0.contribution_pct` select the same element; an explicit index+cannot borrow another element's value. Correction hints suggest exact references+without treating the suggestion itself as evidence.</details>@@ -1387,6 +1392,12 @@ vibe-trading --swarm-run macro_rates_fx_desk '{"focus": "Fed pivot impact on EMvibe-trading --swarm-retry <run_id> --swarm-resume```+Each Swarm task keeps its reports, summary and message log under+`artifacts/<agent_id>/<task_id>/`, so tasks assigned to the same agent retain+their own output during sequential or parallel execution. Retrying a task clears+only that task's output; completed task artifacts remain available to downstream+workers. Resume also preserves artifacts recorded by older runs.+### Cross-Session Memory```bashdiff --git a/agent/backtest/optimizers/turnover_aware.py b/agent/backtest/optimizers/turnover_aware.pyindex b3866fcdc..42ec0f3bc 100644--- a/agent/backtest/optimizers/turnover_aware.py+++ b/agent/backtest/optimizers/turnover_aware.py@@ -122,11 +122,14 @@ class TurnoverAwareOptimizer(BaseOptimizer):if group in self.max_per_group:group_cap = self.max_per_group[group]cap = min(cap, group_cap) if cap is not None else group_cap- if cap is not None and (pos[code].abs() > cap + 1e-7).any():- raise ValueError(- "single-asset allocation exceeds exposure caps "- f"for {code}: maximum permitted weight is {cap:.6g}"- )+ if cap is not None:+ if not np.isfinite(pos[code]).all():+ raise ValueError("capped single-asset allocations must be finite")+ if (pos[code].abs() > cap + 1e-7).any():+ raise ValueError(+ "single-asset allocation exceeds exposure caps "+ f"for {code}: maximum permitted weight is {cap:.6g}"+ )return super().optimize(ret, pos, dates)def _build_context(diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.pyindex 49e87a1e2..065e87b3e 100644--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@ -223,14 +223,30 @@ def _file_sha256(path: Path) -> str | None:return None-def _archive_source(root: Path) -> str | None:- """The run directory name the active run's archived backtest came from."""+def _archive_matches(root: Path, declared_dir: Path, call_id: str) -> bool:+ """Check the engine directory and call that produced an archived result.++ Args:+ root: Active run holding the archive manifest.+ declared_dir: Source run directory declared by the backtest call.+ call_id: Exact successful engine tool call.++ Returns:+ Whether the archive was created for this directory and call.+ """try:payload = json.loads((root / ARCHIVE_MANIFEST).read_text(encoding="utf-8"))except (OSError, UnicodeDecodeError, json.JSONDecodeError):- return None- source = payload.get("source_run") if isinstance(payload, dict) else None- return str(source) if source else None+ return False+ if not isinstance(payload, dict) or payload.get("source_call_id") != call_id:+ return False+ source = payload.get("source_run_dir")+ if not isinstance(source, str) or not source:+ return False+ try:+ return Path(source).resolve() == declared_dir.resolve()+ except (OSError, RuntimeError, ValueError):+ return Falsedef _run_card_manifest(directory: Path) -> dict[str, str]:@@ -703,47 +719,33 @@ class _EvidenceMixin:root = self.run_dir.resolve()candidates: list[Path] = []own_dir: Path | None = None- declared_name: str | None = Noneraw_dir = arguments.get("run_dir") or payload.get("run_dir")+ declared = rootif raw_dir:declared = Path(str(raw_dir))- declared_name = declared.name- candidate = declared if declared.is_absolute() else self.run_dir / declared+ declared = declared if declared.is_absolute() else self.run_dir / declaredtry:- resolved = candidate.resolve()+ resolved = declared.resolve()if resolved == root or resolved.is_relative_to(root):candidates.append(resolved)own_dir = resolved- except OSError:+ except (OSError, RuntimeError, ValueError):pass- # The loop archives a detached backtest's artifacts into the active run- # dir right after it succeeds, so that copy is the second candidate — but- # only once the archive names the directory this call declared. A- # detached backtest's own dir sits outside the active run, so there the- # declared *name* is the only thing tying the archived copy to this call.- candidates.append(root)+ else:+ own_dir = root+ candidates.append(root)+ # The loop copies detached output before ingesting this result. The+ # archive must name the full directory AND this call, since basenames+ # collide and one directory can be backtested repeatedly in a turn.archived = (- declared_name is not None- and own_dir != root- and _archive_source(root) == declared_name+ own_dir != root+ and not self._is_model_written(root / ARCHIVE_MANIFEST)+ and _archive_matches(root, declared, call_id))- if declared_name is not None and own_dir != root and not archived:- candidates = [- item- for item in candidates- if own_dir is not None and item.is_relative_to(own_dir)- ]- artifacts = payload.get("artifacts")- if isinstance(artifacts, dict):- for path_value in artifacts.values():- if not isinstance(path_value, str):- continue- try:- resolved = Path(path_value).resolve()- if resolved.is_relative_to(root):- candidates.append(resolved)- except OSError:- continue+ if archived:+ candidates.append(root)+ # Only canonical engine metric locations count. A result's explicit+ # artifact path cannot reintroduce an unrelated run or arbitrary CSV.files: list[Path] = []seen_dirs: set[Path] = set()for candidate in candidates:@@ -756,7 +758,7 @@ class _EvidenceMixin:for dir_path in (candidate, candidate / "artifacts"):for name in ("metrics.csv", "metrics.json"):target = dir_path / name- if target.is_file():+ if target.is_file() and target.resolve().is_relative_to(candidate.resolve()):files.append(target)recorded = 0seen_files: set[Path] = set()diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.pyindex ab43ccbcc..05cadac9b 100644--- a/agent/src/agent/grounding/policies.py+++ b/agent/src/agent/grounding/policies.py@@ -1108,7 +1108,7 @@ class _PolicyMixin:return ranked[:_MAX_CALL_REF_CANDIDATES]def _indexed_field_ref_candidates(- self, ref: str, figure: Figure+ self, ref: str, figure: Figure, symbol: str | None = None) -> list[str]:"""Exact ``call_id::path[i]`` refs for a ``call::field`` ref that selected no value.@@ -1155,13 +1155,16 @@ class _PolicyMixin:and scope in (call_id, tool)):continue- if record is not None and not self._kind_fits(record, figure):- continue+ if record is not None:+ if symbol and record.symbol and record.symbol != symbol:+ continue+ if not self._kind_fits(record, figure):+ continueitem = f"{call_id}::{path}"if below.search(_index_normalized(path)):containers.add(item)found[item] = float(value)- elif _INDEX_RE.search(path):+ elif _INDEX_RE.search(path) and not _INDEX_RE.search(wanted):stripped = _INDEX_RE.sub("", path)if stripped == bare or stripped.endswith("." + bare):found[item] = float(value)@@ -1600,7 +1603,7 @@ class _PolicyMixin:field_ref_candidates=list(dict.fromkeys([- *self._indexed_field_ref_candidates(declaration.ref, figure),+ *self._indexed_field_ref_candidates(declaration.ref, figure, symbol),*self._other_call_field_ref_candidates(declaration.ref, symbol, figure),])diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 8529a31a9..5a48f4b81 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -3338,7 +3338,7 @@ class AgentLoop:self._successful_call_keys[tc.id] = recorded_keyif tc.name == "backtest":try:- _archive_backtest_result(result, self.memory.run_dir)+ _archive_backtest_result(result, self.memory.run_dir, source_call_id=tc.id)except OSError as exc:logger.warning("Could not archive backtest output into active run: %s", exc)if tc.name in {"write_file", "edit_file"}:diff --git a/agent/src/agent/tool_results.py b/agent/src/agent/tool_results.pyindex 9737d96bf..8b94149f8 100644--- a/agent/src/agent/tool_results.py+++ b/agent/src/agent/tool_results.py@@ -181,7 +181,9 @@ def _previously_archived(target: Path) -> set[str]:}-def _archive_backtest_result(result: str, active_run_dir: str | None) -> bool:+def _archive_backtest_result(+ result: str, active_run_dir: str | None, *, source_call_id: str | None = None+) -> bool:"""Copy a successful detached backtest into the active, reportable run.The model may choose another allowed run directory while iterating. The@@ -204,6 +206,14 @@ def _archive_backtest_result(result: str, active_run_dir: str | None) -> bool::data:`_ARCHIVE_MANIFEST`; anything the active run wrote itself (notably``code/signal_engine.py``, written before ``backtest`` is called) isuntouched, which is why the manifest exists instead of a blanket wipe.++ Args:+ result: Serialized successful backtest tool result.+ active_run_dir: Active turn directory that receives reportable output.+ source_call_id: Exact tool call recorded with the archive's source path.++ Returns:+ Whether a detached backtest's output was archived."""if not active_run_dir:return False@@ -241,7 +251,12 @@ def _archive_backtest_result(result: str, active_run_dir: str | None) -> bool:for stale in previously_archived - set(archived):(target / stale).unlink(missing_ok=True)(target / _ARCHIVE_MANIFEST).write_text(- json.dumps({"source_run": source.name, "files": sorted(archived)}, indent=2),+ json.dumps({+ "source_run": source.name,+ "source_run_dir": str(source.resolve()),+ "source_call_id": source_call_id,+ "files": sorted(archived),+ }, indent=2),encoding="utf-8",)for filename in (diff --git a/agent/src/skills/report-generate/SKILL.md b/agent/src/skills/report-generate/SKILL.mdindex 889270bdb..a80228127 100644--- a/agent/src/skills/report-generate/SKILL.md+++ b/agent/src/skills/report-generate/SKILL.md@@ -196,7 +196,15 @@ recovered by 2023.06 to a new high of 2.10.## Backtest Report Template-After a backtest is completed, read `metrics.csv` and `equity.csv` to generate:+After a backtest is completed, read the engine-written `metrics.csv` and+`equity.csv` from that run. Declare reported measurements with the run directory+or exact engine field as their grounding reference. A metrics file you write+yourself is not evidence, and a previous run's archive cannot substantiate the+current call. For list results, use the exact element reference (for example,+`call_id::data.positions[0].contribution_pct`); correction hints only identify+candidates to check and cite explicitly.++Use the verified output to generate:```markdown# Backtest Report: [Strategy Name]diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.pyindex b418ad354..ae972d2cc 100644--- a/agent/src/swarm/runtime.py+++ b/agent/src/swarm/runtime.py@@ -103,7 +103,7 @@ def _rehome_artifact_paths("""Copy a kept task's run-relative artifacts into *target_run_dir*.Workers persist artifacts as POSIX paths relative to the run directory- (``artifacts/<agent>/<file>``; see ``worker._collect_artifacts``). A+ (``artifacts/<agent>/<task>/<file>``; see ``worker._collect_artifacts``). Aresumed run must not reference the old run's directory — the old runstays as a record and may be deleted later.diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex 3d794d703..6bca05987 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -435,10 +435,10 @@ def agent_artifact_dir(run_dir: Path, agent_id: str, task_id: str) -> Path: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) != 2:+ if relative.parts != (agent_id, task_id):raise ValueError(f"Invalid swarm agent/task id {agent_id!r}/{task_id!r}: artifact "- "path must be two levels below the run artifacts directory"+ "path must preserve its agent and task below the run artifacts directory")return artifact_dir@@ -549,7 +549,7 @@ def _run_worker_impl(2. Build system prompt with role + upstream summaries + filtered skills3. Resolve task.prompt_template with user_vars4. Run ReAct loop (for iteration in range(max_iterations))- 5. Write summary to artifacts/{agent_id}/summary.md+ 5. Write summary to artifacts/{agent_id}/{task_id}/summary.md6. Return WorkerResultArgs:@@ -1332,7 +1332,7 @@ def _finalize_run(artifact_dir: Path, summary: str, messages: list[dict]) -> Nonunchanged.Args:- artifact_dir: Path to artifacts/{agent_id}/ directory.+ artifact_dir: Path to artifacts/{agent_id}/{task_id}/ directory.summary: Final summary text for this worker run.messages: Message history, including tool call arguments."""@@ -1356,7 +1356,7 @@ def _write_summary(artifact_dir: Path, summary: str) -> None:"""Write worker summary to artifacts directory.Args:- artifact_dir: Path to artifacts/{agent_id}/ directory.+ artifact_dir: Path to artifacts/{agent_id}/{task_id}/ directory.summary: Summary text to write."""try:diff --git a/agent/src/tools/report_audit_tool.py b/agent/src/tools/report_audit_tool.pyindex 64a0114c0..d7979d0fe 100644--- a/agent/src/tools/report_audit_tool.py+++ b/agent/src/tools/report_audit_tool.py@@ -39,7 +39,7 @@ _NUMUNIT_RE = re.compile(r"(?P<open>[((])\s*\$?\s*(?P<account_num>[+\-−]?[\d,,.]+)\s*"rf"(?P<inside_unit>{_UNIT_PATTERN})?\s*(?P<close>[))])\s*"rf"(?P<outside_unit>{_UNIT_PATTERN})?"- r"|(?P<num>[+\-−]?[\d,,.]+)\s*"+ r"|(?P<currency_sign>[+\-−])?\s*\$?\s*(?P<num>[+\-−]?[\d,,.]+)\s*"rf"(?P<unit>{_UNIT_PATTERN})?)")_TABLE_SEP_RE = re.compile(r"^\|[\-\s|:]+\|$")@@ -100,6 +100,12 @@ def _report_value(text: str, *, prose: bool = False) -> tuple[float, str, int] |value = -abs(value)else:value = _clean_num(match.group("num"))+ sign = match.group("currency_sign")+ if sign:+ if match.group("num").startswith(("+", "-", "−")):+ return None+ if value is not None and sign in {"-", "−"}:+ value = -valueunit = match.group("unit") or ""if value is None or not math.isfinite(value):return Nonediff --git a/agent/tests/test_grounding_backtest_outputs.py b/agent/tests/test_grounding_backtest_outputs.pyindex dd92eb1ad..946e5ce83 100644--- a/agent/tests/test_grounding_backtest_outputs.py+++ b/agent/tests/test_grounding_backtest_outputs.py@@ -32,6 +32,7 @@ import pytestfrom src.agent.grounding import GroundingLedgerfrom src.agent.grounding.evidence import ARCHIVE_MANIFEST+from src.agent.tool_results import _archive_backtest_resultRP = {"final_value": 1129817.32,@@ -398,6 +399,73 @@ def test_stale_active_metrics_are_not_attributed_to_a_detached_backtest(tmp_pathassert EW["sharpe"] not in recorded[email protected]("detached", [False, True])+def test_artifact_path_cannot_bypass_current_backtest_source(tmp_path: Path, detached: bool) -> None:+ active = tmp_path / "active"+ _write_backtest(active, EW)+ declared = tmp_path / "detached" if detached else active / "current"+ _write_backtest(declared, RP)+ ledger = GroundingLedger(run_dir=active, user_message="Compare backtests")+ ledger.ingest_tool_result(+ tool_name="backtest",+ arguments={"run_dir": str(declared)},+ result=json.dumps({+ "status": "ok", "run_dir": str(declared),+ "artifacts": {"metrics": str(active / "artifacts" / "metrics.csv")},+ }),+ call_id="bt-current", success=True,+ )+ recorded = [item["value"] for item in ledger._analysis_metrics]+ assert EW["sharpe"] not in recorded+ if not detached:+ assert RP["sharpe"] in recorded++[email protected]("mismatch", ["directory", "call"])+def test_archive_identity_includes_full_directory_and_call(tmp_path: Path, mismatch: str) -> None:+ active = tmp_path / "active"+ _write_backtest(active, EW)+ declared = tmp_path / "new" / "same-name"+ old = tmp_path / "old" / "same-name"+ _write_backtest(declared, RP)+ (active / ARCHIVE_MANIFEST).write_text(json.dumps({+ "source_run": declared.name,+ "source_run_dir": str(old if mismatch == "directory" else declared),+ "source_call_id": "old-call" if mismatch == "call" else "new-call",+ }), encoding="utf-8")+ ledger = GroundingLedger(run_dir=active, user_message="Compare backtests")+ _backtest(ledger, declared, "new-call")+ assert not ledger._analysis_metrics+++def test_real_engine_archive_is_accepted_only_for_its_own_call(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))+ source, active = tmp_path / "engine", tmp_path / "active"+ _write_backtest(source, RP)+ result = json.dumps({"status": "ok", "run_dir": str(source)})+ assert _archive_backtest_result(result, str(active), source_call_id="bt-engine")+ ledger = GroundingLedger(run_dir=active, user_message="Compare backtests")+ _backtest(ledger, source, "bt-stale")+ assert not ledger._analysis_metrics+ _backtest(ledger, source, "bt-engine")+ checked = ledger.validate_final_answer(_declared(+ "Sharpe 0.694。", "0.694 | observed | Sharpe | bt-engine::sharpe"+ ))+ assert checked.valid, checked.issues+++def test_metrics_symlink_cannot_supply_another_runs_evidence(tmp_path: Path) -> None:+ active, sibling = tmp_path / "active", tmp_path / "sibling"+ _write_backtest(sibling, RP)+ (active / "artifacts").mkdir(parents=True)+ (active / "artifacts" / "metrics.csv").symlink_to(sibling / "artifacts" / "metrics.csv")+ ledger = GroundingLedger(run_dir=active, user_message="Compare backtests")+ _backtest(ledger, active, "bt-active")+ assert not ledger._analysis_metrics++def test_a_detached_backtest_cannot_inherit_the_active_runs_copy(tmp_path: Path) -> None:"""A run dir outside the active run has no claim on what that dir holds.@@ -438,7 +506,7 @@ def test_a_detached_backtests_archived_copy_counts_once_vouched_for(tmp_path: Patarget.write_bytes((detached / "artifacts" / name).read_bytes())(active / "run_card.json").write_bytes((detached / "run_card.json").read_bytes())(active / ARCHIVE_MANIFEST).write_text(- json.dumps({"source_run": detached.name}), encoding="utf-8"+ json.dumps({"source_run": detached.name, "source_run_dir": str(detached.resolve()), "source_call_id": "bt-detached"}), encoding="utf-8")ledger = GroundingLedger(run_dir=active, user_message="回测")@@ -459,29 +527,29 @@ def test_the_active_runs_copy_belongs_to_the_backtest_the_archive_names(tmp_path_write_backtest(tmp_path / "rp", RP)_write_backtest(tmp_path / "ew", EW)- def archive(source: str) -> None:+ def archive(source: str, call_id: str) -> None:for name in ("metrics.csv", "risk_xray.json", "validation.json"):target = tmp_path / "artifacts" / nametarget.parent.mkdir(exist_ok=True)target.write_bytes((tmp_path / source / "artifacts" / name).read_bytes())(tmp_path / "run_card.json").write_bytes((tmp_path / source / "run_card.json").read_bytes())- (tmp_path / ARCHIVE_MANIFEST).write_text(json.dumps({"source_run": source}), encoding="utf-8")+ (tmp_path / ARCHIVE_MANIFEST).write_text(json.dumps({"source_run": source, "source_run_dir": str((tmp_path / source).resolve()), "source_call_id": call_id}), encoding="utf-8")def copy_says(value: str) -> bool:return ledger.validate_final_answer(_declared(f"Sortino {value}。", f"{value} | observed | Sortino | artifacts/metrics.csv")).valid- archive("ew") # an earlier archive: not rp's output, and not credited to rp+ archive("ew", "earlier-call") # an earlier archive: not rp's output, and not credited to rp_backtest(ledger, tmp_path / "rp", "bt-rp")assert not copy_says("1.133")assert not copy_says("1.212")- archive("rp")+ archive("rp", "bt-rp-2")_backtest(ledger, tmp_path / "rp", "bt-rp-2")assert copy_says("1.133")- archive("ew")+ archive("ew", "bt-ew")_backtest(ledger, tmp_path / "ew", "bt-ew")assert copy_says("1.212")assert not copy_says("1.133")diff --git a/agent/tests/test_grounding_indexed_field_refs.py b/agent/tests/test_grounding_indexed_field_refs.pyindex 802d371a8..1ae4efa4a 100644--- a/agent/tests/test_grounding_indexed_field_refs.py+++ b/agent/tests/test_grounding_indexed_field_refs.py@@ -96,6 +96,18 @@ def test_other_elements_value_is_not_authorized_by_an_indexed_ref(assert {issue["reason"] for issue in result.issues} == {"not_in_referenced_call"}[email protected]("dotted", [False, True])+def test_explicit_leaf_ref_never_hints_a_sibling(tmp_path: Path, dotted: bool) -> None:+ result = _validate(+ tmp_path,+ "The first item contributed -0.87%.",+ f"-0.87% | observed | first item | {_ref(0, dotted)}",+ )+ assert not result.valid+ candidates = result.issues[0].get("field_ref_candidates") or []+ assert not any("positions[1]" in ref for ref in candidates)++def test_elements_are_not_ambiguous_with_each_other(tmp_path: Path) -> None:result = _validate(tmp_path,@@ -123,7 +135,6 @@ def test_dotted_index_does_not_touch_unindexed_or_scalar_refs(tmp_path: Path) ->[f"{CALL}::data.positions.contribution_pct",f"{TOOL}::positions.contribution_pct",- f"{CALL}::data.positions.2.contribution_pct",],)def test_failed_ref_lists_exact_indexed_candidates(tmp_path: Path, ref: str) -> None:@@ -139,6 +150,15 @@ def test_failed_ref_lists_exact_indexed_candidates(tmp_path: Path, ref: str) ->assert all(item.startswith(f"{CALL}::data.positions[") for item in candidates)+def test_out_of_range_explicit_index_never_selects_or_hints_another_item(tmp_path: Path) -> None:+ result = _validate(+ tmp_path, "The missing item contributed 1.23%.",+ f"1.23% | observed | missing item | {CALL}::data.positions.2.contribution_pct",+ )+ assert not result.valid+ assert not result.issues[0].get("field_ref_candidates")++def test_candidates_are_shown_to_the_model_in_the_correction(tmp_path: Path) -> None:ledger = _ledger(tmp_path)result = ledger.validate_final_answer(diff --git a/agent/tests/test_report_audit_signed_values.py b/agent/tests/test_report_audit_signed_values.pyindex b4c3da061..61cd58d10 100644--- a/agent/tests/test_report_audit_signed_values.py+++ b/agent/tests/test_report_audit_signed_values.py@@ -9,6 +9,18 @@ import pytestfrom src.tools.report_audit_tool import ReportAuditTool, extract_data_points[email protected]("value", ["-$25M", "−$25M", "- $25M", "$-25M", "($-25M)"])[email protected]("table", [False, True])+def test_negative_currency_keeps_sign_on_either_side_of_symbol(value: str, table: bool) -> None:+ report = (+ f"| Metric | Value |\n|---|---|\n| Net income | {value} |"+ if table else f"Net income: {value}"+ )+ points = extract_data_points(report)+ assert len(points) == 1+ assert points[0]["reported_value"] == -25++@pytest.mark.parametrize("value", ["-25M", "−25M", "+25M", "25M", "-1,234.5M"])@pytest.mark.parametrize("table", [False, True])def test_extract_preserves_financial_value_sign(value: str, table: bool) -> None:diff --git a/agent/tests/test_swarm_task_artifact_isolation.py b/agent/tests/test_swarm_task_artifact_isolation.pynew file mode 100644index 000000000..d6b9ee611--- /dev/null+++ b/agent/tests/test_swarm_task_artifact_isolation.py@@ -0,0 +1,89 @@+"""Real runtime and workers write distinct same-agent task reports and logs."""++from __future__ import annotations++import json+import threading+from pathlib import Path++import pytest++import src.swarm.worker as worker+from src.providers.chat import LLMResponse, ToolCallRequest+from src.swarm.models import RunStatus, SwarmAgentSpec, SwarmRun, SwarmTask, TaskStatus+from src.swarm.runtime import SwarmRuntime+from src.swarm.store import SwarmStore++[email protected]("parallel", [False, True])+def test_runtime_preserves_each_same_agent_tasks_real_files(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, parallel: bool+) -> None:+ barrier = threading.Barrier(2) if parallel else None+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))++ class ReportLLM:+ def __init__(self, **kwargs):+ self.wrote = False++ def stream_chat(self, messages, **kwargs):+ task_id = messages[1]["content"]+ report = (+ f"# {task_id}\nThe requested research is complete. "+ "This task produced its own report and a clear conclusion, "+ "with the evidence and limitations recorded for the reader."+ )+ if not self.wrote:+ if barrier is not None:+ barrier.wait(timeout=10)+ self.wrote = True+ return LLMResponse(tool_calls=[ToolCallRequest(+ id=f"write-{task_id}", name="write_file",+ arguments={"path": "report.md", "content": report},+ )], finish_reason="tool_calls")+ result = json.loads(next(message["content"] for message in messages if message["role"] == "tool"))+ assert result["status"] == "ok", result+ return LLMResponse(content=report, tool_calls=[], finish_reason="stop")++ def close(self):+ pass++ monkeypatch.setattr(worker, "ChatLLM", ReportLLM)+ store = SwarmStore(base_dir=tmp_path)+ agent = SwarmAgentSpec(+ id="analyst", role="Report writer", system_prompt="Write the task report.",+ tools=["write_file"], max_iterations=3, max_retries=0,+ )+ tasks = [+ SwarmTask(id="first", agent_id=agent.id, prompt_template="first"),+ SwarmTask(+ id="second", agent_id=agent.id, prompt_template="second",+ depends_on=[] if parallel else ["first"],+ ),+ ]+ run = SwarmRun(+ id="task-isolation", preset_name="fixture", created_at="2026-10-03T00:00:00Z",+ agents=[agent], tasks=tasks,+ )+ store.create_run(run)+ runtime = SwarmRuntime(store=store)+ runtime._execute_run(run, threading.Event())+ saved = store.load_run(run.id)+ assert saved is not None and saved.status == RunStatus.completed+ for task in saved.tasks:+ assert task.status == TaskStatus.completed, task.error+ assert task.summary.startswith(f"# {task.id}\n")+ directory = store.run_dir(run.id) / "artifacts" / agent.id / task.id+ assert (directory / "report.md").read_text() == task.summary+ assert (directory / "summary.md").read_text() == task.summary+ messages = json.loads((directory / "messages.json").read_text())+ assert messages[1]["content"] == task.id+ assert all(path.startswith(f"artifacts/{agent.id}/{task.id}/") for path in task.artifacts)+++def test_internal_task_symlink_cannot_share_a_siblings_directory(tmp_path: Path) -> None:+ parent = tmp_path / "artifacts" / "analyst"+ (parent / "second").mkdir(parents=True)+ (parent / "first").symlink_to(parent / "second", target_is_directory=True)+ with pytest.raises(ValueError):+ worker.agent_artifact_dir(tmp_path, "analyst", "first")diff --git a/agent/tests/test_swarm_worker_message_log.py b/agent/tests/test_swarm_worker_message_log.pyindex 81eac50be..c53607a16 100644--- a/agent/tests/test_swarm_worker_message_log.py+++ b/agent/tests/test_swarm_worker_message_log.py@@ -134,7 +134,7 @@ def test_completed_run_persists_the_message_log() -> None:"""A worker that completes must leave a message log, not only a summary."""result = _run_worker_to_terminal(tmp_path, monkeypatch)- artifact_dir = agent_artifact_dir(tmp_path, "analyst")+ artifact_dir = agent_artifact_dir(tmp_path, "analyst", "task")assert result.status == "completed", result.errorassert (artifact_dir / "summary.md").is_file()@@ -147,7 +147,7 @@ def test_token_limit_run_persists_the_message_log("""A worker stopped by the token limit must leave a message log too."""monkeypatch.setattr(worker_mod, "_MAX_TOKEN_ESTIMATE", 0)result = _run_worker_to_terminal(tmp_path, monkeypatch)- artifact_dir = agent_artifact_dir(tmp_path, "analyst")+ artifact_dir = agent_artifact_dir(tmp_path, "analyst", "task")assert result.status == "token_limit"assert (artifact_dir / "summary.md").is_file()@@ -164,7 +164,7 @@ def test_content_filter_circuit_breaker_persists_the_message_log(llm_factory=_ContentFilteredLLM,max_iterations=20,)- artifact_dir = agent_artifact_dir(tmp_path, "analyst")+ artifact_dir = agent_artifact_dir(tmp_path, "analyst", "task")assert result.status == "failed"assert "circuit_breaker" in (result.error or "")@@ -179,7 +179,7 @@ def test_incomplete_run_persists_the_message_log(result = _run_worker_to_terminal(tmp_path, monkeypatch, llm_factory=_AnswersWithoutToolCallsLLM)- artifact_dir = agent_artifact_dir(tmp_path, "analyst")+ artifact_dir = agent_artifact_dir(tmp_path, "analyst", "task")assert result.status == "incomplete", result.errorassert "no tool calls" in (result.error or "")@@ -192,7 +192,7 @@ def test_message_log_carries_the_tool_call_arguments() -> None:"""The log must hold what the model asked the tool for, not only roles."""_run_worker_to_terminal(tmp_path, monkeypatch)- log_path = agent_artifact_dir(tmp_path, "analyst") / "messages.json"+ log_path = agent_artifact_dir(tmp_path, "analyst", "task") / "messages.json"messages = json.loads(log_path.read_text(encoding="utf-8"))assert any(diff --git a/agent/tests/test_turnover_single_asset_caps.py b/agent/tests/test_turnover_single_asset_caps.pyindex e1e2043fc..97a768195 100644--- a/agent/tests/test_turnover_single_asset_caps.py+++ b/agent/tests/test_turnover_single_asset_caps.py@@ -7,6 +7,15 @@ import pytestfrom backtest.optimizers.turnover_aware import TurnoverAwareOptimizer[email protected]("weight", [np.nan, np.inf, -np.inf])+def test_explicit_singleton_cap_rejects_nonfinite_weights(weight: float) -> None:+ dates = pd.date_range("2025-01-01", periods=1)+ pos = pd.DataFrame({"AAA": [weight]}, index=dates)+ optimizer = TurnoverAwareOptimizer(max_per_name=0.4)+ with pytest.raises(ValueError):+ optimizer.optimize(pos * 0, pos, dates)++@pytest.mark.parametrize("direction", [1.0, -1.0])@pytest.mark.parametrize("caps",