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,638 @@
1
+ """Installation: `polyctl update` and `polyctl uninstall`, so a person never has to learn how polyctl was installed (UPDATE-UNINSTALL).
2
+
3
+ A part of src/polyctl/cli.py, run in its namespace by `_part`; it is not importable on its own. What these commands
4
+ take off a machine they take the way it went on: the jobs through `_installed_jobs` and `_unschedule`, with which
5
+ `polyctl remove` takes one project's, the hooks through `_polyctl_hook_inventory` and `_hooks_uninstall`, and the MCP
6
+ entries from the files the adapters declare, where `polyctl init` merged them.
7
+ """
8
+
9
+
10
+ # The distribution pip, pipx and uv install: pyproject.toml's [project] name. The import package and the command
11
+ # are `polyctl`; `polyctl` on PyPI is another project's (packaging/RELEASING.md).
12
+ DISTRIBUTION = "polyctl"
13
+ # How each kind of installation reads in "installed <how> at <where>".
14
+ INSTALLED_HOW = {"clone": "from a git clone", "homebrew": "with Homebrew", "pipx": "with pipx", "uv": "with uv tool",
15
+ "pip": "with pip"}
16
+ # The hook states that are polyctl's own bytes, whatever a target's track state: what an uninstall looks for.
17
+ POLYCTL_HOOK_STATES = ("current-local", "current-scoped", "legacy", "ambiguous-polyctl")
18
+
19
+
20
+ def _argv_text(argv):
21
+ """An argument vector as words a person can read, and paste into a shell, exactly as it runs."""
22
+ return " ".join(A._shell_word(str(word)) for word in argv)
23
+
24
+
25
+ def _installation(package=None, prefix=None, python=None):
26
+ """How the polyctl running now was installed, and the commands that update and remove it.
27
+
28
+ {kind, where, update, remove, env, missing}: kind is clone, homebrew, pipx, uv or pip, or None when it
29
+ cannot be told; where is the clone, the keg, the environment or the site directory; update and remove are
30
+ argument vectors (remove is None for a clone, which is deleted rather than uninstalled); env is the
31
+ environment the update runs in, None for this one; missing names the program an update needs when it is not
32
+ on PATH. It is the code running now that is asked about, not the first polyctl on PATH: this is its command.
33
+
34
+ Told apart in this order, since what marks a later kind can be true of an earlier one too. A clone - the
35
+ quickstart's symlink to bin/polyctl, or an editable install - is a src/ tree beside bin/polyctl, with git's .git
36
+ around them. Homebrew keeps a formula's virtualenv in a keg, <prefix>/Cellar/<formula>/<version>/, which
37
+ holds its INSTALL_RECEIPT.json, and its brew in <prefix>/bin. pipx and uv mark the environment they made with
38
+ pipx_metadata.json and uv-receipt.toml and name it for what they installed. pip leaves the package in one of
39
+ this interpreter's site directories; the user's one means it was given --user, and so must the upgrade be, or
40
+ it installs a second copy beside the first.
41
+ """
42
+ import site
43
+ package = os.path.realpath(package or os.path.dirname(os.path.abspath(A.__file__)))
44
+ prefix = os.path.realpath(prefix or sys.prefix)
45
+ python = python or sys.executable
46
+ found = {"kind": None, "where": package, "update": None, "remove": None, "env": None, "missing": None}
47
+ source = os.path.dirname(package)
48
+ clone = os.path.dirname(source)
49
+ if os.path.basename(source) == "src" and os.path.isfile(os.path.join(clone, "bin", "polyctl")) \
50
+ and os.path.exists(os.path.join(clone, ".git")):
51
+ # Run as polyctl's hooks run git: no repository, index or configuration the caller's environment names
52
+ # reaches the pull, which touches the clone and nothing else.
53
+ return dict(found, kind="clone", where=clone, env=_hook_git_env(),
54
+ update=[A.git_binary(), "-C", clone, "pull", "--ff-only"])
55
+ parts = package.split(os.sep)
56
+ if "Cellar" in parts:
57
+ at = parts.index("Cellar")
58
+ keg = os.sep.join(parts[:at + 3])
59
+ if len(parts) > at + 3 and os.path.isfile(os.path.join(keg, "INSTALL_RECEIPT.json")):
60
+ formula = parts[at + 1]
61
+ brew = os.path.join(os.sep.join(parts[:at]) or os.sep, "bin", "brew")
62
+ brew = brew if os.path.isfile(brew) and os.access(brew, os.X_OK) else A.program_path("brew")
63
+ return dict(found, kind="homebrew", where=os.sep.join(parts[:at + 2]), missing=None if brew else "brew",
64
+ update=[brew or "brew", "upgrade", formula], remove=[brew or "brew", "uninstall", formula])
65
+ if _hook_contains(prefix, package):
66
+ for kind, marker, tool, verb in (("pipx", "pipx_metadata.json", "pipx", []),
67
+ ("uv", "uv-receipt.toml", "uv", ["tool"])):
68
+ if os.path.isfile(os.path.join(prefix, marker)):
69
+ program, name = A.program_path(tool), os.path.basename(prefix)
70
+ return dict(found, kind=kind, where=prefix, missing=None if program else tool,
71
+ update=[program or tool, *verb, "upgrade", name],
72
+ remove=[program or tool, *verb, "uninstall", name])
73
+ sites = list(site.getsitepackages()) if hasattr(site, "getsitepackages") else []
74
+ user = site.getusersitepackages() if hasattr(site, "getusersitepackages") else None
75
+ if user and os.path.realpath(user) == source:
76
+ flags = ["--user"]
77
+ elif any(os.path.realpath(path) == source for path in sites):
78
+ flags = []
79
+ else:
80
+ return found
81
+ return dict(found, kind="pip", where=source,
82
+ update=[python, "-m", "pip", "install", "--upgrade", *flags, DISTRIBUTION],
83
+ remove=[python, "-m", "pip", "uninstall", DISTRIBUTION])
84
+
85
+
86
+ def _clone_state(clone):
87
+ """(why `git pull --ff-only` must not run in this clone, or None; its branch and what that tracks).
88
+
89
+ Uncommitted changes to what git tracks are a person's work, and an update is no reason to put them at risk.
90
+ Untracked files do not count: a fast-forward touches one only when it brings a file of that name itself, and
91
+ then git refuses before it writes anything. A detached HEAD, or a branch that tracks nothing, has nothing a
92
+ pull can fast-forward to. A git that cannot answer is a refusal too, never a clean clone.
93
+ """
94
+ try:
95
+ status = _hook_git(clone, "status", "--porcelain", "--untracked-files=no")
96
+ branch = _hook_git(clone, "symbolic-ref", "--quiet", "--short", "HEAD")
97
+ upstream = _hook_git(clone, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}")
98
+ except _HookResolutionError as exc:
99
+ return f"git cannot read the clone at {clone}: {exc}", None
100
+ if status.returncode:
101
+ detail = status.stderr.decode(UTF8, "replace").strip()[:160] or f"git exit {status.returncode}"
102
+ return f"git cannot read the clone at {clone}: {detail}", None
103
+ changed = [line[3:] for line in status.stdout.decode(UTF8, "replace").splitlines() if line.strip()]
104
+ if changed:
105
+ more = f" and {len(changed) - 3} more" if len(changed) > 3 else ""
106
+ return (f"the clone at {clone} has uncommitted changes ({', '.join(changed[:3])}{more}); commit or stash "
107
+ "them, then run polyctl update again"), None
108
+ name = branch.stdout.decode(UTF8, "replace").strip()
109
+ if branch.returncode or not name:
110
+ return f"the clone at {clone} is on no branch (a detached HEAD); check out the branch to update", None
111
+ tracked = upstream.stdout.decode(UTF8, "replace").strip()
112
+ if upstream.returncode or not tracked:
113
+ return (f"branch {name} of the clone at {clone} tracks no upstream; set one with "
114
+ "`git branch --set-upstream-to`"), None
115
+ return None, f"branch {name}, tracking {tracked}"
116
+
117
+
118
+ def _confirm(question):
119
+ """A person's answer at the terminal: True for yes, False for anything else, None when nobody can be asked.
120
+
121
+ Nobody can when standard input is no terminal - a pipe, a scheduled job, an agent's tool call - or is a
122
+ terminal nobody can type into, as a chat's `!` command input is (`isatty()` is True and `input()` raises
123
+ `EOFError`, HARNESS-SEEN-EOF): EOF is nobody answering, not a person saying no, and silence must not read as
124
+ consent.
125
+ """
126
+ try:
127
+ if sys.stdin is None or not sys.stdin.isatty():
128
+ return None
129
+ return input(question).strip().lower() in ("y", "yes")
130
+ except (EOFError, OSError, ValueError):
131
+ return None
132
+
133
+
134
+ def _no_answer_why():
135
+ """Why `_confirm` returned `None`: standard input is not a terminal, or ended before an answer came (LOWS-0.7)."""
136
+ try:
137
+ tty = bool(sys.stdin is not None and sys.stdin.isatty())
138
+ except (OSError, ValueError):
139
+ tty = False
140
+ return "standard input ended before an answer came" if tty else "standard input is not a terminal"
141
+
142
+
143
+ def _run_update(argv, env=None):
144
+ """Run one update in the foreground, its output going to the person as the tool writes it.
145
+
146
+ The exit status, or None when the program cannot be started. polyctl reads none of what it prints: whether
147
+ anything was newer, and what changed, is the tool's to say.
148
+ """
149
+ try:
150
+ return subprocess.run(argv, env=env).returncode
151
+ except OSError:
152
+ return None
153
+
154
+
155
+ def cmd_update(cfg, args):
156
+ """Update polyctl the way it was installed, having said what will run (UPDATE-UNINSTALL).
157
+
158
+ A clone is fast-forwarded, a Homebrew, pipx or uv install is upgraded by its own tool, and a pip install by
159
+ this interpreter's pip. The command is printed before anything runs, and it runs on --yes or a yes at the
160
+ terminal; --dry-run prints it and stops. A clone with uncommitted changes, on no branch or tracking nothing is
161
+ refused first, and so is an installation polyctl cannot tell. Exit 0 once the update ran, or on a dry run; 1 when
162
+ it was refused, declined or failed.
163
+ """
164
+ found = _installation()
165
+ kind = found["kind"]
166
+ print(f"polyctl {__version__}, " + (f"installed {INSTALLED_HOW[kind]} at {found['where']}" if kind
167
+ else f"running from {found['where']}"))
168
+ if kind is None:
169
+ print(f"{C['red']}not updated{C['reset']}: this is no git clone, and no Homebrew, pipx, uv or pip "
170
+ "installation holds it; update it the way you installed it")
171
+ return 1
172
+ if found["missing"]:
173
+ print(f"{C['red']}not updated{C['reset']}: {found['missing']} updates this installation, and it is not "
174
+ "on PATH")
175
+ return 1
176
+ if kind == "clone":
177
+ problem, detail = _clone_state(found["where"])
178
+ if problem:
179
+ print(f"{C['red']}not updated{C['reset']}: {problem}")
180
+ return 1
181
+ print(f" {detail}")
182
+ print(f"will run: {_argv_text(found['update'])}")
183
+ if args.dry_run:
184
+ print(f"{C['dim']}dry run: nothing was run{C['reset']}")
185
+ return 0
186
+ if not args.yes:
187
+ answer = _confirm("run it? [y/N] ")
188
+ if not answer:
189
+ print("not run" + (f": nobody can answer here, {_no_answer_why()}; run it again with --yes"
190
+ if answer is None else ""))
191
+ return 1
192
+ code = _run_update(found["update"], found["env"])
193
+ if code is None:
194
+ print(f"{C['red']}update failed{C['reset']}: {found['update'][0]} could not be started")
195
+ return 1
196
+ if code:
197
+ print(f"{C['red']}update failed{C['reset']}: {os.path.basename(found['update'][0])} exited {code}; "
198
+ "what it said is above")
199
+ return 1
200
+ print(f"{C['green']}updated{C['reset']}; `polyctl --version` names the version now installed")
201
+ return 0
202
+
203
+
204
+ # ---- polyctl uninstall ---------------------------------------------------------------------------------------------
205
+
206
+ def _machine_jobs():
207
+ """(kind, name) of every job polyctl scheduled on this machine, as `_unschedule` takes one.
208
+
209
+ launchd: every label in polyctl's namespace (LAUNCHD_NAMESPACE, beside `_launchd_label`), whether its plist is in
210
+ LaunchAgents or launchd holds it loaded with the plist gone, so the jobs of a project deleted since, or never
211
+ in the registry, go with the rest. A user systemd (LINUX-SCHEDULER) likewise: every unit in polyctl's namespace,
212
+ `polyctl-<job>-<project>` (`_systemd_unit`), with a file in the user unit directory - the link `enable` made
213
+ counts - and, for each project the registry knows, a job the manager still runs after its files went, as
214
+ `_installed_jobs` reads a job (LEADS-INSTALL). Task Scheduler offers no namespace to list, so there they are
215
+ the tasks of the projects the machine registry knows, named as `polyctl watchdog install` names them. A launchd
216
+ whose listing failed read as holding nothing loaded; its labels are then those of the projects the registry
217
+ knows, each tried and named, as Task Scheduler's are (LEADS-INSTALL).
218
+ """
219
+ if os.name == "nt":
220
+ found = []
221
+ for key in sorted(A.project_registry()):
222
+ found += [job for job in _installed_jobs(key) if job not in found]
223
+ return found
224
+ if _scheduler() == "systemd":
225
+ prefixes, units = tuple(f"polyctl-{job}-" for job in SYSTEMD_JOBS), set()
226
+ for directory in (_systemd_dir(), os.path.join(_systemd_dir(), "timers.target.wants")):
227
+ try:
228
+ names = os.listdir(directory)
229
+ except OSError:
230
+ continue
231
+ units |= {name.rpartition(".")[0] for name in names
232
+ if name.startswith(prefixes) and name.rpartition(".")[2] in ("service", "timer")}
233
+ for key in sorted(A.project_registry()):
234
+ units |= {name[:-len(".timer")] for _, name in _installed_jobs(key)}
235
+ return [("systemd timer", unit + ".timer") for unit in sorted(units)]
236
+ try:
237
+ names = os.listdir(os.path.dirname(_launchd_plist(LAUNCHD_NAMESPACE)))
238
+ except OSError:
239
+ names = []
240
+ labels = {name[:-len(".plist")] for name in names
241
+ if name.startswith(LAUNCHD_NAMESPACE) and name.endswith(".plist")}
242
+ listed, status = _launchctl("list")
243
+ labels |= {label for label in (line.rsplit("\t", 1)[-1].strip() for line in listed.split("\n"))
244
+ if label.startswith(LAUNCHD_NAMESPACE)}
245
+ for key in sorted(A.project_registry()) if status != 0 else []:
246
+ labels |= {label for _, label in _installed_jobs(key)}
247
+ return [("launchd job", label) for label in sorted(labels)]
248
+
249
+
250
+ def _serves_polyctl(entry, root):
251
+ """Whether an MCP server entry is the one `polyctl init` registered for the project at `root`: it runs
252
+ `polyctl … -C <root> mcp serve` (UPDATE-UNINSTALL-2).
253
+
254
+ skillkit.register_mcp writes {command: the polyctl it found, args: [-C, <root>, mcp, serve]}, followed by
255
+ `--role <role>` when the registration names one (MCP-ROLES); an agent's own CLI, asked to register the
256
+ same, keeps the command, and a polyctl run as `python -m polyctl` keeps its interpreter. So an entry is polyctl's when
257
+ its arguments end with `mcp serve` and nothing after it but polyctl's own options, `--role` and
258
+ `--allow-verify`, whatever its command is called: a server named `polyctl` whose program is another one
259
+ called polyctl was taken for polyctl's on its name alone, and removed. And the `-C` right before `mcp serve` names
260
+ this project, as every registration polyctl wrote does: one that serves another project, or any program whose
261
+ arguments merely end in `mcp serve`, was taken with this project's and removed (LEADS-INSTALL). One polyctl
262
+ registered some other way is left, since leaving it is the smaller harm.
263
+ """
264
+ if not isinstance(entry, dict):
265
+ return False
266
+ args = entry.get("args")
267
+ words = [str(word) for word in args] if isinstance(args, list) else []
268
+ served = [index for index in range(2, len(words) - 1) if words[index:index + 2] == ["mcp", "serve"]]
269
+ if not served or words[served[-1] - 2] not in ("-C", "--root"):
270
+ return False
271
+ named = os.path.join(root, os.path.expanduser(words[served[-1] - 1]))
272
+ if os.path.normcase(os.path.realpath(named)) != os.path.normcase(os.path.realpath(root)):
273
+ return False
274
+ rest, index = words[served[-1] + 2:], 0
275
+ while index < len(rest):
276
+ if rest[index] == "--allow-verify" or rest[index].startswith("--role="):
277
+ index += 1
278
+ elif rest[index] == "--role" and index + 1 < len(rest):
279
+ index += 2
280
+ else:
281
+ return False
282
+ return True
283
+
284
+
285
+ def _mcp_entries(root):
286
+ """([(file, key, remove when empty)] holding polyctl's MCP server entry, [(file, why)] that could not be read).
287
+
288
+ Looked for where `polyctl init` merged the entry (skillkit.register_mcp): in the file each adapter declares, under
289
+ the key it declares. Two adapters may declare one file: it may go when either says so. A declared file that
290
+ resolves outside the project is not read, so an adapter a project declares for itself cannot point an
291
+ uninstall at another file. `polyctl remove` takes its project's entries from here too (UPDATE-UNINSTALL-2).
292
+ """
293
+ from . import skillkit
294
+ declared = {}
295
+ for _, adapter in skillkit.setup_adapters(root):
296
+ mcp = adapter.get("mcp") or {}
297
+ if not mcp.get("file"):
298
+ continue
299
+ spot = (os.path.join(root, *str(mcp["file"]).split("/")), mcp.get("key", "mcpServers"))
300
+ declared[spot] = declared.get(spot, False) or bool(mcp.get("remove_when_empty"))
301
+ found, unread = [], []
302
+ for (path, key), remove_when_empty in sorted(declared.items()):
303
+ if not os.path.isfile(path) or not _hook_contains(root, path):
304
+ continue
305
+ try:
306
+ with open(path, encoding=UTF8) as fh:
307
+ document = json.load(fh)
308
+ except (OSError, ValueError) as exc:
309
+ unread.append((path, " ".join(str(exc).split())))
310
+ continue
311
+ servers = document.get(key) if isinstance(document, dict) else None
312
+ if isinstance(servers, dict) and _serves_polyctl(servers.get("polyctl"), root):
313
+ found.append((path, key, remove_when_empty))
314
+ return found, unread
315
+
316
+
317
+ # What an MCP file that changed while polyctl took its entry out is left with, and what the person does.
318
+ MCP_CHANGED = "it changed while polyctl was taking its entry out, and is left as it now is; run the removal again"
319
+
320
+
321
+ def _drop_mcp_entry(path, key, remove_when_empty, root):
322
+ """Take polyctl's server out of one MCP file of the project at `root`, every other entry and key kept; "entry" or
323
+ "file", what went.
324
+
325
+ Written whole and durably, through the project's own folders and file, never a symbolic link. The file itself goes
326
+ only when its adapter says so and nothing but the empty server table is left in it. Raises OSError or
327
+ ValueError when the file cannot be read or written, no longer holds polyctl's entry, resolves outside the project,
328
+ or changed meanwhile.
329
+
330
+ The file is found again here, without following links even to another file inside the project: `_mcp_entries`
331
+ found it before the jobs and hooks went, and a link swapped in since redirected the write (LEADS-INSTALL).
332
+ Storage holds the folders for the read, write and rename: relative descriptors on POSIX, native handles without
333
+ delete sharing
334
+ on Windows, and refusal where neither is available. A file that goes has its directory synced where the
335
+ platform supports it, as a replaced one has (storage.replace_file_durably).
336
+
337
+ A change another program made meanwhile was overwritten (LEADS-INSTALL). The new file is written and synced
338
+ first, and the bytes are read again as the last thing before the rename or the delete: a change made until
339
+ then is left as it is, and said. What files cannot close is the instant between that reading and the rename
340
+ or the delete, a few system calls long: a program that replaces the file in it loses its change. No lock
341
+ helps there, since nothing else that writes these files - a harness, an editor, `polyctl init` - takes one.
342
+ """
343
+ real = os.path.realpath(path)
344
+ if not _hook_contains(root, real):
345
+ raise ValueError(f"it resolves to {real}, outside the project, and is not written there; take polyctl's entry "
346
+ "out of it by hand if it is there")
347
+ from . import storage
348
+ base = os.path.realpath(root)
349
+ # The containment check above is a diagnostic, not the path to open: resolving a link within the project
350
+ # would otherwise rewrite or unlink its target while leaving the link behind (LEADS-INSTALL).
351
+ steps = storage._tree_parts(os.path.relpath(path, root))
352
+ with storage._tree_folder(base, steps[:-1], make=False) as directory:
353
+ if directory is None:
354
+ raise FileNotFoundError(path)
355
+ return _drop_mcp_entry_in(directory, steps[-1], key, remove_when_empty, root)
356
+
357
+
358
+ def _mcp_without_polyctl(data, key, root):
359
+ """The MCP document in `data` with polyctl's server taken out; ValueError when it holds none of this project's."""
360
+ document = json.loads(data.decode(UTF8))
361
+ servers = document.get(key) if isinstance(document, dict) else None
362
+ if not isinstance(servers, dict) or not _serves_polyctl(servers.get("polyctl"), root):
363
+ raise ValueError(f"no `polyctl` entry under {key} any more")
364
+ del servers["polyctl"]
365
+ return document
366
+
367
+
368
+ def _drop_mcp_entry_in(directory, name, key, remove_when_empty, root):
369
+ """`_drop_mcp_entry` on the file `name` in an open directory, every step through it (LEADS-INSTALL)."""
370
+ import secrets
371
+ from . import storage
372
+
373
+ def read():
374
+ with os.fdopen(storage._tree_open(directory, name, os.O_RDONLY), "rb") as fh:
375
+ return fh.read(), os.fstat(fh.fileno()).st_mode & 0o7777
376
+
377
+ data, mode = read()
378
+ document = _mcp_without_polyctl(data, key, root)
379
+ if remove_when_empty and document == {key: {}}:
380
+ if read()[0] != data: # the last thing before the delete (see _drop_mcp_entry)
381
+ raise ValueError(MCP_CHANGED)
382
+ storage._tree_unlink(directory, name)
383
+ storage._tree_sync(directory, os.fsync)
384
+ return "file"
385
+ payload = json.dumps(document, indent=2).encode(UTF8)
386
+ temporary = f".{name}.{os.getpid()}.{secrets.token_hex(4)}.tmp"
387
+ fd = storage._tree_open(directory, temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
388
+ try:
389
+ _write_whole(fd, payload, temporary, mode=mode if isinstance(directory, int) else None)
390
+ if read()[0] != data: # the last thing before the rename (see _drop_mcp_entry)
391
+ raise ValueError(MCP_CHANGED)
392
+ storage._tree_rename(directory, temporary, name)
393
+ except BaseException:
394
+ try:
395
+ storage._tree_unlink(directory, temporary)
396
+ except OSError:
397
+ pass
398
+ raise
399
+ storage._tree_sync(directory, os.fsync)
400
+ return "entry"
401
+
402
+
403
+ def _write_whole(fd, payload, name, mode=None):
404
+ """Write `payload` whole to the new file open at `fd`, sync it and close it, whatever happens."""
405
+ try:
406
+ if mode is not None:
407
+ os.fchmod(fd, mode)
408
+ view = memoryview(payload)
409
+ while view:
410
+ written = os.write(fd, view)
411
+ if written <= 0:
412
+ raise OSError(f"writing {name} made no progress")
413
+ view = view[written:]
414
+ os.fsync(fd)
415
+ finally:
416
+ os.close(fd)
417
+
418
+
419
+ def _registry_problem():
420
+ """Why the machine registry cannot be read, or None; a registry that is simply not there is no problem.
421
+
422
+ A.project_registry() reads an unreadable registry as holding no project, which for an uninstall would be a
423
+ silent pass over every project's hooks.
424
+ """
425
+ path = A.project_registry_path()
426
+ try:
427
+ with open(path, encoding=UTF8) as fh:
428
+ rows = json.load(fh)
429
+ except FileNotFoundError:
430
+ return None
431
+ except (OSError, ValueError) as exc:
432
+ return (f"{_home_relative(path)} cannot be read ({' '.join(str(exc).split())}), so no project's hooks are "
433
+ "looked at")
434
+ return None if isinstance(rows, dict) else (f"{_home_relative(path)} holds no JSON object, so no project's "
435
+ "hooks are looked at")
436
+
437
+
438
+ def _uninstall_projects():
439
+ """What an uninstall finds in each project the machine registry knows: one dict per resolved path.
440
+
441
+ names, every name the registry holds for the path, and root; gone when the directory is not there; problem
442
+ when its hooks cannot be resolved in a git work tree; inv, the hook inventory `_hooks_uninstall` acts on;
443
+ hooks, the files it would remove; stays, polyctl's hooks it leaves - tracked, of a track state git cannot measure
444
+ (outside every work tree), or not polyctl's exact bytes; mcp and unread, from `_mcp_entries`.
445
+ """
446
+ rows = {}
447
+ for name, row in sorted(A.project_registry().items()):
448
+ if row["root"] in rows:
449
+ rows[row["root"]]["names"].append(name)
450
+ continue
451
+ project = rows[row["root"]] = {"names": [name], "root": row["root"], "gone": False, "problem": None,
452
+ "inv": None, "hooks": [], "stays": [], "mcp": [], "unread": []}
453
+ root = row["root"]
454
+ if not os.path.isdir(root):
455
+ project["gone"] = True
456
+ continue
457
+ inv = _polyctl_hook_inventory(root)
458
+ if inv["error"]:
459
+ try:
460
+ in_git = _hook_git(root, "rev-parse", "--git-dir").returncode == 0
461
+ except _HookResolutionError:
462
+ in_git = True # unknown: say so rather than call it hook-free
463
+ project["problem"] = f"its hooks cannot be resolved: {inv['error']}" if in_git else None
464
+ else:
465
+ project["inv"] = inv
466
+ project["hooks"] = _hook_removal_plan(inv)
467
+ project["stays"] = [target for target in inv["targets"] if target not in project["hooks"]
468
+ and _state_base(target["static_state"]) in POLYCTL_HOOK_STATES]
469
+ project["mcp"], project["unread"] = _mcp_entries(root)
470
+ return list(rows.values())
471
+
472
+
473
+ def _program_removal(found):
474
+ """What removes the polyctl program itself, as an instruction to a person: `polyctl uninstall` runs none of it."""
475
+ if found["remove"]:
476
+ return f"run `{_argv_text(found['remove'])}`"
477
+ if found["kind"] == "clone":
478
+ target = os.path.realpath(os.path.join(found["where"], "bin", "polyctl"))
479
+ links = sorted({path for path in (A.program_path("polyctl"), os.path.join(A.HOME, ".local", "bin", "polyctl"))
480
+ if path and os.path.islink(path) and os.path.realpath(path) == target})
481
+ return f"delete the clone {found['where']}" + "".join(f" and the link {link}" for link in links)
482
+ return "remove it the way it was installed"
483
+
484
+
485
+ def _pinged():
486
+ """How many dead man's switch URLs `polyctl pings setup` recorded: the pings stop with the jobs."""
487
+ try:
488
+ with open(A.pings_path(), encoding=UTF8) as fh:
489
+ urls = json.load(fh)
490
+ except (OSError, ValueError):
491
+ return 0
492
+ return len([url for url in urls.values() if url]) if isinstance(urls, dict) else 0
493
+
494
+
495
+ def _uninstall_leaves(args, found):
496
+ """The lines naming what an uninstall leaves on this machine, and what takes each."""
497
+ lines = [f"in each project: .polyctl/ with its ledgers, the mailbox, reviews, the .polyctl-project marker and the "
498
+ f"playbook files — `polyctl remove --yes` in a project takes those, while polyctl is still installed",
499
+ f"projects {_home_relative(A.project_registry_path())} does not hold: `polyctl hooks uninstall` in each"]
500
+ if not args.purge:
501
+ lines.append(f"{_home_relative(os.path.join(A.HOME, '.polyctl'))}: polyctl's settings, channel credentials, logs, "
502
+ "archived reviews and the project registry — `--purge` deletes it")
503
+ lines.append(f"the program itself: {_program_removal(found)}")
504
+ pinged = _pinged()
505
+ if pinged:
506
+ lines.append(f"the dead man's switch: {pinged} ping URL(s) stop being called with the jobs, and the "
507
+ "service behind them will alarm — pause the check there")
508
+ if _scheduler() == "systemd":
509
+ lines.append("systemd: a unit you wrote to run polyctl stays; polyctl's own, the timers `polyctl watchdog install` wrote, "
510
+ "are among the jobs above (LINUX-SCHEDULER)")
511
+ elif A.program_path("systemctl"):
512
+ lines.append("systemd: polyctl schedules no unit of its own here (its jobs are launchd's or Task Scheduler's), "
513
+ "so a unit you wrote to run polyctl stays")
514
+ return lines
515
+
516
+
517
+ def cmd_uninstall(cfg, args):
518
+ """Take off this machine what polyctl installed on it, a dry run unless --yes (UPDATE-UNINSTALL).
519
+
520
+ Three things of polyctl's run or load without anyone asking. Its scheduled jobs go first, each checked gone, so
521
+ none runs against what follows. Then, in every project the machine registry knows, its git hooks - only
522
+ files that are polyctl's exact bytes and untracked, as `polyctl hooks uninstall` takes them, with the same
523
+ --allow-shared-hooks - and the `polyctl` entry `polyctl init` merged into the project's MCP files. The hooks matter
524
+ most: once the program is gone, an enrolled project's hook fails every commit with "polyctl not found". With the
525
+ jobs gone, the watchdog heartbeats of those projects go too, as `polyctl watchdog uninstall` takes one, since a
526
+ heartbeat left behind reads as a dead watchdog.
527
+
528
+ What stays is named: each project's own state, ~/.polyctl unless --purge, and the program, with the command
529
+ that removes it. --purge deletes ~/.polyctl only when nothing was left behind, since its registry is how a
530
+ second run finds the projects whose hooks stayed. Exit 1 names each thing left.
531
+ """
532
+ allow = bool(getattr(args, "allow_shared_hooks", False))
533
+ jobs = _machine_jobs()
534
+ unreadable = _registry_problem()
535
+ projects = _uninstall_projects()
536
+ found = _installation()
537
+ home = os.path.join(A.HOME, ".polyctl")
538
+ names = [name for project in projects for name in project["names"]]
539
+ beats = [path for path in (os.path.join(home, A.project_file_name("heartbeat", name)) for name in names)
540
+ if os.path.lexists(path)]
541
+
542
+ print(f"{C['b']}polyctl uninstall{C['reset']} {'takes' if args.yes else 'would take'} off this machine:")
543
+ for kind, name in jobs:
544
+ print(f" {kind} {name}")
545
+ for path in beats:
546
+ print(f" {_home_relative(path)} (a heartbeat left behind reads as a dead watchdog)")
547
+ if unreadable:
548
+ print(f" {C['red']}{unreadable}{C['reset']}")
549
+ for project in projects:
550
+ root = project["root"]
551
+ empty = not any(project[what] for what in ("problem", "hooks", "mcp", "stays", "unread"))
552
+ print(f" {C['b']}{', '.join(project['names'])}{C['reset']} {root}"
553
+ + (f" {C['dim']}gone from disk: nothing of it to take{C['reset']}" if project["gone"]
554
+ else f" {C['dim']}nothing of polyctl's to take{C['reset']}" if empty else ""))
555
+ if project["problem"]:
556
+ print(f" {C['red']}{project['problem']}{C['reset']}")
557
+ for target in project["hooks"]:
558
+ needs = target["needs_authorization"] and not allow
559
+ print(f" hook {target['role']} — {target['path']}"
560
+ + (f" {C['yellow']}needs --allow-shared-hooks{C['reset']}" if needs else ""))
561
+ for path, _, _ in project["mcp"]:
562
+ print(f" the `polyctl` server entry in {os.path.relpath(path, root)} (other entries stay)")
563
+ for target in project["stays"]:
564
+ print(f" {C['dim']}stays: {target['static_state']} {target['role']} — {target['path']} "
565
+ f"({target['track_state']}, {target['reachability']}){C['reset']}")
566
+ for path, why in project["unread"]:
567
+ print(f" {C['red']}cannot read {os.path.relpath(path, root)}{C['reset']}: {why}")
568
+ if args.purge and os.path.lexists(home):
569
+ print(f" {_home_relative(home)}: every file polyctl keeps on this machine — settings, channel credentials, "
570
+ "logs, archived reviews and the project registry")
571
+ print("it leaves:")
572
+ for line in _uninstall_leaves(args, found):
573
+ print(f" {C['dim']}{line}{C['reset']}")
574
+ if not args.yes:
575
+ print(f"\nre-run with {C['b']}--yes{C['reset']} to do it")
576
+ return 0
577
+
578
+ # The jobs first, in this process, each checked gone: one left behind keeps running against the rest.
579
+ left = []
580
+ for kind, name in jobs:
581
+ problem = _unschedule(name)
582
+ if problem:
583
+ left.append(name)
584
+ print(f"{C['red']}left{C['reset']} {kind} {name}: {problem}")
585
+ else:
586
+ print(f"removed {kind} {name}")
587
+ if left and beats:
588
+ print(f"kept {len(beats)} heartbeat(s): a job left behind still writes one")
589
+ for path in beats if not left else []:
590
+ try:
591
+ os.remove(path)
592
+ except FileNotFoundError:
593
+ pass
594
+ except OSError as exc:
595
+ left.append(path)
596
+ print(f"{C['red']}left{C['reset']} {_home_relative(path)}: {exc}")
597
+ if unreadable:
598
+ left.append(A.project_registry_path())
599
+ print(f"{C['red']}left{C['reset']} the hooks and MCP entries of every project: {unreadable}")
600
+ for project in projects:
601
+ root = project["root"]
602
+ if project["problem"]:
603
+ left.append(root)
604
+ print(f"{C['red']}left{C['reset']} the hooks of {root}: {project['problem']}")
605
+ elif project["inv"] is not None and (project["hooks"] or project["stays"]):
606
+ if _hooks_uninstall(project["inv"], allow):
607
+ left.append(root)
608
+ print(f"{C['red']}left{C['reset']} hooks of {root}, each named above")
609
+ for path, key, remove_when_empty in project["mcp"]:
610
+ shown = os.path.relpath(path, root)
611
+ try:
612
+ gone = _drop_mcp_entry(path, key, remove_when_empty, root)
613
+ except (OSError, ValueError) as exc:
614
+ left.append(path)
615
+ print(f"{C['red']}left{C['reset']} the `polyctl` entry in {path}: {' '.join(str(exc).split())}")
616
+ continue
617
+ print(f"removed {shown} of {root}, which held only polyctl's entry" if gone == "file"
618
+ else f"removed the `polyctl` entry from {shown} of {root}")
619
+ for path, why in project["unread"]:
620
+ left.append(path)
621
+ print(f"{C['red']}left{C['reset']} {path}: it cannot be read ({why}), so any `polyctl` entry in it stays")
622
+ if args.purge and os.path.lexists(home):
623
+ if left:
624
+ print(f"{C['yellow']}kept{C['reset']} {_home_relative(home)}: {len(left)} thing(s) were left, and its "
625
+ "registry is how the next `polyctl uninstall` finds them")
626
+ else:
627
+ try:
628
+ shutil.rmtree(home)
629
+ print(f"removed {_home_relative(home)}")
630
+ except OSError as exc:
631
+ left.append(home)
632
+ print(f"{C['red']}left{C['reset']} {_home_relative(home)}: {exc}")
633
+ if left:
634
+ print(f"{C['red']}not complete{C['reset']}: {len(left)} thing(s) left, each named above")
635
+ return 1
636
+ print(f"{C['green']}uninstalled{C['reset']}: polyctl's jobs, hooks and MCP entries are off this machine; "
637
+ f"the program itself stays — {_program_removal(found)}")
638
+ return 0