cli-watch-kit 0.1.0__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.
Files changed (55) hide show
  1. cli_watch_kit-0.1.0/.editorconfig +15 -0
  2. cli_watch_kit-0.1.0/.github/workflows/ci.yml +67 -0
  3. cli_watch_kit-0.1.0/.github/workflows/publish.yml +44 -0
  4. cli_watch_kit-0.1.0/.gitignore +18 -0
  5. cli_watch_kit-0.1.0/.python-version +1 -0
  6. cli_watch_kit-0.1.0/CLAUDE.md +1 -0
  7. cli_watch_kit-0.1.0/LICENSE +21 -0
  8. cli_watch_kit-0.1.0/PKG-INFO +207 -0
  9. cli_watch_kit-0.1.0/README.md +176 -0
  10. cli_watch_kit-0.1.0/pyproject.toml +81 -0
  11. cli_watch_kit-0.1.0/scripts/hooks/commit-msg +53 -0
  12. cli_watch_kit-0.1.0/scripts/hooks/pre-commit +67 -0
  13. cli_watch_kit-0.1.0/src/cli_watch_kit/__init__.py +27 -0
  14. cli_watch_kit-0.1.0/src/cli_watch_kit/app.py +175 -0
  15. cli_watch_kit-0.1.0/src/cli_watch_kit/atomic.py +37 -0
  16. cli_watch_kit-0.1.0/src/cli_watch_kit/budget.py +209 -0
  17. cli_watch_kit-0.1.0/src/cli_watch_kit/changelog.py +87 -0
  18. cli_watch_kit-0.1.0/src/cli_watch_kit/claude.py +195 -0
  19. cli_watch_kit-0.1.0/src/cli_watch_kit/cli.py +410 -0
  20. cli_watch_kit-0.1.0/src/cli_watch_kit/client.py +625 -0
  21. cli_watch_kit-0.1.0/src/cli_watch_kit/daemon/__init__.py +25 -0
  22. cli_watch_kit-0.1.0/src/cli_watch_kit/daemon/cache.py +48 -0
  23. cli_watch_kit-0.1.0/src/cli_watch_kit/daemon/engine.py +874 -0
  24. cli_watch_kit-0.1.0/src/cli_watch_kit/daemon/lifecycle.py +387 -0
  25. cli_watch_kit-0.1.0/src/cli_watch_kit/daemon/scheduler.py +85 -0
  26. cli_watch_kit-0.1.0/src/cli_watch_kit/daemon/server.py +116 -0
  27. cli_watch_kit-0.1.0/src/cli_watch_kit/daemon/transport.py +324 -0
  28. cli_watch_kit-0.1.0/src/cli_watch_kit/durations.py +28 -0
  29. cli_watch_kit-0.1.0/src/cli_watch_kit/events.py +182 -0
  30. cli_watch_kit-0.1.0/src/cli_watch_kit/locks.py +93 -0
  31. cli_watch_kit-0.1.0/src/cli_watch_kit/paths.py +114 -0
  32. cli_watch_kit-0.1.0/src/cli_watch_kit/py.typed +0 -0
  33. cli_watch_kit-0.1.0/src/cli_watch_kit/sinks.py +106 -0
  34. cli_watch_kit-0.1.0/src/cli_watch_kit/source.py +291 -0
  35. cli_watch_kit-0.1.0/src/cli_watch_kit/timers.py +67 -0
  36. cli_watch_kit-0.1.0/tests/conftest.py +37 -0
  37. cli_watch_kit-0.1.0/tests/fakeapp/__init__.py +1 -0
  38. cli_watch_kit-0.1.0/tests/fakeapp/app.py +19 -0
  39. cli_watch_kit-0.1.0/tests/fakeapp/catalog.py +14 -0
  40. cli_watch_kit-0.1.0/tests/fakeapp/cli.py +55 -0
  41. cli_watch_kit-0.1.0/tests/fakeapp/daemon.py +9 -0
  42. cli_watch_kit-0.1.0/tests/fakeapp/source.py +253 -0
  43. cli_watch_kit-0.1.0/tests/fakeapp/timers.py +41 -0
  44. cli_watch_kit-0.1.0/tests/test_batching.py +354 -0
  45. cli_watch_kit-0.1.0/tests/test_budget.py +94 -0
  46. cli_watch_kit-0.1.0/tests/test_claude.py +210 -0
  47. cli_watch_kit-0.1.0/tests/test_claude_fallback.py +72 -0
  48. cli_watch_kit-0.1.0/tests/test_daemon.py +562 -0
  49. cli_watch_kit-0.1.0/tests/test_engine.py +608 -0
  50. cli_watch_kit-0.1.0/tests/test_events.py +89 -0
  51. cli_watch_kit-0.1.0/tests/test_locks.py +84 -0
  52. cli_watch_kit-0.1.0/tests/test_transport.py +174 -0
  53. cli_watch_kit-0.1.0/tests/test_version.py +7 -0
  54. cli_watch_kit-0.1.0/tests/test_watcher.py +486 -0
  55. cli_watch_kit-0.1.0/uv.lock +441 -0
