Skip to content

fix(tools): read UTF-16 text as text and show search hits on long lines - #4686

Merged
kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:kalin/file-tools-utf16-longline
Oct 4, 2026
Merged

kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:kalin/file-tools-utf16-longline

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

On Windows, a text file saved as UTF-16 (PowerShell 5.1 > and some Notepad saves do this) came back from read_file as [Binary file, 110 bytes], and searches never matched inside it. The agent then fell back to run_python, so the user had to approve a "DESTRUCTIVE" code prompt just to read a text file. Separately, a search hit deep in a long line (minified JS, single-line JSON or CSV, log lines) came back as the line's first 200 characters, so the model never saw the match. One search_code hit on a 5 MB line also returned the entire 5 MB line.

Now file reads and searches detect UTF-16, UTF-32 and UTF-8 byte-order marks and decode the text. Genuinely binary files are still reported as binary. A long matching line comes back as a 200-character window centred on the match, with ... where it was cut.

Test plan

  • python -m pytest tests/unit/agents/test_file_tools_text_encoding.py: 45 pass. With only the src/ changes reverted, 34 of them fail; the 11 that still pass are the binary and plain UTF-8 guards and the pure excerpt-helper tests.
  • python -m pytest tests/unit/agents/test_read_file_line_ranges.py tests/unit/agents/test_chunk_index.py tests/unit/test_file_tools.py tests/unit/agents/test_read_before_edit.py tests/unit/agents/test_file_edit_semantics.py tests/unit/test_tool_tilde_expansion.py: all 462 pass.
  • python -m pytest tests/unit/ -k "file or search or read": no new failures. The 20 failures there also happen on main (profilespec goldens, diarize/speech, email sidecar, shell guardrails, and an order-dependent tool-label test polluted by other suites).
  • python util/lint.py --black --isort --pylint: black and isort pass. The only pylint errors are the existing POSIX-only os.getuid / signal.SIGKILL hits on Windows, in files this PR doesn't touch.
  • Reviewer: in the TUI, ask the flagship to read a file written with Set-Content -Encoding Unicode in PowerShell 5.1 and confirm it reads it without a run_python approval.
🔍 Technical details
  • The shared helper is gaia/agents/tools/text_files.py (text_encoding, read_text, match_excerpt). It's used by both read_file mixins (full read, offset/limit paging, start_line ranges), search_file_content, search_code and get_file_info. get_file_info's latin-1 fallback used to accept UTF-16 bytes and return a ÿþL\x00e\x00… preview.
  • A file starting with a UTF-16/32 BOM that decodes to a NUL is still reported as binary.
  • When the file has a BOM, read_file includes "encoding" in its result. Plain UTF-8 results are unchanged.
  • search_file_content used to open every file twice when context_lines=0 and leaked the inner handle. It now opens each file once.
  • I left read_file on a 5 MB single-line file alone because the result isn't silent. The agent already condenses it with truncated: true, original_chars, an archived artifact and a paged read_tool_output continuation.
  • Out of scope: edit_file on a UTF-16 file still fails with a UTF-8 decode error and leaves the file unchanged, same as on main. Making writes keep the original encoding is a separate change.
  • This touches the same files as fix(tools): every file tool checks the allowed-folders rule #4656, so whichever merges second may need a small rebase.

A UTF-16 file (what PowerShell 5.1 `>` writes) came back from read_file as
"[Binary file, N bytes]" and never matched in search, so the agent fell back
to run_python and a DESTRUCTIVE approval prompt just to read a text file.
Both read_file mixins, search_file_content, search_code and get_file_info now
decode by byte-order mark; a BOM-marked file that decodes to NULs is still
reported binary.

A search hit deep in a long line (minified JS, single-line JSON, logs) came
back as the line's first 200 chars, without the match. search_file_content
now returns a 200-char window centred on the match, and search_code, which
returned whole lines unbounded (5 MB for one hit), is bounded the same way.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Oct 4, 2026
@github-actions

