From e1707183fdc18e700fc200be2b3fc2d527f552cb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 12:16:33 +0200 Subject: [PATCH] Answer the architecture pass's first round --- bin/statusline.py | 102 +++++++++++++++++++++++++++-------------- bin/test_statusline.py | 20 ++++++-- todo.md | 10 ++++ 3 files changed, 92 insertions(+), 40 deletions(-) diff --git a/bin/statusline.py b/bin/statusline.py index 3babd0de..c36ffbcc 100755 --- a/bin/statusline.py +++ b/bin/statusline.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +import dataclasses import datetime import json import math @@ -6,7 +7,6 @@ import os import subprocess import sys import time -import typing CYAN = "\033[36m" DIM = "\033[2m" @@ -16,26 +16,59 @@ RESET = "\033[0m" YELLOW = "\033[33m" -def field(status: object, *path: str) -> object: +@dataclasses.dataclass(frozen=True) +class Limit: + percent: float + resets_at: float | None + + +@dataclasses.dataclass(frozen=True) +class Status: + context_percent: float | None + context_size: float | None + context_used: float | None + directory: str + five_hour: Limit | None + model: str + seven_day: Limit | None + + +def field(raw: object, *path: str) -> object: for key in path: - if not isinstance(status, dict): + if not isinstance(raw, dict): return None - status = status.get(key) - return status + raw = raw.get(key) + return raw -def number(status: object, *path: str) -> float | None: - found = field(status, *path) - return found if isinstance(found, (int, float)) and not isinstance(found, bool) and math.isfinite(found) else None +def number(raw: object, *path: str) -> float | None: + found = field(raw, *path) + if isinstance(found, bool) or not isinstance(found, (int, float)): + return None + return found if isinstance(found, int) or math.isfinite(found) else None -def text(status: object, *path: str) -> str: - found = field(status, *path) +def text(raw: object, *path: str) -> str: + found = field(raw, *path) return found if isinstance(found, str) else "" -def directory(status: object) -> str: - return text(status, "workspace", "current_dir") or text(status, "cwd") +def limit(raw: object, window: str) -> Limit | None: + percent = number(raw, "rate_limits", window, "used_percentage") + return None if percent is None else Limit(percent, number(raw, "rate_limits", window, "resets_at")) + + +# The input's fields: https://code.claude.com/docs/en/statusline +def parse(raw: object) -> Status: + return Status( + context_percent=number(raw, "context_window", "used_percentage"), + context_size=number(raw, "context_window", "context_window_size"), + context_used=number(raw, "context_window", "total_input_tokens"), + directory=text(raw, "workspace", "current_dir") or text(raw, "cwd"), + five_hour=limit(raw, "five_hour"), + model=text(raw, "model", "display_name"), + seven_day=limit(raw, "seven_day"), + ) def usage_color(percent: int) -> str: @@ -51,7 +84,10 @@ def humanize_tokens(count: int) -> str: def reset_suffix(epoch: float, now: int, zone: datetime.tzinfo | None) -> str: - at = datetime.datetime.fromtimestamp(round(epoch), zone) + try: + at = datetime.datetime.fromtimestamp(round(epoch), zone) + except (OSError, OverflowError, ValueError): + return "" seconds = max(0, round(epoch) - now) if seconds >= 86400: left = f"{seconds // 86400}d{seconds % 86400 // 3600}h" @@ -63,39 +99,35 @@ def reset_suffix(epoch: float, now: int, zone: datetime.tzinfo | None) -> str: return f" {DIM}{left} left ({clock}){RESET}" -def usage(label: str, percent: float, suffix: str) -> str: +def usage_segment(label: str, percent: float, suffix: str) -> str: rounded = round(percent) return f"{DIM}{label}{RESET} {usage_color(rounded)}{rounded}%{RESET}{suffix}" -def limit(status: object, label: str, window: str, now: int, zone: datetime.tzinfo | None) -> list[str]: - percent = number(status, "rate_limits", window, "used_percentage") - if percent is None: +def limit_segment(label: str, window: Limit | None, now: int, zone: datetime.tzinfo | None) -> list[str]: + if window is None: return [] - resets = number(status, "rate_limits", window, "resets_at") - return [usage(label, percent, "" if resets is None else reset_suffix(resets, now, zone))] + return [usage_segment(label, window.percent, "" if window.resets_at is None else reset_suffix(window.resets_at, now, zone))] -def render(status: object, branch: str, home: str, now: int, zone: datetime.tzinfo | None) -> str: +def render(status: Status, branch: str, home: str, now: int, zone: datetime.tzinfo | None) -> str: where = [] - shown = directory(status) - if shown: + if status.directory: + shown = status.directory if home and (shown == home or shown.startswith(home + "/")): shown = "~" + shown[len(home):] where.append(f"{CYAN}{shown}{RESET}") if branch: where.append(f"{DIM}{branch}{RESET}") - model = text(status, "model", "display_name") - if model: - where.append(f"{DIM}{model}{RESET}") + if status.model: + where.append(f"{DIM}{status.model}{RESET}") load = [] - context = number(status, "context_window", "used_percentage") - if context is not None: - used, size = number(status, "context_window", "total_input_tokens"), number(status, "context_window", "context_window_size") + if status.context_percent is not None: + used, size = status.context_used, status.context_size tokens = "" if used is None or size is None else f" {DIM}{humanize_tokens(int(used))}/{humanize_tokens(int(size))}{RESET}" - load.append(usage("ctx", context, tokens)) - load += limit(status, "5h", "five_hour", now, zone) + limit(status, "7d", "seven_day", now, zone) + load.append(usage_segment("ctx", status.context_percent, tokens)) + load += limit_segment("5h", status.five_hour, now, zone) + limit_segment("7d", status.seven_day, now, zone) return "\n".join(f"{DIM} | {RESET}".join(row) for row in (where, load) if row) @@ -110,13 +142,13 @@ def current_branch(where: str) -> str: return found.stdout.strip() if found.returncode == 0 else "" -def main(stdin: typing.TextIO, env: typing.Mapping[str, str]) -> str: +def main() -> str: try: - status = json.load(stdin) + status = parse(json.load(sys.stdin)) except ValueError: - status = None - return render(status, current_branch(directory(status)), env.get("HOME", ""), int(time.time()), None) + return f"{RED}warning: statusline.py could not parse its input as JSON{RESET}" + return render(status, current_branch(status.directory), os.environ.get("HOME", ""), int(time.time()), None) if __name__ == "__main__": - sys.stdout.write(main(sys.stdin, os.environ)) + sys.stdout.write(main()) diff --git a/bin/test_statusline.py b/bin/test_statusline.py index 00f9357e..35b24c58 100644 --- a/bin/test_statusline.py +++ b/bin/test_statusline.py @@ -1,5 +1,6 @@ import datetime import json +import os import pathlib import subprocess import sys @@ -17,7 +18,7 @@ UTC = datetime.timezone.utc def render(status, branch="", home="/home/me"): - return statusline.render(status, branch, home, NOW, UTC) + return statusline.render(statusline.parse(status), branch, home, NOW, UTC) class Render(unittest.TestCase): @@ -37,10 +38,15 @@ class Render(unittest.TestCase): ]), ])) - def test_shows_nothing_for_an_empty_or_unparsed_status(self): + def test_shows_nothing_for_an_empty_status(self): self.assertEqual(render({}), "") + self.assertEqual(render([]), "") self.assertEqual(render(None), "") + def test_skips_infinity_and_keeps_an_integer_too_big_for_a_float(self): + self.assertEqual(render({"context_window": {"used_percentage": float("inf")}}), "") + self.assertEqual(render({"context_window": {"used_percentage": 10**400}}), f"{DIM}ctx{RESET} {RED}{10**400}%{RESET}") + def test_skips_a_field_of_the_wrong_type(self): status = {"context_window": {"used_percentage": "42"}, "cwd": 7, "model": {"display_name": None}, "rate_limits": {"five_hour": {"used_percentage": True}}} self.assertEqual(render(status), "") @@ -66,21 +72,25 @@ class Render(unittest.TestCase): def test_humanizes_token_counts(self): self.assertEqual([statusline.humanize_tokens(n) for n in (999, 1000, 999_999, 1_250_000)], ["999", "1k", "999k", "1.2M"]) + def test_omits_a_reset_out_of_the_clocks_range(self): + self.assertEqual(render({"rate_limits": {"seven_day": {"resets_at": 1790618085238, "used_percentage": 1}}}), f"{DIM}7d{RESET} {GREEN}1%{RESET}") + self.assertEqual(render({"rate_limits": {"seven_day": {"resets_at": 1e20, "used_percentage": 1}}}), f"{DIM}7d{RESET} {GREEN}1%{RESET}") + def test_counts_a_past_reset_as_zero_left(self): self.assertEqual(statusline.reset_suffix(NOW - 60, NOW, UTC), f" {DIM}0m left (11:59){RESET}") class Script(unittest.TestCase): def run_script(self, stdin): - return subprocess.run([sys.executable, str(pathlib.Path(statusline.__file__))], capture_output=True, env={"HOME": "/nonexistent", "PATH": "/usr/bin:/bin"}, input=stdin, text=True) + return subprocess.run([statusline.__file__], capture_output=True, env={"HOME": "/nonexistent", "PATH": os.environ["PATH"]}, input=stdin, text=True) def test_prints_the_status_without_a_trailing_newline(self): ran = self.run_script(json.dumps({"cwd": "/nonexistent/a", "model": {"display_name": "Opus"}})) self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, SEP.join([f"{CYAN}~/a{RESET}", f"{DIM}Opus{RESET}"]), "")) - def test_prints_nothing_for_input_that_is_not_json(self): + def test_warns_on_the_status_line_for_input_that_is_not_json(self): ran = self.run_script("not json") - self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, "", "")) + self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, f"{RED}warning: statusline.py could not parse its input as JSON{RESET}", "")) def test_shows_the_branch_of_the_directory(self): with tempfile.TemporaryDirectory() as checkout: diff --git a/todo.md b/todo.md index df3496df..05f25f9f 100644 --- a/todo.md +++ b/todo.md @@ -15,19 +15,29 @@ - **Give principles-auditor and prose-reviewer a way to list the project's files.** In the 2026-09-30 audit run their `tools: Read, Grep, Glob` gave them only Read. Each read the files that imports and `.gitignore` named, and listed the files it could not reach. Goal 4.1. - **Give the reviewer agents only the tools they need.** `systems-architect.md`, `product-owner-reviewer.md` and `stability-reviewer.md` have no `tools:` line, so each can edit the branch it reviews; `review-findings.md` says a reviewer edits nothing. Goal 4.1. - **Measure test coverage in the suite, and fail on a drop.** Nothing measures it, so "Test coverage should not decline" cannot be held. Goal 4.1. +- **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** The repo has no CI, so larv-review's gate is the local run, and §4 rule 1 skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word. Goal 4.1. - **Make larv-review §3 applicable on its own, cite its rules by name, and say where a pass's round count is recorded.** Applying one rule of "Round cap", "Re-entry" or "Findings" takes `review-findings.md`, `CLAUDE.md` → "Vocabulary" and the decision log open beside it. The rules cite each other by number ("Round cap" rule 6), so a renumbering breaks a citation silently. Nothing says where a pass's round count is recorded, so a resumed or compacted session loses it. Goal 4.1. - **Read transcript and stream entries into typed values where they are read.** `read_transcript` and `run_worker` pass raw `dict`s, so about ten accessors in `entries.py` re-check shapes deep inside and mypy cannot check `render`, `human_turns` or `run_worker`. Goal 4.1. - **Inject output and storage into `Effects`, and test what each step prints.** `print` and `open` are called directly across `bin/loop_claude/`, so the stderr lines of the CLI contract can be checked only through the black-box tests. Goal 4.1. +- **Move the judge's transcript rendering from `claude_code/transcript.py` into `cycle/`.** `render`, `part_line` and `JUDGED_TOOL_INPUT` shape what the judge sees, so its input is split from `JUDGED_TRANSCRIPT_TAIL` across two packages, and `claude_code/` no longer holds only Claude Code's shapes as its docstring says. Goal 4.1. - **Give each cycle phase one name across its state, step and event.** Today `Judging` runs `rule` and yields `Ruled`, and `Finishing` runs `close`, which also deletes the session, and yields `Archived`. Goal 4.1. - **Enable the `claude-security` plugin in `settings.json`, or drop larv-review's full-scan row.** No machine has it enabled, so every chunk that fires the pass skips it. Goal 4.1. - **Give `settings.json`'s model one writer, and sort its keys.** Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice. Goal 4.3. - **Say in `systems-architect.md` that a REST API's `/v1/` prefix is not versioning machinery to defer.** Its "defer the versioning story" can be read against `principles/rest-apis.md`, which requires the prefix from the start. Goal 4.3. - **Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.** On this repo the frontend, REST and logging auditors each read the whole project to report "does not apply", and one 🟢 fix reruns ten whole-project reads. Goal 4.4. +- **Cut `systems-architect.md`'s, `stability-reviewer.md`'s and `product-owner-reviewer.md`'s descriptions to one line.** Claude Code loads every agent description into every session; larv-review launches these agents by name, so their worked examples cost tokens in every project and buy nothing. Goal 4.4. - **Record each finished chunk's cost and review numbers on one stats line.** Goal 4.4. - Have `loop-claude` write the line to one file at the root of the transcript archive. The line names the project, the commit the chunk started from and the archived transcript's hash. It holds the worker's tokens from the transcript, the judge's from its JSON output, and the chunk's cycles and interrupts, which the loop counts. - End larv-review with a machine-readable summary, and have `loop-claude` copy it from the transcript onto the line: agents launched and rounds per pass; findings per pass by severity, inside the chunk's diff and outside it; and the comprehension scores when the panel ran. - **Write a `workflow-review` skill that reads the stats and files each change it proposes to the workflow as a plan item, and have `AGENTS.md` run it on the chunk shipping a release's last item.** The workflow is `CLAUDE.md`, `principles/`, the skills, the agents and `loop-claude`. The skill's signals: findings outside the chunk's diff and comprehension scores per release, both from the stats; fixes after merge, from git; and the human's corrections, from the archived transcripts. Goal 4.4. - **Bench about one chunk in ten against an open PR that changes the workflow, and have a blind claude rule which run better serves this repo's goal 4.** Redo the chunk under the PR, from the commit it started from. The ruling claude is not told which run is which. `loop-claude` picks the chunk at random, small diffs and big ones alike; with no such PR open, no bench runs. The same outcome with less code and prose, in the chunk or in the workflow, also counts as better. The PR merges only once three benches rule it better. A bench that rules it worse closes the PR and records, in `docs/workflow-learnings.md`, what the PR changed and why it lost. The ruling and both runs' numbers go on the chunk's stats line. Start from `workflow-bench/`, written for the 2026-09-30 bench's four fixed cases. Needs the stats line. Goals 4.1 and 4.4. +- **Make the small fixes filed by the 2026-10-02 principles audit against `workflow-bench/`.** The bench item starts from it. Goals 2 and 4.1. + - Test `judge.py`'s `blind` and `bench.py`'s rate-limit parsing, and run mypy on both. + - Let `judge.py` import `bench` without `BENCH_SOURCES` set; today reading it at import raises a bare `KeyError`. + - Key `CASES`, `PREFIX` and `TRUTH_END` in one table, sorted. + - Report a failed `git` per run; today `check=True` aborts `main` and drops every other run's result. + - Take the model from a flag or env var, and inject the clock, sleep and shuffle. + - Keep the bench's run logs where the transcript archive's backup reaches them. - **Make the small changes filed against the review's rules.** Goals 4.1 and 4.4. - Make the contributor a standing member of every project's audience. A project drops them only where its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. - **Make the small fixes filed by the 2026-10-01 principles audit against `bin/`.** Goal 4.1.