@@ -0,0 +1,15 @@
1
+ root = true
2
+
3
+ [*]
4
+ charset = utf-8
5
+ end_of_line = lf
6
+ insert_final_newline = true
7
+ trim_trailing_whitespace = true
8
+ indent_style = space
9
+ indent_size = 4
10
+
11
+ [*.{yml,yaml,toml,json}]
12
+ indent_size = 2
13
+
14
+ [*.md]
15
+ trim_trailing_whitespace = false
@@ -0,0 +1,67 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [master]
6
+ pull_request:
7
+
8
+ jobs:
9
+ lint:
10
+ name: Lint and type check
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+
15
+ - uses: astral-sh/setup-uv@v7
16
+ with:
17
+ enable-cache: true
18
+
19
+ - name: Install dependencies
20
+ run: uv sync --locked --dev
21
+
22
+ - name: Ruff check
23
+ run: uv run ruff check --output-format github .
24
+
25
+ - name: Ruff format check
26
+ run: uv run ruff format --check .
27
+
28
+ - name: Mypy
29
+ run: uv run mypy --strict src tests
30
+
31
+ test:
32
+ name: Test (Python ${{ matrix.python-version }})
33
+ runs-on: ubuntu-latest
34
+ strategy:
35
+ matrix:
36
+ python-version: ["3.12", "3.13", "3.14", "3.15"]
37
+ steps:
38
+ - uses: actions/checkout@v4
39
+
40
+ - uses: astral-sh/setup-uv@v7
41
+ with:
42
+ python-version: ${{ matrix.python-version }}
43
+ enable-cache: true
44
+
45
+ - name: Install dependencies
46
+ run: uv sync --locked --dev
47
+
48
+ - name: Run tests
49
+ run: uv run pytest
50
+
51
+ test-without-claude-code:
52
+ name: Test without the claude-code extra
53
+ runs-on: ubuntu-latest
54
+ steps:
55
+ - uses: actions/checkout@v4
56
+
57
+ - uses: astral-sh/setup-uv@v7
58
+ with:
59
+ enable-cache: true
60
+
61
+ - name: Install dependencies without cc-blackbox
62
+ run: |
63
+ uv sync --locked --dev
64
+ uv pip uninstall cc-blackbox
65
+
66
+ - name: Run tests
67
+ run: uv run --no-sync pytest
@@ -0,0 +1,44 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+
8
+ jobs:
9
+ build:
10
+ name: Build
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ with:
15
+ fetch-depth: 0
16
+
17
+ - uses: astral-sh/setup-uv@v7
18
+ with:
19
+ enable-cache: true
20
+
21
+ - name: Build package
22
+ run: uv build
23
+
24
+ - uses: actions/upload-artifact@v4
25
+ with:
26
+ name: dist
27
+ path: dist/
28
+
29
+ publish:
30
+ name: Publish
31
+ needs: build
32
+ runs-on: ubuntu-latest
33
+ environment:
34
+ name: pypi
35
+ url: https://pypi.org/p/cli-watch-kit
36
+ permissions:
37
+ id-token: write
38
+ steps:
39
+ - uses: actions/download-artifact@v4
40
+ with:
41
+ name: dist
42
+ path: dist/
43
+
44
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,18 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
11
+
12
+ # Tool caches
13
+ .mypy_cache/
14
+ .pytest_cache/
15
+ .ruff_cache/
16
+
17
+ # Claude
18
+ .claude/settings.local.json
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1 @@
1
+ @README.md
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Filip Procházka
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,207 @@
1
+ Metadata-Version: 2.5
2
+ Name: cli-watch-kit
3
+ Version: 0.1.0
4
+ Summary: Build a `watch` command for a CLI: poll a source, report changes as JSON events, share one rate-limited daemon between all watchers
5
+ Project-URL: Homepage, https://github.com/fprochazka/cli-watch-kit
6
+ Project-URL: Repository, https://github.com/fprochazka/cli-watch-kit
7
+ Project-URL: Issues, https://github.com/fprochazka/cli-watch-kit/issues
8
+ Author-email: Filip Procházka <dev@fprochazka.cz>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: ai-agent,claude-code,cli,click,daemon,events,polling,watch
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Operating System :: Microsoft :: Windows
18
+ Classifier: Operating System :: POSIX :: Linux
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Programming Language :: Python :: 3.15
24
+ Classifier: Topic :: Software Development :: Libraries
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.12
27
+ Requires-Dist: click<9,>=8.1
28
+ Provides-Extra: claude-code
29
+ Requires-Dist: cc-blackbox<0.13,>=0.11; extra == 'claude-code'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # cli-watch-kit
33
+
34
+ A library for building a `watch` command into a CLI. The CLI says how to poll its API and how to diff two snapshots into events; the library does the rest:
35
+
36
+ - one JSON event per line on stdout (or a message into the Claude Code session that started the watch), with a status header on stderr;
37
+ - `--events` / `--exclude-events` filters with groups, `--until`, `--timeout`, `--idle-after`, and the app's own threshold events computed from time;
38
+ - a changelog (`events.jsonl`) and a baseline per watched resource, so a watcher resumes its numbering and never reports a change twice;
39
+ - one shared daemon per user and app that polls each resource once for all its watchers, batches resources of one account into one API call, paces every account on a rate budget with several dimensions (requests and complexity points, for example), and survives the watcher that started it;
40
+ - a `daemon status|stop|logs` command group.
41
+
42
+ It was extracted from the `glab-watch` command of [glab-cli-extras](https://github.com/fprochazka/glab-cli-extras).
43
+
44
+ ## Installation
45
+
46
+ Requires Python 3.12+. The core depends only on click.
47
+
48
+ ```bash
49
+ uv add cli-watch-kit # stdout only
50
+ uv add 'cli-watch-kit[claude-code]' # also messages into a Claude Code session, through cc-blackbox
51
+ ```
52
+
53
+ ## Concepts
54
+
55
+ - A **source** (`cli_watch_kit.source.Source`) polls **targets** (`Target(kind, id, data)`), such as `issue ABC-123`. Its `poll()` gets a batch of `PollItem`s (target, previous snapshot, the event kinds anyone wants) and returns a `PollOutcome` per target: the new snapshot, the events, an optional end, or a per-target error (`NotFound`, `Unauthorized`, `RateLimited`, `Transient`). The diff should be a pure function the CLI tests on its own. A poll without a previous snapshot is the baseline and reports nothing.
56
+ - **Keep the snapshot stable.** The engine hashes `encode(snapshot)` after every poll, and a new hash is what sends the snapshot to the watchers again (and rewrites their `baseline.json`); after a restart, an equal hash is what drops a repeated `watch_started`. So the snapshot holds only what the diff compares, and stays the same while nothing changed. Volatile values (fetch times, ETags, rate-limit readings, cursors, request counts) belong in `PollItem.state`.
57
+ - `PollItem.state` is a dict private to one resource that lives as long as the resource: the place for an ETag, work held back for a later poll, or a stateful poller object. It starts empty after a daemon restart; only the snapshot survives one.
58
+ - **Source options** are what a watcher asks of the source besides event kinds (glab's `--logs=failed|all|none`, for example). `run_watch(source_options=...)` sends them with the subscription, `Source.check_options` validates them, and `PollItem.options` holds those of every subscriber and parent, each once, for the source to merge. A parent asks its children for kinds and options with `Wants(events, options)`.
59
+ - An **account** (`Source.account(target, params)`) is whose rate limit a poll spends. Targets of different accounts never share a call or a budget.
60
+ - Targets of one account with the same **batch key** (`Source.batch_key`) that are due within `coalesce_window` seconds go into one `poll()` call; the first poll of a new target waits up to that window (`baseline_wait`), so watchers that start a few seconds apart share it, split so that no call costs more than `batch_cost_cap`. `cost(batch)` estimates a call's cost per budget dimension; the source reports what the API said through `ctx.budget.observe(...)` and, when it knows what each response really cost (an ETag 304, a complexity header), charges that with `ctx.spend(...)`; the engine then gives back its estimate for those dimensions. An API client shared by the polls of an account finds the poll it serves with `PollContext.current()`.
61
+ - **Params** are what a watcher sends along with its subscription, such as an API key. They travel over the daemon's private socket (`0600` in a `0700` dir), reach the source per account, and never appear in the status or the log. Before it sends any, the watcher checks that the state dir and the socket (or the TCP endpoint file) belong to the user and that nobody else can write them, and over TCP that a daemon still holds the lock, so a stale port gets no token. The daemon log is `0600` too. The latest params of an account win, so `Source.account()` must check the key it gets (and raise `Unauthorized` for a bad one): otherwise one watcher with a wrong key would break the account's other watchers.
62
+ - The **catalog** (`KindCatalog`) names the event kinds per resource kind, the groups of the filter options, and the threshold kinds the watcher computes itself. `watch_started`, `watch_degraded` and `watch_ended` are always reported.
63
+
64
+ ## A minimal source and CLI
65
+
66
+ ```python
67
+ # my_cli/watch.py
68
+ from collections.abc import Mapping, Sequence
69
+ from typing import Any
70
+
71
+ import click
72
+
73
+ from cli_watch_kit.app import WatchApp
74
+ from cli_watch_kit.budget import DimensionSpec
75
+ from cli_watch_kit.cli import WatchOptions, daemon_group, run_watch, watch_options
76
+ from cli_watch_kit.events import KindCatalog, RawEvent
77
+ from cli_watch_kit.source import NotFound, Params, PollContext, PollItem, PollOutcome, Source, Target
78
+
79
+ type Snapshot = dict[str, Any]
80
+
81
+
82
+ class IssueSource(Source[Snapshot]):
83
+ catalog = KindCatalog({"issue": ("state_changed",)}, groups={"status": ("state_changed",)})
84
+ dimensions = {
85
+ "requests": DimensionSpec(per_minute=40),
86
+ "complexity": DimensionSpec(per_minute=50_000, burst=10_000),
87
+ }
88
+ batch_cost_cap = {"complexity": 5_000}
89
+
90
+ async def account(self, target: Target, params: Params) -> str:
91
+ return await whoami(params["api_key"]) # the user the key belongs to
92
+
93
+ def batch_key(self, target: Target) -> str:
94
+ return "issues" # every issue of an account in one request
95
+
96
+ def interval(self, target: Target, snapshot: Snapshot | None) -> float:
97
+ return 30.0
98
+
99
+ def cost(self, batch: Sequence[PollItem[Snapshot]]) -> Mapping[str, float]:
100
+ return {"requests": 1, "complexity": 20 * len(batch)}
101
+
102
+ async def poll(self, batch: Sequence[PollItem[Snapshot]], ctx: PollContext) -> Mapping[str, PollOutcome[Snapshot]]:
103
+ found = await fetch_issues(ctx.params["api_key"], [item.target.id for item in batch]) # raise RateLimited etc.
104
+ outcomes = {}
105
+ for item in batch:
106
+ issue = found.get(item.target.id)
107
+ if issue is None:
108
+ outcomes[item.key] = PollOutcome(error=NotFound(f"no issue {item.target.id}"))
109
+ continue
110
+ events = diff(item.snapshot, issue) if item.snapshot is not None else [] # list[RawEvent]
111
+ ended = "completed" if issue["state"] == "Done" else None
112
+ outcomes[item.key] = PollOutcome(issue, events, ended=ended)
113
+ return outcomes
114
+
115
+
116
+ APP = WatchApp(
117
+ name="my-cli-watch",
118
+ source=IssueSource, # or an instance; a callable is called once, when needed
119
+ daemon_module="my_cli.watch_daemon",
120
+ app_protocol=1,
121
+ version="1.0.0",
122
+ status_prefix="my-cli watch: ",
123
+ envelope_tag="my-cli-watcher",
124
+ command="my-cli watch",
125
+ files_dir_name="my-cli", # <scratchpad>/my-cli/issue/ABC-123/events.jsonl; default: the name
126
+ )
127
+
128
+
129
+ @click.group()
130
+ def watch() -> None:
131
+ """Watch issues."""
132
+
133
+
134
+ @watch.command()
135
+ @click.argument("issue_id")
136
+ @watch_options
137
+ def issue(issue_id: str, options: WatchOptions) -> None:
138
+ raise SystemExit(run_watch(APP, Target("issue", issue_id), options, params={"api_key": api_key()}))
139
+
140
+
141
+ watch.add_command(daemon_group(APP))
142
+ ```
143
+
144
+ ```python
145
+ # my_cli/watch_daemon.py: what `python -m my_cli.watch_daemon` runs
146
+ from cli_watch_kit.daemon import main
147
+ from my_cli.watch import APP
148
+
149
+ if __name__ == "__main__":
150
+ main(APP)
151
+ ```
152
+
153
+ `run_watch` also takes `enabled_thresholds` and `timers` (the app's `ClientTimer`s for threshold kinds), `also_subscribe` (kinds the daemon should track for a timer without the watcher reporting them), a `writer` factory for the app's own files in the resource dir (it gets a `WriterContext` with the base and resource dirs, the target, the backend for extra ops and the status output), `resource_dir`, `readme`, `sender_name`, `restart` and extra `header` lines. Only one watcher at a time writes a resource dir: a second watcher of the same target into the same base dir exits with 1 and says so, and runs with its own `--base-dir`. A CLI on another framework fills a `WatchOptions` itself, or uses `cli_watch_kit.client.Watcher` directly; that one takes no lock, so the CLI must keep two watchers of one resource out of the same dir itself.
154
+
155
+ An app with requests the daemon should serve within the budget (fetching a log for a watcher, for example) puts them in `Source.ops`; a watcher calls them with `backend.call(op, payload, params)`. A source whose targets relay other targets (an MR and its head pipeline) returns them from `Source.children`.
156
+
157
+ ## The daemon
158
+
159
+ - The first watcher starts the daemon with `python -m <daemon_module>` under a spawn lock. The daemon forks once more, so a tool that kills the watcher's whole process tree does not kill it, and holds a lock for its lifetime; a second one exits at once.
160
+ - IPC is one NDJSON request and response per connection over a Unix socket under `$XDG_RUNTIME_DIR/<name>/` (or `$TMPDIR`, or the temp dir). Windows, or `<PREFIX>TRANSPORT=tcp`, uses loopback TCP with a token in a private file. The socket name carries the library's and the app's protocol versions (`daemon-l1-a1.sock`), so incompatible daemons never meet.
161
+ - Each watcher polls the daemon every 5 s, which renews its lease; a subscription not renewed for 20 s is dropped. Watchers of one target in one account share one resource, which keeps its last 500 events. The daemon exits 30 s after its last subscription.
162
+ - Each account has a token bucket per budget dimension, refilled at half of `remaining / (reset - now)` once the source reports readings. A 429 (`RateLimited`) blocks the account for its `Retry-After` and backs off exponentially. When the watched resources would exceed any dimension, all their intervals stretch by the same factor. Errors are reported once per kind as `watch_degraded`, with exponential backoff per resource.
163
+ - After a daemon crash, the watcher starts a new daemon and resubscribes with its baseline, so the new daemon reports only what changed meanwhile, and the watcher drops a repeated `watch_started`. When another watcher already brought the resource back, the engine diffs the baseline against the current snapshot with `Source.diff`, so every resubscriber gets the gap; the same holds for a watcher whose lease expired. A resubscribe that fails for a reason that may pass (the API unreachable after a suspend) is retried with a backoff. Leases run on a monotonic clock.
164
+ - **Upgrades:** `hello` returns the library and app versions and a stamp of the installed code (a fingerprint and the newest file time of both packages). A watcher with newer code asks an older daemon to `drain` (stop) and starts a current one; the old daemon's watchers resubscribe from their baselines. A watcher with older code uses a newer daemon as it is. This also covers editable installs, where the code changes without a version.
165
+ - `--no-daemon` runs the same engine and request handler in a thread of the watcher, with a private budget.
166
+ - `--no-daemon` and the daemon build their engine the same way (`Engine.for_app`), from `WatchApp.client_poll_ms` and `lease_timeout` and the environment. For tests, `APP.with_overrides(source=..., client_poll_ms=..., lease_timeout=...)` returns a copy of the app with another source and settings, to run with `WatchOptions(no_daemon=True)`.
167
+ - **A hung daemon** (it holds its lock but answers nothing) is replaced: a watcher whose polls time out 3 times in a row, or that gets no answer to two hellos when it starts, kills it and starts a new one, and `daemon stop` kills one that does not stop within `STOP_TIMEOUT`. It is killed only when its pid is verified: the daemon writes it into its lock file, the lock is held, and the process runs the app's daemon module. Otherwise the watcher exits with an error that says how to stop it. `daemon status` reports such a daemon as running but not answering. On Windows a hung daemon is reported but never killed.
168
+ - Environment variables, with the app's prefix (default: the name in upper case, `-` as `_`, plus `_`): `STATE_DIR`, `BASE_DIR`, `TRANSPORT`, `IDLE_TIMEOUT`, `LEASE_TIMEOUT`, `CLIENT_POLL_MS`, `REQUEST_TIMEOUT` (10 s), `STOP_TIMEOUT` (10 s), `DEBUG`.
169
+
170
+ ## Claude Code
171
+
172
+ With the `claude-code` extra, `--events-stream=auto` (the default) sends the events into the Claude Code session that started the watcher, when that session accepts messages, as `<envelope_tag resource="issue ABC-123" seq="1-2">` blocks. cc-blackbox does the delivery: session lookup, the protocol check, burst batching, the 64 KB cap, the receiver's rate limit, and the end of the watch when the session is gone. The resource dir then lives in the session's scratchpad. Without the extra, `auto` uses stdout, and under Claude Code the header says which extra to install; `claude-message` fails with the same hint. Nothing imports cc-blackbox until a stream needs it.
173
+
174
+ ## Developing
175
+
176
+ ```bash
177
+ uv sync
178
+ uv run ruff check . && uv run ruff format --check . && uv run mypy --strict src tests && uv run pytest
179
+ ```
180
+
181
+ The tests run the engine on a fake clock against a fake source (`tests/fakeapp`), and start real daemon processes in short temp dirs over both transports. CI runs the same checks on Python 3.12 to 3.15.
182
+
183
+ To develop a CLI against a local checkout, add it as an editable path dependency of the CLI:
184
+
185
+ ```toml
186
+ [tool.uv.sources]
187
+ cli-watch-kit = { path = "../cli-watch-kit", editable = true }
188
+ ```
189
+
190
+ ### Commit hooks
191
+
192
+ Fixtures and captured output can carry private identifiers such as workspace, account or issue names, API keys or paths. `scripts/hooks` holds a pre-commit and a commit-msg hook that refuse a commit when a staged line or the commit message matches a private identifier. The identifiers live in a file outside the repository, because listing them here would publish the very strings the hooks exist to keep out. Set it up once per clone:
193
+
194
+ ```bash
195
+ git config core.hooksPath scripts/hooks
196
+ git config hooks.forbiddenPatternsFile ~/.config/git/forbidden-patterns.txt # any path outside the repo
197
+ ```
198
+
199
+ The file holds one extended regex per line, matched case-insensitively; blank lines and `#` comments are ignored. Until `hooks.forbiddenPatternsFile` points at a file with at least one pattern, both hooks refuse every commit and print how to fix it.
200
+
201
+ ## Releasing
202
+
203
+ The version comes from the git tag through hatch-vcs. Pushing a `vX.Y.Z` tag runs `.github/workflows/publish.yml`, which builds the package and publishes it to PyPI through trusted publishing (the `pypi` environment of the GitHub repository must be registered as a trusted publisher on PyPI first).
204
+
205
+ ## License
206
+
207
+ MIT
@@ -0,0 +1,176 @@
1
+ # cli-watch-kit
2
+
3
+ A library for building a `watch` command into a CLI. The CLI says how to poll its API and how to diff two snapshots into events; the library does the rest:
4
+
5
+ - one JSON event per line on stdout (or a message into the Claude Code session that started the watch), with a status header on stderr;
6
+ - `--events` / `--exclude-events` filters with groups, `--until`, `--timeout`, `--idle-after`, and the app's own threshold events computed from time;
7
+ - a changelog (`events.jsonl`) and a baseline per watched resource, so a watcher resumes its numbering and never reports a change twice;
8
+ - one shared daemon per user and app that polls each resource once for all its watchers, batches resources of one account into one API call, paces every account on a rate budget with several dimensions (requests and complexity points, for example), and survives the watcher that started it;
9
+ - a `daemon status|stop|logs` command group.
10
+
11
+ It was extracted from the `glab-watch` command of [glab-cli-extras](https://github.com/fprochazka/glab-cli-extras).
12
+
13
+ ## Installation
14
+
15
+ Requires Python 3.12+. The core depends only on click.
16
+
17
+ ```bash
18
+ uv add cli-watch-kit # stdout only
19
+ uv add 'cli-watch-kit[claude-code]' # also messages into a Claude Code session, through cc-blackbox
20
+ ```
21
+
22
+ ## Concepts
23
+
24
+ - A **source** (`cli_watch_kit.source.Source`) polls **targets** (`Target(kind, id, data)`), such as `issue ABC-123`. Its `poll()` gets a batch of `PollItem`s (target, previous snapshot, the event kinds anyone wants) and returns a `PollOutcome` per target: the new snapshot, the events, an optional end, or a per-target error (`NotFound`, `Unauthorized`, `RateLimited`, `Transient`). The diff should be a pure function the CLI tests on its own. A poll without a previous snapshot is the baseline and reports nothing.
25
+ - **Keep the snapshot stable.** The engine hashes `encode(snapshot)` after every poll, and a new hash is what sends the snapshot to the watchers again (and rewrites their `baseline.json`); after a restart, an equal hash is what drops a repeated `watch_started`. So the snapshot holds only what the diff compares, and stays the same while nothing changed. Volatile values (fetch times, ETags, rate-limit readings, cursors, request counts) belong in `PollItem.state`.
26
+ - `PollItem.state` is a dict private to one resource that lives as long as the resource: the place for an ETag, work held back for a later poll, or a stateful poller object. It starts empty after a daemon restart; only the snapshot survives one.
27
+ - **Source options** are what a watcher asks of the source besides event kinds (glab's `--logs=failed|all|none`, for example). `run_watch(source_options=...)` sends them with the subscription, `Source.check_options` validates them, and `PollItem.options` holds those of every subscriber and parent, each once, for the source to merge. A parent asks its children for kinds and options with `Wants(events, options)`.
28
+ - An **account** (`Source.account(target, params)`) is whose rate limit a poll spends. Targets of different accounts never share a call or a budget.
29
+ - Targets of one account with the same **batch key** (`Source.batch_key`) that are due within `coalesce_window` seconds go into one `poll()` call; the first poll of a new target waits up to that window (`baseline_wait`), so watchers that start a few seconds apart share it, split so that no call costs more than `batch_cost_cap`. `cost(batch)` estimates a call's cost per budget dimension; the source reports what the API said through `ctx.budget.observe(...)` and, when it knows what each response really cost (an ETag 304, a complexity header), charges that with `ctx.spend(...)`; the engine then gives back its estimate for those dimensions. An API client shared by the polls of an account finds the poll it serves with `PollContext.current()`.
30
+ - **Params** are what a watcher sends along with its subscription, such as an API key. They travel over the daemon's private socket (`0600` in a `0700` dir), reach the source per account, and never appear in the status or the log. Before it sends any, the watcher checks that the state dir and the socket (or the TCP endpoint file) belong to the user and that nobody else can write them, and over TCP that a daemon still holds the lock, so a stale port gets no token. The daemon log is `0600` too. The latest params of an account win, so `Source.account()` must check the key it gets (and raise `Unauthorized` for a bad one): otherwise one watcher with a wrong key would break the account's other watchers.
31
+ - The **catalog** (`KindCatalog`) names the event kinds per resource kind, the groups of the filter options, and the threshold kinds the watcher computes itself. `watch_started`, `watch_degraded` and `watch_ended` are always reported.
32
+
33
+ ## A minimal source and CLI
34
+
35
+ ```python
36
+ # my_cli/watch.py
37
+ from collections.abc import Mapping, Sequence
38
+ from typing import Any
39
+
40
+ import click
41
+
42
+ from cli_watch_kit.app import WatchApp
43
+ from cli_watch_kit.budget import DimensionSpec
44
+ from cli_watch_kit.cli import WatchOptions, daemon_group, run_watch, watch_options
45
+ from cli_watch_kit.events import KindCatalog, RawEvent
46
+ from cli_watch_kit.source import NotFound, Params, PollContext, PollItem, PollOutcome, Source, Target
47
+
48
+ type Snapshot = dict[str, Any]
49
+
50
+
51
+ class IssueSource(Source[Snapshot]):
52
+ catalog = KindCatalog({"issue": ("state_changed",)}, groups={"status": ("state_changed",)})
53
+ dimensions = {
54
+ "requests": DimensionSpec(per_minute=40),
55
+ "complexity": DimensionSpec(per_minute=50_000, burst=10_000),
56
+ }
57
+ batch_cost_cap = {"complexity": 5_000}
58
+
59
+ async def account(self, target: Target, params: Params) -> str:
60
+ return await whoami(params["api_key"]) # the user the key belongs to
61
+
62
+ def batch_key(self, target: Target) -> str:
63
+ return "issues" # every issue of an account in one request
64
+
65
+ def interval(self, target: Target, snapshot: Snapshot | None) -> float:
66
+ return 30.0
67
+
68
+ def cost(self, batch: Sequence[PollItem[Snapshot]]) -> Mapping[str, float]:
69
+ return {"requests": 1, "complexity": 20 * len(batch)}
70
+
71
+ async def poll(self, batch: Sequence[PollItem[Snapshot]], ctx: PollContext) -> Mapping[str, PollOutcome[Snapshot]]:
72
+ found = await fetch_issues(ctx.params["api_key"], [item.target.id for item in batch]) # raise RateLimited etc.
73
+ outcomes = {}
74
+ for item in batch:
75
+ issue = found.get(item.target.id)
76
+ if issue is None:
77
+ outcomes[item.key] = PollOutcome(error=NotFound(f"no issue {item.target.id}"))
78
+ continue
79
+ events = diff(item.snapshot, issue) if item.snapshot is not None else [] # list[RawEvent]
80
+ ended = "completed" if issue["state"] == "Done" else None
81
+ outcomes[item.key] = PollOutcome(issue, events, ended=ended)
82
+ return outcomes
83
+
84
+
85
+ APP = WatchApp(
86
+ name="my-cli-watch",
87
+ source=IssueSource, # or an instance; a callable is called once, when needed
88
+ daemon_module="my_cli.watch_daemon",
89
+ app_protocol=1,
90
+ version="1.0.0",
91
+ status_prefix="my-cli watch: ",
92
+ envelope_tag="my-cli-watcher",
93
+ command="my-cli watch",
94
+ files_dir_name="my-cli", # <scratchpad>/my-cli/issue/ABC-123/events.jsonl; default: the name
95
+ )
96
+
97
+
98
+ @click.group()
99
+ def watch() -> None:
100
+ """Watch issues."""
101
+
102
+
103
+ @watch.command()
104
+ @click.argument("issue_id")
105
+ @watch_options
106
+ def issue(issue_id: str, options: WatchOptions) -> None:
107
+ raise SystemExit(run_watch(APP, Target("issue", issue_id), options, params={"api_key": api_key()}))
108
+
109
+
110
+ watch.add_command(daemon_group(APP))
111
+ ```
112
+
113
+ ```python
114
+ # my_cli/watch_daemon.py: what `python -m my_cli.watch_daemon` runs
115
+ from cli_watch_kit.daemon import main
116
+ from my_cli.watch import APP
117
+
118
+ if __name__ == "__main__":
119
+ main(APP)
120
+ ```
121
+
122
+ `run_watch` also takes `enabled_thresholds` and `timers` (the app's `ClientTimer`s for threshold kinds), `also_subscribe` (kinds the daemon should track for a timer without the watcher reporting them), a `writer` factory for the app's own files in the resource dir (it gets a `WriterContext` with the base and resource dirs, the target, the backend for extra ops and the status output), `resource_dir`, `readme`, `sender_name`, `restart` and extra `header` lines. Only one watcher at a time writes a resource dir: a second watcher of the same target into the same base dir exits with 1 and says so, and runs with its own `--base-dir`. A CLI on another framework fills a `WatchOptions` itself, or uses `cli_watch_kit.client.Watcher` directly; that one takes no lock, so the CLI must keep two watchers of one resource out of the same dir itself.
123
+
124
+ An app with requests the daemon should serve within the budget (fetching a log for a watcher, for example) puts them in `Source.ops`; a watcher calls them with `backend.call(op, payload, params)`. A source whose targets relay other targets (an MR and its head pipeline) returns them from `Source.children`.
125
+
126
+ ## The daemon
127
+
128
+ - The first watcher starts the daemon with `python -m <daemon_module>` under a spawn lock. The daemon forks once more, so a tool that kills the watcher's whole process tree does not kill it, and holds a lock for its lifetime; a second one exits at once.
129
+ - IPC is one NDJSON request and response per connection over a Unix socket under `$XDG_RUNTIME_DIR/<name>/` (or `$TMPDIR`, or the temp dir). Windows, or `<PREFIX>TRANSPORT=tcp`, uses loopback TCP with a token in a private file. The socket name carries the library's and the app's protocol versions (`daemon-l1-a1.sock`), so incompatible daemons never meet.
130
+ - Each watcher polls the daemon every 5 s, which renews its lease; a subscription not renewed for 20 s is dropped. Watchers of one target in one account share one resource, which keeps its last 500 events. The daemon exits 30 s after its last subscription.
131
+ - Each account has a token bucket per budget dimension, refilled at half of `remaining / (reset - now)` once the source reports readings. A 429 (`RateLimited`) blocks the account for its `Retry-After` and backs off exponentially. When the watched resources would exceed any dimension, all their intervals stretch by the same factor. Errors are reported once per kind as `watch_degraded`, with exponential backoff per resource.
132
+ - After a daemon crash, the watcher starts a new daemon and resubscribes with its baseline, so the new daemon reports only what changed meanwhile, and the watcher drops a repeated `watch_started`. When another watcher already brought the resource back, the engine diffs the baseline against the current snapshot with `Source.diff`, so every resubscriber gets the gap; the same holds for a watcher whose lease expired. A resubscribe that fails for a reason that may pass (the API unreachable after a suspend) is retried with a backoff. Leases run on a monotonic clock.
133
+ - **Upgrades:** `hello` returns the library and app versions and a stamp of the installed code (a fingerprint and the newest file time of both packages). A watcher with newer code asks an older daemon to `drain` (stop) and starts a current one; the old daemon's watchers resubscribe from their baselines. A watcher with older code uses a newer daemon as it is. This also covers editable installs, where the code changes without a version.
134
+ - `--no-daemon` runs the same engine and request handler in a thread of the watcher, with a private budget.
135
+ - `--no-daemon` and the daemon build their engine the same way (`Engine.for_app`), from `WatchApp.client_poll_ms` and `lease_timeout` and the environment. For tests, `APP.with_overrides(source=..., client_poll_ms=..., lease_timeout=...)` returns a copy of the app with another source and settings, to run with `WatchOptions(no_daemon=True)`.
136
+ - **A hung daemon** (it holds its lock but answers nothing) is replaced: a watcher whose polls time out 3 times in a row, or that gets no answer to two hellos when it starts, kills it and starts a new one, and `daemon stop` kills one that does not stop within `STOP_TIMEOUT`. It is killed only when its pid is verified: the daemon writes it into its lock file, the lock is held, and the process runs the app's daemon module. Otherwise the watcher exits with an error that says how to stop it. `daemon status` reports such a daemon as running but not answering. On Windows a hung daemon is reported but never killed.
137
+ - Environment variables, with the app's prefix (default: the name in upper case, `-` as `_`, plus `_`): `STATE_DIR`, `BASE_DIR`, `TRANSPORT`, `IDLE_TIMEOUT`, `LEASE_TIMEOUT`, `CLIENT_POLL_MS`, `REQUEST_TIMEOUT` (10 s), `STOP_TIMEOUT` (10 s), `DEBUG`.
138
+
139
+ ## Claude Code
140
+
141
+ With the `claude-code` extra, `--events-stream=auto` (the default) sends the events into the Claude Code session that started the watcher, when that session accepts messages, as `<envelope_tag resource="issue ABC-123" seq="1-2">` blocks. cc-blackbox does the delivery: session lookup, the protocol check, burst batching, the 64 KB cap, the receiver's rate limit, and the end of the watch when the session is gone. The resource dir then lives in the session's scratchpad. Without the extra, `auto` uses stdout, and under Claude Code the header says which extra to install; `claude-message` fails with the same hint. Nothing imports cc-blackbox until a stream needs it.
142
+
143
+ ## Developing
144
+
145
+ ```bash
146
+ uv sync
147
+ uv run ruff check . && uv run ruff format --check . && uv run mypy --strict src tests && uv run pytest
148
+ ```
149
+
150
+ The tests run the engine on a fake clock against a fake source (`tests/fakeapp`), and start real daemon processes in short temp dirs over both transports. CI runs the same checks on Python 3.12 to 3.15.
151
+
152
+ To develop a CLI against a local checkout, add it as an editable path dependency of the CLI:
153
+
154
+ ```toml
155
+ [tool.uv.sources]
156
+ cli-watch-kit = { path = "../cli-watch-kit", editable = true }
157
+ ```
158
+
159
+ ### Commit hooks
160
+
161
+ Fixtures and captured output can carry private identifiers such as workspace, account or issue names, API keys or paths. `scripts/hooks` holds a pre-commit and a commit-msg hook that refuse a commit when a staged line or the commit message matches a private identifier. The identifiers live in a file outside the repository, because listing them here would publish the very strings the hooks exist to keep out. Set it up once per clone:
162
+
163
+ ```bash
164
+ git config core.hooksPath scripts/hooks
165
+ git config hooks.forbiddenPatternsFile ~/.config/git/forbidden-patterns.txt # any path outside the repo
166
+ ```
167
+
168
+ The file holds one extended regex per line, matched case-insensitively; blank lines and `#` comments are ignored. Until `hooks.forbiddenPatternsFile` points at a file with at least one pattern, both hooks refuse every commit and print how to fix it.
169
+
170
+ ## Releasing
171
+
172
+ The version comes from the git tag through hatch-vcs. Pushing a `vX.Y.Z` tag runs `.github/workflows/publish.yml`, which builds the package and publishes it to PyPI through trusted publishing (the `pypi` environment of the GitHub repository must be registered as a trusted publisher on PyPI first).
173
+
174
+ ## License
175
+
176
+ MIT
@@ -0,0 +1,81 @@
1
+ [project]
2
+ name = "cli-watch-kit"
3
+ dynamic = ["version"]
4
+ description = "Build a `watch` command for a CLI: poll a source, report changes as JSON events, share one rate-limited daemon between all watchers"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Filip Procházka", email = "dev@fprochazka.cz" }]
9
+ keywords = ["watch", "polling", "daemon", "cli", "click", "events", "claude-code", "ai-agent"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Environment :: Console",
13
+ "Intended Audience :: Developers",
14
+ "License :: OSI Approved :: MIT License",
15
+ "Operating System :: POSIX :: Linux",
16
+ "Operating System :: MacOS",
17
+ "Operating System :: Microsoft :: Windows",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Programming Language :: Python :: 3.14",
22
+ "Programming Language :: Python :: 3.15",
23
+ "Topic :: Software Development :: Libraries",
24
+ "Typing :: Typed",
25
+ ]
26
+ requires-python = ">=3.12"
27
+ dependencies = [
28
+ "click>=8.1,<9",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ claude-code = [
33
+ "cc-blackbox>=0.11,<0.13",
34
+ ]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/fprochazka/cli-watch-kit"
38
+ Repository = "https://github.com/fprochazka/cli-watch-kit"
39
+ Issues = "https://github.com/fprochazka/cli-watch-kit/issues"
40
+
41
+ [build-system]
42
+ requires = ["hatchling", "hatch-vcs"]
43
+ build-backend = "hatchling.build"
44
+
45
+ [tool.hatch.version]
46
+ source = "vcs"
47
+
48
+ [tool.hatch.version.raw-options]
49
+ # Without a tag yet (a fresh clone, or before the first release), hatch-vcs still needs a version to start from.
50
+ fallback_version = "0.0.0"
51
+
52
+ [tool.hatch.build.targets.wheel]
53
+ packages = ["src/cli_watch_kit"]
54
+
55
+ [dependency-groups]
56
+ dev = [
57
+ "cc-blackbox>=0.11,<0.12",
58
+ "mypy>=1.15",
59
+ "pytest>=8.0",
60
+ "ruff>=0.14",
61
+ ]
62
+
63
+ [tool.ruff]
64
+ line-length = 120
65
+ target-version = "py312"
66
+ src = ["src", "tests"]
67
+
68
+ [tool.ruff.lint]
69
+ select = ["E", "F", "W", "I", "UP", "B", "C4", "SIM"]
70
+
71
+ [tool.ruff.format]
72
+ quote-style = "double"
73
+
74
+ [tool.mypy]
75
+ strict = true
76
+ python_version = "3.12"
77
+ mypy_path = ["src", "tests"]
78
+
79
+ [tool.pytest.ini_options]
80
+ testpaths = ["tests"]
81
+ addopts = "-ra"