Answer stability round 1: 1 🔴, 8 🟡 (0 misread); read only a regular file, only as far as the shown lines, skip cut-short output, and test the surviving mutants
This commit is contained in:
+103
-26
@@ -1,3 +1,4 @@
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
@@ -9,6 +10,7 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from rule_hook.repeat_read import Asked, result_lines
|
||||
from rule_hook.rules import blocks, Breach, check, command_breaches, file_breaches, overrides
|
||||
from rule_hook.main import breaches_of, read_breaches
|
||||
from rule_hook.call import Call, parsed_call
|
||||
@@ -40,7 +42,7 @@ def checked(command: str) -> list[str]:
|
||||
|
||||
|
||||
def hook(call: dict, cwd: str, env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
|
||||
return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env() | (env or {}), input=json.dumps(call), text=True)
|
||||
return subprocess.run([str(HOOK)], capture_output=True, cwd=cwd, env=isolated_env() | (env or {}), input=json.dumps(call), text=True, timeout=10)
|
||||
|
||||
|
||||
def git(cwd: str, *args: str) -> str:
|
||||
@@ -330,29 +332,44 @@ class ReviewerReport(unittest.TestCase):
|
||||
|
||||
class RepeatRead(unittest.TestCase):
|
||||
LINES = [f"line {n}" for n in range(1, 31)]
|
||||
# The file is written at WRITTEN and each entry stamped READ_AT, unless a test changes the file at CHANGED and stamps a later entry AFTER_THE_CHANGE.
|
||||
WRITTEN = datetime.datetime(2026, 5, 1, tzinfo=datetime.UTC).timestamp()
|
||||
READ_AT = "2026-06-01T00:00:00.000Z"
|
||||
CHANGED = datetime.datetime(2026, 7, 1, tzinfo=datetime.UTC).timestamp()
|
||||
AFTER_THE_CHANGE = "2026-07-01T00:00:01.000Z"
|
||||
|
||||
def setUp(self):
|
||||
self.folder = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", self.folder])
|
||||
self.file = f"{self.folder}/f.txt"
|
||||
pathlib.Path(self.file).write_text("\n".join(self.LINES) + "\n")
|
||||
self.write(self.LINES, self.WRITTEN)
|
||||
self.transcript = f"{self.folder}/s.jsonl"
|
||||
self.entries: list[dict] = []
|
||||
|
||||
def write(self, lines: list[str], at: float) -> None:
|
||||
pathlib.Path(self.file).write_text("\n".join(lines) + "\n")
|
||||
os.utime(self.file, (at, at))
|
||||
|
||||
def change(self, number: int) -> None:
|
||||
self.write([("changed" if n == number else line) for n, line in enumerate(self.LINES, 1)], self.CHANGED)
|
||||
|
||||
def add(self, entry: dict, parent: str | None = "last") -> str:
|
||||
uuid = f"u{len(self.entries)}"
|
||||
parent = (self.entries[-1]["uuid"] if self.entries else None) if parent == "last" else parent
|
||||
self.entries.append({"uuid": uuid, "parentUuid": parent, "cwd": self.folder} | entry)
|
||||
self.entries.append({"uuid": uuid, "parentUuid": parent, "cwd": self.folder, "timestamp": self.READ_AT} | entry)
|
||||
pathlib.Path(self.transcript).write_text("\n".join(json.dumps(entry) for entry in self.entries) + "\n")
|
||||
return uuid
|
||||
|
||||
def used(self, tool: str, given: dict, result: str, error: bool = False) -> None:
|
||||
def used(self, tool: str, given: dict, result: str, error: bool = False, at: str = READ_AT) -> None:
|
||||
tool_id = f"toolu_{len(self.entries)}"
|
||||
self.add({"type": "assistant", "message": {"content": [{"type": "tool_use", "id": tool_id, "name": tool, "input": given}]}})
|
||||
self.add({"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": tool_id, "content": result, "is_error": error}]}})
|
||||
self.add({"type": "assistant", "timestamp": at, "message": {"content": [{"type": "tool_use", "id": tool_id, "name": tool, "input": given}]}})
|
||||
self.add({"type": "user", "timestamp": at, "message": {"content": [{"type": "tool_result", "tool_use_id": tool_id, "content": result, "is_error": error}]}})
|
||||
|
||||
def numbered(self, start: int, end: int) -> str:
|
||||
return "\n".join(f"{n}\t{self.LINES[n - 1]}" for n in range(start, end + 1))
|
||||
|
||||
def read(self, start: int, end: int) -> None:
|
||||
self.used("Read", {"file_path": self.file, "offset": start, "limit": end - start + 1}, "\n".join(f"{n}\t{self.LINES[n - 1]}" for n in range(start, end + 1)))
|
||||
self.used("Read", {"file_path": self.file, "offset": start, "limit": end - start + 1}, self.numbered(start, end))
|
||||
|
||||
def shown(self, start: int, end: int) -> str:
|
||||
return "\n".join(self.LINES[start - 1:end])
|
||||
@@ -366,6 +383,10 @@ class RepeatRead(unittest.TestCase):
|
||||
self.assertEqual(rules(found), ["repeat-read"])
|
||||
self.assertIn(f"lines 2-6 of {self.file} are in your context", found[0].detail)
|
||||
|
||||
def test_the_note_names_a_single_line_as_one(self):
|
||||
self.read(1, 10)
|
||||
self.assertIn(f"line 7 of {self.file} is in your context", self.found("Bash", {"command": "sed -n 7p f.txt"})[0].detail)
|
||||
|
||||
def test_lines_read_in_two_reads_are_in_context(self):
|
||||
self.read(1, 10)
|
||||
self.read(11, 20)
|
||||
@@ -389,24 +410,48 @@ class RepeatRead(unittest.TestCase):
|
||||
self.add({"type": "user", "message": {"content": "This session is being continued"}})
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
|
||||
|
||||
def change_the_first_line(self) -> None:
|
||||
pathlib.Path(self.file).write_text("changed\n" + "\n".join(self.LINES[1:]) + "\n")
|
||||
|
||||
def test_a_changed_line_lets_the_read_through(self):
|
||||
self.read(1, 10)
|
||||
self.change_the_first_line()
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
|
||||
self.change(1)
|
||||
self.assertEqual(self.found("Bash", {"command": f"head {self.file}"}), [])
|
||||
|
||||
def test_a_change_in_the_last_asked_line_lets_the_read_through(self):
|
||||
self.read(1, 10)
|
||||
self.change(10)
|
||||
self.assertEqual(self.found("Bash", {"command": "sed -n 1,10p f.txt"}), [])
|
||||
|
||||
def test_lines_that_did_not_change_stay_in_context(self):
|
||||
self.read(1, 10)
|
||||
self.change_the_first_line()
|
||||
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 2, "limit": 9})), ["repeat-read"])
|
||||
self.change(1)
|
||||
self.assertEqual(rules(self.found("Bash", {"command": "sed -n 2,10p f.txt"})), ["repeat-read"])
|
||||
|
||||
def test_a_failed_read_holds_no_lines(self):
|
||||
self.used("Read", {"file_path": self.file, "offset": 1, "limit": 10}, "\n".join(f"{n}\t{self.LINES[n - 1]}" for n in range(1, 11)), error=True)
|
||||
def test_a_read_without_an_offset_starts_at_line_1(self):
|
||||
self.read(2, 11)
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "limit": 10}), [])
|
||||
|
||||
# Claude Code's Edit refuses a file changed since the agent last read it with Read, or wrote it with Edit or Write, until it reads it again.
|
||||
def test_a_read_goes_through_once_the_file_changed_after_the_last_read(self):
|
||||
self.read(1, 10)
|
||||
self.change(30)
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
|
||||
|
||||
def test_a_read_on_a_branch_the_session_left_holds_no_lines(self):
|
||||
def test_a_refused_edit_does_not_count_as_reading_the_file(self):
|
||||
self.read(1, 10)
|
||||
self.change(30)
|
||||
self.used("Edit", {"file_path": self.file, "old_string": "line 5", "new_string": "five"}, "<tool_use_error>File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.</tool_use_error>", error=True, at=self.AFTER_THE_CHANGE)
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
|
||||
|
||||
def test_an_edit_keeps_the_lines_it_left_unchanged_in_context(self):
|
||||
self.read(1, 10)
|
||||
self.change(30)
|
||||
self.used("Edit", {"file_path": self.file, "old_string": "line 30", "new_string": "changed"}, f"The file {self.file} has been updated successfully.", at=self.AFTER_THE_CHANGE)
|
||||
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10})), ["repeat-read"])
|
||||
|
||||
def test_a_failed_read_holds_no_lines(self):
|
||||
self.used("Read", {"file_path": self.file, "offset": 1, "limit": 10}, self.numbered(1, 10), error=True)
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 1, "limit": 10}), [])
|
||||
|
||||
def test_a_read_on_a_branch_the_session_rewound_holds_no_lines(self):
|
||||
start = self.add({"type": "user", "message": {"content": "go"}})
|
||||
self.read(1, 10)
|
||||
self.add({"type": "user", "message": {"content": "go again"}}, parent=start)
|
||||
@@ -418,11 +463,21 @@ class RepeatRead(unittest.TestCase):
|
||||
with self.subTest(command):
|
||||
self.assertEqual(rules(self.found("Bash", {"command": command})), ["repeat-read"])
|
||||
|
||||
def test_a_head_starts_at_line_1(self):
|
||||
self.read(2, 11)
|
||||
self.assertEqual(self.found("Bash", {"command": f"head {self.file}"}), [])
|
||||
|
||||
def test_a_cat_asks_for_the_whole_file(self):
|
||||
self.read(1, 20)
|
||||
self.assertEqual(self.found("Bash", {"command": f"cat {self.file}"}), [])
|
||||
|
||||
def test_a_sed_output_puts_its_lines_in_context(self):
|
||||
# Claude Code's Edit and Write take only a Read as having read the file.
|
||||
def test_a_read_goes_through_until_the_agent_read_the_file_with_read(self):
|
||||
self.used("Bash", {"command": f"sed -n '1,20p' {self.file}"}, self.shown(1, 20))
|
||||
self.assertEqual(self.found("Read", {"file_path": self.file, "offset": 4, "limit": 3}), [])
|
||||
|
||||
def test_a_bash_output_counts_against_a_read_once_the_agent_read_the_file_with_read(self):
|
||||
self.read(21, 30)
|
||||
self.used("Bash", {"command": f"sed -n '1,20p' {self.file}"}, self.shown(1, 20))
|
||||
self.assertEqual(rules(self.found("Read", {"file_path": self.file, "offset": 4, "limit": 3})), ["repeat-read"])
|
||||
|
||||
@@ -430,19 +485,40 @@ class RepeatRead(unittest.TestCase):
|
||||
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 30))
|
||||
self.assertEqual(rules(self.found("Bash", {"command": "sed -n '25,$p' f.txt"})), ["repeat-read"])
|
||||
|
||||
def test_a_read_whose_output_goes_elsewhere_is_not_checked(self):
|
||||
def test_a_relative_path_in_the_transcript_is_under_its_entry_s_cwd(self):
|
||||
self.used("Bash", {"command": "cat f.txt"}, self.shown(1, 30))
|
||||
self.assertEqual(rules(read_breaches(Call("Bash", {"command": f"head -n 5 {self.file}"}, "/", "", self.transcript), "/h")), ["repeat-read"])
|
||||
|
||||
def test_a_tilde_path_is_under_the_home_folder(self):
|
||||
self.used("Read", {"file_path": "~/f.txt", "offset": 1, "limit": 10}, self.numbered(1, 10))
|
||||
self.used("Bash", {"command": "cat ~/f.txt"}, self.shown(1, 30))
|
||||
for tool, given in [("Read", {"file_path": "~/f.txt", "offset": 1, "limit": 10}), ("Bash", {"command": "sed -n 1,30p ~/f.txt"})]:
|
||||
with self.subTest(tool):
|
||||
self.assertEqual(rules(read_breaches(Call(tool, given, "/", "", self.transcript), self.folder)), ["repeat-read"])
|
||||
|
||||
def test_other_commands_on_the_file_are_not_checked(self):
|
||||
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 30))
|
||||
for command in [f"cat {self.file} > copy", f"cat {self.file} | wc -l", f"cat {self.file} {self.file}", f"head -c 5 {self.file}", f"sed 's/a/b/' {self.file}"]:
|
||||
with self.subTest(command):
|
||||
self.assertEqual(self.found("Bash", {"command": command}), [])
|
||||
|
||||
def test_a_truncated_output_leaves_out_the_lines_it_cut(self):
|
||||
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 5) + "\n... [25 lines truncated] ...")
|
||||
self.assertEqual(self.found("Bash", {"command": f"head -n 10 {self.file}"}), [])
|
||||
# As Claude Code 2.1.312 writes a Bash output it cut short.
|
||||
def test_an_output_cut_short_shows_no_lines(self):
|
||||
for cut in [
|
||||
f"<persisted-output>\nOutput too large (37.9KB). Full output saved to: {self.folder}/tool-results/b2hymdt7w.txt\n\nPreview (first 2KB):\n{self.shown(1, 30)}\n...\n</persisted-output>",
|
||||
f"<truncated-output>\nOutput too large (37.9KB). It could not be saved, so only the first 2KB are shown; the rest was dropped. If the tool can page or filter its results, call it again for the part you need.\n\n{self.shown(1, 30)}\n</truncated-output>",
|
||||
self.shown(1, 5) + "\n\n... [25 lines truncated] ...",
|
||||
]:
|
||||
with self.subTest(cut[:20]):
|
||||
self.assertEqual(result_lines("Bash", Asked(self.file, 1, None), cut), {})
|
||||
|
||||
def test_a_truncated_output_holds_the_lines_it_shows(self):
|
||||
self.used("Bash", {"command": f"cat {self.file}"}, self.shown(1, 5) + "\n... [25 lines truncated] ...")
|
||||
self.assertEqual(rules(self.found("Bash", {"command": f"head -n 5 {self.file}"})), ["repeat-read"])
|
||||
def test_a_fifo_is_never_opened(self):
|
||||
fifo = f"{self.folder}/fifo"
|
||||
os.mkfifo(fifo)
|
||||
self.used("Bash", {"command": f"cat {fifo}"}, "line 1")
|
||||
# Opened, the FIFO would block the hook, since it has no writer.
|
||||
ran = hook({"cwd": self.folder, "tool_name": "Bash", "tool_input": {"command": f"head -n 1 {fifo}"}, "transcript_path": self.transcript}, self.folder)
|
||||
self.assertEqual((ran.returncode, ran.stderr), (0, ""))
|
||||
|
||||
def called(self, agent_id: str = "") -> Call:
|
||||
given = {"cwd": self.folder, "tool_name": "Read", "tool_input": {"file_path": self.file, "offset": 1, "limit": 10}, "transcript_path": self.transcript}
|
||||
@@ -459,7 +535,7 @@ class RepeatRead(unittest.TestCase):
|
||||
self.read(1, 10)
|
||||
self.assertEqual(rules(read_breaches(self.called(), "/h")), ["repeat-read"])
|
||||
|
||||
def test_a_missing_transcript_blocks_nothing(self):
|
||||
def test_a_missing_transcript_lets_the_read_through(self):
|
||||
self.assertEqual(read_breaches(Call("Read", {"file_path": self.file}, self.folder, "", f"{self.folder}/none.jsonl"), "/h"), [])
|
||||
|
||||
def test_the_hook_blocks_a_repeated_read_without_offering_an_override(self):
|
||||
@@ -471,6 +547,7 @@ class RepeatRead(unittest.TestCase):
|
||||
self.assertEqual(ran.returncode, 2)
|
||||
self.assertIn("Blocked by rule repeat-read: ", ran.stderr)
|
||||
self.assertNotIn("rule-override", ran.stderr)
|
||||
self.assertIn("No marker overrides it.", ran.stderr)
|
||||
|
||||
|
||||
class Hook(unittest.TestCase):
|
||||
|
||||
Reference in New Issue
Block a user