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,652 @@
1
+ """What needs doing now, and whose hand does it (NEXT).
2
+
3
+ A part of src/polyctl/lib.py, run in its namespace by `_part` as the parts split out of it are; it is
4
+ not importable on its own.
5
+
6
+ `polyctl board` answers where each item is, `polyctl status` whether an agent is alive, `polyctl gain` what work
7
+ cost. None of them answers the question a person asks on coming back to a project, or the one an
8
+ agent asks when its turn ends: which command, in what order, by whom. With eighty commands, about
9
+ fifty of them needing a project, that question was being answered from memory — which is where a
10
+ landing chain stalls: a candidate verified but never reviewed, a review approved but never granted,
11
+ a stand-in request left in ~/.polyctl unread, a route no person has accepted holding every review that
12
+ would follow it.
13
+
14
+ This is the data layer of that answer: it reads the same files every other surface reads and
15
+ returns items, so `polyctl next`, the `polyctl_next` MCP tool and a later page cannot disagree about what is
16
+ waiting. Two rules hold it together.
17
+
18
+ - every item names its actor. A person's item is returned as the command and run by no one: nothing
19
+ here records, grants or starts anything. `polyctl harness seen`, `polyctl collect-review --by` and
20
+ `polyctl waive --by` stay a person's own hands;
21
+ - nothing here is judged. The pipeline items are the reasons `polyctl commit-ok` would refuse, read
22
+ through the readers it reads — the staged candidate, the newest verification, the review bound to
23
+ that candidate or a person's waiver, the grant — so a candidate this calls ready is one the gate
24
+ agrees with. Where a reader cannot be reached, the item says it cannot be read rather than
25
+ guessing. `polyctl commit-ok` holds further checks of its own (a boundary file's pin, a review's
26
+ integrity); those are the grant's to refuse, and the item after them names the refusal it recorded,
27
+ never a stage of its own. The capability matrix is not one of them: whether a strict project's
28
+ matrix resolves, and whether the grant carries the schema that mode requires, decide whether any
29
+ grant can carry these bytes, so both are read here — and a matrix that does not resolve is blamed
30
+ as the matrix, never as the row it prevented.
31
+ """
32
+
33
+ PERSON = "person"
34
+ WAITING_PERSON = ("human", "person", "owner")
35
+ REQUEST_LIMIT = 5
36
+ PROPOSAL_LIMIT = 3
37
+
38
+ NEXT_ITEM_KEYS = ("who", "kind", "why", "command", "detail", "slice")
39
+
40
+
41
+ def next_item(who, kind, why, command=None, detail=None, slice=None):
42
+ """One thing to do: who does it, what state says so, why, and the command that closes it.
43
+
44
+ Text taken from a ledger - a slice's title, a request's nonce, a gate's name - is shown escaped and on one
45
+ line, so a board an implementer can write cannot start a line of its own or hide a direction mark in what a
46
+ person reads as polyctl's words (LEADS-MCP)."""
47
+ def shown(text):
48
+ return None if text is None else shown_text(" ".join(str(text).split()))
49
+ return {"who": who, "kind": shown(kind), "why": shown(why), "command": shown(command),
50
+ "detail": shown(detail), "slice": shown(slice)}
51
+
52
+
53
+ def reason_of(exc):
54
+ """An exception as one escaped, bounded line: a ledger's own error can be long, and it can hold a
55
+ control character that would start a line of its own in what a person reads as polyctl's words (NEXT)."""
56
+ return shown_text(" ".join(str(part) for part in (type(exc).__name__, exc) if str(part).strip()))[:200]
57
+
58
+
59
+ def next_item_problem(exc, what):
60
+ """A store that cannot be read, as an item that says so: never an empty list, which would read as nothing
61
+ waiting (NEXT)."""
62
+ return next_item(PERSON, f"{what}-unreadable", f"{what} cannot be read: {reason_of(exc)}")
63
+
64
+
65
+ def next_project_key(root):
66
+ """This project's key in ~/.polyctl as `project_key` resolves it, without writing the registry or
67
+ `.polyctl/project-key` when the project has not been registered yet (NEXT)."""
68
+ base = os.path.basename(os.path.abspath(root).rstrip("/\\")) or "root"
69
+ real = os.path.realpath(root)
70
+ if not os.path.isdir(os.path.join(real, ".polyctl")):
71
+ return base
72
+ known = project_registry()
73
+ mine = next((name for name, row in known.items() if row.get("root") == real), None)
74
+ if mine:
75
+ return mine
76
+ held = {name.lower() for name, row in known.items()
77
+ if row.get("root") != real and os.path.isdir(os.path.join(row["root"], ".polyctl"))}
78
+ try:
79
+ with open(os.path.join(real, ".polyctl", PROJECT_KEY_FILE), encoding=UTF8) as fh:
80
+ mark = json.load(fh)
81
+ except (OSError, ValueError):
82
+ mark = {}
83
+ wanted = mark.get("key") if isinstance(mark, dict) and mark.get("root") == real else None
84
+ if _usable_key(wanted) and wanted.lower() not in held:
85
+ return wanted
86
+ if base.lower() not in held:
87
+ return base
88
+ digest = hashlib.sha256(real.encode(UTF8)).hexdigest()
89
+ mine = next((f"{base}-{digest[:length]}" for length in (8, 12, 16, 64)
90
+ if f"{base}-{digest[:length]}".lower() not in held), None)
91
+ suffix = 2
92
+ while mine is None or mine.lower() in held:
93
+ mine = f"{base}-{digest}-{suffix}"
94
+ suffix += 1
95
+ return mine
96
+
97
+
98
+ def next_index_candidate(root):
99
+ """`index_candidate(root)` with any tree objects `git write-tree` makes kept in a scratch directory,
100
+ so reading a newly staged candidate writes nothing to `.git/objects` or `.git/index` (NEXT)."""
101
+ import shutil
102
+ import tempfile
103
+ try:
104
+ objects = os.path.abspath(os.path.join(
105
+ root, _git_output(root, "rev-parse", "--git-path", "objects").decode(UTF8, "surrogateescape").strip()
106
+ ))
107
+ index = os.environ.get("GIT_INDEX_FILE") or os.path.abspath(os.path.join(
108
+ root, _git_output(root, "rev-parse", "--git-path", "index").decode(UTF8, "surrogateescape").strip()
109
+ ))
110
+ except Exception:
111
+ return index_candidate(root)
112
+ prior = {key: os.environ.get(key) for key in (
113
+ "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_INDEX_FILE"
114
+ )}
115
+ with tempfile.TemporaryDirectory(prefix="polyctl-next-git-") as scratch:
116
+ scratch_objects = os.path.join(scratch, "objects")
117
+ os.makedirs(scratch_objects, exist_ok=True)
118
+ alt = [prior["GIT_OBJECT_DIRECTORY"], objects, prior["GIT_ALTERNATE_OBJECT_DIRECTORIES"]]
119
+ os.environ["GIT_OBJECT_DIRECTORY"] = scratch_objects
120
+ os.environ["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = os.pathsep.join(part for part in alt if part)
121
+ if os.path.isfile(index):
122
+ copied = os.path.join(scratch, "index")
123
+ shutil.copyfile(index, copied)
124
+ os.environ["GIT_INDEX_FILE"] = copied
125
+ try:
126
+ return index_candidate(root)
127
+ finally:
128
+ for key, value in prior.items():
129
+ if value is None:
130
+ os.environ.pop(key, None)
131
+ else:
132
+ os.environ[key] = value
133
+
134
+
135
+ def open_review_requests(root):
136
+ """This project's stand-in requests whose answer has not been collected, oldest first, and the count of
137
+ files in that directory polyctl could not read as a request (NEXT).
138
+
139
+ A request is metadata beside its text, outside the tree an agent writes; `polyctl collect-review`
140
+ takes one while its `collected` is empty, so what this returns is exactly what that command would
141
+ still accept. `~/.polyctl/review-requests` keeps no index, so the directory is listed here. A file there
142
+ that names no request - truncated, rewritten, a nonce that does not match its own name - is counted
143
+ and named, because the requests an agent can no longer read are the ones a person must not lose.
144
+ """
145
+ directory = review_requests_dir(root, next_project_key(root))
146
+ try:
147
+ names = sorted(os.listdir(directory))
148
+ except FileNotFoundError:
149
+ return [], 0
150
+ out, unreadable = [], 0
151
+ for name in names:
152
+ if not name.endswith(".json"):
153
+ continue
154
+ nonce = name[:-len(".json")]
155
+ meta = None
156
+ if re.fullmatch(r"[0-9a-f]{32}", nonce):
157
+ try:
158
+ with open(os.path.join(directory, name), encoding=UTF8) as fh:
159
+ data = json.load(fh)
160
+ if isinstance(data, dict) and data.get("nonce") == nonce:
161
+ meta = data
162
+ except (OSError, ValueError):
163
+ meta = None
164
+ if meta is None:
165
+ unreadable += 1
166
+ elif not meta.get("collected"):
167
+ out.append(dict(meta, path=os.path.join(directory, f"{nonce}.md")))
168
+ return sorted(out, key=lambda row: row.get("at") or 0), unreadable
169
+
170
+
171
+ def person_items(cfg):
172
+ """What stands in this project until a person acts, as items (NEXT).
173
+
174
+ Six states polyctl cannot cross on its own, each read from where it is kept: harness configuration no
175
+ person has read, which holds every review, wake, hunt and lane that would start a command; a
176
+ stand-in review request whose answer no person has collected; urgent unacknowledged mail; an open
177
+ rule proposal; a slice blocked waiting on a person; a review switched off in the config no person
178
+ recorded.
179
+ """
180
+ root = cfg["root"]
181
+ out = []
182
+ try:
183
+ key = next_project_key(root)
184
+ unseen = harness_unseen(harness_config_changes(root, key=key), harness_seen_record(root, key=key) or {})
185
+ except Exception as exc:
186
+ out.append(next_item_problem(exc, "what a harness reads from this tree"))
187
+ else:
188
+ if unseen:
189
+ out.append(next_item(PERSON, "harness-unseen",
190
+ f"{harness_config_line(unseen)}: no person has read it, and nothing that starts a "
191
+ "command does until one has",
192
+ "polyctl harness seen --by <your name> --ask",
193
+ detail=harness_config_digest(unseen)))
194
+ staged = None
195
+ try:
196
+ requests, unreadable = open_review_requests(root)
197
+ except Exception as exc:
198
+ requests, unreadable = [], 0
199
+ out.append(next_item_problem(exc, "the review requests"))
200
+ if unreadable:
201
+ out.append(next_item(PERSON, "review-request-unreadable",
202
+ f"{unreadable} request file(s) in ~/.polyctl/review-requests name no request polyctl can read: "
203
+ "one that was cut short or rewritten answers nothing. Its review has to be asked "
204
+ "again, which the chain below names; this says a person's copy may be in there"))
205
+ try:
206
+ staged = next_index_candidate(root)["digest"]
207
+ except Exception:
208
+ staged = None # nothing to bind a request to is no reason to hide what a person must not lose
209
+ # A request binds one candidate's bytes: `polyctl collect-review` refuses an answer while nothing is staged or once
210
+ # they are no longer staged, so nobody can carry it back. A superseded request is not a person's task — but
211
+ # dropping it in silence would hide that a review has to be asked again, so it is named, with no command (NEXT).
212
+ live = [row for row in requests if staged is not None and row.get("candidate") == staged]
213
+ collected = {row.get("nonce") for row in live}
214
+ dead = [row for row in requests if row.get("nonce") not in collected]
215
+ for request in live[:REQUEST_LIMIT]:
216
+ out.append(next_item(PERSON, "review-uncollected",
217
+ f"request {request['nonce']} waits for the answer a person carries back"
218
+ + (f" of {request['slice']}" if request.get("slice") else ""),
219
+ f"polyctl collect-review {request['nonce']} --response <file> --model <model> "
220
+ "--by <your name>",
221
+ slice=request.get("slice"), detail=request.get("path")))
222
+ for request in dead[:REQUEST_LIMIT]:
223
+ out.append(next_item(PERSON, "review-superseded",
224
+ f"request {request['nonce']} binds candidate {request.get('candidate')}, which is no "
225
+ "longer staged: its answer cannot be collected, and no review stands recorded for it",
226
+ slice=request.get("slice"), detail=request.get("path")))
227
+ if len(live) > REQUEST_LIMIT:
228
+ out.append(next_item(PERSON, "review-uncollected-more",
229
+ f"{len(live) - REQUEST_LIMIT} further requests wait to be collected in "
230
+ "~/.polyctl/review-requests, oldest shown first"))
231
+ if len(dead) > REQUEST_LIMIT:
232
+ out.append(next_item(PERSON, "review-superseded-more",
233
+ f"{len(dead) - REQUEST_LIMIT} further superseded requests are kept in "
234
+ "~/.polyctl/review-requests; none of them can be collected"))
235
+ for message in urgent_messages(root, cfg, role=None):
236
+ if message.get("to") == "reviewer":
237
+ continue
238
+ out.append(next_item(PERSON, "mail-urgent",
239
+ f"urgent and unacknowledged: {message['id']} — {message['title']}",
240
+ f"polyctl mail ack {message['id']}"))
241
+ try:
242
+ rows = [row for row in proposals(root) if row.get("state") in ("open", "missing")]
243
+ except Exception as exc:
244
+ rows = []
245
+ out.append(next_item_problem(exc, "the rule proposals"))
246
+ for proposal in rows[:PROPOSAL_LIMIT]:
247
+ question = proposal.get("question")
248
+ missing = proposal.get("state") == "missing" or not question
249
+ out.append(next_item(PERSON, "proposal-open",
250
+ f"rule proposal {proposal.get('id')} "
251
+ + (f"names a question ({question}) that no longer exists"
252
+ if proposal.get("state") == "missing"
253
+ else f"({question}) waits" if question else "waits")
254
+ + " for a person",
255
+ None if missing else f"polyctl answer {question} a|b",
256
+ detail=question))
257
+ for item in board(root)["blocked"]:
258
+ waiting = str((item.get("notes") or {}).get("waiting") or "").strip().lower()
259
+ if waiting in WAITING_PERSON:
260
+ out.append(next_item(PERSON, "slice-waits-human",
261
+ f"{item['id']} is blocked waiting on a person: {item['title']}",
262
+ f"polyctl slice start {item['id']}", slice=item["id"]))
263
+ from . import features as F
264
+ if "review" in F.unrecorded(cfg):
265
+ out.append(next_item(PERSON, "review-off-unrecorded",
266
+ "review is off in .polyctl/config.json with no person's record, so it stays required",
267
+ "polyctl features off review --by <your name>"))
268
+ return out
269
+
270
+
271
+ def verification_isolation_problem(root, record):
272
+ """Why this verification cannot stand as an isolated candidate's, or None (NEXT).
273
+
274
+ The two conditions `polyctl commit-ok` reads, kept here as the data layer's so a lib reader can answer
275
+ without importing the command line: a record that never measured the isolation scope proves nothing,
276
+ and one measured against other inputs verified another candidate's gates. tests/test_next.py holds
277
+ this against the gate's own function, which is the only thing that keeps the two from drifting.
278
+ """
279
+ if "isolation_inputs" not in record:
280
+ return "verification does not record isolation inputs — re-run `polyctl verify`"
281
+ if record["isolation_inputs"] != gate_inputs(root):
282
+ return "verification isolation inputs changed — re-run `polyctl verify`"
283
+ return None
284
+
285
+
286
+ def grant_reuse_problem(cfg, grant, candidate, verification=None):
287
+ """Why this grant cannot carry the staged candidate, or None (NEXT).
288
+
289
+ The bindings a grant has to the bytes it approved, read exactly as the commit hook reads them: the
290
+ schema the mode requires, the candidate, the latest verification it references, and the scope cut
291
+ from it. What the schema carries is the mode's own - a strict project grants through a schema-3 row
292
+ that holds a capability matrix, and a project that has since removed its matrix refuses the row that
293
+ carried one. A matrix that does not resolve is named as the reason no grant can stand, since the
294
+ item would otherwise blame the grant for a declaration the grant never made. A boundary file's pin
295
+ stays `polyctl commit-ok`'s to refuse; this only stops `polyctl next` from calling a grant the hook cannot use
296
+ a reason to commit.
297
+ """
298
+ if grant.get("coordination"):
299
+ if not coordination_candidate(candidate, cfg):
300
+ return f"the grant {grant.get('token')} is a coordination grant, and the staged candidate holds product paths"
301
+ if grant.get("schema") != 2:
302
+ return f"the grant {grant.get('token')} predates index-candidate binding (schema {grant.get('schema')})"
303
+ if grant.get("candidate") != candidate:
304
+ granted = grant.get("candidate")
305
+ tree = granted.get("index_tree") if isinstance(granted, dict) else granted
306
+ return (f"the grant {grant.get('token')} is bound to another candidate: granted {tree}, "
307
+ f"staged {candidate['index_tree']}")
308
+ scope = grant.get("scope")
309
+ if not isinstance(scope, dict) or not isinstance(scope.get("paths"), list):
310
+ return f"the grant {grant.get('token')} carries no candidate scope the hook can read"
311
+ try:
312
+ current = candidate_scope(candidate, scope["paths"])
313
+ except (TypeError, ValueError) as exc:
314
+ return f"the grant {grant.get('token')} has an invalid candidate scope: {reason_of(exc)}"
315
+ if current["outside_paths"]:
316
+ return (f"staged paths fall outside the granted scope of {grant.get('token')}: "
317
+ f"{', '.join(current['outside_paths'][:5])}")
318
+ if current != scope:
319
+ return f"the grant {grant.get('token')}'s scope no longer matches the staged candidate"
320
+ unseen = unseen_harness_config(cfg["root"])
321
+ if unseen:
322
+ return (f"the grant {grant.get('token')} cannot carry unseen harness configuration "
323
+ f"({harness_config_line(unseen)}): run `polyctl harness seen --ask` first")
324
+ return None
325
+ from . import matrix as M
326
+ strict = M.is_strict(cfg)
327
+ if strict:
328
+ try:
329
+ M.resolve(cfg)
330
+ except M.MatrixError as exc:
331
+ return (f"this project's capability matrix does not resolve, so no grant can stand on it: "
332
+ f"{'; '.join(exc.problems[:3])}"
333
+ + (f" ({len(exc.problems)} problems in all)" if len(exc.problems) > 3 else ""))
334
+ except Exception as exc:
335
+ return f"this project's capability matrix cannot be read: {reason_of(exc)}"
336
+ if grant.get("schema") != 3:
337
+ return (f"the grant {grant.get('token')} is not a capability-matrix grant: this project runs strict, "
338
+ "so `polyctl commit-ok` must record one")
339
+ if not strict and (grant.get("schema") == 3 or grant.get("matrix") is not None):
340
+ return (f"the grant {grant.get('token')} was made under a capability matrix this project no longer "
341
+ "declares: `polyctl commit-ok` must record a new one")
342
+ if not strict and grant.get("schema") != 2:
343
+ return f"the grant {grant.get('token')} predates index-candidate binding (schema {grant.get('schema')})"
344
+ if grant.get("candidate") != candidate:
345
+ granted = grant.get("candidate")
346
+ tree = granted.get("index_tree") if isinstance(granted, dict) else granted
347
+ return (f"the grant {grant.get('token')} is bound to another candidate: granted {tree}, "
348
+ f"staged {candidate['index_tree']}")
349
+ if verification is None:
350
+ try:
351
+ verification = latest_verification(cfg["root"])
352
+ except Exception:
353
+ verification = None
354
+ if verification is not None and verification.get("id") != grant.get("verification"):
355
+ return (f"latest verification {verification.get('id') or '<unnamed>'} is not "
356
+ f"the grant's referenced verification {grant.get('verification') or '<missing>'}")
357
+ scope = grant.get("scope")
358
+ if not isinstance(scope, dict) or not isinstance(scope.get("paths"), list):
359
+ return f"the grant {grant.get('token')} carries no candidate scope the hook can read"
360
+ try:
361
+ current = candidate_scope(candidate, scope["paths"])
362
+ except (TypeError, ValueError) as exc:
363
+ return f"the grant {grant.get('token')} has an invalid candidate scope: {reason_of(exc)}"
364
+ if current["outside_paths"]:
365
+ return (f"staged paths fall outside the granted scope of {grant.get('token')}: "
366
+ f"{', '.join(current['outside_paths'][:5])}")
367
+ if current != scope:
368
+ return f"the grant {grant.get('token')}'s scope no longer matches the staged candidate"
369
+ return None
370
+
371
+
372
+ def pipeline_items(cfg):
373
+ """The staged candidate's landing chain, at the first stage that does not hold (NEXT).
374
+
375
+ The five stages are `polyctl commit-ok`'s own, read with its readers. It stops at the first one that
376
+ does not hold: an agent has one thing to do, and listing the three behind it invites it to skip
377
+ ahead.
378
+ """
379
+ root = cfg["root"]
380
+ try:
381
+ candidate = next_index_candidate(root)
382
+ except Exception as exc:
383
+ return [next_item("implementer", "candidate-unreadable",
384
+ f"the staged candidate cannot be measured: {reason_of(exc)}", "polyctl candidate")]
385
+ running = [item["id"] for item in board(root)["running"]]
386
+ slice_id = running[0] if len(running) == 1 else None
387
+ if not candidate["changed_paths"]:
388
+ ready = board_graph(root)["ready"]
389
+ return [next_item("implementer", "no-candidate",
390
+ "nothing is staged: an agent commits only the candidate it staged in the index",
391
+ f"polyctl slice start {ready[0]['id']}" if ready else "polyctl board ready",
392
+ slice=ready[0]["id"] if ready else None)]
393
+ if coordination_candidate(candidate, cfg):
394
+ unseen = unseen_harness_config(root)
395
+ if unseen:
396
+ return [next_item(PERSON, "coordination-commit",
397
+ f"{len(candidate['changed_paths'])} coordination path(s) staged with unseen "
398
+ f"{harness_config_line(unseen)}: a person sees harness configuration before it "
399
+ "rides a coordination grant",
400
+ "polyctl harness seen --by <your name> --ask", slice=slice_id)]
401
+ try:
402
+ grant = latest_authority_decision(root)
403
+ except Exception as exc:
404
+ return [next_item(PERSON, "authority-unreadable",
405
+ f"the authority ledger cannot be read: {reason_of(exc)}",
406
+ "polyctl commit-ok --by <your name> --ask", slice=slice_id)]
407
+ if not isinstance(grant, dict) or grant.get("granted") is not True or not grant.get("coordination"):
408
+ return [next_item(PERSON, "coordination-commit",
409
+ f"{len(candidate['changed_paths'])} coordination path(s) staged: "
410
+ "a coordination commit is a person's act",
411
+ "polyctl commit-ok --by <your name> --ask", slice=slice_id)]
412
+ problem = grant_reuse_problem(cfg, grant, candidate)
413
+ if problem:
414
+ return [next_item(PERSON, "grant-stale", problem,
415
+ "polyctl commit-ok --by <your name> --ask", slice=slice_id)]
416
+ held = hold_state(root)
417
+ if held:
418
+ return [next_item(PERSON, "project-held",
419
+ f"this project is held by {held.get('by')}: {held.get('reason', '')}",
420
+ "polyctl hold status")]
421
+ return [next_item("implementer", "granted",
422
+ f"{len(candidate['changed_paths'])} path(s) stand granted on {grant.get('token')}: commit, "
423
+ "and the hook takes this grant", 'polyctl commit -m "<message>"', slice=slice_id)]
424
+
425
+ from . import features as F
426
+ try:
427
+ ver = latest_verification(root)
428
+ except Exception as exc:
429
+ return [next_item("implementer", "verification-unreadable",
430
+ f"the verification ledger cannot be read: {reason_of(exc)}",
431
+ "polyctl verify", slice=slice_id)]
432
+ if not ver:
433
+ return [next_item("implementer", "no-verification", "no gate has run on this candidate",
434
+ "polyctl verify", slice=slice_id)]
435
+ measured = ver.get("candidate") or {}
436
+ if measured.get("digest") != candidate["digest"]:
437
+ return [next_item("implementer", "verification-stale",
438
+ f"the index changed since {ver.get('id')} verified it: verified "
439
+ f"{measured.get('index_tree')}, staged {candidate['index_tree']}",
440
+ "polyctl verify", slice=slice_id)]
441
+ if not ver.get("candidate_ready"):
442
+ detail = "; ".join(ver.get("candidate_issues") or [])
443
+ return [next_item("implementer", "verification-unisolated",
444
+ f"{ver.get('id')} did not verify an isolated staged candidate"
445
+ + (f": {detail}" if detail else ""), "polyctl verify", slice=slice_id)]
446
+ isolation = verification_isolation_problem(root, ver)
447
+ if isolation:
448
+ return [next_item("implementer", "verification-unisolated", isolation, "polyctl verify", slice=slice_id)]
449
+ try:
450
+ gates_now = gate_definitions_digest(root, ver.get("profile"))
451
+ except Exception as exc:
452
+ return [next_item("implementer", "gates-unreadable",
453
+ f"the gate definitions cannot be read: {reason_of(exc)}",
454
+ "polyctl verify", slice=slice_id)]
455
+ if gates_now != ver.get("gates_digest"):
456
+ return [next_item("implementer", "gates-changed",
457
+ f"the gate definitions changed since {ver.get('id')} ran with them",
458
+ "polyctl verify", slice=slice_id)]
459
+ if not ver.get("passed"):
460
+ waivable_failed, _ = verification_waivable_gates(root, ver)
461
+ gates_waiver = None
462
+ if waivable_failed:
463
+ try:
464
+ gates_waiver, _ = gates_waiver_for(root, running, candidate["digest"], failed_gates=waivable_failed)
465
+ except Exception as exc:
466
+ return [next_item("implementer", "waiver-unreadable",
467
+ f"the waiver ledger cannot be read: {reason_of(exc)}",
468
+ "polyctl verify", slice=slice_id)]
469
+ if not gates_waiver:
470
+ failed = [g["name"] for g in (ver.get("gates") or []) if not g.get("passed")]
471
+ return [next_item("implementer", "gates-failed",
472
+ f"the last verification failed: {', '.join(failed) or ver.get('id')}",
473
+ "polyctl verify", slice=slice_id)]
474
+
475
+ if F.enabled(cfg, "review"):
476
+ try:
477
+ waiver, _notes = review_waiver_for(root, running, candidate["digest"])
478
+ except Exception as exc:
479
+ return [next_item("implementer", "waiver-unreadable",
480
+ f"the waiver ledger cannot be read: {reason_of(exc)}", "polyctl review", slice=slice_id)]
481
+ if not waiver:
482
+ try:
483
+ decision = candidate_review_decision(root, cfg["reviews"], candidate["digest"])
484
+ except Exception as exc:
485
+ decision = {"match": None,
486
+ "problem": f"the review ledger cannot be read: {reason_of(exc)}"}
487
+ if not decision.get("match"):
488
+ return [next_item("implementer", "no-review",
489
+ decision.get("problem")
490
+ or "no APPROVED review is bound to these bytes: a review of another candidate "
491
+ "grants nothing", "polyctl review", slice=slice_id)]
492
+
493
+ try:
494
+ grant = latest_authority_decision(root)
495
+ except Exception as exc:
496
+ return [next_item("implementer", "authority-unreadable",
497
+ f"the authority ledger cannot be read: {reason_of(exc)}", "polyctl commit-ok", slice=slice_id)]
498
+ if not isinstance(grant, dict) or grant.get("granted") is not True:
499
+ why = ("no grant for these bytes: a candidate lands only on a grant" if not isinstance(grant, dict)
500
+ else f"the last authority decision refused: "
501
+ f"{'; '.join(grant.get('reasons') or []) or grant.get('token')}")
502
+ return [next_item("implementer", "no-grant", why, "polyctl commit-ok", slice=slice_id)]
503
+ problem = grant_reuse_problem(cfg, grant, candidate, ver)
504
+ if problem:
505
+ return [next_item("implementer", "grant-stale", problem, "polyctl commit-ok", slice=slice_id)]
506
+ held = hold_state(root)
507
+ if held:
508
+ return [next_item(PERSON, "project-held",
509
+ f"this project is held by {held.get('by')}: {held.get('reason', '')}", "polyctl hold status")]
510
+ urgent = [m for m in urgent_messages(root, cfg, role="implementer")
511
+ if m.get("to") in (None, "implementer")]
512
+ if urgent:
513
+ message = urgent[0]
514
+ return [next_item("implementer", "mail-urgent",
515
+ f"urgent message unacknowledged: {message['id']} — {message['title']}",
516
+ f"polyctl mail ack {message['id']}", slice=slice_id)]
517
+ return [next_item("implementer", "granted",
518
+ f"{len(candidate['changed_paths'])} path(s) stand granted on {grant.get('token')}: commit, "
519
+ "and the hook takes this grant", 'polyctl commit -m "<message>"', slice=slice_id)]
520
+
521
+
522
+ def next_items(cfg):
523
+ """Everything standing in this project: a person's first, then the implementer's chain (NEXT).
524
+
525
+ The order is the point. A person's item holds work an agent can see and cannot cross, and it goes
526
+ unnoticed precisely because everything else looks fine.
527
+ """
528
+ return person_items(cfg) + pipeline_items(cfg)
529
+
530
+
531
+ PIPELINE_COLUMNS = ("waiting", "verified", "in review", "with a person", "landed")
532
+ _WAITING_STAGES = frozenset({
533
+ "candidate-unreadable", "no-candidate", "verification-unreadable", "no-verification",
534
+ "gates-failed", "verification-stale", "verification-unisolated", "gates-unreadable", "gates-changed",
535
+ })
536
+ _VERIFIED_STAGES = frozenset({
537
+ "waiver-unreadable", "no-review", "authority-unreadable", "no-grant", "grant-stale", "mail-urgent", "granted",
538
+ })
539
+
540
+
541
+ def _submitted_review_slices(root):
542
+ """Slices with an uncollected submitted review in `.polyctl/reviews` (WEB-API)."""
543
+ directory = os.path.join(root, ".polyctl", "reviews")
544
+ try:
545
+ names = sorted(os.listdir(directory))
546
+ except OSError:
547
+ return set()
548
+ out = set()
549
+ for name in names:
550
+ if not (name.startswith("R-") and name.endswith(".json")):
551
+ continue
552
+ try:
553
+ with open(os.path.join(directory, name), encoding=UTF8) as fh:
554
+ state = json.load(fh)
555
+ except (OSError, ValueError):
556
+ continue
557
+ if not isinstance(state, dict) or state.get("collected_at") or state.get("collected"):
558
+ continue
559
+ slice_id = (state.get("slice") or "").strip()
560
+ if slice_id and state.get("state") in ("running", "finished", "unavailable", "failed", "stale"):
561
+ out.add(slice_id)
562
+ return out
563
+
564
+
565
+ def pipeline_facts(cfg):
566
+ """The project's pipeline for `/pipeline` and `/api/pipeline`, read from `polyctl next`'s readers (WEB-API).
567
+
568
+ Each slice on the board is placed into one of the five pipeline columns (`waiting`, `verified`,
569
+ `in review`, `with a person`, `landed`), alongside the standing `person` and `implementer` items
570
+ from `person_items` and `pipeline_items`. A person's step is carried as command text only; nothing
571
+ here runs or records anything.
572
+ """
573
+ root = cfg["root"]
574
+ bd = board(root)
575
+ person = person_items(cfg)
576
+ implementer = pipeline_items(cfg)
577
+ in_review = _submitted_review_slices(root)
578
+ running_ids = [item["id"] for item in bd["running"]]
579
+ single_running = running_ids[0] if len(running_ids) == 1 else None
580
+
581
+ person_by_slice = {}
582
+ for item in person:
583
+ sid = item.get("slice")
584
+ if sid:
585
+ person_by_slice.setdefault(sid, []).append(item)
586
+
587
+ impl_by_slice = {}
588
+ for item in implementer:
589
+ sid = item.get("slice") or single_running
590
+ if sid:
591
+ impl_by_slice.setdefault(sid, []).append(item)
592
+
593
+ columns = {col: [] for col in PIPELINE_COLUMNS}
594
+ slices = []
595
+ for state in ("running", "blocked", "queued", "inbox", "verified", "done"):
596
+ for item in bd.get(state, ()):
597
+ sid = item["id"]
598
+ notes = item.get("notes") or {}
599
+ p_items = person_by_slice.get(sid, ())
600
+ i_items = impl_by_slice.get(sid, ()) if state == "running" else ()
601
+ waiting_note = str(notes.get("waiting") or "").strip().lower()
602
+ held_person = [it for it in i_items if it.get("who") == PERSON]
603
+ if state == "done":
604
+ column, stage = "landed", "done"
605
+ elif p_items or held_person or waiting_note in WAITING_PERSON:
606
+ column = "with a person"
607
+ stage = (p_items[0]["kind"] if p_items
608
+ else held_person[0]["kind"] if held_person
609
+ else "slice-waits-human")
610
+ elif sid in in_review:
611
+ column, stage = "in review", "review-submitted"
612
+ elif state == "verified" or any(it.get("kind") in _VERIFIED_STAGES for it in i_items):
613
+ column = "verified"
614
+ stage = i_items[0]["kind"] if i_items else "verified"
615
+ else:
616
+ column = "waiting"
617
+ stage = i_items[0]["kind"] if i_items and i_items[0].get("kind") in _WAITING_STAGES else state
618
+
619
+ active = p_items[0] if p_items else held_person[0] if held_person else (i_items[0] if i_items else None)
620
+ if active is not None:
621
+ why, command = active.get("why"), active.get("command")
622
+ elif state == "blocked":
623
+ raw_why = notes.get("needs") or notes.get("waiting") or None
624
+ why = shown_text(" ".join(str(raw_why).split())) if raw_why else None
625
+ command = f"polyctl slice start {shown_text(sid)}" if waiting_note in WAITING_PERSON else None
626
+ elif state in ("queued", "inbox") and notes.get("needs"):
627
+ why = shown_text(f"needs: {' '.join(str(notes['needs']).split())}")
628
+ command = None
629
+ else:
630
+ why, command = None, None
631
+
632
+ entry = {
633
+ "id": shown_text(sid),
634
+ "title": shown_text(" ".join(str(item.get("title") or "").split())),
635
+ "state": state,
636
+ "column": column,
637
+ "stage": stage,
638
+ "why": why,
639
+ "command": command,
640
+ }
641
+ columns[column].append(entry)
642
+ slices.append(entry)
643
+
644
+ return {
645
+ "project": cfg.get("project") or os.path.basename(root),
646
+ "root": root,
647
+ "at": int(time.time()),
648
+ "columns": columns,
649
+ "slices": slices,
650
+ "person": person,
651
+ "implementer": implementer,
652
+ }