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,898 @@
1
+ """Status: the status screen, watch, fleet, tail, mail and events commands.
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 _ctx(cfg):
9
+ root = cfg["root"]
10
+ impl = cfg.get("implementer") or {}
11
+ adapter = A.load_adapter(impl.get("adapter", ""), root) if impl else {}
12
+ return root, impl, adapter
13
+
14
+
15
+ def _bar(pct, width=20):
16
+ filled = max(0, min(width, int(pct / (100 / width))))
17
+ col = C["red"] if pct > 85 else C["yellow"] if pct > 70 else C["green"]
18
+ return f"{col}{'█' * filled}{'░' * (width - filled)}{C['reset']} {pct:.0f}%"
19
+
20
+
21
+ def _checkout_position(g):
22
+ """One line for where a checkout stands: never an ahead count on its own (#89)."""
23
+ if g.get("base") is None:
24
+ return f"{C['yellow']}no remote default branch to compare against{C['reset']}"
25
+ text = f"{C['dim']}{g['ahead']} ahead / {g['behind']} behind {g['base']}{C['reset']}"
26
+ if g.get("merged"):
27
+ return text + f" {C['yellow']}already merged; this checkout is {g['behind']} commits old{C['reset']}"
28
+ if g.get("behind"):
29
+ return text + f" {C['yellow']}behind{C['reset']}"
30
+ return text
31
+
32
+
33
+ def _idle_answer_text(idle, now=None):
34
+ """How long the implementer has had nothing to do, and what would change that (#96)."""
35
+ since = idle.get("since") or 0
36
+ minutes = max(0, int(((now or time.time()) - since) / 60))
37
+ return (f"since {time.strftime('%H:%M', time.localtime(since))} ({minutes // 60}h {minutes % 60}m): "
38
+ "answered a nudge without changing anything; waiting for the board, the backlog, "
39
+ "a decision or mail")
40
+
41
+
42
+ def _window_label(hours):
43
+ return f"{hours:g}h" if hours < 48 else f"{hours / 24:g}d"
44
+
45
+
46
+ def _throughput_lines(tp):
47
+ """The throughput section as two plain lines: the counts, then the state and why (#91)."""
48
+ counts = (f"staged {tp['staged']} · landed {tp['landed']} · decisions {tp['decisions_asked']} asked, "
49
+ f"{tp['decisions_open']} waiting")
50
+ if tp.get("oldest_open_minutes") is not None:
51
+ counts += f" (oldest {tp['oldest_open_minutes'] // 60}h {tp['oldest_open_minutes'] % 60}m)"
52
+ stall = tp.get("stall")
53
+ if tp["state"] == "stalled" and stall:
54
+ paths = ", ".join(stall["paths"][:3]) + (" …" if len(stall["paths"]) > 3 else "")
55
+ state = (f"stalled {stall['minutes'] // 60}h {stall['minutes'] % 60}m on a staged candidate "
56
+ f"({paths or 'no paths recorded'}) — {stall['reason']}")
57
+ else:
58
+ state = {"landing": "landing: candidates are reaching commits",
59
+ "staging": "staging: candidates verified, none landed yet",
60
+ "busy": "busy: the implementer took turns and staged nothing",
61
+ "idle": "idle: no turns in this window"}[tp["state"]]
62
+ return counts, state
63
+
64
+
65
+ def _session_facts(state):
66
+ """A role's session as the JSON documents name it: its id, how polyctl found it, and why it could not (JSON-OUTPUT)."""
67
+ return {"id": state.get("session"), "how": state.get("how"), "why": state.get("why")} if state else None
68
+
69
+
70
+ def _unresolved_session(seconds, session):
71
+ """The session polyctl could not resolve, when that is why no transcript was read; None otherwise.
72
+
73
+ An `auto` polyctl could not resolve says why, where it would read as a transcript gone missing
74
+ (SESSION-IDENTITY).
75
+ """
76
+ return session if seconds is None and session and not session["id"] and session["why"] else None
77
+
78
+
79
+ def status_facts(cfg, msg_count=8, window_hours=24.0, shown=False):
80
+ """What the status panel shows, read once: `render` draws it and `polyctl status --json` prints it (JSON-OUTPUT).
81
+
82
+ docs/surfaces.md lists the keys. What the panel reads only for an implementer - its session,
83
+ telemetry, problems, throughput and messages - is null or empty without one, and the workspaces
84
+ a person could point polyctl at instead are read only then. The reads run in the panel's order.
85
+
86
+ `shown` is for the panel, whose banner puts the urgent messages in front of its reader: naming
87
+ them records them as seen, as drawing them always did (#30), before the unseen ones are read.
88
+ The document records nothing, as `polyctl_status` records nothing. A program reads it - a status bar,
89
+ a scheduled job - under whatever POLYCTL_ROLE it inherited, and a message recorded as seen by a
90
+ reader who never saw it would never climb the watchdog's ladder.
91
+ """
92
+ root, impl, adapter = _ctx(cfg)
93
+ facts = {"project": cfg.get("project") or os.path.basename(root), "root": root, "at": int(time.time()),
94
+ "implementer": None, "workspaces": None, "telemetry": None, "problems": None}
95
+ if project_mode(cfg) == "lite":
96
+ facts["mode"] = "lite"
97
+ facts["enforcement"] = ENFORCEMENT_OFF_LITE_LINE
98
+ else:
99
+ push_guard = _push_guard_status_line(_polyctl_hook_inventory(root))
100
+ if push_guard is not None:
101
+ facts["push_guard"] = push_guard
102
+ recs = []
103
+ if impl:
104
+ state, age, desc = A.busy(cfg, adapter)
105
+ session = _session_facts(A.session_state(cfg, "implementer"))
106
+ # The agent may be writing in a secondary project; the panel says where (#22).
107
+ elsewhere = A.working_elsewhere(cfg, S.get(cfg, "watchdog.idle_minutes") * 60) \
108
+ if state in ("stopped", "idle", "slowing") else None
109
+ facts["implementer"] = {
110
+ "adapter": impl.get("adapter"), "state": state, "seconds_since_write": age, "doing": desc,
111
+ "session": session,
112
+ "working_elsewhere": {"name": elsewhere["name"], "root": elsewhere["root"],
113
+ "seconds_since_write": int(elsewhere["age"])} if elsewhere else None}
114
+ msgs_path, _ = A.session_paths(cfg)
115
+ recs = A.read_tail(msgs_path, 12_000_000) if msgs_path else []
116
+ tel = A.telemetry(recs, adapter, msgs_path)
117
+ last = tel.get("last")
118
+ facts["telemetry"] = {
119
+ "context_percent": tel.get("ctx"), "cost_unit": tel.get("unit"), "turns": tel.get("turns"),
120
+ "cost_total": tel.get("total"), "cost_average": tel["total"] / max(1, tel["turns"]) if last else None,
121
+ "cost_delegated": tel.get("delegated"),
122
+ "last_turn_cost": last[0] if last else None, "last_turn_tool_calls": last[1] if last else None,
123
+ # keyflip's provider windows are the machine's, never the implementer's own pool. Read by the command
124
+ # the package's adapter declares, never one a layer the implementer writes declares (TRIAGE-HIGHS).
125
+ "machine_quota": A.quota(A.metered_adapter(cfg))}
126
+ nudge_err = A.last_nudge_error(root)
127
+ errs = A.recent_errors(recs, 2, adapter)
128
+ spin = A.spinning(root)
129
+ from .watchdog import load_state as _load_state
130
+ idle_answer = (_load_state(root) or {}).get("idle_answer")
131
+ facts["problems"] = {
132
+ "nothing_to_do_since": (idle_answer.get("since") or 0) if idle_answer else None,
133
+ "spinning_minutes": spin,
134
+ "nudge_error": {"at": nudge_err.get("at", 0), "code": nudge_err.get("code"),
135
+ "tail": nudge_err.get("tail", ""),
136
+ "log": A.project_file(root, "nudge-log", key=A.next_project_key(root))}
137
+ if nudge_err else None,
138
+ "agent_errors": [{"time": hh, "text": text} for hh, text in errs]}
139
+ else:
140
+ facts["workspaces"] = [{"path": ws["path"], "seconds_since_write": int(time.time() - ws["mtime"])}
141
+ for ws in A.all_workspaces()[:5]]
142
+ facts["returned_reviews"] = [{"id": review["id"], "slice": review.get("slice"), "verdict": review.get("verdict"),
143
+ "state": review.get("state")} for review in A.returned_reviews(root)]
144
+ revs = A.reviews(root, cfg["reviews"])
145
+ facts["reviews"] = [{"file": name, "verdict": verdict} for name, verdict in revs]
146
+ facts["rounds"] = {"spent": A.rounds(root, cfg["reviews"]), "budget": S.get(cfg, "round_budget")} \
147
+ if revs else None
148
+ facts["throughput"] = A.throughput(root, cfg, hours=window_hours) if impl else None
149
+ g = A.git_state(root)
150
+ facts["repository"] = {"log": [line for line in g["log"][:3] if line], "dirty_files": len(g["dirty"]),
151
+ "ahead": int(g["ahead"]) if str(g["ahead"]).isdigit() else None,
152
+ "behind": g.get("behind"), "base": g.get("base"), "merged": bool(g.get("merged"))}
153
+ waiting = A.mailbox(root, cfg["mailbox"])
154
+ marked = _marked_mail(cfg, shown)
155
+ facts["mail"] = {
156
+ "dir": cfg.get("mailbox", "agent-mail"), "waiting": waiting,
157
+ "urgent": None if marked is None else [{"id": m["id"], "to": m["to"], "title": m["title"]}
158
+ for m in marked[0]],
159
+ # Read after the panel's banner recorded its messages as seen, so the panel does not call them
160
+ # unseen (#30). The document recorded nothing: a marked message nobody was shown is in both lists.
161
+ "unseen": [{"id": m["id"], "class": m["class"], "age_seconds": int(m["age"])}
162
+ for m in A.unseen_messages(root, cfg)]}
163
+ bd = A.board(root)
164
+ facts["board"] = {"counts": {state: len(items) for state, items in bd.items()},
165
+ "blocked": [{"id": it["id"], "title": it["title"],
166
+ "why": it["notes"].get("needs") or it["notes"].get("waiting") or None}
167
+ for it in bd["blocked"]]}
168
+ try:
169
+ waivers = A.open_waiver_report(root)
170
+ except Exception as exc:
171
+ waivers = [f"waiver ledger is unreadable: {exc}"]
172
+ if waivers:
173
+ facts["waivers"] = waivers
174
+ facts["messages"] = [{"time": hh, "role": kind, "text": text}
175
+ for hh, kind, text in (A.messages(recs, msg_count, adapter) if impl else [])]
176
+ return facts
177
+
178
+
179
+ # The narrowest a panel is laid out to: past its indents, every line it wraps keeps a column to wrap in.
180
+ PANEL_MIN_COLUMNS = 20
181
+
182
+
183
+ def render(cfg, msg_count=8, width=None, max_lines=None, window_hours=24.0, shown=True, facts=None):
184
+ """Render the panel from status_facts. When max_lines is given the output never exceeds it:
185
+ the fixed sections are laid out first and the message log — the only elastic
186
+ part — takes whatever is left. A panel taller than the window scrolls, and a
187
+ scrolled panel stacks its own headers on every refresh. With `shown` false the
188
+ urgent messages it names are not recorded as seen, as in the document (status_facts)."""
189
+ facts = status_facts(cfg, msg_count, window_hours, shown=shown) if facts is None else facts
190
+ impl = cfg.get("implementer") or {}
191
+ # A terminal a few columns wide gets the narrowest panel, which wraps there, and a short one no line: textwrap
192
+ # raised on a width it was handed below one, and -1 lines kept all but the last (LEADS-ADAPTERS).
193
+ w = max(PANEL_MIN_COLUMNS, min(width or shutil.get_terminal_size((120, 40)).columns, 130))
194
+ max_lines = None if max_lines is None else max(0, max_lines)
195
+ L = []
196
+ a = L.append
197
+ # What the panel shows of a transcript, a session's record, mail, the board, a file's name or a vendor's output
198
+ # is shown escaped, a wrapped text a line at a time: an agent writes all of them, and an escape sequence among
199
+ # them acted on the terminal of whoever watched, or a line feed wrote a line that read as polyctl's (LEADS-MCP).
200
+
201
+ a(f"{C['b']}{C['cyan']}{'═' * w}{C['reset']}")
202
+ a(f"{C['b']} {A.shown_text(facts['project'].upper())}{C['reset']}{C['dim']} polyctl "
203
+ f"{datetime.fromtimestamp(facts['at']):%d %b %H:%M:%S}{C['reset']}")
204
+ a(f"{C['b']}{C['cyan']}{'═' * w}{C['reset']}")
205
+ if project_mode(cfg) == "lite":
206
+ a(f" {C['yellow']}{C['b']}{ENFORCEMENT_OFF_LITE}{C['reset']} — nothing is enforced (no reviewer probe, no commit hooks)")
207
+ elif unrecorded_lite(cfg):
208
+ a(f" {C['yellow']}mode is lite in {unrecorded_lite(cfg)} with no person's record, so full mode stays in force: "
209
+ f"polyctl mode lite --by <name>{C['reset']}")
210
+ if facts.get("push_guard"):
211
+ push_tone = C["dim"] if "is the repository's own pre-push hook" in str(facts["push_guard"]) else C["yellow"]
212
+ a(f" {push_tone}push guard {A.shown_text(facts['push_guard'])}{C['reset']}")
213
+
214
+ # implementer state
215
+ implementer = facts["implementer"]
216
+ if implementer:
217
+ txt, col = {"working": ("● WORKING", C["green"]),
218
+ "slowing": ("◐ slowing", C["yellow"]),
219
+ "stopped": ("■ STOPPED", C["red"]),
220
+ "idle": ("○ IDLE", C["red"])}.get(implementer["state"], ("? unknown", C["dim"]))
221
+ age, desc = implementer["seconds_since_write"], implementer["doing"]
222
+ agestr = f"last write {age // 60}m {age % 60}s ago" if age is not None else "no transcript"
223
+ unresolved = _unresolved_session(age, implementer["session"])
224
+ if unresolved:
225
+ agestr, desc = f"session {unresolved['how']}", unresolved["why"]
226
+ a(f"\n{col}{C['b']}{txt}{C['reset']} {C['dim']}{A.shown_text(impl.get('adapter','?'))} · "
227
+ f"{A.shown_text(agestr)}{C['reset']}")
228
+ for i, ln in enumerate(textwrap.wrap(desc, w - 6)[:2]):
229
+ a(f" {C['dim']}↳{C['reset']} {A.shown_text(ln)}" if i == 0 else f" {A.shown_text(ln)}")
230
+ elsewhere = implementer["working_elsewhere"]
231
+ if elsewhere:
232
+ a(f" {C['green']}↳ working in {A.shown_text(elsewhere['name'])}{C['reset']} {C['dim']}"
233
+ f"{A.shown_text(elsewhere['root'])} · last write {elsewhere['seconds_since_write']}s ago there"
234
+ f"{C['reset']}")
235
+ else:
236
+ a(f"\n{C['yellow']}No implementer session found for this workspace.{C['reset']}")
237
+ a(f" {C['dim']}{A.shown_text(facts['root'])}{C['reset']}")
238
+ if facts["workspaces"]:
239
+ a("\n Run it from a project, or point at one:")
240
+ for ws in facts["workspaces"]:
241
+ mins = int(ws["seconds_since_write"] / 60)
242
+ age = f"{mins}m ago" if mins < 90 else f"{mins // 60}h ago"
243
+ # A command to copy: the path quoted as one word for the shell, as `polyctl harness seen` quotes a name; a
244
+ # path no quoting holds as one word in every shell is shown, and no command made of it (LEADS-MCP).
245
+ word = A.copyable_word(ws["path"])
246
+ a(f" {C['b']}polyctl -C {word}{C['reset']} {C['dim']}{age}{C['reset']}" if word else
247
+ f" {A.shown_text(ws['path'])} {C['dim']}{age}; no command is printed for a path a shell would "
248
+ f"read as more than a name{C['reset']}")
249
+ else:
250
+ a(f" {C['dim']}No local agent sessions found at all. See docs/adapters.md.{C['reset']}")
251
+
252
+ # telemetry
253
+ tel = facts["telemetry"]
254
+ if tel and (tel["context_percent"] is not None or tel["last_turn_cost"] is not None or tel["machine_quota"]):
255
+ a(f"\n{C['b']}{C['mag']}── QUOTA / CONTEXT {'─' * max(0, w - 20)}{C['reset']}")
256
+ if tel["context_percent"] is not None:
257
+ note = " ← start a fresh session" if tel["context_percent"] > 85 else ""
258
+ a(f" context {_bar(tel['context_percent'])}{C['dim']}{note}{C['reset']}")
259
+ if tel["last_turn_cost"] is not None:
260
+ lu, avg = tel["last_turn_cost"], tel["cost_average"]
261
+ warn = f" {C['yellow']}⚠ {lu/max(avg,1):.1f}× average{C['reset']}" if lu > 2 * avg else ""
262
+ # The subagents a turn started spent inside its cost, and inside the total.
263
+ delegated = f", {tel['cost_delegated']:.0f} delegated" if tel["cost_delegated"] else ""
264
+ a(f" cost last turn {C['b']}{lu:.0f}{C['reset']} {A.shown_text(tel['cost_unit'])} "
265
+ f"({tel['last_turn_tool_calls']} tool calls) · {tel['turns']} turns, total "
266
+ f"{C['b']}{tel['cost_total']:.0f}{C['reset']}{C['dim']} (avg {avg:.0f}{delegated}){C['reset']}{warn}")
267
+ if tel["machine_quota"]:
268
+ # keyflip reports machine-wide provider windows, which are NOT the
269
+ # implementer's own pool — Kiro bills credits, Claude Code bills a
270
+ # 5h window. Labelling it plainly avoids reading someone else's
271
+ # quota as this agent's.
272
+ a(f" {C['dim']}other tools on this machine (not {A.shown_text(impl.get('adapter','this agent'))}'s "
273
+ f"pool):{C['reset']}")
274
+ for line in tel["machine_quota"]:
275
+ a(f" {C['dim']}{A.shown_text(line)}{C['reset']}")
276
+
277
+ # problems — only rendered when there is one, so an empty panel means healthy
278
+ trouble = facts["problems"]
279
+ if trouble and (trouble["nudge_error"] or trouble["agent_errors"] or trouble["spinning_minutes"]
280
+ or trouble["nothing_to_do_since"] is not None):
281
+ a(f"\n{C['b']}{C['red']}── PROBLEMS {'─' * max(0, w - 13)}{C['reset']}")
282
+ if trouble["nothing_to_do_since"] is not None:
283
+ a(f" {C['yellow']}nothing to do{C['reset']} "
284
+ f"{C['dim']}{_idle_answer_text({'since': trouble['nothing_to_do_since']})}{C['reset']}")
285
+ if trouble["spinning_minutes"]:
286
+ a(f" {C['red']}spinning{C['reset']} {C['dim']}{trouble['spinning_minutes']}m busy, nothing committed "
287
+ f"or changed{C['reset']}")
288
+ a(f" {C['dim']}activity is not progress — re-specify, split, or check for "
289
+ f"a wait loop{C['reset']}")
290
+ nudge_err = trouble["nudge_error"]
291
+ if nudge_err:
292
+ mins = int((time.time() - nudge_err["at"]) / 60)
293
+ a(f" {C['red']}restart failed{C['reset']} {C['dim']}{mins}m ago · "
294
+ f"exit {nudge_err['code']}{C['reset']}")
295
+ for ln in textwrap.wrap(nudge_err["tail"], w - 8)[:2]:
296
+ a(f" {C['dim']}{A.shown_text(ln)}{C['reset']}")
297
+ a(f" {C['dim']}full log: {_home_relative(nudge_err['log'])}{C['reset']}")
298
+ for error in trouble["agent_errors"]:
299
+ for i, ln in enumerate(textwrap.wrap(error["text"], w - 12)[:2]):
300
+ a(f" {C['dim']}{error['time']}{C['reset']} {C['yellow']}agent error{C['reset']} {A.shown_text(ln)}"
301
+ if i == 0 else f" {C['dim']}│{C['reset']} {A.shown_text(ln)}")
302
+
303
+ # A returned review is handled before new work starts (#28, W1).
304
+ for review in facts["returned_reviews"]:
305
+ # One that ended with no verdict is collected and submitted again; it was told to be handled as a
306
+ # review that came back (PIPELINE-HANDLE-2). Its record is a file in the tree, so what it says is shown
307
+ # escaped, and its id goes into the command to copy only as an id polyctl makes, quoted as one word for any shell
308
+ # the person may paste it into: a PowerShell window runs `$(...)` inside double quotes (LEADS-MCP).
309
+ rid, slice_ = A.shown_text(review["id"]), A.shown_text(review["slice"] or "a slice")
310
+ made = str(review["id"])
311
+ word = A.copyable_word(made) if made[:2] == "R-" and made[2:].isascii() and made[2:].isdigit() else None
312
+ collect = (f"({C['b']}polyctl review collect {word}{C['reset']})" if word else
313
+ f"({C['red']}its id is none polyctl makes: read its record in .polyctl/reviews/ before acting on it"
314
+ f"{C['reset']})")
315
+ a(f"\n {C['yellow']}{C['b']}REVIEW RETURNED{C['reset']} for {slice_}: "
316
+ f"{rid} {A.shown_text(review['verdict'])} — handle it before new work {collect}" if review["verdict"] else
317
+ f"\n {C['yellow']}{C['b']}REVIEW ENDED{C['reset']} for {slice_}: "
318
+ f"{rid} {A.shown_text(review['state'])}, no verdict — collect it, then submit again {collect}")
319
+ # reviews + round budget
320
+ if facts["reviews"]:
321
+ rn, budget = facts["rounds"]["spent"], facts["rounds"]["budget"]
322
+ a(f"\n{C['b']}{C['mag']}── REVIEWS {'─' * max(0, w - 12)}{C['reset']}")
323
+ if rn > budget:
324
+ a(f" {C['red']}⚠ round {rn}/{budget} — over budget: re-specify, split, "
325
+ f"or change actor{C['reset']}")
326
+ elif rn:
327
+ a(f" {C['dim']}round {rn}/{budget}{C['reset']}")
328
+ for review in facts["reviews"]:
329
+ col = C["green"] if "APPROVED" in review["verdict"].upper() else C["yellow"]
330
+ a(f" {A.shown_text(review['file'].split('-pr')[0])} {col}{A.shown_text(review['verdict'])}{C['reset']}")
331
+
332
+ # throughput: what the window produced, so busy-and-landing-nothing shows (#91)
333
+ tp = facts["throughput"]
334
+ if tp is not None:
335
+ label = _window_label(window_hours)
336
+ a(f"\n{C['b']}{C['mag']}── THROUGHPUT {label} {'─' * max(0, w - 16 - len(label))}{C['reset']}")
337
+ counts, state = _throughput_lines(tp)
338
+ colour = {"stalled": C["red"], "busy": C["yellow"], "idle": C["dim"],
339
+ "landing": C["green"]}.get(tp["state"], "")
340
+ a(f" {C['dim']}{counts}{C['reset']}")
341
+ # A stall names paths and a reason; keep it to two lines so a bounded panel stays bounded.
342
+ for i, ln in enumerate(textwrap.wrap(state, w - 6, break_on_hyphens=False)[:2]):
343
+ a(f" {colour}{A.shown_text(ln)}{C['reset']}" if i == 0
344
+ else f" {C['dim']}{A.shown_text(ln)}{C['reset']}")
345
+
346
+ # git + mail
347
+ repo = facts["repository"]
348
+ a(f"\n{C['b']}{C['mag']}── REPOSITORY {'─' * max(0, w - 15)}{C['reset']}")
349
+ for ln in repo["log"]:
350
+ a(f" {A.shown_text(ln[:w-5])}")
351
+ a(f" {C['dim']}{repo['dirty_files']} files uncommitted · {C['reset']}{_checkout_position(repo)}")
352
+
353
+ mail = facts["mail"]
354
+ a(f"\n {C['b']}Mailbox:{C['reset']} " +
355
+ (", ".join(A.shown_text(name) for name in mail["waiting"]) if mail["waiting"]
356
+ else f"{C['dim']}empty{C['reset']}"))
357
+ if mail["urgent"] is not None:
358
+ for line in _banner_lines(mail["dir"], mail["urgent"], len(mail["waiting"])):
359
+ a(f" {line}")
360
+ unseen = mail["unseen"]
361
+ if unseen:
362
+ oldest = unseen[0]
363
+ a(f" {C['yellow']}oldest unseen{C['reset']} {A.shown_text(oldest['id'])} {C['dim']}{oldest['class']}, "
364
+ f"{oldest['age_seconds'] // 60}m" + (f" · {len(unseen) - 1} more unseen" if len(unseen) > 1 else "")
365
+ + f"{C['reset']}")
366
+
367
+ # Board — one line, because a parked item is invisible by construction: work
368
+ # moved on past it, so no other signal in this panel looks wrong.
369
+ board = facts["board"]
370
+ counts = " · ".join(f"{board['counts'][k]} {k}" for k in
371
+ ("running", "blocked", "queued", "verified", "done") if board["counts"][k])
372
+ # Drawn when it names something: a board holding only the inbox drew a `Board:` naming nothing (LEADS-ADAPTERS).
373
+ if counts:
374
+ a(f" {C['b']}Board:{C['reset']} {counts}")
375
+ for it in board["blocked"]:
376
+ why = it["why"] or "reason not recorded"
377
+ for i, ln in enumerate(textwrap.wrap(f"{it['id']} {it['title']} — {why}", w - 14)[:2]):
378
+ a(f" {C['red']}⊘{C['reset']} {A.shown_text(ln)}" if i == 0
379
+ else f" {C['dim']}{A.shown_text(ln)}{C['reset']}")
380
+ for line in facts.get("waivers") or ():
381
+ a(f" {C['b']}Waiver:{C['reset']} {A.shown_text(line)}")
382
+
383
+ # The message log is elastic and goes last, so a short window drops history
384
+ # rather than the state you actually steer by.
385
+ msgs_block = []
386
+ if facts["messages"]:
387
+ msgs_block.append(f"\n{C['b']}{C['mag']}── RECENT MESSAGES {'─' * max(0, w - 20)}{C['reset']}")
388
+ for message in facts["messages"]:
389
+ tag = f"{C['blue']}YOU {C['reset']}" if message["role"] == "user" else f"{C['cyan']}AGENT{C['reset']}"
390
+ for i, ln in enumerate(textwrap.wrap(message["text"], w - 14)[:3]):
391
+ msgs_block.append(f" {C['dim']}{message['time']}{C['reset']} {tag} {A.shown_text(ln)}" if i == 0
392
+ else f" {C['dim']}│{C['reset']} {A.shown_text(ln)}")
393
+
394
+ if max_lines is None:
395
+ return "\n".join(L + msgs_block)
396
+
397
+ # Truncate by real lines, not by list elements: a section header carries its
398
+ # own leading blank line, so element count and line count are not the same.
399
+ fixed = "\n".join(L).split("\n")
400
+ if len(fixed) >= max_lines:
401
+ return "\n".join(fixed[:max_lines])
402
+ room = max_lines - len(fixed)
403
+ msg_lines = "\n".join(msgs_block).split("\n") if msgs_block else []
404
+ if len(msg_lines) > room:
405
+ msg_lines = msg_lines[:max(0, room - 1)]
406
+ if msg_lines:
407
+ msg_lines.append(f" {C['dim']}… older messages hidden (window too short){C['reset']}")
408
+ return "\n".join(fixed + msg_lines)
409
+
410
+
411
+ def _marked_mail(cfg, shown):
412
+ """(the marked messages for the role running this command, how many messages wait), or None when the
413
+ mailbox cannot be read. Where they are `shown`, drawn for whoever runs the command, they are recorded
414
+ as seen: named on a screen is shown to its reader (#30). A document a program reads shows nobody anything.
415
+
416
+ A person, or a caller with no POLYCTL_ROLE, is shown what is marked for either role (#29).
417
+ """
418
+ root = cfg["root"]
419
+ try:
420
+ urgent = A.urgent_messages(root, cfg, A.invoking_role())
421
+ waiting = len(A.mailbox(root, cfg.get("mailbox", "agent-mail")))
422
+ if shown:
423
+ A.mail_seen(root, [m["id"] for m in urgent], A.invoking_role() or "person")
424
+ except OSError:
425
+ return None
426
+ return urgent, waiting
427
+
428
+
429
+ def _banner_lines(mailbox_dir, urgent, waiting):
430
+ """The banner: each marked message and whom it is for, then how many others wait (#29).
431
+
432
+ A message's title is its writer's and its id a file's name, so both are shown escaped (LEADS-MCP).
433
+ """
434
+ lines = [f"{C['red']}{C['b']}URGENT{C['reset']} for the {m['to']}: {C['b']}{A.shown_text(m['title'])}"
435
+ f"{C['reset']} {C['dim']}{A.shown_text(m['id'])}{C['reset']}" for m in urgent]
436
+ others = waiting - len(urgent)
437
+ if others > 0:
438
+ lines.append(f"{C['dim']}{others} other message(s) waiting in {A.shown_text(mailbox_dir)}/{C['reset']}")
439
+ return lines
440
+
441
+
442
+ def _mailbox_banner(cfg, shown=True):
443
+ """Lines naming the marked messages for the role running this command, and how many others wait (#29).
444
+
445
+ A person, or a caller with no POLYCTL_ROLE, sees what is marked for either role. With `shown` false
446
+ nothing is recorded (_marked_mail): `polyctl watch --web` shows the lines to whatever fetched the
447
+ page, and a fetch is no proof that the message's reader saw it.
448
+ """
449
+ marked = _marked_mail(cfg, shown)
450
+ return [] if marked is None else _banner_lines(cfg.get("mailbox", "agent-mail"), *marked)
451
+
452
+
453
+ def cmd_status(cfg, args):
454
+ window = getattr(args, "window", None) or 24.0
455
+ if getattr(args, "json", False):
456
+ # The facts alone, as one document: no colour, no banner, nothing else on stdout, and nothing
457
+ # recorded as seen, since no reader was shown the messages it names (JSON-OUTPUT).
458
+ print(json.dumps(status_facts(cfg, args.messages, window, shown=False), ensure_ascii=False))
459
+ return
460
+ print(render(cfg, args.messages, window_hours=window))
461
+
462
+
463
+ def cmd_watch(cfg, args):
464
+ if getattr(args, "web", False):
465
+ return _watch_web(cfg, args)
466
+ if getattr(args, "port", None) is not None:
467
+ print("polyctl watch: --port is the port of --web; add --web to serve the pages", file=sys.stderr)
468
+ return 2
469
+ if not A.terminal():
470
+ # A pipe, a log or a dumb terminal gets the panel once. Looping there wrote the alternate
471
+ # screen and a clear before every frame into whatever read it, and never ended (CLI-ROBUST).
472
+ width = shutil.get_terminal_size((120, 40)).columns
473
+ print("\n".join(render_fleet(width)) if getattr(args, "all", False) else render(cfg, args.messages, width))
474
+ return 0
475
+ sys.stdout.write("\033[?1049h\033[?25l") # alternate screen, hidden cursor
476
+ try:
477
+ while True:
478
+ size = shutil.get_terminal_size((120, 40))
479
+ if getattr(args, "all", False):
480
+ lines = render_fleet(size.columns)
481
+ out = "\n".join(lines[:max(4, size.lines - 2)])
482
+ else:
483
+ out = render(cfg, args.messages, size.columns, size.lines - 2)
484
+ sys.stdout.write("\033[H\033[J" + out +
485
+ f"\n{C['dim']} every {args.interval}s · Ctrl+C to exit{C['reset']}")
486
+ sys.stdout.flush()
487
+ time.sleep(args.interval)
488
+ except KeyboardInterrupt:
489
+ pass
490
+ finally:
491
+ sys.stdout.write("\033[?25h\033[?1049l") # cursor back, restore scrollback
492
+ sys.stdout.flush()
493
+
494
+
495
+ WEB_PORT = 8732 # `polyctl watch --web`, beside `polyctl a2a serve` on 8731
496
+ WEB_COLUMNS = 120 # the width a panel is laid out to when it cannot read its terminal's
497
+
498
+
499
+ def _load_config_readonly(root):
500
+ """Read `root`'s config without registering it in ~/.polyctl/projects.json or .polyctl/project-key (WEB-API).
501
+
502
+ A test double for `A.load_config` that takes `root` alone (tests/test_json_output.py) has no `record`
503
+ keyword; a TypeError raised inside `load_config` itself is re-raised rather than retried with `record=True`.
504
+ """
505
+ try:
506
+ return A.load_config(root, record=False)
507
+ except TypeError as exc:
508
+ if "unexpected keyword argument 'record'" not in str(exc):
509
+ raise
510
+ return A.load_config(root)
511
+
512
+
513
+ def _web_pages(root, args):
514
+ """The pages `polyctl watch --web` serves (WEB-VIEW, WEB-API): {path: (label, compute)}, each computed when asked for.
515
+
516
+ A page is what `polyctl watch`, `polyctl board`, `polyctl next` (the pipeline) and `polyctl fleet` show at that
517
+ moment, by the functions those commands and `/api/*` use. The project's config is read again
518
+ for each request without recording the project in the registry, so a view left open for a day
519
+ shows a session or a role that changed after it started and writes nothing anywhere. One
520
+ difference from the terminal is deliberate: a page marks no urgent message seen (#30), as
521
+ `polyctl status --json` marks none: both read with `shown` false (status_facts). Any process on
522
+ this machine can fetch a loopback page, and a fetch is no proof that a person read it; an
523
+ urgent message stays unseen, and its alarm keeps climbing, until a command shows it to its
524
+ reader.
525
+ """
526
+ from . import web
527
+
528
+ def panel():
529
+ cfg = _load_config_readonly(root)
530
+ return render(cfg, args.messages, WEB_COLUMNS, shown=False,
531
+ facts=status_facts(cfg, args.messages, shown=False))
532
+
533
+ def board():
534
+ cfg = _load_config_readonly(root)
535
+ facts = board_facts(cfg, shown=False)
536
+ mail = facts["mail"]
537
+ banner = [] if mail["urgent"] is None else _banner_lines(mail["dir"], mail["urgent"], mail["waiting"])
538
+ return "\n".join(banner + _board_lines(cfg, facts=facts))
539
+
540
+ def pipeline():
541
+ return web.render_pipeline(A.pipeline_facts(_load_config_readonly(root)))
542
+
543
+ def fleet():
544
+ return "\n".join(render_fleet(WEB_COLUMNS))
545
+
546
+ return {"/": ("panel", panel), "/board": ("board", board),
547
+ "/pipeline": ("pipeline", pipeline), "/fleet": ("fleet", fleet)}
548
+
549
+
550
+ def _web_api(root, args):
551
+ """The JSON endpoints `polyctl watch --web` serves beside its pages (WEB-API): {path: compute}."""
552
+ return {
553
+ "/api/status": lambda: status_facts(_load_config_readonly(root), args.messages, shown=False),
554
+ "/api/board": lambda: board_facts(_load_config_readonly(root), shown=False),
555
+ "/api/pipeline": lambda: A.pipeline_facts(_load_config_readonly(root)),
556
+ "/api/fleet": lambda: fleet_facts(),
557
+ }
558
+
559
+
560
+ def _watch_web(cfg, args):
561
+ """Serve the pages on 127.0.0.1 until Ctrl+C: a browser tab in place of a terminal (WEB-VIEW, WEB-API)."""
562
+ from . import web
563
+ port = WEB_PORT if args.port is None else args.port
564
+ if not 0 <= port <= 65535:
565
+ print(f"polyctl watch --web: --port {port}: a port is 0 to 65535, and 0 takes a free one", file=sys.stderr)
566
+ return 2
567
+ if args.interval < 1:
568
+ # A page refreshed every 0 seconds reloads as fast as the browser can ask.
569
+ print(f"polyctl watch --web: --interval {args.interval}: a page refreshes at most once a second", file=sys.stderr)
570
+ return 2
571
+ root = cfg["root"]
572
+ try:
573
+ server = web.listen(_web_pages(root, args), cfg.get("project") or os.path.basename(root), args.interval, port,
574
+ api=_web_api(root, args))
575
+ except OSError as exc:
576
+ print(f"polyctl watch --web: cannot listen on 127.0.0.1:{port}: {exc.strerror or exc}", file=sys.stderr)
577
+ return 1
578
+ start = "/fleet" if args.all else "/"
579
+ print(f"polyctl watch --web: http://127.0.0.1:{server.server_port}{start} read-only, refreshes every "
580
+ f"{args.interval}s · Ctrl+C to stop", flush=True)
581
+ try:
582
+ server.serve_forever()
583
+ except KeyboardInterrupt:
584
+ pass
585
+ finally:
586
+ server.server_close()
587
+ return 0
588
+
589
+
590
+ def _fleet_rows():
591
+ """One row per workspace with a local agent session, what needs a human first.
592
+
593
+ `polyctl fleet` draws the rows and `polyctl fleet --json` prints them, under the keys docs/parallel.md
594
+ lists (JSON-OUTPUT).
595
+ """
596
+ rows = []
597
+ for ws in A.all_workspaces():
598
+ root = ws["path"]
599
+ try:
600
+ cfg = _load_config_readonly(root)
601
+ except Exception:
602
+ continue
603
+ impl = cfg.get("implementer") or {}
604
+ # Read as `polyctl status` reads it there, its project's adapter layer included (LEADS-ADAPTERS).
605
+ adapter = A.load_adapter(impl.get("adapter", ""), root) if impl else {}
606
+ state, age, desc = A.busy(cfg, adapter) if impl else ("unknown", None, "")
607
+ session = _session_facts(A.session_state(cfg, "implementer"))
608
+ bd = A.board(root)
609
+ g = A.git_state(root)
610
+ rows.append({"name": cfg.get("project") or os.path.basename(root), "root": root,
611
+ "state": state, "seconds_since_write": age, "doing": desc, "session": session,
612
+ "queued": len(bd["queued"]), "blocked": len(bd["blocked"]),
613
+ "running": len(bd["running"]), "dirty_files": len(g["dirty"]),
614
+ "mail_waiting": len(A.mailbox(root, cfg["mailbox"])),
615
+ "spinning_minutes": A.spinning(root),
616
+ "has_source": bool(A.sources(root))})
617
+ # what needs a human first: spinning, then blocked, then idle
618
+ rows.sort(key=lambda r: (r["spinning_minutes"] is None, r["blocked"] == 0, r["state"] != "idle"))
619
+ return rows
620
+
621
+
622
+ def fleet_facts():
623
+ """The fleet, read once: when it was read, and the rows in the order `polyctl fleet` draws them (JSON-OUTPUT)."""
624
+ return {"at": int(time.time()), "projects": _fleet_rows()}
625
+
626
+
627
+ def render_fleet(width=None, facts=None):
628
+ w = max(PANEL_MIN_COLUMNS, min(width or shutil.get_terminal_size((120, 40)).columns, 130))
629
+ facts = fleet_facts() if facts is None else facts
630
+ L = [f"{C['b']}{C['cyan']}{'═' * w}{C['reset']}",
631
+ f"{C['b']} ALL PROJECTS{C['reset']}{C['dim']} polyctl "
632
+ f"{datetime.fromtimestamp(facts['at']):%d %b %H:%M:%S}{C['reset']}",
633
+ f"{C['b']}{C['cyan']}{'═' * w}{C['reset']}"]
634
+ rows = facts["projects"]
635
+ if not rows:
636
+ L.append(f"\n{C['dim']}No workspaces with a local agent session.{C['reset']}")
637
+ return L
638
+ for r in rows:
639
+ dot, col = {"working": ("●", C["green"]), "slowing": ("◐", C["yellow"]),
640
+ "stopped": ("■", C["red"]),
641
+ "idle": ("○", C["red"])}.get(r["state"], ("?", C["dim"]))
642
+ agestr = f"{r['seconds_since_write'] // 60}m" if r["seconds_since_write"] is not None else "—"
643
+ flags = []
644
+ if r["spinning_minutes"]:
645
+ flags.append(f"{C['red']}spinning {r['spinning_minutes']}m{C['reset']}")
646
+ if r["blocked"]:
647
+ flags.append(f"{C['red']}{r['blocked']} blocked{C['reset']}")
648
+ if r["mail_waiting"]:
649
+ flags.append(f"{C['cyan']}{r['mail_waiting']} mail{C['reset']}")
650
+ if not r["has_source"]:
651
+ flags.append(f"{C['dim']}no source{C['reset']}")
652
+ # A project's name and what its session says it does are its agent's to write: shown escaped (LEADS-MCP).
653
+ L.append(f"\n {col}{dot}{C['reset']} {C['b']}{A.shown_text(r['name'][:22]):<22}{C['reset']}"
654
+ f"{C['dim']}{r['state']:<8} {agestr:>4}{C['reset']} "
655
+ f"q{r['queued']} r{r['running']} "
656
+ f"{C['dim']}·{C['reset']} {r['dirty_files']} dirty"
657
+ + (" " + " ".join(flags) if flags else ""))
658
+ desc = r["doing"]
659
+ unresolved = _unresolved_session(r["seconds_since_write"], r["session"])
660
+ if unresolved:
661
+ desc = f"session {unresolved['how']}: {unresolved['why']}" # why it is unknown (SESSION-IDENTITY)
662
+ if desc:
663
+ for ln in textwrap.wrap(desc, w - 8)[:1]:
664
+ L.append(f" {C['dim']}↳ {A.shown_text(ln)}{C['reset']}")
665
+ return L
666
+
667
+
668
+ def cmd_fleet(cfg, args):
669
+ if getattr(args, "json", False):
670
+ # The rows alone, as one document: no colour, no header, nothing else on stdout (JSON-OUTPUT).
671
+ print(json.dumps(fleet_facts(), ensure_ascii=False))
672
+ return 0
673
+ for ln in render_fleet():
674
+ print(ln)
675
+ return 0
676
+
677
+
678
+ def cmd_tail(cfg, args):
679
+ for line in _mailbox_banner(cfg):
680
+ print(line)
681
+ msgs_path, _ = A.session_paths(cfg)
682
+ if not msgs_path:
683
+ session = A.session_state(cfg, "implementer") or {}
684
+ why = session.get("why") if not session.get("session") else None
685
+ print(f"No implementer session found: {why}" if why else "No implementer session found.", file=sys.stderr)
686
+ return 1
687
+ _, _, adapter = _ctx(cfg)
688
+ for hh, kind, text in A.messages(A.read_tail(msgs_path), args.n, adapter):
689
+ who = "YOU " if kind == "user" else "AGENT"
690
+ print(f"--- {hh} [{who}] ---\n{_shown_lines(text)}\n")
691
+
692
+
693
+ def _shown_lines(text):
694
+ """Text of many lines - a transcript's words, a message's body - as a person reads it: a line at a time, each
695
+ escaped as A.shown_text escapes one, so its lines stay lines and nothing in them acts on a terminal
696
+ (LEADS-MCP)."""
697
+ return "\n".join(A.shown_text(line) for line in str(text).split("\n"))
698
+
699
+
700
+ def cmd_mail(cfg, args):
701
+ root = cfg["root"]
702
+ d = os.path.join(root, cfg["mailbox"])
703
+ if args.action in ("list", "read"):
704
+ for line in _mailbox_banner(cfg):
705
+ print(line)
706
+ if args.action in ("list", "read"):
707
+ # What a reader's own command lists is seen by that reader, not yet handled (#30).
708
+ role = A.invoking_role()
709
+ shown = [f for f in A.mailbox(root, cfg["mailbox"]) if A.addressed_to(f, cfg, role)]
710
+ A.mail_seen(root, shown, role or "person")
711
+ # A message's name and body are its writer's, an agent's among them: shown escaped (LEADS-MCP).
712
+ if args.action == "list":
713
+ for f in A.mailbox(root, cfg["mailbox"]):
714
+ print(A.shown_text(f))
715
+ elif args.action == "read":
716
+ for f in A.mailbox(root, cfg["mailbox"]):
717
+ print(f"===== {A.shown_text(f)} =====\n{_shown_lines(open(os.path.join(d, f), encoding=UTF8).read())}")
718
+ elif args.action == "send":
719
+ os.makedirs(d, exist_ok=True)
720
+ stamp = datetime.now().strftime("%Y%m%d-%H%M")
721
+ topic = A.safe_slug((args.topic or "note").lower())
722
+ impl, arch = A.mail_names(cfg)
723
+ name = f"{stamp}-{arch}-to-{impl}-{A.safe_slug(args.type.upper(), 'INFO')}-{topic}.md"
724
+ body = args.body if args.body else sys.stdin.read()
725
+ name = A.write_mail(root, cfg, name, body.rstrip() + "\n",
726
+ {"kind": args.type.lower(), "from": arch, "to": impl,
727
+ "class": getattr(args, "mail_class", None)})
728
+ print(name)
729
+ elif args.action == "ack":
730
+ import fnmatch
731
+ pattern = args.type if args.type and args.type != "INFO" else None
732
+ if not pattern:
733
+ print("usage: polyctl mail ack <file-or-glob> e.g. polyctl mail ack 'watchdog-to-*-ANOMALY-*'"); return 2
734
+ hits = [f for f in A.mailbox(root, cfg["mailbox"]) if f == pattern or fnmatch.fnmatch(f, pattern)]
735
+ if not hits:
736
+ print(f"no message matches {pattern}"); return 1
737
+ # An agent acknowledged another reader's mail, including its append-only handled record. Check the
738
+ # whole glob before consuming any of it; an unknown role is no person's session (LEADS-OPEN).
739
+ role = (os.environ.get("POLYCTL_ROLE") or "").strip().lower()
740
+ refused = hits if role and role not in A.ROLES else [
741
+ f for f in hits if not A.addressed_to(f, cfg, role or None)]
742
+ if refused:
743
+ print("not acknowledged: these messages belong to another reader, or POLYCTL_ROLE names no mail reader: "
744
+ + ", ".join(A.shown_text(f) for f in refused))
745
+ print(" ask their reader to acknowledge them with polyctl mail ack; no matching message was consumed")
746
+ return 1
747
+ store = A.mail_store_mode(root) == "append-only"
748
+ if store:
749
+ A.ingest_mail(root, cfg)
750
+ for f in hits:
751
+ if store:
752
+ # Handling is a record; the message stays in the store (#80).
753
+ A.handle_message(root, cfg, f, A.invoking_role() or "person", args.body or "processed")
754
+ else:
755
+ os.remove(os.path.join(d, f))
756
+ A.mail_ledger_append(root, {"event": "consumed", "id": f, "outcome": args.body or "processed"})
757
+ print(f" {C['green']}acked{C['reset']} {A.shown_text(f)}")
758
+ elif args.action == "sync":
759
+ A.ingest_mail(root, cfg)
760
+ try:
761
+ commit, where = A.sync_mail(root, cfg)
762
+ except (RuntimeError, OSError, subprocess.CalledProcessError) as exc:
763
+ print(f"{C['red']}not synced{C['reset']}: {exc}")
764
+ return 1
765
+ print(f"{C['green']}synced{C['reset']} the message store {commit[:12]} → {where}")
766
+ elif args.action == "compact":
767
+ # The age shares its positional with send's type, so no argparse type can read it; the
768
+ # same parser can (CLI-ROBUST). A bare number is days, as it always was.
769
+ try:
770
+ days = A.time_span(args.type, "d") if args.type and args.type != "INFO" else 30.0
771
+ except ValueError as exc:
772
+ print(f"polyctl mail compact: {exc}")
773
+ return 2
774
+ compacted = A.compact_messages(root, days)
775
+ print(f"compacted {len(compacted)} stored message(s) older than {days:g} day(s) to stubs; "
776
+ "their bodies stay in .polyctl/mail/archive/")
777
+ elif args.action == "log":
778
+ A.reconcile_mail_ledger(root, cfg)
779
+ for r in A.mail_log(root, 40):
780
+ when = datetime.fromtimestamp(r["at"]).strftime("%d %b %H:%M")
781
+ extra = f" stood {r['stood_s'] // 60}m" if r.get("stood_s") is not None else ""
782
+ print(f" {when} {A.shown_text(r.get('event', '?')):<9} {A.shown_text(r.get('id', '')[:70])}{extra}")
783
+ elif args.action == "search":
784
+ if not args.type or args.type == "INFO":
785
+ print("usage: polyctl mail search <text>"); return 2
786
+ for r in A.mail_search(root, args.type):
787
+ when = datetime.fromtimestamp(r["at"]).strftime("%d %b %H:%M")
788
+ print(f" {when} {A.shown_text(r.get('kind') or ''):<9} {A.shown_text(r['id'][:60])} "
789
+ f"{C['dim']}{A.shown_text(r.get('summary', '')[:70])}{C['reset']}")
790
+
791
+
792
+ # ---- the machine's event log, read and followed (EVENTS-LOG) ------------------------------
793
+
794
+ EVENTS_FOLLOW_SECONDS = 1.0 # how often `polyctl events --follow` looks for new lines: a stat and a read, then a sleep
795
+
796
+
797
+ def _events_wait(seconds):
798
+ """The pause between two looks at the event log; a test puts its own in."""
799
+ time.sleep(seconds)
800
+
801
+
802
+ def _event_value(value):
803
+ """One value of an event as a person reads it: a plain word as it is, anything else as JSON.
804
+
805
+ Any program on the machine can write to the log, so a string with a space is quoted, and one
806
+ holding a character a terminal would act on - an escape, a direction override - is escaped.
807
+ """
808
+ if isinstance(value, bool):
809
+ return "true" if value else "false"
810
+ if isinstance(value, str) and value.isprintable():
811
+ return value if value and not any(ch.isspace() for ch in value) else json.dumps(value, ensure_ascii=False)
812
+ return json.dumps(value, ensure_ascii=True, separators=(",", ":"), default=str)
813
+
814
+
815
+ def _event_text(row):
816
+ """One event as a line a person reads: its local time, project and kind, then name=value for what it carried.
817
+
818
+ A line another program wrote in its own shape is shown too: what it holds beside the time,
819
+ the project and the kind is read as if it were the payload.
820
+ """
821
+ at, when = row.get("at"), "????-??-?? ??:??:??"
822
+ if isinstance(at, (int, float)) and not isinstance(at, bool):
823
+ try:
824
+ when = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(at))
825
+ except (ValueError, OverflowError, OSError):
826
+ pass
827
+ fields = dict(row["data"]) if isinstance(row.get("data"), dict) else {}
828
+ fields.update((key, value) for key, value in row.items()
829
+ if key not in ("at", "project", "kind") and not (key == "data" and isinstance(value, dict)))
830
+ carried = " ".join(f"{_event_value(key)}={_event_value(value)}" for key, value in fields.items()
831
+ if value is not None)
832
+ return (f"{C['dim']}{when}{C['reset']} {_event_value(row.get('project', '?')):<14} "
833
+ f"{C['cyan']}{_event_value(row.get('kind', '?')):<17}{C['reset']} {carried}").rstrip()
834
+
835
+
836
+ def cmd_events(cfg, args):
837
+ """What polyctl did on this machine, read from its event log (EVENTS-LOG).
838
+
839
+ The newest events of every project, or of one, or every one since a time; with --follow, then
840
+ each event as it is written, until Ctrl+C. Following looks at the file once a second - a stat
841
+ and a read of what is new, never a busy loop - and goes on across the bound's trims
842
+ (A.EventTail). --json prints each event as a line of JSON in the log's own shape - polyctl's lines as
843
+ they were written - for a program to read; what is said about the log itself then goes to
844
+ standard error, so the output stays one event a line.
845
+ """
846
+ tail = A.EventTail()
847
+ since = args.since.moment() if args.since else None
848
+
849
+ def wanted(rows):
850
+ return [row for row in rows if A.event_matches(row, args.project, since)]
851
+
852
+ def say(text):
853
+ if args.json:
854
+ print(text, file=sys.stderr, flush=True)
855
+ else:
856
+ print(f"{C['dim']}{text}{C['reset']}", flush=True)
857
+
858
+ def show(rows):
859
+ # Flushed a line at a time: a program reading a pipe gets each event as it is written.
860
+ for row in rows:
861
+ print(A.event_line(row).decode(UTF8).rstrip("\n") if args.json else _event_text(row), flush=True)
862
+
863
+ rows = wanted(tail.poll())
864
+ shown = rows[-args.n:] if args.n > 0 else rows
865
+ if len(shown) < len(rows):
866
+ say(f"{len(rows) - len(shown)} earlier event(s) not shown; -n 0 shows every one")
867
+ show(shown)
868
+ skipped = tail.skipped
869
+ if skipped:
870
+ say(f"{skipped} line(s) of {tail.path} hold no event and were passed over")
871
+ if not args.follow:
872
+ if not rows:
873
+ say(f"no events{' of ' + args.project if args.project else ''}"
874
+ f"{' since ' + str(args.since) if args.since else ''} in {tail.path}")
875
+ return 0
876
+ say(f"following {tail.path}; Ctrl+C ends it")
877
+ trouble = None
878
+ try:
879
+ while True:
880
+ _events_wait(EVENTS_FOLLOW_SECONDS)
881
+ try:
882
+ rows = tail.poll()
883
+ except OSError as exc:
884
+ # Said once, not every second; the follower goes on looking until the file can be read.
885
+ if str(exc) != trouble:
886
+ trouble = str(exc)
887
+ say(f"cannot read {tail.path}: {exc}; still looking")
888
+ continue
889
+ trouble = None
890
+ if tail.missed:
891
+ tail.missed = False
892
+ say(f"{tail.path} was cut past where this reader had read; events may be missing")
893
+ if tail.skipped > skipped:
894
+ say(f"{tail.skipped - skipped} line(s) hold no event and were passed over")
895
+ skipped = tail.skipped
896
+ show(wanted(rows))
897
+ except KeyboardInterrupt:
898
+ return 0 # Ctrl+C is how a follow ends, as it ends `polyctl watch`