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,2857 @@
1
+ """The project: digest, notes, templates, init and profiles, decisions, the board, holds, fan-out,
2
+ e-mail, alarms, the playbook.
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 cmd_digest(cfg, args):
10
+ """What happened in a window — read from the ledgers, never estimated.
11
+
12
+ Event alerts answer "did something just occur". They cannot answer "is this
13
+ week going well", and reconstructing that from thirty notifications is asking
14
+ a human to do the tool's job.
15
+
16
+ It also absorbs the question people actually ask most: *why is nothing
17
+ moving*. That is not a separate command — it is the same facts, read at the
18
+ top instead of the bottom.
19
+ """
20
+ root = cfg["root"]
21
+ d = A.digest(root, cfg, args.days)
22
+
23
+ def say(key, **values):
24
+ # In the project's language; a count, a verdict and a command read the same in any (LANGUAGE-OUTPUT).
25
+ return language.text(cfg, key, **values)
26
+
27
+ days = int(args.days) if args.days == int(args.days) else args.days
28
+ win = say("digest.day") if args.days == 1 else say("digest.days", n=days)
29
+
30
+ # Lead with the blocking answer. Someone opening this at 3am wants "what is
31
+ # in the way", not a scoreboard.
32
+ impl = cfg.get("implementer") or {}
33
+ adapter = A.load_adapter(impl.get("adapter", "")) if impl else {}
34
+ state, age, doing = A.busy(cfg, adapter) if impl else ("unknown", None, "")
35
+ spin = A.spinning(root)
36
+ print(f"{C['b']}{cfg.get('project') or os.path.basename(root)}{C['reset']}"
37
+ f"{C['dim']} {say('digest.window', window=win)}{C['reset']}\n")
38
+
39
+ col = {"working": C["green"], "slowing": C["yellow"]}.get(state, C["red"])
40
+ line = f"{col}{state}{C['reset']}"
41
+ if age is not None:
42
+ line += f"{C['dim']}{say('digest.last-write', minutes=age // 60)}{C['reset']}"
43
+ if spin:
44
+ line += f" {C['red']}{say('digest.spinning', minutes=spin)}{C['reset']}"
45
+ print(f" {say('digest.state'):<9}{line}")
46
+ if doing:
47
+ print(f" {C['dim']}↳ {doing[:110]}{C['reset']}")
48
+
49
+ if d["decisions"]["open"]:
50
+ print(f"\n {C['yellow']}{say('digest.open-decisions', n=d['decisions']['open'])}{C['reset']}"
51
+ f"{C['dim']} — {say('digest.unblocks')}{C['reset']}")
52
+ for b in d["blocked"]:
53
+ print(f" {C['red']}⊘{C['reset']} {b['id']} {C['dim']}{b['needs'][:88]}{C['reset']}")
54
+
55
+ print(_digest_heading(say("digest.landed")))
56
+ print(f" {C['b']}{len(d['commits'])}{C['reset']} commit"
57
+ f"{C['dim']}, {say('digest.unpushed', n=d['unpushed'])}{C['reset']}")
58
+ for c in d["commits"][:args.n]:
59
+ print(f" {C['dim']}{c['sha']}{C['reset']} {c['subject'][:76]}")
60
+
61
+ v, a, r = d["verifications"], d["authority"], d["reviews"]
62
+ print(_digest_heading(say("digest.gates")))
63
+ vf = f", {C['red']}{say('digest.failed', n=v['failed'])}{C['reset']}" if v["failed"] else ""
64
+ rc = f", {C['yellow']}{say('digest.changes', n=r['changes'])}{C['reset']}" if r["changes"] else ""
65
+ ar = f", {C['yellow']}{say('digest.refused', n=a['refused'])}{C['reset']}" if a["refused"] else ""
66
+ print(f" {say('digest.verify'):<11}{C['green']}{say('digest.passed', n=v['passed'])}{C['reset']}{vf}")
67
+ print(f" review {C['green']}{r['approved']} APPROVED{C['reset']}{rc}")
68
+ if a.get("integrity") == "broken":
69
+ print(f" commit-ok {C['red']}{say('digest.ledger-broken')}{C['reset']}")
70
+ if a.get("error"):
71
+ print(f" {C['dim']}{a['error'][:110]}{C['reset']}")
72
+ else:
73
+ print(f" commit-ok {C['green']}{say('digest.granted', n=a['granted'])}{C['reset']}{ar}")
74
+ # A refusal repeated all week is a process problem, not an incident.
75
+ for reason, n in d["refusal_reasons"]:
76
+ if n > 1:
77
+ print(f" {C['dim']}{n}× {reason}{C['reset']}")
78
+
79
+ dec = d["decisions"]
80
+ if dec["asked"]:
81
+ med = say("digest.minutes", n=dec["median_minutes"]) if dec["median_minutes"] is not None else "—"
82
+ answered = say("digest.answered", answered=dec["answered"], asked=dec["asked"])
83
+ print(f"\n {say('digest.decisions'):<11}{answered}"
84
+ f"{C['dim']}, {say('digest.median', median=med)}{C['reset']}")
85
+
86
+ account = d.get("account") or {}
87
+ if d.get("credits"):
88
+ c = d["credits"]
89
+ pct = c["used"] / c["limit"] * 100 if c["limit"] else 0
90
+ cc = C["red"] if pct > 90 else C["yellow"] if pct > 70 else C["green"]
91
+ print(_digest_heading(say("digest.credit")))
92
+ left = say("digest.left", n=f"{c['remaining']:,.0f}")
93
+ print(f" {cc}{c['used']:,.0f}{C['reset']} / {c['limit']:,.0f}"
94
+ f"{C['dim']} ({left}){C['reset']}")
95
+ elif account and not account.get("readable"):
96
+ # Where the figure stood, the implementer's adapter declares no account (ACCOUNT-READERS).
97
+ print(_digest_heading(say("digest.credit")))
98
+ print(f" {C['dim']}{_no_account(account.get('adapter'))}{C['reset']}")
99
+ for day, val in d["credit_days"][-args.n:]:
100
+ print(f" {C['dim']}{day}{C['reset']} {val:>8,.0f}")
101
+
102
+ al = d["alerts"]
103
+ print(f"\n{C['dim']}{say('digest.board')} " +
104
+ " · ".join(f"{k} {n}" for k, n in d["board"].items()) +
105
+ f" | {say('digest.alerts', sent=al['sent'], held=al['held'])}{C['reset']}")
106
+ return 0
107
+
108
+
109
+ def _digest_heading(label):
110
+ """A digest section's heading, ruled to the same width whatever the length of its label in a language."""
111
+ return f"\n{C['b']}{C['mag']}── {label} {'─' * (53 - len(label))}{C['reset']}"
112
+
113
+
114
+ def cmd_note(cfg, args):
115
+ """Write an architect message into the mailbox — through the tool, on purpose.
116
+
117
+ A woken architect should need no raw Write or Edit to do its job. The one
118
+ time it had them, it used them on the orchestrator's own source and built a
119
+ runaway. This is the only door to the mailbox an unattended architect gets.
120
+ """
121
+ # Read stdin only when asked. Defaulting to it made `polyctl note "title"` hang
122
+ # waiting on a terminal that would never close, which is the wrong failure
123
+ # for a command an unattended architect calls.
124
+ body = args.body if args.body else (sys.stdin.read() if args.stdin else "")
125
+ if not args.title or not body.strip():
126
+ print(f"usage: {C['b']}polyctl note \"title\" --body \"…\" [--to implementer] [--urgent]{C['reset']}")
127
+ print(f" {C['dim']}or pipe the body on stdin{C['reset']}")
128
+ return 1
129
+ name = A.note(cfg["root"], cfg, args.to, args.title, body, urgent=args.urgent)
130
+ print(f"{C['green']}written{C['reset']} {cfg['mailbox']}/{name}")
131
+ if args.urgent:
132
+ print(f"{C['dim']}urgent: reaches the implementer via polyctl lock, polyctl verify and "
133
+ f"polyctl commit-ok{C['reset']}")
134
+ return 0
135
+
136
+
137
+ # The board, backlog, authority and mailbox files `polyctl init` writes are in language.py, in the
138
+ # project's language (LANGUAGE-FILES). This steering is English in every project, as it always
139
+ # was; only the urgent heading it names is the project's, filled in as {urgent}.
140
+ STEERING_COORD = """---
141
+ inclusion: always
142
+ ---
143
+
144
+ # Coordination: the `polyctl` tools
145
+
146
+ Every turn starts with `polyctl_inbox`; apply or explicitly reject each message, then
147
+ `polyctl_ack`. Report changes as they happen: `polyctl_report {{kind: "blocked"|"status"|"done"}}`.
148
+ When you need a decision, ask with options — `polyctl_ask` — and move to the next queued
149
+ item; do not park on prose. Check `polyctl_decisions` next turn.
150
+
151
+ Urgent messages (`{urgent}`) reach you through `polyctl lock`, `polyctl verify` and every `polyctl_*`
152
+ response. `polyctl commit-ok` refuses authority until you acknowledge them; an installed
153
+ polyctl pre-commit hook runs `polyctl commit-check` to revalidate them immediately before commit.
154
+
155
+ Review with `polyctl review`, never yourself. `polyctl commit-ok` refuses a review you wrote.
156
+ Heavy commands go through the machine lock: `polyctl lock -- <cmd>`. `polyctl verify` takes it
157
+ itself. Authority lives in `.polyctl/authority.md`, not in mail. `push` is never yours.
158
+ """
159
+
160
+
161
+ # Directories one level down whose manifests are a build's output or another project's dependencies, not a project
162
+ # of this repository's: a package.json copied into dist/ is no workspace (TRIAGE-HIGHS).
163
+ GATE_DETECTION_SKIPS = ("node_modules", "vendor", "dist", "build", "target", "venv")
164
+
165
+
166
+ def _detect_gates(root, children=True):
167
+ """Guess the project's gates from what is already there. A wrong guess costs a
168
+ failed verify, which is visible; no guess costs an empty gate file nobody
169
+ notices, which is not.
170
+
171
+ Every toolchain found gets its gates (#5): a repository with a JavaScript
172
+ workspace and a .NET backend got npm gates only, and nothing verified the
173
+ backend. A toolchain was found by its manifest at the top alone, so a backend
174
+ whose project file sat in backend/ still got none, and init went ahead: its
175
+ manifest one directory down gives gates that run there and declare it as their
176
+ inputs, and Maven, Gradle and Swift packages are found too (TRIAGE-HIGHS).
177
+ """
178
+ gates, quick = {}, []
179
+ _detect_toolchain_gates(root, ".", gates, quick)
180
+ for gate in gates.values():
181
+ gate["inputs"] = ["**"]
182
+ # A backend one level down was left out beside a root package.json (TRIAGE-2-MEDIUM).
183
+ if children:
184
+ for child in sorted(os.listdir(root)):
185
+ path = os.path.join(root, child)
186
+ if child.startswith(".") or child in GATE_DETECTION_SKIPS \
187
+ or not os.path.isdir(path) or os.path.islink(path):
188
+ continue
189
+ found = _detect_gates(path, children=False)
190
+ # An unrelated directory needs no shell spelling (TRIAGE-2-MEDIUM).
191
+ if set(found["gates"]) == {"diff-check"}:
192
+ continue
193
+ quoted = A.copyable_word(child)
194
+ if quoted is None:
195
+ raise ValueError(f"cannot quote gate directory {child!r}; rename it or declare its gates by hand")
196
+ for name, gate in found["gates"].items():
197
+ if name == "diff-check":
198
+ continue
199
+ scoped = f"{child}-{name}"
200
+ gates[scoped] = dict(gate, run=f"cd {quoted} && {gate['run']}",
201
+ inputs=[f"{child}/**"])
202
+ if name in found["profiles"]["quick"]:
203
+ quick.append(scoped)
204
+ gates["diff-check"] = {"run": "git diff --check", "expect": "exit_zero", "timeout": 60}
205
+ quick.append("diff-check")
206
+ return {"gates": gates,
207
+ "profiles": {"quick": quick, "full": list(gates)},
208
+ "default_profile": "quick"}
209
+
210
+
211
+ def _detect_toolchain_gates(root, where, gates, quick):
212
+ """Add to `gates` the gates of each toolchain whose manifest `where` holds - "." for the top of the repository,
213
+ else a directory one level down - and their quick ones to `quick` (#5, TRIAGE-HIGHS).
214
+
215
+ One directory down a gate is named after the directory, runs in it and declares it as its inputs, so the
216
+ coverage check reads it as reaching that tree and no other.
217
+ """
218
+ here = os.path.join(root, where)
219
+ down = where != "."
220
+
221
+ def gate(name, run, timeout, fast=False, serialise=False):
222
+ named = f"{where}-{name}" if down else name
223
+ gates[named] = {"run": f"cd {where} && {run}" if down else run, "expect": "exit_zero", "timeout": timeout}
224
+ if serialise:
225
+ gates[named]["serialise"] = True
226
+ if down:
227
+ gates[named]["inputs"] = [f"{where}/**"]
228
+ if fast:
229
+ quick.append(named)
230
+
231
+ def holds(*names):
232
+ return any(os.path.isfile(os.path.join(here, name)) for name in names)
233
+
234
+ if holds("package.json"):
235
+ try:
236
+ with open(os.path.join(here, "package.json"), encoding=UTF8) as fh:
237
+ scripts = json.load(fh).get("scripts") or {}
238
+ except Exception:
239
+ scripts = {}
240
+ for name in ("typecheck", "lint", "test"):
241
+ if name in scripts:
242
+ gate(name, f"npm run {name}", 600 if name != "test" else 2400, fast=name != "test",
243
+ serialise=name == "test")
244
+ if holds("pyproject.toml", "setup.py"):
245
+ gate("pytest", "python -m pytest -q", 2400, serialise=True)
246
+ # Collecting imports every test module: cheap, and it exercises the code.
247
+ gate("pytest-collect", "python -m pytest --collect-only -q", 300, fast=True)
248
+ if A.program_path("ruff"):
249
+ gate("ruff", "ruff check .", 300, fast=True)
250
+ try:
251
+ dotnet = any(name.endswith((".sln", ".csproj", ".fsproj")) for name in os.listdir(here))
252
+ except OSError:
253
+ dotnet = False
254
+ if dotnet:
255
+ gate("dotnet-build", "dotnet build --nologo -v q", 1200, fast=True)
256
+ gate("dotnet-test", "dotnet test --nologo", 2400, serialise=True)
257
+ if holds("go.mod"):
258
+ gate("go-vet", "go vet ./...", 600, fast=True)
259
+ gate("go-test", "go test ./...", 2400, serialise=True)
260
+ if holds("Cargo.toml"):
261
+ gate("cargo-check", "cargo check", 1200, fast=True)
262
+ gate("cargo-test", "cargo test", 2400, serialise=True)
263
+ if holds("pom.xml"):
264
+ gate("maven-compile", "mvn -q -B compile", 1200, fast=True)
265
+ gate("maven-verify", "mvn -q -B verify", 2400, serialise=True)
266
+ if holds("build.gradle", "build.gradle.kts"):
267
+ # The project's own wrapper where it has one; cmd.exe runs gradlew.bat by that name.
268
+ gradle = ("gradlew" if os.name == "nt" else "./gradlew") if holds("gradlew", "gradlew.bat") else "gradle"
269
+ gate("gradle-assemble", f"{gradle} assemble --quiet", 1200, fast=True)
270
+ gate("gradle-check", f"{gradle} check --quiet", 2400, serialise=True)
271
+ if holds("Package.swift"):
272
+ gate("swift-build", "swift build", 1200, fast=True)
273
+ gate("swift-test", "swift test", 2400, serialise=True)
274
+
275
+
276
+ def _models(adapter_id):
277
+ try:
278
+ return A.load_adapter(adapter_id).get("models") or {}
279
+ except Exception:
280
+ return {}
281
+
282
+
283
+ def _reviewer_block(adapter_id, model=None):
284
+ """A reviewer block composed from its adapter: its actor's name, family, and argv (#88, #76)."""
285
+ declared = A.load_adapter(adapter_id)
286
+ route = A.compose_reviewer(adapter_id, model=model)
287
+ name = declared.get("actor_name") or adapter_id
288
+ block = {"id": f"{name}-reviewer-{model}" if model else f"{name}-reviewer"}
289
+ if declared.get("family"):
290
+ block["family"] = declared["family"]
291
+ block["argv"] = route["argv"]
292
+ return block
293
+
294
+
295
+ def _architect_argv(adapter_id):
296
+ """The architect's argv: its adapter's resume, with the implementer's grant replaced by `options.architect_tools`.
297
+
298
+ The grant is the adapter's to spell (#58, GRANTS-PINNED): every polyctl command the playbook's
299
+ routine and the wake and refill prompts name, and writes to polyctl's coordination files only.
300
+ An adapter that declares how to grant tools but no architect grant leaves the architect
301
+ none: a wake then only reads, rather than holding the implementer's grant.
302
+
303
+ Composed from the adapter the package ships alone: init writes this command into
304
+ .polyctl/config.json and accepts it as seen, and a wake starts it, so a resume or a grant a
305
+ user's layer declared - ~/.polyctl/adapters, which an agent can write - was taken into every
306
+ wake with no person having read it. A command polyctl runs comes from the package, as a turn's
307
+ is composed at the wake (TURN-ARGV, TRIAGE-HIGHS).
308
+ """
309
+ declared = A.turn_adapter(adapter_id) or {}
310
+ argv = list((declared.get("resume") or {}).get("argv") or [])
311
+ options = declared.get("options") or {}
312
+ grant = options.get("allowed_tools") or []
313
+ if grant:
314
+ while grant[0] in argv:
315
+ at = argv.index(grant[0])
316
+ del argv[at:at + 2]
317
+ if options.get("architect_tools"):
318
+ argv += [part.replace("{tools}", options["architect_tools"]) for part in grant]
319
+ return argv
320
+
321
+
322
+ def _can_architect(adapter_id, adapter=None):
323
+ """Whether `adapter_id` has a restricted architect wake command scoped to coordination-only tools."""
324
+ from . import allowlist as AL
325
+ declared = adapter if isinstance(adapter, dict) else (A.turn_adapter(adapter_id) or {})
326
+ if not declared or declared.get("kind") in ("cloud", "model-backend", "tool-reviewer"):
327
+ return False
328
+ if A.tool_review_contract(declared) is not None:
329
+ return False
330
+ roles_decl = declared.get("roles") if isinstance(declared.get("roles"), dict) else {}
331
+ if str(roles_decl.get("architect") or "").startswith(("ineligible", "untested")):
332
+ return False
333
+ options = declared.get("options") if isinstance(declared.get("options"), dict) else {}
334
+ if not options.get("allowed_tools") or not options.get("architect_tools"):
335
+ return False
336
+ argv = _architect_argv(adapter_id)
337
+ if not argv or not any("{session}" in str(part) for part in argv) or not any("{prompt}" in str(part) for part in argv):
338
+ return False
339
+ if not A.carries_scope(argv) or not AL.rules(argv):
340
+ return False
341
+ if AL.problems(argv, options, role="architect"):
342
+ return False
343
+ return A.turn_refusal("architect", adapter_id, argv) is None
344
+
345
+
346
+ def _configured_roles(root, cfg):
347
+ """The role blocks `cfg` already has, directly or through its role table."""
348
+ if not isinstance(cfg, dict):
349
+ return []
350
+ resolved = A.resolve_roles(root, dict(cfg))
351
+ table = cfg.get("roles") if isinstance(cfg.get("roles"), dict) else {}
352
+ return [role for role in ("implementer", "reviewer", "architect") if role in resolved or role in table]
353
+
354
+
355
+ def _profile_config(root, args, base):
356
+ """Return the profile's intended config and added block names without writing.
357
+
358
+ --review-tier chooses the tier a single harness reviews at (REVIEW-TIERS): `person` writes no
359
+ model reviewer, and `same-family` writes review.same_family labeled, which init records as the
360
+ person's opt-in once it writes.
361
+ """
362
+ cfg = dict(base) if isinstance(base, dict) else {}
363
+ presets = A.profiles(root)
364
+ given_roles = getattr(args, "roles", None)
365
+ prof = dict(given_roles) if isinstance(given_roles, dict) else presets.get(getattr(args, "profile", None) or "")
366
+ impl_adapter = getattr(args, "implementer", None) or (prof or {}).get("implementer")
367
+ tier = getattr(args, "review_tier", None)
368
+ opted = []
369
+ if tier == "same-family" and S.lookup(cfg, "review.same_family") != "labeled":
370
+ cfg["review"] = dict(cfg["review"]) if isinstance(cfg.get("review"), dict) else {}
371
+ S.assign(cfg, "review.same_family", "labeled")
372
+ opted.append("review.same_family labeled")
373
+ if not impl_adapter and not prof:
374
+ return cfg, opted
375
+ present = set(_configured_roles(root, cfg))
376
+ roles = prof or presets.get(A.default_profile(root)) or {}
377
+ added = []
378
+ if "implementer" not in present:
379
+ impl_adapter = impl_adapter or roles.get("implementer")
380
+ block = {"adapter": impl_adapter, "session": "auto",
381
+ "name": A.load_adapter(impl_adapter).get("actor_name") or impl_adapter}
382
+ model = getattr(args, "model", None) or _models(impl_adapter).get("default")
383
+ if model:
384
+ block["model"] = model
385
+ if getattr(args, "effort", None):
386
+ block["effort"] = args.effort
387
+ cfg["implementer"] = block
388
+ added.append("implementer")
389
+ if "reviewer" not in present and tier != "person":
390
+ # With --review-tier person no model reviews: a person reviews each candidate.
391
+ existing_impl = (cfg.get("implementer") or {}).get("adapter") if isinstance(cfg.get("implementer"), dict) else None
392
+ reviewer = (impl_adapter or existing_impl) if tier == "same-family" and not prof else roles.get("reviewer")
393
+ rmodel = getattr(args, "reviewer_model", None) or _models(reviewer).get("review")
394
+ cfg["reviewer"] = dict(_reviewer_block(reviewer, rmodel),
395
+ _why="must not be the implementer; a different model where one is available")
396
+ added.append("reviewer")
397
+ architect = roles.get("architect")
398
+ if "architect" not in present and architect and _can_architect(architect):
399
+ cfg["architect"] = {"adapter": architect, "session": "auto", "cwd": root, "name": "architect",
400
+ "argv": _architect_argv(architect),
401
+ "_why": "resumable and woken only into absence; read-only tools plus polyctl"}
402
+ added.append("architect")
403
+ return cfg, added + opted
404
+
405
+
406
+ def _apply_profile(root, args):
407
+ """Write missing profile blocks while preserving existing project choices.
408
+
409
+ A config that exists but cannot be read is refused: planning from an empty
410
+ document and writing the plan over it would erase what it held (#56).
411
+ """
412
+ document = A.project_config_document(root)
413
+ if document["problem"] and os.path.lexists(os.path.join(root, ".polyctl", "config.json")):
414
+ raise ValueError(document["problem"])
415
+ planned, added = _profile_config(root, args, document["config"] or {})
416
+ if added:
417
+ A.write_project_config(root, json.dumps(planned, indent=2, ensure_ascii=False))
418
+ return added
419
+
420
+
421
+ def _planned_project_config_text(cfg):
422
+ """Serialize and validate one in-memory config against the disk contract."""
423
+ if not isinstance(cfg, dict) or not cfg:
424
+ return None, ".polyctl/config.json must be a non-empty top-level JSON object"
425
+ try:
426
+ text = json.dumps(cfg, indent=2, ensure_ascii=False) + "\n"
427
+ raw = text.encode(UTF8)
428
+ except (TypeError, ValueError, UnicodeError, RecursionError) as exc:
429
+ return None, f".polyctl/config.json is not readable valid JSON ({exc})"
430
+ if len(raw) > A.PROJECT_CONFIG_MAX_BYTES:
431
+ return None, (
432
+ ".polyctl/config.json exceeds the "
433
+ f"{A.PROJECT_CONFIG_MAX_BYTES:,}-byte limit"
434
+ )
435
+ problem = A._json_container_depth_problem(raw)
436
+ return (None, problem) if problem else (text, None)
437
+
438
+
439
+ def _planned_runtime_config(root, cfg):
440
+ """Apply load_config's runtime-only defaults to an in-memory document."""
441
+ runtime = dict(cfg)
442
+ runtime.setdefault("root", root)
443
+ runtime.setdefault("mailbox", "agent-mail")
444
+ runtime.setdefault("reviews", "semantic-review")
445
+ A.resolve_roles(root, runtime)
446
+ if "implementer" not in runtime:
447
+ found = A.discover_session(root)
448
+ if found:
449
+ runtime["implementer"] = found
450
+ return runtime
451
+
452
+
453
+ def _init_tier_hints(args, root=None):
454
+ """How `polyctl init` goes on after its probe refused a reviewer no review tier admits (REVIEW-TIERS)."""
455
+ profile = getattr(args, "profile", None)
456
+ base = f"polyctl init --profile {profile}" if profile else " ".join(
457
+ ["polyctl init"] + ([f"--implementer {args.implementer}"] if getattr(args, "implementer", None) else []))
458
+ other = A.default_profile(root)
459
+ lines = [f"{C['dim']}or, at init:{C['reset']}"]
460
+ if other and other != profile:
461
+ lines.append(f"polyctl init --profile {other} a reviewer of another model family: the strongest tier")
462
+ lines.append(f"{base} --review-tier same-family --by <name> another model of the same family, labeled "
463
+ "weaker independence; a person opts in, on the record")
464
+ lines.append(f"{base} --review-tier person no model reviewer: a person reviews each candidate with "
465
+ "polyctl person-review --by <name>")
466
+ return lines
467
+
468
+
469
+ def _append_to_project_file(path, text):
470
+ """Add `text` to the end of the project's own file at `path`, made where it is missing; None, or why it was not
471
+ (LEADS-ADAPTERS).
472
+
473
+ `polyctl init` read and added to `.gitignore` through whatever stood there: a link, or a file with a second name - a hard
474
+ link to a file of the person's - took its lines into that file, a shell's startup file among them. Only a regular
475
+ file with this one name is written, opened without following a link and without waiting on a FIFO."""
476
+ from . import storage
477
+ try:
478
+ storage.append_in_tree(os.path.dirname(path), os.path.basename(path), text.encode(UTF8))
479
+ except OSError as exc:
480
+ return f"it is not a writable file of the project's alone ({exc})"
481
+ return None
482
+
483
+
484
+ def cmd_init(cfg, args):
485
+ """Put `polyctl` on a project. Idempotent: existing files are left alone.
486
+
487
+ This is the answer to "how do I apply this to another project". Everything
488
+ it writes is a file the agent already knows how to read, so a project without
489
+ MCP or a watchdog gets the whole protocol from the files alone; the optional
490
+ flags add the automation on top. `--adopt` is the other answer, for a project
491
+ that has polyctl state and no tracked marker: `_adopt_project`.
492
+ """
493
+ if getattr(args, "adopt", False):
494
+ return _adopt_project(cfg, args)
495
+ if getattr(args, "allow_shared_hooks", False):
496
+ print(f"{C['red']}init refused{C['reset']}: --allow-shared-hooks authorizes the hooks --adopt installs; "
497
+ "init without --adopt installs none")
498
+ return 1
499
+ root = cfg["root"]
500
+ name = args.name or os.path.basename(root)
501
+ config_path = os.path.join(root, ".polyctl", "config.json")
502
+ marker_path = os.path.join(root, PROJECT_MARKER)
503
+
504
+ # Resolve every project-local decision before creating anything. A failed
505
+ # reviewer probe is a clean refusal, not a half-initialized installation.
506
+ marker_document = _worktree_project_marker_document(root)
507
+ marker_fingerprint = marker_document["fingerprint"]
508
+ if marker_document["exists"] and marker_document["problem"]:
509
+ print(
510
+ f"{C['red']}init refused{C['reset']}: "
511
+ f"{_project_refusal(marker_document['problem'])}"
512
+ )
513
+ return 1
514
+
515
+ config_existed = os.path.lexists(config_path)
516
+ existing_raw = None
517
+ if config_existed:
518
+ document = A.project_config_document(root)
519
+ if document["problem"]:
520
+ print(
521
+ f"{C['red']}init refused{C['reset']}: "
522
+ f"{_project_refusal(document['problem'])}"
523
+ )
524
+ return 1
525
+ base_config = document["config"]
526
+ existing_raw = document["raw"]
527
+ else:
528
+ base_config = {"project": name, "round_budget": S.default("round_budget")}
529
+
530
+ planned_config, added = _profile_config(root, args, base_config)
531
+ # --language is chosen before init writes a word, where `polyctl config set` needs the config init writes
532
+ # (LANGUAGE-OUTPUT). A person asked for it, so it replaces a language the config holds.
533
+ chosen = getattr(args, "language", None)
534
+ if chosen and S.lookup(planned_config, "language") != chosen:
535
+ planned_config = S.assign(dict(planned_config), "language", chosen)
536
+ added.append(f"language {chosen}")
537
+ config_text, config_problem = _planned_project_config_text(planned_config)
538
+ if config_problem:
539
+ print(f"{C['red']}init refused{C['reset']}: {_project_refusal(config_problem)}")
540
+ return 1
541
+ # Opting into the same-family tier is a person's act, on the record, as `polyctl config set` makes it (REVIEW-TIERS).
542
+ by = (getattr(args, "by", None) or "").strip()
543
+ opt_in = None
544
+ if getattr(args, "review_tier", None) == "same-family":
545
+ if not by:
546
+ print(f"{C['red']}init refused{C['reset']}: --by is required with --review-tier same-family: a person "
547
+ "opts into weaker independence, on the record")
548
+ return 1
549
+ if by.lower() in _agent_names(planned_config):
550
+ print(f"{C['red']}init refused{C['reset']}: --by names an agent or a role ({by}); opting into "
551
+ "same-family review is a person's act")
552
+ return 1
553
+ user, interactive = A._login_and_terminal()
554
+ opt_in = {"value": "labeled", "by": by, "user": user, "interactive": interactive}
555
+ elif by:
556
+ print(f"{C['red']}init refused{C['reset']}: --by names the person who opts in with --review-tier same-family")
557
+ return 1
558
+ # A quick profile that exercises none of the code gives every verify a green it did
559
+ # not earn (#5). Checked while planning, before anything is written.
560
+ detected_gates = None
561
+ if not os.path.lexists(os.path.join(root, ".polyctl", "gates.json")):
562
+ # Handwritten gates are also the recovery for an unquotable child (TRIAGE-2-MEDIUM).
563
+ try:
564
+ detected_gates = _detect_gates(root)
565
+ except ValueError as exc:
566
+ print(f"{C['red']}init refused{C['reset']}: {exc}")
567
+ return 1
568
+ minimum = S.default("gates.coverage_min_files")
569
+ trees = A.source_trees(root, minimum)
570
+ quick = detected_gates["profiles"]["quick"]
571
+ uncovered = A.gate_coverage_gaps(root, detected_gates, minimum, names=quick)
572
+ if trees and len(uncovered) == sum(len(chains) for chains in trees.values()) \
573
+ and not getattr(args, "allow_uncovered_gates", False):
574
+ chains = sorted({chain for chains in trees.values() for chain in chains})
575
+ print(f"{C['red']}init refused{C['reset']}: the quick gates ({', '.join(quick)}) exercise none of "
576
+ f"the detected toolchains ({', '.join(chains)}); declare gates in .polyctl/gates.json first, "
577
+ "or pass --allow-uncovered-gates")
578
+ return 1
579
+ # A copy, since the probe's routes may carry a mark the plan must not (ROUTE-ARGV).
580
+ runtime_cfg = _planned_runtime_config(root, json.loads(json.dumps(planned_config)))
581
+ if opt_in:
582
+ runtime_cfg["_same_family_opt_in"] = opt_in
583
+ already_lite = config_existed and project_mode(_planned_runtime_config(root, base_config)) == "lite"
584
+ # A reviewer kept from the configuration as it stood is probed only as a person accepted it, as a review starts it;
585
+ # one init composes is its own (ROUTE-ARGV).
586
+ if already_lite:
587
+ reviewer_probe = {"ok": False, "kind": "lite-mode", "reason": "skipped in lite mode"}
588
+ else:
589
+ if config_existed and "reviewer" not in added:
590
+ A.note_routes_read(runtime_cfg)
591
+ reviewer_probe = _reviewer_probe(runtime_cfg)
592
+ if not reviewer_probe["ok"]:
593
+ print(
594
+ f"{C['red']}init refused{C['reset']}: reviewer probe "
595
+ f"{_reviewer_probe_text(reviewer_probe)}"
596
+ )
597
+ if reviewer_probe.get("tier_refused"):
598
+ for line in _init_tier_hints(args, root):
599
+ print(f" {line}")
600
+ print(
601
+ f" {C['dim']}or, to start in lite mode ({ENFORCEMENT_OFF_LITE_LINE}): "
602
+ f"polyctl mode lite --by <name>, then run polyctl init again{C['reset']}"
603
+ )
604
+ return 1
605
+
606
+ # The probe may take time. Revalidate both planning inputs immediately
607
+ # before the first write; never apply a plan to marker/config state that
608
+ # moved while the reviewer was running.
609
+ if config_existed:
610
+ current_config = A.project_config_document(root)
611
+ if current_config["problem"] or current_config["raw"] != existing_raw:
612
+ problem = (
613
+ current_config["problem"]
614
+ or ".polyctl/config.json changed while reviewer probe ran"
615
+ )
616
+ print(f"{C['red']}init refused{C['reset']}: {_project_refusal(problem)}")
617
+ return 1
618
+ elif os.path.lexists(config_path):
619
+ print(
620
+ f"{C['red']}init refused{C['reset']}: "
621
+ ".polyctl/config.json appeared while reviewer probe ran"
622
+ )
623
+ return 1
624
+
625
+ # Keep the marker read last: the concurrent-init boundary that authorizes
626
+ # project writes is then the final observation before mutation begins.
627
+ current_marker = _worktree_project_marker_document(root)
628
+ if current_marker["fingerprint"] != marker_fingerprint:
629
+ problem = (
630
+ current_marker["problem"]
631
+ if current_marker["exists"] and current_marker["problem"]
632
+ else f"{PROJECT_MARKER} changed while reviewer probe ran"
633
+ )
634
+ print(f"{C['red']}init refused{C['reset']}: {_project_refusal(problem)}")
635
+ return 1
636
+ if not already_lite:
637
+ hook_problem = _init_hook_problem(root, allow_shared_hooks=True)
638
+ if hook_problem:
639
+ print(f"{C['red']}init refused{C['reset']}: commit hooks cannot be installed ({hook_problem})")
640
+ print(
641
+ f" {C['dim']}or, to start in lite mode ({ENFORCEMENT_OFF_LITE_LINE}): "
642
+ f"polyctl mode lite --by <name>, then run polyctl init again{C['reset']}"
643
+ )
644
+ return 1
645
+ # Every file init writes in the project is made, replaced or read in folders held open from the root down, never
646
+ # through a link (storage.create_in_tree and its kin): one on the way, there before init or put there while it
647
+ # writes, took the configuration, the board, the playbook and the manifest wherever it led (LEADS-ADAPTERS).
648
+ from . import storage
649
+ # What init keeps of the project goes into .polyctl/, a folder of the project's own and never a link.
650
+ if storage.not_a_folder_of_its_own(os.path.join(root, ".polyctl")):
651
+ print(f"{C['red']}init refused{C['reset']}: .polyctl is a link or a file, where init keeps the project's "
652
+ "configuration, board and ledgers: make it a folder of the project's, then run polyctl init again")
653
+ return 1
654
+
655
+ wrote, kept, unwritten = [], [], []
656
+
657
+ def put(rel, content):
658
+ # The bytes as given on every platform: Windows text mode wrote the marker with
659
+ # CRLF, and the marker check below refused the init that had just written it (#71).
660
+ try:
661
+ done = storage.create_in_tree(root, rel, content.encode(UTF8))
662
+ except storage.InTheWay as exc:
663
+ unwritten.append((rel, f"{exc}: make it a folder, then run polyctl init again"))
664
+ return
665
+ (wrote if done == "wrote" else kept).append(rel)
666
+
667
+ # The config is replaced whole or not at all (#56); a crash never leaves it
668
+ # empty of the opt-ins it held. A link put in place of .polyctl after the look above is never written through: the
669
+ # configuration is refused, before anything else is written (LEADS-ADAPTERS).
670
+ if not config_existed or added:
671
+ try:
672
+ if not config_existed:
673
+ done = storage.create_in_tree(root, ".polyctl/config.json", config_text.encode(UTF8))
674
+ if done != "wrote":
675
+ print(f"{C['red']}init refused{C['reset']}: .polyctl/config.json appeared while init ran, after it "
676
+ "planned the project without one: kept it; run polyctl init again to plan from it")
677
+ return 1
678
+ else:
679
+ storage.replace_in_tree(root, ".polyctl/config.json", config_text.encode(UTF8))
680
+ except storage.InTheWay as exc:
681
+ print(f"{C['red']}init refused{C['reset']}: {exc}: init keeps the project's configuration, board and "
682
+ "ledgers in .polyctl; make it a folder of the project's own, then run polyctl init again")
683
+ return 1
684
+ if config_existed:
685
+ kept_roles = _configured_roles(root, base_config)
686
+ kept.append(".polyctl/config.json" + (f" ({', '.join(kept_roles)})" if kept_roles else ""))
687
+ else:
688
+ wrote.append(".polyctl/config.json")
689
+ if added:
690
+ wrote.append(".polyctl/config.json (+" + ", ".join(added) + ")")
691
+
692
+ config_problem = _project_config_problem(root)
693
+ if config_problem:
694
+ print(f"{C['red']}init refused{C['reset']}: {_project_refusal(config_problem)}")
695
+ return 1
696
+ try:
697
+ existing_ledgers = sorted(
698
+ lname for lname in os.listdir(os.path.join(root, ".polyctl", "ledger"))
699
+ if lname.endswith(".jsonl")
700
+ )
701
+ except OSError:
702
+ existing_ledgers = []
703
+ if opt_in:
704
+ try:
705
+ newest = A.recorded_opt_in(root, "review.same_family")
706
+ if not newest or newest.get("value") != "labeled":
707
+ A.record_opt_in(root, "review.same_family", "labeled", opt_in["by"])
708
+ wrote.append(f".polyctl/ledger/opt-ins.jsonl (review.same_family labeled by {opt_in['by']})")
709
+ except Exception as exc:
710
+ print(f"{C['red']}init stopped{C['reset']}: the opt-in into same-family review could not be recorded "
711
+ f"({exc}), so it is not in force: polyctl config set review.same_family labeled --by <name>")
712
+ return 1
713
+ put(PROJECT_MARKER, PROJECT_MARKER_BYTES.decode("ascii"))
714
+ marker_problem = _worktree_project_marker_problem(root)
715
+ if marker_problem:
716
+ print(f"{C['red']}init refused{C['reset']}: {_project_refusal(marker_problem)}")
717
+ return 1
718
+ # In the project's language, read from the config just planned: a project that set `language`
719
+ # before init, or a machine that did, gets its files in that language (LANGUAGE-FILES).
720
+ put(".polyctl/board.md", language.text(runtime_cfg, "init.board"))
721
+ put(".polyctl/backlog.md", language.text(runtime_cfg, "init.backlog", name=name))
722
+ put(".polyctl/authority.md", language.text(runtime_cfg, "init.authority"))
723
+ if detected_gates is not None:
724
+ put(".polyctl/gates.json", json.dumps(detected_gates, indent=2) + "\n")
725
+ else:
726
+ kept.append(".polyctl/gates.json")
727
+ for lname in existing_ledgers:
728
+ kept.append(f".polyctl/ledger/{lname}")
729
+ if not existing_ledgers or os.path.lexists(os.path.join(root, ".polyctl", "ledger", ".gitkeep")):
730
+ put(".polyctl/ledger/.gitkeep", "")
731
+ put(".polyctl/decisions/.gitkeep", "")
732
+ put("semantic-review/.gitkeep", "")
733
+ put("agent-mail/README.md", language.text(runtime_cfg, "init.mail-readme"))
734
+
735
+ gi = os.path.join(root, ".gitignore")
736
+ # Read only as the project's own file: a FIFO there held init for as long as its writer liked, and a link was read
737
+ # through (LEADS-ADAPTERS). What is no such file is added to by nothing below either.
738
+ try:
739
+ raw = storage.read_in_tree(root, ".gitignore")
740
+ except storage.InTheWay:
741
+ raw = None
742
+ # Each line as a text-mode read gave it, a CRLF checkout's among them.
743
+ lines = [] if raw is None else raw.decode(UTF8, "replace").replace("\r\n", "\n").replace("\r", "\n").split("\n")
744
+ # The sessions polyctl settles for this checkout's roles are this machine's, never the repository's (SESSION-IDENTITY),
745
+ # and so are the lanes it starts from here: each names a directory on this machine (LANE-START).
746
+ add = [l for l in ("agent-mail/*.md", "!agent-mail/README.md", ".polyctl/inbox/", ".polyctl/hold", ".polyctl/sessions.json",
747
+ ".polyctl/lanes/") if l not in lines]
748
+ # So is the MCP file init writes into the tree for a harness that reads one there, `.mcp.json` for Claude Code: its
749
+ # entry names this machine's polyctl. Left untracked, it was the product file the first `polyctl verify` refused
750
+ # (README-QUICKSTART-7); one the repository already tracks is the repository's, and stays so.
751
+ add += [l for l in ([] if args.no_mcp else _mcp_files_in_tree(root, args)) if l not in lines and l not in add]
752
+ if add:
753
+ # Under a comment that names these lines as init's, so that `polyctl remove` takes them and no line a person wrote
754
+ # (LEADS-INSTALL); written only into the project's own file (LEADS-ADAPTERS).
755
+ refused = _append_to_project_file(gi, "\n" + _gitignore_block(add) + "\n" + "\n".join(add) + "\n")
756
+ if refused:
757
+ unwritten.append((".gitignore", f"{refused}; add these lines to the project's own .gitignore yourself: "
758
+ + " ".join(add)))
759
+ else:
760
+ wrote.append(".gitignore (+%d)" % len(add))
761
+
762
+ # Steering for whichever agent this repo uses. Kiro reads .kiro/steering;
763
+ # Claude Code and most others read CLAUDE.md / AGENTS.md.
764
+ # Steering goes only into files polyctl owns. The owner's rule files (CLAUDE.md,
765
+ # AGENTS.md) are never appended to unless they ask with --rules: a tool that
766
+ # writes instructions there has, from the reading agent's side, issued rules
767
+ # nobody authorised — the second pilot's coordinator refused exactly that.
768
+ from . import skillkit
769
+ requested = skillkit.detect_agents(root, args.agent)[0]
770
+ # What polyctl writes into what a harness reads, from its own declarations, to record as seen (HARNESS-SEEN-OWN).
771
+ ours = []
772
+ for ident, adapter in skillkit.setup_adapters(root):
773
+ coordination = (adapter.get("directives") or {}).get("coordination")
774
+ detect = adapter.get("detect") or {}
775
+ # A harness is here by a file of its own as much as by a directory: one declared by its files alone had
776
+ # the playbook and no coordination (HARNESS-SETUP-3).
777
+ present = any(os.path.isdir(skillkit._local(root, path) or "\0") for path in detect.get("dirs") or []) \
778
+ or any(os.path.isfile(skillkit._local(root, path) or "\0") for path in detect.get("files") or [])
779
+ if coordination and (ident == requested or present):
780
+ if skillkit._escapes(coordination):
781
+ print(f" {C['yellow']}not written{C['reset']} {coordination}: it lies outside the project (HARNESS-SETUP-2)")
782
+ continue
783
+ if skillkit._local(root, coordination) is None:
784
+ unwritten.append((coordination, skillkit._through_a_link(coordination)))
785
+ continue
786
+ steering = STEERING_COORD.format(urgent=language.marker(runtime_cfg, "urgent"))
787
+ put(coordination, steering)
788
+ if skillkit._shipped(ident, adapter, lambda a: (a.get("directives") or {}).get("coordination")):
789
+ ours.append((os.path.join(root, coordination), steering.encode(UTF8))) # put writes "\n" as it is
790
+
791
+ for rel in wrote:
792
+ print(f" {C['green']}wrote{C['reset']} {rel}")
793
+ for rel in kept:
794
+ print(f" {C['dim']}kept {rel}{C['reset']}")
795
+ for rel, why in unwritten:
796
+ print(f" {C['yellow']}not written{C['reset']} {rel}: {why}")
797
+
798
+ # The polyctl the MCP registrations name, by an absolute path, never one the current directory - the repository being
799
+ # enrolled - holds, which Windows looks in first (WINDOWS-NO-CWD-EXEC); the watchdog's install below re-enters
800
+ # this polyctl itself.
801
+ exe = A.polyctl_program()
802
+ # The playbook and the MCP registration are the two things an agent needs to
803
+ # behave like the architect from its first turn; both are written for every
804
+ # agent this repository is seen to use. Ask the human before running init;
805
+ # the tool itself does not ask.
806
+ from . import skillkit
807
+ _, agents = skillkit.detect_agents(root, args.agent)
808
+ # The playbook and the registrations are read and written as init's own files are, never through a link: what
809
+ # they did not write for one is named and counted with the rest (LEADS-ADAPTERS).
810
+ refused = []
811
+ playbook_files = skillkit.install_playbook(root, agents, rules=getattr(args, "rules", False), ours=ours,
812
+ unwritten=refused)
813
+ _print_playbook_files(playbook_files)
814
+ if not getattr(args, "rules", False):
815
+ print(f" {C['dim']}rule files untouched — paste this into {' / '.join(skillkit.rule_file_names(root))} "
816
+ f"yourself, or re-run with --rules:{C['reset']}")
817
+ for line in skillkit.RULE_POINTER.split("\n"):
818
+ print(f" {line}")
819
+ registered = {} if args.no_mcp else skillkit.register_mcp(root, agents, exe, ours=ours, unwritten=refused)
820
+ unwritten += refused
821
+ # What init wrote, so `polyctl remove` can take exactly that away again.
822
+ hook_inv = _polyctl_hook_inventory(root)
823
+ manifest = {"at": int(time.time()),
824
+ "wrote": list(wrote) + [r for r, w in playbook_files.items() if w in ("wrote", "updated", "appended")],
825
+ "mcp": [k for k, v in registered.items() if v == "registered"],
826
+ "gitignore": any(rel.startswith(".gitignore") for rel in wrote),
827
+ **_manifest_pre_push_fields(root, hook_inv)}
828
+ # Replaced whole under a name no file had, so a link an agent left at its name is replaced, never written through
829
+ # (LEADS-ADAPTERS).
830
+ manifest_path = os.path.join(root, ".polyctl", "init-manifest.json")
831
+ if (
832
+ os.path.isfile(manifest_path)
833
+ and not os.path.islink(manifest_path)
834
+ and not manifest["wrote"]
835
+ and not manifest["mcp"]
836
+ ):
837
+ _record_pre_push_provenance(root, hook_inv)
838
+ print(f" {C['dim']}kept .polyctl/init-manifest.json{C['reset']}")
839
+ else:
840
+ try:
841
+ storage.replace_in_tree(root, ".polyctl/init-manifest.json", json.dumps(manifest, indent=2).encode(UTF8))
842
+ print(f" {C['green']}wrote{C['reset']} .polyctl/init-manifest.json")
843
+ except storage.InTheWay as exc:
844
+ unwritten.append((".polyctl/init-manifest.json", str(exc)))
845
+ print(f" {C['yellow']}not written{C['reset']} .polyctl/init-manifest.json: {exc}")
846
+ # A person adopted the tree as it stands: its harness configuration is measured from this HEAD, once (HARNESS-CONFIG).
847
+ A.record_harness_baseline(root, "polyctl init")
848
+ # The role blocks init composed are its own commands, and the rest are accepted as they stand, once (TURN-ARGV).
849
+ composed = [A.turn_path(role) for role in A.record_turns_written(root, planned_config, added, "polyctl init")]
850
+ A.record_turn_baseline(root, "polyctl init")
851
+ _print_seen_own(A.record_harness_written(root, ours, "polyctl init") + composed)
852
+ for agent, what in registered.items():
853
+ print(f" {C['green']}mcp{C['reset']} {agent}: {what.splitlines()[0]}")
854
+ if what.startswith("manual"):
855
+ print(" " + "\n ".join(what.splitlines()[1:]))
856
+ if args.watchdog:
857
+ # This interpreter running this polyctl, handed where polyctl lives (SELF-REENTRY): never a program found by name.
858
+ code = subprocess.run([sys.executable, "-m", "polyctl", "-C", root, "watchdog", "install"],
859
+ cwd=A.self_child_cwd(), env=A.self_child_env(dict(os.environ)),
860
+ capture_output=True, text=True, encoding=UTF8, errors="replace").returncode
861
+ print(f" {C['green'] if code == 0 else C['red']}watchdog{C['reset']} "
862
+ f"{'installed' if code == 0 else 'install failed — run polyctl watchdog install'}")
863
+
864
+ if already_lite:
865
+ print(f" {C['yellow']}mode{C['reset']} {ENFORCEMENT_OFF_LITE_LINE}")
866
+ print(f" {C['dim']}commit hook{C['reset']} not installed ({ENFORCEMENT_OFF_LITE} — nothing is enforced)")
867
+ print(f" {C['dim']}reviewer probe{C['reset']} not enforced ({ENFORCEMENT_OFF_LITE} — nothing is enforced)")
868
+ else:
869
+ hook_proof = _hook_execution_probe(hook_inv)
870
+ tone = C["green"] if hook_proof["installed"] else C["yellow"]
871
+ print(f" {tone}commit hook{C['reset']} {_hook_probe_text(hook_proof)}")
872
+ push_target = _own_pre_push_target(hook_inv)
873
+ if push_target is not None:
874
+ print(f" {C['dim']}push guard{C['reset']} {_own_pre_push_line(push_target)}")
875
+ else:
876
+ other_push = _other_pre_push_line(hook_inv)
877
+ if other_push is not None:
878
+ print(f" {C['yellow']}push guard {other_push}{C['reset']}")
879
+
880
+ probe_tone = C["green"] if reviewer_probe["ok"] else C["red"]
881
+ print(
882
+ f" {probe_tone}reviewer probe{C['reset']} "
883
+ f"{_reviewer_probe_text(reviewer_probe)}"
884
+ )
885
+
886
+ print(f"\n{C['b']}Next, for a person:{C['reset']}")
887
+ if not already_lite and not hook_inv["error"] and any(
888
+ target["needs_authorization"] for target in _active_hook_targets(hook_inv).values()
889
+ ):
890
+ print(
891
+ f" · Run `polyctl hooks install --allow-shared-hooks` to install commit hooks at {hook_inv['active_dir']} "
892
+ f"({hook_inv['directory_class']})."
893
+ )
894
+ for line in skillkit.next_steps(agents, registered):
895
+ print(f" · {line}")
896
+ if unwritten:
897
+ print(f"{C['yellow']}init wrote the rest; {len(unwritten)} file(s) were not written, each named above with "
898
+ f"why: make each a file or folder of the project's own, then run polyctl init again{C['reset']}")
899
+ return 1
900
+ return 0
901
+
902
+
903
+ def _print_playbook_files(written):
904
+ """Each playbook file `install_playbook` wrote, kept or did not write, the last with why (LEADS-ADAPTERS)."""
905
+ for rel, what in written.items():
906
+ if what.startswith("not written: "):
907
+ print(f" {C['yellow']}not written{C['reset']} {rel}: {what[len('not written: '):]}")
908
+ else:
909
+ print(f" {C['green'] if what != 'kept' else C['dim']}{what:<8}{C['reset']} {rel}")
910
+
911
+
912
+ # What a new setup chooses, or asks init to write. Adoption takes a project as it was set up and
913
+ # writes only the marker and the hooks, so each of these is refused beside --adopt rather than
914
+ # ignored (INIT-ADOPTION); --agent counts only when it names an agent, and --no-mcp asks for
915
+ # nothing adoption does.
916
+ def _adopt_refused(args):
917
+ """The options `--adopt` refuses that were given, as their flags; each read by its name, since the split proof reads
918
+ no attribute named at run time (#111)."""
919
+ given = (("name", getattr(args, "name", None)), ("profile", getattr(args, "profile", None)),
920
+ ("implementer", getattr(args, "implementer", None)), ("model", getattr(args, "model", None)),
921
+ ("effort", getattr(args, "effort", None)), ("reviewer_model", getattr(args, "reviewer_model", None)),
922
+ ("review_tier", getattr(args, "review_tier", None)), ("by", getattr(args, "by", None)),
923
+ ("language", getattr(args, "language", None)), ("mcp", getattr(args, "mcp", None)),
924
+ ("rules", getattr(args, "rules", None)), ("watchdog", getattr(args, "watchdog", None)),
925
+ ("allow_uncovered_gates", getattr(args, "allow_uncovered_gates", None)),
926
+ ("prove", getattr(args, "prove", None)), ("no_review", getattr(args, "no_review", None)))
927
+ return ["--" + option.replace("_", "-") for option, value in given if value]
928
+
929
+
930
+ def _mcp_files_in_tree(root, args):
931
+ """The MCP files inside the tree that init registers polyctl's server in for the agents it sees, and that the
932
+ repository does not track: each holds an entry naming this machine's polyctl (README-QUICKSTART-7)."""
933
+ from . import skillkit
934
+ _, agents = skillkit.detect_agents(root, args.agent)
935
+ files = set()
936
+ for ident, adapter in skillkit.setup_adapters(root):
937
+ declared = str((adapter.get("mcp") or {}).get("file") or "") if ident in agents else ""
938
+ if declared and not declared.startswith(("~", "/")) and ".." not in declared.split("/"):
939
+ files.add(declared)
940
+ if not files:
941
+ return []
942
+ try:
943
+ tracked = A._git_output(root, "ls-files", "-z", "--", *sorted(files)).decode(UTF8, "replace").split("\0")
944
+ except RuntimeError: # what git cannot answer for is left as it is
945
+ return []
946
+ return sorted(files - set(tracked))
947
+
948
+
949
+ def _git_on_active_index(root, *args):
950
+ """Run one git command against the index enrollment is measured in; None when it succeeded, else why not."""
951
+ extra_env, problem = _project_index_env(root)
952
+ if problem:
953
+ return problem
954
+ try:
955
+ result = _hook_git(root, *args, extra_env=extra_env)
956
+ except _HookResolutionError as exc:
957
+ return str(exc)
958
+ if result.returncode:
959
+ return result.stderr.decode(UTF8, "replace").strip()[:160] or f"git exit {result.returncode}"
960
+ return None
961
+
962
+
963
+ def _tracked_coordination_files(root, cfg):
964
+ """The coordination paths tracked in the active index of `root`, sorted; empty when none or git cannot say."""
965
+ extra_env, problem = _project_index_env(root)
966
+ if problem:
967
+ return []
968
+ try:
969
+ result = _hook_git(root, "ls-files", "-z", "--", extra_env=extra_env)
970
+ except _HookResolutionError:
971
+ return []
972
+ if result.returncode:
973
+ return []
974
+ return sorted(
975
+ (os.fsdecode(raw) for raw in result.stdout.split(b"\0")
976
+ if raw and A._is_coordination_path(os.fsdecode(raw), cfg)),
977
+ key=os.fsencode,
978
+ )
979
+
980
+
981
+ def _adopt_project(cfg, args):
982
+ """`polyctl init --adopt`: enroll polyctl state no tracked .polyctl-project covers, keeping all of it (INIT-ADOPTION).
983
+
984
+ A project an older polyctl set up has a config that governs its commits, a hook that runs
985
+ commit-check, and no marker anywhere in its history; one whose marker `polyctl init` wrote and
986
+ nobody staged measures the same. The current hooks stand aside while no marker is
987
+ tracked, so `polyctl hooks install` refuses such a project, and each message about it spelled
988
+ out a recipe of its own. This is the one step. The exact marker is written where the
989
+ working tree has none, then staged: enrollment is measured in the index, so the hooks
990
+ installed next enforce from the moment they are written, as the old one did, and go on
991
+ enforcing while the marker stays staged - the output asks for that until it lands. They
992
+ are installed as `polyctl hooks install` installs them, Git is made to run the commit hook to
993
+ prove it, and the commit that finishes the adoption is named.
994
+
995
+ Adoption writes nothing under .polyctl/: the config, the board, every ledger and decision stay
996
+ as they are. A marker file that is not the exact marker is refused, never replaced, and a
997
+ staged marker that does not read back as one is unstaged again, which leaves the project
998
+ governed as it was. Run again, it finds the marker staged or committed, leaves it, and
999
+ only makes sure of the hooks. Exits 0 only when Git was seen to run the commit hook.
1000
+ """
1001
+ root = cfg["root"]
1002
+ given = _adopt_refused(args)
1003
+ if getattr(args, "agent", None) not in (None, "auto"):
1004
+ given.append("--agent")
1005
+ if given:
1006
+ print(f"{C['red']}init refused{C['reset']}: --adopt keeps the project as it was set up, and "
1007
+ f"{', '.join(given)} belong{'s' if len(given) == 1 else ''} to a new setup: polyctl init without --adopt")
1008
+ return 1
1009
+ enrollment = _project_enrollment(root)
1010
+ if enrollment["state"] in ("broken", "redirected"):
1011
+ print(f"{C['red']}init --adopt refused{C['reset']}: {enrollment['detail']}")
1012
+ return 1
1013
+ if enrollment["state"] == "uninitialized":
1014
+ if os.path.lexists(os.path.join(root, ".polyctl", "config.json")):
1015
+ why = (f"{PROJECT_MARKER} was tracked here and its removal is committed, so this polyctl state is inert "
1016
+ f"on purpose; enrolling it again is a new setup: {PROJECT_INIT_COMMAND}")
1017
+ else:
1018
+ why = f"no .polyctl/config.json here, so no polyctl state to adopt; a new project starts with {PROJECT_INIT_COMMAND}"
1019
+ print(f"{C['red']}init --adopt refused{C['reset']}: {why}")
1020
+ return 1
1021
+
1022
+ if enrollment["state"] == "legacy":
1023
+ document = _worktree_project_marker_document(root)
1024
+ if document["exists"] and document["problem"]:
1025
+ print(f"{C['red']}init --adopt refused{C['reset']}: {document['problem']}, and polyctl never replaces it: "
1026
+ f"make it exactly polyctl-project-v1 or move it aside, then {PROJECT_ADOPT_COMMAND}")
1027
+ return 1
1028
+ if document["exists"]:
1029
+ print(f" {C['dim']}kept {PROJECT_MARKER} (polyctl-project-v1 already){C['reset']}")
1030
+ else:
1031
+ try:
1032
+ # Created, never replaced: a file that appeared since the read above is left as it is.
1033
+ with open(os.path.join(root, PROJECT_MARKER), "x", encoding=UTF8, newline="\n") as fh:
1034
+ fh.write(PROJECT_MARKER_BYTES.decode("ascii"))
1035
+ except OSError as exc:
1036
+ print(f"{C['red']}init --adopt refused{C['reset']}: cannot create {PROJECT_MARKER}: {exc}")
1037
+ return 1
1038
+ print(f" {C['green']}wrote{C['reset']} {PROJECT_MARKER} (polyctl-project-v1)")
1039
+ problem = _worktree_project_marker_problem(root)
1040
+ if problem:
1041
+ print(f"{C['red']}init --adopt stopped{C['reset']}: {problem}; nothing was staged")
1042
+ return 1
1043
+ failure = _git_on_active_index(root, "add", "--", PROJECT_MARKER)
1044
+ if failure:
1045
+ print(f"{C['red']}init --adopt stopped{C['reset']}: git could not stage {PROJECT_MARKER}: {failure}")
1046
+ return 1
1047
+ enrollment = _project_enrollment(root)
1048
+ if enrollment["state"] == "redirected":
1049
+ print(f"{C['red']}init --adopt stopped{C['reset']}: {enrollment['detail']}")
1050
+ return 1
1051
+ if enrollment["state"] != "enrolled":
1052
+ # A clean filter or an attribute can store other bytes than the file's. Such a marker
1053
+ # would read as broken and refuse every commit with another repair; the project is
1054
+ # left governed as it was instead.
1055
+ undone = _git_on_active_index(root, "rm", "--cached", "--ignore-unmatch", "--quiet", "--",
1056
+ PROJECT_MARKER)
1057
+ print(f"{C['red']}init --adopt stopped{C['reset']}: the staged {PROJECT_MARKER} does not enroll the "
1058
+ f"project ({enrollment['detail']}); "
1059
+ + (f"it could not be unstaged ({undone}): git rm --cached -- {PROJECT_MARKER}" if undone
1060
+ else "it was unstaged again, and the project is governed as it was"))
1061
+ return 1
1062
+ print(f" {C['green']}staged{C['reset']} {PROJECT_MARKER}")
1063
+ else:
1064
+ where = "committed" if enrollment["head"]["status"] == "canonical" else "staged"
1065
+ print(f" {C['dim']}kept {PROJECT_MARKER} ({where} already){C['reset']}")
1066
+ try:
1067
+ ledgers = sorted(name for name in os.listdir(os.path.join(root, ".polyctl", "ledger")) if name.endswith(".jsonl"))
1068
+ except OSError:
1069
+ ledgers = []
1070
+ held = f" with its {len(ledgers)} ledger(s) ({', '.join(ledgers)})" if ledgers else ""
1071
+ print(f" {C['dim']}kept .polyctl/{held}: adoption writes nothing there{C['reset']}")
1072
+ tracked_coord = _tracked_coordination_files(root, cfg)
1073
+ if tracked_coord:
1074
+ print(f" {C['yellow']}tracked{C['reset']} coordination file(s) ({len(tracked_coord)}): "
1075
+ f"{', '.join(tracked_coord)}")
1076
+
1077
+ allow = bool(getattr(args, "allow_shared_hooks", False))
1078
+ # Its exit status is not the answer: a foreign pre-push it preserves fails it and leaves commit
1079
+ # authority whole. What it says is printed; whether the commit hook runs is proven below.
1080
+ cmd_hooks(cfg, argparse.Namespace(action="install", allow_shared_hooks=allow))
1081
+ inventory = _polyctl_hook_inventory(root)
1082
+ proof = _hook_execution_probe(inventory)
1083
+ print(f" {C['green'] if proof['installed'] else C['yellow']}commit hook{C['reset']} {_hook_probe_text(proof)}")
1084
+ push_target = _own_pre_push_target(inventory)
1085
+ if push_target is not None:
1086
+ print(f" {C['dim']}push guard{C['reset']} {_own_pre_push_line(push_target)}")
1087
+ else:
1088
+ other_push = _other_pre_push_line(inventory)
1089
+ if other_push is not None:
1090
+ print(f" {C['yellow']}push guard {other_push}{C['reset']}")
1091
+
1092
+ print(f"\n{C['b']}Next, for a person:{C['reset']}")
1093
+ if not proof["installed"]:
1094
+ target = {} if inventory["error"] else _active_hook_targets(inventory)["pre-commit"]
1095
+ if HOOK_POLYCTL_NOT_FOUND in proof["detail"]:
1096
+ fix = _polyctl_link_fix() # an alias is invisible to the hook's /bin/sh (SAFE-REMOVE)
1097
+ elif target.get("needs_authorization") and not allow and os.name != "nt":
1098
+ fix = f"{PROJECT_ADOPT_COMMAND} --allow-shared-hooks, since Git runs these hooks from a shared place"
1099
+ else:
1100
+ fix = f"polyctl hooks status names what runs in its place; once that is resolved, {PROJECT_ADOPT_COMMAND}"
1101
+ print(f" · the commit hook is not proven: {fix}")
1102
+ if enrollment["head"]["status"] == "canonical":
1103
+ print(f" · nothing to commit: {PROJECT_MARKER} is in HEAD")
1104
+ else:
1105
+ print(f" · land the staged {PROJECT_MARKER} through the loop - polyctl verify, polyctl review, polyctl commit-ok, then "
1106
+ "polyctl commit -m \"…\" - and the project is adopted for good")
1107
+ print(f" · keep it staged until then: the current hooks enforce while {PROJECT_MARKER} is in the index "
1108
+ "or in HEAD")
1109
+ if tracked_coord:
1110
+ quoted = " ".join(A._shell_word(path) for path in tracked_coord)
1111
+ print(f" · tracked coordination file(s) ({', '.join(tracked_coord)}) must not share a product commit: "
1112
+ f"stage changes to them (or untrack them with `git rm --cached -- {quoted}`) in a commit of their own "
1113
+ "and grant it with `polyctl commit-ok --by <name> --ask`, then `polyctl commit -m \"…\"`")
1114
+ return 0 if proof["installed"] else 1
1115
+
1116
+
1117
+ def cmd_decide(cfg, args):
1118
+ """Record an architect decision where it survives.
1119
+
1120
+ `polyctl note` is a message: read, acted on, deleted. A decision is a fact about
1121
+ the project that the next architect — or the same one after a compaction —
1122
+ has to be able to find. It goes to the ledger, and to the implementer's
1123
+ mailbox so it is acted on; if it answers an open `polyctl ask`, that is closed too.
1124
+ """
1125
+ root = cfg["root"]
1126
+ if args.list:
1127
+ p = os.path.join(root, ".polyctl", "ledger", "decisions.jsonl")
1128
+ rows = []
1129
+ if os.path.exists(p):
1130
+ for line in open(p, errors="replace", encoding=UTF8):
1131
+ try:
1132
+ rows.append(json.loads(line))
1133
+ except Exception:
1134
+ pass
1135
+ # A rule proposal shares the ledger and is no architect's decision: `polyctl proposals` lists it (RULE-PROPOSALS).
1136
+ rows = [r for r in rows if isinstance(r, dict) and r.get("kind") != "proposal"]
1137
+ if not rows:
1138
+ print(f"{C['dim']}No decisions recorded.{C['reset']}")
1139
+ return 0
1140
+ for r in rows[-args.n:]:
1141
+ when = datetime.fromtimestamp(r["at"]).strftime("%d %b %H:%M")
1142
+ print(f" {C['dim']}{when}{C['reset']} {C['b']}{r['id']}{C['reset']} {r['decision']}")
1143
+ if r.get("why"):
1144
+ print(f" {C['dim']}{r['why'][:110]}{C['reset']}")
1145
+ return 0
1146
+ if not args.decision:
1147
+ print(f"usage: {C['b']}polyctl decide \"decision\" --why \"…\" [--answers D-123] "
1148
+ f"[--scope B2] [--urgent]{C['reset']}")
1149
+ return 1
1150
+ asked = next((d for d in A.decisions(root) if d["id"] == args.answers), None) if args.answers else None
1151
+ if asked and asked.get("proposal"):
1152
+ # Refused before anything is recorded or mailed: a decision settling it would reach the implementer as
1153
+ # one, and a rule proposal is a person's to decide (RULE-PROPOSALS).
1154
+ print(f"{C['red']}refused{C['reset']}: {args.answers} asks about rule proposal {asked['proposal']}, which a "
1155
+ f"person decides with polyctl answer {args.answers} <key>; no architect decision settles it")
1156
+ return 2
1157
+ holder = A.architect_lock_holder(root)
1158
+ if holder and holder.get("pid") != os.getpid() and holder.get("pid") != os.getppid():
1159
+ print(f"{C['yellow']}another architect turn holds the lock{C['reset']} ({holder.get('who')}, pid {holder.get('pid')}, "
1160
+ f"since {time.strftime('%H:%M', time.localtime(holder.get('at', 0)))}) — two judges at once contradict each other; "
1161
+ f"recording anyway, check `polyctl decide --list`")
1162
+ rec = A.scan_record({"id": f"AD-{int(time.time())}", "at": int(time.time()), "decision": args.decision,
1163
+ "why": args.why, "scope": args.scope, "answers": args.answers, "by": "architect"})
1164
+ # Chained, so a row added by hand cannot pass for a re-specification (#65).
1165
+ from .storage import append_chained_jsonl
1166
+ append_chained_jsonl(A.decisions_path(root), rec, A.DECISION_CHAIN, legacy_prefix=True)
1167
+ if args.answers:
1168
+ try:
1169
+ # The decision is the answer in its own words: the free-text option (CLI-ROBUST).
1170
+ ans = A.answer(root, args.answers, "x " + args.decision, by="architect")
1171
+ print(f" {C['green']}answered{C['reset']} {args.answers}" if ans else
1172
+ f" {C['yellow']}no open question {args.answers}{C['reset']}")
1173
+ except A.AnswerRefused as exc:
1174
+ # Recorded in the ledger all the same; an answer already given is not overwritten by it.
1175
+ print(f" {C['yellow']}{args.answers} not answered{C['reset']}: {exc}")
1176
+ # The note is in the project's language (LANGUAGE-OUTPUT).
1177
+ body = f"{args.decision}\n\n" + language.text(cfg, "decide.why", why=args.why or "—")
1178
+ if args.scope:
1179
+ body += "\n\n" + language.text(cfg, "decide.scope", scope=args.scope)
1180
+ body += "\n\n" + language.text(cfg, "decide.record", id=rec["id"])
1181
+ name = A.note(root, cfg, args.to, args.decision[:60], body, urgent=args.urgent)
1182
+ print(f" {C['green']}recorded{C['reset']} {rec['id']} → {cfg['mailbox']}/{name}")
1183
+ return 0
1184
+
1185
+
1186
+ def _since_marker(root):
1187
+ return os.path.join(root, ".polyctl", "ledger", "since.json")
1188
+
1189
+
1190
+ def cmd_since(cfg, args):
1191
+ """What changed since I last looked — for an architect coming back.
1192
+
1193
+ `polyctl digest` is a window; this is a delta, anchored on the moment you last
1194
+ asked. A resumed session after a compaction, or a human back from lunch, has
1195
+ one question — what happened while I was gone — and reconstructing it from
1196
+ the whole day's digest is the tool making them do its job.
1197
+ """
1198
+ root = cfg["root"]
1199
+ ref = args.ref or "last"
1200
+ now = time.time()
1201
+ if ref == "last":
1202
+ try:
1203
+ cut = json.load(open(_since_marker(root), encoding=UTF8))["at"]
1204
+ except Exception:
1205
+ cut = now - 86400
1206
+ else:
1207
+ try:
1208
+ # The time every command reads is tried before a ref, as a duration always was; a bare
1209
+ # number is no time here, since digits alone name a commit (CLI-ROBUST).
1210
+ cut = A.parse_time(ref, now=now).moment(now=now)
1211
+ except ValueError:
1212
+ # One ref, handed to git as one argument. Through a shell the ref was split and expanded, and
1213
+ # `HEAD;touch x` ran touch; an option is no ref either (`--output=<file>` had git write a file).
1214
+ ts = "" if ref.startswith("-") else A._git_text(root, "log", "-1", "--format=%ct", ref)
1215
+ if not ts.isdigit():
1216
+ print(f"{C['red']}not a time ({A.TIME_FORMS}), a git ref, or 'last': {ref}{C['reset']}")
1217
+ return 1
1218
+ cut = float(ts)
1219
+ mins = int((now - cut) / 60)
1220
+ print(f"{C['b']}since{C['reset']} {C['dim']}{mins // 60}h {mins % 60}m ago{C['reset']}")
1221
+
1222
+ log = A.git_text(root, "log", f"--since=@{int(cut)}", "--pretty=%h|%s")
1223
+ commits = [l.split("|", 1) for l in log.split("\n") if "|" in l]
1224
+ print(f"\n {C['b']}{len(commits)}{C['reset']} commit")
1225
+ for sha, subj in commits[:8]:
1226
+ print(f" {C['dim']}{sha}{C['reset']} {subj[:72]}")
1227
+
1228
+ def newer(rel):
1229
+ d = os.path.join(root, rel)
1230
+ if not os.path.isdir(d):
1231
+ return []
1232
+ return sorted(f for f in os.listdir(d)
1233
+ if not f.startswith(".") and os.path.getmtime(os.path.join(d, f)) >= cut)
1234
+ revs = newer(cfg["reviews"])
1235
+ if revs:
1236
+ verdicts = dict(A.reviews(root, cfg["reviews"], limit=40))
1237
+ print(f"\n {C['b']}{len(revs)}{C['reset']} review")
1238
+ for f in revs[-6:]:
1239
+ v = verdicts.get(f, "")
1240
+ col = C["green"] if "APPROVED" in v.upper() else C["yellow"]
1241
+ print(f" {col}{v or '?':<14}{C['reset']} {f[:60]}")
1242
+ decs = [d for d in A.decisions(root) if d.get("asked_at", 0) >= cut or (d.get("answered_at") or 0) >= cut]
1243
+ if decs:
1244
+ print(f"\n {C['b']}{len(decs)}{C['reset']} decision")
1245
+ for d in decs[-6:]:
1246
+ st = f"{C['green']}→ {d['answer']}{C['reset']}" if d["state"] == "answered" else f"{C['yellow']}open{C['reset']}"
1247
+ print(f" {d['id']} {d['question'][:56]} {st}")
1248
+ mail = [m for m in A.mailbox(root, cfg["mailbox"])
1249
+ if os.path.getmtime(os.path.join(root, cfg["mailbox"], m)) >= cut]
1250
+ if mail:
1251
+ print(f"\n {C['b']}{len(mail)}{C['reset']} message in the mailbox now")
1252
+ for m in mail[:6]:
1253
+ print(f" {C['dim']}{m[:70]}{C['reset']}")
1254
+ notices = [n for n in A.notices(root, 50, include_suppressed=False) if n.get("at", 0) >= cut]
1255
+ if notices:
1256
+ print(f"\n {C['b']}{len(notices)}{C['reset']} alert sent")
1257
+ for n in notices[:4]:
1258
+ print(f" {C['dim']}{n['title']}: {n['msg'][:60]}{C['reset']}")
1259
+ b = A.board(root)
1260
+ print(f"\n {C['dim']}board now: " + " · ".join(f"{k} {len(v)}" for k, v in b.items() if v) + C["reset"])
1261
+
1262
+ if not args.no_mark:
1263
+ os.makedirs(os.path.dirname(_since_marker(root)), exist_ok=True)
1264
+ json.dump({"at": now}, open(_since_marker(root), "w", encoding=UTF8))
1265
+ return 0
1266
+
1267
+
1268
+ # What a board line carries between its brackets and a needs note can name whole: lib_transcript.board
1269
+ # reads up to the first ']', lib_state._edge_ids splits at commas and spaces and takes a word in
1270
+ # parentheses for a remark, and plan_digest reads the plan named before the first '/'. A backslash is a
1271
+ # path separator on one system and not on another, and a '·' separates a line's notes to a person.
1272
+ BOARD_ID = r"[^\s,\]\\·(/][^\s,\]\\·]*"
1273
+
1274
+
1275
+ def _board_add(cfg, args, edit):
1276
+ """Admit one item to `queued` the way `polyctl source import` admits one: only with its boundary.
1277
+
1278
+ Work entered a board by hand-editing `.polyctl/board.md` or through a tracker import. Both keep the rule
1279
+ that matters - nothing runs unattended without an acceptance boundary written before the work - and
1280
+ the first asks a person to learn a file's shape first. This writes the line the import writes and
1281
+ records the same plan baseline, and it refuses what the import would hold back or the board could
1282
+ not hold: no boundary, an id already there or one another item's needs could not name, a dependency
1283
+ on an item that is not on the board. Refused, nothing is written.
1284
+
1285
+ An id is what the board reads between a line's brackets and what a needs note can name: a phase
1286
+ item such as ACME-187/1 is one, baselined on the plan ACME-187 (BOARD-ADD-2). `--needs` is read the
1287
+ way the board reads a needs note, split at commas and spaces, so what is checked is what is written.
1288
+ The checks and the line they admit are made on one reading of the board, `edit` (SLICE-LIFECYCLE-2).
1289
+ """
1290
+ import re
1291
+ root = cfg["root"]
1292
+ for line in _mailbox_banner(cfg):
1293
+ print(line)
1294
+ iid, title = (args.id or "").strip(), " ".join((args.title or "").split())
1295
+ acceptance, role = " ".join((args.acceptance or "").split()), (args.role or "").strip()
1296
+ needs = [token for token in re.split(r"[,\s]+", args.needs or "") if token]
1297
+ board = edit.board
1298
+ held = {item["id"] for state in A.BOARD_STATES for item in board.get(state, [])}
1299
+ if edit.data is None:
1300
+ problem = "this project has no .polyctl/board.md; `polyctl init` writes one"
1301
+ elif not re.fullmatch(BOARD_ID, iid):
1302
+ problem = (f"`{iid}` cannot be an id: an id holds no space, comma, ']', backslash or '·' and does not "
1303
+ "start with '(' or '/', so that a board line carries it whole and a needs note can name it")
1304
+ elif iid in held:
1305
+ problem = f"{iid} is already on the board"
1306
+ elif not title:
1307
+ problem = "an item needs a title: `polyctl board add ID \"what it is\" --acceptance \"…\"`"
1308
+ elif not acceptance:
1309
+ problem = ("an item enters the board only with a written acceptance boundary: "
1310
+ "--acceptance \"what the work must meet\"")
1311
+ elif any("·" in text for text in (title, acceptance, role)):
1312
+ problem = "a title, a boundary and a role hold no '·': it separates a board line's notes"
1313
+ elif [name for name in needs if not re.fullmatch(BOARD_ID, name)]:
1314
+ problem = ("--needs names " + ", ".join(f"`{name}`" for name in needs if not re.fullmatch(BOARD_ID, name))
1315
+ + ", which a needs note would not read as an id")
1316
+ elif [name for name in needs if name not in held]:
1317
+ problem = ("it needs " + ", ".join(name for name in needs if name not in held)
1318
+ + ", which the board does not hold")
1319
+ else:
1320
+ problem = None
1321
+ if problem:
1322
+ print(f"{C['red']}REFUSED{C['reset']} {problem}")
1323
+ return 2
1324
+ notes = [("acceptance", acceptance)] + ([("needs", ", ".join(needs))] if needs else []) \
1325
+ + ([("role", role)] if role else [])
1326
+ edit.append("queued", f"- [{iid}] {title}" + "".join(f" · {key}: {value}" for key, value in notes))
1327
+ edit.write()
1328
+ digest = A.plan_digest(root, iid)
1329
+ if digest:
1330
+ A.record_plan(root, iid, digest) # the plan as admitted: later edits are measured against it
1331
+ waiting = f" {C['dim']}waits for {', '.join(needs)}{C['reset']}" if needs else ""
1332
+ print(f"{C['green']}queued{C['reset']} {C['b']}{iid}{C['reset']} {title}{waiting}")
1333
+ return 0
1334
+
1335
+
1336
+ def cmd_board(cfg, args):
1337
+ """Where every pre-authorised item is, blocked ones first.
1338
+
1339
+ Order is deliberate: `running` and `blocked` are the two states a human can
1340
+ act on, and `blocked` is the one that goes unnoticed — work carried on past
1341
+ it, so nothing else in the panel looks wrong.
1342
+ """
1343
+ if getattr(args, "view", None) == "add":
1344
+ with A.BoardEdit(cfg["root"], hold=True) as edit:
1345
+ return _board_add(cfg, args, edit)
1346
+ root = cfg["root"]
1347
+ for line in _mailbox_banner(cfg):
1348
+ print(line)
1349
+ if getattr(args, "view", None) == "ready" and os.path.exists(os.path.join(root, ".polyctl", "board.md")):
1350
+ # Exactly the eligible items, for a script: a broken edge exits 1 (#33).
1351
+ graph = A.board_graph(root)
1352
+ for problem in graph["problems"]:
1353
+ print(f"{C['red']}board: {A.shown_text(problem)}{C['reset']}")
1354
+ for it in graph["ready"]:
1355
+ print(f"{A.shown_text(it['id'])} {A.shown_text(it['title'])}")
1356
+ return 1 if graph["problems"] else 0
1357
+ for line in _board_lines(cfg):
1358
+ print(line)
1359
+ return 0
1360
+
1361
+
1362
+ def board_facts(cfg, shown=False):
1363
+ """What the board page shows, read once: `_board_lines` draws it and `/api/board` serves it (WEB-API).
1364
+
1365
+ With `shown` false nothing is recorded as seen, as `status_facts` records nothing.
1366
+ """
1367
+ root = cfg["root"]
1368
+ path = os.path.join(root, ".polyctl", "board.md")
1369
+ exists = os.path.exists(path)
1370
+ b = A.board(root)
1371
+ graph = A.board_graph(root) if exists else {"ready": [], "problems": []}
1372
+ sections = {}
1373
+ for st in A.BOARD_STATES:
1374
+ rows = []
1375
+ for it in b[st]:
1376
+ advice = A.boundary_advice(root, cfg, it) if exists and st in ("running", "queued") else []
1377
+ rows.append({"id": it["id"], "title": it["title"], "notes": dict(it["notes"]),
1378
+ "boundary_advice": advice})
1379
+ sections[st] = rows
1380
+ marked = _marked_mail(cfg, shown)
1381
+ return {
1382
+ "project": cfg.get("project") or os.path.basename(root),
1383
+ "root": root,
1384
+ "at": int(time.time()),
1385
+ "exists": exists,
1386
+ "problems": list(graph["problems"]),
1387
+ "ready": [{"id": it["id"], "title": it["title"], "role": it.get("role") or "",
1388
+ "notes": dict(it["notes"])} for it in graph["ready"]],
1389
+ "sections": sections,
1390
+ "counts": {st: len(b[st]) for st in A.BOARD_STATES},
1391
+ "mail": {
1392
+ "dir": cfg.get("mailbox", "agent-mail"),
1393
+ "waiting": None if marked is None else marked[1],
1394
+ "urgent": None if marked is None else [{"id": m["id"], "to": m["to"], "title": m["title"]}
1395
+ for m in marked[0]],
1396
+ },
1397
+ }
1398
+
1399
+
1400
+ def _board_lines(cfg, facts=None):
1401
+ """The board as `polyctl board` prints it below the mailbox banner, one string a line.
1402
+
1403
+ `polyctl watch --web` serves the same lines, so the page and the command cannot drift apart.
1404
+ """
1405
+ if facts is None:
1406
+ facts = board_facts(cfg, shown=False)
1407
+ if not facts["exists"]:
1408
+ return [f"{C['yellow']}No board here.{C['reset']} Create {C['b']}.polyctl/board.md{C['reset']} with "
1409
+ f"`## running` / `## blocked` / `## queued` / `## verified` / `## done` sections\n"
1410
+ f"and one `- [ID] title · note: value` line per item."]
1411
+ colours = {"running": C["green"], "blocked": C["red"], "queued": C["dim"],
1412
+ "verified": C["cyan"], "done": C["dim"]}
1413
+ # Eligible work first: queued items whose `needs:` are all done. This is the
1414
+ # dependency graph answering "what is next" without the implementer choosing
1415
+ # its own scope. A broken edge is named before anything else (#33).
1416
+ # The board is text an agent writes, and what is read from it is shown escaped (LEADS-MCP).
1417
+ shown = A.shown_text
1418
+ b = facts["sections"]
1419
+ lines = []
1420
+ for problem in facts["problems"]:
1421
+ lines.append(f"{C['red']}{C['b']}BOARD{C['reset']} {C['red']}{shown(problem)}{C['reset']}")
1422
+ rd = facts["ready"]
1423
+ if rd:
1424
+ lines.append(f"\n{C['b']}{C['green']}READY{C['reset']} {C['dim']}({len(rd)}) — "
1425
+ f"dependencies satisfied{C['reset']}")
1426
+ for it in rd:
1427
+ role = f" {C['cyan']}role:{shown(it['role'])}{C['reset']}" if it.get("role") else ""
1428
+ lines.append(f" {C['b']}{shown(it['id'])}{C['reset']} {shown(it['title'])}{role}")
1429
+ for st in ("running", "blocked", "queued", "verified", "done"):
1430
+ items = b[st]
1431
+ if not items:
1432
+ continue
1433
+ lines.append(f"\n{C['b']}{colours[st]}{st.upper()}{C['reset']} {C['dim']}({len(items)}){C['reset']}")
1434
+ for it in items:
1435
+ notes = " ".join(f"{C['dim']}{shown(k)}:{C['reset']} {shown(v)}" if v
1436
+ else f"{C['dim']}{shown(k)}{C['reset']}" for k, v in it["notes"].items())
1437
+ lines.append(f" {C['b']}{shown(it['id'])}{C['reset']} {shown(it['title'])}"
1438
+ + (f" {notes}" if notes else ""))
1439
+ if st in ("running", "queued"):
1440
+ # Named when the item is registered, while widening or splitting is cheap (#35).
1441
+ for advice in it.get("boundary_advice") or ():
1442
+ lines.append(f" {C['yellow']}boundary: {shown(advice)}{C['reset']}")
1443
+ if not any(b[st] for st in colours):
1444
+ # A board holding only what waits for a boundary printed nothing at all (LEADS-ADAPTERS).
1445
+ lines.append(f"{C['dim']}No item is admitted: {len(b['inbox'])} wait(s) in the inbox of .polyctl/board.md for an "
1446
+ f"acceptance boundary.{C['reset']}" if b["inbox"] else f"{C['dim']}Board is empty.{C['reset']}")
1447
+ return lines
1448
+
1449
+
1450
+ # ---- a slice's moves: start, block, abandon, each a line in the slice ledger (SLICE-LIFECYCLE) ----------
1451
+
1452
+ # The sections a slice is open in; done and rejected are where it ends.
1453
+ SLICE_OPEN = ("running", "blocked", "queued", "inbox", "verified")
1454
+
1455
+
1456
+ def _slice_refused(problem):
1457
+ print(f"{C['red']}REFUSED{C['reset']} {A.shown_text(problem)}")
1458
+ return 2
1459
+
1460
+
1461
+ def _slice_when(at):
1462
+ return time.strftime("%Y-%m-%d %H:%M", time.localtime(float(at or 0)))
1463
+
1464
+
1465
+ def _slice_age(seconds):
1466
+ minutes = max(0, int(seconds // 60))
1467
+ if minutes < 60:
1468
+ return f"{minutes}m"
1469
+ if minutes < 24 * 60:
1470
+ return f"{minutes // 60}h {minutes % 60}m"
1471
+ return f"{minutes // (24 * 60)}d {minutes % (24 * 60) // 60}h"
1472
+
1473
+
1474
+ def _slice_places(board, iid):
1475
+ """[(state, item)] for each line the board holds with this id: one, unless the board names it twice."""
1476
+ return [(state, item) for state in A.BOARD_STATES for item in board[state] if item["id"] == iid]
1477
+
1478
+
1479
+ def _slice_named(board, named):
1480
+ """(id, None) for the slice a command acts on: the one named, else the one running; (None, why) when neither."""
1481
+ named = (named or "").strip()
1482
+ if named:
1483
+ return named, None
1484
+ running = [item["id"] for item in board["running"]]
1485
+ if not running:
1486
+ return None, "nothing is running: name the slice with --slice"
1487
+ if len(running) > 1:
1488
+ return None, f"{len(running)} slices are running ({', '.join(running)}): name one with --slice"
1489
+ return running[0], None
1490
+
1491
+
1492
+ def _slice_item(board, iid):
1493
+ """(state, item, None) for one board id, or (None, None, why it cannot be moved)."""
1494
+ places = _slice_places(board, iid)
1495
+ if not places:
1496
+ return None, None, f"{iid} is not on the board; `polyctl board add` admits an item with its acceptance boundary"
1497
+ if len(places) > 1:
1498
+ return None, None, (f"{iid} is on the board twice, under {places[0][0]} and {places[1][0]}: keep one line "
1499
+ "of it, then move it")
1500
+ return places[0][0], places[0][1], None
1501
+
1502
+
1503
+ def _slice_blocked_by(root, iid):
1504
+ """Who made a blocked slice's block, from the newest move polyctl recorded of it; None when no move says so."""
1505
+ rows = [row for row in A.slice_moves(root) if row.get("slice") == iid]
1506
+ return rows[-1].get("by") if rows and rows[-1].get("to") == "blocked" else None
1507
+
1508
+
1509
+ def _slice_budget_parked(root, iid, item):
1510
+ """Whether a blocked slice was parked on its budget by the watchdog."""
1511
+ needs = str((item.get("notes") or {}).get("needs") or "")
1512
+ if needs == "budget" or needs.startswith("budget ("):
1513
+ return True
1514
+ parked = False
1515
+ for row in A.slice_moves(root):
1516
+ if row.get("slice") != iid:
1517
+ continue
1518
+ if row.get("to") == "running" and row.get("by") not in ("implementer", "watchdog", None):
1519
+ parked = False
1520
+ elif row.get("to") == "blocked" and row.get("by") == "watchdog":
1521
+ row_needs = str(((row.get("notes") if isinstance(row.get("notes"), dict) else None) or {}).get("needs")
1522
+ or "")
1523
+ if (row.get("why") == "the slice spent past the budget it was given"
1524
+ or row_needs == "budget" or row_needs.startswith("budget (")):
1525
+ parked = True
1526
+ return parked
1527
+
1528
+
1529
+ def _boundary_file_pointer(root, named):
1530
+ """(`path@commit`, None) for the boundary file a slice starts against, or (None, why it cannot be one).
1531
+
1532
+ A boundary file is read at the commit its pointer names (docs/slices.md), so it must be in the repository
1533
+ and committed as it stands: an uncommitted one would be read as the worktree holds it, which the
1534
+ implementer can change. The path is the repository's, from its root, as a row's `paths:` are.
1535
+ """
1536
+ real_root = os.path.realpath(root)
1537
+ full = os.path.realpath(os.path.join(root, named))
1538
+ if not full.startswith(real_root + os.sep) or not os.path.isfile(full):
1539
+ return None, f"--boundary-file {named}: no file of that name inside the repository, from its root"
1540
+ rel = os.path.relpath(full, real_root).replace(os.sep, "/")
1541
+ if "·" in rel or "@" in rel:
1542
+ return None, f"--boundary-file {rel}: a pointer is `path@commit`, and a path holding '·' or '@' cannot be one"
1543
+ try:
1544
+ tracked = rel.encode(UTF8) in A._git_output(root, "ls-files", "-z", "--", rel).split(b"\0")
1545
+ changed = A._git_output(root, "status", "--porcelain", "-z", "--", rel).strip(b"\0")
1546
+ except RuntimeError as exc:
1547
+ return None, f"--boundary-file {rel}: {exc}"
1548
+ if not tracked or changed:
1549
+ what = "has changes nobody committed" if tracked else "is not committed"
1550
+ return None, (f"--boundary-file {rel} {what}: commit it first, since a boundary is read at the commit its "
1551
+ "pointer names")
1552
+ head = A._git_text(root, "rev-parse", "--short=12", "HEAD")
1553
+ return f"{rel}@{head}", None
1554
+
1555
+
1556
+ def _slice_start(cfg, args, edit):
1557
+ """Move a queued slice to running, or resume a blocked one; each start is a line in the slice ledger.
1558
+
1559
+ The playbook has the implementer take the first READY item and settle alone which READY item comes next, so a
1560
+ turn polyctl started for the implementer may start a READY item - queued, its needs landed, waiting on no one - and
1561
+ resume a slice it blocked itself. Anything else chooses scope, which is the architect's or a person's: an item
1562
+ that is not READY, a block someone else made, a boundary file. Refused, nothing is written (SLICE-LIFECYCLE).
1563
+ Whether it is READY is judged on `edit`, the reading the move is made on (SLICE-LIFECYCLE-2).
1564
+ """
1565
+ shown_text = A.shown_text
1566
+ root = cfg["root"]
1567
+ iid, role = (args.text or "").strip(), A.invoking_role()
1568
+ if not iid:
1569
+ return _slice_refused("name the item: `polyctl slice start <id>`; `polyctl board ready` lists what may start now")
1570
+ state, item, problem = _slice_item(edit.board, iid)
1571
+ if problem:
1572
+ return _slice_refused(problem)
1573
+ if state == "running":
1574
+ if args.boundary_file:
1575
+ return _slice_refused(f"{iid} is running already: a boundary that changes mid-slice is a "
1576
+ f"re-specification, recorded with `polyctl decide \"…\" --scope {iid} --why \"…\"`")
1577
+ print(f"{C['dim']}{shown_text(iid)} is running already; nothing moved{C['reset']}")
1578
+ return 0
1579
+ if state not in ("queued", "blocked"):
1580
+ return _slice_refused({
1581
+ "inbox": f"{iid} is in the inbox, held without an acceptance boundary: it starts once one is written "
1582
+ "and it is queued",
1583
+ "verified": f"{iid} is verified: its gates passed, and it lands rather than starts again",
1584
+ }.get(state, f"{iid} is {state}: a slice that ended does not start again; `polyctl board add` admits new work"))
1585
+ not_ready = A.lane_not_ready(root, iid, edit.data) if state == "queued" else None
1586
+ if role == "implementer":
1587
+ if args.boundary_file:
1588
+ return _slice_refused("a boundary is the architect's to write (docs/roles.md): start the item as the "
1589
+ "board admitted it, or ask for another boundary with `polyctl ask`")
1590
+ if not_ready:
1591
+ return _slice_refused(f"{not_ready}; an implementer starts only a READY item, and `polyctl board ready` "
1592
+ "lists them")
1593
+ if state == "blocked" and _slice_budget_parked(root, iid, item):
1594
+ return _slice_refused(
1595
+ f"{iid} is parked on its budget by the watchdog, and nothing gives it back on its own: "
1596
+ f"the architect or a person gives it more with `polyctl slice start {iid}`")
1597
+ blocker = _slice_blocked_by(root, iid) if state == "blocked" else "implementer"
1598
+ if blocker != "implementer":
1599
+ return _slice_refused(
1600
+ f"{iid} is parked on quota by the watchdog, which gives it back when the limit resets"
1601
+ if blocker == "watchdog" else
1602
+ f"{iid} was blocked by {blocker or 'a hand edit polyctl has no record of'}: a block is lifted by whoever "
1603
+ "made it, the architect or a person")
1604
+ notes = {"waiting": None}
1605
+ if state == "queued" or not item["notes"].get("since"):
1606
+ notes["since"] = time.strftime("%Y-%m-%d %H:%M")
1607
+ if state == "blocked":
1608
+ # The block's reason goes; a `needs:` the slice carried before it comes back, as a quota park gives it back.
1609
+ notes.update({"needs": item["notes"].get(A.HELD_NEEDS) or None, A.HELD_NEEDS: None})
1610
+ if args.boundary_file:
1611
+ pointer, problem = _boundary_file_pointer(root, args.boundary_file)
1612
+ if problem:
1613
+ return _slice_refused(problem)
1614
+ # One source of truth, never two: the file replaces the sentence, which the ledger keeps (docs/slices.md).
1615
+ notes.update({"boundary": pointer, "acceptance": None})
1616
+ why = "; ".join(part for part in (" ".join((args.why or "").split()),
1617
+ f"started while not READY: {not_ready}" if not_ready else "") if part) or None
1618
+ others = [other["id"] for other in edit.board["running"]]
1619
+ edit.move(iid, "running", notes, by=role or "person", why=why)
1620
+ edit.write()
1621
+ print(f"{C['green']}running{C['reset']} {C['b']}{shown_text(iid)}{C['reset']} {shown_text(item['title'])} "
1622
+ f"{C['dim']}{state} → running, recorded in .polyctl/ledger/slices.jsonl{C['reset']}")
1623
+ if why:
1624
+ print(f" {C['yellow']}{shown_text(why)}{C['reset']}")
1625
+ if others:
1626
+ print(f" {C['dim']}also running: {shown_text(', '.join(others))}; reviews now count for {shown_text(iid)}, "
1627
+ f"the first slice under running{C['reset']}")
1628
+ return 0
1629
+
1630
+
1631
+ def _slice_block(cfg, args, edit):
1632
+ """Park a running slice under `blocked` with what it waits on, which anyone may do.
1633
+
1634
+ The reason becomes the item's `needs:`, which on a blocked item is its reason in words and what `polyctl status`
1635
+ shows; a `needs:` the slice carried is kept in `held-needs:` and given back when it resumes, as the watchdog's
1636
+ quota park keeps it. `--waiting human` says it waits on a person, who is told directly (SLICE-LIFECYCLE).
1637
+ """
1638
+ shown_text = A.shown_text
1639
+ import re
1640
+ why, waiting = " ".join((args.text or args.why or "").split()), (args.waiting or "").strip()
1641
+ if not why:
1642
+ return _slice_refused("say what the slice waits on: `polyctl slice block \"the vendor's signing key\"`")
1643
+ if "·" in why:
1644
+ return _slice_refused("a reason holds no '·': it separates a board line's notes")
1645
+ if waiting and not re.fullmatch(r"[\w-]+", waiting):
1646
+ return _slice_refused("--waiting is one word: human, architect, decision or external")
1647
+ iid, problem = _slice_named(edit.board, args.slice)
1648
+ state, item, problem = (None, None, problem) if problem else _slice_item(edit.board, iid)
1649
+ if problem:
1650
+ return _slice_refused(problem)
1651
+ if state == "blocked":
1652
+ print(f"{C['dim']}{shown_text(iid)} is blocked already, on "
1653
+ f"{shown_text(item['notes'].get('needs') or 'nothing it names')}; nothing moved{C['reset']}")
1654
+ return 0
1655
+ if state != "running":
1656
+ return _slice_refused(f"{iid} is {state}: only a running slice is blocked; a queued item that must not "
1657
+ "start yet carries `waiting:` instead")
1658
+ notes = {"needs": why}
1659
+ if item["notes"].get("needs") and not item["notes"].get(A.HELD_NEEDS):
1660
+ notes[A.HELD_NEEDS] = item["notes"]["needs"]
1661
+ if waiting:
1662
+ notes["waiting"] = waiting
1663
+ edit.move(iid, "blocked", notes, by=A.invoking_role() or "person", why=why)
1664
+ edit.write()
1665
+ print(f"{C['red']}blocked{C['reset']} {C['b']}{shown_text(iid)}{C['reset']} {shown_text(item['title'])} "
1666
+ f"{C['dim']}needs: {shown_text(why)}{' · waiting: ' + shown_text(waiting) if waiting else ''}; "
1667
+ f"running → blocked, recorded in .polyctl/ledger/slices.jsonl{C['reset']}")
1668
+ print(f" {C['dim']}take the next READY item (`polyctl board ready`); `polyctl slice start {shown_text(iid)}` resumes it{C['reset']}")
1669
+ return 0
1670
+
1671
+
1672
+ def _slice_abandon(cfg, args, edit):
1673
+ """Drop a slice on the record: its row moves to `rejected`, with the reason as its `abandoned:` note.
1674
+
1675
+ Abandoning is a legitimate outcome (docs/slices.md), and a row deleted from the board said nothing of the
1676
+ slice ever having been dropped, or why. `rejected` is the section the board already keeps for work that will
1677
+ not land: its worktree may be retired and its review artefacts archived. Whether work is dropped is scope, the
1678
+ architect's or a person's to decide, so a turn polyctl started for the implementer is refused (SLICE-LIFECYCLE).
1679
+ """
1680
+ shown_text = A.shown_text
1681
+ role = A.invoking_role()
1682
+ if role == "implementer":
1683
+ return _slice_refused("abandoning a slice is the architect's decision or a person's (docs/roles.md): park it "
1684
+ "with `polyctl slice block \"…\"` and ask whether to drop it with `polyctl ask`")
1685
+ why = " ".join((args.why or "").split())
1686
+ if not why:
1687
+ return _slice_refused("--why is required: an abandoned slice is an outcome, and its reason is what is kept "
1688
+ "of it")
1689
+ if "·" in why:
1690
+ return _slice_refused("a reason holds no '·': it separates a board line's notes")
1691
+ iid, problem = _slice_named(edit.board, args.slice or args.text)
1692
+ state, item, problem = (None, None, problem) if problem else _slice_item(edit.board, iid)
1693
+ if problem:
1694
+ return _slice_refused(problem)
1695
+ if state == "rejected":
1696
+ print(f"{C['dim']}{shown_text(iid)} is rejected already; nothing moved{C['reset']}")
1697
+ return 0
1698
+ if state == "done":
1699
+ return _slice_refused(f"{iid} is done: a slice that landed is not abandoned; undoing what it landed is a "
1700
+ "slice of its own")
1701
+ edit.move(iid, "rejected", {"abandoned": why}, by=role or "person", why=why)
1702
+ edit.write()
1703
+ print(f"{C['yellow']}abandoned{C['reset']} {C['b']}{shown_text(iid)}{C['reset']} {shown_text(item['title'])} "
1704
+ f"{C['dim']}{state} → rejected, recorded in .polyctl/ledger/slices.jsonl{C['reset']}")
1705
+ if state in ("running", "blocked"):
1706
+ print(f" {C['dim']}it was {state}: tell the implementer with `polyctl note \"…\"`, since what it has in the tree "
1707
+ f"for {shown_text(iid)} belongs to no slice now{C['reset']}")
1708
+ return 0
1709
+
1710
+
1711
+ def _slice_status(cfg, args):
1712
+ """Where one slice stands: its state and since when, the moves polyctl recorded, rounds used and its newest review.
1713
+
1714
+ It reads and writes nothing. The board is what a restarted session reads; the ledger says how the slice got
1715
+ there, and where the two disagree the slice was moved by hand, which is said rather than smoothed over
1716
+ (SLICE-LIFECYCLE).
1717
+ """
1718
+ shown_text = A.shown_text
1719
+ root, reviews = cfg["root"], cfg.get("reviews", "semantic-review")
1720
+ board = A.board(root)
1721
+ named = (args.text or args.slice or "").strip()
1722
+ if not named:
1723
+ running = [item["id"] for item in board["running"]]
1724
+ if not running:
1725
+ print(f"{C['dim']}Nothing is running.{C['reset']} `polyctl slice status <id>` for another slice, `polyctl slices` "
1726
+ "for every one.")
1727
+ return 0
1728
+ named = running[0] # the one review accounting reads as current
1729
+ places = _slice_places(board, named)
1730
+ try:
1731
+ history, unreadable = [row for row in A.slice_moves(root, voided=True) if row.get("slice") == named], None
1732
+ except Exception as exc:
1733
+ history, unreadable = [], f"{type(exc).__name__}: {' '.join(str(exc).split())}"
1734
+ # A move whose board write failed is in the history, marked, and nowhere else (SLICE-LIFECYCLE-2).
1735
+ moves = [row for row in history if not row.get("void")]
1736
+ if not places and not moves:
1737
+ print(f"{C['yellow']}{shown_text(named)} is not on the board{C['reset']}, and polyctl recorded no move of it"
1738
+ + (" that reached the board" if history else "") + "; `polyctl slices` lists every slice")
1739
+ return 1 if unreadable is None else _slice_unreadable(unreadable)
1740
+ state, item = places[0] if places else (None, None)
1741
+ newest = moves[-1] if moves else None
1742
+ title = item["title"] if item else next((row["title"] for row in history if row.get("title")), "")
1743
+ print(f"{C['b']}{shown_text(named)}{C['reset']} {shown_text(title)}")
1744
+ if state is None:
1745
+ print(f" state {C['red']}not on the board{C['reset']}: polyctl last recorded it under {shown_text(newest.get('to'))} on "
1746
+ f"{_slice_when(newest.get('at'))}, and its row was removed by hand; `polyctl slice abandon --why` drops a "
1747
+ "slice on the record")
1748
+ elif newest and newest.get("to") == state:
1749
+ print(f" state {state} since {_slice_when(newest.get('at'))}, "
1750
+ f"{_slice_age(time.time() - float(newest.get('at') or 0))} ago, moved by {shown_text(newest.get('by'))}")
1751
+ elif newest:
1752
+ print(f" state {state} {C['yellow']}{shown_text(_slice_off_record(newest, state))}{C['reset']}")
1753
+ else:
1754
+ since = item["notes"].get("since")
1755
+ print(f" state {state}" + (f" since {shown_text(since)}, as the board's since: note says" if since else "")
1756
+ + f" {C['dim']}no move recorded: put on the board or moved by hand{C['reset']}")
1757
+ if places[1:]:
1758
+ print(f" {C['red']}on the board twice{C['reset']}, under {places[0][0]} and {places[1][0]}")
1759
+ if item and state in SLICE_OPEN:
1760
+ spent, budget = A.rounds(root, reviews, item), S.get(cfg, "round_budget")
1761
+ colour = C["red"] if spent > budget else C["reset"]
1762
+ print(f" rounds {colour}{spent} of {budget}{C['reset']}")
1763
+ try:
1764
+ review = A.latest_slice_review(root, reviews, named)
1765
+ except Exception as exc:
1766
+ review, unreadable = None, unreadable or f"the review ledger: {type(exc).__name__}: {exc}"
1767
+ if review is None:
1768
+ print(f" review {C['dim']}none that reached a verdict{C['reset']}")
1769
+ else:
1770
+ kind = " (retrospective)" if review["kind"] == "commit-range" else ""
1771
+ colour = C["green"] if review["verdict"] == "APPROVED" else C["yellow"]
1772
+ print(f" review {colour}{shown_text(review['verdict'])}{C['reset']}{kind} on {_slice_when(review['at'])} "
1773
+ f"{C['dim']}{shown_text(reviews)}/{shown_text(review['artefact'])}{C['reset']}")
1774
+ if not review.get("recorded", True):
1775
+ print(f" {C['yellow']}no row in the review ledger: a review from before it, read from its file "
1776
+ f"as it stands{C['reset']}")
1777
+ counts = review["counts"] or {}
1778
+ if counts:
1779
+ print(" " + " · ".join(f"{key} {shown_text(counts.get(key, 0))}"
1780
+ for key in ("BLOCKER", "HIGH", "MEDIUM", "LOW")))
1781
+ if review["problem"]:
1782
+ print(f" {C['yellow']}{shown_text(review['problem'])}{C['reset']}: its findings cannot be read")
1783
+ elif review["verdict"] == "NEEDS_CHANGES":
1784
+ for finding in review["findings"][:10]:
1785
+ print(f" - {shown_text(finding)}")
1786
+ if len(review["findings"]) > 10:
1787
+ print(f" {C['dim']}and {len(review['findings']) - 10} more{C['reset']}")
1788
+ if history:
1789
+ print(" moves")
1790
+ for row in history:
1791
+ arrow = f"{row.get('from')} → {row.get('to')}" if row.get("from") else f"enters {row.get('to')}"
1792
+ void = row.get("void")
1793
+ print(f" {_slice_when(row.get('at'))} {shown_text(arrow):<20} by {shown_text(row.get('by'))}"
1794
+ + (f": {shown_text(row['why'])}" if row.get("why") else "")
1795
+ + (f" {C['yellow']}did not happen: {shown_text(void.get('why'))}{C['reset']}" if void else ""))
1796
+ if item and item["notes"]:
1797
+ print(" notes " + " · ".join(f"{shown_text(key)}: {shown_text(value)}" if value else shown_text(key)
1798
+ for key, value in item["notes"].items()))
1799
+ return 0 if unreadable is None else _slice_unreadable(unreadable)
1800
+
1801
+
1802
+ def _slice_off_record(row, state):
1803
+ """What it means that the board holds a slice under `state` while polyctl's newest recorded move put it elsewhere.
1804
+
1805
+ A row moved by hand, mostly. Where the board still holds it in the section that move took it from, the board
1806
+ may never have taken the move: polyctl records a move before it writes the board, and a process stopped between
1807
+ the two writes leaves no line voiding it (SLICE-LIFECYCLE-2).
1808
+ """
1809
+ if row.get("from") == state:
1810
+ return (f"the board never took polyctl's last recorded move of it, {state} → {row.get('to')} on "
1811
+ f"{_slice_when(row.get('at'))}: polyctl stopped between recording it and writing the board, or a hand "
1812
+ "moved it back")
1813
+ return f"moved by hand: polyctl last recorded it under {row.get('to')} on {_slice_when(row.get('at'))}"
1814
+
1815
+
1816
+ def _slice_unreadable(problem):
1817
+ print(f"{C['red']}a ledger cannot be read{C['reset']}: {A.shown_text(problem)}. Nothing is appended to a chained "
1818
+ "ledger until it is mended, so no move is recorded or made until then (docs/ledger.md)")
1819
+ return 1
1820
+
1821
+
1822
+ def cmd_slice(cfg, args):
1823
+ """`polyctl slice start|block|abandon|status`: a slice's moves between the board's sections, each one recorded.
1824
+
1825
+ A move is decided on one reading of the board and made on that same reading, which polyctl's other writers wait
1826
+ for and which is compared with the board as it stands before it is replaced (BoardEdit): a row edited
1827
+ meanwhile is never moved on a judgement made before the edit (SLICE-LIFECYCLE-2).
1828
+ """
1829
+ for line in _mailbox_banner(cfg):
1830
+ print(line)
1831
+ if args.action == "status":
1832
+ return _slice_status(cfg, args)
1833
+ with A.BoardEdit(cfg["root"], hold=True) as edit:
1834
+ return {"start": _slice_start, "block": _slice_block, "abandon": _slice_abandon}[args.action](cfg, args, edit)
1835
+
1836
+
1837
+ def cmd_slices(cfg, args):
1838
+ """Every slice on the board, by state, with since when; `--open` leaves out done and rejected.
1839
+
1840
+ A slice whose row was removed by hand is listed too, from the last move polyctl recorded of it: a deleted row is
1841
+ the quiet drop docs/slices.md warns of, and abandoning one on the record is `polyctl slice abandon` (SLICE-LIFECYCLE).
1842
+ """
1843
+ shown_text = A.shown_text
1844
+ root = cfg["root"]
1845
+ for line in _mailbox_banner(cfg):
1846
+ print(line)
1847
+ board = A.board(root)
1848
+ try:
1849
+ moves, unreadable = A.slice_moves(root), None
1850
+ except Exception as exc:
1851
+ moves, unreadable = [], f"{type(exc).__name__}: {' '.join(str(exc).split())}"
1852
+ newest, titles = {}, {}
1853
+ for row in moves:
1854
+ newest[row.get("slice")] = row
1855
+ titles[row.get("slice")] = row.get("title") or titles.get(row.get("slice")) or ""
1856
+ held = {item["id"] for items in board.values() for item in items}
1857
+ shown = 0
1858
+ for state in SLICE_OPEN + (() if args.open else ("done", "rejected")):
1859
+ for item in board[state]:
1860
+ row, shown = newest.get(item["id"]), shown + 1
1861
+ since = _slice_when(row.get("at")) if row and row.get("to") == state else "-"
1862
+ why = item["notes"].get("needs") if state == "blocked" else item["notes"].get("abandoned")
1863
+ hand = f" {C['yellow']}{shown_text(_slice_off_record(row, state))}{C['reset']}" \
1864
+ if row and row.get("to") != state else ""
1865
+ print(f" {C['b']}{shown_text(item['id']):<14}{C['reset']} {state:<9} {since:<16} {shown_text(item['title'])}"
1866
+ + (f" {C['dim']}{shown_text(why)}{C['reset']}" if why else "") + hand)
1867
+ for sid, row in newest.items():
1868
+ if sid not in held and row.get("to") and (not args.open or row.get("to") in SLICE_OPEN):
1869
+ shown += 1
1870
+ print(f" {C['b']}{shown_text(sid):<14}{C['reset']} {C['red']}gone{C['reset']} "
1871
+ f"{_slice_when(row.get('at')):<16} "
1872
+ f"{shown_text(titles.get(sid))} {C['yellow']}not on the board: polyctl last recorded it under "
1873
+ f"{shown_text(row.get('to'))}, and its row was removed by hand{C['reset']}")
1874
+ if not shown:
1875
+ print(f"{C['dim']}No {'open ' if args.open else ''}slices on the board.{C['reset']}")
1876
+ return 0 if unreadable is None else _slice_unreadable(unreadable)
1877
+
1878
+
1879
+ def cmd_source(cfg, args):
1880
+ """External work queues: what is configured, what is waiting, what may enter.
1881
+
1882
+ Admission is the whole point of this command. Pulling an issue is free and
1883
+ carries no authority; a tracker item is something a person wrote, not a
1884
+ specification anyone verified. An item enters the board only with a written
1885
+ acceptance boundary, because the alternative — an agent inferring scope from
1886
+ a title — is how a one-line bug fix becomes a refactor nobody asked for.
1887
+
1888
+ `polyctl` does not judge which items qualify: it has no model and no tracker
1889
+ credential. It enforces the rule; an architect turn makes the call and writes
1890
+ it into the inbox file.
1891
+ """
1892
+ root = cfg["root"]
1893
+ sc = A.sources(root)
1894
+ if not sc:
1895
+ print(f"{C['yellow']}No sources configured.{C['reset']} Create {C['b']}.polyctl/sources.json{C['reset']}:\n"
1896
+ f' {{"bound_root": "{root}", "wip_limit": 1, "refill_below": 3,\n'
1897
+ f' "sources": [{{"id": "linear-x", "kind": "mcp", "server": "linear",\n'
1898
+ f' "select": {{"team": "…", "state": "Todo"}}}}]}}')
1899
+ return 0
1900
+
1901
+ files = A.inbox_files(root)
1902
+ if args.action in ("list", "status"):
1903
+ bd = A.board(root)
1904
+ print(f"{C['b']}bound to{C['reset']} {sc.get('bound_root', root)}")
1905
+ for src in sc["sources"]:
1906
+ sel = " ".join(f"{k}={v}" for k, v in (src.get("select") or {}).items())
1907
+ wb = (src.get("writeback") or {})
1908
+ wbs = (f"{C['yellow']}writes back{C['reset']}" if wb.get("enabled")
1909
+ else f"{C['dim']}read-only{C['reset']}")
1910
+ print(f" {C['b']}{src['id']}{C['reset']} {src.get('kind','mcp')}:{src.get('server','?')}"
1911
+ f" {C['dim']}{sel}{C['reset']} {wbs}")
1912
+ depth = len(bd["queued"])
1913
+ low = depth < sc["refill_below"]
1914
+ col = C["yellow"] if low else C["green"]
1915
+ print(f"\n{C['b']}queue{C['reset']} {col}{depth} admitted{C['reset']}"
1916
+ f"{C['dim']} · refill below {sc['refill_below']} · wip limit {sc['wip_limit']}{C['reset']}"
1917
+ + (f" {C['yellow']}← needs a refill pass{C['reset']}" if low else ""))
1918
+ print(f"{C['b']}inbox{C['reset']} {len(bd['inbox'])} on the board, "
1919
+ f"{len(files)} pull file(s) not yet imported")
1920
+ return 0
1921
+
1922
+ # import — the only place an item crosses from "someone wrote this" to
1923
+ # "an agent may work on it unattended". Every item is judged and put on one reading of the board, written
1924
+ # once, and a pull file is marked imported only after that write: a board that changed meanwhile leaves
1925
+ # every file to import again (SLICE-LIFECYCLE-2).
1926
+ if not files:
1927
+ print(f"{C['dim']}Nothing in .polyctl/inbox/ to import.{C['reset']}")
1928
+ return 0
1929
+ admitted, held, refused, done = [], 0, 0, []
1930
+ with A.BoardEdit(root, hold=True) as edit:
1931
+ for f in files:
1932
+ try:
1933
+ doc = json.load(open(f, encoding=UTF8))
1934
+ except Exception as e:
1935
+ print(f"{C['red']}skip{C['reset']} {os.path.basename(f)}: unreadable ({e})")
1936
+ continue
1937
+ err = A.binding_error(root, doc.get("bound_root"))
1938
+ if err:
1939
+ print(f"{C['red']}REFUSED{C['reset']} {os.path.basename(f)}: {err}")
1940
+ continue
1941
+ # Each text a board line carries is one line, as `polyctl board add` writes it: a tracker item's title is
1942
+ # anyone's text, and a line break in it wrote items and sections of its own into the board, an
1943
+ # acceptance boundary among them that nobody wrote (LEADS-ADAPTERS).
1944
+ sid = " ".join(str(doc.get("source", "?")).split())
1945
+ refused_here = 0
1946
+ for number, it in enumerate(doc.get("items", []), 1):
1947
+ iid = it.get("id") if isinstance(it, dict) else None
1948
+ # An id is a text or a whole number: an item with none, an empty one or a false one was dropped
1949
+ # without a word and its file marked imported, so nobody could correct it (the review of
1950
+ # LEADS-ADAPTERS).
1951
+ if isinstance(iid, bool) or not isinstance(iid, (str, int)) or not str(iid).strip():
1952
+ print(f"{C['red']}REFUSED{C['reset']} item {number} in {os.path.basename(f)}: "
1953
+ + ("it has no id, a text or a whole number the board names it by" if isinstance(it, dict)
1954
+ else "it is no object with an id"))
1955
+ refused_here += 1
1956
+ continue
1957
+ iid = str(iid)
1958
+ title = " ".join(str(it.get("title") or "").split())
1959
+ acc = " ".join(str(it.get("acceptance") or "").split())
1960
+ why = " ".join(str(it.get("shape") or "").split()) or "no acceptance boundary written"
1961
+ problem = _source_item_problem(iid, (sid, title, acc, why))
1962
+ if problem:
1963
+ print(f"{C['red']}REFUSED{C['reset']} {A.shown_text(iid)} in {os.path.basename(f)}: {problem}")
1964
+ refused_here += 1
1965
+ continue
1966
+ if any(x["id"] == iid for st in A.BOARD_STATES for x in edit.board[st]):
1967
+ continue # already on the board
1968
+ if acc:
1969
+ edit.append("queued", f"- [{iid}] {title} · source: {sid} · acceptance: {acc}")
1970
+ admitted.append(iid)
1971
+ else:
1972
+ edit.append("inbox", f"- [{iid}] {title} · source: {sid} · needs: {why}")
1973
+ held += 1
1974
+ refused += refused_here
1975
+ if refused_here:
1976
+ # Kept to be imported again once corrected: what it admitted is on the board, and is not added twice.
1977
+ print(f"{C['yellow']}kept{C['reset']} {os.path.basename(f)}: correct its refused item(s) and run "
1978
+ "polyctl source import again")
1979
+ else:
1980
+ done.append(f)
1981
+ edit.write()
1982
+ for iid in admitted:
1983
+ dg = A.plan_digest(root, iid)
1984
+ if dg:
1985
+ A.record_plan(root, iid, dg) # baseline: the plan as admitted
1986
+ for f in done:
1987
+ os.rename(f, f + ".imported")
1988
+ print(f"{C['green']}{len(admitted)} admitted{C['reset']} to queued · "
1989
+ f"{C['yellow']}{held} held{C['reset']} in inbox (no acceptance boundary)"
1990
+ + (f" · {C['red']}{refused} refused{C['reset']}" if refused else ""))
1991
+ return 1 if refused else 0
1992
+
1993
+
1994
+ def _source_item_problem(iid, texts):
1995
+ """Why an imported item cannot be a board line as it reads, or None: its id must be one the board reads whole and a
1996
+ needs note can name, and no text of its line may hold the '·' that separates a line's notes - what `polyctl board add`
1997
+ holds an item to (BOARD-ADD-2, LEADS-ADAPTERS)."""
1998
+ import re
1999
+ if not re.fullmatch(BOARD_ID, iid):
2000
+ return ("its id cannot be one: an id holds no space, comma, ']', backslash or '·' and does not start with '(' "
2001
+ "or '/', so that a board line carries it whole")
2002
+ if any("·" in text for text in texts):
2003
+ return "its source, title, boundary or reason holds a '·', which separates a board line's notes"
2004
+ return None
2005
+
2006
+
2007
+ def cmd_hold(cfg, args):
2008
+ """Stop this project's agents and keep them stopped.
2009
+
2010
+ A kill switch that only kills is not a switch: the watchdog sees an idle
2011
+ session with open work and restarts it within a couple of minutes. So the
2012
+ stop and the lock are one operation, and every restart path checks the lock
2013
+ first.
2014
+
2015
+ It stops *every* agent process whose cwd is this repository, not just the one
2016
+ we most recently started. Detached turns accumulate — this project found
2017
+ fifteen live `kiro-cli` processes in one tree, four of them still burning
2018
+ CPU, because each nudge spawned one and nothing ever reaped them. Tracking
2019
+ only our own last child made the rest invisible.
2020
+ """
2021
+ root = cfg["root"]
2022
+ impl = cfg.get("implementer") or {}
2023
+ adapter = A.load_adapter(impl.get("adapter", ""), root) if impl else {}
2024
+ path = os.path.join(root, A.HOLD_FILE)
2025
+
2026
+ if args.action == "status":
2027
+ st = A.hold_state(root)
2028
+ if not st:
2029
+ print(f"{C['green']}running free{C['reset']} — no hold")
2030
+ else:
2031
+ print(f"{C['red']}HELD{C['reset']} by {C['b']}{st.get('by')}{C['reset']} "
2032
+ f"for {st['minutes']}m: {st.get('reason','')}")
2033
+ try:
2034
+ pids = A.agent_pids(root, adapter)
2035
+ except TableUnreadable as exc:
2036
+ # Not counted is not none (WINDOWS-TABLE-CLOSED).
2037
+ print(f"{C['yellow']}agent processes in this tree: unknown{C['reset']} — {exc}")
2038
+ return 0
2039
+ print(f"{len(pids)} agent process(es) in this tree" + (f": {pids}" if pids else ""))
2040
+ return 0
2041
+
2042
+ if args.action == "release":
2043
+ if not os.path.exists(path):
2044
+ print(f"{C['dim']}No hold to release.{C['reset']}")
2045
+ return 0
2046
+ st = A.hold_state(root) or {}
2047
+ name = None
2048
+ if args.note:
2049
+ # The agent wakes into a tree it did not change. Say what moved, or it
2050
+ # spends its first turns rediscovering it — or worse, mistrusting it.
2051
+ impl, arch = A.mail_names(cfg)
2052
+ name = f"{datetime.now():%Y%m%d-%H%M}-{arch}-to-{impl}-INFO-hold-released.md"
2053
+ # Through write_mail, as every mail polyctl writes; it was written past it (ROLE-TABLE-2). Written while the hold
2054
+ # stands: the watchdog starts a turn as soon as it finds none, and a turn started before the note was
2055
+ # written woke without it (LEADS-ADAPTERS).
2056
+ name = A.write_mail(root, cfg, name, language.text(cfg, "hold.released", minutes=st.get("minutes", 0),
2057
+ reason=st.get("reason", ""), note=args.note),
2058
+ {"kind": "info", "class": "fyi", "from": arch, "to": impl})
2059
+ os.remove(path)
2060
+ print(f"{C['green']}released{C['reset']} after {st.get('minutes', 0)}m")
2061
+ if name:
2062
+ print(f"handover note → {cfg['mailbox']}/{name}")
2063
+ return 0
2064
+
2065
+ # hold — stops unattended turns only. An interactive session has a person in
2066
+ # it who did not ask to be stopped; the lock still keeps the watchdog from
2067
+ # starting anything new.
2068
+ # The hold stands before anything is counted, and a watchdog cycle already past its own reading of it is
2069
+ # waited for: counted first, a turn a cycle started between the count and the hold read no hold and ran on
2070
+ # under it (JOURNAL-6).
2071
+ from .storage import replace_file_durably, _exclusive_lock
2072
+ from . import watchdog as W
2073
+ hold = {"by": args.by, "reason": args.reason or "manual intervention", "at": int(time.time()), "stopped": []}
2074
+ os.makedirs(os.path.dirname(path), exist_ok=True)
2075
+ replace_file_durably(path, json.dumps(hold, indent=2).encode(UTF8))
2076
+ late = None
2077
+ try:
2078
+ with _exclusive_lock(os.path.join(W.STATE_DIR, W.CYCLE_LOCK.format(key=A.project_key(root))), timeout=60):
2079
+ pass
2080
+ except LedgerLockTimeout:
2081
+ late = "a watchdog cycle that began before this hold was still running after a minute"
2082
+ except OSError as exc:
2083
+ late = f"the watchdog's cycle lock could not be taken ({exc})"
2084
+ try:
2085
+ code = _hold_stop(root, adapter, args, path, hold)
2086
+ except TableUnreadable as exc:
2087
+ # It said no agent turn was running, where it could not see one (WINDOWS-TABLE-CLOSED).
2088
+ print(f"{C['red']}hold set, but {exc}{C['reset']}: a turn in this tree may still be running, and polyctl "
2089
+ "cannot see it to stop it. The hold keeps the watchdog from starting another; stop a running "
2090
+ "turn by hand, or run `polyctl hold` again once the table can be read")
2091
+ code = 1
2092
+ if late:
2093
+ # Counted while that cycle ran: a turn it starts after its last reading of the hold is not counted (JOURNAL-6).
2094
+ print(f"{C['yellow']}{late}{C['reset']}: the hold stands, and a cycle reads it again before it starts a "
2095
+ "turn, but a turn it started as the hold was placed may not be stopped - `polyctl hold status` shows "
2096
+ "it, and `polyctl hold` again stops it")
2097
+ return 1
2098
+ return code
2099
+
2100
+
2101
+ def _hold_stop(root, adapter, args, path, hold):
2102
+ """Count the unattended turns in this tree, record them in the hold, stop them, and prove it (JOURNAL-6).
2103
+
2104
+ What was stopped is read again, never assumed: on Windows taskkill is refused a process
2105
+ another user or an elevated prompt started, and misses a child whose parent had already
2106
+ exited, and the hold still said every tree was stopped (the 2026-09-08 audit). Each stop
2107
+ returns what of its tree still runs, the process table is read once more for unattended
2108
+ turns and what ended turns left, and whatever still runs is named and the hold exits 1
2109
+ (WINDOWS-STOP-PROVEN).
2110
+ """
2111
+ from .storage import replace_file_durably
2112
+ pids = A.agent_pids(root, adapter, headless_only=True)
2113
+ hold["stopped"] = pids
2114
+ replace_file_durably(path, json.dumps(hold, indent=2).encode(UTF8))
2115
+ dead, survived = A.orphans(root, adapter), []
2116
+ if dead:
2117
+ print(f"clearing {len(dead)} orphaned process(es) left by ended turns: {dead}")
2118
+ survived += A.sweep_orphans(dead) or []
2119
+ if not pids:
2120
+ still = _hold_still_running(root, adapter, survived) if dead else []
2121
+ if A.unplaced_agent_pids(root, adapter):
2122
+ print(f"{C['yellow']}hold set{C['reset']} — no agent turn could be placed in this tree")
2123
+ return max(_hold_unplaced(root, adapter), _hold_proven(still))
2124
+ print(f"{C['yellow']}hold set{C['reset']} — no agent turn was running")
2125
+ return _hold_proven(still)
2126
+ print(f"stopping {len(pids)} process(es): {pids}")
2127
+ for pid in pids:
2128
+ survived += A.kill_turn(pid, signal.SIGTERM) or [] # whole group; let it finish the write it is in
2129
+ deadline = time.time() + args.grace
2130
+ while time.time() < deadline:
2131
+ alive = [p for p in pids if _alive(p)]
2132
+ if not alive:
2133
+ break
2134
+ time.sleep(0.5)
2135
+ alive = [p for p in pids if _alive(p)]
2136
+ for pid in alive:
2137
+ survived += A.kill_turn(pid, getattr(signal, "SIGKILL", signal.SIGTERM)) or []
2138
+ still = _hold_still_running(root, adapter, survived)
2139
+ if os.name == "nt":
2140
+ # taskkill /T /F ends a tree at once; nothing exited on request (#71).
2141
+ print(f"{C['red']}HELD{C['reset']} — {len([p for p in pids if p not in still])} process tree(s) stopped "
2142
+ "by force (Windows). The watchdog will not restart while .polyctl/hold exists.")
2143
+ else:
2144
+ print(f"{C['red']}HELD{C['reset']} — {len([p for p in pids if p not in alive and p not in still])} exited "
2145
+ f"on request, {len([p for p in alive if p not in still])} killed. The watchdog will not restart while "
2146
+ ".polyctl/hold exists.")
2147
+ return max(_hold_unplaced(root, adapter), _hold_proven(still))
2148
+
2149
+
2150
+ def _hold_still_running(root, adapter, survived):
2151
+ """What still runs in this tree after a hold stopped it: what a stop returned that runs yet - a later stop may
2152
+ have ended it - and the unattended turns and what ended turns left, the process table read again
2153
+ (WINDOWS-STOP-PROVEN)."""
2154
+ return sorted(set(A._still_running(survived, seconds=0)) | set(A.agent_pids(root, adapter, headless_only=True))
2155
+ | set(A.orphans(root, adapter)))
2156
+
2157
+
2158
+ def _hold_proven(still):
2159
+ """0 when nothing the hold stopped still runs; else name what does and what to do about it, and 1
2160
+ (WINDOWS-STOP-PROVEN)."""
2161
+ if not still:
2162
+ return 0
2163
+ print(f"{C['red']}{len(still)} process(es) still run in this tree after the hold{C['reset']}: {still}. The "
2164
+ f"hold stands and the watchdog starts nothing beside them; {_stop_by_hand()} - `polyctl hold status` shows "
2165
+ "what still runs")
2166
+ return 1
2167
+
2168
+
2169
+ def _stop_by_hand():
2170
+ """What a person does about a process polyctl could not stop, as their platform does it (WINDOWS-STOP-PROVEN)."""
2171
+ if os.name == "nt":
2172
+ return ("stop them by hand with `taskkill /T /F /PID <pid>`, from a prompt of the user that started them, "
2173
+ "or an elevated one where access is denied")
2174
+ return "stop them by hand with `kill -9 <pid>`, as the user that started them"
2175
+
2176
+
2177
+ def _hold_unplaced(root, adapter):
2178
+ """Say which agent processes a hold could not stop because they cannot be placed (#71)."""
2179
+ unplaced = A.unplaced_agent_pids(root, adapter)
2180
+ if not unplaced:
2181
+ return 0
2182
+ print(f"{C['red']}{len(unplaced)} agent process(es) were not stopped{C['reset']}: their working "
2183
+ f"directory could not be read, so they cannot be placed in this tree: {unplaced}. Stop them "
2184
+ "by hand if they work here; the hold keeps the watchdog from starting another.")
2185
+ return 1
2186
+
2187
+
2188
+ def _etime(seconds):
2189
+ """Seconds as `ps -o etime` writes them: [[dd-]hh:]mm:ss, the days two digits wide where macOS's ps pads them."""
2190
+ days, rest = divmod(int(seconds), 86400)
2191
+ hours, rest = divmod(rest, 3600)
2192
+ minutes, secs = divmod(rest, 60)
2193
+ clock = f"{hours:02d}:{minutes:02d}:{secs:02d}" if days or hours else f"{minutes:02d}:{secs:02d}"
2194
+ return (f"{days:02d}-" if sys.platform == "darwin" else f"{days}-") + clock if days else clock
2195
+
2196
+
2197
+ def _ps_args(argv):
2198
+ """An argument vector as `ps -o args=` writes it: joined by spaces, each control character escaped as ps does.
2199
+
2200
+ A prompt handed to a turn as an argument holds newlines, and ps kept each turn on one
2201
+ line: macOS writes a tab and a newline in octal and the other controls as ^X, procps
2202
+ a question mark.
2203
+ """
2204
+ def shown(ch):
2205
+ code = ord(ch)
2206
+ if code >= 32 and code != 127:
2207
+ return ch
2208
+ if sys.platform != "darwin":
2209
+ return "?"
2210
+ return f"\\{code:03o}" if ch in "\t\n" else "^" + chr(code ^ 64)
2211
+
2212
+ return " ".join("".join(shown(ch) for ch in arg) for arg in argv)
2213
+
2214
+
2215
+ def cmd_writers(cfg, args):
2216
+ """Who is writing in this tree — turns, not processes, with orphans set aside.
2217
+
2218
+ This is the measurement a single-writer rule should run. The process table
2219
+ answers a different question: one turn is a wrapper, a runtime and an engine,
2220
+ and a turn that ended can leave the last two behind at 0% CPU with the repo
2221
+ as their cwd. Counting processes reported four writers where there were
2222
+ none, and an implementer that trusted the count refused to write for three
2223
+ and a half hours. Exit status is 0 for at most one live turn, 1 otherwise;
2224
+ `--clean` stops orphans only — never a live turn, never a person's session.
2225
+ """
2226
+ root = cfg["root"]
2227
+ impl = cfg.get("implementer") or {}
2228
+ adapter = A.load_adapter(impl.get("adapter", "")) if impl else {}
2229
+ try:
2230
+ roots, dead = A.writers(root, adapter)
2231
+ unplaced = A.unplaced_agent_pids(root, adapter)
2232
+ except TableUnreadable as exc:
2233
+ # A count that could not look must not report none, nor pass a single-writer rule (WINDOWS-TABLE-CLOSED).
2234
+ if args.json:
2235
+ print(json.dumps({"writers": None, "unreadable": str(exc)}, ensure_ascii=False))
2236
+ else:
2237
+ print(f"{C['red']}writers unknown{C['reset']} — {exc}; whoever counts writers must not read "
2238
+ "this as none: run `polyctl writers` again once the table can be read")
2239
+ return 1
2240
+ if unplaced:
2241
+ # A count that cannot see a writer must not report none (#71).
2242
+ print(f"{C['red']}writers unknown{C['reset']} — {len(unplaced)} agent process(es) cannot be placed "
2243
+ f"in a tree: their working directory could not be read ({unplaced})")
2244
+ return 1
2245
+ from . import procs
2246
+ table = A._proc_table()
2247
+ rows = []
2248
+ for pid in roots:
2249
+ # From the process table, as `ps -o etime=,args=` printed them; Windows has no ps at all.
2250
+ seconds = procs.elapsed(pid)
2251
+ et, cmd = ("" if seconds is None else _etime(seconds)), _ps_args(procs.argv(pid) or [])
2252
+ rows.append({"pid": pid, "elapsed": et, "headless": A._is_headless(pid),
2253
+ "tty": table.get(pid, (0, 0, "?"))[2], "cmd": cmd.strip()[:90]})
2254
+ if args.clean and dead:
2255
+ # What the sweep could not stop is what it returns, each process asked (WINDOWS-STOP-PROVEN).
2256
+ left = A.sweep_orphans(dead) or []
2257
+ cleaned = [p for p in dead if p not in left]
2258
+ else:
2259
+ cleaned, left = [], dead
2260
+ # Windows has no process groups to tell an ended turn's leftovers by: none set aside there is not none, and the
2261
+ # count may hold them (WINDOWS-SAY-WHY).
2262
+ blind = os.name == "nt"
2263
+ if args.json:
2264
+ told = {"writers": len(roots), "turns": rows, "orphans": None if blind else left, "cleaned": cleaned}
2265
+ if blind:
2266
+ told["orphans_unknown"] = WINDOWS_LIMITS["orphans"]
2267
+ print(json.dumps(told, ensure_ascii=False))
2268
+ return 0 if len(roots) <= 1 else 1
2269
+ if not roots:
2270
+ print(f"{C['green']}0 writers{C['reset']} — no live turn in this tree")
2271
+ else:
2272
+ colour = C['green'] if len(roots) == 1 else C['red']
2273
+ print(f"{colour}{len(roots)} writer(s){C['reset']}")
2274
+ for r in rows:
2275
+ kind = "headless" if r["headless"] else f"interactive tty={r['tty']}"
2276
+ print(f" {r['pid']:>6} {r['elapsed']:>10} {kind:<22} {r['cmd']}")
2277
+ if cleaned:
2278
+ print(f" cleaned {len(cleaned)} orphan(s): {cleaned}")
2279
+ if left and args.clean:
2280
+ print(f" {C['red']}{len(left)} process(es){C['reset']} left by ended turns still run after they were "
2281
+ f"stopped, not counted: {left}; {_stop_by_hand()}")
2282
+ elif left:
2283
+ print(f" {C['yellow']}{len(left)} orphan(s){C['reset']} left by ended turns, not counted: {left}"
2284
+ " (`polyctl writers --clean` stops them)")
2285
+ if blind:
2286
+ print(f" {C['yellow']}orphans not told apart{C['reset']}: {WINDOWS_LIMITS['orphans']}")
2287
+ return 0 if len(roots) <= 1 else 1
2288
+
2289
+
2290
+ def cmd_fanout(cfg, args):
2291
+ """May a fan-out of N sub-agents start now — and what did the last one cost.
2292
+
2293
+ `ok` answers from three facts (hard cap, recent limit hit, provider window);
2294
+ `record` writes what a run cost so the next estimate is empirical; `history`
2295
+ lists the runs. Exit 1 on any refusal, so a coordinator can gate on it.
2296
+ """
2297
+ root = cfg["root"]
2298
+ if args.action == "record":
2299
+ if args.agents is None:
2300
+ print("--agents is required"); return 2
2301
+ rec = A.record_fanout(root, args.agents, args.done, args.errors, args.tokens, args.note)
2302
+ print(f"{C['green']}recorded{C['reset']} {json.dumps(rec, ensure_ascii=False)}")
2303
+ return 0
2304
+ if args.action == "history":
2305
+ rows = A.fanout_history(root, args.limit)
2306
+ if not rows:
2307
+ print("no fan-outs recorded"); return 0
2308
+ for r in rows:
2309
+ when = datetime.fromtimestamp(r["at"]).strftime("%d %b %H:%M")
2310
+ flag = f" {C['red']}limit hit{C['reset']}" if r.get("limit_hit") else ""
2311
+ print(f" {when} {r['agents']:>3} agents done {r.get('done','?'):>3} "
2312
+ f"errors {r.get('errors','?'):>3} tokens {r.get('tokens','?')}{flag}"
2313
+ + (f" — {r['note']}" if r.get('note') else ""))
2314
+ return 0
2315
+ agents = args.agents
2316
+ if args.roots and args.per_root:
2317
+ # A pipeline's fan-out is not known up front: 7 roots that each may
2318
+ # spawn up to 12 branches is a bound of 7 + 7×12. Gate on the bound.
2319
+ agents = args.roots + args.roots * args.per_root
2320
+ print(f"{C['dim']}pipeline bound: {args.roots} roots + {args.roots}×{args.per_root} branches = {agents} agents{C['reset']}")
2321
+ if agents is None:
2322
+ print("--agents N, or --roots R --per-root K for a pipeline, is required"); return 2
2323
+ v = A.fanout_verdict(root, cfg, agents, args.per_agent_tokens, args.provider)
2324
+ if args.json:
2325
+ print(json.dumps(v, ensure_ascii=False))
2326
+ return 0 if v["ok"] else 1
2327
+ colour = C['green'] if v["ok"] else C['red']
2328
+ print(f"{colour}{v['verdict'].upper()}{C['reset']} {v['agents']} agents × ~{v['per_agent_tokens']:,} "
2329
+ f"tokens ({v['per_agent_source']}) ≈ {v['estimated_tokens']:,} tokens")
2330
+ w = v.get("window")
2331
+ if w:
2332
+ # The provider whose window was read, not the argument: without --provider that named None (HARNESS-ACCOUNTS-2).
2333
+ print(f" {v['provider']} window: {w['pct']}% used, {w['window']} window, resets in {w['resets_in']}"
2334
+ + (f"; {v['spent_this_window']:,} tokens fanned out in it so far" if v['spent_this_window'] else ""))
2335
+ for r in v["reasons"]:
2336
+ print(f" {C['yellow'] if not v['ok'] else C['dim']}· {r}{C['reset']}")
2337
+ if v["ok"]:
2338
+ print(f" {C['dim']}after the run: polyctl fanout record --agents {v['agents']} --done D --errors E --tokens T{C['reset']}")
2339
+ return 0 if v["ok"] else 1
2340
+
2341
+
2342
+ def cmd_email(cfg, args):
2343
+ """The red channel: e-mail through a provider - formsubmit.co, or any SMTP server (#74)."""
2344
+ from . import email
2345
+ provider = getattr(args, "provider", None) or "formsubmit"
2346
+ if args.action == "setup" and provider != "formsubmit":
2347
+ password = None
2348
+ if getattr(args, "password_env", None):
2349
+ # Read once from the environment: a password on the command line stays in history.
2350
+ password = os.environ.get(args.password_env)
2351
+ if password is None:
2352
+ print(f"{C['red']}not saved{C['reset']}: ${args.password_env} is not set"); return 2
2353
+ elif args.user:
2354
+ # An account's password is asked at the terminal, not shown: the setup text had a person read it into a
2355
+ # variable first, a line that swallowed the next one pasted with it as the password, and left the
2356
+ # variable set when it was cut short (EMAIL-SETUP-PROMPT).
2357
+ if not sys.stdin.isatty():
2358
+ print(f"{C['red']}not saved{C['reset']}: {args.user}'s password is asked at a terminal, and none is "
2359
+ "attached; --password-env names a variable that holds it")
2360
+ return 2
2361
+ password = _hidden_input(f"password for {args.user} on {args.host} (not shown): ")
2362
+ if password is None:
2363
+ print(f"{C['red']}not saved{C['reset']}: this terminal cannot hide what is typed, and a password "
2364
+ "typed here would stand in its scrollback; --password-env names a variable that holds it")
2365
+ return 2
2366
+ if not password:
2367
+ print(f"{C['red']}not saved{C['reset']}: no password was given"); return 2
2368
+ try:
2369
+ c = email.save_provider(provider, host=args.host, port=args.port, user=args.user,
2370
+ password=password, to=args.to, tls=args.tls,
2371
+ **{"from": args.sender})
2372
+ except ValueError as exc:
2373
+ print(f"{C['red']}not saved{C['reset']}: {exc}"); return 2
2374
+ print(f"{C['green']}saved{C['reset']} {email.CONF} ({_private_mode()}) provider={provider} → {c.get('to')}")
2375
+ print(f"now: {C['b']}polyctl email test{C['reset']}")
2376
+ return 0
2377
+ if args.action == "setup":
2378
+ if args.token:
2379
+ c = email.save(args.token, to=args.to)
2380
+ print(f"{C['green']}saved{C['reset']} {email.CONF} ({_private_mode()}) → "
2381
+ f"{c.get('to') or 'address hidden behind token'}")
2382
+ print(f"now: {C['b']}polyctl email test{C['reset']}")
2383
+ return 0
2384
+ # The channel is the machine's, so its steps are in the machine's language (LANGUAGE-OUTPUT); how its file is
2385
+ # kept private is the platform's (WINDOWS-SAY-WHY).
2386
+ print(language.text(None, "email.setup", conf=email.CONF,
2387
+ kept=language.text(None, "private-file.kept-windows" if os.name == "nt"
2388
+ else "private-file.kept")))
2389
+ return 0
2390
+ c = email.config()
2391
+ if args.action == "status":
2392
+ if not c:
2393
+ print(f"{C['yellow']}not configured{C['reset']} — polyctl email setup"); return 1
2394
+ print(f"{C['green']}configured{C['reset']} provider={c['provider']} to={c.get('to') or '(hidden)'} file={email.CONF}")
2395
+ return 0
2396
+ if args.action == "test":
2397
+ if not c:
2398
+ print(f"{C['red']}not configured{C['reset']} — polyctl email setup"); return 1
2399
+ ok = email.send("test", language.text(cfg, "email.test", root=cfg["root"]), cfg["root"])
2400
+ print(f"{C['green']}sent{C['reset']}" if ok else f"{C['red']}relay refused{C['reset']} — token/activation?")
2401
+ return 0 if ok else 1
2402
+ return 0
2403
+
2404
+
2405
+ def cmd_alarms(cfg, args):
2406
+ """Live alarm episodes and their level; `test` rings every channel."""
2407
+ root = cfg["root"]
2408
+ project = A.project_key(root)
2409
+ if args.action in ("snooze", "unsnooze"):
2410
+ key = getattr(args, "key", None)
2411
+ if not key:
2412
+ print(f"usage: polyctl alarms {args.action} <key>"
2413
+ + (" --until <date or span> --why '…'" if args.action == "snooze" else ""))
2414
+ return 2
2415
+ if args.action == "unsnooze":
2416
+ gone = A.alarm_unsnooze(project, key)
2417
+ print(f"{'unsnoozed' if gone else 'no snooze for'} {key}")
2418
+ return 0
2419
+ try:
2420
+ # A date, or a span counted forward: a snooze of 3d ends three days from now (CLI-ROBUST).
2421
+ until = A.parse_time(getattr(args, "until", None) or "").moment(ahead=True)
2422
+ except ValueError:
2423
+ print("snooze needs --until: a date such as 2026-10-01, or a span from now such as 3d")
2424
+ return 2
2425
+ if until <= time.time():
2426
+ print("--until must be a date in the future")
2427
+ return 2
2428
+ why = (getattr(args, "why", None) or "").strip()
2429
+ if not why:
2430
+ print("snooze needs --why: a snoozed alarm says why nobody can act on it yet")
2431
+ return 2
2432
+ A.alarm_snooze(project, key, until, by=getattr(args, "by", None) or "human", why=why)
2433
+ print(f"snoozed {key} until {time.strftime('%d %b %Y', time.localtime(until))} — "
2434
+ "it stays in polyctl alarms and rings again from that date")
2435
+ return 0
2436
+ if args.action == "test":
2437
+ from .watchdog import notify
2438
+ lvl = args.level or "orange"
2439
+ # Worded in the project's language, keyed and routed the same in any (LANGUAGE-OUTPUT).
2440
+ ok = notify(language.text(cfg, "alarm.test-title", project=project),
2441
+ language.text(cfg, "alarm.test", level=lvl), root,
2442
+ key=f"alarm-test-{int(time.time())}", window=0, audience="human", level=lvl)
2443
+ print(f"{lvl}: desktop+telegram {'sent' if ok else 'suppressed'}"
2444
+ + (" · e-mail attempted (see polyctl notices)" if lvl == "red" else ""))
2445
+ return 0
2446
+ alive = A.active_alarms(project)
2447
+ for full, snooze in sorted(A.load_alarm_snoozes().items()):
2448
+ owner, _, key = full.partition(":")
2449
+ if owner == project and A.alarm_snoozed(project, key):
2450
+ print(f" {C['dim']}snoozed{C['reset']} {key:<32} until "
2451
+ f"{datetime.fromtimestamp(snooze['until']).strftime('%d %b')} "
2452
+ f"{C['dim']}by {snooze.get('by')}: {(snooze.get('why') or '')[:60]}{C['reset']}")
2453
+ if not alive:
2454
+ print(f"{C['green']}no live alarms{C['reset']}"); return 0
2455
+ for e in alive:
2456
+ tone = {"red": C['red'], "orange": C['yellow']}.get(e.get("ring"), C['dim'])
2457
+ since = datetime.fromtimestamp(e["first"]).strftime("%d %b %H:%M")
2458
+ print(f" {tone}{e.get('ring', '?'):<7}{C['reset']} {e['key']:<32} since {since} "
2459
+ f"×{e.get('count', 1)} {C['dim']}{e.get('title', '')[:50]}{C['reset']}"
2460
+ + (f" mailed {datetime.fromtimestamp(e['red_sent']).strftime('%H:%M')}" if e.get('red_sent') else ""))
2461
+ if e.get("evidence"):
2462
+ for line in A.evidence_lines(e["evidence"]):
2463
+ print(f" {C['dim']}{line}{C['reset']}")
2464
+ return 0
2465
+
2466
+
2467
+ def _watchdog_debug(cfg, args):
2468
+ """`polyctl watchdog explain` runs one dry cycle and shows every measurement and
2469
+ verdict; `polyctl watchdog trace` shows the recorded cycles. The question both
2470
+ answer is the one that cost the most this project: why did it not act?"""
2471
+ from types import SimpleNamespace
2472
+ from . import watchdog as W
2473
+ root = cfg["root"]
2474
+ if args.action == "explain":
2475
+ ns = SimpleNamespace(root=root, idle_minutes=S.get(cfg, "watchdog.idle_minutes"), dry_run=True)
2476
+ W.run(ns)
2477
+ print(f"\n{C['b']}{C['mag']}── MEASUREMENTS ──{C['reset']}")
2478
+ for k, v in W._FACTS.items():
2479
+ print(f" {k:<22} {v}")
2480
+ print(f"\n{C['b']}{C['mag']}── DECISIONS (in order) ──{C['reset']}")
2481
+ for i, line in enumerate(W._TRACE, 1):
2482
+ last = i == len(W._TRACE)
2483
+ print(f" {C['b'] if last else ''}{i:>2}. {line}{C['reset']}")
2484
+ return 0
2485
+ rows = W.cycles(root, args.last or 20)
2486
+ if not rows:
2487
+ print("no cycles recorded yet"); return 0
2488
+ for r in rows:
2489
+ when = datetime.fromtimestamp(r["at"]).strftime("%d %b %H:%M:%S")
2490
+ f = r.get("facts", {})
2491
+ print(f" {when} {C['b']}{(r.get('verdict') or '')[:70]:<70}{C['reset']} "
2492
+ f"{C['dim']}idle {f.get('idle_s', '?')}s · writers {f.get('writers', '?')} · inbox {f.get('inbox', '?')} "
2493
+ f"· queued {f.get('queued', '?')}{' · standing request' if f.get('standing_request') else ''}{C['reset']}")
2494
+ return 0
2495
+
2496
+
2497
+ def _print_seen_own(paths):
2498
+ """Say which files polyctl wrote into what a harness reads and recorded as seen, as they stand (HARNESS-SEEN-OWN)."""
2499
+ if paths:
2500
+ print(f" {C['green']}{'seen':<8}{C['reset']} {', '.join(A.shown_text(path) for path in paths)} "
2501
+ f"{C['dim']}polyctl's own text holds no turn; a change made to it later does, until a person sees it"
2502
+ f"{C['reset']}")
2503
+
2504
+
2505
+ def cmd_skill(cfg, args):
2506
+ """The playbook, rendered for the agents this repository uses.
2507
+
2508
+ What it writes as a file of polyctl's own is recorded as seen, so the turns HARNESS-CONFIG holds on harness configuration
2509
+ nobody has seen start on it (HARNESS-SEEN-OWN).
2510
+ """
2511
+ from . import skillkit
2512
+ root = cfg["root"]
2513
+ if args.action == "show":
2514
+ print(skillkit.playbook()[1])
2515
+ return 0
2516
+ _, agents = skillkit.detect_agents(root, args.agent)
2517
+ ours, refused = [], []
2518
+ # Written as init writes it, never through a link: what was not is named, and the command exits 1 (LEADS-ADAPTERS).
2519
+ _print_playbook_files(skillkit.install_playbook(root, agents, ours=ours, unwritten=refused))
2520
+ _print_seen_own(A.record_harness_written(root, ours, "polyctl skill install"))
2521
+ print(f"{C['dim']}agents: {', '.join(sorted(agents))} · regenerate any time; hand edits outside the markers survive{C['reset']}")
2522
+ if refused:
2523
+ print(f"{C['yellow']}{len(refused)} file(s) were not written, each named above with why: make each a file or "
2524
+ f"folder of the project's own, then run polyctl skill install again{C['reset']}")
2525
+ return 1
2526
+ return 0
2527
+
2528
+
2529
+ # ---- first-run onboarding wizard (`polyctl start`, ONBOARD) -------------------------------------
2530
+
2531
+ def _start_detect_adapters():
2532
+ """Installed and absent agent CLIs from the adapters polyctl ships, read the way `polyctl adapters` reads them."""
2533
+ installed, absent = [], []
2534
+ for adapter_id, adapter in sorted(A.package_adapters().items()):
2535
+ if adapter.get("contract", A.ADAPTER_CONTRACT) != A.ADAPTER_CONTRACT:
2536
+ continue
2537
+ binaries = A.adapter_binaries(adapter)
2538
+ present = ([b for b in binaries if A.binary_candidates(b) or _tool_beside_interpreter(b)]
2539
+ if A.tool_review_contract(adapter) is not None
2540
+ else [b for b in binaries if A.binary_candidates(b)])
2541
+ family = A.declared_family(adapter)[0]
2542
+ verified = str(adapter.get("verified") or "untested")
2543
+ eligible_rev, rev_why = A.reviewer_eligibility(adapter)
2544
+ kind = adapter.get("kind")
2545
+ roles_decl = adapter.get("roles") if isinstance(adapter.get("roles"), dict) else {}
2546
+ impl_role = str(roles_decl.get("implementer") or "")
2547
+ can_impl = (bool(present) and kind not in ("cloud", "model-backend", "tool-reviewer")
2548
+ and A.tool_review_contract(adapter) is None
2549
+ and not impl_role.startswith("ineligible")
2550
+ and bool((adapter.get("send") or {}).get("argv") or (adapter.get("resume") or {}).get("argv")))
2551
+ can_rev = bool(present) and eligible_rev and A.tool_review_contract(adapter) is None
2552
+ can_arch = bool(present) and _can_architect(adapter_id, adapter)
2553
+ row = {
2554
+ "id": adapter_id,
2555
+ "name": str(adapter.get("name") or adapter_id),
2556
+ "adapter": adapter,
2557
+ "binaries": binaries,
2558
+ "present": present,
2559
+ "family": family,
2560
+ "verified": verified,
2561
+ "can_implement": can_impl,
2562
+ "can_review": can_rev,
2563
+ "can_architect": can_arch,
2564
+ "review_why": rev_why,
2565
+ }
2566
+ (installed if present else absent).append(row)
2567
+ return installed, absent
2568
+
2569
+
2570
+ def _start_pairs(root, installed):
2571
+ """Cross-family implementer/reviewer pairs accepted by polyctl's independence rule, ranked by measured `verified` level."""
2572
+ from . import tiers as T
2573
+ order = {level: idx for idx, level in enumerate(A.ADAPTER_VERIFIED)}
2574
+ shipped = A._layer_profile_document(os.path.join(A.adapters_dir(), A.PROFILES_FILE))
2575
+ shipped_profiles = shipped.get("profiles") if isinstance(shipped.get("profiles"), dict) else {}
2576
+ shipped_init = str(shipped.get("init") or "")
2577
+ implementers = [row for row in installed if row["can_implement"]]
2578
+ reviewers = [row for row in installed if row["can_review"]]
2579
+ by_id = {row["id"]: row for row in installed}
2580
+ fallback_arch = next(
2581
+ (row["id"] for row in sorted(installed, key=lambda r: (order.get(r["verified"], len(order)), r["id"]))
2582
+ if row.get("can_architect")),
2583
+ None,
2584
+ )
2585
+ pairs = []
2586
+ for impl in implementers:
2587
+ impl_model = _models(impl["id"]).get("default")
2588
+ impl_block = {"adapter": impl["id"], "session": "auto",
2589
+ "name": impl["adapter"].get("actor_name") or impl["id"]}
2590
+ if impl_model:
2591
+ impl_block["model"] = impl_model
2592
+ for rev in reviewers:
2593
+ rev_model = _models(rev["id"]).get("review")
2594
+ rev_block = _reviewer_block(rev["id"], rev_model)
2595
+ probe_cfg = {"root": root, "implementer": impl_block, "reviewer": rev_block}
2596
+ tier, _, code = _review_decision(probe_cfg, rev_block, sessions=set())
2597
+ if tier != T.INDEPENDENT or code is not None:
2598
+ continue
2599
+ iv = order.get(impl["verified"], len(order))
2600
+ rv = order.get(rev["verified"], len(order))
2601
+ both_measured = iv <= 1 and rv <= 1
2602
+ either_measured = iv <= 1 or rv <= 1
2603
+ measured_rank = 0 if both_measured else (1 if either_measured else 2)
2604
+ fam_rank = (0 if (impl["family"] and rev["family"] and impl["family"] != rev["family"])
2605
+ else (1 if (impl["family"] or rev["family"]) else 2))
2606
+ preset_name = f"{impl['id']}-{rev['id']}"
2607
+ shipped_arch = None
2608
+ for name, roles in sorted(shipped_profiles.items()):
2609
+ if isinstance(roles, dict) and roles.get("implementer") == impl["id"] \
2610
+ and roles.get("reviewer") == rev["id"]:
2611
+ preset_name = name
2612
+ shipped_arch = roles.get("architect")
2613
+ break
2614
+ preset_rank = 0 if preset_name == shipped_init else (1 if preset_name in shipped_profiles else 2)
2615
+ if impl["family"] and rev["family"]:
2616
+ fam_why = (f"{impl['id']} ({impl['family']} family) and {rev['id']} ({rev['family']} family) "
2617
+ "are different model families")
2618
+ elif impl["family"] or rev["family"]:
2619
+ declared = f"{impl['id']} ({impl['family']})" if impl["family"] else f"{rev['id']} ({rev['family']})"
2620
+ other = rev["id"] if impl["family"] else impl["id"]
2621
+ fam_why = f"{declared} and {other} run separate harnesses outside the same model family"
2622
+ else:
2623
+ fam_why = f"{impl['id']} and {rev['id']} are separate harnesses ({T.label(tier)})"
2624
+ if both_measured:
2625
+ ver_why = (f"both adapters have measured verified levels "
2626
+ f"(implementer verified={impl['verified']}, reviewer verified={rev['verified']})")
2627
+ else:
2628
+ ver_why = f"implementer verified={impl['verified']}, reviewer verified={rev['verified']}"
2629
+ trust = " ".join(str(x) for x in ((rev["adapter"].get("options") or {}).get("trust_none") or []))
2630
+ why = f"{fam_why}; {ver_why}; {rev['id']} reviews read-only ({trust})"
2631
+ if shipped_arch and by_id.get(shipped_arch, {}).get("can_architect"):
2632
+ arch_id = shipped_arch
2633
+ elif impl.get("can_architect"):
2634
+ arch_id = impl["id"]
2635
+ elif rev.get("can_architect"):
2636
+ arch_id = rev["id"]
2637
+ else:
2638
+ arch_id = fallback_arch
2639
+ roles = {"implementer": impl["id"], "reviewer": rev["id"]}
2640
+ if arch_id:
2641
+ roles["architect"] = arch_id
2642
+ pairs.append({
2643
+ "key": (measured_rank, max(iv, rv), iv + rv, rv, fam_rank, preset_rank, impl["id"], rev["id"]),
2644
+ "implementer": impl,
2645
+ "reviewer": rev,
2646
+ "profile": preset_name,
2647
+ "roles": roles,
2648
+ "why": why,
2649
+ })
2650
+ pairs.sort(key=lambda item: item["key"])
2651
+ return pairs
2652
+
2653
+
2654
+ def _start_init_args(profile_name, roles=None):
2655
+ return argparse.Namespace(
2656
+ name=None,
2657
+ agent="auto",
2658
+ mcp=True,
2659
+ no_mcp=False,
2660
+ rules=False,
2661
+ profile=profile_name,
2662
+ roles=dict(roles) if isinstance(roles, dict) else None,
2663
+ implementer=None,
2664
+ model=None,
2665
+ effort=None,
2666
+ reviewer_model=None,
2667
+ watchdog=False,
2668
+ allow_uncovered_gates=False,
2669
+ prove=False,
2670
+ no_review=False,
2671
+ review_tier=None,
2672
+ by=None,
2673
+ language=None,
2674
+ adopt=False,
2675
+ allow_shared_hooks=False,
2676
+ )
2677
+
2678
+
2679
+ def _start_prompt_choice(pairs, yes):
2680
+ if yes or len(pairs) == 1 or not sys.stdin.isatty():
2681
+ return pairs[0]
2682
+ try:
2683
+ ans = input(f"\nChoose pair [1-{len(pairs)}, default 1]: ").strip()
2684
+ except (EOFError, KeyboardInterrupt):
2685
+ print()
2686
+ return None
2687
+ if not ans:
2688
+ return pairs[0]
2689
+ if ans.isdigit() and 1 <= int(ans) <= len(pairs):
2690
+ return pairs[int(ans) - 1]
2691
+ for pair in pairs:
2692
+ if ans in (pair["profile"], f"{pair['implementer']['id']}-{pair['reviewer']['id']}"):
2693
+ return pair
2694
+ print(f"{C['yellow']}unknown choice {A.shown_text(ans)}; using #1 ({pairs[0]['profile']}){C['reset']}")
2695
+ return pairs[0]
2696
+
2697
+
2698
+ def _start_person_steps(root):
2699
+ """Steps only a person can take; `polyctl start` never records a person's approval itself."""
2700
+ from . import skillkit
2701
+ rule_files = " / ".join(skillkit.rule_file_names(root))
2702
+ lines = [
2703
+ f"{C['b']}polyctl harness seen --ask{C['reset']} — inspect and record your approval of any harness or rule file "
2704
+ "changes in the tree (polyctl never records a person's approval itself)",
2705
+ f"paste the polyctl rule pointer into {rule_files} if you want agents to load the playbook from your rule file, "
2706
+ "then run `polyctl harness seen --ask`",
2707
+ "land the initial .polyctl-project and .polyctl/ setup through the governed loop (`polyctl verify`, `polyctl review`, "
2708
+ "`polyctl commit-ok`, `polyctl commit -m \"…\"`), and open a push window (`polyctl push allow`) before `git push`",
2709
+ "`polyctl watchdog install` if you want the background watchdog and doctor timers on this machine",
2710
+ ]
2711
+ try:
2712
+ unseen = A.unseen_harness_config(root) if os.path.isdir(os.path.join(root, ".polyctl")) else []
2713
+ except Exception:
2714
+ unseen = []
2715
+ if unseen:
2716
+ shown = ", ".join(A.shown_text(path) for path, _, _ in unseen[:5])
2717
+ lines.insert(1, f"unseen harness config now ({len(unseen)}): {shown}")
2718
+ return lines
2719
+
2720
+
2721
+ def cmd_start(cfg, args):
2722
+ """First-run wizard from nothing to a working, governed project (ONBOARD).
2723
+
2724
+ Detects the agent CLIs installed from the adapters polyctl ships and their model families; proposes
2725
+ cross-family implementer/reviewer pairs that polyctl's independence rule accepts (preferring adapters
2726
+ with a measured `verified` level, and saying why each pair is offered); then, asking before each
2727
+ step (or running the steps that need no person when `--yes` is given), runs `polyctl demo`, writes the
2728
+ chosen profile to profiles.json and runs `polyctl init` with that pair, then runs `polyctl hooks install`
2729
+ and `polyctl prove`; and ends by listing the steps only a person can take. It never records a person's
2730
+ approval itself and never installs software.
2731
+ """
2732
+ root = cfg["root"]
2733
+ yes = bool(getattr(args, "yes", False))
2734
+ print(f"{C['b']}polyctl start{C['reset']} {C['dim']}{root}{C['reset']}")
2735
+
2736
+ installed, absent = _start_detect_adapters()
2737
+ print(f"\n{C['b']}1. Detected agent CLIs{C['reset']} (from the adapters polyctl ships):")
2738
+ if installed:
2739
+ for row in installed:
2740
+ fam = row["family"] or "undeclared"
2741
+ bins = ", ".join(row["present"])
2742
+ roles = "/".join(r for r, ok in (("implementer", row["can_implement"]),
2743
+ ("reviewer", row["can_review"]),
2744
+ ("architect", row.get("can_architect"))) if ok) or "observation only"
2745
+ print(f" {C['green']}{row['id']:<14}{C['reset']} binary: {bins:<12} family: {fam:<12} "
2746
+ f"verified: {row['verified']:<10} roles: {roles}")
2747
+ else:
2748
+ print(f" {C['yellow']}none of the agent CLIs polyctl ships adapters for were found on PATH{C['reset']}")
2749
+ if absent:
2750
+ print(f" {C['dim']}not installed ({len(absent)}): "
2751
+ f"{', '.join(r['id'] for r in absent[:8])}"
2752
+ f"{', …' if len(absent) > 8 else ''}{C['reset']}")
2753
+
2754
+ pairs = _start_pairs(root, installed)
2755
+ print(f"\n{C['b']}2. Cross-family implementer / reviewer pairs{C['reset']} "
2756
+ "(accepted by polyctl's independence rule, measured `verified` levels first):")
2757
+ if not pairs:
2758
+ families = sorted({row["family"] or row["id"] for row in installed
2759
+ if row["can_implement"] or row["can_review"]})
2760
+ print(f" {C['red']}no cross-family implementer/reviewer pair is available from the installed CLIs{C['reset']}")
2761
+ if not installed:
2762
+ print(" polyctl never installs software itself. Install two agent CLIs from different model families "
2763
+ "(see `polyctl adapters`), then run `polyctl start` again.")
2764
+ else:
2765
+ print(f" installed eligible CLI(s) cover only {', '.join(families) or 'no eligible role'}; "
2766
+ "polyctl's independence rule requires a reviewer from a different model family than the implementer.")
2767
+ print(" polyctl never installs software and never records a person's opt-in into weaker independence itself.")
2768
+ impl_id = next((row["id"] for row in installed if row["can_implement"]), installed[0]["id"])
2769
+ print(" What only a person can do if you want to proceed with one harness or install another:")
2770
+ print(" · install a second CLI from another model family (`polyctl adapters`), then re-run `polyctl start`")
2771
+ print(f" · or opt into same-family review yourself: "
2772
+ f"polyctl init --implementer {impl_id} --review-tier same-family --by <name>")
2773
+ print(f" · or review each candidate yourself: "
2774
+ f"polyctl init --implementer {impl_id} --review-tier person")
2775
+ print(" · or see the guarantee in a scratch folder with no model CLI: polyctl demo")
2776
+ return 1
2777
+
2778
+ for idx, pair in enumerate(pairs, 1):
2779
+ impl, rev = pair["implementer"], pair["reviewer"]
2780
+ mark = f"{C['green']}*{C['reset']}" if idx == 1 else " "
2781
+ print(f" {mark} [{idx}] {C['b']}{pair['profile']}{C['reset']}: "
2782
+ f"implementer {impl['id']} ({impl['family'] or 'undeclared'}) + "
2783
+ f"reviewer {rev['id']} ({rev['family'] or 'undeclared'})")
2784
+ print(f" why: {pair['why']}")
2785
+
2786
+ chosen = _start_prompt_choice(pairs, yes)
2787
+ if chosen is None:
2788
+ print(f"{C['yellow']}cancelled{C['reset']}")
2789
+ return 1
2790
+ print(f"\n {C['green']}selected{C['reset']} {chosen['profile']} "
2791
+ f"(implementer={chosen['roles']['implementer']}, reviewer={chosen['roles']['reviewer']}, "
2792
+ f"architect={chosen['roles'].get('architect') or 'none'})")
2793
+
2794
+ def ask_step(title, command_text):
2795
+ print(f"\n{C['b']}{title}{C['reset']} — `{command_text}`")
2796
+ if yes:
2797
+ return True
2798
+ if not _confirm(f"Run `{command_text}` now? [y/N] "):
2799
+ print(f" {C['dim']}skipped `{command_text}`{C['reset']}")
2800
+ return False
2801
+ return True
2802
+
2803
+ if ask_step("Step 1/4: polyctl demo", "polyctl demo"):
2804
+ code = cmd_demo(cfg, argparse.Namespace(keep=False))
2805
+ if code:
2806
+ return code
2807
+
2808
+ init_cmd = f"polyctl init --profile {chosen['profile']}"
2809
+ if ask_step("Step 2/4: polyctl init", init_cmd):
2810
+ try:
2811
+ A.write_profile(chosen["profile"], chosen["roles"], default=True, check_only=True)
2812
+ except OSError as exc:
2813
+ print(f"\n {C['red']}start refused{C['reset']}: could not write profile to "
2814
+ f"{A.shown_text(_home_relative(A.user_profiles_path()))} ({exc}); "
2815
+ "make the adapter folder and profiles.json regular files of your own, then run `polyctl start` again")
2816
+ return 1
2817
+ code = cmd_init(cfg, _start_init_args(chosen["profile"], chosen["roles"]))
2818
+ if code:
2819
+ return code
2820
+ try:
2821
+ profile_path = A.write_profile(chosen["profile"], chosen["roles"], default=True)
2822
+ except OSError as exc:
2823
+ print(f"\n {C['red']}start refused{C['reset']}: could not write profile to "
2824
+ f"{A.shown_text(_home_relative(A.user_profiles_path()))} ({exc}); "
2825
+ "make the adapter folder and profiles.json regular files of your own, then run `polyctl start` again")
2826
+ return 1
2827
+ print(f" {C['green']}wrote profile{C['reset']} {chosen['profile']} "
2828
+ f"(implementer={chosen['roles']['implementer']}, reviewer={chosen['roles']['reviewer']}, "
2829
+ f"architect={chosen['roles'].get('architect') or 'none'}) → {_home_relative(profile_path)}")
2830
+
2831
+ if ask_step("Step 3/4: polyctl hooks install", "polyctl hooks install"):
2832
+ if not os.path.lexists(os.path.join(root, ".polyctl", "config.json")):
2833
+ print(f" {C['yellow']}skipped: `polyctl hooks install` needs `.polyctl/config.json` from `polyctl init` first{C['reset']}")
2834
+ else:
2835
+ enrollment = _project_enrollment(root)
2836
+ if enrollment["state"] == "legacy" and os.path.lexists(os.path.join(root, PROJECT_MARKER)):
2837
+ # Stage .polyctl-project so the hook and its execution probe see the project enrolled before the first commit.
2838
+ staged = _git_on_active_index(root, "add", "--", PROJECT_MARKER)
2839
+ if staged:
2840
+ print(f" {C['red']}could not stage {PROJECT_MARKER}{C['reset']}: {staged}")
2841
+ return 1
2842
+ code = cmd_hooks(A.load_config(root), argparse.Namespace(action="install", allow_shared_hooks=False))
2843
+ if code:
2844
+ return code
2845
+
2846
+ if ask_step("Step 4/4: polyctl prove", "polyctl prove"):
2847
+ if not os.path.lexists(os.path.join(root, ".polyctl", "config.json")):
2848
+ print(f" {C['yellow']}skipped: `polyctl prove` needs `.polyctl/config.json` from `polyctl init` first{C['reset']}")
2849
+ else:
2850
+ code = cmd_prove(A.load_config(root), argparse.Namespace(no_review=False))
2851
+ if code:
2852
+ return code
2853
+
2854
+ print(f"\n{C['b']}Steps only a person can take:{C['reset']}")
2855
+ for line in _start_person_steps(root):
2856
+ print(f" · {line}")
2857
+ return 0