Answer principles round 1: 0 🔴, 3 🟡 (0 misread); hand the home folder, the clock and the output to larv-review's commands from their wiring

This commit is contained in:
2026-11-13 03:04:44 +01:00
parent 87d5023773
commit e6da7b0b9c
22 changed files with 155 additions and 131 deletions
+5 -3
View File
@@ -1,14 +1,16 @@
import pathlib
from failure import Failure from failure import Failure
from git_cli.git_repo import file_at, full_history, git from git_cli.git_repo import file_at, full_history, git
from review_rules.comprehension_history import HistoryChange from review_rules.comprehension_history import HistoryChange
from project_config.main import project from project_config.main import located
def history_changes(default: str) -> list[HistoryChange] | Failure: def history_changes(default: str, home: pathlib.Path) -> list[HistoryChange] | Failure:
"""Each merged change on the default branch that touched the history, newest first. A Failure where the project's config puts the history outside the checkout, where no commit holds it.""" """Each merged change on the default branch that touched the history, newest first. A Failure where the project's config puts the history outside the checkout, where no commit holds it."""
if partial := full_history(): if partial := full_history():
return partial return partial
config = project() config = located(None, home)
if isinstance(config, Failure): if isinstance(config, Failure):
return config return config
history = config.tracked("comprehension-history") history = config.tracked("comprehension-history")
+43 -43
View File
@@ -1,5 +1,4 @@
import pathlib import pathlib
import time
import typing import typing
from larv_review.agreement import agreement_report from larv_review.agreement import agreement_report
@@ -10,14 +9,17 @@ from larv_review.ruling import counted, overall, ruling, split, surplus, votes
from failure import Failure from failure import Failure
from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
from larv_review.scoring import floor_step, means, under_floor from larv_review.scoring import floor_step, means, under_floor
from project_config.main import located
from release_plan import plan_file from release_plan import plan_file
from project_config.main import project
from larv_review.scoring_setup import removed_setup from larv_review.scoring_setup import removed_setup
from text_files.file_writes import replace_file from text_files.file_writes import replace_file
Say = typing.Callable[[str], None]
def record_ruling(votes_file: pathlib.Path) -> Failure | None:
read = read_seats(votes_file, paired=True) def record_ruling(votes_file: pathlib.Path, home: pathlib.Path, now: float) -> str | Failure:
"""Records the ruling the votes file's seats reach, and returns what the tool prints: the ruling and where it went, or which seats to launch where they split."""
read = read_seats(votes_file, True, home, now)
if isinstance(read, Failure): if isinstance(read, Failure):
return read return read
heading_read, seats_read = read heading_read, seats_read = read
@@ -30,27 +32,27 @@ def record_ruling(votes_file: pathlib.Path) -> Failure | None:
return Failure(f"{' and '.join(FIRST_SEATS)} both count as {overall_votes[0]} overall, which settles the ruling; drop the other seats' lines") return Failure(f"{' and '.join(FIRST_SEATS)} both count as {overall_votes[0]} overall, which settles the ruling; drop the other seats' lines")
tally = ", ".join(f"{seat.name} {vote_text(DIMENSIONS[-1], overall(written[seat.name]), overall(counts[seat.name]))}" for seat in seats_read.seats) tally = ", ".join(f"{seat.name} {vote_text(DIMENSIONS[-1], overall(written[seat.name]), overall(counts[seat.name]))}" for seat in seats_read.seats)
if split(overall_votes): if split(overall_votes):
print(f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the votes file, and run this again.") return f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the votes file, and run this again."
return None
ruled = ruling(overall_votes) ruled = ruling(overall_votes)
print(f"Ruling: {ruled}. Overall votes as counted: {tally}.") appended_to = append(seats_read.read, ruling_entry(heading_read.title, seats_read.seats, written, counts, ruled), home)
return append(seats_read.read, ruling_entry(heading_read.title, seats_read.seats, written, counts, ruled)) return appended_to if isinstance(appended_to, Failure) else f"Ruling: {ruled}. Overall votes as counted: {tally}.\n{appended_to}"
def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> Failure | None: def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int], home: pathlib.Path, now: float, say: Say, warn: Say) -> Failure | None:
read = read_seats(scores_file, paired=False) """Records the scoring run in the scores file and ranks the plan again. It says each result as it holds, since a later step may fail with the run already recorded."""
read = read_seats(scores_file, False, home, now)
if isinstance(read, Failure): if isinstance(read, Failure):
return read return read
named, given = read named, given = read
scoring = scored_seats(given) scoring = scored_seats(given)
if isinstance(scoring, Failure): if isinstance(scoring, Failure):
return scoring return scoring
reasons = plan_reasons(default, ids) reasons = plan_reasons(default, ids, home)
if isinstance(reasons, Failure): if isinstance(reasons, Failure):
return reasons return reasons
if not reasons: if not reasons:
return Failure("no plan item or release calls this scoring run; name the item IDs the chunk ships, as needs-scoring-run took them") return Failure("no plan item or release calls this scoring run; name the item IDs the chunk ships, as needs-scoring-run took them")
config = project() config = located(None, home)
if isinstance(config, Failure): if isinstance(config, Failure):
return config return config
checkout = str(config.top) checkout = str(config.top)
@@ -58,26 +60,31 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> F
if isinstance(todo, Failure): if isinstance(todo, Failure):
return todo return todo
_, plan = todo _, plan = todo
print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, scoring.means))}.") say(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, scoring.means))}.")
if under := under_floor(scoring.means): if under := under_floor(scoring.means):
print(f"Floor: {', '.join(under)} under the floor of {FLOOR}.") say(f"Floor: {', '.join(under)} under the floor of {FLOOR}.")
print(floor_step(scoring.means, plan, ids)) if step := floor_step(scoring.means, plan, ids):
if unrecorded := append(given.read, scoring_entry(named.title, scoring)): say(step)
return unrecorded appended_to = append(given.read, scoring_entry(named.title, scoring), home)
reranked = rerank() if isinstance(appended_to, Failure):
removed = removed_setup(checkout) return appended_to
say(appended_to)
reranked = rerank(home, warn)
removed = removed_setup(checkout, home)
return reranked or (removed and Failure(f"recorded the run, but {removed.reason}")) return reranked or (removed and Failure(f"recorded the run, but {removed.reason}"))
def rerank() -> Failure | None: def rerank(home: pathlib.Path, warn: Say) -> Failure | None:
"""Rank the project's todo.md again as rank_todo.py does, since the overall sets code health's weight, and fail where rank_todo.py would. The run stays recorded whatever happens, so those failures say to settle todo.md and run rank_todo.py on it, not to record the run again.""" """Rank the project's todo.md again as rank_todo.py does, since the overall sets code health's weight, and fail where rank_todo.py would. The run stays recorded whatever happens, so those failures say to settle todo.md and run rank_todo.py on it, not to record the run again."""
config = project() config = located(None, home)
if isinstance(config, Failure): if isinstance(config, Failure):
return config return config
todo = config.paths["plan"] todo = config.paths["plan"]
ranked = plan_file.rank_file(todo, config) ranked = plan_file.rank_file(todo, config)
if isinstance(ranked, Failure): if isinstance(ranked, Failure):
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again") return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
for line in plan_file.report_lines(todo, ranked):
warn(line)
if ranked.under_bar: if ranked.under_bar:
return Failure(f"recorded the run and ranked {todo}, but the lines above name items now under the bar. Settle each as its line says, then run rank_todo.py on {todo}, not record-scoring again") return Failure(f"recorded the run and ranked {todo}, but the lines above name items now under the bar. Settle each as its line says, then run rank_todo.py on {todo}, not record-scoring again")
return None return None
@@ -90,16 +97,16 @@ def scored_seats(given: SeatsFile) -> ScoringRun | Failure:
return ScoringRun(given.seats, found, means(list(found.values()))) return ScoringRun(given.seats, found, means(list(found.values())))
def read_seats(path: pathlib.Path, paired: bool) -> tuple[Heading, SeatsFile] | Failure: def read_seats(path: pathlib.Path, paired: bool, home: pathlib.Path, now: float) -> tuple[Heading, SeatsFile] | Failure:
"""The heading the seats file's entry goes under, and the file, as decided says. Its callers run it first, so a file it refuses fails before anything is printed.""" """The heading the seats file's entry goes under, and the file, as decided says. Its callers run it first, so a file it refuses fails before anything is printed."""
try: try:
text = path.read_text(encoding="utf-8") text = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as failure: except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read {path}: {failure}") return Failure(f"could not read {path}: {failure}")
history = history_file() history = history_file(home)
if isinstance(history, Failure): if isinstance(history, Failure):
return history return history
return decided(text, time.time(), paired, commit_exists, history) return decided(text, now, paired, commit_exists, history)
def decided(text: str, now: float, paired: bool, commit_known: typing.Callable[[str], bool], history: tuple[pathlib.Path, str]) -> tuple[Heading, SeatsFile] | Failure: def decided(text: str, now: float, paired: bool, commit_known: typing.Callable[[str], bool], history: tuple[pathlib.Path, str]) -> tuple[Heading, SeatsFile] | Failure:
@@ -117,12 +124,9 @@ def decided(text: str, now: float, paired: bool, commit_known: typing.Callable[[
return named, given return named, given
def show_places() -> Failure | None: def read_places(home: pathlib.Path) -> str | Failure:
history = history_file() history = history_file(home)
if isinstance(history, Failure): return history if isinstance(history, Failure) else places_report(history[1])
return history
print(places_report(history[1]))
return None
def places_report(history: str) -> str: def places_report(history: str) -> str:
@@ -130,17 +134,14 @@ def places_report(history: str) -> str:
return (latest_places(history) or "Seats found no places hard.").rstrip("\n") return (latest_places(history) or "Seats found no places hard.").rstrip("\n")
def show_agreement() -> Failure | None: def read_agreement(home: pathlib.Path) -> str | Failure:
history = history_file() history = history_file(home)
if isinstance(history, Failure): return history if isinstance(history, Failure) else agreement_report(history[1])
return history
print(agreement_report(history[1]))
return None
def history_file() -> tuple[pathlib.Path, str] | Failure: def history_file(home: pathlib.Path) -> tuple[pathlib.Path, str] | Failure:
"""The project's comprehension history, where its config puts it, and its text, empty when the file is missing.""" """The project's comprehension history, where its config puts it, and its text, empty when the file is missing."""
config = project() config = located(None, home)
if isinstance(config, Failure): if isinstance(config, Failure):
return config return config
history = config.paths["comprehension-history"] history = config.paths["comprehension-history"]
@@ -150,9 +151,9 @@ def history_file() -> tuple[pathlib.Path, str] | Failure:
return Failure(f"could not read {history}: {failure}") return Failure(f"could not read {history}: {failure}")
def append(read: str, entry: str) -> Failure | None: def append(read: str, entry: str, home: pathlib.Path) -> str | Failure:
"""Append entry unless the history already holds one on what the seats read.""" """Append entry unless the history already holds one on what the seats read; what the tool prints once it has."""
read_history = history_file() read_history = history_file(home)
if isinstance(read_history, Failure): if isinstance(read_history, Failure):
return read_history return read_history
history, text = read_history history, text = read_history
@@ -164,5 +165,4 @@ def append(read: str, entry: str) -> Failure | None:
return Failure(f"could not create {history.parent}: {failure}") return Failure(f"could not create {history.parent}: {failure}")
if unwritten := replace_file(history, appended(text, entry).encode()): if unwritten := replace_file(history, appended(text, entry).encode()):
return Failure(f"could not write {history}: {unwritten.reason}") return Failure(f"could not write {history}: {unwritten.reason}")
print(f"Appended to {history}.") return f"Appended to {history}."
return None
+22 -17
View File
@@ -156,6 +156,7 @@ folder.
import pathlib import pathlib
import re import re
import sys import sys
import time
import typing import typing
from git_cli.git_repo import branch_titles, default_branch, git, top from git_cli.git_repo import branch_titles, default_branch, git, top
@@ -171,7 +172,7 @@ from larv_review.owed import owed_scoring_run
from review_rules.review_passes import PASSES, REVIEWERS from review_rules.review_passes import PASSES, REVIEWERS
from larv_review.plan import plan_reasons from larv_review.plan import plan_reasons
from larv_review.scoring_setup import prepare_scoring from larv_review.scoring_setup import prepare_scoring
from larv_review.history_commands import record_ruling, record_scoring, show_agreement, show_places from larv_review.history_commands import read_agreement, read_places, record_ruling, record_scoring
from larv_review.reviewer_header import reviewer_header from larv_review.reviewer_header import reviewer_header
@@ -195,7 +196,7 @@ def are_ids(given: list[str]) -> bool:
def run_needs_scoring_run(given: list[str]) -> Failure | None: def run_needs_scoring_run(given: list[str]) -> Failure | None:
return with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False) return with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given], pathlib.Path.home()), stale_ok=False)
def fits_prepare_scoring(given: list[str]) -> bool: def fits_prepare_scoring(given: list[str]) -> bool:
@@ -203,7 +204,7 @@ def fits_prepare_scoring(given: list[str]) -> bool:
def run_record_scoring(given: list[str]) -> Failure | None: def run_record_scoring(given: list[str]) -> Failure | None:
return with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False) return with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]], pathlib.Path.home(), time.time(), print, warn), stale_ok=False)
def fits_reviewer_header(given: list[str]) -> bool: def fits_reviewer_header(given: list[str]) -> bool:
@@ -211,21 +212,21 @@ def fits_reviewer_header(given: list[str]) -> bool:
def run_reviewer_header(given: list[str]) -> Failure | None: def run_reviewer_header(given: list[str]) -> Failure | None:
return with_default_branch(lambda default: reviewer_header(default, given[0], given[1:] == ["--rerun"]), stale_ok=True) return with_default_branch(lambda default: printed(reviewer_header(default, given[0], given[1:] == ["--rerun"], pathlib.Path.home())), stale_ok=True)
# One row per subcommand: main, USAGE and `--help` all read this table. # One row per subcommand: main, USAGE and `--help` all read this table.
COMMANDS = { COMMANDS = {
"review-folder": Command("review-folder", no_arguments, lambda given: make_review_folder()), "review-folder": Command("review-folder", no_arguments, lambda given: make_review_folder()),
"ruling-base": Command("ruling-base", no_arguments, lambda given: with_default_branch(show_ruling_base, stale_ok=False)), "ruling-base": Command("ruling-base", no_arguments, lambda given: with_default_branch(lambda default: show_ruling_base(default, pathlib.Path.home()), stale_ok=False)),
"round-count": Command("round-count", no_arguments, lambda given: with_default_branch(round_count, stale_ok=True)), "round-count": Command("round-count", no_arguments, lambda given: with_default_branch(round_count, stale_ok=True)),
"needs-scoring-run": Command("needs-scoring-run [<item ID>...]", are_ids, run_needs_scoring_run, ids_from=0), "needs-scoring-run": Command("needs-scoring-run [<item ID>...]", are_ids, run_needs_scoring_run, ids_from=0),
"scoring-run-owed": Command("scoring-run-owed", no_arguments, lambda given: with_default_branch(owed, stale_ok=False)), "scoring-run-owed": Command("scoring-run-owed", no_arguments, lambda given: with_default_branch(lambda default: owed(default, pathlib.Path.home()), stale_ok=False)),
"record-ruling": Command("record-ruling <votes file>", lambda given: len(given) == 1, lambda given: record_ruling(pathlib.Path(given[0]))), "record-ruling": Command("record-ruling <votes file>", lambda given: len(given) == 1, lambda given: printed(record_ruling(pathlib.Path(given[0]), pathlib.Path.home(), time.time()))),
"prepare-scoring": Command("prepare-scoring [--preloaded <text>]", fits_prepare_scoring, lambda given: prepared_scoring(given[1] if given else None)), "prepare-scoring": Command("prepare-scoring [--preloaded <text>]", fits_prepare_scoring, lambda given: prepared_scoring(given[1] if given else None)),
"record-scoring": Command("record-scoring <scores file> [<item ID>...]", lambda given: bool(given) and are_ids(given[1:]), run_record_scoring, ids_from=1), "record-scoring": Command("record-scoring <scores file> [<item ID>...]", lambda given: bool(given) and are_ids(given[1:]), run_record_scoring, ids_from=1),
"places": Command("places", no_arguments, lambda given: show_places()), "places": Command("places", no_arguments, lambda given: printed(read_places(pathlib.Path.home()))),
"agreement": Command("agreement", no_arguments, lambda given: show_agreement()), "agreement": Command("agreement", no_arguments, lambda given: printed(read_agreement(pathlib.Path.home()))),
"reviewer-header": Command("reviewer-header <pass> [--rerun]", fits_reviewer_header, run_reviewer_header), "reviewer-header": Command("reviewer-header <pass> [--rerun]", fits_reviewer_header, run_reviewer_header),
"reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), pathlib.Path.home()))), "reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), pathlib.Path.home()))),
} }
@@ -256,6 +257,10 @@ def main(argv: list[str]) -> int:
return 0 return 0
def warn(line: str) -> None:
print(line, file=sys.stderr)
def printed(reply: str | Failure) -> Failure | None: def printed(reply: str | Failure) -> Failure | None:
if isinstance(reply, Failure): if isinstance(reply, Failure):
return reply return reply
@@ -276,22 +281,22 @@ def with_default_branch(command: typing.Callable[[str], Failure | None], stale_o
def prepared_scoring(preloaded: str | None) -> Failure | None: def prepared_scoring(preloaded: str | None) -> Failure | None:
worktree = top() worktree = top()
return worktree if isinstance(worktree, Failure) else printed(prepare_scoring(worktree, preloaded)) return worktree if isinstance(worktree, Failure) else printed(prepare_scoring(worktree, preloaded, pathlib.Path.home()))
def make_review_folder() -> Failure | None: def make_review_folder() -> Failure | None:
worktree = top() worktree = top()
if isinstance(worktree, Failure): if isinstance(worktree, Failure):
return worktree return worktree
folder = made_review_folder(worktree) folder = made_review_folder(worktree, pathlib.Path.home())
if isinstance(folder, Failure): if isinstance(folder, Failure):
return folder return folder
print(folder) print(folder)
return None return None
def show_ruling_base(default: str) -> Failure | None: def show_ruling_base(default: str, home: pathlib.Path) -> Failure | None:
changes = history_changes(default) changes = history_changes(default, home)
if isinstance(changes, Failure): if isinstance(changes, Failure):
return changes return changes
if found := measured_commit(changes): if found := measured_commit(changes):
@@ -319,15 +324,15 @@ def cap_note(count: int, most: int) -> str:
return f", {'at' if count == most else 'past'} the cap: no more rounds" return f", {'at' if count == most else 'past'} the cap: no more rounds"
def owed(default: str) -> Failure | None: def owed(default: str, home: pathlib.Path) -> Failure | None:
unrecorded = owed_scoring_run(default) unrecorded = owed_scoring_run(default, home, warn)
if unrecorded is None: if unrecorded is None:
print("No scoring run owed.") print("No scoring run owed.")
return unrecorded return unrecorded
def needs_scoring_run(default: str, ids: list[int]) -> Failure | None: def needs_scoring_run(default: str, ids: list[int], home: pathlib.Path) -> Failure | None:
reasons = plan_reasons(default, ids) reasons = plan_reasons(default, ids, home)
if isinstance(reasons, Failure): if isinstance(reasons, Failure):
return reasons return reasons
print(f"Scoring run due: the chunk {' and '.join(reasons)}." if reasons else "No scoring run due.") print(f"Scoring run due: the chunk {' and '.join(reasons)}." if reasons else "No scoring run due.")
+6 -6
View File
@@ -1,20 +1,20 @@
import pathlib import pathlib
import sys import typing
from larv_review.plan import EMPTIED_WORDS, plan_reasons from larv_review.plan import EMPTIED_WORDS, plan_reasons
from review_rules.comprehension_history import entries from review_rules.comprehension_history import entries
from failure import Failure from failure import Failure
from git_cli.git_repo import file_at, git from git_cli.git_repo import file_at, git
from release_plan.todo_table import items, NoItemsTable from release_plan.todo_table import items, NoItemsTable
from project_config.main import project from project_config.main import located
def owed_scoring_run(default: str) -> Failure | None: def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[str], None]) -> Failure | None:
"""A Failure saying which scoring runs the chunk owes and has not recorded; None where it owes none. """A Failure saying which scoring runs the chunk owes and has not recorded; None where it owes none.
The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began doesn't count. A project with no plan owes none. Neither does one whose plan or history is outside the checkout: it says on stderr that it cannot tell. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking. The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began doesn't count. A project with no plan owes none. Neither does one whose plan or history is outside the checkout: it says on stderr that it cannot tell. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking.
""" """
config = project() config = located(None, home)
if isinstance(config, Failure): if isinstance(config, Failure):
return config return config
checkout = str(config.top) checkout = str(config.top)
@@ -24,12 +24,12 @@ def owed_scoring_run(default: str) -> Failure | None:
plan, history = config.tracked("plan"), config.tracked("comprehension-history") plan, history = config.tracked("plan"), config.tracked("comprehension-history")
if plan is None or history is None: if plan is None or history is None:
name, setting = ("plan", "plan") if plan is None else ("comprehension history", "comprehension-history") name, setting = ("plan", "plan") if plan is None else ("comprehension history", "comprehension-history")
print(f"larv-review doesn't support a {name} outside the checkout, so it cannot tell whether the chunk owes a scoring run: {config.paths[setting]}", file=sys.stderr) warn(f"larv-review doesn't support a {name} outside the checkout, so it cannot tell whether the chunk owes a scoring run: {config.paths[setting]}")
return None return None
base = git("merge-base", default, "HEAD", cwd=checkout) base = git("merge-base", default, "HEAD", cwd=checkout)
if isinstance(base, Failure): if isinstance(base, Failure):
return base return base
reasons = plan_reasons(base.strip(), None) reasons = plan_reasons(base.strip(), None, home)
if isinstance(reasons, Failure): if isinstance(reasons, Failure):
return reasons return reasons
if not reasons: if not reasons:
+3 -3
View File
@@ -4,8 +4,8 @@ from release_plan.release_standing import Cut, default_plan, held_at, LastCut, n
from failure import Failure from failure import Failure
from larv_review.scoring import is_floor_item from larv_review.scoring import is_floor_item
from release_plan.todo_table import Item, items, NoItemsTable, renames from release_plan.todo_table import Item, items, NoItemsTable, renames
from project_config.main import located
from release_plan.goals_file import OPTED_OUT from release_plan.goals_file import OPTED_OUT
from project_config.main import project
from release_plan.release import Release, version from release_plan.release import Release, version
from larv_review.unmeasured import unmeasured_cut from larv_review.unmeasured import unmeasured_cut
@@ -63,9 +63,9 @@ def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed:
return sorted(named - {item.release for item in kept} - renamed) return sorted(named - {item.release for item in kept} - renamed)
def plan_reasons(ref: str, ids: list[int] | None) -> list[str] | Failure: def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[str] | Failure:
"""Why the plan calls a scoring run, from todo.md at ref and the checkout's, each file where the project's config puts it; empty where the project opts out of the comprehension check. ref is the default branch, or the commit where the chunk began. Where ids is None, the chunk ships each item the plan at ref holds and the checkout's does not.""" """Why the plan calls a scoring run, from todo.md at ref and the checkout's, each file where the project's config puts it; empty where the project opts out of the comprehension check. ref is the default branch, or the commit where the chunk began. Where ids is None, the chunk ships each item the plan at ref holds and the checkout's does not."""
config = project() config = located(None, home)
if isinstance(config, Failure): if isinstance(config, Failure):
return config return config
checkout = str(config.top) checkout = str(config.top)
+8 -9
View File
@@ -66,7 +66,7 @@ def unanswered_round(titles: list[str], pass_: str) -> int | Failure:
return done + 1 return done + 1
def reviewer_header(default: str, pass_: str, rerun: bool) -> Failure | None: def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -> str | Failure:
"""Writes the branch diff and the places into the review folder, and prints the header that launches pass_'s reviewer in the pass's unanswered round, or its relaunch one rung up where rerun.""" """Writes the branch diff and the places into the review folder, and prints the header that launches pass_'s reviewer in the pass's unanswered round, or its relaunch one rung up where rerun."""
titles = branch_titles(default) titles = branch_titles(default)
if isinstance(titles, Failure): if isinstance(titles, Failure):
@@ -79,32 +79,31 @@ def reviewer_header(default: str, pass_: str, rerun: bool) -> Failure | None:
if failed is not None: if failed is not None:
return failed return failed
worktree, branch, head, base = (str(answer).strip() for answer in found) worktree, branch, head, base = (str(answer).strip() for answer in found)
folder = made_review_folder(worktree) folder = made_review_folder(worktree, home)
if isinstance(folder, Failure): if isinstance(folder, Failure):
return folder return folder
config = located(None, pathlib.Path.home()) config = located(None, home)
if isinstance(config, Failure): if isinstance(config, Failure):
return config return config
principles = config.paths["principles"] principles = config.paths["principles"]
# A typo in the config would otherwise hand every reviewer an empty folder, and the review would run with no principles. # A typo in the config would otherwise hand every reviewer an empty folder, and the review would run with no principles.
if not principles.is_dir() or not any(principles.iterdir()): if not principles.is_dir() or not any(principles.iterdir()):
return Failure(f"{principles} is not a folder with a file in it; {config.folder / 'config.toml'} sets it as `principles`") return Failure(f"{principles} is not a folder with a file in it; {config.folder / 'config.toml'} sets it as `principles`")
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, config.paths["goals-and-audience"], starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), pathlib.Path.home()), config.paths["working-rules"], config.paths["decisions"]) launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, config.paths["goals-and-audience"], starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], config.paths["decisions"])
if rerun and not launch.asked().exists(): if rerun and not launch.asked().exists():
return Failure(f"no report asked for a rerun of {pass_}'s round {round_}: {launch.asked()} is missing; relaunch before you commit the round's answers") return Failure(f"no report asked for a rerun of {pass_}'s round {round_}: {launch.asked()} is missing; relaunch before you commit the round's answers")
written = write_inputs(launch, base) written = write_inputs(launch, base, home)
if isinstance(written, Failure): if isinstance(written, Failure):
return written return written
print(launch.header()) return launch.header()
return None
def write_inputs(launch: Launch, base: str) -> Failure | None: def write_inputs(launch: Launch, base: str, home: pathlib.Path) -> Failure | None:
"""Writes the branch diff from base to HEAD and what `larv-review places` prints into the review folder.""" """Writes the branch diff from base to HEAD and what `larv-review places` prints into the review folder."""
diff = git("diff", base, "HEAD", errors="replace") diff = git("diff", base, "HEAD", errors="replace")
if isinstance(diff, Failure): if isinstance(diff, Failure):
return diff return diff
history = history_file() history = history_file(home)
if isinstance(history, Failure): if isinstance(history, Failure):
return history return history
try: try:
+15 -9
View File
@@ -151,13 +151,12 @@ def scoring_folder(worktree: str, home: pathlib.Path) -> pathlib.Path:
return pathlib.Path(review_folder(str(home), worktree)) / "scoring" return pathlib.Path(review_folder(str(home), worktree)) / "scoring"
def prepare_scoring(worktree: str, preloaded: str | None) -> str | Failure: def prepare_scoring(worktree: str, preloaded: str | None, home: pathlib.Path) -> str | Failure:
"""Makes the scoring run's worktree at worktree's HEAD and writes each seat's prompt beside it, in the chunk's review folder; what it made, as the tool prints it.""" """Makes the scoring run's worktree at worktree's HEAD and writes each seat's prompt beside it, in the chunk's review folder; what it made, as the tool prints it."""
home = pathlib.Path.home()
folder = scoring_folder(worktree, home) folder = scoring_folder(worktree, home)
# A setup record-scoring never removed, as where the seats failed, would otherwise block every later run. # A setup record-scoring never removed, as where the seats failed, would otherwise block every later run.
replaced = folder.exists() replaced = folder.exists()
if replaced and isinstance(removed := removed_setup(worktree), Failure): if replaced and isinstance(removed := removed_setup(worktree, home), Failure):
return removed return removed
config = located(worktree, home) config = located(worktree, home)
if isinstance(config, Failure): if isinstance(config, Failure):
@@ -166,13 +165,17 @@ def prepare_scoring(worktree: str, preloaded: str | None) -> str | Failure:
source = config.paths["working-rules"] source = config.paths["working-rules"]
if not source.is_file() and (own := pathlib.Path(worktree) / "skills" / "comprehension-panel" / "seat-prompts.md").is_file(): if not source.is_file() and (own := pathlib.Path(worktree) / "skills" / "comprehension-panel" / "seat-prompts.md").is_file():
source = own source = own
values = project_values(source.read_text() if source.is_file() else "", source.name) try:
rules, skill = source.read_text() if source.is_file() else "", (PANEL / "SKILL.md").read_text()
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"could not read what the seats' prompts quote: {failure}")
values = project_values(rules, source.name)
if isinstance(values, Failure): if isinstance(values, Failure):
return values return values
parts = prompt_parts() parts = prompt_parts()
if isinstance(parts, Failure): if isinstance(parts, Failure):
return parts return parts
score = score_bullets((PANEL / "SKILL.md").read_text()) score = score_bullets(skill)
if isinstance(score, Failure): if isinstance(score, Failure):
return score return score
listing = git("worktree", "list", "--porcelain", cwd=worktree) listing = git("worktree", "list", "--porcelain", cwd=worktree)
@@ -183,7 +186,7 @@ def prepare_scoring(worktree: str, preloaded: str | None) -> str | Failure:
if isinstance(head, Failure): if isinstance(head, Failure):
return head return head
main = listing.splitlines()[0].removeprefix("worktree ") main = listing.splitlines()[0].removeprefix("worktree ")
made = made_review_folder(worktree) made = made_review_folder(worktree, home)
if isinstance(made, Failure): if isinstance(made, Failure):
return made return made
checkout = folder / "checkout" checkout = folder / "checkout"
@@ -211,15 +214,18 @@ def prepare_scoring(worktree: str, preloaded: str | None) -> str | Failure:
for name, label, report in SEATS: for name, label, report in SEATS:
prompt = "\n\n".join((parts["Opening"], parts[label], parts["Shared brief"], parts[report])) prompt = "\n\n".join((parts["Opening"], parts[label], parts["Shared brief"], parts[report]))
path = folder / f"{name}.md" path = folder / f"{name}.md"
path.write_text(placeholder.sub(lambda found: filled[found.group(1)], prompt) + "\n") try:
path.write_text(placeholder.sub(lambda found: filled[found.group(1)], prompt) + "\n")
except OSError as failure:
return Failure(f"could not write the seat's prompt {path}: {failure}")
written.append(str(path)) written.append(str(path))
before = f"Removed the scoring run set up before in {folder}.\n" if replaced else "" before = f"Removed the scoring run set up before in {folder}.\n" if replaced else ""
return before + f"Scoring worktree, at {head.strip()}: {checkout}\nPrompts:\n" + "\n".join(written) return before + f"Scoring worktree, at {head.strip()}: {checkout}\nPrompts:\n" + "\n".join(written)
def removed_setup(worktree: str) -> Failure | None: def removed_setup(worktree: str, home: pathlib.Path) -> Failure | None:
"""Removes the scoring worktree and prompts prepare_scoring made for the chunk at worktree, where they exist.""" """Removes the scoring worktree and prompts prepare_scoring made for the chunk at worktree, where they exist."""
folder = scoring_folder(worktree, pathlib.Path.home()) folder = scoring_folder(worktree, home)
if not folder.exists(): if not folder.exists():
return None return None
if (folder / "checkout").exists() and isinstance(removed := git("worktree", "remove", "--force", str(folder / "checkout"), cwd=worktree), Failure): if (folder / "checkout").exists() and isinstance(removed := git("worktree", "remove", "--force", str(folder / "checkout"), cwd=worktree), Failure):
+5 -5
View File
@@ -577,15 +577,15 @@ class LarvReviewTool(unittest.TestCase):
self.addCleanup(os.chdir, os.getcwd()) self.addCleanup(os.chdir, os.getcwd())
os.chdir(self.checkout) os.chdir(self.checkout)
with unittest.mock.patch.dict(os.environ, {"HOME": str(self.config.parents[2])}): with unittest.mock.patch.dict(os.environ, {"HOME": str(self.config.parents[2])}):
self.assertEqual(plan_reasons("origin/main", [2]), ["ships item 2, a floor item", "leaves release 0.2.0 with no plan item"]) self.assertEqual(plan_reasons("origin/main", [2], pathlib.Path.home()), ["ships item 2, a floor item", "leaves release 0.2.0 with no plan item"])
(self.config.parent / "decisions.md").write_text("# Decisions\n\n## review opt-out: the comprehension check\n\nServes goal 1.\n") (self.config.parent / "decisions.md").write_text("# Decisions\n\n## review opt-out: the comprehension check\n\nServes goal 1.\n")
self.assertEqual(plan_reasons("origin/main", [2]), []) self.assertEqual(plan_reasons("origin/main", [2], pathlib.Path.home()), [])
(self.config.parent / "decisions.md").unlink() (self.config.parent / "decisions.md").unlink()
gone = plan_reasons("origin/main", [1, 7]) gone = plan_reasons("origin/main", [1, 7], pathlib.Path.home())
assert isinstance(gone, Failure), gone assert isinstance(gone, Failure), gone
self.assertEqual(gone.reason, f"todo.md as it stands holds no item 7, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {self.config.parent}/todo.md") self.assertEqual(gone.reason, f"todo.md as it stands holds no item 7, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {self.config.parent}/todo.md")
(self.config.parent / "todo.md").write_bytes(b"\xff") (self.config.parent / "todo.md").write_bytes(b"\xff")
unreadable = plan_reasons("origin/main", [2]) unreadable = plan_reasons("origin/main", [2], pathlib.Path.home())
assert isinstance(unreadable, Failure), unreadable assert isinstance(unreadable, Failure), unreadable
self.assertTrue(unreadable.reason.startswith(f"cannot read {self.config.parent}/todo.md: "), unreadable.reason) self.assertTrue(unreadable.reason.startswith(f"cannot read {self.config.parent}/todo.md: "), unreadable.reason)
@@ -745,7 +745,7 @@ class LarvReviewTool(unittest.TestCase):
def test_refuses_where_the_default_branchs_unreleased_changes_cannot_be_read(self): def test_refuses_where_the_default_branchs_unreleased_changes_cannot_be_read(self):
self.addCleanup(os.chdir, os.getcwd()) self.addCleanup(os.chdir, os.getcwd())
os.chdir(self.checkout) os.chdir(self.checkout)
self.assertIsInstance(plan_reasons("no-such-ref", []), Failure) self.assertIsInstance(plan_reasons("no-such-ref", [], pathlib.Path.home()), Failure)
def test_refuses_a_checkout_plan_whose_renamed_section_does_not_parse(self): def test_refuses_a_checkout_plan_whose_renamed_section_does_not_parse(self):
self.commit("Break the mark", {"todo.md": todo("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |") + "\n## Renamed\n\nsoon\n"}) self.commit("Break the mark", {"todo.md": todo("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |") + "\n## Renamed\n\nsoon\n"})
+2 -2
View File
@@ -104,7 +104,7 @@ class PrepareScoring(unittest.TestCase):
def prepare(self, preloaded=None): def prepare(self, preloaded=None):
"""What prepare-scoring returns in the checkout, run in this process so mutation tests see the lines it runs.""" """What prepare-scoring returns in the checkout, run in this process so mutation tests see the lines it runs."""
with mock.patch.dict(os.environ, self.env, clear=True): with mock.patch.dict(os.environ, self.env, clear=True):
return prepare_scoring(str(self.checkout), preloaded) return prepare_scoring(str(self.checkout), preloaded, pathlib.Path.home())
def run_tool(self, *args): def run_tool(self, *args):
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True) return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True)
@@ -141,7 +141,7 @@ class PrepareScoring(unittest.TestCase):
checkout = self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" / "checkout" checkout = self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" / "checkout"
checkout.mkdir(parents=True) checkout.mkdir(parents=True)
with mock.patch.dict(os.environ, self.env, clear=True): with mock.patch.dict(os.environ, self.env, clear=True):
removed = removed_setup(str(self.checkout)) removed = removed_setup(str(self.checkout), pathlib.Path.home())
self.assertIsInstance(removed, Failure) self.assertIsInstance(removed, Failure)
self.assertTrue(removed.reason.startswith(f"could not remove the scoring worktree {checkout}: "), removed.reason) self.assertTrue(removed.reason.startswith(f"could not remove the scoring worktree {checkout}: "), removed.reason)
self.assertTrue(checkout.exists()) self.assertTrue(checkout.exists())
+2 -2
View File
@@ -19,8 +19,8 @@ def slot_count(cpus: int | None) -> int:
return max(1, (cpus or 0) // CPUS_PER_SLOT) return max(1, (cpus or 0) // CPUS_PER_SLOT)
def slot_folder(env: typing.Mapping[str, str]) -> pathlib.Path: def slot_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Path:
state = env.get("XDG_STATE_HOME") or str(pathlib.Path.home() / ".local" / "state") state = env.get("XDG_STATE_HOME") or str(home / ".local" / "state")
return pathlib.Path(state) / "run-heavy" return pathlib.Path(state) / "run-heavy"
+2 -2
View File
@@ -51,8 +51,8 @@ class SlotShare(unittest.TestCase):
class SlotFolder(unittest.TestCase): class SlotFolder(unittest.TestCase):
def test_every_session_shares_the_slots_under_the_users_state_folder(self): def test_every_session_shares_the_slots_under_the_users_state_folder(self):
self.assertEqual(slots.slot_folder({}), pathlib.Path.home() / ".local" / "state" / "run-heavy") self.assertEqual(slots.slot_folder({}, pathlib.Path.home()), pathlib.Path.home() / ".local" / "state" / "run-heavy")
self.assertEqual(slots.slot_folder({"XDG_STATE_HOME": "/s"}), pathlib.Path("/s/run-heavy")) self.assertEqual(slots.slot_folder({"XDG_STATE_HOME": "/s"}, pathlib.Path.home()), pathlib.Path("/s/run-heavy"))
class TakenSlot(unittest.TestCase): class TakenSlot(unittest.TestCase):
+1 -1
View File
@@ -56,7 +56,7 @@ class Route:
escalated_at: int = 0 escalated_at: int = 0
def __post_init__(self) -> None: def __post_init__(self) -> None:
# Raises on a programming error only, so nothing catches it: route_of checks fits before it builds a route. # Raises on a programming error only, so nothing catches it: route_of checks fits before it builds a route, and todo_table.items gives first_route only levels on their scales.
if not levels_fit(self.item, self.likelihood, self.escape_and_impact, self.escape_and_impact_taken_in): if not levels_fit(self.item, self.likelihood, self.escape_and_impact, self.escape_and_impact_taken_in):
raise ValueError(f"a route by item {self.item} cannot hold an L of {self.likelihood}, an E + I of {self.escape_and_impact} and an E + I taken in of {self.escape_and_impact_taken_in}") raise ValueError(f"a route by item {self.item} cannot hold an L of {self.likelihood}, an E + I of {self.escape_and_impact} and an E + I taken in of {self.escape_and_impact_taken_in}")
+3 -3
View File
@@ -9,7 +9,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure from failure import Failure
from project_config.settings import held, load, ProjectConfig from project_config.settings import held, load, ProjectConfig, SETTINGS
from test_env import isolated_env from test_env import isolated_env
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-config" TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-config"
@@ -79,7 +79,7 @@ class LoadTest(ConfigCase):
self.assertEqual(found.paths["decisions"], folder / "docs" / "decisions.md") self.assertEqual(found.paths["decisions"], folder / "docs" / "decisions.md")
self.assertEqual(found.paths["changelog"], self.checkout / "CHANGELOG.md") self.assertEqual(found.paths["changelog"], self.checkout / "CHANGELOG.md")
self.assertEqual(found.paths["principles"], self.home / ".claude" / "principles") self.assertEqual(found.paths["principles"], self.home / ".claude" / "principles")
self.assertEqual(len(found.paths), 9) self.assertEqual(tuple(found.paths), SETTINGS)
def test_a_worktree_finds_the_main_checkouts_config_and_reads_its_own_files(self) -> None: def test_a_worktree_finds_the_main_checkouts_config_and_reads_its_own_files(self) -> None:
self.write("acme", CLIENT) self.write("acme", CLIENT)
@@ -207,7 +207,7 @@ class ToolTest(ConfigCase):
everything = self.run_tool() everything = self.run_tool()
self.assertEqual((everything.returncode, everything.stderr), (0, "")) self.assertEqual((everything.returncode, everything.stderr), (0, ""))
self.assertEqual(everything.stdout.splitlines()[0], f"plan: {folder}/todo.md") self.assertEqual(everything.stdout.splitlines()[0], f"plan: {folder}/todo.md")
self.assertEqual(len(everything.stdout.splitlines()), 9) self.assertEqual(tuple(line.split(": ")[0] for line in everything.stdout.splitlines()), SETTINGS)
(self.checkout / "src").mkdir() (self.checkout / "src").mkdir()
one = self.run_tool("changelog", cwd=self.checkout / "src") one = self.run_tool("changelog", cwd=self.checkout / "src")
self.assertEqual((one.returncode, one.stdout), (0, f"{self.checkout}/CHANGELOG.md\n")) self.assertEqual((one.returncode, one.stdout), (0, f"{self.checkout}/CHANGELOG.md\n"))
+2
View File
@@ -118,6 +118,8 @@ def main(argv: list[str]) -> int:
ranked = plan_file.rank_file(todo, config) ranked = plan_file.rank_file(todo, config)
if isinstance(ranked, Failure): if isinstance(ranked, Failure):
return fail(ranked) return fail(ranked)
for line in plan_file.report_lines(todo, ranked):
print(line, file=sys.stderr)
return 1 if ranked.under_bar else 0 return 1 if ranked.under_bar else 0
+4 -7
View File
@@ -1,6 +1,5 @@
"""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.""" """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 pathlib
import sys
from failure import Failure from failure import Failure
from project_config.settings import ProjectConfig from project_config.settings import ProjectConfig
@@ -9,7 +8,7 @@ from text_files.file_writes import replace_file
def rank_file(todo: pathlib.Path, config: ProjectConfig) -> 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.""" """Rank todo in place: rank what read_all reads, and write todo where that changed it. The caller prints `report_lines`."""
texts = read_all(todo, config) texts = read_all(todo, config)
if isinstance(texts, Failure): if isinstance(texts, Failure):
return texts return texts
@@ -18,14 +17,12 @@ def rank_file(todo: pathlib.Path, config: ProjectConfig) -> Ranked | Failure:
return ranked return ranked
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)): if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
return unwritten return unwritten
print_report(todo, ranked)
return ranked return ranked
def print_report(todo: pathlib.Path, ranked: Ranked) -> None: def report_lines(todo: pathlib.Path, ranked: Ranked) -> list[str]:
"""Print ranking's notes and under-bar lines on stderr, each prefixed with todo's path.""" """Ranking's notes and under-bar lines, each prefixed with todo's path, as a tool prints them on stderr."""
for line in ranked.notes + ranked.under_bar: return [f"{todo}: {line}" for line in ranked.notes + ranked.under_bar]
print(f"{todo}: {line}", file=sys.stderr)
def check_failures(todo: pathlib.Path, config: ProjectConfig) -> list[str]: def check_failures(todo: pathlib.Path, config: ProjectConfig) -> list[str]:
+1 -2
View File
@@ -14,9 +14,8 @@ def review_folder(home: str, worktree: str) -> str:
return os.path.join(home, REPORTS, os.path.relpath(worktree, home) if inside else worktree.lstrip("/")) return os.path.join(home, REPORTS, os.path.relpath(worktree, home) if inside else worktree.lstrip("/"))
def made_review_folder(worktree: str) -> pathlib.Path | Failure: def made_review_folder(worktree: str, home: pathlib.Path) -> pathlib.Path | Failure:
"""Makes the review folder of the chunk whose worktree is at worktree, leaving REPORTS readable by the user alone, and returns its path.""" """Makes the review folder of the chunk whose worktree is at worktree, leaving REPORTS readable by the user alone, and returns its path."""
home = pathlib.Path.home()
folder = pathlib.Path(review_folder(str(home), worktree)) folder = pathlib.Path(review_folder(str(home), worktree))
try: try:
(home / REPORTS).mkdir(parents=True, exist_ok=True) (home / REPORTS).mkdir(parents=True, exist_ok=True)
+2 -1
View File
@@ -35,6 +35,7 @@ cannot read.
""" """
import json import json
import os import os
import pathlib
import sys import sys
import time import time
import typing import typing
@@ -118,5 +119,5 @@ def bash_breaches(command: str, cwd: str, home: str) -> list[Breach]:
found = commits(simples, home) found = commits(simples, home)
in_files = [breach for directory in dict.fromkeys(commit.directory for commit in found) for breach in committed_file_breaches(directory)] in_files = [breach for directory in dict.fromkeys(commit.directory for commit in found) for breach in committed_file_breaches(directory)]
round_cap = [breach for commit in found for breach in round_cap_breaches(commit)] round_cap = [breach for commit in found for breach in round_cap_breaches(commit)]
todo = [breach for commit in found for breach in todo_breaches(commit.directory)] todo = [breach for commit in found for breach in todo_breaches(commit.directory, pathlib.Path(home))]
return command_breaches(command, simples, home) + round_cap + todo + in_files return command_breaches(command, simples, home) + round_cap + todo + in_files
+15 -8
View File
@@ -75,14 +75,14 @@ class Commits(unittest.TestCase):
self.assertEqual(committed("cd a # go there\nGIT_EDITOR=true git commit -m x"), [CommitCall("/r/a", ["x"], False, False)]) self.assertEqual(committed("cd a # go there\nGIT_EDITOR=true git commit -m x"), [CommitCall("/r/a", ["x"], False, False)])
def test_a_commit_after_a_heredoc_or_a_blank_line_is_seen(self): def test_a_commit_after_a_heredoc_or_a_blank_line_is_seen(self):
self.assertEqual(len(committed("cat <<EOF > notes\nhello\nEOF\ngit commit -m a")), 1) self.assertEqual(committed("cat <<EOF > notes\nhello\nEOF\ngit commit -m a"), [CommitCall("/r", ["a"], False, False)])
self.assertEqual(len(committed("git status &&\n\ngit commit -m a")), 1) self.assertEqual(committed("git status &&\n\ngit commit -m a"), [CommitCall("/r", ["a"], False, False)])
def test_an_arithmetic_shift_is_no_heredoc(self): def test_an_arithmetic_shift_is_no_heredoc(self):
self.assertEqual(len(committed("echo $((1<<2))\ngit commit -m a\n2")), 1) self.assertEqual(committed("echo $((1<<2))\ngit commit -m a\n2"), [CommitCall("/r", ["a"], False, False)])
def test_a_line_that_does_not_parse_hides_only_itself(self): def test_a_line_that_does_not_parse_hides_only_itself(self):
self.assertEqual(len(committed("echo 'open\ngit commit -m a")), 1) self.assertEqual(committed("echo 'open\ngit commit -m a"), [CommitCall("/r", ["a"], False, False)])
def test_a_redirect_keeps_its_command_s_words_together(self): def test_a_redirect_keeps_its_command_s_words_together(self):
self.assertEqual(segments("echo hi > f arg"), [["echo", "hi", "arg"]]) self.assertEqual(segments("echo hi > f arg"), [["echo", "hi", "arg"]])
@@ -892,16 +892,23 @@ class TodoRankCheck(unittest.TestCase):
self.config = configured(self, pathlib.Path(checkout)) / "config.toml" self.config = configured(self, pathlib.Path(checkout)) / "config.toml"
return checkout return checkout
def test_a_changed_plan_that_cannot_be_read_is_a_breach(self):
checkout = self.changed_plan(self.other, "")
pathlib.Path(checkout, "todo.md").chmod(0)
self.addCleanup(pathlib.Path(checkout, "todo.md").chmod, 0o600)
self.assertEqual(len(self.details(checkout)), 1)
self.assertIn("Permission denied", self.details(checkout)[0])
def details(self, checkout: str) -> list[str]: def details(self, checkout: str) -> list[str]:
return [breach.detail for breach in todo_breaches(checkout, pathlib.Path(self.own))] return [breach.detail for breach in todo_breaches(checkout, pathlib.Path.home(), pathlib.Path(self.own))]
def test_a_checkout_of_the_hooks_repo_runs_its_own_rank_todo(self): def test_a_checkout_of_the_hooks_repo_runs_its_own_rank_todo(self):
checkout = self.changed_plan(f"{self.folder}/clone", self.STUB) checkout = self.changed_plan(f"{self.folder}/clone", self.STUB)
self.assertEqual(self.details(checkout), [f"own script checked {checkout}/todo.md"]) self.assertEqual(self.details(checkout), [f"own script checked {checkout}/todo.md"])
top = str(pathlib.Path(checkout).resolve()) top = str(pathlib.Path(checkout).resolve())
self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, pathlib.Path(self.own))], [("todo-rank-check", top)]) self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, pathlib.Path.home(), pathlib.Path(self.own))], [("todo-rank-check", top)])
self.config.unlink() self.config.unlink()
self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, pathlib.Path(self.own))], [("todo-rank-check", top)], "a todo.md with no config") self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, pathlib.Path.home(), pathlib.Path(self.own))], [("todo-rank-check", top)], "a todo.md with no config")
def test_its_own_rank_todo_passing_passes(self): def test_its_own_rank_todo_passing_passes(self):
self.assertEqual(self.details(self.changed_plan(f"{self.folder}/clone", "")), []) self.assertEqual(self.details(self.changed_plan(f"{self.folder}/clone", "")), [])
@@ -935,7 +942,7 @@ class TodoRankCheck(unittest.TestCase):
self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"'))
(self.config.parent / "todo.md").write_text("# todo\n") (self.config.parent / "todo.md").write_text("# todo\n")
self.assertEqual(self.details(folder), [f"own script checked {folder}/todo.md"], "checked with the checkout's own rank_todo.py, as a commit there would be") self.assertEqual(self.details(folder), [f"own script checked {folder}/todo.md"], "checked with the checkout's own rank_todo.py, as a commit there would be")
self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(folder, pathlib.Path(self.own))], [("todo-rank-check", str(pathlib.Path(folder).resolve()))]) self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(folder, pathlib.Path.home(), pathlib.Path(self.own))], [("todo-rank-check", str(pathlib.Path(folder).resolve()))])
git(folder, "add", "-A") git(folder, "add", "-A")
git(folder, "commit", "-q", "-m", "plan") git(folder, "commit", "-q", "-m", "plan")
self.assertEqual(self.details(folder), [], "committed, so unchanged") self.assertEqual(self.details(folder), [], "committed, so unchanged")
+8 -4
View File
@@ -19,15 +19,15 @@ OWN = pathlib.Path(__file__).resolve().parents[2]
OWN_CHECK_SECONDS = 20 OWN_CHECK_SECONDS = 20
def todo_breaches(directory: str, own: pathlib.Path = OWN) -> list[Breach]: def todo_breaches(directory: str, home: pathlib.Path, 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. directory may also be in a config's folder, a git repo of its own.""" """Why the plan of directory's project is not ranked, where the plan has changed; the plan is the todo.md its config names. directory may also be in a config's folder, a git repo of its own."""
top = guarded_git(directory, "rev-parse", "--show-toplevel") top = guarded_git(directory, "rev-parse", "--show-toplevel")
if isinstance(top, Failure): if isinstance(top, Failure):
return [] return []
held_here = held(pathlib.Path(top), pathlib.Path.home()) held_here = held(pathlib.Path(top), home)
if held_here is not None: if held_here is not None:
return folder_breaches(top, held_here, own) return folder_breaches(top, held_here, own)
config = located(top, pathlib.Path.home(), functools.partial(git, guarded=True)) config = located(top, home, functools.partial(git, guarded=True))
if isinstance(config, Failure): if isinstance(config, Failure):
# A checkout whose todo.md changes with no config is one whose config is still to write. An unchanged todo.md may be a third party's, whose clone needs no config. # A checkout whose todo.md changes with no config is one whose config is still to write. An unchanged todo.md may be a third party's, whose clone needs no config.
unconfigured = pathlib.Path(top) / "todo.md" unconfigured = pathlib.Path(top) / "todo.md"
@@ -78,6 +78,10 @@ def changed(top: str, todo: pathlib.Path, tracked: str) -> bool:
# Hashed here, never by `git status`, which would run a clean filter the checkout's own config names before the call is allowed. # 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", f":{tracked}"), guarded_git(top, "rev-parse", f"HEAD:{tracked}") 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") algorithm = guarded_git(top, "rev-parse", "--show-object-format")
content = todo.read_bytes() try:
content = todo.read_bytes()
except OSError:
# An unreadable plan counts as changed, so the check runs and its breach says why the plan cannot be read. Raising here would end the hook with an exit that lets the commit through unchecked.
return True
worktree = hashlib.new("sha1" if isinstance(algorithm, Failure) else algorithm, b"blob %d\0" % len(content) + content).hexdigest() worktree = hashlib.new("sha1" if isinstance(algorithm, Failure) else algorithm, b"blob %d\0" % len(content) + content).hexdigest()
return isinstance(staged, Failure) or staged != worktree or staged != committed return isinstance(staged, Failure) or staged != worktree or staged != committed
+1 -1
View File
@@ -52,7 +52,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None, memor
print(f"run-heavy: no command given; {USAGE}", file=sys.stderr) print(f"run-heavy: no command given; {USAGE}", file=sys.stderr)
return OWN_FAILURE return OWN_FAILURE
if HELD not in env: if HELD not in env:
slot = held_slot(slot_folder(env), slot_count(cpus)) slot = held_slot(slot_folder(env, pathlib.Path.home()), slot_count(cpus))
if isinstance(slot, Failure): if isinstance(slot, Failure):
print(f"run-heavy: {slot.reason}", file=sys.stderr) print(f"run-heavy: {slot.reason}", file=sys.stderr)
return OWN_FAILURE return OWN_FAILURE
+4 -2
View File
@@ -112,7 +112,8 @@ def add(args: argparse.Namespace, config: ProjectConfig, stdin: typing.TextIO) -
return Failure(f"not filed: {under[0]}") return Failure(f"not filed: {under[0]}")
if unwritten := plan_file.write(todo, ranked.text): if unwritten := plan_file.write(todo, ranked.text):
return unwritten return unwritten
plan_file.print_report(todo, ranked) for line in plan_file.report_lines(todo, ranked):
print(line, file=sys.stderr)
return f"Filed item {id_} in {todo}." return f"Filed item {id_} in {todo}."
@@ -126,7 +127,8 @@ def finish(args: argparse.Namespace, config: ProjectConfig) -> str | Failure:
return Failure(f"not finished: {unwritten.reason}") return Failure(f"not finished: {unwritten.reason}")
if news is not None and (unwritten := plan_file.write(changelog, news)): 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") 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) for line in plan_file.report_lines(todo, ranked):
print(line, file=sys.stderr)
return f"Finished item {args.id} in {todo}." return f"Finished item {args.id} in {todo}."
+1 -1
View File
@@ -485,7 +485,7 @@ The archive holds 277 chunk folders under `home/lilleman/.claude`, from 2026-09-
### 193. Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy. ### 193. Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.
Found by review of PR #317. `bin/release_plan/ranking.py`'s `readme_goals` writes `typing.cast(Mark, mark or None)`, which asserts the type `goal_weights` branches on without checking it: a mark added to the regex reaches `goal_weights` as a value `Mark` lacks. mypy does not read the regex, so no lookup lets it catch that. Replace the cast with a lookup typed `dict[str, Mark]`, from each mark the regex captures, and `""` for none, to its `Mark` value. A mark added to the regex but not the lookup then raises `KeyError` at run time, and a value added to the lookup but not `Mark` fails mypy. Found by review of PR #317. `bin/release_plan/goals_file.py`'s `numbered` writes `typing.cast(Mark, mark or None)`, which asserts the type `goal_weights` branches on without checking it: a mark added to the regex reaches `goal_weights` as a value `Mark` lacks. mypy does not read the regex, so no lookup lets it catch that. Replace the cast with a lookup typed `dict[str, Mark]`, from each mark the regex captures, and `""` for none, to its `Mark` value. A mark added to the regex but not the lookup then raises `KeyError` at run time, and a value added to the lookup but not `Mark` fails mypy.
### 194. Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run. ### 194. Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.