Answer architecture round 1: 4 🔴, 5 🟡 (0 misread); one-way plan packages with a plan core and an Atlassian client, one parse and print of an item's cells, a pure chunk-start decision, a settings table, one plan read and one standing per pick, one config load in chunk-pr, notifier backends in notifier, and the bin regroup filed as item 392

This commit is contained in:
2026-11-16 14:47:46 +01:00
parent 3f7d85c48e
commit f58250d0ce
103 changed files with 1299 additions and 1044 deletions
+65
View File
@@ -0,0 +1,65 @@
"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4. The `notifier` setting `mattermost` picks it."""
import dataclasses
import pathlib
import urllib.parse
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 = ("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
@dataclasses.dataclass(frozen=True)
class Config:
url: str
token: str
recipient: str
def read_config(path: pathlib.Path) -> Config | Failure:
"""The server, 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
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 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 to the bot's request, None where the answer has no body, 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:
"""Mattermost's message in the JSON of an error answer; empty where it holds none."""
message = answer.get("message") if isinstance(answer, dict) else None
return message if isinstance(message, str) else ""
+3 -4
View File
@@ -6,9 +6,8 @@ import typing
from failure import Failure
from rest_client.json_request import Http
from project_config.main import located
import mattermost_dm.dm
from notifier import mattermost, slack
from project_config.settings import Notifier, NOTIFIER, NOTIFIERS, ProjectConfig
import slack_dm.dm
# Sends one message, with the credentials already read.
Sender = typing.Callable[[str], Failure | None]
@@ -25,8 +24,8 @@ class Backend[C]:
# The one place each notifier is wired to the network: a caller that tests a send passes a table with its own `http`.
BACKENDS: dict[Notifier, Backend[typing.Any]] = {
"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),
"mattermost": Backend(mattermost.read_config, mattermost.send, mattermost.http_json, mattermost.KEYS),
"slack": Backend(slack.read_config, slack.send, slack.http_json, slack.KEYS),
}
assert tuple(BACKENDS) == NOTIFIERS
+52
View File
@@ -0,0 +1,52 @@
"""Sends a direct message from a Slack app's bot to one user, through Slack's Web API. The `notifier` setting `slack` picks it."""
import dataclasses
import html
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. Slack reads `&`, `<` and `>` as control characters, so they are escaped as its docs ask."""
answer = http("POST", f"{API}/chat.postMessage", config.token, {"channel": config.recipient, "text": html.escape(message, quote=False)})
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, None where the answer has no body, 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 ""
+117
View File
@@ -0,0 +1,117 @@
import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from notifier import mattermost as dm
from failure import Failure
CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman")
def env_file(folder: str, text: str, mode: int = 0o600) -> pathlib.Path:
path = pathlib.Path(folder) / ".env"
path.write_text(text)
path.chmod(mode)
return path
class FakeServer:
"""Mattermost's answers by method and path, recording each request it gets."""
def __init__(self, answers: dict[tuple[str, str], object]) -> None:
self.answers = answers
self.requests: list[tuple[str, str, str, object]] = []
def __call__(self, method: str, url: str, token: str, body: object) -> object:
self.requests.append((method, url, token, body))
return self.answers[(method, url.removeprefix("https://chat.example"))]
def mattermost() -> FakeServer:
return FakeServer({
("GET", "/api/v4/users/me"): {"id": "bot-id"},
("GET", "/api/v4/users/username/lilleman"): {"id": "human-id"},
("POST", "/api/v4/channels/direct"): {"id": "channel-id"},
("POST", "/api/v4/posts"): {"id": "post-id"},
})
class ReadConfig(unittest.TestCase):
def test_reads_the_server_the_token_and_the_recipient_skipping_blanks_comments_and_quotes(self):
with tempfile.TemporaryDirectory() as folder:
path = env_file(folder, '# larvit-bot\n\nMATTERMOST_URL = https://chat.example/\nMATTERMOST_TOKEN="secret-token"\nMATTERMOST_RECIPIENT=\'lilleman\'\nOTHER=1\n')
self.assertEqual(dm.read_config(path), dm.Config("https://chat.example", "secret-token", "lilleman"))
def test_names_the_file_and_the_keys_it_needs_where_the_file_is_missing(self):
with tempfile.TemporaryDirectory() as folder:
path = pathlib.Path(folder) / ".env"
self.assertEqual(dm.read_config(path), Failure(f"{path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
def test_names_each_key_missing_or_empty(self):
with tempfile.TemporaryDirectory() as folder:
path = env_file(folder, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=\n")
self.assertEqual(dm.read_config(path), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
def test_refuses_a_file_that_group_or_others_can_read_since_it_holds_the_token(self):
with tempfile.TemporaryDirectory() as folder:
for mode in (0o640, 0o604):
with self.subTest(mode=oct(mode)):
path = env_file(folder, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=t\nMATTERMOST_RECIPIENT=r\n", mode)
self.assertEqual(dm.read_config(path), Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}"))
def test_refuses_a_server_off_https_which_would_send_the_token_in_the_clear(self):
with tempfile.TemporaryDirectory() as folder:
path = env_file(folder, "MATTERMOST_URL=http://chat.example\nMATTERMOST_TOKEN=t\nMATTERMOST_RECIPIENT=r\n")
self.assertEqual(dm.read_config(path), Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear"))
class Send(unittest.TestCase):
def test_finds_both_users_opens_their_direct_channel_and_posts_the_message_there(self):
server = mattermost()
self.assertIsNone(dm.send(CONFIG, "Which one?", server))
self.assertEqual(server.requests, [
("GET", "https://chat.example/api/v4/users/me", "secret-token", None),
("GET", "https://chat.example/api/v4/users/username/lilleman", "secret-token", None),
("POST", "https://chat.example/api/v4/channels/direct", "secret-token", ["bot-id", "human-id"]),
("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}),
])
def test_stops_at_the_first_failed_request(self):
server = mattermost()
server.answers[("GET", "/api/v4/users/username/lilleman")] = Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username.")
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username."))
self.assertEqual(len(server.requests), 2)
def test_fails_on_an_answer_without_an_id_or_one_that_is_not_an_object(self):
for answer in ({"status": "OK"}, ["channel-id"], {"id": ""}):
with self.subTest(answer=answer):
server = mattermost()
server.answers[("POST", "/api/v4/channels/direct")] = answer
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/channels/direct answered without an id"))
self.assertEqual(len(server.requests), 3)
def test_fails_where_the_post_itself_fails(self):
server = mattermost()
server.answers[("POST", "/api/v4/posts")] = Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions.")
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions."))
class HttpJson(unittest.TestCase):
def test_sends_the_token_as_a_bearer_and_reads_mattermosts_message_from_an_error(self):
with unittest.mock.patch.object(dm.json_request, "http_json", return_value={"id": "post-id"}) as sent:
self.assertEqual(dm.http_json("POST", "https://chat.example/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"})
sent.assert_called_once_with("POST", "https://chat.example/api/v4/posts", "Bearer secret-token", {"message": "hi"}, dm.TIMEOUT, dm.error_message)
self.assertEqual(dm.TIMEOUT, 10)
def test_reads_mattermosts_message_from_an_error_answer(self):
for answer, message in (({"message": "Invalid or expired session."}, "Invalid or expired session."), ({"message": 7}, ""), ({}, ""), (["message"], "")):
with self.subTest(answer=answer):
self.assertEqual(dm.error_message(answer), message)
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -16,9 +16,9 @@ from rest_client.json_request import Http
from test_env import isolated_env
from project_config.main import located
from notifier import main, notify
from mattermost_dm.test_mattermost_dm import mattermost
from notifier.test_mattermost import mattermost
from project_config.settings import Notifier
from slack_dm.test_slack_dm import Slack
from notifier.test_slack import Slack
from loop_effects.effects import system_effects
TOOL = pathlib.Path(__file__).resolve().parents[1] / "notify"
+88
View File
@@ -0,0 +1,88 @@
import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from notifier import slack as 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_escapes_the_three_characters_slack_reads_as_control_characters(self):
slack = Slack({"ok": True})
self.assertIsNone(dm.send(CONFIG, "Use <b> & [<setting>]?", slack))
self.assertEqual(slack.requests[0][3], {"channel": "U0123ABCD", "text": "Use &lt;b&gt; &amp; [&lt;setting&gt;]?"})
def test_leaves_quotes_as_they_are_since_slack_reads_only_three_characters_as_control(self):
slack = Slack({"ok": True})
self.assertIsNone(dm.send(CONFIG, "Use \"a\" or 'b'?", slack))
self.assertEqual(slack.requests[0][3]["text"], "Use \"a\" or 'b'?")
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()