## 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>
422 lines
19 KiB
Python
422 lines
19 KiB
Python
"""The fork's file-tool face over trunk's file tools.
|
|
|
|
Each class here subclasses the trunk tool it replaces and changes three things:
|
|
the model-facing schema (the fork's parameter spelling and its conduct-bearing
|
|
descriptions), the accepted spellings (``cast_params`` maps the host's
|
|
``path`` / ``old_text`` / ``new_text`` onto the fork's names, so a call in
|
|
either convention runs), and two pieces of conduct the fork measured its way
|
|
to -- a read ledger that refuses to edit content unseen by the current session, and
|
|
post-write Python diagnostics in the same tool result.
|
|
|
|
Everything else (path resolution against the bound working directory, the
|
|
unified diff the UI renders, ``FileChange`` on the result, image reads) is
|
|
trunk's, inherited unchanged.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from code_flow.tools.diagnostics import UNKNOWN, PythonDiagnostics, read_before
|
|
from code_flow.tools.read_state import Owner, ReadLedger, current_ledger
|
|
from raven.agent.tools import filesystem as trunk
|
|
from raven.contracts.tool import FileChange, ToolResult
|
|
|
|
|
|
def _append_note(result: str | ToolResult, note: str) -> str | ToolResult:
|
|
if not note:
|
|
return result
|
|
if isinstance(result, ToolResult):
|
|
result.model_text = f"{result.model_text}{note}"
|
|
return result
|
|
return f"{result}{note}"
|
|
|
|
|
|
class _Aliased:
|
|
"""``cast_params`` that maps the host's spelling onto the fork's.
|
|
|
|
Runs before schema validation, so a call spelled either way validates
|
|
against the fork schema and reaches ``execute`` under one name. When a
|
|
call carries both spellings the fork's wins and the legacy key is dropped.
|
|
"""
|
|
|
|
ALIASES: dict[str, str] = {}
|
|
|
|
def __init__(
|
|
self, *args: Any, ledger: ReadLedger | None = None, read_owner: Owner | None = None, **kwargs: Any
|
|
) -> None:
|
|
super().__init__(*args, **kwargs)
|
|
self._explicit_ledger = ledger
|
|
self._read_owner = read_owner
|
|
|
|
@property
|
|
def _ledger(self) -> ReadLedger | None:
|
|
return self._explicit_ledger if self._explicit_ledger is not None else current_ledger(self._read_owner)
|
|
|
|
def cast_params(self, params: dict[str, Any]) -> dict[str, Any]:
|
|
out = dict(params)
|
|
for legacy, canonical in self.ALIASES.items():
|
|
if legacy not in out:
|
|
continue
|
|
value = out.pop(legacy)
|
|
out.setdefault(canonical, value)
|
|
return out
|
|
|
|
|
|
class ReadFileTool(_Aliased, trunk.ReadFileTool):
|
|
ALIASES = {"path": "file_path"}
|
|
|
|
#: One line may spend this many characters before it is cut, the fork's
|
|
#: budget. Cut on trunk's own hook, before the page's budget counts the
|
|
#: line, so a page of minified lines holds its lines rather than one
|
|
#: line's head; the mark makes the description's promise true.
|
|
_MAX_LINE_CHARS = 2_000
|
|
|
|
@property
|
|
def description(self) -> str:
|
|
return (
|
|
"Read the contents of a file. Returns numbered lines formatted as "
|
|
"'12| text' -- the 'N| ' prefix is added by this tool and is NOT part "
|
|
"of the file. Use offset and limit to paginate through large files. "
|
|
f"Lines longer than {self._MAX_LINE_CHARS} chars are truncated with an "
|
|
"explicit marker; use grep to search inside such files. "
|
|
"Do not assume a path exists: locate it with glob or list_dir instead of guessing, "
|
|
"and if a read fails, find the real path rather than retrying a guess."
|
|
)
|
|
|
|
@property
|
|
def parameters(self) -> dict[str, Any]:
|
|
base = super().parameters
|
|
props = dict(base["properties"])
|
|
props = {"file_path": {"type": "string", "description": "The file path to read"}, **props}
|
|
props.pop("path", None)
|
|
return {"type": "object", "properties": props, "required": ["file_path"]}
|
|
|
|
async def execute(self, file_path: str = "", offset: int = 1, limit: int | None = None, **kwargs: Any): # type: ignore[override]
|
|
if not file_path:
|
|
return "Error: missing required parameter 'file_path'."
|
|
result = await super().execute(path=file_path, offset=offset, limit=limit, **kwargs)
|
|
if _failed(result):
|
|
return result
|
|
# Recorded only now, and only for a file that answers a stat: a read
|
|
# that failed must not license an edit of content nobody has seen.
|
|
try:
|
|
fp = self._resolve(file_path)
|
|
except Exception: # noqa: BLE001 - the read itself reported the path problem
|
|
fp = None
|
|
if fp is not None and (ledger := self._ledger) is not None:
|
|
ledger.note(fp)
|
|
if trunk._machine_of(file_path) is not None:
|
|
# Answered by a registered machine's node, which runs trunk's tool
|
|
# without this fork's hook: cut after the read. Decided by where
|
|
# the read ran, never by a line's text -- a line whose own text
|
|
# ends like the mark was taken for a cut one and came back whole.
|
|
return _cut_long_lines(result, self._MAX_LINE_CHARS)
|
|
# Read here: every line was cut on the hook before the page's budget counted it.
|
|
return result
|
|
|
|
def _cut_line(self, line: str) -> str:
|
|
"""Trunk's hook: the line cut to the fork's budget before it is numbered and the page's budget counts it."""
|
|
return _cut(line, self._MAX_LINE_CHARS)
|
|
|
|
|
|
class WriteFileTool(_Aliased, trunk.WriteFileTool):
|
|
ALIASES = {"path": "file_path"}
|
|
|
|
def __init__(
|
|
self, *args: Any, syntax_note: bool = True, lint: bool = True, unused_imports: bool = False, **kwargs: Any
|
|
) -> None:
|
|
super().__init__(*args, **kwargs)
|
|
self._syntax_note = syntax_note
|
|
self._diagnostics = PythonDiagnostics(lint=lint, unused_imports=unused_imports)
|
|
|
|
@property
|
|
def description(self) -> str:
|
|
return (
|
|
"Write content to a file at the given path. Creates parent directories if needed. "
|
|
"ALWAYS prefer editing existing files in the codebase: before creating a new file, "
|
|
"check whether an existing file (an entry point, a stub, a TODO) already owns that "
|
|
"responsibility, and NEVER write new files unless the task requires it. "
|
|
"If the target file already exists, read it with read_file before overwriting. "
|
|
"mode='overwrite' replaces the entire file; mode='append' adds content at the end. "
|
|
"Appending to an existing file does not count as reading its previous content. "
|
|
"After replacing a symbol that is used elsewhere, check its other call "
|
|
"sites, overrides, and sibling branches for the same required change."
|
|
)
|
|
|
|
@property
|
|
def parameters(self) -> dict[str, Any]:
|
|
base = super().parameters
|
|
props = dict(base["properties"])
|
|
props = {"file_path": {"type": "string", "description": "The file path to write to"}, **props}
|
|
props.pop("path", None)
|
|
return {"type": "object", "properties": props, "required": ["file_path", "content"]}
|
|
|
|
async def execute(self, file_path: str = "", content: str | None = None, mode: str = "overwrite", **kwargs: Any): # type: ignore[override]
|
|
if not file_path or content is None:
|
|
return "Error: missing required parameter(s): write_file needs file_path and content."
|
|
try:
|
|
fp = self._resolve(file_path)
|
|
except (OSError, ValueError) as exc:
|
|
return f"Error: {exc}"
|
|
ledger = self._ledger
|
|
previous = await read_before(fp) if self._syntax_note and fp.suffix == ".py" and mode == "append" else UNKNOWN
|
|
known = ledger is not None and ledger.status(fp) == ReadLedger.OK
|
|
authored = mode == "overwrite" or not fp.exists()
|
|
result = await super().execute(path=file_path, content=content, mode=mode, **kwargs)
|
|
if _failed(result):
|
|
return result
|
|
try:
|
|
fp = self._resolve(file_path)
|
|
except Exception: # noqa: BLE001 - the write itself reported the path problem
|
|
return result
|
|
# Only a full write or a previously current record covers the old
|
|
# content. Appending an unseen tail must not license editing the head.
|
|
if ledger is not None:
|
|
if authored or known:
|
|
ledger.note(fp)
|
|
else:
|
|
ledger.forget(fp)
|
|
if not self._syntax_note:
|
|
return result
|
|
if isinstance(result, ToolResult) and result.file_change is not None:
|
|
previous = result.file_change.before
|
|
elif mode != "append" and isinstance(result, ToolResult) and result.model_text.startswith("File unchanged:"):
|
|
# Nothing was written, so the content is its own baseline: name
|
|
# findings are not repeated, a syntax error still present is.
|
|
previous = content
|
|
note = await self._diagnostics.check(fp, text=None if mode == "append" else content, before=previous)
|
|
return _append_note(result, note)
|
|
|
|
|
|
def _respell(result: str | ToolResult) -> str | ToolResult:
|
|
"""Trunk's messages name its own parameters; the model was shown the fork's.
|
|
|
|
Only the first line is respelled. Trunk's own messages put their sentence
|
|
there and any quoted file content on the lines after it (the not-found
|
|
report prints the closest matching excerpt), and a blanket replacement
|
|
rewrote the FILE's text: a file that really contains ``old_text`` was
|
|
shown to the model as containing ``old_string``, so the model copied an
|
|
excerpt that never matched anything.
|
|
"""
|
|
swaps = (("old_text", "old_string"), ("new_text", "new_string"))
|
|
|
|
def respelled(text: str) -> str:
|
|
head, sep, tail = text.partition("\n")
|
|
for legacy, spelled in swaps:
|
|
head = head.replace(legacy, spelled)
|
|
return head + sep + tail
|
|
|
|
if isinstance(result, ToolResult):
|
|
result.model_text = respelled(result.model_text)
|
|
return result
|
|
return respelled(str(result))
|
|
|
|
|
|
def _cut(line: str, budget: int) -> str:
|
|
"""``line`` cut to ``budget`` characters and marked, or as it is when it fits."""
|
|
if len(line) <= budget:
|
|
return line
|
|
return line[:budget] + f"... (line truncated to {budget} chars)"
|
|
|
|
|
|
def _cut_long_lines(result: str | ToolResult, budget: int) -> str | ToolResult:
|
|
"""Cut any line of a result past ``budget`` characters, marking the cut: a page cut nowhere else."""
|
|
|
|
def cut(text: str) -> str:
|
|
if not any(len(line) > budget for line in text.split("\n")):
|
|
return text
|
|
return "\n".join(_cut(line, budget) for line in text.split("\n"))
|
|
|
|
if isinstance(result, ToolResult):
|
|
result.model_text = cut(result.model_text)
|
|
return result
|
|
return cut(str(result))
|
|
|
|
|
|
def _failed(result: str | ToolResult) -> bool:
|
|
text = result.model_text if isinstance(result, ToolResult) else str(result)
|
|
return text.lstrip().startswith("Error")
|
|
|
|
|
|
class EditFileTool(_Aliased, trunk.EditFileTool):
|
|
ALIASES = {"path": "file_path", "old_text": "old_string", "new_text": "new_string"}
|
|
|
|
def __init__(
|
|
self,
|
|
*args: Any,
|
|
syntax_note: bool = True,
|
|
lint: bool = True,
|
|
unused_imports: bool = False,
|
|
require_read: bool = True,
|
|
**kwargs: Any,
|
|
) -> None:
|
|
super().__init__(*args, **kwargs)
|
|
self._syntax_note = syntax_note
|
|
self._diagnostics = PythonDiagnostics(lint=lint, unused_imports=unused_imports)
|
|
self._require_read = require_read
|
|
|
|
@property
|
|
def description(self) -> str:
|
|
prerequisite = (
|
|
"You must first read the file with read_file or write its complete content with write_file "
|
|
"in this session of this Raven-Code instance. Unread or externally changed files are rejected. "
|
|
"Appending to unseen existing content does not satisfy this check. "
|
|
if self._require_read
|
|
else "Read the file before editing so the replacement matches its current content. "
|
|
)
|
|
return (
|
|
"Edit a file by replacing old_string with new_string. "
|
|
+ prerequisite
|
|
+ "old_string must be the file's actual content -- never include the "
|
|
"'N| ' line-number prefix that read_file output adds. "
|
|
"Without occurrence, supports minor whitespace/line-ending differences. "
|
|
"If old_string matches several places, either set replace_all=true to "
|
|
"change every one, or occurrence=<n> to change only the nth non-overlapping exact match "
|
|
"(1-based, in file order, with CRLF normalized to LF). These options cannot be combined. "
|
|
"After changing a symbol that is used elsewhere, check its other call "
|
|
"sites, overrides, and sibling branches for the same required change."
|
|
)
|
|
|
|
@property
|
|
def parameters(self) -> dict[str, Any]:
|
|
base = super().parameters
|
|
props = dict(base["properties"])
|
|
for legacy in ("path", "old_text", "new_text"):
|
|
props.pop(legacy, None)
|
|
props = {
|
|
"file_path": {"type": "string", "description": "The file path to edit"},
|
|
"old_string": {"type": "string", "description": "The text to find and replace"},
|
|
"new_string": {"type": "string", "description": "The text to replace with"},
|
|
**props,
|
|
"occurrence": {
|
|
"type": "integer",
|
|
"description": (
|
|
"Replace only the Nth non-overlapping exact match (1-based, in file order, "
|
|
"with CRLF normalized to LF). Cannot be combined with replace_all."
|
|
),
|
|
"minimum": 1,
|
|
},
|
|
}
|
|
return {"type": "object", "properties": props, "required": ["file_path", "old_string", "new_string"]}
|
|
|
|
async def execute( # type: ignore[override]
|
|
self,
|
|
file_path: str = "",
|
|
old_string: str | None = None,
|
|
new_string: str | None = None,
|
|
replace_all: bool = False,
|
|
occurrence: int | None = None,
|
|
**kwargs: Any,
|
|
):
|
|
if not file_path or old_string is None or new_string is None:
|
|
return "Error: missing required parameter(s): edit_file needs file_path, old_string and new_string."
|
|
if replace_all and occurrence is not None:
|
|
return "Error: replace_all and occurrence are mutually exclusive; pass one or the other."
|
|
if not old_string:
|
|
return "Error: old_string is empty. To create or overwrite a file use write_file instead."
|
|
try:
|
|
fp = self._resolve(file_path)
|
|
except Exception as exc: # noqa: BLE001 - the same wording trunk's tool gives
|
|
return f"Error: {exc}"
|
|
if not fp.exists():
|
|
return f"Error: File not found: {file_path}. To create a new file use write_file instead."
|
|
ledger = self._ledger
|
|
if self._require_read:
|
|
if ledger is None:
|
|
return "Error: edit_file has no active Raven-Code session. Bind the session before editing."
|
|
seen = ledger.status(fp)
|
|
if seen == ReadLedger.UNREAD:
|
|
return (
|
|
f"Error: you have not read {file_path} in this session -- editing unread content "
|
|
"is rejected. Read the file with read_file first, then edit the text you actually saw."
|
|
)
|
|
if seen == ReadLedger.STALE:
|
|
return (
|
|
f"Error: {file_path} changed since you last read it, so the text you are editing "
|
|
"may no longer be there. Read it again, then edit the content you actually saw."
|
|
)
|
|
if occurrence is not None and occurrence < 1:
|
|
return "Error: occurrence must be 1 or greater (it counts matches in file order)."
|
|
if occurrence is not None:
|
|
result = self._edit_occurrence(fp, file_path, old_string, new_string, occurrence)
|
|
else:
|
|
result = _respell(
|
|
await super().execute(
|
|
path=file_path, old_text=old_string, new_text=new_string, replace_all=replace_all, **kwargs
|
|
)
|
|
)
|
|
if not isinstance(result, ToolResult) or result.file_change is None:
|
|
return result
|
|
# The edit is the newest thing anyone has seen of this file, so the
|
|
# ledger follows it -- otherwise the tool's own write would read back
|
|
# as someone else's change and the next edit would be refused as stale.
|
|
if ledger is not None:
|
|
ledger.note(fp)
|
|
if not self._syntax_note:
|
|
return result
|
|
note = await self._diagnostics.check(fp, text=result.file_change.after, before=result.file_change.before)
|
|
return _append_note(result, note)
|
|
|
|
@staticmethod
|
|
def _edit_occurrence(fp: Path, shown: str, old: str, new: str, occurrence: int) -> str | ToolResult:
|
|
"""Replace exactly the Nth exact match; trunk's fuzzy matching stays
|
|
with the default path, since 'the Nth of several' needs one unambiguous
|
|
counting rule."""
|
|
try:
|
|
raw = fp.read_bytes()
|
|
uses_crlf = b"\r\n" in raw
|
|
content = raw.decode("utf-8").replace("\r\n", "\n")
|
|
except UnicodeDecodeError:
|
|
return f"Error: {shown} is not a UTF-8 text file; edit_file cannot edit it."
|
|
except OSError as exc:
|
|
return f"Error: {exc}"
|
|
old = old.replace("\r\n", "\n")
|
|
new = new.replace("\r\n", "\n")
|
|
count = content.count(old)
|
|
if count == 0:
|
|
return f"Error: old_string not found in {shown}. Verify the file content with read_file."
|
|
if occurrence > count:
|
|
return (
|
|
f"Error: occurrence={occurrence} but old_string matches only {count} "
|
|
f"place(s) in {shown}. Use read_file to see the current content."
|
|
)
|
|
start = 0
|
|
for _ in range(occurrence):
|
|
index = content.find(old, start)
|
|
start = index + len(old)
|
|
after = content[:index] + new + content[index + len(old) :]
|
|
# Written back in the file's own line ending, the way trunk's edit
|
|
# path does it: reading through ``read_text`` and writing back through
|
|
# ``write_text`` rewrote every line of a CRLF file, so a one-line edit
|
|
# arrived as a whole-file diff.
|
|
fp.write_bytes((after.replace("\n", "\r\n") if uses_crlf else after).encode("utf-8"))
|
|
line = content.count("\n", 0, index) + 1
|
|
return ToolResult(
|
|
model_text=f"Successfully edited {fp} (occurrence {occurrence} of {count}, line {line}).",
|
|
diff=trunk._unified(content, after, str(fp)),
|
|
file_change=FileChange(path=str(fp), after=after, before=content),
|
|
)
|
|
|
|
|
|
class ListDirTool(trunk.ListDirTool):
|
|
@property
|
|
def description(self) -> str:
|
|
return (
|
|
"List the contents of a directory. "
|
|
"For a first look at a repository, use recursive=true -- a flat listing "
|
|
"hides everything inside subdirectories. "
|
|
"Do not assume a directory exists; list its parent first when unsure. "
|
|
"Common noise directories (.git, node_modules, __pycache__, etc.) are auto-ignored."
|
|
)
|
|
|
|
|
|
__all__ = [
|
|
"EditFileTool",
|
|
"ListDirTool",
|
|
"ReadFileTool",
|
|
"ReadLedger",
|
|
"WriteFileTool",
|
|
]
|