polyctl 0.7.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.
Files changed (99) hide show
  1. polyctl/__init__.py +7 -0
  2. polyctl/__main__.py +5 -0
  3. polyctl/a2a.py +226 -0
  4. polyctl/a2a_mcp.py +546 -0
  5. polyctl/acp.py +417 -0
  6. polyctl/adapters/README.md +101 -0
  7. polyctl/adapters/aider.json +32 -0
  8. polyctl/adapters/amazon-q.json +15 -0
  9. polyctl/adapters/amp.json +16 -0
  10. polyctl/adapters/antigravity.json +120 -0
  11. polyctl/adapters/claude-code.json +229 -0
  12. polyctl/adapters/cloud-generic.json +57 -0
  13. polyctl/adapters/codex.json +47 -0
  14. polyctl/adapters/command-code.json +45 -0
  15. polyctl/adapters/copilot.json +17 -0
  16. polyctl/adapters/cursor-agent.json +29 -0
  17. polyctl/adapters/deepseek.json +13 -0
  18. polyctl/adapters/droid.json +34 -0
  19. polyctl/adapters/gemini.json +30 -0
  20. polyctl/adapters/grok.json +22 -0
  21. polyctl/adapters/hermes.json +34 -0
  22. polyctl/adapters/kilocode.json +30 -0
  23. polyctl/adapters/kimi.json +23 -0
  24. polyctl/adapters/kiro.json +332 -0
  25. polyctl/adapters/ollama.json +29 -0
  26. polyctl/adapters/omp.json +34 -0
  27. polyctl/adapters/openai-api.json +68 -0
  28. polyctl/adapters/opencode.json +162 -0
  29. polyctl/adapters/pi.json +24 -0
  30. polyctl/adapters/pr-agent.json +54 -0
  31. polyctl/adapters/profiles.json +9 -0
  32. polyctl/adapters/qoder.json +163 -0
  33. polyctl/adapters/qwen.json +27 -0
  34. polyctl/adapters/reasonix.json +25 -0
  35. polyctl/adapters/rewriters/rtk.json +24 -0
  36. polyctl/adapters/trae.json +31 -0
  37. polyctl/adapters/vendors.json +42 -0
  38. polyctl/adapters/warp.json +88 -0
  39. polyctl/allowlist.py +1756 -0
  40. polyctl/api_review.py +920 -0
  41. polyctl/cli.py +835 -0
  42. polyctl/conformance_harness.py +9 -0
  43. polyctl/demo.py +503 -0
  44. polyctl/drivers.py +146 -0
  45. polyctl/email.py +160 -0
  46. polyctl/features.py +98 -0
  47. polyctl/journal.py +144 -0
  48. polyctl/language.py +945 -0
  49. polyctl/lib.py +1296 -0
  50. polyctl/matrix.py +660 -0
  51. polyctl/mcp.py +1362 -0
  52. polyctl/ntfy.py +169 -0
  53. polyctl/outbound.py +39 -0
  54. polyctl/parts/__init__.py +5 -0
  55. polyctl/parts/cli_authority.py +2615 -0
  56. polyctl/parts/cli_channels.py +1325 -0
  57. polyctl/parts/cli_checks.py +2293 -0
  58. polyctl/parts/cli_completion.py +686 -0
  59. polyctl/parts/cli_evidence.py +141 -0
  60. polyctl/parts/cli_gain.py +375 -0
  61. polyctl/parts/cli_harness.py +392 -0
  62. polyctl/parts/cli_hooks.py +1816 -0
  63. polyctl/parts/cli_install.py +638 -0
  64. polyctl/parts/cli_lanes.py +106 -0
  65. polyctl/parts/cli_maintenance.py +2536 -0
  66. polyctl/parts/cli_next.py +248 -0
  67. polyctl/parts/cli_pr.py +53 -0
  68. polyctl/parts/cli_project.py +2857 -0
  69. polyctl/parts/cli_review.py +5158 -0
  70. polyctl/parts/cli_status.py +898 -0
  71. polyctl/parts/lib_adapters.py +2933 -0
  72. polyctl/parts/lib_alarms.py +2106 -0
  73. polyctl/parts/lib_events.py +224 -0
  74. polyctl/parts/lib_evidence.py +412 -0
  75. polyctl/parts/lib_gates.py +2099 -0
  76. polyctl/parts/lib_lanes.py +829 -0
  77. polyctl/parts/lib_mail.py +1541 -0
  78. polyctl/parts/lib_next.py +652 -0
  79. polyctl/parts/lib_pr.py +331 -0
  80. polyctl/parts/lib_slices.py +3337 -0
  81. polyctl/parts/lib_state.py +2415 -0
  82. polyctl/parts/lib_transcript.py +4118 -0
  83. polyctl/pressure.py +325 -0
  84. polyctl/prices.json +47 -0
  85. polyctl/procs.py +1194 -0
  86. polyctl/settings.py +505 -0
  87. polyctl/skill/SKILL.md +365 -0
  88. polyctl/skillkit.py +503 -0
  89. polyctl/storage.py +2055 -0
  90. polyctl/telegram.py +327 -0
  91. polyctl/tiers.py +123 -0
  92. polyctl/verdicts.py +41 -0
  93. polyctl/watchdog.py +3887 -0
  94. polyctl/web.py +337 -0
  95. polyctl-0.7.0.dist-info/METADATA +235 -0
  96. polyctl-0.7.0.dist-info/RECORD +99 -0
  97. polyctl-0.7.0.dist-info/WHEEL +4 -0
  98. polyctl-0.7.0.dist-info/entry_points.txt +5 -0
  99. polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,2536 @@
