From 6a553b9574672bd6ed8c839fc3105805a2a945e9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 22:53:00 +0100 Subject: [PATCH] Name each project's notifier in its config, with Mattermost and Slack as backends --- .gitignore | 6 +- CHANGELOG.md | 3 +- README.md | 10 +- bin/loop_claude/direct_message.py | 2 +- bin/loop_claude/loop/usage.py | 4 +- bin/loop_claude/test_black_box.py | 6 +- bin/loop_claude/test_loop_claude.py | 4 +- bin/loop_effects/effects.py | 6 +- bin/mattermost-dm | 9 -- bin/mattermost_dm/dm.py | 28 +---- bin/mattermost_dm/main.py | 47 ------- bin/mattermost_dm/test_mattermost_dm.py | 124 +----------------- bin/notifier/__init__.py | 0 bin/notifier/main.py | 55 ++++++++ bin/notifier/notify.py | 58 +++++++++ bin/notifier/test_notifier.py | 146 ++++++++++++++++++++++ bin/notify | 9 ++ bin/project_config/main.py | 15 ++- bin/project_config/settings.py | 12 +- bin/project_config/test_project_config.py | 31 ++++- bin/rest_client/json_request.py | 3 + bin/slack_dm/__init__.py | 0 bin/slack_dm/dm.py | 51 ++++++++ bin/slack_dm/test_slack_dm.py | 78 ++++++++++++ docs/reading-cost.md | 17 +++ 25 files changed, 495 insertions(+), 229 deletions(-) delete mode 100755 bin/mattermost-dm delete mode 100644 bin/mattermost_dm/main.py create mode 100644 bin/notifier/__init__.py create mode 100644 bin/notifier/main.py create mode 100644 bin/notifier/notify.py create mode 100644 bin/notifier/test_notifier.py create mode 100755 bin/notify create mode 100644 bin/slack_dm/__init__.py create mode 100644 bin/slack_dm/dm.py create mode 100644 bin/slack_dm/test_slack_dm.py diff --git a/.gitignore b/.gitignore index 2094a65b..afdb19a0 100644 --- a/.gitignore +++ b/.gitignore @@ -67,7 +67,6 @@ !bin/loop_state/*.py !bin/machine_load/ !bin/machine_load/*.py -!bin/mattermost-dm !bin/mattermost_dm/ !bin/mattermost_dm/*.py !bin/metric-bench @@ -78,6 +77,9 @@ !bin/mutate-changes !bin/mutate_changes/ !bin/mutate_changes/*.py +!bin/notifier/ +!bin/notifier/*.py +!bin/notify !bin/plan_store/ !bin/plan_store/*.py !bin/project-config @@ -123,6 +125,8 @@ !bin/score_outcomes/*.py !bin/settings_filter.py !bin/setup.cfg +!bin/slack_dm/ +!bin/slack_dm/*.py !bin/statusline.py !bin/subagent-rung !bin/subagent_rung/ diff --git a/CHANGELOG.md b/CHANGELOG.md index f4ebbe44..ab930e50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,8 @@ - The new `project-record open ` prints the file in which an agent reads and edits one of a project's five records (`decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`), and `project-record save ` stores the edit. Every tool now reads and writes a record the same one way, so that a later release can keep a record outside files. No config needs a change. - `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The Mattermost DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link. Once every loop started before the upgrade has reloaded or ended, remove the folder `~/.local/state/loop-claude/`, which nothing reads any more. - rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either or searches a folder holding either with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through. -- To keep Mattermost DMs, move the keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/.env`, and name it in the project's config as `env-file`; `mattermost-dm` and loop-claude's DMs no longer read `~/.claude/.env`, and a project with no `env-file` gets none. A failure names each missing key and holds no token. +- A project's config names the service for loop-claude's DMs: `notifier = "mattermost"` or `"slack"`, with the bot's token and the recipient in the `env-file`. Slack's keys are `SLACK_TOKEN` and `SLACK_RECIPIENT`, a bot token with the `chat:write` scope and a member ID. To upgrade, move the Mattermost keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/.env`, name it as `env-file` and add `notifier = "mattermost"`. A project with no `notifier` gets no DM, and `~/.claude/.env` is no longer read. A failure names each missing key and holds no token. +- `mattermost-dm` is now `notify`, which sends through the project's `notifier`; `notify --help` names the keys. ## 0.10.0 diff --git a/README.md b/README.md index a1f26959..52511de2 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ Then pick a model with `/model`. Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, 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-projects/.env`, in the keys `~/.claude/bin/mattermost-dm --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/.env"` to the project's config, as Install → "Set up a project" describes. Without that setting, loop-claude sends no DM for the project; `~/.claude/.env` is no longer read. +To get loop-claude's questions and stops as DMs from a bot, write the bot's token and your recipient into `~/.claude-projects/.env`, in the keys `~/.claude/bin/notify --help` names for Mattermost or Slack, run `chmod 600` on it, and add `env-file = "~/.claude-projects/.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes. Without `notifier`, loop-claude sends no DM for the project, whatever the env file holds; `~/.claude/.env` is no longer read. ### Set up a project @@ -96,6 +96,8 @@ principles = "~/.claude/principles" A project may also set `env-file`, the file of `KEY=value` credentials its tools read, such as `env-file = "~/.claude-projects/log.env"`. It is a path that starts with `/` or `~/`, outside the checkout and the config's folder, so that no git remote receives it. A tool that needs a key fails and names each one the file lacks. No failure message, prompt, log line or archived loop output holds a token from the file. rule-hook refuses a Read or a Grep of the file and a Bash command that names it or searches a folder holding it with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so a worker doesn't read it in passing; `rule-hook --help` says which calls it checks. A project without the setting has no credentials, and never reads another project's. `project-config env-file` prints the path. +It may set `notifier = "mattermost"` or `"slack"` too, the service that carries loop-claude's DMs; it needs `env-file`, which holds the notifier's keys, and `project-config notifier` prints it. A project that names none gets no DMs. + A project's config may set four more things, each optional, as `project-config --help` describes. `language` names the language its owners write in, where that isn't English: the worker writes the project's prose in it, and the prose reviewer judges the prose in it. `commit-title`, `pull-request-title` and `branch` are templates for a project that titles and names these in another way than `CLAUDE.md` → "Git, commits, and PRs" says. `chunk-preflight` names the branch and the worktree by the `branch` template. On a branch that fits it, rule-hook refuses a commit, and `chunk-pr` a pull request, whose title doesn't fit its template; on any other branch, such as a release review's, a title is the summary alone. A tool that reads a commit title, such as a round's `Answer round :`, reads the template's `{summary}`: it tries `commit-title`, then `pull-request-title`, since a squash merge titles the commit as the pull request, then takes the title whole. While a project's config holds a fault, rule-hook refuses every commit there, and the tools that read its titles fail naming the fault. A legacy project with no container setup sets `tooling-on-host = true`, so the loop runs its language runtime, package manager, tests and task runner directly on the host. One whose code the comprehension panel scores low may lower `readability-floor` from 7.0: under it, the ranking weighs code health 4 times as much, and a scoring run asks for a floor item. @@ -162,7 +164,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `judge-replay ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay. - `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 and setup; 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. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections. - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. -- `mattermost-dm []` sends a message, or else stdin, from the Mattermost bot to the human; the project's `env-file` 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. +- `notify []` sends a message, or else stdin, from the bot of the project's `notifier`, Mattermost or Slack, to the human; the project's `env-file` holds the bot's token and the human, and `notify --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. - `project-config []` prints the paths a project's config sets, or the one asked for, and fails naming each setting the config leaves out; Install → "Set up a project" shows a config. @@ -193,14 +195,14 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, both replay tools and `reviewer-merge-trials`' driver use it. - `loop_state/` holds where loop-claude keeps its files (`paths.py`), which `rung_replay` reads too. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, 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`. +- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`; `mattermost_dm/` and `slack_dm/` are its two backends. - `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read. - `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, and `fakes.py` a plan in memory. - `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. - `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use. - `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py` and `rule_hook`. - `repo_checks/` tests the repo itself. -- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm` and `plan_store`. +- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm`, `slack_dm` and `plan_store`. - `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format. - `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls. - `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths. diff --git a/bin/loop_claude/direct_message.py b/bin/loop_claude/direct_message.py index 09c73959..86cf10cf 100644 --- a/bin/loop_claude/direct_message.py +++ b/bin/loop_claude/direct_message.py @@ -4,4 +4,4 @@ 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) + say(f"could not DM you: {failed.reason}", effects) diff --git a/bin/loop_claude/loop/usage.py b/bin/loop_claude/loop/usage.py index 1ca02464..5c30bf58 100644 --- a/bin/loop_claude/loop/usage.py +++ b/bin/loop_claude/loop/usage.py @@ -34,8 +34,8 @@ loop-claude prints the question on its terminal, where the human answers it: - Enter alone: stops the loop. A release ready to cut opens that session on the terminal at once, since only the human may cut it. While claude is open, Ctrl-C reaches it alone, and the loop goes on. -Where the project's config sets env-file, 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 +Where the project's config sets notifier, loop-claude also sends the human each question, each +release ready to cut and each stop as a DM, as bin/notify 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. As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 38a375b1..baeaa7a1 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -741,17 +741,17 @@ class Interrupt(unittest.TestCase): self.assertEqual(run.code, 2) self.assertEqual(len(checkout.archived()), 2) - def test_sends_the_dm_through_the_env_file_the_config_names_and_no_credential_reaches_a_prompt_a_line_printed_or_a_file_written(self): + def test_sends_the_dm_through_the_notifier_and_env_file_the_config_names_and_no_credential_reaches_a_prompt_a_line_printed_or_a_file_written(self): checkout = Checkout(self) token = "tok-3f9a1c7e-sentinel" env_file = checkout.home / ".claude-projects" / "proj.env" env_file.write_text(f"MATTERMOST_URL=https://127.0.0.1:1\nMATTERMOST_TOKEN={token}\nMATTERMOST_RECIPIENT=lilleman\n") env_file.chmod(0o600) with (checkout.home / ".claude-projects" / "proj" / "config.toml").open("a") as config: - config.write('env-file = "~/.claude-projects/proj.env"\n') + config.write('env-file = "~/.claude-projects/proj.env"\nnotifier = "mattermost"\n') run = checkout.run([worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) - self.assertIn("could not DM you on Mattermost: cannot reach https://127.0.0.1:1", run.stderr) + self.assertIn("could not DM you: cannot reach https://127.0.0.1:1", run.stderr) held = [run.raw_stdout, run.raw_stderr, json.dumps(run.calls), json.dumps(run.starts)] held += [file.read_text(errors="replace") for file in checkout.home.rglob("*") if file.is_file() and file != env_file and not file.is_symlink()] self.assertGreater(len(held), 8, "the walk reached the archive, the state and the transcripts") diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 04a78edb..85153c11 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -763,7 +763,7 @@ class Interrupts(unittest.TestCase): 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")) + self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n{STAMP} could not DM you: 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. "]) @@ -1893,7 +1893,7 @@ class StopDms(unittest.TestCase): 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")) + self.assertTrue(self.run_main([main.RELOAD_FLAG, "3"], fake)[1].endswith(f"Handed: 3\n{STAMP} could not DM you: 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)): diff --git a/bin/loop_effects/effects.py b/bin/loop_effects/effects.py index e18f66ac..1eb8b1a3 100644 --- a/bin/loop_effects/effects.py +++ b/bin/loop_effects/effects.py @@ -12,10 +12,10 @@ import termios import time import typing -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 +from notifier.notify import notify # Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop. PYTHON_TIMEOUT = 600 @@ -35,7 +35,7 @@ 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, for the project whose checkout holds the current directory; a Failure where it could not. + # Sends the human a direct message through the notifier the project's config names, as `notify` does, for the project whose checkout holds the current directory; a Failure where it could not. dm: typing.Callable[[str], Failure | None] execv: typing.Callable[[str, list[str]], None] git: git_repo.Git @@ -69,7 +69,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, None, pathlib.Path.home(), http_json), + dm=lambda text: notify(text, None, pathlib.Path.home()), execv=os.execv, git=git_repo.git, input=input, diff --git a/bin/mattermost-dm b/bin/mattermost-dm deleted file mode 100755 index cd814c9c..00000000 --- a/bin/mattermost-dm +++ /dev/null @@ -1,9 +0,0 @@ -#!/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.config_of(None, pathlib.Path.home()), dm.http_json, sys.stderr)) diff --git a/bin/mattermost_dm/dm.py b/bin/mattermost_dm/dm.py index f3ac085f..54d7fd00 100644 --- a/bin/mattermost_dm/dm.py +++ b/bin/mattermost_dm/dm.py @@ -1,21 +1,17 @@ -"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4.""" +"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4. `notifier` picks it where a project's config names `mattermost`.""" import dataclasses import pathlib -import typing import urllib.parse from failure import Failure +from rest_client.json_request import Http from rest_client import json_request -from project_config.main import located from rest_client.env_file import read_env 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] - @dataclasses.dataclass(frozen=True) class Config: @@ -67,23 +63,3 @@ def error_message(answer: object) -> str: message = answer.get("message") if isinstance(answer, dict) else None return message if isinstance(message, str) else "" - -def dm(text: str, directory: str | None, home: pathlib.Path, http: Http) -> Failure | None: - """Sends text to the recipient that the project's env file names. The project is the one whose checkout holds directory, and its config names the file. - - The DM is skipped where the config sets no env-file, since the project hasn't asked for DMs. It is skipped too where no config can be read: loop-claude has stopped with that reason, and without a config there is no file to read the recipient from.""" - project = located(directory, home) - if isinstance(project, Failure) or project.env_file is None: - return None - config = read_config(project.env_file) - return config if isinstance(config, Failure) else send(config, text, http) - - -def config_of(directory: str | None, home: pathlib.Path) -> Config | Failure: - """The server, token and recipient in the env file that the config of the project holding directory names.""" - project = located(directory, home) - if isinstance(project, Failure): - return project - if project.env_file is None: - return Failure(f"{project.folder / 'config.toml'} sets no `env-file`; set it to the file that holds {', '.join(KEYS[:-1])} and {KEYS[-1]}") - return read_config(project.env_file) diff --git a/bin/mattermost_dm/main.py b/bin/mattermost_dm/main.py deleted file mode 100644 index fb0a2aa0..00000000 --- a/bin/mattermost_dm/main.py +++ /dev/null @@ -1,47 +0,0 @@ -"""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 a project's env file names. Run it -inside the project's checkout, or a worktree of it. The project's config, -~/.claude-projects//config.toml, names the env file in `env-file`, a path outside the checkout -and the config's folder, such as "~/.claude-projects/.env". The 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, a directory with no project config, -a config that sets no `env-file`, or an env file that is missing or unreadable, lacks a key, names a -server off https, or that others may read. None of these messages holds the token. -""" -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 index 0427cbac..62089bdc 100644 --- a/bin/mattermost_dm/test_mattermost_dm.py +++ b/bin/mattermost_dm/test_mattermost_dm.py @@ -1,7 +1,4 @@ -import contextlib -import io import pathlib -import subprocess import sys import tempfile import unittest @@ -9,18 +6,14 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from project_config.test_project_config import configured -from mattermost_dm import dm, main +from mattermost_dm import dm from failure import Failure -from test_env import isolated_env -from loop_effects.effects import system_effects -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, name: str = ".env") -> pathlib.Path: - path = pathlib.Path(folder) / name +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 @@ -120,116 +113,5 @@ class HttpJson(unittest.TestCase): self.assertEqual(dm.error_message(answer), message) -class Project(unittest.TestCase): - """A home with a git checkout that a config names; `folder` is the config's folder.""" - - def setUp(self) -> None: - made = tempfile.TemporaryDirectory() - self.addCleanup(made.cleanup) - self.home = pathlib.Path(made.name).resolve() - self.checkout = self.home / "code" / "proj" - self.checkout.mkdir(parents=True) - self.folder = configured(self, self.checkout, home=self.home) - - def name_env_file(self, text: str | None = None) -> pathlib.Path: - """Makes the config name ~/.claude-projects/proj.env, holding text where that is not None.""" - with (self.folder / "config.toml").open("a") as config: - config.write('env-file = "~/.claude-projects/proj.env"\n') - path = self.home / ".claude-projects" / "proj.env" - return path if text is None else env_file(str(path.parent), text, name=path.name) - - -class Dm(Project): - def test_sends_through_the_env_file_the_config_names(self): - self.name_env_file("MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n") - server = mattermost() - self.assertIsNone(dm.dm("Which one?", str(self.checkout), self.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_loop_claudes_dm_posts_the_text_for_the_project_holding_the_current_directory(self): - self.name_env_file("MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n") - server = mattermost() - with unittest.mock.patch("loop_effects.effects.http_json", server), contextlib.chdir(self.checkout): - self.assertIsNone(system_effects().dm("Which one?")) - 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_for_a_project_whose_config_names_no_env_file_even_where_the_old_shared_file_exists(self): - (self.home / ".claude").mkdir() - env_file(str(self.home / ".claude"), "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=other-projects-token\nMATTERMOST_RECIPIENT=lilleman\n", name=".env") - server = mattermost() - self.assertIsNone(dm.dm("Which one?", str(self.checkout), self.home, server)) - self.assertEqual(server.requests, []) - - def test_fails_naming_the_file_where_the_config_names_one_that_is_not_there(self): - path = self.name_env_file() - self.assertEqual(dm.dm("Which one?", str(self.checkout), self.home, mattermost()), Failure(f"{path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")) - - def test_fails_naming_the_mistake_where_the_env_file_is_there_but_wrong(self): - path = self.name_env_file("MATTERMOST_URL=https://chat.example\n") - self.assertEqual(dm.dm("Which one?", str(self.checkout), self.home, mattermost()), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")) - - def test_skips_the_dm_where_no_config_names_the_checkout_since_loop_claude_stops_on_that_itself(self): - other = self.home / "code" / "other" - other.mkdir() - subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env()) - server = mattermost() - self.assertIsNone(dm.dm("Which one?", str(other), self.home, server)) - self.assertEqual(server.requests, []) - - def test_config_of_names_the_setting_to_add_where_the_config_names_no_env_file(self): - failed = dm.config_of(str(self.checkout), self.home) - assert isinstance(failed, Failure), failed - self.assertEqual(failed.reason, f"{self.folder / 'config.toml'} sets no `env-file`; set it to the file that holds MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT") - - def test_config_of_reads_the_env_file_the_config_names(self): - self.name_env_file("MATTERMOST_URL=https://chat.example/\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n") - self.assertEqual(dm.config_of(str(self.checkout), self.home), CONFIG) - - def test_the_failure_for_an_unreachable_server_names_the_server_and_not_the_token(self): - self.name_env_file("MATTERMOST_URL=https://127.0.0.1:1\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n") - failed = dm.dm("Which one?", str(self.checkout), self.home, dm.http_json) - assert isinstance(failed, Failure), failed - self.assertIn("cannot reach https://127.0.0.1:1", failed.reason) - self.assertNotIn("secret-token", failed.reason) - - -class Main(Project): - 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_the_projects_config_names(self): - env = {**isolated_env(), "HOME": str(self.home)} - helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env, cwd=self.checkout) - self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0])) - path = self.name_env_file() - sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env, cwd=self.checkout) - self.assertEqual((sent.returncode, sent.stderr), (2, f"mattermost-dm: {path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT\n")) - - if __name__ == "__main__": unittest.main() diff --git a/bin/notifier/__init__.py b/bin/notifier/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/notifier/main.py b/bin/notifier/main.py new file mode 100644 index 00000000..8501a5ad --- /dev/null +++ b/bin/notifier/main.py @@ -0,0 +1,55 @@ +"""Send a message from the notifier's bot to the human. + +usage: notify [] + +Sends , or else stdin, through the notifier that a project's config names, from the bot to the +recipient that the project's env file names. Run it inside the project's checkout, or a worktree of it. +The project's config, ~/.claude-projects//config.toml, sets `notifier` to "mattermost" or "slack" +and `env-file` to a path outside the checkout and the config's folder, such as +"~/.claude-projects/.env". The env file holds the notifier's KEY=value lines, and only its owner +may read it, since it holds the bot's token. For mattermost: + + MATTERMOST_URL=https://chat.example + MATTERMOST_TOKEN= + MATTERMOST_RECIPIENT= + +For slack, a bot token with the `chat:write` scope, and the recipient's member ID, which Slack shows +under Profile → ⋮ → Copy member ID: + + SLACK_TOKEN= + SLACK_RECIPIENT= + +Exit 0 once the message is sent. +Exit 1, saying why, when the notifier cannot be reached or refuses the message. +Exit 2, saying why, on misuse: bad arguments, an empty message, a directory with no project config, +a config that sets no `notifier` or no `env-file`, or an env file that is missing or unreadable, lacks +a key, names a Mattermost server off https, or that others may read. None of these messages holds the +token. +""" +import typing + +from failure import Failure +from notifier.notify import Sender + +USAGE = "usage: notify []" + + +def main(argv: list[str], stdin: typing.TextIO, sender: typing.Callable[[], Sender | Failure], stderr: typing.TextIO) -> int: + if argv[:1] in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + if len(argv) > 1: + print(f"notify: 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("notify: the message is empty", file=stderr) + return 2 + found = sender() + if isinstance(found, Failure): + print(f"notify: {found.reason}", file=stderr) + return 2 + if failed := found(message): + print(f"notify: {failed.reason}", file=stderr) + return 1 + return 0 diff --git a/bin/notifier/notify.py b/bin/notifier/notify.py new file mode 100644 index 00000000..52347ab4 --- /dev/null +++ b/bin/notifier/notify.py @@ -0,0 +1,58 @@ +"""Sends a notice through the notifier that a project's config names.""" +import dataclasses +import pathlib +import typing + +from failure import Failure +from rest_client.json_request import Http +from project_config.main import located +import mattermost_dm.dm +from project_config.settings import NOTIFIER, NOTIFIERS, ProjectConfig +import slack_dm.dm + +# Sends one message, with the credentials already read. +Sender = typing.Callable[[str], Failure | None] + + +@dataclasses.dataclass(frozen=True) +class Backend: + """A notifier's three parts. `read_config` returns whatever `send` takes as its config.""" + read_config: typing.Callable[[pathlib.Path], typing.Any] + send: typing.Callable[[typing.Any, str, Http], Failure | None] + http: Http + keys: tuple[str, ...] + + +BACKENDS = { + "mattermost": Backend(mattermost_dm.dm.read_config, mattermost_dm.dm.send, mattermost_dm.dm.http_json, mattermost_dm.dm.KEYS), + "slack": Backend(slack_dm.dm.read_config, slack_dm.dm.send, slack_dm.dm.http_json, slack_dm.dm.KEYS), +} +assert tuple(BACKENDS) == NOTIFIERS + + +def sender_of(project: ProjectConfig, http: Http | None = None) -> Sender | Failure: + """A sender through the project's notifier, with the credentials in its env file read; http replaces the backend's own. A Failure where the project names no notifier or its env file cannot be used.""" + if project.notifier is None or project.env_file is None: + return Failure(f"{project.folder / 'config.toml'} sets no `{NOTIFIER}`; set it to one of {', '.join(NOTIFIERS)}, and `env-file` to the file that holds its keys: mattermost needs {', '.join(BACKENDS['mattermost'].keys)}, slack needs {', '.join(BACKENDS['slack'].keys)}") + backend = BACKENDS[project.notifier] + config = backend.read_config(project.env_file) + if isinstance(config, Failure): + return config + return lambda message: backend.send(config, message, http or backend.http) + + +def notify(text: str, directory: str | None, home: pathlib.Path, http: Http | None = None) -> Failure | None: + """Sends text through the notifier of the project whose checkout holds directory. + + It is skipped where the config names no notifier, since the project hasn't asked for notices. It is skipped too where no config can be read: loop-claude has stopped with that reason, and without a config there is no notifier to ask.""" + project = located(directory, home) + if isinstance(project, Failure) or project.notifier is None: + return None + sender = sender_of(project, http) + return sender if isinstance(sender, Failure) else sender(text) + + +def sender_in(directory: str | None, home: pathlib.Path) -> Sender | Failure: + """sender_of the project whose checkout holds directory.""" + project = located(directory, home) + return project if isinstance(project, Failure) else sender_of(project) diff --git a/bin/notifier/test_notifier.py b/bin/notifier/test_notifier.py new file mode 100644 index 00000000..b4f0e10b --- /dev/null +++ b/bin/notifier/test_notifier.py @@ -0,0 +1,146 @@ +import contextlib +import dataclasses +import io +import pathlib +import subprocess +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from project_config.test_project_config import configured +from failure import Failure +from test_env import isolated_env +from notifier import main, notify +from mattermost_dm.test_mattermost_dm import mattermost +from slack_dm.test_slack_dm import Slack +from loop_effects.effects import system_effects + +TOOL = pathlib.Path(__file__).resolve().parents[1] / "notify" +MATTERMOST_KEYS = "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n" +SLACK_KEYS = "SLACK_TOKEN=xoxb-secret\nSLACK_RECIPIENT=U0123ABCD\n" +MATTERMOST_POST = ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}) +SLACK_POST = ("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"channel": "U0123ABCD", "text": "Which one?"}) +MISSING_MATTERMOST = "does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT" + + +class Project(unittest.TestCase): + """A home with a git checkout that a config names; `folder` is the config's folder.""" + + def setUp(self) -> None: + made = tempfile.TemporaryDirectory() + self.addCleanup(made.cleanup) + self.home = pathlib.Path(made.name).resolve() + self.checkout = self.home / "code" / "proj" + self.checkout.mkdir(parents=True) + self.folder = configured(self, self.checkout, home=self.home) + + def name_notifier(self, notifier: str | None, keys: str | None = None) -> pathlib.Path: + """Makes the config name ~/.claude-projects/proj.env as its env file, and the notifier where there is one; the file holds keys where that is not None.""" + with (self.folder / "config.toml").open("a") as config: + config.write('env-file = "~/.claude-projects/proj.env"\n' + (f'notifier = "{notifier}"\n' if notifier else "")) + path = self.home / ".claude-projects" / "proj.env" + if keys is not None: + path.write_text(keys) + path.chmod(0o600) + return path + + +class Notify(Project): + def test_sends_through_mattermost_where_the_config_names_it(self): + self.name_notifier("mattermost", MATTERMOST_KEYS) + server = mattermost() + self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, server)) + self.assertEqual(server.requests[-1], MATTERMOST_POST) + + def test_sends_through_slack_where_the_config_names_it(self): + self.name_notifier("slack", SLACK_KEYS) + slack = Slack({"ok": True}) + self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, slack)) + self.assertEqual(slack.requests, [SLACK_POST]) + + def test_loop_claudes_dm_goes_through_the_notifier_for_the_project_holding_the_current_directory(self): + self.name_notifier("slack", SLACK_KEYS) + slack = Slack({"ok": True}) + with unittest.mock.patch.dict(notify.BACKENDS, {"slack": dataclasses.replace(notify.BACKENDS["slack"], http=slack)}), contextlib.chdir(self.checkout): + self.assertIsNone(system_effects().dm("Which one?")) + self.assertEqual(slack.requests, [SLACK_POST]) + + def test_skips_the_notice_for_a_project_that_names_no_notifier_even_where_its_env_file_holds_the_keys(self): + self.name_notifier(None, MATTERMOST_KEYS) + server = mattermost() + self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, server)) + self.assertEqual(server.requests, []) + + def test_skips_the_notice_where_no_config_names_the_checkout_since_loop_claude_stops_on_that_itself(self): + other = self.home / "code" / "other" + other.mkdir() + subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env()) + server = mattermost() + self.assertIsNone(notify.notify("Which one?", str(other), self.home, server)) + self.assertEqual(server.requests, []) + + def test_fails_naming_the_file_or_the_key_where_the_env_file_is_missing_or_wrong(self): + path = self.name_notifier("slack") + self.assertEqual(notify.notify("hi", str(self.checkout), self.home, Slack({"ok": True})), Failure(f"{path} does not exist; it needs SLACK_TOKEN and SLACK_RECIPIENT")) + path.write_text("SLACK_TOKEN=xoxb-secret\n") + path.chmod(0o600) + self.assertEqual(notify.notify("hi", str(self.checkout), self.home, Slack({"ok": True})), Failure(f"{path} lacks SLACK_RECIPIENT")) + + def test_the_failure_for_an_unreachable_server_names_the_server_and_not_the_token(self): + self.name_notifier("mattermost", MATTERMOST_KEYS.replace("https://chat.example", "https://127.0.0.1:1")) + failed = notify.notify("Which one?", str(self.checkout), self.home) + assert isinstance(failed, Failure), failed + self.assertIn("cannot reach https://127.0.0.1:1", failed.reason) + self.assertNotIn("secret-token", failed.reason) + + def test_sender_in_names_the_settings_to_add_where_the_config_names_no_notifier(self): + failed = notify.sender_in(str(self.checkout), self.home) + assert isinstance(failed, Failure), failed + self.assertEqual(failed.reason, f"{self.folder / 'config.toml'} sets no `notifier`; set it to one of mattermost, slack, and `env-file` to the file that holds its keys: mattermost needs MATTERMOST_URL, MATTERMOST_TOKEN, MATTERMOST_RECIPIENT, slack needs SLACK_TOKEN, SLACK_RECIPIENT") + + +class Main(Project): + def run_main(self, argv: list[str], stdin: str = "", sender: object = None) -> tuple[int, str]: + stderr = io.StringIO() + ready = sender or (lambda message: None) + code = main.main(argv, io.StringIO(stdin), lambda: ready, 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): + sent: list[str] = [] + self.assertEqual(self.run_main(argv, stdin, lambda message: sent.append(message)), (0, "")) + self.assertEqual(sent, ["Which one?"]) + + def test_exits_2_on_misuse_naming_it(self): + for argv, stdin, said in ( + ([], " \n", "notify: the message is empty\n"), + (["a", "b"], "", f"notify: takes one message, or none to read stdin; got 2 arguments\n{main.USAGE}\n"), + ): + with self.subTest(argv=argv, stdin=stdin): + self.assertEqual(self.run_main(argv, stdin), (2, said)) + + def test_exits_2_naming_the_config_fault_where_there_is_no_sender(self): + stderr = io.StringIO() + self.assertEqual(main.main(["hi"], io.StringIO(), lambda: Failure("/h/proj.env does not exist"), stderr), 2) # type: ignore[arg-type] + self.assertEqual(stderr.getvalue(), "notify: /h/proj.env does not exist\n") + + def test_exits_1_naming_why_the_send_failed(self): + failed = Failure("POST /api/chat.postMessage refused the message: invalid_auth") + self.assertEqual(self.run_main(["hi"], sender=lambda message: failed), (1, f"notify: {failed.reason}\n")) + + def test_the_launcher_prints_help_and_reads_the_env_file_the_projects_config_names(self): + env = {**isolated_env(), "HOME": str(self.home)} + helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env, cwd=self.checkout) + self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0])) + path = self.name_notifier("mattermost") + sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env, cwd=self.checkout) + self.assertEqual((sent.returncode, sent.stderr), (2, f"notify: {path} {MISSING_MATTERMOST}\n")) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/notify b/bin/notify new file mode 100755 index 00000000..325a9169 --- /dev/null +++ b/bin/notify @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from notifier import main, notify + +sys.exit(main.main(sys.argv[1:], sys.stdin, lambda: notify.sender_in(None, pathlib.Path.home()), sys.stderr)) diff --git a/bin/project_config/main.py b/bin/project_config/main.py index df446863..6ab39031 100644 --- a/bin/project_config/main.py +++ b/bin/project_config/main.py @@ -36,6 +36,11 @@ a path that starts with / or ~/ and lies outside the checkout and the config's f "~/.claude-projects/acme-billing.env". Where it is left out, the project has no credentials file, and a tool that needs one fails naming the setting. It is printed with the others only where it is set. +`notifier` is an optional setting, "mattermost" or "slack": the service that carries loop-claude's notices +and `notify`'s messages to the human, with the credentials in `env-file`, which it then requires; `notify +--help` names the keys. Left out, the project gets no notices. It is printed with the others only where +it is set. + `wait-for-approval` is an optional setting, true or false: whether `chunk-pr merge` waits for a human's approval of the pull request, as its branch protection requires on GitHub, before it merges. Left out, it is false. `project-config wait-for-approval` prints true or false; the full listing shows the setting only where @@ -84,14 +89,14 @@ The chunk for the issue ABC-123 is then on the branch ABC-123, in the worktree < and its commits and pull request are titled "ABC-123 - …". Exit 1, naming each fault on stderr, where no config names the checkout, or its config leaves out a -setting, names an unknown one, misspells a path, a language or a template, sets `wait-for-approval` or +setting, names an unknown one, misspells a path, a language or a template, names a notifier that is neither mattermost nor slack or sets one without `env-file`, sets `wait-for-approval` or `tooling-on-host` to anything but true or false, or sets `readability-floor` to anything but a number -from 1 to 10, and where `env-file` is asked for and not set. No path setting has a default. +from 1 to 10, and where `env-file` or `notifier` is asked for and not set. No path setting has a default. """ import pathlib import sys -from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, load, OPTIONAL, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL +from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, load, NOTIFIER, OPTIONAL, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL from failure import Failure from git_cli.git_repo import git, Git from project_config import templates @@ -118,9 +123,9 @@ def main(argv: list[str]) -> int: if argv and argv[0] in config.texts: print(config.texts[argv[0]]) return 0 - paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {})} + paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {})} if argv and argv[0] not in paths: - print(f"{config.folder / CONFIG} sets no `{ENV_FILE}`", file=sys.stderr) + print(f"{config.folder / CONFIG} sets no `{argv[0]}`", file=sys.stderr) return 1 defaults = ProjectConfig(config.key, config.folder, config.top, {}).texts listed = [f"{name}: {path}" for name, path in paths.items()] + [f"{name}: true" for name, on in switches.items() if on] + ([f"{READABILITY_FLOOR}: {config.readability_floor}"] if config.readability_floor != DEFAULT_FLOOR else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]] diff --git a/bin/project_config/settings.py b/bin/project_config/settings.py index 42d3d365..15e8b01e 100644 --- a/bin/project_config/settings.py +++ b/bin/project_config/settings.py @@ -19,6 +19,9 @@ SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehensio SPELLING = '"checkout:" for a path in the checkout, "folder:" for one in the config\'s folder, or a path that starts with / or ~/' # A path setting a project may leave out: the file of KEY=value credentials its tools read. It has no default either: a project without it asks for no credentials, and never reads another project's. ENV_FILE = "env-file" +# An optional setting: the service that carries the loop's notices to the human, one of NOTIFIERS. A project that names none gets no notices, so a client's env file for Jira credentials is never read for a chat token. It needs `env-file`, which holds the notifier's credentials. +NOTIFIER = "notifier" +NOTIFIERS = ("mattermost", "slack") # An optional boolean setting: whether `chunk-pr merge` waits for a human's approval of the pull request. False where left out. WAIT_FOR_APPROVAL = "wait-for-approval" # An optional boolean setting: whether the loop may run the project's language runtime, package manager, tests and task runner on the host, for a project with no container setup. False where left out. @@ -32,7 +35,7 @@ LANGUAGE = "language" COMMIT_TITLE = "commit-title" PULL_REQUEST_TITLE = "pull-request-title" BRANCH = "branch" -OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, WAIT_FOR_APPROVAL) +OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, WAIT_FOR_APPROVAL) # What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it. JIRA = "jira:" EPIC_SPELLINGS = { @@ -79,6 +82,8 @@ class ProjectConfig: epic: Epic | None = None # The epic whose description holds the goals and audience, where the config's `goals-and-audience` names one. goals_epic: Epic | None = None + # The config's `notifier`, or None where it names none. + notifier: str | None = None @property def plan_file(self) -> pathlib.Path | None: @@ -135,6 +140,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo epics = {name: epic_of(values.get(name)) for name in EPIC_SPELLINGS} env_file = anywhere(values.get(ENV_FILE), home) misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent)) + notifier = str(values[NOTIFIER]) if NOTIFIER in values else None waits = values.get(WAIT_FOR_APPROVAL, False) on_host = values.get(TOOLING_ON_HOST, False) floor = floor_of(values[READABILITY_FLOOR]) if READABILITY_FLOOR in values else DEFAULT_FLOOR @@ -148,6 +154,8 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo # rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira mustn't hold up. *(["`goals-and-audience` names a Jira epic, so `plan` must name one too"] if epics["goals-and-audience"] and not epics["plan"] else []), *([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []), + *([f"`{NOTIFIER}` is {values[NOTIFIER]!r}, not {' or '.join(NOTIFIERS)}"] if NOTIFIER in values and values[NOTIFIER] not in NOTIFIERS else []), + *([f"`{NOTIFIER}` names a notifier, so `{ENV_FILE}` must name the file that holds its credentials"] if NOTIFIER in values and ENV_FILE not in values else []), *(f"`{name}` is {value!r}, not true or false" for name, value in ((WAIT_FOR_APPROVAL, waits), (TOOLING_ON_HOST, on_host)) if not isinstance(value, bool)), *([f"`{READABILITY_FLOOR}` is {values[READABILITY_FLOOR]!r}, not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`"] if floor is None else []), *(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))), @@ -156,7 +164,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.") # faults names a floor the config misspells. assert floor is not None - return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"]) + return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier) def epic_of(value: object) -> Epic | None: diff --git a/bin/project_config/test_project_config.py b/bin/project_config/test_project_config.py index e924381b..5dbbf102 100644 --- a/bin/project_config/test_project_config.py +++ b/bin/project_config/test_project_config.py @@ -9,7 +9,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from project_config.settings import env_files, Epic, held, load, OUTSIDE, ProjectConfig, SETTINGS, Unnamed +from project_config.settings import env_files, Epic, held, load, NOTIFIERS, OUTSIDE, ProjectConfig, SETTINGS, Unnamed from failure import Failure from test_env import isolated_env from project_config.main import title_templates @@ -233,6 +233,24 @@ class LoadTest(ConfigCase): assert isinstance(named, ProjectConfig), named self.assertEqual(named.env_file, self.home / ".claude-projects" / "acme.env") + def test_the_notifier_is_optional_and_names_mattermost_or_slack_beside_an_env_file(self) -> None: + self.write("acme", CLIENT) + left_out = load(self.checkout, self.checkout, self.home) + assert isinstance(left_out, ProjectConfig), left_out + self.assertIsNone(left_out.notifier, "a project that names none has asked for no notices") + for index, name in enumerate(NOTIFIERS): + with self.subTest(name): + self.write(f"acme-{index}", CLIENT.replace("acme-billing", f"acme-{index}") + f'env-file = "~/acme.env"\nnotifier = "{name}"\n') + named = load(self.home / "code" / f"acme-{index}", self.home / "code" / f"acme-{index}", self.home) + assert isinstance(named, ProjectConfig), named + self.assertEqual(named.notifier, name) + + def test_a_notifier_that_is_unknown_or_has_no_env_file_fails_naming_it(self) -> None: + self.write("acme", CLIENT + 'env-file = "~/acme.env"\nnotifier = "teams"\n') + self.assertIn("`notifier` is 'teams', not mattermost or slack", self.failure()) + (self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'notifier = "slack"\n') + self.assertIn("`notifier` names a notifier, so `env-file` must name the file that holds its credentials", self.failure()) + def test_an_env_file_in_the_checkout_or_the_configs_folder_or_spelt_loosely_fails_naming_it(self) -> None: cases = { "a checkout: path": lambda home: '"checkout:.env"', @@ -355,7 +373,7 @@ class LoadTest(ConfigCase): def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None: folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n') - self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, language, pull-request-title, readability-floor, tooling-on-host and wait-for-approval.") + self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, language, notifier, pull-request-title, readability-floor, tooling-on-host and wait-for-approval.") def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None: self.write("acme", CLIENT) @@ -465,6 +483,15 @@ class ToolTest(ConfigCase): self.assertEqual((one.returncode, one.stdout), (0, f"{self.home}/.claude-projects/acme.env\n")) self.assertEqual(self.run_tool().stdout.splitlines()[-1], f"env-file: {self.home}/.claude-projects/acme.env") + def test_prints_the_notifier_where_the_config_sets_one_and_fails_asking_for_it_where_it_does_not(self) -> None: + folder = self.write("acme", CLIENT) + unset = self.run_tool("notifier") + self.assertEqual((unset.returncode, unset.stdout, unset.stderr), (1, "", f"{folder / 'config.toml'} sets no `notifier`\n")) + self.assertNotIn("notifier", self.run_tool().stdout) + (folder / "config.toml").write_text(CLIENT + 'env-file = "~/.claude-projects/acme.env"\nnotifier = "slack"\n') + self.assertEqual(self.run_tool("notifier").stdout, "slack\n") + self.assertEqual(self.run_tool().stdout.splitlines()[-1], "notifier: slack") + def test_prints_true_or_false_for_wait_for_approval_and_lists_it_only_where_the_config_sets_it(self) -> None: folder = self.write("acme", CLIENT) left_out = self.run_tool("wait-for-approval") diff --git a/bin/rest_client/json_request.py b/bin/rest_client/json_request.py index e6c517e3..16394dc1 100644 --- a/bin/rest_client/json_request.py +++ b/bin/rest_client/json_request.py @@ -19,6 +19,9 @@ class NoRedirect(urllib.request.HTTPRedirectHandler): return None +# Sends a request: method, url, token and the body as JSON where there is one. It answers the JSON, or a Failure saying why there is none. +Http = typing.Callable[[str, str, str, object], object] + OPENER = urllib.request.build_opener(NoRedirect) diff --git a/bin/slack_dm/__init__.py b/bin/slack_dm/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/slack_dm/dm.py b/bin/slack_dm/dm.py new file mode 100644 index 00000000..b6c7a05f --- /dev/null +++ b/bin/slack_dm/dm.py @@ -0,0 +1,51 @@ +"""Sends a direct message from a Slack app's bot to one user, through Slack's Web API. `notifier` picks it where a project's config names `slack`.""" +import dataclasses +import pathlib + +from failure import Failure +from rest_client.json_request import Http +from rest_client import json_request +from rest_client.env_file import read_env + +KEYS = ("SLACK_TOKEN", "SLACK_RECIPIENT") +# Slack's one host for every workspace. +API = "https://slack.com/api" +# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly. +TIMEOUT = 10 + + +@dataclasses.dataclass(frozen=True) +class Config: + token: str + recipient: str + + +def read_config(path: pathlib.Path) -> Config | Failure: + """The bot token and recipient that path's KEY=value lines hold.""" + values = read_env(path, KEYS, "the bot's token") + if isinstance(values, Failure): + return values + return Config(*(values[key] for key in KEYS)) + + +def send(config: Config, message: str, http: Http) -> Failure | None: + """Posts message to the recipient's member ID, which Slack opens as a DM from the app's bot; the bot needs the `chat:write` scope.""" + answer = http("POST", f"{API}/chat.postMessage", config.token, {"channel": config.recipient, "text": message}) + if isinstance(answer, Failure): + return answer + if isinstance(answer, dict) and answer.get("ok") is True: + return None + # Slack answers 200 with `ok` false and a short code, such as `channel_not_found` or `invalid_auth`. + error = answer.get("error") if isinstance(answer, dict) else None + return Failure(f"POST /api/chat.postMessage refused the message: {error if isinstance(error, str) and error else 'no error code'}") + + +def http_json(method: str, url: str, token: str, body: object) -> object: + """The JSON that url answers to the bot's request, or a Failure saying why there is none.""" + return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message) + + +def error_message(answer: object) -> str: + """Slack's error code in the JSON of an error answer; empty where it holds none.""" + error = answer.get("error") if isinstance(answer, dict) else None + return error if isinstance(error, str) else "" diff --git a/bin/slack_dm/test_slack_dm.py b/bin/slack_dm/test_slack_dm.py new file mode 100644 index 00000000..8d941b1e --- /dev/null +++ b/bin/slack_dm/test_slack_dm.py @@ -0,0 +1,78 @@ +import pathlib +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from slack_dm import dm +from failure import Failure + +CONFIG = dm.Config("xoxb-secret", "U0123ABCD") + + +class Slack: + """Slack's answer to every request, recording each one it gets.""" + + def __init__(self, answer: object) -> None: + self.answer = answer + 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.answer + + +def env_file(folder: str, text: str, mode: int = 0o600) -> pathlib.Path: + path = pathlib.Path(folder) / "slack.env" + path.write_text(text) + path.chmod(mode) + return path + + +class ReadConfig(unittest.TestCase): + def test_reads_the_token_and_the_recipient_skipping_comments_and_quotes(self): + with tempfile.TemporaryDirectory() as folder: + path = env_file(folder, '# acme\nSLACK_TOKEN="xoxb-secret"\nSLACK_RECIPIENT = U0123ABCD\nOTHER=1\n') + self.assertEqual(dm.read_config(path), CONFIG) + + def test_names_each_key_missing_and_refuses_a_file_others_can_read(self): + with tempfile.TemporaryDirectory() as folder: + path = env_file(folder, "SLACK_TOKEN=xoxb-secret\n") + self.assertEqual(dm.read_config(path), Failure(f"{path} lacks SLACK_RECIPIENT")) + path = env_file(folder, "SLACK_TOKEN=t\nSLACK_RECIPIENT=r\n", 0o640) + 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}")) + + +class Send(unittest.TestCase): + def test_posts_the_message_to_the_recipients_member_id_with_the_token(self): + slack = Slack({"ok": True, "ts": "1.2"}) + self.assertIsNone(dm.send(CONFIG, "Which one?", slack)) + self.assertEqual(slack.requests, [("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"channel": "U0123ABCD", "text": "Which one?"})]) + + def test_fails_naming_slacks_error_code_where_slack_answers_ok_false(self): + self.assertEqual(dm.send(CONFIG, "hi", Slack({"ok": False, "error": "invalid_auth"})), Failure("POST /api/chat.postMessage refused the message: invalid_auth")) + + def test_fails_on_an_answer_that_says_neither_ok_nor_an_error(self): + for answer in ({}, ["ok"], {"ok": "true"}, {"ok": False, "error": 7}): + with self.subTest(answer=answer): + self.assertEqual(dm.send(CONFIG, "hi", Slack(answer)), Failure("POST /api/chat.postMessage refused the message: no error code")) + + def test_passes_on_the_failure_of_the_request_itself(self): + failed = Failure("cannot reach https://slack.com: timed out") + self.assertEqual(dm.send(CONFIG, "hi", Slack(failed)), failed) + + +class HttpJson(unittest.TestCase): + def test_sends_the_token_as_a_bearer_and_reads_slacks_code_from_an_error(self): + with unittest.mock.patch.object(dm.json_request, "http_json", return_value={"ok": True}) as sent: + self.assertEqual(dm.http_json("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"text": "hi"}), {"ok": True}) + sent.assert_called_once_with("POST", "https://slack.com/api/chat.postMessage", "Bearer xoxb-secret", {"text": "hi"}, dm.TIMEOUT, dm.error_message) + for answer, code in (({"error": "ratelimited"}, "ratelimited"), ({"error": 7}, ""), ({}, ""), (["error"], "")): + with self.subTest(answer=answer): + self.assertEqual(dm.error_message(answer), code) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 74cec0b7..f5b396e7 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -2118,3 +2118,20 @@ Read most (opens and searches): - `skills/larv-review/SKILL.md` 2 - `bin/adf_codec/convert.py` 1 - `bin/loop_claude/loop/usage.py` 1 + +## Reading cost, chunk 566d96364f2d, finished 2026-11-14T21:20:32Z + +287363 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/project_config/test_project_config.py` 9 +- `docs/decisions.md` 9 +- `bin/larv_review/test_larv_review.py` 8 +- `bin/release_plan/ranking.py` 6 +- `bin/release_plan/test_ranking.py` 6 +- `bin/larv_review/main.py` 5 +- `bin/plan_store/stores.py` 5 +- `bin/project_config/main.py` 5 +- `bin/project_config/settings.py` 4 +- `bin/release_plan/goals_file.py` 4