Raven-1/tests/test_agents_code_flow_exec.py
Tong Li 0a1a711123
feat(*): add bounded Python diagnostics after code edits (#967)
## Summary

Raven-Code reports Python syntax errors after file edits but misses
unresolved names and equivalent feedback after shell edits. Add advisory
Pyflakes F821/F822/F823 checks to the existing tool result; optional
F401 notices remain off by default. No additional model call or code
execution is involved.

```text
write_file / edit_file
  -> inspect final source, compare with a baseline that can be read and analyzed
  -> retain syntax warnings; suppress existing name findings
exec
  -> require checkpoint visibility for the working directory
  -> read the changed files from the host's write record for the command
  -> ask visibility in batches of 256, select at most 8, check up to 4 concurrently
  -> append ordered diagnostics, preserving exit status and file metadata
```

Existing syntax failures remain visible after unrelated edits and
identical rewrites. A baseline that cannot be read, parsed or analyzed
is marked unknown; overwriting non-UTF-8 source still checks the known
replacement. Source nested too deeply for the parser or checker, and a
changed file that cannot be read, report diagnostics unavailable for
that file rather than passing as clean. Every check reads a file as the
bytes Python runs: text a write or edit stores is checked as its UTF-8
bytes, the content it replaced included, and a file from disk as its
bytes, each decoded as Python decodes source, by its coding declaration
or as UTF-8. Bytes that do not decode are reported as a syntax error at
the line where decoding stops, so a declaration the written text cannot
satisfy is reported however the file was changed. Noqa comments are read
as Ruff reads them, including after other comment directives and never
inside string literals: a file-level `ruff: noqa` / `flake8: noqa`
counts only on a line of its own, and a marker counts only when codes
follow its colon or, with no colon, whitespace, another comment or the
end of the comment follows it. Unlike Ruff, which takes the first
directive in a comment, every directive in it counts. The seeded tool
guide gives the syntax note's own advice. With no checkpoint or no
visibility verdict, exec diagnostics do not inspect changed file
contents; direct file checks remain available.

Pyflakes is imported when the tool face loads, not by whichever check
first needs it: imported lazily, its cold import fell inside that
check's one-second wait, and on a slow Windows runner the one test that
paid it reported diagnostics unavailable for a plain syntax error.
Private workers bound reads and checks to four active jobs per process.
Saturated capacity rejects new work without queuing, and
timeout/cancellation retains each slot until the actual work finishes.
Name checks are capped at 256 KiB of source and the syntax check at 2
MiB, and a check skipped for size says so in one line. Findings are
capped at eight per file, and exec diagnostic text at 6,000 characters
plus omission notices.

Runtime changes stay inside the Raven-Code code-flow plugin, except for
one fix to `CheckpointService.trackable`, the visibility verdict that
exec diagnostics and the host's exec write record both rely on. On
macOS, git precomposes a file name it reads off the disk before matching
an ignore rule, but takes the paths `trackable` sends to `git
check-ignore --stdin` as written. A file stored with a decomposed (NFD)
name under a `.gitignore` rule written precomposed (NFC) is therefore
left out of the checkpoint, yet main vouches for it, so the write
record's diff carries its text, and exec diagnostics would quote its
source lines to the model. Nor is git's precomposition NFC: it composes
only neighbouring characters, by Unicode 3.2's table, and reorders
nothing, so a name whose combining marks are out of canonical order
comes out as neither the name as given nor its NFC. `trackable` now asks
about each name as given, as NFC and in git's macOS spelling, and
withholds it when any spelling is ignored. Other shared
file/shell/snapshot implementations are unchanged.

Raven-Code has no separate dependency manifest, so Pyflakes uses the
existing root dependencies. It is the only added package; uv normalized
existing lockfile markers without changing other package versions.

## Type

- [ ] Fix
- [x] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

- **Before:** on main, Raven-Code's file tools report Python syntax
errors only, and its exec reports nothing about the Python files a
command changed. On macOS, main's `CheckpointService.trackable` vouches
for a file stored as `secret_cafe` + U+0301 + `.py` under the rule
`secret_caf` + U+00E9 + `.py`: the user's own git ignores it and the
checkpoint's staged tree leaves it out, yet its text reaches the exec
write record's stored diff.
- **After:** on macOS 26.6.2 / arm64 with Apple Git 2.54.0, the command
below passes 364 tests on Python 3.12.13 and on 3.14.6. The full default
suite on 3.12.13 has 32283 passed, 169 skipped, 20 failed and 3 errors
over 22 test ids: 21 of them also fail on the exact base in the same
environment, and the other, a remote process-tree cancel test that
missed its deadline under the suite's load, passes when run alone. Tests
cover actual worker overlap, retained capacity after
timeout/cancellation, host-tool isolation, hidden-file quotas,
visibility batching through the host's write-record wiring, baseline
handling, parser-limit failures, the size bounds and their skip notes,
undecodable bytes placed where decoding stops, coding declarations in
written and edited text, the baseline read staying on a worker, the
checker loaded with its module, the file each unavailable note names,
comment directives and their marker boundary, the tool guide's agreement
with the syntax note, portable commands in paths with spaces/non-ASCII
characters, and the checkpoint's verdict on decomposed names and on
names git spells as neither given nor NFC, held against its own staged
tree. Removing any of the three spellings from the query fails the cases
that pin it, as does removing the marker boundary, the parser-limit
report, the unknown-baseline handling, the syntax check past the
name-check bound and the decoding report, checking written text as its
stored bytes, the worker around the baseline read, loading the checker
with its module, or the file name in an unavailable note; restoring the
guide's earlier advice fails its agreement test. git's macOS spelling is
what libiconv's UTF-8-MAC conversion returns, which git precomposes
with: composing neighbours by Unicode 3.2's table reproduced it for all
281,928 names built from every decomposable character's decomposition
(reordered, partly composed, or with a mark added), and across 784,220
further mixed names and pairs no name was spelled outside the three
asked; the same held under Python 3.13 and 3.14. The decomposed-name
check asserts the macOS outcome only where git precomposes names, so it
also passes with `core.precomposeunicode = false` set through
`GIT_CONFIG_GLOBAL`. Across 102 noqa comment variants the reported lines
match Ruff 0.15.12, except the three that hold several directives in one
comment. Through the real `AgentLoop`, code-flow tool face,
`CodeExecutor` and checkpoint, with the working directory under `/tmp`,
under `$TMPDIR` and in a path with spaces and CJK characters, exec
diagnostics report created, modified and decomposed-name files, follow
`working_dir`, report an undecodable file at the line where decoding
stops, a syntax error past 256 KiB and a skip past 2 MiB, and withhold
`.gitignore`d files, including decomposed names and names git spells as
neither given nor NFC; across repeated runs on both interpreters, a file
near the 256 KiB cap is checked in 52-135 ms (117-128 ms against a
baseline), the syntax of a file near 2 MiB in 318-371 ms, and 600
ignored files plus one visible file take 73-90 ms with the event loop
held at most 20 ms. At this head CI passes the unit suite on
Linux/Python 3.12 (32619 tests over four shards), and its two Windows
steps pass the diagnostic files on native Windows/Python 3.13: 122
file/worker tests, and 27 exec diagnostic tests with 17 pre-existing
executor tests deselected; the symlink fixture skips only where the host
cannot create links.

```sh
env -u SERPER_API_KEY -u RAVEN_MIRRORED_SERPER_API_KEY uv run --no-sync pytest tests/test_agents_code_diagnostic_workers.py tests/test_agents_code_tools_plugin.py tests/test_agents_code_flow_exec.py tests/test_agents_code_flow_plugin.py tests/test_agents_code_flow_read_state.py tests/test_agents_code_launcher.py tests/test_workdir_snapshot.py tests/test_shell_command_writes.py tests/test_runtime_checkpoint.py tests/test_trajectory_upload.py::test_blocked_upload_hits_the_deadline -o addopts= -q --tb=short --maxfail=3
uv run --no-sync ruff check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py tests/test_runtime_checkpoint.py tests/test_agents_code_flow_exec.py tests/test_agents_code_tools_plugin.py tests/test_agents_code_diagnostic_workers.py
uv run --no-sync ty check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py
uv run --no-sync lint-imports
uv run --no-sync ruff format --check raven/agent/loop/checkpoint.py agents/raven-code/plugins/code-flow/code_flow/tools agents/raven-code/plugins/code-flow/code_flow/config.py tests/test_runtime_checkpoint.py tests/test_agents_code_flow_exec.py tests/test_agents_code_tools_plugin.py
```

Native Windows CI commands:

```sh
uv run --frozen --python 3.13 --no-sync pytest tests/test_agents_code_diagnostic_workers.py tests/test_agents_code_tools_plugin.py -q -n 0 --tb=short
uv run --frozen --python 3.13 --no-sync pytest tests/test_agents_code_flow_exec.py -k test_exec_ -q -n 0 --tb=short
```

Ruff, format and type checks passed; all 10 import contracts kept; the
commit-message, large-file and source-language checks pass over the
branch. The launcher tests unset inherited search API keys to keep the
expected tool list deterministic.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [x] User-facing docs or screenshots are updated when needed

## Risk

Scope: Raven-Code's enabled code-flow tool face; installing Pyflakes
does not activate checks in other agents. The change is reversible and
never fixes/removes code or rolls back edits. Static diagnostics can
need judgment for dynamic names, target Python versions, and project
lint configuration; only explicit noqa directives are honored. Passing
diagnostics do not replace tests.

The `trackable` fix reaches every exec write record, not only
Raven-Code: a file whose name, as given, as NFC or in git's macOS
spelling, matches an ignore rule keeps its counts and loses its diff and
removal body. Where git matches another of those spellings, as off macOS
for a decomposed name under a precomposed rule, the checkpoint stores
the file but it is still withheld; its counts remain.

Exec diagnostics now require an active checkpoint. Noninteractive runs
using the default interactive checkpoint policy must explicitly enable
checkpoints to receive this feedback. Visibility is checked in batches
of up to 256 files and stops once eight visible files are found; each
batch holds the event loop while the host resolves its paths, about 130
ms for a full batch on native Windows. Each file-check wait is one
second, and post-command diagnostics have a three-second wait budget;
past it, or when they fail as a whole, they are dropped and the
command's result is kept. These are caller budgets, not hard I/O
deadlines: running OS reads and inherited synchronous host callbacks
cannot be forcibly interrupted. Private worker capacity remains bounded.
Between 256 KiB and 2 MiB only syntax is checked: near 2 MiB that took
0.3-0.4 s and about 190 MiB here, up to four checks run at once, and on
slower hardware such a check can outlast the one-second wait and report
diagnostics unavailable. Python's GIL means concurrency does not promise
a CPU speedup.

Windows CI exercises the diagnostics layer with the real native
DirectExecutor. The existing CodeExecutor environment probe uses POSIX
quoting and already fails on Windows at the base; this PR neither
changes that probe nor claims end-to-end compatibility for it. Symlink
setup is skipped only if the host cannot create the fixture.

Disable `pythonLint` for syntax-only feedback, `execPythonDiagnostics`
for no post-command checks, or `pythonSyntaxNote` for no diagnostics,
under `plugins.config["code-flow"].tools`. The PR can also be reverted
as a unit.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Dizhan Xue <xuedizhan17@mails.ucas.ac.cn>
Co-authored-by: Claude (claude-opus-5-5) <noreply@anthropic.com>
2026-10-18 20:21:04 +08:00

807 lines
33 KiB
Python

"""The code flow's exec: trunk's shell tool with the fork's fixes.
A long timeout is clamped instead of refused; a timed-out command keeps the
output it produced and says so in as many words; an oversized output is saved
whole under Agent home with the path in the result. Keeping the output is no
longer a difference -- trunk does that itself now -- so what this adds on that
axis is the explicit marker. And the sandbox discipline: the factory serves this
host-running replacement only where the host's own exec would run on the host
too, and declines under any configured sandbox backend.
"""
from __future__ import annotations
import asyncio
import json
import os
import shlex
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
import pytest
from raven.agent.loop.checkpoint import CheckpointService
from raven.agent.tools.registry import ToolRegistry
from raven.agent.tools.shell import ExecTool as TrunkExecTool
from raven.plugins.context import PluginContext, ServiceLocator
from raven.sandbox.direct_executor import DirectExecutor
REPO = Path(__file__).resolve().parent.parent
PLUGIN_DIR = REPO / "agents" / "raven-code" / "plugins" / "code-flow"
sys.path.insert(0, str(PLUGIN_DIR))
from code_flow.tools import plugin as factories # noqa: E402
from code_flow.tools.exec import ( # noqa: E402
MAX_OUTPUT,
SPILL_SUBDIR,
TIMED_OUT_NOTE,
CodeExecResult,
CodeExecTool,
CodeExecutor,
)
def _run(coro):
return asyncio.run(coro)
def _ctx(tmp_path: Path, tools: dict | None = None) -> PluginContext:
return PluginContext(
config={"enabled": True, "tools": {"enabled": True, **(tools or {})}},
services=ServiceLocator(workspace=tmp_path / "home", user_id="u", agent_id="a"),
)
def _tool(tmp_path: Path, max_timeout: int = 1200) -> CodeExecTool:
home = tmp_path / "home"
home.mkdir(exist_ok=True)
return CodeExecTool(
timeout=60,
working_dir=str(home),
executor=CodeExecutor(max_timeout=max_timeout, spill_dir=home / SPILL_SUBDIR),
extra_allowed_dirs=(home,),
max_timeout=max_timeout,
)
def _diagnostic_tool(tmp_path: Path, tools: dict | None = None) -> CodeExecTool:
(tmp_path / "home").mkdir(exist_ok=True)
tool = factories.make_exec(_ctx(tmp_path, tools))
assert tool is not None
# The existing CodeExecutor probe uses POSIX quoting. Exercise the new
# diagnostic layer with the real native host executor on Windows.
if os.name == "nt":
tool._executor = DirectExecutor()
repos = {}
def shadow(root):
if root not in repos:
repos[root] = CheckpointService(root)
return repos[root]
# As the loop wires a same-name exec: the write record and the visibility
# hook arrive together, through the one door production uses.
tool.measure_writes(shadow)
return tool
def _python_command(tmp_path: Path, source: str) -> str:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=tmp_path, suffix=".py", delete=False) as script:
script.write(source)
argv = [sys.executable, script.name]
return subprocess.list2cmdline(argv) if os.name == "nt" else shlex.join(argv)
def _write_command(tmp_path: Path, files: dict[str, str], *, exit_code: int = 0) -> str:
source = "from pathlib import Path\n"
for name, text in files.items():
source += f"Path({name!r}).parent.mkdir(parents=True, exist_ok=True)\n"
source += f"Path({name!r}).write_text({text!r}, encoding='utf-8')\n"
return _python_command(tmp_path, source + f"raise SystemExit({exit_code})\n")
def test_exec_created_python_gets_name_diagnostics_in_the_command_result(tmp_path):
tool = _diagnostic_tool(tmp_path)
out = _run(tool.execute(command=_write_command(tmp_path, {"created.py": "result = missing_value\n"})))
assert "Exit code: 0" in str(out) and "F821" in str(out) and "missing_value" in str(out)
assert getattr(out, "ok", None) is True
assert (tmp_path / "home" / "created.py").read_text() == "result = missing_value\n"
def test_exec_diagnostics_work_in_paths_with_spaces_and_non_ascii_characters(tmp_path):
root = tmp_path / "space path \u00e9"
root.mkdir()
tool = _diagnostic_tool(root)
out = _run(tool.execute(command=_write_command(root, {"created.py": "result = missing_value\n"})))
assert out.ok is True and "F821" in str(out)
assert (root / "home" / "created.py").read_text() == "result = missing_value\n"
def test_exec_reuses_the_hosts_write_record_and_keeps_it_in_the_result(tmp_path):
tool = _diagnostic_tool(tmp_path)
out = _run(tool.execute(command=_write_command(tmp_path, {"recorded.py": "result = missing_value\n"})))
assert "F821" in str(out)
assert len(out.written) == 1 and out.written[0].path.endswith("recorded.py")
def test_exec_modified_python_labels_unknown_baseline_and_ignores_untouched_files(tmp_path):
tool = _diagnostic_tool(tmp_path)
home = tmp_path / "home"
(home / "untouched.py").write_text("old = untouched_missing\n")
(home / "changed.py").write_text("value = 1\n")
out = str(_run(tool.execute(command=_write_command(tmp_path, {"changed.py": "value = newly_missing\n"}))))
assert "newly_missing" in out and "baseline is unknown" in out
assert "untouched_missing" not in out
assert "Python diagnostics" not in str(
_run(
tool.execute(
command=_python_command(tmp_path, "from pathlib import Path; print(Path('changed.py').read_text())")
)
)
)
def test_exec_syntax_feedback_keeps_command_failure_and_does_not_rollback(tmp_path):
tool = _diagnostic_tool(tmp_path)
out = _run(tool.execute(command=_write_command(tmp_path, {"broken.py": "def f(:\n"}, exit_code=7)))
assert "Exit code: 7" in str(out) and "syntax error" in str(out)
assert getattr(out, "ok", None) is False
assert (tmp_path / "home" / "broken.py").read_text() == "def f(:\n"
def test_exec_diagnostics_follow_explicit_working_directory_and_have_a_switch(tmp_path):
home = tmp_path / "home"
home.mkdir()
elsewhere = home / "elsewhere"
elsewhere.mkdir()
tool = _diagnostic_tool(tmp_path)
out = str(
_run(tool.execute(command=_write_command(tmp_path, {"other.py": "x = missing\n"}), working_dir=str(elsewhere)))
)
assert os.path.join("elsewhere", "other.py") in out and "F821" in out
quiet = _diagnostic_tool(tmp_path, {"execPythonDiagnostics": False})
out = str(_run(quiet.execute(command=_write_command(tmp_path, {"quiet.py": "def f(:\n"}))))
assert "Python diagnostics" not in out
def test_exec_notes_preserve_file_metadata_and_control_flags():
from code_flow.tools.exec import _prefixed
from raven.contracts.tool import Continuation, FileRemoval, FileWrite, ToolOutput, ToolResult
for cls in (ToolOutput, ToolResult):
original = cls(
"command failed",
ok=False,
retryable=False,
blocks_call=True,
continuation=Continuation.CONTINUE,
written=(FileWrite(path="a.py", created=True, size=1),),
removed=(FileRemoval(path="gone.py"),),
)
annotated = _prefixed(" diagnostic", original, append=True)
assert annotated.written == original.written and annotated.removed == original.removed
assert annotated.ok is False and annotated.retryable is False and annotated.blocks_call is True
def test_exec_diagnostics_do_not_read_files_withheld_by_the_host(tmp_path):
class Shadow:
async def stage_tree(self):
return None
async def trackable(self, paths):
return {path for path in paths if Path(path).name != "private.py"}
tool = _diagnostic_tool(tmp_path)
tool.measure_writes(lambda root: Shadow())
out = _run(
tool.execute(
command=_write_command(
tmp_path,
{"private.py": "private_value = private_missing\n", "public.py": "public_value = public_missing\n"},
)
)
)
assert "public_missing" in str(out)
assert "private_missing" not in str(out)
assert out.ok is True and len(out.written) == 2
def test_exec_without_a_write_record_reads_nothing(tmp_path, monkeypatch):
from code_flow.tools import diagnostics
from raven.contracts.tool import FileWrite, ToolOutput
tool = _diagnostic_tool(tmp_path)
target = tmp_path / "home" / "recorded.py"
reads, records = [], []
monkeypatch.setattr(diagnostics, "read_source", lambda path: reads.append(path) or b"")
async def host(*args, **kwargs):
# With no record, as when the host's listing gave up: the output alone.
return ToolOutput("Exit code: 0", ok=True, written=tuple(records))
monkeypatch.setattr(TrunkExecTool, "execute", host)
out = _run(tool.execute(command="test command"))
assert out.ok is True and str(out) == "Exit code: 0" and reads == []
# The control: the same tool reads the file once the host records it.
records.append(FileWrite(path=str(target), created=True, size=24))
_run(tool.execute(command="test command"))
assert reads == [target]
@pytest.mark.parametrize("kind", ["timeout", "exception"])
def test_exec_post_command_checker_failure_keeps_original_exit_and_output(tmp_path, monkeypatch, kind):
from code_flow.tools import exec as module
tool = _diagnostic_tool(tmp_path)
async def broken(*args):
if kind == "timeout":
await asyncio.Event().wait()
raise RuntimeError("diagnostic failed")
monkeypatch.setattr(tool, "_diagnose_writes", broken)
monkeypatch.setattr(module, "_DIAGNOSTIC_WAIT_SECONDS", 0.01)
out = _run(tool.execute(command=_python_command(tmp_path, "print('evidence'); raise SystemExit(9)")))
assert "evidence" in str(out) and "Exit code: 9" in str(out)
assert out.ok is False
def test_exec_refused_command_takes_no_diagnostics(tmp_path, monkeypatch):
tool = _diagnostic_tool(tmp_path)
calls = []
async def diagnose(*args):
calls.append(args)
return "unexpected"
monkeypatch.setattr(tool, "_diagnose_writes", diagnose)
monkeypatch.setattr(tool, "_guard_command", lambda *args: "refused for this test")
out = _run(tool.execute(command="echo refused"))
assert not calls and out.blocks_call
def test_exec_diagnostics_limit_changed_files_and_output(tmp_path):
tool = _diagnostic_tool(tmp_path)
files = {f"file{i}.py": "result = missing\n" for i in range(10)}
files.update({f"notes{i}.txt": "not python\n" for i in range(3)})
out = str(_run(tool.execute(command=_write_command(tmp_path, files))))
assert out.count("Python diagnostics for") == 8
assert "2 more were skipped" in out and "notes" not in out
assert len(out) < 6500
def test_exec_checks_four_files_at_a_time_in_stable_order_with_an_eight_file_cap(tmp_path, monkeypatch):
from code_flow.tools import diagnostics
tool = _diagnostic_tool(tmp_path)
barrier = threading.Barrier(4, timeout=2)
lock = threading.Lock()
active = peak = 0
checked = []
def note(self, path, text, **kwargs):
nonlocal active, peak
with lock:
active += 1
peak = max(peak, active)
checked.append(path.name)
try:
barrier.wait()
return f"checked:{path.name}"
finally:
with lock:
active -= 1
monkeypatch.setattr(diagnostics.PythonDiagnostics, "note", note)
out = str(_run(tool.execute(command=_write_command(tmp_path, {f"file{i}.py": "x = 1\n" for i in range(10)}))))
assert peak == 4 and len(checked) == 8
assert sorted(checked) == [f"file{i}.py" for i in range(8)]
positions = [out.index(f"checked:file{i}.py") for i in range(8)]
assert positions == sorted(positions)
assert "2 more were skipped" in out
@pytest.mark.parametrize("visible_count", [1, 10])
def test_exec_withheld_files_do_not_consume_the_diagnostic_file_limit(tmp_path, monkeypatch, visible_count):
from raven.contracts.tool import FileWrite, ToolOutput
batches = []
class Shadow:
async def trackable(self, paths):
batches.append(list(paths))
return {path for path in paths if Path(path).name.startswith("visible")}
tool = _diagnostic_tool(tmp_path)
tool.measure_writes(lambda root: Shadow())
paths = [tmp_path / "home" / f"private{i}.py" for i in range(8)] + [
tmp_path / "home" / f"visible{i}.py" for i in range(visible_count)
]
for path in paths:
path.write_text("value = missing_binding\n")
async def host(*args, **kwargs):
return ToolOutput(
"Exit code: 0", ok=True, written=tuple(FileWrite(path=str(p), created=True, size=24) for p in paths)
)
monkeypatch.setattr(TrunkExecTool, "execute", host)
out = str(_run(tool.execute(command="test command")))
assert "visible0.py" in out and "F821" in out
assert all(f"private{i}.py" not in out for i in range(8))
assert [len(batch) for batch in batches] == [8 + visible_count]
assert out.count("Python diagnostics for") == min(8, visible_count)
if visible_count > 8:
assert "2 more were skipped" in out and "visible8.py" not in out
else:
assert "were skipped" not in out
def test_exec_ignored_files_are_asked_about_in_wide_batches(tmp_path, monkeypatch):
from raven.contracts.tool import FileWrite, ToolOutput
queries = []
class Shadow:
async def trackable(self, paths):
queries.append(len(paths))
return {path for path in paths if Path(path).name == "visible.py"}
tool = _diagnostic_tool(tmp_path)
tool.measure_writes(lambda root: Shadow())
home = tmp_path / "home"
ignored = [home / "build" / f"mod{i}.py" for i in range(600)]
visible = home / "visible.py"
visible.write_text("shown = visible_missing\n")
async def host(*args, **kwargs):
# Ordered the way the host sorts its record: the ignored tree first.
records = [FileWrite(path=str(p), created=True, size=1) for p in ignored]
records.append(FileWrite(path=str(visible), created=True, size=24))
return ToolOutput("Exit code: 0", ok=True, written=tuple(records))
monkeypatch.setattr(TrunkExecTool, "execute", host)
out = str(_run(tool.execute(command="test command")))
assert queries == [256, 256, 89]
assert "visible_missing" in out and "mod0.py" not in out
def test_exec_visibility_queries_stop_once_the_file_limit_is_visible(tmp_path, monkeypatch):
from raven.contracts.tool import FileWrite, ToolOutput
queries = []
class Shadow:
async def trackable(self, paths):
queries.append(len(paths))
return set(paths)
tool = _diagnostic_tool(tmp_path)
tool.measure_writes(lambda root: Shadow())
paths = [tmp_path / "home" / f"file{i:03}.py" for i in range(300)]
for path in paths[:8]:
path.write_text("value = missing_binding\n")
async def host(*args, **kwargs):
return ToolOutput(
"Exit code: 0", ok=True, written=tuple(FileWrite(path=str(p), created=True, size=24) for p in paths)
)
monkeypatch.setattr(TrunkExecTool, "execute", host)
out = str(_run(tool.execute(command="test command")))
assert queries == [256]
assert out.count("Python diagnostics for") == 8
assert "248 more were skipped" in out
assert "44 additional changed files were not checked" in out
def test_exec_visibility_batches_yield_to_the_post_command_deadline(tmp_path, monkeypatch):
from code_flow.tools import exec as module
from raven.contracts.tool import FileWrite, ToolOutput
calls = []
class Shadow:
async def trackable(self, paths):
# Stands for the host resolving every path on the loop: no await.
calls.append(len(paths))
time.sleep(0.06)
return set()
tool = _diagnostic_tool(tmp_path)
tool.measure_writes(lambda root: Shadow())
home = tmp_path / "home"
records = tuple(FileWrite(path=str(home / f"mod{i}.py"), created=True, size=1) for i in range(3000))
async def host(*args, **kwargs):
return ToolOutput("Exit code: 0", ok=True, written=records)
monkeypatch.setattr(TrunkExecTool, "execute", host)
monkeypatch.setattr(module, "_DIAGNOSTIC_WAIT_SECONDS", 0.05)
out = _run(tool.execute(command="test command"))
assert str(out) == "Exit code: 0" and out.ok is True
# Twelve batches in all; the deadline stops them at a yield in between.
assert 1 <= len(calls) < 12
@pytest.mark.asyncio
async def test_exec_diagnostics_do_not_stat_walk_or_open_files_on_the_event_loop(tmp_path, monkeypatch):
"""The plugin's own selection, with the host's visibility hook faked out:
every stat, walk and open it needs happens on a diagnostic worker."""
import io
from raven.contracts.tool import FileWrite, ToolOutput
loop_thread = threading.get_ident()
on_loop, walked = [], []
active = False
def watch(module, name):
original = getattr(module, name)
def watched(*args, **kwargs):
if active and threading.get_ident() == loop_thread:
on_loop.append(name)
if active and name == "scandir":
walked.append(args)
return original(*args, **kwargs)
monkeypatch.setattr(module, name, watched)
for module, name in ((os, "stat"), (os, "lstat"), (os, "scandir"), (os.path, "realpath"), (io, "open")):
watch(module, name)
class Shadow:
async def trackable(self, paths):
return {path for path in paths if Path(path).name == "visible.py"}
tool = _diagnostic_tool(tmp_path)
tool.measure_writes(lambda root: Shadow())
home = tmp_path / "home"
visible = home / "visible.py"
visible.write_text("shown = visible_missing\n")
records = [FileWrite(path=str(home / "build" / f"mod{i}.py"), created=True, size=1) for i in range(3000)]
records.append(FileWrite(path=str(visible), created=True, size=24))
active = True
try:
note = await tool._diagnose_writes(home, ToolOutput("Exit code: 0", ok=True, written=tuple(records)))
finally:
active = False
assert "visible_missing" in note
assert on_loop == [] and walked == []
@pytest.mark.asyncio
async def test_exec_checks_a_changed_file_as_a_written_one_is_checked(tmp_path):
"""Syntax past the name checks' bound, a line for each check that did not
run, and bytes Python cannot decode reported where decoding stops."""
from code_flow.tools.diagnostics import MAX_SOURCE_BYTES, MAX_SYNTAX_BYTES
from raven.contracts.tool import FileWrite, ToolOutput
class Shadow:
async def trackable(self, paths):
return set(paths)
tool = _diagnostic_tool(tmp_path)
tool.measure_writes(lambda root: Shadow())
home = tmp_path / "home"
rows = MAX_SOURCE_BYTES // len("value = 1\n") + 1
files = {
"large_broken.py": ("value = 1\n" * rows + "def broken(:\n").encode(),
"large_clean.py": ("value = 1\n" * rows).encode(),
"huge.py": b"#" * (MAX_SYNTAX_BYTES + 1),
"legacy.py": "# coding: gbk\nlabel = '\u4e2d'\n".encode(),
}
for name, raw in files.items():
(home / name).write_bytes(raw)
records = tuple(FileWrite(path=str(home / name), created=True, size=len(raw)) for name, raw in files.items())
note = await tool._diagnose_writes(home, ToolOutput("Exit code: 0", ok=True, written=records))
assert f"WARNING: line {rows + 1}, column 12: Python syntax error" in note
assert f"Python name checks skipped for {home / 'large_clean.py'}" in note
assert f"Python diagnostics skipped for {home / 'huge.py'}: the source is over 2 MiB" in note
assert "line 2, column 12: Python syntax error: 'gbk' codec can't decode byte 0xad" in note
def test_exec_diagnostics_skip_symlinks_cache_and_non_python_files(tmp_path):
tool = _diagnostic_tool(tmp_path)
home = tmp_path / "home"
outside = tmp_path / "outside.py"
outside.write_text("value = external_missing\n")
try:
(tmp_path / "probe_link.py").symlink_to(outside)
except (OSError, NotImplementedError):
pytest.skip("This host cannot create the symlink fixture")
command = _python_command(
tmp_path,
"import os\n"
"from pathlib import Path\n"
f"os.symlink({str(outside)!r}, 'link.py')\n"
"Path('.venv').mkdir()\n"
"Path('.venv/cached.py').write_text('x = cached_missing\\n')\n"
"Path('text.txt').write_text('def f(:\\n')\n"
"Path('shown.py').write_text('y = shown_missing\\n')\n",
)
out = str(_run(tool.execute(command=command)))
assert (home / "link.py").is_symlink()
assert "shown_missing" in out
assert "external_missing" not in out and "cached_missing" not in out and "text.txt" not in out
@pytest.mark.parametrize("params", [{"machine": "elsewhere"}, {"run_in_background": True}])
def test_exec_nonlocal_or_background_commands_take_no_local_diagnostics(tmp_path, monkeypatch, params):
from raven.contracts.tool import ToolOutput
tool = _diagnostic_tool(tmp_path)
calls = []
async def diagnose(*args):
calls.append(args)
return "unexpected"
async def host(*args, **kwargs):
return ToolOutput("host response", ok=True)
monkeypatch.setattr(tool, "_diagnose_writes", diagnose)
monkeypatch.setattr(TrunkExecTool, "execute", host)
assert str(_run(tool.execute(command="test command", **params))) == "host response"
assert calls == []
def test_exec_missing_visibility_verdict_never_falls_back_to_reading_the_file(tmp_path, monkeypatch):
from raven.contracts.tool import FileWrite, ToolOutput
class Shadow:
async def trackable(self, paths):
raise RuntimeError("visibility unavailable")
tool = _diagnostic_tool(tmp_path)
target = tmp_path / "home" / "withheld.py"
target.write_text("value = confidential_name\n")
tool.measure_writes(lambda root: Shadow())
async def host(*args, **kwargs):
return ToolOutput("Exit code: 0", ok=True, written=(FileWrite(path=str(target), created=True, size=1),))
monkeypatch.setattr(TrunkExecTool, "execute", host)
out = _run(tool.execute(command="test command"))
assert out.ok is True and len(out.written) == 1
assert "confidential_name" not in str(out)
@pytest.mark.parametrize("hook", [None, lambda root: None])
def test_exec_without_checkpoint_never_reads_changed_file_contents(tmp_path, monkeypatch, hook):
from code_flow.tools import diagnostics
from raven.contracts.tool import FileWrite, ToolOutput
tool = _tool(tmp_path)
tool.measure_writes(hook)
target = tmp_path / "home" / "local_secrets.py"
target.write_text("token = confidential_name\n")
(target.parent / ".gitignore").write_text("local_secrets.py\n")
reads = []
def read(path):
reads.append(path)
return path.read_bytes()
async def host(*args, **kwargs):
return ToolOutput("Exit code: 0", ok=True, written=(FileWrite(path=str(target), created=True, size=26),))
monkeypatch.setattr(diagnostics, "read_source", read)
monkeypatch.setattr(TrunkExecTool, "execute", host)
out = _run(tool.execute(command="test command"))
assert reads == [] and str(out) == "Exit code: 0"
assert out.ok is True and len(out.written) == 1
# --- the schema and the clamp -------------------------------------------------------
def test_the_timeout_has_a_ceiling_but_no_schema_maximum(tmp_path):
"""Trunk refuses ``timeout > 600`` at validation; here the schema carries no
maximum, so the call runs and the clamp is reported instead."""
tool = _tool(tmp_path)
timeout = tool.parameters["properties"]["timeout"]
assert "maximum" not in timeout
assert "clamped" in timeout["description"] and "1200" in timeout["description"]
trunk = TrunkExecTool().parameters["properties"]["timeout"]
assert trunk["maximum"] == 600, "the trunk shape this replacement departs from"
assert tool.timeout_seconds == 1260.0
def test_a_timeout_above_the_ceiling_is_clamped_and_said_so(tmp_path):
tool = _tool(tmp_path)
out = _run(tool.execute(command="echo clamped-run", timeout=99_999))
text = str(out)
assert text.startswith("[note: timeout 99999s clamped to the 1200s ceiling")
assert "clamped-run" in text and "Exit code: 0" in text
assert getattr(out, "ok", None) is True, "the note does not change the verdict"
def test_a_timeout_within_the_ceiling_runs_untouched(tmp_path):
tool = _tool(tmp_path)
out = str(_run(tool.execute(command="echo fine", timeout=900)))
assert not out.startswith("[note") and "fine" in out
def test_the_registry_runs_a_long_timeout_instead_of_refusing_it(tmp_path):
"""Through the registry, which validates against the schema: trunk's tool
would answer a validation error, this one runs."""
reg = ToolRegistry()
reg.register(_tool(tmp_path))
out = str(_run(reg.execute("exec", {"command": "echo via-registry", "timeout": 5000})))
assert "via-registry" in out and "clamped to the 1200s ceiling" in out
# --- partial output on timeout -----------------------------------------------------------
def test_a_timed_out_command_keeps_the_output_it_produced(tmp_path):
tool = _tool(tmp_path)
out = _run(tool.execute(command="echo started; echo more >&2; sleep 30", timeout=1))
text = str(out)
assert "started" in text, "what the command printed before the kill is kept"
assert "STDERR:\nmore" in text
assert "Timed out after 1s" in text and TIMED_OUT_NOTE in text
assert "Exit code: -1" in text
assert getattr(out, "ok", None) is False
def test_trunks_executor_preserves_output_on_timeout(tmp_path):
"""The shared executor preserves output produced before the timeout.
This is the retired half of the reason the fork replaced it: trunk used to
wait on ``communicate()`` and lose the buffered output when that raised,
which is why this file's own partial-output fix was written. Trunk drains
the pipes itself now, so that axis no longer tells the two apart.
What is still this fork's on the same axis is the explicit marker. Trunk
reports the kill through the stderr line and exit ``-1`` and nothing more,
while ``CodeExecResult`` also flags ``timed_out`` and renders
``TIMED_OUT_NOTE``, which tells the model its output is a fragment. The
last assertion is what keeps the two from quietly converging.
"""
from raven.sandbox.direct_executor import DirectExecutor
command = "echo started; sleep 30"
result = _run(DirectExecutor().exec(command, timeout=0.3))
assert result.stdout == "started\n"
assert "Timed out" in result.stderr
assert result.exit_code == -1
# Both sides measured in one run, because the absence on its own is the
# vacuous kind of assertion: it also holds for a fork that stopped marking
# anything. The pair says the difference exists and which way round it is.
forked = str(_run(_tool(tmp_path).execute(command=command, timeout=0.3)))
assert TIMED_OUT_NOTE in forked, "the fork tells the model its output is a fragment"
assert TIMED_OUT_NOTE not in result.as_text(), "trunk does not, and that is what is left"
def test_a_finished_command_reports_its_exit_code_and_both_streams(tmp_path):
tool = _tool(tmp_path)
text = str(_run(tool.execute(command="echo out; echo err >&2; exit 3")))
assert "out" in text and "STDERR:\nerr" in text and "Exit code: 3" in text
assert TIMED_OUT_NOTE not in text
# --- the output budget and the spill ---------------------------------------------------
def test_an_oversized_output_is_cut_at_the_budget_and_saved_whole(tmp_path):
tool = _tool(tmp_path)
text = str(_run(tool.execute(command="i=0; while [ $i -lt 4000 ]; do echo line-$i-0123456789; i=$((i+1)); done")))
assert len(text) < MAX_OUTPUT + 600
assert "chars truncated; full output" in text
assert "full output saved to " in text
saved = Path(text.split("full output saved to ", 1)[1].split(";", 1)[0])
assert saved.parent == tmp_path / "home" / SPILL_SUBDIR, "under Agent home, never in the repository"
body = saved.read_text()
assert body.count("line-") == 4000 and "line-3999-0123456789" in body
assert "line-0-0123456789" in text and "line-3999-0123456789" in text, "head and tail stay in view"
def test_the_budget_is_thirty_thousand_not_trunks_ten(tmp_path):
result = CodeExecResult(stdout="x" * 20_000, stderr="", exit_code=0, spill_dir=tmp_path / "spill")
assert "truncated" not in result.as_text(), "20k fits the new budget"
assert not (tmp_path / "spill").exists(), "nothing is saved while nothing was cut"
assert "truncated" in result.as_text(10_000), "and would not have fit trunk's"
assert (tmp_path / "spill").exists(), "cut at trunk's budget, the whole output is saved"
def test_a_spill_that_cannot_be_written_still_returns_the_head_and_tail(tmp_path):
blocked = tmp_path / "blocked"
blocked.write_text("a file where the directory should be")
result = CodeExecResult(stdout="y" * 40_000, stderr="", exit_code=0, spill_dir=blocked)
text = result.as_text()
assert "truncated" in text and "re-run redirecting to a file" in text
# --- the environment discipline --------------------------------------------------------
def _child_env_keys(text: str) -> set[str]:
body = text.split("\nExit code:", 1)[0]
return set(json.loads(body))
def test_the_child_sees_exactly_the_host_executors_baseline(tmp_path, monkeypatch):
"""No private import of the trunk allowlist (a cargo redline), yet no drift
from it either: the keys a child gets here equal the keys a child gets from
the host's own executor, and a credential in the process environment
reaches neither."""
from raven.sandbox.direct_executor import DirectExecutor
monkeypatch.setenv("CODE_FLOW_TEST_SECRET", "do-not-leak")
probe = f"{sys.executable} -c 'import json,os;print(json.dumps(sorted(os.environ)))'"
theirs = set(json.loads(_run(DirectExecutor().exec(probe, timeout=15)).stdout))
ours = _child_env_keys(str(_run(_tool(tmp_path).execute(command=probe))))
shell_added = {"PWD", "OLDPWD", "SHLVL", "_"}
assert ours - shell_added == theirs - shell_added
assert "CODE_FLOW_TEST_SECRET" not in ours and "CODE_FLOW_TEST_SECRET" not in theirs
assert "PATH" in ours
def test_the_baseline_is_learned_once_and_read_fresh(tmp_path, monkeypatch):
tool = _tool(tmp_path)
executor = tool._executor
first = _run(executor.allowed_keys())
assert first is _run(executor.allowed_keys()), "one probe per executor"
monkeypatch.setenv("PATH", os.environ["PATH"] + os.pathsep + str(tmp_path / "fresh-bin"))
text = str(_run(tool.execute(command="echo $PATH")))
assert str(tmp_path / "fresh-bin") in text, "values come from the process environment at spawn time"
def test_a_failed_probe_leaves_exec_erroring_rather_than_guessing(tmp_path, monkeypatch):
tool = _tool(tmp_path)
monkeypatch.setattr(sys, "executable", str(tmp_path / "no-such-python"))
out = str(_run(tool.execute(command="echo never")))
assert out.startswith("Error executing command:") and "environment baseline" in out
# --- the factory and the sandbox discipline ---------------------------------------------
def test_the_factory_serves_the_replacement_only_on_the_host_backend(tmp_path):
served = factories.make_exec(
_ctx(tmp_path, {"exec": {"sandboxBackend": "none", "maxTimeout": 900, "timeout": 120}})
)
assert isinstance(served, CodeExecTool)
assert served._MAX_TIMEOUT == 900 and served.timeout == 120
assert isinstance(served._executor, CodeExecutor) and served._executor.is_sandboxed is False
for backend in ("boxlite", "auto", "docker"):
assert factories.make_exec(_ctx(tmp_path, {"exec": {"sandboxBackend": backend}})) is None, backend
def test_the_factory_declines_with_the_rest_of_the_face(tmp_path):
off = PluginContext(
config={"enabled": True, "tools": {"enabled": False}},
services=ServiceLocator(workspace=tmp_path / "home", user_id="u", agent_id="a"),
)
assert factories.make_exec(off) is None
def test_the_same_name_replacement_answers_the_call(tmp_path):
reg = ToolRegistry()
reg.register(TrunkExecTool(working_dir=str(tmp_path)))
reg.register(factories.make_exec(_ctx(tmp_path)))
served = reg.get("exec")
assert type(served) is CodeExecTool
assert "clamped" in reg.get("exec").parameters["properties"]["timeout"]["description"]
def test_the_published_config_carries_the_ceiling_in_the_slice_not_in_a_dead_host_key():
"""Trunk's ``tools.exec`` knows ``timeout`` and ``pathAppend`` only; a
``maxTimeout`` there was silently ignored. It lives in this plugin's slice."""
published = json.loads((REPO / "agents" / "raven-code" / "config.json").read_text())
assert "maxTimeout" not in published["tools"]["exec"]
assert published["plugins"]["config"]["code-flow"]["tools"]["exec"] == {"maxTimeout": 1200}