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/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/README.md b/README.md index b4403ccb..6bc60dc2 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 `~/.claude/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; `~/.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. @@ -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..0b710a40 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,10 +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) - if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): + 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, 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 new file mode 100644 index 00000000..09c73959 --- /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. 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 7c002163..2590b206 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 @@ -30,8 +31,14 @@ 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) + # 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 79c4266c..b9627d6e 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, 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 e1bf08ec..886cf359 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. 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)} # 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,24 @@ 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_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")) + 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")) @@ -964,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): @@ -1787,6 +1815,48 @@ 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_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) + 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_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): 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..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,6 +14,8 @@ import time import typing import uuid +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 @@ -44,6 +47,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 +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=lambda text: dm(text, pathlib.Path.home(), http_json), 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..b71d27df --- /dev/null +++ b/bin/mattermost_dm/dm.py @@ -0,0 +1,135 @@ +"""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 +import urllib.error +import urllib.parse +import urllib.request + +from failure import Failure + +KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT") +# 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, or a Failure saying why there is none. +Http = typing.Callable[[str, str, str, object], object] + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + """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 + + +OPENER = urllib.request.build_opener(NoRedirect) + + +@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 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) + try: + with OPENER.open(request, timeout=TIMEOUT) as response: + raw = response.read() + except urllib.error.HTTPError as failure: + with failure: + 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: + 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(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(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 "" + + +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) diff --git a/bin/mattermost_dm/main.py b/bin/mattermost_dm/main.py new file mode 100644 index 00000000..6d7cd04a --- /dev/null +++ b/bin/mattermost_dm/main.py @@ -0,0 +1,43 @@ +"""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= + +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 + +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..9ed360be --- /dev/null +++ b/bin/mattermost_dm/test_mattermost_dm.py @@ -0,0 +1,268 @@ +import http.server +import io +import json +import pathlib +import socket +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_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/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): + """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] + 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") + 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_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_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_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) + 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")) + + 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 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: + 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): + 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) diff --git a/todo.md b/todo.md index bff4935b..448a02e9 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 329` +`Next ID = 330` ## Items