From f51900106faac50237ae7d0f501ff9e195e3fdb7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Fri, 2 Oct 2026 09:36:57 +0200 Subject: [PATCH] Rewrite the status line in Python, and test it --- .gitignore | 2 +- README.md | 4 +- bin/statusline.py | 122 +++++++++++++++++++++++++++++++++++++++++ bin/test_statusline.py | 89 ++++++++++++++++++++++++++++++ bin/test_types.py | 4 +- settings.json | 2 +- statusline.sh | 115 -------------------------------------- todo.md | 1 - 8 files changed, 217 insertions(+), 122 deletions(-) create mode 100755 bin/statusline.py create mode 100644 bin/test_statusline.py delete mode 100755 statusline.sh diff --git a/.gitignore b/.gitignore index 808964d7..da30a316 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,6 @@ !CLAUDE.md !README.md !settings.json -!statusline.sh !todo.md !.claude/ @@ -22,6 +21,7 @@ !bin/loop_claude/ !bin/loop_claude/**/ !bin/loop_claude/**/*.py +!bin/statusline.py !bin/test_*.py !docs/ !docs/*.md diff --git a/README.md b/README.md index 85228e4d..974426c8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Claude Code configuration -My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold every project to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `statusline.sh`; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; and `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review. +My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `agents/` and `skills/`; `principles/` for what the reviewer agents hold every project to; `docs/` for decisions; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`, the status line among them; and `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review. ## Goals @@ -20,7 +20,7 @@ Me, on my own machines, which take tagged releases. Nobody else depends on it. ## Install -Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`, and `jq` and GNU `date` for `statusline.sh`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run it only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interrupt included, skips every permission prompt. +Check out the latest tag in `~/.claude`, with Python 3.11 or newer as `python3` on `PATH`. Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run it only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interrupt included, skips every permission prompt. ## Release diff --git a/bin/statusline.py b/bin/statusline.py new file mode 100755 index 00000000..3babd0de --- /dev/null +++ b/bin/statusline.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +import datetime +import json +import math +import os +import subprocess +import sys +import time +import typing + +CYAN = "\033[36m" +DIM = "\033[2m" +GREEN = "\033[32m" +RED = "\033[31m" +RESET = "\033[0m" +YELLOW = "\033[33m" + + +def field(status: object, *path: str) -> object: + for key in path: + if not isinstance(status, dict): + return None + status = status.get(key) + return status + + +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 text(status: object, *path: str) -> str: + found = field(status, *path) + return found if isinstance(found, str) else "" + + +def directory(status: object) -> str: + return text(status, "workspace", "current_dir") or text(status, "cwd") + + +def usage_color(percent: int) -> str: + return RED if percent >= 80 else YELLOW if percent >= 50 else GREEN + + +def humanize_tokens(count: int) -> str: + if count >= 1_000_000: + return f"{count // 1_000_000}.{count % 1_000_000 // 100_000}M" + if count >= 1000: + return f"{count // 1000}k" + return str(count) + + +def reset_suffix(epoch: float, now: int, zone: datetime.tzinfo | None) -> str: + at = datetime.datetime.fromtimestamp(round(epoch), zone) + seconds = max(0, round(epoch) - now) + if seconds >= 86400: + left = f"{seconds // 86400}d{seconds % 86400 // 3600}h" + elif seconds >= 3600: + left = f"{seconds // 3600}h{seconds % 3600 // 60}m" + else: + left = f"{seconds // 60}m" + clock = at.strftime("%H:%M" if at.date() == datetime.datetime.fromtimestamp(now, zone).date() else "%a %H:%M") + return f" {DIM}{left} left ({clock}){RESET}" + + +def usage(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: + return [] + resets = number(status, "rate_limits", window, "resets_at") + return [usage(label, percent, "" if resets is None else reset_suffix(resets, now, zone))] + + +def render(status: object, branch: str, home: str, now: int, zone: datetime.tzinfo | None) -> str: + where = [] + shown = directory(status) + if shown: + 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}") + + 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") + 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) + + return "\n".join(f"{DIM} | {RESET}".join(row) for row in (where, load) if row) + + +def current_branch(where: str) -> str: + if not where: + return "" + try: + found = subprocess.run(["git", "-C", where, "branch", "--show-current"], capture_output=True, text=True) + except OSError: + return "" + return found.stdout.strip() if found.returncode == 0 else "" + + +def main(stdin: typing.TextIO, env: typing.Mapping[str, str]) -> str: + try: + status = json.load(stdin) + except ValueError: + status = None + return render(status, current_branch(directory(status)), env.get("HOME", ""), int(time.time()), None) + + +if __name__ == "__main__": + sys.stdout.write(main(sys.stdin, os.environ)) diff --git a/bin/test_statusline.py b/bin/test_statusline.py new file mode 100644 index 00000000..00f9357e --- /dev/null +++ b/bin/test_statusline.py @@ -0,0 +1,89 @@ +import datetime +import json +import pathlib +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +import statusline +from statusline import CYAN, DIM, GREEN, RED, RESET, YELLOW + +NOW = int(datetime.datetime(2026, 10, 2, 12, 0, tzinfo=datetime.timezone.utc).timestamp()) +SEP = f"{DIM} | {RESET}" +UTC = datetime.timezone.utc + + +def render(status, branch="", home="/home/me"): + return statusline.render(status, branch, home, NOW, UTC) + + +class Render(unittest.TestCase): + def test_shows_every_field_on_two_rows(self): + status = { + "context_window": {"context_window_size": 1_000_000, "total_input_tokens": 85_000, "used_percentage": 42.5}, + "model": {"display_name": "Opus"}, + "rate_limits": {"five_hour": {"resets_at": NOW + 5000, "used_percentage": 63}, "seven_day": {"resets_at": NOW + 300_000, "used_percentage": 91.2}}, + "workspace": {"current_dir": "/home/me/code/a"}, + } + self.assertEqual(render(status, "main"), "\n".join([ + SEP.join([f"{CYAN}~/code/a{RESET}", f"{DIM}main{RESET}", f"{DIM}Opus{RESET}"]), + SEP.join([ + f"{DIM}ctx{RESET} {GREEN}42%{RESET} {DIM}85k/1.0M{RESET}", + f"{DIM}5h{RESET} {YELLOW}63%{RESET} {DIM}1h23m left (13:23){RESET}", + f"{DIM}7d{RESET} {RED}91%{RESET} {DIM}3d11h left (Mon 23:20){RESET}", + ]), + ])) + + def test_shows_nothing_for_an_empty_or_unparsed_status(self): + self.assertEqual(render({}), "") + self.assertEqual(render(None), "") + + 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), "") + + def test_falls_back_to_cwd_and_shows_the_branch_only_beside_a_directory(self): + self.assertEqual(render({"cwd": "/srv"}, "main"), SEP.join([f"{CYAN}/srv{RESET}", f"{DIM}main{RESET}"])) + self.assertEqual(render({"model": {"display_name": "Opus"}}, "main"), f"{DIM}Opus{RESET}") + + def test_abbreviates_home_only_at_a_path_boundary(self): + self.assertEqual(render({"cwd": "/home/me"}), f"{CYAN}~{RESET}") + self.assertEqual(render({"cwd": "/home/meg"}), f"{CYAN}/home/meg{RESET}") + self.assertEqual(render({"cwd": "/home/me"}, home=""), f"{CYAN}/home/me{RESET}") + + def test_omits_the_token_counts_unless_both_are_known(self): + self.assertEqual(render({"context_window": {"total_input_tokens": 5, "used_percentage": 1}}), f"{DIM}ctx{RESET} {GREEN}1%{RESET}") + + def test_omits_the_reset_unless_known(self): + self.assertEqual(render({"rate_limits": {"five_hour": {"used_percentage": 50}}}), f"{DIM}5h{RESET} {YELLOW}50%{RESET}") + + def test_colors_usage_by_threshold(self): + self.assertEqual([statusline.usage_color(p) for p in (49, 50, 79, 80)], [GREEN, YELLOW, YELLOW, RED]) + + 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_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) + + 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): + ran = self.run_script("not json") + self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (0, "", "")) + + def test_shows_the_branch_of_the_directory(self): + with tempfile.TemporaryDirectory() as checkout: + subprocess.run(["git", "init", "-q", "-b", "trunk", checkout], check=True) + ran = self.run_script(json.dumps({"cwd": checkout})) + self.assertEqual(ran.stdout, SEP.join([f"{CYAN}{checkout}{RESET}", f"{DIM}trunk{RESET}"])) diff --git a/bin/test_types.py b/bin/test_types.py index 17500139..8e2c84dc 100644 --- a/bin/test_types.py +++ b/bin/test_types.py @@ -6,10 +6,10 @@ from test_python_floor import ROOT, readme_floor class Types(unittest.TestCase): - def test_mypy_passes_on_loop_claude_at_the_floor(self): + def test_mypy_passes_on_the_tools_at_the_floor(self): floor = readme_floor() self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`") if shutil.which("uv") is None: self.fail("uv on PATH fetches mypy; see README.md's Test line") - ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) + ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "-m", "statusline", "-p", "loop_claude"], capture_output=True, cwd=ROOT / "bin", text=True) self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr) diff --git a/settings.json b/settings.json index f839ed0b..f7dfa605 100644 --- a/settings.json +++ b/settings.json @@ -13,7 +13,7 @@ "disableClaudeAiConnectors": true, "statusLine": { "type": "command", - "command": "~/.claude/statusline.sh", + "command": "~/.claude/bin/statusline.py", "refreshInterval": 30 }, "enabledPlugins": { diff --git a/statusline.sh b/statusline.sh deleted file mode 100755 index 3ec20c86..00000000 --- a/statusline.sh +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env bash -set -uo pipefail - -input=$(cat) - -# @sh quotes every value, so the JSON reaches eval as data. -eval "$(printf '%s' "$input" | jq -r ' - @sh "dir=\(.workspace.current_dir // .cwd // "")", - @sh "model=\(.model.display_name // "")", - @sh "ctx_pct=\(.context_window.used_percentage // "")", - @sh "ctx_used=\(.context_window.total_input_tokens // "")", - @sh "ctx_size=\(.context_window.context_window_size // "")", - @sh "five=\(.rate_limits.five_hour.used_percentage // "")", - @sh "five_reset=\(.rate_limits.five_hour.resets_at // "")", - @sh "week=\(.rate_limits.seven_day.used_percentage // "")", - @sh "week_reset=\(.rate_limits.seven_day.resets_at // "")" -')" - -DIM=$'\033[2m' -RESET=$'\033[0m' -CYAN=$'\033[36m' -GREEN=$'\033[32m' -YELLOW=$'\033[33m' -RED=$'\033[31m' - -usage_color() { - local pct=${1%%.*} - if [ "$pct" -ge 80 ]; then printf '%s' "$RED" - elif [ "$pct" -ge 50 ]; then printf '%s' "$YELLOW" - else printf '%s' "$GREEN" - fi -} - -humanize_tokens() { - local n=$1 - if [ "$n" -ge 1000000 ]; then printf '%d.%dM' "$(( n / 1000000 ))" "$(( n % 1000000 / 100000 ))" - elif [ "$n" -ge 1000 ]; then printf '%dk' "$(( n / 1000 ))" - else printf '%d' "$n" - fi -} - -reset_suffix() { - local epoch=$1 secs at fmt - epoch=$(printf '%.0f' "$epoch") - secs=$(( epoch - $(date +%s) )) - [ "$secs" -lt 0 ] && secs=0 - - if [ "$secs" -ge 86400 ]; then - printf ' %s%dd%dh left' "$DIM" "$(( secs / 86400 ))" "$(( secs % 86400 / 3600 ))" - elif [ "$secs" -ge 3600 ]; then - printf ' %s%dh%dm left' "$DIM" "$(( secs / 3600 ))" "$(( secs % 3600 / 60 ))" - else - printf ' %s%dm left' "$DIM" "$(( secs / 60 ))" - fi - - fmt='%H:%M' - [ "$(date -d "@$epoch" +%F 2>/dev/null)" != "$(date +%F)" ] && fmt='%a %H:%M' - at=$(date -d "@$epoch" "+$fmt" 2>/dev/null) - [ -n "$at" ] && printf ' (%s)' "$at" - printf '%s' "$RESET" -} - -row1=() -row2=() - -home=${HOME:-} -if [ -n "$dir" ]; then - shortdir=$dir - [ -n "$home" ] && shortdir=${dir/#$home/\~} - row1+=("${CYAN}${shortdir}${RESET}") - - branch=$(git -C "$dir" branch --show-current 2>/dev/null) - [ -n "$branch" ] && row1+=("${DIM}${branch}${RESET}") -fi - -[ -n "$model" ] && row1+=("${DIM}${model}${RESET}") - -if [ -n "$ctx_pct" ]; then - pct=$(printf '%.0f' "$ctx_pct") - tokens="" - [ -n "$ctx_used" ] && [ -n "$ctx_size" ] && tokens=" ${DIM}$(humanize_tokens "$ctx_used")/$(humanize_tokens "$ctx_size")${RESET}" - row2+=("${DIM}ctx${RESET} $(usage_color "$pct")${pct}%${RESET}${tokens}") -fi - -if [ -n "$five" ]; then - pct=$(printf '%.0f' "$five") - left="" - [ -n "$five_reset" ] && left=$(reset_suffix "$five_reset") - row2+=("${DIM}5h${RESET} $(usage_color "$pct")${pct}%${RESET}${left}") -fi - -if [ -n "$week" ]; then - pct=$(printf '%.0f' "$week") - left="" - [ -n "$week_reset" ] && left=$(reset_suffix "$week_reset") - row2+=("${DIM}7d${RESET} $(usage_color "$pct")${pct}%${RESET}${left}") -fi - -join_parts() { - local sep="${DIM} | ${RESET}" out="" part - for part in "$@"; do - [ -n "$out" ] && out+="$sep" - out+="$part" - done - printf '%s' "$out" -} - -out="" -# ${a[@]+"${a[@]}"}: before bash 4.4 an empty array is unset under set -u. -for line in "$(join_parts ${row1[@]+"${row1[@]}"})" "$(join_parts ${row2[@]+"${row2[@]}"})"; do - [ -z "$line" ] && continue - [ -n "$out" ] && out+=$'\n' - out+="$line" -done -printf '%s' "$out" diff --git a/todo.md b/todo.md index 72d03cac..df3496df 100644 --- a/todo.md +++ b/todo.md @@ -2,7 +2,6 @@ ## 0.1.0 -- **Rewrite `statusline.sh` in Python, and test it.** It needs `jq` and GNU `date` on every machine, `eval`s jq output, has three near-identical usage blocks and no test. Goal 1. - **Put the scoring run's four seat prompts in `skills/comprehension-panel/`.** Each run copies them from the last run's handoff folder outside the repo, so another machine cannot rerun a comparable panel. Goal 1. - **Archive the transcript as each cycle ends.** Today only an interrupt or a finished chunk archives it, so after a failed exit or Ctrl-C the transcript stays unarchived until the chunk finishes, and is never archived if it does not. Goal 2. - **Archive a finished chunk's subagent transcripts before `delete_session` removes them.** Today only `.jsonl` is copied, so every reviewer's full run in an unattended chunk is lost. Goal 2.