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,2293 @@
1
+ """Checks: doctor problems, costs, settings, features, waivers, catch-up, pings.
2
+
3
+ A part of src/polyctl/cli.py (#44): moved out byte for byte and run in its namespace by `_part`,
4
+ where it stood; it is not importable on its own.
5
+ """
6
+
7
+
8
+ def _actor_grant_problems(cfg):
9
+ """Doctor findings for each configured actor whose tool grant admits a bypass (#58), whose permission mode is
10
+ not the one its adapter pins, or whose wake grant lacks what its playbook asks of it (GRANTS-PINNED)."""
11
+ from . import allowlist as AL
12
+ grants = []
13
+ impl = cfg.get("implementer") or {}
14
+ adapter = A.load_adapter(impl["adapter"]) if impl.get("adapter") else {}
15
+ if impl.get("adapter"):
16
+ grants.append(("implementer", impl["adapter"],
17
+ (adapter.get("resume") or {}).get("argv") or [], adapter.get("options") or {}, False))
18
+ # Another launch whose argv carries a grant of its own is asked what it admits too; only the resume's
19
+ # was, and a grant written into another launch went unread (GRANTS-AUDIT-2).
20
+ for key in sorted(adapter):
21
+ block = adapter[key]
22
+ argv = block.get("argv") if key != "resume" and isinstance(block, dict) else None
23
+ if isinstance(argv, list) and (A.carries_scope(argv) or any(str(arg) in AL.GRANT_ALL for arg in argv)):
24
+ grants.append((f"implementer {key}", impl["adapter"], argv, {}, False))
25
+ for role in ("architect", "reviewer"):
26
+ actor = cfg.get(role) or {}
27
+ if actor.get("argv"):
28
+ grants.append((role, actor.get("id") or actor.get("name") or role, actor["argv"], {}, _tool_route(actor)))
29
+ for fallback in (cfg.get("reviewer") or {}).get("fallbacks") or []:
30
+ if fallback.get("argv"):
31
+ grants.append(("reviewer fallback", fallback.get("id") or "fallback", fallback["argv"], {},
32
+ _tool_route(fallback)))
33
+ if M.is_strict(cfg):
34
+ # Doctor reads the routes a strict review starts, not its ignored inline argv (TRIAGE-3-LOW).
35
+ grants = [grant for grant in grants if not grant[0].startswith("reviewer")]
36
+ try:
37
+ for route in _resolve_matrix(cfg, require_independent=False)["reviewers"]:
38
+ grants.append(("reviewer", route["identity"]["binding"], M.expand_argv(route, "{prompt}"), {}, False))
39
+ except M.MatrixError:
40
+ pass # the matrix check names the error (TRIAGE-3-LOW).
41
+ out = []
42
+ for role, name, argv, options, tool in grants:
43
+ if role == "implementer":
44
+ # A turn that would turn off its harness's own sandbox is not started until a person allows it,
45
+ # and the doctor says what allowing it costs (GRANTS-PINNED).
46
+ flags = A.unattended_flags(adapter, argv)[0]
47
+ refused = A.bypass_refusal(adapter, flags, cfg)
48
+ if refused:
49
+ out.append((f"nudge-refused:{name}", f"the watchdog nudges no {name} implementer: {refused}; allowed, "
50
+ "each unattended turn runs every command outside that sandbox, "
51
+ "with the network, and writes wherever this user can"))
52
+ continue
53
+ text = AL.describe(role, name, AL.problems(argv, options, role=role.split()[0]))
54
+ if text and role == "implementer" and A.sandbox_bypass(adapter, A.unattended_flags(adapter, argv)[0]):
55
+ text += (f"; and a person allowed {A.sandbox_bypass(adapter, A.unattended_flags(adapter, argv)[0])[0]} "
56
+ "on this machine (watchdog.bypass_adapters), so its turns run outside its sandbox, with the network")
57
+ if text:
58
+ out.append((f"actor-grant:{role.replace(' ', '-')}", text))
59
+ # A reviewer reads, and starts no MCP server it was not given (#24).
60
+ if role.startswith("reviewer"):
61
+ # File tools do not read a tree; review invocation skips these checks too (TRIAGE-3-LOW).
62
+ if tool:
63
+ continue
64
+ argv, _ = A.pinned_argv(argv, "reviewer")
65
+ reach = AL.reviewer_problems(argv)
66
+ if A.command_adapter(argv) is not None:
67
+ reach += A.reading_problems(argv)
68
+ if reach:
69
+ out.append((f"reviewer-tools:{name}", f"{role} ({name}): " + "; ".join(reach)))
70
+ elif A.pin_conflicts(argv, role):
71
+ out.append((f"actor-mode:{role}", f"{role} ({name}): " + "; ".join(A.pin_conflicts(argv, role))))
72
+ out.extend(_architect_grant_gaps(cfg))
73
+ return out
74
+
75
+
76
+ def _architect_grant_gaps(cfg):
77
+ """The rules the architect's configured grant lacks of the one its adapter declares now (GRANTS-PINNED).
78
+
79
+ `polyctl init` writes the architect's argv into .polyctl/config.json, so a grant composed before the
80
+ adapter's changed stays as it was: a refill wake told to write .polyctl/inbox/ could not. The grant
81
+ is the package's adapter's, as init composes it (TRIAGE-HIGHS).
82
+ """
83
+ from . import allowlist as AL
84
+ architect = cfg.get("architect") or {}
85
+ declared = (A.turn_adapter(architect["adapter"]) or {}) if architect.get("adapter") and architect.get("argv") \
86
+ else {}
87
+ options = declared.get("options") or {}
88
+ wanted = A.split_tool_list(str(options.get("architect_tools") or ""))
89
+ have = set(AL.rules(architect.get("argv") or []))
90
+ missing = [rule for rule in wanted if rule not in have]
91
+ if not wanted or not missing:
92
+ return []
93
+ flag = (options.get("allowed_tools") or ["the tool grant"])[0]
94
+ return [("architect-grant", f"the architect's grant lacks {len(missing)} rule(s) its playbook and prompts need "
95
+ f"({', '.join(missing[:5])}{', …' if len(missing) > 5 else ''}): replace the value "
96
+ f"after {flag} in the architect's argv in .polyctl/config.json with "
97
+ f"{architect['adapter']}'s options.architect_tools")]
98
+
99
+
100
+ def _implementer_commit_guard(cfg):
101
+ """Which guard holds commits for the configured implementer, in one sentence (#109)."""
102
+ from . import allowlist as AL
103
+ impl = cfg.get("implementer") or {}
104
+ if not impl.get("adapter"):
105
+ return None
106
+ adapter = A.load_adapter(impl["adapter"])
107
+ argv = (adapter.get("resume") or {}).get("argv") or []
108
+ if AL.problems(argv, adapter.get("options") or {}):
109
+ return (f"{impl['adapter']} can commit around the hook; an ungranted commit is not "
110
+ "prevented but surfaces within one watchdog cycle (landed-tree check)")
111
+ return f"{impl['adapter']}'s grant admits no hook bypass; polyctl commit and the hook hold commits"
112
+
113
+
114
+ ENFORCEMENT_OFF_LITE = "enforcement: off - lite"
115
+ ENFORCEMENT_OFF_LITE_LINE = f"{ENFORCEMENT_OFF_LITE} — nothing is enforced"
116
+
117
+
118
+ def _lite_mode_opt_in(cfg):
119
+ """The recorded opt-in row when `mode` is `'lite'` in `.polyctl/config.json` with a valid `by` record, else None (MODES)."""
120
+ root = cfg.get("root")
121
+ if not root:
122
+ return None
123
+ try:
124
+ row = A.recorded_opt_in(root, "mode")
125
+ except Exception:
126
+ return None
127
+ if not isinstance(row, dict) or row.get("value") != "lite":
128
+ return None
129
+ value, source, _ = S.resolve(cfg, "mode")
130
+ if value != "lite" or source != "project":
131
+ try:
132
+ A.record_opt_in(root, "mode", "full", "polyctl")
133
+ except Exception:
134
+ pass
135
+ return None
136
+ by = str(row.get("by") or "").strip()
137
+ if not by or by == "polyctl init" or by.lower() in _agent_names(cfg):
138
+ return None
139
+ return row
140
+
141
+
142
+ def unrecorded_lite(cfg):
143
+ """Where `mode` is set to `lite` without a recorded opt-in, or None (MODES)."""
144
+ value, source, _ = S.resolve(cfg, "mode")
145
+ if value == "lite" and _lite_mode_opt_in(cfg) is None:
146
+ return ".polyctl/config.json" if source == "project" else f"the {source} settings"
147
+ return None
148
+
149
+
150
+ def project_mode(cfg):
151
+ """The project's effective mode: `'lite'` when set to `lite` in `.polyctl/config.json` with a recorded opt-in, else `'full'`."""
152
+ return "lite" if _lite_mode_opt_in(cfg) is not None else "full"
153
+
154
+
155
+ def _init_hook_problem(root, allow_shared_hooks=False):
156
+ """Why commit hooks cannot be installed in `root`, or None when they can (MODES)."""
157
+ enrollment = _project_enrollment(root)
158
+ redirected = enrollment["detail"] if enrollment["state"] == "redirected" else _commit_repository_binding(root)
159
+ if redirected:
160
+ return redirected
161
+ if enrollment.get("unknown"):
162
+ return _hook_install_problem(enrollment)
163
+ inv = _polyctl_hook_inventory(root)
164
+ if inv["error"]:
165
+ return inv["error"]
166
+ if os.path.lexists(inv["active_dir"]) and not os.path.isdir(inv["active_dir"]):
167
+ return f"effective hook path is not a directory: {inv['active_dir']}"
168
+ targets = _active_hook_targets(inv)
169
+ target = targets["pre-commit"]
170
+ base = _state_base(target["static_state"])
171
+ if base not in ("current-local", "current-scoped") and not (
172
+ target["eligible"] and base in ("absent", "legacy")
173
+ ):
174
+ return (
175
+ f"pre-commit hook at {target['path']} is {target['static_state']} / {target['track_state']} "
176
+ "and cannot be installed"
177
+ )
178
+ if any(t["needs_authorization"] for t in targets.values()) and (os.name == "nt" or not allow_shared_hooks):
179
+ return (
180
+ SHARED_HOOKS_REFUSED
181
+ if os.name == "nt"
182
+ else f"hooks at {inv['active_dir']} are {inv['directory_class']} (pass --allow-shared-hooks)"
183
+ )
184
+ return None
185
+
186
+
187
+ def _mode_full_missing(cfg, allow_shared_hooks=False):
188
+ """What `polyctl mode full` needs before switching: reviewer independence/probe and installable commit hooks (MODES)."""
189
+ root = cfg["root"]
190
+ probe_cfg = dict(cfg, mode="full")
191
+ missing = []
192
+ if M.is_strict(probe_cfg):
193
+ probe = _reviewer_probe(probe_cfg)
194
+ if not probe["ok"]:
195
+ missing.append(f"independent reviewer: {_reviewer_probe_text(probe)}")
196
+ elif not probe_cfg.get("implementer"):
197
+ missing.append(
198
+ "independent reviewer: no implementer is configured "
199
+ f"(polyctl init --profile {A.default_profile()}, or an implementer in .polyctl/config.json)"
200
+ )
201
+ else:
202
+ reviewer = probe_cfg.get("reviewer") or {}
203
+ if reviewer and not reviewer.get("argv"):
204
+ missing.append(
205
+ "independent reviewer: no model reviewer is configured "
206
+ "(polyctl role set reviewer <adapter> --model <model>)"
207
+ )
208
+ elif reviewer.get("argv"):
209
+ probe = _reviewer_probe(probe_cfg)
210
+ if not probe["ok"]:
211
+ missing.append(f"independent reviewer: {_reviewer_probe_text(probe)}")
212
+ enrollment = _project_enrollment(root)
213
+ redirected = enrollment["detail"] if enrollment["state"] == "redirected" else _commit_repository_binding(root)
214
+ if redirected:
215
+ missing.append(f"commit hooks: {redirected}")
216
+ elif enrollment.get("unknown") or _hook_install_problem(enrollment):
217
+ missing.append(f"commit hooks: {_hook_install_problem(enrollment)}")
218
+ elif enrollment["state"] == "uninitialized":
219
+ missing.append(
220
+ f"commit hooks: {PROJECT_MARKER} is not tracked in HEAD or the index "
221
+ f"(stage {PROJECT_MARKER} with git add {PROJECT_MARKER})"
222
+ )
223
+ else:
224
+ hook_problem = _init_hook_problem(root, allow_shared_hooks=allow_shared_hooks)
225
+ if hook_problem:
226
+ missing.append(f"commit hooks: {hook_problem}")
227
+ return missing
228
+
229
+
230
+ def _uninstall_lite_hooks(root, allow_shared_hooks=False):
231
+ """Remove untracked polyctl hooks when switching to `lite` mode; tracked hooks stay in the tree and stand aside in `polyctl commit-check` and `polyctl push check`."""
232
+ inv = _polyctl_hook_inventory(root)
233
+ if inv["error"]:
234
+ return
235
+ for target in inv["targets"]:
236
+ base = _state_base(target["static_state"])
237
+ if base not in ("current-local", "current-scoped", "legacy"):
238
+ continue
239
+ if target["track_state"] != "untracked":
240
+ continue
241
+ if (target["directory_class"] in ("shared", "external") or target["globally_configured"]) and (
242
+ os.name == "nt" or not allow_shared_hooks
243
+ ):
244
+ continue
245
+ try:
246
+ os.remove(target["path"])
247
+ except OSError:
248
+ pass
249
+
250
+
251
+ def cmd_mode(cfg, args):
252
+ """Show or switch the project mode: `lite`, `full`, or `show` (MODES)."""
253
+ from .storage import ReplacedNotDurable
254
+ root = cfg["root"]
255
+ action = getattr(args, "action", "show") or "show"
256
+ by = (getattr(args, "by", None) or "").strip()
257
+ if action == "show":
258
+ if by:
259
+ print("--by is only used with `polyctl mode lite --by <name>`")
260
+ return 2
261
+ where = unrecorded_lite(cfg)
262
+ if where:
263
+ print(
264
+ f"{C['yellow']}mode is lite in {where} with no person's record, so full mode stays in force"
265
+ f"{C['reset']}: polyctl mode lite --by <name>"
266
+ )
267
+ mode = project_mode(cfg)
268
+ if mode == "lite":
269
+ opt_in = _lite_mode_opt_in(cfg)
270
+ who = f" (set by {_person_line(opt_in)})" if opt_in else ""
271
+ print(f"mode: lite — {ENFORCEMENT_OFF_LITE_LINE}{who}")
272
+ else:
273
+ print("mode: full — enforcement: on")
274
+ print("\nfull mode:")
275
+ print(
276
+ " protects: independent reviewer probe and review gate, commit-ok grant, "
277
+ "pre-commit and pre-push hooks, and polyctl commit gate enforcement"
278
+ )
279
+ print(
280
+ " does not protect: commits made outside polyctl's hooks or with --no-verify on a harness whose "
281
+ "tool grant admits raw git commit (surfaced after the fact as landed-without-grant)"
282
+ )
283
+ print(f"\nlite mode ({ENFORCEMENT_OFF_LITE}):")
284
+ print(
285
+ " protects: nothing is enforced — basic setup only (.polyctl/config.json, .polyctl/backlog.md, "
286
+ ".polyctl/gates.json, mailbox, status, doctor, and the playbook)"
287
+ )
288
+ print(
289
+ " does not protect: no reviewer probe, no independent review gate, no commit hooks, "
290
+ "no pre-commit or pre-push enforcement, and polyctl commit refuses because there is no gate to commit through"
291
+ )
292
+ return 0
293
+ if action == "lite":
294
+ if not by or not by.isprintable() or len(by) > 80:
295
+ print(
296
+ "--by is required: switching to lite mode turns enforcement off (no reviewer probe, no commit hooks), "
297
+ "and a person does it on the record, in one line of at most 80 characters"
298
+ )
299
+ return 2
300
+ if by.lower() in _agent_names(cfg):
301
+ print(f"--by names an agent or a role ({by}); switching to lite mode is a person's act")
302
+ return 2
303
+ config_path = os.path.join(root, ".polyctl", "config.json")
304
+ if os.path.lexists(config_path) or _project_enrollment(root)["state"] != "uninitialized":
305
+ document = A.project_config_document(root)
306
+ if document["problem"]:
307
+ print(f"{C['red']}not changed{C['reset']}: {document['problem']}")
308
+ return 1
309
+ base_config = document["config"]
310
+ else:
311
+ base_config = {
312
+ "project": os.path.basename(root),
313
+ "round_budget": S.default("round_budget"),
314
+ }
315
+ try:
316
+ A.write_project_config(
317
+ root, json.dumps(S.assign(base_config, "mode", "lite"), indent=2, ensure_ascii=False)
318
+ )
319
+ except ReplacedNotDurable as exc:
320
+ print(f"{C['red']}{exc}{C['reset']}; no opt-in was recorded; retry this command to record one if required")
321
+ return 1
322
+ except (OSError, ValueError) as exc:
323
+ print(f"{C['red']}not changed{C['reset']}: {exc}")
324
+ return 1
325
+ try:
326
+ A.record_opt_in(root, "mode", "lite", by)
327
+ except Exception as exc:
328
+ print(f"{C['red']}not recorded{C['reset']}: {exc}; lite mode is not in force until it is")
329
+ return 1
330
+ _uninstall_lite_hooks(root, allow_shared_hooks=bool(getattr(args, "allow_shared_hooks", False)))
331
+ print(f"mode = 'lite' (recorded as set by {by}) — {ENFORCEMENT_OFF_LITE_LINE}")
332
+ return 0
333
+ if action == "full":
334
+ document = A.project_config_document(root)
335
+ if document["problem"]:
336
+ print(f"{C['red']}not changed{C['reset']}: {document['problem']}")
337
+ return 1
338
+ allow = bool(getattr(args, "allow_shared_hooks", False))
339
+ missing = _mode_full_missing(cfg, allow_shared_hooks=allow)
340
+ if missing:
341
+ print(
342
+ f"{C['red']}mode full refused{C['reset']}: full mode needs an independent reviewer route and "
343
+ f"working commit hooks; still in {project_mode(cfg)} mode:"
344
+ )
345
+ for item in missing:
346
+ print(f" - {item}")
347
+ return 1
348
+ was_lite = project_mode(cfg) == "lite"
349
+ rc, install_problems = _hooks_install(dict(cfg, mode="full"), allow_shared_hooks=allow)
350
+ after_inv = _polyctl_hook_inventory(root)
351
+ pre_commit_ok = (
352
+ not after_inv["error"]
353
+ and not _hook_install_problem(_project_enrollment(root))
354
+ and _state_base(_active_hook_targets(after_inv)["pre-commit"]["static_state"])
355
+ in ("current-local", "current-scoped")
356
+ )
357
+ if rc != 0 and not pre_commit_ok:
358
+ if was_lite:
359
+ _uninstall_lite_hooks(root, allow_shared_hooks=allow)
360
+ print(
361
+ f"{C['red']}mode full refused{C['reset']}: commit hooks could not be installed; "
362
+ f"still in {project_mode(cfg)} mode"
363
+ )
364
+ return 1
365
+ hook_proof = _hook_execution_probe(after_inv)
366
+ if not hook_proof["installed"]:
367
+ if was_lite:
368
+ _uninstall_lite_hooks(root, allow_shared_hooks=allow)
369
+ print(
370
+ f"{C['red']}mode full refused{C['reset']}: commit hooks: {_hook_probe_text(hook_proof)}; "
371
+ f"still in {project_mode(cfg)} mode"
372
+ )
373
+ return 1
374
+ planned_text = json.dumps(S.assign(document["config"], "mode", "full"), indent=2, ensure_ascii=False)
375
+ try:
376
+ A.record_opt_in(root, "mode", "full", by or "human")
377
+ except Exception as exc:
378
+ if was_lite:
379
+ _uninstall_lite_hooks(root, allow_shared_hooks=allow)
380
+ print(f"{C['red']}not recorded{C['reset']}: {exc}")
381
+ return 1
382
+ try:
383
+ A.write_project_config(root, planned_text)
384
+ except ReplacedNotDurable as exc:
385
+ print(f"{C['red']}{exc}{C['reset']}")
386
+ return 1
387
+ except (OSError, ValueError) as exc:
388
+ print(f"{C['red']}not changed{C['reset']}: {exc}")
389
+ return 1
390
+ push_target = _own_pre_push_target(after_inv)
391
+ if push_target is not None:
392
+ print(f" {C['dim']}push guard{C['reset']} {_own_pre_push_line(push_target)}")
393
+ else:
394
+ other_push = _other_pre_push_line(after_inv)
395
+ if other_push is not None:
396
+ print(f" {C['yellow']}push guard {other_push}{C['reset']}")
397
+ else:
398
+ push_after = _active_hook_targets(after_inv).get("pre-push") if not after_inv.get("error") else None
399
+ if not push_after or _state_base(push_after["static_state"]) not in ("current-local", "current-scoped"):
400
+ why = install_problems.get("pre-push") or install_problems.get("install") or (
401
+ f"{push_after['path']} is {push_after['static_state']} / {push_after['track_state']}"
402
+ if push_after else "hook target could not be resolved"
403
+ )
404
+ print(
405
+ f" {C['yellow']}push guard not installed — pre-push was not installed ({why}); "
406
+ f"run `polyctl hooks install`{C['reset']}"
407
+ )
408
+ print("mode = 'full' — enforcement: on (independent reviewer probe and commit hooks active)")
409
+ return 0
410
+ return 2
411
+
412
+
413
+ def _active_review_tier(cfg):
414
+ """(the review tier a review would stand in now, [(key, problem)]), from the configuration alone (REVIEW-TIERS).
415
+
416
+ No reviewer is run. A project with no implementer to compare a reviewer with passed
417
+ every check while checking nothing, and a reviewer no tier admits was named only by
418
+ a probe: both are problems now, and so is an opt-in written into a config by hand
419
+ with no person's record, which is not in force.
420
+ """
421
+ from . import tiers as T
422
+ root = cfg["root"]
423
+ problems = []
424
+ value, source, _ = S.resolve(cfg, "mode")
425
+ if value == "lite" and _lite_mode_opt_in(cfg) is None:
426
+ where = ".polyctl/config.json" if source == "project" else f"the {source} settings"
427
+ problems.append(("mode-opt-in", f"mode is lite in {where}, but no person's opt-in is recorded for this "
428
+ "project, so full mode stays in force — polyctl mode lite --by <name>"))
429
+ if project_mode(cfg) == "lite":
430
+ return f"none ({ENFORCEMENT_OFF_LITE})", problems
431
+ value, source, _ = S.resolve(cfg, "review.same_family")
432
+ opt_in = _same_family_opt_in(cfg)
433
+ if value == T.LABELED and opt_in is None:
434
+ where = ".polyctl/config.json" if source == "project" else f"the {source} settings"
435
+ problems.append(("review-opt-in", f"review.same_family is labeled in {where}, but no person's opt-in is "
436
+ "recorded for this project, so a reviewer of the implementer's family "
437
+ "is still refused — polyctl config set review.same_family labeled --by <name>"))
438
+ opted = f"; opted in by {_person_line(opt_in)}" if opt_in is not None else ""
439
+ if M.is_strict(cfg):
440
+ try:
441
+ eligible = [route for route in _resolve_matrix(cfg, require_independent=False)["reviewers"]
442
+ if route["eligible"]]
443
+ except M.MatrixError:
444
+ return "not established: the capability matrix cannot be resolved", problems
445
+ if not eligible:
446
+ return "none: no reviewer binding may review the implementer's work", problems
447
+ tier = eligible[0].get("tier")
448
+ return f"{T.label(tier)} ({eligible[0]['identity']['binding']}){opted if tier == T.SAME_FAMILY else ''}", \
449
+ problems
450
+ reviewer = cfg.get("reviewer") or {}
451
+ if not cfg.get("implementer") and os.path.exists(os.path.join(root, ".polyctl", "config.json")):
452
+ problems.append(("no-implementer", "no implementer is configured, so no reviewer can be shown to be of "
453
+ "another model family than the author and no review tier holds — "
454
+ f"polyctl init --profile {A.default_profile()}, or an implementer in "
455
+ ".polyctl/config.json"))
456
+ if not reviewer.get("argv"):
457
+ return ("person review: no model reviewer is configured, and each candidate lands on "
458
+ "polyctl person-review --by <name>" + _waiting_reviewer(cfg)), problems
459
+ tier, refused = _review_tier(cfg, reviewer)
460
+ if refused:
461
+ problems.append(("review-tier", _tier_refusal(refused)))
462
+ return f"none: {refused}", problems
463
+ if tier is None:
464
+ return "not established: no implementer is configured to compare the reviewer with", problems
465
+ return f"{T.label(tier)} ({reviewer.get('id') or 'reviewer'}){opted if tier == T.SAME_FAMILY else ''}", problems
466
+
467
+
468
+ def _harness_config_unseen(root):
469
+ """(the changes to what a harness reads here that no person has seen, or None; why they cannot be read, or None)
470
+ (HARNESS-CONFIG)."""
471
+ try:
472
+ return A.unseen_harness_config(root), None
473
+ except Exception as exc:
474
+ return None, " ".join(str(exc).split())[:240]
475
+
476
+
477
+ def _harness_config_problem(root):
478
+ """[("harness-config", text)] naming each change to what a harness reads here that no person has seen, or that it
479
+ cannot be read; [] when neither (HARNESS-CONFIG). A person must act: nothing polyctl starts in the tree runs until
480
+ then."""
481
+ unseen, unreadable = _harness_config_unseen(root)
482
+ if unreadable:
483
+ return [("harness-config", f"what a harness reads from this tree cannot be read ({unreadable}), so no wake, "
484
+ "refill, nudge, hunt or lane starts here until it can")]
485
+ if not unseen:
486
+ return []
487
+ return [("harness-config", f"{len(unseen)} change(s) to what a harness reads from this tree, unseen by a person: "
488
+ f"{A.harness_config_line(unseen, limit=20)} - no wake, refill, nudge, hunt or lane "
489
+ "starts here until a person reads them: polyctl harness seen --by <name>")]
490
+
491
+
492
+ def _harness_config_told(root):
493
+ """What the harness-config alarm is about, as the watchdog raises it: the digest of what stands unseen, or that it
494
+ cannot be read (HARNESS-CONFIG)."""
495
+ unseen, unreadable = _harness_config_unseen(root)
496
+ return "unreadable" if unreadable else A.harness_config_digest(unseen or [])
497
+
498
+
499
+ def _environment_problem(root):
500
+ """[("environment-in-tree", text)] when polyctl runs from, loads or trusts a place inside the tree an agent writes; []
501
+ otherwise (PYTHON-ENV). An advisory: what ran there ran before polyctl could name it, and only the person who set it up
502
+ can move it, so no turn is held for it - the files Python runs as it starts there are, as harness configuration."""
503
+ try:
504
+ found = A.environment_in_tree(root)
505
+ except Exception:
506
+ return []
507
+ if not found:
508
+ return []
509
+ named = "; ".join(f"{what} {A.shown_text(path)}" for what, path in found)
510
+ return [("environment-in-tree", f"polyctl runs from, loads or trusts what an agent can write: {named} - a .pth file "
511
+ "or a module there runs before polyctl can name it; run polyctl from an installation "
512
+ "outside the tree, and point these variables outside it")]
513
+
514
+
515
+ # What polyctl cannot hold on Windows, and why: each is said where it bears - `polyctl writers`, a reviewer's wait, the
516
+ # setup of a channel - and all of them in `polyctl doctor`. Each was a guarantee that quietly did not hold there, and
517
+ # read as if it held (WINDOWS-SAY-WHY). None is a fault a person can fix, so `polyctl doctor --check` pages nobody.
518
+ WINDOWS_LIMITS = {
519
+ "orphans": ("Windows has no process groups, so a process an ended turn left is not told apart from a turn: "
520
+ "`polyctl writers` counts it as a writer, and the watchdog starts no turn beside it until it is stopped - "
521
+ "`polyctl writers` lists it"),
522
+ "stall check": ("Windows has no process group to read a reviewer's CPU from, so review.stall_minutes does not "
523
+ "apply: only the review's timeout ends a reviewer that hangs"),
524
+ "private files": ("Windows keeps no file mode, so ~/.polyctl/email.json, telegram.json and pings.json are as private "
525
+ "as ~/.polyctl, which takes its permissions from your user profile unless someone changed them"),
526
+ }
527
+
528
+
529
+ def _private_mode():
530
+ """How a file polyctl keeps private is kept, as a saved line says it: mode 0600, or on Windows its folder's
531
+ permissions (WINDOWS-SAY-WHY)."""
532
+ return "no file mode on Windows: as private as its folder" if os.name == "nt" else "0600"
533
+
534
+
535
+ def _windows_limit_lines():
536
+ """`polyctl doctor`'s lines naming what polyctl cannot hold on Windows, and why; none elsewhere (WINDOWS-SAY-WHY)."""
537
+ if os.name != "nt":
538
+ return []
539
+ return ([f"{'on Windows':<16}{C['yellow']}what polyctl cannot hold here, and why{C['reset']}"]
540
+ + [f"{'':<16}{C['dim']}{name}: {text}{C['reset']}" for name, text in WINDOWS_LIMITS.items()])
541
+
542
+ # The features that start each role's turn: a command no turn starts with is no finding (TURN-ARGV).
543
+ TURN_FEATURES = {"implementer": ("nudge",), "architect": ("architect_wake", "refill")}
544
+
545
+
546
+ def _turn_problems(cfg):
547
+ """[("turn-refused:<role>", text)] for each role whose turn the watchdog would refuse to start, in the words it
548
+ refuses it in, so the doctor and the watchdog raise one alarm (TURN-ARGV). Read as the command is composed before a
549
+ program is looked for: where the program is found is the watchdog's to say."""
550
+ from . import features as F
551
+ out = []
552
+ for role, features in TURN_FEATURES.items():
553
+ block = cfg.get(role) if isinstance(cfg.get(role), dict) else {}
554
+ if not block or not any(F.enabled(cfg, name) for name in features):
555
+ continue
556
+ ident, argv = A.turn_command(cfg, role)
557
+ if argv is None and (role == "architect" or A.turn_adapter(ident) is not None):
558
+ continue
559
+ values = {"session": A.session_to_resume(cfg, role)[0]}
560
+ values.update({"model": block.get("model"), "effort": block.get("effort")} if role == "implementer"
561
+ else {"prompt": block.get("prompt")})
562
+ refused = A.turn_refusal(role, ident, argv or [], root=cfg["root"], values=values)
563
+ if refused:
564
+ out.append((f"turn-refused:{role}", refused))
565
+ return out
566
+
567
+
568
+ def _path_problems():
569
+ """[("path-relative", what it says)] where PATH holds a relative or empty entry on Windows, else [].
570
+
571
+ Such an entry names the directory a program is started in, or one below it, and polyctl starts
572
+ programs from inside trees agents write, so polyctl looks for no program there: one PATH reaches
573
+ only through it is not started, and the entry only waits for a program left under its name
574
+ (WINDOWS-NO-CWD-EXEC).
575
+ """
576
+ unsafe = A.unsafe_path_entries() if os.name == "nt" else []
577
+ if not unsafe:
578
+ return []
579
+ named = ["an empty entry" if not entry else f"`{entry}`" for entry in dict.fromkeys(unsafe)]
580
+ return [("path-relative", f"PATH holds {', '.join(named)}: each names the directory a program is started in, "
581
+ "or one below it, and that can be a tree an agent writes; polyctl starts no program found "
582
+ f"only through {'it' if len(named) == 1 else 'them'} - take "
583
+ f"{'it' if len(named) == 1 else 'them'} out of PATH")]
584
+
585
+
586
+ def _gates_file(root, cfg=None):
587
+ """(.polyctl/gates.json as read, or None; what keeps polyctl from running it, said after the file's name, or None)
588
+ (TRIAGE-HIGHS).
589
+
590
+ Read with the checks a run reads it with (_profile_gates): the profile `polyctl verify` runs when none is named,
591
+ every other profile `--profile` and `polyctl merge-check` may name, and each gate, since the coverage check reads
592
+ those no profile runs. The coverage check raised on a gate or a file of a shape it could not read, and the
593
+ doctor's scheduled check ended there without sending any alarm.
594
+ """
595
+ try:
596
+ with open(os.path.join(root, ".polyctl", "gates.json"), encoding=UTF8) as fh:
597
+ spec = json.load(fh)
598
+ except FileNotFoundError:
599
+ if not os.path.isdir(os.path.join(root, ".polyctl")):
600
+ return None, None # no polyctl project here, so nothing it would verify
601
+ return None, ("is missing, so `polyctl verify` has nothing to run and no candidate is granted - `polyctl init` "
602
+ "writes one, or declare the gates as docs/gates.md shows")
603
+ except (OSError, ValueError) as exc:
604
+ return None, f"cannot be read ({' '.join(str(exc).split())}) - fix it as docs/gates.md shows"
605
+ refused = "`polyctl verify` refuses it - fix it as docs/gates.md shows"
606
+ declared = spec.get("profiles") if isinstance(spec, dict) else None
607
+ default = spec.get("default_profile", "quick") if isinstance(spec, dict) else "quick"
608
+ names, problem = _profile_gates(spec, default, cfg)
609
+ if problem:
610
+ return spec, f"cannot run: {problem}; {refused}"
611
+ if not names:
612
+ return spec, (f"runs no gate in profile {default}, the one `polyctl verify` runs when none is named - declare it "
613
+ "as docs/gates.md shows")
614
+ for profile in sorted(name for name in declared if name != default):
615
+ names, problem = _profile_gates(spec, profile, cfg)
616
+ if not problem and not names:
617
+ problem = f"profile {profile} selects no gate"
618
+ if problem:
619
+ return spec, f"cannot run: {problem}; `polyctl verify --profile {profile}` and `polyctl merge-check` refuse it"
620
+ for name, gate in spec["gates"].items():
621
+ why = _gate_shape_problem(gate)
622
+ if why:
623
+ return spec, f"cannot be read: its gate {name} is in no profile, and {why} - fix it as docs/gates.md shows"
624
+ return spec, None
625
+
626
+
627
+ def doctor_problems(cfg):
628
+ """What `polyctl doctor --check` acts on: conditions a person must fix, as (key, text)."""
629
+ from .watchdog import wake_error, STATE_DIR
630
+ root = cfg["root"]
631
+ redirected = _commit_repository_binding(root)
632
+ key = A.project_key(root)
633
+ # A redirect is a finding, not a reason to suppress the other checks or their alarms (NESTED-GIT).
634
+ out = [("repository-redirect", redirected)] if redirected else []
635
+ lite = project_mode(cfg) == "lite"
636
+ strict_matrix = M.is_strict(cfg)
637
+ if strict_matrix and not lite:
638
+ try:
639
+ matrix_resolution = _resolve_matrix(cfg, require_independent=False)
640
+ except M.MatrixError as exc:
641
+ out.append(("capability-matrix", "; ".join(exc.problems[:3])))
642
+ else:
643
+ if not any(route["eligible"] for route in matrix_resolution["reviewers"]):
644
+ out.append((
645
+ "no-independent-reviewer",
646
+ "capability matrix reviewer chain has no binding outside the implementer binding and model family",
647
+ ))
648
+ out.extend(_active_review_tier(cfg)[1])
649
+ # A review switch the config turns off with no person's record stays on, and says so (FEATURE-RECORDED).
650
+ from . import features as F
651
+ for switch in F.unrecorded(cfg):
652
+ out.append((f"unrecorded-switch:{switch}",
653
+ f"{switch} is off in .polyctl/config.json with no person's record, so it stays on - "
654
+ f"polyctl features off {switch} --by <name>, or remove it"))
655
+ # A row of a gate ledger this machine never recorded polyctl appending is nobody's record (OPTIN-ATTESTED,
656
+ # LEDGER-ATTESTED).
657
+ from .storage import GATE_LEDGERS, _unattested_repair, unattested_in_tree, unattested_ledger
658
+ for name, rel, chain, legacy, effect in GATE_LEDGERS:
659
+ try:
660
+ foreign, attested = (unattested_in_tree(root, rel, chain) if rel == ".polyctl/ledger/opt-ins.jsonl"
661
+ else unattested_ledger(os.path.join(root, *rel.split("/")), chain,
662
+ legacy_prefix=legacy))
663
+ except Exception as exc:
664
+ # Said, never swallowed: a ledger polyctl cannot read decides nothing, and the person learns why.
665
+ foreign, attested = 0, 0
666
+ out.append((f"{name}-unreadable", f"{rel} cannot be read, so {effect}: {exc}"))
667
+ if foreign:
668
+ out.append((f"{name}-unattested", f"{rel} holds {_unattested_repair(foreign, attested)}"))
669
+ where_lite = unrecorded_lite(cfg)
670
+ if where_lite:
671
+ out.append((
672
+ "mode-opt-in",
673
+ f"mode is lite in {where_lite} with no opt-in record, so full mode stays in force — "
674
+ "polyctl mode lite --by <name>, or remove it",
675
+ ))
676
+ out.extend(_harness_config_problem(root))
677
+ out.extend(_environment_problem(root))
678
+
679
+ out.extend(_turn_problems(cfg))
680
+ # A platform run polyctl recorded no longer covers this tree: red, naming a commit this repository
681
+ # cannot place, or past the bound. Absence is not a finding (LANE-EVIDENCE).
682
+ out.extend(A.evidence_problems(cfg))
683
+ hb = A.heartbeat_age(root)
684
+ if hb is not None and hb > WATCHDOG_SILENT_AFTER:
685
+ # The tool named is this platform's: launchctl means nothing on Windows or Linux (WINDOWS-SAY-WHY).
686
+ out.append(("watchdog-dead", f"watchdog silent for {hb // 60}m — {A.scheduler_hint()} / polyctl watchdog status"))
687
+ we = wake_error(os.path.join(STATE_DIR, A.project_file_name("escalate-log", key)))
688
+ if we and we["kind"] in ("binary", "session"):
689
+ try:
690
+ when = time.mktime(time.strptime(we["when"], "%Y-%m-%d %H:%M:%S"))
691
+ except ValueError:
692
+ when = time.time()
693
+ if time.time() - when < 24 * 3600:
694
+ out.append(("wake-failed", f"last architect wake failed ({we['kind']}): {we['text'][:90]}"))
695
+ from . import telegram as _tg, email as _em, ntfy as _nt
696
+ if not (_tg.config() or _em.config() or _nt.config()):
697
+ out.append(("no-channel", "no human channel beyond desktop notifications — polyctl email setup"))
698
+ for sib, age in A.stale_siblings(root).items():
699
+ out.append((f"sibling-dead:{sib}", f"{sib}: watchdog silent for {age // 60}m"))
700
+ own = _implementer_credits(cfg)
701
+ credits = _credits_problem(own["rate"], own["samples"][-1] if own["samples"] else None)
702
+ if credits:
703
+ out.append(credits)
704
+ from . import features as _features
705
+ try:
706
+ from .watchdog import load_state as _load_state
707
+ blind = (_load_state(root) or {}).get("credit_check_problem")
708
+ except Exception:
709
+ blind = None
710
+ # Paged only while the implementer is being driven: a check that cannot read
711
+ # usage matters because exhaustion stops the work, and an owner who stopped the
712
+ # work on purpose does not need an hourly page saying so. Plain doctor always
713
+ # prints it. Only a check of the implementer's own account is its blind check
714
+ # (ACCOUNT-READERS): one another harness's lookup failed is not.
715
+ if blind and own["readable"] and blind.get("adapter") == own["adapter"] and _features.enabled(cfg, "nudge"):
716
+ out.append(("credits-check", f"credit usage cannot be read ({blind.get('reason')}) — "
717
+ f"the exhaustion alarm is blind until it reads again"))
718
+ try:
719
+ msgs_p, _ = A.session_paths(cfg)
720
+ # The watchdog's heartbeat now comes before its transcript check, so a
721
+ # transcript it cannot find no longer looks like a dead watchdog (#71).
722
+ if (A.session_state(cfg, "implementer") or {}).get("session") and _features.enabled(cfg, "nudge") \
723
+ and (not msgs_p or not os.path.exists(msgs_p)):
724
+ out.append(("transcript-missing", "the implementer's transcript cannot be found — the "
725
+ "watchdog has nothing to watch and restarts nobody; check implementer.session"))
726
+ if msgs_p and os.path.exists(msgs_p) and time.time() - os.path.getmtime(msgs_p) < 3600 \
727
+ and not A.read_tail(msgs_p, 2_000_000):
728
+ out.append(("transcript-blind", "fresh transcript, nothing parsed — the agent CLI's format changed"))
729
+ except Exception:
730
+ pass
731
+ # A role's `auto` that settles on no session it may resume: the watchdog nudges or wakes nobody, and an
732
+ # ambiguity is named rather than guessed at (SESSION-IDENTITY).
733
+ try:
734
+ for role, key, feature in (("implementer", "implementer-session", "nudge"),
735
+ ("architect", "architect-session", "architect_wake")):
736
+ state = A.session_state(cfg, role)
737
+ if state is None or state["how"] == "pinned" or not _features.enabled(cfg, feature) \
738
+ or (role == "architect" and not any("{session}" in str(part)
739
+ for part in (cfg.get(role) or {}).get("argv") or [])):
740
+ continue
741
+ if not (state["session"] and state["trusted"]):
742
+ out.append((key, f"the {role}'s session is {state['how']}: {state['why']}"))
743
+ except Exception:
744
+ pass
745
+ # A source tree no gate exercises is a tree nothing verifies (#5). The file is read with the checks `polyctl verify`
746
+ # reads it with, and one that cannot run is a finding of its own: a shape the coverage check could not read
747
+ # raised out of `polyctl doctor --check --notify` before it sent any alarm, and a missing or unreadable file said
748
+ # nothing (TRIAGE-HIGHS).
749
+ gate_spec, gates_problem = _gates_file(root, cfg)
750
+ if isinstance(gate_spec, dict):
751
+ try:
752
+ gaps = A.gate_coverage_gaps(root, gate_spec, S.get(cfg, "gates.coverage_min_files"))
753
+ except Exception as exc:
754
+ gaps = []
755
+ gates_problem = gates_problem or (f"cannot be read for coverage ({' '.join(str(exc).split())}) - fix it "
756
+ "as docs/gates.md shows")
757
+ for tree, chain, files in gaps:
758
+ out.append((f"gate-uncovered:{tree}", f"{tree}/ holds {files} {chain} files that no gate in "
759
+ ".polyctl/gates.json exercises"))
760
+ if gates_problem:
761
+ out.append(("gates-unusable", f".polyctl/gates.json {gates_problem}"))
762
+ # A setting that is written but not used says one thing and does another (#74).
763
+ for name, text in S.problems(cfg):
764
+ out.append((f"setting:{name}", text))
765
+ # A program found only through a relative or empty PATH entry is one polyctl does not start (WINDOWS-NO-CWD-EXEC).
766
+ out.extend(_path_problems())
767
+ if len(A.deferred_open(root)) >= 3:
768
+ out.append(("deferred-pile", f"{len(A.deferred_open(root))} deferred actions waiting — polyctl catchup"))
769
+ # The playbook exists but nothing the agent reads points at it: the rules are
770
+ # written and not in force. init prints the pointer; this is the reminder.
771
+ from . import skillkit
772
+ if skillkit.rules_wired(root) is False:
773
+ named = ", ".join(skillkit.rule_file_names(root) + skillkit.steering_dirs(root))
774
+ out.append(("rules-not-wired", f"no rule file ({named}) points at the polyctl playbook — "
775
+ "paste the pointer or run `polyctl init --rules`"))
776
+ # Two critical roles on one rate-limited pool fail together: the day the
777
+ # architect ran dry, so did the reviewer, and the run locked.
778
+ arch_bin = os.path.basename(((cfg.get("architect") or {}).get("argv") or [""])[0])
779
+ rv = cfg.get("reviewer") or {}
780
+ rv_bin = os.path.basename((rv.get("argv") or [""])[0])
781
+ if not lite and not strict_matrix and arch_bin and arch_bin == rv_bin and not rv.get("fallbacks"):
782
+ out.append(("shared-pool", f"architect and reviewer both run `{arch_bin}` on one quota pool and the reviewer has no "
783
+ f"fallback — let keyflip rotate accounts before a spawn (`polyctl config set "
784
+ f"keyflip.rotation on --machine`), use another model family, or, on a "
785
+ f"machine without keyflip, add reviewer.fallbacks"))
786
+ # A dependency the board cannot resolve makes READY wrong without a word (#33).
787
+ try:
788
+ graph_problems = A.board_graph(root)["problems"]
789
+ except Exception as exc:
790
+ # A board that cannot be read as a graph is the finding; it was nothing (READY-GRAPH-2).
791
+ graph_problems = [f"the board cannot be read as a graph ({' '.join(str(exc).split())})"]
792
+ if graph_problems:
793
+ out.append(("board-graph", "; ".join(graph_problems[:3])
794
+ + (f" and {len(graph_problems) - 3} more" if len(graph_problems) > 3 else "")
795
+ + " — polyctl board"))
796
+ # A boundary its own acceptance cannot fit is found before the work, not in it (#35).
797
+ try:
798
+ conflicts = [f"{item['id']}: {text}" for state in ("running", "queued")
799
+ for item in A.board(root)[state] for text in A.boundary_conflicts(root, item)]
800
+ except Exception:
801
+ conflicts = []
802
+ if conflicts:
803
+ out.append(("boundary-conflict", "; ".join(conflicts[:3])
804
+ + (f" and {len(conflicts) - 3} more" if len(conflicts) > 3 else "") + " — polyctl board"))
805
+ # Green branches make a red main when nobody ran their merge (#39).
806
+ try:
807
+ unverified = A.unverified_merges(root, cfg)
808
+ except Exception as exc:
809
+ # A merge ledger that cannot be read vouches for nothing: one row broken took every recent merge
810
+ # for a checked one, since the error was read as no merge to name (MERGE-EVIDENCE-2).
811
+ unverified = [("merge ledger", f"cannot be read ({' '.join(str(exc).split())}), so no recent merge "
812
+ "is known to have been checked")]
813
+ if unverified:
814
+ out.append(("unverified-merge", "; ".join(f"{sha[:12]}: {why}" for sha, why in unverified[:3])
815
+ + (f" and {len(unverified) - 3} more" if len(unverified) > 3 else "")
816
+ + " — polyctl merge-check <branch> before merging"))
817
+ # A mail store that cannot be read leaves the queue to the view alone, where a message removed unhandled
818
+ # is missing: the queue said nothing of it (MESSAGE-STORE-2).
819
+ if A.mail_store_mode(root) == "append-only":
820
+ try:
821
+ A.unhandled_messages(root)
822
+ except Exception as exc:
823
+ out.append(("mail-store", f"the mail store cannot be read ({' '.join(str(exc).split())}), so the queue "
824
+ "is read from the mailbox view alone and a message removed unhandled is "
825
+ "missing from it — restore .polyctl/ledger/mail-store.jsonl from a backup"))
826
+ # A reviewer whose adapter cannot deny tools is not a reviewer (#88).
827
+ reviewer_adapter = (cfg.get("reviewer") or {}).get("adapter")
828
+ if reviewer_adapter and not lite:
829
+ eligible, why = A.reviewer_eligibility(A.load_adapter(reviewer_adapter, root))
830
+ if not eligible:
831
+ out.append((f"reviewer-ineligible:{reviewer_adapter}", f"the reviewer runs {reviewer_adapter}, which may not "
832
+ f"review: {why} — polyctl role set reviewer <adapter> --model <model>"))
833
+ # A configured adapter whose command this machine lacks would fail at its first spawn (#89).
834
+ try:
835
+ absent = A.absent_adapter_binaries(cfg)
836
+ except Exception:
837
+ absent = []
838
+ for actor, ident, binaries in absent:
839
+ if lite and actor == "reviewer":
840
+ continue
841
+ out.append((f"adapter-binary:{actor}", f"{actor} runs the {ident} adapter, but {' or '.join(binaries)} "
842
+ "is not on this machine (PATH, binaries.extra_dirs, the usual install directories)"))
843
+ # Agent configuration checked by AgentShield's categories, natively (#14).
844
+ try:
845
+ for category, text in A.agent_config_findings(root):
846
+ out.append((f"agent-config:{category}", text))
847
+ for text in A.verify_content(root):
848
+ out.append(("content-drift", text))
849
+ except Exception:
850
+ pass
851
+ # A filter in front of an agent's shell is asked what it does to each measurement,
852
+ # not trusted to leave them alone because its configuration says so (#52).
853
+ try:
854
+ probed = A.probe_filters(root)
855
+ except Exception as exc:
856
+ probed = []
857
+ out.append(("measurement-filter", f"the filter probe failed ({exc}); what a filter does to a "
858
+ "measurement is not verified"))
859
+ filtering = {}
860
+ for result in probed:
861
+ if result["verdict"] == "in-force":
862
+ continue
863
+ hint = ("add them to the filter's exclusions" if result["changed"]
864
+ else "docs/gates.md says which filters polyctl may ask")
865
+ key, text = f"measurement-filter:{result['program']}", f"{A.filter_probe_text(result)} — {hint}"
866
+ filtering[key] = f"{filtering[key]}; {text}" if key in filtering else text
867
+ out.extend(filtering.items())
868
+ # Mail is governance; a store ahead of its private copy is on one disk (#83).
869
+ try:
870
+ sync = A.mail_sync_state(root, cfg)
871
+ except Exception:
872
+ sync = None
873
+ if sync:
874
+ local, remote, problem = sync
875
+ if problem:
876
+ out.append(("mail-sync", problem + (" — polyctl mail sync refuses it" if problem.endswith("verified private")
877
+ else "")))
878
+ elif local and local != remote:
879
+ out.append(("mail-sync", "the message store is ahead of its private copy — polyctl mail sync"))
880
+ # An implementer with nothing pre-authorised to pick up next stalls the moment
881
+ # the architect is away; two READY items is the floor.
882
+ try:
883
+ ready = len(A.ready(root)) if hasattr(A, "ready") else len(A.board(root)["queued"])
884
+ if ready < 2 and not A.board(root)["running"]:
885
+ out.append(("queue-shallow", f"{ready} READY item(s) and nothing running — refill .polyctl/backlog.md before the architect is away"))
886
+ except Exception:
887
+ pass
888
+
889
+ # Static intent is only the safety precondition for running a hook. A green
890
+ # commit-hook result requires Git itself to resolve the active path, execute
891
+ # it with an isolated synthetic index, and return polyctl's nonce-bound refusal.
892
+ # Pre-push remains informational: #59 is about commit authority.
893
+ if not lite:
894
+ hook_inventory = _polyctl_hook_inventory(root)
895
+ proof = _hook_execution_probe(hook_inventory)
896
+ if hook_inventory["error"]:
897
+ out.append(("commit-hook", proof["detail"] + " — polyctl hooks status"))
898
+ else:
899
+ active = _active_hook_targets(hook_inventory)
900
+ commit = active["pre-commit"]
901
+ misplaced = [
902
+ target for target in hook_inventory["targets"]
903
+ if not target["active"]
904
+ and target["role"] == "pre-commit"
905
+ and target["reachability"] == "potentially-effective"
906
+ and _state_base(target["static_state"]) in (
907
+ "current-local", "current-scoped", "legacy", "ambiguous-polyctl"
908
+ )
909
+ ]
910
+ reasons = []
911
+ if not proof["installed"]:
912
+ reasons.append("execution proof failed: " + proof["detail"])
913
+ if misplaced:
914
+ reasons.append(
915
+ "potentially-effective misplaced pre-commit: "
916
+ + ", ".join(target["path"] for target in misplaced[:3])
917
+ )
918
+ if reasons:
919
+ enrollment = _project_enrollment(root)
920
+ install_problem = _hook_install_problem(enrollment)
921
+ if install_problem:
922
+ repair = _hook_install_problem(enrollment, said=proof["detail"])
923
+ elif commit["repository_source"] and commit["track_state"] == "tracked" \
924
+ and commit["crlf_only"]:
925
+ repair = "git restore -- .githooks/pre-commit"
926
+ elif misplaced:
927
+ needs_allow = any(
928
+ target["directory_class"] in ("shared", "external")
929
+ or target["globally_configured"]
930
+ for target in misplaced
931
+ )
932
+ flag = " --allow-shared-hooks" if needs_allow else ""
933
+ repair = f"polyctl hooks uninstall{flag}, then polyctl hooks install{flag}"
934
+ elif _state_base(commit["static_state"]) not in (
935
+ "current-local", "current-scoped"
936
+ ):
937
+ repair = "polyctl hooks install (restore tracked hooks with Git)"
938
+ elif HOOK_POLYCTL_NOT_FOUND in proof["detail"]:
939
+ repair = _polyctl_link_fix() # an alias is invisible to the hook's /bin/sh (SAFE-REMOVE)
940
+ else:
941
+ repair = "ensure the hook can resolve this polyctl executable, then polyctl hooks status"
942
+ out.append(("commit-hook", "; ".join(reasons) + (f" — {repair}" if repair else "")))
943
+ out.extend(_actor_grant_problems(cfg))
944
+ if not lite and _project_enrollment(root)["state"] in ("enrolled", "legacy"):
945
+ # Every commit since the first grant, merges among them, and a check that cannot run named as such: an
946
+ # error read as no commit to name (LEDGER-HISTORY).
947
+ landed = A.landed_without_grant(root)
948
+ if landed:
949
+ out.append(("landed-without-grant", landed))
950
+ return out
951
+
952
+
953
+ # Conditions the watchdog raises itself, by the doctor's finding: the key, level and
954
+ # window the watchdog raises them with. Two alarms for one condition double the
955
+ # ladder - two ids, two levels, two mails - and ringing the doctor's copy only while
956
+ # the watchdog's was quiet still rang both: the watchdog's alarm is quiet after a
957
+ # silence, under a snooze and between readings it could not take. So the doctor
958
+ # raises the watchdog's own alarm at the watchdog's level and known end: one
959
+ # condition is one alarm whoever sees it, with one snooze and one mail (#106).
960
+ DOCTOR_WATCHDOG_ALARMS = {"credits-exhaust": {"key": "credits-exhaust", "level": "red", "window": 6 * 3600},
961
+ "wake-failed": {"key": "architect-wake-failed", "level": None, "window": 6 * 3600},
962
+ "harness-config": {"key": "harness-config", "level": None, "window": 6 * 3600},
963
+ # A turn the watchdog refuses to start, in the words it refuses it in (TURN-ARGV).
964
+ "turn-refused:implementer": {"key": "turn-refused:implementer", "level": None,
965
+ "window": 6 * 3600},
966
+ "turn-refused:architect": {"key": "turn-refused:architect", "level": None,
967
+ "window": 6 * 3600},
968
+ # A commit no grant bound, in the words the watchdog raises it in (LEDGER-HISTORY).
969
+ "landed-without-grant": {"key": "landed-without-grant", "level": None,
970
+ "window": 6 * 3600}}
971
+
972
+ # A heartbeat older than this is a watchdog that stopped.
973
+ WATCHDOG_SILENT_AFTER = 360
974
+ # The scheduled check runs every fifteen minutes, from its launchd job, its systemd timer or its
975
+ # Windows task: a run this long after its last one follows a silence of its own.
976
+ DOCTOR_SILENT_AFTER = 20 * 60
977
+
978
+
979
+ def _watchdog_interval(root):
980
+ """Seconds between the watchdog's cycles: its systemd timer's, its launchd job's StartInterval, or two minutes.
981
+
982
+ Two minutes is what `polyctl watchdog install` schedules without --interval, and what
983
+ the Windows task runs. Each file is read where it is, whatever the platform: only
984
+ the scheduler this machine has holds one.
985
+ """
986
+ import plistlib
987
+ key = A.project_key(root)
988
+ interval = _systemd_interval(os.path.join(_systemd_dir(), _systemd_unit("watchdog", key) + ".timer"))
989
+ if interval is None:
990
+ try:
991
+ with open(_launchd_plist(_launchd_label("watchdog", key)), "rb") as fh:
992
+ interval = int(plistlib.load(fh).get("StartInterval") or 120)
993
+ except (OSError, ValueError, TypeError, AttributeError, plistlib.InvalidFileException):
994
+ interval = 120
995
+ return max(60, interval)
996
+
997
+
998
+ def _watchdog_first_cycle_due(root, now=None):
999
+ """When the watchdog's first cycle after its job came back is due, while it still is; else None.
1000
+
1001
+ Both scheduled jobs run at load, and the doctor could run before the watchdog's
1002
+ first cycle: on re-enabling a project after two weeks it rang a dead watchdog and
1003
+ exhausted credits on the desktop and the phone, two notices each about a watchdog
1004
+ that was starting and credits its first cycle was about to name (NOTICE-NOISE).
1005
+
1006
+ Nothing the job loader keeps says when a job was loaded, and a marker written by
1007
+ `polyctl watchdog install` is not written when the jobs are enabled again with launchctl,
1008
+ after a reboot or after sleep. What every one of those leaves is this check's own
1009
+ silence: the scheduled check records each run, and a run that finds its last one
1010
+ more than twenty minutes ago was stopped too, by whatever stopped the watchdog. The
1011
+ watchdog then has one of its own cycles from that run before it counts as dead,
1012
+ unless its heartbeat had already stopped when this check last ran - a watchdog that
1013
+ died while the check was watching is not given another cycle. A check with no
1014
+ record counts as back: at worst a dead watchdog is paged one run later.
1015
+
1016
+ A watchdog with no heartbeat at all has its cycle too when this check saw its heartbeat
1017
+ at its last run: `polyctl watchdog uninstall` takes the heartbeat with the jobs, and the check
1018
+ that ran first after `polyctl watchdog install` paged what that cycle was about to name, a
1019
+ reading two weeks old among it. Each run records the heartbeat it saw for that. A check
1020
+ that saw none at its last run, or has no run of its own yet, gives none, as before: it
1021
+ knows of no watchdog to come back, and one run by hand where none is installed would
1022
+ hold its pages on every run (LEADS-OPS).
1023
+ """
1024
+ from .storage import replace_file_durably
1025
+ now = time.time() if now is None else now
1026
+ path = A.project_file(root, "doctor-runs")
1027
+ try:
1028
+ with open(path, encoding=UTF8) as fh:
1029
+ record = json.load(fh)
1030
+ except (OSError, ValueError):
1031
+ record = {}
1032
+ record = record if isinstance(record, dict) else {}
1033
+ last = record.get("at") if isinstance(record.get("at"), (int, float)) else None
1034
+ back = record.get("back") if isinstance(record.get("back"), (int, float)) else None
1035
+ age = A.heartbeat_age(root)
1036
+ beat = None if age is None else now - age
1037
+ if last is None or now - last > DOCTOR_SILENT_AFTER:
1038
+ seen = beat if beat is not None else record.get("beat") if isinstance(record.get("beat"), (int, float)) \
1039
+ else None # with none now, the heartbeat this check's last run saw
1040
+ stopped_first = seen is None or (last is not None and last - seen > WATCHDOG_SILENT_AFTER)
1041
+ back = None if stopped_first else now
1042
+ try:
1043
+ replace_file_durably(path, json.dumps({"at": int(now), "back": back,
1044
+ "beat": None if beat is None else int(beat)}).encode("utf-8"))
1045
+ except OSError:
1046
+ return None # a check that cannot keep its record gives no cycle: it pages as it did
1047
+ if back is None or (beat is not None and beat >= back):
1048
+ return None
1049
+ due = back + _watchdog_interval(root)
1050
+ return due if now < due else None
1051
+
1052
+
1053
+ def _no_account(ident):
1054
+ """What stands where a credit figure would, for an implementer whose adapter declares no account polyctl can read."""
1055
+ return f"{ident or 'the implementer'} declares none polyctl can read"
1056
+
1057
+
1058
+ def _implementer_credits(cfg):
1059
+ """The implementer's own credit readings: {adapter, readable, samples, rate} (ACCOUNT-READERS).
1060
+
1061
+ The account is the one the implementer's adapter declares a lookup for, and its
1062
+ readings are the samples that lookup took. A ledger can hold another harness's
1063
+ readings, and every credits finding, page and line was computed from all of them:
1064
+ an implementer whose adapter declares no account polyctl can read is not readable, and has
1065
+ no samples and no rate whatever the ledger holds.
1066
+ """
1067
+ ident = A.implementer_adapter_id(cfg)
1068
+ readable = bool(A.usage_api(ident))
1069
+ return {"adapter": ident, "readable": readable,
1070
+ "samples": A.credit_samples(cfg["root"], ident) if readable else [],
1071
+ "rate": A.burn_rate(cfg["root"], ident) if readable else None}
1072
+
1073
+
1074
+ def _credits_problem(br, last, now=None):
1075
+ """The one credits problem the readings show: exhausted outranks a projection.
1076
+
1077
+ At 12503/10000 the doctor still said "credits run out 15 Sep, before the
1078
+ reset", because the projection was checked first and a date that had already
1079
+ passed read like one still ahead. A spent reading whose own reset has passed says
1080
+ nothing of the plan after it: rehearsing 2026-10-01, the scheduled check paged
1081
+ credits exhausted from a reading taken before the plan reset, on the desktop, the
1082
+ phone and in four mails in a day while the usage could not be read again (OCT1-FIXES).
1083
+ """
1084
+ from .watchdog import credit_reset
1085
+ now = time.time() if now is None else now
1086
+ # Which account, since a switch leaves another account's figures behind (#36).
1087
+ whose = (f"account {last['account']}" if last and last.get("account")
1088
+ else "account not named by the reading")
1089
+ reset = credit_reset(last.get("reset_at"), now) if last else None
1090
+ if last and last.get("limit") and float(last.get("used") or 0) >= float(last["limit"]) \
1091
+ and not (reset is not None and reset <= now):
1092
+ return ("credits-exhaust", f"credits exhausted at the last reading: "
1093
+ f"{float(last['used']):.0f}/{float(last['limit']):.0f} ({whose})")
1094
+ if br and br.get("before_reset"):
1095
+ return ("credits-exhaust", f"credits run out {time.strftime('%d %b', time.localtime(br['exhausts_at']))}, "
1096
+ f"before the reset ({br['per_day']:.0f}/day, account {br.get('account')}) "
1097
+ "— new account or fewer features")
1098
+ return None
1099
+
1100
+
1101
+ def _doctor_credit_lines(cfg):
1102
+ """`polyctl doctor`'s credits lines, read from the implementer's own readings (ACCOUNT-READERS).
1103
+
1104
+ Where the figure stood, an implementer whose adapter declares no account polyctl can read is
1105
+ told so: no credit alarm can ring for it, and a check that cannot exist must not look
1106
+ like one that passes. A blind check is shown only for the implementer's own account.
1107
+ """
1108
+ from .watchdog import credit_reset
1109
+ own = _implementer_credits(cfg)
1110
+ if not own["readable"]:
1111
+ return [f"credits {C['dim']}{_no_account(own['adapter'])}{C['reset']}"]
1112
+ lines, br = [], own["rate"]
1113
+ last = (own["samples"] or [None])[-1]
1114
+ # A reading already over the limit is exhausted; a date ahead would say otherwise.
1115
+ over = bool(last and last.get("limit") and float(last.get("used") or 0) >= float(last["limit"]))
1116
+ # Unless its own reset has passed: it says nothing of the plan after it, as the check reads it (OCT1-FIXES).
1117
+ # The panel still said exhausted, in red, of a plan the check no longer paged about (LEADS-OPS).
1118
+ reset = credit_reset(last.get("reset_at")) if over else None
1119
+ reset_passed = reset is not None and reset <= time.time()
1120
+ if br and not over:
1121
+ when = time.strftime('%d %b', time.localtime(br['exhausts_at'])) if br['exhausts_at'] else '—'
1122
+ tone = C['red'] if br['before_reset'] else C['green']
1123
+ lines.append(f"credits {br['used']:.0f}/{br['limit']:.0f} · {br['per_day']:.0f}/day · runs out "
1124
+ f"{tone}{when}{C['reset']}"
1125
+ + (f" {C['red']}before the reset — new account / polyctl features off{C['reset']}"
1126
+ if br['before_reset'] else ""))
1127
+ if reset_passed:
1128
+ lines.append(f"credits {C['dim']}{float(last.get('used') or 0):.0f}/{float(last['limit']):.0f} at the "
1129
+ f"last reading, taken before its reset on {time.strftime('%d %b %H:%M', time.localtime(reset))}"
1130
+ f" — unknown since; `polyctl credits` reads them now{C['reset']}")
1131
+ elif (over or not br) and last and last.get("limit"):
1132
+ used, limit = float(last.get("used") or 0), float(last["limit"])
1133
+ lines.append(f"credits {C['red'] if used >= limit else C['green']}{used:.0f}/{limit:.0f}{C['reset']} "
1134
+ "at the last reading" + (f" {C['red']}exhausted{C['reset']}" if used >= limit else ""))
1135
+ try:
1136
+ from .watchdog import load_state as _load_state
1137
+ blind = (_load_state(cfg["root"]) or {}).get("credit_check_problem")
1138
+ except Exception:
1139
+ blind = None
1140
+ if blind and blind.get("adapter") == own["adapter"]:
1141
+ lines.append(f"credits check {C['red']}cannot read usage{C['reset']} — {blind.get('reason')} "
1142
+ f"{C['dim']}the exhaustion alarm is blind until it reads again{C['reset']}")
1143
+ return lines
1144
+
1145
+
1146
+ # Findings that mean work has stopped and only a person can restart it. Everything
1147
+ # else a doctor finds is an advisory: recorded for the architect, never paged (#40).
1148
+ # Harness configuration nobody has seen holds every turn polyctl starts, and only a person
1149
+ # may read it and record it as seen (HARNESS-CONFIG). A turn the watchdog refuses to
1150
+ # start waits for its configuration to change (TURN-ARGV). A commit no grant bound is
1151
+ # the backstop for a harness that can commit around the hook, and was an advisory row
1152
+ # nobody sends (LEDGER-HISTORY).
1153
+ DOCTOR_RED = {"watchdog-dead", "wake-failed", "transcript-blind", "transcript-missing", "implementer-session",
1154
+ "harness-config", "turn-refused:implementer", "turn-refused:architect", "repository-redirect",
1155
+ "landed-without-grant"}
1156
+
1157
+
1158
+ def _doctor_severity(key, text):
1159
+ if key in DOCTOR_RED or (key == "credits-exhaust" and text.startswith("credits exhausted")):
1160
+ return "red"
1161
+ return "yellow"
1162
+
1163
+
1164
+ def _doctor_check(cfg, page=False):
1165
+ """Machine-facing doctor: one line per problem, exit 1 if any.
1166
+
1167
+ Run by a person or an agent it pages nobody: it reports to its caller and
1168
+ returns non-zero (#40). Only the scheduled job passes page=True, and then a red
1169
+ finding goes to the human ladder while an advisory is recorded for the
1170
+ architect. On 2026-09-08 two wake turns ran --check by hand and mailed a
1171
+ standing advisory; on 2026-09-15 the scheduled job mailed exhausted credits
1172
+ every six hours although nothing could change before their reset.
1173
+
1174
+ A condition the watchdog raises itself is raised under the watchdog's own alarm
1175
+ (#106). While the watchdog's first cycle after its job came back is due, neither
1176
+ that cycle's conditions nor its silence are paged: that cycle names them (NOTICE-NOISE).
1177
+ """
1178
+ from .watchdog import credit_reset, credits_told, notify
1179
+ root = cfg["root"]
1180
+ project = A.project_key(root)
1181
+ if project_mode(cfg) == "lite":
1182
+ print(ENFORCEMENT_OFF_LITE_LINE)
1183
+ due = _watchdog_first_cycle_due(root) if page else None
1184
+ problems = doctor_problems(cfg)
1185
+ if not problems:
1186
+ print(f"ok {time.strftime('%H:%M')} — no problems")
1187
+ return 0
1188
+ samples = A.credit_samples(root, A.implementer_adapter_id(cfg)) if page else []
1189
+ last = samples[-1] if samples else {}
1190
+ for key, text in problems:
1191
+ print(f"PROBLEM {key}: {text}")
1192
+ if not page:
1193
+ continue
1194
+ if _doctor_severity(key, text) != "red":
1195
+ notify(f"{project}: {key}", text, root, key=f"doctor:{key}", window=3600,
1196
+ audience="architect")
1197
+ continue
1198
+ shared = DOCTOR_WATCHDOG_ALARMS.get(key)
1199
+ if due and (shared or key == "watchdog-dead"):
1200
+ print(f" not paged: the watchdog's job came back with this check; its first cycle is due by "
1201
+ f"{time.strftime('%H:%M', time.localtime(due))}")
1202
+ elif key == "credits-exhaust":
1203
+ notify(f"{project}: {key}", text, root, key=shared["key"], window=shared["window"],
1204
+ audience="human", level=shared["level"], quiet_until=credit_reset(last.get("reset_at")),
1205
+ what=credits_told("exhausted", last.get("account")),
1206
+ evidence=A.notice_evidence("credit_reading", [
1207
+ {"value": f"{last['used']:.0f}/{last['limit']:.0f}", "at": last.get("at"),
1208
+ "source": f"GetUsageLimits, account {last.get('account')}"}] if last else []))
1209
+ elif shared:
1210
+ # A failed wake says what the watchdog's own raise of it says, so the same failure rings once
1211
+ # whoever sees it (NOISE-REPEATS); so does harness configuration nobody has seen (HARNESS-CONFIG),
1212
+ # and a refused turn, in the words the watchdog refuses it in (TURN-ARGV), and a commit no grant
1213
+ # bound, in the words the watchdog raises it in (LEDGER-HISTORY).
1214
+ from .watchdog import STATE_DIR, wake_error, wake_failure_told
1215
+ failed = wake_error(os.path.join(STATE_DIR, A.project_file_name("escalate-log", project))) \
1216
+ if key == "wake-failed" else None
1217
+ what = wake_failure_told(failed) if failed else _harness_config_told(root) \
1218
+ if key == "harness-config" else text \
1219
+ if key.startswith("turn-refused:") or key == "landed-without-grant" else None
1220
+ notify(f"{project}: {key}", text, root, key=shared["key"], window=shared["window"],
1221
+ audience="human", level=shared["level"], what=what)
1222
+ else:
1223
+ notify(f"{project}: {key}", text, root, key=f"doctor:{key}", window=3600,
1224
+ audience="human")
1225
+ return 1
1226
+
1227
+
1228
+ # A credit pool is shared: what polyctl reads is polyctl's share, what the account says is everyone's (#95).
1229
+ SHARED_POOL_NOTE = ("the account's figure counts every session on it - another project's CLI, an IDE, "
1230
+ "another orchestrator - and polyctl's transcript holds only polyctl's own turns")
1231
+
1232
+
1233
+ def _account_beside_share(cfg, acct=None):
1234
+ """Lines setting the implementer's own account beside polyctl's own transcript share, labelled as such.
1235
+
1236
+ The account is the one the implementer's adapter declares a lookup for. The first shipped
1237
+ adapter's was read whatever the implementer ran, so an implementer on a harness that bills
1238
+ another pool in another unit was shown a credit account it never spends; it has none polyctl
1239
+ can read, and the line says so.
1240
+ """
1241
+ ident = A.implementer_adapter_id(cfg)
1242
+ if not A.usage_api(ident):
1243
+ return [f"{C['dim']}the account: {_no_account(ident)}; what follows is polyctl's transcript only{C['reset']}"]
1244
+ if acct is None:
1245
+ try:
1246
+ acct = A.account_usage(adapter_id=ident)
1247
+ except Exception:
1248
+ acct = None
1249
+ if not acct or acct.get("error") or acct.get("expired") or not acct.get("limit"):
1250
+ return [f"{C['dim']}the account's figure could not be read; what follows is polyctl's transcript "
1251
+ f"only{C['reset']}"]
1252
+ lines = [f"the account: {float(acct['used']):,.0f} of {float(acct['limit']):,.0f} used"]
1253
+ start = acct.get("cycle_start")
1254
+ known = isinstance(start, (int, float)) and not isinstance(start, bool) and 0 < start <= time.time()
1255
+ if known:
1256
+ try:
1257
+ mine = A.turn_costs(cfg, since=start)
1258
+ except Exception:
1259
+ mine = None
1260
+ if mine and mine.get("turns") and float(acct["used"] or 0) > 0:
1261
+ lines.append(f"polyctl's own share, from its transcript: {mine['total']:,.0f} {mine['unit']} "
1262
+ f"({100 * mine['total'] / float(acct['used']):.0f}% of the account's used); "
1263
+ f"cycle since {time.strftime('%Y-%m-%d %H:%M', time.localtime(start))}")
1264
+ else:
1265
+ lines.append("the account's cycle start is unknown; no transcript share percentage can be compared")
1266
+ lines.append(f"{C['dim']}{SHARED_POOL_NOTE}{C['reset']}")
1267
+ return lines
1268
+
1269
+
1270
+ def _cost_by_feature(cfg, since, window):
1271
+ """`polyctl cost --features`: the implementer's spend each switch caused, over the window it was measured (#10)."""
1272
+ measured = A.feature_costs(cfg, since=since)
1273
+ if not measured["turns"]:
1274
+ print("no transcript turns in this window")
1275
+ else:
1276
+ span = " to ".join(time.strftime("%d %b %H:%M", time.localtime(at))
1277
+ for at in (measured["from"], measured["to"]))
1278
+ print(f"{C['b']}implementer spend by feature{C['reset']} {C['dim']}({measured['unit']}; {measured['turns']} "
1279
+ f"turns, {span}{' — ' + window if window else ''}){C['reset']}")
1280
+ for name, spent in measured["features"].items():
1281
+ share = 100 * spent["usage"] / measured["total"] if measured["total"] else 0
1282
+ print(f" {name:<18}{spent['turns']:>5} turns {spent['usage']:>9.1f} {share:>5.1f}%")
1283
+ # What runs on another command is counted whether or not this transcript has turns: hunts were left out
1284
+ # when it had none, and the hunter runs on its own command, not the architect's (BUG-HUNTER-2).
1285
+ for name, count in measured["counted"].items():
1286
+ whose = "its own command" if name == "hunter" else "the architect's pool"
1287
+ print(f" {name:<18}{count:>5} started {C['dim']}{whose}, not this transcript{C['reset']}")
1288
+ if measured["turns"]:
1289
+ print(f" {'inventory_review':<18} {C['dim']}counted with review: a transcript cannot tell them apart"
1290
+ f"{C['reset']}")
1291
+ return 0
1292
+
1293
+
1294
+ def _usd(amount):
1295
+ """A dollar figure as the estimate prints it: `unknown` for none, and a spend under a cent never as free."""
1296
+ if amount is None:
1297
+ return "unknown"
1298
+ return "<$0.01" if 0 < amount < 0.005 else f"${amount:,.2f}"
1299
+
1300
+
1301
+ def _cost_in_usd(cfg, since, window):
1302
+ """`polyctl cost --usd`: the implementer's tokens priced from the table polyctl ships, labelled an estimate (USD-COST).
1303
+
1304
+ Each model at each rate is a row, its tokens by kind beneath it. A row the table cannot
1305
+ price says `unknown` and why, never $0.00, and the total is then unknown too, with what the
1306
+ priced rows add up to as a floor. The label names the table's version and each vendor's
1307
+ as-of day and source, so a reader sees how old the prices are and where to check them. An
1308
+ implementer billed in another unit - credits - gets no dollar figure: a credit's price in
1309
+ dollars is its plan's, which no table here holds.
1310
+ """
1311
+ c = A.turn_costs(cfg, since=since, by_model=True)
1312
+ if not c["turns"]:
1313
+ print("no transcript")
1314
+ return 0
1315
+ if c["tokens"] is None:
1316
+ print(f"no estimate in US dollars: {A.implementer_adapter_id(cfg) or 'the implementer'} declares no tokens by "
1317
+ f"model and kind that polyctl can price (`telemetry.cost.tokens`); `polyctl cost` counts its spend in its own "
1318
+ f"unit, {c['unit']}")
1319
+ return 0
1320
+ table, problems = A.price_table()
1321
+ if problems:
1322
+ print(f"{C['red']}no estimate in US dollars{C['reset']}: " + "; ".join(problems))
1323
+ return 1
1324
+ estimate = A.usd_estimate(c["tokens"], table)
1325
+ print(f"{C['b']}implementer spend in US dollars: an estimate{C['reset']} {C['dim']}(list prices, not a bill; "
1326
+ f"{window or 'whole transcript'}){C['reset']}")
1327
+ if not estimate["rows"]:
1328
+ print(" no tokens in this window")
1329
+ return 0
1330
+ order = list(table["kinds"])
1331
+ for row in estimate["rows"]:
1332
+ label = (row["model"] or "a model the transcript does not name") + (f" at {row['rate']}" if row["rate"] else "")
1333
+ why = f" {C['dim']}{row['why']}{C['reset']}" if row["why"] else ""
1334
+ print(f" {label:<40}{_usd(row['usd']):>14}{why}")
1335
+ kinds = sorted(row["tokens"], key=lambda kind: order.index(kind) if kind in order else len(order))
1336
+ print(f" {C['dim']}" + " · ".join(f"{kind} {row['tokens'][kind]:,.0f}" for kind in kinds) + C["reset"])
1337
+ floor = f" at least {_usd(estimate['priced'])}, what the rows priced add up to" \
1338
+ if estimate["total"] is None and estimate["priced"] else ""
1339
+ print(f" {C['b']}{'total (estimate)':<40}{_usd(estimate['total']):>14}{C['reset']}{floor}")
1340
+ used = "".join(f"; {vendor} as of {spec['as_of']}, {spec['source']}"
1341
+ for vendor, spec in estimate["vendors"].items())
1342
+ print(f" {C['dim']}prices: table version {estimate['version']}{used}{C['reset']}")
1343
+ print(f" {C['dim']}unknown is never counted as zero: a model, a kind of token or a rate the table does not "
1344
+ f"price{C['reset']}")
1345
+ return 0
1346
+
1347
+
1348
+ def cmd_cost(cfg, args):
1349
+ """What the coordination spends: the implementer's turns by what they did.
1350
+
1351
+ The honest answer to "is polyctl bureaucracy" is the share of spend in turns that
1352
+ wrote nothing — ceremony (review/gate commands), coordination (inbox, reports,
1353
+ writer checks) — against turns that wrote product. `wasted` counts turns that
1354
+ ended in a blocked report without a product change: the queue-empty loop.
1355
+ `--usd` prices the same turns' tokens in US dollars, as an estimate (`_cost_in_usd`).
1356
+ """
1357
+ root = cfg["root"]
1358
+ # One time syntax for every command (CLI-ROBUST): `yesterday` or `30m` reached a pattern of
1359
+ # hours and days here and ended in a traceback.
1360
+ when = A.parse_time(args.since) if args.since else None
1361
+ since = when.moment() if when else None
1362
+ window = when.label() if when else None
1363
+ if getattr(args, "features", False):
1364
+ return _cost_by_feature(cfg, since, window)
1365
+ if getattr(args, "usd", False):
1366
+ return _cost_in_usd(cfg, since, window)
1367
+ c = A.turn_costs(cfg, since=since)
1368
+ if not c["turns"]:
1369
+ print("no transcript"); return 0
1370
+ # Nothing spent has no shares: the total was printed as 1, and each class as 0% of it (LEADS-OPS).
1371
+ tot = c["total"]
1372
+ print(f"{C['b']}implementer spend by turn class{C['reset']} {C['dim']}({c['unit']}; "
1373
+ f"{window or 'whole transcript'}){C['reset']}")
1374
+ # What the subagents a turn started spent is inside that turn's spend; a column says how much, when any did.
1375
+ delegated = any(b.get("delegated") for b in c["by_class"].values())
1376
+ column = f"{'delegated':>11}" if delegated else ""
1377
+ print(f" {'class':<14}{'turns':>6}{'spend':>10}{'share':>7}{column} {'wasted turns':>12}")
1378
+ for cls in ("product", "analysis", "ceremony", "coordination"):
1379
+ b = c["by_class"].get(cls)
1380
+ if not b:
1381
+ continue
1382
+ w = f"{b['wasted']} ({b['wasted_usage']:.0f})" if b["wasted"] else ""
1383
+ d = f"{b.get('delegated', 0.0):>11.0f}" if delegated else ""
1384
+ share = f"{100 * b['usage'] / tot:>6.0f}%" if tot else f"{'—':>7}"
1385
+ print(f" {cls:<14}{b['turns']:>6}{b['usage']:>10.0f}{share}{d} {w:>12}")
1386
+ d = f"{'':>7}{sum(b.get('delegated', 0.0) for b in c['by_class'].values()):>11.0f}" if delegated else ""
1387
+ # A turn the model never answered is the implementer's work in no class, and in no total of turns.
1388
+ work = [b for cls, b in c["by_class"].items() if cls != A.UNANSWERED]
1389
+ print(f" {'total':<14}{sum(b['turns'] for b in work):>6}{tot:>10.0f}{d}")
1390
+ unanswered = c["by_class"].get(A.UNANSWERED)
1391
+ if unanswered:
1392
+ print(f" {C['dim']}{A.UNANSWERED}: {unanswered['turns']} more turn(s) the model never answered, the harness "
1393
+ f"replying in its place with nothing spent{C['reset']}")
1394
+ if delegated:
1395
+ print(f" {C['dim']}delegated: what the subagents a turn started spent, inside that turn's spend{C['reset']}")
1396
+ overhead = sum(c["by_class"].get(k, {}).get("usage", 0) for k in ("ceremony", "coordination"))
1397
+ for line in _account_beside_share(cfg):
1398
+ print(f" {line}")
1399
+ told = f"{C['b']}{100 * overhead / tot:.0f}%{C['reset']} of spend" if tot else "no share: nothing was spent"
1400
+ print(f"\n coordination + ceremony: {told}"
1401
+ f" · polyctl commands: {', '.join(f'{k} {v}' for k, v in c['polyctl_commands'].most_common(6))}")
1402
+ # the reviewer's side: files, wasted, sizes
1403
+ d = os.path.join(root, cfg["reviews"])
1404
+ if os.path.isdir(d):
1405
+ # Each file is looked at once, and one removed since it was listed - a prune running beside this - is
1406
+ # not counted: listed, then looked at again for its time and its size, it ended the command (LEADS-OPS).
1407
+ sizes = {}
1408
+ for name in os.listdir(d):
1409
+ if not name.endswith(".md"):
1410
+ continue
1411
+ try:
1412
+ found = os.stat(os.path.join(d, name))
1413
+ except OSError:
1414
+ continue
1415
+ if not since or found.st_mtime >= since:
1416
+ sizes[name] = found.st_size
1417
+ verdicts = dict(A.reviews(root, cfg["reviews"], limit=10_000))
1418
+ una = sum(1 for name in sizes if verdicts.get(name) in ("UNAVAILABLE", "INVALID"))
1419
+ print(f" reviews: {len(sizes)} files ({una} unavailable/invalid, cost nothing), "
1420
+ f"{sum(sizes.values()) // 1000}k chars of verdict text; each review sends the slice diff to the reviewer model")
1421
+ return 0
1422
+
1423
+
1424
+ def cmd_config(cfg, args):
1425
+ """Read and change what polyctl lets a person set (#74).
1426
+
1427
+ `list` shows every setting with its value, its default and where the value came
1428
+ from; `get` prints one; `set` and `unset` change the project's config, or with
1429
+ --machine the machine's settings. Both are written whole or not at all.
1430
+ """
1431
+ from .storage import ReplacedNotDurable
1432
+ root = cfg["root"]
1433
+ key = getattr(args, "key", None)
1434
+ if args.action == "list":
1435
+ print(f" {'setting':<32}{'value':<14}{'default':<12}{'from':<9}what it decides")
1436
+ for name, spec in S.SETTINGS.items():
1437
+ value, source, problem = S.resolve(cfg, name)
1438
+ mark = f" {C['red']}!{C['reset']}" if problem else ""
1439
+ colour = C["dim"] if source == "default" else C["b"]
1440
+ print(f" {name:<32}{colour}{str(value):<14}{C['reset']}{str(spec.default):<12}{source:<9}"
1441
+ f"{C['dim']}{spec.text}{C['reset']}{mark}")
1442
+ if problem:
1443
+ print(f" {'':<32}{C['red']}{problem}{C['reset']}")
1444
+ print(f"\n {C['dim']}project: .polyctl/config.json · machine: {S.machine_path()} · "
1445
+ f"polyctl config set <setting> <value> [--machine]{C['reset']}")
1446
+ return 0
1447
+ if key not in S.SETTINGS:
1448
+ print(f"unknown setting {key!r}; `polyctl config list` shows the names")
1449
+ return 2
1450
+ if args.action == "get":
1451
+ print(project_mode(cfg) if key == "mode" else S.get(cfg, key))
1452
+ return 0
1453
+ machine = bool(getattr(args, "machine", False))
1454
+ if S.SETTINGS[key].scope == "machine" and not machine:
1455
+ print(f"{key} governs the whole machine; set it with --machine")
1456
+ return 2
1457
+ if key == "mode":
1458
+ print("mode is switched with `polyctl mode lite --by <name>` or `polyctl mode full`, not `polyctl config`")
1459
+ return 2
1460
+ by = (getattr(args, "by", None) or "").strip()
1461
+ if key in S.RECORDED:
1462
+ # A setting that weakens a guarantee is a person's act on one project, on the record (REVIEW-TIERS).
1463
+ if machine:
1464
+ print(f"{key} is a person's choice for one project, recorded there; set it without --machine")
1465
+ return 2
1466
+ if not by:
1467
+ print(f"--by is required: {key} changes what a review must be independent of, and a person "
1468
+ "changes it on the record")
1469
+ return 2
1470
+ if by.lower() in _agent_names(cfg):
1471
+ print(f"--by names an agent or a role ({by}); changing {key} is a person's act")
1472
+ return 2
1473
+ elif by:
1474
+ print(f"--by records who changed a setting that weakens a guarantee ({', '.join(S.RECORDED)}); "
1475
+ f"{key} is not one")
1476
+ return 2
1477
+ if args.action == "set":
1478
+ try:
1479
+ value = S.parse(key, args.value)
1480
+ except (TypeError, ValueError) as exc:
1481
+ print(f"{C['red']}not changed{C['reset']}: {exc}")
1482
+ return 2
1483
+ else:
1484
+ value = S._MISSING
1485
+ if machine:
1486
+ try:
1487
+ S.write_machine(S.assign(S.machine_settings(), key, value))
1488
+ except ReplacedNotDurable as exc:
1489
+ print(f"{C['red']}{exc}{C['reset']}")
1490
+ return 1
1491
+ except OSError as exc:
1492
+ print(f"{C['red']}not changed{C['reset']}: {exc}")
1493
+ return 1
1494
+ else:
1495
+ document = A.project_config_document(root)
1496
+ if document["problem"]:
1497
+ # Rebuilding a config polyctl cannot read would drop what it held (#56).
1498
+ print(f"{C['red']}not changed{C['reset']}: {document['problem']}")
1499
+ return 1
1500
+ try:
1501
+ A.write_project_config(root, json.dumps(S.assign(document["config"], key, value), indent=2,
1502
+ ensure_ascii=False))
1503
+ except ReplacedNotDurable as exc:
1504
+ print(f"{C['red']}{exc}{C['reset']}; no opt-in was recorded; retry this command to record one if required")
1505
+ return 1
1506
+ except (OSError, ValueError) as exc:
1507
+ print(f"{C['red']}not changed{C['reset']}: {exc}")
1508
+ return 1
1509
+ if key in S.RECORDED:
1510
+ # Written after the config: a value with no record is not in force, never the other way round.
1511
+ try:
1512
+ A.record_opt_in(root, key, None if value is S._MISSING else value, by)
1513
+ except Exception as exc:
1514
+ print(f"{C['red']}not recorded{C['reset']}: {exc}; {key} is not in force until it is")
1515
+ return 1
1516
+ cfg = dict(A.load_config(root), root=root)
1517
+ value, source, _ = S.resolve(cfg, key)
1518
+ print(f"{key} = {value!r} ({source})" + (f", recorded as set by {by}" if key in S.RECORDED else ""))
1519
+ if key == "review.transport" and value != S.default(key):
1520
+ # How a review reaches its routes is part of the reviewer a person accepts, as the routes are (REVIEW-PATH-HIGHS).
1521
+ print(f"{C['dim']}a review starts its routes this way once a person has read the change: "
1522
+ f"polyctl harness seen --by <name>{C['reset']}")
1523
+ return 0
1524
+
1525
+
1526
+ def _feature_cell(measured, key):
1527
+ """One feature's measured cost as a short cell: a share of the implementer's spend, or a count (#10)."""
1528
+ if not measured:
1529
+ return "—"
1530
+ if key in measured["counted"]:
1531
+ return f"{measured['counted'][key]} started"
1532
+ if key not in measured["features"] or not measured["total"]:
1533
+ return "with review" if key == "inventory_review" else "—"
1534
+ return f"{100 * measured['features'][key]['usage'] / measured['total']:.1f}%"
1535
+
1536
+
1537
+ def cmd_features(cfg, args):
1538
+ """The switches and what each costs. All off: deterministic polyctl, zero model spend."""
1539
+ from .storage import ReplacedNotDurable
1540
+ from . import features as F
1541
+ root = cfg["root"]
1542
+ if args.action in ("on", "off"):
1543
+ if args.key not in F.FEATURES:
1544
+ print(f"unknown feature {args.key}; one of {', '.join(F.ORDER)}"); return 2
1545
+ # A switch that weakens a guarantee is turned off by a person, on the record (FEATURE-RECORDED).
1546
+ by = (getattr(args, "by", None) or "").strip()
1547
+ if args.key in F.RECORDED and args.action == "off":
1548
+ if not by or not by.isprintable() or len(by) > 80:
1549
+ print(f"--by is required: turning {args.key} off lets a commit land without that review, and a person "
1550
+ "does it on the record, in one line of at most 80 characters")
1551
+ return 2
1552
+ if by.lower() in _agent_names(cfg):
1553
+ print(f"--by names an agent or a role ({by}); turning {args.key} off is a person's act")
1554
+ return 2
1555
+ elif by and args.key not in F.RECORDED:
1556
+ print(f"--by records who turned off a switch that weakens a guarantee ({', '.join(F.RECORDED)}); "
1557
+ f"{args.key} is not one")
1558
+ return 2
1559
+ try:
1560
+ F.set_switch(root, args.key, args.action == "on")
1561
+ except ReplacedNotDurable as exc:
1562
+ print(f"{C['red']}{exc}{C['reset']}; no opt-in was recorded; retry this command to record one if required")
1563
+ return 1
1564
+ except (OSError, ValueError) as exc:
1565
+ print(f"{C['red']}not changed{C['reset']}: {exc}")
1566
+ return 1
1567
+ if args.key in F.RECORDED:
1568
+ # Written after the config, and on as well as off: a value with no record is not in force, and an
1569
+ # earlier off is never one a later hand edit can stand on.
1570
+ try:
1571
+ A.record_opt_in(root, f"features.{args.key}", args.action == "on", by)
1572
+ except Exception as exc:
1573
+ print(f"{C['red']}not recorded{C['reset']}: {exc}; {args.key} stays on until it is")
1574
+ return 1
1575
+ cfg = dict(A.load_config(root), root=root)
1576
+ on = F.switches(cfg)
1577
+ for key in F.unrecorded(cfg):
1578
+ print(f"{C['yellow']}{key} is off in .polyctl/config.json with no person's record, so it stays on{C['reset']}: "
1579
+ f"polyctl features off {key} --by <name>")
1580
+ try:
1581
+ measured = A.feature_costs(cfg, since=time.time() - 7 * 86400)
1582
+ except Exception:
1583
+ measured = None
1584
+ print(f" {'feature':<18}{'':<4}{'last 7 days':>13} what it spends")
1585
+ for k in F.ORDER:
1586
+ label, _, what = F.FEATURES[k]
1587
+ state = f"{C['green']}on {C['reset']}" if on[k] else f"{C['dim']}off{C['reset']}"
1588
+ print(f" {k:<18}{state:<4}{_feature_cell(measured, k):>13} {C['dim']}{what}{C['reset']}")
1589
+ print(f"\n {C['dim']}measured from the implementer's transcript and the watchdog's logs, never estimated; "
1590
+ f"all off = board, mail, gates, commit-ok, alarms, pings and hooks only; `polyctl cost --features` "
1591
+ f"for the window{C['reset']}")
1592
+ print(f" {C['dim']}polyctl features on|off <feature>{C['reset']}")
1593
+ return 0
1594
+
1595
+
1596
+ def _agent_names(cfg):
1597
+ """Names that belong to agents or roles, never to the person a waiver or a person's review must name.
1598
+
1599
+ Every actor in the role table counts, not only those holding a role now: an actor
1600
+ waiting for the next slice is an agent all the same (REVIEW-TIERS). Every shipped
1601
+ adapter's id, name, actor_name and family count too, so an agent's name is refused
1602
+ even when another adapter holds the role in this project (COORDINATION-COMMIT).
1603
+ """
1604
+ names = {"architect", "implementer", "reviewer", "watchdog", "polyctl", "agent", "human"}
1605
+ for ident, spec in A.package_adapters().items():
1606
+ names.add(str(ident))
1607
+ if isinstance(spec, dict):
1608
+ names.update(str(spec.get(key) or "") for key in ("id", "name", "actor_name", "family"))
1609
+ for role in ("implementer", "architect"):
1610
+ block = cfg.get(role) or {}
1611
+ names.update(str(block.get(key) or "") for key in ("name", "adapter", "session"))
1612
+ primary = cfg.get("reviewer") or {}
1613
+ names.update(str(route.get("id") or "") for route in [primary] + list(primary.get("fallbacks") or [])
1614
+ if isinstance(route, dict))
1615
+ actors = cfg.get("actors") if isinstance(cfg.get("actors"), dict) else {}
1616
+ for actor, block in actors.items():
1617
+ names.add(str(actor))
1618
+ if isinstance(block, dict):
1619
+ names.update(str(block.get(key) or "") for key in ("id", "name", "adapter", "session"))
1620
+ return {name.strip().lower() for name in names if name.strip()}
1621
+
1622
+
1623
+ def cmd_waive(cfg, args):
1624
+ """A person bypasses a gate for a slice, on the record. Reconciled later by `polyctl catchup`."""
1625
+ root = cfg["root"]
1626
+ if args.gate == "inventory":
1627
+ print("inventory is not a gate `polyctl commit-ok` checks; nothing reads an inventory waiver, "
1628
+ "so none is recorded (`polyctl features off inventory_review --by <name>` turns the playbook "
1629
+ "switch off)")
1630
+ return 2
1631
+ if args.gate not in ("review", "gates"):
1632
+ print(f"unknown gate {args.gate!r}: choose review or gates"); return 2
1633
+ raw_gates = getattr(args, "gates", None)
1634
+ if raw_gates is not None and args.gate != "gates":
1635
+ print(f"--gates applies only to `polyctl waive gates`, not `{args.gate}`"); return 2
1636
+ try:
1637
+ named_gates = A._normalize_waived_gates(raw_gates) if args.gate == "gates" else None
1638
+ except ValueError as exc:
1639
+ print(str(exc)); return 2
1640
+ if not args.why:
1641
+ print("--why is required: a waiver without a reason cannot be reconciled"); return 2
1642
+ # A waiver covers one slice for a bounded time and names a person (#67).
1643
+ if not args.slice or args.slice == "*":
1644
+ print("--slice is required: a waiver covers one slice, never every slice"); return 2
1645
+ if not (args.by or "").strip():
1646
+ print("--by is required: name the person who authorises this waiver"); return 2
1647
+ if args.by.strip().lower() in _agent_names(cfg):
1648
+ print(f"--by names an agent or a role ({args.by}); a waiver is a person's act"); return 2
1649
+ hours = args.hours if args.hours is not None else S.get(cfg, "waivers.default_hours")
1650
+ longest = S.get(cfg, "waivers.max_hours")
1651
+ if not 0 < hours <= longest:
1652
+ print(f"--hours must be above 0 and at most {longest}"); return 2
1653
+ try:
1654
+ rec = A.waive(root, args.gate, args.slice, args.why, by=args.by.strip(), hours=hours, gates=named_gates)
1655
+ except Exception as exc:
1656
+ print(f"{C['red']}waiver not recorded{C['reset']}: {exc}"); return 1
1657
+ if args.gate == "review":
1658
+ print(f"{C['yellow']}{C['b']}waived{C['reset']} review for {rec['slice']} ({rec['id']}) "
1659
+ f"by {rec['by']} at HEAD {rec['head'][:8]}")
1660
+ print(f"{C['dim']}commit-ok honours it in place of an APPROVED review for one staged candidate while "
1661
+ f"{rec['slice']} is running; `polyctl catchup` runs the missed review against the landed range "
1662
+ f"and closes it.{C['reset']}")
1663
+ else:
1664
+ which = f" ({', '.join(rec['gates'])})" if rec.get("gates") else ""
1665
+ covered = f"failed gate(s) {', '.join(rec['gates'])}" if rec.get("gates") else "any failed gate(s) of the profile"
1666
+ print(f"{C['yellow']}{C['b']}waived{C['reset']} gates{which} for {rec['slice']} ({rec['id']}) "
1667
+ f"by {rec['by']} at HEAD {rec['head'][:8]}")
1668
+ print(f"{C['dim']}commit-ok honours it for one staged candidate while {rec['slice']} is running when "
1669
+ f"verification ran every gate of the profile, failed only {covered}, and is bound to the staged "
1670
+ f"candidate; `polyctl catchup` re-runs the waived gates on the landed range and closes it.{C['reset']}")
1671
+ A.record_notice(root, f"waiver {args.gate}", f"{rec['slice']}: {args.why[:120]} ({rec['by']})", sent=False, key="waiver")
1672
+ return 0
1673
+
1674
+
1675
+ def _catchup_statement(cfg, args):
1676
+ """(what a person states for this run, or None; why the command is refused, or None).
1677
+
1678
+ A person may name the family that wrote the waived ranges (--author-family) and the
1679
+ waived slices that were pure moves (--move-only), or replace the commit claims with
1680
+ --boundary (TRIAGE-4-REST). Each is a person's statement. It is
1681
+ recorded with what it decides, beside what polyctl can check about who made it - the login
1682
+ and whether a terminal was attached - as a waiver is. A statement of moves closes
1683
+ nothing by itself: a waiver closes only on the move proof, run on what landed (#44).
1684
+ """
1685
+ family = str(getattr(args, "author_family", None) or "").strip().lower()
1686
+ boundary = bool(getattr(args, "boundary", None))
1687
+ named = getattr(args, "move_only", None)
1688
+ moves = list(dict.fromkeys(part.strip() for part in str(named or "").split(",") if part.strip()))
1689
+ by = str(getattr(args, "by", None) or "").strip()
1690
+ if named is not None and (not moves or not all(move.isprintable() and len(move) <= 200 for move in moves)):
1691
+ return None, "--move-only names waived slices as the board writes them, separated by commas"
1692
+ if not family and not moves and not boundary:
1693
+ return None, ("--by names the person who states --author-family, --move-only or --boundary; give one with it"
1694
+ if by else None)
1695
+ if family and not A.re.fullmatch(r"[a-z0-9][a-z0-9._:-]{0,63}", family):
1696
+ return None, "--author-family is one family name, such as the lowercase id its model family goes by"
1697
+ if not by and boundary:
1698
+ return None, "--by is required with --boundary: name the person who replaces the commit claims"
1699
+ if not by:
1700
+ return None, ("--by is required with --author-family: name the person who says which family wrote the ranges"
1701
+ if family else "--by is required with --move-only: name the person who says those slices "
1702
+ "only moved code")
1703
+ if by.lower() in _agent_names(cfg):
1704
+ what = ("replacing the commit claims" if boundary else
1705
+ "naming the author's family" if family else "saying which slices only moved code")
1706
+ return None, f"--by names an agent or a role ({by}); {what} is a person's statement"
1707
+ user, interactive = A._login_and_terminal()
1708
+ return {"family": family or None, "move_only": moves, "by": by, "user": user, "interactive": interactive}, None
1709
+
1710
+
1711
+ def _catchup_reviewer(cfg, actor):
1712
+ """(cfg, None) with `actor` holding the reviewer role for this run alone, or (cfg, why it may not) (CATCHUP-REVIEWER).
1713
+
1714
+ Runs over different slices can then go side by side, each with its own reviewer, as the machine's
1715
+ load and each platform's quota allow. Only an actor `polyctl role set reviewer` composed may stand in,
1716
+ and never the implementer's: the table is read, not changed, and every rule a review applies to
1717
+ the reviewer role - the author's family, the implementer's session and engine, the flags that
1718
+ keep a reviewer from writing - applies to the actor as it is.
1719
+ """
1720
+ if not actor:
1721
+ return cfg, None
1722
+ actors, roles, _ = A.role_table(cfg)
1723
+ block = actors.get(actor)
1724
+ if not isinstance(block, dict):
1725
+ composed = ", ".join(sorted(name for name, item in actors.items() if item.get("composed"))) or "none"
1726
+ return cfg, f"--reviewer {actor}: the project's table has no such actor; its reviewer actors: {composed}"
1727
+ if actor == roles.get("implementer"):
1728
+ return cfg, f"--reviewer {actor}: {actor} is the implementer, and no actor reviews its own work"
1729
+ if not block.get("composed"):
1730
+ return cfg, f"--reviewer {actor}: only an actor `polyctl role set reviewer` composed may review, and {actor} was not"
1731
+ print(f"{C['dim']}this run reviews with {actor} in place of {roles.get('reviewer') or 'the reviewer role'}; "
1732
+ f"the table is unchanged{C['reset']}")
1733
+ return dict(cfg, reviewer=dict(block, actor=actor)), None
1734
+
1735
+
1736
+ def _catchup_author(item, statement):
1737
+ """What a waived range's review is told about who wrote it: its grant's record, and a person's statement."""
1738
+ recorded = item.get("author") if isinstance(item.get("author"), dict) else {}
1739
+ author = {key: recorded.get(key) for key in ("role", "actor", "adapter")}
1740
+ stated = {key: statement[key] for key in ("family", "by", "user", "interactive")} \
1741
+ if statement and statement.get("family") else None
1742
+ author.update(family=str(recorded.get("family") or "").strip().lower() or None,
1743
+ grant=item.get("grant"), stated=stated)
1744
+ return author
1745
+
1746
+
1747
+ def _catchup_reviewer_note(cfg, author):
1748
+ """Why the configured reviewers may not review a range this author wrote, or None; a plan names it early."""
1749
+ if M.is_strict(cfg):
1750
+ try:
1751
+ _resolve_matrix(cfg, require_independent=True, author_families=_author_families(author))
1752
+ except M.MatrixError as exc:
1753
+ return "; ".join(exc.problems[:2])
1754
+ return None
1755
+ reviewer = cfg.get("reviewer") or {}
1756
+ if not reviewer.get("argv"):
1757
+ return "no reviewer is configured" + _waiting_reviewer(cfg)
1758
+ refused = _reviewer_ineligible(cfg, reviewer, author=author)
1759
+ return f"the reviewer may not review it: {refused}" if refused else None
1760
+
1761
+
1762
+ def _waiting_reviewer(cfg):
1763
+ """'; <actor> is assigned the reviewer role and holds it once <slice> leaves running', or '' (OCT1-FIXES)."""
1764
+ waiting, after = A.pending_roles(cfg.get("root"), cfg)
1765
+ return (f"; {waiting['reviewer']} is assigned the reviewer role and holds it once {after} leaves running"
1766
+ if waiting.get("reviewer") else "")
1767
+
1768
+
1769
+ def _catchup_mail(root, cfg, waiver, rng, artefact):
1770
+ """The architect's decision request after a waived range is reviewed NEEDS_CHANGES.
1771
+
1772
+ Named and addressed as every message polyctl writes (#31): to whoever holds the architect
1773
+ role, from the role this command runs for, or from a person when polyctl did not start it.
1774
+ """
1775
+ implementer, architect = A.mail_names(cfg)
1776
+ sender = {"implementer": implementer, "architect": architect}.get(A.invoking_role(), "human")
1777
+ # The waiver's fields come from a ledger anyone on the machine can edit: one line each (#55).
1778
+ slice_id, wid, by, why = (A.review_header_value(waiver.get(key) or "") for key in ("slice", "id", "by", "why"))
1779
+ name = (f"{time.strftime('%Y%m%d-%H%M')}-{sender}-to-{architect}-REVIEW-"
1780
+ f"{A.safe_slug(str(waiver.get('slice') or '').lower(), 'slice')}-needs-changes.md")
1781
+ findings = A.review_header_value(f"{cfg['reviews']}/{artefact or ''}")
1782
+ body = (f"# The waived review of {slice_id} needs changes\n\n## Decision required\n\n"
1783
+ f"The retrospective review of {rng}, which landed under waiver {wid} ({by}: {why}), "
1784
+ f"returned NEEDS_CHANGES. The findings are in {findings}.\n\n"
1785
+ "The waiver closes on this review. Decide the fix slice.\n")
1786
+ return A.write_mail(root, cfg, name, body, {"kind": "review", "class": "needs-decision", "from": sender,
1787
+ "to": architect, "slice": slice_id})
1788
+
1789
+
1790
+ def _catchup_undecided(root, targets):
1791
+ """{waiver id: verdict} for each waived range whose newest review of exactly that range decided nothing.
1792
+
1793
+ A review that ends UNAVAILABLE or INVALID keeps its waiver open, and the next run met
1794
+ that waiver first again: runs of --limit N whose first N reviews kept failing reviewed
1795
+ nothing else, however often they were repeated (OCT1-FIXES). A ledger that cannot be
1796
+ read orders nothing; the review that needs it says so.
1797
+ """
1798
+ from .storage import read_chained_jsonl
1799
+ try:
1800
+ rows = read_chained_jsonl(A.review_ledger_path(root), A.REVIEW_CHAIN)
1801
+ except Exception:
1802
+ return {}
1803
+ newest = {row.get("commits"): row.get("verdict") for row in rows
1804
+ if isinstance(row, dict) and row.get("kind") == "commit-range"}
1805
+ ranges = {item["waiver"].get("id"): f"{item['start']}..{item['end']}" for item in targets if item.get("landed")}
1806
+ return {wid: newest[rng] for wid, rng in ranges.items() if newest.get(rng) in ("UNAVAILABLE", "INVALID")}
1807
+
1808
+
1809
+ def _catchup_exit(failed, started, decided):
1810
+ """The exit code of a catch-up run: what failed, reviews that decided nothing, or 0 (CATCHUP-POLISH).
1811
+
1812
+ Rehearsing the catch-up planned for 2026-10-01, a run whose every review ended
1813
+ UNAVAILABLE exited 0, as a run that closed ten waivers did, so a person or a script
1814
+ repeating --limit could not tell a reviewer that decides nothing from progress. 1 stays
1815
+ what could not be written or read. 3 is reviews started and none deciding anything,
1816
+ whatever else closed, as `polyctl review` exits 3 when no reviewer could review. Anything else
1817
+ is 0: progress, or nothing to do, since an idle catch-up is no failure and a wake turn, a
1818
+ `set -e` script and a person all read a nonzero exit as one.
1819
+ """
1820
+ if failed:
1821
+ return 1
1822
+ return 3 if started and not decided else 0
1823
+
1824
+
1825
+ def cmd_catchup(cfg, args):
1826
+ """Replay what could not run: waived reviews and waived gates, deferred wakes and nudges.
1827
+
1828
+ A gates waiver re-runs the waived gates on the landed commit under the gate definitions
1829
+ that the grant's verification bound, and closes when they pass (WAIVE-GATES).
1830
+ A waived range is reviewed by a model family other than the one that wrote it (#65):
1831
+ the family the grant under the waiver recorded, and any a person names with
1832
+ --author-family and --by. With neither, its review is refused and the waiver stays
1833
+ open. The reviewer judges the range against what its commit messages claim, unless a
1834
+ person gives --boundary, and the review is recorded as the waived slice's. A range whose
1835
+ grant recorded a move proof, or whose slice a person names with --move-only and --by, is
1836
+ not reviewed: the proof runs on what landed, and the waiver closes on it or stays open
1837
+ with the reason (#44). A range with neither is reviewed, whatever its diff looks like.
1838
+ --plan says what a run would do and changes nothing; --slice and --limit bound a run. A
1839
+ review stays synchronous: a waiver closes in the same run, on the review recorded for
1840
+ exactly its range, or stays open. A range whose last review decided nothing waits behind
1841
+ the rest, and once a review finds the reviewer unavailable the run starts no other. --limit
1842
+ bounds the gate re-runs and reviews a run starts in the same way: what needs neither is still done.
1843
+
1844
+ A person's review of exactly a waived range (`polyctl person-review --commits <range>`) closes
1845
+ its waiver with no reviewer started (REVIEW-TIERS): a person is of no model family, so the
1846
+ author-family rule holds whichever family wrote the range. No same-family tier reaches a
1847
+ range: its grant recorded the family that wrote it, never the model.
1848
+
1849
+ The exit code says what a run did (CATCHUP-POLISH): 3 when it started reviews and none of
1850
+ them decided anything, whatever else it closed; 1 when a waived gate failed or a close, a ledger
1851
+ or a decision request could not be written or read; 2 when it is refused; otherwise 0, for progress
1852
+ and for nothing to do alike. --plan exits 0, or 1 when the waivers cannot be read.
1853
+ """
1854
+ from types import SimpleNamespace
1855
+ from .storage import LedgerCorruption
1856
+ root = cfg["root"]
1857
+ plan = bool(getattr(args, "plan", False))
1858
+ limit = getattr(args, "limit", None)
1859
+ only = getattr(args, "slice", None)
1860
+ statement, refusal = _catchup_statement(cfg, args)
1861
+ if refusal:
1862
+ print(refusal)
1863
+ return 2
1864
+ cfg, refusal = _catchup_reviewer(cfg, getattr(args, "reviewer", None))
1865
+ if refusal:
1866
+ print(refusal)
1867
+ return 2
1868
+ if limit is not None and limit < 1:
1869
+ print("--limit is at least 1: the number of gate re-runs and reviews this run may start")
1870
+ return 2
1871
+ did = started = reruns = decided = held = waiting = 0
1872
+ unavailable = None # the waiver whose review found the reviewer unavailable
1873
+ failed = []
1874
+ totals = {"waivers": 0, "commits": 0, "lines": 0, "unnamed": 0, "proven": 0} # what --plan sums up
1875
+
1876
+ def close(wid, outcome, evidence=None):
1877
+ # A waiver retires on a durable append or not at all; a failure is reported
1878
+ # and fails the command, never counted as handled (#67).
1879
+ try:
1880
+ A.close_waiver(root, wid, outcome, evidence=evidence)
1881
+ return True
1882
+ except Exception as exc:
1883
+ print(f" {C['red']}could not close {wid}{C['reset']}: {exc}")
1884
+ failed.append(wid)
1885
+ return False
1886
+
1887
+ def request(waiver, rng, artefact):
1888
+ # The architect's decision request is written before its waiver closes: closed first, a request
1889
+ # that could not be written left no open waiver, and no later run wrote it (LEADS-OPS).
1890
+ try:
1891
+ _catchup_mail(root, cfg, waiver, rng, artefact)
1892
+ return True
1893
+ except OSError as exc:
1894
+ print(f" {C['red']}the architect's decision request was not written{C['reset']}: {exc}; "
1895
+ f"{waiver['id']} stays open, and the next run writes it")
1896
+ failed.append(waiver["id"])
1897
+ return False
1898
+
1899
+ if plan:
1900
+ print(f"{C['b']}catchup plan{C['reset']}{C['dim']}: nothing is reviewed or written{C['reset']}")
1901
+ try:
1902
+ targets = A.review_waiver_ranges(root)
1903
+ gate_targets = A.gates_waiver_ranges(root)
1904
+ except Exception as exc:
1905
+ print(f" {C['red']}waivers cannot be read{C['reset']}: {exc}")
1906
+ targets, gate_targets = [], []
1907
+ failed.append("ledger")
1908
+ moves = (statement or {}).get("move_only") or []
1909
+ open_slices = {item["waiver"].get("slice") for item in targets}
1910
+ # A ledger that cannot be read says nothing about which slices it names (OCT1-FIXES).
1911
+ for name in [] if "ledger" in failed else moves:
1912
+ # A statement about a slice with nothing to prove is reported, never dropped quietly.
1913
+ if name not in open_slices:
1914
+ print(f" --move-only {name}: no open review waiver names it; nothing is proven or closed")
1915
+ elif only and name != only:
1916
+ print(f" --move-only {name}: --slice {only} bounds this run; it waits for another")
1917
+ if only:
1918
+ targets = [item for item in targets if item["waiver"].get("slice") == only]
1919
+ gate_targets = [item for item in gate_targets if item["waiver"].get("slice") == only]
1920
+ undecided = _catchup_undecided(root, targets)
1921
+ targets = sorted(targets, key=lambda item: item["waiver"].get("id") in undecided)
1922
+ for item in gate_targets:
1923
+ w = item["waiver"]
1924
+ label = f"{w['id']} ({w['slice']})"
1925
+ totals["waivers"] += 1
1926
+ if item["problem"]:
1927
+ print(f" {label}: {item['problem']}; keeping it open")
1928
+ continue
1929
+ if item.get("unused"):
1930
+ if not item.get("expired"):
1931
+ print(f" {label}: nothing was granted under it yet; keeping it open until it expires")
1932
+ elif plan:
1933
+ print(f" {label}: expired unused; a run closes it")
1934
+ elif close(w["id"], "nothing was granted under it before it expired"):
1935
+ print(f" {label}: expired unused; closed")
1936
+ did += 1
1937
+ continue
1938
+ if not item["landed"]:
1939
+ if item["newest"]:
1940
+ print(f" {label}: nothing landed yet after the waiver; keeping it open")
1941
+ elif plan:
1942
+ print(f" {label}: no commits landed before the next waiver; a run closes it")
1943
+ elif close(w["id"], "no commits landed before the next waiver was opened"):
1944
+ print(f" {label}: no commits landed before the next waiver; closed")
1945
+ did += 1
1946
+ continue
1947
+ rng = f"{item['start'][:12]}..{item['end'][:12]}"
1948
+ waived_names = item.get("waived_gates") or w.get("gates") or []
1949
+ gate_list = ", ".join(waived_names) if waived_names else "profile gates"
1950
+ if limit is not None and (started + reruns) >= limit:
1951
+ waiting += 1
1952
+ continue
1953
+ reruns += 1
1954
+ if plan:
1955
+ print(f" {label}: {rng}: re-run waived gates ({gate_list}) on {item['end'][:12]}")
1956
+ continue
1957
+ print(f" {label}: re-running waived gates ({gate_list}) on {rng}")
1958
+ ok, ran_names, detail = _rerun_waived_gates(cfg, root, item, getattr(args, "wait", None))
1959
+ if ok:
1960
+ evidence = {"commits": f"{item['start']}..{item['end']}", "grant": item.get("grant"), "gates": ran_names}
1961
+ if close(w["id"], f"waived gates passed on {rng}: {', '.join(ran_names)}", evidence):
1962
+ print(f" {label}: {rng}: waived gates passed ({', '.join(ran_names)}); closed")
1963
+ did += 1
1964
+ else:
1965
+ try:
1966
+ A.fail_waiver(root, w["id"], detail)
1967
+ except Exception:
1968
+ pass
1969
+ print(f" {label}: {rng}: waived gates failed ({detail}); {w['id']} stays open")
1970
+ failed.append(w["id"])
1971
+ for item in targets:
1972
+ w = item["waiver"]
1973
+ label = f"{w['id']} ({w['slice']})"
1974
+ totals["waivers"] += 1
1975
+ if item["problem"]:
1976
+ print(f" {label}: {item['problem']}; keeping it open")
1977
+ continue
1978
+ if item.get("unused"):
1979
+ if not item.get("expired"):
1980
+ print(f" {label}: nothing was granted under it yet; keeping it open until it expires")
1981
+ elif plan:
1982
+ print(f" {label}: expired unused; a run closes it")
1983
+ elif close(w["id"], "nothing was granted under it before it expired"):
1984
+ print(f" {label}: expired unused; closed")
1985
+ did += 1
1986
+ continue
1987
+ if not item["landed"]:
1988
+ if item["newest"]:
1989
+ print(f" {label}: nothing landed yet after the waiver; keeping it open")
1990
+ elif plan:
1991
+ print(f" {label}: no commits landed before the next waiver; a run closes it")
1992
+ elif close(w["id"], "no commits landed before the next waiver was opened"):
1993
+ print(f" {label}: no commits landed before the next waiver; closed")
1994
+ did += 1
1995
+ continue
1996
+ rng = f"{item['start'][:12]}..{item['end'][:12]}"
1997
+ lines = A.range_changed_lines(root, item["start"], item["end"])
1998
+ size = f"{item['landed']} commit(s), {'unknown' if lines is None else lines} changed line(s)"
1999
+ granted_proof = item.get("move_only")
2000
+ # Older grants could record a different running slice's proof (TRIAGE-4-REST).
2001
+ if not isinstance(granted_proof, dict) or granted_proof.get("slice") != w.get("slice"):
2002
+ granted_proof = None
2003
+ stated = w.get("slice") in moves
2004
+ if granted_proof or stated:
2005
+ # A semantic review of a proven pure move reads nothing the proof did not. Its grant
2006
+ # recorded the proof for the tree it granted, or a person states the slice only moved
2007
+ # code; either way what landed is proven here, and the waiver closes on that proof
2008
+ # alone, with no reviewer, or stays open. A statement never closes one by itself (#44).
2009
+ claimed = " and ".join(part for part in ("its grant recorded a pure move" if granted_proof else "",
2010
+ f"{statement['by']} states it is a pure move" if stated else "")
2011
+ if part)
2012
+ moved, problems = A.range_move_proof(root, item["start"], item["end"])
2013
+ if problems:
2014
+ print(f" {label}: {rng}, {size}: {claimed}, and the landed range is not one: "
2015
+ f"{'; '.join(problems[:3])}" + (f" and {len(problems) - 3} more" if len(problems) > 3 else "")
2016
+ + "; keeping it open")
2017
+ continue
2018
+ totals["proven"] += 1
2019
+ proof = {"proof": "split-moves", "commits": f"{item['start']}..{item['end']}", "grant": item.get("grant"),
2020
+ "moved": len(moved), "paths": sorted({f"{source} -> {target}" for _, source, target in moved})}
2021
+ if granted_proof:
2022
+ proof["recorded"] = granted_proof
2023
+ if stated:
2024
+ proof["stated"] = {key: statement[key] for key in ("move_only", "by", "user", "interactive")}
2025
+ proven = f"{len(moved)} definition(s) moved byte for byte on the landed range"
2026
+ if plan:
2027
+ print(f" {label}: {rng}, {size}: {claimed}; closes by proof, {proven}; no reviewer")
2028
+ elif close(w["id"], f"closed by proof: {proven}; {claimed}", proof):
2029
+ print(f" {label}: {rng}, {size}: {claimed}; {proven}; closed by proof, with no reviewer")
2030
+ did += 1
2031
+ continue
2032
+ try:
2033
+ person = _person_range_review(root, cfg, f"{item['start']}..{item['end']}")
2034
+ except Exception as exc:
2035
+ person = None
2036
+ print(f" {C['red']}review ledger cannot be read{C['reset']}: {exc}")
2037
+ if person:
2038
+ # A person is of no model family, so a person's review of exactly this range holds whichever
2039
+ # family wrote it: the waiver closes on it, with no reviewer started (REVIEW-TIERS).
2040
+ who = _person_line(person.get("person"))
2041
+ if plan:
2042
+ print(f" {label}: {rng}, {size}: {person['verdict']} in a person's review ({who}); a run closes on it")
2043
+ elif (person["verdict"] != "NEEDS_CHANGES" or request(w, rng, person.get("artefact"))) \
2044
+ and close(w["id"], f"reviewed by a person: {person['verdict']}",
2045
+ {"review": person.get("artefact"), "person": person.get("person")}):
2046
+ print(f" {label}: {rng}, {size}: closed on a person's review ({who}): {person['verdict']}")
2047
+ did += 1
2048
+ continue
2049
+ author = _catchup_author(item, statement)
2050
+ families = _author_families(author)
2051
+ if not families:
2052
+ # A review by the family that wrote the range would not be independent (#65).
2053
+ totals["unnamed"] += 1
2054
+ landed_by = " ".join(str(author[key]) for key in ("role", "actor") if author.get(key))
2055
+ print(f" {label}: {rng}, {size}: the family of the model that wrote it is not established"
2056
+ + (f" (landed by the {landed_by})" if landed_by else "")
2057
+ + "; a person names it with --author-family <family> --by <name>, or reviews the range: "
2058
+ "polyctl person-review --commits <range> --by <name>; keeping it open")
2059
+ continue
2060
+ if unavailable:
2061
+ # Every review after one that found the reviewer unavailable waits on it too; each
2062
+ # could spend the review's whole time budget finding that out again (OCT1-FIXES).
2063
+ held += 1
2064
+ continue
2065
+ if limit is not None and (started + reruns) >= limit:
2066
+ # --limit bounds the gate re-runs and reviews a run starts, as an unavailable reviewer does, and
2067
+ # nothing else. The run stopped at the limit instead, and said a waiver nothing was granted under
2068
+ # waited for the next run, which would close it unreviewed (CATCHUP-POLISH, LOWS-0.7).
2069
+ waiting += 1
2070
+ continue
2071
+ started += 1
2072
+ totals["commits"] += item["landed"]
2073
+ totals["lines"] += lines or 0
2074
+ last = (f"; its last review ended {undecided[w['id']]}, so it comes after the ranges no review has "
2075
+ "failed on") if w["id"] in undecided else ""
2076
+ if plan:
2077
+ note = _catchup_reviewer_note(cfg, author)
2078
+ print(f" {label}: {rng}, {size}: review by a family other than {', '.join(families)}"
2079
+ + (f"; {note}" if note else "") + last)
2080
+ continue
2081
+ print(f" {label}: reviewing its own landed range {rng}, {size}, by a family other than {', '.join(families)}"
2082
+ + last)
2083
+ # No deadline is passed: a reviewer's time is review_timeout per call, and a silent
2084
+ # one is killed after review.stall_minutes (#63, #25). The range's commit messages
2085
+ # are the statement it is judged against; a person's --boundary replaces them.
2086
+ ns = SimpleNamespace(boundary=args.boundary or f"waived review for {w['slice']}: {w['why']}",
2087
+ paths=None, commits=f"{item['start']}..{item['end']}", author=author,
2088
+ claims=not args.boundary, range_slice=w["slice"],
2089
+ boundary_by={key: statement[key] for key in ("by", "user", "interactive")}
2090
+ if args.boundary else None)
2091
+ # The row count is only a readability check: without it a broken ledger spent
2092
+ # a reviewer call, or let an unchanged range close unreviewed (CATCHUP-ROW).
2093
+ try:
2094
+ A.review_row_count(root)
2095
+ except Exception as exc:
2096
+ print(f" {C['red']}review ledger cannot be read{C['reset']}: {exc}; {w['id']} stays open")
2097
+ failed.append(w["id"])
2098
+ continue
2099
+ try:
2100
+ code = cmd_review(cfg, ns)
2101
+ except (OSError, LedgerCorruption) as exc:
2102
+ # A ledger or artefact can fail after the pre-check; keep this waiver for
2103
+ # another run and still attempt the later ranges (CATCHUP-ROW).
2104
+ print(f" {C['red']}review could not be recorded{C['reset']}: {exc}; "
2105
+ f"{w['id']} stays open; retry catch-up once the review can be recorded")
2106
+ failed.append(w["id"])
2107
+ continue
2108
+ # The exit code is not a verdict: a review that refused to run exits 1 or 2
2109
+ # too. Counting ledger rows took another review of the same range and author
2110
+ # for this call's; cmd_review hands back the row it recorded (CATCHUP-ROW).
2111
+ recorded = getattr(ns, "recorded", None) or {}
2112
+ verdict = recorded.get("verdict")
2113
+ if verdict in ("APPROVED", "NEEDS_CHANGES") or (verdict is None and code == 0):
2114
+ decided += 1 # the review decided what becomes of the waiver
2115
+ if verdict == "APPROVED":
2116
+ if close(w["id"], "reviewed: APPROVED"):
2117
+ did += 1
2118
+ elif verdict == "NEEDS_CHANGES":
2119
+ if request(w, rng, recorded.get("artefact")) and close(w["id"], "reviewed: NEEDS_CHANGES — fix slice needed"):
2120
+ did += 1
2121
+ elif verdict is None and code == 0 and A.range_unchanged(root, item["start"], item["end"]) is not True:
2122
+ # A review that exits 0 with no verdict recorded for exactly this range closes it only when the
2123
+ # range has no net change; one whose record polyctl cannot find, or a range it cannot size, was taken
2124
+ # for an empty one and its waiver retired unreviewed (WAIVER-BOUND-2). No net change is the same
2125
+ # tree at both ends: a range no line of which changed, a binary file's, can still change
2126
+ # (WAIVER-BOUND-3).
2127
+ print(f" the review of {rng} recorded no verdict polyctl can find; {w['id']} stays open")
2128
+ failed.append(w["id"])
2129
+ elif verdict is None and code == 0:
2130
+ if close(w["id"], "nothing to review: the landed range has no net change"):
2131
+ print(f" {label}: the landed range has no net change; closed")
2132
+ did += 1
2133
+ elif verdict == "INVALID":
2134
+ # An INVALID review exits 3 as an unavailable one does: the verdict tells them apart (OCT1-FIXES).
2135
+ print(f" the reviewer returned no valid verdict; {w['id']} stays open")
2136
+ elif verdict == "UNAVAILABLE":
2137
+ # An unavailable reviewer is recorded so before `polyctl review` exits 3. One that exits 3 with nothing
2138
+ # recorded asked no reviewer - another review of the range held its sections - and was told as an
2139
+ # unavailable reviewer; it is told as what it is, and holds no other review (LEADS-OPS).
2140
+ print(f" reviewer still unavailable; {w['id']} stays open")
2141
+ unavailable = w["id"]
2142
+ elif code == 2:
2143
+ print(f" reviewer configuration invalid, or the range cannot be reviewed; {w['id']} stays open")
2144
+ else:
2145
+ print(f" no review was recorded (exit {code}); {w['id']} stays open")
2146
+ if held:
2147
+ print(f" the reviewer was unavailable for {unavailable}: this run started no other review, and "
2148
+ f"{held} waiver(s) wait for a run in which it answers")
2149
+ if waiting:
2150
+ print(f" --limit {limit}: {waiting} waiver(s) wait for a later run to review them")
2151
+ if plan:
2152
+ rerun_part = f"{reruns} gate re-run(s); " if reruns else ""
2153
+ print(f"totals: {totals['waivers']} waiver(s); {rerun_part}{started} review(s) of {totals['commits']} commit(s) and "
2154
+ f"{totals['lines']} changed line(s); {totals['unnamed']} refused until a person names the author's "
2155
+ f"family; {totals['proven']} closed by proof, with no reviewer; "
2156
+ f"{len(A.deferred_open(root))} deferred wake(s) and nudge(s) a run replays")
2157
+ return 1 if failed else 0
2158
+ # A deferral is replayed by a cycle that runs with it in view, and closed after it: closed first, a cycle
2159
+ # that then did not run - no watchdog, or another cycle holding the project - left it forgotten (JOURNAL-4).
2160
+ ran = False
2161
+ from . import watchdog as W
2162
+ # What was open before the cycle: the cycle closes what it did itself, before catchup asks (JOURNAL-4-3).
2163
+ before = {row["id"]: row for row in A.deferred_open(root)}
2164
+ if A.heartbeat_age(root) is None:
2165
+ # A cycle writes this project's heartbeat. Where no watchdog runs, that file
2166
+ # goes stale within minutes and every sibling watchdog reports it as dead.
2167
+ print(f"{C['dim']}no watchdog runs for this project; skipping the cycle{C['reset']}")
2168
+ else:
2169
+ print(f"{C['dim']}running one watchdog cycle to act on what is now possible{C['reset']}")
2170
+ cycle = SimpleNamespace(root=root, idle_minutes=S.get(cfg, "watchdog.idle_minutes"), dry_run=False)
2171
+ W.run(cycle)
2172
+ ran = bool(getattr(cycle, "ran", False))
2173
+ if not ran:
2174
+ print(f"{C['dim']}another cycle holds this project; what was deferred waits for it{C['reset']}")
2175
+ # A deferral closes on the work it waited for, started after it by this cycle or an earlier one. One the
2176
+ # cycle still could not do - it deferred it again, or wrote it - stays open.
2177
+ W._close_deferred_done(root, W.load_state(root))
2178
+ standing = {row["id"] for row in A.deferred_open(root)}
2179
+ for r in (row for rid, row in before.items() if rid not in standing):
2180
+ print(f" deferred {r['kind']} ({r.get('reason', '')}) since {time.strftime('%d %b %H:%M', time.localtime(r['at']))}: done")
2181
+ did += 1
2182
+ for r in A.deferred_open(root):
2183
+ print(f" deferred {r['kind']} ({r.get('reason', '')}) since {time.strftime('%d %b %H:%M', time.localtime(r['at']))}"
2184
+ + ("; stays open: its cycle could not do it yet" if ran else "; stays open: no cycle ran"))
2185
+ code = _catchup_exit(failed, started, decided)
2186
+ print(f"{C['green']}catchup{C['reset']} handled {did} item(s)"
2187
+ + (f"; none of the {started} review(s) it started decided anything" if code == 3 else ""))
2188
+ return code
2189
+
2190
+
2191
+ def cmd_pings(cfg, args):
2192
+ """Dead man's switch: an external service that alarms when the pings stop."""
2193
+ root = cfg["root"]
2194
+ if args.action == "setup":
2195
+ return _pings_setup(root, args)
2196
+ url = A.ping_url(root)
2197
+ if args.action == "test":
2198
+ ok = A.ping(root)
2199
+ print(f"{C['green']}pinged{C['reset']}" if ok else f"{C['red']}no ping{C['reset']} ({'no url' if not url else 'request failed'})")
2200
+ return 0 if ok else 1
2201
+ if not url:
2202
+ print(f"ping url: {C['yellow']}not configured{C['reset']}")
2203
+ return 0
2204
+ print(f"ping url: {_ping_url_shown(url)} {C['dim']}(the rest is the secret, in {A.pings_path()}){C['reset']}")
2205
+ return 0
2206
+
2207
+
2208
+ def _pings_setup(root, args):
2209
+ """`polyctl pings setup`: its steps, then the ping URL asked at the terminal and not shown, or read from the variable a
2210
+ script names.
2211
+
2212
+ The steps had a person type the URL on a command line, `polyctl pings setup --url https://hc-ping.com/<uuid>`: the
2213
+ shell's history and the process list kept it, and whoever reads the check's UUID can ping it, so a dead watchdog
2214
+ looks alive. polyctl asks for it now as `polyctl telegram setup` asks for the bot token (LEADS-SECRETS) and `polyctl email setup`
2215
+ for an account's password (EMAIL-SETUP-PROMPT); neither ever took its secret on a command line, and a URL given
2216
+ with --url is refused unsaved (SECRETS-2).
2217
+ """
2218
+ url_env = getattr(args, "url_env", None)
2219
+ if getattr(args, "url", None) is not None:
2220
+ print(f"{C['red']}not saved{C['reset']}: a ping URL on a command line stays in the shell's history and the "
2221
+ "process list, where whoever reads it can ping the check; run polyctl pings setup to paste it unseen, or "
2222
+ "name the variable that holds it with --url-env NAME")
2223
+ return 2
2224
+ if url_env:
2225
+ # Read once from the environment, for a script.
2226
+ url = os.environ.get(url_env)
2227
+ if not url:
2228
+ print(f"{C['red']}not saved{C['reset']}: ${url_env} is {'empty' if url == '' else 'not set'}")
2229
+ return 2
2230
+ else:
2231
+ print("1. Create a check at https://healthchecks.io (free) with a 15-minute period and a 10-minute grace.\n"
2232
+ "2. Copy its ping URL and paste it when polyctl asks. It is not shown: whoever has the check's UUID can ping\n"
2233
+ " it, so no command line or shell history holds it. With --all it is the URL of every project that\n"
2234
+ " has none of its own.\n"
2235
+ "The watchdog and the doctor job ping it every cycle; when both die, healthchecks e-mails you.\n")
2236
+ if not sys.stdin.isatty():
2237
+ print(f"{C['red']}not saved{C['reset']}: the ping URL is asked at a terminal, and none is attached; run "
2238
+ "polyctl pings setup in a terminal of yours, or name the variable that holds it with --url-env NAME")
2239
+ return 2
2240
+ url = _hidden_input("ping URL (not shown): ")
2241
+ if url is None:
2242
+ print(f"{C['red']}not saved{C['reset']}: this terminal cannot hide what is typed, and a ping URL typed "
2243
+ "here would stand in its scrollback; --url-env names a variable that holds it")
2244
+ return 2
2245
+ url = url.strip()
2246
+ if not url:
2247
+ print(f"{C['red']}not saved{C['reset']}: no ping URL was given"); return 2
2248
+ if not _pingable(url):
2249
+ # Said without the value: what was pasted unseen may be another secret.
2250
+ print(f"{C['red']}not saved{C['reset']}: that is no ping URL; healthchecks gives one as "
2251
+ "https://hc-ping.com/<uuid>")
2252
+ return 2
2253
+ every = bool(getattr(args, "all", False))
2254
+ A.set_ping_url(root, url, all_projects=every)
2255
+ print(f"{C['green']}saved{C['reset']} {A.pings_path()} ({_private_mode()}): "
2256
+ f"{'every project with no URL of its own' if every else 'this project'} pings {_ping_url_shown(url)}")
2257
+ print(f"now: {C['b']}polyctl pings test{C['reset']}")
2258
+ return 0
2259
+
2260
+
2261
+ def _pingable(url):
2262
+ """Whether a URL is one the watchdog's ping can request: http or https, a host, and no space or control character.
2263
+
2264
+ It is pasted where it is not shown, so a person cannot see they pasted something else, and the ping hands it to
2265
+ urllib, which opens a file:// address as readily (SECRETS-2).
2266
+ """
2267
+ from urllib.parse import urlsplit
2268
+ if any(ch.isspace() or not ch.isprintable() for ch in url):
2269
+ return False
2270
+ try:
2271
+ parts = urlsplit(url)
2272
+ host = parts.hostname and parts.hostname + (f":{parts.port}" if parts.port else "")
2273
+ except ValueError: # a URL urllib cannot read, a port that is no number among them
2274
+ return False
2275
+ return parts.scheme in ("http", "https") and bool(host)
2276
+
2277
+
2278
+ def _ping_url_shown(url):
2279
+ """A ping URL as `polyctl pings` shows it: its scheme, and the file that holds it.
2280
+
2281
+ The address is the secret: whoever has it can ping the check, and then a dead watchdog looks alive and the alarm
2282
+ that its pings stopped never rings. `polyctl pings` printed the URL whole, then its host - and a check's UUID can stand
2283
+ in a host's labels, or a host can be the check's own name, `https://deadmansecret.com`, and its last four
2284
+ characters can be all of the secret (LEADS-SECRETS). So no part of it is shown but its scheme, and the file that
2285
+ holds it is named.
2286
+ """
2287
+ from urllib.parse import urlsplit
2288
+ try:
2289
+ scheme = urlsplit(url).scheme
2290
+ except ValueError: # a URL urllib cannot read, a port that is no number among them
2291
+ scheme = ""
2292
+ # No character of it: four from its end were the whole secret of an address with a public prefix.
2293
+ return (f"{scheme}://" if scheme in ("http", "https") else "") + "…"