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)