import os import pathlib import re import subprocess import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from touch_predictions.beside import Beside, chunks_beside from touch_predictions import diff_parts, file_parts, main, record from failure import Failure from test_env import isolated_env from project_config.main import located from record_store.fakes import MemoryStore from touch_predictions.prediction import overlaps, Part, predicted, rendered, together from plan_store.todo_md import plan_of from project_config.settings import ProjectConfig from project_config.test_project_config import write_config DETAIL = """A planning call. Touches: - `bin/a.py`: `main`, `Plan.branch` (small) - `README.md`: `## Goals, and (more): things` - `bin/run.sh`: lines 10-20 - `docs/new.md` More prose, with `bin/b.py` named. """ PYTHON = """\"\"\"Docstring.\"\"\" import os LIMIT = 3 # A comment that belongs to first. def first(): return 1 class Plan: size: int = 0 @property def branch(self): def inner(): return 2 return inner() if os.name: pass """ MARKDOWN = """Intro. # Title Text. ``` ## Not a heading ``` ## Goals 1. One. """ class PredictedTest(unittest.TestCase): def test_reads_each_bullet_of_the_touches_list(self) -> None: self.assertEqual(predicted(DETAIL), { "bin/a.py": (Part("main"), Part("Plan.branch", small=True)), "README.md": (Part("## Goals, and (more): things"),), "bin/run.sh": (Part("lines 10-20"),), "docs/new.md": (), }) def test_a_detail_without_the_list_predicts_nothing(self) -> None: self.assertIsNone(predicted("Only prose, with `bin/a.py` named.")) def test_a_bullet_it_cannot_read_is_a_failure_that_quotes_it(self) -> None: for bullet in ("- bin/a.py: main", "- `bin/a.py`: main", "- `bin/a.py`: lines 20-10", "- `bin/a.py`: `main` `other`"): with self.subTest(bullet): found = predicted(f"Touches:\n\n{bullet}\n") assert isinstance(found, Failure) self.assertIn(bullet, found.reason) def test_an_empty_list_is_a_failure(self) -> None: self.assertIsInstance(predicted("Touches:\n\nProse.\n"), Failure) found = predicted("Touches:\n") assert isinstance(found, Failure) self.assertEqual(found.reason, "no bullet follows `Touches:`") def test_reads_a_list_right_under_its_label_a_one_line_range_and_a_name_of_any_letters(self) -> None: self.assertEqual(predicted("Touches:\n- `a.py`: `Xray`, lines 5-5\n"), {"a.py": (Part("Xray"), Part("lines 5-5"))}) def test_rendered_reads_back(self) -> None: touches = predicted(DETAIL) assert isinstance(touches, dict) self.assertEqual(predicted(f"Touches:\n\n{rendered(touches)}\n"), touches) def test_a_name_that_holds_backticks_takes_a_longer_run_with_a_space_inside_each_end(self) -> None: self.assertEqual(predicted("Touches:\n- `a.md`: `` ## The `foo` tool `` (small), ``` `` ```, `` `x` ``\n"), {"a.md": (Part("## The `foo` tool", small=True), Part("``"), Part("`x`"))}) self.assertEqual(rendered({"a.md": (Part("## The `foo` tool", small=True), Part("``"))}), "- `a.md`: `` ## The `foo` tool `` (small), ``` `` ```") def test_a_name_ends_only_at_a_run_as_long_as_the_one_that_opens_it(self) -> None: self.assertEqual(predicted("Touches:\n- `a.md`: `` a ``` b ``, `c``d`\n"), {"a.md": (Part("a ``` b"), Part("c``d"))}) def test_a_path_holds_any_character_and_a_single_backtick_keeps_a_names_spaces(self) -> None: self.assertEqual(predicted("Touches:\n- `my file.md`: ` x `\n- `` a`b.md ``\n"), {"my file.md": (Part(" x "),), "a`b.md": ()}) def test_rendered_reads_back_whatever_a_path_or_a_name_holds(self) -> None: touches = {"my file.md": (Part("## todo.md: under `Touches:` in its detail"), Part("## ``a`` and `b`", small=True), Part("`"), Part("## ends in `x`"), Part(" x "), Part("lines 2-3")), "a`b.md": (), "c, d: e.md": (Part("# T"),)} self.assertEqual(predicted(f"Touches:\n\n{rendered(touches)}\n"), touches) def test_a_longer_run_without_its_spaces_or_its_end_or_a_name_is_a_failure(self) -> None: for bullet in ("- `a.md`: ``## A``", "- `a.md`: `` ## A", "- `a.md`: `` ## A `", "- `a.md`: `` ``", "- `a.md`: ", "- `a.md`:", "- `a.md`: `f`, ", "- `a.md`: `f`,`g`", "- ``", "- `a.md` (small)", "- `a.md`: `f` (small) (small)"): with self.subTest(bullet): self.assertIsInstance(predicted(f"Touches:\n\n{bullet}\n"), Failure) def test_a_range_that_runs_backwards_is_a_failure_that_says_so(self) -> None: found = predicted("Touches:\n\n- `bin/a.py`: `f`, lines 20-10\n") assert isinstance(found, Failure) self.assertEqual(found.reason, "the bullet '- `bin/a.py`: `f`, lines 20-10' under `Touches:` holds a line range whose first line comes after its last") def test_together_joins_items_and_keeps_small_only_where_each_says_so(self) -> None: joined = together([{"a.py": (Part("f", small=True), Part("g", small=True))}, {"a.py": (Part("f"),), "b.md": ()}, {"b.md": (Part("# T"),)}]) self.assertEqual(joined, {"a.py": (Part("f"), Part("g", small=True)), "b.md": ()}) def test_together_keeps_a_part_not_small_once_one_says_so_and_reads_on_past_a_whole_file(self) -> None: joined = together([{"a.py": (Part("f"),), "b.md": ()}, {"b.md": (Part("# T"),), "a.py": (Part("f", small=True),), "c.py": (Part("h"),)}]) self.assertEqual(joined, {"a.py": (Part("f"),), "b.md": (), "c.py": (Part("h"),)}) class OverlapsTest(unittest.TestCase): def test_other_files_and_other_parts_do_not_overlap(self) -> None: self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("g"),), "b.py": ()}), []) def test_the_same_part_overlaps(self) -> None: self.assertEqual(overlaps({"a.py": (Part("f"), Part("g"))}, {"a.py": (Part("g"),)}), ["`a.py` `g`"]) def test_a_class_overlaps_its_method_but_not_a_name_it_only_starts(self) -> None: self.assertEqual(overlaps({"a.py": (Part("Plan"),)}, {"a.py": (Part("Plan.branch"), Part("Planned"))}), ["`a.py` `Plan`"]) def test_a_whole_file_overlaps_any_part_of_it(self) -> None: self.assertEqual(overlaps({"a.py": ()}, {"a.py": (Part("g", small=True),)}), ["`a.py`"]) def test_reads_on_past_a_file_only_one_touches_and_past_a_whole_file(self) -> None: theirs = {"a.py": (), "b.py": (Part("g"),)} self.assertEqual(overlaps({"z.py": (Part("f"),), "a.py": (), "b.py": (Part("g"),)}, theirs), ["`a.py`", "`b.py` `g`"]) def test_line_ranges_overlap_where_they_share_a_line(self) -> None: self.assertEqual(overlaps({"x.sh": (Part("lines 1-10"),)}, {"x.sh": (Part("lines 10-12"),)}), ["`x.sh` lines 1-10"]) self.assertEqual(overlaps({"x.sh": (Part("lines 1-9"),)}, {"x.sh": (Part("lines 10-12"),)}), []) self.assertEqual(overlaps({"x.sh": (Part("lines 10-12"),)}, {"x.sh": (Part("lines 1-10"),)}), ["`x.sh` lines 10-12"]) self.assertEqual(overlaps({"x.sh": (Part("lines 11-12"),)}, {"x.sh": (Part("lines 1-10"),)}), []) def test_a_line_range_overlaps_a_named_part_since_nothing_tells_them_apart(self) -> None: self.assertEqual(overlaps({"a.py": (Part("lines 1-9"),)}, {"a.py": (Part("f"),)}), ["`a.py` lines 1-9"]) self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("lines 1-9"),)}), ["`a.py` `f`"]) def test_a_small_change_on_either_side_is_taken(self) -> None: self.assertEqual(overlaps({"a.py": (Part("f", small=True),)}, {"a.py": (Part("f"),)}), []) self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("f", small=True),)}), []) class FilePartsTest(unittest.TestCase): def names(self, path: str, text: str, *lines: int) -> set[str] | None: return file_parts.part_names(path, text, lines) def test_python_names_the_innermost_function_or_class(self) -> None: self.assertEqual(self.names("a.py", PYTHON, 9), {"first"}) self.assertEqual(self.names("a.py", PYTHON, 13), {"Plan"}) self.assertEqual(self.names("a.py", PYTHON, 15, 18), {"Plan.branch", "Plan.branch.inner"}) def test_python_names_a_top_level_assignment_and_calls_the_rest_the_module(self) -> None: self.assertEqual(self.names("a.py", PYTHON, 4), {"LIMIT"}) self.assertEqual(self.names("a.py", PYTHON, 1, 2, 22), {"(module)"}) def test_python_gives_a_line_between_statements_to_the_next_one(self) -> None: self.assertEqual(self.names("a.py", PYTHON, 7), {"first"}) self.assertEqual(self.names("a.py", PYTHON, 99), {"(module)"}) self.assertEqual(self.names("a.py", "", 1), {"(module)"}) def test_python_names_no_part_for_a_blank_line_between_statements(self) -> None: text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n# end\n\n" self.assertEqual(self.names("a.py", text, 1, 2, 3, 4), {"a"}) self.assertEqual(self.names("a.py", text, 3, 4), set()) self.assertEqual(self.names("a.py", text, 7, 9), set()) self.assertEqual(self.names("a.py", text, 8), {"b"}) self.assertEqual(self.names("a.py", "# only\n\n", 2), set()) def test_python_names_the_part_a_blank_line_inside_a_statement_lies_in(self) -> None: self.assertEqual(self.names("a.py", "def a():\n\tx = 1\n\n\treturn x\n\nT = \"\"\"\n\n\"\"\"\n", 3, 7), {"a", "T"}) def test_blank_lines_name_their_parts_where_separators_count(self) -> None: text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n" self.assertEqual(file_parts.part_names("a.py", text, [3, 7], separators=True), {"b"}) self.assertEqual(file_parts.part_names("a.py", "# only\n\n", [2], separators=True), {"(module)"}) self.assertEqual(file_parts.part_names("a.md", "# A\n\n", [2], separators=True), {"# A"}) def test_python_without_statements_names_the_module_only_for_a_line(self) -> None: self.assertEqual(self.names("a.py", ""), set()) self.assertEqual(self.names("a.py", "# only a comment\n"), set()) self.assertEqual(self.names("a.py", "# only a comment\n", 1), {"(module)"}) def test_python_that_does_not_parse_has_no_names(self) -> None: self.assertIsNone(self.names("a.py", "def (:\n", 1)) def test_python_names_a_function_under_another_statement_and_an_annotated_assignment(self) -> None: text = "if True:\n\tdef f():\n\t\treturn 1\n\nclass C:\n\tif True:\n\t\tdef m(self):\n\t\t\treturn 2\n\nX: int = 1\n" self.assertEqual(self.names("a.py", text, 3, 8, 10), {"f", "C.m", "X"}) def test_python_gives_a_line_after_the_last_statement_to_it(self) -> None: self.assertEqual(self.names("a.py", "A = 1\nB = 2\nC = 3\n# end\n", 4), {"C"}) self.assertEqual(self.names("a.py", "class A:\n\tdef f(self):\n\t\tpass\n\n# end\n", 5), {"A"}) def test_markdown_drops_a_headings_trailing_space_and_puts_a_line_past_the_end_under_the_last_heading(self) -> None: self.assertEqual(self.names("a.md", "# A \ntext\n## B\n", 2, 4), {"# A", "## B"}) def test_markdown_names_the_heading_above_and_skips_fenced_lines(self) -> None: self.assertEqual(self.names("a.md", MARKDOWN, 1), {"(top)"}) self.assertEqual(self.names("a.md", MARKDOWN, 3, 5, 8), {"# Title"}) self.assertEqual(self.names("a.md", MARKDOWN, 13), {"## Goals"}) def test_markdown_names_no_part_for_a_blank_line(self) -> None: self.assertEqual(self.names("a.md", "# A\ntext\n\n## End\nmore\n", 3, 4, 5), {"## End"}) self.assertEqual(self.names("a.md", "# A\n \t\n", 2), set()) def test_markdown_closes_a_fence_only_on_its_own_character_at_least_as_long(self) -> None: self.assertEqual(self.names("a.md", "# A\n````\n```\n# not\n````\n# B\ntext\n", 4, 7), {"# A", "# B"}) self.assertEqual(self.names("a.md", "# A\n```\n~~~\n# not\n```\n# B\ntext\n", 4, 7), {"# A", "# B"}) self.assertEqual(self.names("a.md", "# A\n~~~\n~~~ not the end\n# not\n~~~~~ \n# B\ntext\n", 4, 7), {"# A", "# B"}) def test_any_other_file_has_no_names(self) -> None: self.assertIsNone(self.names("run.sh", "echo\n", 1)) def plan(*items: tuple[int, str, str, str]) -> list: """A plan's items, each given as its ID, release, the IDs that block it and the bullets of its prediction, none for an item without one.""" rows = "".join(f"| {id_} | {release} | {blocked} | | **Do {id_}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n" for id_, release, blocked, _ in items) details = "".join(f"### {id_}. Do {id_}.\n\nTouches:\n\n{bullets}\n\n" for id_, _, _, bullets in items if bullets) found = plan_of(f"# todo\n\n## Scoring\n\n`Score = 100 * V / (2**S + 8)`\n\n`Bar = 0.1`\n\n`Next ID = 99`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n{rows}\n## Details\n\n{details}") assert not isinstance(found, Failure), found return found.items class ChunksBesideTest(unittest.TestCase): def test_picks_in_the_plans_order_each_item_that_overlaps_none_before_it(self) -> None: items = plan((1, "0.2.0", "", "- `a.py`: `f`"), (2, "0.2.0", "", "- `a.py`: `g`\n- `b.py`"), (3, "0.2.0", "", "- `b.py`: `h`"), (4, "0.2.0", "", "- `a.py`: `f`"), (5, "0.2.0", "", "- `c.py`")) self.assertEqual(chunks_beside(items, items[0]), Beside([2, 5], ["item 3, which overlaps item 2 at `b.py`", "item 4, which overlaps item 1 at `a.py` `f`"])) def test_leaves_out_an_item_that_waits_or_names_a_later_release(self) -> None: items = plan((1, "0.2.0", "", "- `a.py`"), (2, "0.2.0", "1", "- `b.py`"), (3, "0.3.0", "", "- `c.py`")) self.assertEqual(chunks_beside(items, items[0]), Beside([], [])) def test_refuses_an_item_without_a_prediction_it_can_read(self) -> None: items = plan((1, "0.2.0", "", "- `a.py`"), (2, "0.2.0", "", ""), (3, "0.2.0", "", "- b.py")) found = chunks_beside(items, items[0]) assert isinstance(found, Beside) self.assertEqual(found.picked, []) self.assertEqual(found.refused[0], "item 2, whose detail has no `Touches:` list") self.assertTrue(found.refused[1].startswith("item 3, whose `Touches:` list cannot be read: the bullet '- b.py'")) def test_no_item_starts_beside_one_that_predicts_nothing(self) -> None: items = plan((1, "0.2.0", "", ""), (2, "0.2.0", "", "- `b.py`")) self.assertEqual(chunks_beside(items, items[0]), "item 1's detail has no `Touches:` list") items = plan((1, "0.2.0", "", "- a.py"), (2, "0.2.0", "", "- `b.py`")) found = chunks_beside(items, items[0]) assert isinstance(found, str) self.assertTrue(found.startswith("item 1's `Touches:` list cannot be read: the bullet '- a.py'"), found) def test_names_each_place_an_item_overlaps(self) -> None: items = plan((1, "0.2.0", "", "- `a.py`: `f`, `g`"), (2, "0.2.0", "", "- `a.py`: `f`, `g`")) self.assertEqual(chunks_beside(items, items[0]), Beside([], ["item 2, which overlaps item 1 at `a.py` `f`, `a.py` `g`"])) def test_says_nothing_where_no_item_predicts(self) -> None: items = plan((1, "0.2.0", "", ""), (2, "0.2.0", "", ""), (3, "0.3.0", "", "- `c.py`")) self.assertIsNone(chunks_beside(items, items[0])) class Repo: """A git checkout in a temporary folder.""" def __init__(self, folder: str) -> None: self.folder = folder self.run("init", "-q", "-b", "main") def run(self, *args: str) -> str: return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.folder, check=True, capture_output=True, text=True).stdout.strip() def commit(self, files: dict[str, str | bytes | None]) -> str: for name, text in files.items(): path = pathlib.Path(self.folder, name) if text is None: path.unlink() elif isinstance(text, bytes): path.write_bytes(text) else: path.write_text(text, encoding="utf-8") self.run("add", "-A") self.run("commit", "-qm", "x") return self.run("rev-parse", "HEAD") class TouchedTest(unittest.TestCase): def setUp(self) -> None: folder = tempfile.TemporaryDirectory() self.addCleanup(folder.cleanup) self.repo = Repo(folder.name) self.base = self.repo.commit({"a.py": PYTHON, "a.md": MARKDOWN, "run.sh": "one\ntwo\nthree\nfour\n", "gone.py": "x = 1\n", "todo.md": "plan\n", "blob.bin": b"\x00\x01"}) def touched(self, files: dict[str, str | bytes | None], *skipped: str) -> object: return diff_parts.touched(self.base, self.repo.commit(files), self.repo.folder, set(skipped)) def test_names_the_parts_of_changed_lines_on_both_sides(self) -> None: changed = PYTHON.replace("\treturn 1\n", "\treturn 3\n").replace("LIMIT = 3\n", "").replace("\tpass\n", "\tpass\n\n\ndef last():\n\tpass\n") self.assertEqual(self.touched({"a.py": changed, "a.md": MARKDOWN + "2. Two.\n"}), { "a.md": (Part("## Goals"),), "a.py": (Part("LIMIT"), Part("first"), Part("last")), }) def test_an_added_or_deleted_file_is_touched_whole(self) -> None: self.assertEqual(self.touched({"new.py": "y = 2\n", "gone.py": None}), {"gone.py": (), "new.py": ()}) def test_a_file_without_names_falls_back_to_the_new_sides_line_ranges(self) -> None: self.assertEqual(self.touched({"run.sh": "one\n2\n3\nfour\nfive\n"}), {"run.sh": (Part("lines 2-3"), Part("lines 5-5"))}) def test_a_deletion_falls_back_to_the_line_it_left(self) -> None: self.assertEqual(self.touched({"run.sh": "one\nfour\n"}), {"run.sh": (Part("lines 1-1"),)}) def test_a_binary_file_is_touched_whole(self) -> None: self.assertEqual(self.touched({"blob.bin": b"\x00\x02"}), {"blob.bin": ()}) def test_python_that_stops_parsing_falls_back_to_line_ranges(self) -> None: self.assertEqual(self.touched({"gone.py": "def (:\n"}), {"gone.py": (Part("lines 1-1"),)}) def test_skipped_paths_do_not_count(self) -> None: self.assertEqual(self.touched({"todo.md": "plan\nmore\n", "gone.py": "x = 2\n"}, "todo.md"), {"gone.py": (Part("x"),)}) def test_reads_on_past_a_skipped_path(self) -> None: self.assertEqual(self.touched({"a.md": "# New\n", "gone.py": "x = 3\n"}, "a.md"), {"gone.py": (Part("x"),)}) def test_a_renamed_file_is_one_deleted_and_one_added(self) -> None: self.repo.run("mv", "a.py", "b.py") self.assertEqual(self.touched({}), {"a.py": (), "b.py": ()}) def test_lists_the_paths_in_order_whatever_happened_to_each(self) -> None: found = self.touched({"z.py": "y = 2\n", "gone.py": "x = 2\n"}) assert isinstance(found, dict) self.assertEqual(list(found), ["gone.py", "z.py"]) def test_reads_the_diff_up_to_head_and_no_later(self) -> None: head = self.repo.commit({"gone.py": "x = 2\n"}) self.repo.commit({"gone.py": "x = 2\ny = 3\n", "run.sh": "one\n"}) self.assertEqual(diff_parts.touched(self.base, head, self.repo.folder, set()), {"gone.py": (Part("x"),)}) def test_reads_the_diff_up_to_head_whatever_the_work_tree_holds(self) -> None: text = "def f():\n\treturn 1\n\n\ndef g():\n\treturn 2\n" self.base = self.repo.commit({"gone.py": text}) head = self.repo.commit({"gone.py": text.replace("return 2", "return 3")}) pathlib.Path(self.repo.folder, "gone.py").write_text("def new():\n\treturn 0\n\n\n" + text.replace("return 2", "return 3"), encoding="utf-8") self.assertEqual(diff_parts.touched(self.base, head, self.repo.folder, set()), {"gone.py": (Part("g"),)}) def test_an_inserted_function_or_section_does_not_name_its_neighbours(self) -> None: text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n\ndef c():\n\treturn 3\n" self.base = self.repo.commit({"m.py": text, "m.md": "# A\ntext\n\n## B\ntext\n", "pkg.py": "", "c.py": "# only a comment\n"}) self.assertEqual(self.touched({"m.py": text.replace("def b", "def new():\n\treturn 9\n\n\ndef b"), "m.md": "# A\ntext\n\n## B\ntext\n\n## End\nmore\n", "pkg.py": "def f():\n\treturn 1\n", "c.py": "# only a comment\n\n\ndef g():\n\treturn 1\n"}), { "c.py": (Part("g"),), "m.md": (Part("## End"),), "m.py": (Part("new"),), "pkg.py": (Part("f"),), }) def test_a_deleted_function_does_not_name_the_next_one(self) -> None: text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n\ndef c():\n\treturn 3\n" self.base = self.repo.commit({"m.py": text}) self.assertEqual(self.touched({"m.py": text.replace("def b():\n\treturn 2\n\n\n", "")}), {"m.py": (Part("b"),)}) def test_a_change_of_blank_lines_alone_names_the_part_they_go_with(self) -> None: self.assertEqual(self.touched({"a.py": PYTHON.replace("\n\nclass Plan", "\n\n\nclass Plan"), "a.md": MARKDOWN.replace("Text.\n", "Text.\n\n")}), {"a.md": (Part("# Title"),), "a.py": (Part("Plan"),)}) def test_reads_text_that_is_not_utf_8(self) -> None: self.repo.commit({"n.md": b"# T\ncaf\xe9\n"}) self.base = self.repo.run("rev-parse", "HEAD") self.assertEqual(self.touched({"n.md": b"# T\ncaf\xe9s\n"}), {"n.md": (Part("# T"),)}) def test_an_unknown_base_is_a_failure(self) -> None: self.assertIsInstance(diff_parts.touched("nope", "HEAD", self.repo.folder, set()), Failure) class EntryTest(unittest.TestCase): def test_appends_the_prediction_beside_the_touched_parts(self) -> None: store = MemoryStore("# Touch predictions\n\n## Chunk 1, 2026-01-01T00:00:00Z, at aaaaaaa\n\nPredicted: none.\n\nTouched: none.\n") failed = record.append(store, [373, 374], record.entry([373, 374], "2026-11-15T10:00:00Z", "abc1234", {"a.py": (Part("f", small=True),)}, {"a.py": (Part("f"), Part("g")), "b.md": ()})) self.assertIsNone(failed) self.assertEqual(store.read(), "# Touch predictions\n\n## Chunk 1, 2026-01-01T00:00:00Z, at aaaaaaa\n\nPredicted: none.\n\nTouched: none.\n\n## Chunk 373, 374, 2026-11-15T10:00:00Z, at abc1234\n\nPredicted:\n\n- `a.py`: `f` (small)\n\nTouched:\n\n- `a.py`: `f`, `g`\n- `b.md`\n") def test_starts_an_empty_record_with_its_title(self) -> None: store = MemoryStore("") record.append(store, [5], record.entry([5], "2026-11-15T10:00:00Z", "abc1234", None, {})) self.assertEqual(store.read(), "# Touch predictions\n\n## Chunk 5, 2026-11-15T10:00:00Z, at abc1234\n\nPredicted: none.\n\nTouched: none.\n") def test_replaces_the_entry_of_the_same_items_and_keeps_the_others(self) -> None: store = MemoryStore("") for items, head in (([5], "aaaaaaa"), ([5, 6], "bbbbbbb"), ([7], "ccccccc"), ([5], "ddddddd"), ([5, 6], "eeeeeee")): record.append(store, items, record.entry(items, "2026-11-15T10:00:00Z", head, None, {})) self.assertEqual([line.split(" at ")[1] for line in store.text.splitlines() if line.startswith("## ")], ["ccccccc", "ddddddd", "eeeeeee"]) self.assertEqual(store.text.count("\n\n\n"), 0) def test_writes_over_the_version_it_read(self) -> None: store = MemoryStore("", version=3) record.append(store, [5], "## Chunk 5, 2026-01-01T00:00:00Z, at aaaaaaa\n") self.assertEqual(store.overs, ["3"]) def test_a_record_that_cannot_be_read_is_a_failure(self) -> None: self.assertEqual(record.append(MemoryStore(fails="no disk"), [5], "x"), Failure("no disk")) class RecordCommandTest(unittest.TestCase): """`touch-predictions record`, run as a program in a configured checkout on a chunk's branch.""" APP = "def run():\n\treturn 1\n\n\ndef stop():\n\treturn 2\n" TODO = "# todo\n\n## Scoring\n\n`Score = 100 * V / (2**S + 8)`\n\n`Bar = 0.1`\n\n`Next ID = 9`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 3 | 0.2.0 | | | **Do three.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n| 4 | 0.2.0 | | | **Do four.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n\n## Details\n\n### 3. Do three.\n\nTouches:\n\n- `app.py`: `run`\n\n### 4. Do four.\n\nNo prediction.\n" def setUp(self) -> None: made = tempfile.TemporaryDirectory() self.addCleanup(made.cleanup) self.home = pathlib.Path(made.name, "home") self.checkout = pathlib.Path(made.name, "proj") self.checkout.mkdir() self.repo = Repo(str(self.checkout)) self.config = write_config(self.home, self.checkout) / "config.toml" self.repo.commit({"app.py": self.APP, "todo.md": self.TODO}) self.repo.run("checkout", "-q", "-b", "item-3") self.repo.commit({"app.py": self.APP.replace("return 1", "return 3").replace("return 2", "return 4"), "todo.md": self.TODO + "\nMore.\n", "CHANGELOG.md": "- New.\n"}) def record(self, *args: str) -> subprocess.CompletedProcess[str]: tool = pathlib.Path(__file__).resolve().parents[1] / "touch-predictions" return subprocess.run([sys.executable, str(tool), *args], cwd=self.checkout, env={**isolated_env(), "HOME": str(self.home), "GIT_CONFIG_GLOBAL": os.devnull}, capture_output=True, text=True) def set_record(self) -> pathlib.Path: self.config.write_text(self.config.read_text(encoding="utf-8") + 'touch-predictions = "checkout:docs/touch-predictions.md"\n', encoding="utf-8") return self.checkout / "docs/touch-predictions.md" def test_appends_the_items_prediction_beside_what_the_branch_touched_less_the_plan_and_records(self) -> None: path = self.set_record() ran = self.record("record", "3", "4") self.assertEqual((ran.returncode, ran.stderr), (0, "")) self.assertEqual(ran.stdout, f"Recorded what chunk 3, 4 was predicted to touch, and what it touched, in {path}.\n") head = self.repo.run("rev-parse", "--short", "HEAD") entry = re.fullmatch(rf"# Touch predictions\n\n## Chunk 3, 4, \d{{4}}-\d\d-\d\dT\d\d:\d\d:\d\dZ, at {head}\n\n(.*)", path.read_text(encoding="utf-8"), re.S) assert entry is not None self.assertEqual(entry.group(1), "Predicted:\n\n- `app.py`: `run`\n\nTouched:\n\n- `app.py`: `run`, `stop`\n") def test_stamps_the_entry_at_the_clock_it_is_handed(self) -> None: path = self.set_record() config = located(str(self.checkout), self.home) assert isinstance(config, ProjectConfig), config self.assertNotIsInstance(main.recorded(config, [3], now=lambda: 0.0), Failure) self.assertIn("## Chunk 3, 1970-01-01T00:00:00Z, at ", path.read_text(encoding="utf-8")) def test_a_second_run_replaces_the_entry_and_leaves_the_record_out_of_what_was_touched(self) -> None: path = self.set_record() self.record("record", "3") self.repo.commit({}) self.assertEqual(self.record("record", "3").returncode, 0) text = path.read_text(encoding="utf-8") self.assertEqual(text.count("## Chunk 3, "), 1) self.assertNotIn("touch-predictions.md", text) def test_names_a_chunk_by_its_ids_in_order_each_once(self) -> None: path = self.set_record() self.record("record", "3", "4") ran = self.record("record", "4", "3", "4") self.assertEqual(ran.stdout, f"Recorded what chunk 3, 4 was predicted to touch, and what it touched, in {path}.\n") self.assertEqual(re.findall(r"^## Chunk ([\d, ]+), \d{4}", path.read_text(encoding="utf-8"), re.M), ["3, 4"]) def test_records_nothing_where_the_config_leaves_the_setting_out(self) -> None: ran = self.record("record", "3") self.assertEqual((ran.returncode, ran.stdout), (0, "The project's config sets no `touch-predictions`, so nothing is recorded.\n")) self.assertFalse((self.checkout / "docs").exists()) def test_fails_on_an_item_the_plan_lacks_a_list_it_cannot_read_and_other_arguments(self) -> None: path = self.set_record() for args, said in ((("record", "8"), "touch-predictions: the plan holds no item 8\n"), (("record",), "usage: touch-predictions record ...\n"), (("record", "x"), "usage: touch-predictions record ...\n"), ((), "usage: touch-predictions record ...\n")): with self.subTest(args): ran = self.record(*args) self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (1, "", said)) (self.checkout / "todo.md").write_text(self.TODO.replace("- `app.py`: `run`", "- app.py"), encoding="utf-8") ran = self.record("record", "3") self.assertEqual(ran.returncode, 1) self.assertTrue(ran.stderr.startswith("touch-predictions: item 3: the bullet '- app.py'"), ran.stderr) self.assertFalse(path.exists()) if __name__ == "__main__": unittest.main()