Files
claude-config/bin/chunk_preflight/test_chunk_preflight.py
T

719 lines
40 KiB
Python

import dataclasses
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.templates import BRANCH
from chunk_preflight.gathered import CarriedOver, Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
from chunk_preflight import choices
from failure import Failure
from chunk_preflight.choices import forge_of, worktree_add
from test_env import isolated_env
from release_plan.release_standing import LastCut, UNSEEN_RELEASES
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
from chunk_preflight.facts import open_pulls, render
from plan_store.stores import plan_of
from project_config.test_project_config import write_config
BIN = pathlib.Path(__file__).resolve().parents[1]
README = "# Project\n\n## Goals\n\n**Void:** code health, since the plan's scores weigh goal 1 alone.\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n"
# Item 3 is the next release's first item that does not wait; 7 waits only on 3, 5 is a question, 8 waits on 5, 9 is in a later release.
TODO = """# todo
## Scoring
`Score = 100 * V / (2**S + 8)`
`Bar = 0.1`
`Next ID = 10`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 5 | 0.2.0 | | question | **Ask first.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |
| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |
| 7 | 0.2.0 | 3 | | **Do the thing after.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |
| 8 | 0.2.0 | 5 | | **Do the answered thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |
| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |
## Details
### 3. Do the next thing.
Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.
"""
# The plan once item 3 has shipped: item 7 no longer waits, and its detail names the files.
SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.")
# The plan once release 0.2.0 has shipped all its items: only release 0.3.0's item 9 is left.
LATER = TODO[:TODO.index("| 5 |")] + "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
# Item 9's row, the only one under release 0.3.0.
NINTH = "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
# A plan whose release 0.2.0 holds item 3 alone, before release 0.3.0's item 9.
SHIPPED_BUT_3 = TODO[:TODO.index("| 5 |")] + "| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n" + NINTH
# An items table that holds no row.
EMPTY = TODO[:TODO.index("| 5 |")]
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
# What the preflight reads of the last release: tag v0.1.0, two entries under ## Unreleased, and 4 commits since the tag.
CUT = LastCut("v0.1.0", CHANGELOG, 4, [])
# Two open pull requests, as `tea pulls list --fields index,head,url --output tsv` prints them; anything else exits 1.
FAKE_TEA = "#!/bin/sh\n[ \"$*\" = 'pulls list --fields index,head,url --output tsv' ] || exit 1\nprintf 'index\\thead\\turl\\n12\\titem-7\\thttps://forge/pulls/12\\n13\\tother\\thttps://forge/pulls/13\\n'\n"
# Item 3's open pull request, as `gh pr list` prints it through the preflight's template; any other arguments exit 1.
FAKE_GH = """#!PYTHON
import sys
if sys.argv[1:] != ["pr", "list", "--head", "item-3", "--json", "number,url", "--template", "{{range .}}{{.number}}\\t{{.url}}\\n{{end}}"]:
sys.exit(1)
print("12\\thttps://github.com/o/r/pull/12")
""".replace("PYTHON", sys.executable)
class Repo:
"""An origin with a tagged release, a clone of it at <temp>/proj, and a fake tea and gh on PATH."""
def __init__(self, test, todo=TODO, origin="origin.git", changelog=CHANGELOG):
temp = tempfile.TemporaryDirectory()
test.addCleanup(temp.cleanup)
self.temp = pathlib.Path(os.path.realpath(temp.name))
self.origin = self.temp / origin
self.root = self.temp / "proj"
self.fake = self.temp / "fake-bin"
self.fake.mkdir()
for name, script in (("gh", FAKE_GH), ("tea", FAKE_TEA)):
(self.fake / name).write_text(script)
(self.fake / name).chmod(0o755)
(self.fake / "git").symlink_to(shutil.which("git"))
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "HOME": str(self.temp / "home"), "PATH": str(self.fake), "LOOP_CLAUDE_TRANSCRIPTS": str(self.temp / "archive")}
self.git(self.temp, "init", "--quiet", "--bare", "--initial-branch=main", str(self.origin))
self.git(self.temp, "clone", "--quiet", str(self.origin), str(self.root))
write_config(self.temp / "home", self.root)
self.write(self.root, "README.md", README)
self.write(self.root, "src/app.py", "def run():\n\treturn 1\n\n")
self.commit(self.root, "start")
self.git(self.root, "tag", "v0.1.0")
self.write(self.root, "CHANGELOG.md", changelog)
if todo:
self.write(self.root, "todo.md", todo)
self.commit(self.root, "plan")
self.git(self.root, "push", "--quiet", "origin", "main", "v0.1.0")
def git(self, cwd, *args):
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=cwd, env=self.env, text=True).stdout
def write(self, root, path, text):
(root / path).parent.mkdir(parents=True, exist_ok=True)
(root / path).write_text(text)
def commit(self, root, title):
self.git(root, "add", "-A")
self.git(root, "commit", "--quiet", "-m", title)
def push_from_elsewhere(self, path, text):
"""Pushes a change to path from another clone, leaving the checkout behind origin."""
other = self.temp / "other"
self.git(self.temp, "clone", "--quiet", str(self.origin), str(other))
self.write(other, path, text)
self.commit(other, "elsewhere")
self.git(other, "push", "--quiet", "origin", "main")
def stub_git(self, arm):
"""Puts a git on PATH that runs arm, a shell case arm, on its arguments, and the real git on any others."""
stub = self.fake / "git"
stub.unlink()
stub.write_text(f'#!/bin/sh\ncase "$*" in\n{arm}\nesac\nexec {shutil.which("git")} "$@"\n')
stub.chmod(0o755)
def preflight(self, *args, **env):
return subprocess.run([sys.executable, str(BIN / "chunk-preflight"), *args], capture_output=True, cwd=self.root, env={**self.env, **env}, text=True, timeout=120)
class ChunkPreflightTool(unittest.TestCase):
def test_reads_a_plan_outside_the_checkout_as_it_stands_and_names_where_the_config_puts_each_file(self):
repo = Repo(self)
folder = repo.temp / "home" / ".claude-projects" / "proj"
config = folder / "config.toml"
config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"'))
(folder / "todo.md").write_text(SHIPPED)
done = repo.preflight("--worktree")
self.assertEqual(done.returncode, 0, done.stderr)
worktree = repo.temp / "proj-item-7"
self.assertIn("item 7, L 1, E + I 2", done.stdout, "origin's todo.md still holds item 3, which the plan in the config's folder does not")
self.assertIn(f"- The project's config puts its files and plan at: plan {folder}/todo.md; working-rules {worktree}/AGENTS.md; decisions {worktree}/docs/decisions.md; ", done.stdout)
self.assertIn("`rank_todo.py --check` exited 0", done.stdout)
self.assertIn(f"- {UNSEEN_RELEASES}\n", done.stdout)
config.unlink()
refused = repo.preflight("--worktree")
self.assertEqual((refused.returncode, refused.stdout), (1, ""))
self.assertIn(f"no config names the checkout {repo.root}", refused.stderr)
def test_names_the_branch_and_the_worktree_by_the_configs_template_and_states_the_language_and_templates(self):
repo = Repo(self)
repo.push_from_elsewhere("todo.md", SHIPPED)
plain = repo.preflight()
self.assertIn("- The project's config sets: language English; commit-title {summary}; pull-request-title {summary}; branch item-{id}.\n", plain.stdout)
config = repo.temp / "home" / ".claude-projects" / "proj" / "config.toml"
config.write_text(config.read_text() + 'language = "Swedish"\ncommit-title = "PAY-{id} - {summary}"\nbranch = "feature/PAY-{id}"\n')
done = repo.preflight("--worktree")
self.assertEqual(done.returncode, 0, done.stderr)
worktree = repo.temp / "proj-feature-PAY-7"
self.assertEqual(repo.git(worktree, "rev-parse", "--abbrev-ref", "HEAD").strip(), "feature/PAY-7")
self.assertIn("- Open pull requests from feature/PAY-7: ", done.stdout)
self.assertIn("- The project's config sets: language Swedish; commit-title PAY-{id} - {summary}; pull-request-title {summary}; branch feature/PAY-{id}.\n", done.stdout)
def test_reads_the_fetched_default_branchs_plan_and_makes_the_items_worktree_off_it_leaving_the_checkout_as_it_was(self):
repo = Repo(self)
repo.push_from_elsewhere("todo.md", SHIPPED)
# Claude Code rewrites tracked files, such as settings.json, so a checkout behind origin often holds changes.
repo.write(repo.root, "todo.md", TODO + "\nA change of the checkout's own.\n")
head = repo.git(repo.root, "rev-parse", "HEAD")
done = repo.preflight("--worktree")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertEqual(repo.git(repo.root, "rev-parse", "HEAD"), head)
worktree = repo.temp / "proj-item-7"
self.assertEqual(repo.git(worktree, "rev-parse", "--abbrev-ref", "HEAD").strip(), "item-7")
self.assertEqual(repo.git(worktree, "rev-parse", "HEAD"), repo.git(repo.root, "rev-parse", "origin/main"))
for fact in (
"item 7, L 1, E + I 2",
str(worktree),
"item-7, made off origin/main",
"#12 https://forge/pulls/12",
"`src/app.py`: 3 lines",
"`src`: 1 file",
"`rank_todo.py --check` exited 0",
"`larv-review needs-scoring-run 7` exited 0",
"`reading-cost` exited 0",
"`larv-review places` exited 0",
f"{worktree}/docs/reading-cost.md",
):
with self.subTest(fact=fact):
self.assertIn(fact, done.stdout)
self.assertNotIn("#13", done.stdout)
self.assertNotIn("`gone.py`:", done.stdout)
def test_names_no_item_and_makes_no_worktree_where_the_release_after_the_last_cut_has_emptied(self):
for changelog, reviewed, fact in ((CHANGELOG, False, "release review is due"), (CHANGELOG, True, "finished and ready to cut"), ("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n", False, "planned first")):
with self.subTest(fact=fact):
repo = Repo(self, changelog=changelog)
repo.write(repo.root, "todo.md", LATER)
repo.commit(repo.root, "ship 0.2.0")
if reviewed:
repo.git(repo.root, "commit", "--quiet", "--allow-empty", "-m", "Release review of 0.2.0")
repo.git(repo.root, "push", "--quiet", "origin", "main")
done = repo.preflight("--worktree")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn(fact, done.stdout)
self.assertNotIn("item 9", done.stdout)
self.assertFalse((repo.temp / "proj-item-9").exists())
def test_takes_the_next_item_where_the_plan_marks_the_release_after_the_last_cut_renamed_and_calls_it_finished_where_it_does_not(self):
for mark, fact, absent in (("\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", "item 3", "release review"), ("", "release review is due", "item 3")):
with self.subTest(mark=mark):
repo = Repo(self)
repo.write(repo.root, "todo.md", TODO.replace("| 0.3.0 |", "| 0.4.0 |").replace("| 0.2.0 |", "| 0.3.0 |") + mark)
repo.commit(repo.root, "move 0.2.0's items to 0.3.0")
repo.git(repo.root, "push", "--quiet", "origin", "main")
done = repo.preflight()
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn(fact, done.stdout)
self.assertNotIn(absent, done.stdout)
def test_weighs_todo_md_at_the_last_cut_and_on_the_default_branch_after_it_alone(self):
"""Each case's plans: before the tag, at it, on a side branch merged after it, and after it, each committed in turn where given."""
cases = (
("a release named only before the cut", TODO, LATER, None, None, "item 9"),
("a release named at the cut", None, TODO, None, LATER, "release review is due"),
("a release named only on a side branch", None, LATER, TODO, None, "item 9"),
)
for name, before, at, side, after, fact in cases:
with self.subTest(name):
repo = Repo(self, todo="")
for todo, title in ((before, "before"), (at, "at")):
if todo is not None:
repo.write(repo.root, "todo.md", todo)
repo.commit(repo.root, title)
repo.git(repo.root, "tag", "--force", "v0.1.0")
if side is not None:
repo.git(repo.root, "switch", "--quiet", "-c", "side")
# The branch ends on a plan main never held, so the merge changes todo.md.
for todo in (side, LATER + "| 10 | 0.3.0 | | | **Do another later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"):
repo.write(repo.root, "todo.md", todo)
repo.commit(repo.root, "side")
repo.git(repo.root, "switch", "--quiet", "main")
repo.git(repo.root, "merge", "--quiet", "--no-ff", "-m", "merge side", "side")
if after is not None:
repo.write(repo.root, "todo.md", after)
repo.commit(repo.root, "after")
repo.git(repo.root, "push", "--quiet", "--force", "origin", "main", "v0.1.0")
done = repo.preflight()
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn(fact, done.stdout)
def test_continues_the_items_worktree_and_else_its_pushed_branch(self):
repo = Repo(self)
repo.preflight("--worktree")
worktree = repo.temp / "proj-item-3"
continued = repo.preflight("--worktree").stdout
self.assertIn(str(worktree), continued)
self.assertIn("continued", continued)
(worktree / "work.txt").write_text("work\n")
repo.git(worktree, "add", "work.txt")
repo.git(worktree, "commit", "--quiet", "-m", "work")
repo.git(worktree, "push", "--quiet", "origin", "item-3")
repo.git(repo.root, "worktree", "remove", "--force", str(worktree))
repo.git(repo.root, "branch", "--quiet", "-D", "item-3")
pushed = repo.preflight("--worktree").stdout
self.assertIn(str(worktree), pushed)
self.assertIn("made off origin/item-3", pushed)
self.assertTrue((worktree / "work.txt").exists())
def test_makes_no_worktree_where_its_path_holds_something_else_and_runs_no_tool(self):
repo = Repo(self)
(repo.temp / "proj-item-3").mkdir()
done = repo.preflight("--worktree")
self.assertIn(f"none made, since {repo.temp / 'proj-item-3'} exists", done.stdout)
self.assertNotIn("`reading-cost`", done.stdout)
def test_makes_no_worktree_and_runs_no_tool_where_git_cannot_add_it(self):
repo = Repo(self)
repo.temp.chmod(0o555)
self.addCleanup(repo.temp.chmod, 0o755)
done = repo.preflight("--worktree")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("Worktree: none made: git worktree add", done.stdout)
self.assertNotIn("`reading-cost`", done.stdout)
self.assertFalse((repo.temp / "proj-item-3").exists())
def test_makes_no_worktree_and_runs_no_tool_where_git_cannot_list_the_worktrees(self):
repo = Repo(self)
repo.stub_git('"worktree list --porcelain") echo "listing broke" >&2; exit 1;;')
done = repo.preflight("--worktree")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("listing broke", done.stdout)
self.assertNotIn("`reading-cost`", done.stdout)
self.assertFalse((repo.temp / "proj-item-3").exists())
def test_reads_origin_as_last_fetched_where_the_fetch_stalls_and_still_states_the_other_facts(self):
repo = Repo(self)
repo.stub_git(f'"fetch --quiet origin") exec {shutil.which("sleep")} 10;;')
done = repo.preflight("--worktree", CHUNK_PREFLIGHT_TIMEOUT="1")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("as last fetched", done.stdout)
self.assertIn("item 3, L 2, E + I 5", done.stdout)
self.assertIn("`reading-cost` exited 0", done.stdout)
def test_without_worktree_states_the_items_facts_and_makes_no_worktree_and_runs_no_tool(self):
repo = Repo(self)
done = repo.preflight()
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("item 3, L 2, E + I 5", done.stdout)
self.assertIn("Worktree: none made, since it ran without --worktree.", done.stdout)
self.assertIn("Open pull requests from item-3: none.", done.stdout)
self.assertIn("`src/app.py`: 3 lines", done.stdout)
self.assertNotIn("`reading-cost`", done.stdout)
self.assertFalse((repo.temp / "proj-item-3").exists())
self.assertNotIn("item-3", repo.git(repo.root, "branch", "--list"))
def test_item_names_the_item_the_chunk_starts_from_in_place_of_the_plans_next(self):
repo = Repo(self)
for args in (["--item", "7"], ["--worktree", "--item", "7"], ["--item", "7", "--worktree"]):
with self.subTest(args):
done = repo.preflight(*args)
self.assertEqual((done.returncode, done.stderr), (0, ""))
self.assertIn("0.2.0. The item this chunk starts from, named with --item: item 7, L 1, E + I 2.", done.stdout)
self.assertNotIn("Its first item that does not wait", done.stdout)
self.assertTrue((repo.temp / "proj-item-7").is_dir())
self.assertFalse((repo.temp / "proj-item-3").exists())
def test_item_names_no_item_where_the_plan_no_longer_holds_it(self):
done = Repo(self).preflight("--worktree", "--item", "4")
self.assertEqual((done.returncode, done.stderr), (0, ""))
self.assertIn("- No plan item: origin/main's todo.md holds no item 4, the one --item names; it may have shipped. No worktree was made.", done.stdout)
def test_exits_1_on_an_item_that_is_no_id(self):
for args in (["--item"], ["--item", "x"], ["--item", "7", "8"]):
with self.subTest(args):
done = Repo(self).preflight(*args)
self.assertEqual((done.returncode, done.stdout), (1, ""))
self.assertIn(f"unknown arguments {' '.join(args)}; usage: chunk-preflight [--worktree] [--item <ID>]", done.stderr)
def test_exits_1_on_an_argument_other_than_worktree(self):
done = Repo(self).preflight("--start")
self.assertEqual(done.returncode, 1)
self.assertIn("unknown arguments --start", done.stderr)
self.assertEqual(done.stdout, "")
def test_lists_the_open_pull_requests_with_gh_on_a_github_origin(self):
repo = Repo(self, origin="github.com/o/r.git")
self.assertIn("#12 https://github.com/o/r/pull/12", repo.preflight().stdout)
def test_without_a_plan_states_the_release_facts_and_makes_no_worktree(self):
repo = Repo(self, todo="")
done = repo.preflight("--worktree")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn("v0.1.0", done.stdout)
self.assertIn("no items table", done.stdout)
self.assertFalse((repo.temp / "proj-item-3").exists())
def test_states_its_timeout_in_its_help(self):
done = subprocess.run([sys.executable, str(BIN / "chunk-preflight"), "--help"], capture_output=True, env=isolated_env(), text=True)
self.assertEqual(done.returncode, 0, done.stderr)
self.assertIn(f"after {TIMEOUT} seconds", done.stdout)
def test_exits_1_on_a_timeout_setting_that_is_no_number_of_seconds(self):
done = Repo(self).preflight(CHUNK_PREFLIGHT_TIMEOUT="soon")
self.assertEqual(done.returncode, 1)
self.assertIn("CHUNK_PREFLIGHT_TIMEOUT", done.stderr)
self.assertEqual(done.stdout, "")
def test_exits_1_without_a_default_branch(self):
with tempfile.TemporaryDirectory() as temp:
env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}
subprocess.run(["git", "init", "--quiet", "--initial-branch=trunk", temp], check=True, env=env)
done = subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=temp, env=env, text=True)
self.assertEqual(done.returncode, 1)
self.assertIn("main or master", done.stderr)
self.assertEqual(done.stdout, "")
def test_exits_1_outside_a_checkout(self):
with tempfile.TemporaryDirectory() as temp:
done = subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=temp, env={**isolated_env(), "GIT_CONFIG_NOSYSTEM": "1"}, text=True)
self.assertEqual(done.returncode, 1)
self.assertIn("git rev-parse --show-toplevel", done.stderr)
def planned(todo, *rest):
"""choices.planned for the plan a todo.md's text holds, or for the Failure given."""
return choices.planned(plan_of(todo) if isinstance(todo, str) else todo, *rest)
def item_facts(todo=TODO, **fields):
"""The facts of todo's next item, its worktree made, with fields given replacing the rest."""
return ItemFacts(**{"plan": planned(todo, CUT, "origin/main", BRANCH), "worktree": Worktree(pathlib.Path("/c/proj-item-3"), "added on the new branch item-3, made off origin/main."), "pulls": None, "named": [], "tools": [], **fields})
def gathered(item, release=CUT, note=None, plan_outside=False):
return Gathered("origin/main", note, release, item, "origin/main's todo.md", {"plan": pathlib.Path("/c/proj-item-3/todo.md"), "changelog": pathlib.Path("/c/proj-item-3/CHANGELOG.md")}, plan_outside, {"language": "English"})
def rendered(item, release=CUT, note=None):
return "\n".join(render(gathered(item, release, note)))
class Render(unittest.TestCase):
def test_states_the_earliest_releases_first_item_its_levels_and_detail_and_each_item_that_may_join_its_chunk(self):
said = rendered(item_facts())
self.assertIn("origin/main's todo.md: 0.2.0", said)
self.assertIn("item 3, L 2, E + I 5", said)
self.assertIn("> Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.", said)
self.assertIn("item 7, L 1, E + I 2, S 1: **Do the thing after.**", said)
self.assertNotIn("item 8,", said)
def test_says_the_item_was_named_with_item(self):
said = rendered(item_facts(plan=planned(TODO, CUT, "origin/main", BRANCH, None, 7)))
self.assertIn("origin/main's todo.md: 0.2.0. The item this chunk starts from, named with --item: item 7, L 1, E + I 2.", said)
def test_states_each_fact_once_with_the_paths_between_the_worktree_and_the_open_pull_requests(self):
lines = render(gathered(item_facts()))
self.assertEqual([line.partition(":")[0] for line in lines[:6]], ["- Last version cut", "- The earliest release in origin/main's todo.md", "- Worktree", "- The project's config puts its files and plan at", "- The project's config sets", "- Open pull requests from item-3"])
self.assertEqual([line for line in lines[6:] if line.startswith("- Open pull requests")], [])
def test_says_that_a_plan_outside_the_checkout_hides_a_release_whose_items_are_all_done(self):
for item in (item_facts(), NoItem("the plan holds no item.")):
with self.subTest(item=type(item).__name__):
lines = render(gathered(item, plan_outside=True))
self.assertEqual(lines[1], f"- {UNSEEN_RELEASES}")
self.assertIn("no release review is called due and no release is called ready to cut: both are the human's to call", lines[1])
self.assertNotIn(f"- {UNSEEN_RELEASES}", render(gathered(item)))
def test_quotes_the_detail_of_each_item_that_may_join_the_chunk(self):
said = rendered(item_facts(TODO + "\n### 7. Do the thing after.\n\nTouch `src/other.py`.\n\nRun the e2e leg.\n\n### 8. Do the answered thing.\n\nNot quoted.\n"))
self.assertIn("Item 7's detail:\n\n> Touch `src/other.py`.\n> \n> Run the e2e leg.", said)
self.assertNotIn("Not quoted", said)
def test_lists_a_joining_item_nobody_scored_as_unscored(self):
plan = item_facts().plan
unscored = [dataclasses.replace(item, scores={}) if item.id == 7 else item for item in plan.items]
said = rendered(item_facts(plan=dataclasses.replace(plan, items=unscored)))
self.assertIn(" - item 7, L unscored, E + I unscored, S unscored: ", said)
def test_states_that_a_joining_item_has_no_detail(self):
said = rendered(item_facts())
self.assertIn("Item 7 has no detail.", said)
self.assertNotIn("Item 7's detail", said)
def test_quotes_the_details_of_the_first_ten_joining_items_and_names_the_rest(self):
rows = "".join(f"| {id_} | 0.2.0 | | | **Do thing {id_}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n" for id_ in range(20, 32))
details = "".join(f"\n### {id_}. Do thing {id_}.\n\nDetail {id_}.\n" for id_ in range(7, 8)) + "".join(f"\n### {id_}. Do thing {id_}.\n\nDetail {id_}.\n" for id_ in range(20, 32))
said = rendered(item_facts(TODO.replace("\n## Details", rows + "\n## Details") + details))
self.assertIn("> Detail 28.", said)
self.assertNotIn("Detail 29.", said)
self.assertIn("The details of items 29, 30 and 31 are not quoted: only the first 10 are. Run `~/.claude/bin/todo-item show <ID>` for each.", said)
def test_states_the_items_worktree_or_why_none_was_made(self):
self.assertIn("/c/proj-item-3", rendered(item_facts()))
self.assertIn("none made: path taken", rendered(item_facts(worktree=Failure("none made: path taken"))))
def test_states_that_no_other_item_may_join_the_chunk(self):
said = rendered(item_facts(TODO.replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | 5 |")))
self.assertIn("No other item", said)
self.assertNotIn("item 7,", said)
def test_states_that_an_item_above_r_5_ships_alone(self):
said = rendered(item_facts(TODO.replace("| 2 | 2 | 3 | 5 | 3 |", "| 3 | 2 | 3 | 6 | 3 |")))
self.assertIn("Item 3 has R above 5, so it ships alone.", said)
self.assertNotIn("item 7,", said)
def test_states_an_unscored_level_as_unscored(self):
unscored = TODO.replace("| L | E | I | R | S |", "| R | S |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|").replace("| 2 | 2 | 3 | 5 | 3 |", "| 5 | 3 |").replace("| 1 | 1 | 1 | 1 | 1 |", "| 1 | 1 |")
self.assertIn("item 3, L unscored, E + I unscored", rendered(item_facts(unscored)))
def test_states_the_unreleased_entries_and_else_the_commits_since_the_last_cut(self):
self.assertIn("v0.1.0. Unreleased: 2 entries", rendered(NoItem("x.")))
self.assertIn("1 entry", rendered(NoItem("x."), LastCut("v0.1.0", "## Unreleased\n\n- One.\n", 4, [])))
without = rendered(NoItem("x."), LastCut("v0.1.0", "# Changelog\n", 4, []))
self.assertIn("4 commits since v0.1.0", without)
self.assertIn("no ## Unreleased", without)
untagged = rendered(NoItem("x."), LastCut(None, "", 1, []))
self.assertIn("cut: none", untagged)
self.assertIn("1 commit on origin/main", untagged)
headed = rendered(NoItem("x."), LastCut(None, "## 0.0.1 - 2026-10-03\n", 1, []))
self.assertIn("cut: 0.0.1 (dated in CHANGELOG.md).", headed)
self.assertIn("1 commit since CHANGELOG.md dated 0.0.1", headed)
def test_states_why_the_changelog_and_the_commits_since_the_last_cut_cannot_be_read(self):
said = rendered(NoItem("x."), LastCut("v0.1.0", Failure("changelog unreadable"), Failure("count unreadable"), []))
self.assertIn("changelog unreadable", said)
self.assertIn("cannot be counted: count unreadable", said)
self.assertNotIn("no ## Unreleased", said)
def test_states_why_origin_reads_as_last_fetched_and_nothing_after_a_fetch(self):
self.assertIn("- reading origin as last fetched: fetch stalled", rendered(NoItem("x."), note="reading origin as last fetched: fetch stalled"))
fetched = rendered(NoItem("x."))
self.assertNotIn("last fetched", fetched)
self.assertNotIn("None", fetched)
def test_states_why_there_is_no_plan_item(self):
said = rendered(NoItem("every item waits."))
self.assertIn("every item waits.", said)
self.assertNotIn("Worktree", said)
def test_states_the_open_pull_requests_from_the_items_branch_or_why_none_are_listed(self):
cases = (
(("tea", Ran(0, "index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n", "")), ("#12 https://forge/pulls/12",)),
(("gh", Ran(0, "12\thttps://github.com/o/r/pull/12\n14\thttps://github.com/o/r/pull/14\n", "")), ("#12 https://github.com/o/r/pull/12, #14 https://github.com/o/r/pull/14",)),
(("gh", Ran(0, "", "")), ("item-3: none.",)),
(None, ("item-3: none", "no origin remote")),
(("tea", Ran(1, "", "no login\n")), ("`tea pulls list`", "exited 1", "no login")),
(("gh", Ran(1, "", "not logged in\n")), ("`gh pr list`", "exited 1", "not logged in")),
(("gh", Failure("could not finish: timed out")), ("`gh pr list`", "could not finish: timed out")),
)
for pulls, facts in cases:
with self.subTest(pulls=pulls):
said = rendered(item_facts(pulls=pulls))
for fact in facts:
self.assertIn(fact, said)
def test_states_each_named_files_lines_and_each_named_folders_files(self):
said = rendered(item_facts(named=[NamedPath("src/app.py", 1, 3), NamedPath("src", 2, None), NamedPath("bad.py", 1, Failure("not UTF-8")), NamedPath("one.py", 1, 1), NamedPath("docs", 1, None)]))
self.assertIn("`src/app.py`: 3 lines", said)
self.assertIn("`src`: 2 files", said)
self.assertIn("`bad.py`: cannot be read: not UTF-8", said)
self.assertIn("`one.py`: 1 line\n", said)
self.assertIn("`docs`: 1 file\n", said)
def test_states_that_the_item_names_no_tracked_file_or_why_they_cannot_be_listed(self):
self.assertIn("no file", rendered(item_facts(named=[])))
self.assertIn("ls-files broke", rendered(item_facts(named=Failure("ls-files broke"))))
def test_states_what_each_tool_printed_and_its_exit_code(self):
said = rendered(item_facts(tools=[("rank_todo.py --check", Ran(0, "ranked\n", "")), ("reading-cost", Ran(1, "", "")), ("larv-review needs-scoring-run 3", Ran(1, "out\n", "err\n")), ("larv-review places", Failure("could not finish: timed out"))]))
self.assertIn("`rank_todo.py --check` exited 0", said)
self.assertIn("> ranked", said)
self.assertIn("`reading-cost` exited 1, printing no output", said)
self.assertIn("> out\n> err", said)
self.assertIn("`larv-review places` could not finish: timed out", said)
class OpenPulls(unittest.TestCase):
def test_lists_gh_rows_as_they_come_and_only_teas_rows_from_the_branch(self):
self.assertEqual(open_pulls("12\thttps://github.com/o/r/pull/12\n14\thttps://github.com/o/r/pull/14\n", "gh", "item-3"), ["#12 https://github.com/o/r/pull/12", "#14 https://github.com/o/r/pull/14"])
self.assertEqual(open_pulls("index\thead\turl\n12\titem-3\thttps://forge/pulls/12\n13\tother\thttps://forge/pulls/13\n", "tea", "item-3"), ["#12 https://forge/pulls/12"])
class Plans(unittest.TestCase):
def test_picks_the_earliest_releases_first_item_that_does_not_wait_or_says_why_there_is_none(self):
self.assertEqual(planned(TODO, CUT, "origin/main", BRANCH).first.id, 3)
waits = planned(TODO.replace("| 3 | 0.2.0 | | |", "| 3 | 0.2.0 | | question |"), CUT, "origin/main", BRANCH)
self.assertIn("waits", waits.why)
self.assertIn("0.2.0", waits.why)
self.assertIn("Permission denied", planned(Failure("Permission denied"), CUT, "origin/main", BRANCH).why)
self.assertEqual(planned(Failure("Permission denied"), CUT, "origin/main", BRANCH).why, "origin/main's todo.md cannot be read: Permission denied.")
self.assertEqual(planned(Failure("Permission denied"), CUT, "origin/main", BRANCH, pathlib.Path("/projects/acme/todo.md")).why, "/projects/acme/todo.md cannot be read: Permission denied.")
self.assertIn("L 'x'", planned(TODO.replace("| 2 | 2 | 3 | 5 |", "| x | 2 | 3 | 5 |"), CUT, "origin/main", BRANCH).why)
self.assertIn("## Details holds a fenced code block", planned(TODO + "```\n", CUT, "origin/main", BRANCH).why)
def test_takes_the_item_item_names_even_one_that_waits_or_says_it_left_the_plan(self):
# Item 7 waits for item 3, which another chunk runs.
named = planned(TODO, CUT, "origin/main", BRANCH, None, 7)
self.assertEqual((named.first.id, named.first.tagline, named.named), (7, "**Do the thing after.**", True))
self.assertTrue(named.text.startswith("**Do the thing after.**"), named.text)
self.assertFalse(planned(TODO, CUT, "origin/main", BRANCH).named)
self.assertEqual(planned(TODO, CUT, "origin/main", BRANCH, None, 4), NoItem("origin/main's todo.md holds no item 4, the one --item names; it may have shipped."))
def test_tells_a_plan_with_no_items_table_from_one_whose_table_holds_no_item(self):
without = planned("", CUT, "origin/main", BRANCH).why
self.assertIn("origin/main", without)
self.assertIn("no items table", without)
self.assertNotIn("cannot be read", without)
empty = planned(EMPTY, LastCut(None, "", 4, []), "origin/main", BRANCH).why
self.assertIn("holds no item", empty)
self.assertNotIn("no items table", empty)
def test_names_a_release_cut_under_a_dated_heading_as_the_last_cut_on_a_branch_with_no_tag(self):
said = planned(EMPTY, LastCut(None, "## 0.0.1 - 2026-10-03\n", 0, []), "origin/main", BRANCH).why
self.assertIn("the next release after the last cut, 0.0.1 (dated in CHANGELOG.md)", said)
def test_says_the_tags_cannot_be_read_with_gits_reason_and_names_no_cut(self):
said = planned(EMPTY, LastCut(Failure("git exited 128: not a git repository"), "", 4, []), "origin/main", BRANCH).why
self.assertIn("origin/main's tags cannot be read: git exited 128: not a git repository.", said)
self.assertIn("Find the next release yourself.", said)
self.assertNotIn("no release is cut yet", said)
def test_names_the_start_as_the_last_cut_where_nothing_is_cut(self):
said = planned(EMPTY, LastCut(None, "", 4, [TODO]), "origin/main", BRANCH).why
self.assertIn("release 0.2.0, the next after the start, since no release is cut yet,", said)
self.assertIn("has landed yet.", said)
self.assertIn("since the cut.", planned(EMPTY, LastCut(None, "## 0.1.0 - 2026-10-03\n", 4, [TODO]), "origin/main", BRANCH).why)
def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self):
named = "release 0.2.0, the next after the last cut, v0.1.0"
unnamed = "the next release after the last cut, v0.1.0"
cases = (
(LATER, 4, [TODO], False, "release review is due", named),
(LATER, 4, [TODO], True, "finished and ready to cut", named),
(LATER, 0, [TODO], False, "planned first", named),
(EMPTY, 4, [TODO], True, "finished and ready to cut", named),
(EMPTY, 0, [TODO], False, "planned first", named),
(EMPTY, 4, [EMPTY], True, "finished and ready to cut", unnamed),
(LATER, Failure("count unreadable"), [TODO], False, "cannot be read", unnamed),
)
for todo, commits, todos, reviewed, fact, release in cases:
with self.subTest(todo=todo, commits=commits, todos=todos, reviewed=reviewed):
why = planned(todo, LastCut("v0.1.0", "", commits, todos, reviewed), "origin/main", BRANCH).why
self.assertIn(fact, why)
self.assertIn(release, why)
def test_says_what_todo_md_named_since_the_last_cut_cannot_be_read(self):
self.assertIn("cannot be read", planned(LATER, LastCut("v0.1.0", "", 4, Failure("log unreadable")), "origin/main", BRANCH).why)
def test_takes_the_earliest_release_where_no_earlier_one_was_named_since_the_last_cut(self):
self.assertEqual(planned(LATER, LastCut("v0.1.0", "", 4, [LATER]), "origin/main", BRANCH).first.id, 9)
def test_counts_the_items_of_a_release_already_cut_as_the_next_releases_and_says_to_move_them(self):
plan = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH)
self.assertEqual((plan.first.id, plan.first.release), (3, (0, 3, 0)))
self.assertEqual({item.release for item in plan.items}, {(0, 3, 0)})
self.assertEqual(plan.carried, CarriedOver((0, 3, 0), (5, 3, 7, 8)))
said = rendered(dataclasses.replace(item_facts(), plan=plan), LastCut("v0.2.0", "", 4, []))
self.assertIn("- Items 5, 3, 7 and 8 are filed under a release already cut, so they count as release 0.3.0's, the next.", said)
self.assertIn("`~/.claude/bin/todo-item move`", said)
self.assertIn("- The next release, after the last cut, that origin/main's todo.md names: 0.3.0. Its first item that does not wait: item 3,", said)
self.assertNotIn("already cut", rendered(item_facts()))
def test_says_to_move_one_or_two_items_of_a_release_already_cut_in_the_singular_or_the_plural(self):
cut = LastCut("v0.2.0", "", 4, [])
for todo, ids, said in ((SHIPPED_BUT_3, (3,), "- Item 3 is filed under a release already cut, so it counts as release 0.3.0's, the next. Move it there"), (SHIPPED_BUT_3 + NINTH.replace("| 9 | 0.3.0 |", "| 4 | 0.1.0 |"), (3, 4), "- Items 3 and 4 are filed under a release already cut, so they count as release 0.3.0's, the next. Move them there")):
with self.subTest(ids=ids):
plan = planned(todo, cut, "origin/main", BRANCH)
self.assertEqual(plan.carried, CarriedOver((0, 3, 0), ids))
self.assertIn(said, rendered(dataclasses.replace(item_facts(), plan=plan), cut))
def test_says_the_plan_files_items_under_a_release_already_cut(self):
why = planned(TODO.replace(NINTH, ""), LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH).why
self.assertIn("release 0.2.0", why)
self.assertIn("v0.2.0", why)
self.assertIn("not after", why)
def test_takes_an_item_without_a_detail_as_its_tagline_alone(self):
self.assertEqual(planned(TODO[:TODO.index("## Details")], CUT, "origin/main", BRANCH).text, "**Do the next thing.**")
class Gathering(unittest.TestCase):
def test_adds_the_worktree_on_the_local_branch_else_on_a_new_one_tracking_origins_else_on_a_new_one_off_the_default_branch(self):
path = pathlib.Path("/c/proj-item-3")
self.assertEqual(worktree_add("item-3", path, "origin/main", True, True)[0], ["worktree", "add", "--quiet", "/c/proj-item-3", "item-3"])
self.assertEqual(worktree_add("item-3", path, "origin/main", False, True)[0], ["worktree", "add", "--quiet", "--track", "-b", "item-3", "/c/proj-item-3", "origin/item-3"])
self.assertEqual(worktree_add("item-3", path, "origin/main", False, False)[0], ["worktree", "add", "--quiet", "--no-track", "-b", "item-3", "/c/proj-item-3", "origin/main"])
def test_lists_pull_requests_with_gh_on_a_github_origin_and_with_tea_elsewhere(self):
self.assertEqual(forge_of("git@github.com:o/r.git"), "gh")
self.assertEqual(forge_of("https://gitea.larvit.se/o/r.git"), "tea")
def test_reads_the_timeout_setting_as_seconds_above_0_and_else_takes_the_default(self):
self.assertEqual(seconds(None), TIMEOUT)
self.assertEqual(seconds("2.5"), 2.5)
for setting in ("soon", "0", "-1", "1e3", ""):
with self.subTest(setting=setting):
self.assertIn("CHUNK_PREFLIGHT_TIMEOUT", seconds(setting).reason)
class Running(unittest.TestCase):
def test_says_why_a_command_could_not_finish(self):
with tempfile.TemporaryDirectory() as cwd:
cases = (([str(pathlib.Path(cwd, "missing"))], 60, "missing"), ([sys.executable, "-c", "import time; time.sleep(5)"], 0.2, "0.2"))
for command, timeout, fact in cases:
with self.subTest(fact=fact):
done = ran(command, pathlib.Path(cwd), timeout)
self.assertIsInstance(done, Failure)
self.assertIn(fact, done.reason)
def test_counts_a_files_lines_says_why_they_cannot_be_read_and_counts_none_for_a_folder(self):
with tempfile.TemporaryDirectory() as temp:
folder = pathlib.Path(temp)
(folder / "two.txt").write_text("a\nb\n")
(folder / "latin.txt").write_bytes(b"caf\xe9\n")
(folder / "locked.txt").write_text("a\n")
(folder / "locked.txt").chmod(0)
self.assertEqual(line_count(folder / "two.txt"), 2)
self.assertIn("utf-8", line_count(folder / "latin.txt").reason)
self.assertIn("locked.txt", line_count(folder / "locked.txt").reason)
self.assertIsNone(line_count(folder))
class BesideTest(unittest.TestCase):
"""The fact that names the items that may start chunks beside the next one."""
# Items 3 and 4 touch other parts of one file, and item 6 touches what item 3 does.
ROWS = "| 4 | 0.2.0 | | | **Do four.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n| 6 | 0.2.0 | | | **Do six.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
DETAILS = "\nTouches:\n\n- `src/app.py`: `run`\n\n### 4. Do four.\n\nTouches:\n\n- `src/app.py`: `stop`\n\n### 6. Do six.\n\nTouches:\n\n- `src/app.py`: `run`\n"
def said(self, todo):
return [line for line in rendered(item_facts(todo)).splitlines() if "beside" in line]
def test_names_the_items_that_may_start_chunks_beside_it_and_why_the_others_may_not(self):
todo = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + self.DETAILS
self.assertEqual(self.said(todo), ["- The items of release 0.2.0 that may start chunks beside item 3's: 4. None is predicted to touch a part that item 3 touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own. Not beside it: item 6, which overlaps item 3 at `src/app.py` `run`."])
def test_names_each_item_that_may_and_stops_there_when_none_is_refused(self):
todo = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + self.DETAILS.removesuffix("`run`\n") + "`other`\n"
self.assertEqual(self.said(todo), ["- The items of release 0.2.0 that may start chunks beside item 3's: 4, 6. None is predicted to touch a part that item 3 touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own."])
def test_says_when_none_may(self):
todo = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + self.DETAILS.replace("`stop`", "`run`")
self.assertEqual(self.said(todo), ["- No item of release 0.2.0 may start a chunk beside item 3's. Not beside it: item 4, which overlaps item 3 at `src/app.py` `run`; item 6, which overlaps item 3 at `src/app.py` `run`."])
alone = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + "\n### 4. Do four.\n\nTouches:\n\n- `src/app.py`\n"
self.assertEqual(self.said(alone), ["- No item of release 0.2.0 may start a chunk beside item 3's: item 3's detail has no `Touches:` list."])
def test_says_nothing_in_a_plan_without_predictions(self):
self.assertEqual(self.said(TODO), [])
if __name__ == "__main__":
unittest.main()