diff --git a/bin/project_config/settings.py b/bin/project_config/settings.py index 61120581..be2757ab 100644 --- a/bin/project_config/settings.py +++ b/bin/project_config/settings.py @@ -14,14 +14,26 @@ SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehensio # They also picked a prefix over bare relative paths: each line says its own place, and a relative path with no prefix fails instead of landing somewhere by default. SPELLING = '"checkout:" for a path in the checkout, "folder:" for one in the config\'s folder, or a path that starts with / or ~/' +# Where a project keeps a file, for a tool that reads it at a commit: a path from the checkout's top, as git names it; or, outside the checkout, the file itself, which the tool reads as it stands, since git holds no version of it. +Place = str | pathlib.Path + @dataclasses.dataclass(frozen=True) class ProjectConfig: - """folder is `~/.claude-projects/`, and paths holds each of SETTINGS as an absolute path.""" + """folder is `~/.claude-projects/`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path.""" key: str folder: pathlib.Path + top: pathlib.Path paths: dict[str, pathlib.Path] + def tracked(self, setting: str) -> str | None: + """setting's path from top, as git names a file in a commit; None where the config puts it outside the checkout, where git holds no version of it.""" + path = self.paths[setting] + return path.relative_to(self.top).as_posix() if path.is_relative_to(self.top) else None + + def place(self, setting: str) -> Place: + return self.tracked(setting) or self.paths[setting] + def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure: """The config that names main, the project's main checkout. @@ -49,7 +61,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo ] if faults: return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}.") - return ProjectConfig(file.parent.name, file.parent, {name: path for name, path in paths.items() if path}) + return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}) def read(file: pathlib.Path, home: pathlib.Path) -> tuple[pathlib.Path, dict[str, object]] | Failure: diff --git a/bin/project_config/test_project_config.py b/bin/project_config/test_project_config.py index 7cf631c6..51c4a505 100644 --- a/bin/project_config/test_project_config.py +++ b/bin/project_config/test_project_config.py @@ -88,6 +88,15 @@ class LoadTest(ConfigCase): assert isinstance(found, ProjectConfig), found self.assertEqual(found.paths["changelog"], worktree / "CHANGELOG.md") + def test_names_a_file_in_the_checkout_as_git_does_and_none_outside_it(self) -> None: + self.write("acme", CLIENT.replace("folder:docs/decisions.md", "checkout:project/decisions.md")) + worktree = self.home / "code" / "acme-billing-item-3" + found = load(worktree, self.checkout, self.home) + assert isinstance(found, ProjectConfig), found + self.assertEqual(found.tracked("changelog"), "CHANGELOG.md") + self.assertEqual(found.tracked("decisions"), "project/decisions.md") + self.assertIsNone(found.tracked("plan"), "the config's folder is outside the checkout") + def test_an_absolute_checkout_and_path_are_taken_as_written(self) -> None: self.write("acme", CLIENT.replace("~/code/acme-billing", str(self.checkout)).replace("~/.claude/principles", "/srv/principles")) found = load(self.checkout, self.checkout, self.home) diff --git a/bin/rank_todo.py b/bin/rank_todo.py index efbbbc2f..4894a270 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -3,8 +3,9 @@ usage: rank_todo.py [--check] [todo.md] -Reads todo.md (default: ./todo.md); the goals file, which todo.md's project config sets as -goals-and-audience; and docs/decisions.md and docs/comprehension-history.md where they exist. +Run inside a checkout. Reads four files at the paths the project's config names, which +`project-config` prints: todo.md, its plan, or else the file given; the goals file; and +docs/decisions.md and docs/comprehension-history.md where they exist. Rewrites each item's Score from the formula and sorts the items by release; within a release, question rows come first, then security rows, then the rest, each group by score from highest, then by ID. Then it moves each blocker, an item another's Blocked by cell names, that ranks below @@ -91,6 +92,7 @@ import pathlib import sys from failure import Failure +from project_config.main import located from release_plan import plan_file @@ -101,13 +103,16 @@ def main(argv: list[str]) -> int: args = parse_args(argv) if isinstance(args, Failure): return fail(args) - check, todo = args + config = located(None, pathlib.Path.home()) + if isinstance(config, Failure): + return fail(config) + check, todo = args[0], args[1] or config.paths["plan"] if check: - failures = plan_file.check_failures(todo) + failures = plan_file.check_failures(todo, config) for line in failures: print(line, file=sys.stderr) return 1 if failures else 0 - ranked = plan_file.rank_file(todo) + ranked = plan_file.rank_file(todo, config) if isinstance(ranked, Failure): return fail(ranked) return 1 if ranked.under_bar else 0 @@ -118,11 +123,11 @@ def fail(failure: Failure) -> int: return 1 -def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure: +def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path | None] | Failure: paths = [arg for arg in argv if arg != "--check"] if len(paths) > 1 or any(path.startswith("-") for path in paths): return Failure(f"rank_todo.py: cannot read the arguments {' '.join(argv)}; usage: rank_todo.py [--check] [todo.md]") - return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md") + return "--check" in argv, pathlib.Path(paths[0]) if paths else None if __name__ == "__main__": diff --git a/bin/release_plan/plan_file.py b/bin/release_plan/plan_file.py index 7d633bce..ba6dc7ef 100644 --- a/bin/release_plan/plan_file.py +++ b/bin/release_plan/plan_file.py @@ -1,17 +1,16 @@ -"""todo.md on disk: read it with the project files ranking reads, then rank or check it, write it back, and print what ranking reports.""" +"""todo.md on disk: read it with the files ranking reads, at the paths the project's config names, then rank or check it, write it back, and print what ranking reports.""" import pathlib import sys from failure import Failure -from project_config.main import goals_file -from review_rules.comprehension_history import HISTORY +from project_config.settings import ProjectConfig from release_plan.ranking import rank, Ranked from records.file_writes import replace_file -def rank_file(todo: pathlib.Path) -> Ranked | Failure: +def rank_file(todo: pathlib.Path, config: ProjectConfig) -> Ranked | Failure: """Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr.""" - texts = read_all(todo) + texts = read_all(todo, config) if isinstance(texts, Failure): return texts ranked = rank(*texts) @@ -29,9 +28,9 @@ def print_report(todo: pathlib.Path, ranked: Ranked) -> None: print(f"{todo}: {line}", file=sys.stderr) -def check_failures(todo: pathlib.Path) -> list[str]: +def check_failures(todo: pathlib.Path, config: ProjectConfig) -> list[str]: """Why --check fails on todo, empty when it passes.""" - texts = read_all(todo) + texts = read_all(todo, config) if isinstance(texts, Failure): return [texts.reason] ranked = rank(*texts) @@ -41,16 +40,12 @@ def check_failures(todo: pathlib.Path) -> list[str]: return unranked + [f"{todo}: {line}" for line in ranked.under_bar] -def read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure: - """todo.md, the goals file its project's config names, and its docs/decisions.md and docs/comprehension-history.md. The last two are empty when missing; a missing todo.md, config or goals file is a Failure.""" +def read_all(todo: pathlib.Path, config: ProjectConfig) -> tuple[str, str, str, str] | Failure: + """todo, the plan, then the goals file, the decision log and the comprehension history that config names. The last two are empty when missing; a missing plan or goals file is a Failure.""" plan = read(todo, "every project keeps a todo.md, and rank_todo.py --help shows one") if isinstance(plan, Failure): return plan - # Looked up after todo.md is read, so a mistyped path fails naming todo.md, not in git's words. - goals = goals_file(str(todo.parent), pathlib.Path.home()) - if isinstance(goals, Failure): - return goals - goals_text, decisions, history = read(goals, "rank_todo.py weighs goals from the file the project's config names as goals-and-audience"), read(todo.parent / "docs" / "decisions.md", None), read(todo.parent / HISTORY, None) + goals_text, decisions, history = read(config.paths["goals-and-audience"], "rank_todo.py weighs goals from the file the project's config names as goals-and-audience"), read(config.paths["decisions"], None), read(config.paths["comprehension-history"], None) if isinstance(goals_text, Failure): return goals_text if isinstance(decisions, Failure): diff --git a/bin/release_plan/release_standing.py b/bin/release_plan/release_standing.py index 16d1804b..535235d0 100644 --- a/bin/release_plan/release_standing.py +++ b/bin/release_plan/release_standing.py @@ -1,9 +1,11 @@ """How the plan stands to the last release cut: the next release, whether work has landed towards it, and whether it is to be planned, reviewed or cut; and, from that standing, the item the next chunk takes first, with what the default branch holds for the pick.""" import dataclasses +import pathlib from git_cli.git_repo import commits_since, file_at, git, Git from release_plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged from failure import Failure +from project_config.settings import Place from release_plan.todo_table import Item, items, next_item, renames from records.markdown_text import sections @@ -90,21 +92,35 @@ class DefaultPlan: cut: LastCut -def default_plan(root: str, ref: str, run: Git = git) -> DefaultPlan: - """What ref, the default branch as last fetched, holds for the pick, read in the checkout at root through run.""" +def default_plan(root: str, ref: str, plan: Place, changelog: Place, run: Git = git) -> DefaultPlan: + """What ref, the default branch as last fetched, holds for the pick, read in the checkout at root through run. plan and changelog are where the project's config puts todo.md and CHANGELOG.md.""" tag = newest_tag(root, merged_into=ref, run=run) - changelog = file_at(ref, "CHANGELOG.md", root, run) - after = dated_cut(tag, changelog) - since = tag if after is None else heading_commit(after, ref, root, run) + changes = held_at(ref, changelog, root, run) + after = dated_cut(tag, changes) + since = tag if after is None else heading_commit(after, ref, changelog, root, run) commits = since if isinstance(since, Failure) else commits_since(since, ref, root, run) reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, after, run) - return DefaultPlan(file_at(ref, "todo.md", root, run), LastCut(tag, changelog, commits, todos_since(tag, ref, root, run), reviewed)) + return DefaultPlan(held_at(ref, plan, root, run), LastCut(tag, changes, commits, todos_since(tag, ref, plan, root, run), reviewed)) -def heading_commit(release: Release, ref: str, cwd: str, run: Git = git) -> str | None | Failure: - """The oldest commit on ref that added release's dated heading to CHANGELOG.md, which a branch with no tag counts the unreleased commits from; None where git finds none.""" +def held_at(revision: str, place: Place, cwd: str, run: Git = git) -> str | Failure: + """The text of the file at place: at revision where it is in the checkout, else as it stands. Empty where there is no such file.""" + if isinstance(place, str): + return file_at(revision, place, cwd, run) + try: + return place.read_text(encoding="utf-8") + except FileNotFoundError: + return "" + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"cannot read {place}: {failure}") + + +def heading_commit(release: Release, ref: str, changelog: Place, cwd: str, run: Git = git) -> str | None | Failure: + """The oldest commit on ref that added release's dated heading to CHANGELOG.md, which a branch with no tag counts the unreleased commits from; None where git finds none, as for a changelog outside the checkout.""" + if isinstance(changelog, pathlib.Path): + return None # -G matches the heading line itself, so a changelog entry that quotes the heading doesn't count. - added = run("log", "--reverse", "--format=%H", "-G", dated_heading_pattern(release), ref, "--", "CHANGELOG.md", cwd=cwd) + added = run("log", "--reverse", "--format=%H", "-G", dated_heading_pattern(release), ref, "--", changelog, cwd=cwd) return added if isinstance(added, Failure) else next(iter(added.split()), None) @@ -120,16 +136,21 @@ def release_reviewed(tag: str | None, ref: str, cwd: str, after: Release | None return any(after is None or ((named := parsed(review)) is not None and named > after) for review in reviews) -def todos_since(tag: str | None | Failure, ref: str, cwd: str, run: Git = git) -> list[str] | Failure: - """LastCut.todos_since, read from ref in cwd. A pull request's own commits do not count, only the merge that landed it: --first-parent.""" +def todos_since(tag: str | None | Failure, ref: str, plan: Place, cwd: str, run: Git = git) -> list[str] | Failure: + """LastCut.todos_since, read from ref in cwd. A pull request's own commits do not count, only the merge that landed it: --first-parent. + + A plan outside the checkout has no commits, so only its text as it stands counts.""" if isinstance(tag, Failure): return [] - changed = run("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}" if tag else ref, "--", "todo.md", cwd=cwd) + if isinstance(plan, pathlib.Path): + text = held_at(ref, plan, cwd, run) + return text if isinstance(text, Failure) else [text] + changed = run("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}" if tag else ref, "--", plan, cwd=cwd) if isinstance(changed, Failure): return changed texts = [] for commit in [*([tag] if tag else []), *changed.split()]: - text = file_at(commit, "todo.md", cwd, run) + text = file_at(commit, plan, cwd, run) if isinstance(text, Failure): return text texts.append(text) diff --git a/bin/release_plan/test_ranking.py b/bin/release_plan/test_ranking.py index 5bd6be78..949a3b83 100644 --- a/bin/release_plan/test_ranking.py +++ b/bin/release_plan/test_ranking.py @@ -8,6 +8,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from project_config.main import located from project_config.test_project_config import configured from failure import Failure from release_plan import plan_file, ranking @@ -338,7 +339,7 @@ class CodeHealth(unittest.TestCase): self.assertIsInstance(todo_table.parse_moves("1", "code health by 11"), Failure) self.assertIsInstance(todo_table.parse_moves("1", "health by 4"), Failure) - def test_reads_the_history_beside_todo_md_and_the_goals_the_config_names(self): + def test_reads_the_history_and_the_goals_the_config_names(self): with tempfile.TemporaryDirectory() as temp: todo = pathlib.Path(temp, "todo.md") todo.write_text(self.todo) @@ -347,7 +348,7 @@ class CodeHealth(unittest.TestCase): pathlib.Path(temp, "docs").mkdir() pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00")) with contextlib.redirect_stderr(io.StringIO()): - ranked = plan_file.rank_file(todo) + ranked = plan_file.rank_file(todo, located(temp, pathlib.Path.home())) self.assertIsInstance(ranked, ranking.Ranked) self.assertEqual(ranked.under_bar, []) self.assertIn("| code health by 1 | 25.4 |", todo.read_text()) diff --git a/bin/release_plan/test_release_standing.py b/bin/release_plan/test_release_standing.py index 7b6108f0..c6f64a72 100644 --- a/bin/release_plan/test_release_standing.py +++ b/bin/release_plan/test_release_standing.py @@ -140,8 +140,8 @@ class ChunkItem(unittest.TestCase): run("commit", "-q", "--allow-empty", "-m", "Ship item 1") pathlib.Path(repo, "todo.md").write_text(newest) run("commit", "-q", "-a", "-m", "Ship item 1 for good") - self.assertEqual(release_standing.todos_since(None, "main", repo), [first, newest]) - self.assertEqual(release_standing.todos_since(Failure("tags unreadable"), "main", repo), []) + self.assertEqual(release_standing.todos_since(None, "main", "todo.md", repo), [first, newest]) + self.assertEqual(release_standing.todos_since(Failure("tags unreadable"), "main", "todo.md", repo), []) def test_finds_a_release_review_among_the_commits_since_the_cut(self): repo = tempfile.mkdtemp() @@ -157,7 +157,7 @@ class ChunkItem(unittest.TestCase): self.assertIs(release_standing.release_reviewed("v0.1.0", "main", repo), True) self.assertIs(release_standing.release_reviewed(None, "main", repo), True) self.assertIsInstance(release_standing.release_reviewed("v9.9.9", "main", repo), Failure) - self.assertEqual(release_standing.default_plan(repo, "main").cut.reviewed, True) + self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.reviewed, True) def test_counts_no_release_review_of_a_release_cut_under_a_dated_heading_on_a_branch_with_no_tag(self): repo = tempfile.mkdtemp() @@ -168,13 +168,13 @@ class ChunkItem(unittest.TestCase): pathlib.Path(repo, "CHANGELOG.md").write_text("# Changelog\n\n## 0.0.1 - 2026-10-03\n") run("add", "CHANGELOG.md") run("commit", "-q", "-m", "Cut 0.0.1") - self.assertIs(release_standing.default_plan(repo, "main").cut.reviewed, False, "that review reviewed 0.0.1, which is cut") - self.assertEqual(release_standing.default_plan(repo, "main").cut.commits, 0, "no commit follows the one that cut 0.0.1") - self.assertEqual(release_standing.chunk_item([], release_standing.default_plan(repo, "main").cut), release_standing.Unplanned(None)) + self.assertIs(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.reviewed, False, "that review reviewed 0.0.1, which is cut") + self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.commits, 0, "no commit follows the one that cut 0.0.1") + self.assertEqual(release_standing.chunk_item([], release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut), release_standing.Unplanned(None)) run("commit", "-q", "--allow-empty", "-m", "Ship item 2") - self.assertEqual(release_standing.default_plan(repo, "main").cut.commits, 1) + self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.commits, 1) run("commit", "-q", "--allow-empty", "-m", "Release review of 0.1.0") - self.assertIs(release_standing.default_plan(repo, "main").cut.reviewed, True) + self.assertIs(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.reviewed, True) def test_counts_from_the_commit_on_the_named_branch_that_first_added_the_dated_heading_to_changelog_md(self): repo = tempfile.mkdtemp() @@ -193,7 +193,7 @@ class ChunkItem(unittest.TestCase): run("commit", "-q", "--allow-empty", "-m", "Ship item 2") run("checkout", "-q", "-b", "side") run("commit", "-q", "--allow-empty", "-m", "Side work") - self.assertEqual(release_standing.default_plan(repo, "main").cut.commits, 2, "the commits after Cut 0.0.1 on main") + self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.commits, 2, "the commits after Cut 0.0.1 on main") def test_takes_the_tag_over_a_dated_heading_and_counts_every_commit_without_either(self): repo = tempfile.mkdtemp() @@ -203,16 +203,35 @@ class ChunkItem(unittest.TestCase): pathlib.Path(repo, "todo.md").write_text(HEADER + ROW.format(id=1, release="0.2.0")) run("add", "todo.md") run("commit", "-q", "-m", "Plan") - self.assertEqual(release_standing.default_plan(repo, "main").cut, release_standing.LastCut(None, "", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False)) + self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut, release_standing.LastCut(None, "", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False)) run("tag", "v0.1.0") pathlib.Path(repo, "CHANGELOG.md").write_text("# Changelog\n\n## 0.2.0 - 2026-10-03\n") run("add", "CHANGELOG.md") run("commit", "-q", "-m", "Date 0.2.0") - held = release_standing.default_plan(repo, "main") + held = release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md") self.assertEqual(held.todo, HEADER + ROW.format(id=1, release="0.2.0")) self.assertEqual(held.cut, release_standing.LastCut("v0.1.0", "# Changelog\n\n## 0.2.0 - 2026-10-03\n", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False)) self.assertEqual(release_standing.chunk_item(plan_under((0, 2, 0)), held.cut), release_standing.Next((0, 2, 0), one((0, 2, 0)))) + def test_reads_a_plan_and_a_changelog_outside_the_checkout_as_they_stand(self): + repo, folder = tempfile.mkdtemp(), pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(subprocess.run, ["rm", "-rf", repo, str(folder)]) + run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True) + run("init", "-q", "-b", "main") + pathlib.Path(repo, "todo.md").write_text(HEADER + ROW.format(id=1, release="0.9.0")) + run("add", "todo.md") + run("commit", "-q", "-m", "A todo.md the project's owners keep") + held = release_standing.default_plan(repo, "main", folder / "todo.md", folder / "CHANGELOG.md") + self.assertEqual((held.todo, held.cut), ("", release_standing.LastCut(None, "", 1, [""], False)), "neither file exists yet") + plan = HEADER + ROW.format(id=2, release="0.2.0") + (folder / "todo.md").write_text(plan) + (folder / "CHANGELOG.md").write_text("# Changelog\n\n## 0.1.0 - 2026-10-03\n") + held = release_standing.default_plan(repo, "main", folder / "todo.md", folder / "CHANGELOG.md") + self.assertEqual(held.todo, plan) + self.assertEqual(held.cut, release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 1, [plan], False)) + (folder / "todo.md").write_bytes(b"\xff") + self.assertIsInstance(release_standing.default_plan(repo, "main", folder / "todo.md", "CHANGELOG.md").todo, Failure) + def test_counts_the_changes_unreleased_since_the_last_cut_by_unreleased_entries_and_else_by_commits(self): changelog = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n" self.assertEqual(release_standing.unreleased_changes(release_standing.LastCut("v0.1.0", changelog, 5, [])), 2) diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index ab12edc2..29185874 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -889,6 +889,7 @@ class TodoRankCheck(unittest.TestCase): pathlib.Path(checkout, "bin").mkdir() pathlib.Path(checkout, "bin", "rank_todo.py").write_text(stub) pathlib.Path(checkout, "todo.md").write_text("# todo\n") + self.config = configured(self, pathlib.Path(checkout)) / "config.toml" return checkout def details(self, checkout: str) -> list[str]: @@ -915,6 +916,30 @@ class TodoRankCheck(unittest.TestCase): self.assertTrue(reasons) self.assertNotIn("own script", " ".join(reasons)) + def test_a_plan_the_config_puts_outside_the_checkout_is_checked_in_place_of_the_checkouts_todo_md(self): + checkout = self.changed_plan(f"{self.folder}/clone", self.STUB) + self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) + self.assertEqual(self.details(checkout), [], "the project has no plan yet, and the checkout's todo.md is its owners'") + (self.config.parent / "todo.md").write_text("# todo\n") + self.assertEqual(self.details(checkout), [f"own script checked {self.config.parent}/todo.md"]) + + def test_a_plan_in_a_folder_of_the_checkout_is_checked_once_it_changes(self): + checkout = self.changed_plan(f"{self.folder}/clone", self.STUB) + self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"checkout:plan/todo.md"')) + pathlib.Path(checkout, "plan").mkdir() + pathlib.Path(checkout, "plan", "todo.md").write_text("# todo\n") + self.assertEqual(self.details(checkout), [f"own script checked {checkout}/plan/todo.md"]) + git(checkout, "add", "plan") + git(checkout, "commit", "-q", "-m", "plan") + self.assertEqual(self.details(checkout), [], "committed, so unchanged") + + def test_a_checkout_with_a_todo_md_and_no_config_is_told_to_write_one(self): + checkout = self.changed_plan(self.other, self.STUB) + self.config.unlink() + self.assertEqual(self.details(checkout), [f"no config names the checkout {checkout}: write ~/.claude-projects//config.toml, as `project-config --help` shows"]) + pathlib.Path(checkout, "todo.md").unlink() + self.assertEqual(self.details(checkout), []) + class CommittedFiles(unittest.TestCase): """A git commit holds the files it would commit to the file rules, as an Edit or Write of each would be.""" diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py index 42f47b67..63734de9 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -3,6 +3,8 @@ import pathlib import subprocess import sys +from project_config.main import located +from project_config.settings import ProjectConfig from rule_hook.rules import Breach from failure import Failure from rule_hook.git import guarded_git @@ -16,18 +18,26 @@ OWN_CHECK_SECONDS = 20 def todo_breaches(directory: str, own: pathlib.Path = OWN) -> list[Breach]: + """Why the plan of directory's project is not ranked, where the plan has changed; the plan is the todo.md its config names.""" top = guarded_git(directory, "rev-parse", "--show-toplevel") - if isinstance(top, Failure) or not (pathlib.Path(top) / "todo.md").is_file(): + if isinstance(top, Failure): return [] - todo = pathlib.Path(top) / "todo.md" - return [Breach("todo-rank-check", line, top) for line in check_failures(top, todo, own)] if changed(top, todo) else [] + config = located(top, pathlib.Path.home()) + if isinstance(config, Failure): + # A checkout with a todo.md and no config is one whose config is still to write. + return [Breach("todo-rank-check", config.reason, top)] if (pathlib.Path(top) / "todo.md").is_file() else [] + todo, tracked = config.paths["plan"], config.tracked("plan") + # A plan outside the checkout has no commit to differ from, so it is checked on every call. + if not todo.is_file() or (tracked is not None and not changed(top, todo, tracked)): + return [] + return [Breach("todo-rank-check", line, top) for line in check_failures(top, todo, config, own)] -def check_failures(top: str, todo: pathlib.Path, own: pathlib.Path) -> list[str]: +def check_failures(top: str, todo: pathlib.Path, config: ProjectConfig, own: pathlib.Path) -> list[str]: """Why rank_todo.py --check fails on todo. A checkout of the repo the hook runs from checks with its own bin/rank_todo.py, so a branch that changes the table's shape is held to its own rules. Any other checkout checks with the hook's ranking: running its script would run its code before every commit.""" script = pathlib.Path(top) / "bin" / "rank_todo.py" if not script.is_file() or not same_repo(top, own): - return plan_file.check_failures(todo) + return plan_file.check_failures(todo, config) try: ran = subprocess.run([sys.executable, str(script), "--check", str(todo)], capture_output=True, cwd=top, text=True, timeout=OWN_CHECK_SECONDS) except subprocess.TimeoutExpired: @@ -45,10 +55,10 @@ def same_repo(top: str, own: pathlib.Path) -> bool: return not isinstance(theirs, Failure) and not isinstance(mine, Failure) and bool(set(theirs.split()) & set(mine.split())) -def changed(top: str, todo: pathlib.Path) -> bool: - """Whether todo.md differs from the index or the index from HEAD: any change, staged or not, since the hook runs before a `git add` earlier in the same command.""" +def changed(top: str, todo: pathlib.Path, tracked: str) -> bool: + """Whether todo, which git names tracked, differs from the index or the index from HEAD: any change, staged or not, since the hook runs before a `git add` earlier in the same command.""" # Hashed here, never by `git status`, which would run a clean filter the checkout's own config names before the call is allowed. - staged, committed = guarded_git(top, "rev-parse", ":todo.md"), guarded_git(top, "rev-parse", "HEAD:todo.md") + staged, committed = guarded_git(top, "rev-parse", f":{tracked}"), guarded_git(top, "rev-parse", f"HEAD:{tracked}") algorithm = guarded_git(top, "rev-parse", "--show-object-format") content = todo.read_bytes() worktree = hashlib.new("sha1" if isinstance(algorithm, Failure) else algorithm, b"blob %d\0" % len(content) + content).hexdigest() diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 71d68950..50343792 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -23,6 +23,7 @@ class Main(unittest.TestCase): with tempfile.TemporaryDirectory() as temp: todo = pathlib.Path(temp, "todo.md") configured(self, pathlib.Path(temp)) + self.enterContext(contextlib.chdir(temp)) todo.write_text(TODO) pathlib.Path(temp, "README.md").write_text(README) pathlib.Path(temp, "docs").mkdir() @@ -38,11 +39,30 @@ class Main(unittest.TestCase): todo.unlink() self.assertEqual(self.run_main(str(todo)), (1, f"{todo}: not found; every project keeps a todo.md, and rank_todo.py --help shows one\n")) + def test_ranks_the_plan_and_reads_the_decisions_where_the_config_puts_them(self): + with tempfile.TemporaryDirectory() as temp: + folder = configured(self, pathlib.Path(temp)) + self.enterContext(contextlib.chdir(temp)) + config = folder / "config.toml" + config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"').replace('"checkout:docs/decisions.md"', '"folder:decisions.md"')) + pathlib.Path(temp, "README.md").write_text(README) + pathlib.Path(temp, "todo.md").write_text("the project owners' own notes\n") + (folder / "todo.md").write_text(TODO) + self.assertIn("docs/decisions.md does not cite", self.run_main()[1]) + (folder / "decisions.md").write_text(DECISIONS) + self.assertEqual(self.run_main("--check")[0], 1, "the plan in the config's folder is not ranked yet") + self.assertEqual(self.run_main(), (0, "")) + self.assertEqual(self.run_main("--check"), (0, "")) + self.assertEqual(pathlib.Path(temp, "todo.md").read_text(), "the project owners' own notes\n") + (folder / "decisions.md").write_bytes(b"\xff") + self.assertEqual(self.run_main(), (1, f"{folder}/decisions.md: not UTF-8\n")) + def test_writes_the_ranked_file_yet_fails_on_an_item_under_the_bar(self): under = "item 2 scores 3.1, under the bar 4; delete it, or mark it with a reason the bar does not apply" with tempfile.TemporaryDirectory() as temp: todo = pathlib.Path(temp, "todo.md") configured(self, pathlib.Path(temp)) + self.enterContext(contextlib.chdir(temp)) todo.write_text(TODO.replace("`Bar = 2`", "`Bar = 4`")) pathlib.Path(temp, "README.md").write_text(README) pathlib.Path(temp, "docs").mkdir() @@ -54,6 +74,7 @@ class Main(unittest.TestCase): with tempfile.TemporaryDirectory() as temp: todo = pathlib.Path(temp, "todo.md") configured(self, pathlib.Path(temp)) + self.enterContext(contextlib.chdir(temp)) todo.write_text(OLD_SHAPE) pathlib.Path(temp, "README.md").write_text(README) pathlib.Path(temp, "docs").mkdir() diff --git a/bin/todo_item/main.py b/bin/todo_item/main.py index 40255d28..d388e701 100644 --- a/bin/todo_item/main.py +++ b/bin/todo_item/main.py @@ -5,22 +5,23 @@ usage: todo-item add --release --l --e --i --s [--move todo-item finish [--changelog | --no-changelog] todo-item show -All three work on the todo.md in the current folder. add and finish also use the CHANGELOG.md beside it, -and read the docs/decisions.md beside it and the goals file that todo.md's project config names. +Run inside a checkout. All three work on the project's todo.md, and name its path in what they +print. add and finish also use its CHANGELOG.md, and read its docs/decisions.md and its goals file. +Each file sits where the project's config puts it, which `project-config` prints. The cells take the format rank_todo.py --help states; the letter flags take upper case too, as --L. add takes Next ID as the item's ID and raises Next ID by one. It writes the row, with the tagline in bold and each | in it escaped, and the detail it reads from stdin, if any, under ## Details. The detail may hold no ## or ### heading. -It prints `Filed item .` It doesn't write anything where ranking fails or scores the item under the bar. +It prints `Filed item in .` It doesn't write anything where ranking fails or scores the item under the bar. finish removes the item's row and its detail. With --changelog it adds the bullet first under CHANGELOG.md's ## Unreleased, or a ## heading that says unreleased, creating the section, or the file, where missing. It refuses where that section holds ### subsections: add the bullet by hand. Where CHANGELOG.md exists, finish needs --changelog or --no-changelog, so no bullet is left out by -mistake. It prints `Finished item .` It doesn't write anything while docs/decisions.md cites the item. +mistake. It prints `Finished item in .` It doesn't write anything while docs/decisions.md cites the item. -show reads only todo.md. It prints the items table's header and divider, item 's row, and its detail +show reads only todo.md. It prints `From :`, then the items table's header and divider, item 's row, and its detail from its ### heading to the next item's, sub-headings included. It fails, saying so, where todo.md has no row for . @@ -35,6 +36,8 @@ import typing from todo_item.edits import added, finished, shown, with_bullet from release_plan.todo_table import BLOCKED_BY, MOVES from failure import Failure +from project_config.main import located +from project_config.settings import ProjectConfig from release_plan import plan_file, ranking # Each score flag, as --l or --L, and the column it fills. @@ -46,10 +49,13 @@ def main(argv: list[str], folder: pathlib.Path = pathlib.Path(), stdin: typing.T print(__doc__.strip()) return 0 args = parser().parse_args(argv) - if args.command == "show": - done = show(args, folder) + config = located(str(folder), pathlib.Path.home()) + if isinstance(config, Failure): + done: str | Failure = config + elif args.command == "show": + done = show(args, config.paths["plan"]) else: - done = add(args, folder, stdin) if args.command == "add" else finish(args, folder) + done = add(args, config, stdin) if args.command == "add" else finish(args, config) if isinstance(done, Failure): print(done.reason, file=sys.stderr) return 1 @@ -78,19 +84,19 @@ def parser() -> argparse.ArgumentParser: return parsed -def show(args: argparse.Namespace, folder: pathlib.Path) -> str | Failure: - todo = folder / "todo.md" +def show(args: argparse.Namespace, todo: pathlib.Path) -> str | Failure: try: - return shown(todo.read_text(encoding="utf-8"), args.id) + found = shown(todo.read_text(encoding="utf-8"), args.id) + return found if isinstance(found, Failure) else f"From {todo}:\n\n{found}" except OSError as failure: return Failure(f"{todo}: {failure.strerror}") except UnicodeDecodeError: return Failure(f"{todo}: not UTF-8") -def add(args: argparse.Namespace, folder: pathlib.Path, stdin: typing.TextIO) -> str | Failure: - todo = folder / "todo.md" - texts = plan_file.read_all(todo) +def add(args: argparse.Namespace, config: ProjectConfig, stdin: typing.TextIO) -> str | Failure: + todo = config.paths["plan"] + texts = plan_file.read_all(todo, config) if isinstance(texts, Failure): return texts named = {"Release": args.release, BLOCKED_BY: args.blocked_by, "Exempt": args.exempt, "Item": args.tagline, MOVES: args.moves} @@ -107,12 +113,12 @@ def add(args: argparse.Namespace, folder: pathlib.Path, stdin: typing.TextIO) -> if unwritten := plan_file.write(todo, ranked.text): return unwritten plan_file.print_report(todo, ranked) - return f"Filed item {id_}." + return f"Filed item {id_} in {todo}." -def finish(args: argparse.Namespace, folder: pathlib.Path) -> str | Failure: - todo, changelog = folder / "todo.md", folder / "CHANGELOG.md" - texts = finish_texts(args, todo, changelog) +def finish(args: argparse.Namespace, config: ProjectConfig) -> str | Failure: + todo, changelog = config.paths["plan"], config.paths["changelog"] + texts = finish_texts(args, config) if isinstance(texts, Failure): return Failure(f"not finished: {texts.reason}") ranked, news = texts @@ -121,14 +127,15 @@ def finish(args: argparse.Namespace, folder: pathlib.Path) -> str | Failure: if news is not None and (unwritten := plan_file.write(changelog, news)): return Failure(f"{unwritten.reason}; todo.md no longer holds item {args.id}, so add its bullet by hand") plan_file.print_report(todo, ranked) - return f"Finished item {args.id}." + return f"Finished item {args.id} in {todo}." -def finish_texts(args: argparse.Namespace, todo: pathlib.Path, changelog: pathlib.Path) -> tuple[ranking.Ranked, str | None] | Failure: - """What finish writes: todo ranked without item args.id, and changelog's new text, None where finish leaves it as is.""" +def finish_texts(args: argparse.Namespace, config: ProjectConfig) -> tuple[ranking.Ranked, str | None] | Failure: + """What finish writes: the plan ranked without item args.id, and the changelog's new text, None where finish leaves it as is.""" + todo, changelog = config.paths["plan"], config.paths["changelog"] if changelog.exists() and args.changelog is None and not args.no_changelog: - return Failure("CHANGELOG.md exists beside todo.md; pass --changelog , or --no-changelog where the repo doesn't publish anything") - texts = plan_file.read_all(todo) + return Failure(f"{changelog} exists; pass --changelog , or --no-changelog where the repo doesn't publish anything") + texts = plan_file.read_all(todo, config) if isinstance(texts, Failure): return texts text = finished(texts[0], args.id) diff --git a/bin/todo_item/test_todo_item.py b/bin/todo_item/test_todo_item.py index 2d60fb7c..f3ba0050 100644 --- a/bin/todo_item/test_todo_item.py +++ b/bin/todo_item/test_todo_item.py @@ -7,6 +7,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent)) +from project_config.main import located from project_config.test_project_config import configured from release_plan.test_ranking import DECISIONS, README, TODO from todo_item import edits, main @@ -31,7 +32,7 @@ class TodoItem(unittest.TestCase): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) self.folder = pathlib.Path(temp.name) - configured(self, self.folder) + self.config = configured(self, self.folder) / "config.toml" self.todo = self.folder / "todo.md" self.changelog = self.folder / "CHANGELOG.md" (self.folder / "README.md").write_text(README) @@ -52,7 +53,7 @@ class TodoItem(unittest.TestCase): return raised.exception.code def assert_ranked(self): - self.assertEqual(plan_file.check_failures(self.todo), []) + self.assertEqual(plan_file.check_failures(self.todo, located(str(self.folder), pathlib.Path.home())), []) def details(self): text = self.todo.read_text() @@ -81,7 +82,7 @@ class BadArguments(TodoItem): class Add(TodoItem): def test_takes_next_id_and_raises_it(self): - self.assertEqual(self.run_main(*ADD)[:2], (0, "Filed item 6.\n")) + self.assertEqual(self.run_main(*ADD)[:2], (0, f"Filed item 6 in {self.todo}.\n")) self.assertIn("`Next ID = 7`", self.todo.read_text()) def test_writes_the_row_with_the_tagline_bold_and_its_pipes_escaped(self): @@ -151,7 +152,7 @@ class Add(TodoItem): class Finish(TodoItem): def test_removes_the_row(self): - self.assertEqual(self.run_main("finish", "3", "--no-changelog"), (0, "Finished item 3.\n", "")) + self.assertEqual(self.run_main("finish", "3", "--no-changelog"), (0, f"Finished item 3 in {self.todo}.\n", "")) self.assertNotRegex(self.todo.read_text(), r"(?m)^\| 3 \|") def test_removes_the_detail_and_keeps_the_others(self): @@ -169,7 +170,7 @@ class Finish(TodoItem): def test_adds_the_bullet_first_under_unreleased(self): self.changelog.write_text(CHANGELOG) - self.assertEqual(self.run_main("finish", "3", "--changelog", "Runs are fast."), (0, "Finished item 3.\n", "")) + self.assertEqual(self.run_main("finish", "3", "--changelog", "Runs are fast."), (0, f"Finished item 3 in {self.todo}.\n", "")) self.assertEqual(self.changelog.read_text(), "# Changelog\n\n## Unreleased\n\n- Runs are fast.\n- Older news.\n\n## 0.1.0\n\n- First.\n") def test_creates_unreleased_above_the_first_release(self): @@ -254,12 +255,28 @@ class Show(TodoItem): def test_prints_the_header_the_row_and_the_detail(self): row = next(line for line in self.todo.read_text().split("\n") if line.startswith("| 3 |")) - self.assertEqual(self.run_main("show", "3"), (0, f"{self.HEADER}{row}\n\n### 3. Make it fast, `a | b`.\n\nFast detail.\n", "")) + self.assertEqual(self.run_main("show", "3"), (0, f"From {self.todo}:\n\n{self.HEADER}{row}\n\n### 3. Make it fast, `a | b`.\n\nFast detail.\n", "")) + + def test_works_on_the_plan_and_the_changelog_where_the_config_puts_them(self): + folder = self.config.parent + self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"').replace('"checkout:CHANGELOG.md"', '"folder:news/CHANGELOG.md"').replace('"checkout:docs/decisions.md"', '"folder:decisions.md"')) + (folder / "decisions.md").write_text(DECISIONS) + self.todo.rename(folder / "todo.md") + self.todo.write_text("the project owners' own notes\n") + (folder / "news").mkdir() + (folder / "news" / "CHANGELOG.md").write_text("# Changelog\n") + self.assertEqual(self.run_main("show", "3")[1].split("\n")[0], f"From {folder}/todo.md:") + self.assertEqual(self.run_main(*ADD)[:2], (0, f"Filed item 6 in {folder}/todo.md.\n")) + self.assertEqual(self.run_main("finish", "3"), (1, "", f"not finished: {folder}/news/CHANGELOG.md exists; pass --changelog , or --no-changelog where the repo doesn't publish anything\n")) + self.assertEqual(self.run_main("finish", "3", "--changelog", "Runs are fast."), (0, f"Finished item 3 in {folder}/todo.md.\n", "")) + self.assertIn("- Runs are fast.", (folder / "news" / "CHANGELOG.md").read_text()) + self.assertEqual(self.todo.read_text(), "the project owners' own notes\n") + self.assertFalse(self.changelog.exists()) def test_prints_the_row_alone_where_the_item_has_no_detail(self): code, out, err = self.run_main("show", "4") self.assertEqual((code, err), (0, "")) - self.assertEqual(out.split("\n")[2:], ["| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 |", ""]) + self.assertEqual(out.split("\n")[4:], ["| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 |", ""]) def test_prints_a_detail_with_a_sub_heading_whole_and_no_other_detail(self): self.todo.write_text(self.todo.read_text().replace("Fast detail.\n", "Fast detail.\n\n### Why\n\nFast tail.\n")) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 5d224e20..0eeca908 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -1856,3 +1856,20 @@ Read most (opens and searches): - `bin/project_config/settings.py` 2 - `rules/decisions.md` 2 - `rules/todo-items.md` 2 + +## Reading cost, chunk 318e45cb8bb1, finished 2026-11-12T23:34:13Z + +269384 new input tokens before the first commit. + +Read most (opens and searches): + +- `CLAUDE.md` 18 +- `bin/rank_todo.py` 14 +- `bin/loop_claude/test_black_box.py` 7 +- `rules/todo-items.md` 7 +- `bin/larv_review/test_larv_review.py` 6 +- `README.md` 5 +- `bin/chunk_preflight/test_chunk_preflight.py` 5 +- `bin/release_plan/test_ranking.py` 5 +- `bin/rule_hook/test_rule_hook.py` 5 +- `bin/judge_replay/test_judge_replay.py` 4