Answer stability round 1: 0 🔴, 8 🟡 (0 misread); keep Ask.asked in seconds and stamp it only in its file, keep the dated-heading rule in one function and the preflight's wording in chunk_preflight, match the heading line itself, and test a device path, a tagged repo with a dated heading, an untagged one without, and the wording where nothing is cut

This commit is contained in:
2026-11-04 21:25:16 +01:00
parent 0a47507756
commit 8a35412a0a
13 changed files with 98 additions and 54 deletions
+12 -17
View File
@@ -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:
+9 -1
View File
@@ -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"
+3 -3
View File
@@ -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"
@@ -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"
+1 -2
View File
@@ -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):
+1 -1
View File
@@ -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:
+2 -2
View File
@@ -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), [])
+11 -8
View File
@@ -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:
+2 -3
View File
@@ -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:
+4 -11
View File
@@ -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)
+1 -2
View File
@@ -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):
+9 -4
View File
@@ -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: <reason>`", 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):
+37
View File
@@ -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)