1
+ """Maintenance: remove, prune, notices, the watchdog command, projects, adapters, worktrees, prove,
2
+ demo, backup, doctor.
3
+
4
+ A part of src/polyctl/cli.py (#44): moved out byte for byte and run in its namespace by `_part`,
5
+ where it stood; it is not importable on its own.
6
+ """
7
+
8
+
9
+ def _remove_inert_local(target, inv):
10
+ """The one protected effective hook that may safely outlive project state."""
11
+ common_hooks = os.path.realpath(os.path.join(inv["common_dir"], "hooks"))
12
+ return bool(
13
+ target["active"]
14
+ and _state_base(target["static_state"]) == "current-local"
15
+ and target["directory_class"] == "project-local"
16
+ and not target["globally_configured"]
17
+ and target["effective_count"] == 1
18
+ and not target["legacy_location"]
19
+ and os.path.realpath(target["directory"]) != common_hooks
20
+ and (_hook_contains(inv["top"], target["directory"])
21
+ or _hook_contains(inv["git_dir"], target["directory"]))
22
+ )
23
+
24
+
25
+ def _remove_hook_preflight(inv, allow):
26
+ plan, blockers, inert = [], [], []
27
+ if inv["error"]:
28
+ print(f"{C['red']}hook resolver failed; state kept intact{C['reset']}: {inv['error']}")
29
+ return False, plan, inert
30
+ for target in inv["targets"]:
31
+ base = _state_base(target["static_state"])
32
+ if target["eligible"] and base in ("current-local", "current-scoped", "legacy"):
33
+ plan.append(target)
34
+ continue
35
+ if not target["protected"] or base not in (
36
+ "current-local", "current-scoped", "legacy", "ambiguous-polyctl"
37
+ ):
38
+ continue
39
+ if target["reachability"] == "dead-misplaced":
40
+ print(f"preserved protected dead-misplaced {target['role']} (does not block remove): "
41
+ f"{target['path']}")
42
+ continue
43
+ if base == "current-local" and _remove_inert_local(target, inv):
44
+ inert.append(target)
45
+ print(f"preserved protected current-local {target['role']} — becomes inert after .polyctl removal: "
46
+ f"{target['path']}")
47
+ continue
48
+ blockers.append(target)
49
+ print(f"{C['red']}remove blocked{C['reset']} by protected potentially-effective "
50
+ f"{target['static_state']} {target['role']}: {target['path']}")
51
+ if blockers or _authorization_refusal(plan, allow):
52
+ print("polyctl state was not changed")
53
+ return False, plan, inert
54
+ return True, plan, inert
55
+
56
+
57
+ def _home_relative(path):
58
+ """A path under the home directory as ~/…, the way a person reads it.
59
+
60
+ With forward slashes on Windows too, where the rest of the path came with backslashes, so a file
61
+ in the home is named one way on every platform (WINDOWS-LANE-4).
62
+ """
63
+ home = A.HOME.rstrip("/\\")
64
+ if path == home or path.startswith(home + os.sep):
65
+ return "~" + path[len(home):].replace(os.sep, "/")
66
+ return path
67
+
68
+
69
+ def _remove_key(root):
70
+ """(the name this project's files outside its tree are kept under, whether that name is this project's).
71
+
72
+ A directory with no .polyctl/ is named by its basename, and that can be another project's
73
+ name: a second remove, run after the first took .polyctl/, would take that project's files.
74
+ Only a project with .polyctl/, or one the registry still holds by its path, owns a name.
75
+ """
76
+ if os.path.isdir(os.path.join(os.path.realpath(root), ".polyctl")):
77
+ return A.project_key(root), True
78
+ registered = A.registered_key(root)
79
+ return (registered, True) if registered else (A.project_key(root), False)
80
+
81
+
82
+ def _project_home_files(key, root=None):
83
+ """This project's files in ~/.polyctl that exist, named from PROJECT_FILES (SAFE-REMOVE), and the record that its
84
+ repository is enrolled (LEADS-GATE-HOOK).
85
+
86
+ One path per file: a case-insensitive disk answers to a lower-cased name and to the
87
+ name as it is, and both would otherwise be listed and removed as two files.
88
+ """
89
+ seen, found = set(), []
90
+ names = [os.path.join(A.HOME, ".polyctl", name) for name in A.project_file_names(key)]
91
+ if root is not None:
92
+ # The record is the repository's, whichever of its worktrees the project is removed from (LEADS-GATE-HOOK).
93
+ record = A.enrollment_record(root)
94
+ if record and record.get("repository"):
95
+ names.append(A.enrollment_record_path(root)[0])
96
+ for path in names:
97
+ try:
98
+ st = os.lstat(path)
99
+ except OSError:
100
+ continue
101
+ identity = (st.st_dev, st.st_ino) if st.st_ino else os.path.normcase(path)
102
+ if identity not in seen:
103
+ seen.add(identity)
104
+ found.append(path)
105
+ return found
106
+
107
+
108
+ def _registry_names(root):
109
+ """The names the machine registry holds for this project's resolved path."""
110
+ real = os.path.realpath(root)
111
+ return sorted(name for name, row in A.project_registry().items() if row.get("root") == real)
112
+
113
+
114
+ POLYCTL_GITIGNORE = ("agent-mail/*.md", "!agent-mail/README.md", ".polyctl/inbox/", ".polyctl/hold", ".polyctl/sessions.json",
115
+ ".polyctl/lanes/")
116
+ # What the comment `polyctl init` writes above the lines it adds to .gitignore says (cmd_init), and the comment itself.
117
+ POLYCTL_GITIGNORE_MARK = "polyctl: mail is transient"
118
+ POLYCTL_GITIGNORE_COMMENT = "# polyctl: mail is transient; the ledger and reviews are not"
119
+ # Why a comment in polyctl's words stays in .gitignore with the lines under it, and what the person does.
120
+ GITIGNORE_UNCLAIMED = ("polyctl cannot tell it wrote them (an older polyctl named no lines, and a block changed since is not "
121
+ "what it wrote); delete them by hand if polyctl added them")
122
+
123
+
124
+ def _gitignore_block(lines):
125
+ """The comment `polyctl init` writes above the lines it adds to .gitignore, naming them its own: how many follow it,
126
+ and a digest of exactly those lines (LEADS-INSTALL).
127
+
128
+ A comment in polyctl's words was all that marked them, and a person's own block under such a comment - copied from
129
+ another project, or written before init - was taken with polyctl's. The count and the digest are what polyctl wrote and
130
+ nobody writes by chance: `polyctl remove` takes a block only when the lines under its comment are those.
131
+ """
132
+ import hashlib
133
+ digest = hashlib.sha256("\n".join(lines).encode(UTF8)).hexdigest()[:16]
134
+ return f"{POLYCTL_GITIGNORE_COMMENT} (polyctl: {len(lines)} line{'' if len(lines) == 1 else 's'} below, {digest})"
135
+
136
+
137
+ def _gitignore_without_polyctl(root):
138
+ """(.gitignore's path, its lines without the ones polyctl added, how many of those it had, and where a comment in
139
+ polyctl's words stands over lines polyctl cannot tell it wrote: [(its line now, its line once polyctl's lines are out)]).
140
+
141
+ polyctl's lines are the blocks `polyctl init` wrote: its comment, naming the lines under it by their count and digest
142
+ (_gitignore_block), and exactly those lines. Every line holding one of polyctl's patterns went, wherever it stood,
143
+ and then the run of polyctl's patterns under any comment in polyctl's words, so a person's own block under such a
144
+ comment went too (LEADS-INSTALL). A block an older polyctl wrote names no lines, and one changed since is not
145
+ what polyctl wrote: each stays, and is named, for the person to delete if it is polyctl's.
146
+ """
147
+ import re
148
+ from . import storage
149
+ path = os.path.join(root, ".gitignore")
150
+ raw = storage.read_in_tree(root, ".gitignore")
151
+ if raw is None:
152
+ return path, [], 0, []
153
+ # Match init's text decoding, but never read through a link or wait on a FIFO. The caller names an
154
+ # unreadable file at both planning and removal, including a link swapped in between them (LEADS-INSTALL).
155
+ lines = raw.decode(UTF8, "replace").replace("\r\n", "\n").replace("\r", "\n").split("\n")
156
+ keep, unclaimed, index = [], [], 0
157
+ while index < len(lines):
158
+ line = lines[index]
159
+ if line.lstrip().startswith("#") and POLYCTL_GITIGNORE_MARK in line:
160
+ named = re.search(r" \(polyctl: (\d{1,6}) lines? below, [0-9a-f]{16}\)$", line)
161
+ count = int(named.group(1)) if named else 0
162
+ block = lines[index + 1:index + 1 + count]
163
+ if named and len(block) == count and line == _gitignore_block(block):
164
+ index += 1 + count
165
+ continue
166
+ unclaimed.append((index + 1, len(keep) + 1))
167
+ keep.append(line)
168
+ index += 1
169
+ return path, keep, len(lines) - len(keep), unclaimed
170
+
171
+
172
+ # The jobs `polyctl watchdog install` and `polyctl telegram install` schedule for a project (SAFE-REMOVE). Windows
173
+ # has no telegram task of polyctl's: `polyctl telegram install` refuses there. Linux's are SYSTEMD_JOBS, below.
174
+ LAUNCHD_JOBS = ("watchdog", "doctor", "telegram")
175
+ WINDOWS_TASKS = ("watchdog", "doctor")
176
+ # How long a job taken off may take to leave `launchctl list`, or to stop being active in a user
177
+ # systemd, before it counts as left.
178
+ JOB_GONE_SECONDS = 5
179
+
180
+
181
+ def _windows_task(job, key):
182
+ return f"polyctl-{job}-{key.lower()}"
183
+
184
+
185
+ def _schtasks(*args):
186
+ """(what schtasks printed, its exit status), asked without a shell; ("", None) when it cannot be run.
187
+
188
+ Windows' own schtasks, from its system directory: by its bare name Windows looked for it in the
189
+ current directory first, and a schtasks.exe an agent left in the tree would have run as the
190
+ person, and been asked to schedule polyctl's jobs (WINDOWS-NO-CWD-EXEC). What it prints is in the
191
+ OEM code page, read as such (console_text, WINDOWS-SAY-WHY).
192
+ """
193
+ schtasks = A.program_path("schtasks")
194
+ if schtasks is None:
195
+ return "", None
196
+ try:
197
+ done = subprocess.run([schtasks, *args], capture_output=True)
198
+ except OSError:
199
+ return "", None
200
+ return A.console_text((done.stdout or b"") + (done.stderr or b"")).strip(), done.returncode
201
+
202
+
203
+ def _scheduler():
204
+ """Which scheduler holds polyctl's jobs here: Task Scheduler on Windows, a user systemd on Linux, else launchd."""
205
+ if os.name == "nt":
206
+ return "schtasks"
207
+ return "systemd" if sys.platform.startswith("linux") else "launchd"
208
+
209
+
210
+ # ---- a user systemd, Linux's launchd (LINUX-SCHEDULER) ----------------------------------------
211
+ #
212
+ # Each job `polyctl watchdog install` schedules is two units in the user's own unit directory: a oneshot
213
+ # service that runs it once, and a timer that starts the service. Nothing here needs root: the units
214
+ # are the user's, run by the user's manager, and asked for with `systemctl --user`.
215
+
216
+ SYSTEMD_JOBS = ("watchdog", "doctor")
217
+ # Present while systemd is the init system (sd_booted(3)). Without it no manager can hold a unit,
218
+ # whatever a systemctl on PATH answers: a container, or WSL without systemd.
219
+ SYSTEMD_RUNTIME = "/run/systemd/system"
220
+ # The longest unit name systemd accepts, its suffix included.
221
+ SYSTEMD_NAME_MAX = 255
222
+ # What `systemctl is-active` says of a unit that is running or about to be.
223
+ SYSTEMD_UP = ("active", "activating", "reloading")
224
+ # And of one whose process may still run: a service being stopped is `deactivating` until it has ended.
225
+ SYSTEMD_NOT_GONE = SYSTEMD_UP + ("deactivating",)
226
+ # And of one that does not run and will not start of itself, a unit it does not know included. Any other word, or
227
+ # no word for a unit, is no answer, and a job it is said of counts as there (LEADS-INSTALL).
228
+ SYSTEMD_DOWN = ("inactive", "failed")
229
+ LINGER_ADVICE = ("the timers run while you are logged in; to keep them running after you log out: "
230
+ "loginctl enable-linger")
231
+
232
+ # The unit files, as a person reading ~/.config/systemd/user should understand them. A value in them
233
+ # is written by _systemd_word or _systemd_text, which keep a project's path from ending the line.
234
+ SYSTEMD_SERVICE = """# Written by `polyctl watchdog install`; `polyctl watchdog uninstall` removes it.
235
+ [Unit]
236
+ Description={description}
237
+
238
+ [Service]
239
+ Type=oneshot
240
+ ExecStart={argv}
241
+ Environment={path}
242
+ # The watchdog starts each nudge in a session of its own and exits. With systemd's default
243
+ # KillMode, a oneshot unit that ends kills every process left in its control group: the nudge too.
244
+ KillMode=process
245
+ StandardOutput=append:{log}
246
+ StandardError=append:{log}
247
+ """
248
+
249
+ SYSTEMD_TIMER = """# Written by `polyctl watchdog install`; `polyctl watchdog uninstall` removes it.
250
+ [Unit]
251
+ Description={description}
252
+
253
+ [Timer]
254
+ # At once when the timer starts, as a launchd job's RunAtLoad, then every interval from the last
255
+ # start, as its StartInterval: to the second, not anywhere in the minute systemd allows by default.
256
+ OnActiveSec=0
257
+ OnUnitActiveSec={seconds}s
258
+ AccuracySec=1s
259
+
260
+ [Install]
261
+ WantedBy=timers.target
262
+ """
263
+
264
+
265
+ def _systemctl(*args, merge=False):
266
+ """(what `systemctl --user <args>` printed, its exit status), asked without a shell as launchctl is.
267
+
268
+ Its standard error is discarded unless `merge` keeps it in the answer, where a failure says why.
269
+ """
270
+ return A._run_program(["systemctl", "--user", *args], stderr=subprocess.STDOUT if merge else subprocess.DEVNULL)
271
+
272
+
273
+ def _systemd_dir():
274
+ """The user unit directory the jobs are written to, and the one a user manager reads by default."""
275
+ return os.path.join(A.HOME, ".config", "systemd", "user")
276
+
277
+
278
+ def _systemd_unit(job, key):
279
+ """The name, without its suffix, of the units that schedule one of polyctl's jobs for a project.
280
+
281
+ `polyctl-<job>-<key>`, as the Windows task is named. A unit name holds letters, digits and `:_.-`
282
+ only, and a project's key may hold any other character: each is written as systemd-escape
283
+ writes it, `\\xNN` for each of its bytes, a backslash among them, so two keys stay two names.
284
+ A name longer than systemd accepts keeps its first part and eight hex digits of the key's hash.
285
+ """
286
+ import hashlib
287
+ prefix, key = f"polyctl-{job}-", key.lower()
288
+ pieces = [ch if ch.isascii() and (ch.isalnum() or ch in ":_.-")
289
+ else "".join(f"\\x{byte:02x}" for byte in ch.encode(UTF8, "surrogateescape")) for ch in key]
290
+ room = SYSTEMD_NAME_MAX - len(prefix) - len(".service")
291
+ if sum(map(len, pieces)) <= room:
292
+ return prefix + "".join(pieces)
293
+ kept = ""
294
+ for piece in pieces:
295
+ if len(kept) + len(piece) > room - 9:
296
+ break
297
+ kept += piece
298
+ return f"{prefix}{kept}-{hashlib.sha256(key.encode(UTF8, 'surrogateescape')).hexdigest()[:8]}"
299
+
300
+
301
+ def _systemd_files(unit):
302
+ """The paths of one job's service, its timer, and the link `systemctl --user enable` makes to the timer.
303
+
304
+ The link is named as a file of the job's too: a disable that did not run leaves it pointing at
305
+ a timer that is gone, and the manager then names that missing unit at every login.
306
+ """
307
+ return [os.path.join(_systemd_dir(), unit + ".service"), os.path.join(_systemd_dir(), unit + ".timer"),
308
+ os.path.join(_systemd_dir(), "timers.target.wants", unit + ".timer")]
309
+
310
+
311
+ def _systemd_word(word, expand=True):
312
+ """One word as systemd reads it back unchanged from ExecStart= or Environment= (systemd.syntax(7)).
313
+
314
+ Double-quoted, with a backslash and a quote escaped and a control character written as its C
315
+ escape, which systemd undoes inside quotes; a `%` doubled, since specifiers are expanded before
316
+ the line is split into words; and, on a line that expands variables (ExecStart=), a `$` doubled.
317
+ """
318
+ out = []
319
+ for ch in word:
320
+ if ch in '\\"':
321
+ out.append("\\" + ch)
322
+ elif ord(ch) < 32 or ord(ch) == 127:
323
+ out.append(f"\\x{ord(ch):02x}")
324
+ elif ch == "%" or (ch == "$" and expand):
325
+ out.append(ch + ch)
326
+ else:
327
+ out.append(ch)
328
+ return '"' + "".join(out) + '"'
329
+
330
+
331
+ def _systemd_text(text):
332
+ """`text` as a value systemd reads with its specifiers and nothing else, such as Description=.
333
+
334
+ A `%` doubled; a control character, which would end the line, and a backslash, which at the
335
+ end of one joins the next line to it, each shown as `?`.
336
+ """
337
+ return "".join("?" if ord(ch) < 32 or ch in "\\\x7f" else ch for ch in text).replace("%", "%%")
338
+
339
+
340
+ def _systemd_unit_texts(unit, job, argv, seconds, log, root, path):
341
+ """{file name: text} of the service that runs `argv` once and the timer that starts it every `seconds`."""
342
+ return {unit + ".service": SYSTEMD_SERVICE.format(
343
+ description=_systemd_text(f"polyctl {job} for {root}"),
344
+ argv=" ".join(_systemd_word(word) for word in argv),
345
+ path=_systemd_word(f"PATH={path}", expand=False), log=log.replace("%", "%%")),
346
+ unit + ".timer": SYSTEMD_TIMER.format(
347
+ description=_systemd_text(f"polyctl {job} for {root}, every {seconds}s"), seconds=seconds)}
348
+
349
+
350
+ def _systemd_interval(path):
351
+ """The seconds between starts a timer written by `polyctl watchdog install` names; None when it names none."""
352
+ try:
353
+ with open(path, encoding=UTF8) as fh:
354
+ for line in fh:
355
+ name, _, value = line.strip().partition("=")
356
+ if name == "OnUnitActiveSec" and value[:-1].isdigit() and value.endswith("s"):
357
+ return int(value[:-1])
358
+ except (OSError, ValueError):
359
+ return None
360
+ return None
361
+
362
+
363
+ def _systemd_user_problem():
364
+ """None when a user systemd answers here; else why none does, as a person reads it.
365
+
366
+ The jobs run in the user's own manager, which `systemctl --user` reaches through
367
+ $XDG_RUNTIME_DIR: a container or WSL without systemd has no manager at all, and a `su`
368
+ or `sudo -u` shell has one it cannot reach.
369
+ """
370
+ if not os.path.isdir(SYSTEMD_RUNTIME):
371
+ return "this machine does not run systemd (a container, WSL without systemd, or another init)"
372
+ said, status = _systemctl("show", "--property=Version", merge=True)
373
+ if status == 0:
374
+ return None
375
+ if status is None:
376
+ return "systemctl could not be run"
377
+ return "systemctl --user reaches no user manager: " + (said.split("\n")[0].strip() or f"exit {status}")
378
+
379
+
380
+ def _systemd_states(*units):
381
+ """{unit: what `systemctl --user is-active` says of it}; None for each when the manager cannot be asked.
382
+
383
+ It prints one state for each unit it is given, in order, and `inactive` for a unit it does not know.
384
+ """
385
+ said, status = _systemctl("is-active", *units)
386
+ states = said.split("\n") if said else []
387
+ if status is None or len(states) != len(units):
388
+ return dict.fromkeys(units)
389
+ return {unit: state.strip() for unit, state in zip(units, states)}
390
+
391
+
392
+ def _systemd_linger():
393
+ """Whether this user's manager outlives their last session, "yes" or "no"; None when loginctl cannot say.
394
+
395
+ Without it the manager stops when the last session ends, and every timer in it: on a server,
396
+ the moment the person who installed the jobs logs out.
397
+ """
398
+ said, status = A._run_program(["loginctl", "show-user", str(os.getuid()), "--property=Linger"])
399
+ name, _, value = said.partition("=")
400
+ return value if status == 0 and name == "Linger" and value in ("yes", "no") else None
401
+
402
+
403
+ def _systemd_unschedule(timer):
404
+ """Take one job's timer and service off the user systemd and out of its directory; what is left, or None.
405
+
406
+ Without systemd as the init system nothing can hold them, and their files are all there is to
407
+ remove. With it, the manager is asked to disable and stop them and then whether each is gone:
408
+ the timer, and the service, whose cycle may be running as it is asked. Only the timer was
409
+ asked after, so a service a stop did not end ran on against a project its removal said was
410
+ free of it (LEADS-INSTALL). A manager this shell cannot reach may still run them: they are
411
+ then left as they are, files included, so that a session that reaches it still finds them to
412
+ take off - and so they are when no file of theirs is left, since the manager keeps running a
413
+ unit whose files went; that was read as nothing to take off (LEADS-INSTALL). Each is stopped by
414
+ name as well as disabled: a disable finds no unit file to act on once the files went, and its
415
+ `--now` then stops nothing.
416
+ """
417
+ unit = timer[:-len(".timer")]
418
+ service = unit + ".service"
419
+ files = _systemd_files(unit)
420
+ booted = os.path.isdir(SYSTEMD_RUNTIME)
421
+ if booted:
422
+ problem = _systemd_user_problem()
423
+ if problem:
424
+ return f"{problem} — take it off from a login session of this user: polyctl watchdog uninstall"
425
+ # What these answer is not read: each unit's state afterwards is what decides.
426
+ _systemctl("disable", "--now", timer)
427
+ _systemctl("stop", timer, service)
428
+ left = []
429
+ for path in files:
430
+ try:
431
+ if os.path.lexists(path):
432
+ os.remove(path)
433
+ except OSError as exc:
434
+ left.append(f"cannot remove {_home_relative(path)}: {exc}")
435
+ if not booted:
436
+ return "; ".join(left) or None
437
+ _systemctl("daemon-reload")
438
+ deadline = time.monotonic() + JOB_GONE_SECONDS
439
+ states = _systemd_states(timer, service)
440
+ while any(state in SYSTEMD_NOT_GONE for state in states.values()) and time.monotonic() < deadline:
441
+ time.sleep(0.25)
442
+ states = _systemd_states(timer, service)
443
+ running = _systemd_running(states)
444
+ if states[timer] in SYSTEMD_NOT_GONE:
445
+ left.append(f"still {states[timer]} — systemctl --user stop {timer}")
446
+ if states[service] in SYSTEMD_NOT_GONE:
447
+ left.append(f"its service still {states[service]} — systemctl --user stop {service}")
448
+ if running is not True and running is not False:
449
+ left.append(f"{running}, so whether it still runs is not known — take it off from a login session of this "
450
+ "user: polyctl watchdog uninstall")
451
+ return "; ".join(left) or None
452
+
453
+
454
+ def _systemd_running(states):
455
+ """True when the user manager says one of these units runs or is about to, False when it says each is down;
456
+ else why what it said is neither (LEADS-INSTALL).
457
+
458
+ `_systemd_states` names no state when the manager cannot be asked, or does not answer a state for each unit,
459
+ and that read as no unit running: a job the manager could not be asked about counted as gone.
460
+ """
461
+ if any(state in SYSTEMD_NOT_GONE for state in states.values()):
462
+ return True
463
+ if all(state in SYSTEMD_DOWN for state in states.values()):
464
+ return False
465
+ if None in states.values():
466
+ return (_systemd_user_problem()
467
+ or f"the user manager did not answer systemctl --user is-active {' '.join(states)}")
468
+ unit, state = next((unit, state) for unit, state in states.items() if state not in SYSTEMD_DOWN)
469
+ return f"systemctl --user is-active answers {state!r} for {unit}, neither running nor stopped"
470
+
471
+
472
+ def _task_held(name):
473
+ """True when Task Scheduler holds a task of this name, False when it says it holds none; else why it cannot say.
474
+
475
+ schtasks exits 1 for a task it does not have and for one it will not show alike - access is
476
+ denied, the service does not answer - and says which in the machine's own language. Every
477
+ failed query read as no task, so `polyctl remove` took a project's state while a task it could not
478
+ read went on running against it (LEADS-INSTALL). So it is also asked for a name no task has,
479
+ and a failed query is an absence only when it failed the same way, that name aside. And only
480
+ when Task Scheduler answered at all, by listing its tasks: a failure every query shares - access
481
+ to Task Scheduler denied, its service not running - read the same for both names, and was taken
482
+ for an absence (LEADS-INSTALL).
483
+ """
484
+ import secrets
485
+ said, status = _schtasks("/Query", "/TN", name)
486
+ if status == 0:
487
+ return True
488
+ if status is None:
489
+ return "schtasks could not be run"
490
+ listed, listed_status = _schtasks("/Query")
491
+ if listed_status != 0:
492
+ return f"it lists no task: {listed[:120] or 'schtasks /Query exit ' + str(listed_status)}"
493
+ nobody = f"polyctl-no-task-{secrets.token_hex(6)}"
494
+ absent, absent_status = _schtasks("/Query", "/TN", nobody)
495
+ if absent_status == status and absent.replace(nobody, "\0") == said.replace(name, "\0"):
496
+ return False
497
+ return said[:120] or f"schtasks exit {status}"
498
+
499
+
500
+ def _systemd_loaded(unit):
501
+ """Whether the user manager runs one job's timer or service, or is about to: True, False when it says neither
502
+ does, else why it cannot be asked - a job with no file left.
503
+
504
+ The manager keeps a unit it has loaded after its files are gone, a timer running included, until it
505
+ stops; files deleted by hand left one running that `polyctl remove` never looked for (LEADS-INSTALL). A
506
+ manager this shell cannot reach, or an answer that is not a state for each unit, read as neither
507
+ running, and the removal took the state of a project whose timer ran on: it is no answer, and the
508
+ job counts as there (LEADS-INSTALL). False where systemd is not the init system: no manager holds
509
+ a unit there, and the files are all there is to find.
510
+ """
511
+ if not os.path.isdir(SYSTEMD_RUNTIME):
512
+ return False
513
+ return _systemd_running(_systemd_states(unit + ".timer", unit + ".service"))
514
+
515
+
516
+ def _installed_jobs(key):
517
+ """(kind, name) of each job polyctl scheduled for a project that is there to remove on this platform.
518
+
519
+ A user systemd loads polyctl's units from the files `polyctl watchdog install` writes, and keeps one it
520
+ loaded running after they are gone: on Linux a job is there while one of its files is, or
521
+ while the manager runs it. A job its scheduler cannot say it lacks - Task Scheduler, a user
522
+ manager or launchd that does not answer - is there too, so that removing it is tried, and
523
+ what could not be asked is named (LEADS-INSTALL).
524
+ """
525
+ scheduler = _scheduler()
526
+ if scheduler == "schtasks":
527
+ return [("scheduled task", name) for name in (_windows_task(job, key) for job in WINDOWS_TASKS)
528
+ if _task_held(name) is not False]
529
+ if scheduler == "systemd":
530
+ return [("systemd timer", unit + ".timer") for unit in (_systemd_unit(job, key) for job in SYSTEMD_JOBS)
531
+ if any(os.path.lexists(path) for path in _systemd_files(unit)) or _systemd_loaded(unit) is not False]
532
+ return [("launchd job", label) for label in (_launchd_label(job, key) for job in LAUNCHD_JOBS)
533
+ if _launchd_loaded(label) is not False or os.path.lexists(_launchd_plist(label))]
534
+
535
+
536
+ def _unschedule(name):
537
+ """Remove one scheduled job in this process and check that it is gone; what is left of it, or None.
538
+
539
+ `polyctl remove` ran `python -m polyctl watchdog uninstall` and did not read the result: from a clone
540
+ that interpreter has no polyctl module, the jobs went on running against a removed project, and
541
+ remove said they were gone. The telegram poller, which launchd keeps alive, was never removed.
542
+ A job its scheduler cannot say is gone is left, named, as one it still holds (LEADS-INSTALL).
543
+ """
544
+ scheduler = _scheduler()
545
+ if scheduler == "schtasks":
546
+ said, status = _schtasks("/Delete", "/TN", name, "/F")
547
+ held = _task_held(name)
548
+ if held is True:
549
+ return f"Task Scheduler still holds it: {said[:120] or f'schtasks exit {status}'}"
550
+ if held is not False:
551
+ return (f"Task Scheduler cannot say whether it still holds it ({held}) — delete it from a prompt "
552
+ f"that can: schtasks /Delete /TN {name} /F")
553
+ return None
554
+ if scheduler == "systemd":
555
+ return _systemd_unschedule(name)
556
+ plist, left = _launchd_plist(name), []
557
+ if _launchd_loaded(name) is not False and _launchctl("bootout", _launchd_domain(name))[1] != 0 \
558
+ and os.path.exists(plist):
559
+ _launchctl("unload", plist)
560
+ try:
561
+ if os.path.lexists(plist):
562
+ os.remove(plist)
563
+ except OSError as exc:
564
+ left.append(f"cannot remove {_home_relative(plist)}: {exc}")
565
+ deadline = time.monotonic() + JOB_GONE_SECONDS
566
+ loaded = _launchd_loaded(name)
567
+ while loaded is True and time.monotonic() < deadline:
568
+ time.sleep(0.25)
569
+ loaded = _launchd_loaded(name)
570
+ if loaded is True:
571
+ left.append(f"still loaded — launchctl bootout {_launchd_domain(name)}")
572
+ elif loaded is not False:
573
+ left.append(f"launchd cannot say whether it still holds it ({loaded}) — check from a login session of this "
574
+ f"user with `launchctl list`, and take it off: launchctl bootout {_launchd_domain(name)}")
575
+ return "; ".join(left) or None
576
+
577
+
578
+ def _plan_words(rel):
579
+ """The names that lead from the project to one path of `polyctl remove`'s plan, or None when it names none inside it.
580
+
581
+ A path of the plan comes partly from words an agent can write - the reviews directory of .polyctl/config.json, a
582
+ project adapter's `polyctl_files` - and `..` there named the directory above the project, `.` the project itself:
583
+ a containment check of the directory the path is in passes for both, and the delete took that directory whole
584
+ (LEADS-INSTALL). An empty name and `.` are dropped as a path's reading drops them; `..`, and a drive on
585
+ Windows, name nothing inside.
586
+ """
587
+ words = [word for word in rel.replace(os.sep, "/").split("/") if word not in ("", ".")]
588
+ if not words or ".." in words or os.path.splitdrive(os.path.join(*words))[0]:
589
+ return None
590
+ return words
591
+
592
+
593
+ def _remove_in_project(root, rel):
594
+ """Delete one path of `polyctl remove`'s plan where it lies in the project; None once it is gone, else why it is not.
595
+
596
+ A directory goes whole, a link in it as a link; a file or a link goes itself, never what a link
597
+ points at. Every error of the recursive delete was ignored, and a removal that left part of .polyctl/
598
+ behind said that polyctl state was gone (LEADS-INSTALL). A path whose directory resolves outside the
599
+ project is left as it is: a link put on its way would send the delete there.
600
+
601
+ Storage holds each folder while it is used: relative descriptors on POSIX and native handles
602
+ without delete sharing on Windows. A platform with neither refuses the operation (LEADS-INSTALL).
603
+ """
604
+ from . import storage
605
+ words = _plan_words(rel)
606
+ if words is None:
607
+ return "it names no path inside the project, and nothing is deleted for it"
608
+ path = os.path.join(root, *words)
609
+ if not os.path.lexists(path):
610
+ return None
611
+ parent = os.path.realpath(os.path.dirname(path))
612
+ if not _hook_contains(root, parent):
613
+ return f"its directory resolves outside the project, to {parent}, and nothing is deleted there"
614
+ base = os.path.realpath(root)
615
+ failed = []
616
+ # The resolved parent above is only a diagnostic. Walk the plan's original names so a link to another
617
+ # directory inside the project is refused too, rather than deleting from its target (LEADS-INSTALL).
618
+ steps = words[:-1]
619
+ try:
620
+ with storage._tree_folder(base, steps, make=False) as directory:
621
+ if directory is None:
622
+ return None
623
+ _delete_in_directory(directory, words[-1], failed)
624
+ try:
625
+ storage._tree_stat(directory, words[-1])
626
+ except FileNotFoundError:
627
+ return None
628
+ except OSError as exc:
629
+ failed.append(exc)
630
+ return " ".join(str(failed[0]).split()) if failed else "it is still there"
631
+
632
+
633
+ def _delete_in_directory(directory, name, failed):
634
+ """Delete `name` from the open directory `directory` without following a link; each error goes into `failed`.
635
+
636
+ A file or a link goes itself. A directory is emptied first, each directory in it opened relative to the one it
637
+ is in, without following a link, and each name deleted relative to the directory it is in, so that a link
638
+ swapped in for one of them is deleted as a link or stops the walk where it stands (LEADS-INSTALL). It is a walk
639
+ of polyctl's own because shutil.rmtree starts from a held directory only from Python 3.11, and polyctl runs on 3.9; it
640
+ keeps a stack of its own, so that a tree nested deeper than the interpreter recurses ends no removal in a
641
+ RecursionError.
642
+ """
643
+ import stat
644
+ from contextlib import ExitStack
645
+ from . import storage
646
+ if isinstance(directory, int) and (os.rmdir not in os.supports_dir_fd or os.scandir not in os.supports_fd):
647
+ failed.append(storage.InTheWay(name, "cannot hold folders for removal; polyctl refuses this file operation"))
648
+ return
649
+ opened_context = ExitStack()
650
+ try:
651
+ info = storage._tree_stat(directory, name)
652
+ if not stat.S_ISDIR(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400:
653
+ storage._tree_remove_leaf(directory, name)
654
+ return
655
+ opened = opened_context.enter_context(storage._tree_child(directory, name))
656
+ if opened is None:
657
+ opened_context.close()
658
+ return
659
+ except FileNotFoundError:
660
+ return
661
+ except OSError as exc:
662
+ failed.append(exc)
663
+ return
664
+ stack = [(directory, name, opened, _directory_entries(opened, failed), opened_context)]
665
+ try:
666
+ while stack:
667
+ parent, here, held, entries, context = stack[-1]
668
+ entry = next(entries, None)
669
+ if entry is None:
670
+ stack.pop()
671
+ context.close()
672
+ try:
673
+ storage._tree_rmdir(parent, here)
674
+ except FileNotFoundError:
675
+ pass
676
+ except OSError as exc:
677
+ failed.append(exc)
678
+ continue
679
+ child, is_directory = entry
680
+ try:
681
+ if is_directory:
682
+ context = ExitStack()
683
+ try:
684
+ inner = context.enter_context(storage._tree_child(held, child))
685
+ except BaseException:
686
+ context.close()
687
+ raise
688
+ if inner is None:
689
+ context.close()
690
+ continue
691
+ stack.append((held, child, inner, _directory_entries(inner, failed), context))
692
+ else:
693
+ storage._tree_remove_leaf(held, child)
694
+ except FileNotFoundError:
695
+ pass
696
+ except OSError as exc:
697
+ failed.append(exc)
698
+ finally:
699
+ for _, _, _, _, context in reversed(stack):
700
+ context.close()
701
+
702
+
703
+ def _directory_entries(directory, failed):
704
+ """An iterator of (name, whether it is a directory itself, not through a link) over an open directory, read whole
705
+ before anything in it is deleted; an error goes into `failed`, and the entries read before it stay."""
706
+ found = []
707
+ try:
708
+ with os.scandir(directory) as entries:
709
+ for entry in entries:
710
+ try:
711
+ found.append((entry.name, entry.is_dir(follow_symlinks=False)
712
+ and (isinstance(directory, int) or not
713
+ getattr(entry.stat(follow_symlinks=False), "st_file_attributes", 0) & 0x400)))
714
+ except OSError:
715
+ found.append((entry.name, False)) # deleted as a file, or named with why it is not
716
+ except OSError as exc:
717
+ failed.append(exc)
718
+ return iter(found)
719
+
720
+
721
+ def cmd_remove(cfg, args):
722
+ """Take polyctl off only after every reachable hook target passes one preflight, and while no lane stands."""
723
+ root = cfg["root"]
724
+ redirected = _commit_repository_binding(root)
725
+ if redirected:
726
+ print(f"{C['red']}remove refused; polyctl state kept intact{C['reset']}: {redirected}")
727
+ return 1
728
+ key, owned = _remove_key(root)
729
+ from . import skillkit
730
+ harness_files, _ = skillkit.polyctl_files(root)
731
+ # Found as `polyctl uninstall` finds them, an entry named polyctl taken only when it runs polyctl's server, and read
732
+ # now: the adapters that declare the files may be the project's own, in the .polyctl/ this removes
733
+ # (UPDATE-UNINSTALL-2).
734
+ mcp_entries, mcp_unread = _mcp_entries(root)
735
+ plan = [PROJECT_MARKER, ".polyctl/", "agent-mail/", cfg.get("reviews", "semantic-review") + "/"] + harness_files
736
+ print(f"{C['b']}polyctl remove{C['reset']} would delete from {root}:")
737
+ for rel in plan:
738
+ words = _plan_words(rel)
739
+ if words is None:
740
+ print(f" {C['red']}not {rel}{C['reset']}: it names no path inside the project")
741
+ elif os.path.exists(os.path.join(root, *words)):
742
+ print(f" {rel}")
743
+ for path, _, _ in mcp_entries:
744
+ print(f" {os.path.relpath(path, root)}: the `polyctl` server entry (other entries stay)")
745
+ for path, why in mcp_unread:
746
+ print(f" {C['red']}cannot read {os.path.relpath(path, root)}{C['reset']}: {why}; any `polyctl` entry in it stays")
747
+ try:
748
+ _, _, dropped, unclaimed = _gitignore_without_polyctl(root)
749
+ except OSError as exc:
750
+ dropped, unclaimed = 0, []
751
+ print(f" {C['red']}cannot read .gitignore{C['reset']}: {exc}; the lines polyctl added stay")
752
+ if dropped:
753
+ print(" .gitignore: the lines polyctl added")
754
+ for line, _ in unclaimed:
755
+ print(f" {C['yellow']}stays{C['reset']} .gitignore line {line} and the lines under it: {GITIGNORE_UNCLAIMED}")
756
+ # Outside the tree, each thing by name, found as the removal below finds it (SAFE-REMOVE).
757
+ for kind, name in _installed_jobs(key) if owned else []:
758
+ print(f" {kind} {name}")
759
+ for path in _project_home_files(key, root) if owned else []:
760
+ print(f" {_home_relative(path)}")
761
+ requests = A.review_requests_dir(root, key) if owned else None
762
+ if requests and os.path.isdir(requests) and not os.path.islink(requests):
763
+ # Its stand-in review requests, kept outside the tree since REVIEW-PATH-HIGHS, as .polyctl/ kept them before.
764
+ print(f" {_home_relative(requests)}/: the review requests polyctl wrote for it")
765
+ for name in _registry_names(root):
766
+ print(f" {_home_relative(A.project_registry_path())}: the `{name}` entry (other projects stay)")
767
+ archive = os.path.join(A.HOME, ".polyctl", "archive", key)
768
+ print(f" {C['dim']}hook files only when statically POLYCTL-owned, untracked, and fully authorized; "
769
+ f"protected dead-misplaced files are preserved{C['reset']}")
770
+ print(f" {C['dim']}not touched: product files, reviews you moved elsewhere, "
771
+ + (f"what polyctl archived in {_home_relative(archive)}/, " if owned and os.path.isdir(archive) else "")
772
+ + f"other projects' and the machine's files in ~/.polyctl, "
773
+ f"{' / '.join(skillkit.rule_file_names(root))} text (paste-in was yours){C['reset']}")
774
+ # What only a layer an agent can write names as polyctl's is named and left (REMOVE-SHIPPED).
775
+ for rel in skillkit.layer_polyctl_files(root):
776
+ if os.path.lexists(os.path.join(root, rel)):
777
+ print(f" {C['dim']}left: {A.shown_text(rel)}, which only a user's or a project's adapter layer names "
778
+ f"as polyctl's; polyctl deletes what an adapter it ships names, and you can delete it if polyctl wrote it"
779
+ f"{C['reset']}")
780
+ if not owned:
781
+ print(f" {C['dim']}nothing of ~/.polyctl: no .polyctl/ here, and the registry holds no project at this path"
782
+ f"{C['reset']}")
783
+ # A lane's record is in .polyctl/, and with it gone no polyctl command could retire the lane's worktree or branch.
784
+ lanes = A.lane_records(root)
785
+ for lane in lanes:
786
+ who = lane.get("item") or lane["name"]
787
+ print(f" {C['red']}refused while it stands{C['reset']}: lane {who} at {lane.get('path') or '-'}; "
788
+ f"`polyctl lane remove {who}` retires it first")
789
+ if not args.yes:
790
+ print(f"\nre-run with {C['b']}--yes{C['reset']} to do it")
791
+ return 0
792
+ if lanes:
793
+ print(f"{C['red']}remove refused; polyctl state kept intact{C['reset']}: {len(lanes)} lane(s) stand, and "
794
+ f".polyctl/ holds what retires them: `polyctl lane remove {lanes[0].get('item') or lanes[0]['name']}`"
795
+ + (" and the rest, as `polyctl lane list` shows" if len(lanes) > 1 else "") + " first")
796
+ return 1
797
+
798
+ enrollment = _project_enrollment(root)
799
+ if enrollment["state"] in ("broken", "redirected"):
800
+ print(f"{C['red']}remove refused; polyctl state kept intact{C['reset']}: "
801
+ f"{enrollment['detail']}")
802
+ return 1
803
+ if enrollment["state"] == "enrolled":
804
+ marker_path = os.path.join(root, PROJECT_MARKER)
805
+ if os.path.lexists(marker_path):
806
+ if os.path.isdir(marker_path) and not os.path.islink(marker_path):
807
+ print(f"{C['red']}remove refused; polyctl state kept intact{C['reset']}: "
808
+ f"{PROJECT_MARKER} is a directory")
809
+ return 1
810
+ try:
811
+ os.remove(marker_path)
812
+ except OSError as exc:
813
+ print(f"{C['red']}remove refused; polyctl state kept intact{C['reset']}: "
814
+ f"cannot remove {PROJECT_MARKER}: {exc}")
815
+ return 1
816
+ print(f"removed working-tree {PROJECT_MARKER}")
817
+ print(f"{C['yellow']}phase 1/2{C['reset']} — polyctl project state and enforcement remain active")
818
+ print(f" stage the marker deletion: git add -u -- {PROJECT_MARKER}")
819
+ print(" authorize and commit that deletion, then run: polyctl remove --yes")
820
+ return 0
821
+
822
+ allow = bool(getattr(args, "allow_shared_hooks", False))
823
+ inventory = _polyctl_hook_inventory(root)
824
+ safe, hook_plan, _ = _remove_hook_preflight(inventory, allow)
825
+ if not safe:
826
+ return 1
827
+ for target in hook_plan:
828
+ try:
829
+ os.remove(target["path"])
830
+ print(f"removed {target['role']} — {target['path']}")
831
+ except OSError as exc:
832
+ print(f"{C['red']}failed to remove hook; state kept intact{C['reset']} "
833
+ f"{target['path']}: {exc}")
834
+ return 1
835
+
836
+ # Re-resolve before the first state deletion. A topology race cannot turn a
837
+ # shared live hook into an unrecorded survivor behind deleted polyctl state.
838
+ after_hooks = _polyctl_hook_inventory(root)
839
+ safe, new_plan, _ = _remove_hook_preflight(after_hooks, allow)
840
+ if not safe or new_plan:
841
+ print(f"{C['red']}hook topology changed during remove; state kept intact{C['reset']}")
842
+ return 1
843
+
844
+ # The jobs go first, in this process, and each is checked gone (SAFE-REMOVE). A job left
845
+ # behind runs against the project every few minutes, so its state stays until none is left,
846
+ # and so it does while a scheduler cannot say whether it holds one (LEADS-INSTALL).
847
+ left = []
848
+ for kind, name in _installed_jobs(key) if owned else []:
849
+ problem = _unschedule(name)
850
+ if problem:
851
+ left.append(name)
852
+ print(f"{C['red']}left{C['reset']} {kind} {name}: {problem}")
853
+ else:
854
+ print(f"removed {kind} {name}")
855
+ if left:
856
+ print(f"{C['red']}remove stopped; polyctl state kept intact{C['reset']}: {len(left)} scheduled job(s) may go on "
857
+ "running against a removed project — take each off as said above, then run: polyctl remove --yes")
858
+ return 1
859
+
860
+ for rel in plan:
861
+ problem = _remove_in_project(root, rel)
862
+ if problem:
863
+ left.append(os.path.join(root, rel))
864
+ print(f"{C['red']}left{C['reset']} {rel}: {problem}")
865
+ for path, mcp_key, remove_when_empty in mcp_entries:
866
+ shown = os.path.relpath(path, root)
867
+ try:
868
+ gone = _drop_mcp_entry(path, mcp_key, remove_when_empty, root)
869
+ except (OSError, ValueError) as exc:
870
+ left.append(path)
871
+ print(f"{C['red']}left{C['reset']} the `polyctl` entry in {shown}: {' '.join(str(exc).split())}")
872
+ continue
873
+ print(f"removed {shown}, which held only polyctl's entry" if gone == "file"
874
+ else f"removed the `polyctl` entry from {shown}")
875
+ for path, why in mcp_unread:
876
+ left.append(path)
877
+ print(f"{C['red']}left{C['reset']} {os.path.relpath(path, root)}: it cannot be read ({why}), "
878
+ "so any `polyctl` entry in it stays")
879
+ gi = os.path.join(root, ".gitignore")
880
+ try:
881
+ gi, keep, dropped, unclaimed = _gitignore_without_polyctl(root)
882
+ if dropped:
883
+ from .storage import replace_in_tree
884
+ replace_in_tree(root, ".gitignore", "\n".join(keep).encode(UTF8))
885
+ except OSError as exc:
886
+ left.append(gi)
887
+ print(f"{C['red']}left{C['reset']} the lines polyctl added to .gitignore: {exc}")
888
+ else:
889
+ # Named, and no failure of the removal: lines polyctl cannot tell it wrote are the person's until they say not.
890
+ for before, after in unclaimed:
891
+ print(f"{C['yellow']}kept{C['reset']} .gitignore line {after if dropped else before} and the lines under "
892
+ f"it: {GITIGNORE_UNCLAIMED}")
893
+ # Exactly this project's files in ~/.polyctl, named by the table their writers name them from, and
894
+ # its row of the registry, which stays for every other project (SAFE-REMOVE).
895
+ removed = 0
896
+ for path in _project_home_files(key, root) if owned else []:
897
+ try:
898
+ os.remove(path)
899
+ removed += 1
900
+ except OSError as exc:
901
+ left.append(path)
902
+ print(f"{C['red']}left{C['reset']} {_home_relative(path)}: {exc}")
903
+ if removed:
904
+ print(f"removed {removed} file(s) of {key} from {_home_relative(os.path.join(A.HOME, '.polyctl'))}")
905
+ # Its stand-in review requests, which polyctl keeps outside the tree, each file by name and then their folder, which
906
+ # no other project's name reaches (REVIEW-PATH-HIGHS).
907
+ requests = A.review_requests_dir(root, key) if owned else None
908
+ if requests and os.path.isdir(requests) and not os.path.islink(requests):
909
+ try:
910
+ for name in os.listdir(requests):
911
+ os.remove(os.path.join(requests, name))
912
+ os.rmdir(requests)
913
+ print(f"removed {_home_relative(requests)}/, the review requests polyctl wrote for it")
914
+ except OSError as exc:
915
+ left.append(requests)
916
+ print(f"{C['red']}left{C['reset']} {_home_relative(requests)}/: {exc}")
917
+ registry = _home_relative(A.project_registry_path())
918
+ try:
919
+ for name in A.forget_project(root) if owned else []:
920
+ print(f"removed the `{name}` entry from {registry}")
921
+ except (OSError, ValueError) as exc:
922
+ left.append(registry)
923
+ print(f"{C['red']}left{C['reset']} the `{key}` entry in {registry}: {exc}")
924
+ if left:
925
+ print(f"{C['red']}not complete{C['reset']} — phase 2/2 left {len(left)} thing(s) behind, each named above")
926
+ return 1
927
+ print(f"{C['green']}removed{C['reset']} — phase 2/2 complete; polyctl state is gone and preserved local source hooks are inert")
928
+ return 0
929
+
930
+
931
+ def _alive(pid):
932
+ # os.kill(pid, 0) is CTRL_C_EVENT on Windows, not a question (#71).
933
+ return A._pid_alive(pid)
934
+
935
+
936
+ # What each store is for. The split matters: pruning operational noise is
937
+ # housekeeping, pruning evidence destroys the record that commit authority was
938
+ # granted against — so they cannot share a default.
939
+ STORES = [
940
+ ("progress", "operational", ".polyctl/ledger/progress.jsonl", "watchdog samples behind the spin check"),
941
+ ("notices", "operational", ".polyctl/ledger/notices.jsonl", "alerts raised and suppressed"),
942
+ ("inbox", "operational", ".polyctl/inbox", "imported source pulls (*.imported)"),
943
+ ("verifications", "evidence", ".polyctl/ledger/verifications.jsonl", "measured gate results"),
944
+ ("plans", "evidence", ".polyctl/ledger/plans.jsonl", "plan hashes as admitted"),
945
+ ]
946
+ HOME_LOGS = ["nudge-log", "watchdog-log", "refill-log"] # PROJECT_FILES
947
+
948
+
949
+ def _prune_jsonl(path, cutoff, dry):
950
+ """Drop records older than cutoff. Returns (dropped, kept, bytes_freed)."""
951
+ if not os.path.exists(path):
952
+ return 0, 0, 0
953
+ before = os.path.getsize(path)
954
+ keep = []
955
+ dropped = 0
956
+ for line in open(path, errors="replace", encoding=UTF8):
957
+ if not line.strip():
958
+ continue
959
+ try:
960
+ if json.loads(line).get("at", 0) < cutoff:
961
+ dropped += 1
962
+ continue
963
+ except Exception:
964
+ pass # unparseable: keep it, do not silently lose data
965
+ keep.append(line if line.endswith("\n") else line + "\n")
966
+ if dropped and not dry:
967
+ from .storage import replace_file_durably
968
+ replace_file_durably(path, "".join(keep).encode(UTF8))
969
+ freed = before - sum(len(k.encode()) for k in keep) if dropped else 0
970
+ return dropped, len(keep), max(0, freed)
971
+
972
+
973
+ def cmd_prune(cfg, args):
974
+ """Trim the records this tool accumulates, without touching the audit trail.
975
+
976
+ Every store here grows monotonically — one nudge log reached 295 KB in a
977
+ night, and the progress ledger gains a row every two minutes. Left alone they
978
+ become the reason someone stops running the tool.
979
+
980
+ Evidence is excluded by default and needs `--evidence`. Verification records
981
+ and plan hashes are what commit authority was granted against; deleting them
982
+ as housekeeping would quietly remove the ability to answer "on what basis did
983
+ this land".
984
+ """
985
+ root = cfg["root"]
986
+ cutoff = time.time() - args.days * 86400
987
+ dry = not args.yes
988
+ key = A.project_key(root)
989
+ print(f"{C['b']}pruning records older than {args.days} day(s){C['reset']}"
990
+ f"{C['dim']} {root}{C['reset']}")
991
+ if dry:
992
+ print(f"{C['yellow']}dry run — add --yes to apply{C['reset']}")
993
+
994
+ total = 0
995
+ for name, kind, rel, desc in STORES:
996
+ if kind == "evidence" and args.evidence:
997
+ # Evidence is never pruned. A chained ledger past its bound is sealed:
998
+ # its oldest rows move whole to .polyctl/ledger/sealed/ and stay readable (#50).
999
+ keep = S.get(cfg, "retention.evidence_keep")
1000
+ sealed = None
1001
+ if name == "verifications" and not dry:
1002
+ from .storage import seal_chained_jsonl
1003
+ sealed = seal_chained_jsonl(os.path.join(root, rel), A.VERIFICATION_CHAIN, keep, legacy_prefix=True)
1004
+ print(f" {C['dim']}keep {name:<14} evidence is never pruned; "
1005
+ + (f"sealed through row {sealed['retired']} into .polyctl/ledger/sealed/" if sealed
1006
+ else "plans are kept whole; never sealed" if name == "plans"
1007
+ else f"rows past the newest {keep} are sealed, not dropped") + f"{C['reset']}")
1008
+ continue
1009
+ if kind == "evidence" and not args.evidence:
1010
+ path = os.path.join(root, rel)
1011
+ if os.path.exists(path):
1012
+ n = sum(1 for _ in open(path, errors="replace", encoding=UTF8))
1013
+ print(f" {C['dim']}skip {name:<14} {n} records — evidence, needs --evidence{C['reset']}")
1014
+ continue
1015
+ path = os.path.join(root, rel)
1016
+ if name == "inbox":
1017
+ if not os.path.isdir(path):
1018
+ continue
1019
+ gone = 0
1020
+ for f in os.listdir(path):
1021
+ fp = os.path.join(path, f)
1022
+ if f.endswith(".imported") and os.path.getmtime(fp) < cutoff:
1023
+ total += os.path.getsize(fp)
1024
+ gone += 1
1025
+ if not dry:
1026
+ os.remove(fp)
1027
+ if gone:
1028
+ print(f" {C['green']}{'would drop' if dry else 'dropped'}{C['reset']} "
1029
+ f"{name:<14} {gone} file(s) {C['dim']}{desc}{C['reset']}")
1030
+ continue
1031
+ # What the prune drops still counts in a window once folded (NOTICE-WINDOW); a fold that could not be
1032
+ # written leaves the ledger whole (NOTICE-WINDOW-2).
1033
+ if name == "notices" and not dry and not A.fold_notice_times(root):
1034
+ print(f" {C['yellow']}kept{C['reset']} {name:<14} the notices could not be folded, and what no fold "
1035
+ f"counted is not dropped {C['dim']}{desc}{C['reset']}")
1036
+ continue
1037
+ dropped, kept, freed = _prune_jsonl(path, cutoff, dry)
1038
+ total += freed
1039
+ if dropped:
1040
+ print(f" {C['green']}{'would drop' if dry else 'dropped'}{C['reset']} "
1041
+ f"{name:<14} {dropped} of {dropped + kept} {C['dim']}{desc}{C['reset']}")
1042
+
1043
+ # Review artefacts stay while anything rests on them; the rest leave by age (#38).
1044
+ review_days = getattr(args, "review_days", None)
1045
+ if review_days is None:
1046
+ review_days = S.get(cfg, "review.prune_after_days")
1047
+ try:
1048
+ outcome = A.prune_review_artefacts(root, cfg, review_days, apply=not dry)
1049
+ except Exception as exc:
1050
+ print(f" {C['yellow']}keep {'reviews':<14} every artefact: what rests on them cannot be read "
1051
+ f"({exc}){C['reset']}")
1052
+ else:
1053
+ why = {}
1054
+ for reasons in outcome["kept"].values():
1055
+ for reason in reasons:
1056
+ why[reason] = why.get(reason, 0) + 1
1057
+ if outcome["moved"]:
1058
+ total += outcome["bytes"]
1059
+ print(f" {C['green']}{'would move' if dry else 'moved'}{C['reset']} {'reviews':<14} "
1060
+ f"{len(outcome['moved'])} older than {review_days:g} day(s) that nothing rests on "
1061
+ f"{C['dim']}→ {outcome['archive']}{C['reset']}")
1062
+ if outcome["kept"] or outcome["recent"]:
1063
+ detail = ", ".join(f"{count} {reason}" for reason, count in sorted(why.items()))
1064
+ print(f" {C['dim']}keep {'reviews':<14} {len(outcome['kept'])} referenced"
1065
+ + (f" ({detail})" if detail else "") + f", {outcome['recent']} recent{C['reset']}")
1066
+
1067
+ # The authority chain is never truncated by deletion: past its bound it is sealed (#50).
1068
+ if args.evidence and not dry:
1069
+ from .storage import seal_chained_jsonl
1070
+ sealed = seal_chained_jsonl(os.path.join(root, ".polyctl", "ledger", "authority.jsonl"), A.AUTHORITY_CHAIN,
1071
+ S.get(cfg, "retention.evidence_keep"))
1072
+ if sealed:
1073
+ print(f" {C['green']}sealed{C['reset']} {'authority':<14} through row {sealed['retired']}; "
1074
+ f"{C['dim']}polyctl commit-check validates across the seal{C['reset']}")
1075
+ # Dedupe by inode, not by path string: this filesystem is case-insensitive, so
1076
+ # "nudge-Acme-API.log" and "nudge-acme-api.log" are one file that would
1077
+ # otherwise be counted — and truncated — twice.
1078
+ seen_inodes = set()
1079
+ for name in HOME_LOGS:
1080
+ path = os.path.join(A.HOME, ".polyctl", A.project_file_name(name, key))
1081
+ alt = os.path.join(A.HOME, ".polyctl", A.project_file_name(name, key.lower()))
1082
+ for pth in {path, alt}:
1083
+ if not os.path.exists(pth):
1084
+ continue
1085
+ ino = os.stat(pth).st_ino
1086
+ if ino in seen_inodes:
1087
+ continue
1088
+ seen_inodes.add(ino)
1089
+ size = os.path.getsize(pth)
1090
+ if size < args.keep_kb * 1024:
1091
+ continue
1092
+ if not dry:
1093
+ # keep the tail: the last turn's output is the only part anyone
1094
+ # reads, and it is what a failed nudge is diagnosed from
1095
+ with open(pth, errors="replace", encoding=UTF8) as fh:
1096
+ fh.seek(max(0, size - args.keep_kb * 1024))
1097
+ tail = fh.read()
1098
+ with open(pth, "w", encoding=UTF8) as fh:
1099
+ fh.write(f"[truncated by polyctl prune {datetime.now():%Y-%m-%d %H:%M}]\n" + tail)
1100
+ total += size - args.keep_kb * 1024
1101
+ print(f" {C['green']}{'would trim' if dry else 'trimmed'}{C['reset']} "
1102
+ f"{os.path.basename(pth):<24} {size // 1024}KB → {args.keep_kb}KB")
1103
+
1104
+ print(f"\n{C['b']}{total // 1024}KB{C['reset']} {'reclaimable' if dry else 'reclaimed'}")
1105
+ return 0
1106
+
1107
+
1108
+ def _notice_facts(row):
1109
+ """One recorded notice as `polyctl notices --json` prints it: every key present, null where an older row has none."""
1110
+ return {"id": row.get("id"), "at": row.get("at"), "title": row.get("title"), "msg": row.get("msg"),
1111
+ "sent": bool(row.get("sent")), "key": row.get("key"), "evidence": row.get("evidence")}
1112
+
1113
+
1114
+ def cmd_notices(cfg, args):
1115
+ """Alerts this project raised — the desktop notification, kept.
1116
+
1117
+ A notification reaches the human and vanishes, so the architect reading the
1118
+ panel is the one participant who never sees what the human was told.
1119
+
1120
+ With --json the same rows are one JSON document and nothing else (JSON-OUTPUT): the list,
1121
+ or the one notice an id names, with null and exit 1 for an id no notice has.
1122
+ """
1123
+ root = cfg["root"]
1124
+ wanted = getattr(args, "ident", None)
1125
+ as_json = getattr(args, "json", False)
1126
+ if wanted:
1127
+ # "Why did I get this?" is one command (#37).
1128
+ row = next((r for r in A.notices(root, 10**9, include_suppressed=True) if r.get("id") == wanted), None)
1129
+ if not row:
1130
+ missing = f"no notice {wanted}; `polyctl notices --all` lists them with their ids"
1131
+ print(json.dumps({"notice": None, "error": missing}, ensure_ascii=False) if as_json else A.shown_text(missing))
1132
+ return 1
1133
+ if as_json:
1134
+ print(json.dumps({"notice": _notice_facts(row)}, ensure_ascii=False))
1135
+ return 0
1136
+ when = datetime.fromtimestamp(row["at"]).strftime("%d %b %H:%M")
1137
+ print(f"{C['b']}{A.shown_text(row['title'])}{C['reset']} {C['dim']}{A.shown_text(wanted)} · {when} · "
1138
+ f"{'sent' if row.get('sent') else 'held'} · key {A.shown_text(row.get('key'))}{C['reset']}")
1139
+ print(f" {_shown_lines(row.get('msg'))}")
1140
+ for line in A.evidence_lines(row.get("evidence")):
1141
+ print(f" {A.shown_text(line)}")
1142
+ return 0
1143
+ rows = A.notices(root, args.n, include_suppressed=args.all)
1144
+ if as_json:
1145
+ print(json.dumps({"notices": [_notice_facts(r) for r in rows], "include_suppressed": bool(args.all)},
1146
+ ensure_ascii=False))
1147
+ return 0
1148
+ if not rows:
1149
+ print(f"{C['dim']}No notices recorded.{C['reset']}")
1150
+ return 0
1151
+ for r in rows:
1152
+ when = datetime.fromtimestamp(r["at"]).strftime("%d %b %H:%M")
1153
+ tag = (f"{C['green']}sent{C['reset']}" if r.get("sent")
1154
+ else f"{C['dim']}held{C['reset']}")
1155
+ print(f" {C['dim']}{when}{C['reset']} {tag} {C['b']}{A.shown_text(r['title'])}{C['reset']} {A.shown_text(r['msg'])}"
1156
+ + (f" {C['dim']}{A.shown_text(r['id'])}{' · evidence' if r.get('evidence') else ''}{C['reset']}"
1157
+ if r.get("id") else ""))
1158
+ if not args.all:
1159
+ print(f"{C['dim']} (--all also shows alerts the rate limit suppressed){C['reset']}")
1160
+ return 0
1161
+
1162
+
1163
+ def _package_installed():
1164
+ """Whether this interpreter imports polyctl from its own site directories, as a scheduler starting it would.
1165
+
1166
+ A clone puts its own src/ on the import path; a scheduled `python -m polyctl` from one fails
1167
+ with "No module named polyctl".
1168
+ """
1169
+ import site
1170
+ here = os.path.realpath(os.path.dirname(os.path.dirname(os.path.abspath(A.__file__))))
1171
+ sites = list(site.getsitepackages()) if hasattr(site, "getsitepackages") else []
1172
+ sites.append(site.getusersitepackages())
1173
+ return any(os.path.realpath(path) == here for path in sites)
1174
+
1175
+
1176
+ def _scheduled_argv(console, clone, module):
1177
+ """The words a scheduled job starts one of polyctl's entry points with; None when there are none (SAFE-REMOVE).
1178
+
1179
+ Install fell back to the clone's script whether or not there was a clone: a package whose
1180
+ console scripts are not on PATH, as `pip install --user` leaves it, has no such file, and
1181
+ launchd ran a missing file every two minutes while install said "installed". In order:
1182
+ the console script on PATH, which carries its own interpreter in its shebang (prefixing
1183
+ this process's python imports polyctl from an interpreter that may not have it); the clone's
1184
+ script, with this interpreter, since its shebang is `/usr/bin/env python3`; this
1185
+ interpreter running the module, when it imports polyctl from its own site directories. PATH is searched
1186
+ as polyctl searches it, its absolute entries alone and never the current directory: a console script
1187
+ found through a relative entry, made absolute, named a file in whatever directory install ran in,
1188
+ an agent's tree among them (WINDOWS-NO-CWD-EXEC, where SAFE-REMOVE-2 had made such a path absolute).
1189
+ """
1190
+ found = A.program_path(console)
1191
+ found = os.path.abspath(found) if found else None
1192
+ python = sys.executable if sys.executable and os.path.isfile(sys.executable) else None
1193
+ if found:
1194
+ in_repo = os.path.realpath(found).startswith(os.path.realpath(A.REPO) + os.sep)
1195
+ return ([python] if in_repo and python else []) + [found]
1196
+ script = os.path.join(A.REPO, *clone)
1197
+ if python and os.path.isfile(script):
1198
+ return [python, script]
1199
+ if python and _package_installed():
1200
+ return [python, "-m", module]
1201
+ return None
1202
+
1203
+
1204
+ def _schedule_refused(missing):
1205
+ print(f"{C['red']}not installed{C['reset']}: nothing a scheduler can start for {' or '.join(missing)} — not on "
1206
+ "PATH, no clone beside this code, and this interpreter imports no installed polyctl")
1207
+ print(" put the directory holding polyctl's console scripts on PATH, or install the jobs from a clone")
1208
+ return 1
1209
+
1210
+
1211
+ def _watchdog_programs():
1212
+ """(the watchdog's words, the doctor's words) a scheduler starts; None, once refused, when either has none.
1213
+
1214
+ launchd and a user systemd both need an absolute program that exists: resolve the one this
1215
+ installation has, or refuse before anything is written, since a job naming a missing file
1216
+ fails silently (SAFE-REMOVE).
1217
+ """
1218
+ wargv = _scheduled_argv("polyctl-watchdog", ("scripts", "polyctl-watchdog"), "polyctl.watchdog")
1219
+ dargv = _scheduled_argv("polyctl", ("bin", "polyctl"), "polyctl")
1220
+ missing = [name for name, argv in (("polyctl-watchdog", wargv), ("polyctl", dargv)) if argv is None]
1221
+ if missing:
1222
+ _schedule_refused(missing)
1223
+ return None
1224
+ return wargv, dargv
1225
+
1226
+
1227
+ def _job_log(what, key):
1228
+ """Where a scheduled job's output goes: its PROJECT_FILES log in ~/.polyctl, `watchdog-log` or `doctor-log`."""
1229
+ return os.path.join(A.HOME, ".polyctl", A.project_file_name(what, key))
1230
+
1231
+
1232
+ def _forget_heartbeat(root):
1233
+ """Remove the watchdog's heartbeat with its jobs.
1234
+
1235
+ A heartbeat left behind reads as a dead watchdog to every other project (audit).
1236
+ """
1237
+ try:
1238
+ os.remove(A.heartbeat_path(root))
1239
+ except OSError:
1240
+ pass
1241
+
1242
+
1243
+ def _print_watchdog_health(root, log):
1244
+ """How the recorded cycles went and the log's last lines, as `polyctl watchdog status` shows them under any scheduler."""
1245
+ from .watchdog import cycle_health
1246
+ health = cycle_health(root)
1247
+ if health:
1248
+ took = (f"longest took {health['longest_seconds']:.0f}s at {health['longest_at']}"
1249
+ if health["longest_seconds"] is not None else "durations not recorded yet")
1250
+ gap = (f"longest gap {health['gap_minutes']:.0f}m before {health['gap_at']}"
1251
+ if health["gap_at"] else "no gaps")
1252
+ print(f"cycles {health['count']} recorded · {took} · {gap}")
1253
+ if os.path.exists(log):
1254
+ print(f"\nlast lines of {log}:")
1255
+ print(_log_tail(log))
1256
+
1257
+
1258
+ def _systemd_absent(problem, argvs, seconds, logs):
1259
+ """Say that no user systemd answers here, why, and what runs the same two jobs without it; 1.
1260
+
1261
+ A crontab is the scheduler nearly every Linux has without systemd, and its lines are what
1262
+ a person can paste: the words run through /bin/sh, so each is quoted, and cron reads a `%`
1263
+ as a line break unless it is escaped.
1264
+ """
1265
+ import shlex
1266
+ print(f"{C['red']}not installed{C['reset']}: no user systemd — {problem}")
1267
+ print(" nothing was written. Any scheduler this machine has can run the two jobs; a crontab, for instance:")
1268
+ for job in SYSTEMD_JOBS:
1269
+ minutes = max(1, -(-seconds[job] // 60))
1270
+ line = f"*/{minutes} * * * * {shlex.join(argvs[job])} >> {shlex.quote(logs[job])} 2>&1"
1271
+ print(" " + line.replace("%", "\\%"))
1272
+ print(f" or one watchdog cycle by hand: {shlex.join(argvs['watchdog'])}")
1273
+ return 1
1274
+
1275
+
1276
+ def _watchdog_systemd(cfg, args):
1277
+ """Install, remove or inspect the two jobs as systemd user units: a user systemd is Linux's launchd.
1278
+
1279
+ Each job is a oneshot service and a timer that starts it at once and then every interval, as
1280
+ the launchd job's RunAtLoad and StartInterval do, written to ~/.config/systemd/user and enabled
1281
+ with `systemctl --user`, asked by argument vector. Where no user systemd answers, nothing is
1282
+ written, and what would run the jobs instead is printed (LINUX-SCHEDULER).
1283
+ """
1284
+ root = cfg["root"]
1285
+ key = A.project_key(root).lower()
1286
+ units = {job: _systemd_unit(job, key) for job in SYSTEMD_JOBS}
1287
+ timers = {job: unit + ".timer" for job, unit in units.items()}
1288
+ logs = {job: _job_log(f"{job}-log", key) for job in SYSTEMD_JOBS}
1289
+
1290
+ if args.action == "status":
1291
+ problem = _systemd_user_problem()
1292
+ states = dict.fromkeys(timers.values()) if problem else _systemd_states(*timers.values())
1293
+ present = any(os.path.lexists(path) for unit in units.values() for path in _systemd_files(unit))
1294
+ print(f"unit {timers['watchdog']}")
1295
+ print(f"timer {states[timers['watchdog']] or 'unknown'}")
1296
+ print(f"doctor {states[timers['doctor']] or 'unknown'} (polyctl doctor --check every 15m)")
1297
+ print(f"units {'present' if present else 'absent'} ({_home_relative(_systemd_dir())})")
1298
+ if problem:
1299
+ print(f"systemd {C['yellow']}{problem}{C['reset']}")
1300
+ else:
1301
+ linger = _systemd_linger()
1302
+ print("linger " + (f"no — {LINGER_ADVICE}" if linger == "no" else linger or "unknown"))
1303
+ _print_watchdog_health(root, logs["watchdog"])
1304
+ return 0
1305
+
1306
+ if args.action == "uninstall":
1307
+ left = 0
1308
+ for unit in units.values():
1309
+ present = any(os.path.lexists(path) for path in _systemd_files(unit))
1310
+ problem = _systemd_unschedule(unit + ".timer")
1311
+ if problem:
1312
+ left += 1
1313
+ print(f"{C['red']}left{C['reset']} {unit}.timer: {problem}")
1314
+ elif present:
1315
+ print(f"removed {unit}.timer")
1316
+ _forget_heartbeat(root)
1317
+ return 1 if left else 0
1318
+
1319
+ if args.interval < 1:
1320
+ # OnUnitActiveSec=0 starts the next cycle the moment one ends.
1321
+ print(f"{C['red']}not installed{C['reset']}: --interval is the seconds between cycles, at least 1")
1322
+ return 1
1323
+ programs = _watchdog_programs()
1324
+ if programs is None:
1325
+ return 1
1326
+ wargv, dargv = programs
1327
+ argvs = {"watchdog": wargv + ["--root", root, "--idle-minutes", str(args.idle_minutes)],
1328
+ "doctor": dargv + ["-C", root, "doctor", "--check", "--notify"]}
1329
+ seconds = {"watchdog": args.interval, "doctor": 900}
1330
+ problem = _systemd_user_problem()
1331
+ if problem:
1332
+ return _systemd_absent(problem, argvs, seconds, logs)
1333
+ # StandardOutput=append: takes a path as it stands, with no escape a line break could be written as.
1334
+ broken = [log for log in logs.values() if any(ord(ch) < 32 or ord(ch) == 127 for ch in log)]
1335
+ if broken:
1336
+ print(f"{C['red']}not installed{C['reset']}: a unit cannot send output to a path holding a control "
1337
+ f"character: {broken[0]!r}")
1338
+ return 1
1339
+ os.makedirs(_systemd_dir(), exist_ok=True)
1340
+ os.makedirs(os.path.join(A.HOME, ".polyctl"), exist_ok=True)
1341
+ path = _scheduled_path()
1342
+ for job, unit in units.items():
1343
+ for name, text in _systemd_unit_texts(unit, job, argvs[job], seconds[job], logs[job], root, path).items():
1344
+ with open(os.path.join(_systemd_dir(), name), "w", encoding=UTF8) as fh:
1345
+ fh.write(text)
1346
+ # Restarted rather than started: on a reinstall a timer that is already running starts again and
1347
+ # runs a cycle at once, as the launchd job's bootout and bootstrap do; a start would run none.
1348
+ failed = []
1349
+ for step in (("daemon-reload",), ("enable", *timers.values()), ("restart", *timers.values())):
1350
+ said, status = _systemctl(*step, merge=True)
1351
+ if status != 0:
1352
+ failed.append(said.split("\n")[0].strip() or f"systemctl --user {step[0]} exited {status}")
1353
+ states = _systemd_states(*timers.values())
1354
+ for timer, state in states.items():
1355
+ if state not in SYSTEMD_UP:
1356
+ failed.append(f"{timer} is {state or 'not known to the user manager'}")
1357
+ if failed:
1358
+ print(f"{C['red']}NOT SCHEDULED{C['reset']}: {'; '.join(failed)[:240]}")
1359
+ print(f" run: systemctl --user enable --now {timers['watchdog']} {timers['doctor']}")
1360
+ return 1
1361
+ print(f"installed {timers['watchdog']}")
1362
+ print(f"installed {timers['doctor']} (polyctl doctor --check --notify every 15m — the second, independent check)")
1363
+ print(f" checks every {args.interval}s · nudges after {args.idle_minutes}m idle")
1364
+ print(f" units: {_home_relative(_systemd_dir())}")
1365
+ print(f" log: {logs['watchdog']}")
1366
+ print(f" remove with: polyctl -C {root} watchdog uninstall")
1367
+ if _systemd_linger() == "no":
1368
+ print(f" {C['yellow']}{LINGER_ADVICE}{C['reset']}")
1369
+ return 0
1370
+
1371
+
1372
+ def _watchdog_windows(cfg, args):
1373
+ """Task Scheduler is Windows' launchd: one task every two minutes, one every fifteen."""
1374
+ root = cfg["root"]
1375
+ key = A.project_key(root)
1376
+ idle = getattr(args, "idle_minutes", None) or S.get(cfg, "watchdog.idle_minutes")
1377
+ tasks = {_windows_task("watchdog", key): (2, ("polyctl-watchdog", ("scripts", "polyctl-watchdog"), "polyctl.watchdog"),
1378
+ ["--root", root, "--idle-minutes", str(idle)]),
1379
+ _windows_task("doctor", key): (15, ("polyctl", ("bin", "polyctl"), "polyctl"),
1380
+ ["-C", root, "doctor", "--check", "--notify"])}
1381
+ if args.action == "status":
1382
+ for name in tasks:
1383
+ held = _task_held(name)
1384
+ print(f"{name}: " + ("scheduled" if held is True else "absent" if held is False
1385
+ else f"unknown — Task Scheduler cannot say ({held})"))
1386
+ return 0
1387
+ if args.action == "uninstall":
1388
+ # Each checked gone, as `polyctl remove` checks it: "removed" was printed whatever schtasks did (LEADS-INSTALL).
1389
+ left = 0
1390
+ for name in tasks:
1391
+ problem = _unschedule(name)
1392
+ left += bool(problem)
1393
+ print(f"{C['red']}left{C['reset']} {name}: {problem}" if problem else f"removed {name}")
1394
+ return 1 if left else 0
1395
+ # A task that names a missing program fails every run and says nothing (SAFE-REMOVE).
1396
+ argvs = {name: _scheduled_argv(*entry) for name, (_, entry, _) in tasks.items()}
1397
+ missing = [entry[0] for name, (_, entry, _) in tasks.items() if argvs[name] is None]
1398
+ if missing:
1399
+ return _schedule_refused(missing)
1400
+ failed = 0
1401
+ for name, (minutes, _, rest) in tasks.items():
1402
+ said, status = _schtasks("/Create", "/F", "/SC", "MINUTE", "/MO", str(minutes), "/TN", name,
1403
+ "/TR", subprocess.list2cmdline(argvs[name] + rest))
1404
+ failed += status != 0
1405
+ print(f"{'installed' if status == 0 else 'FAILED'} {name} (every {minutes}m)"
1406
+ + ("" if status == 0 else f": {said[:120] or 'schtasks could not be run'}"))
1407
+ return 1 if failed else 0
1408
+
1409
+
1410
+ def _log_tail(path, count=5):
1411
+ """A log's last `count` lines as `tail -<count>` printed them, stripped; "" when it cannot be read.
1412
+
1413
+ Read back from the end in blocks: a job's log grows for as long as the job runs.
1414
+ """
1415
+ try:
1416
+ with open(path, "rb") as fh:
1417
+ position, data = fh.seek(0, os.SEEK_END), b""
1418
+ while position and data.count(b"\n") <= count:
1419
+ step = min(position, 65536)
1420
+ position -= step
1421
+ fh.seek(position)
1422
+ data = fh.read(step) + data
1423
+ except OSError:
1424
+ return ""
1425
+ lines = data.split(b"\n")
1426
+ if data.endswith(b"\n"):
1427
+ lines.pop()
1428
+ # Decoded as sh() decoded tail's output: text mode also reads a carriage return as a newline.
1429
+ text = b"\n".join(lines[-count:]).decode(UTF8, "replace")
1430
+ return text.replace("\r\n", "\n").replace("\r", "\n").strip()
1431
+
1432
+
1433
+ def cmd_watchdog(cfg, args):
1434
+ if getattr(args, "idle_minutes", None) is None:
1435
+ args.idle_minutes = S.get(cfg, "watchdog.idle_minutes")
1436
+ return _cmd_watchdog(cfg, args)
1437
+
1438
+
1439
+ def _cmd_watchdog(cfg, args):
1440
+ """Install, remove or inspect the jobs that restart a stalled agent: launchd's, a user systemd's on Linux,
1441
+ Task Scheduler's on Windows."""
1442
+ if args.action in ("explain", "trace"):
1443
+ return _watchdog_debug(cfg, args)
1444
+ scheduler = _scheduler()
1445
+ if scheduler == "schtasks":
1446
+ return _watchdog_windows(cfg, args)
1447
+ if scheduler == "systemd":
1448
+ return _watchdog_systemd(cfg, args)
1449
+ root = cfg["root"]
1450
+ key = A.project_key(root).lower()
1451
+ label = _launchd_label("watchdog", key)
1452
+ plist_path = _launchd_plist(label)
1453
+ log = _job_log("watchdog-log", key)
1454
+
1455
+ if args.action == "status":
1456
+ loaded = _launchd_listed(label)
1457
+ dloaded = _launchd_listed(_launchd_label("doctor", key))
1458
+ print(f"label {label}")
1459
+ print(f"doctor {'loaded' if dloaded else 'not installed'} (polyctl doctor --check every 15m)")
1460
+ print(f"plist {'present' if os.path.exists(plist_path) else 'absent'}")
1461
+ print(f"loaded {loaded if loaded else 'no'}")
1462
+ _print_watchdog_health(root, log)
1463
+ return
1464
+
1465
+ if args.action == "uninstall":
1466
+ if _launchctl("bootout", _launchd_domain(label))[1] != 0:
1467
+ _launchctl("unload", plist_path)
1468
+ if os.path.exists(plist_path):
1469
+ os.remove(plist_path)
1470
+ print(f"removed {label}")
1471
+ dlabel = _launchd_label("doctor", key)
1472
+ dplist = _launchd_plist(dlabel)
1473
+ _launchctl("bootout", _launchd_domain(dlabel))
1474
+ if os.path.exists(dplist):
1475
+ os.remove(dplist)
1476
+ print(f"removed {dlabel}")
1477
+ _forget_heartbeat(root)
1478
+ return
1479
+
1480
+ programs = _watchdog_programs()
1481
+ if programs is None:
1482
+ return 1
1483
+ wargv, dargv = programs
1484
+ os.makedirs(os.path.dirname(plist_path), exist_ok=True)
1485
+ os.makedirs(os.path.join(A.HOME, ".polyctl"), exist_ok=True)
1486
+ open(plist_path, "w", encoding=UTF8).write(PLIST.format(
1487
+ path=_launchd_path(), label=label, python_arg="".join(f"<string>{a}</string>" for a in wargv[:-1]),
1488
+ script=wargv[-1], root=root,
1489
+ idle=args.idle_minutes, interval=args.interval, log=log))
1490
+ _launchctl("bootout", _launchd_domain(label))
1491
+ # bootout is asynchronous: a bootstrap issued before the old job is fully
1492
+ # gone fails with "5: Input/output error" and leaves nothing loaded — a
1493
+ # reinstall that silently uninstalled. Wait for the label to clear, retry.
1494
+ out = ""
1495
+ for attempt in range(5):
1496
+ if _launchd_listed(label):
1497
+ time.sleep(1)
1498
+ out, status = _launchctl("bootstrap", _launchd_domain(), plist_path, merge=True)
1499
+ out = out or ("launchctl could not be run" if status is None else "loaded")
1500
+ if "error" not in out.lower() or _launchd_listed(label):
1501
+ break
1502
+ time.sleep(1 + attempt)
1503
+ if not _launchd_listed(label):
1504
+ print(f"{C['red']}NOT LOADED{C['reset']} {label}: {out.strip()[:120]} — run: launchctl bootstrap gui/$(id -u) {plist_path}")
1505
+ return 1
1506
+ print(f"installed {label}")
1507
+ # The second, independent check. A watchdog cannot report its own death;
1508
+ # this job runs `polyctl doctor --check --notify` every fifteen minutes from its own
1509
+ # launchd entry and raises the alarm the watchdog would have.
1510
+ dlabel = _launchd_label("doctor", key)
1511
+ dplist = _launchd_plist(dlabel)
1512
+ dargs = dargv + ["-C", root, "doctor", "--check", "--notify"]
1513
+ open(dplist, "w", encoding=UTF8).write(PLIST_CMD.format(
1514
+ path=_launchd_path(), label=dlabel, args="".join(f"<string>{a}</string>" for a in dargs),
1515
+ interval=900, log=_job_log("doctor-log", key)))
1516
+ _launchctl("bootout", _launchd_domain(dlabel))
1517
+ _launchctl("bootstrap", _launchd_domain(), dplist, merge=True)
1518
+ print(f"installed {dlabel} (polyctl doctor --check --notify every 15m — the second, independent check)")
1519
+ print(f" checks every {args.interval}s · nudges after {args.idle_minutes}m idle")
1520
+ print(f" log: {log}")
1521
+ print(f" remove with: polyctl -C {root} watchdog uninstall")
1522
+ if "error" in out.lower():
1523
+ print(f" launchctl: {out}")
1524
+
1525
+
1526
+ def cmd_projects(cfg, args):
1527
+ ws = A.all_workspaces()
1528
+ if not ws:
1529
+ print("No local agent sessions found.")
1530
+ else:
1531
+ print(f"{'last active':<12}{'agent':<14}{'status':<14}workspace")
1532
+ for r in ws:
1533
+ mins = int((time.time() - r["mtime"]) / 60)
1534
+ age = f"{mins}m" if mins < 90 else (f"{mins//60}h" if mins < 2880 else f"{mins//1440}d")
1535
+ col = C["green"] if mins < 5 else C["dim"]
1536
+ # Every store an adapter declares is listed, and a store that keeps no status says none (SESSION-IDENTITY).
1537
+ print(f"{col}{age:<12}{C['reset']}{str(r['adapter'])[:13]:<14}{str(r['status'] or '—')[:13]:<14}{r['path']}")
1538
+ # Directories with one name used to share every file polyctl keeps outside them (#66).
1539
+ for base, rows in A.project_key_collisions().items():
1540
+ print(f"\n{C['yellow']}{len(rows)} projects are named {base}{C['reset']}; "
1541
+ "each keeps its own files under its key:")
1542
+ for key, where in rows:
1543
+ print(f" {key:<28}{where}")
1544
+
1545
+
1546
+ def cmd_adapters(cfg, args):
1547
+ """Every adapter polyctl can load, where it came from, and whether a candidate is sound (#77)."""
1548
+ root = cfg["root"]
1549
+ action = getattr(args, "action", None) or "list"
1550
+ if action in ("validate", "conform"):
1551
+ target = getattr(args, "target", None)
1552
+ catalog = A.adapter_catalog(root)
1553
+ if target in catalog:
1554
+ adapter = catalog[target]["adapter"]
1555
+ else:
1556
+ try:
1557
+ with open(target or "", encoding=UTF8) as fh:
1558
+ adapter = json.load(fh)
1559
+ except (OSError, ValueError) as exc:
1560
+ print(f"{C['red']}no adapter {target}{C['reset']}: {exc}")
1561
+ return 2
1562
+ if action == "validate":
1563
+ problems = A.validate_adapter(adapter)
1564
+ for problem in problems:
1565
+ print(f" {C['red']}·{C['reset']} {problem}")
1566
+ print(f"{C['green']}sound{C['reset']}" if not problems else f"{len(problems)} problem(s)")
1567
+ return 1 if problems else 0
1568
+ import tempfile
1569
+ harness = os.path.join(os.path.dirname(A.__file__), "conformance_harness.py")
1570
+ # The fixture harness is started by this interpreter, isolated (-I) so that nothing beside the script is
1571
+ # imported. It was a copy whose first line named the interpreter, made executable: Windows runs no such
1572
+ # line and refused to start it, and an interpreter whose path holds a space made a line POSIX cannot read,
1573
+ # so every capability failed as "the harness did not run" (LEADS-INSTALL).
1574
+ with tempfile.TemporaryDirectory(prefix="polyctl-conform-") as workdir:
1575
+ results = A.conform_adapter(adapter, [sys.executable, "-I", harness], workdir)
1576
+ for capability, state, detail in results:
1577
+ tone = C["green"] if state == "pass" else C["red"] if state == "fail" else C["dim"]
1578
+ print(f" {capability:<11} {tone}{state}{C['reset']} {C['dim']}{detail}{C['reset']}")
1579
+ return 1 if any(state == "fail" for _, state, _ in results) else 0
1580
+ avail = A.tool_availability()
1581
+ print(f"{'adapter':<16}{'source':<9}{'contract':<10}{'verified':<12}{'on this machine':<22}observation")
1582
+ for ident, entry in sorted(A.adapter_catalog(root).items()):
1583
+ a = entry["adapter"]
1584
+ if a.get("kind") == "cloud":
1585
+ continue
1586
+ if entry["problem"]:
1587
+ print(f"{ident:<16}{entry['source']:<9}{C['red']}refused{C['reset']} {entry['problem']}")
1588
+ continue
1589
+ verified = a.get("verified", "?")
1590
+ col = C["green"] if verified == "full" else C["yellow"] if verified == "partial" else C["dim"]
1591
+ have = avail.get(ident, {})
1592
+ here = ("installed + account" if have.get("installed") and have.get("account") else "installed"
1593
+ if have.get("installed") else "account, no CLI" if have.get("account") else "—")
1594
+ observation = "call-return" if a.get("observation_mode") == "call-return" \
1595
+ else (a.get("transcript", {}) or {}).get("kind", "—")
1596
+ if observation in ("jsonl", "sqlite", "json", "markdown") and not A.session_store_reachable(a):
1597
+ observation = f"{observation}, not reached"
1598
+ eligible, _ = A.reviewer_eligibility(a)
1599
+ print(f"{ident:<16}{entry['source']:<9}{str(a.get('contract', A.ADAPTER_CONTRACT)):<10}{col}{verified:<12}"
1600
+ f"{C['reset']}{here:<22}{observation:<22}"
1601
+ f"{'reviewer: eligible' if eligible else C['dim'] + 'reviewer: ineligible' + C['reset']}")
1602
+ for vendor in A.vendor_list():
1603
+ if not vendor.get("adapter"):
1604
+ print(f"{vendor['id']:<16}{C['dim']}{'vendor':<9}{'—':<10}{'no adapter':<12}{vendor.get('why', '')}"
1605
+ f"{C['reset']}")
1606
+ for problem in A.vendor_problems():
1607
+ print(f"{C['red']}vendor list{C['reset']}: {problem}")
1608
+ print(f"\n{C['dim']}Account detection via keyflip surfaces; it never reads the secret. Adapters load from the "
1609
+ f"package, then ~/.polyctl/adapters, then .polyctl/adapters; a later one overrides by id.{C['reset']}")
1610
+
1611
+
1612
+ def _optional_features(cfg):
1613
+ """(name, state, what would enable it) for each optional capability, core excluded (#82)."""
1614
+ from . import email, ntfy, telegram
1615
+ root = cfg["root"]
1616
+ mail = email.config()
1617
+ features = [
1618
+ ("keyflip", "installed" if A.program_path("keyflip") else "absent",
1619
+ "install keyflip for account budgets and quota rotation"),
1620
+ ("telegram", "configured" if telegram.config() else "absent", "polyctl telegram setup"),
1621
+ ("ntfy", "configured" if ntfy.config() else "absent", "polyctl ntfy setup"),
1622
+ ("email", f"configured ({mail['provider']})" if mail else "absent", "polyctl email setup"),
1623
+ # The command that sets the ping up: the hint named `polyctl ping set <url>`, which never existed (SECRETS-2).
1624
+ ("ping", "configured" if A.ping_url(root) else "absent", "polyctl pings setup"),
1625
+ ]
1626
+ # A tool reviewer is an optional extra with its own provider account (#86).
1627
+ primary = cfg.get("reviewer") or {}
1628
+ routes = [primary] + list(primary.get("fallbacks") or []) if isinstance(primary, dict) else []
1629
+ configured = {route.get("adapter") for route in routes if _tool_route(route)}
1630
+ for ident, adapter in sorted(A.package_adapters().items()):
1631
+ contract = A.tool_review_contract(adapter)
1632
+ if contract is None:
1633
+ continue
1634
+ found = any(A.program_path(binary) or _tool_beside_interpreter(binary)
1635
+ for binary in A.adapter_binaries(adapter))
1636
+ features.append((ident, "absent" if not found else "configured" if ident in configured else "installed",
1637
+ str(contract.get("install") or f"install {ident}")))
1638
+ return features
1639
+
1640
+
1641
+ def _measurement_lines(cfg):
1642
+ """How polyctl measures, what could filter the numbers an agent reads (#51), and what each filter does to them (#52)."""
1643
+ filters = A.measurement_filters(cfg["root"])
1644
+ state = (f"{C['yellow']}{len(filters)} possible filter(s){C['reset']}" if filters
1645
+ else f"{C['green']}unfiltered{C['reset']}")
1646
+ lines = [f"{'measurement':<16}{state} {C['dim']}polyctl measures with {A.git_binary()}, "
1647
+ f"the candidate without a shell{C['reset']}"]
1648
+ lines += [f"{'':<16}{C['dim']}{text}{C['reset']}" for text in filters]
1649
+ try:
1650
+ probed = A.probe_filters(cfg["root"])
1651
+ except Exception as exc:
1652
+ return lines + [f"{'filter probe':<16}{C['yellow']}cannot tell: {exc}{C['reset']}"]
1653
+ return lines + [f"{'filter probe':<16}{C['green'] if result['verdict'] == 'in-force' else C['yellow']}"
1654
+ f"{A.filter_probe_text(result)}{C['reset']}" for result in probed]
1655
+
1656
+
1657
+ def _review_evidence_lines(cfg):
1658
+ """The reviews a grant rests on that git does not hold: one disk from gone (#38)."""
1659
+ try:
1660
+ risky = A.grant_artefacts_at_risk(cfg["root"], cfg)
1661
+ except Exception as exc:
1662
+ return [f"{'review evidence':<16}{C['yellow']}cannot tell: {exc}{C['reset']}"]
1663
+ if not risky:
1664
+ return [f"{'review evidence':<16}{C['green']}every review a grant rests on is in git{C['reset']}"]
1665
+ untracked = sum(1 for _, state in risky if state == "untracked")
1666
+ lines = [f"{'review evidence':<16}{C['yellow']}{untracked} untracked, {len(risky) - untracked} missing of "
1667
+ f"the reviews grants rest on{C['reset']} {C['dim']}commit them; polyctl prune never moves them{C['reset']}"]
1668
+ lines += [f"{'':<16}{C['dim']}{state:<9} {name}{C['reset']}" for name, state in risky[:5]]
1669
+ if len(risky) > 5:
1670
+ lines.append(f"{'':<16}{C['dim']}and {len(risky) - 5} more{C['reset']}")
1671
+ return lines
1672
+
1673
+
1674
+ def _session_lines(cfg):
1675
+ """`polyctl doctor`'s line for each role's session: the id polyctl resolved and how, or why there is none (SESSION-IDENTITY).
1676
+
1677
+ It printed the implementer's `session` as written, and `auto` read as a session's id.
1678
+ """
1679
+ lines = []
1680
+ for role in A.SESSION_ROLES:
1681
+ state = A.session_state(cfg, role)
1682
+ if state is None:
1683
+ if role == "implementer":
1684
+ lines.append(f"{role:<16}{C['red']}none found{C['reset']}")
1685
+ continue
1686
+ adapter = A.block_adapter(cfg.get(role)) or "?"
1687
+ if state["session"]:
1688
+ tone = C["green"] if state["trusted"] else C["yellow"]
1689
+ head = f"{role:<16}{adapter} / {state['session'][:36]} {tone}{state['how']}{C['reset']}"
1690
+ else:
1691
+ tone = C["red"] if state["how"] == "ambiguous" else C["yellow"]
1692
+ head = f"{role:<16}{adapter} / auto {tone}{state['how']}{C['reset']}"
1693
+ lines.append(head + (f" {C['dim']}{state['why']}{C['reset']}" if state.get("why") else ""))
1694
+ return lines
1695
+
1696
+
1697
+ def _architect_absence_lines(cfg):
1698
+ """How long the architect has been away and how many questions wait for it (#84)."""
1699
+ try:
1700
+ away = A.architect_absence(cfg["root"], cfg)
1701
+ except Exception as exc:
1702
+ return [f"{'architect away':<16}{C['yellow']}cannot tell: {exc}{C['reset']}"]
1703
+ seen = (f"last seen {_elapsed(time.time() - away['seen_at'])} ago" if away["seen_at"]
1704
+ else "not seen in this project's records")
1705
+ if not away["waiting"]:
1706
+ return [f"{'architect away':<16}{C['dim']}{seen} · no question waiting{C['reset']}"]
1707
+ oldest = _elapsed(time.time() - float(away["oldest_at"] or time.time()))
1708
+ return [f"{'architect away':<16}{C['yellow']}{seen} · {len(away['waiting'])} question(s) waiting, the oldest "
1709
+ f"{away['waiting'][0]} for {oldest}{C['reset']} {C['dim']}answered in one pass: polyctl decisions{C['reset']}"]
1710
+
1711
+
1712
+ def _human_bytes(count):
1713
+ for unit in ("B", "KB", "MB", "GB"):
1714
+ if count < 1024 or unit == "GB":
1715
+ return f"{count:.0f} {unit}" if unit == "B" else f"{count:.1f} {unit}"
1716
+ count /= 1024
1717
+
1718
+
1719
+ def cmd_worktrees(cfg, args):
1720
+ """Every worktree, what keeps it and whether it may go; `prune` retires those that may (#42).
1721
+
1722
+ Seven worktrees stood on this machine, one per slice, none removed when its
1723
+ branch landed, each a full checkout with its own state and stale reviews.
1724
+ Prune is a dry run until --yes.
1725
+ """
1726
+ root = cfg["root"]
1727
+ try:
1728
+ facts = A.worktree_facts(root, cfg, sizes=True)
1729
+ except RuntimeError as exc:
1730
+ print(f"{C['red']}{exc}{C['reset']}")
1731
+ return 2
1732
+ pruning = getattr(args, "action", None) == "prune"
1733
+ apply = pruning and getattr(args, "yes", False)
1734
+ if pruning and not apply:
1735
+ print(f"{C['yellow']}dry run — add --yes to apply{C['reset']}")
1736
+ for fact in facts:
1737
+ size = _human_bytes(fact["bytes"]) if fact["bytes"] is not None \
1738
+ else "gone" if not os.path.isdir(fact["path"]) else "—"
1739
+ state = (f"{C['green']}may go{C['reset']} ({fact['why']})" if fact["may_go"]
1740
+ else f"{C['dim']}keep{C['reset']} ({'; '.join(fact['keep']) or 'not merged, slice not rejected'})")
1741
+ print(f" {fact['path']} {C['dim']}{fact['branch'] or 'detached'} · {size}{C['reset']} {state}")
1742
+ if pruning and fact["may_go"]:
1743
+ try:
1744
+ for step in A.prune_worktree(root, fact, apply=apply):
1745
+ print(f" {'done' if apply else 'would'}: {step}")
1746
+ except (OSError, RuntimeError) as exc:
1747
+ print(f" {C['red']}stopped{C['reset']}: {exc}")
1748
+ return 1
1749
+ return 0
1750
+
1751
+
1752
+ def _worktree_lines(cfg):
1753
+ """Worktrees whose branch is merged or gone, with their size on disk (#42)."""
1754
+ try:
1755
+ going = [fact for fact in A.worktree_facts(cfg["root"], cfg, sizes=True) if fact["may_go"]]
1756
+ except Exception as exc:
1757
+ return [f"{'worktrees':<16}{C['yellow']}cannot tell: {exc}{C['reset']}"]
1758
+ if not going:
1759
+ return []
1760
+ total = sum(fact["bytes"] or 0 for fact in going)
1761
+ lines = [f"{'worktrees':<16}{C['yellow']}{len(going)} may go ({_human_bytes(total)}){C['reset']} "
1762
+ f"{C['dim']}polyctl worktrees prune{C['reset']}"]
1763
+ lines += [f"{'':<16}{C['dim']}{fact['path']} {fact['why']} "
1764
+ f"{_human_bytes(fact['bytes']) if fact['bytes'] is not None else 'gone'}{C['reset']}" for fact in going[:5]]
1765
+ return lines
1766
+
1767
+
1768
+ def _harness_config_lines(cfg):
1769
+ """Each change to what a harness reads from this tree that no person has seen, by name, and what records it as
1770
+ seen; or that there is none, or that it cannot be read (HARNESS-CONFIG)."""
1771
+ unseen, unreadable = _harness_config_unseen(cfg["root"])
1772
+ if unreadable:
1773
+ return [f"{'harness config':<16}{C['red']}cannot be read: {unreadable}{C['reset']} {C['dim']}no wake, refill, "
1774
+ f"nudge, hunt or lane starts here until it can{C['reset']}"]
1775
+ if not unseen:
1776
+ return [f"{'harness config':<16}{C['green']}no change nobody has seen{C['reset']}"]
1777
+ lines = [f"{'harness config':<16}{C['yellow']}{len(unseen)} change(s) nobody has seen{C['reset']} "
1778
+ f"{C['dim']}no wake, refill, nudge, hunt or lane starts here until a person reads them: "
1779
+ f"polyctl harness seen --by <name>{C['reset']}"]
1780
+ lines += [f"{'':<16}{A.shown_text(path)} ({A.HARNESS_CONFIG_STATES.get(state, state)})"
1781
+ for path, state, _ in unseen]
1782
+ return lines
1783
+
1784
+
1785
+ def _environment_lines(cfg):
1786
+ """What polyctl runs from, loads or trusts inside the tree an agent writes, one line each; none when nothing is
1787
+ (PYTHON-ENV)."""
1788
+ found = dict(_environment_problem(cfg["root"])).get("environment-in-tree")
1789
+ return [f"{'environment':<16}{C['yellow']}{found}{C['reset']}"] if found else []
1790
+
1791
+
1792
+ def _turn_command_lines(cfg):
1793
+ """Each role's command the watchdog refuses to start, in the words it refuses it in (TURN-ARGV)."""
1794
+ return [f"{'turn command':<16}{C['red']}{text}{C['reset']}" for _, text in _turn_problems(cfg)]
1795
+
1796
+
1797
+ # Said as what is accepted, never as a word to a reviewer: a boundary that tells a reviewer what to answer reads as
1798
+ # the instruction a candidate must not carry (the review of TURN-ARGV). One sentence with no semicolon: a boundary's
1799
+ # semicolons part its criteria, and each criterion needs a verdict of its own (PROVE-BOUNDARY-2).
1800
+ PROVE_BOUNDARY = "polyctl prove: a throwaway candidate whose whole diff adds one line to polyctl-prove.txt and nothing else."
1801
+
1802
+
1803
+ def _prove_throwaway(cfg):
1804
+ """A one-line slice through verify, review and commit-ok in a temporary worktree; nothing lands (#85).
1805
+
1806
+ Returns (ok, what failed or None, what would fix it or None, worktree path or None). The worktree's
1807
+ coordination state and review go to ~/.polyctl/archive/<project>/prove-<stamp>/.
1808
+ """
1809
+ import io
1810
+ import shutil
1811
+ import tempfile
1812
+ root = cfg["root"]
1813
+ scratch = tempfile.mkdtemp(prefix="polyctl-prove-")
1814
+ tree = os.path.join(scratch, "tree")
1815
+ links, unlinked, heard = [], [], io.StringIO()
1816
+ made = False
1817
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
1818
+ try:
1819
+ added = subprocess.run([A.git_binary(), "worktree", "add", "--detach", "--quiet", tree, "HEAD"], cwd=root,
1820
+ capture_output=True)
1821
+ made = added.returncode == 0 or os.path.lexists(os.path.join(tree, ".git"))
1822
+ if added.returncode:
1823
+ result = (False, "a temporary worktree could not be made: "
1824
+ + added.stderr.decode(UTF8, "replace").strip(), "a repository with at least one commit")
1825
+ else:
1826
+ # A step that raises is a check that failed, said with what would fix it: it ended `polyctl prove` in a
1827
+ # traceback (PROVE-2).
1828
+ try:
1829
+ result = _prove_steps(cfg, root, tree, stamp, links, unlinked, heard)
1830
+ except Exception as exc:
1831
+ result = (False, f"the throwaway slice stopped: {type(exc).__name__}: {' '.join(str(exc).split())}",
1832
+ "run the step it names by hand in this checkout, or `polyctl doctor`")
1833
+ finally:
1834
+ for link in links:
1835
+ try:
1836
+ os.unlink(link)
1837
+ except OSError:
1838
+ pass
1839
+ # An archive that cannot be written is said, and the worktree goes all the same: a copy that raised here
1840
+ # skipped the removal below and left the worktree registered in the checkout (LEADS-INSTALL).
1841
+ try:
1842
+ _archive_throwaway(cfg, root, tree, stamp)
1843
+ except Exception as exc:
1844
+ print(f" {C['yellow']}the throwaway's coordination state and review were not archived{C['reset']}: "
1845
+ f"{type(exc).__name__}: {' '.join(str(exc).split())}")
1846
+ finally:
1847
+ try:
1848
+ cleanup_steps = (("remove", "--force", tree), ("prune",)) if made else ()
1849
+ if not made:
1850
+ shutil.rmtree(scratch, ignore_errors=True)
1851
+ for cleanup_args in cleanup_steps:
1852
+ try:
1853
+ A._git_worktree_cleanup(root, *cleanup_args)
1854
+ except A.WorktreeCleanupRefused:
1855
+ raise
1856
+ except RuntimeError as exc:
1857
+ print(f"{C['yellow']}worktree cleanup incomplete{C['reset']}: "
1858
+ f"{' '.join(str(exc).split())}; inspect the worktree administration and retry cleanup")
1859
+ if cleanup_args[0] == "remove":
1860
+ shutil.rmtree(scratch, ignore_errors=True)
1861
+ except A.WorktreeCleanupRefused as exc:
1862
+ result = (False, f"worktree cleanup failed: {exc}", "repair the worktree administration and retry")
1863
+ return (*result, tree if made else None)
1864
+
1865
+
1866
+ def _archive_throwaway(cfg, root, tree, stamp):
1867
+ """Copy the throwaway's .polyctl/ and reviews to ~/.polyctl/archive/<project>/prove-<stamp>/, a directory of this run's own.
1868
+
1869
+ Named by the second, two runs in one second shared a directory and the second was merged into the
1870
+ first (LEADS-INSTALL): one that is there already is followed by -2, -3 and on, each made by this run.
1871
+ """
1872
+ import shutil
1873
+ parts = [part for part in (".polyctl", cfg.get("reviews", "semantic-review")) if os.path.isdir(os.path.join(tree, part))]
1874
+ if not parts:
1875
+ return None
1876
+ parent = os.path.join(A.HOME, ".polyctl", "archive", A.project_key(root))
1877
+ os.makedirs(parent, exist_ok=True)
1878
+ count = 1
1879
+ while True:
1880
+ archive = os.path.join(parent, f"prove-{stamp}" + (f"-{count}" if count > 1 else ""))
1881
+ try:
1882
+ os.mkdir(archive)
1883
+ break
1884
+ except FileExistsError:
1885
+ count += 1
1886
+ for part in parts:
1887
+ shutil.copytree(os.path.join(tree, part), os.path.join(archive, part), symlinks=True)
1888
+ return archive
1889
+
1890
+
1891
+ def _prove_steps(cfg, root, tree, stamp, links, unlinked, heard):
1892
+ """The throwaway slice's own steps, in a worktree made for them: (ok, what failed, what would fix it)."""
1893
+ import contextlib
1894
+ import shutil
1895
+ from types import SimpleNamespace
1896
+ os.makedirs(os.path.join(tree, ".polyctl"), exist_ok=True)
1897
+ for name in ("config.json", "gates.json"):
1898
+ if os.path.exists(os.path.join(root, ".polyctl", name)):
1899
+ shutil.copy2(os.path.join(root, ".polyctl", name), os.path.join(tree, ".polyctl", name))
1900
+ with open(os.path.join(tree, ".polyctl", "board.md"), "w", encoding=UTF8) as fh:
1901
+ fh.write(f"# Board\n\n## running\n- [POLYCTL-PROVE] a throwaway one-line change · acceptance: {PROVE_BOUNDARY}\n"
1902
+ "\n## blocked\n\n## queued\n\n## verified\n\n## done\n")
1903
+ for name in S.get(cfg, "merge.link_paths"):
1904
+ source, target = os.path.join(root, name), os.path.join(tree, name)
1905
+ if os.path.exists(source) and not os.path.lexists(target):
1906
+ try:
1907
+ os.symlink(source, target)
1908
+ links.append(target)
1909
+ except OSError as exc:
1910
+ # Named when a gate fails: a gate that needed it failed for this, not for the change (PROVE-2).
1911
+ unlinked.append(f"{name} ({' '.join(str(exc).split())})")
1912
+ with open(os.path.join(tree, "polyctl-prove.txt"), "a", encoding=UTF8) as fh:
1913
+ fh.write(f"polyctl prove {stamp}\n")
1914
+ subprocess.run([A.git_binary(), "add", "polyctl-prove.txt"], cwd=tree, check=True, capture_output=True)
1915
+ tree_cfg = A.load_config(tree)
1916
+ # Its reviewer is this project's, accepted or not by this project's record, never a fresh one's (ROUTE-ARGV).
1917
+ A.hold_unseen_routes(root, tree_cfg)
1918
+ with contextlib.redirect_stdout(heard):
1919
+ verified = cmd_verify(tree_cfg, SimpleNamespace(profile="quick", wait=900))
1920
+ if verified != 0:
1921
+ return False, "the quick gates did not pass a one-line change" \
1922
+ + (f"; merge.link_paths could not link {', '.join(unlinked)}" if unlinked else ""), \
1923
+ "run `polyctl verify -p quick` and read the failing gate:\n" + _last_lines(heard.getvalue())
1924
+ with contextlib.redirect_stdout(heard):
1925
+ reviewed = cmd_review(tree_cfg, SimpleNamespace(action=None, rid=None, any=False, run=None, boundary=None,
1926
+ paths=None, commits=None, timeout=None))
1927
+ if reviewed != 0:
1928
+ return False, "the reviewer did not approve a trivial candidate", \
1929
+ "read the review it wrote (archived below); exit 3 means no reviewer could review:\n" \
1930
+ + _last_lines(heard.getvalue())
1931
+ with contextlib.redirect_stdout(heard):
1932
+ granted = cmd_commit_ok(tree_cfg, SimpleNamespace(verify=False, profile=None, review=None))
1933
+ if granted != 0:
1934
+ return False, "polyctl commit-ok refused the approved candidate", _last_lines(heard.getvalue())
1935
+ return True, None, None
1936
+
1937
+
1938
+ def _last_lines(text, count=6):
1939
+ lines = [A.re.sub(r"\x1b\[[0-9;]*m", "", line) for line in text.strip().splitlines() if line.strip()]
1940
+ return "\n".join(" " + line for line in lines[-count:])
1941
+
1942
+
1943
+ def cmd_prove(cfg, args):
1944
+ """Run the guarantees instead of describing them, and say what would fix each one that fails (#85).
1945
+
1946
+ The hook must refuse a synthetic candidate, the reviewer must answer and be
1947
+ another actor than the implementer, and a throwaway slice must go through
1948
+ verify, review and commit-ok in a temporary worktree. Nothing is committed.
1949
+ """
1950
+ root = cfg["root"]
1951
+ results = []
1952
+ worktree = None
1953
+ enrollment = _project_enrollment(root)
1954
+ if enrollment["state"] == "redirected":
1955
+ print(f"{C['red']}prove refused{C['reset']}: {enrollment['detail']}")
1956
+ return 1
1957
+ probe = _hook_execution_probe(_polyctl_hook_inventory(root))
1958
+ # A hook whose /bin/sh finds no polyctl is not fixed by installing it again (SAFE-REMOVE), and a project no
1959
+ # tracked marker covers refuses `polyctl hooks install` until it is adopted; a current hook there failed its
1960
+ # proof with the adoption's own text, which is said once (INIT-ADOPTION).
1961
+ install_problem = _hook_install_problem(enrollment)
1962
+ if install_problem:
1963
+ hook_fix = _hook_install_problem(enrollment, said=probe["detail"])
1964
+ elif HOOK_POLYCTL_NOT_FOUND in probe["detail"]:
1965
+ hook_fix = _polyctl_link_fix()
1966
+ else:
1967
+ hook_fix = "polyctl hooks install"
1968
+ results.append(("hook refuses an unauthorised commit", probe["installed"],
1969
+ None if probe["installed"]
1970
+ else _hook_probe_text(probe) + (f" — {hook_fix}" if hook_fix else "")))
1971
+ reviewer = _reviewer_probe(cfg)
1972
+ reviewer_ok = reviewer["ok"] and reviewer["configured"]
1973
+ # What would fix it names the review tiers; a reviewer of a weaker tier is proven, and labeled (REVIEW-TIERS).
1974
+ from . import tiers as T
1975
+ if reviewer_ok:
1976
+ note = f"tier: {T.label(reviewer.get('tier'))}" if T.weaker(reviewer.get("tier")) else None
1977
+ elif not reviewer["configured"]:
1978
+ note = f"not configured — {T.WAYS_FORWARD} (docs/roles.md)"
1979
+ elif reviewer.get("kind") == "configuration-error":
1980
+ note = f"{_reviewer_probe_text(reviewer)} (docs/roles.md)"
1981
+ else:
1982
+ note = f"{_reviewer_probe_text(reviewer)} — name a reviewer that answers in .polyctl/config.json (docs/roles.md)"
1983
+ results.append(("reviewer answers and is another actor", reviewer_ok, note))
1984
+ if getattr(args, "no_review", False):
1985
+ results.append(("a throwaway slice lands end to end", False, "skipped with --no-review: not proven"))
1986
+ elif not reviewer_ok:
1987
+ results.append(("a throwaway slice lands end to end", False, "not tried: no reviewer can review"))
1988
+ else:
1989
+ ok, failed, fix, worktree = _prove_throwaway(cfg)
1990
+ results.append(("a throwaway slice lands end to end", ok, None if ok else f"{failed} — {fix}"))
1991
+ for claim, ok, fix in results:
1992
+ print(f" {C['green'] + 'proven' if ok else C['red'] + 'NOT PROVEN'}{C['reset']} {claim}")
1993
+ if fix:
1994
+ print(f" {fix}")
1995
+ proven = all(ok for _, ok, _ in results)
1996
+ if worktree is None:
1997
+ cleanup = "no throwaway worktree was made"
1998
+ elif os.path.lexists(worktree):
1999
+ cleanup = f"the throwaway worktree remains at {worktree}; inspect it before retrying cleanup"
2000
+ else:
2001
+ cleanup = "the throwaway worktree is gone"
2002
+ print(f"\n{C['b']}{'PROVEN' if proven else 'NOT PROVEN'}{C['reset']} "
2003
+ f"{C['dim']}nothing was committed; {cleanup}{C['reset']}")
2004
+ return 0 if proven else 1
2005
+
2006
+
2007
+ def _init_then_prove(cfg, args):
2008
+ code = cmd_init(cfg, args)
2009
+ if code or not getattr(args, "prove", False):
2010
+ return code
2011
+ print(f"\n{C['b']}proving the guarantees{C['reset']}")
2012
+ return cmd_prove(A.load_config(cfg["root"]), args)
2013
+
2014
+
2015
+ def cmd_demo(cfg, args):
2016
+ """`polyctl demo [--keep]`: the guarantee played on a project of its own, before anyone adopts polyctl (DEMO).
2017
+
2018
+ `polyctl prove` runs the guarantees on a project that has polyctl; the demo shows them to someone who has
2019
+ none yet, in a scratch folder with a home of its own. It uses nothing of `cfg`, the project the
2020
+ command was run in, which polyctl loaded before dispatching as it does for every command, and writes
2021
+ nothing outside that folder. The demo is src/polyctl/demo.py.
2022
+ """
2023
+ from . import demo
2024
+ return demo.run(keep=getattr(args, "keep", False))
2025
+
2026
+
2027
+ def _doctor_consistency(cfg, repair=False):
2028
+ """`polyctl doctor --consistency [--repair]`: the four stores checked against each other (#47)."""
2029
+ root = cfg["root"]
2030
+ findings = A.consistency_findings(root, cfg)
2031
+ if repair:
2032
+ for finding in A.repair_consistency(root, findings):
2033
+ print(f"{C['green']}repaired{C['reset']} {finding['text']} {C['dim']}recorded in "
2034
+ f".polyctl/ledger/repairs.jsonl{C['reset']}")
2035
+ findings = A.consistency_findings(root, cfg)
2036
+ if not findings:
2037
+ print(f"{C['green']}consistent{C['reset']} board, ledgers, review artefacts and git agree")
2038
+ return 0
2039
+ for finding in findings:
2040
+ mark = f"{C['yellow']}repairable{C['reset']}" if finding["repair"] else f"{C['red']}disagrees{C['reset']}"
2041
+ print(f"{mark} {finding['kind']}: {finding['text']}")
2042
+ if any(finding["repair"] for finding in findings):
2043
+ print(f"{C['dim']}polyctl doctor --consistency --repair fixes the repairable ones and records what it did{C['reset']}")
2044
+ return 1
2045
+
2046
+
2047
+ def _store_bound_lines(cfg):
2048
+ """Name row bounds separately from byte bounds, with the action that holds each (TRIAGE-1-LOW)."""
2049
+ from .watchdog import STATE_DIR
2050
+ from .storage import LedgerCorruption
2051
+ try:
2052
+ over = A.stores_over_bound(cfg["root"], cfg, STATE_DIR)
2053
+ except (OSError, LedgerCorruption) as exc:
2054
+ return [f"{'stores':<16}{C['yellow']}cannot measure evidence retention{C['reset']}: "
2055
+ f"{' '.join(str(exc).split())}; restore the ledger from a known-good backup and run `polyctl doctor` again"]
2056
+ if not over:
2057
+ return []
2058
+ lines = []
2059
+ for unit in ("bytes", "rows"):
2060
+ stores = [(path, size, limit) for path, size, limit, kind in over if kind == unit]
2061
+ if not stores:
2062
+ continue
2063
+ detail = ", ".join(f"{os.path.basename(path)} " +
2064
+ (f"{size}/{limit} rows" if unit == "rows" else f"{size // 1024}KB/{limit // 1024}KB")
2065
+ for path, size, limit in stores)
2066
+ action = ("run `polyctl prune --evidence --yes` to seal older rows" if unit == "rows" else
2067
+ "the watchdog trims them each cycle; is it running?")
2068
+ lines.append(f"{'stores':<16}{C['yellow']}{len(stores)} over their bound{C['reset']} "
2069
+ f"{C['dim']}{detail} — {action}{C['reset']}")
2070
+ return lines
2071
+
2072
+
2073
+ def cmd_backup(cfg, args):
2074
+ """Write the project's governance to the destination it names: a directory, `ref`, or `remote:<name>` (#46)."""
2075
+ destination = getattr(args, "to", None) or (cfg.get("backup") or {}).get("to")
2076
+ if not destination:
2077
+ print(f"{C['yellow']}no destination{C['reset']}: `polyctl backup --to <directory|ref|remote:name>`, or name one as "
2078
+ "backup.to in .polyctl/config.json")
2079
+ return 2
2080
+ try:
2081
+ manifest = A.write_backup(cfg["root"], cfg, destination)
2082
+ except (OSError, RuntimeError, subprocess.CalledProcessError) as exc:
2083
+ print(f"{C['red']}not backed up{C['reset']}: {exc}")
2084
+ return 1
2085
+ print(f"{C['green']}backed up{C['reset']} {len(manifest['files'])} governance file(s) → {manifest['where']}")
2086
+ try:
2087
+ A.authority_history(cfg["root"])
2088
+ except Exception as exc:
2089
+ # Which artefacts a grant rests on is the chain's word; without it every one was kept (GOVERNANCE-BACKUP-2).
2090
+ # The word of the whole chain, the archives a seal wrote held to it (LEDGER-HISTORY).
2091
+ print(f" {C['yellow']}the authority chain does not validate{C['reset']} ({exc}): every review artefact "
2092
+ "was backed up, not only those a grant names")
2093
+ return 0
2094
+
2095
+
2096
+ def cmd_restore(cfg, args):
2097
+ """Reconstruct the control plane from a backup directory; say what could not be verified (#46)."""
2098
+ root = cfg["root"]
2099
+ raw_by = getattr(args, "by", None)
2100
+ by = (raw_by or "").strip()
2101
+ ask = bool(getattr(args, "ask", False))
2102
+ if raw_by is not None:
2103
+ if not by or not by.isprintable() or len(by) > 80:
2104
+ print("--by is required: the person who attests the restored backup, in one line of at most 80 characters")
2105
+ return 2
2106
+ if by.lower() in _agent_names(cfg):
2107
+ print(f"--by names an agent or a role ({by}); attesting a restored backup is a person's act")
2108
+ return 2
2109
+ if ask and not by:
2110
+ print("--by is required with --ask: the person who attests the restored backup, in one line of at most 80 characters")
2111
+ return 2
2112
+ try:
2113
+ restored, unverified = A.restore_backup(root, args.source)
2114
+ except (OSError, ValueError, KeyError) as exc:
2115
+ print(f"{C['red']}not restored{C['reset']}: {exc}")
2116
+ return 2
2117
+ print(f"restored {len(restored)} file(s)")
2118
+ for line in unverified:
2119
+ print(f" {C['red']}not verified{C['reset']} {line}")
2120
+ # A backup that put nothing back, or no config, is no control plane: it "validated" and exited 0, and a
2121
+ # script acted on that (GOVERNANCE-BACKUP-2).
2122
+ if not restored or not os.path.isfile(os.path.join(root, ".polyctl", "config.json")):
2123
+ print(f"{C['red']}the backup restored no control plane{C['reset']}: "
2124
+ + ("no file was restored" if not restored else ".polyctl/config.json is not among what was restored"))
2125
+ return 1
2126
+ if by and by.lower() in _agent_names(A.load_config(root)):
2127
+ print(f"--by names an agent or a role ({by}); attesting a restored backup is a person's act")
2128
+ return 2
2129
+ try:
2130
+ unattested = A._restored_ledgers(root, restored, attest=False)
2131
+ if ".polyctl/ledger/authority.jsonl" not in restored:
2132
+ A.authority_history(root) # the sealed archives too, as one chain (LEDGER-HISTORY)
2133
+ A.board(root)
2134
+ print(f"{C['green']}the authority chain and the board validate{C['reset']}")
2135
+ except Exception as exc:
2136
+ print(f"{C['red']}restored state does not validate{C['reset']}: {exc}")
2137
+ return 1
2138
+ if by and ask and unattested:
2139
+ manifest_digest = A.backup_manifest_digest(args.source)
2140
+ print(f" manifest {manifest_digest}")
2141
+ for rel, rows, digest in unattested:
2142
+ print(f" ledger {rel}: {rows} row(s), last {digest}")
2143
+ if _confirm(f" Attest these {len(unattested)} restored gate ledger(s) on this machine as {by}? [y/N]: ") is True:
2144
+ try:
2145
+ attested = A._restored_ledgers(root, restored, attest=True)
2146
+ A.authority_history(root)
2147
+ row = A.record_restore_attestation(root, by, manifest_digest, attested)
2148
+ except Exception as exc:
2149
+ print(f"{C['red']}restored state does not validate{C['reset']}: {exc}")
2150
+ return 1
2151
+ print(f" {C['green']}attested{C['reset']} {len(attested)} gate ledger(s) by {row['by']} "
2152
+ f"(manifest {manifest_digest[:19]})")
2153
+ unattested = []
2154
+ for rel, rows, _ in unattested:
2155
+ print(f" {C['yellow']}unattested{C['reset']} {rel}: restored ({rows} row(s)), but unattested on this "
2156
+ f"machine — attest with: polyctl restore {args.source} --by <name> --ask")
2157
+ return 1 if unverified else 0
2158
+
2159
+
2160
+ def _shipped_tool_lines(root):
2161
+ """`polyctl doctor`'s lines naming any PATH copy of a tool that ships with polyctl (`polyctl-api-review`) whose version differs
2162
+ from this polyctl's own (API-REVIEWER-TOOLS-2)."""
2163
+ lines, seen = [], set()
2164
+ binaries = sorted({binary for adapter in A.package_adapters().values()
2165
+ for contract in (A.tool_review_contract(adapter),)
2166
+ if contract is not None and not contract.get("install") and not contract.get("release")
2167
+ for binary in A.adapter_binaries(adapter)})
2168
+ for binary in binaries:
2169
+ for entry in A.search_directories():
2170
+ cand = A.program_path(binary, path=entry)
2171
+ if not cand or A.program_in_repository(cand, root):
2172
+ continue
2173
+ real = os.path.normcase(os.path.realpath(cand))
2174
+ if real in seen:
2175
+ continue
2176
+ seen.add(real)
2177
+ ver = _reviewer_binary_version(root, cand)
2178
+ if ver != __version__:
2179
+ lines.append(
2180
+ f"{binary:<16}{C['yellow']}{cand} on PATH is {ver or 'of a version it does not state'}, "
2181
+ f"not this polyctl's {__version__}{C['reset']} {C['dim']}polyctl runs its own installation's copy when "
2182
+ f"present; update or remove the stale PATH copy{C['reset']}"
2183
+ )
2184
+ return lines
2185
+
2186
+
2187
+ def _backup_lines(cfg):
2188
+ """How old the newest backup is, and whether governance exists with none (#46); also the newest restore
2189
+ attestation when one is recorded (LEDGER-ATTESTED)."""
2190
+ root = cfg["root"]
2191
+ age = A.backup_age(root)
2192
+ if age is None:
2193
+ lines = [f"{'backup':<16}{C['yellow']}none{C['reset']} {C['dim']}the control plane is on this disk only — "
2194
+ f"polyctl backup --to <directory|ref|remote:name>{C['reset']}"]
2195
+ else:
2196
+ seconds, where = age
2197
+ tone = C["green"] if seconds < 7 * 86400 else C["yellow"]
2198
+ lines = [f"{'backup':<16}{tone}{_elapsed(seconds)} ago{C['reset']} {C['dim']}{where}{C['reset']}"]
2199
+ try:
2200
+ att = A.latest_restore_attestation(root)
2201
+ except Exception:
2202
+ att = None
2203
+ if att is not None:
2204
+ ledgers = att.get("ledgers") or {}
2205
+ lines.append(f"{'restore':<16}{C['green']}attested{C['reset']} by {att.get('by', '?')} "
2206
+ f"({len(ledgers)} ledger(s), manifest {str(att.get('manifest', ''))[:19]})")
2207
+ return lines
2208
+
2209
+
2210
+ def _machine_line(cfg):
2211
+ """The machine as a gate run reads it, on one line: memory, paging and disk, each past its limit naming the limit
2212
+ (MACHINE-PRESSURE). Not a problem `polyctl doctor --check` pages about: a busy machine is waited for, not mended."""
2213
+ from . import pressure
2214
+ reading = pressure.read()
2215
+ tone = C["yellow"] if pressure.shortfalls(reading, cfg) else C["dim"] if reading.unmeasured else C["green"]
2216
+ return f"{'machine':<16}{tone}{pressure.summary(reading, cfg)}{C['reset']}"
2217
+
2218
+
2219
+ def cmd_doctor(cfg, args):
2220
+ if getattr(args, "consistency", False):
2221
+ return _doctor_consistency(cfg, repair=getattr(args, "repair", False))
2222
+ if getattr(args, "check", False):
2223
+ # Scheduled checks return through the existing static helper here;
2224
+ # only the manual path below invokes the reviewer nonce probe.
2225
+ if getattr(args, "notify", False):
2226
+ return _doctor_check(cfg, page=True)
2227
+ return _doctor_check(cfg)
2228
+ root, impl, adapter = _ctx(cfg)
2229
+ redirected = _commit_repository_binding(root)
2230
+ if redirected:
2231
+ print(f"{C['red']}repository redirect{C['reset']}: {redirected}")
2232
+ ok = lambda b: f"{C['green']}ok{C['reset']}" if b else f"{C['red']}missing{C['reset']}"
2233
+
2234
+ # Run outside a project, every check is "missing" and none of it is a fault.
2235
+ # Say that instead of printing a wall of red.
2236
+ if not impl and not os.path.isdir(os.path.join(root, cfg["mailbox"])):
2237
+ print(f"{C['yellow']}No project here.{C['reset']} {C['dim']}{root}{C['reset']}\n")
2238
+ ws = A.all_workspaces()[:5]
2239
+ if ws:
2240
+ print("Point at one of these:")
2241
+ for r in ws:
2242
+ mins = int((time.time() - r["mtime"]) / 60)
2243
+ age = f"{mins}m ago" if mins < 90 else f"{mins // 60}h ago"
2244
+ print(f" {C['b']}polyctl -C {r['path']} doctor{C['reset']} {C['dim']}{age}{C['reset']}")
2245
+ else:
2246
+ print(f"{C['dim']}No local agent sessions found. See docs/adapters.md.{C['reset']}")
2247
+ return 1 if redirected else None
2248
+ print(f"root {root}")
2249
+ # Configuration is optional: discovery covers the common case, so its absence
2250
+ # is a fact, not a fault. Red is reserved for things that need fixing.
2251
+ has_cfg = os.path.exists(os.path.join(root, ".polyctl", "config.json"))
2252
+ print(f"config " + (f"{C['green']}.polyctl/config.json{C['reset']}" if has_cfg
2253
+ else f"{C['dim']}none — using auto-discovery{C['reset']}"))
2254
+ lite = project_mode(cfg) == "lite"
2255
+ if lite:
2256
+ opt_in = _lite_mode_opt_in(cfg)
2257
+ who = f" (set by {_person_line(opt_in)})" if opt_in else ""
2258
+ print(f"mode {C['yellow']}{ENFORCEMENT_OFF_LITE_LINE}{C['reset']}{who}")
2259
+ else:
2260
+ print(f"mode {C['green']}full{C['reset']} — enforcement: on")
2261
+ for line in _session_lines(cfg):
2262
+ print(line)
2263
+ msgs, _ = A.session_paths(cfg)
2264
+ print(f"transcript {ok(bool(msgs and os.path.exists(msgs)))}")
2265
+ print(f"mailbox {ok(os.path.isdir(os.path.join(root, cfg['mailbox'])))}")
2266
+ print(f"reviews {ok(os.path.isdir(os.path.join(root, cfg['reviews'])))}")
2267
+ if lite:
2268
+ reviewer_probe = {"ok": True}
2269
+ print(f"reviewer probe {C['dim']}not run ({ENFORCEMENT_OFF_LITE} — nothing is enforced){C['reset']}")
2270
+ else:
2271
+ reviewer_probe = _reviewer_probe(cfg)
2272
+ probe_tone = C["green"] if reviewer_probe["ok"] else C["red"]
2273
+ print(
2274
+ f"reviewer probe {probe_tone}{_reviewer_probe_text(reviewer_probe)}"
2275
+ f"{C['reset']}"
2276
+ )
2277
+ # The tier the next review would stand in, and whether any does (REVIEW-TIERS).
2278
+ from . import tiers as T
2279
+ tier_text, tier_problems = _active_review_tier(cfg)
2280
+ strongest = tier_text.startswith(T.LABELS[T.INDEPENDENT]) and not tier_problems
2281
+ print(f"review tier {C['green'] if strongest else C['yellow']}{tier_text}{C['reset']}")
2282
+ for _, text in tier_problems:
2283
+ print(f" {C['yellow']}{text}{C['reset']}")
2284
+ print(f"review budget {C['dim']}{_review_budget_text(_review_timeout(cfg))}{C['reset']}")
2285
+ guard = None if lite else _implementer_commit_guard(cfg)
2286
+ if guard:
2287
+ print(f"commit guard {C['dim']}{guard}{C['reset']}")
2288
+ try:
2289
+ waiver_lines = A.open_waiver_report(root)
2290
+ except Exception as exc:
2291
+ waiver_lines = [f"{C['red']}waiver ledger is unreadable: {exc}{C['reset']}"]
2292
+ print(f"waivers {len(waiver_lines) if waiver_lines else 'none open'}"
2293
+ + (" open" if waiver_lines else ""))
2294
+ for line in waiver_lines:
2295
+ print(f" {C['dim']}{line}{C['reset']}")
2296
+ for line in _harness_config_lines(cfg):
2297
+ print(line)
2298
+ for line in _environment_lines(cfg):
2299
+ print(line)
2300
+ for line in _turn_command_lines(cfg):
2301
+ print(line)
2302
+ for line in _review_evidence_lines(cfg):
2303
+ print(line)
2304
+ for line in _architect_absence_lines(cfg):
2305
+ print(line)
2306
+ for line in _worktree_lines(cfg):
2307
+ print(line)
2308
+ for line in _store_bound_lines(cfg):
2309
+ print(line)
2310
+ for line in _backup_lines(cfg):
2311
+ print(line)
2312
+ print(f"quota source {'keyflip' if A.runnable_binary('keyflip') else '—'}")
2313
+ # Optional capabilities announce themselves; the core never needs them (#82).
2314
+ for name, state, hint in _optional_features(cfg):
2315
+ print(f"optional {name:<9} {state}" + (f" {C['dim']}{hint}{C['reset']}" if state == "absent" else ""))
2316
+ key = A.project_key(root).lower()
2317
+ scheduler = _scheduler()
2318
+ if scheduler == "schtasks":
2319
+ # Windows schedules the watchdog with Task Scheduler, not launchd (#71).
2320
+ wd = _schtasks("/Query", "/TN", _windows_task("watchdog", key))[1] == 0
2321
+ elif scheduler == "systemd":
2322
+ timer = _systemd_unit("watchdog", key) + ".timer"
2323
+ wd = _systemd_states(timer)[timer] in SYSTEMD_UP
2324
+ else:
2325
+ wd = _launchd_listed(_launchd_label("watchdog", key))
2326
+ print(f"watchdog {C['green']}running{C['reset']}" if wd else
2327
+ f"watchdog {C['dim']}not installed — polyctl watchdog install{C['reset']}")
2328
+ err = A.last_nudge_error(root)
2329
+ if err:
2330
+ mins = int((time.time() - err.get("at", 0)) / 60)
2331
+ print(f"last restart {C['red']}failed {mins}m ago (exit {err.get('code')}){C['reset']}")
2332
+ print(f" {C['dim']}{err.get('tail','')[:110]}{C['reset']}")
2333
+ else:
2334
+ print(f"last restart {C['dim']}no failures recorded{C['reset']}")
2335
+ if lite:
2336
+ print(f"{'commit hook':<16}{C['dim']}not installed ({ENFORCEMENT_OFF_LITE} — nothing is enforced){C['reset']}")
2337
+ print(f"{'push hook':<16}{C['dim']}not installed ({ENFORCEMENT_OFF_LITE} — nothing is enforced){C['reset']}")
2338
+ print(f"{'commit proof':<16}{C['dim']}not run ({ENFORCEMENT_OFF_LITE} — nothing is enforced){C['reset']}")
2339
+ else:
2340
+ hook_inventory = _polyctl_hook_inventory(root)
2341
+ if hook_inventory["error"]:
2342
+ detail = f"resolver failure: {hook_inventory['error']}"
2343
+ print(f"{'commit hook':<16}{C['yellow']}{detail}{C['reset']} polyctl hooks status")
2344
+ print(f"{'push hook':<16}{C['yellow']}{detail}{C['reset']} polyctl push-window hook unavailable")
2345
+ else:
2346
+ active = _active_hook_targets(hook_inventory)
2347
+ enrollment = _project_enrollment(root)
2348
+ install_problem = _hook_install_problem(enrollment)
2349
+ own_push = _own_pre_push_target(hook_inventory)
2350
+ for role, label in (("pre-commit", "commit hook"), ("pre-push", "push hook")):
2351
+ target = active[role]
2352
+ base = _state_base(target["static_state"])
2353
+ current = base in ("current-local", "current-scoped")
2354
+ tone = (
2355
+ C["green"]
2356
+ if current
2357
+ else (C["dim"] if role == "pre-push" and own_push is not None else C["yellow"])
2358
+ )
2359
+ notes = []
2360
+ if install_problem and not (role == "pre-push" and own_push is not None):
2361
+ tone = C["yellow"]
2362
+ notes.append(install_problem)
2363
+ elif role == "pre-commit" and not current:
2364
+ notes.append("polyctl hooks install")
2365
+ if role == "pre-push" and not current:
2366
+ notes.append("polyctl push-window hook unavailable")
2367
+ suffix = " " + "; ".join(notes) if notes else ""
2368
+ print(
2369
+ f"{label:<16}{tone}{target['static_state']} / "
2370
+ f"{target['track_state']}{C['reset']}{suffix}"
2371
+ )
2372
+ push_guard = _push_guard_status_line(hook_inventory)
2373
+ if push_guard is not None:
2374
+ push_tone = C["dim"] if own_push is not None else C["yellow"]
2375
+ print(
2376
+ f"{'push guard':<16}{push_tone}{push_guard}{C['reset']}"
2377
+ )
2378
+ for target in hook_inventory["targets"]:
2379
+ if target["active"] or target["role"] != "pre-commit" \
2380
+ or target["reachability"] != "potentially-effective" \
2381
+ or _state_base(target["static_state"]) not in (
2382
+ "current-local", "current-scoped", "legacy", "ambiguous-polyctl"
2383
+ ):
2384
+ continue
2385
+ print(
2386
+ f"{'commit misplaced':<16}{C['yellow']}{target['static_state']} / "
2387
+ f"{target['track_state']} / {target['directory_class']} — "
2388
+ f"{target['path']}{C['reset']} polyctl hooks uninstall, then polyctl hooks install"
2389
+ )
2390
+ hook_proof = _hook_execution_probe(hook_inventory)
2391
+ proof_tone = C["green"] if hook_proof["installed"] else C["yellow"]
2392
+ print(f"{'commit proof':<16}{proof_tone}{_hook_probe_text(hook_proof)}{C['reset']}")
2393
+ reach = _hook_polyctl_reach(hook_inventory)
2394
+ if reach:
2395
+ print(f"{'polyctl for hooks':<16}{C['yellow']}{reach[0]}{C['reset']}")
2396
+ print(f"{'':<16}{C['dim']}fix: {reach[1]}{C['reset']}")
2397
+ print(f"{'checkout':<16}{_checkout_position(A.git_state(root))}")
2398
+ print(_machine_line(cfg))
2399
+ for line in _measurement_lines(cfg):
2400
+ print(line)
2401
+ for _, text in _path_problems(): # (WINDOWS-NO-CWD-EXEC)
2402
+ print(f"{'PATH':<16}{C['yellow']}{text}{C['reset']}")
2403
+ # What polyctl cannot hold on Windows, and why, where a person looks for it; none is a fault to page about
2404
+ # (WINDOWS-SAY-WHY).
2405
+ for line in _windows_limit_lines():
2406
+ print(line)
2407
+ # Can the *agent* run `polyctl`? A shell alias is invisible to a non-interactive
2408
+ # process, so steering that says "run your gates through polyctl lock" is an
2409
+ # instruction the agent cannot follow — and a disciplined agent then parks the
2410
+ # slice rather than working around it. That cost this project three parked
2411
+ # items and half a day. Check the child's PATH, not this shell's.
2412
+ from .watchdog import child_path
2413
+ reachable = A.program_path("polyctl", path=child_path())
2414
+ # The architect is woken through a binary the watchdog resolves by version,
2415
+ # not by PATH order; say which one, and whether the last wake died on it.
2416
+ arch = cfg.get("architect") or {}
2417
+ if arch.get("argv"):
2418
+ from .watchdog import wake_error, STATE_DIR, architect_command
2419
+ # Use the wake's preparation and refusal values before any version probe (ARCH-PROBE-ORDER).
2420
+ command, _, stopped = architect_command(root, cfg, arch.get("prompt", language.text(cfg, "prompt.refill")))
2421
+ rb, rv = (None, "") if stopped else A.resolve_binary(command["argv"][0], path=command["path"])
2422
+ others = [] if stopped else [c for c in A.binary_candidates(command["argv"][0], command["path"]) if c != rb]
2423
+ if stopped:
2424
+ print(f"architect bin {C['red']}not asked{C['reset']} {C['dim']}{A.shown_text(stopped)}{C['reset']}")
2425
+ else:
2426
+ print(f"architect bin {C['green'] if rb else C['red']}{rb or 'not found'}{C['reset']} {C['dim']}{rv}"
2427
+ f"{C['reset']}" + (f" {C['dim']}({len(others)} older copy: {', '.join(others)}){C['reset']}"
2428
+ if others else ""))
2429
+ key = A.project_key(root)
2430
+ we = wake_error(os.path.join(STATE_DIR, A.project_file_name("escalate-log", key)))
2431
+ if we:
2432
+ text, used, when = we["text"], we["binary"], we["when"]
2433
+ print(f"last wake {C['red']}failed{C['reset']} {when} [{used or '?'}]: {text[:90]}")
2434
+ if stopped:
2435
+ print(f" {C['dim']}no wake starts while the architect's command is held or refused"
2436
+ f"{C['reset']}")
2437
+ elif not used:
2438
+ print(f" {C['dim']}binary not recorded (older log); the next wake uses the one above{C['reset']}")
2439
+ elif used != f"{rb} {rv}":
2440
+ print(f" {C['dim']}a different binary resolves now; the next wake will use it{C['reset']}")
2441
+ else:
2442
+ update = next((adapter["detect"]["update"] for adapter in A.package_adapters().values()
2443
+ if (adapter.get("detect") or {}).get("update")
2444
+ and os.path.basename(arch["argv"][0]) in A.adapter_binaries(adapter)), None)
2445
+ how = f" ({' '.join(update)})" if update else ""
2446
+ print(f" {C['yellow']}same binary — update it{how} or remove the stale copy{C['reset']}")
2447
+ # Liveness and channels. A watchdog nobody can prove is alive, and an orange
2448
+ # alarm with no channel beyond the desktop, are both silent failures.
2449
+ hb = A.heartbeat_age(root)
2450
+ if hb is None:
2451
+ print(f"last tick {C['yellow']}never{C['reset']} {C['dim']}(no heartbeat file yet){C['reset']}")
2452
+ else:
2453
+ tone = C['green'] if hb < 360 else C['red']
2454
+ print(f"last tick {tone}{hb // 60}m {hb % 60}s ago{C['reset']}"
2455
+ + (f" {C['red']}watchdog is not running its cycles{C['reset']}" if hb >= 360 else ""))
2456
+ from . import telegram as _tg, email as _em, ntfy as _nt
2457
+ tg_ok, nt_ok, em_ok = bool(_tg.config()), bool(_nt.config()), bool(_em.config())
2458
+ print(f"channels desktop {C['green']}on{C['reset']} · telegram "
2459
+ f"{C['green'] if tg_ok else C['yellow']}{'on' if tg_ok else 'off'}{C['reset']}"
2460
+ + (f" · ntfy {C['green']}on{C['reset']}" if nt_ok else "")
2461
+ + f" · e-mail {C['green'] if em_ok else C['yellow']}{'on' if em_ok else 'off'}{C['reset']}"
2462
+ + ("" if (tg_ok or nt_ok or em_ok) else f" {C['yellow']}orange alarms reach nothing but the desktop — polyctl email setup{C['reset']}"))
2463
+ try:
2464
+ from .watchdog import load_state as _ls, reset_when as _reset_when
2465
+ _st = _ls(root)
2466
+ if _st.get("arch_quota_until", 0) > time.time():
2467
+ # The date too when the end is a day or more away: a week's end is not tonight (ARCHITECT-WAKE-QUOTA).
2468
+ print(f"architect {C['yellow']}at quota{C['reset']} until {_reset_when(_st['arch_quota_until'])}")
2469
+ except Exception:
2470
+ pass
2471
+ alive = A.active_alarms(A.project_key(root))
2472
+ if alive:
2473
+ worst = max(alive, key=lambda e: {"yellow": 0, "orange": 1, "red": 2}.get(e.get("ring"), 0))
2474
+ print(f"alarms {C['red'] if worst['ring'] == 'red' else C['yellow']}{len(alive)} live, worst {worst['ring']}{C['reset']} {C['dim']}polyctl alarms{C['reset']}")
2475
+ # Things that fail silently unless someone asks: the transcript format (a CLI
2476
+ # update changes it and every status goes blind), the credits running out
2477
+ # before the reset, the external ping, the push hook, the switches.
2478
+ try:
2479
+ msgs_p, _ = A.session_paths(cfg)
2480
+ if msgs_p and os.path.exists(msgs_p):
2481
+ n_recs = len(A.read_tail(msgs_p, 2_000_000))
2482
+ age_m = int((time.time() - os.path.getmtime(msgs_p)) / 60)
2483
+ bad = n_recs == 0 and age_m < 60
2484
+ print(f"transcript {C['red'] if bad else C['green']}{n_recs} records parsed{C['reset']}, last write {age_m}m ago"
2485
+ + (f" {C['red']}fresh file, nothing parsed — the CLI's format changed; update the adapter{C['reset']}" if bad else ""))
2486
+ except Exception:
2487
+ pass
2488
+ # The implementer's own account only, or that its adapter declares none (ACCOUNT-READERS).
2489
+ for line in _doctor_credit_lines(cfg):
2490
+ print(line)
2491
+ print(f"ping {C['green'] + 'configured' + C['reset'] if A.ping_url(root) else C['yellow'] + 'off' + C['reset'] + ' polyctl pings setup'}")
2492
+ from . import features as _F
2493
+ print(f"features {sum(_F.switches(cfg).values())}/{len(_F.ORDER)} on {C['dim']}polyctl cost --features for what "
2494
+ f"each spent{C['reset']}")
2495
+ # Only this line is about finding polyctl for the agents. Every line above was printed only when polyctl was found,
2496
+ # and a machine where it was not lost the heartbeat, the alarms, the transcript, the credits, the ping and
2497
+ # the channels with it (LEADS-INSTALL).
2498
+ if reachable:
2499
+ print(f"polyctl for agents {C['green']}{reachable}{C['reset']}")
2500
+ else:
2501
+ print(f"polyctl for agents {C['red']}not on a spawned agent's PATH{C['reset']}")
2502
+ print(f" {C['dim']}a shell alias does not count — {_polyctl_link_fix()}{C['reset']}")
2503
+
2504
+ from . import skillkit as _skillkit
2505
+ for steering in _skillkit.steering_dirs(root):
2506
+ steer = os.path.join(root, *steering.split("/"))
2507
+ if not os.path.isdir(steer) or reachable:
2508
+ continue
2509
+ refs = [f for f in os.listdir(steer)
2510
+ if f.endswith(".md") and "polyctl " in open(os.path.join(steer, f),
2511
+ errors="replace", encoding=UTF8).read()]
2512
+ if refs:
2513
+ print(f" {C['yellow']}steering references it: "
2514
+ f"{', '.join(refs)}{C['reset']}")
2515
+
2516
+ # Two copies of `polyctl` on one machine is an ambiguity that bites silently: a
2517
+ # shell alias to a git checkout and a package install answer to the same
2518
+ # name, drift apart after the next commit, and which one runs depends on
2519
+ # how it was invoked. The second pilot's agent caught it on its first day.
2520
+ cands = []
2521
+ for cand in (A.program_path("polyctl"), os.path.join(A.HOME, ".local", "bin", "polyctl"),
2522
+ os.path.join(A.REPO, "bin", "polyctl")):
2523
+ if cand and os.path.exists(cand):
2524
+ real = os.path.realpath(cand)
2525
+ if real not in [os.path.realpath(c) for c in cands]:
2526
+ cands.append(cand)
2527
+ if len(cands) > 1:
2528
+ print(f"polyctl binaries {C['yellow']}{len(cands)} distinct{C['reset']} — "
2529
+ f"{C['dim']}which one runs depends on how it is invoked{C['reset']}")
2530
+ for c in cands:
2531
+ print(f" {C['dim']}{c} → {os.path.realpath(c)}{C['reset']}")
2532
+ print(f" {C['dim']}keep one: drop the shell alias, or "
2533
+ f"uv tool uninstall polyctl{C['reset']}")
2534
+ for line in _shipped_tool_lines(root):
2535
+ print(line)
2536
+ return 0 if reviewer_probe["ok"] and not redirected else 1