polyctl 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. polyctl/__init__.py +7 -0
  2. polyctl/__main__.py +5 -0
  3. polyctl/a2a.py +226 -0
  4. polyctl/a2a_mcp.py +546 -0
  5. polyctl/acp.py +417 -0
  6. polyctl/adapters/README.md +101 -0
  7. polyctl/adapters/aider.json +32 -0
  8. polyctl/adapters/amazon-q.json +15 -0
  9. polyctl/adapters/amp.json +16 -0
  10. polyctl/adapters/antigravity.json +120 -0
  11. polyctl/adapters/claude-code.json +229 -0
  12. polyctl/adapters/cloud-generic.json +57 -0
  13. polyctl/adapters/codex.json +47 -0
  14. polyctl/adapters/command-code.json +45 -0
  15. polyctl/adapters/copilot.json +17 -0
  16. polyctl/adapters/cursor-agent.json +29 -0
  17. polyctl/adapters/deepseek.json +13 -0
  18. polyctl/adapters/droid.json +34 -0
  19. polyctl/adapters/gemini.json +30 -0
  20. polyctl/adapters/grok.json +22 -0
  21. polyctl/adapters/hermes.json +34 -0
  22. polyctl/adapters/kilocode.json +30 -0
  23. polyctl/adapters/kimi.json +23 -0
  24. polyctl/adapters/kiro.json +332 -0
  25. polyctl/adapters/ollama.json +29 -0
  26. polyctl/adapters/omp.json +34 -0
  27. polyctl/adapters/openai-api.json +68 -0
  28. polyctl/adapters/opencode.json +162 -0
  29. polyctl/adapters/pi.json +24 -0
  30. polyctl/adapters/pr-agent.json +54 -0
  31. polyctl/adapters/profiles.json +9 -0
  32. polyctl/adapters/qoder.json +163 -0
  33. polyctl/adapters/qwen.json +27 -0
  34. polyctl/adapters/reasonix.json +25 -0
  35. polyctl/adapters/rewriters/rtk.json +24 -0
  36. polyctl/adapters/trae.json +31 -0
  37. polyctl/adapters/vendors.json +42 -0
  38. polyctl/adapters/warp.json +88 -0
  39. polyctl/allowlist.py +1756 -0
  40. polyctl/api_review.py +920 -0
  41. polyctl/cli.py +835 -0
  42. polyctl/conformance_harness.py +9 -0
  43. polyctl/demo.py +503 -0
  44. polyctl/drivers.py +146 -0
  45. polyctl/email.py +160 -0
  46. polyctl/features.py +98 -0
  47. polyctl/journal.py +144 -0
  48. polyctl/language.py +945 -0
  49. polyctl/lib.py +1296 -0
  50. polyctl/matrix.py +660 -0
  51. polyctl/mcp.py +1362 -0
  52. polyctl/ntfy.py +169 -0
  53. polyctl/outbound.py +39 -0
  54. polyctl/parts/__init__.py +5 -0
  55. polyctl/parts/cli_authority.py +2615 -0
  56. polyctl/parts/cli_channels.py +1325 -0
  57. polyctl/parts/cli_checks.py +2293 -0
  58. polyctl/parts/cli_completion.py +686 -0
  59. polyctl/parts/cli_evidence.py +141 -0
  60. polyctl/parts/cli_gain.py +375 -0
  61. polyctl/parts/cli_harness.py +392 -0
  62. polyctl/parts/cli_hooks.py +1816 -0
  63. polyctl/parts/cli_install.py +638 -0
  64. polyctl/parts/cli_lanes.py +106 -0
  65. polyctl/parts/cli_maintenance.py +2536 -0
  66. polyctl/parts/cli_next.py +248 -0
  67. polyctl/parts/cli_pr.py +53 -0
  68. polyctl/parts/cli_project.py +2857 -0
  69. polyctl/parts/cli_review.py +5158 -0
  70. polyctl/parts/cli_status.py +898 -0
  71. polyctl/parts/lib_adapters.py +2933 -0
  72. polyctl/parts/lib_alarms.py +2106 -0
  73. polyctl/parts/lib_events.py +224 -0
  74. polyctl/parts/lib_evidence.py +412 -0
  75. polyctl/parts/lib_gates.py +2099 -0
  76. polyctl/parts/lib_lanes.py +829 -0
  77. polyctl/parts/lib_mail.py +1541 -0
  78. polyctl/parts/lib_next.py +652 -0
  79. polyctl/parts/lib_pr.py +331 -0
  80. polyctl/parts/lib_slices.py +3337 -0
  81. polyctl/parts/lib_state.py +2415 -0
  82. polyctl/parts/lib_transcript.py +4118 -0
  83. polyctl/pressure.py +325 -0
  84. polyctl/prices.json +47 -0
  85. polyctl/procs.py +1194 -0
  86. polyctl/settings.py +505 -0
  87. polyctl/skill/SKILL.md +365 -0
  88. polyctl/skillkit.py +503 -0
  89. polyctl/storage.py +2055 -0
  90. polyctl/telegram.py +327 -0
  91. polyctl/tiers.py +123 -0
  92. polyctl/verdicts.py +41 -0
  93. polyctl/watchdog.py +3887 -0
  94. polyctl/web.py +337 -0
  95. polyctl-0.7.0.dist-info/METADATA +235 -0
  96. polyctl-0.7.0.dist-info/RECORD +99 -0
  97. polyctl-0.7.0.dist-info/WHEEL +4 -0
  98. polyctl-0.7.0.dist-info/entry_points.txt +5 -0
  99. polyctl-0.7.0.dist-info/licenses/LICENSE +21 -0
