## 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>
436 lines
18 KiB
Python
436 lines
18 KiB
Python
"""exec -- the host's shell tool with the fork's fixes, served by name.
|
|
|
|
The trunk ``ExecTool`` is kept whole (its guards, its background lane, its
|
|
machine lane); this subclass changes what a coding run kept tripping over, and
|
|
does it on the executor seam ``ExecTool.__init__`` already exposes:
|
|
|
|
*A long timeout is clamped, not refused.* Trunk's schema says ``maximum: 600``,
|
|
so a model asking for 900 seconds for a slow test suite is answered with a
|
|
validation error and learns nothing. Here the schema carries no maximum, the
|
|
request is clamped to the configured ceiling, and the result says so.
|
|
|
|
*A timed-out command says so, in as many words.* Trunk's executor used to wait
|
|
on ``communicate()``, so when that raised on timeout the buffered output was
|
|
gone and the model read ``Timed out after 600s`` with nothing else -- for a
|
|
test suite that printed forty passes and one hang, the forty passes vanished.
|
|
Trunk drains the pipes itself now and hands back what arrived, so the output is
|
|
no longer what separates the two. What remains here is the reading: trunk
|
|
signals the kill through ``exit_code`` and a stderr line, while
|
|
``CodeExecResult`` flags ``timed_out`` and renders ``TIMED_OUT_NOTE``, which
|
|
tells the model the output is a fragment rather than the whole run. The drain
|
|
below therefore duplicates trunk's; retiring it is the fork owners' call, and
|
|
nothing depends on which of the two performs it.
|
|
|
|
*A large output is saved whole, not lost in the middle.* Trunk keeps the head
|
|
and the tail of 10,000 characters; the middle is nowhere. Here the budget is
|
|
30,000 and the complete output is written under Agent home (never into the
|
|
repository), with the path in the result, so the model can grep it instead of
|
|
re-running blind.
|
|
|
|
Sandbox discipline: this executor runs on the host, exactly as the trunk's
|
|
``DirectExecutor`` does when ``tools.sandbox.backend`` is ``none``. The factory
|
|
serves this tool only in that case and declines otherwise, so a configured
|
|
sandbox is never bypassed by a same-name replacement.
|
|
|
|
Environment discipline: the host executor hands a child only an allowlisted
|
|
baseline of the process environment (never credentials), and that allowlist is
|
|
a private detail of the trunk module -- a product plugin may not import it
|
|
(the cargo redlines). So the baseline is learned from the host executor itself:
|
|
one probe command run through the public ``exec`` reports which variables a
|
|
child receives, and this executor passes exactly those, read fresh from the
|
|
process environment at every spawn. No copy of the list, so no drift.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import itertools
|
|
import json
|
|
import os
|
|
import shlex
|
|
import sys
|
|
import time
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from loguru import logger
|
|
|
|
from code_flow.tools.diagnostic_workers import MAX_WORKERS
|
|
from code_flow.tools.diagnostics import UNKNOWN, PythonDiagnostics
|
|
from raven.agent.tools.shell import ExecTool
|
|
from raven.contracts.tool import ToolOutput, ToolResult
|
|
from raven.sandbox.direct_executor import DirectExecutor
|
|
from raven.sandbox.interfaces import ExecResult
|
|
|
|
DEFAULT_TIMEOUT = 60
|
|
DEFAULT_MAX_TIMEOUT = 1200
|
|
MAX_OUTPUT = 30_000
|
|
#: Where an oversized output is saved whole, under Agent home.
|
|
SPILL_SUBDIR = "exec-output"
|
|
|
|
TIMED_OUT_NOTE = (
|
|
"[the command hit its time limit and was killed; the output above is what it had "
|
|
"produced by then and is partial. Retry with a larger `timeout` if it just needs "
|
|
"longer, or run it with run_in_background: true and read its log]"
|
|
)
|
|
|
|
_SPILL_COUNTER = itertools.count(1)
|
|
|
|
#: Variables the probe's own shell adds on top of the baseline; not part of it.
|
|
_SHELL_ADDED = frozenset({"PWD", "OLDPWD", "SHLVL", "_"})
|
|
_PROBE_TIMEOUT = 15
|
|
_DIAGNOSTIC_WAIT_SECONDS = 3.0
|
|
_DIAGNOSTIC_FILES = 8
|
|
_DIAGNOSTIC_CHARS = 6000
|
|
_VISIBILITY_BATCH = 256
|
|
|
|
|
|
def spill_output(text: str, spill_dir: Path | None) -> str | None:
|
|
"""Save ``text`` whole under ``spill_dir``; the path, or None when it cannot be saved."""
|
|
if spill_dir is None:
|
|
return None
|
|
path = spill_dir / f"exec-{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}-{next(_SPILL_COUNTER)}.log"
|
|
try:
|
|
spill_dir.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(text, encoding="utf-8")
|
|
except OSError as exc:
|
|
logger.warning("code-flow exec: could not save the full output to {}: {}", path, exc)
|
|
return None
|
|
return str(path)
|
|
|
|
|
|
@dataclass
|
|
class CodeExecResult(ExecResult):
|
|
"""Trunk's result plus what a coding run needs to read it right."""
|
|
|
|
timed_out: bool = False
|
|
spill_dir: Path | None = None
|
|
|
|
def as_text(self, max_chars: int = MAX_OUTPUT) -> str:
|
|
parts = []
|
|
if self.stdout:
|
|
parts.append(self.stdout)
|
|
if self.stderr.strip():
|
|
parts.append(f"STDERR:\n{self.stderr}")
|
|
parts.append(f"\nExit code: {self.exit_code}")
|
|
if self.timed_out:
|
|
parts.append(TIMED_OUT_NOTE)
|
|
result = "\n".join(parts)
|
|
if len(result) <= max_chars:
|
|
return result
|
|
half = max_chars // 2
|
|
total_lines = result.count("\n") + 1
|
|
spilled = spill_output(result, self.spill_dir)
|
|
if spilled:
|
|
recovery = (
|
|
f"... [full output saved to {spilled}; grep it, or page through it with read_file offset/limit] ...\n\n"
|
|
)
|
|
else:
|
|
recovery = (
|
|
"... [re-run redirecting to a file (`cmd > out.log 2>&1`) and page through it "
|
|
"with read_file to see all of it] ...\n\n"
|
|
)
|
|
marker = (
|
|
f"\n\n... ({len(result) - max_chars:,} chars truncated; full output "
|
|
f"{len(result):,} chars / {total_lines:,} lines) ...\n" + recovery
|
|
)
|
|
return result[:half] + marker + result[-half:]
|
|
|
|
|
|
async def _drain(stream: asyncio.StreamReader | None, into: bytearray) -> None:
|
|
if stream is None:
|
|
return
|
|
while True:
|
|
chunk = await stream.read(65536)
|
|
if not chunk:
|
|
return
|
|
into.extend(chunk)
|
|
|
|
|
|
class CodeExecutor(DirectExecutor):
|
|
"""The host executor, draining the pipes as the command runs.
|
|
|
|
Same spawn (``sh -c``, the baseline environment allowlist, its own
|
|
session so the whole group can be killed) and the same kill on timeout;
|
|
the difference is that output already read is returned instead of
|
|
dropped, and the ceiling is the product's, not the module constant.
|
|
"""
|
|
|
|
def __init__(self, *, max_timeout: int = DEFAULT_MAX_TIMEOUT, spill_dir: Path | None = None) -> None:
|
|
super().__init__()
|
|
self._max_timeout = max_timeout
|
|
self._spill_dir = spill_dir
|
|
self._allowed_keys: frozenset[str] | None = None
|
|
|
|
async def allowed_keys(self) -> frozenset[str]:
|
|
"""The environment variables the host executor lets a child see.
|
|
|
|
Learned once, through the public ``exec`` of the parent class: the
|
|
probe is this interpreter printing the child's variable names, so what
|
|
comes back is exactly the trunk allowlist as applied on this host. A
|
|
probe that cannot run leaves exec unusable on purpose -- guessing a
|
|
list here is how credentials would start reaching commands.
|
|
"""
|
|
if self._allowed_keys is None:
|
|
probe = (
|
|
shlex.quote(sys.executable)
|
|
+ " -c 'import json,os,sys;sys.stdout.write(json.dumps(sorted(os.environ)))'"
|
|
)
|
|
result = await super().exec(probe, timeout=_PROBE_TIMEOUT)
|
|
try:
|
|
names = json.loads(result.stdout)
|
|
except ValueError as exc:
|
|
raise RuntimeError(
|
|
f"could not learn the host executor's environment baseline (exit {result.exit_code}): "
|
|
f"{result.stderr.strip() or result.stdout[:200]!r}"
|
|
) from exc
|
|
self._allowed_keys = frozenset(str(n) for n in names) - _SHELL_ADDED
|
|
return self._allowed_keys
|
|
|
|
async def _spawn_env(self, extra: dict[str, str] | None) -> dict[str, str]:
|
|
allowed = await self.allowed_keys()
|
|
env = {key: value for key, value in os.environ.items() if key in allowed}
|
|
env.update(extra or {})
|
|
return env
|
|
|
|
async def exec(
|
|
self,
|
|
command: str,
|
|
cwd: str | None = None,
|
|
timeout: int | None = None,
|
|
env: dict[str, str] | None = None,
|
|
) -> CodeExecResult:
|
|
effective = min(DEFAULT_TIMEOUT if timeout is None else timeout, self._max_timeout)
|
|
spawn_env = await self._spawn_env(env)
|
|
process = await asyncio.create_subprocess_shell(
|
|
command,
|
|
stdout=asyncio.subprocess.PIPE,
|
|
stderr=asyncio.subprocess.PIPE,
|
|
cwd=cwd,
|
|
env=spawn_env,
|
|
start_new_session=True,
|
|
)
|
|
pgid = process.pid
|
|
out, err = bytearray(), bytearray()
|
|
drains = [
|
|
asyncio.create_task(_drain(process.stdout, out)),
|
|
asyncio.create_task(_drain(process.stderr, err)),
|
|
]
|
|
timed_out = False
|
|
try:
|
|
await asyncio.wait_for(process.wait(), timeout=effective)
|
|
except asyncio.TimeoutError:
|
|
timed_out = True
|
|
self._kill_process_group(process, pgid)
|
|
try:
|
|
await asyncio.wait_for(process.wait(), timeout=5.0)
|
|
except asyncio.TimeoutError:
|
|
pass
|
|
except asyncio.CancelledError:
|
|
self._kill_process_group(process, pgid)
|
|
for task in drains:
|
|
task.cancel()
|
|
try:
|
|
await asyncio.wait_for(process.wait(), timeout=5.0)
|
|
except (asyncio.TimeoutError, asyncio.CancelledError):
|
|
pass
|
|
raise
|
|
# The pipes close when the group is gone; a grandchild that kept one open
|
|
# after the shell exited is not waited on for ever.
|
|
try:
|
|
await asyncio.wait_for(asyncio.gather(*drains, return_exceptions=True), timeout=5.0)
|
|
except asyncio.TimeoutError:
|
|
for task in drains:
|
|
task.cancel()
|
|
stderr = err.decode("utf-8", errors="replace")
|
|
if timed_out:
|
|
stderr = (stderr.rstrip("\n") + "\n" if stderr.strip() else "") + f"Timed out after {effective}s"
|
|
return CodeExecResult(
|
|
stdout=out.decode("utf-8", errors="replace"),
|
|
stderr=stderr,
|
|
exit_code=-1 if timed_out else int(process.returncode if process.returncode is not None else -1),
|
|
timed_out=timed_out,
|
|
spill_dir=self._spill_dir,
|
|
)
|
|
|
|
|
|
def _prefixed(note: str, out: str | ToolResult, *, append: bool = False) -> str | ToolResult:
|
|
"""``note`` in front of a tool's answer, whatever shape the answer took."""
|
|
text = out.model_text if isinstance(out, ToolResult) else str(out)
|
|
text = text + note if append else note + text
|
|
if isinstance(out, ToolOutput):
|
|
return ToolOutput(
|
|
text,
|
|
out.display_text,
|
|
retryable=out.retryable,
|
|
blocks_call=out.blocks_call,
|
|
continuation=out.continuation,
|
|
ok=out.ok,
|
|
blocks=out.blocks,
|
|
diff=out.diff,
|
|
file_change=out.file_change,
|
|
removed=out.removed,
|
|
written=out.written,
|
|
)
|
|
if isinstance(out, ToolResult):
|
|
return ToolResult(
|
|
model_text=text,
|
|
display_text=out.display_text,
|
|
retryable=out.retryable,
|
|
blocks_call=out.blocks_call,
|
|
continuation=out.continuation,
|
|
ok=out.ok,
|
|
blocks=out.blocks,
|
|
diff=out.diff,
|
|
file_change=out.file_change,
|
|
removed=out.removed,
|
|
written=out.written,
|
|
)
|
|
return text
|
|
|
|
|
|
class CodeExecTool(ExecTool):
|
|
"""Trunk's exec with a clamped ceiling and a 30,000-character budget."""
|
|
|
|
_MAX_OUTPUT = MAX_OUTPUT
|
|
|
|
def __init__(
|
|
self,
|
|
*args: Any,
|
|
max_timeout: int = DEFAULT_MAX_TIMEOUT,
|
|
python_diagnostics: bool = True,
|
|
python_lint: bool = True,
|
|
python_unused_imports: bool = False,
|
|
**kwargs: Any,
|
|
) -> None:
|
|
super().__init__(*args, **kwargs)
|
|
self._python_diagnostics = python_diagnostics
|
|
self._diagnostics = PythonDiagnostics(lint=python_lint, unused_imports=python_unused_imports)
|
|
# The base ``execute`` clamps against ``self._MAX_TIMEOUT``; the
|
|
# instance value replaces the class constant of 600.
|
|
self._MAX_TIMEOUT = max_timeout
|
|
# The loop's backstop above the executor's own timeout, as trunk sets it.
|
|
self.timeout_seconds = float(max_timeout + 60)
|
|
|
|
async def _diagnose_writes(self, root: Path, out: str | ToolResult) -> str:
|
|
if self._shadow is None or (shadow := self._shadow(root)) is None:
|
|
return ""
|
|
# The host's write record lists regular files under the command's
|
|
# directory and already skips symlinks; only its Python files matter.
|
|
changed = [
|
|
(item.path, None if item.created else UNKNOWN)
|
|
for item in getattr(out, "written", ())
|
|
if Path(item.path).suffix == ".py"
|
|
]
|
|
if not changed:
|
|
return ""
|
|
unchecked_visibility = 0
|
|
candidates = []
|
|
for start in range(0, len(changed), _VISIBILITY_BATCH):
|
|
# The host resolves a batch's paths on the loop, so batches bound
|
|
# each stretch and the sleep gives the outer deadline a point to
|
|
# cancel between them. Far wider than the file limit: each query
|
|
# is a git process, and batches of eight spent the wait on ignored
|
|
# files.
|
|
await asyncio.sleep(0)
|
|
batch = changed[start : start + _VISIBILITY_BATCH]
|
|
shown = await shadow.trackable([path for path, _ in batch])
|
|
candidates.extend((Path(path), old) for path, old in batch if path in shown)
|
|
if len(candidates) >= _DIAGNOSTIC_FILES:
|
|
unchecked_visibility = len(changed) - start - len(batch)
|
|
break
|
|
selected = candidates[:_DIAGNOSTIC_FILES]
|
|
limit = asyncio.Semaphore(MAX_WORKERS)
|
|
|
|
async def check(path: Path, old: Any) -> str:
|
|
async with limit:
|
|
return await self._diagnostics.check(path, before=old)
|
|
|
|
results = await asyncio.gather(*(check(path, old) for path, old in selected))
|
|
notes = []
|
|
size = 0
|
|
for note in results:
|
|
if note:
|
|
if size + len(note) > _DIAGNOSTIC_CHARS:
|
|
notes.append("\nFurther Python diagnostics omitted to keep this tool result bounded.")
|
|
break
|
|
notes.append(note)
|
|
size += len(note)
|
|
if len(candidates) > _DIAGNOSTIC_FILES:
|
|
notes.append(
|
|
f"\nPython diagnostics limited to {_DIAGNOSTIC_FILES} changed files; "
|
|
f"{len(candidates) - _DIAGNOSTIC_FILES} more were skipped."
|
|
)
|
|
if unchecked_visibility:
|
|
notes.append(
|
|
f"\n{unchecked_visibility} additional changed files were not checked after the "
|
|
f"{_DIAGNOSTIC_FILES}-file diagnostic limit; their visibility was not evaluated."
|
|
)
|
|
return "\n".join(notes)
|
|
|
|
@property
|
|
def parameters(self) -> dict[str, Any]:
|
|
schema = super().parameters
|
|
timeout = schema["properties"]["timeout"]
|
|
timeout.pop("maximum", None)
|
|
timeout["description"] = (
|
|
"Timeout in seconds for a command on THIS computer. Increase for long-running work "
|
|
f"such as a build or a test suite (default {self.timeout}, ceiling {self._MAX_TIMEOUT}; a "
|
|
"larger value is clamped to the ceiling, not rejected). A command that hits its limit is "
|
|
"killed and the output it produced so far comes back marked partial. Not read with "
|
|
"'machine' or 'run_in_background'."
|
|
)
|
|
return schema
|
|
|
|
async def execute(
|
|
self,
|
|
command: str,
|
|
working_dir: str | None = None,
|
|
timeout: int | None = None,
|
|
machine: str = "",
|
|
run_in_background: bool = False,
|
|
**kwargs: Any,
|
|
) -> str | ToolResult:
|
|
note = ""
|
|
inspect_writes = (
|
|
self._python_diagnostics and not machine and not run_in_background and not self._executor.is_sandboxed
|
|
)
|
|
if timeout is not None and not machine and not run_in_background and timeout > self._MAX_TIMEOUT:
|
|
note = (
|
|
f"[note: timeout {timeout}s clamped to the {self._MAX_TIMEOUT}s ceiling; for longer "
|
|
"work use run_in_background: true]\n"
|
|
)
|
|
timeout = self._MAX_TIMEOUT
|
|
out = await super().execute(
|
|
command,
|
|
working_dir=working_dir,
|
|
timeout=timeout,
|
|
machine=machine,
|
|
run_in_background=run_in_background,
|
|
**kwargs,
|
|
)
|
|
if inspect_writes and isinstance(out, (ToolOutput, ToolResult)) and not out.blocks_call:
|
|
root = Path(self._cwd_for(working_dir))
|
|
try:
|
|
diagnostics = await asyncio.wait_for(self._diagnose_writes(root, out), timeout=_DIAGNOSTIC_WAIT_SECONDS)
|
|
except Exception as exc: # noqa: BLE001 - never replace a completed command's output with a checker error
|
|
logger.debug("code-flow: post-exec diagnostics unavailable: {}", exc)
|
|
else:
|
|
if diagnostics:
|
|
out = _prefixed(diagnostics, out, append=True)
|
|
return _prefixed(note, out) if note else out
|
|
|
|
|
|
__all__ = [
|
|
"DEFAULT_MAX_TIMEOUT",
|
|
"DEFAULT_TIMEOUT",
|
|
"MAX_OUTPUT",
|
|
"SPILL_SUBDIR",
|
|
"TIMED_OUT_NOTE",
|
|
"CodeExecResult",
|
|
"CodeExecTool",
|
|
"CodeExecutor",
|
|
"spill_output",
|
|
]
|