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
polyctl/skillkit.py ADDED
@@ -0,0 +1,503 @@
1
+ """The playbook, and putting it where the agents read.
2
+
3
+ `polyctl init` used to leave a repository with the files and a short steering note;
4
+ the rest of how to behave lived in one architect's head. That is the wrong
5
+ place for it: the promise of this tool is "add it and hand the project to the
6
+ agent already running", and the agent can only keep that promise if it knows
7
+ what the architect knows — the roles, the loop, what authority is, how to talk,
8
+ how to measure, what never to do, and every command. So the playbook ships
9
+ inside the package and is written, on init, in the dialect each agent reads.
10
+ One source, one rendering per harness, and a test that fails when a command is
11
+ missing from it.
12
+
13
+ Which harnesses there are, what each leaves in a repository, where its playbook
14
+ and its MCP registration go: all of that is declared by the adapters (#76). This
15
+ module reads the declarations and names no harness itself.
16
+ """
17
+ import json
18
+ import os
19
+ import re
20
+ import shutil
21
+ import shlex
22
+ import subprocess
23
+
24
+ from . import lib as A, matrix as M, storage
25
+ UTF8 = "utf-8" # every text file polyctl writes or reads; Windows would otherwise use cp1252
26
+
27
+ MARK_START = "<!-- polyctl-playbook:start -->"
28
+ MARK_END = "<!-- polyctl-playbook:end -->"
29
+ SKILL_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "skill", "SKILL.md")
30
+ SHARED_RULE_FILE = "AGENTS.md" # the cross-harness convention; a harness's own rule file is declared
31
+
32
+
33
+ def playbook():
34
+ """(frontmatter, body) of the packaged playbook."""
35
+ text = open(SKILL_PATH, encoding=UTF8).read()
36
+ if text.startswith("---\n"):
37
+ end = text.find("\n---\n", 4)
38
+ return text[:end + 5], text[end + 5:].lstrip("\n")
39
+ return "", text
40
+
41
+
42
+ def _escapes(rel):
43
+ """Whether a declared setup path leaves the repository by its words: absolute, a home (`~`), a drive or a `..`."""
44
+ text = str(rel or "").replace("\\", "/")
45
+ return not text or text.startswith(("/", "~")) or text[1:2] == ":" or ".." in text.split("/")
46
+
47
+
48
+ def _local(root, rel):
49
+ """`rel` inside the repository `root`, or None where it would leave it (HARNESS-SETUP-2).
50
+
51
+ A setup path is an adapter's word, and the project's adapter layer is one an agent can write: a
52
+ playbook, a rule file or an MCP file declared as `../x` was written outside the project, `polyctl remove`
53
+ deleted it there, and a home path such as opencode's `~/.config/...` was written into the project as
54
+ a directory named `~`. The path is held to the repository by its words and by where it resolves.
55
+ """
56
+ if _escapes(rel):
57
+ return None
58
+ path = os.path.join(root, *str(rel).split("/"))
59
+ real = os.path.realpath(root)
60
+ try:
61
+ return path if os.path.commonpath([real, os.path.realpath(path)]) == real else None
62
+ except ValueError:
63
+ return None
64
+
65
+
66
+ def setup_adapters(root=None, agents=None):
67
+ """[(id, adapter)] for every adapter that declares how polyctl is set up in a repository, by id (#76).
68
+
69
+ An adapter takes part when it declares a playbook, a coordination file or an MCP
70
+ registration. With `agents`, only those.
71
+ """
72
+ out = []
73
+ for ident, entry in sorted(A.adapter_catalog(root).items()):
74
+ adapter = entry["adapter"]
75
+ if entry["problem"] or (agents is not None and ident not in agents):
76
+ continue
77
+ directives = adapter.get("directives") or {}
78
+ if directives.get("playbook") or directives.get("coordination") or adapter.get("mcp"):
79
+ out.append((ident, adapter))
80
+ return out
81
+
82
+
83
+ def resolve_agent(name, root=None):
84
+ """An adapter id for a name a person typed: the id itself, or a vendor's name for it."""
85
+ for vendor in A.vendor_list():
86
+ if vendor.get("id") == name and vendor.get("adapter"):
87
+ return vendor["adapter"]
88
+ return name
89
+
90
+
91
+ def agent_choices(root=None):
92
+ """The names `--agent` accepts: every valid adapter, by adapter id and by vendor name.
93
+
94
+ A project's own adapters are among them where `root` names the project: `polyctl -C <repo> init --agent <id>`
95
+ was refused for an adapter the project declared, though init and skill set it up (HARNESS-SETUP-3).
96
+ """
97
+ # A harness with no measured MCP setup still gets the files-only playbook (WARP-ADAPTER).
98
+ ids = {ident for ident, entry in A.adapter_catalog(root).items() if not entry["problem"]}
99
+ names = ids | {vendor["id"] for vendor in A.vendor_list() if vendor.get("adapter") in ids}
100
+ return sorted(names) + ["auto", "all"]
101
+
102
+
103
+ def detect_agents(root, requested="auto"):
104
+ """Which agents read this repository. Cheap signals, each declared by its adapter: directories, files, binaries."""
105
+ if requested and requested not in ("auto", "all"):
106
+ ident = resolve_agent(requested, root)
107
+ return ident, {ident}
108
+ found = set()
109
+ for ident, adapter in setup_adapters(root):
110
+ detect = adapter.get("detect") or {}
111
+ marks = [path for path in (detect.get("dirs") or []) if os.path.isdir(_local(root, path) or "\0")]
112
+ marks += [path for path in (detect.get("files") or []) if os.path.exists(_local(root, path) or "\0")]
113
+ if requested == "all" or marks or any(A.program_path(binary) for binary in detect.get("binaries") or []):
114
+ found.add(ident)
115
+ return None, found or {"generic"}
116
+
117
+
118
+ def _marked(body, header=""):
119
+ """What `_write_marked` writes into a file of its own: `header`, then `body` between the markers."""
120
+ return f"{header}{MARK_START}\n{body.rstrip()}\n{MARK_END}\n"
121
+
122
+
123
+ def _as_written(text):
124
+ """The bytes a text-mode write of `text` leaves on this platform, as `_write_marked` and the MCP merge write it."""
125
+ return text.replace("\n", os.linesep).encode(UTF8)
126
+
127
+
128
+ def _shipped(ident, adapter, read):
129
+ """Whether the adapter polyctl ships as `ident` declares what `adapter` does, as `read` takes it from either.
130
+
131
+ What polyctl writes is recorded as seen only where its own declarations say where and in what words: a project's adapter
132
+ layer is a file an agent can write, and a playbook path or header declared there would put an agent's text under
133
+ polyctl's name (HARNESS-SEEN-OWN).
134
+ """
135
+ shipped = A.package_adapters().get(ident)
136
+ return shipped is not None and read(shipped) == read(adapter)
137
+
138
+
139
+ def _write_marked(root, rel, body, header=""):
140
+ """Write `body` between markers in the file `rel` of the project at `root`; replace an earlier rendering; keep the
141
+ rest.
142
+
143
+ The file is read and replaced whole in its folder, held open from the root down, and never through a link: a
144
+ `.polyctl/PLAYBOOK.md` or a rule file that was a link had polyctl's block added to the file of the person's it led to, and
145
+ one put on the way after a look did the same (LEADS-ADAPTERS). Such a file is "not written: <why>", and nothing
146
+ else is touched.
147
+ """
148
+ block = _marked(body)
149
+ try:
150
+ raw = storage.read_in_tree(root, rel)
151
+ if raw is None:
152
+ # Made only where nothing stands: one that appeared since the read is not written over.
153
+ done = storage.create_in_tree(root, rel, _as_written(header + block))
154
+ return done if done == "wrote" else "not written: it appeared while polyctl wrote it; run this again"
155
+ # As a text-mode read gave it: every line break read as "\n".
156
+ old = raw.decode(UTF8, "replace").replace("\r\n", "\n").replace("\r", "\n")
157
+ if MARK_START in old and MARK_END in old:
158
+ new = old[:old.index(MARK_START)] + block + old[old.index(MARK_END) + len(MARK_END):].lstrip("\n")
159
+ if new == old:
160
+ return "kept"
161
+ storage.replace_in_tree(root, rel, _as_written(new))
162
+ return "updated"
163
+ # Added after the bytes as they stand, as an append left them.
164
+ storage.replace_in_tree(root, rel, raw + _as_written("\n\n" + block))
165
+ return "appended"
166
+ except storage.InTheWay as exc:
167
+ return f"not written: {exc}"
168
+
169
+
170
+ RULE_POINTER = ("## polyctl\n\nThis repository runs under polyctl. Load the `polyctl` playbook "
171
+ "(`.polyctl/PLAYBOOK.md`, or the `polyctl` skill) before coordinating, implementing or reviewing "
172
+ "here, and start every turn with `polyctl status` and the mailbox.")
173
+
174
+
175
+ def rule_file_names(root=None):
176
+ """The owner's rule files: each harness's own, as its adapter declares them, then the shared one."""
177
+ own = sorted({name for _, adapter in setup_adapters(root)
178
+ for name in (adapter.get("directives") or {}).get("rule_files") or []
179
+ if name != SHARED_RULE_FILE and not _escapes(name)})
180
+ return own + [SHARED_RULE_FILE]
181
+
182
+
183
+ def steering_dirs(root=None):
184
+ """Directories whose every file a harness always reads, as the adapters declare them."""
185
+ return sorted({(adapter.get("directives") or {}).get("steering_dir") for _, adapter in setup_adapters(root)} - {None})
186
+
187
+
188
+ def _through_a_link(rel):
189
+ """Why `rel`, a path an adapter declares within the project by its words, is not written: `_local` found it resolve
190
+ out of the project, which only a link on its way or at its name makes it do (LEADS-ADAPTERS)."""
191
+ return f"{rel} leads out of the project through a link, and polyctl writes through none"
192
+
193
+
194
+ def install_playbook(root, agents, rules=False, ours=None, unwritten=None):
195
+ """Render the playbook for each agent. Returns {relpath: wrote|updated|kept|appended|not written: <why>}.
196
+
197
+ Only files polyctl owns are written: the file each adapter declares as its playbook
198
+ and `.polyctl/PLAYBOOK.md`. The owner's rule files sit on the authority boundary: a
199
+ tool that appends instructions to them has, from the reading agent's side,
200
+ issued rules nobody authorised. A coordinator on the second pilot refused
201
+ exactly such lines and escalated them, and was right to. With `rules=True` the
202
+ owner asks for the pointer; otherwise it is printed for them to paste.
203
+
204
+ `ours`, a list when given, gets (path, the bytes polyctl's rendering leaves there) for each file a shipped adapter
205
+ declares that holds nothing but polyctl's text when polyctl has written it, for `A.record_harness_written` to record as seen
206
+ where the file holds exactly that (HARNESS-SEEN-OWN).
207
+
208
+ `unwritten`, a list when given, gets (relpath, why) for each file not written for what stood in its way - a link,
209
+ or a file where a folder goes - which `_write_marked` reads and writes through none (LEADS-ADAPTERS). A path an
210
+ adapter declares outside the project by its words is no such file: it is the adapter's, said as before.
211
+ """
212
+ front, body = playbook()
213
+ out = {}
214
+
215
+ def write(rel, text, header):
216
+ out[rel] = what = _write_marked(root, rel, text, header=header)
217
+ if what.startswith("not written") and unwritten is not None:
218
+ unwritten.append((rel, what[len("not written: "):]))
219
+ return not what.startswith("not written")
220
+
221
+ note = ("<!-- No agent reads this file until a rule file points at it. Paste into "
222
+ + " or ".join(rule_file_names(root)) + ": "
223
+ + RULE_POINTER.split("\n\n", 1)[1].replace("\n", " ")
224
+ + " (or run `polyctl init --rules`). `polyctl doctor` reports rules-not-wired until then. -->\n\n")
225
+ write(".polyctl/PLAYBOOK.md", body, note)
226
+ for ident, adapter in setup_adapters(root, agents):
227
+ target = (adapter.get("directives") or {}).get("playbook") or {}
228
+ if not target.get("path"):
229
+ continue
230
+ header = front if target.get("header") == "frontmatter" else str(target.get("header") or "")
231
+ place = _local(root, target["path"])
232
+ if place is None:
233
+ if _escapes(target["path"]):
234
+ out[target["path"]] = "not written: outside the project"
235
+ else:
236
+ out[target["path"]] = "not written: " + _through_a_link(target["path"])
237
+ if unwritten is not None:
238
+ unwritten.append((target["path"], _through_a_link(target["path"])))
239
+ continue
240
+ if write(target["path"], body, header) and ours is not None \
241
+ and _shipped(ident, adapter, lambda a: (a.get("directives") or {}).get("playbook")):
242
+ ours.append((place, _as_written(_marked(body, header))))
243
+ if rules:
244
+ own = any(name != SHARED_RULE_FILE for _, adapter in setup_adapters(root, agents)
245
+ for name in (adapter.get("directives") or {}).get("rule_files") or [])
246
+ shipped = {name for adapter in A.package_adapters().values()
247
+ for name in (adapter.get("directives") or {}).get("rule_files") or []} | {SHARED_RULE_FILE}
248
+ planned = [name for name in rule_file_names(root)
249
+ if os.path.lexists(os.path.join(root, name)) or name == SHARED_RULE_FILE and not own]
250
+ links = {}
251
+ for name in planned:
252
+ p = os.path.join(root, name)
253
+ if os.path.islink(p):
254
+ # Resolve only to choose among writes this run already makes. Never write through this link;
255
+ # the target still goes through the tree primitive, even if the link changes (LEADS-ADAPTERS).
256
+ try:
257
+ target = os.path.relpath(os.path.realpath(p), os.path.realpath(root)).replace(os.sep, "/")
258
+ except ValueError:
259
+ # Windows has no relative path across drives or shares; name the refusal (LEADS-ADAPTERS).
260
+ why = _through_a_link(name)
261
+ out[name] = "not written: " + why
262
+ if unwritten is not None:
263
+ unwritten.append((name, why))
264
+ continue
265
+ links[name] = target
266
+ continue
267
+ header = "# Agents\n\n" if name == SHARED_RULE_FILE else ""
268
+ if write(name, RULE_POINTER, header) and ours is not None and name in shipped:
269
+ ours.append((p, _as_written(_marked(RULE_POINTER, header))))
270
+ for name, target in links.items():
271
+ if target in planned and target not in links and target in out and not out[target].startswith("not written"):
272
+ out[name] = f"link to {target}; pointer written there once"
273
+ else:
274
+ write(name, RULE_POINTER, "")
275
+ return out
276
+
277
+
278
+ def _toml_string_body(value):
279
+ """`value` escaped as the inside of a double-quoted TOML string (#71).
280
+
281
+ A manual snippet quotes `{exe}` and `{root}`, and a TOML basic string reads a
282
+ backslash as an escape: a Windows root, C:\\Users\\..., began with a \\U the parser
283
+ refused. Backslashes and quotes are escaped, and control characters written as
284
+ \\uXXXX, which JSON and YAML double-quoted strings read the same way.
285
+ """
286
+ out = []
287
+ for char in str(value):
288
+ if char in "\\\"":
289
+ out.append("\\" + char)
290
+ elif char < " " or char == "\x7f":
291
+ out.append(f"\\u{ord(char):04X}")
292
+ else:
293
+ out.append(char)
294
+ return "".join(out)
295
+
296
+
297
+ def registration_role(root, ident):
298
+ """The role the polyctl MCP registration for harness `ident` names in this project, or None (MCP-ROLES).
299
+
300
+ Read from the project's role blocks: the roles whose block, or a reviewer's fallback, runs
301
+ a harness that reads the registration. That is every harness whose adapter declares the
302
+ same file, since two harnesses can read one file and a file holds one `polyctl` entry; a
303
+ registration a person adds by hand is read by its own harness alone. Exactly one role names
304
+ it. Several, or none, name nothing, and the server serves every tool, as before roles
305
+ existed: a registration read by two roles' sessions cannot hold either to its own tools,
306
+ and naming one would take tools from the other. A project on a capability matrix binds its
307
+ roles to declared tools rather than to harnesses, and its registrations name none.
308
+ """
309
+ adapters = dict(setup_adapters(root))
310
+ declared = ((adapters.get(ident) or {}).get("mcp") or {}).get("file")
311
+ readers = {ident} | {other for other, adapter in adapters.items()
312
+ if declared and (adapter.get("mcp") or {}).get("file") == declared}
313
+ document = A.project_config_document(root)["config"]
314
+ if not isinstance(document, dict) or M.is_strict(document):
315
+ return None
316
+ cfg = A.resolve_roles(root, dict(document))
317
+ held = set()
318
+ for role in A.ROLE_BLOCKS:
319
+ block = cfg.get(role) if isinstance(cfg.get(role), dict) else {}
320
+ runs = [block]
321
+ if role == "reviewer":
322
+ runs += list(block.get("fallbacks") or [])
323
+ if any(A.block_adapter(each) in readers for each in runs):
324
+ held.add(role)
325
+ return held.pop() if len(held) == 1 else None
326
+
327
+
328
+ def _snippet(template, exe, root, args):
329
+ """A manual registration's snippet with `{exe}`, `{root}` and `{args}` filled in one pass.
330
+
331
+ One pass, so a value holding a placeholder's spelling is never filled again. `{args}` is the
332
+ server's arguments as a bracketed list of double-quoted strings, each escaped as `{root}` is.
333
+ """
334
+ values = {"exe": _toml_string_body(exe), "root": _toml_string_body(root),
335
+ "args": "[" + ", ".join(f'"{_toml_string_body(arg)}"' for arg in args) + "]"}
336
+ return re.sub(r"\{(exe|root|args)\}", lambda match: values[match.group(1)], str(template or ""))
337
+
338
+
339
+ def register_mcp(root, agents, exe=None, ours=None, unwritten=None):
340
+ """Register the polyctl MCP server for each agent, in the file its adapter declares.
341
+
342
+ Merged, never clobbered: other servers in the same file survive. Returns
343
+ {agent: what happened}. A harness that keeps its servers in a user-level file
344
+ gets the snippet its adapter declares, and the human decides. Each registration
345
+ names the role its readers hold in this project, when they hold one (`registration_role`).
346
+
347
+ `ours`, a list when given, gets (path, the bytes a file holding polyctl's entry alone has) for each file a shipped
348
+ adapter declares, as install_playbook's does (HARNESS-SEEN-OWN). One the harness's own `register` command wrote is
349
+ in that harness's words, not polyctl's, and is left for a person to see.
350
+
351
+ The file is read and replaced whole in its folder, held open from the root down, never through a link: one that
352
+ was a link, or was made one after `_local` looked where it resolves, had the person's file it led to read and
353
+ written over with polyctl's entry beside what it held (LEADS-ADAPTERS). `unwritten`, a list when given, gets
354
+ (file, why) for each registration not written for what stood in its way, as install_playbook's does. A harness's
355
+ own `register` command cannot promise that: known JSON formats use polyctl's merge, other formats are refused.
356
+ """
357
+ # The polyctl the registration names runs as the person whenever a harness starts it: one named by an absolute path,
358
+ # never one the current directory holds (WINDOWS-NO-CWD-EXEC).
359
+ exe = exe or A.polyctl_program()
360
+ out = {}
361
+
362
+ def merge(rel, server, key="mcpServers", extra=None):
363
+ data = {}
364
+ raw = storage.read_in_tree(root, rel)
365
+ if raw is not None:
366
+ try:
367
+ data = json.loads(raw.decode(UTF8))
368
+ except ValueError:
369
+ data = {}
370
+ servers = data.setdefault(key, {})
371
+ entry = dict(server, **(extra or {}))
372
+ if servers.get("polyctl") == entry:
373
+ return "kept"
374
+ servers["polyctl"] = entry
375
+ storage.replace_in_tree(root, rel, _as_written(json.dumps(data, indent=2)))
376
+ return "registered"
377
+
378
+ def refused(ident, rel, why):
379
+ out[ident] = f"not written: {why}; add polyctl to it by hand, or make it a file of the project's own and run polyctl " \
380
+ "init again"
381
+ if unwritten is not None:
382
+ unwritten.append((rel, why))
383
+
384
+ for ident, adapter in setup_adapters(root, agents):
385
+ mcp = adapter.get("mcp") or {}
386
+ if exe is None and (mcp.get("manual") or mcp.get("file")):
387
+ # A registration naming a program that is not there starts nothing, and says nothing of why (the review
388
+ # of WINDOWS-NO-CWD-EXEC): none is written until polyctl can be named by an absolute path.
389
+ out[ident] = ("not registered: no polyctl program to name - none is on PATH and this polyctl was not started from "
390
+ "one; put polyctl on PATH and run polyctl init again")
391
+ continue
392
+ role = registration_role(root, ident)
393
+ args = ["-C", root, "mcp", "serve"] + (["--role", role] if role else [])
394
+ if mcp.get("manual"):
395
+ out[ident] = f"manual: add to {mcp['manual']}\n{_snippet(mcp.get('snippet'), exe, root, args)}"
396
+ continue
397
+ if not mcp.get("file"):
398
+ continue
399
+ path = _local(root, mcp["file"])
400
+ if path is None:
401
+ if _escapes(mcp["file"]):
402
+ out[ident] = f"not written: {mcp['file']} lies outside the project; add polyctl to it by hand"
403
+ else:
404
+ refused(ident, mcp["file"], _through_a_link(mcp["file"]))
405
+ continue
406
+ server = {"command": exe, "args": args}
407
+ # A command named for a person comes from a shipped adapter alone (HARNESS-SETUP-2, LEADS-ADAPTERS).
408
+ register = ((A.package_adapters().get(ident) or {}).get("mcp") or {}).get("register") or []
409
+ key, extra = mcp.get("key", "mcpServers"), mcp.get("extra")
410
+ known = mcp.get("format", "json" if mcp["file"].lower().endswith(".json") else None) == "json"
411
+ if not known:
412
+ command = [part.replace("{exe}", exe).replace("{args}", json.dumps(args)) for part in register]
413
+ why = "polyctl cannot write this MCP format through no link"
414
+ if command:
415
+ why += "; run this command yourself: " + shlex.join(command)
416
+ refused(ident, mcp["file"], why)
417
+ continue
418
+ try:
419
+ out[ident] = merge(mcp["file"], server, key, extra)
420
+ except storage.InTheWay as exc:
421
+ refused(ident, mcp["file"], str(exc))
422
+ continue
423
+ if ours is not None and _shipped(ident, adapter, lambda a: a.get("mcp")):
424
+ ours.append((path, _as_written(json.dumps({key: {"polyctl": dict(server, **(extra or {}))}}, indent=2))))
425
+ return out
426
+
427
+
428
+ def polyctl_files(root=None):
429
+ """(paths, [(mcp file, server, remove when empty)]) polyctl may have written for any harness, for `polyctl remove`.
430
+
431
+ The paths are those the adapter the package ships under each id declares. A user's or a project's layer is a
432
+ file the agents it describes can write, and `"polyctl_files": ["src/"]` there had the removal delete the project's
433
+ source: what a layer names beyond them is layer_polyctl_files', which the removal names and leaves (REMOVE-SHIPPED).
434
+ An MCP file stays every adapter's, since only the `polyctl` entry that runs polyctl's server is taken from it.
435
+ """
436
+ paths, mcp_files = [], []
437
+ shipped = A.package_adapters()
438
+ for ident, adapter in setup_adapters(root):
439
+ own = ((shipped.get(ident) or {}).get("directives") or {}).get("polyctl_files") or []
440
+ paths += [path for path in own if path not in paths and not _escapes(path)]
441
+ mcp = adapter.get("mcp") or {}
442
+ if mcp.get("file") and not _escapes(mcp["file"]):
443
+ mcp_files.append((os.path.join(*mcp["file"].split("/")), "polyctl", bool(mcp.get("remove_when_empty"))))
444
+ return paths, mcp_files
445
+
446
+
447
+ def layer_polyctl_files(root=None):
448
+ """The paths a user's or a project's adapter layer names as polyctl's and no shipped adapter does: `polyctl remove` names
449
+ them and deletes none, since an agent can write the layer (REMOVE-SHIPPED)."""
450
+ shipped, _ = polyctl_files(root)
451
+ out = []
452
+ for _, adapter in setup_adapters(root):
453
+ for path in (adapter.get("directives") or {}).get("polyctl_files") or []:
454
+ if isinstance(path, str) and path not in shipped and path not in out and not _escapes(path):
455
+ out.append(path)
456
+ return out
457
+
458
+
459
+ def next_steps(agents, registered):
460
+ """What the human has to do now — the one thing the tool cannot do for them."""
461
+ names = [adapter.get("name") or ident for ident, adapter in setup_adapters(None, agents)]
462
+ lines = []
463
+ if names:
464
+ lines.append(f"Start or restart {' / '.join(names)} in this directory so the `polyctl` MCP "
465
+ f"tools load (registered: "
466
+ f"{', '.join(f'{k}: {v.splitlines()[0]}' for k, v in registered.items())}).")
467
+ else:
468
+ lines.append("No MCP-capable agent detected; the mailbox protocol works from the files alone.")
469
+ lines.append("Then `polyctl doctor` — binaries, channels, watchdog — and `polyctl email setup` if it says no channel.")
470
+ lines.append("Write the first slice into .polyctl/backlog.md with an acceptance boundary; the agent takes it from there.")
471
+ return lines
472
+
473
+
474
+ def rules_wired(root):
475
+ """Does any file the agents read point at the playbook?
476
+
477
+ True when a rule file mentions the playbook or the skill, None when no
478
+ playbook has been installed (nothing to wire), False when the playbook is
479
+ there and nothing references it — written, not in force.
480
+ """
481
+ if not os.path.exists(os.path.join(root, ".polyctl", "PLAYBOOK.md")):
482
+ return None
483
+ needles = ("PLAYBOOK.md", "skills/polyctl", "polyctl-playbook", "polyctl-coordination", "polyctl")
484
+ candidates = [os.path.join(root, name) for name in rule_file_names(root)]
485
+ for steering in steering_dirs(root):
486
+ place = _local(root, steering)
487
+ if place and os.path.isdir(place):
488
+ candidates += [os.path.join(place, f) for f in os.listdir(place)]
489
+ # A harness can discover skills without declaring how polyctl sets up MCP or rules (WARP-ADAPTER).
490
+ for entry in A.adapter_catalog(root).values():
491
+ if entry["problem"]:
492
+ continue
493
+ skills = (entry["adapter"].get("directives") or {}).get("skills_dir")
494
+ place = _local(root, skills)
495
+ if place and os.path.isdir(os.path.join(place, "polyctl")):
496
+ return True # a skill is discovered by the agent on its own
497
+ for p in candidates:
498
+ try:
499
+ if any(n in open(p, encoding="utf-8", errors="replace").read() for n in needles):
500
+ return True
501
+ except OSError:
502
+ continue
503
+ return False