polyctl/telegram.py ADDED
@@ -0,0 +1,327 @@
1
+ #!/usr/bin/env python3
2
+ """polyctl telegram — a second keyboard for the mailbox, and a phone that says what happened.
3
+
4
+ Two directions, and the inbound one is the point. When the architect's quota runs
5
+ out everything stops, twice in one day here; if a human can write a decision from
6
+ a phone at that moment, it does not stop. The architect role is already file-driven
7
+ — a decision is a file in `agent-mail/` — so this adds no new source of truth. It
8
+ is a keyboard for the mailbox, exactly as the MCP tools are.
9
+
10
+ Outbound carries what a human can act on *and* what is being done about the rest,
11
+ because "an anomaly was detected" without "and the architect is handling it" is the
12
+ half that makes someone check manually.
13
+
14
+ Everything a human sends is treated as urgent. A person who reaches for their
15
+ phone to type a decision has already decided it matters, and second-guessing that
16
+ with a marker they must remember is how a channel gets ignored.
17
+
18
+ Standard library only. Long polling — a webhook needs a public endpoint, and
19
+ nothing else here does.
20
+ """
21
+ import json
22
+ import os
23
+ import sys
24
+ import re
25
+ import time
26
+ import urllib.error
27
+ import urllib.parse
28
+ import urllib.request
29
+
30
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
31
+ from polyctl import language, lib as A # noqa: E402
32
+ UTF8 = "utf-8" # every text file polyctl writes or reads; Windows would otherwise use cp1252
33
+
34
+ CONF = os.path.join(A.HOME, ".polyctl", "telegram.json")
35
+ API = "https://api.telegram.org/bot{token}/{method}"
36
+
37
+
38
+ def config():
39
+ """Token and allowed chats. A file with 0600, never the repository.
40
+
41
+ A bot token is a credential that can instruct the implementer, so it lives
42
+ where credentials live and not where code lives. The allowlist is not
43
+ optional: an inbound channel without one is an authority surface open to
44
+ whoever finds the bot.
45
+ """
46
+ if not os.path.exists(CONF):
47
+ return None
48
+ try:
49
+ c = json.load(open(CONF, encoding=UTF8))
50
+ except Exception:
51
+ return None
52
+ if not c.get("token") or not c.get("chats"):
53
+ return None
54
+ c["chats"] = [str(x) for x in c["chats"]]
55
+ return c
56
+
57
+
58
+ # A bot token as @BotFather gives one: the bot's number, a colon, and letters, digits, `-` and `_`. Anything else is
59
+ # refused before it is put into a request's URL, where an error could quote it back (LEADS-SECRETS).
60
+ TOKEN_SHAPE = re.compile(r"\d+:[A-Za-z0-9_-]+")
61
+ # A chat as Telegram numbers it, which is what the poller compares a message's chat with; a group's is negative.
62
+ CHAT_SHAPE = re.compile(r"-?\d+")
63
+
64
+
65
+ def save(token, chats):
66
+ """Write the bot token and the chats it allows to CONF, readable by the person alone from the moment it exists.
67
+
68
+ The setup had a person echo the file into place and chmod it afterwards: anyone on the machine could read the
69
+ token between the two, and the shell's history kept the line that held it. polyctl asks for the token now and
70
+ writes the file itself, as ~/.polyctl/email.json is written: 0600 from its creation, in place of the old one whole
71
+ (HUNT-LEADS-SEC, LEADS-SECRETS).
72
+
73
+ A token of another bot drops the poller's place in the messages, ~/.polyctl/telegram-offset, which counts the old
74
+ bot's updates: kept, it asked the new bot for its updates from that number on, and Telegram takes every update
75
+ below the number asked from as read, so the messages a person sent the new bot, numbered lower, were dropped
76
+ unread. The same token keeps its place, or what was read since its last confirmation is read again (SECRETS-2).
77
+ """
78
+ from polyctl.storage import replace_file_durably
79
+ try:
80
+ with open(CONF, encoding=UTF8) as fh:
81
+ saved = json.load(fh)
82
+ except (OSError, ValueError):
83
+ saved = None
84
+ data = (json.dumps({"token": token, "chats": [str(chat) for chat in chats]}, indent=1) + "\n").encode(UTF8)
85
+ replace_file_durably(CONF, data, mode=0o600)
86
+ if not isinstance(saved, dict) or saved.get("token") != token:
87
+ try:
88
+ os.remove(_offset_path())
89
+ except FileNotFoundError:
90
+ pass
91
+ return config()
92
+
93
+
94
+ def _chat_name(chat):
95
+ """What Telegram calls a chat, as a terminal can show it: a group's title, or a person's names and username.
96
+
97
+ The names are whatever the chat's owner chose, a stranger's among them, so a character a terminal would act
98
+ on is left out (LEADS-SECRETS).
99
+ """
100
+ name = " ".join(str(chat[key]) for key in ("title", "first_name", "last_name") if chat.get(key))
101
+ if chat.get("username"):
102
+ name += f" (@{chat['username']})"
103
+ return "".join(ch for ch in name if ch.isprintable())[:60] or str(chat.get("type") or "?")
104
+
105
+
106
+ def recent_chats(token):
107
+ """({chat id: its name}, None) for the chats that wrote to the bot, or (None, what Telegram answered instead).
108
+
109
+ Asked in this process with the token the setup was given: it had a person put the token into a curl or
110
+ PowerShell command line to find their chat id, and the shell's history and the process list kept it
111
+ (LEADS-SECRETS). Without an offset getUpdates confirms nothing, so the poller still reads these messages;
112
+ Telegram keeps an update it was not asked to confirm for 24 hours.
113
+ """
114
+ answer = api({"token": token}, "getUpdates", timeout=0)
115
+ if not answer.get("ok"):
116
+ why = str(answer.get("description") or answer.get("error") or "getUpdates failed")
117
+ return None, why.replace(token, "<token>")
118
+ found = {}
119
+ for update in answer.get("result") or []:
120
+ for kind in ("message", "edited_message", "channel_post", "my_chat_member"):
121
+ chat = (update.get(kind) or {}).get("chat") or {}
122
+ if chat.get("id") is not None:
123
+ found[str(chat["id"])] = _chat_name(chat)
124
+ return found, None
125
+
126
+
127
+ def api(cfg, method, **params):
128
+ url = API.format(token=cfg["token"], method=method)
129
+ data = urllib.parse.urlencode(
130
+ {k: (json.dumps(v) if isinstance(v, (dict, list)) else v)
131
+ for k, v in params.items() if v is not None}).encode()
132
+ try:
133
+ with urllib.request.urlopen(urllib.request.Request(url, data=data),
134
+ timeout=(params.get("timeout") or 10) + 15) as r:
135
+ return json.loads(r.read().decode())
136
+ except urllib.error.HTTPError as e:
137
+ return {"ok": False, "error": f"HTTP {e.code}", "body": e.read()[:200].decode(errors="replace")}
138
+ except Exception as e:
139
+ return {"ok": False, "error": str(e)[:200]}
140
+
141
+
142
+ def send(text, root=None, keyboard=None):
143
+ """Send to every allowed chat. Returns how many got it."""
144
+ cfg = config()
145
+ if not cfg:
146
+ return 0
147
+ n = 0
148
+ for chat in cfg["chats"]:
149
+ r = api(cfg, "sendMessage", chat_id=chat, text=text[:4000],
150
+ parse_mode="Markdown", disable_web_page_preview="true",
151
+ reply_markup={"inline_keyboard": keyboard} if keyboard else None)
152
+ if r.get("ok"):
153
+ n += 1
154
+ elif root:
155
+ A.record_notice(root, "telegram send failed", str(r)[:200], sent=False,
156
+ key="telegram-error")
157
+ return n
158
+
159
+
160
+ def _offset_path():
161
+ return os.path.join(A.HOME, ".polyctl", "telegram-offset")
162
+
163
+
164
+ def poll(root, cfg_project, seconds=25):
165
+ """Fetch new messages and turn each into an urgent architect message.
166
+
167
+ Delivery-by-file, like everything else: the message lands in `agent-mail/`
168
+ where the implementer already looks, rather than in a queue only this process
169
+ knows about.
170
+ """
171
+ cfg = config()
172
+ if not cfg:
173
+ return {"error": f"no config at {CONF}"}
174
+ try:
175
+ offset = int(open(_offset_path(), encoding=UTF8).read().strip())
176
+ except Exception:
177
+ offset = 0
178
+ r = api(cfg, "getUpdates", offset=offset or None, timeout=seconds,
179
+ allowed_updates=["message", "channel_post", "callback_query"])
180
+ if not r.get("ok"):
181
+ return {"error": r.get("error") or r.get("description") or "getUpdates failed"}
182
+
183
+ box = cfg_project.get("mailbox", "agent-mail")
184
+ os.makedirs(os.path.join(root, box), exist_ok=True)
185
+ # What a person is answered in, and what their message is written as, is the project's language as it
186
+ # stands now: a poller runs for days, and a project can choose another meanwhile (LANGUAGE-OUTPUT).
187
+ # What they type or tap is read the same in every language.
188
+ project = A.load_config(root) if r.get("result") else cfg_project
189
+ written, ignored, last = [], 0, offset
190
+ for u in r.get("result", []):
191
+ last = max(last, u.get("update_id", 0) + 1)
192
+
193
+ # A tapped button. This is the whole point of asking with options: the
194
+ # answer costs one tap, where the same blocker as prose costs minutes.
195
+ cq = u.get("callback_query")
196
+ if cq:
197
+ chat = str(((cq.get("message") or {}).get("chat") or {}).get("id", ""))
198
+ if chat not in cfg["chats"]:
199
+ ignored += 1
200
+ api(cfg, "answerCallbackQuery", callback_query_id=cq["id"],
201
+ text=language.text(project, "telegram.unauthorised"))
202
+ continue
203
+ did, _, keyv = (cq.get("data") or "").partition(":")
204
+ try:
205
+ rec = A.answer(root, did, keyv,
206
+ by=(cq.get("from") or {}).get("username") or chat)
207
+ except A.AnswerRefused as refused:
208
+ # A second tap, or a button of an answered question, keeps the first answer.
209
+ api(cfg, "answerCallbackQuery", callback_query_id=cq["id"], text=str(refused)[:200])
210
+ continue
211
+ if rec:
212
+ api(cfg, "answerCallbackQuery", callback_query_id=cq["id"],
213
+ text=language.text(project, "telegram.recorded", option=keyv))
214
+ send(f"✅ *{rec['question']}*\n→ {rec['answer']}", root)
215
+ written.append(f"{did}={keyv}")
216
+ else:
217
+ api(cfg, "answerCallbackQuery", callback_query_id=cq["id"],
218
+ text=language.text(project, "telegram.no-decision"))
219
+ continue
220
+
221
+ m = u.get("message") or u.get("channel_post") or {}
222
+ text = (m.get("text") or "").strip()
223
+ chat = str((m.get("chat") or {}).get("id", ""))
224
+ if not text:
225
+ continue
226
+ if chat not in cfg["chats"]:
227
+ ignored += 1 # not on the allowlist: it never happened
228
+ continue
229
+ if text.startswith("/"):
230
+ written.append(_command(root, project, text, chat))
231
+ continue
232
+
233
+ # "D-123 b" or "D-123 x <free text>" answers a pending question by typing,
234
+ # for when a button is not in reach — an old message, a different device.
235
+ mm = re.match(r"^(D-\d+)\s+(\S+)\s*(.*)$", text, re.S)
236
+ if mm:
237
+ did, key, extra = mm.group(1), mm.group(2), mm.group(3).strip()
238
+ try:
239
+ # The key leads, as on the terminal: the free-text key takes the words after it.
240
+ rec = A.answer(root, did, f"{key} {extra}" if key.lower() == "x" else key,
241
+ by=(m.get("from") or {}).get("username") or chat)
242
+ except A.AnswerRefused as refused:
243
+ send(f"`{did}`: {refused}", root)
244
+ continue
245
+ if rec:
246
+ send(f"✅ *{rec['question']}*\n→ {rec['answer']}", root)
247
+ written.append(f"{did}={rec.get('answer_key') or 'free'}")
248
+ continue
249
+ send(language.text(project, "telegram.no-such-decision", id=did), root)
250
+ continue
251
+ # Everything a person types is urgent. They reached for a phone to say it.
252
+ # Marked in the project's language; every reader knows both (LANGUAGE-FILES).
253
+ slug = A.safe_slug(text.lower(), language.text(project, "mail.untitled-message"))
254
+ # From a person, to whoever holds the implementer role (#31).
255
+ name = (f"{time.strftime('%Y%m%d-%H%M%S')}-human-to-{A.mail_names(project)[0]}-"
256
+ f"{language.marker(project, 'urgent-kind')}-{slug}.md")
257
+ who = (m.get("from") or {}).get("username") or chat
258
+ # Through write_mail, as every mail polyctl writes - its envelope, the credential scan, the mail ledger - where
259
+ # a person's message was written past all three (ROLE-TABLE-2).
260
+ name = A.write_mail(root, dict(project, mailbox=box), name,
261
+ f"# {text.splitlines()[0][:120]}\n\n{language.marker(project, 'urgent')}\n\n{text}\n\n"
262
+ f"_Telegram, {who}, {time.strftime('%Y-%m-%d %H:%M')}_\n",
263
+ {"kind": language.marker(project, "urgent-kind"), "class": "urgent", "from": "human",
264
+ "to": A.mail_names(project)[0]})
265
+ written.append(name)
266
+ send(language.text(project, "telegram.saved", name=name), root)
267
+ if last != offset:
268
+ open(_offset_path(), "w", encoding=UTF8).write(str(last))
269
+ return {"written": written, "ignored_unauthorised": ignored}
270
+
271
+
272
+ def _command(root, cfg_project, text, chat):
273
+ """A few read-only commands, so the phone can answer 'what is happening'.
274
+
275
+ The commands are the same words in every language; the list of them is in the project's (LANGUAGE-OUTPUT).
276
+ """
277
+ import subprocess
278
+ cmd = text.split()[0].lstrip("/").split("@")[0]
279
+ exe = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
280
+ "..", "bin", "polyctl")
281
+ # Past the clone's own script, the polyctl on PATH, never one the current directory holds (WINDOWS-NO-CWD-EXEC).
282
+ exe = os.path.abspath(exe) if os.path.exists(exe) else A.program_path("polyctl")
283
+ allowed = {"status": ["status"], "board": ["board"], "credits": ["credits"],
284
+ "notices": ["notices", "-n", "8"], "fleet": ["fleet"],
285
+ "decisions": ["decisions", "-n", "6"]}
286
+ if cmd not in allowed:
287
+ send(language.text(cfg_project, "telegram.commands"), root)
288
+ return f"/{cmd} (unknown)"
289
+ try:
290
+ if exe is None:
291
+ raise FileNotFoundError("polyctl is not on PATH")
292
+ out = subprocess.run([exe, "-C", root] + allowed[cmd], capture_output=True,
293
+ text=True, encoding=UTF8, errors="replace", timeout=60).stdout
294
+ except Exception as e:
295
+ out = str(e)
296
+ import re
297
+ clean = re.sub(r"\x1b\[[0-9;?]*[a-zA-Z]", "", out)[:3500]
298
+ send(f"```\n{clean}\n```", root)
299
+ return f"/{cmd}"
300
+
301
+
302
+ def main():
303
+ A.utf8_streams() # the names of the messages it wrote are UTF-8 in its log (#71)
304
+ root = os.getcwd()
305
+ if "-C" in sys.argv:
306
+ root = os.path.abspath(os.path.expanduser(sys.argv[sys.argv.index("-C") + 1]))
307
+ cfg_project = A.load_config(root)
308
+ once = "--once" in sys.argv
309
+ while True:
310
+ r = poll(root, cfg_project)
311
+ if r.get("error"):
312
+ print(r["error"], flush=True)
313
+ if once:
314
+ return 1
315
+ time.sleep(30)
316
+ continue
317
+ if r.get("written"):
318
+ print(f"{len(r['written'])} message(s): {', '.join(r['written'])}", flush=True)
319
+ if r.get("ignored_unauthorised"):
320
+ print(f"{r['ignored_unauthorised']} ignored (chat not on the allowlist)",
321
+ flush=True)
322
+ if once:
323
+ return 0
324
+
325
+
326
+ if __name__ == "__main__":
327
+ sys.exit(main())
polyctl/tiers.py ADDED
@@ -0,0 +1,123 @@
1
+ """The review tiers: which one a reviewer stands in, decided in one place (REVIEW-TIERS).
2
+
3
+ polyctl lands code only after a review by a model family other than the one that wrote it. Someone
4
+ who runs a single harness could not meet that rule, and polyctl refused them three different ways:
5
+ `polyctl init` refused the single-harness profile its own documents recommended, `polyctl role set`
6
+ assigned a reviewer that `polyctl review` then refused, and the one configuration that worked - a
7
+ reviewer with no implementer - compared the reviewer with nobody. There are three tiers now,
8
+ each recorded with the review and labeled wherever the review shows:
9
+
10
+ - independent: a model of another family. The default, and the strongest.
11
+ - same-family: another model of the implementer's family. Only where a person opted in with
12
+ `review.same_family` `labeled`, on the record, and every surface says SAME_FAMILY_LABEL.
13
+ - person: a person read the diff and recorded the verdict with `polyctl person-review`.
14
+
15
+ `polyctl role set`, the reviewer probe, `polyctl review`, `polyctl commit-ok`, the capability matrix and catch-up
16
+ all ask `tier`. What each knows about a reviewer and an author is gathered where it is known; which
17
+ tier that makes is decided here and nowhere else. Standard library only, and pure: nothing here
18
+ reads a file, a setting or a ledger.
19
+ """
20
+
21
+ INDEPENDENT = "independent"
22
+ SAME_FAMILY = "same-family"
23
+ PERSON = "person"
24
+ TIERS = (INDEPENDENT, SAME_FAMILY, PERSON)
25
+
26
+ LABELS = {INDEPENDENT: "another model family",
27
+ SAME_FAMILY: "same family: weaker independence",
28
+ PERSON: "person review"}
29
+ SAME_FAMILY_LABEL = LABELS[SAME_FAMILY]
30
+
31
+ # `review.same_family`: its default, and the value a person opts in with.
32
+ REFUSED = "refused"
33
+ LABELED = "labeled"
34
+
35
+ # A route may not declare this family: only a review a person recorded is a person's.
36
+ PERSON_FAMILY = "person"
37
+
38
+ # What a refusal names as the ways forward, wherever a model reviewer of no tier is refused.
39
+ WAYS_FORWARD = ("Ways forward: a reviewer of another model family (polyctl role set reviewer <adapter> --model <model>); "
40
+ "another model of the implementer's family, labeled, once a person opts in on the record "
41
+ "(polyctl config set review.same_family labeled --by <name>); or a person's review of each candidate "
42
+ "(polyctl person-review --by <name>).")
43
+ # A waived range records the family that wrote it and never its model, so no same-family tier reaches it.
44
+ RANGE_WAYS_FORWARD = ("Ways forward: a reviewer of another model family, or a person's review of the range "
45
+ "(polyctl person-review --commits <range> --by <name>).")
46
+
47
+
48
+ def label(tier):
49
+ """The words every surface prints for a tier; '' for none."""
50
+ return LABELS.get(tier, "")
51
+
52
+
53
+ def weaker(tier):
54
+ """Whether a tier is one a surface must call out: anything below another model family."""
55
+ return tier in (SAME_FAMILY, PERSON)
56
+
57
+
58
+ def tier(reviewer, author, same_family=False):
59
+ """(tier, None) for the tier a reviewer stands in against the author of what it reviews, or (None, refusal).
60
+
61
+ `reviewer` is what is known of the reviewer, each key optional:
62
+ person - a person read the diff and recorded the verdict; nothing a route declares sets it
63
+ identity - it runs as the author: the implementer's session, or its capability binding
64
+ tool - it is a tool that reaches many model families through its provider
65
+ family - the family it states itself, lowercased
66
+ declared - the family it or its adapter declares, None when none does or the two disagree
67
+ model - the model it runs
68
+ engine - the program it runs
69
+ `author` is what is known of whoever wrote the work:
70
+ range - a waived range under catch-up, held to `families`: recorded or named for it
71
+ known - an implementer is configured at all
72
+ family, declared, model - as for the reviewer
73
+ engines - the programs the implementer's adapter runs
74
+ `same_family` is whether a person's opt-in into the same-family tier is in force.
75
+
76
+ A refusal is a base - `author`, `person-family`, `tool-unnamed`, `range-unnamed`,
77
+ `unnamed-family`, `author-family`, `family` or `engine` - and, where the opt-in is in force and
78
+ still admits nothing, `/families`, `/model-unnamed` or `/model` after it. (None, None) is an
79
+ implementer nobody configured: no tier can be established and nothing is refused, which
80
+ `polyctl doctor` names as a problem rather than a review surface guessing a tier.
81
+ """
82
+ reviewer = reviewer if isinstance(reviewer, dict) else {}
83
+ author = author if isinstance(author, dict) else {}
84
+ if reviewer.get("person"):
85
+ return PERSON, None
86
+ if reviewer.get("identity"):
87
+ return None, "author"
88
+ if PERSON_FAMILY in (reviewer.get("family"), reviewer.get("declared")):
89
+ return None, "person-family"
90
+ if reviewer.get("tool") and not reviewer.get("family"):
91
+ # A model name is not a family, and a tool's provider reaches many (#86).
92
+ return None, "tool-unnamed"
93
+ if author.get("range"):
94
+ # A waived range is held to the family that wrote it; nothing recorded its model (#65).
95
+ families = author.get("families") or ()
96
+ if not families:
97
+ return None, "range-unnamed"
98
+ if not reviewer.get("declared"):
99
+ return None, "unnamed-family"
100
+ return (INDEPENDENT, None) if reviewer["declared"] not in families else (None, "author-family")
101
+ if not author.get("known"):
102
+ return None, None
103
+ stated = (reviewer.get("family"), author.get("family"))
104
+ if all(stated):
105
+ if stated[0] != stated[1]:
106
+ return INDEPENDENT, None
107
+ base = "family"
108
+ elif reviewer.get("engine") and reviewer["engine"] in (author.get("engines") or ()):
109
+ # One engine serves many models; with families unstated, sharing it is sharing the author (#65).
110
+ base = "engine"
111
+ else:
112
+ return INDEPENDENT, None
113
+ if not same_family:
114
+ return None, base
115
+ declared = (reviewer.get("declared"), author.get("declared"))
116
+ if not all(declared) or declared[0] != declared[1]:
117
+ return None, base + "/families"
118
+ models = (reviewer.get("model"), author.get("model"))
119
+ if not all(models):
120
+ return None, base + "/model-unnamed"
121
+ if str(models[0]).strip().lower() == str(models[1]).strip().lower():
122
+ return None, base + "/model"
123
+ return SAME_FAMILY, None
polyctl/verdicts.py ADDED
@@ -0,0 +1,41 @@
1
+ """The values a review's outcome can take, and nothing else (#4).
2
+
3
+ Verdicts and review statuses were free-form strings compared by equality in a
4
+ dozen places, and free-form strings drift: a reviewer's "APPROVE", a status of
5
+ "completed". These enums own the literals. A verdict that is not one of them is
6
+ INVALID when read, a status that is not one of them is refused when written, and
7
+ the playbook and docs/protocol.md list the same values - a test keeps the three
8
+ in agreement.
9
+ """
10
+ from enum import Enum
11
+
12
+
13
+ class Verdict(str, Enum):
14
+ """A review's verdict. A reviewer writes the first two; polyctl writes the other two."""
15
+ APPROVED = "APPROVED"
16
+ NEEDS_CHANGES = "NEEDS_CHANGES"
17
+ UNAVAILABLE = "UNAVAILABLE" # no review took place: not a verdict, not a round
18
+ INVALID = "INVALID" # an answer that broke the verdict and count schema
19
+
20
+
21
+ class ReviewStatus(str, Enum):
22
+ """How a review run ended, recorded in strict evidence as review_status."""
23
+ PENDING = "pending"
24
+ COMPLETE = "complete"
25
+ INVALID = "invalid"
26
+ UNAVAILABLE = "unavailable"
27
+
28
+
29
+ class CriterionVerdict(str, Enum):
30
+ """What a review found of one criterion its boundary lists (CRITERIA-VERDICTS).
31
+
32
+ A criterion no answer judged is recorded with no verdict at all, and a value
33
+ that is not one of these reads as none: only MET lets a commit through.
34
+ """
35
+ MET = "met"
36
+ NOT_MET = "not met"
37
+
38
+
39
+ VERDICTS = tuple(item.value for item in Verdict)
40
+ REVIEWER_VERDICTS = (Verdict.APPROVED.value, Verdict.NEEDS_CHANGES.value)
41
+ REVIEW_STATUSES = tuple(item.value for item in ReviewStatus)