compactlab 0.2.0__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.
- compactlab/__init__.py +3 -0
- compactlab/adapters/__init__.py +2 -0
- compactlab/adapters/base.py +212 -0
- compactlab/adapters/cache.py +396 -0
- compactlab/adapters/claude_code.py +226 -0
- compactlab/adapters/codex.py +298 -0
- compactlab/adapters/dsh.py +287 -0
- compactlab/adapters/gemini_cli.py +259 -0
- compactlab/adapters/opencode.py +375 -0
- compactlab/apply/__init__.py +582 -0
- compactlab/cli/__init__.py +5 -0
- compactlab/cli/main.py +2436 -0
- compactlab/data/config_knobs.json +158 -0
- compactlab/data/harness_defaults.json +72 -0
- compactlab/data/harness_formats.json +300 -0
- compactlab/data/pricing.json +51 -0
- compactlab/engine/__init__.py +138 -0
- compactlab/engine/live.py +306 -0
- compactlab/engine/settings.py +175 -0
- compactlab/engine/watch.py +82 -0
- compactlab/eval/__init__.py +1 -0
- compactlab/eval/deep.py +390 -0
- compactlab/eval/executors.py +84 -0
- compactlab/eval/factcheck.py +75 -0
- compactlab/lens.py +80 -0
- compactlab/model/__init__.py +285 -0
- compactlab/pricing/__init__.py +211 -0
- compactlab/pricing/auto.py +118 -0
- compactlab/pricing/ids.py +148 -0
- compactlab/pricing/refresh.py +299 -0
- compactlab/publish.py +125 -0
- compactlab/py.typed +0 -0
- compactlab/recommend/__init__.py +201 -0
- compactlab/recommend/claude_code.py +172 -0
- compactlab/recommend/codex.py +104 -0
- compactlab/recommend/dsh.py +89 -0
- compactlab/recommend/gemini_cli.py +85 -0
- compactlab/recommend/opencode.py +117 -0
- compactlab/recommend/units.py +63 -0
- compactlab/report/__init__.py +3 -0
- compactlab/report/html.py +27 -0
- compactlab/report/template.html +1189 -0
- compactlab/service/__init__.py +1 -0
- compactlab/service/core.py +220 -0
- compactlab/service/http.py +133 -0
- compactlab/service/lock.py +92 -0
- compactlab/service/policy.py +258 -0
- compactlab/service/schedule.py +212 -0
- compactlab/share.py +553 -0
- compactlab/sim/__init__.py +1 -0
- compactlab/sim/baseline.py +214 -0
- compactlab/sim/calibrate.py +108 -0
- compactlab/sim/engine.py +1130 -0
- compactlab/sim/select.py +238 -0
- compactlab/sim/timing.py +134 -0
- compactlab/synth.py +416 -0
- compactlab/term/__init__.py +0 -0
- compactlab/term/style.py +134 -0
- compactlab/term/top.py +531 -0
- compactlab/term/views.py +598 -0
- compactlab/term/widgets.py +238 -0
- compactlab/verify.py +462 -0
- compactlab-0.2.0.dist-info/METADATA +243 -0
- compactlab-0.2.0.dist-info/RECORD +67 -0
- compactlab-0.2.0.dist-info/WHEEL +4 -0
- compactlab-0.2.0.dist-info/entry_points.txt +2 -0
- compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Pre-authorized auto-apply: stored consent, anti-flapping rules, manual-edit detection, change journal.
|
|
2
|
+
|
|
3
|
+
Nothing here writes a settings file directly: an accepted decision goes through compactlab.apply (backup, atomic
|
|
4
|
+
write, manifest that `compactlab revert` understands).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
from dataclasses import asdict, dataclass, field
|
|
13
|
+
from datetime import date
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from .. import apply as ap
|
|
18
|
+
from ..sim.engine import GLOBAL_KEY_HARNESSES
|
|
19
|
+
from ..sim.select import PROFILE_NAMES, PROFILES
|
|
20
|
+
|
|
21
|
+
CONSENT_VERSION = 1
|
|
22
|
+
KEYS = {"claude-code": ["modelSettings.*.autoCompactWindow"], "codex": [ap.CODEX_KEY]}
|
|
23
|
+
# flags that mean the pick cannot be trusted for an unattended change
|
|
24
|
+
UNSAFE_FLAGS = {"recall_floor_not_met", "wait_cap_unreachable", "min_window_unreachable", "wait_over_cap"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Consent:
|
|
29
|
+
"""What the person allowed: one harness settings file, these models, this profile."""
|
|
30
|
+
|
|
31
|
+
harness: str
|
|
32
|
+
file: str
|
|
33
|
+
models: list[str]
|
|
34
|
+
profile: str = "balanced"
|
|
35
|
+
created: str = field(default_factory=lambda: date.today().isoformat())
|
|
36
|
+
expires: str | None = None
|
|
37
|
+
version: int = CONSENT_VERSION
|
|
38
|
+
|
|
39
|
+
def preauth(self) -> ap.Preauth:
|
|
40
|
+
lo, hi = ap.CLAUDE_LIMITS
|
|
41
|
+
t = ap.Target(self.harness, ap._p(self.file), list(KEYS[self.harness]), list(self.models), lo, hi)
|
|
42
|
+
return ap.Preauth([t], allow_retune=True, source="consent")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def save_consent(path: Path, c: Consent) -> None:
|
|
46
|
+
if c.harness not in KEYS:
|
|
47
|
+
raise ap.ApplyError(f"consent: unknown harness {c.harness!r}")
|
|
48
|
+
if c.profile not in PROFILE_NAMES:
|
|
49
|
+
raise ap.ApplyError(f"consent: unknown profile {c.profile!r}")
|
|
50
|
+
if not c.models:
|
|
51
|
+
raise ap.ApplyError("consent: name at least one model")
|
|
52
|
+
c.file = str(ap._p(c.file)) # absolute now: a relative path would later resolve against the scheduler's cwd
|
|
53
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
path.write_text(json.dumps(asdict(c), indent=2))
|
|
55
|
+
path.chmod(0o600)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def load_consent(path: Path) -> Consent:
|
|
59
|
+
if not path.exists():
|
|
60
|
+
raise ap.ApplyError(f"no consent file at {path}; create one with: compactlab consent set ...")
|
|
61
|
+
try:
|
|
62
|
+
d = json.loads(path.read_text())
|
|
63
|
+
if d.get("version") != CONSENT_VERSION:
|
|
64
|
+
raise ap.ApplyError("consent file: unsupported version")
|
|
65
|
+
c = Consent(
|
|
66
|
+
**{k: d[k] for k in ("harness", "file", "models", "profile", "created", "expires", "version") if k in d}
|
|
67
|
+
)
|
|
68
|
+
if c.expires and date.fromisoformat(c.expires) < date.today():
|
|
69
|
+
raise ap.ApplyError("consent file has expired")
|
|
70
|
+
except (ValueError, TypeError, AttributeError, OSError) as e:
|
|
71
|
+
raise ap.ApplyError(f"consent file {path} is unreadable: {e}") from e
|
|
72
|
+
if c.harness not in KEYS or c.profile not in PROFILE_NAMES:
|
|
73
|
+
raise ap.ApplyError("consent file: unknown harness or profile")
|
|
74
|
+
if not isinstance(c.file, str) or not os.path.isabs(os.path.expanduser(c.file)):
|
|
75
|
+
raise ap.ApplyError(f"consent file: {c.file!r} is not an absolute path; set the consent again")
|
|
76
|
+
return c
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Rules:
|
|
81
|
+
"""Anti-flapping settings. Defaults are deliberately slow: a setting moves at most weekly, in small steps."""
|
|
82
|
+
|
|
83
|
+
min_days: float = 7.0
|
|
84
|
+
min_turns: int = 500
|
|
85
|
+
dead_band: int = 25_000 # moves within one grid step plus this are ignored
|
|
86
|
+
min_benefit_pct: float = 2.0 # of the current list-price cost per day...
|
|
87
|
+
min_benefit_min: float = 2.0 # ...or this many minutes per day
|
|
88
|
+
max_step: int = 100_000
|
|
89
|
+
cooldown_s: float = 7 * 86400.0
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class Decision:
|
|
94
|
+
model: str
|
|
95
|
+
action: str # "apply" | "skip" | "notify"
|
|
96
|
+
reason: str
|
|
97
|
+
current: int | None = None
|
|
98
|
+
target: int | None = None
|
|
99
|
+
value: int | None = None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _idx(grid: list[int], v: int) -> int:
|
|
103
|
+
return min(range(len(grid)), key=lambda i: abs(grid[i] - v))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def decide(
|
|
107
|
+
g: dict[str, Any],
|
|
108
|
+
profile: str,
|
|
109
|
+
current: int | None,
|
|
110
|
+
last_written: int | None,
|
|
111
|
+
last_applied_at: float | None,
|
|
112
|
+
now: float,
|
|
113
|
+
rules: Rules,
|
|
114
|
+
force: bool = False,
|
|
115
|
+
) -> Decision:
|
|
116
|
+
"""Whether to move one model's setting, to what, and why not. `current` is what the settings file holds now
|
|
117
|
+
(None: not set, so the harness default applies); `last_written` is what compactlab last wrote there."""
|
|
118
|
+
m = g["model"]
|
|
119
|
+
p = g["profiles"][profile]
|
|
120
|
+
target = int(p["threshold"])
|
|
121
|
+
d = Decision(m, "skip", "", current, target)
|
|
122
|
+
if g["days"] < rules.min_days or g["n_turns"] < rules.min_turns:
|
|
123
|
+
need = f"{rules.min_days:g} days / {rules.min_turns} turns"
|
|
124
|
+
d.reason = f"too little history ({g['days']:.1f} days, {g['n_turns']} turns; need {need})"
|
|
125
|
+
return d
|
|
126
|
+
tm = g.get("time_model") or {}
|
|
127
|
+
if tm.get("compact_source") == "prior" or tm.get("turn_source") == "prior":
|
|
128
|
+
d.reason = "time model is a prior (no usable timing data): low confidence"
|
|
129
|
+
return d
|
|
130
|
+
bad = UNSAFE_FLAGS.intersection(p["flags"])
|
|
131
|
+
if bad:
|
|
132
|
+
d.reason = "profile flags " + ", ".join(sorted(bad))
|
|
133
|
+
return d
|
|
134
|
+
if g["comparison"][profile]["action"] in ("no action needed", "keep default") and current is None:
|
|
135
|
+
d.reason = g["comparison"][profile]["action"]
|
|
136
|
+
return d
|
|
137
|
+
if g["comparison"][profile]["action"] == "keep current":
|
|
138
|
+
d.reason = "keep current: the pick is within the tolerance of the current setting"
|
|
139
|
+
return d
|
|
140
|
+
if last_written is not None and current != last_written and not force:
|
|
141
|
+
d.action = "notify"
|
|
142
|
+
d.reason = f"edited by someone else (now {current!r}, compactlab last wrote {last_written}); not overwriting"
|
|
143
|
+
return d
|
|
144
|
+
if last_applied_at is not None and now - last_applied_at < rules.cooldown_s and not force:
|
|
145
|
+
d.reason = f"cooldown: last applied {(now - last_applied_at) / 86400:.1f} days ago"
|
|
146
|
+
return d
|
|
147
|
+
grid = g["grid"]
|
|
148
|
+
step = grid[1] - grid[0] if len(grid) > 1 else 25_000
|
|
149
|
+
cur_eff = current if current is not None else int(g["default"]["threshold"])
|
|
150
|
+
if abs(target - cur_eff) < step + rules.dead_band:
|
|
151
|
+
d.reason = f"within the dead-band ({cur_eff} -> {target})"
|
|
152
|
+
return d
|
|
153
|
+
# move at most max_step toward the target, on the grid
|
|
154
|
+
# (grid points beyond max_step, or on the wrong side, are not candidates: rounding must not overshoot the limit)
|
|
155
|
+
move = max(-rules.max_step, min(rules.max_step, target - cur_eff))
|
|
156
|
+
sign = 1 if move > 0 else -1
|
|
157
|
+
reach = [x for x in grid if 0 < (x - cur_eff) * sign <= rules.max_step]
|
|
158
|
+
if not reach:
|
|
159
|
+
d.reason = f"no grid point within {rules.max_step} of {cur_eff} toward {target}"
|
|
160
|
+
return d
|
|
161
|
+
value = min(reach, key=lambda x: abs(x - (cur_eff + move)))
|
|
162
|
+
i, j = grid.index(value), _idx(grid, cur_eff)
|
|
163
|
+
days = max(float(g["days"]), 1.0)
|
|
164
|
+
d_usd = (g["combined_cost"][j] - g["combined_cost"][i]) / days
|
|
165
|
+
d_min = (g["time_s"][j] - g["time_s"][i]) / 60 / days
|
|
166
|
+
cost_day = g["combined_cost"][j] / days
|
|
167
|
+
if d_usd < cost_day * rules.min_benefit_pct / 100 and d_min < rules.min_benefit_min:
|
|
168
|
+
d.reason = f"benefit too small ({d_usd:+.2f} $/day, {d_min:+.1f} min/day)"
|
|
169
|
+
return d
|
|
170
|
+
# each step stays inside the profile's guardrails, or (when the current setting is already outside them, as a
|
|
171
|
+
# default above the recall floor's reach can be) at least moves strictly toward them
|
|
172
|
+
spec = PROFILES[profile]
|
|
173
|
+
floor = g["recommendation"]["recall_floor"]
|
|
174
|
+
dflt = g["default"]
|
|
175
|
+
|
|
176
|
+
def wait(k: int) -> float:
|
|
177
|
+
extra = g["time_compact_s"][k] + g["time_redisc_s"][k] - dflt["time_compact_s"] - dflt["time_redisc_s"]
|
|
178
|
+
return float(extra) / 60 / days
|
|
179
|
+
|
|
180
|
+
recall_ok = g["recall"][i] >= floor or g["recall"][i] > g["recall"][j]
|
|
181
|
+
wait_ok = not spec["enforce_wait_cap"] or wait(i) <= p["wait_cap_min_per_day"] or wait(i) < wait(j)
|
|
182
|
+
floor_ok = value >= p["min_threshold"] or value > cur_eff
|
|
183
|
+
if not (recall_ok and wait_ok and floor_ok):
|
|
184
|
+
d.reason = f"{value} would break the {profile} guardrails"
|
|
185
|
+
return d
|
|
186
|
+
d.action, d.value = "apply", value
|
|
187
|
+
d.reason = f"{cur_eff} -> {value} (target {target}): saves ${d_usd:.2f}/day, {d_min:.1f} min/day (- = adds)"
|
|
188
|
+
return d
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# ---------- state: what compactlab last wrote, and the journal ----------
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def load_applied(path: Path) -> dict[str, Any]:
|
|
195
|
+
return json.loads(path.read_text()) if path.exists() else {}
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def journal(path: Path, entry: dict[str, Any]) -> None:
|
|
199
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
200
|
+
with path.open("a") as f:
|
|
201
|
+
f.write(json.dumps({"at": time.time(), **entry}) + "\n")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def run_auto_apply(
|
|
205
|
+
result: dict[str, Any],
|
|
206
|
+
consent: Consent,
|
|
207
|
+
state_dir: Path,
|
|
208
|
+
rules: Rules,
|
|
209
|
+
now: float,
|
|
210
|
+
dry_run: bool = False,
|
|
211
|
+
force: bool = False,
|
|
212
|
+
) -> dict[str, Any]:
|
|
213
|
+
"""Decide per consented model; write the accepted changes through compactlab.apply (backup + manifest)."""
|
|
214
|
+
applied_path = state_dir / "service" / "applied.json"
|
|
215
|
+
applied = load_applied(applied_path)
|
|
216
|
+
pre = consent.preauth()
|
|
217
|
+
file = pre.targets[0].file
|
|
218
|
+
decisions: list[Decision] = []
|
|
219
|
+
for g in result["groups"]:
|
|
220
|
+
if g["role"] != "main" or g["harness"] != consent.harness:
|
|
221
|
+
continue
|
|
222
|
+
if not ap.model_allowed(consent.harness, g["model"], consent.models):
|
|
223
|
+
continue
|
|
224
|
+
mk = ap.model_key(consent.harness, g["model"]) # the key the settings file uses for this model
|
|
225
|
+
cur = ap._read_current(file, consent.harness, mk)
|
|
226
|
+
cur = cur if isinstance(cur, int) else None
|
|
227
|
+
rec = applied.get(f"{file}::{mk}") or applied.get(f"{file}::{g['model']}", {})
|
|
228
|
+
d = decide(g, consent.profile, cur, rec.get("value"), rec.get("at"), now, rules, force)
|
|
229
|
+
d.model = mk
|
|
230
|
+
decisions.append(d)
|
|
231
|
+
todo = [{"harness": consent.harness, "model": d.model, "value": d.value} for d in decisions if d.action == "apply"]
|
|
232
|
+
if consent.harness in GLOBAL_KEY_HARNESSES: # one setting for every model: the models agree on it, write it once
|
|
233
|
+
todo = todo[:1]
|
|
234
|
+
out: dict[str, Any] = {
|
|
235
|
+
"decisions": [asdict(d) for d in decisions],
|
|
236
|
+
"dry_run": dry_run,
|
|
237
|
+
"diff": "",
|
|
238
|
+
"manifest": None,
|
|
239
|
+
}
|
|
240
|
+
if not todo:
|
|
241
|
+
return out
|
|
242
|
+
changes, rejected = ap.plan_changes(todo, pre)
|
|
243
|
+
out["rejected"] = rejected
|
|
244
|
+
if not changes:
|
|
245
|
+
return out
|
|
246
|
+
out["diff"] = ap.diff_text(ap.render(changes))
|
|
247
|
+
if dry_run:
|
|
248
|
+
return out
|
|
249
|
+
manifest = ap.write_changes(changes, state_dir, pre)
|
|
250
|
+
out["manifest"] = str(manifest)
|
|
251
|
+
for c in changes:
|
|
252
|
+
applied[f"{c.file}::{c.model}"] = {"value": c.new, "at": now, "manifest": manifest.stem}
|
|
253
|
+
journal(state_dir / "service" / "journal.jsonl",
|
|
254
|
+
{"model": c.model, "file": str(c.file), "key": c.key, "old": c.old, "new": c.new,
|
|
255
|
+
"manifest": manifest.stem, "profile": consent.profile}) # fmt: skip
|
|
256
|
+
applied_path.parent.mkdir(parents=True, exist_ok=True)
|
|
257
|
+
applied_path.write_text(json.dumps(applied, indent=2))
|
|
258
|
+
return out
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Calibration intervals and the OS scheduler files (launchd LaunchAgent, systemd user units).
|
|
2
|
+
|
|
3
|
+
Only text is generated here. `install` writes the unit files into the user's own LaunchAgents or systemd user folder,
|
|
4
|
+
after the caller has shown the diff and had it confirmed; it never runs launchctl or systemctl.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import difflib
|
|
10
|
+
import re
|
|
11
|
+
import shlex
|
|
12
|
+
import sys
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from xml.sax.saxutils import escape
|
|
16
|
+
|
|
17
|
+
UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 7 * 86400}
|
|
18
|
+
MIN_EVERY_S = 60
|
|
19
|
+
MARKER = "generated by compactlab schedule"
|
|
20
|
+
LABEL = "com.compactlab.agent"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_every(text: str) -> float | None:
|
|
24
|
+
"""'6h', '1d', '90m', '2w', '45s' -> seconds; 'off' -> None (manual only). At least 60 s."""
|
|
25
|
+
t = text.strip().lower()
|
|
26
|
+
if t in ("off", "never", "manual", "0"):
|
|
27
|
+
return None
|
|
28
|
+
m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([smhdw])", t)
|
|
29
|
+
if not m:
|
|
30
|
+
raise ValueError(f"interval {text!r}: use a number with s, m, h, d or w (e.g. 6h, 1d, 7d), or 'off'")
|
|
31
|
+
secs = float(m.group(1)) * UNITS[m.group(2)]
|
|
32
|
+
if secs < MIN_EVERY_S:
|
|
33
|
+
raise ValueError(f"interval {text!r} is under {MIN_EVERY_S} s")
|
|
34
|
+
return secs
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def fmt_every(secs: float | None) -> str:
|
|
38
|
+
if secs is None:
|
|
39
|
+
return "off"
|
|
40
|
+
for u in ("w", "d", "h", "m"):
|
|
41
|
+
if secs >= UNITS[u] and secs % UNITS[u] == 0:
|
|
42
|
+
return f"{int(secs // UNITS[u])}{u}"
|
|
43
|
+
return f"{int(secs)}s"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def backoff(every: float | None, failures: int, base: float = 300.0) -> float:
|
|
47
|
+
"""Wait after `failures` consecutive failed runs: 5 min doubling, never longer than the interval (or 1 day)."""
|
|
48
|
+
cap = every if every is not None else 86400.0
|
|
49
|
+
return min(cap, base * 2 ** max(failures - 1, 0))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def next_due(every: float | None, last_ok: float | None, last_attempt: float | None, failures: int,
|
|
53
|
+
now: float) -> float | None: # fmt: skip
|
|
54
|
+
"""When the next scheduled calibration is due (epoch seconds), or None when scheduling is off.
|
|
55
|
+
|
|
56
|
+
Never calibrated: now. After a failure: the last attempt plus the backoff. Otherwise the last success plus the
|
|
57
|
+
interval.
|
|
58
|
+
"""
|
|
59
|
+
if every is None:
|
|
60
|
+
return None
|
|
61
|
+
if failures and last_attempt is not None:
|
|
62
|
+
return last_attempt + backoff(every, failures)
|
|
63
|
+
if last_ok is None:
|
|
64
|
+
return now
|
|
65
|
+
return last_ok + every
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def is_stale(calibrated_at: float | None, every: float | None, now: float) -> bool:
|
|
69
|
+
"""A result is stale once it is older than twice the interval (1 day when scheduling is off)."""
|
|
70
|
+
if calibrated_at is None:
|
|
71
|
+
return True
|
|
72
|
+
return now - calibrated_at > 2 * (every if every is not None else 86400.0)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# ---------- OS scheduler files ----------
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass
|
|
79
|
+
class UnitFile:
|
|
80
|
+
path: Path
|
|
81
|
+
text: str
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _cmd(mode: str, every: float | None, extra: list[str]) -> list[str]:
|
|
85
|
+
base = [sys.executable, "-m", "compactlab.cli.main"]
|
|
86
|
+
if mode == "serve":
|
|
87
|
+
return [*base, "serve", "--every", fmt_every(every), *extra]
|
|
88
|
+
return [*base, "recalibrate", *extra]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def launchd_units(mode: str, every: float | None, extra: list[str], home: Path) -> list[UnitFile]:
|
|
92
|
+
"""One LaunchAgent: `serve` kept alive, or `recalibrate` run every interval (low priority, background)."""
|
|
93
|
+
args = "".join(f"\n <string>{escape(a)}</string>" for a in _cmd(mode, every, extra))
|
|
94
|
+
log = home / ".compactlab" / "service" / "launchd.log"
|
|
95
|
+
timing = (
|
|
96
|
+
" <key>RunAtLoad</key><true/>\n <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n"
|
|
97
|
+
if mode == "serve"
|
|
98
|
+
else f" <key>StartInterval</key><integer>{int(every or 86400)}</integer>\n"
|
|
99
|
+
)
|
|
100
|
+
text = f"""<?xml version="1.0" encoding="UTF-8"?>
|
|
101
|
+
<!-- {MARKER}; remove with: compactlab schedule uninstall --yes -->
|
|
102
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
103
|
+
<plist version="1.0">
|
|
104
|
+
<dict>
|
|
105
|
+
<key>Label</key><string>{LABEL}</string>
|
|
106
|
+
<key>ProgramArguments</key>
|
|
107
|
+
<array>{args}
|
|
108
|
+
</array>
|
|
109
|
+
{timing} <key>ProcessType</key><string>Background</string>
|
|
110
|
+
<key>LowPriorityIO</key><true/>
|
|
111
|
+
<key>Nice</key><integer>10</integer>
|
|
112
|
+
<key>StandardOutPath</key><string>{escape(str(log))}</string>
|
|
113
|
+
<key>StandardErrorPath</key><string>{escape(str(log))}</string>
|
|
114
|
+
</dict>
|
|
115
|
+
</plist>
|
|
116
|
+
"""
|
|
117
|
+
return [UnitFile(home / "Library" / "LaunchAgents" / f"{LABEL}.plist", text)]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def systemd_units(mode: str, every: float | None, extra: list[str], home: Path) -> list[UnitFile]:
|
|
121
|
+
"""A user service (`serve`, restarted on failure) or a oneshot `recalibrate` service plus a timer."""
|
|
122
|
+
d = home / ".config" / "systemd" / "user"
|
|
123
|
+
cmd = " ".join(shlex.quote(a) for a in _cmd(mode, every, extra))
|
|
124
|
+
if mode == "serve":
|
|
125
|
+
svc = f"""# {MARKER}; remove with: compactlab schedule uninstall --yes
|
|
126
|
+
[Unit]
|
|
127
|
+
Description=compactlab calibration service (localhost only)
|
|
128
|
+
|
|
129
|
+
[Service]
|
|
130
|
+
ExecStart={cmd}
|
|
131
|
+
Restart=on-failure
|
|
132
|
+
RestartSec=300
|
|
133
|
+
Nice=10
|
|
134
|
+
IOSchedulingClass=idle
|
|
135
|
+
|
|
136
|
+
[Install]
|
|
137
|
+
WantedBy=default.target
|
|
138
|
+
"""
|
|
139
|
+
return [UnitFile(d / "compactlab.service", svc)]
|
|
140
|
+
svc = f"""# {MARKER}; remove with: compactlab schedule uninstall --yes
|
|
141
|
+
[Unit]
|
|
142
|
+
Description=compactlab recalibration (one run)
|
|
143
|
+
|
|
144
|
+
[Service]
|
|
145
|
+
Type=oneshot
|
|
146
|
+
ExecStart={cmd}
|
|
147
|
+
Nice=10
|
|
148
|
+
IOSchedulingClass=idle
|
|
149
|
+
"""
|
|
150
|
+
timer = f"""# {MARKER}; remove with: compactlab schedule uninstall --yes
|
|
151
|
+
[Unit]
|
|
152
|
+
Description=compactlab recalibration every {fmt_every(every or 86400)}
|
|
153
|
+
|
|
154
|
+
[Timer]
|
|
155
|
+
OnBootSec=15min
|
|
156
|
+
OnUnitActiveSec={int(every or 86400)}s
|
|
157
|
+
Persistent=true
|
|
158
|
+
|
|
159
|
+
[Install]
|
|
160
|
+
WantedBy=timers.target
|
|
161
|
+
"""
|
|
162
|
+
return [UnitFile(d / "compactlab.service", svc), UnitFile(d / "compactlab.timer", timer)]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def units(platform: str, mode: str, every: float | None, extra: list[str], home: Path) -> list[UnitFile]:
|
|
166
|
+
if mode not in ("serve", "recalibrate"):
|
|
167
|
+
raise ValueError("mode must be serve or recalibrate")
|
|
168
|
+
if mode == "recalibrate" and every is None:
|
|
169
|
+
raise ValueError("a scheduled recalibrate needs an interval (not 'off')")
|
|
170
|
+
return (launchd_units if platform == "launchd" else systemd_units)(mode, every, extra, home)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def diff(units_: list[UnitFile]) -> str:
|
|
174
|
+
out: list[str] = []
|
|
175
|
+
for u in units_:
|
|
176
|
+
old = u.path.read_text() if u.path.exists() else ""
|
|
177
|
+
out += difflib.unified_diff(old.splitlines(True), u.text.splitlines(True), f"{u.path} (current)", str(u.path))
|
|
178
|
+
return "".join(out) or "(no change)\n"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def install(units_: list[UnitFile]) -> list[Path]:
|
|
182
|
+
"""Writes the unit files (only under the user's LaunchAgents / systemd user folder). Refuses to overwrite a
|
|
183
|
+
file compactlab did not generate."""
|
|
184
|
+
for u in units_:
|
|
185
|
+
if u.path.exists() and MARKER not in u.path.read_text():
|
|
186
|
+
raise PermissionError(f"{u.path} exists and was not generated by compactlab; not overwriting")
|
|
187
|
+
for u in units_:
|
|
188
|
+
u.path.parent.mkdir(parents=True, exist_ok=True)
|
|
189
|
+
u.path.write_text(u.text)
|
|
190
|
+
return [u.path for u in units_]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def installed(platform: str, home: Path) -> list[Path]:
|
|
194
|
+
paths = (
|
|
195
|
+
[home / "Library" / "LaunchAgents" / f"{LABEL}.plist"]
|
|
196
|
+
if platform == "launchd"
|
|
197
|
+
else [home / ".config" / "systemd" / "user" / n for n in ("compactlab.service", "compactlab.timer")]
|
|
198
|
+
)
|
|
199
|
+
return [p for p in paths if p.exists() and MARKER in p.read_text()]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def uninstall(platform: str, home: Path) -> list[Path]:
|
|
203
|
+
gone = installed(platform, home)
|
|
204
|
+
for p in gone:
|
|
205
|
+
p.unlink()
|
|
206
|
+
return gone
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def activation_hint(platform: str) -> str:
|
|
210
|
+
if platform == "launchd":
|
|
211
|
+
return f"load it yourself: launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/{LABEL}.plist"
|
|
212
|
+
return "enable it yourself: systemctl --user daemon-reload && systemctl --user enable --now compactlab.timer"
|