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,1325 @@
1
+ """Channels: MCP and A2A servers, locks, credits, telegram, recall, stats, roles, hunting, content,
2
+ rooms, questions, handoff.
3
+
4
+ A part of src/polyctl/cli.py (#44): moved out byte for byte and run in its namespace by `_part`,
5
+ where it stood; it is not importable on its own.
6
+ """
7
+
8
+
9
+ def _serve(module, cfg, extra):
10
+ """Run a server module in this process.
11
+
12
+ Calling it beats exec'ing a sibling script: the script path only exists in a
13
+ git clone, and after `pip install polyctl` there is no scripts/ directory to point
14
+ at. Importing works from both.
15
+ """
16
+ sys.argv = ["polyctl-" + module, "-C", cfg["root"]] + extra
17
+ # Each by an import that names it: the move proof reads a module imported by a string as one that may be any (#111).
18
+ if module == "mcp":
19
+ from . import mcp as server
20
+ elif module == "a2a_mcp":
21
+ from . import a2a_mcp as server
22
+ elif module == "a2a":
23
+ from . import a2a as server
24
+ elif module == "telegram":
25
+ from . import telegram as server
26
+ else:
27
+ raise ValueError(f"no server module {module}")
28
+ return server.main()
29
+
30
+
31
+ # A client starts the program a config names, by that name, wherever it runs: one this polyctl cannot name by an absolute
32
+ # path is put on PATH first (WINDOWS-NO-CWD-EXEC).
33
+ NO_POLYCTL_PROGRAM = ("no polyctl program to name in the config: none is on PATH, and this polyctl was not started from one - put polyctl "
34
+ "on PATH (pip install polyctl, or link a clone's bin/polyctl) and ask again")
35
+
36
+
37
+ def cmd_mcp(cfg, args):
38
+ """Serve this project's state to any MCP client, over stdio."""
39
+ # The role and project scope are the server's own arguments, so the config printed for a client carries them too (MCP-ROLES, MCP-RES).
40
+ role = ["--role", args.role] if args.role is not None else []
41
+ project = ["--project", args.project] if getattr(args, "project", None) is not None else []
42
+ if args.action != "serve":
43
+ command = A.polyctl_program() # never one the current directory holds (WINDOWS-NO-CWD-EXEC)
44
+ if command is None:
45
+ print(NO_POLYCTL_PROGRAM); return 1
46
+ print(f"{C['b']}Add to an MCP client's config:{C['reset']}")
47
+ print(json.dumps({"mcpServers": {"polyctl": {
48
+ "command": command, "args": ["-C", cfg["root"], "mcp", "serve"] + project + role}}}, indent=2))
49
+ return 0
50
+ return _serve("mcp", cfg, (["--allow-verify"] if args.allow_verify else []) + project + role)
51
+
52
+
53
+ def cmd_a2a_mcp(cfg, args):
54
+ """Expose configured A2A agents to an MCP client."""
55
+ if args.action != "serve":
56
+ reg = os.path.join(cfg["root"], ".polyctl", "a2a-agents.json")
57
+ command = A.polyctl_program() # never one the current directory holds (WINDOWS-NO-CWD-EXEC)
58
+ if command is None:
59
+ print(NO_POLYCTL_PROGRAM); return 1
60
+ print(f"{C['b']}Add to an MCP client's config:{C['reset']}")
61
+ print(json.dumps({"mcpServers": {"a2a": {
62
+ "command": command, "args": ["-C", cfg["root"], "a2a-mcp", "serve"]}}}, indent=2))
63
+ print(f"\n{C['b']}Then register agents in {reg}:{C['reset']}")
64
+ # The example wrote a token into the project's file, which a commit takes: a header names the variable that
65
+ # holds it, and one written out there is refused (LEADS-SECRETS).
66
+ print(json.dumps({"weather": {"url": "https://agent.example.com/a2a/v1",
67
+ "headers": {"Authorization": "Bearer ${WEATHER_A2A_TOKEN}"}}}, indent=2))
68
+ print(f"{C['dim']}A credential stays out of the file: ${{NAME}} is read from the environment the client starts "
69
+ f"the bridge with.\nThe dialect is read from each agent's card; set "
70
+ f'"version": "0.3" to pin one.{C["reset"]}')
71
+ return 0
72
+ return _serve("a2a_mcp", cfg, [])
73
+
74
+
75
+ def cmd_a2a(cfg, args):
76
+ """Serve this project's board as A2A tasks, on loopback."""
77
+ if args.action != "serve":
78
+ print(f"{C['b']}polyctl a2a serve --port {args.port}{C['reset']}")
79
+ print(f" card http://127.0.0.1:{args.port}/.well-known/agent-card.json")
80
+ print(f" tasks http://127.0.0.1:{args.port}/tasks")
81
+ return 0
82
+ return _serve("a2a", cfg, ["--port", str(args.port)])
83
+
84
+
85
+ def _urgent_banner(cfg):
86
+ """Print anything urgent before the caller does something expensive.
87
+
88
+ This is the injection point MCP cannot provide. The agent came here on its
89
+ own, on the way to a heavy operation, and that is the last cheap moment to
90
+ tell it the ground moved.
91
+ """
92
+ msgs = A.urgent_messages(cfg["root"], cfg)
93
+ if not msgs:
94
+ return msgs
95
+ print(f"{C['red']}{C['b']}{'━' * 62}{C['reset']}")
96
+ print(f"{C['red']}{C['b']} {len(msgs)} URGENT message(s) from the architect, unacknowledged"
97
+ f"{C['reset']}")
98
+ for m in msgs:
99
+ print(f"{C['red']} ·{C['reset']} {C['b']}{A.shown_text(m['title'])}{C['reset']}")
100
+ print(f" {C['dim']}{A.shown_text(m['id'])}{C['reset']}")
101
+ print(f"{C['dim']} Read them (polyctl_inbox, or the file) and acknowledge before "
102
+ f"continuing.{C['reset']}")
103
+ print(f"{C['red']}{C['b']}{'━' * 62}{C['reset']}\n")
104
+ # Flush before returning. The caller is about to hand the terminal to a
105
+ # subprocess writing straight to the fd, and buffered output would surface
106
+ # *after* the thing it was warning about — a warning nobody can act on.
107
+ sys.stdout.flush()
108
+ return msgs
109
+
110
+
111
+ def cmd_lock(cfg, args):
112
+ """Run a heavy command under the machine-wide lock.
113
+
114
+ `polyctl verify` already serialises its own runs, but the implementer does not go
115
+ through `polyctl verify` — it runs `npm test` directly, as it should. So the lock
116
+ covered the architect's measurements and not the thing they were competing
117
+ with, which is the collision that actually happens.
118
+
119
+ Wrapping is the fix, and it generalises past tests: a container build, a
120
+ database restore, an integration environment. Anything that saturates a
121
+ shared machine belongs behind one lock, or the machine is not shared, it is
122
+ contended.
123
+
124
+ polyctl lock -- npm test
125
+ polyctl lock --wait 1800 -- docker build .
126
+ """
127
+ if not args.command:
128
+ print(f"usage: {C['b']}polyctl lock -- <command>{C['reset']}")
129
+ holder = A.gate_lock_holder()
130
+ print(f" {C['dim']}holder:{C['reset']} " +
131
+ (f"{os.path.basename(holder['root'])} ({holder['minutes']}m)"
132
+ if holder else f"{C['dim']}free{C['reset']}"))
133
+ return 0
134
+ import subprocess
135
+ _urgent_banner(cfg)
136
+ if args.command and args.command[0] == "--":
137
+ args.command = args.command[1:]
138
+ if not args.command:
139
+ print("nothing to run")
140
+ return 0
141
+ root = cfg["root"]
142
+ command = list(args.command)
143
+ if not os.path.dirname(command[0]):
144
+ # Named without a directory, the program is the one PATH holds, never one the current directory holds,
145
+ # which Windows looks in first (WINDOWS-NO-CWD-EXEC); one named by its path is that file, as before.
146
+ program = A.program_path(command[0])
147
+ if program is None:
148
+ print(f"{C['red']}{command[0]} is not on PATH{C['reset']}: name it by its path to run it")
149
+ return 127
150
+ command[0] = program
151
+ holder = A.gate_lock_holder()
152
+ if holder and holder.get("root") != root:
153
+ print(f"{C['yellow']}{os.path.basename(holder['root'])} holds the machine lock"
154
+ f"{C['reset']} {C['dim']}({holder['minutes']}m){C['reset']} — waiting up to "
155
+ f"{args.wait}s", flush=True)
156
+ if not A.acquire_gate_lock(root, args.wait):
157
+ print(f"{C['red']}machine still busy after {args.wait}s; not starting{C['reset']}")
158
+ return 2
159
+ try:
160
+ if not _machine_has_room(cfg, args.wait, "the command"): # memory, paging and disk (MACHINE-PRESSURE)
161
+ return 2
162
+ return subprocess.run(command, cwd=root).returncode
163
+ finally:
164
+ A.release_gate_lock()
165
+
166
+
167
+ def _credits_account_line(api, acct):
168
+ """One adapter's account reading, in a line: its plan, what it used and its reset (CREDITS-ALL).
169
+
170
+ A response that omits usage or the limit is no balance: coercing a missing field to zero prints
171
+ `0.00 of 0 (0.0%)` for a figure polyctl never read (CREDITS-ALL).
172
+ """
173
+ from datetime import datetime
174
+ if acct is None:
175
+ return f"{C['dim']}the account: no token available{C['reset']}"
176
+ if acct.get("expired"):
177
+ login = " ".join(api.get("login") or []) or "the CLI's login"
178
+ return f"{C['yellow']}the account: the CLI's token has expired; run {login}{C['reset']}"
179
+ if acct.get("error"):
180
+ return f"{C['yellow']}the account: lookup failed — {acct['error']}{C['reset']}"
181
+ used, limit = acct.get("used"), acct.get("limit")
182
+ has_used = (isinstance(used, (int, float)) and not isinstance(used, bool)
183
+ and used == used and 0 <= used < float("inf"))
184
+ has_limit = (isinstance(limit, (int, float)) and not isinstance(limit, bool)
185
+ and limit == limit and 0 < limit < float("inf"))
186
+ missing = [name for name, ok in (("usage", has_used), ("limit", has_limit)) if not ok]
187
+ if missing:
188
+ return f"{C['yellow']}the account: reading unavailable — no {' or '.join(missing)} in response{C['reset']}"
189
+ reset = "no reset date in response"
190
+ reset_at = acct.get("reset_at")
191
+ if isinstance(reset_at, (int, float)) and not isinstance(reset_at, bool) and 0 < reset_at < float("inf"):
192
+ try:
193
+ reset = f"resets {C['b']}{datetime.fromtimestamp(reset_at).strftime('%d %b')}{C['reset']}"
194
+ except (OSError, OverflowError, ValueError):
195
+ pass
196
+ return (f"{C['b']}{acct.get('plan') or 'account'}{C['reset']} · {used:,.2f} of {limit:,.0f} "
197
+ f"({used / limit * 100:.1f}%) · {reset}")
198
+
199
+
200
+ def _credits_all(cfg, args):
201
+ """Every shipped adapter's account and local estimate, one block each (CREDITS-ALL).
202
+
203
+ A lookup is asked only where the adapter declares one polyctl has a driver for, one request each;
204
+ an adapter that declares none is named with the rest, never shown another harness's figure or
205
+ a zero. The local estimate is read where the adapter declares its transcripts, and `--offline`
206
+ asks nothing. The adapters are the package's: a lookup runs the command its adapter names, and
207
+ a layer an agent can write must not name that command.
208
+ """
209
+ from datetime import date, timedelta
210
+ today = date.today()
211
+ first = today.replace(day=1).isoformat()
212
+ last = ((today.replace(day=28) + timedelta(days=4)).replace(day=1) - timedelta(days=1)).isoformat()
213
+ readable, silent = [], []
214
+ for ident, adapter in sorted(A.package_adapters().items()):
215
+ api = A.usage_api(ident)
216
+ fallback = (adapter.get("billing") or {}).get("fallback") or {}
217
+ if api or fallback.get("transcripts"):
218
+ readable.append((ident, api, fallback))
219
+ else:
220
+ silent.append(ident)
221
+ print(f"{C['b']}polyctl credits --all{C['reset']} {C['dim']}— every account polyctl can read, and this machine's "
222
+ f"estimate{C['reset']}")
223
+ for ident, api, fallback in readable:
224
+ print(f"\n{C['b']}{ident}{C['reset']}")
225
+ if not api:
226
+ print(f" {C['dim']}the account: {_no_account(ident)}{C['reset']}")
227
+ elif args.offline:
228
+ print(f" {C['dim']}the account: not asked (--offline){C['reset']}")
229
+ else:
230
+ print(" " + _credits_account_line(api, A.account_usage(adapter_id=ident)))
231
+ if not fallback.get("transcripts"):
232
+ print(f" {C['dim']}this machine: no transcript estimate declared{C['reset']}")
233
+ continue
234
+ u = A.credit_usage(adapter_id=ident)
235
+ # Only records inside the current calendar month, bounded on both ends: a record dated after
236
+ # the month is named with the earlier ones as left out, never added into this month (CREDITS-ALL).
237
+ here = [v for d, v in u["days"].items() if first <= d <= last]
238
+ outside = sorted(d for d in u["days"] if not (first <= d <= last))
239
+ named = ", ".join(outside) if len(outside) <= 5 else f"{outside[0]}..{outside[-1]}"
240
+ left = f"; {len(outside)} day(s) outside {first[:7]} left out ({named})" if outside else ""
241
+ if here:
242
+ print(f" {C['dim']}this machine, {first[:7]}: {sum(here):,.2f} on {len(here)} day(s){left}{C['reset']}")
243
+ else:
244
+ print(f" {C['dim']}this machine: no usage records this month{left}{C['reset']}")
245
+ if silent:
246
+ print(f"\n{C['dim']}no account polyctl can read, and no local estimate declared: {', '.join(silent)}"
247
+ f"{C['reset']}")
248
+ return 0
249
+
250
+
251
+ def cmd_credits(cfg, args):
252
+ """Credit usage: the provider's own figure, with a local estimate behind it.
253
+
254
+ Prefer the account. `GetUsageLimits` returns exactly what the dashboard shows,
255
+ authenticated with the token the CLI already holds, so there is no reason to
256
+ estimate when the real number is one request away. The transcript reading
257
+ stays as the offline path and is labelled as the floor it is, because it
258
+ cannot see what ran on another machine. The two thirds of the true figure it
259
+ was once measured at came from reading usage records as running totals, a
260
+ reading that comes to 79% of what this machine's records add up to; the sum
261
+ they are read as now has not been measured against the account.
262
+
263
+ The account and the estimate are the implementer's own: the ones its adapter declares
264
+ (ACCOUNT-READERS). The first shipped adapter's were read whatever the implementer ran,
265
+ so an implementer on a harness that bills no account polyctl can read was shown one it never
266
+ spends. It is told it has none, and shown no other harness's figure. With `--all`,
267
+ every shipped adapter that declares a lookup or its transcripts is read, one block each,
268
+ and the rest are named: what another harness bills is readable only where it says so.
269
+ """
270
+ if getattr(args, "all", False):
271
+ return _credits_all(cfg, args)
272
+ from datetime import date, datetime
273
+
274
+ ident = A.implementer_adapter_id(cfg)
275
+ api = A.usage_api(ident)
276
+ acct = None if args.offline or not api else A.account_usage(adapter_id=ident)
277
+ if acct and not acct.get("error") and not acct.get("expired"):
278
+ used, limit = acct["used"], acct["limit"]
279
+ pct = used / limit * 100 if limit else 0
280
+ col = C["red"] if pct > 90 else C["yellow"] if pct > 70 else C["green"]
281
+ filled = int(pct / 5)
282
+ reset = datetime.fromtimestamp(acct["reset_at"]).strftime("%d %b") if acct.get("reset_at") else "?"
283
+ print(f"{C['b']}{acct.get('plan') or 'account'}{C['reset']}"
284
+ f"{C['dim']} resets {reset}{C['reset']}")
285
+ print(f"\n {col}{'█' * filled}{'░' * (20 - filled)}{C['reset']} {pct:5.1f}%"
286
+ f" {C['b']}{used:,.2f}{C['reset']} of {limit:,.0f}")
287
+ print(f" {C['b']}{limit - used:,.2f}{C['reset']} remaining")
288
+ # Whose spend this is: the whole account's, with polyctl's transcript share beside it (#95).
289
+ for line in _account_beside_share(cfg, acct=acct)[1:]:
290
+ print(f" {line}")
291
+ if acct.get("overage_status") == "DISABLED":
292
+ print(f"\n {C['dim']}overage disabled — work stops at the limit, it does not "
293
+ f"bill on{C['reset']}")
294
+ elif acct.get("overage_cap"):
295
+ print(f"\n {C['dim']}overage {acct['overage_now']:,.2f} of "
296
+ f"{acct['overage_cap']:,.0f} at {acct.get('overage_rate')}/credit{C['reset']}")
297
+
298
+ if args.local:
299
+ u = A.credit_usage(adapter_id=ident)
300
+ month = date.today().replace(day=1).isoformat()
301
+ here = sum(v for d, v in u["days"].items() if d >= month)
302
+ print(f"\n {C['dim']}local transcript estimate, calendar month {month[:7]}: "
303
+ f"{here:,.0f}{C['reset']}")
304
+ return 0
305
+
306
+ if not api:
307
+ print(f"{C['dim']}the account: {_no_account(ident)}{C['reset']}")
308
+ elif acct and acct.get("expired"):
309
+ login = " ".join(api.get("login") or []) or "the CLI's login"
310
+ print(f"{C['yellow']}The CLI's token has expired.{C['reset']} "
311
+ f"Run {C['b']}{login}{C['reset']} and try again.")
312
+ elif acct and acct.get("error"):
313
+ print(f"{C['yellow']}Account lookup failed:{C['reset']} {acct['error']}")
314
+ elif not args.offline:
315
+ print(f"{C['dim']}No account token available; falling back to transcripts.{C['reset']}")
316
+
317
+ u = A.credit_usage(adapter_id=ident)
318
+ if not u["days"]:
319
+ if not api:
320
+ return 0 # nothing to read, and the line above says so
321
+ print(f"{C['dim']}No local sessions with usage records either.{C['reset']}")
322
+ return 1
323
+ impl = cfg.get("implementer") or {}
324
+ adapter = A.load_adapter(impl.get("adapter", "")) if impl else {}
325
+ reset = args.reset_day or (adapter.get("billing") or {}).get("reset_day") or 1
326
+ reset = max(1, min(28, int(reset)))
327
+ periods = {}
328
+ for d, v in u["days"].items():
329
+ y, m, dd = (int(x) for x in d.split("-"))
330
+ if dd < reset:
331
+ m -= 1
332
+ if m == 0:
333
+ y, m = y - 1, 12
334
+ periods[f"{y:04d}-{m:02d}"] = periods.get(f"{y:04d}-{m:02d}", 0) + v
335
+ print(f"\n{C['b']}{C['mag']}── ESTIMATE FROM LOCAL TRANSCRIPTS {'─' * 22}{C['reset']}")
336
+ for pm in sorted(periods):
337
+ print(f" {pm} {periods[pm]:>9,.2f}")
338
+ print(f"\n{C['dim']}A floor: only sessions stored here are visible, and the account's"
339
+ f"\nown figure is the one to trust.{C['reset']}")
340
+ return 0
341
+
342
+
343
+ # What keeps the phone channel's poller running where there is no launchd, as `polyctl telegram install`, `uninstall` and
344
+ # `status` say when they refuse: only macOS has launchd (LEADS-SECRETS).
345
+ TELEGRAM_POLLER_ELSEWHERE = {
346
+ "schtasks": "Windows does not have; schedule `polyctl telegram poll` with Task Scheduler instead",
347
+ "systemd": "Linux does not have; keep `polyctl telegram poll` running as a systemd user service instead",
348
+ }
349
+
350
+
351
+ def _telegram_steps(conf):
352
+ """The steps of `polyctl telegram setup`, in the machine's language: the phone channel is the machine's
353
+ (LANGUAGE-OUTPUT)."""
354
+ print(f"{C['b']}1.{C['reset']} Telegram: {C['b']}@BotFather{C['reset']} → /newbot → token")
355
+ print(f"{C['b']}2.{C['reset']} {language.text(None, 'telegram.setup-chat')}")
356
+ # How the file is kept private is the platform's: Windows keeps no file mode (WINDOWS-SAY-WHY).
357
+ kept = language.text(None, "private-file.kept-windows" if os.name == "nt" else "private-file.kept")
358
+ print(f"{C['b']}3.{C['reset']} " + language.text(None, "telegram.setup-file", b=C["b"], reset=C["reset"],
359
+ conf=conf, kept=kept))
360
+ if os.name == "nt":
361
+ print(f" {C['dim']}{language.text(None, 'private-file.windows')}{C['reset']}")
362
+ # The poller is a launchd job: where there is no launchd it is started by hand (LEADS-SECRETS).
363
+ then = "install" if _scheduler() == "launchd" else "poll"
364
+ print(f"\n{C['b']}4.{C['reset']} {C['b']}polyctl telegram test{C['reset']} → {C['b']}polyctl telegram {then}{C['reset']}")
365
+ print(f"\n{C['dim']}The allowlist is not optional: an inbound channel without one")
366
+ print(f"is an authority surface open to whoever finds the bot.{C['reset']}")
367
+
368
+
369
+ def _telegram_setup(args):
370
+ """`polyctl telegram setup`: its steps, then the bot token asked at the terminal and not shown, and the file polyctl writes.
371
+
372
+ The steps had a person put the token into a curl command line - on Windows a PowerShell one - to find their
373
+ chat id, then echo the file into ~/.polyctl and chmod it: the shell's history and the process list kept the token,
374
+ and anyone on the machine could read the file until the chmod. polyctl asks for the token now, as `polyctl email setup`
375
+ asks for an account's password (EMAIL-SETUP-PROMPT), finds the chats that wrote to the bot with it, and writes
376
+ the file itself, 0600 from its creation (LEADS-SECRETS).
377
+ """
378
+ from . import telegram
379
+ token_env = getattr(args, "token_env", None)
380
+ chats = list(dict.fromkeys(getattr(args, "chat", None) or []))
381
+ at_terminal = sys.stdin.isatty()
382
+ if not token_env and not chats:
383
+ _telegram_steps(telegram.CONF)
384
+ if not at_terminal:
385
+ print("\n" + language.text(None, "telegram.setup-no-terminal"))
386
+ return 0
387
+ print()
388
+ if token_env:
389
+ # Read once from the environment, for a script: a token on a command line stays in the shell's history.
390
+ token = os.environ.get(token_env)
391
+ if not token:
392
+ print(f"{C['red']}not saved{C['reset']}: ${token_env} is {'empty' if token == '' else 'not set'}")
393
+ return 2
394
+ elif not at_terminal:
395
+ print(f"{C['red']}not saved{C['reset']}: the bot token is asked at a terminal, and none is attached; "
396
+ "--token-env names a variable that holds it")
397
+ return 2
398
+ else:
399
+ token = _hidden_input("bot token (not shown): ")
400
+ if token is None:
401
+ print(f"{C['red']}not saved{C['reset']}: this terminal cannot hide what is typed, and a token typed here "
402
+ "would stand in its scrollback; --token-env names a variable that holds it")
403
+ return 2
404
+ token = token.strip()
405
+ if not token:
406
+ print(f"{C['red']}not saved{C['reset']}: no token was given"); return 2
407
+ if not telegram.TOKEN_SHAPE.fullmatch(token):
408
+ print(f"{C['red']}not saved{C['reset']}: that is no bot token; @BotFather gives one as the bot's number, a "
409
+ "colon, then letters and digits")
410
+ return 2
411
+ if not chats:
412
+ found, why = telegram.recent_chats(token)
413
+ if found is None:
414
+ print(f"{C['red']}not saved{C['reset']}: Telegram did not say which chats wrote to the bot ({why}); "
415
+ "check the token with @BotFather, or name the chats it allows with --chat")
416
+ return 2
417
+ if found:
418
+ print("chats that wrote to the bot:")
419
+ for chat, name in found.items():
420
+ print(f" {chat:>14} {name}")
421
+ else:
422
+ print(f"{C['yellow']}no chat wrote to the bot in the last 24 hours{C['reset']}: write it a message, "
423
+ "then run this again, or name a chat whose id you know")
424
+ if not at_terminal:
425
+ print(f"{C['red']}not saved{C['reset']}: name the chats it allows with --chat"); return 2
426
+ typed = input("chats it allows, their ids separated by spaces: ")
427
+ chats = list(dict.fromkeys(typed.replace(",", " ").split()))
428
+ wrong = [chat for chat in chats if not telegram.CHAT_SHAPE.fullmatch(chat)]
429
+ if wrong:
430
+ print(f"{C['red']}not saved{C['reset']}: a chat id is a number, as Telegram gives it: {', '.join(wrong)}")
431
+ return 2
432
+ if not chats:
433
+ print(f"{C['red']}not saved{C['reset']}: no chat was allowed, and the allowlist is not optional")
434
+ return 2
435
+ telegram.save(token, chats)
436
+ print(f"{C['green']}saved{C['reset']} {telegram.CONF} ({_private_mode()}): {len(chats)} chat(s) allowed")
437
+ print(f"now: {C['b']}polyctl telegram test{C['reset']}")
438
+ return 0
439
+
440
+
441
+ def _hidden_input(prompt):
442
+ """What a person types at `prompt` with nothing shown, or None where this terminal cannot hide it.
443
+
444
+ getpass falls back to reading the line as typed, echo on, where it cannot turn a terminal's echo off - a terminal
445
+ emulator that refuses it, a pipe that passes for a terminal - and says so only in a warning: a token or a password
446
+ typed there stood in the terminal's scrollback and in whatever recorded the session (LEADS-SECRETS). Its warning is
447
+ taken as the refusal it is, before anything is read.
448
+ """
449
+ import getpass
450
+ import warnings
451
+ with warnings.catch_warnings():
452
+ warnings.simplefilter("error", getpass.GetPassWarning)
453
+ try:
454
+ return getpass.getpass(prompt)
455
+ except getpass.GetPassWarning:
456
+ return None
457
+
458
+
459
+ def cmd_telegram(cfg, args):
460
+ """Set up, test, or run the phone channel.
461
+
462
+ The inbound direction is the reason this exists. When the architect's quota
463
+ runs out everything stops — twice in one day here — and a person who can write
464
+ a decision from a phone at that moment keeps it moving. Their message becomes
465
+ an urgent file in the mailbox, which is what the architect's own decisions
466
+ already are.
467
+ """
468
+ from . import telegram
469
+ conf = telegram.CONF
470
+ c = telegram.config()
471
+ label = _launchd_label("telegram", A.project_key(cfg["root"]))
472
+
473
+ if args.action == "setup":
474
+ return _telegram_setup(args)
475
+
476
+ if args.action == "test":
477
+ if not c:
478
+ print(f"{C['red']}No config at {conf}{C['reset']} — run {C['b']}polyctl telegram setup{C['reset']}")
479
+ return 1
480
+ name = cfg.get("project") or os.path.basename(cfg["root"])
481
+ n = telegram.send(language.text(cfg, "telegram.test", name=name), cfg["root"])
482
+ print(f"{C['green']}sent to {n} chat(s){C['reset']}" if n else
483
+ f"{C['red']}send failed{C['reset']} — check the token and the chat ids")
484
+ return 0 if n else 1
485
+
486
+ if args.action == "poll":
487
+ return _serve("telegram", cfg, ["--once"] if args.once else [])
488
+
489
+ scheduler = _scheduler()
490
+ if scheduler != "launchd" and args.action in ("install", "uninstall", "status"):
491
+ # The poller is a launchd job, and only macOS has launchd. On Windows these printed success and did nothing
492
+ # (#71); on Linux install wrote into a ~/Library/LaunchAgents that is not there and asked for launchctl,
493
+ # uninstall said it had removed the job, and status sent the person to install (LEADS-SECRETS).
494
+ print(f"{C['yellow']}refused{C['reset']}: the telegram poller is scheduled with launchd, which "
495
+ + TELEGRAM_POLLER_ELSEWHERE.get(scheduler, f"{sys.platform} does not have; keep `polyctl telegram poll` "
496
+ "running with its own service manager instead"))
497
+ return 1
498
+
499
+ if args.action == "uninstall":
500
+ _launchctl("bootout", _launchd_domain(label))
501
+ p = os.path.join(A.HOME, "Library", "LaunchAgents", label + ".plist")
502
+ if os.path.exists(p):
503
+ os.remove(p)
504
+ print(f"removed {label}")
505
+ return 0
506
+
507
+ if args.action == "install":
508
+ if not c:
509
+ print(f"{C['red']}No config{C['reset']} — run polyctl telegram setup first")
510
+ return 1
511
+ # The program is one a scheduler can start, as the watchdog's jobs name theirs: never this process's
512
+ # argv[0], which under `python -m polyctl` is a module file launchd cannot run (SAFE-REMOVE-2).
513
+ argv = _scheduled_argv("polyctl", ("bin", "polyctl"), "polyctl")
514
+ if argv is None:
515
+ return _schedule_refused(["polyctl"])
516
+ log = os.path.join(A.HOME, ".polyctl", A.project_file_name("telegram-log", A.project_key(cfg["root"]).lower()))
517
+ # KeepAlive rather than StartInterval: long polling holds the connection
518
+ # open, so the job wants restarting when it ends, not running on a clock.
519
+ plist = os.path.join(A.HOME, "Library", "LaunchAgents", label + ".plist")
520
+ open(plist, "w", encoding=UTF8).write(
521
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
522
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" '
523
+ '"http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
524
+ '<plist version="1.0"><dict>\n'
525
+ f' <key>Label</key><string>{label}</string>\n'
526
+ ' <key>ProgramArguments</key>\n'
527
+ f' <array>{"".join(f"<string>{word}</string>" for word in argv)}<string>-C</string>'
528
+ f'<string>{cfg["root"]}</string>\n'
529
+ ' <string>telegram</string><string>poll</string></array>\n'
530
+ f' <key>EnvironmentVariables</key><dict><key>PATH</key><string>{_launchd_path()}</string></dict>\n'
531
+ ' <key>KeepAlive</key><true/>\n <key>RunAtLoad</key><true/>\n'
532
+ f' <key>StandardOutPath</key><string>{log}</string>\n'
533
+ f' <key>StandardErrorPath</key><string>{log}</string>\n'
534
+ '</dict></plist>\n')
535
+ _launchctl("bootout", _launchd_domain(label))
536
+ _launchctl("bootstrap", _launchd_domain(), plist, merge=True)
537
+ print(f"{C['green']}installed{C['reset']} {label}")
538
+ return 0
539
+
540
+ print("config " + (f"{C['green']}{conf}{C['reset']}" if c else
541
+ f"{C['red']}missing{C['reset']} — polyctl telegram setup"))
542
+ if c:
543
+ print(f"chats allowed {len(c['chats'])}")
544
+ print("poller " + (f"{C['green']}running{C['reset']}"
545
+ if _launchd_listed(label) else
546
+ f"{C['dim']}not installed — polyctl telegram install{C['reset']}"))
547
+ return 0
548
+
549
+
550
+ def cmd_ntfy(cfg, args):
551
+ """Outbound phone channel via ntfy (ntfy.sh or a self-hosted ntfy server)."""
552
+ from . import ntfy
553
+ if args.action == "setup":
554
+ if getattr(args, "token", None) is not None:
555
+ print(f"{C['red']}not saved{C['reset']}: an access token on a command line stays in the shell's history "
556
+ "and the process list; name the variable that holds it with --token-env NAME")
557
+ return 2
558
+ topic_url = getattr(args, "topic_url", None)
559
+ token_env = getattr(args, "token_env", None)
560
+ if not topic_url:
561
+ if token_env:
562
+ print(f"{C['red']}not saved{C['reset']}: setup needs --topic-url URL")
563
+ return 2
564
+ print(language.text(None, "ntfy.setup", conf=ntfy.CONF,
565
+ kept=language.text(None, "private-file.kept-windows" if os.name == "nt"
566
+ else "private-file.kept")))
567
+ return 0
568
+ token = None
569
+ if token_env:
570
+ # Read once from the environment: an access token is never passed on a command line or printed.
571
+ raw = os.environ.get(token_env)
572
+ if not raw or not raw.strip():
573
+ print(f"{C['red']}not saved{C['reset']}: ${token_env} is "
574
+ f"{'empty' if raw is not None else 'not set'}")
575
+ return 2
576
+ token = raw.strip()
577
+ try:
578
+ c = ntfy.save(topic_url, token=token)
579
+ except ValueError as exc:
580
+ print(f"{C['red']}not saved{C['reset']}: {exc}")
581
+ return 2
582
+ print(f"{C['green']}saved{C['reset']} {ntfy.CONF} ({_private_mode()}) host={ntfy.host(c)}"
583
+ + (" (token set)" if c.get("token") else ""))
584
+ print(f"now: {C['b']}polyctl ntfy test{C['reset']}")
585
+ return 0
586
+ c = ntfy.config()
587
+ if args.action == "test":
588
+ if not c:
589
+ print(f"{C['red']}not configured{C['reset']} — polyctl ntfy setup")
590
+ return 1
591
+ name = cfg.get("project") or os.path.basename(cfg["root"])
592
+ ok = ntfy.send(language.text(cfg, "ntfy.test", name=name), cfg["root"])
593
+ print(f"{C['green']}sent{C['reset']}" if ok else
594
+ f"{C['red']}send failed{C['reset']} — check the topic URL and token")
595
+ return 0 if ok else 1
596
+ if not c:
597
+ print(f"{C['yellow']}not configured{C['reset']} — polyctl ntfy setup")
598
+ return 1
599
+ auth = "token=set" if c.get("token") else "token=none"
600
+ print(f"{C['green']}configured{C['reset']} host={ntfy.host(c)} {auth} file={ntfy.CONF}")
601
+ return 0
602
+
603
+
604
+ def _decision_text(rec, cfg=None):
605
+ """A decision as the phone shows it, worded in the project's language (LANGUAGE-OUTPUT).
606
+
607
+ `cfg` is the project's config, and without one the machine's choice is read. The keys, and the
608
+ reply typed with them, are the same in either language.
609
+ """
610
+ lines = [f"❓ *{rec['question']}*"]
611
+ if rec.get("context"):
612
+ lines.append(f"\n_{rec['context']}_")
613
+ if rec.get("slice"):
614
+ lines.append("\n" + language.text(cfg, "decision.slice", slice=rec["slice"]))
615
+ for found in rec.get("precedents") or []:
616
+ lines.append("\n" + language.text(cfg, "decision.precedent", project=found["project"], kind=found["kind"],
617
+ id=found["id"], outcome=found["outcome"]))
618
+ lines.append("")
619
+ for o in rec["options"]:
620
+ lines.append(f"*{o['key']})* {o['label']}")
621
+ lines.append("\n" + language.text(cfg, "decision.answer", id=rec["id"]))
622
+ return "\n".join(lines)
623
+
624
+
625
+ def _phone_decision(rec, cfg):
626
+ """Send a decision to the phone, a button for each option not answered in words; how many chats got it.
627
+
628
+ `polyctl ask`, `polyctl propose` and their MCP tools send it the same way. It raises what the phone
629
+ channel raises, and each caller catches it: the question is recorded whether or not a phone
630
+ hears of it.
631
+ """
632
+ from . import telegram
633
+ keyboard = [[{"text": f"{o['key']}) {o['label'][:40]}", "callback_data": f"{rec['id']}:{o['key']}"}]
634
+ for o in rec["options"] if not o.get("free_text")]
635
+ return telegram.send(_decision_text(rec, cfg), cfg["root"], keyboard=keyboard)
636
+
637
+
638
+ def cmd_recall(cfg, args):
639
+ """What was decided, found or learned before, in every project on this machine (#43)."""
640
+ results = A.recall(" ".join(args.text), cfg["root"], limit=args.limit)
641
+ if not results:
642
+ print(f"{C['dim']}nothing recorded shares those words{C['reset']}")
643
+ return 1
644
+ for found in results:
645
+ when = time.strftime("%Y-%m-%d", time.localtime(found["at"])) if found.get("at") else "—"
646
+ text = " ".join(str(found["text"]).split())
647
+ print(f"{C['b']}{found['project']}{C['reset']} {when} {found['kind']} {found['id']} "
648
+ f"{C['dim']}{found['outcome']}{C['reset']}")
649
+ print(f" {text[:160]}{'…' if len(text) > 160 else ''}")
650
+ print(f" {C['dim']}{found['source']}{C['reset']}")
651
+ return 0
652
+
653
+
654
+ def cmd_stats(cfg, args):
655
+ """Slice outcomes across projects, so a process change is judged by what happened (#49)."""
656
+ roots = A.recall_roots(cfg["root"]) if getattr(args, "all", False) else [(A.project_key(cfg["root"]), cfg["root"])]
657
+ # A When from the command line, or text from any other caller, read by the one time syntax (CLI-ROBUST).
658
+ since = A.parse_time(args.since).moment() if getattr(args, "since", None) else None
659
+ until = A.parse_time(args.until).moment() if getattr(args, "until", None) else None
660
+ outcomes = []
661
+ for project, path in roots:
662
+ try:
663
+ outcomes += [o for o in A.slice_outcomes(path, project)
664
+ if (since is None or (o["landed_at"] or 0) >= since)
665
+ and (until is None or (o["landed_at"] or 0) < until)]
666
+ except (OSError, ValueError, RuntimeError) as exc:
667
+ print(f"{project}: cannot read outcomes: {exc}; repair this project's evidence before comparing it")
668
+ if not outcomes:
669
+ print(f"{C['dim']}no landed slice with a recorded grant in this window{C['reset']}")
670
+ return 1
671
+ stats = A.outcome_stats(outcomes)
672
+
673
+ def show(label, spread, unit=""):
674
+ if spread:
675
+ print(f" {label:<22} median {spread['median']}{unit}, p90 {spread['p90']}{unit} "
676
+ f"{C['dim']}({spread['n']} slices){C['reset']}")
677
+
678
+ projects = sorted({o["project"] for o in outcomes})
679
+ print(f"{C['b']}{stats['slices']} slices landed{C['reset']} {C['dim']}{', '.join(projects)}"
680
+ f"{' · ' + str(stats['waived']) + ' with review waived' if stats['waived'] else ''}{C['reset']}")
681
+ # A slice that landed on a weaker tier is counted under its label, never mixed into the rest (REVIEW-TIERS).
682
+ from . import tiers as T
683
+ for tier, count in (stats.get("tiers") or {}).items():
684
+ if T.weaker(tier):
685
+ print(f" {'review tier':<22} {count} slice(s) on {C['yellow']}{T.label(tier)}{C['reset']}")
686
+ show("review rounds", stats["rounds"])
687
+ if stats["first_pass_pct"] is not None:
688
+ print(f" {'approved first time':<22} {stats['first_pass_pct']}%")
689
+ show("ready to landed", stats["hours"], "h")
690
+ show("product lines", stats["product_lines"])
691
+ print(f" {'defect found later':<22} {stats['defects_pct']}%")
692
+ if getattr(args, "slices", False):
693
+ for o in outcomes:
694
+ print(f" {o['project']:<14} {o['slice']:<16} {' → '.join(o['verdicts']) or 'waived'}"
695
+ f"{' ' + T.label(o.get('tier')) if T.weaker(o.get('tier')) else ''}"
696
+ f"{' defect found later' if o['defect_found'] else ''}")
697
+ return 0
698
+
699
+
700
+ def cmd_role(cfg, args):
701
+ """Show the role table, or reassign a role; separation of duties is enforced on assignment (#79)."""
702
+ root = cfg["root"]
703
+ try:
704
+ with open(os.path.join(root, ".polyctl", "config.json"), encoding=UTF8) as fh:
705
+ stored = json.load(fh)
706
+ except (OSError, ValueError):
707
+ stored = {}
708
+ actors, roles, _ = A.role_table(stored or cfg)
709
+ # An assignment made while a slice ran holds once that slice has left running, and waits until
710
+ # then. The table shows what holds, a new assignment is checked against what will hold, and it
711
+ # joins the one that waits: replacing it dropped a reviewer nobody had reassigned (OCT1-FIXES).
712
+ held = A.effective_roles(root, dict(stored or cfg, roles=roles))
713
+ waiting, after = A.pending_roles(root, stored or cfg)
714
+ action = getattr(args, "action", None) or "show"
715
+ if action == "show":
716
+ for role in A.ROLE_BLOCKS:
717
+ actor = held.get(role)
718
+ block = actors.get(actor) or {}
719
+ detail = " · ".join(str(block[key]) for key in ("adapter", "model", "family") if block.get(key))
720
+ print(f" {role:<12} {C['b']}{actor or '—'}{C['reset']} {C['dim']}{detail}{C['reset']}")
721
+ if waiting:
722
+ print(f" {C['yellow']}next{C['reset']} {waiting} once {after} leaves running")
723
+ return 0
724
+ eventual = dict(held, **waiting)
725
+ new = dict(eventual)
726
+ if action == "set" and args.role == "reviewer" and args.actor not in actors \
727
+ and A.load_adapter(args.actor, root):
728
+ # Name an adapter and a model: the reviewer's invocation is composed from it (#88).
729
+ family = getattr(args, "family", None)
730
+ if A.tool_review_contract(A.load_adapter(args.actor, root)) is not None and getattr(args, "model", None) \
731
+ and not family:
732
+ # A tool reviewer reaches many model families, and a model name is not a family (#86).
733
+ print(f"{C['red']}refused{C['reset']}: {args.actor} runs whichever model it is given; name that "
734
+ "model's family with --family, so independence from the implementer can be checked")
735
+ return 2
736
+ try:
737
+ route = A.compose_reviewer(args.actor, getattr(args, "model", None), getattr(args, "effort", None), root,
738
+ family=family)
739
+ except ValueError as exc:
740
+ print(f"{C['red']}refused{C['reset']}: {exc}")
741
+ return 2
742
+ actors[route["id"]] = route
743
+ args.actor = route["id"]
744
+ if action == "set":
745
+ if args.actor not in actors:
746
+ print(f"{C['red']}no actor {args.actor}{C['reset']}; actors: {', '.join(sorted(actors))}")
747
+ return 2
748
+ new[args.role] = args.actor
749
+ else:
750
+ # A swap names two different roles: with the second left out, or an actor's name in its place, a
751
+ # role of no name was written into the table and the one named was left empty (ROLE-TABLE-2).
752
+ if args.role not in A.ROLE_BLOCKS or args.actor not in A.ROLE_BLOCKS or args.actor == args.role:
753
+ print(f"{C['red']}refused{C['reset']}: polyctl role swap names two different roles of "
754
+ f"{', '.join(A.ROLE_BLOCKS)}")
755
+ return 2
756
+ new[args.role], new[args.actor] = eventual.get(args.actor), eventual.get(args.role)
757
+ problem = A.assignment_problem(actors, new, S.get(cfg, "repository.kind"), getattr(args, "hotfix", False))
758
+ if problem:
759
+ print(f"{C['red']}refused{C['reset']}: {problem}")
760
+ return 2
761
+ # The reviewer that will hold the role is asked what `polyctl review` and the probe ask, and refused
762
+ # in their words: `polyctl role set` assigned reviewers they then refused (REVIEW-TIERS).
763
+ from . import tiers as T
764
+ trial = dict(cfg)
765
+ for role in ("implementer", "reviewer"):
766
+ if isinstance(actors.get(new.get(role)), dict):
767
+ trial[role] = dict(actors[new[role]], actor=new[role])
768
+ reviewer = actors.get(new.get("reviewer"))
769
+ tier, code, refused = _review_decision(trial, trial["reviewer"]) \
770
+ if isinstance(reviewer, dict) and reviewer.get("argv") else (None, None, None)
771
+ if refused:
772
+ touched = {role for role in A.ROLE_BLOCKS if new.get(role) != eventual.get(role)}
773
+ # A reviewer being assigned is refused whatever the reason. A new implementer is refused, as it
774
+ # was, when both declare one family; one that shares only an engine is refused at review (#79).
775
+ if "reviewer" in touched or code.partition("/")[0] == "family":
776
+ print(f"{C['red']}refused{C['reset']}: {_tier_refusal(refused)}")
777
+ return 2
778
+ print(f"{C['yellow']}note{C['reset']}: {_tier_refusal(refused)}")
779
+ stored = dict(stored, actors=actors)
780
+ running = A.running_slice(root)
781
+ changed = {role: actor for role, actor in new.items() if held.get(role) != actor}
782
+ tiered = f"; the reviewer stands in {T.label(tier)}" if T.weaker(tier) else ""
783
+ if running:
784
+ # Work in flight keeps its actor; the next slice gets the new one.
785
+ stored.update(roles=held, roles_next={"after": running["id"], "roles": changed})
786
+ print(f"takes effect once {running['id']} leaves running: {changed}{tiered}")
787
+ else:
788
+ stored.update(roles=new)
789
+ stored.pop("roles_next", None)
790
+ print(f"assigned: {changed}{tiered}")
791
+ A.write_project_config(root, json.dumps(stored, indent=2, ensure_ascii=False) + "\n")
792
+ # A reassigned role's command is a change nobody has seen, as any write to the configuration is, so a person reads
793
+ # it before a turn or a review starts it (TURN-ARGV, ROUTE-ARGV).
794
+ print(f"{C['dim']}a turn or a review starts a reassigned role's command once a person has read it: "
795
+ f"polyctl harness seen --by <name>{C['reset']}")
796
+ return 0
797
+
798
+
799
+ def _hunter_reading_problems(argv):
800
+ """What keeps a hunter's command from being one that only reads, by the rule a reviewer meets (BUG-HUNTER-2).
801
+
802
+ A reviewer is composed from a harness polyctl ships that declares how it runs without tools, with
803
+ those flags; a hunter's command is written by hand. `reviewer_problems` passed a program no
804
+ adapter declares - `sh -c` rewrote a file - and a harness in a writing mode, such as
805
+ `codex exec -s workspace-write`. So the command must run a harness polyctl ships, one able to
806
+ review, with every flag its `options.trust_none` names (`A.reading_problems`), as a reviewer's
807
+ route must where a review starts it (REVIEWER-REACH-2).
808
+ """
809
+ return A.reading_problems(argv)
810
+
811
+
812
+ def cmd_hunt(cfg, args):
813
+ """A scheduled, read-only bug hunt over a bounded slice of the tree; leads go to the architect (#45).
814
+
815
+ It never writes to the repository, never holds or influences a grant, and never
816
+ raises a human alarm: a lead is a mail the architect triages or discards. A repeat
817
+ is suppressed by fingerprint and a discard is remembered.
818
+ """
819
+ from . import allowlist
820
+ root = cfg["root"]
821
+ action = getattr(args, "action", None) or "run"
822
+ if action == "discard":
823
+ if not getattr(args, "fingerprint", None):
824
+ print("usage: polyctl hunt discard <fingerprint>")
825
+ return 2
826
+ A.hunter_record(root, "discarded", fingerprint=args.fingerprint, by=A.invoking_role() or "person")
827
+ print(f"discarded {args.fingerprint}; it is not sent again")
828
+ return 0
829
+ if action == "status":
830
+ rows = A.hunter_rows(root)
831
+ runs = [row for row in rows if row.get("event") == "run"]
832
+ sent = sum(1 for row in rows if row.get("event") == "sent")
833
+ discarded = sum(1 for row in rows if row.get("event") == "discarded")
834
+ print(f"{len(runs)} hunt(s), {sent} lead(s) sent, {discarded} discarded"
835
+ + (f", last {time.strftime('%d %b %H:%M', time.localtime(runs[-1]['at']))}" if runs else ""))
836
+ return 0
837
+ argv = S.get(cfg, "hunter.argv")
838
+ if not argv:
839
+ print(f"{C['yellow']}no hunter configured{C['reset']}: `hunter.argv` in .polyctl/config.json, read-only, "
840
+ "a different family from the implementer where one is available")
841
+ return 2
842
+ # A hunter command no person has accepted starts nothing, judged as this run read it (ROUTE-ARGV).
843
+ A.hold_unseen_routes(root, cfg)
844
+ unseen = cfg.get("_unseen") if isinstance(cfg.get("_unseen"), dict) else {}
845
+ if unseen.get("hunter"):
846
+ print(f"{C['red']}refused{C['reset']}: {A.unseen_route_text('hunter', unseen['hunter'])}")
847
+ return 2
848
+ # The hunter is held to a reviewer's pin: the mode and the tools its adapter pins for one (GRANTS-PINNED).
849
+ argv, pinned = A.pinned_argv(argv, "reviewer")
850
+ if pinned:
851
+ print(f"{C['dim']}the hunter's command names no {' or '.join(part for part in pinned if part.startswith('-'))}; "
852
+ f"polyctl appends {' '.join(pinned)}, as its adapter pins for a reviewer{C['reset']}")
853
+ problems = allowlist.reviewer_problems(argv) + _hunter_reading_problems(argv)
854
+ if problems:
855
+ print(f"{C['red']}refused{C['reset']}: the hunter must not be able to write — {'; '.join(problems)}")
856
+ return 2
857
+ # And it runs its shipped adapter's own program, never one named from where it starts or left in this
858
+ # repository (ROUTE-ARGV).
859
+ refused = A.route_refusal("hunter", None, argv, root=root,
860
+ resolved=str(argv[0]) if os.path.isabs(str(argv[0])) else None)
861
+ if refused:
862
+ print(f"{C['red']}refused{C['reset']}: {refused}")
863
+ return 2
864
+ passed_over = []
865
+ pieces, cursor = A.hunt_slice(root, cfg, passed_over)
866
+ if passed_over:
867
+ # Said, not skipped in silence: a file this large is never read by a hunt (BUG-HUNTER-3).
868
+ print(f"{C['dim']}passed over {len(passed_over)} file(s) larger than hunter.max_file_kb "
869
+ f"({S.get(cfg, 'hunter.max_file_kb')} KB): {', '.join(A.shown_text(path) for path in passed_over)}"
870
+ f"{C['reset']}")
871
+ if not pieces:
872
+ print("nothing tracked to hunt in")
873
+ return 0
874
+ files = [(path, text) for path, text, _, _, _ in pieces]
875
+ # A piece of a file larger than one hunt says which lines it is, so a lead's line is the file's (BUG-HUNTER-3).
876
+ parts = [[path, first, last, total] for path, _, first, last, total in pieces if (first, last) != (1, total)]
877
+ # The hunter is told in the project's language, and a lead is read in one shape in either (LANGUAGE-PROMPTS).
878
+ prompt = language.text(cfg, "prompt.hunt", categories=", ".join(A.HUNT_CATEGORIES)) + "".join(
879
+ "\n--- " + (path if (first, last) == (1, total) else language.text(
880
+ cfg, "prompt.hunt-part", path=path, first=first, last=last, total=total)) + f" ---\n{text}"
881
+ for path, text, first, last, total in pieces)
882
+ # A slice of files can outgrow one argument; past that the prompt goes where the hunter's
883
+ # adapter declares, or the hunt is refused as a configuration (PROMPT-CHANNEL).
884
+ plan, refused = A.prompt_plan(argv, prompt, A.block_adapter({"argv": argv}))
885
+ if refused:
886
+ A.hunter_record(root, "run", files=[path for path, _ in files], cursor=cursor, ok=False, reason=refused,
887
+ leads=0, sent=0, hunter=S.get(cfg, "hunter.id"), **({"parts": parts} if parts else {}))
888
+ print(f"{C['red']}refused{C['reset']}: {refused}")
889
+ return 2
890
+ # Found as a reviewer's program is, on the path polyctl searches and never inside the repository: started by name, it
891
+ # was whatever the platform found first, the current directory among the places Windows looks (ROUTE-ARGV).
892
+ run = [part.replace("{prompt}", prompt) for part in plan["argv"]]
893
+ exe, _ = _reviewer_resolve_binary(root, run[0])
894
+ if exe:
895
+ run[0] = exe
896
+ result = _run_reviewer(root, run, _review_timeout(cfg), label=S.get(cfg, "hunter.id"),
897
+ **({"channel": plan} if plan["channel"] != "argument" else {}))
898
+ else:
899
+ result = {"ok": False, "out": "", "reason": f"{argv[0]} is not installed on any path polyctl searches, or only "
900
+ "inside this repository, which an agent writes"}
901
+ leads = A.parse_leads(result.get("out")) if result.get("ok") else []
902
+ # What a hunt sends is chosen, mailed and recorded sent under one lock: two hunts at once each read the
903
+ # leads already sent before either recorded its own, both sent one lead, and in the same minute the
904
+ # second wrote its mail over the first's (LEADS-OPS).
905
+ from .storage import _exclusive_lock
906
+ with _exclusive_lock(os.path.join(root, ".polyctl", "hunter.lock"), timeout=60):
907
+ known = A.hunter_known(root)
908
+ fresh = []
909
+ for lead in leads:
910
+ if lead["fingerprint"] not in known and lead["fingerprint"] not in {f["fingerprint"] for f in fresh}:
911
+ fresh.append(lead)
912
+ fresh = fresh[:S.get(cfg, "hunter.max_leads")]
913
+ A.hunter_record(root, "run", files=[path for path, _ in files], cursor=cursor, ok=bool(result.get("ok")),
914
+ reason=result.get("reason") or None, leads=len(leads), sent=len(fresh),
915
+ hunter=S.get(cfg, "hunter.id"), **({"parts": parts} if parts else {}))
916
+ if not result.get("ok"):
917
+ print(f"{C['yellow']}hunt did not run{C['reset']}: {result.get('reason')}")
918
+ return 3
919
+ if fresh:
920
+ _, architect = A.mail_names(cfg)
921
+ # The first lead's fingerprint names the mail: a second hunt in the same minute wrote over the first
922
+ # one's, and its leads, recorded as sent, were never sent again (BUG-HUNTER-2).
923
+ name = (f"{datetime.now():%Y%m%d-%H%M}-hunter-to-{architect}-LEADS-{A.safe_slug(fresh[0]['path'])}"
924
+ f"-{fresh[0]['fingerprint'][:8]}.md")
925
+ body = [f"# {len(fresh)} lead(s) from the bug hunter", "",
926
+ "Leads, not verdicts: triage each into a backlog row or discard it with `polyctl hunt discard <id>`.",
927
+ ""]
928
+ body += [f"- [{lead['category']}] {lead['path']}:{lead['line']} {lead['symbol']} — {lead['finding']} "
929
+ f"(`{lead['fingerprint']}`)" for lead in fresh]
930
+ name = A.write_mail(root, cfg, name, "\n".join(body) + "\n", {"kind": "leads", "class": "needs-read",
931
+ "from": "hunter", "to": architect})
932
+ for lead in fresh:
933
+ A.hunter_record(root, "sent", fingerprint=lead["fingerprint"], mail=name, path=lead["path"],
934
+ category=lead["category"])
935
+ print(f"hunted {len(files)} file(s): {len(leads)} lead(s), {len(fresh)} new")
936
+ return 0
937
+
938
+
939
+ def cmd_content(cfg, args):
940
+ """Borrow third-party skills, steering and agents pinned to a commit, text only; verify them (#14, #15)."""
941
+ from . import skillkit
942
+ root = cfg["root"]
943
+ if args.action == "verify":
944
+ drift = A.verify_content(root)
945
+ for line in drift:
946
+ print(f" {C['red']}·{C['reset']} {line}")
947
+ print(f"{C['green']}vendored content matches its pins{C['reset']}" if not drift else f"{len(drift)} file(s) drifted")
948
+ return 1 if drift else 0
949
+ source, _, pin = (args.spec or "").rpartition("@")
950
+ # A caller that predates steering and agents hands skills alone.
951
+ # Each read by its name: the split proof reads no attribute named at run time (#111).
952
+ given = {"skills": getattr(args, "skills", None), "steering": getattr(args, "steering", None),
953
+ "agents": getattr(args, "agents", None)}
954
+ chosen = {kind: [name.strip() for name in (given.get(kind) or "").split(",") if name.strip()]
955
+ for kind, _ in A.CONTENT_KINDS}
956
+ if not source or not any(chosen.values()):
957
+ print("usage: polyctl content add <source>@<40-character commit> [--skills a,b] [--steering c,d] [--agents e,f] "
958
+ "[--from <dir>] [--harness <adapter>,<adapter>] [--dry-run]")
959
+ return 2
960
+ harnesses = [name.strip() for name in (args.harness or "").split(",") if name.strip()] \
961
+ or sorted(skillkit.detect_agents(root)[1])
962
+ dry_run = bool(getattr(args, "dry_run", False))
963
+ try:
964
+ plan = A.vendor_content(root, source, pin, harnesses, base=getattr(args, "base", None) or "",
965
+ dry_run=dry_run, **chosen)
966
+ except (ValueError, RuntimeError, OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
967
+ print(f"{C['red']}not vendored{C['reset']}: {exc}")
968
+ return 2
969
+ written = not (dry_run or plan["refused"])
970
+ for item in plan["items"]:
971
+ print(f"{C['green'] if written else C['b']}{'vendored' if written else 'would vendor'}{C['reset']} "
972
+ f"{dict(A.CONTENT_KINDS)[item['kind']]} {item['name']}@{pin[:12]} → "
973
+ f"{', '.join(sorted(item['files'])) or 'nothing'}")
974
+ for path, why in item["skipped"]:
975
+ print(f" {C['dim']}skipped {path} ({why}){C['reset']}")
976
+ for target, why in item["unsupported"]:
977
+ print(f" {C['yellow']}unsupported {target} ({why}){C['reset']}")
978
+ for note in item["notes"]:
979
+ print(f" {C['dim']}{note}{C['reset']}")
980
+ for path, why in plan["hooks"]:
981
+ print(f"{C['dim']}skipped {path} ({why}){C['reset']}")
982
+ for why in plan["refused"]:
983
+ print(f"{C['red']}refused{C['reset']} {why}")
984
+ if plan["refused"]:
985
+ print(f"{C['red']}not vendored{C['reset']}: nothing was written")
986
+ return 2
987
+ if dry_run:
988
+ print(f"{C['dim']}dry run: nothing was written{C['reset']}")
989
+ return 0
990
+
991
+
992
+ def cmd_room(cfg, args):
993
+ """Stored messages in every registered project that mention the words (#80)."""
994
+ found = A.room_search(" ".join(args.text), cfg["root"])
995
+ for row in found:
996
+ when = time.strftime("%Y-%m-%d", time.localtime(float(row.get("at") or 0)))
997
+ print(f"{C['b']}{row['project']}{C['reset']} {when} {row['id']} "
998
+ f"{C['dim']}{row.get('from') or '?'} → {row.get('to') or '?'}{C['reset']}")
999
+ if not found:
1000
+ print(f"{C['dim']}no stored message mentions that{C['reset']}")
1001
+ return 0 if found else 1
1002
+
1003
+
1004
+ def cmd_split_check(cfg, args):
1005
+ """Is the staged candidate a pure move? Every moved definition byte for byte, nothing else changed (#44)."""
1006
+ try:
1007
+ result = A.split_moves(cfg["root"])
1008
+ except RuntimeError as exc:
1009
+ print(f"{C['red']}cannot read the candidate{C['reset']}: {exc}")
1010
+ return 2
1011
+ for name, source, target in result["moved"]:
1012
+ print(f" {C['green']}moved{C['reset']} {name} {C['dim']}{source} → {target}{C['reset']}")
1013
+ for problem in result["problems"]:
1014
+ print(f" {C['red']}·{C['reset']} {problem}")
1015
+ print(f"{C['green']}a pure move{C['reset']}: {len(result['moved'])} definition(s), byte for byte"
1016
+ if not result["problems"] else f"{C['red']}not a pure move{C['reset']}")
1017
+ return 1 if result["problems"] else 0
1018
+
1019
+
1020
+ def cmd_ask(cfg, args):
1021
+ """Pose a decision the implementer cannot make for itself.
1022
+
1023
+ A blocker written as prose costs minutes to answer from a phone. The same
1024
+ blocker as a question with options costs one tap, and that difference decides
1025
+ whether a run survives the hours when nobody is at a desk.
1026
+ """
1027
+ root = cfg["root"]
1028
+ if getattr(args, "codebase", False):
1029
+ # A question to the code goes to a provider and comes back cited, or not at all (#81).
1030
+ try:
1031
+ found = A.ask_codebase(root, cfg, args.question or "")
1032
+ except ValueError as exc:
1033
+ print(f"{C['yellow']}not answered{C['reset']}: {exc}")
1034
+ return 2
1035
+ print(found["answer"])
1036
+ for item in found["citations"]:
1037
+ print(f" {C['dim']}{item['file']}{':' + str(item['lines']) if item.get('lines') else ''}{C['reset']}")
1038
+ return 0
1039
+ if not args.question:
1040
+ print(f"usage: {C['b']}polyctl ask \"question\" \"option a\" \"option b\" …{C['reset']}")
1041
+ return 0
1042
+ rec = A.ask(root, args.question, args.options or [], context=args.context,
1043
+ slice_id=args.slice, cfg=cfg)
1044
+ print(f"{C['b']}{rec['id']}{C['reset']} {rec['question']}")
1045
+ for o in rec["options"]:
1046
+ print(f" {C['b']}{o['key']}){C['reset']} {o['label']}")
1047
+ for found in rec.get("precedents") or []:
1048
+ print(f" {C['yellow']}asked or decided before{C['reset']}: {found['project']} {found['kind']} "
1049
+ f"{found['id']} — {found['outcome']} {C['dim']}{found['source']}{C['reset']}")
1050
+ try:
1051
+ n = _phone_decision(rec, cfg)
1052
+ print(f"\n{C['dim']}sent to {n} chat(s){C['reset']}" if n else
1053
+ f"\n{C['dim']}no phone channel configured — answer with "
1054
+ f"`polyctl answer {rec['id']} <key>`{C['reset']}")
1055
+ except Exception as e:
1056
+ print(f"\n{C['dim']}phone delivery skipped: {e}{C['reset']}")
1057
+ return 0
1058
+
1059
+
1060
+ def cmd_answer(cfg, args):
1061
+ """Answer a pending decision from the terminal.
1062
+
1063
+ Only an option the question offers is taken, and a question answered once keeps its
1064
+ answer unless --change replaces it; the replaced answer stays in the record (CLI-ROBUST).
1065
+ """
1066
+ user, interactive = A._login_and_terminal()
1067
+ try:
1068
+ rec = A.answer(cfg["root"], args.id, " ".join(args.value), by="terminal",
1069
+ change=getattr(args, "change", False), user=user, interactive=interactive)
1070
+ except A.AnswerRefused as exc:
1071
+ print(f"{C['red']}not answered{C['reset']}: {exc}")
1072
+ return 2
1073
+ if not rec:
1074
+ print(f"{C['red']}no such decision{C['reset']} {args.id}")
1075
+ return 1
1076
+ rows = rec.get("answers") or []
1077
+ if len(rows) > 1:
1078
+ print(f"{C['green']}changed{C['reset']} {rec['id']}: {rows[-2].get('answer')} → {rec['answer']}")
1079
+ else:
1080
+ print(f"{C['green']}answered{C['reset']} {rec['id']}: {rec['answer']}")
1081
+ if rec.get("proposal"):
1082
+ # The answer is the decision; the change itself is a person's edit, which no polyctl command makes (RULE-PROPOSALS).
1083
+ print(f" {C['dim']}rule proposal {rec['proposal']}: polyctl writes no rule file; polyctl proposals --all shows it "
1084
+ f"with this answer{C['reset']}")
1085
+ return 0
1086
+
1087
+
1088
+ def cmd_decisions(cfg, args):
1089
+ """Open and recently answered questions."""
1090
+ rows = A.decisions(cfg["root"])
1091
+ if not rows:
1092
+ print(f"{C['dim']}No decisions recorded.{C['reset']}")
1093
+ return 0
1094
+ for r in sorted(rows, key=lambda x: x["asked_at"], reverse=True)[:args.n]:
1095
+ age = int((time.time() - r["asked_at"]) / 60)
1096
+ if r["state"] in ("open", A.PROPOSED):
1097
+ # A rule proposal's question waits for a person, and parks no slice (RULE-PROPOSALS).
1098
+ label = "OPEN" if r["state"] == "open" else "PROPOSED"
1099
+ whose = f", rule proposal {A.shown_text(r['proposal'])}: a person's to decide" if r.get("proposal") else ""
1100
+ print(f"{C['yellow']}{label}{C['reset']}{' ' * (9 - len(label))}{C['b']}{A.shown_text(r['id'])}{C['reset']} "
1101
+ f"{A.shown_text(r['question'])} {C['dim']}{age}m{whose}{C['reset']}")
1102
+ for o in r["options"]:
1103
+ print(f" {C['dim']}{A.shown_text(o['key'])}){C['reset']} {A.shown_text(o['label'])}")
1104
+ else:
1105
+ rows = r.get("answers") or []
1106
+ was = f"; was {A.shown_text(rows[-2].get('answer'))}" if len(rows) > 1 else ""
1107
+ print(f"{C['green']}answered{C['reset']} {C['b']}{A.shown_text(r['id'])}{C['reset']} "
1108
+ f"{A.shown_text(r['question'])} {C['dim']}→ {A.shown_text(r['answer'])} "
1109
+ f"({A.shown_text(r.get('answered_by'))}{was}){C['reset']}")
1110
+ return 0
1111
+
1112
+
1113
+ def _proposal_evidence_line(proposal):
1114
+ """What a proposal was measured beside, in the words `polyctl stats` uses (RULE-PROPOSALS)."""
1115
+ evidence = proposal.get("evidence") or {}
1116
+ stats = evidence.get("stats") or {}
1117
+ if evidence.get("unread"):
1118
+ return f"evidence: none, the review ledger could not be read when it was proposed ({evidence['unread']})"
1119
+ if not stats.get("slices"):
1120
+ return "evidence: no slice had landed to measure it beside"
1121
+ rounds = (stats.get("rounds") or {}).get("median")
1122
+ reviewed = stats["slices"] - (stats.get("waived") or 0)
1123
+ parts = [f"the last {stats['slices']} landed slice(s), {reviewed} of them reviewed"]
1124
+ if stats.get("first_pass_pct") is not None:
1125
+ parts.append(f"{stats['first_pass_pct']}% of those approved first time")
1126
+ if rounds is not None:
1127
+ parts.append(f"median {rounds} review round(s)")
1128
+ if stats.get("defects_pct") is not None:
1129
+ parts.append(f"{stats['defects_pct']}% of all {stats['slices']} with a defect found later")
1130
+ return "evidence: " + ", ".join(parts)
1131
+
1132
+
1133
+ def _rule_file_since(root, proposal):
1134
+ """Whether the rule file a proposal names still holds the bytes it was proposed against."""
1135
+ try:
1136
+ _, digest = A.proposal_rule_file(root, proposal["rule_file"])
1137
+ except (A.ProposalRefused, OSError):
1138
+ return "gone since it was proposed"
1139
+ return ("unchanged" if digest == proposal.get("rule_digest") else "changed") + " since it was proposed"
1140
+
1141
+
1142
+ def cmd_propose(cfg, args):
1143
+ """An agent proposes a change to a rule it works under, instead of editing it (RULE-PROPOSALS).
1144
+
1145
+ The proposal goes to the decision ledger with who made it, why, the rule file and the
1146
+ outcomes of the project's last landed slices, and its question to a person through the
1147
+ decision flow, and to the phone when one is set up. It writes no rule file, and neither
1148
+ does the answer. Exit 2 when it is refused; 0 when it is recorded, or when the same change
1149
+ stands open already and nothing new is recorded.
1150
+ """
1151
+ if not (args.why or "").strip():
1152
+ print("--why is required: what went wrong under the rule as it stands; a proposal without a reason "
1153
+ "cannot be judged")
1154
+ return 2
1155
+ try:
1156
+ proposal, question, created = A.propose(cfg["root"], cfg, " ".join(args.text), args.why,
1157
+ rule_file=args.rule_file, via="cli")
1158
+ except A.ProposalRefused as exc:
1159
+ print(f"{C['red']}not proposed{C['reset']}: {exc}")
1160
+ return 2
1161
+ did = proposal["question"]
1162
+ if not created:
1163
+ print(f"{C['yellow']}proposed already{C['reset']} {proposal['id']}, open for a person as {did}; "
1164
+ "nothing new was recorded")
1165
+ return 0
1166
+ print(f"{C['green']}proposed{C['reset']} {proposal['id']} → {did}, for a person to decide")
1167
+ print(f" {C['dim']}{_proposal_evidence_line(proposal)}{C['reset']}")
1168
+ print(f" {C['dim']}accept: polyctl answer {did} a · reject: polyctl answer {did} b · in words: polyctl answer {did} x <text>"
1169
+ f"{C['reset']}")
1170
+ print(f" {C['dim']}no rule file was written: work on under the rule as it stands{C['reset']}")
1171
+ try:
1172
+ n = _phone_decision(question, cfg)
1173
+ print(f" {C['dim']}sent to {n} chat(s){C['reset']}" if n else
1174
+ f" {C['dim']}no phone channel configured{C['reset']}")
1175
+ except Exception as exc:
1176
+ print(f" {C['dim']}phone delivery skipped: {exc}{C['reset']}")
1177
+ return 0
1178
+
1179
+
1180
+ def cmd_proposals(cfg, args):
1181
+ """The rule proposals waiting for a person, newest first; --all adds the decided ones (RULE-PROPOSALS).
1182
+
1183
+ One whose question's file is gone is shown with them: nobody can answer it any more, and
1184
+ dropping it from the list would lose it silently.
1185
+ """
1186
+ root = cfg["root"]
1187
+ rows = A.proposals(root)
1188
+ shown = rows if args.all else [p for p in rows if p["state"] in ("open", "missing")]
1189
+ if not shown:
1190
+ print(f"{C['dim']}No {'' if args.all else 'open '}rule proposals.{C['reset']}")
1191
+ return 0
1192
+ for p in list(reversed(shown))[:args.n]:
1193
+ author = p.get("by") if isinstance(p.get("by"), dict) else {}
1194
+ who = (f"{author.get('actor')} ({author['role']})" if author.get("role")
1195
+ else f"a caller polyctl did not start ({p.get('via')})")
1196
+ when = time.strftime("%Y-%m-%d %H:%M", time.localtime(p["at"])) if p.get("at") else "—"
1197
+ tone = C["yellow"] if p["state"] == "open" else C["red"] if p["state"] == "missing" else C["green"]
1198
+ print(f"{tone}{p['state'].upper():<9}{C['reset']}{C['b']}{p['id']}{C['reset']} {when} {who}")
1199
+ print(f" {p.get('text')}")
1200
+ print(f" {C['dim']}why: {p.get('why')}{C['reset']}")
1201
+ if p.get("rule_file"):
1202
+ print(f" {C['dim']}rule file: {p['rule_file']}, {_rule_file_since(root, p)}{C['reset']}")
1203
+ print(f" {C['dim']}{_proposal_evidence_line(p)}{C['reset']}")
1204
+ did = p.get("question")
1205
+ if p["state"] == "open":
1206
+ print(f" accept: polyctl answer {did} a · reject: polyctl answer {did} b")
1207
+ elif p["state"] == "missing":
1208
+ print(f" {C['red']}its question {did} is gone{C['reset']}: propose it again to ask a person")
1209
+ else:
1210
+ answered = (time.strftime("%Y-%m-%d %H:%M", time.localtime(p["answered_at"]))
1211
+ if p.get("answered_at") else "—")
1212
+ who = p.get("answered_by")
1213
+ if p.get("answered_user"):
1214
+ who = f"{who}, login {p['answered_user']}, " + ("a terminal attached" if p.get("answered_interactive")
1215
+ else "no terminal attached")
1216
+ print(f" → {p.get('answer')} {C['dim']}({who}, {answered}, {did}){C['reset']}")
1217
+ return 0
1218
+
1219
+
1220
+ def _handoff_head(text):
1221
+ """What of a handoff note goes to the phone: everything above what a successor can do.
1222
+
1223
+ The note is written in the project's language; the heading is looked for in every language, as a
1224
+ marker is (LANGUAGE-OUTPUT).
1225
+ """
1226
+ for heading in language.forms("handoff-successor"):
1227
+ text = text.split(heading)[0]
1228
+ return text
1229
+
1230
+
1231
+ def cmd_handoff(cfg, args):
1232
+ """Write down everything a successor needs, and send it.
1233
+
1234
+ The centre running out of quota does not break delivery — reports are written
1235
+ before the quota gate and the transport is HTTP, so a question still reaches a
1236
+ phone when the architect is dead. What breaks is that nobody decides, and the
1237
+ person who could is handed "out of quota" and nothing else.
1238
+
1239
+ So say what is actually stopped, what it is waiting on, and what would move it.
1240
+ Twice in one day here the state that would have unblocked a run existed only
1241
+ inside a conversation nobody else could reach; this is that state, on disk,
1242
+ where the next actor — a human, a fresh architect, tomorrow's session — can
1243
+ pick it up.
1244
+ """
1245
+ root = cfg["root"]
1246
+ impl = cfg.get("implementer") or {}
1247
+ adapter = A.load_adapter(impl.get("adapter", "")) if impl else {}
1248
+ bd = A.board(root)
1249
+ g = A.git_state(root)
1250
+ opens = A.decisions(root, "open")
1251
+ revs = A.reviews(root, cfg["reviews"], limit=1)
1252
+ # The implementer's own account, asked of the package's lookup for its adapter: whether to
1253
+ # read one was decided by a layer the implementer can write, and the first shipped
1254
+ # adapter's account was read whatever it ran (ACCOUNT-READERS).
1255
+ ident = A.implementer_adapter_id(cfg) if impl else ""
1256
+ readable = bool(A.usage_api(ident))
1257
+ acct = A.account_usage(adapter_id=ident) if readable else None
1258
+ state, age, doing = A.busy(cfg, adapter) if impl else ("unknown", None, "")
1259
+
1260
+ # In the project's language, as a person reads it (LANGUAGE-OUTPUT).
1261
+ lines = [language.text(cfg, "handoff.title", project=cfg.get("project") or os.path.basename(root)),
1262
+ f"_{datetime.now():%Y-%m-%d %H:%M}_", ""]
1263
+ if args.reason:
1264
+ lines += [language.text(cfg, "handoff.reason", reason=args.reason), ""]
1265
+
1266
+ lines += [language.text(cfg, "handoff.now"), language.text(cfg, "handoff.implementer", state=state)
1267
+ + (language.text(cfg, "digest.last-write", minutes=age // 60) if age is not None else ""),
1268
+ f"- HEAD `{(g['log'][0] if g['log'] else '?')[:60]}`",
1269
+ language.text(cfg, "handoff.git", dirty=len(g["dirty"]), ahead=g["ahead"],
1270
+ behind=g["behind"] if g.get("behind") is not None else "?",
1271
+ base=g.get("base") or language.text(cfg, "handoff.no-remote"))]
1272
+ if revs:
1273
+ lines.append(language.text(cfg, "handoff.last-review", verdict=revs[0][1], name=revs[0][0]))
1274
+ if doing:
1275
+ lines.append(language.text(cfg, "handoff.saying", doing=doing[:200]))
1276
+ if impl and not readable:
1277
+ lines.append(language.text(cfg, "handoff.credit", credit=_no_account(ident)))
1278
+ elif acct and not acct.get("error") and not acct.get("expired") and acct.get("limit"):
1279
+ left = language.text(cfg, "digest.left", n=f"{acct['limit'] - acct['used']:,.0f}")
1280
+ lines.append(language.text(cfg, "handoff.credit",
1281
+ credit=f"{acct['used']:,.0f} / {acct['limit']:,.0f} ({left})"))
1282
+
1283
+ if opens:
1284
+ lines += ["", language.text(cfg, "handoff.open-decisions")]
1285
+ for d in opens:
1286
+ lines.append(f"- `{d['id']}` {d['question']}")
1287
+ for o in d["options"]:
1288
+ lines.append(f" - `{d['id']} {o['key']}` → {o['label']}")
1289
+
1290
+ if bd["blocked"]:
1291
+ lines += ["", "## Blocked"]
1292
+ for it in bd["blocked"]:
1293
+ lines.append(f"- **{it['id']}** {it['title']} — "
1294
+ f"{it['notes'].get('needs', language.text(cfg, 'handoff.no-reason'))}")
1295
+ if bd["running"]:
1296
+ lines += ["", language.text(cfg, "handoff.running")]
1297
+ for it in bd["running"]:
1298
+ lines.append(f"- **{it['id']}** {it['title']}")
1299
+ if bd["queued"]:
1300
+ lines += ["", language.text(cfg, "handoff.next", n=len(bd["queued"])),
1301
+ f"- **{bd['queued'][0]['id']}** {bd['queued'][0]['title']}"]
1302
+
1303
+ lines += ["", language.text(cfg, "handoff.successor", heading=language.marker(cfg, "handoff-successor"))]
1304
+
1305
+ text = "\n".join(lines)
1306
+ # Named in the project's language; a note named in either is listed and read the same (LANGUAGE-FILES).
1307
+ kind = language.marker(cfg, "handoff-kind")
1308
+ # The writer allocates the final name, including when another handoff takes it meanwhile (SECRETS-2).
1309
+ name = f"{datetime.now():%Y%m%d-%H%M}-{A.mail_names(cfg)[1]}-to-anyone-{kind}.md"
1310
+ # As every mail polyctl writes: an envelope with its roles, scanned for credentials, mirrored in the mail
1311
+ # ledger. The note was written past write_mail, and so were none of those (ROLE-TABLE-2).
1312
+ name = A.write_mail(root, cfg, name, text + "\n",
1313
+ {"kind": kind, "class": "needs-read", "from": A.mail_names(cfg)[1], "to": "anyone"})
1314
+ path = os.path.join(root, cfg["mailbox"], name)
1315
+ print(text)
1316
+
1317
+ if not args.no_send:
1318
+ try:
1319
+ from . import telegram
1320
+ n = telegram.send(_handoff_head(text)[:3800], root)
1321
+ print(f"\n{C['dim']}sent to {n} chat(s) · saved to "
1322
+ f"{os.path.relpath(path, root)}{C['reset']}")
1323
+ except Exception as e:
1324
+ print(f"\n{C['dim']}saved; phone delivery skipped: {e}{C['reset']}")
1325
+ return 0