Files

84 lines
5.3 KiB
Python

"""Reads the goals file, for the ranking and for loop-claude's premises: its ## Goals and ## Audience sections, each goal's number and mark, and what each goal weighs."""
import decimal
import re
import typing
from plan.todo_table import CODE_HEALTH
from failure import Failure
from text_files.markdown_text import sections
# What each achieve goal weighs of the one above it; docs/decisions.md records the choice.
GOAL_STEP = 0.97
# Code health weighs this many times its weight by position while the comprehension panel's overall is under the project's readability floor, or unmeasured; lilleman's choice, which docs/decisions.md records.
UNDER_FLOOR = 4
# Any **Void:** line of the goals file's ## Goals; ranked_goals accepts only `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → "Shared goal" spells it.
VOID = re.compile(r"^\*\*Void:\*\* (.*)$", re.M)
# A docs/decisions.md title opting the project out of the comprehension check, as larv-review's SKILL.md → "Opt-out" spells it.
OPTED_OUT = re.compile(r"^## review opt-out:.*\bcomprehension check\b", re.M)
# How the goals file marks a goal; None where it marks it neither way.
Mark = typing.Literal["Maintain", "Achieve"] | None
def section(goals_text: str, name: str) -> str | Failure:
"""The text under the goals file's one ## name heading. A Failure whose reason completes "the goals file ..." where the heading is missing or repeated, or holds no text."""
bodies = sections(goals_text).get(name, [])
if not bodies:
return Failure(f"has no ## {name} heading")
if len(bodies) > 1:
return Failure(f"has ## {name} more than once")
return bodies[0] or Failure(f"has no text under ## {name}")
def ranked_goals(goals_text: str, decisions: str) -> list[tuple[str, Mark]] | Failure:
"""Every goal in rank order, each with its mark: code health first, unless the goals file voids it, then the goals file's goals in reading order. A **Void:** line other than `**Void:** code health, since <reason>.` fails, and so does a docs/decisions.md that opts out of the comprehension check where the goals file keeps code health, since the goal then has no signal."""
body = goals_section(goals_text)
if isinstance(body, Failure):
return body
goals = numbered(body)
if isinstance(goals, Failure):
return goals
voids = VOID.findall(body)
if other := [void for void in voids if not void.startswith(f"{CODE_HEALTH}, since ")]:
if other[0].lower().startswith(CODE_HEALTH):
return Failure(f"the goals file's ## Goals voids code health as `{other[0]}`; spell the void exactly `**Void:** {CODE_HEALTH}, since <reason>.`")
return Failure(f"the goals file's ## Goals voids `{other[0]}`; only code health may be voided, as `**Void:** {CODE_HEALTH}, since <reason>.`")
if voids:
return goals
if OPTED_OUT.search(decisions):
return Failure(f"docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in the goals file's ## Goals with `**Void:** {CODE_HEALTH}, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says")
return [(CODE_HEALTH, "Achieve"), *goals]
def goals_section(goals_text: str) -> str | Failure:
body = section(goals_text, "Goals")
return Failure(f"the goals file {body.reason}") if isinstance(body, Failure) else body
def numbered(body: str) -> list[tuple[str, Mark]] | Failure:
goals: list[tuple[str, Mark]] = []
path: list[tuple[int, str]] = []
for indent, position, mark in re.findall(r"^([ \t]*)(\d+)\. (?:\*\*(Maintain|Achieve):\*\*)?", body.expandtabs(4), re.M):
while path and path[-1][0] >= len(indent):
path.pop()
path.append((len(indent), position))
goals.append((".".join(part for _, part in path), typing.cast(Mark, mark or None)))
numbers = [number for number, _ in goals]
if not goals:
return Failure("the goals file's ## Goals has no numbered goal")
if len(set(numbers)) < len(numbers):
return Failure(f"the goals file's ## Goals numbers {', '.join(numbers)}; number each goal by its position")
return goals
def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None, floor: decimal.Decimal) -> dict[str, float] | Failure:
"""Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is None or under floor, the project's readability floor, and the other goals keep their weights. Every weight is 0 where goals holds no achieve goal, as where the goals file voids code health and marks no goal **Achieve:**; an item then scores V 0 unless it names a maintain goal, and only an exempt one passes the bar. A maintain goal has no weight here: weight_of weighs it per item."""
if unmarked := [number for number, mark in goals if mark is None]:
return Failure(f"the goals file's goal {unmarked[0]} is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score")
achieve = [number for number, mark in goals if mark == "Achieve"]
total = sum(GOAL_STEP**rank for rank in range(len(achieve)))
weights = {number: GOAL_STEP**rank / total for rank, number in enumerate(achieve)}
if CODE_HEALTH in weights and (overall is None or overall < floor):
weights[CODE_HEALTH] *= UNDER_FLOOR
return weights