The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(file-ops): refuse JSON NaN/Infinity only when the write introduces it
kshitijk4poor8b31a4f49362
diff --git a/tests/tools/test_file_operations_edge_cases.py b/tests/tools/test_file_operations_edge_cases.pyindex bbf0cf8dc8d..742e4467e90 100644--- a/tests/tools/test_file_operations_edge_cases.py+++ b/tests/tools/test_file_operations_edge_cases.py@@ -176,6 +176,30 @@ class TestCheckLintInproc:assert "TOMLDecodeError" in result.output[email protected]("token", ["NaN", "Infinity", "-Infinity"])+def test_json_write_refuses_only_introduced_nonstandard_constants(tmp_path, token):+ """NaN/Infinity are refused when the write introduces them (strict JSON+ consumers reject them), but a file already holding one still takes edits."""+ from tools.environments.local import LocalEnvironment++ ops = ShellFileOperations(LocalEnvironment(cwd=str(tmp_path)), cwd=str(tmp_path))+ clean = tmp_path / "clean.json"+ clean.write_text('{"value": 1}\n', encoding="utf-8")+ result = ops.write_file(str(clean), '{"value": %s}\n' % token)+ assert result.error and token in result.error+ assert clean.read_text(encoding="utf-8") == '{"value": 1}\n'++ quoted = '{"value": ["%s", 1.5, null]}\n' % token+ assert ops.write_file(str(clean), quoted).error is None+ assert clean.read_text(encoding="utf-8") == quoted++ legacy = tmp_path / "legacy.json"+ legacy.write_text('{"value": %s, "n": 1}\n' % token, encoding="utf-8")+ edited = '{"value": %s, "n": 2}\n' % token+ assert ops.write_file(str(legacy), edited).error is None+ assert legacy.read_text(encoding="utf-8") == edited++class TestCheckLintDelta:"""Verify _check_lint_delta() filters pre-existing errors from post-edit output."""diff --git a/tests/tools/test_json_write_constants.py b/tests/tools/test_json_write_constants.pydeleted file mode 100644index a4f12f375d2..00000000000--- a/tests/tools/test_json_write_constants.py+++ /dev/null@@ -1,35 +0,0 @@-"""JSON file writes reject non-JSON constants without changing existing bytes."""--import json--from tools import file_tools, terminal_tool-from tools.registry import registry---def test_json_write_refuses_nonstandard_constants_without_overwriting(tmp_path, monkeypatch):- home = tmp_path / "home"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- task = "strict-json-write"- path = tmp_path / "config.json"- original = '{"value": 1}\n'- path.write_text(original, encoding="utf-8")- terminal_tool.register_task_env_overrides(task, {"env_type": "local", "cwd": str(tmp_path)})- try:- read = json.loads(registry.dispatch("read_file", {"path": str(path)}, task_id=task))- assert "error" not in read, read- for token in ("NaN", "Infinity", "-Infinity"):- result = json.loads(registry.dispatch("write_file", {- "path": str(path), "content": '{"value": ' + token + '}\n',- }, task_id=task))- assert "error" in result, result- assert path.read_text(encoding="utf-8") == original- valid = '{"value": ["NaN", "Infinity", "-Infinity", 1.5, null]}\n'- result = json.loads(registry.dispatch("write_file", {- "path": str(path), "content": valid,- }, task_id=task))- assert "error" not in result, result- assert path.read_text(encoding="utf-8") == valid- finally:- file_tools.clear_file_ops_cache(task)- terminal_tool.clear_task_env_overrides(task)diff --git a/tools/file_operations.py b/tools/file_operations.pyindex cc028e89f13..c51cba24bf7 100644--- a/tools/file_operations.py+++ b/tools/file_operations.py@@ -168,6 +168,38 @@ def _split_segments(output: str, sentinel: str) -> list[str]:return output.split(sentinel + "\n")+def _json_nonstandard_constant(text: str) -> Optional[str]:+ """First NaN/Infinity/-Infinity in ``text`` when it is otherwise valid JSON,+ else None. ``json.loads`` accepts these JavaScript extensions by default."""+ found: list[str] = []++ def note_constant(value: str) -> float:+ found.append(value)+ return float("nan")++ try:+ json.loads(text.lstrip(_UTF8_BOM), parse_constant=note_constant)+ except Exception: # noqa: BLE001 — unparseable text has no constant to report+ return None+ return found[0] if found else None+++def _refuse_introduced_json_constant(path: str, content: str,+ pre_content: Optional[str]) -> Optional[WriteResult]:+ """Refuse a JSON write that INTRODUCES a nonstandard constant (strict JSON+ consumers reject them). A file that already holds one keeps accepting+ unrelated edits, which is why the lenient syntax gate can't do this check."""+ constant = _json_nonstandard_constant(content)+ if constant is None:+ return None+ if pre_content is not None and _json_nonstandard_constant(pre_content) is not None:+ return None+ return WriteResult(error=(+ f"Refusing to write '{path}': candidate content uses {constant}, which is "+ "not valid JSON. The file was NOT created or modified. Use null or a "+ "string instead and retry."))++class ShellFileOperations(LintMixin, SearchMixin, FileOperations):"""File operations over any terminal backend exposing ``execute(command, cwd)``returning ``{"output": str, "returncode": int}``.@@ -1463,7 +1495,8 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):Order: deny list → lone-surrogate refusal → fail-closed syntax gate on theCANDIDATE content (JSON/YAML/TOML) → one compound on-disk probe(pre-content when wanted, CRLF, BOM; see ``_probe_write_target``) →- CRLF/BOM preservation → LSP baseline snapshot → atomic write (content rides+ JSON NaN/Infinity refusal when the write introduces one → CRLF/BOM+ preservation → LSP baseline snapshot → atomic write (content ridesstdin: no ARG_MAX limit) → sha256 verification → lint delta → LSPdiagnostics when syntax is clean. ``pre_content``: pre-edit content thecaller already has (skips the read); BOM detection always probes disk.@@ -1484,6 +1517,10 @@ class ShellFileOperations(LintMixin, SearchMixin, FileOperations):# LSP coverage (keeps the hot path fast for binaries).want_pre = ext in LINTERS_INPROC or self._lsp_handles_extension(ext)has_bom, pre_content, original_ending = self._probe_write_target(path, pre_content, want_pre)+ if ext == ".json":+ refused = _refuse_introduced_json_constant(path, content, pre_content)+ if refused is not None:+ return refused# read_file strips the BOM and models send bare-LF text, so a round-trip would# otherwise normalize CRLF files and drop the BOM (prepend only when absent).if original_ending == "\r\n":diff --git a/tools/file_operations_lint.py b/tools/file_operations_lint.pyindex 0ade3321924..ff3273c0ead 100644--- a/tools/file_operations_lint.py+++ b/tools/file_operations_lint.py@@ -68,13 +68,8 @@ def _looks_like_linter_unusable(base_cmd: str, output: str) -> bool:def _lint_json_inproc(content: str) -> tuple[bool, str]:"""In-process JSON syntax check. Returns (ok, error_message)."""- def reject_constant(value: str):- # json.loads accepts these JavaScript extensions by default, but strict- # JSON consumers reject them and file writes promise a syntax gate.- raise ValueError(f"{value} is not a valid JSON constant")-try:- json.loads(content, parse_constant=reject_constant)+ json.loads(content)return True, ""except json.JSONDecodeError as e:return False, f"JSONDecodeError: {e.msg} (line {e.lineno}, column {e.colno})"