cli-svckit 0.1.2__py3-none-any.whl

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.
cli_svckit/testing.py ADDED
@@ -0,0 +1,448 @@
1
+ """Helpers for tools that adopt cli-svckit: a fake participant, temp lease dirs and a conformance check.
2
+
3
+ ``FakeParticipant`` stands in for :class:`~cli_svckit.contract.client.Participant` in controller tests.
4
+ ``assert_conforms`` runs a real participant command through every method it declares and lists every
5
+ contract violation it finds.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ import tempfile
16
+ import time
17
+ import uuid
18
+ from collections.abc import Callable, Iterable
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from cli_svckit.contract.client import CallResult
24
+ from cli_svckit.contract.envelope import (
25
+ CONTRACT_VERSION,
26
+ ERROR_CODES,
27
+ EXIT_BUSY,
28
+ EXIT_FAIL,
29
+ EXIT_OK,
30
+ EXIT_TEMPFAIL,
31
+ EXIT_WARN,
32
+ METHODS,
33
+ Error,
34
+ Op,
35
+ Request,
36
+ SvcError,
37
+ load_schema,
38
+ new_op_id,
39
+ )
40
+ from cli_svckit.coord.lease import LeaseDir
41
+
42
+ __all__ = [
43
+ "ConformanceReport",
44
+ "FakeParticipant",
45
+ "assert_conforms",
46
+ "make_op",
47
+ "temp_lease_dir",
48
+ ]
49
+
50
+
51
+ # --------------------------------------------------------------------------------------------------------------
52
+ # Fakes
53
+ # --------------------------------------------------------------------------------------------------------------
54
+
55
+ Reply = dict[str, Any] | Error | SvcError
56
+
57
+
58
+ class FakeParticipant:
59
+ """A scripted stand-in for ``Participant``: same ``call()``/``describe()`` surface, records every call.
60
+
61
+ ``responses`` is either ``{method: [reply, ...]}`` or a callable ``(method, params) -> reply``. A reply is a
62
+ result dict (an ok answer), or an ``Error``/``SvcError`` (a failed answer; code ``timeout`` also sets
63
+ ``timed_out``). Replies are used in order and the last one repeats. A method with no reply answers
64
+ ``unsupported``; ``describe`` falls back to a generated answer built from ``coordination``.
65
+ A ``prepare`` result with ``state == "busy"`` reports rc 3, like a real participant.
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ name: str,
71
+ responses: dict[str, list[dict[str, Any]]] | Callable[[str, dict[str, Any]], Reply] | None = None,
72
+ fail_policy: str = "open",
73
+ wait_for: str = "interrupted",
74
+ coordination: dict[str, Any] | None = None,
75
+ ) -> None:
76
+ if fail_policy not in ("open", "closed"):
77
+ raise SvcError("invalid", "fail_policy must be 'open' or 'closed'", data={"participant": name})
78
+ self.name = name
79
+ self.responses = responses if responses is not None else {}
80
+ self.fail_policy = fail_policy
81
+ self.wait_for = wait_for
82
+ self.coordination = coordination
83
+ self.cmd: list[str] = ["fake", name]
84
+ self.timeout_s = 120.0
85
+ self.services: list[str] = list((coordination or {}).get("services", []))
86
+ self.calls: list[tuple[str, dict[str, Any]]] = []
87
+ self._counts: dict[str, int] = {}
88
+
89
+ def calls_to(self, method: str) -> list[dict[str, Any]]:
90
+ """Return the params of every recorded call to ``method``, oldest first."""
91
+ return [p for m, p in self.calls if m == method]
92
+
93
+ def _next_reply(self, method: str, params: dict[str, Any]) -> Reply | None:
94
+ if callable(self.responses):
95
+ return self.responses(method, params)
96
+ queue = self.responses.get(method)
97
+ if not queue:
98
+ return None
99
+ index = self._counts.get(method, 0)
100
+ self._counts[method] = index + 1
101
+ return queue[min(index, len(queue) - 1)]
102
+
103
+ def _describe_default(self) -> dict[str, Any]:
104
+ result: dict[str, Any] = {
105
+ "tool": {"name": self.name, "version": "0.0.0"},
106
+ "contract": {"min": CONTRACT_VERSION, "max": CONTRACT_VERSION},
107
+ "methods": sorted({m for m in self.responses if m in METHODS}) if isinstance(self.responses, dict) else [],
108
+ "services": [],
109
+ }
110
+ if self.coordination is not None:
111
+ result["coordination"] = dict(self.coordination)
112
+ return result
113
+
114
+ def call(self, method: str, params: dict[str, Any] | None = None, *, timeout_s: float | None = None) -> CallResult:
115
+ """Record the call and return the scripted ``CallResult`` (never raises)."""
116
+ params = dict(params or {})
117
+ self.calls.append((method, params))
118
+ reply = self._next_reply(method, params)
119
+ if reply is None and method == "describe":
120
+ reply = self._describe_default()
121
+ if reply is None:
122
+ reply = Error("unsupported", f"{method} is not supported by {self.name}")
123
+ return self._result(method, reply)
124
+
125
+ def _result(self, method: str, reply: Reply) -> CallResult:
126
+ from cli_svckit.contract.envelope import Response
127
+
128
+ if isinstance(reply, SvcError):
129
+ reply = reply.to_error()
130
+ if isinstance(reply, Error):
131
+ timed_out = reply.code == "timeout"
132
+ rc = EXIT_TEMPFAIL if timed_out else EXIT_FAIL
133
+ response = None if timed_out else Response(id="", ok=False, error=reply)
134
+ return CallResult(self.name, method, False, response, reply, rc, 0.0, timed_out, self.fail_policy)
135
+ rc = EXIT_BUSY if method == "prepare" and reply.get("state") == "busy" else EXIT_OK
136
+ response = Response(id="", ok=True, result=dict(reply))
137
+ return CallResult(self.name, method, True, response, None, rc, 0.0, False, self.fail_policy)
138
+
139
+ def describe(self, cache: Any = None) -> dict[str, Any] | None:
140
+ """Return the scripted ``describe`` result, or None when it failed. ``cache`` is ignored."""
141
+ res = self.call("describe")
142
+ if res.ok and res.response is not None and isinstance(res.response.result, dict):
143
+ return res.response.result
144
+ return None
145
+
146
+
147
+ # --------------------------------------------------------------------------------------------------------------
148
+ # Small builders
149
+ # --------------------------------------------------------------------------------------------------------------
150
+
151
+
152
+ def temp_lease_dir(tmp_path: str | os.PathLike[str], *, clock: Callable[[], float] = time.time) -> LeaseDir:
153
+ """Return a ready ``LeaseDir`` in a fresh ``leases`` folder under ``tmp_path`` (create dirs included)."""
154
+ lease_dir = LeaseDir(Path(tmp_path) / "leases", clock=clock)
155
+ lease_dir.ensure()
156
+ return lease_dir
157
+
158
+
159
+ def make_op(kind: str = "service.restart", targets: Iterable[str] = ("svc",), **kw: Any) -> Op:
160
+ """Build an ``Op`` with sensible test defaults (starts now, 5 min deadline/expiry); ``kw`` overrides any field."""
161
+ clock = kw.pop("clock", time.time)
162
+ now = clock()
163
+ fields: dict[str, Any] = {
164
+ "id": new_op_id(clock),
165
+ "kind": kind,
166
+ "targets": list(targets),
167
+ "reason": "test",
168
+ "by": {"tool": "example-tool"},
169
+ "started_at": now,
170
+ "deadline": now + 300.0,
171
+ "expires_at": now + 300.0,
172
+ }
173
+ fields.update(kw)
174
+ return Op(**fields)
175
+
176
+
177
+ # --------------------------------------------------------------------------------------------------------------
178
+ # Conformance
179
+ # --------------------------------------------------------------------------------------------------------------
180
+
181
+
182
+ @dataclass
183
+ class ConformanceReport:
184
+ """What ``assert_conforms`` saw: the describe result, per-method results and any violations."""
185
+
186
+ describe: dict[str, Any] | None = None
187
+ methods: list[str] = field(default_factory=list)
188
+ results: dict[str, CallResult] = field(default_factory=dict)
189
+ violations: list[str] = field(default_factory=list)
190
+
191
+ @property
192
+ def ok(self) -> bool:
193
+ """True when no violation was found."""
194
+ return not self.violations
195
+
196
+
197
+ _TYPES: dict[str, tuple[type, ...]] = {
198
+ "object": (dict,),
199
+ "array": (list,),
200
+ "string": (str,),
201
+ "boolean": (bool,),
202
+ "integer": (int,),
203
+ "number": (int, float),
204
+ "null": (type(None),),
205
+ }
206
+
207
+
208
+ def _type_ok(value: Any, name: str) -> bool:
209
+ if name in ("integer", "number") and isinstance(value, bool):
210
+ return False
211
+ return isinstance(value, _TYPES.get(name, (object,)))
212
+
213
+
214
+ def _check_schema(value: Any, schema: dict[str, Any], defs: dict[str, Any], path: str, out: list[str]) -> None:
215
+ """Check ``value`` against the subset of JSON Schema the bundled schemas use; append problems to ``out``."""
216
+ ref = schema.get("$ref")
217
+ if isinstance(ref, str):
218
+ if ref.startswith("#/$defs/") and ref[8:] in defs:
219
+ _check_schema(value, defs[ref[8:]], defs, path, out)
220
+ return # cross-file refs are not followed by the stdlib check
221
+ types = schema.get("type")
222
+ if types is not None:
223
+ names = [types] if isinstance(types, str) else list(types)
224
+ if not any(_type_ok(value, n) for n in names):
225
+ out.append(f"{path}: expected {'|'.join(names)}, got {type(value).__name__}")
226
+ return
227
+ if "enum" in schema and value not in schema["enum"]:
228
+ out.append(f"{path}: {value!r} is not one of {schema['enum']}")
229
+ pattern = schema.get("pattern")
230
+ if isinstance(pattern, str) and isinstance(value, str) and not re.search(pattern, value):
231
+ out.append(f"{path}: {value!r} does not match {pattern}")
232
+ minimum = schema.get("minimum")
233
+ if minimum is not None and _type_ok(value, "number") and value < minimum:
234
+ out.append(f"{path}: {value} is below the minimum {minimum}")
235
+ if isinstance(value, dict):
236
+ for key in schema.get("required", []):
237
+ if key not in value:
238
+ out.append(f"{path}: missing required key {key!r}")
239
+ for key, sub in schema.get("properties", {}).items():
240
+ if key in value:
241
+ _check_schema(value[key], sub, defs, f"{path}.{key}", out)
242
+ extra = schema.get("additionalProperties")
243
+ if isinstance(extra, dict):
244
+ known = schema.get("properties", {})
245
+ for key, item in value.items():
246
+ if key not in known:
247
+ _check_schema(item, extra, defs, f"{path}.{key}", out)
248
+ elif isinstance(value, list) and isinstance(schema.get("items"), dict):
249
+ for i, item in enumerate(value):
250
+ _check_schema(item, schema["items"], defs, f"{path}[{i}]", out)
251
+
252
+
253
+ def _validate(value: Any, def_name: str, schema_file: str, path: str, out: list[str]) -> None:
254
+ """Validate against ``$defs/<def_name>`` of a bundled schema (stdlib check, plus jsonschema when importable)."""
255
+ try:
256
+ doc = load_schema(schema_file)
257
+ except Exception: # noqa: BLE001 - a missing schema file just means nothing to check against
258
+ return
259
+ defs = doc.get("$defs", {})
260
+ if def_name not in defs:
261
+ return
262
+ _check_schema(value, defs[def_name], defs, path, out)
263
+ if out:
264
+ return # the stdlib check already explained what is wrong
265
+ try:
266
+ import jsonschema # type: ignore[import-not-found,import-untyped,unused-ignore]
267
+ except ImportError:
268
+ return
269
+ try:
270
+ jsonschema.validate(value, {"$schema": doc.get("$schema"), "$defs": defs, "$ref": f"#/$defs/{def_name}"})
271
+ except jsonschema.ValidationError as exc:
272
+ out.append(f"{path}: {exc.message}")
273
+ except Exception: # noqa: BLE001 - unresolvable cross-file refs etc.: the stdlib check stands
274
+ return
275
+
276
+
277
+ def _sample_op(contract_kinds: list[str], services: list[str], lease_dir: LeaseDir) -> Op:
278
+ """Build a synthetic op that matches the participant's declared interest, with a lease in a temp dir."""
279
+ kind = next((k.replace("*", "check") for k in contract_kinds), "service.restart")
280
+ target = next((s.replace("*", "check") for s in services), "svc")
281
+ op = make_op(kind=kind, targets=[target], reason="conformance check", by={"tool": "svckit-conformance"})
282
+ return lease_dir.create(op).op
283
+
284
+
285
+ def _sample_params(method: str, op: Op) -> dict[str, Any]:
286
+ safe_flags = {"dry_run": True, "confirm": False, "scope": "all"}
287
+ if method == "doctor":
288
+ return {"fix": False, "deep": False}
289
+ if method in ("install", "uninstall"):
290
+ return dict(safe_flags)
291
+ if method == "prepare":
292
+ return {"op": op.to_dict(), "poll": 0}
293
+ if method == "complete":
294
+ facts = {"targets": {}, "duration_s": 0.0, "waited_s": 0.0, "capped": False, "forced_now": False}
295
+ return {"op": op.to_dict(), "outcome": "aborted", "facts": facts}
296
+ return {}
297
+
298
+
299
+ def _expected_rc(method: str, response: dict[str, Any]) -> int:
300
+ if not response.get("ok"):
301
+ err = response.get("error")
302
+ return EXIT_TEMPFAIL if isinstance(err, dict) and err.get("code") == "timeout" else EXIT_FAIL
303
+ result = response.get("result") or {}
304
+ if method == "prepare" and result.get("state") == "busy":
305
+ return EXIT_BUSY
306
+ if method in ("health", "doctor"):
307
+ return {"warn": EXIT_WARN, "fail": EXIT_FAIL}.get(result.get("status"), EXIT_OK)
308
+ return EXIT_OK
309
+
310
+
311
+ def _run_raw(cmd: list[str], method: str, params: dict[str, Any], timeout_s: float) -> tuple[str, int | None, str, str]:
312
+ """Run ``cmd svc <method> --json`` with a request on stdin; return (request id, rc, stdout, problem)."""
313
+ req = Request(
314
+ method=method,
315
+ params=params,
316
+ id=uuid.uuid4().hex,
317
+ caller={"tool": "svckit-conformance"},
318
+ deadline_ms=int(timeout_s * 1000),
319
+ )
320
+ env = {k: v for k, v in os.environ.items() if not k.startswith("HERMES_KANBAN_")}
321
+ try:
322
+ done = subprocess.run(
323
+ [*cmd, "svc", method, "--json"],
324
+ input=req.to_json() + "\n",
325
+ capture_output=True,
326
+ text=True,
327
+ timeout=timeout_s,
328
+ env=env,
329
+ )
330
+ except subprocess.TimeoutExpired:
331
+ return req.id, None, "", f"timed out after {timeout_s:g}s"
332
+ except (OSError, ValueError) as exc:
333
+ return req.id, None, "", f"cannot run command: {type(exc).__name__}: {exc}"
334
+ return req.id, done.returncode, done.stdout, ""
335
+
336
+
337
+ def _last_json_line(stdout: str) -> Any:
338
+ for line in reversed(stdout.splitlines()):
339
+ line = line.strip()
340
+ if line:
341
+ try:
342
+ obj = json.loads(line)
343
+ except ValueError:
344
+ continue
345
+ if isinstance(obj, dict):
346
+ return obj
347
+ return None
348
+
349
+
350
+ def _check_envelope(
351
+ method: str, rid: str, rc: int | None, stdout: str, problem: str, out: list[str]
352
+ ) -> dict[str, Any] | None:
353
+ label = f"{method}"
354
+ if problem:
355
+ out.append(f"{label}: {problem}")
356
+ return None
357
+ obj = _last_json_line(stdout)
358
+ if obj is None:
359
+ out.append(f"{label}: stdout has no JSON object line (rc={rc})")
360
+ return None
361
+ problems: list[str] = []
362
+ _validate(obj, "response", "envelope", f"{label}.response", problems)
363
+ out.extend(problems)
364
+ if obj.get("id") != rid:
365
+ out.append(f"{label}: response id {obj.get('id')!r} does not echo the request id")
366
+ if isinstance(obj.get("svckit"), str) and obj["svckit"].split(".")[0] != CONTRACT_VERSION.split(".")[0]:
367
+ out.append(f"{label}: response svckit {obj['svckit']!r} has a different major than {CONTRACT_VERSION}")
368
+ if isinstance(obj.get("ok"), bool):
369
+ want = _expected_rc(method, obj)
370
+ if rc != want:
371
+ out.append(f"{label}: exit code {rc}, expected {want} for this response")
372
+ error = obj.get("error")
373
+ if obj.get("ok") is False and isinstance(error, dict) and error.get("code") not in ERROR_CODES:
374
+ out.append(f"{label}: error code {error.get('code')!r} is not one of {list(ERROR_CODES)}")
375
+ return obj
376
+
377
+
378
+ def assert_conforms(
379
+ cmd: list[str], *, methods: Iterable[str] | None = None, timeout_s: float = 30
380
+ ) -> ConformanceReport:
381
+ """Check that ``cmd`` speaks the svckit contract; return a report or raise ``AssertionError`` listing everything.
382
+
383
+ Calls ``describe`` and checks the envelope, the describe shape and that the contract range includes ours. Then
384
+ calls every declared method (or just ``methods``) with safe sample params (``dry_run`` true, ``confirm`` false,
385
+ a synthetic op whose lease lives in a temp dir) and checks each response's envelope, result shape and exit code.
386
+ A declared method answering ``unsupported`` or ``internal`` is a violation; other error codes are accepted.
387
+ """
388
+ report = ConformanceReport()
389
+ out = report.violations
390
+ cmd = list(cmd)
391
+ tmp = tempfile.mkdtemp(prefix="svckit-conformance-")
392
+ try:
393
+ rid, rc, stdout, problem = _run_raw(cmd, "describe", {}, timeout_s)
394
+ obj = _check_envelope("describe", rid, rc, stdout, problem, out)
395
+ result = obj.get("result") if obj else None
396
+ if obj is not None and obj.get("ok") is not True:
397
+ out.append("describe: must succeed (ok: true)")
398
+ if isinstance(result, dict):
399
+ report.describe = result
400
+ problems: list[str] = []
401
+ _validate(result, "result", "describe", "describe.result", problems)
402
+ out.extend(problems)
403
+ contract = result.get("contract")
404
+ if isinstance(contract, dict) and "min" in contract and "max" in contract:
405
+ from cli_svckit.contract.client import negotiate
406
+
407
+ try:
408
+ negotiate(contract)
409
+ except SvcError as exc:
410
+ out.append(f"describe: {exc.message}")
411
+ declared = [m for m in (report.describe or {}).get("methods", []) if isinstance(m, str)]
412
+ for m in declared:
413
+ if m not in METHODS:
414
+ out.append(f"describe: declared method {m!r} is not a contract method")
415
+ if "describe" not in declared and report.describe is not None:
416
+ out.append("describe: methods must include 'describe'")
417
+ wanted = [m for m in declared if m in METHODS and m != "describe"]
418
+ if methods is not None:
419
+ chosen = list(methods)
420
+ wanted = [m for m in chosen if m != "describe"]
421
+ for m in wanted:
422
+ if m not in declared:
423
+ out.append(f"{m}: requested but not declared in describe.methods")
424
+ report.methods = wanted
425
+
426
+ coord = (report.describe or {}).get("coordination")
427
+ coord = coord if isinstance(coord, dict) else {}
428
+ lease_dir = LeaseDir(Path(tmp) / "leases")
429
+ lease_dir.ensure()
430
+ op = _sample_op(list(coord.get("kinds") or []), list(coord.get("services") or []), lease_dir)
431
+ for method in wanted:
432
+ params = _sample_params(method, op)
433
+ rid, rc, stdout, problem = _run_raw(cmd, method, params, timeout_s)
434
+ obj = _check_envelope(method, rid, rc, stdout, problem, out)
435
+ if obj is None:
436
+ continue
437
+ error = obj.get("error") if isinstance(obj.get("error"), dict) else {}
438
+ if obj.get("ok") is True:
439
+ problems = []
440
+ _validate(obj.get("result"), "result", method, f"{method}.result", problems)
441
+ out.extend(problems)
442
+ elif error.get("code") in ("unsupported", "internal"):
443
+ out.append(f"{method}: declared but answered error {error.get('code')!r}: {error.get('message')}")
444
+ finally:
445
+ shutil.rmtree(tmp, ignore_errors=True)
446
+ if out:
447
+ raise AssertionError(f"{len(out)} contract violation(s) for {cmd}:\n" + "\n".join(f" - {v}" for v in out))
448
+ return report
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.5
2
+ Name: cli-svckit
3
+ Version: 0.1.2
4
+ Summary: Toolkit for CLIs that ship local services: lifecycle, CLI install, a JSON contract and restart/update coordination.
5
+ Project-URL: Homepage, https://github.com/ejlevin1/cli-svckit
6
+ Project-URL: Issues, https://github.com/ejlevin1/cli-svckit/issues
7
+ Author: ejlevin1
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: cli,coordination,launchd,services,systemd,typer
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: System :: Systems Administration
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.11
20
+ Provides-Extra: rich
21
+ Requires-Dist: rich>=13; extra == 'rich'
22
+ Provides-Extra: typer
23
+ Requires-Dist: rich>=13; extra == 'typer'
24
+ Requires-Dist: typer>=0.12; extra == 'typer'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # cli-svckit
28
+
29
+ A small toolkit for command-line tools that ship local background services, so that one controller can
30
+ manage a whole set of them the same way.
31
+
32
+ > **Status: 0.1.0 (phase 0).** The contract and the coordination layer work today. Install from the git tag:
33
+ >
34
+ > ```sh
35
+ > pip install "cli-svckit @ git+https://github.com/ejlevin1/cli-svckit@v0.1.0"
36
+ > ```
37
+
38
+ Compatibility guarantees for the contract, lease format and Python API: [docs/compatibility.md](docs/compatibility.md).
39
+
40
+ ## What works now
41
+
42
+ - **The JSON contract** (`cli_svckit.contract`): every participating tool answers
43
+ `<tool> svc describe|health|doctor|install|uninstall|prepare|complete --json` with one versioned envelope
44
+ (`Request`, `Response`, `Error`, exit codes, JSON Schemas). `server.run` serves a provider object;
45
+ `client.Participant` calls a tool and `discovery` finds participants. Spec: [docs/contract.md](docs/contract.md).
46
+ - **Lease coordination** (`cli_svckit.coord`): before a disruptive operation the controller writes a durable lease
47
+ file; leases expire, so a controller that dies never freezes anyone. `LeaseDir`, `Lease`.
48
+ - **Watcher** (`coord.watch.LeaseWatcher`): kqueue, inotify or polling, with a callback after every change.
49
+ - **Controller** (`coord.controller.Operation`): a context manager that writes the lease, calls `prepare` until
50
+ every relevant participant is ready (or a cap is hit), runs your action, then calls `complete`.
51
+ - **Participant helpers** (`coord.participant`): `Interest` and `Quiescer` turn watcher events into one
52
+ `on_prepare` and one `on_complete` per operation, and survive daemon restarts.
53
+ - **Health and doctor** (`cli_svckit.health`, `cli_svckit.doctor`): health results, HTTP/port/pid probes, a doctor
54
+ runner with exit codes.
55
+ - **rc-file install** (`cli_svckit.rcfile`, `cli_svckit.receipts`): one marked line in a shell rc file or a
56
+ symlink on `PATH`; removal backs up first and refuses if the line was edited.
57
+ - **Testing helpers** (`cli_svckit.testing`): `FakeParticipant`, `temp_lease_dir`, `assert_conforms`.
58
+
59
+ ## Not yet
60
+
61
+ - launchd and systemd service backends (a declarative service spec rendered to the host's service manager).
62
+ - Rich renderers for health and doctor tables.
63
+ - A PyPI release (install from the git tag for now).
64
+
65
+ ## A participant in about 20 lines
66
+
67
+ A daemon that pauses its work while an `update` of its service is in progress. The `svc` entry point answers the
68
+ controller's `prepare` and `complete` calls; the lease watcher covers the case where nobody calls it.
69
+
70
+ ```python
71
+ import sys
72
+ from cli_svckit.contract.server import run
73
+ from cli_svckit.coord.lease import LeaseDir
74
+ from cli_svckit.coord.participant import Interest, Quiescer
75
+ from cli_svckit.coord.watch import LeaseWatcher
76
+
77
+ class Provider:
78
+ def describe(self, params):
79
+ return {"tool": {"name": "example-tool", "version": "1.0"},
80
+ "coordination": {"kinds": ["update"], "services": ["com.example.*"], "watches_lease": True}}
81
+ def prepare(self, params):
82
+ return {"state": "ready", "op_id": params["op"]["id"], "quiesced": True, "in_flight": []}
83
+ def complete(self, params):
84
+ return {"state": "resumed", "actions": []}
85
+
86
+ def daemon(lease_path):
87
+ leases = LeaseDir(lease_path)
88
+ leases.ensure()
89
+ q = Quiescer(leases, Interest(["update"], ["com.example.*"]),
90
+ on_prepare=lambda lease: print("pausing for", lease.op.id),
91
+ on_complete=lambda lease: print("resuming:", lease.outcome))
92
+ q.catch_up()
93
+ LeaseWatcher(leases.path, q.refresh).start()
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(run(Provider(), sys.argv[2:])) # example-tool svc <method> --json
97
+ ```
98
+
99
+ A longer, runnable version is `examples/toy_participant.py`.
100
+
101
+ ## A controller in about 15 lines
102
+
103
+ ```python
104
+ import os
105
+ from cli_svckit.contract.client import Participant
106
+ from cli_svckit.coord.controller import Operation
107
+ from cli_svckit.coord.lease import LeaseDir
108
+
109
+ leases = LeaseDir(os.path.expanduser("~/.local/state/example-tool/leases"))
110
+ workers = [Participant("example-tool", ["example-tool"])]
111
+
112
+ op = Operation("update", ["com.example.worker"], lease_dir=leases, participants=workers,
113
+ reason="upgrade to 1.4.0", by={"tool": "example-tool", "user": "alice"},
114
+ max_wait_s=300, on_cap="proceed")
115
+ with op: # writes the lease, calls prepare until ready, sets phase running
116
+ restart_service("com.example.worker") # your code
117
+ op.facts["new_version"] = "1.4.0" # stored on the lease and passed to complete
118
+ # leaving the block calls complete on each participant and moves the lease to done/
119
+ ```
120
+
121
+ `restart_service` stands for your own code. If it raises, the operation ends with outcome `failed`. If participants
122
+ are not ready at the cap and `on_cap="abort"`, `OperationAborted` is raised and the lease ends as `aborted`.
123
+
124
+ ## Further reading
125
+
126
+ - [docs/design.md](docs/design.md): why hooks plus a lease directory, and the semantics.
127
+ - [docs/coordination.md](docs/coordination.md): the full prepare, run, complete sequence and the lease file.
128
+ - [docs/contract.md](docs/contract.md): the wire contract.
129
+
130
+ ## Design rules
131
+
132
+ - Generic: every name, label, path, host and port comes from the consuming tool. Nothing site-specific
133
+ lives here.
134
+ - Small: launchd and systemd remain the supervisors. The library renders specs and talks to them; it is
135
+ not a process manager.
136
+ - Python 3.11+, zero runtime dependencies in the core.
137
+
138
+ ## Development
139
+
140
+ ```sh
141
+ uv sync
142
+ scripts/install-hooks.sh # once per clone: secret + system-info checks on commit and push
143
+ uv run pytest -q
144
+ uv run ruff check
145
+ ```
146
+
147
+ See [CONTRIBUTING.md](CONTRIBUTING.md) and [SECURITY.md](SECURITY.md).
148
+
149
+ ## License
150
+
151
+ [MIT](LICENSE)
@@ -0,0 +1,32 @@
1
+ cli_svckit/__init__.py,sha256=AQq0RLVM-PpYNtpFO0ZIYV7_P8h1xeL7EDSKaXkKzLo,1590
2
+ cli_svckit/doctor.py,sha256=LiAZYMEZ9Wp3CayQpPsG5grrzYOIpa6hAtnapbRcdow,4365
3
+ cli_svckit/health.py,sha256=pJYWkZ2XFml7-ZXuQauRQBiiWWJPFww6y6TVEyD8SJU,5648
4
+ cli_svckit/procs.py,sha256=wen5olpPdaHshn0zyXRSY4PP3CoP6-3Pi7WY8FgzGac,4689
5
+ cli_svckit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ cli_svckit/rcfile.py,sha256=Eqys_0KksD0sPMJsuxFms9a5ZnMkYLsg4ofFHdXH6sI,12170
7
+ cli_svckit/receipts.py,sha256=kKVofoNSscAPQap5J5hpOfIdrWp5q-Zo1GPYnlBh-84,2339
8
+ cli_svckit/testing.py,sha256=f5PoOjETSPDBUhKR-7QzH-aZdxcQokwn337HAC2ykPY,19276
9
+ cli_svckit/contract/__init__.py,sha256=zJrOd9q4bLQnF1kkdwOwKlP5lYaH74w-yZckcVt9m3I,797
10
+ cli_svckit/contract/argparse_cli.py,sha256=4aekot0ChUc2VS0XIOfqaaHIYTYiPTjQw-Nim_vC3SM,1393
11
+ cli_svckit/contract/client.py,sha256=nJ3axrgtiMmmQnE1QBcJfDq4ar_vKzTXRc7njhcDs_c,10908
12
+ cli_svckit/contract/discovery.py,sha256=_XCCfcFR_V-kHOe9vHjkhfKu_oUThxO-7_jc3wIlLfQ,3167
13
+ cli_svckit/contract/envelope.py,sha256=Y9UQ279ip_WfDURBc6AvLnRLi-aUfV9pqphLmITVDPE,12998
14
+ cli_svckit/contract/server.py,sha256=BAODUZlht3T5CGafr0nBeRvSQzlUhLsdwkR4K1UfdVw,6182
15
+ cli_svckit/contract/typer_cli.py,sha256=4j7m9Z4D6_6RzPJjXDYZVK-hK4Hasl1F99K7pCPQ9fI,1247
16
+ cli_svckit/contract/schemas/complete.json,sha256=kw3qX_tw3G4WTELhThTMJWw162b1MqUCNuu19L20oOU,2436
17
+ cli_svckit/contract/schemas/describe.json,sha256=De_DCJpJ8xrkDUN5HJ395yDhZWDUCTS7Ih42u8fEEvA,3201
18
+ cli_svckit/contract/schemas/doctor.json,sha256=jUNS5sdMC2Hb3BsIvQYiaiWCMiJstR4zC0pLjK1botQ,1685
19
+ cli_svckit/contract/schemas/envelope.json,sha256=HtmOYxV6tk3TVJiBGXSsUquY_j8s1_YH2MhxDP9_qas,2634
20
+ cli_svckit/contract/schemas/health.json,sha256=DYBfpDustvnTiQTs_Gr_m3AvkkBMRn_DxEwtNfEy43o,1553
21
+ cli_svckit/contract/schemas/install.json,sha256=ioD65gvYptATWM7qb-PldBUYoAFkWIpUYGoGQ72E0g8,2071
22
+ cli_svckit/contract/schemas/lease.json,sha256=y7o5tkTe1WWjQJ_FXRyJrHPrzDwioI-xvwO1_Y3aJHo,2176
23
+ cli_svckit/contract/schemas/prepare.json,sha256=QQK_AEDM_DXKzRj19PPJNqaSn9nK3w1vbKlqbsjvU20,1783
24
+ cli_svckit/coord/__init__.py,sha256=dsMvrmRZ9Htgs4jJdFYNY0QnRwl_UI3mgYpnP6PES-4,111
25
+ cli_svckit/coord/controller.py,sha256=1fq8cKiGOq9A7Gafu1PQ57pajkIqsbRJjox85dfMKXA,14718
26
+ cli_svckit/coord/lease.py,sha256=K75lsP-38bwfLajcW5WiOYNutyZ-gp0agWw3mAdVSFc,18475
27
+ cli_svckit/coord/participant.py,sha256=x9qzzqf9BRHgaXZl1X38z4W-kX12MkIXsfExfTv5x9Q,9951
28
+ cli_svckit/coord/watch.py,sha256=Xkh54BD8xr2_M8LJJANqqsb1l19WuyAR4NfSM8VuBVI,13648
29
+ cli_svckit-0.1.2.dist-info/METADATA,sha256=QkHvGkHO9TklgLuUlJQ6U1tebY1ixCnH--DNmx3mtGQ,6734
30
+ cli_svckit-0.1.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
31
+ cli_svckit-0.1.2.dist-info/licenses/LICENSE,sha256=WF7YCXjH3-P4Xl6BFggzLmyDSaP3xmjXzAXnScAKQNo,1065
32
+ cli_svckit-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ejlevin1
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.