"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tools): resolve a skill-relative reference link in read_file
ethanstoner3574bcfd9d80
diff --git a/agent/src/tools/read_file_tool.py b/agent/src/tools/read_file_tool.pyindex e383927d7..933b4eb6c 100644--- a/agent/src/tools/read_file_tool.py+++ b/agent/src/tools/read_file_tool.py@@ -14,6 +14,54 @@ from src.tools.redaction import redact_internal_paths_OUTPUT_LIMIT = 50_000+# Subdirectories a SKILL.md links into. A link inside a skill document is+# written relative to that document — `references/foo.md` — because that is the+# form that resolves for a human reading the file on GitHub. This tool roots at+# the bundled skills/ directory, so the same string has to be resolved against+# the skill that owns it or the agent cannot open what the document points at.+# The list is deliberately narrow: only these two names are searched, so an+# arbitrary model-supplied relative path never starts reaching into skills/.+_SKILL_RELATIVE_PREFIXES = ("references/", "scripts/")+++def _bundled_skills_dir() -> Path:+ """Return the bundled read-only skills root."""+ return Path(__file__).resolve().parents[1] / "skills"+++def _skill_relative_matches(file_path: str, skills_dir: Path) -> list[tuple[str, Path]]:+ """Return the bundled skills that carry ``file_path`` inside their directory.++ Args:+ file_path: Skill-relative path as written in a SKILL.md link, e.g.+ ``references/sec_edgar_client.md``.+ skills_dir: Bundled read-only skills root.++ Returns:+ ``(skill_name, path)`` for each owning skill, in skill-name order. Empty+ when no bundled skill carries the path.+ """+ # A link written in a skill document never needs to climb, and `..` would+ # let a path that merely *starts* with an allowed prefix land somewhere+ # else — `references/../SKILL.md` matching all 90 skills, for one. Refusing+ # the segment outright keeps "starts with references/" and "stays under+ # references/" the same statement.+ if ".." in file_path.replace("\\", "/").split("/"):+ return []++ matches: list[tuple[str, Path]] = []+ for skill_dir in sorted(p for p in skills_dir.iterdir() if p.is_dir()):+ try:+ candidate = _safe_path(file_path, skill_dir)+ except ValueError:+ # Absolute paths and UNC shares, rejected by the same containment+ # check the skills/ root already applies, enforced one level down+ # so the fallback cannot widen the boundary.+ continue+ if candidate.is_file():+ matches.append((skill_dir.name, candidate))+ return matches+class ReadFileTool(BaseTool):"""Read file contents with optional line limit."""@@ -27,7 +75,9 @@ class ReadFileTool(BaseTool):"type": "string","description": ("File path relative to run_dir or skills/. "- "The skills/ prefix always resolves to the bundled skills."+ "The skills/ prefix always resolves to the bundled skills. "+ "A references/ or scripts/ path copied out of a SKILL.md "+ "resolves against the skill that owns it."),},"limit": {"type": "integer", "description": "Max number of lines to return (default: all)"},@@ -62,7 +112,7 @@ class ReadFileTool(BaseTool):ensure_ascii=False,)# Read-only access to skills/- skills_dir = Path(__file__).resolve().parents[1] / "skills"+ skills_dir = _bundled_skills_dir()if skills_dir.exists():allowed_roots.append(skills_dir.resolve())@@ -98,6 +148,35 @@ class ReadFileTool(BaseTool):except ValueError:continue+ # Last resort: a skill-relative link. Tried only after every allowed+ # root has already missed, so nothing that resolves today changes, and+ # it reads out of the read-only skills tree, so run_dir cannot poison+ # it. An ambiguous path is reported rather than guessed — silently+ # picking one of two same-named references would hand the agent a+ # document from the wrong skill and read as a correct answer.+ if (+ resolved is None+ and not namespaced+ and skills_dir.exists()+ and file_path.startswith(_SKILL_RELATIVE_PREFIXES)+ ):+ matches = _skill_relative_matches(file_path, skills_dir)+ if len(matches) == 1:+ resolved = matches[0][1]+ elif len(matches) > 1:+ owners = ", ".join(name for name, _ in matches)+ return json.dumps(+ {+ "status": "error",+ "error": (+ f"Ambiguous skill-relative path: {file_path} exists in "+ f"{len(matches)} skills ({owners}). Prefix it with the "+ f"skill name, e.g. skills/<skill>/{file_path}."+ ),+ },+ ensure_ascii=False,+ )+if resolved is None:return json.dumps({diff --git a/agent/tests/test_read_file_skill_relative.py b/agent/tests/test_read_file_skill_relative.pynew file mode 100644index 000000000..0500a82f3--- /dev/null+++ b/agent/tests/test_read_file_skill_relative.py@@ -0,0 +1,162 @@+"""Regression tests: ``read_file`` resolves skill-relative reference links.++Background:+ A ``references/`` or ``scripts/`` link inside a SKILL.md is written relative+ to the document, which is the form GitHub resolves for a human reader.+ ``read_file`` roots at the bundled ``skills/`` directory, so historically+ only the ``<skill>/references/...`` form was reachable by the agent and the+ two consumers could not be satisfied by one string. Both forms now resolve.++No live API is touched: ``read_file`` performs local filesystem reads of the+bundled skill docs only.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Tuple++import pytest++from src.tools import read_file_tool+from src.tools.read_file_tool import ReadFileTool, _skill_relative_matches++_SKILLS_DIR = Path(__file__).resolve().parents[1] / "src" / "skills"+++def _body(raw: str) -> dict:+ """Parse a JSON tool response."""+ return json.loads(raw)+++def _unique_link(subdir: str, suffix: str) -> Tuple[str, str]:+ """Find a bundled file under ``subdir`` that exactly one skill owns.++ Deriving the fixture from the corpus keeps the test from rotting when a+ skill is renamed or its references are reorganised.++ Args:+ subdir: ``references`` or ``scripts``.+ suffix: File extension to look for, e.g. ``.md``.++ Returns:+ ``(skill_name, skill_relative_path)``.+ """+ owners: dict[str, list[str]] = {}+ for skill_dir in sorted(p for p in _SKILLS_DIR.iterdir() if p.is_dir()):+ base = skill_dir / subdir+ if not base.is_dir():+ continue+ for path in base.rglob(f"*{suffix}"):+ if path.is_file():+ rel = path.relative_to(skill_dir).as_posix()+ owners.setdefault(rel, []).append(skill_dir.name)+ for rel, skills in sorted(owners.items()):+ if len(skills) == 1:+ return skills[0], rel+ pytest.fail(f"no bundled skill owns a unique {subdir}/*{suffix} file")++[email protected]("subdir,suffix", [("references", ".md"), ("scripts", ".py")])+def test_bare_link_resolves_to_the_owning_skill(subdir: str, suffix: str) -> None:+ """A bare link resolves to the same file as its skill-prefixed form."""+ skill, rel = _unique_link(subdir, suffix)++ bare = _body(ReadFileTool().execute(path=rel))+ prefixed = _body(ReadFileTool().execute(path=f"{skill}/{rel}"))++ assert bare["status"] == "ok", bare+ assert prefixed["status"] == "ok", prefixed+ assert bare["path"] == prefixed["path"]+ assert bare["content"] == prefixed["content"]+++def test_skills_rooted_form_still_resolves() -> None:+ """The explicit ``skills/`` namespace keeps working unchanged."""+ skill, rel = _unique_link("references", ".md")++ body = _body(ReadFileTool().execute(path=f"skills/{skill}/{rel}"))++ assert body["status"] == "ok", body+ assert body["content"]+++def test_bare_link_does_not_shadow_run_dir(tmp_path: Path, monkeypatch) -> None:+ """A file the agent wrote into run_dir still wins over the skills tree.++ The fallback is a last resort, so existing resolution order is unchanged.+ """+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path))+ _, rel = _unique_link("references", ".md")+ local = tmp_path / rel+ local.parent.mkdir(parents=True, exist_ok=True)+ local.write_text("RUN DIR CONTENT", encoding="utf-8")++ body = _body(ReadFileTool().execute(path=rel, run_dir=str(tmp_path)))++ assert body["status"] == "ok", body+ assert body["content"] == "RUN DIR CONTENT"+++def test_unknown_bare_link_is_still_an_error() -> None:+ """A references/ path no skill owns reports not-found, not a wrong file."""+ body = _body(ReadFileTool().execute(path="references/no_such_document.md"))++ assert body["status"] == "error"+ assert "not found" in body["error"]+++def test_bare_link_cannot_climb_out_of_the_skill(tmp_path: Path, monkeypatch) -> None:+ """``..`` inside a bare link is refused rather than followed.++ Without this the fallback would widen the boundary the ``skills/`` prefix+ already enforces: a path only has to *start* with ``references/``.+ """+ monkeypatch.setattr(read_file_tool, "_bundled_skills_dir", lambda: _SKILLS_DIR)+ secret = _SKILLS_DIR.parent.parent.parent / "pyproject.toml"+ assert secret.is_file(), "fixture assumes pyproject.toml sits above skills/"++ for attempt in (+ "references/../SKILL.md",+ "references/../../tushare/SKILL.md",+ "references/../../../../pyproject.toml",+ "scripts/../../../../../etc/passwd",+ ):+ body = _body(ReadFileTool().execute(path=attempt))+ assert body["status"] == "error", f"{attempt} resolved: {body}"+++def test_ambiguous_bare_link_names_the_candidates(tmp_path: Path, monkeypatch) -> None:+ """Two skills owning one path is reported, never silently resolved.++ Picking one would hand the agent a document from the wrong skill and read+ as a correct answer.+ """+ for skill in ("alpha-skill", "beta-skill"):+ target = tmp_path / skill / "references" / "overview.md"+ target.parent.mkdir(parents=True)+ target.write_text(f"content from {skill}", encoding="utf-8")+ monkeypatch.setattr(read_file_tool, "_bundled_skills_dir", lambda: tmp_path)++ body = _body(ReadFileTool().execute(path="references/overview.md"))++ assert body["status"] == "error"+ assert "Ambiguous" in body["error"]+ assert "alpha-skill" in body["error"] and "beta-skill" in body["error"]+++def test_skill_relative_matches_rejects_traversal(tmp_path: Path) -> None:+ """The matcher itself drops climbing and absolute paths."""+ target = tmp_path / "one-skill" / "references" / "doc.md"+ target.parent.mkdir(parents=True)+ target.write_text("body", encoding="utf-8")+ (tmp_path / "one-skill" / "SKILL.md").write_text("root doc", encoding="utf-8")++ outside = tmp_path.parent / "outside.md"+ outside.write_text("outside", encoding="utf-8")++ assert len(_skill_relative_matches("references/doc.md", tmp_path)) == 1+ assert _skill_relative_matches("references/../SKILL.md", tmp_path) == []+ assert _skill_relative_matches("references/..\\SKILL.md", tmp_path) == []+ assert _skill_relative_matches(str(outside), tmp_path) == []diff --git a/agent/tests/test_skill_reference_links.py b/agent/tests/test_skill_reference_links.pyindex 6d14b96bc..379178715 100644--- a/agent/tests/test_skill_reference_links.py+++ b/agent/tests/test_skill_reference_links.py@@ -2,11 +2,12 @@resolves through the ``read_file`` tool.Background:- ``read_file`` roots reads at the bundled ``skills/`` directory, so a link- must carry the skill-name prefix (e.g. ``tushare/references/...``) to be- reachable. Bare ``references/...`` links silently fail because- ``skills/references/`` does not exist. These tests lock in the prefixed- convention so the bug cannot regress.+ ``read_file`` roots reads at the bundled ``skills/`` directory. The+ skill-name prefix (e.g. ``tushare/references/...``) is what these files are+ written with, and these tests lock that convention in. A bare+ ``references/...`` is now resolved against the skill that owns it as well,+ so the form a human follows on GitHub reaches the same file — see+ ``test_read_file_skill_relative.py`` for that resolution path.No live API is touched: ``read_file`` performs local filesystem reads of thebundled skill docs only.@@ -121,8 +122,9 @@ def test_every_skill_with_reference_links_is_covered() -> None:def test_reference_links_carry_skill_prefix(skill: str, link: str) -> None:"""Every references/ or scripts/ link is written with its skill-name prefix.- A bare ``references/...`` / ``scripts/...`` link is unreachable because- read_file roots at ``skills/`` and ``skills/references/`` does not exist.+ The prefixed form names one file outright. The bare form now resolves too,+ but by searching the skills tree, which a future same-named reference in a+ second skill would make ambiguous — so this is still the form to write."""assert link.startswith(f"{skill}/"), (f"{skill}/SKILL.md link must carry the '{skill}/' prefix, got: {link}"@@ -137,12 +139,14 @@ def test_reference_links_resolve_through_read_file(skill: str, link: str) -> Nonassert body["content"], f"{link} resolved to empty content"-def test_bare_reference_link_would_fail() -> None:- """Guard: a bare references/ path (no prefix) is NOT resolvable.+def test_bare_reference_link_resolves_to_the_same_file() -> None:+ """A bare references/ path (no prefix) reaches the same document.- This documents the exact failure mode the prefix convention prevents.+ This is the form GitHub resolves for a human reading the SKILL.md, so both+ consumers of the link have to land on one file."""skill, link = _all_links()[0]bare = link[len(f"{skill}/"):] # strip the skill-name prefixbody = _read(bare)- assert body["status"] == "error"+ assert body["status"] == "ok", f"{bare} did not resolve: {body}"+ assert body["path"] == _read(link)["path"]