beaconry 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ # wads CI — calls the reusable workflow hosted in i2mint/wads.
2
+ #
3
+ # All configuration comes from this repo's pyproject.toml [tool.wads.ci.*].
4
+ # To customize the workflow itself (rare), replace this file with the
5
+ # full inline template `wads/data/github_ci_uv.yml` from i2mint/wads.
6
+ #
7
+ # Pinning: `@master` floats with wads. If you need version stability for
8
+ # a release-sensitive repo, change `@master` to a wads tag (e.g. `@0.2.15`;
9
+ # tags have no `v` prefix). A stub whose `secrets:` block passes the JSON
10
+ # transport (the default below) needs a tag from a release after 0.2.14 —
11
+ # older tags don't declare that secret and GitHub then rejects the
12
+ # workflow at parse time.
13
+ # CI failure does not block a published release — it blocks the publish
14
+ # step itself — so floating master is generally safe.
15
+ #
16
+ # Permissions: GitHub validates that the caller grants AT LEAST the
17
+ # permissions any job in the called workflow requests — at workflow-parse
18
+ # time, not at run-time, even if the job would be skipped via `if:`.
19
+ # The reusable workflow needs:
20
+ # contents: write for the publish job's version-bump push-back
21
+ # and for the github-pages job's gh-pages branch push
22
+ # pages: write for the github-pages job's REST API Pages config
23
+ # Both default to `write` on org-account GITHUB_TOKEN and need to be
24
+ # granted explicitly on personal-account callers (where the default is
25
+ # read-only). No `id-token: write` needed — the publish-github-pages
26
+ # action uses peaceiris/actions-gh-pages (branch-based) + REST API,
27
+ # not the OIDC `actions/deploy-pages` flow.
28
+ name: Continuous Integration
29
+ on: [push, pull_request]
30
+ jobs:
31
+ ci:
32
+ uses: i2mint/wads/.github/workflows/uv-ci.yml@master
33
+ permissions:
34
+ contents: write
35
+ pages: write
36
+ # Transport (NAMED, legacy): explicitly passes only the secrets
37
+ # listed below (PYPI_PASSWORD + those declared in
38
+ # [tool.wads.ci.env]). Every name must be in the frozen wads
39
+ # superset (wads/ci_secrets.py) or GitHub rejects the workflow
40
+ # at parse time. The default JSON transport has no such limit;
41
+ # regenerate with `wads-migrate ci-to-stub` to switch.
42
+ secrets:
43
+ PYPI_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
@@ -0,0 +1,120 @@
1
+ .claude/handoffs/
2
+ .claude/scratch/
3
+
4
+ # Byte-compiled / optimized / DLL files
5
+ __pycache__/
6
+ *.py[cod]
7
+ *$py.class
8
+
9
+
10
+ .DS_Store
11
+ # C extensions
12
+ *.so
13
+
14
+ # TLS certificates
15
+ ## Ignore all PEM files anywhere
16
+ *.pem
17
+ ## Also ignore any certs directory
18
+ certs/
19
+
20
+ # Distribution / packaging
21
+ .Python
22
+ build/
23
+ develop-eggs/
24
+ dist/
25
+ downloads/
26
+ eggs/
27
+ .eggs/
28
+ lib/
29
+ lib64/
30
+ parts/
31
+ sdist/
32
+ var/
33
+ wheels/
34
+ *.egg-info/
35
+ .installed.cfg
36
+ *.egg
37
+ MANIFEST
38
+ _build
39
+
40
+ # PyInstaller
41
+ # Usually these files are written by a python script from a template
42
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
43
+ *.manifest
44
+ *.spec
45
+
46
+ # Installer logs
47
+ pip-log.txt
48
+ pip-delete-this-directory.txt
49
+
50
+ # Unit test / coverage reports
51
+ htmlcov/
52
+ .tox/
53
+ .coverage
54
+ .coverage.*
55
+ .cache
56
+ nosetests.xml
57
+ coverage.xml
58
+ *.cover
59
+ .hypothesis/
60
+ .pytest_cache/
61
+
62
+ # Translations
63
+ *.mo
64
+ *.pot
65
+
66
+ # Django stuff:
67
+ *.log
68
+ local_settings.py
69
+ db.sqlite3
70
+
71
+ # Flask stuff:
72
+ instance/
73
+ .webassets-cache
74
+
75
+ # Scrapy stuff:
76
+ .scrapy
77
+
78
+ # Sphinx documentation
79
+ docs/_build/
80
+ docs/*
81
+
82
+ # PyBuilder
83
+ target/
84
+
85
+ # Jupyter Notebook
86
+ .ipynb_checkpoints
87
+
88
+ # pyenv
89
+ .python-version
90
+
91
+ # celery beat schedule file
92
+ celerybeat-schedule
93
+
94
+ # SageMath parsed files
95
+ *.sage.py
96
+
97
+ # Environments
98
+ .env
99
+ .venv
100
+ env/
101
+ venv/
102
+ ENV/
103
+ env.bak/
104
+ venv.bak/
105
+
106
+ # Spyder project settings
107
+ .spyderproject
108
+ .spyproject
109
+
110
+ # Rope project settings
111
+ .ropeproject
112
+
113
+ # mkdocs documentation
114
+ /site
115
+
116
+ # mypy
117
+ .mypy_cache/
118
+
119
+ # PyCharm
120
+ .idea
beaconry-0.0.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thor Whalen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.5
2
+ Name: beaconry
3
+ Version: 0.0.1
4
+ Summary: Monitoring notifications that remember what they said and why: alert evaluation, a scrubbed history with evidence, delivery channels, and agent-readable surfaces.
5
+ Project-URL: Homepage, https://github.com/addaix/beaconry
6
+ Project-URL: Repository, https://github.com/addaix/beaconry
7
+ Project-URL: Documentation, https://addaix.github.io/beaconry
8
+ Project-URL: Issues, https://github.com/addaix/beaconry/issues
9
+ Author: Thor Whalen
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,alerting,monitoring,notifications,ntfy,observability
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
16
+ Classifier: Operating System :: POSIX
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: System :: Monitoring
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: cw<0.2,>=0.1.1
24
+ Requires-Dist: dol
25
+ Provides-Extra: correspond
26
+ Requires-Dist: correspond; extra == 'correspond'
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
29
+ Requires-Dist: pytest>=7.0; extra == 'dev'
30
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
31
+ Provides-Extra: docs
32
+ Requires-Dist: sphinx-rtd-theme>=1.0; extra == 'docs'
33
+ Requires-Dist: sphinx>=6.0; extra == 'docs'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # beaconry
37
+
38
+ Monitoring notifications that remember what they said, and why.
39
+
40
+ Your monitor runs its checks; beaconry decides whether that is news, sends it, and keeps a history of every notice with the evidence gathered at send time (secrets scrubbed), so an agent can answer "what did the server last say, and what should I do?" in one call.
41
+
42
+ ```bash
43
+ pip install beaconry
44
+ ```
45
+
46
+ ## Example
47
+
48
+ ```python
49
+ from beaconry import Check, tick
50
+
51
+ checks = [
52
+ Check("disk", "Disk /", "crit", "95% used", remedy="Clear old logs.", volatile=True),
53
+ Check("web", "Web app", "ok", "200 in 80 ms"),
54
+ ]
55
+ tick(checks, source="myserver") # run this every few minutes, e.g. from cron
56
+ ```
57
+
58
+ The first run sends "myserver: 1 issue(s)" to your ntfy topic (`$NTFY_TOPIC`) and records it under `~/.local/share/beaconry/`. The same run again sends nothing: the alert has not changed.
59
+
60
+ ## Reading the history (CLI)
61
+
62
+ ```bash
63
+ beaconry latest myserver # the newest notice: checks, remedies, evidence
64
+ beaconry latest myserver --json # the same, for an agent
65
+ beaconry list --since 2d --kind alert --q disk
66
+ beaconry show myserver/20261204T101500Z-3fa2c1
67
+ beaconry sources
68
+ beaconry latest myserver --json --on otherhost # read another machine's history over ssh
69
+ ```
70
+
71
+ Human output is short; `--json` is the agent format. `--on HOST` runs `ssh HOST beaconry ... --json` (set `$BEACONRY_REMOTE_CMD` if `beaconry` is not on that host's non-interactive `PATH`). The same functions are in `beaconry.tools`, for other surfaces.
72
+
73
+ ## The seams
74
+
75
+ Each step of `tick` is a keyword argument with a working default:
76
+
77
+ | keyword | default | swap in |
78
+ |---|---|---|
79
+ | `history=`, `state_store=` | JSON files under `~/.local/share/beaconry/{history,state}/` (`$BEACONRY_HOME` moves the root) | any `MutableMapping` (a dict, an S3 store) |
80
+ | `send=` | `ntfy_sender()`: a stdlib POST, topic from `$NTFY_TOPIC` or `ntfy_sender(topic_file=...)` | `correspond_sender("ntfy:")` (`pip install beaconry[correspond]`), or any `notice -> (ok, error)` callable |
81
+ | `gather=` | the recent journal (`journalctl`) of the units a check names in `evidence_units`, skipped off Linux | any `checks -> dict` callable |
82
+ | `scrub=` | regex scrubber (token shapes, PEM blocks, `name=value` secrets, long hex/base64) plus the literal `secrets=` you pass and the sender's topic | any `(obj, *, secrets) -> obj` callable |
83
+ | `policy=` | `Policy(renotify_hours=6, renotify_max_hours=24, recover_ticks=3, retry_minutes=30)` | a `Policy`, or settings data with per-source overrides: `{"renotify_hours": 12, "sources": {"myserver": {"recover_ticks": 1}}}` |
84
+
85
+ `notify(notice, send=..., history=...)` is the scrub-send-record half on its own, for an alerter that decides for itself when to speak. `adopt_state(old_state_text, source=...)` imports the state a monitor kept before moving onto beaconry (JSON, or a legacy `"<sig> <ts>"` line), so the move does not re-send the alert already out.
86
+
87
+ The decision itself is a pure function, `evaluate(checks, state, now=..., policy=..., source=...)`, returning the notice due (or `None`) and the state to persist whether delivery works or fails, so it can be tested and reused without any I/O.
88
+
89
+ ## What it decides
90
+
91
+ - **Alert on change.** A failing check is identified by its `cause`, or by its status for a `volatile` measurement (a growing disk), or by its rendered value with elapsed times masked ("unshipped for 10h59m" and "for 11h09m" are the same problem). The same set of problems is not news.
92
+ - **Reminders with backoff.** An unchanged alert is re-sent after 6 h, then 12 h, then every 24 h.
93
+ - **Resolved and recovered.** When some alerted checks clear, a quiet "N resolved, M still open"; when all clear, "myserver recovered".
94
+ - **Hysteresis.** A check must stay ok for 3 runs before it counts as resolved, so a value flapping around its threshold does not spam.
95
+ - **Retry backoff.** A notice whose delivery failed is retried at most every 30 minutes while it stays the same, and recorded either way.
@@ -0,0 +1,60 @@
1
+ # beaconry
2
+
3
+ Monitoring notifications that remember what they said, and why.
4
+
5
+ Your monitor runs its checks; beaconry decides whether that is news, sends it, and keeps a history of every notice with the evidence gathered at send time (secrets scrubbed), so an agent can answer "what did the server last say, and what should I do?" in one call.
6
+
7
+ ```bash
8
+ pip install beaconry
9
+ ```
10
+
11
+ ## Example
12
+
13
+ ```python
14
+ from beaconry import Check, tick
15
+
16
+ checks = [
17
+ Check("disk", "Disk /", "crit", "95% used", remedy="Clear old logs.", volatile=True),
18
+ Check("web", "Web app", "ok", "200 in 80 ms"),
19
+ ]
20
+ tick(checks, source="myserver") # run this every few minutes, e.g. from cron
21
+ ```
22
+
23
+ The first run sends "myserver: 1 issue(s)" to your ntfy topic (`$NTFY_TOPIC`) and records it under `~/.local/share/beaconry/`. The same run again sends nothing: the alert has not changed.
24
+
25
+ ## Reading the history (CLI)
26
+
27
+ ```bash
28
+ beaconry latest myserver # the newest notice: checks, remedies, evidence
29
+ beaconry latest myserver --json # the same, for an agent
30
+ beaconry list --since 2d --kind alert --q disk
31
+ beaconry show myserver/20261204T101500Z-3fa2c1
32
+ beaconry sources
33
+ beaconry latest myserver --json --on otherhost # read another machine's history over ssh
34
+ ```
35
+
36
+ Human output is short; `--json` is the agent format. `--on HOST` runs `ssh HOST beaconry ... --json` (set `$BEACONRY_REMOTE_CMD` if `beaconry` is not on that host's non-interactive `PATH`). The same functions are in `beaconry.tools`, for other surfaces.
37
+
38
+ ## The seams
39
+
40
+ Each step of `tick` is a keyword argument with a working default:
41
+
42
+ | keyword | default | swap in |
43
+ |---|---|---|
44
+ | `history=`, `state_store=` | JSON files under `~/.local/share/beaconry/{history,state}/` (`$BEACONRY_HOME` moves the root) | any `MutableMapping` (a dict, an S3 store) |
45
+ | `send=` | `ntfy_sender()`: a stdlib POST, topic from `$NTFY_TOPIC` or `ntfy_sender(topic_file=...)` | `correspond_sender("ntfy:")` (`pip install beaconry[correspond]`), or any `notice -> (ok, error)` callable |
46
+ | `gather=` | the recent journal (`journalctl`) of the units a check names in `evidence_units`, skipped off Linux | any `checks -> dict` callable |
47
+ | `scrub=` | regex scrubber (token shapes, PEM blocks, `name=value` secrets, long hex/base64) plus the literal `secrets=` you pass and the sender's topic | any `(obj, *, secrets) -> obj` callable |
48
+ | `policy=` | `Policy(renotify_hours=6, renotify_max_hours=24, recover_ticks=3, retry_minutes=30)` | a `Policy`, or settings data with per-source overrides: `{"renotify_hours": 12, "sources": {"myserver": {"recover_ticks": 1}}}` |
49
+
50
+ `notify(notice, send=..., history=...)` is the scrub-send-record half on its own, for an alerter that decides for itself when to speak. `adopt_state(old_state_text, source=...)` imports the state a monitor kept before moving onto beaconry (JSON, or a legacy `"<sig> <ts>"` line), so the move does not re-send the alert already out.
51
+
52
+ The decision itself is a pure function, `evaluate(checks, state, now=..., policy=..., source=...)`, returning the notice due (or `None`) and the state to persist whether delivery works or fails, so it can be tested and reused without any I/O.
53
+
54
+ ## What it decides
55
+
56
+ - **Alert on change.** A failing check is identified by its `cause`, or by its status for a `volatile` measurement (a growing disk), or by its rendered value with elapsed times masked ("unshipped for 10h59m" and "for 11h09m" are the same problem). The same set of problems is not news.
57
+ - **Reminders with backoff.** An unchanged alert is re-sent after 6 h, then 12 h, then every 24 h.
58
+ - **Resolved and recovered.** When some alerted checks clear, a quiet "N resolved, M still open"; when all clear, "myserver recovered".
59
+ - **Hysteresis.** A check must stay ok for 3 runs before it counts as resolved, so a value flapping around its threshold does not spam.
60
+ - **Retry backoff.** A notice whose delivery failed is retried at most every 30 minutes while it stays the same, and recorded either way.
@@ -0,0 +1,64 @@
1
+ """beaconry: monitoring notifications that remember what they said, and why.
2
+
3
+ A monitor runs its checks and hands them to :func:`tick`. beaconry decides whether that
4
+ is news (alert on change, reminders with backoff, resolved and recovered notices,
5
+ hysteresis against flapping, retry backoff on failed delivery), gathers evidence,
6
+ scrubs secrets, sends the notice, and records it, with its delivery outcome, in a
7
+ history an agent can read in one call (``beaconry latest <source> --json``).
8
+
9
+ >>> from beaconry import Check, tick
10
+ >>> sent = []
11
+ >>> n = tick(
12
+ ... [Check("disk", "Disk /", "crit", "95% used", remedy="free some space")],
13
+ ... source="box", history={}, state_store={},
14
+ ... send=lambda notice: (sent.append(notice.title) or True, ""),
15
+ ... )
16
+ >>> n.title, n.delivery["ok"], sent
17
+ ('box: 1 issue(s)', True, ['box: 1 issue(s)'])
18
+ """
19
+
20
+ from beaconry.channels import correspond_sender, ntfy_sender
21
+ from beaconry.evaluate import Decision, alert_part, evaluate, parse_state, signature
22
+ from beaconry.evidence import gather_default, journal
23
+ from beaconry.history import History
24
+ from beaconry.model import (
25
+ CRIT,
26
+ NOTICE_KINDS,
27
+ OK,
28
+ WARN,
29
+ Check,
30
+ Notice,
31
+ Policy,
32
+ resolve_policy,
33
+ )
34
+ from beaconry.monitor import adopt_state, notify, send_test, tick
35
+ from beaconry.scrub import scrub
36
+ from beaconry.stores import beaconry_home, json_store
37
+
38
+ __all__ = [
39
+ "CRIT",
40
+ "Check",
41
+ "Decision",
42
+ "History",
43
+ "NOTICE_KINDS",
44
+ "Notice",
45
+ "OK",
46
+ "Policy",
47
+ "WARN",
48
+ "adopt_state",
49
+ "alert_part",
50
+ "beaconry_home",
51
+ "correspond_sender",
52
+ "evaluate",
53
+ "gather_default",
54
+ "journal",
55
+ "json_store",
56
+ "notify",
57
+ "ntfy_sender",
58
+ "parse_state",
59
+ "resolve_policy",
60
+ "scrub",
61
+ "send_test",
62
+ "signature",
63
+ "tick",
64
+ ]
@@ -0,0 +1,155 @@
1
+ # PYTHON_ARGCOMPLETE_OK
2
+ """The ``beaconry`` command line: read the notice history.
3
+
4
+ ::
5
+
6
+ beaconry latest [source] [--kind K] [--json] [--on HOST]
7
+ beaconry list [source] [--since 2d] [--kind K] [--q TEXT] [--limit N] [--json] [--on HOST]
8
+ beaconry show <id> [--json] [--on HOST]
9
+ beaconry sources [--json] [--on HOST]
10
+
11
+ Human output is short; ``--json`` is the format for agents (and what ``--on HOST``
12
+ asks the other machine for). Each command is a thin wrapper over the same function in
13
+ :mod:`beaconry.tools`.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import functools
19
+ import json as _json
20
+
21
+ import cw
22
+
23
+ from beaconry import tools
24
+
25
+
26
+ def _dumps(obj) -> str:
27
+ return _json.dumps(obj, indent=2, ensure_ascii=False)
28
+
29
+
30
+ def _first_line(s: str, width: int = 160) -> str:
31
+ line = (s or "").strip().splitlines()[0] if (s or "").strip() else ""
32
+ return line if len(line) <= width else line[: width - 3] + "..."
33
+
34
+
35
+ def format_notice(n: dict) -> str:
36
+ """A notice as a few lines: header, body, checks (with remedies), evidence summary."""
37
+ d = n.get("delivery") or {}
38
+ delivered = (
39
+ "delivered" if d.get("ok") else f"NOT delivered ({d.get('error') or 'unknown'})"
40
+ )
41
+ out = [
42
+ f"{n['ts']} [{n['kind']}] {n['title']} ({delivered} via {d.get('channel', '?')})"
43
+ ]
44
+ out.append(f"id: {n['id']}")
45
+ if n.get("body"):
46
+ out += ["", n["body"]]
47
+ if n.get("checks"):
48
+ out.append("")
49
+ for c in n["checks"]:
50
+ out.append(f"[{c['status']}] {c['label']}: {c.get('value', '')}")
51
+ if c.get("detail"):
52
+ out.append(f" {_first_line(c['detail'])}")
53
+ if c.get("remedy"):
54
+ out.append(f" remedy: {_first_line(c['remedy'])}")
55
+ journal = (n.get("evidence") or {}).get("journal") or {}
56
+ if journal:
57
+ out += [
58
+ "",
59
+ "evidence: "
60
+ + ", ".join(
61
+ f"{u} ({len(t.splitlines())} journal lines)" for u, t in journal.items()
62
+ ),
63
+ ]
64
+ return "\n".join(out)
65
+
66
+
67
+ def _errors_as_command_errors(func):
68
+ """Expected failures (unknown id, bad input, a remote error) as one line, no traceback."""
69
+
70
+ @functools.wraps(func)
71
+ def wrapper(*args, **kwargs):
72
+ try:
73
+ return func(*args, **kwargs)
74
+ except (KeyError, ValueError, tools.RemoteError) as e:
75
+ msg = e.args[0] if isinstance(e, KeyError) and e.args else str(e)
76
+ raise cw.CommandError(f"beaconry: {msg}") from None
77
+
78
+ return wrapper
79
+
80
+
81
+ @_errors_as_command_errors
82
+ def latest(source: str = None, *, kind: str = None, json: bool = False, on: str = None):
83
+ """The newest notice (of SOURCE), with its checks, remedies and evidence."""
84
+ n = tools.latest(source, kind=kind, on=on)
85
+ if json:
86
+ return _dumps(n)
87
+ return "no notices" if n is None else format_notice(n)
88
+
89
+
90
+ @_errors_as_command_errors
91
+ def list_(
92
+ source: str = None,
93
+ *,
94
+ since: str = None,
95
+ kind: str = None,
96
+ q: str = None,
97
+ limit: int = 50,
98
+ json: bool = False,
99
+ on: str = None,
100
+ ):
101
+ """Notices newest first, one line each (SINCE: a duration like 2d, or an ISO time)."""
102
+ hits = tools.list_notices(source, since=since, kind=kind, q=q, limit=limit, on=on)
103
+ if json:
104
+ return _dumps(hits)
105
+ lines = [
106
+ f"{h['id']} {h['kind']:<9} {h['title']}"
107
+ + ("" if h["delivered"] else " [undelivered]")
108
+ for h in hits
109
+ ]
110
+ return "\n".join(lines) or "no notices"
111
+
112
+
113
+ @_errors_as_command_errors
114
+ def show(id: str, *, json: bool = False, on: str = None):
115
+ """The full notice with this ID."""
116
+ n = tools.show(id, on=on)
117
+ return _dumps(n) if json else format_notice(n)
118
+
119
+
120
+ @_errors_as_command_errors
121
+ def sources(*, json: bool = False, on: str = None):
122
+ """The sources that have notices."""
123
+ s = tools.sources(on=on)
124
+ return _dumps(s) if json else ("\n".join(s) or "no sources")
125
+
126
+
127
+ COMMANDS = {"latest": latest, "list": list_, "show": show, "sources": sources}
128
+
129
+ _COMMON = {
130
+ "json": {"help": "print JSON (the agent format)"},
131
+ "on": {"help": "read HOST's history over ssh", "metavar": "HOST"},
132
+ }
133
+ _KIND = {"help": "alert, reminder, resolved, recovered or test", "metavar": "KIND"}
134
+ _CONFIG = {
135
+ "latest": {**_COMMON, "source": {"help": "only this source"}, "kind": _KIND},
136
+ "list": {
137
+ **_COMMON,
138
+ "source": {"help": "only this source"},
139
+ "since": {"help": "a duration (2d, 6h) or an ISO time"},
140
+ "kind": _KIND,
141
+ "q": {"help": "text in the title, body or checks", "metavar": "TEXT"},
142
+ "limit": {"help": "at most this many"},
143
+ },
144
+ "show": {**_COMMON, "id": {"help": "a notice id, as list prints it"}},
145
+ "sources": _COMMON,
146
+ }
147
+
148
+
149
+ def main(argv=None) -> int:
150
+ """Run the CLI; returns the exit code."""
151
+ return cw.dispatch(COMMANDS, argv, config=_CONFIG, convention=cw.MODERN)
152
+
153
+
154
+ if __name__ == "__main__":
155
+ raise SystemExit(main())