github-actions Bot commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Windows text files saved as UTF-16 (PowerShell 5.1 >, some Notepad saves) used to read as "binary", so the agent asked for a risky run_python approval just to open a text file. They now read and search as text. Search hits deep inside a long line now come back as a window around the match, where before you got the line's first 200 characters. The change is well-scoped, shares one helper across both file-tool mixins, keeps genuinely binary files reported as binary, and has focused tests that fail without the fix. One small edge case is below; it doesn't block merge.

  • Small edge case: a case-insensitive search whose pattern isn't valid regex (e.g. foo() can show a snippet that misses the match. This only happens on a long line where characters before the match get longer when lowercased (e.g. Turkish İ). Very rare, and the hit is still reported. It just isn't visible in the snippet.

Real-world evidence

N/A: no evidence bundle was produced for this run. The change is inside agent file tools with no new CLI/API/UI surface. The verdict rests on static review plus the author's reported unit-test runs. I could not re-run pytest here because it isn't installed on this runner. The PR's one manual check is still unticked: reading a Set-Content -Encoding Unicode file in the TUI without a run_python prompt. Please do it before merge, since that is the user-visible path.

🔍 Technical details

Issues

🟢 Case-insensitive excerpt offsets can drift on the plain-substring fallback (src/gaia/agents/tools/file_tools.py, _match_span): when pattern isn't valid regex, the span comes from line.lower().find(...), but match_excerpt slices the original line. str.lower() can change length ("İ".lower() is 2 chars). I reproduced it: a 906-char line with 300 İ gives a lowered offset of 900, and the excerpt doesn't contain NEEDLE. There's no crash because match_excerpt clamps. A simple fix is to fall back to an escaped regex rather than lowercasing, so every span is measured on the original string:

                except re.error:
                    _regex = re.compile(re.escape(pattern), _flags)
                    _use_regex = True

(This also lets you drop the _search_plain branch in _match_span.)

🟢 size_bytes no longer matches the file on disk for BOM files: both read_file mixins still report len(content.encode("utf-8")). For UTF-16 that's about half the real size. Nothing breaks, but the field is now misleading for exactly the files this PR adds. Consider os.path.getsize(file_path).

Strengths

  • text_encoding checks the UTF-32 LE BOM before UTF-16 LE, which is correct since one is a prefix of the other. The NUL guard keeps FF FE-prefixed binaries reported as binary, and a parametrized test covers it.
  • search_file_content now opens each file once, which removes the second handle that was leaking on the context_lines=0 path.
  • get_file_info now skips its latin-1 fallback when the file has a BOM, so it no longer returns a garbled ÿþL\x00e\x00… preview.
  • Spec docs were updated in both file-io-tools-mixin.mdx and file-search-mixin.mdx, so they don't contradict each other.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 4, 2026
Merged via the queue into amd:main with commit eef7bdf Oct 4, 2026
@kovtcharov-amd
kovtcharov-amd deleted the kalin/file-tools-utf16-longline branch October 4, 2026 22:23
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 4, 2026
…es (amd#4697)

Running a `gaia_*` eval locally used to mean copying a few environment
variables out of `eval_flagship.yml`, and it was easy to get it subtly
wrong. Started from the checkout, the backend can't see the staged
fixtures. Without the fake `gh` first on PATH, auto-approved triage
scenarios send writes to real GitHub. The agent under test inherits the
judge's credentials. `util/run_eval_lane.py --lane <lane>` reuses
`eval_lane_matrix.py`'s lane environment and repeats the workflow's
setup, so a local score means what a CI score means.

`util/stress_corpus.py` generates the large and hostile files used to
validate v0.25: a 1,667-page PDF with one buried fact, a 400k-row CSV, a
120 MB log, injection, UTF-16, a 5 MB single line, and hostile
filenames. They found amd#4679, amd#4686 and amd#4688. Its answer key is refused
if placed inside the corpus, because the agent's content search would
otherwise find the answers there. CLAUDE.md and the testing skill point
at both. CLAUDE.md also notes that worktrees share one stash list.

## Test plan
- [x] `pytest tests/unit/eval/test_run_eval_lane.py
tests/unit/eval/test_eval_lane_matrix.py` (67 passed)
- [x] `python util/stress_corpus.py --out <dir> --answers <file>` builds
110 MB, and refuses `--answers` inside `--out`
- [x] `python util/check_doc_links.py`, `python util/lint.py --black
--isort`
- [ ] `python util/run_eval_lane.py --category gaia_honesty` on a Strix
Halo box produces a scorecard
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants