From 079c65110551087f3271f6d0830355cfcded8c1a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 22:16:06 +0100 Subject: [PATCH 1/9] File item 325: DM the human on Mattermost when loop-claude needs them --- todo.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index ff3c2568..1ab018e3 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 325` +`Next ID = 326` ## Items @@ -24,6 +24,7 @@ | 295 | 0.8.0 | | | **Have `chunk-pr merge` wait for the forge's required checks itself, and give workers one command that waits for a background log or report file.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 2, 1.5 by 2 | 1.6 | | 319 | 0.8.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.4 | | 309 | 0.8.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.3 | +| 325 | 0.8.0 | | owner | **DM the human through larvit-bot on Mattermost whenever loop-claude interrupts, a release is ready to cut, or the loop stops on an error, reading the server, the bot token and the recipient from `~/.claude/.env`.** | 4 | 2 | 3 | 7 | 4 | 1.5 by 4 | 1.3 | | 299 | 0.8.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 | | 311 | 0.8.0 | | | **Hand each worker's claude a Bash output ceiling that saves longer output to a file, and refuse a Read of a session transcript under `~/.claude/projects`.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3 | 1.2 | | 316 | 0.8.0 | | | **Launch comprehension seats as an agent type of their own under `agents/`, without `CLAUDE.md` and the skill and agent listings a general-purpose subagent carries.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 | @@ -147,6 +148,14 @@ Why it should hold quality: the seats are one model with different personas, so Decide once `agreement` has its 10 commits scored twice. Keep four seats on any pass that files a floor item, since its places come from seat reports. Revise the decision `review: the comprehension check records how hard a project is to read…`, which names the four-seat run. +### 325. DM the human through larvit-bot on Mattermost whenever loop-claude interrupts, a release is ready to cut, or the loop stops on an error, reading the server, the bot token and the recipient from `~/.claude/.env`. + +The human asked for this, for 0.8.0. A new tool, `bin/mattermost-dm`, sends its argument, or stdin, as a direct message from the bot to the recipient through Mattermost's REST API v4: `GET /api/v4/users/me` for the bot's id, `GET /api/v4/users/username/` for the recipient's, `POST /api/v4/channels/direct` for the channel, then `POST /api/v4/posts`. It uses only Python's standard library. + +`~/.claude/.env` holds `MATTERMOST_URL`, `MATTERMOST_TOKEN` and `MATTERMOST_RECIPIENT` as `KEY=value` lines. The `.gitignore` allowlist already keeps it out of every commit. The tool refuses a file that group or others can read, since it holds the token. Exit 0 when sent, 1 when the send failed, 2 on misuse, such as a missing file or key or an empty message. + +loop-claude sends the DM through an injected effect, so tests never reach the network. A DM that fails prints one line on loop-claude's terminal and the loop carries on, since the DM only copies what the terminal shows. Answering by replying to the DM is a later item. + ### 299. Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt. The judge's LLM still decides three things: the verdict kind, the escalation it quotes, and whether a release is ready to cut (`docs/decisions.md` → `routing: loop-claude reads the items a chunk takes …`). This item replays the verdict kind. No single rule found so far separates interrupts: a "?" in the worker's final message appears in 48 interrupts and misses 66. A smaller LLM already failed the replay (`docs/decisions.md` → `routing: on a model judge-replay covered, …`: Sonnet returned another kind on 3 interrupts, Haiku missed 7). Untested are combined code rules, a decision table, and a small classifier trained and run on this machine on the archived verdicts (372 finished, 234 interrupt, 42 unfinished, 20 quoted). Run each offline, nothing sent to an outside service (goal 4), and count disagreements by kind; the bar is zero missed interrupts. A hosted decision model is out of scope, since it would send transcripts to an outside service. -- 2.52.0 From c9514fe8b41b8109cbe644144b3c703db41d475d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 22:20:04 +0100 Subject: [PATCH 2/9] Append the reading-cost figure of the last finished chunk --- docs/reading-cost.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 548c66fa..0d858811 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -1616,3 +1616,18 @@ Read most (opens and searches): - `bin/loop_claude/verdicts.py` 2 - `bin/loop_claude/routing.py` 1 - `docs/decisions.md` 1 + +## Reading cost, chunk 3fba05e72d95, finished 2026-11-11T21:05:07Z + +86411 new input tokens before the first commit. + +Read most (opens and searches): + +- `todo.md` 7 +- `skills/larv-review/SKILL.md` 4 +- `README.md` 2 +- `docs/decisions.md` 2 +- `CLAUDE.md` 1 +- `agents/stability-reviewer.md` 1 +- `bin/reading-cost` 1 +- `bin/rule_hook/heavy_command.py` 1 -- 2.52.0 From 5588270e43b4e3334f813a3d15a5302114d96e1f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 22:24:06 +0100 Subject: [PATCH 3/9] DM the human on Mattermost for each question, release ready to cut and exit 1 of loop-claude --- .gitignore | 3 + README.md | 6 +- bin/judge_replay/test_judge_replay.py | 2 +- bin/loop_claude/cycle/interrupt.py | 3 + bin/loop_claude/direct_message.py | 7 + bin/loop_claude/loop/main.py | 4 + bin/loop_claude/loop/usage.py | 3 + bin/loop_claude/test_loop_claude.py | 43 ++++- bin/loop_effects/effects.py | 5 + bin/mattermost-dm | 9 + bin/mattermost_dm/__init__.py | 0 bin/mattermost_dm/dm.py | 120 ++++++++++++++ bin/mattermost_dm/main.py | 45 +++++ bin/mattermost_dm/test_mattermost_dm.py | 210 ++++++++++++++++++++++++ bin/review_replay/test_review_replay.py | 2 +- 15 files changed, 458 insertions(+), 4 deletions(-) create mode 100644 bin/loop_claude/direct_message.py create mode 100755 bin/mattermost-dm create mode 100644 bin/mattermost_dm/__init__.py create mode 100644 bin/mattermost_dm/dm.py create mode 100644 bin/mattermost_dm/main.py create mode 100644 bin/mattermost_dm/test_mattermost_dm.py diff --git a/.gitignore b/.gitignore index 0a5e580c..bfeabe1e 100644 --- a/.gitignore +++ b/.gitignore @@ -64,6 +64,9 @@ !bin/loop_state/**/*.py !bin/machine_load/ !bin/machine_load/*.py +!bin/mattermost-dm +!bin/mattermost_dm/ +!bin/mattermost_dm/*.py !bin/metric-bench !bin/metric_bench/ !bin/metric_bench/*.py diff --git a/README.md b/README.md index b4403ccb..93926f8f 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,8 @@ Then pick a model with `/model`. Link `loop-claude` and `loop-inbox` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude` and `ln -s ~/.claude/bin/loop-inbox ~/.local/bin/loop-inbox`. Every claude they start, the interactive ones included, skips every permission prompt. +To get loop-claude's questions and stops as Mattermost DMs from a bot, write the server, the bot's token and your username into `~/.claude/.env`, in the keys `bin/mattermost-dm --help` names, and run `chmod 600 ~/.claude/.env`. Without that file, loop-claude sends no DM. + ## Update Move `~/.claude` to the newest release: @@ -103,6 +105,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `larv-review ` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. - `loop-inbox` shows the interrupts of every loop-claude on the machine, oldest first, takes each one's answer, `/talk` included, and lists every running loop with the `todo.md` items its chunk takes; `loop-inbox --help` states how. +- `mattermost-dm []` sends a message, or else stdin, from the Mattermost bot to the human, configured in `~/.claude/.env`; `loop-claude` sends one for each question and each stop with exit 1, and `mattermost-dm --help` names the file's keys. - `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores. - `mutate-changes [--base ] [--prefix ] [--jobs ]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language. - `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format. @@ -116,7 +119,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `subagent-rung [--plan] ` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule. - `todo-item add …` files an item in a project's `todo.md`, taking `Next ID` as the item's ID, and `todo-item finish ` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`; both rank the file, and `todo-item --help` states the flags. -`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` and `transcript_archive/` serve more than one tool. +`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `mattermost_dm/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` and `transcript_archive/` serve more than one tool. - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. @@ -128,6 +131,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, loop-inbox, both replay tools and `reviewer-merge-trials`' driver use it. - `loop_state/` holds the files loop-claude and loop-inbox share: the question files (`waiting/`), the files a running loop lists itself in (`running_loops.py`, `session_lock.py`), their paths, and `hand_over.py`, which opens claude for `/talk`. A change to any of them changes both tools. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. +- `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`. - `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. - `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. - `records/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, and replaces a file in one step, private where it is new. diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index f9094b08..e39080fb 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -115,7 +115,7 @@ class Main(unittest.TestCase): result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1]) return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 0565692f..f18cdb89 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -14,6 +14,7 @@ from loop_state.waiting.listing import listed, shown from loop_state.waiting.talk import make_way, TALK from loop_claude.stop import needs_human, needs_terminal, Stop from model_routing.ladder import Rung +from loop_claude.direct_message import tell ANSWER_QUESTION = "answer the question above" # ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it. @@ -42,6 +43,8 @@ class Talked: def interrupt(question: str, answer_here: bool, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> str | Talked | Stop: """Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends.""" say(f"\n{question}", effects) + # Before the terminal check, so a loop that cannot ask still tells the human what it would have asked. + tell(f"loop-claude in {session.root} asks:\n\n{question}", effects) if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): return stop # Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK. diff --git a/bin/loop_claude/direct_message.py b/bin/loop_claude/direct_message.py new file mode 100644 index 00000000..d5b09955 --- /dev/null +++ b/bin/loop_claude/direct_message.py @@ -0,0 +1,7 @@ +from loop_effects.effects import Effects, say + + +def tell(text: str, effects: Effects) -> None: + """DMs text to the human, saying on the terminal why where the DM fails; the DM only copies what the terminal shows, so its failure never stops the loop.""" + if failed := effects.dm(text): + say(f"could not DM you on Mattermost: {failed.reason}", effects) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 7c002163..8fd55bf4 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -22,6 +22,7 @@ from loop_claude.project.records import read_records from claude_code.session import session_named from loop_state.running_loops import shown_running from loop_claude.stop import Stop +from loop_claude.direct_message import tell @@ -32,6 +33,9 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: stop = Stop(130, "") if stop.reason: say(stop.reason, effects, stdout=not stop.code) + # Exit 2 is a stop the human chose or must answer at the terminal, and 130 is Ctrl-C; a loop given no task stops before it runs. + if stop.code == 1 and argv: + tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects) return stop.code diff --git a/bin/loop_claude/loop/usage.py b/bin/loop_claude/loop/usage.py index 79c4266c..1d4b1522 100644 --- a/bin/loop_claude/loop/usage.py +++ b/bin/loop_claude/loop/usage.py @@ -33,6 +33,9 @@ interrupts of every loop on the machine. The first answer counts, from either pl - Enter alone, on loop-claude's terminal: stops the loop. A release ready to cut opens that session on the terminal at once, since only the human may cut it; loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on. +Where ~/.claude/.env exists, each question, and each stop with exit 1, also goes to the human as a +Mattermost DM, as bin/mattermost-dm sends it; a DM that fails is said on the terminal, and the loop +goes on. While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes, as bin/loop_state/running_loops.py describes. diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index e1bf08ec..7e270c81 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -92,8 +92,11 @@ def a_loop(effects, **fields): class FakeEffects: """Effects that record each call and answer from a script, one answer per call.""" - def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=()): + def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=()): self.calls = [] + # Each direct message sent, apart from calls, so tests that list every call need not list them. Without a script, each is sent. + self.dms = [] + self.dm_failures = list(dm_failures) self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)} # Without a script, every read finds all memory available. self.free_memory = list(free_memory) @@ -108,6 +111,7 @@ class FakeEffects: claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)), claude_on_terminal=self.on_terminal_claude, discard_typed=lambda: self.calls.append(("discard_typed", None)), + dm=self.dm, execv=self.execv, git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)), input=lambda prompt: self.answer("input", prompt), @@ -123,6 +127,10 @@ class FakeEffects: stream_claude=self.stream, ) + def dm(self, text): + self.dms.append(text) + return self.dm_failures.pop(0) if self.dm_failures else None + def memory(self): self.calls.append(("memory", None)) return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16) @@ -727,6 +735,17 @@ class Interrupts(unittest.TestCase): self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n")) self.assertEqual(fake.calls, []) + def test_dms_the_question_naming_the_project_before_asking_on_a_terminal_or_off_one(self): + for on_terminal in (True, False): + with self.subTest(on_terminal=on_terminal): + fake = FakeEffects(inputs=["Use B."], on_terminal=on_terminal) + self.put(fake) + self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks:\n\nWhich one?"]) + + def test_says_why_a_dm_failed_and_still_takes_the_answer(self): + fake = FakeEffects(inputs=["Use B."], dm_failures=[Failure("cannot reach https://chat.example: timed out")]) + self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n{STAMP} could not DM you on Mattermost: cannot reach https://chat.example: timed out\n")) + def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self): fake = FakeEffects(inputs=[" Use B. "]) self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n")) @@ -1787,6 +1806,28 @@ class LoopRuns(unittest.TestCase): self.assertEqual(reload.exec_if_edited(a_loop(fake.effects(), launcher=launcher), "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude ")) +class StopDms(unittest.TestCase): + def run_main(self, argv, fake): + with tempfile.TemporaryDirectory() as home, contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()): + code = main.main(argv, {}, paths.paths_from(pathlib.Path(home)), pathlib.Path(home, "loop-claude"), CWD, fake.effects()) + return code, said.getvalue() + + def test_dms_the_reason_where_a_loop_given_a_task_stops_with_exit_1(self): + fake = FakeEffects() + code, said = self.run_main([main.RELOAD_FLAG, "3"], fake) + self.assertEqual(code, 1) + self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude . Handed: 3"]) + + def test_says_why_the_dm_of_a_stop_failed_after_the_reason(self): + fake = FakeEffects(dm_failures=[Failure("cannot reach https://chat.example: timed out")]) + self.assertTrue(self.run_main([main.RELOAD_FLAG, "3"], fake)[1].endswith(f"Handed: 3\n{STAMP} could not DM you on Mattermost: cannot reach https://chat.example: timed out\n")) + + def test_sends_nothing_where_no_task_is_given(self): + fake = FakeEffects() + self.assertEqual(self.run_main([], fake)[0], 1) + self.assertEqual(fake.dms, []) + + class HelpLimits(unittest.TestCase): def test_help_wraps_at_100_columns(self): self.assertEqual([line for line in usage.HELP.splitlines() if len(line) > 100], []) diff --git a/bin/loop_effects/effects.py b/bin/loop_effects/effects.py index dae396b2..5b45714b 100644 --- a/bin/loop_effects/effects.py +++ b/bin/loop_effects/effects.py @@ -13,6 +13,8 @@ import time import typing import uuid +from mattermost_dm.dm import dm +from failure import Failure from git_cli import git_repo from machine_load.memory import Memory, read_memory @@ -44,6 +46,8 @@ class Effects: claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int] # Drops what was typed on the terminal and not yet read. discard_typed: typing.Callable[[], None] + # Sends the human a direct message on Mattermost, as `mattermost-dm` does; a Failure where it could not. + dm: typing.Callable[[str], Failure | None] execv: typing.Callable[[str, list[str]], None] git: git_repo.Git input: typing.Callable[[str], str] @@ -80,6 +84,7 @@ def system_effects() -> Effects: claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True), claude_on_terminal=claude_on_terminal, discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH), + dm=dm, execv=os.execv, git=git_repo.git, input=input, diff --git a/bin/mattermost-dm b/bin/mattermost-dm new file mode 100755 index 00000000..0118ef94 --- /dev/null +++ b/bin/mattermost-dm @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from mattermost_dm import dm, main + +sys.exit(main.main(sys.argv[1:], sys.stdin, lambda: dm.read_config(dm.env_file(pathlib.Path.home())), dm.http_json, sys.stderr)) diff --git a/bin/mattermost_dm/__init__.py b/bin/mattermost_dm/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/mattermost_dm/dm.py b/bin/mattermost_dm/dm.py new file mode 100644 index 00000000..cb0f4614 --- /dev/null +++ b/bin/mattermost_dm/dm.py @@ -0,0 +1,120 @@ +"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4.""" +import dataclasses +import json +import pathlib +import typing +import urllib.error +import urllib.parse +import urllib.request + +from failure import Failure + +KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT") +# Seconds a request may take, so an unreachable server holds loop-claude's interrupt only briefly. +TIMEOUT = 10 + +# Sends a request, the body as JSON where there is one, and returns the JSON answer. +Http = typing.Callable[[str, str, str, object], object] + + +@dataclasses.dataclass(frozen=True) +class Config: + url: str + token: str + recipient: str + + +def env_file(home: pathlib.Path) -> pathlib.Path: + return home / ".claude" / ".env" + + +def read_config(path: pathlib.Path) -> Config | Failure: + """The server, bot token and recipient that path's KEY=value lines hold.""" + try: + mode = path.stat().st_mode + text = path.read_text(encoding="utf-8") + except FileNotFoundError: + return Failure(f"{path} does not exist; it needs {', '.join(KEYS[:-1])} and {KEYS[-1]}") + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"cannot read {path}: {failure}") + if mode & 0o077: + return Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}") + values = parse_env(text) + if missing := [key for key in KEYS if not values.get(key)]: + return Failure(f"{path} lacks {' and '.join(missing)}") + url, token, recipient = (values[key] for key in KEYS) + if not url.startswith("https://"): + return Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear") + return Config(url.rstrip("/"), token, recipient) + + +def parse_env(text: str) -> dict[str, str]: + values = {} + for line in text.splitlines(): + key, equals, value = line.partition("=") + if not equals or key.lstrip().startswith("#"): + continue + value = value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"": + value = value[1:-1] + values[key.strip()] = value + return values + + +def send(config: Config, message: str, http: Http) -> Failure | None: + api = f"{config.url}/api/v4" + bot = id_of(http("GET", f"{api}/users/me", config.token, None), "GET /api/v4/users/me") + if isinstance(bot, Failure): + return bot + recipient = id_of(http("GET", f"{api}/users/username/{urllib.parse.quote(config.recipient)}", config.token, None), f"GET /api/v4/users/username/{config.recipient}") + if isinstance(recipient, Failure): + return recipient + channel = id_of(http("POST", f"{api}/channels/direct", config.token, [bot, recipient]), "POST /api/v4/channels/direct") + if isinstance(channel, Failure): + return channel + posted = id_of(http("POST", f"{api}/posts", config.token, {"channel_id": channel, "message": message}), "POST /api/v4/posts") + return posted if isinstance(posted, Failure) else None + + +def id_of(answer: object, request: str) -> str | Failure: + if isinstance(answer, Failure): + return answer + found = answer.get("id") if isinstance(answer, dict) else None + return found if isinstance(found, str) and found else Failure(f"{request} answered without an id") + + +def http_json(method: str, url: str, token: str, body: object) -> object: + """The JSON that url answers; a Failure naming the request where it cannot be reached, answers an error or answers something other than JSON.""" + request_name = f"{method} {urllib.parse.urlsplit(url).path}" + data = None if body is None else json.dumps(body).encode() + request = urllib.request.Request(url, data, {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, method=method) + try: + with urllib.request.urlopen(request, timeout=TIMEOUT) as response: + raw = response.read() + except urllib.error.HTTPError as failure: + return Failure(f"{request_name} answered {failure.code}: {error_message(failure.read()) or failure.reason}") + except (OSError, ValueError) as failure: + server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", "")) + return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}") + try: + return json.loads(raw) + except ValueError: + return Failure(f"{request_name} answered with something other than JSON") + + +def error_message(raw: bytes) -> str: + try: + answer = json.loads(raw) + except ValueError: + return "" + message = answer.get("message") if isinstance(answer, dict) else None + return message if isinstance(message, str) else "" + + +def dm(text: str) -> Failure | None: + """Sends text as configured in ~/.claude/.env; sends nothing on a machine without that file, which hasn't asked for DMs.""" + path = env_file(pathlib.Path.home()) + if not path.exists(): + return None + config = read_config(path) + return config if isinstance(config, Failure) else send(config, text, http_json) diff --git a/bin/mattermost_dm/main.py b/bin/mattermost_dm/main.py new file mode 100644 index 00000000..3c320412 --- /dev/null +++ b/bin/mattermost_dm/main.py @@ -0,0 +1,45 @@ +"""Send a direct message from the Mattermost bot to the human. + +usage: mattermost-dm [] + +Sends , or else stdin, from the bot to the recipient that ~/.claude/.env names. That file +holds three KEY=value lines, and only its owner may read it, since it holds the bot's token: + + MATTERMOST_URL=https://chat.example + MATTERMOST_TOKEN= + MATTERMOST_RECIPIENT= + +Where that file exists, loop-claude sends the human a DM when it asks a question, a release is +ready to cut, or the loop stops with exit 1. + +Exit 0 once sent, 1, saying why, when the send failed, and 2 on misuse: bad arguments, an empty +message, or a ~/.claude/.env that is missing, lacks a key, names a server off https or that +others may read. +""" +import typing + +from mattermost_dm.dm import Config, Http, send +from failure import Failure + +USAGE = "usage: mattermost-dm []" + + +def main(argv: list[str], stdin: typing.TextIO, config: typing.Callable[[], Config | Failure], http: Http, stderr: typing.TextIO) -> int: + if argv[:1] in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + if len(argv) > 1: + print(f"mattermost-dm: takes one message, or none to read stdin; got {len(argv)} arguments\n{USAGE}", file=stderr) + return 2 + message = (argv[0] if argv else stdin.read()).strip() + if not message: + print("mattermost-dm: the message is empty", file=stderr) + return 2 + found = config() + if isinstance(found, Failure): + print(f"mattermost-dm: {found.reason}", file=stderr) + return 2 + if failed := send(found, message, http): + print(f"mattermost-dm: {failed.reason}", file=stderr) + return 1 + return 0 diff --git a/bin/mattermost_dm/test_mattermost_dm.py b/bin/mattermost_dm/test_mattermost_dm.py new file mode 100644 index 00000000..3e405ebc --- /dev/null +++ b/bin/mattermost_dm/test_mattermost_dm.py @@ -0,0 +1,210 @@ +import http.server +import io +import json +import pathlib +import subprocess +import sys +import tempfile +import threading +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from mattermost_dm import dm, main +from failure import Failure +from test_env import isolated_env + +TOOL = pathlib.Path(__file__).resolve().parents[1] / "mattermost-dm" +CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman") + + +def env_file(folder: str, text: str, mode: int = 0o600) -> pathlib.Path: + path = pathlib.Path(folder) / ".env" + path.write_text(text) + path.chmod(mode) + return path + + +class FakeServer: + """Mattermost's answers by method and path, recording each request it gets.""" + + def __init__(self, answers: dict[tuple[str, str], object]) -> None: + self.answers = answers + self.requests: list[tuple[str, str, str, object]] = [] + + def __call__(self, method: str, url: str, token: str, body: object) -> object: + self.requests.append((method, url, token, body)) + return self.answers[(method, url.removeprefix("https://chat.example"))] + + +def mattermost() -> FakeServer: + return FakeServer({ + ("GET", "/api/v4/users/me"): {"id": "bot-id"}, + ("GET", "/api/v4/users/username/lilleman"): {"id": "human-id"}, + ("POST", "/api/v4/channels/direct"): {"id": "channel-id"}, + ("POST", "/api/v4/posts"): {"id": "post-id"}, + }) + + +class ReadConfig(unittest.TestCase): + def test_reads_the_server_the_token_and_the_recipient_skipping_blanks_comments_and_quotes(self): + with tempfile.TemporaryDirectory() as folder: + path = env_file(folder, '# larvit-bot\n\nMATTERMOST_URL = https://chat.example/\nMATTERMOST_TOKEN="secret-token"\nMATTERMOST_RECIPIENT=\'lilleman\'\nOTHER=1\n') + self.assertEqual(dm.read_config(path), dm.Config("https://chat.example", "secret-token", "lilleman")) + + def test_names_the_file_and_the_keys_it_needs_where_the_file_is_missing(self): + with tempfile.TemporaryDirectory() as folder: + path = pathlib.Path(folder) / ".env" + self.assertEqual(dm.read_config(path), Failure(f"{path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")) + + def test_names_each_key_missing_or_empty(self): + with tempfile.TemporaryDirectory() as folder: + path = env_file(folder, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=\n") + self.assertEqual(dm.read_config(path), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")) + + def test_refuses_a_file_that_group_or_others_can_read_since_it_holds_the_token(self): + with tempfile.TemporaryDirectory() as folder: + for mode in (0o640, 0o604): + with self.subTest(mode=oct(mode)): + path = env_file(folder, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=t\nMATTERMOST_RECIPIENT=r\n", mode) + self.assertEqual(dm.read_config(path), Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}")) + + def test_refuses_a_server_off_https_which_would_send_the_token_in_the_clear(self): + with tempfile.TemporaryDirectory() as folder: + path = env_file(folder, "MATTERMOST_URL=http://chat.example\nMATTERMOST_TOKEN=t\nMATTERMOST_RECIPIENT=r\n") + self.assertEqual(dm.read_config(path), Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear")) + + +class Send(unittest.TestCase): + def test_finds_both_users_opens_their_direct_channel_and_posts_the_message_there(self): + server = mattermost() + self.assertIsNone(dm.send(CONFIG, "Which one?", server)) + self.assertEqual(server.requests, [ + ("GET", "https://chat.example/api/v4/users/me", "secret-token", None), + ("GET", "https://chat.example/api/v4/users/username/lilleman", "secret-token", None), + ("POST", "https://chat.example/api/v4/channels/direct", "secret-token", ["bot-id", "human-id"]), + ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}), + ]) + + def test_stops_at_the_first_failed_request(self): + server = mattermost() + server.answers[("GET", "/api/v4/users/username/lilleman")] = Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username.") + self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username.")) + self.assertEqual(len(server.requests), 2) + + def test_fails_on_an_answer_without_an_id(self): + server = mattermost() + server.answers[("POST", "/api/v4/channels/direct")] = {"status": "OK"} + self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/channels/direct answered without an id")) + self.assertEqual(len(server.requests), 3) + + +class Recorded(http.server.BaseHTTPRequestHandler): + """Answers each request with the server's next scripted status and body, recording what it got.""" + + def do_GET(self) -> None: + self.answer() + + def do_POST(self) -> None: + self.answer() + + def answer(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined] + status, body = self.server.script.pop(0) # type: ignore[attr-defined] + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + pass + + +class HttpJson(unittest.TestCase): + def serve(self, *script: tuple[int, bytes]) -> str: + server = http.server.HTTPServer(("127.0.0.1", 0), Recorded) + server.script = list(script) # type: ignore[attr-defined] + server.got = [] # type: ignore[attr-defined] + threading.Thread(target=server.serve_forever, daemon=True).start() + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + self.server = server + return f"http://127.0.0.1:{server.server_port}" + + def test_sends_the_token_as_a_bearer_and_the_body_as_json_and_reads_the_json_answer(self): + base = self.serve((201, b'{"id": "post-id"}')) + self.assertEqual(dm.http_json("POST", f"{base}/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"}) + [(method, path, headers, body)] = self.server.got # type: ignore[attr-defined] + self.assertEqual((method, path, headers["Authorization"], headers["Content-Type"], json.loads(body)), ("POST", "/api/v4/posts", "Bearer secret-token", "application/json", {"message": "hi"})) + + def test_names_the_request_the_status_and_mattermosts_message_on_an_error(self): + base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}')) + self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.")) + + def test_fails_on_an_answer_that_is_not_json(self): + base = self.serve((200, b"")) + self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON")) + + def test_fails_naming_the_server_it_cannot_reach(self): + base = self.serve() + self.server.server_close() + failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None) + self.assertIsInstance(failed, Failure) + self.assertTrue(str(getattr(failed, "reason", "")).startswith(f"cannot reach {base}: "), failed) + + +class Dm(unittest.TestCase): + def test_sends_nothing_and_fails_nothing_on_a_machine_without_the_env_file(self): + with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict("os.environ", {"HOME": home}): + self.assertIsNone(dm.dm("Which one?")) + + def test_fails_naming_the_mistake_where_the_env_file_is_there_but_wrong(self): + with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict("os.environ", {"HOME": home}): + path = pathlib.Path(home, ".claude") + path.mkdir() + env_file(str(path), "MATTERMOST_URL=https://chat.example\n") + self.assertEqual(dm.dm("Which one?"), Failure(f"{path}/.env lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")) + + +class Main(unittest.TestCase): + def run_main(self, argv: list[str], stdin: str = "", config: object = CONFIG, server: object = None) -> tuple[int, str]: + stderr = io.StringIO() + sent = server or mattermost() + code = main.main(argv, io.StringIO(stdin), lambda: config, sent, stderr) # type: ignore[arg-type] + return code, stderr.getvalue() + + def test_sends_its_argument_or_else_stdin_and_exits_0(self): + for argv, stdin in ((["Which one?"], ""), ([], "Which one?\n")): + with self.subTest(argv=argv): + server = mattermost() + self.assertEqual(self.run_main(argv, stdin, server=server), (0, "")) + self.assertEqual(server.requests[-1][3], {"channel_id": "channel-id", "message": "Which one?"}) + + def test_exits_2_on_misuse_naming_it(self): + missing = Failure("/h/.claude/.env does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT") + for argv, stdin, config, said in ( + ([], " \n", CONFIG, "mattermost-dm: the message is empty\n"), + (["a", "b"], "", CONFIG, f"mattermost-dm: takes one message, or none to read stdin; got 2 arguments\n{main.USAGE}\n"), + (["hi"], "", missing, f"mattermost-dm: {missing.reason}\n"), + ): + with self.subTest(argv=argv, stdin=stdin): + self.assertEqual(self.run_main(argv, stdin, config), (2, said)) + + def test_exits_1_naming_why_the_send_failed(self): + server = mattermost() + server.answers[("GET", "/api/v4/users/me")] = Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.") + self.assertEqual(self.run_main(["hi"], server=server), (1, "mattermost-dm: GET /api/v4/users/me answered 401: Invalid or expired session, please login again.\n")) + + def test_the_launcher_prints_help_and_reads_the_env_file_under_home(self): + with tempfile.TemporaryDirectory() as home: + env = {**isolated_env(), "HOME": home} + helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env) + self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0])) + sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env) + self.assertEqual((sent.returncode, sent.stderr), (2, f"mattermost-dm: {home}/.claude/.env does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT\n")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index 28525b42..699ffac4 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -230,7 +230,7 @@ class Main(unittest.TestCase): result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}} return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) -- 2.52.0 From f10170bf8b080059a7ed4c973da4bd153c298e0b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 22:25:34 +0100 Subject: [PATCH 4/9] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20follow=20no?= =?UTF-8?q?=20redirect,=20so=20the=20token=20reaches=20only=20the=20server?= =?UTF-8?q?=20named?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/mattermost_dm/dm.py | 15 +++++++++++++-- bin/mattermost_dm/test_mattermost_dm.py | 7 +++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/bin/mattermost_dm/dm.py b/bin/mattermost_dm/dm.py index cb0f4614..1ceae933 100644 --- a/bin/mattermost_dm/dm.py +++ b/bin/mattermost_dm/dm.py @@ -17,6 +17,16 @@ TIMEOUT = 10 Http = typing.Callable[[str, str, str, object], object] +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Follows no redirect: urllib resends the token to the new location, even one off https, and Mattermost's API answers without one.""" + + def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None: + return None + + +OPENER = urllib.request.build_opener(NoRedirect) + + @dataclasses.dataclass(frozen=True) class Config: url: str @@ -89,10 +99,11 @@ def http_json(method: str, url: str, token: str, body: object) -> object: data = None if body is None else json.dumps(body).encode() request = urllib.request.Request(url, data, {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, method=method) try: - with urllib.request.urlopen(request, timeout=TIMEOUT) as response: + with OPENER.open(request, timeout=TIMEOUT) as response: raw = response.read() except urllib.error.HTTPError as failure: - return Failure(f"{request_name} answered {failure.code}: {error_message(failure.read()) or failure.reason}") + with failure: + return Failure(f"{request_name} answered {failure.code}: {error_message(failure.read()) or failure.reason}") except (OSError, ValueError) as failure: server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", "")) return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}") diff --git a/bin/mattermost_dm/test_mattermost_dm.py b/bin/mattermost_dm/test_mattermost_dm.py index 3e405ebc..0747efa1 100644 --- a/bin/mattermost_dm/test_mattermost_dm.py +++ b/bin/mattermost_dm/test_mattermost_dm.py @@ -114,6 +114,8 @@ class Recorded(http.server.BaseHTTPRequestHandler): self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined] status, body = self.server.script.pop(0) # type: ignore[attr-defined] self.send_response(status) + if 300 <= status < 400: + self.send_header("Location", "/elsewhere") self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(body) @@ -143,6 +145,11 @@ class HttpJson(unittest.TestCase): base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}')) self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.")) + def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self): + base = self.serve((302, b"{}")) + self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found")) + self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined] + def test_fails_on_an_answer_that_is_not_json(self): base = self.serve((200, b"")) self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON")) -- 2.52.0 From 23af106b47c0545667cc7a0b2f1991033efad080 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 22:37:52 +0100 Subject: [PATCH 5/9] =?UTF-8?q?Answer=20stability=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=205=20=F0=9F=9F=A1=20(0=20misread);=20catch=20a?= =?UTF-8?q?=20broken=20HTTP=20answer,=20drop=20typed=20keys=20before=20the?= =?UTF-8?q?=20DM,=20DM=20every=20stop=20but=20Ctrl-C=20and=20a=20crash,=20?= =?UTF-8?q?inject=20home=20and=20http,=20and=20test=20the=20gaps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- bin/loop_claude/cycle/interrupt.py | 10 ++-- bin/loop_claude/direct_message.py | 2 +- bin/loop_claude/loop/main.py | 7 ++- bin/loop_claude/loop/routing_check.py | 2 + bin/loop_claude/loop/usage.py | 6 +-- bin/loop_claude/test_loop_claude.py | 41 +++++++++++--- bin/loop_effects/effects.py | 5 +- bin/mattermost_dm/dm.py | 19 ++++--- bin/mattermost_dm/main.py | 10 ++-- bin/mattermost_dm/test_mattermost_dm.py | 71 ++++++++++++++++++++----- 11 files changed, 131 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 93926f8f..6bc60dc2 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Then pick a model with `/model`. Link `loop-claude` and `loop-inbox` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude` and `ln -s ~/.claude/bin/loop-inbox ~/.local/bin/loop-inbox`. Every claude they start, the interactive ones included, skips every permission prompt. -To get loop-claude's questions and stops as Mattermost DMs from a bot, write the server, the bot's token and your username into `~/.claude/.env`, in the keys `bin/mattermost-dm --help` names, and run `chmod 600 ~/.claude/.env`. Without that file, loop-claude sends no DM. +To get loop-claude's questions and stops as Mattermost DMs from a bot, write the server, the bot's token and your username into `~/.claude/.env`, in the keys `~/.claude/bin/mattermost-dm --help` names, and run `chmod 600 ~/.claude/.env`. Without that file, loop-claude sends no DM. ## Update @@ -105,7 +105,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `larv-review ` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. - `loop-inbox` shows the interrupts of every loop-claude on the machine, oldest first, takes each one's answer, `/talk` included, and lists every running loop with the `todo.md` items its chunk takes; `loop-inbox --help` states how. -- `mattermost-dm []` sends a message, or else stdin, from the Mattermost bot to the human, configured in `~/.claude/.env`; `loop-claude` sends one for each question and each stop with exit 1, and `mattermost-dm --help` names the file's keys. +- `mattermost-dm []` sends a message, or else stdin, from the Mattermost bot to the human; `~/.claude/.env` names the server, the bot's token and the human, and `mattermost-dm --help` names its keys. `loop-claude --help` says when loop-claude sends one. - `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores. - `mutate-changes [--base ] [--prefix ] [--jobs ]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language. - `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format. diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index f18cdb89..0b710a40 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -43,12 +43,14 @@ class Talked: def interrupt(question: str, answer_here: bool, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> str | Talked | Stop: """Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends.""" say(f"\n{question}", effects) - # Before the terminal check, so a loop that cannot ask still tells the human what it would have asked. + on_terminal = effects.on_terminal() + if on_terminal: + # Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK. + effects.discard_typed() + # After the discard, so an answer typed while the DM sends counts; before the terminal check, so a loop that cannot ask still tells the human what it would have asked. tell(f"loop-claude in {session.root} asks:\n\n{question}", effects) - if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): + if stop := needs_terminal(ANSWER_QUESTION, on_terminal): return stop - # Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK. - effects.discard_typed() ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal()) with listed(questions, ask, effects): answer = first_answer(ask, questions, effects) if answer_here else OpenOnTerminal() diff --git a/bin/loop_claude/direct_message.py b/bin/loop_claude/direct_message.py index d5b09955..09c73959 100644 --- a/bin/loop_claude/direct_message.py +++ b/bin/loop_claude/direct_message.py @@ -2,6 +2,6 @@ from loop_effects.effects import Effects, say def tell(text: str, effects: Effects) -> None: - """DMs text to the human, saying on the terminal why where the DM fails; the DM only copies what the terminal shows, so its failure never stops the loop.""" + """DMs text to the human. Where the DM fails, it says why on stderr and goes on: the DM only copies what the terminal shows, so its failure never stops the loop.""" if failed := effects.dm(text): say(f"could not DM you on Mattermost: {failed.reason}", effects) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 8fd55bf4..2590b206 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -31,10 +31,13 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: stop = run_loop(argv, env, paths, launcher, cwd, effects) except KeyboardInterrupt: stop = Stop(130, "") + except Exception as crash: + tell(f"loop-claude in {cwd} crashed: {crash!r}", effects) + raise if stop.reason: say(stop.reason, effects, stdout=not stop.code) - # Exit 2 is a stop the human chose or must answer at the terminal, and 130 is Ctrl-C; a loop given no task stops before it runs. - if stop.code == 1 and argv: + # Every stop but the human's own Ctrl-C and the help is DMed, so a loop left overnight never ends unseen. A loop given no task prints the help. + if stop.code != 130 and stop.reason != HELP: tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects) return stop.code diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 20087a6b..8e69abf7 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -14,6 +14,7 @@ from routing_figures.render import render from model_routing.ladder import Rung from routing_figures import state from loop_claude.stop import Stop +from loop_claude.direct_message import tell from records.utc_stamp import utc @@ -54,6 +55,7 @@ def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) -> bullets = "".join(f"- {call.sentence()}\n" for call in new) question = f"loop-claude's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}" say(f"\n{question}", loop.effects) + tell(f"loop-claude in {loop.root} asks:\n\n{question}", loop.effects) if not loop.effects.on_terminal(): say("Not on a terminal: the calls are raised again at the next measurement.", loop.effects) return None diff --git a/bin/loop_claude/loop/usage.py b/bin/loop_claude/loop/usage.py index 1d4b1522..b9627d6e 100644 --- a/bin/loop_claude/loop/usage.py +++ b/bin/loop_claude/loop/usage.py @@ -33,9 +33,9 @@ interrupts of every loop on the machine. The first answer counts, from either pl - Enter alone, on loop-claude's terminal: stops the loop. A release ready to cut opens that session on the terminal at once, since only the human may cut it; loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on. -Where ~/.claude/.env exists, each question, and each stop with exit 1, also goes to the human as a -Mattermost DM, as bin/mattermost-dm sends it; a DM that fails is said on the terminal, and the loop -goes on. +Where ~/.claude/.env exists, loop-claude also sends the human each question, each release ready +to cut and each stop as a Mattermost DM, as bin/mattermost-dm sends it. Two stops are left out: +Ctrl-C, and printing this help. A DM that fails is said on stderr, and the loop goes on. While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes, as bin/loop_state/running_loops.py describes. diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 7e270c81..886cf359 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -94,7 +94,7 @@ class FakeEffects: def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=()): self.calls = [] - # Each direct message sent, apart from calls, so tests that list every call need not list them. Without a script, each is sent. + # Each direct message sent. They stay out of self.calls, so a test that lists every call doesn't list them. Without a script, each is sent. self.dms = [] self.dm_failures = list(dm_failures) self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)} @@ -735,13 +735,20 @@ class Interrupts(unittest.TestCase): self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n")) self.assertEqual(fake.calls, []) - def test_dms_the_question_naming_the_project_before_asking_on_a_terminal_or_off_one(self): + def test_dms_the_question_naming_the_project_on_a_terminal_or_off_one(self): for on_terminal in (True, False): with self.subTest(on_terminal=on_terminal): fake = FakeEffects(inputs=["Use B."], on_terminal=on_terminal) self.put(fake) self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks:\n\nWhich one?"]) + def test_drops_the_keys_typed_before_the_question_ahead_of_the_dm_so_an_answer_typed_while_it_sends_counts(self): + fake = FakeEffects(inputs=["Use B."]) + seen = [] + effects = dataclasses.replace(fake.effects(), dm=lambda text: seen.append(list(fake.calls))) + self.assertEqual(self.put(fake, effects=effects)[0], "Use B.") + self.assertEqual(seen, [[("discard_typed", None)]]) + def test_says_why_a_dm_failed_and_still_takes_the_answer(self): fake = FakeEffects(inputs=["Use B."], dm_failures=[Failure("cannot reach https://chat.example: timed out")]) self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n{STAMP} could not DM you on Mattermost: cannot reach https://chat.example: timed out\n")) @@ -983,6 +990,8 @@ class RoutingCheck(unittest.TestCase): self.assertIn(f"change nothing until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6]) self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", said.getvalue()) self.assertIn("routing figures: full", said.getvalue()) + [sent] = fake.dms + self.assertTrue(sent.startswith(f"loop-claude in {self.loop(fake).root} asks:\n\nloop-claude's routing figures call for a routing change:\n- {new[0].sentence()}\n"), sent) class ModelPrompt(unittest.TestCase): @@ -1812,6 +1821,24 @@ class StopDms(unittest.TestCase): code = main.main(argv, {}, paths.paths_from(pathlib.Path(home)), pathlib.Path(home, "loop-claude"), CWD, fake.effects()) return code, said.getvalue() + def test_dms_the_reason_of_a_stop_with_exit_2_such_as_a_chunk_left_unfinished_too_often(self): + fake = FakeEffects() + with unittest.mock.patch.object(main, "run_loop", return_value=Stop(2, "the human is needed to look at the chunk, but it stayed unfinished")): + self.assertEqual(self.run_main(["do it"], fake)[0], 2) + self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the human is needed to look at the chunk, but it stayed unfinished"]) + + def test_skips_the_dm_where_ctrl_c_stopped_the_loop(self): + fake = FakeEffects() + with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt): + self.assertEqual(self.run_main(["do it"], fake)[0], 130) + self.assertEqual(fake.dms, []) + + def test_dms_a_crash_before_it_reaches_the_terminal(self): + fake = FakeEffects() + with unittest.mock.patch.object(main, "run_loop", side_effect=RuntimeError("boom")), self.assertRaises(RuntimeError): + self.run_main(["do it"], fake) + self.assertEqual(fake.dms, [f"loop-claude in {CWD} crashed: RuntimeError('boom')"]) + def test_dms_the_reason_where_a_loop_given_a_task_stops_with_exit_1(self): fake = FakeEffects() code, said = self.run_main([main.RELOAD_FLAG, "3"], fake) @@ -1822,10 +1849,12 @@ class StopDms(unittest.TestCase): fake = FakeEffects(dm_failures=[Failure("cannot reach https://chat.example: timed out")]) self.assertTrue(self.run_main([main.RELOAD_FLAG, "3"], fake)[1].endswith(f"Handed: 3\n{STAMP} could not DM you on Mattermost: cannot reach https://chat.example: timed out\n")) - def test_sends_nothing_where_no_task_is_given(self): - fake = FakeEffects() - self.assertEqual(self.run_main([], fake)[0], 1) - self.assertEqual(fake.dms, []) + def test_skips_the_dm_where_it_prints_its_help(self): + for argv, code in (([], 1), (["--help"], 0)): + with self.subTest(argv=argv): + fake = FakeEffects() + self.assertEqual(self.run_main(argv, fake)[0], code) + self.assertEqual(fake.dms, []) class HelpLimits(unittest.TestCase): diff --git a/bin/loop_effects/effects.py b/bin/loop_effects/effects.py index 5b45714b..c5594964 100644 --- a/bin/loop_effects/effects.py +++ b/bin/loop_effects/effects.py @@ -4,6 +4,7 @@ A change here, such as to how input reads a line, changes every tool that runs o """ import dataclasses import os +import pathlib import select import signal import subprocess @@ -13,7 +14,7 @@ import time import typing import uuid -from mattermost_dm.dm import dm +from mattermost_dm.dm import dm, http_json from failure import Failure from git_cli import git_repo from machine_load.memory import Memory, read_memory @@ -84,7 +85,7 @@ def system_effects() -> Effects: claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True), claude_on_terminal=claude_on_terminal, discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH), - dm=dm, + dm=lambda text: dm(text, pathlib.Path.home(), http_json), execv=os.execv, git=git_repo.git, input=input, diff --git a/bin/mattermost_dm/dm.py b/bin/mattermost_dm/dm.py index 1ceae933..0f01578b 100644 --- a/bin/mattermost_dm/dm.py +++ b/bin/mattermost_dm/dm.py @@ -1,5 +1,6 @@ """Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4.""" import dataclasses +import http.client import json import pathlib import typing @@ -10,15 +11,15 @@ import urllib.request from failure import Failure KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT") -# Seconds a request may take, so an unreachable server holds loop-claude's interrupt only briefly. +# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly. TIMEOUT = 10 -# Sends a request, the body as JSON where there is one, and returns the JSON answer. +# Sends a request, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none. Http = typing.Callable[[str, str, str, object], object] class NoRedirect(urllib.request.HTTPRedirectHandler): - """Follows no redirect: urllib resends the token to the new location, even one off https, and Mattermost's API answers without one.""" + """Refuses every redirect, which Mattermost's API never sends: urllib would resend the token to the new location, even one off https.""" def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None: return None @@ -94,7 +95,7 @@ def id_of(answer: object, request: str) -> str | Failure: def http_json(method: str, url: str, token: str, body: object) -> object: - """The JSON that url answers; a Failure naming the request where it cannot be reached, answers an error or answers something other than JSON.""" + """The JSON that url answers; a Failure naming the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON.""" request_name = f"{method} {urllib.parse.urlsplit(url).path}" data = None if body is None else json.dumps(body).encode() request = urllib.request.Request(url, data, {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, method=method) @@ -104,6 +105,8 @@ def http_json(method: str, url: str, token: str, body: object) -> object: except urllib.error.HTTPError as failure: with failure: return Failure(f"{request_name} answered {failure.code}: {error_message(failure.read()) or failure.reason}") + except http.client.HTTPException as failure: + return Failure(f"{request_name} got a broken answer: {failure!r}") except (OSError, ValueError) as failure: server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", "")) return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}") @@ -122,10 +125,10 @@ def error_message(raw: bytes) -> str: return message if isinstance(message, str) else "" -def dm(text: str) -> Failure | None: - """Sends text as configured in ~/.claude/.env; sends nothing on a machine without that file, which hasn't asked for DMs.""" - path = env_file(pathlib.Path.home()) +def dm(text: str, home: pathlib.Path, http: Http) -> Failure | None: + """Sends text as home's .claude/.env configures it. A machine without that file hasn't asked for DMs, so there the DM is skipped.""" + path = env_file(home) if not path.exists(): return None config = read_config(path) - return config if isinstance(config, Failure) else send(config, text, http_json) + return config if isinstance(config, Failure) else send(config, text, http) diff --git a/bin/mattermost_dm/main.py b/bin/mattermost_dm/main.py index 3c320412..6d7cd04a 100644 --- a/bin/mattermost_dm/main.py +++ b/bin/mattermost_dm/main.py @@ -9,12 +9,10 @@ holds three KEY=value lines, and only its owner may read it, since it holds the MATTERMOST_TOKEN= MATTERMOST_RECIPIENT= -Where that file exists, loop-claude sends the human a DM when it asks a question, a release is -ready to cut, or the loop stops with exit 1. - -Exit 0 once sent, 1, saying why, when the send failed, and 2 on misuse: bad arguments, an empty -message, or a ~/.claude/.env that is missing, lacks a key, names a server off https or that -others may read. +Exit 0 once the message is sent. +Exit 1, saying why, when Mattermost cannot be reached or refuses the message. +Exit 2, saying why, on misuse: bad arguments, an empty message, or a ~/.claude/.env that is +missing or unreadable, lacks a key, names a server off https, or that others may read. """ import typing diff --git a/bin/mattermost_dm/test_mattermost_dm.py b/bin/mattermost_dm/test_mattermost_dm.py index 0747efa1..8924e5a2 100644 --- a/bin/mattermost_dm/test_mattermost_dm.py +++ b/bin/mattermost_dm/test_mattermost_dm.py @@ -2,6 +2,7 @@ import http.server import io import json import pathlib +import socket import subprocess import sys import tempfile @@ -93,11 +94,18 @@ class Send(unittest.TestCase): self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username.")) self.assertEqual(len(server.requests), 2) - def test_fails_on_an_answer_without_an_id(self): + def test_fails_on_an_answer_without_an_id_or_one_that_is_not_an_object(self): + for answer in ({"status": "OK"}, ["channel-id"], {"id": ""}): + with self.subTest(answer=answer): + server = mattermost() + server.answers[("POST", "/api/v4/channels/direct")] = answer + self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/channels/direct answered without an id")) + self.assertEqual(len(server.requests), 3) + + def test_fails_where_the_post_itself_fails(self): server = mattermost() - server.answers[("POST", "/api/v4/channels/direct")] = {"status": "OK"} - self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/channels/direct answered without an id")) - self.assertEqual(len(server.requests), 3) + server.answers[("POST", "/api/v4/posts")] = Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions.") + self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions.")) class Recorded(http.server.BaseHTTPRequestHandler): @@ -113,6 +121,11 @@ class Recorded(http.server.BaseHTTPRequestHandler): length = int(self.headers.get("Content-Length") or 0) self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined] status, body = self.server.script.pop(0) # type: ignore[attr-defined] + if status is None: + # Raw bytes, as a server that breaks HTTP sends them. + self.wfile.write(body) + self.close_connection = True + return self.send_response(status) if 300 <= status < 400: self.send_header("Location", "/elsewhere") @@ -150,6 +163,28 @@ class HttpJson(unittest.TestCase): self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found")) self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined] + def test_sends_no_body_with_a_get(self): + base = self.serve((200, b'{"id": "bot-id"}')) + dm.http_json("GET", f"{base}/api/v4/users/me", "t", None) + [(_, _, headers, body)] = self.server.got # type: ignore[attr-defined] + self.assertEqual((headers.get("Content-Length"), body), (None, b"")) + + def test_fails_on_an_answer_that_breaks_http(self): + for raw in (b"garbage\r\n\r\n", b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{}"): + with self.subTest(raw=raw): + base = self.serve((None, raw)) + failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None) + self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed) + + def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self): + silent = socket.socket() + self.addCleanup(silent.close) + silent.bind(("127.0.0.1", 0)) + silent.listen(1) + base = f"http://127.0.0.1:{silent.getsockname()[1]}" + with unittest.mock.patch.object(dm, "TIMEOUT", 0.2): + self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure(f"cannot reach {base}: timed out")) + def test_fails_on_an_answer_that_is_not_json(self): base = self.serve((200, b"")) self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON")) @@ -163,16 +198,28 @@ class HttpJson(unittest.TestCase): class Dm(unittest.TestCase): - def test_sends_nothing_and_fails_nothing_on_a_machine_without_the_env_file(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict("os.environ", {"HOME": home}): - self.assertIsNone(dm.dm("Which one?")) + def home_with(self, home: str, text: str) -> pathlib.Path: + folder = pathlib.Path(home, ".claude") + folder.mkdir() + return env_file(str(folder), text) + + def test_sends_through_the_env_file_under_home(self): + with tempfile.TemporaryDirectory() as home: + self.home_with(home, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n") + server = mattermost() + self.assertIsNone(dm.dm("Which one?", pathlib.Path(home), server)) + self.assertEqual(server.requests[-1], ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"})) + + def test_skips_the_dm_on_a_machine_without_the_env_file(self): + with tempfile.TemporaryDirectory() as home: + server = mattermost() + self.assertIsNone(dm.dm("Which one?", pathlib.Path(home), server)) + self.assertEqual(server.requests, []) def test_fails_naming_the_mistake_where_the_env_file_is_there_but_wrong(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict("os.environ", {"HOME": home}): - path = pathlib.Path(home, ".claude") - path.mkdir() - env_file(str(path), "MATTERMOST_URL=https://chat.example\n") - self.assertEqual(dm.dm("Which one?"), Failure(f"{path}/.env lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")) + with tempfile.TemporaryDirectory() as home: + path = self.home_with(home, "MATTERMOST_URL=https://chat.example\n") + self.assertEqual(dm.dm("Which one?", pathlib.Path(home), mattermost()), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")) class Main(unittest.TestCase): -- 2.52.0 From 313e129b20f6cf797f375ed9373b84165cedba44 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 22:37:52 +0100 Subject: [PATCH 6/9] =?UTF-8?q?Answer=20product-owner=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20DM=20a=20ro?= =?UTF-8?q?uting=20call=20and=20a=20crash,=20fixed=20in=20the=20stability?= =?UTF-8?q?=20round=201=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From b6c14ba223c7b8dc8367c51aedaa1c01bf891062 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 22:37:52 +0100 Subject: [PATCH 7/9] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=206=20=F0=9F=9F=A1=20(0=20misread);=20fixed=20in?= =?UTF-8?q?=20the=20stability=20round=201=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From d2d5e10e1931f72553f2203a255703e820c63b22 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 22:39:45 +0100 Subject: [PATCH 8/9] =?UTF-8?q?Answer=20stability=20round=202:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20read=20an?= =?UTF-8?q?=20error=20answer's=20body=20guarded,=20so=20one=20cut=20short?= =?UTF-8?q?=20names=20its=20status?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/mattermost_dm/dm.py | 9 +++++---- bin/mattermost_dm/test_mattermost_dm.py | 4 ++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/bin/mattermost_dm/dm.py b/bin/mattermost_dm/dm.py index 0f01578b..b71d27df 100644 --- a/bin/mattermost_dm/dm.py +++ b/bin/mattermost_dm/dm.py @@ -104,7 +104,7 @@ def http_json(method: str, url: str, token: str, body: object) -> object: raw = response.read() except urllib.error.HTTPError as failure: with failure: - return Failure(f"{request_name} answered {failure.code}: {error_message(failure.read()) or failure.reason}") + return Failure(f"{request_name} answered {failure.code}: {error_message(failure) or failure.reason}") except http.client.HTTPException as failure: return Failure(f"{request_name} got a broken answer: {failure!r}") except (OSError, ValueError) as failure: @@ -116,10 +116,11 @@ def http_json(method: str, url: str, token: str, body: object) -> object: return Failure(f"{request_name} answered with something other than JSON") -def error_message(raw: bytes) -> str: +def error_message(failure: urllib.error.HTTPError) -> str: + """Mattermost's message in an error answer; empty where the body is cut short, breaks HTTP or holds none.""" try: - answer = json.loads(raw) - except ValueError: + answer = json.loads(failure.read()) + except (http.client.HTTPException, OSError, ValueError): return "" message = answer.get("message") if isinstance(answer, dict) else None return message if isinstance(message, str) else "" diff --git a/bin/mattermost_dm/test_mattermost_dm.py b/bin/mattermost_dm/test_mattermost_dm.py index 8924e5a2..9ed360be 100644 --- a/bin/mattermost_dm/test_mattermost_dm.py +++ b/bin/mattermost_dm/test_mattermost_dm.py @@ -176,6 +176,10 @@ class HttpJson(unittest.TestCase): failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None) self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed) + def test_names_the_status_of_an_error_whose_body_is_cut_short(self): + base = self.serve((None, b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\n{}")) + self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error")) + def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self): silent = socket.socket() self.addCleanup(silent.close) -- 2.52.0 From 4d132e9a3cce0b8ceec97450c275a4da428a9366 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 22:41:56 +0100 Subject: [PATCH 9/9] Finish item 329 --- CHANGELOG.md | 1 + todo.md | 11 ----------- 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a331bf0..4e598c6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- loop-claude now sends you a Mattermost DM from a bot for each question it asks, each release ready to cut, each routing call and each stop but Ctrl-C, where `~/.claude/.env` names the server, the bot's token and your username. `bin/mattermost-dm` sends one by hand; `mattermost-dm --help` names the keys. A DM that fails is one line on loop-claude's terminal, and the loop goes on. - larv-review's worker now runs the project's tests and static analysis, and checks the docs for each name its change touches, before each stability round, and hands stability-reviewer the commit that passed; the reviewer doesn't run them again on it. - stability-reviewer, product-owner-reviewer and systems-architect have one-line descriptions, which shrinks the agent listing every session carries. - `mutate-changes` mutation-tests the lines a branch changes, running cargo-mutants, Infection, mutmut or Stryker by each file's language, and prints each mutant that no test kills. Where a project's README documents no mutation command of its own, larv-review now runs it before each stability round and hands stability-reviewer the mutants that survive. diff --git a/todo.md b/todo.md index b4ec7391..448a02e9 100644 --- a/todo.md +++ b/todo.md @@ -24,7 +24,6 @@ | 295 | 0.8.0 | | | **Have `chunk-pr merge` wait for the forge's required checks itself, and give workers one command that waits for a background log or report file.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 2, 1.5 by 2 | 1.6 | | 319 | 0.8.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.4 | | 309 | 0.8.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.3 | -| 329 | 0.8.0 | | owner | **DM the human through larvit-bot on Mattermost whenever loop-claude interrupts, a release is ready to cut, or the loop stops on an error, reading the server, the bot token and the recipient from `~/.claude/.env`.** | 4 | 2 | 3 | 7 | 4 | 1.5 by 4 | 1.3 | | 299 | 0.8.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 | | 311 | 0.8.0 | | | **Hand each worker's claude a Bash output ceiling that saves longer output to a file, and refuse a Read of a session transcript under `~/.claude/projects`.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3 | 1.2 | | 316 | 0.8.0 | | | **Launch comprehension seats as an agent type of their own under `agents/`, without `CLAUDE.md` and the skill and agent listings a general-purpose subagent carries.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 | @@ -157,16 +156,6 @@ Why it should hold quality: the seats are one model with different personas, so Decide once `agreement` has its 10 commits scored twice. Keep four seats on any pass that files a floor item, since its places come from seat reports. Revise the decision `review: the comprehension check records how hard a project is to read…`, which names the four-seat run. -### 329. DM the human through larvit-bot on Mattermost whenever loop-claude interrupts, a release is ready to cut, or the loop stops on an error, reading the server, the bot token and the recipient from `~/.claude/.env`. - -The human asked for this, for 0.8.0. A new tool, `bin/mattermost-dm`, sends its argument, or stdin, as a direct message from the bot to the recipient through Mattermost's REST API v4: `GET /api/v4/users/me` for the bot's id, `GET /api/v4/users/username/` for the recipient's, `POST /api/v4/channels/direct` for the channel, then `POST /api/v4/posts`. It uses only Python's standard library. - -`~/.claude/.env` holds `MATTERMOST_URL`, `MATTERMOST_TOKEN` and `MATTERMOST_RECIPIENT` as `KEY=value` lines. The `.gitignore` allowlist already keeps it out of every commit. The tool refuses a file that group or others can read, since it holds the token. Exit 0 when sent, 1 when the send failed, 2 on misuse, such as a missing file or key or an empty message. - -loop-claude sends the DM through an injected effect, so tests never reach the network. A DM that fails prints one line on loop-claude's terminal and the loop carries on, since the DM only copies what the terminal shows. Answering by replying to the DM is a later item. - -This item was filed as 325 on branch item-325 while main filed its own 325, so it was renumbered as the branch merged main. - ### 299. Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt. The judge's LLM still decides three things: the verdict kind, the escalation it quotes, and whether a release is ready to cut (`docs/decisions.md` → `routing: loop-claude reads the items a chunk takes …`). This item replays the verdict kind. No single rule found so far separates interrupts: a "?" in the worker's final message appears in 48 interrupts and misses 66. A smaller LLM already failed the replay (`docs/decisions.md` → `routing: on a model judge-replay covered, …`: Sonnet returned another kind on 3 interrupts, Haiku missed 7). Untested are combined code rules, a decision table, and a small classifier trained and run on this machine on the archived verdicts (372 finished, 234 interrupt, 42 unfinished, 20 quoted). Run each offline, nothing sent to an outside service (goal 4), and count disagreements by kind; the bar is zero missed interrupts. A hosted decision model is out of scope, since it would send transcripts to an outside service. -- 2.52.0