From 8a35412a0a98e56a2202211c380f7e4ee792d6de Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 4 Nov 2026 21:25:16 +0100 Subject: [PATCH] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=208=20=F0=9F=9F=A1=20(0=20misread);=20keep=20Ask.?= =?UTF-8?q?asked=20in=20seconds=20and=20stamp=20it=20only=20in=20its=20fil?= =?UTF-8?q?e,=20keep=20the=20dated-heading=20rule=20in=20one=20function=20?= =?UTF-8?q?and=20the=20preflight's=20wording=20in=20chunk=5Fpreflight,=20m?= =?UTF-8?q?atch=20the=20heading=20line=20itself,=20and=20test=20a=20device?= =?UTF-8?q?=20path,=20a=20tagged=20repo=20with=20a=20dated=20heading,=20an?= =?UTF-8?q?=20untagged=20one=20without,=20and=20the=20wording=20where=20no?= =?UTF-8?q?thing=20is=20cut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_pick.py | 29 +++++++--------- bin/chunk_preflight/choices.py | 10 +++++- bin/chunk_preflight/facts.py | 6 ++-- bin/chunk_preflight/test_chunk_preflight.py | 6 ++++ bin/loop_claude/cycle/interrupt.py | 3 +- bin/loop_claude/loop/routing_check.py | 2 +- bin/loop_claude/test_loop_claude.py | 4 +-- bin/loop_claude/waiting/ask.py | 19 ++++++----- bin/loop_claude/waiting/listing.py | 5 ++- bin/loop_inbox/inbox.py | 15 +++------ bin/loop_inbox/test_loop_inbox.py | 3 +- bin/rule_hook/test_rule_hook.py | 13 +++++--- bin/test_chunk_pick.py | 37 +++++++++++++++++++++ 13 files changed, 98 insertions(+), 54 deletions(-) diff --git a/bin/chunk_pick.py b/bin/chunk_pick.py index 0e12b872..44ef3774 100644 --- a/bin/chunk_pick.py +++ b/bin/chunk_pick.py @@ -94,7 +94,7 @@ def default_plan(root: str, ref: str) -> DefaultPlan: """What ref, the default branch as last fetched, holds for the pick, read in the checkout at root.""" tag = newest_release_tag(ref, root) changelog = file_at(ref, "CHANGELOG.md", root) - after = max(dated_headings(changelog), default=None) if tag is None else None + after = dated_cut(tag, changelog) since = tag if after is None else heading_commit(after, ref, root) commits = since if isinstance(since, Failure) else commits_since(since, ref, root) reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, after) @@ -103,7 +103,9 @@ def default_plan(root: str, ref: str) -> DefaultPlan: def heading_commit(release: tuple[int, int, int], ref: str, cwd: str) -> 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.""" - added = git("log", "--reverse", "--format=%H", "-S", f"## {version(release)} - ", ref, "--", "CHANGELOG.md", cwd=cwd) + # -G matches the heading line itself, so a changelog entry that quotes the heading doesn't count. + heading = "^## " + version(release).replace(".", "\\.") + " - [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$" + added = git("log", "--reverse", "--format=%H", "-G", heading, ref, "--", "CHANGELOG.md", cwd=cwd) return added if isinstance(added, Failure) else next(iter(added.split()), None) @@ -160,29 +162,22 @@ def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown: if earliest is not None: after.add(earliest) release = min(after, default=None) - return Upcoming(release, earliest == release and (earliest is not None or version == BEFORE_FIRST_RELEASE), landed(cut)) + nothing_cut = version == BEFORE_FIRST_RELEASE + return Upcoming(release, earliest == release and (earliest is not None or nothing_cut), landed(cut)) def cut_version(cut: LastCut) -> tuple[int, int, int] | None: """Which version is cut. It is the tag's, or None where the tag names no version. On a branch with no tag, it is the newest version under a dated CHANGELOG.md heading, else BEFORE_FIRST_RELEASE.""" if cut.tag is None: - return max(dated_headings(cut.changelog), default=BEFORE_FIRST_RELEASE) + return dated_cut(cut.tag, cut.changelog) or BEFORE_FIRST_RELEASE return version_of(cut.tag) -def cut_name(cut: LastCut) -> str | None: - """How the preflight names cut_version's cut: the tag, or the version under its dated heading; None where nothing is cut.""" - if cut.tag is not None: - return None if isinstance(cut.tag, Failure) else cut.tag - headed = max(dated_headings(cut.changelog), default=None) - return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)" - - -def dated_headings(changelog: str | Failure) -> list[tuple[int, int, int]]: - """Each version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`, the heading a cut release takes; an undated heading is not cut.""" - if isinstance(changelog, Failure): - return [] - return [release_of(dated[1]) for heading in sections(changelog) if (dated := re.fullmatch(r"([0-9]+\.[0-9]+\.[0-9]+) - [0-9]{4}-[0-9]{2}-[0-9]{2}", heading))] +def dated_cut(tag: str | None | Failure, changelog: str | Failure) -> tuple[int, int, int] | None: + """The version a branch with no tag counts as cut: the newest CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`, the heading a cut release takes. None where the branch has a tag, or CHANGELOG.md has no such heading; an undated heading is not cut.""" + if tag is not None or isinstance(changelog, Failure): + return None + return max((release_of(dated[1]) for heading in sections(changelog) if (dated := re.fullmatch(r"([0-9]+\.[0-9]+\.[0-9]+) - [0-9]{4}-[0-9]{2}-[0-9]{2}", heading))), default=None) def version_of(tag: str | None | Failure) -> tuple[int, int, int] | None: diff --git a/bin/chunk_preflight/choices.py b/bin/chunk_preflight/choices.py index 6ffd4c5b..8d5e7ec2 100644 --- a/bin/chunk_preflight/choices.py +++ b/bin/chunk_preflight/choices.py @@ -2,7 +2,7 @@ import pathlib import re -from chunk_pick import chunk_item, Cut, cut_name, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned +from chunk_pick import chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned from failure import Failure from chunk_preflight.gathered import Forge, NoItem, Plan from todo_table import item_details, items, NoItemsTable, version @@ -11,6 +11,14 @@ from todo_table import item_details, items, NoItemsTable, version PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")} +def cut_name(cut: LastCut) -> str | None: + """How the preflight names the last cut: the tag, or the version under its dated CHANGELOG.md heading; None where nothing is cut.""" + if cut.tag is not None: + return None if isinstance(cut.tag, Failure) else cut.tag + headed = dated_cut(cut.tag, cut.changelog) + return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)" + + def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem: """The plan in todo, the default branch's todo.md, with the item the next chunk takes first, chunk_pick.chunk_item's pick; else why there is none.""" where = f"{default}'s todo.md" diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index d3d80e38..f027f0a7 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -1,9 +1,9 @@ """The lines the preflight prints, stated from what it gathered.""" from todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone, version -from chunk_pick import cut_name, dated_headings, LastCut, unreleased_entries +from chunk_preflight.choices import cut_name, PULLS_LIST +from chunk_pick import dated_cut, LastCut, unreleased_entries from failure import Failure from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran -from chunk_preflight.choices import PULLS_LIST from markdown_text import quoted @@ -24,7 +24,7 @@ def last_release(default: str, release: LastCut) -> str: entries = unreleased_entries(release.changelog) if isinstance(release.changelog, str) else None if entries is not None: return f"{cut} Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased." - headed = max(dated_headings(release.changelog), default=None) if release.tag is None else None + headed = dated_cut(release.tag, release.changelog) since = f"since {release.tag}" if release.tag else f"since CHANGELOG.md dated {version(headed)}" if headed else f"on {default}" commits = f"the commits {since} cannot be counted: {release.commits.reason}" if isinstance(release.commits, Failure) else f"{counted(release.commits, 'commit', 'commits')} {since}" changelog = f"CHANGELOG.md cannot be read: {release.changelog.reason}" if isinstance(release.changelog, Failure) else "no ## Unreleased in CHANGELOG.md" diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 925d65b6..dc7af3c9 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -454,6 +454,12 @@ class Plans(unittest.TestCase): said = planned(EMPTY, LastCut(None, "## 0.0.1 - 2026-10-03\n", 0, []), "origin/main").why self.assertIn("the next release after the last cut, 0.0.1 (dated in CHANGELOG.md)", said) + def test_names_the_start_as_the_last_cut_where_nothing_is_cut(self): + said = planned(EMPTY, LastCut(None, "", 4, [TODO]), "origin/main").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").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" diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 80482246..8798892d 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -14,7 +14,6 @@ from loop_claude.waiting.talk import make_way, TALK from loop_claude.stop import needs_human, needs_terminal, Stop from loop_claude.paths import Paths from model_routing.ladder import Rung -from utc_stamp import utc ANSWER_QUESTION = "answer the question above" # ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it. @@ -47,7 +46,7 @@ def interrupt(question: str, answer_here: bool, session: WorkerSession, paths: P return stop # Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK. effects.discard_typed() - ask = Ask(effects.new_id(), str(session.id), session.root, question, utc(effects.now()), Asking(session.claude_command()) if answer_here else OpenOnTerminal()) + ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal()) with listed(paths.waiting, ask, effects): answer = first_answer(ask, paths, effects) if answer_here else OpenOnTerminal() if isinstance(answer, OpenOnTerminal | OpenInInbox): diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 99de204a..75c07afa 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -53,7 +53,7 @@ def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], say("Not on a terminal: the calls are raised again at the next measurement.", effects) return None prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls." - ask = Ask(effects.new_id(), session, checkout, question, utc(effects.now()), OpenOnTerminal()) + ask = Ask(effects.new_id(), session, checkout, question, effects.now(), OpenOnTerminal()) with listed(paths.waiting, ask, effects): unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), effects) if unstarted: diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index c83f5674..4dc81c9e 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -705,7 +705,7 @@ class Interrupts(unittest.TestCase): def ask(self, question="Which one?", state=None): """The ask interrupt makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session.""" resumed = hand_over.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}) - return Ask(ASK_ID, str(self.session.id), str(self.home), question, utc(NOW), state or Asking(resumed)) + return Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, state or Asking(resumed)) def opening(self, other): """loop-inbox's /talk, as the loop's input sees it: loop-inbox claims the one ask listed, and the claim is the first answer.""" @@ -866,7 +866,7 @@ class RoutingCheck(unittest.TestCase): self.chunks(5, 4) question = f"loop-claude's routing figures call for a routing change:\n- Explore subagents' reports took more of the worker's context than their searches would have.\nThe figures: {self.root / 'routing-figures.md'}" def ran(args): - self.assertEqual(waiting(self.paths.waiting), [Ask(ASK_ID, "s1", "/code/log", question, utc(NOW), OpenOnTerminal())]) + self.assertEqual(waiting(self.paths.waiting), [Ask(ASK_ID, "s1", "/code/log", question, NOW, OpenOnTerminal())]) return 0 self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD])) self.assertEqual(asks_and_answers(self.paths.waiting), []) diff --git a/bin/loop_claude/waiting/ask.py b/bin/loop_claude/waiting/ask.py index a4ea0ec4..e67a228a 100644 --- a/bin/loop_claude/waiting/ask.py +++ b/bin/loop_claude/waiting/ask.py @@ -7,7 +7,7 @@ import pathlib import typing from loop_claude.hand_over import ClaudeCommand -from utc_stamp import seconds +from utc_stamp import seconds, utc if typing.TYPE_CHECKING: from _typeshed import DataclassInstance @@ -46,22 +46,25 @@ class Ask: # The checkout the loop runs in. root: str question: str - # When the loop asked, as utc_stamp.utc writes it: an ISO UTC datetime. - asked: str + # When the loop asked, in seconds since the epoch; its file holds it as an ISO UTC datetime, as ask_fields writes it. + asked: float state: AskState +def ask_fields(ask: Ask) -> dict[str, object]: + """ask as its file holds it, which read_ask reads back to the second.""" + return dataclasses.asdict(ask) | {"asked": utc(ask.asked), "state": tagged(ask.state)} + + def read_ask(path: pathlib.Path) -> Ask | None: """The ask in path. None where a field has the wrong type, where utc_stamp.seconds cannot read asked, or where the ask names another session than path does.""" try: data = json.loads(path.read_text(encoding="utf-8")) - ask = Ask(**{**data, "state": ask_state(data["state"])}) - if not all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question, ask.asked)) or ask.session != path.stem: - return None - seconds(ask.asked) + ask = Ask(**{**data, "asked": seconds(data["asked"]), "state": ask_state(data["state"])}) except (OSError, ValueError, TypeError, KeyError): return None - return ask + texts = all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question)) + return ask if texts and ask.session == path.stem else None def ask_state(data: object) -> AskState: diff --git a/bin/loop_claude/waiting/listing.py b/bin/loop_claude/waiting/listing.py index 2f0cadc7..041e3ae4 100644 --- a/bin/loop_claude/waiting/listing.py +++ b/bin/loop_claude/waiting/listing.py @@ -1,11 +1,10 @@ """The ask's file in the folder loop-inbox reads, and which asks it lists.""" import contextlib -import dataclasses import pathlib import typing from loop_claude.waiting.answers import answer_file -from loop_claude.waiting.ask import Ask, read_ask, tagged +from loop_claude.waiting.ask import Ask, ask_fields, read_ask from loop_claude.effects import Effects, say from loop_claude.session_lock import ended, running from failure import Failure @@ -21,7 +20,7 @@ def publish(folder: pathlib.Path, ask: Ask) -> Failure | None: make_private(folder) except OSError as failure: return Failure(f"cannot make {folder}: {failure.strerror}") - return replace_json(ask_file(folder, ask.session), dataclasses.asdict(ask) | {"state": tagged(ask.state)}) + return replace_json(ask_file(folder, ask.session), ask_fields(ask)) def withdraw(folder: pathlib.Path, session: str) -> Failure | None: diff --git a/bin/loop_inbox/inbox.py b/bin/loop_inbox/inbox.py index 2cb66a5c..68c6abcf 100644 --- a/bin/loop_inbox/inbox.py +++ b/bin/loop_inbox/inbox.py @@ -12,7 +12,6 @@ import typing from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal from loop_claude.running_loops import RunningLoop, Taken -from utc_stamp import seconds from loop_claude.waiting.talk import TALK ENTER = "enter" @@ -109,7 +108,7 @@ def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[floa lines = [*wrapped(head, width), ""] for number, ask in enumerate(screen.shown, 1): state = "" if isinstance(ask.state, Asking) else f"; claude is open {where_open(ask.state)}" - lines += wrapped(f"[{number}] {ask.root}, {waiting_since(ask, now, local_time)}{state}", width) + lines += wrapped(f"[{number}] {ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}){state}", width) lines += cut(wrapped(ask.question, width - len(INDENT) - len(ELLIPSIS)), SHOWN_LINES) lines.append("") lines += running_lines(screen.running, screen.shown, width) @@ -140,7 +139,7 @@ def item_line(item: Taken | None) -> str: def answering_lines(screen: Answering, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]: """The question, in lines of at most width characters, and its foot, the prompt for the answer.""" ask = screen.ask - head = f"{ask.root}, {waiting_since(ask, now, local_time)}:" + head = f"{ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}):" return [*wrapped(head, width), "", *wrapped(ask.question, width), ""], typed_after(ANSWER_PROMPT, screen.typed, width) @@ -169,14 +168,8 @@ def cut(lines: list[str], count: int) -> list[str]: return [*shown[:-1], f"{shown[-1]}{ELLIPSIS}"] if len(lines) > count else shown -def waiting_since(ask: Ask, now: float, local_time: typing.Callable[[float], str]) -> str: - """When ask's loop asked, in local time, and how long it has waited.""" - asked = seconds(ask.asked) - return f"waiting since {local_time(asked)} ({waited(now - asked)})" - - -def waited(span: float) -> str: - minutes = int(span // 60) +def waited(seconds: float) -> str: + minutes = int(seconds // 60) if minutes < 60: return f"{minutes} min" hours, minutes = divmod(minutes, 60) diff --git a/bin/loop_inbox/test_loop_inbox.py b/bin/loop_inbox/test_loop_inbox.py index d406f917..ff3a91ac 100644 --- a/bin/loop_inbox/test_loop_inbox.py +++ b/bin/loop_inbox/test_loop_inbox.py @@ -24,7 +24,6 @@ from loop_claude.paths import paths_from from loop_claude import running_loops, session_lock from loop_claude.running_loops import RunningLoop, Taken from loop_claude.effects import system_effects -from utc_stamp import utc ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {})) # The pid of this loop-inbox. @@ -33,7 +32,7 @@ ANSWERED_ON_TERMINAL = object() def asked(session, root, question="Which one?", at=100.0, state=ASKING): - return Ask(f"ask-{session}", session, root, question, utc(at), state) + return Ask(f"ask-{session}", session, root, question, at, state) def loops_hold(test, folder, *sessions): diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 945d8d23..87a6ad99 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -1,7 +1,9 @@ import datetime +import itertools import json import os import pathlib +import resource import subprocess import sys import tempfile @@ -659,12 +661,15 @@ class Hook(unittest.TestCase): self.assertIn("Blocked by rule image-pin: ", ran.stderr) self.assertIn("`# rule-override image-pin: `", ran.stderr) - def test_an_edit_of_a_fifo_finishes(self): + def test_an_edit_of_a_fifo_or_a_device_finishes(self): fifo = f"{self.repo}/pipe" os.mkfifo(fifo) - for tool, given in (("Write", {"content": "x\n"}), ("Edit", {"old_string": "a", "new_string": "b"}), ("MultiEdit", {"edits": [{"old_string": "a", "new_string": "b"}]})): - with self.subTest(tool=tool): - ran = hook({"cwd": self.repo, "tool_input": {"file_path": fifo, **given}, "tool_name": tool}, self.repo) + # A cap on the hook's memory, so a read of /dev/zero fails fast instead of filling the machine. + capped = lambda: resource.setrlimit(resource.RLIMIT_AS, (1 << 30, 1 << 30)) + for path, (tool, given) in itertools.product((fifo, "/dev/zero"), (("Write", {"content": "x\n"}), ("Edit", {"old_string": "a", "new_string": "b"}), ("MultiEdit", {"edits": [{"old_string": "a", "new_string": "b"}]}))): + with self.subTest(path=path, tool=tool): + call = {"cwd": self.repo, "tool_input": {"file_path": path, **given}, "tool_name": tool} + ran = subprocess.run([str(HOOK)], capture_output=True, cwd=self.repo, env=isolated_env(), input=json.dumps(call), preexec_fn=capped, text=True, timeout=10) self.assertEqual(ran.returncode, 0) def test_an_override_passes_and_is_listed_for_the_chunk(self): diff --git a/bin/test_chunk_pick.py b/bin/test_chunk_pick.py index 2a66446f..208b3aac 100644 --- a/bin/test_chunk_pick.py +++ b/bin/test_chunk_pick.py @@ -174,6 +174,43 @@ class ChunkItem(unittest.TestCase): run("commit", "-q", "--allow-empty", "-m", "Release review of 0.1.0") self.assertIs(chunk_pick.default_plan(repo, "main").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() + self.addCleanup(subprocess.run, ["rm", "-rf", repo]) + 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) + changelog = pathlib.Path(repo, "CHANGELOG.md") + run("init", "-q", "-b", "main") + pathlib.Path(repo, "notes.md").write_text("## 0.0.1 - 2026-10-01\n") + changelog.write_text("# Changelog\n\n## Unreleased\n\n- Quote `## 0.0.1 - 2026-10-02`.\n") + run("add", ".") + run("commit", "-q", "-m", "Notes and a quoted heading") + changelog.write_text("# Changelog\n\n## 0.0.1 - 2026-10-03\n") + run("commit", "-q", "-am", "Cut 0.0.1") + changelog.write_text("# Changelog\n\n## 0.0.1 - 2026-10-04\n") + run("commit", "-q", "-am", "Fix 0.0.1's date") + run("commit", "-q", "--allow-empty", "-m", "Ship item 2") + run("checkout", "-q", "-b", "side") + run("commit", "-q", "--allow-empty", "-m", "Side work") + self.assertEqual(chunk_pick.default_plan(repo, "main").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() + self.addCleanup(subprocess.run, ["rm", "-rf", repo]) + 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.2.0")) + run("add", "todo.md") + run("commit", "-q", "-m", "Plan") + self.assertEqual(chunk_pick.default_plan(repo, "main").cut, chunk_pick.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 = chunk_pick.default_plan(repo, "main") + self.assertEqual(held.todo, HEADER + ROW.format(id=1, release="0.2.0")) + self.assertEqual(held.cut, chunk_pick.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(chunk_pick.chunk_item(plan_under((0, 2, 0)), held.cut), chunk_pick.Next((0, 2, 0), one((0, 2, 0)))) + 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(chunk_pick.unreleased_changes(chunk_pick.LastCut("v0.1.0", changelog, 5, [])), 2)