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

312 lines
13 KiB
Python

"""Bounded Python diagnostics attached to the edit that made them observable."""
from __future__ import annotations
import ast
import importlib.util
import io
import re
import sys
import tokenize
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
from code_flow.tools.diagnostic_workers import WORKERS
# The name checks' one import, paid at plugin load rather than by whichever
# check first needs it: a cold import inside a check's wait was measured at
# 30-70 ms here and can outlast the wait on a cold Windows runner. Absent,
# the import below fails as it did before, and a check reports it.
try:
import pyflakes.checker # noqa: F401
except ImportError:
pass
MAX_SOURCE_BYTES = 256 * 1024
# The syntax check runs past the name checks' bound up to this one. Python's
# syntax tree of 2 MiB of source took about 0.3 s and 190 MiB to build, and of
# 16 MiB 7 s and 1.4 GiB, on a worker nothing can interrupt once it starts.
MAX_SYNTAX_BYTES = 2 * 1024 * 1024
MAX_FINDINGS = 8
CHECK_WAIT_SECONDS = 1.0
UNKNOWN = object()
# A marker counts the way Ruff reads one: an optional lowercase ``ruff:`` or
# ``flake8:`` prefix for the file-level form, ``noqa`` in any case, then either
# a colon and codes or, with no colon, whitespace, another comment or the
# comment's end. Anything else (a URL fragment, a quoted mention, a colon
# without codes) is text. Unlike Ruff, which takes the first directive in a
# comment, every directive in it counts.
_NOQA = re.compile(
r"#\s*(?:(ruff|flake8)\s*:\s*)?(?i:noqa)"
r"(?:\s*:\s*([A-Z]+[0-9]+(?:[\s,]+[A-Z]+[0-9]+)*)|(?!\s*:)(?=[\s#]|$))"
)
@dataclass(frozen=True)
class Finding:
code: str
line: int
column: int
message: str
source: str
@property
def key(self) -> tuple[str, str, str]:
return self.code, self.message, self.source.strip()
def read_source(path: Path) -> bytes:
"""A changed file's bytes for a check, at most one past the syntax bound.
A failed read raises: a baseline that cannot be read is unknown, but the
content being checked has no verdict without its bytes.
"""
if not path.is_file():
raise FileNotFoundError(f"no regular file at {path}")
with path.open("rb") as handle:
return handle.read(MAX_SYNTAX_BYTES + 1)
def _stored(content: str | bytes, limit: int) -> str | bytes:
"""``content`` as the bytes the file tool stores it as: text in UTF-8.
Text longer than ``limit`` in characters is longer in bytes too, so it is
left unencoded, still over the limit by length.
"""
return content.encode("utf-8") if isinstance(content, str) and len(content) <= limit else content
def _refused(raw: bytes, exc: SyntaxError | UnicodeDecodeError) -> Finding:
"""Source Python refuses to decode, placed at the first byte it cannot.
Python's parser places a declared encoding's failure at line 0, and 3.12's
passes undecodable bytes inside a comment, so the place is found here: the
first byte that does not decode, or else the line of the first two that
``tokenize.detect_encoding`` rejects.
"""
if isinstance(exc, UnicodeDecodeError):
# The codec's own buffer: a BOM's codec decodes only what follows the mark.
raw, at, encoding, message = exc.object, exc.start, exc.encoding, str(exc)
else:
first = raw.split(b"\n", 1)[0]
try:
tokenize.detect_encoding(io.BytesIO(first).readline)
except SyntaxError:
at = 0
else:
at = len(first) + 1
encoding, message = "utf-8", exc.msg
start = raw.rfind(b"\n", 0, at) + 1
end = raw.find(b"\n", at)
line = raw[start : end if end >= 0 else len(raw)].decode(encoding, "replace")
return Finding("syntax", raw.count(b"\n", 0, at) + 1, at - start + 1, message, line)
def read_python(path: Path) -> bytes | None | object:
"""Read bounded source bytes; distinguish an absent file from an unavailable baseline.
Bytes, decoded by ``findings`` the way Python decodes a source file: text
decoded here would pick an encoding of its own and hide the file's coding
declaration from the comparison.
"""
try:
if not path.exists():
return None
if not path.is_file() or path.stat().st_size > MAX_SOURCE_BYTES:
return UNKNOWN
with path.open("rb") as handle:
raw = handle.read(MAX_SOURCE_BYTES + 1)
return raw if len(raw) <= MAX_SOURCE_BYTES else UNKNOWN
except OSError:
return UNKNOWN
async def read_before(path: Path) -> bytes | None | object:
try:
return await WORKERS.run(lambda: read_python(path), timeout=CHECK_WAIT_SECONDS)
except Exception: # noqa: BLE001 - an unavailable baseline must not block a write
return UNKNOWN
def _ignores(text: str) -> dict[int, set[str] | None]:
ignored: dict[int, set[str] | None] = {}
for token in tokenize.generate_tokens(io.StringIO(text).readline):
if token.type != tokenize.COMMENT:
continue
# Ruff honors a file-level directive only on a line of its own and
# ignores one that trails code, which suppresses nothing.
own_line = not token.line[: token.start[1]].strip()
for match in _NOQA.finditer(token.string):
if match[1] and not own_line:
continue
row = 0 if match[1] else token.start[0]
codes = set(re.findall(r"[A-Z]+\d+", match[2].upper())) if match[2] else None
if row not in ignored:
ignored[row] = codes
elif ignored[row] is not None:
ignored[row] = None if codes is None else ignored[row] | codes
return ignored
class PythonDiagnostics:
"""Report actionable name errors; optional import notices never rewrite code."""
def __init__(self, *, lint: bool = True, unused_imports: bool = False) -> None:
self.lint = lint
self.unused_imports = unused_imports
def findings(self, path: Path, content: str | bytes, *, syntax_only: bool = False) -> list[Finding]:
"""Syntax findings, then the name findings unless ``syntax_only``.
Bytes are decoded as Python reads a source file, by its coding
declaration or else as UTF-8; bytes that do not decode are the syntax
error Python reports for them.
"""
if isinstance(content, str):
text = content
else:
try:
text = importlib.util.decode_source(content)
except (SyntaxError, UnicodeDecodeError) as exc:
return [_refused(content, exc)]
lines = text.splitlines()
try:
tree = ast.parse(text, filename=str(path))
except SyntaxError as exc:
row = exc.lineno or 1
source = lines[row - 1] if 0 < row <= len(lines) else ""
return [Finding("syntax", row, exc.offset or 1, exc.msg, source)]
except ValueError:
return []
if syntax_only or not self.lint:
return []
from pyflakes.checker import Checker
codes = {"UndefinedName": "F821", "UndefinedExport": "F822", "UndefinedLocal": "F823"}
if self.unused_imports:
codes["UnusedImport"] = "F401"
ignored = _ignores(text)
findings = []
for message in Checker(tree, filename=str(path)).messages:
code = codes.get(type(message).__name__)
if code is None:
continue
row = message.lineno
if any(key in ignored and (ignored[key] is None or code in ignored[key]) for key in (0, row)):
continue
source = lines[row - 1] if 0 < row <= len(lines) else ""
findings.append(Finding(code, row, message.col + 1, message.message % message.message_args, source))
return sorted(findings, key=lambda item: (item.line, item.column, item.code))
def note(self, path: Path, content: str | bytes, *, before: str | bytes | None | object = UNKNOWN) -> str:
try:
if path.suffix != ".py":
return ""
# Text is what the file tool writes, UTF-8, so it is checked as those
# bytes: Python reads the stored file, not the string in hand, and a
# coding declaration in the text applies to it. The content replaced
# is compared the same way, or one line would read two ways.
stored = _stored(content, MAX_SYNTAX_BYTES)
if len(stored) > MAX_SYNTAX_BYTES:
return (
f"\nPython diagnostics skipped for {path}: the source is over "
f"{MAX_SYNTAX_BYTES // 1024 // 1024} MiB. Run targeted project checks."
)
syntax_only = len(stored) > MAX_SOURCE_BYTES
findings = self.findings(path, stored, syntax_only=syntax_only)
replaced = _stored(before, MAX_SOURCE_BYTES) if isinstance(before, (str, bytes)) else before
if replaced is None:
baseline = Counter()
elif isinstance(replaced, bytes) and len(replaced) <= MAX_SOURCE_BYTES:
# Source nested too deeply for the parser or checker raises
# rather than parsing to nothing: unavailable for the content
# written, an unknown baseline for the content replaced.
try:
earlier = self.findings(path, replaced)
except Exception: # noqa: BLE001 - an unanalyzable baseline is unknown, not clean
earlier = None
baseline = (
None
if earlier is None or any(item.code == "syntax" for item in earlier)
else Counter(item.key for item in earlier)
)
else:
baseline = None
except Exception as exc: # noqa: BLE001 - diagnostics must not change an already completed write's verdict
return (
f"\nPython diagnostics unavailable ({type(exc).__name__}) for {path}; the file was kept. "
"Run targeted project checks."
)
if baseline is not None:
fresh = []
for finding in findings:
if baseline[finding.key]:
baseline[finding.key] -= 1
else:
fresh.append(finding)
findings = fresh
if not findings:
if syntax_only and self.lint:
return (
f"\nPython name checks skipped for {path}: the source is over "
f"{MAX_SOURCE_BYTES // 1024} KiB, so only its syntax was checked."
)
return ""
scope = (
"new findings compared with the content before this call"
if baseline is not None
else "current findings; the baseline is unknown or could not be parsed, so these may predate this call"
)
rows = [f"\nPython diagnostics for {path} ({scope}; the file was kept):"]
for finding in findings[:MAX_FINDINGS]:
label = "Python syntax error" if finding.code == "syntax" else finding.code
severity = "NOTICE" if finding.code == "F401" else "WARNING"
rows.append(f"{severity}: line {finding.line}, column {finding.column}: {label}: {finding.message[:240]}")
if finding.source:
rows.append(f" {finding.source.strip()[:160]}")
if len(findings) > MAX_FINDINGS:
rows.append(f"{len(findings) - MAX_FINDINGS} more findings omitted; inspect this file directly.")
if any(item.code == "syntax" for item in findings):
rows.append(
f"Parsed with Python {sys.version_info.major}.{sys.version_info.minor}; "
"check the project's Python version before changing newer syntax. "
"Fix confirmed syntax/indentation errors before relying on execution results."
)
if any(item.code in {"F821", "F822", "F823"} for item in findings):
rows.append(
"Check the named symbol's spelling, scope, import, or assignment order. "
"Confirm the intended binding; do not add dummy values just to silence this warning."
)
if any(item.code == "F401" for item in findings):
rows.append(
"An unused import can be a public re-export or have side effects; inspect its role before removing it."
)
return "\n".join(rows)
async def check(self, path: Path, *, text: str | None = None, before: str | None | object = UNKNOWN) -> str:
if path.suffix != ".py":
return ""
def inspect() -> str:
return self.note(path, read_source(path) if text is None else text, before=before)
try:
return await WORKERS.run(inspect, timeout=CHECK_WAIT_SECONDS)
except Exception as exc: # noqa: BLE001 - keep the completed operation's result on checker failure
return (
f"\nPython diagnostics unavailable ({type(exc).__name__}) for {path}; the file was kept. "
"Run targeted project checks."
)
__all__ = [
"MAX_SOURCE_BYTES",
"MAX_SYNTAX_BYTES",
"UNKNOWN",
"PythonDiagnostics",
"read_before",
"read_python",
"read_source",
]