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/matrix.py ADDED
@@ -0,0 +1,660 @@
1
+ """Pure capability-matrix validation and identity resolution.
2
+
3
+ The matrix is deliberately declarative. This module never reads files, inspects
4
+ installed binaries, spawns a process, or attests a provider/model/tool claim. It
5
+ only validates what a project declared and returns JSON-safe identity snapshots
6
+ for the impure CLI boundary to measure and persist.
7
+ """
8
+ import hashlib
9
+ import json
10
+ import re
11
+ import string
12
+
13
+ from . import tiers
14
+
15
+ MATRIX_VERSION = 1
16
+ MATRIX_DIGEST_PREFIX = "sha256:"
17
+
18
+ _ID_RE = re.compile(r"^[^\s\x00-\x1f\x7f]+$")
19
+ _NORMAL_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._:-]*$")
20
+ _ALLOWED_PLACEHOLDERS = frozenset(("prompt", "model"))
21
+
22
+ # A route's ineligible_reason, for each refusal tiers.tier can give a declared binding. Evidence
23
+ # persists these closed words and compares them on every grant, so they never change.
24
+ MATRIX_REFUSALS = {
25
+ "author": "same binding as implementer",
26
+ "family": "same model family as implementer",
27
+ "family/model": "same model as implementer",
28
+ "author-family": "same model family as the author",
29
+ }
30
+
31
+ IMPLEMENTER_REQUIREMENTS = {
32
+ "provider": frozenset(("invoke",)),
33
+ "model": frozenset(("implementation",)),
34
+ "tool": frozenset(("prompt", "workspace-write")),
35
+ }
36
+ REVIEWER_REQUIREMENTS = {
37
+ "provider": frozenset(("invoke",)),
38
+ "model": frozenset(("semantic-review",)),
39
+ "tool": frozenset(("prompt",)),
40
+ }
41
+
42
+
43
+ class MatrixError(ValueError):
44
+ """A closed, user-fixable strict-configuration failure."""
45
+
46
+ def __init__(self, problems, key="capability-matrix"):
47
+ self.problems = tuple(str(problem) for problem in problems)
48
+ self.key = key
49
+ super().__init__("; ".join(self.problems))
50
+
51
+
52
+ def is_strict(cfg):
53
+ """True only when a project opted in (including an unreadable opt-in)."""
54
+ return isinstance(cfg, dict) and (
55
+ "capability_matrix" in cfg or "_capability_matrix_error" in cfg
56
+ )
57
+
58
+
59
+ def canonical_digest(value):
60
+ """Canonical-JSON SHA-256 for a validated JSON value."""
61
+ payload = json.dumps(
62
+ value, ensure_ascii=True, sort_keys=True, separators=(",", ":")
63
+ ).encode("utf-8")
64
+ return MATRIX_DIGEST_PREFIX + hashlib.sha256(payload).hexdigest()
65
+
66
+
67
+ def _problem(problems, path, message):
68
+ problems.append("%s: %s" % (path, message))
69
+
70
+
71
+ def _mapping(value, path, problems):
72
+ if not isinstance(value, dict):
73
+ _problem(problems, path, "must be an object")
74
+ return None
75
+ return value
76
+
77
+
78
+ def _opaque_id(value, path, problems):
79
+ if not isinstance(value, str):
80
+ _problem(problems, path, "must be a string")
81
+ return None
82
+ if not value or value != value.strip() or not _ID_RE.fullmatch(value):
83
+ _problem(problems, path, "must be a nonempty identifier without whitespace")
84
+ return None
85
+ return value
86
+
87
+
88
+ def _normal_id(value, path, problems):
89
+ if not isinstance(value, str):
90
+ _problem(problems, path, "must be a string")
91
+ return None
92
+ if not _NORMAL_ID_RE.fullmatch(value):
93
+ _problem(problems, path, "must be a normalized lowercase identifier")
94
+ return None
95
+ return value
96
+
97
+
98
+ def _only_keys(value, allowed, path, problems):
99
+ for key in value:
100
+ if not isinstance(key, str):
101
+ _problem(problems, path, "keys must be strings")
102
+ elif key not in allowed:
103
+ _problem(problems, "%s.%s" % (path, key), "is not supported")
104
+
105
+
106
+ def _capabilities(value, path, problems):
107
+ if not isinstance(value, list):
108
+ _problem(problems, path, "must be a list")
109
+ return None
110
+ result = []
111
+ for index, item in enumerate(value):
112
+ cap = _normal_id(item, "%s[%d]" % (path, index), problems)
113
+ if cap is not None:
114
+ if cap in result:
115
+ _problem(problems, "%s[%d]" % (path, index), "duplicates %s" % cap)
116
+ else:
117
+ result.append(cap)
118
+ return result
119
+
120
+
121
+ def _argv_template(value, path, problems):
122
+ if not isinstance(value, list):
123
+ _problem(problems, path, "must be a list")
124
+ return None, frozenset()
125
+ if not value:
126
+ _problem(problems, path, "must not be empty")
127
+ return None, frozenset()
128
+ formatter = string.Formatter()
129
+ fields = set()
130
+ result = []
131
+ for index, item in enumerate(value):
132
+ item_path = "%s[%d]" % (path, index)
133
+ if not isinstance(item, str):
134
+ _problem(problems, item_path, "must be a string")
135
+ continue
136
+ if "\x00" in item:
137
+ _problem(problems, item_path, "must not contain NUL")
138
+ continue
139
+ if index == 0 and (not item or item != item.strip()):
140
+ _problem(problems, item_path, "executable must be a nonempty identifier")
141
+ try:
142
+ parsed = list(formatter.parse(item))
143
+ except ValueError as exc:
144
+ _problem(problems, item_path, "invalid template: %s" % exc)
145
+ continue
146
+ for _, field, format_spec, conversion in parsed:
147
+ if field is None:
148
+ continue
149
+ if field not in _ALLOWED_PLACEHOLDERS:
150
+ _problem(problems, item_path, "unknown placeholder {%s}" % field)
151
+ continue
152
+ if format_spec or conversion:
153
+ _problem(problems, item_path, "placeholder formatting is not supported")
154
+ continue
155
+ if index == 0:
156
+ _problem(problems, item_path, "executable cannot be a placeholder")
157
+ fields.add(field)
158
+ result.append(item)
159
+ return result if len(result) == len(value) else None, frozenset(fields)
160
+
161
+
162
+ def _records(value, path, fields, problems):
163
+ records = _mapping(value, path, problems)
164
+ if records is None:
165
+ return {}
166
+ if not records:
167
+ _problem(problems, path, "must not be empty")
168
+ result = {}
169
+ for raw_id, raw_record in records.items():
170
+ item_id = _opaque_id(raw_id, "%s key" % path, problems)
171
+ item_path = "%s.%s" % (path, raw_id)
172
+ record = _mapping(raw_record, item_path, problems)
173
+ if item_id is None or record is None:
174
+ continue
175
+ _only_keys(record, fields, item_path, problems)
176
+ result[item_id] = record
177
+ return result
178
+
179
+
180
+ def _identity(binding_id, binding, providers, models, tools):
181
+ provider_id = binding["provider"]
182
+ model_id = binding["model"]
183
+ tool_id = binding["tool"]
184
+ provider = providers[provider_id]
185
+ model = models[model_id]
186
+ tool = tools[tool_id]
187
+ return {
188
+ "binding": binding_id,
189
+ "provider": provider_id,
190
+ "model": model_id,
191
+ "model_argument": model["argument"],
192
+ "tool": tool_id,
193
+ "adapter": tool.get("adapter"),
194
+ "family": model["family"],
195
+ "provider_capabilities": sorted(provider["capabilities"]),
196
+ "model_capabilities": sorted(model["capabilities"]),
197
+ "tool_capabilities": sorted(tool["capabilities"]),
198
+ }
199
+
200
+
201
+ def _require_capabilities(identity, requirements, path, problems):
202
+ labels = {
203
+ "provider": "provider_capabilities",
204
+ "model": "model_capabilities",
205
+ "tool": "tool_capabilities",
206
+ }
207
+ for layer, required in requirements.items():
208
+ actual = set(identity[labels[layer]])
209
+ missing = sorted(required - actual)
210
+ if missing:
211
+ _problem(
212
+ problems,
213
+ path,
214
+ "%s is missing required capabilities: %s"
215
+ % (layer, ", ".join(missing)),
216
+ )
217
+
218
+
219
+ def _role_binding(role, path, bindings, problems):
220
+ block = _mapping(role, path, problems)
221
+ if block is None:
222
+ return None
223
+ binding_id = _opaque_id(block.get("binding"), path + ".binding", problems)
224
+ if binding_id is not None and binding_id not in bindings:
225
+ _problem(problems, path + ".binding", "references unknown binding %s" % binding_id)
226
+ return None
227
+ return binding_id
228
+
229
+
230
+ def _concrete(value):
231
+ return isinstance(value, str) and bool(value.strip()) and value.strip().lower() != "auto"
232
+
233
+
234
+ def resolve(cfg, require_independent=True, author_families=(), same_family=False):
235
+ """Validate and resolve a strict config.
236
+
237
+ Returned dictionaries contain runtime argv templates for the CLI, but callers
238
+ must persist only ``matrix``, identities and attempt summaries. ``argv`` is
239
+ intentionally absent from every identity snapshot.
240
+
241
+ ``author_families`` are the model families that wrote a waived range under
242
+ retrospective review. Its independence is judged against them instead of the
243
+ implementer binding, which need not be the author: a binding of one of those
244
+ families is ineligible, and the implementer's may review what another wrote.
245
+
246
+ Which tier a binding stands in is decided by tiers.tier, as it is for every
247
+ reviewer (REVIEW-TIERS). ``same_family`` is whether a person's recorded opt-in
248
+ into the same-family tier is in force, which only the caller can read: a
249
+ binding of the implementer's family and another model argument is then
250
+ eligible, and its route says so in ``tier``.
251
+ """
252
+ if not is_strict(cfg):
253
+ raise MatrixError(("capability_matrix is absent",))
254
+ load_error = cfg.get("_capability_matrix_error")
255
+ if load_error:
256
+ raise MatrixError(("capability_matrix: configuration JSON is malformed",))
257
+
258
+ problems = []
259
+ matrix = _mapping(cfg.get("capability_matrix"), "capability_matrix", problems)
260
+ if matrix is None:
261
+ raise MatrixError(problems)
262
+ _only_keys(
263
+ matrix, frozenset(("version", "providers", "models", "tools", "bindings")),
264
+ "capability_matrix", problems,
265
+ )
266
+ version = matrix.get("version")
267
+ if type(version) is not int:
268
+ _problem(problems, "capability_matrix.version", "must be integer 1")
269
+ elif version != MATRIX_VERSION:
270
+ _problem(problems, "capability_matrix.version", "unsupported version %s" % version)
271
+
272
+ providers_raw = _records(
273
+ matrix.get("providers"), "capability_matrix.providers",
274
+ frozenset(("capabilities",)), problems,
275
+ )
276
+ models_raw = _records(
277
+ matrix.get("models"), "capability_matrix.models",
278
+ frozenset(("family", "argument", "capabilities")), problems,
279
+ )
280
+ tools_raw = _records(
281
+ matrix.get("tools"), "capability_matrix.tools",
282
+ frozenset(("adapter", "argv", "capabilities")), problems,
283
+ )
284
+ bindings_raw = _records(
285
+ matrix.get("bindings"), "capability_matrix.bindings",
286
+ frozenset(("provider", "model", "tool")), problems,
287
+ )
288
+
289
+ providers = {}
290
+ for item_id, record in providers_raw.items():
291
+ caps = _capabilities(
292
+ record.get("capabilities"),
293
+ "capability_matrix.providers.%s.capabilities" % item_id, problems,
294
+ )
295
+ if caps is not None:
296
+ providers[item_id] = {"capabilities": caps}
297
+
298
+ models = {}
299
+ for item_id, record in models_raw.items():
300
+ base = "capability_matrix.models.%s" % item_id
301
+ family = _normal_id(record.get("family"), base + ".family", problems)
302
+ argument = record.get("argument")
303
+ if not isinstance(argument, str):
304
+ _problem(problems, base + ".argument", "must be a string")
305
+ argument = None
306
+ elif not argument or not argument.strip() or "\x00" in argument or "\n" in argument:
307
+ _problem(problems, base + ".argument", "must be a nonempty single-line runtime argument")
308
+ argument = None
309
+ caps = _capabilities(record.get("capabilities"), base + ".capabilities", problems)
310
+ if family is not None and argument is not None and caps is not None:
311
+ models[item_id] = {
312
+ "family": family, "argument": argument, "capabilities": caps,
313
+ }
314
+
315
+ tools = {}
316
+ for item_id, record in tools_raw.items():
317
+ base = "capability_matrix.tools.%s" % item_id
318
+ adapter = None
319
+ if "adapter" in record:
320
+ adapter = _opaque_id(record.get("adapter"), base + ".adapter", problems)
321
+ argv, placeholders = None, frozenset()
322
+ if "argv" in record:
323
+ argv, placeholders = _argv_template(record.get("argv"), base + ".argv", problems)
324
+ caps = _capabilities(record.get("capabilities"), base + ".capabilities", problems)
325
+ if caps is not None and ("adapter" not in record or adapter is not None) \
326
+ and ("argv" not in record or argv is not None):
327
+ tools[item_id] = {
328
+ "adapter": adapter, "argv": argv,
329
+ "placeholders": placeholders, "capabilities": caps,
330
+ }
331
+
332
+ bindings = {}
333
+ for item_id, record in bindings_raw.items():
334
+ base = "capability_matrix.bindings.%s" % item_id
335
+ refs = {}
336
+ for field, declared in (("provider", providers_raw), ("model", models_raw), ("tool", tools_raw)):
337
+ ref = _opaque_id(record.get(field), base + "." + field, problems)
338
+ if ref is not None and ref not in declared:
339
+ _problem(problems, base + "." + field, "references unknown %s %s" % (field, ref))
340
+ refs[field] = ref
341
+ if all(refs.values()):
342
+ bindings[item_id] = refs
343
+
344
+ impl_block = cfg.get("implementer")
345
+ impl_binding = _role_binding(
346
+ impl_block, "implementer", bindings_raw, problems
347
+ )
348
+ reviewer_block = _mapping(cfg.get("reviewer"), "reviewer", problems)
349
+ reviewer_bindings = []
350
+ if reviewer_block is not None:
351
+ primary_binding = _role_binding(reviewer_block, "reviewer", bindings_raw, problems)
352
+ if primary_binding is not None:
353
+ reviewer_bindings.append(primary_binding)
354
+ fallbacks = reviewer_block.get("fallbacks", [])
355
+ if not isinstance(fallbacks, list):
356
+ _problem(problems, "reviewer.fallbacks", "must be a list")
357
+ else:
358
+ for index, fallback in enumerate(fallbacks):
359
+ binding_id = _role_binding(
360
+ fallback, "reviewer.fallbacks[%d]" % index, bindings_raw, problems
361
+ )
362
+ if binding_id is not None:
363
+ reviewer_bindings.append(binding_id)
364
+ seen = set()
365
+ for binding_id in reviewer_bindings:
366
+ if binding_id in seen:
367
+ _problem(problems, "reviewer.fallbacks", "duplicates reviewer binding %s" % binding_id)
368
+ seen.add(binding_id)
369
+
370
+ if problems:
371
+ raise MatrixError(problems)
372
+
373
+ # Every referenced record survived scalar/list validation if the binding is
374
+ # usable. Report broken referenced records as closed configuration errors.
375
+ referenced = [impl_binding] + reviewer_bindings
376
+ for binding_id in referenced:
377
+ binding = bindings.get(binding_id)
378
+ if binding is None or binding["provider"] not in providers \
379
+ or binding["model"] not in models or binding["tool"] not in tools:
380
+ _problem(problems, "capability_matrix.bindings.%s" % binding_id,
381
+ "references an invalid declaration")
382
+ if problems:
383
+ raise MatrixError(problems)
384
+
385
+ implementer_identity = _identity(impl_binding, bindings[impl_binding], providers, models, tools)
386
+ _require_capabilities(
387
+ implementer_identity, IMPLEMENTER_REQUIREMENTS,
388
+ "implementer.binding %s" % impl_binding, problems,
389
+ )
390
+
391
+ impl = impl_block
392
+ for field in ("adapter", "model"):
393
+ if field in impl and not isinstance(impl.get(field), str):
394
+ _problem(problems, "implementer.%s" % field, "must be a string")
395
+ adapter = impl.get("adapter")
396
+ if _concrete(adapter) and adapter != implementer_identity["adapter"]:
397
+ _problem(
398
+ problems, "implementer.adapter",
399
+ "does not match binding %s adapter %s"
400
+ % (impl_binding, implementer_identity["adapter"] or "<none>"),
401
+ )
402
+ model = impl.get("model")
403
+ if _concrete(model) and model != implementer_identity["model_argument"]:
404
+ _problem(
405
+ problems, "implementer.model",
406
+ "does not match binding %s model argument %s"
407
+ % (impl_binding, implementer_identity["model_argument"]),
408
+ )
409
+
410
+ routes = []
411
+ for index, binding_id in enumerate(reviewer_bindings):
412
+ binding = bindings[binding_id]
413
+ identity = _identity(binding_id, binding, providers, models, tools)
414
+ path = "reviewer.binding" if index == 0 else "reviewer.fallbacks[%d].binding" % (index - 1)
415
+ _require_capabilities(identity, REVIEWER_REQUIREMENTS, path + " " + binding_id, problems)
416
+ tool = tools[binding["tool"]]
417
+ if tool.get("argv") is None:
418
+ _problem(problems, path, "reviewer tool must declare a nonempty argv template")
419
+ else:
420
+ missing = sorted(_ALLOWED_PLACEHOLDERS - tool["placeholders"])
421
+ if missing:
422
+ _problem(
423
+ problems, path,
424
+ "reviewer argv must expand placeholders: %s" % ", ".join(missing),
425
+ )
426
+ # Family comes only from the bound model declaration, so an inline field cannot spoof a tier.
427
+ if author_families:
428
+ decided, refusal = tiers.tier({"declared": identity["family"]},
429
+ {"range": True, "families": list(author_families)})
430
+ else:
431
+ decided, refusal = tiers.tier(
432
+ {"identity": binding_id == impl_binding, "family": identity["family"],
433
+ "declared": identity["family"], "model": identity["model_argument"]},
434
+ {"known": True, "family": implementer_identity["family"],
435
+ "declared": implementer_identity["family"], "model": implementer_identity["model_argument"]},
436
+ same_family=same_family,
437
+ )
438
+ routes.append({
439
+ "index": index,
440
+ "identity": identity,
441
+ "argv": list(tool.get("argv") or []),
442
+ "eligible": decided is not None,
443
+ "ineligible_reason": "" if decided is not None else MATRIX_REFUSALS.get(refusal, "not independent of the "
444
+ "implementer"),
445
+ "tier": decided,
446
+ })
447
+
448
+ if problems:
449
+ raise MatrixError(problems)
450
+ if require_independent and not any(route["eligible"] for route in routes):
451
+ raise MatrixError(
452
+ ("reviewer chain has no binding independent of the author's model family" if author_families
453
+ else "reviewer chain has no binding independent of the implementer binding and model family"
454
+ + ("" if same_family else "; a binding of the implementer's family and another model reviews "
455
+ "only where a person opted in (review.same_family labeled)"),),
456
+ key="no-independent-reviewer",
457
+ )
458
+
459
+ return {
460
+ "strict": True,
461
+ "version": MATRIX_VERSION,
462
+ "digest": canonical_digest(matrix),
463
+ "matrix": {"version": MATRIX_VERSION, "digest": canonical_digest(matrix)},
464
+ "implementer_identity": implementer_identity,
465
+ "reviewers": routes,
466
+ }
467
+
468
+
469
+ def expand_argv(route, prompt):
470
+ """Expand a validated reviewer route without invoking a shell."""
471
+ if not isinstance(prompt, str) or not prompt:
472
+ raise MatrixError(("review prompt must be a nonempty string",))
473
+ model = route["identity"]["model_argument"]
474
+ try:
475
+ argv = [part.format(prompt=prompt, model=model) for part in route["argv"]]
476
+ except (KeyError, ValueError) as exc:
477
+ raise MatrixError(("reviewer argv expansion failed: %s" % exc,))
478
+ if not argv or not argv[0]:
479
+ raise MatrixError(("reviewer argv expansion produced no executable",))
480
+ return argv
481
+
482
+
483
+ def initial_attempts(resolution):
484
+ """Safe, complete ordered chain snapshot; no argv or process output."""
485
+ attempts = []
486
+ for route in resolution["reviewers"]:
487
+ if route["eligible"]:
488
+ outcome, reason = "not-attempted", ""
489
+ else:
490
+ outcome, reason = "ineligible", route["ineligible_reason"]
491
+ attempts.append({
492
+ "binding": route["identity"]["binding"],
493
+ "outcome": outcome,
494
+ "reason": reason,
495
+ })
496
+ return attempts
497
+
498
+
499
+ def set_attempt(attempts, route, outcome, reason=""):
500
+ """Update one safe attempt row by its unique declared binding."""
501
+ binding = route["identity"]["binding"]
502
+ for attempt in attempts:
503
+ if attempt["binding"] == binding:
504
+ attempt["outcome"] = str(outcome)
505
+ attempt["reason"] = str(reason)
506
+ return
507
+ raise MatrixError(("reviewer attempt binding %s is not in the resolved chain" % binding,))
508
+
509
+
510
+ def safe_unavailable_reason(kind):
511
+ """Collapse invocation kinds to the closed, non-diagnostic evidence vocabulary.
512
+
513
+ Retry and fallback decisions consume the full ``kind`` before this boundary.
514
+ Evidence intentionally preserves only three actionable, content-free reasons;
515
+ every other closed or unknown kind becomes ``runtime unavailable`` rather than
516
+ persisting process diagnostics or growing an open-ended authority schema.
517
+ """
518
+ return {
519
+ "missing-binary": "tool not installed",
520
+ "timeout": "timeout",
521
+ "silence": "no output",
522
+ }.get(str(kind or ""), "runtime unavailable")
523
+
524
+
525
+ def _role_bindings(resolution):
526
+ return {
527
+ "implementer": resolution["implementer_identity"]["binding"],
528
+ "reviewers": [
529
+ route["identity"]["binding"] for route in resolution["reviewers"]
530
+ ],
531
+ }
532
+
533
+
534
+ def add_evidence_context(evidence, resolution, attempts, reviewer_identity=None,
535
+ review_status="pending"):
536
+ """Attach schema-3 declared identity evidence; never attach argv."""
537
+ from .verdicts import REVIEW_STATUSES
538
+ if review_status not in REVIEW_STATUSES:
539
+ # A status outside the closed set would read as neither complete nor failed (#4).
540
+ raise ValueError(f"unknown review status {review_status!r}; one of {', '.join(REVIEW_STATUSES)}")
541
+ evidence.update({
542
+ "schema": 3,
543
+ "matrix": dict(resolution["matrix"]),
544
+ "role_bindings": _role_bindings(resolution),
545
+ "implementer_identity": dict(resolution["implementer_identity"]),
546
+ "reviewer_identity": dict(reviewer_identity) if reviewer_identity else None,
547
+ "reviewer_attempts": [dict(attempt) for attempt in attempts],
548
+ "review_status": review_status,
549
+ })
550
+ return evidence
551
+
552
+
553
+ def review_evidence_problems(resolution, evidence):
554
+ """Validate authorizable strict prospective evidence against live config."""
555
+ problems = []
556
+ if not isinstance(evidence, dict):
557
+ return ["strict review evidence is not a structured object"]
558
+ if evidence.get("schema") != 3:
559
+ problems.append("strict review evidence must use schema 3")
560
+ if evidence.get("matrix") != resolution["matrix"]:
561
+ problems.append("strict review matrix version or digest does not match current config")
562
+ if evidence.get("role_bindings") != _role_bindings(resolution):
563
+ problems.append("strict review role bindings do not match current config")
564
+ if evidence.get("implementer_identity") != resolution["implementer_identity"]:
565
+ problems.append("strict review implementer identity does not match current config")
566
+ if evidence.get("review_status") != "complete":
567
+ problems.append("strict review did not complete")
568
+
569
+ reviewer_identity = evidence.get("reviewer_identity")
570
+ selected = next(
571
+ (route for route in resolution["reviewers"]
572
+ if route["eligible"] and route["identity"] == reviewer_identity),
573
+ None,
574
+ )
575
+ if selected is None:
576
+ problems.append("strict review reviewer identity is not independently eligible now")
577
+
578
+ attempts = evidence.get("reviewer_attempts")
579
+ expected_bindings = [route["identity"]["binding"] for route in resolution["reviewers"]]
580
+ if not isinstance(attempts, list):
581
+ problems.append("strict review attempts must be a list")
582
+ attempts = []
583
+ else:
584
+ for attempt in attempts:
585
+ if not isinstance(attempt, dict) or set(attempt) != {"binding", "outcome", "reason"} \
586
+ or not all(isinstance(attempt.get(key), str)
587
+ for key in ("binding", "outcome", "reason")):
588
+ problems.append("strict review attempts contain a malformed or unsafe entry")
589
+ break
590
+ actual_bindings = [attempt.get("binding") for attempt in attempts
591
+ if isinstance(attempt, dict)]
592
+ if actual_bindings != expected_bindings:
593
+ problems.append("strict review attempts do not match the current reviewer chain")
594
+
595
+ if selected is not None and len(attempts) == len(resolution["reviewers"]):
596
+ selected_index = selected["index"]
597
+ for route, attempt in zip(resolution["reviewers"], attempts):
598
+ if not isinstance(attempt, dict):
599
+ continue
600
+ if not route["eligible"]:
601
+ expected = "ineligible"
602
+ valid_reasons = {route["ineligible_reason"]}
603
+ elif route["index"] < selected_index:
604
+ expected = "unavailable"
605
+ valid_reasons = {
606
+ "tool not installed", "timeout", "no output", "runtime unavailable",
607
+ }
608
+ elif route["index"] == selected_index:
609
+ expected = "reviewed"
610
+ valid_reasons = {""}
611
+ else:
612
+ expected = "not-attempted"
613
+ valid_reasons = {""}
614
+ if attempt.get("outcome") != expected:
615
+ problems.append(
616
+ "strict review attempt outcome for %s must be %s"
617
+ % (route["identity"]["binding"], expected)
618
+ )
619
+ if attempt.get("reason") not in valid_reasons:
620
+ problems.append(
621
+ "strict review attempt reason for %s is not safe or canonical"
622
+ % route["identity"]["binding"]
623
+ )
624
+ return problems
625
+
626
+
627
+ def authority_fields(resolution, reviewer_identity=None):
628
+ """Safe strict fields added to a schema-3 authority row."""
629
+ safe_reviewer = next(
630
+ (route["identity"] for route in resolution["reviewers"]
631
+ if route["eligible"] and route["identity"] == reviewer_identity),
632
+ None,
633
+ )
634
+ return {
635
+ "matrix": dict(resolution["matrix"]),
636
+ "role_bindings": _role_bindings(resolution),
637
+ "implementer_identity": dict(resolution["implementer_identity"]),
638
+ "reviewer_identity": dict(safe_reviewer) if safe_reviewer else None,
639
+ }
640
+
641
+
642
+ def authority_problems(resolution, grant):
643
+ """Validate the live strict matrix and implementer against a persisted grant."""
644
+ problems = []
645
+ if not isinstance(grant, dict) or grant.get("schema") != 3:
646
+ problems.append("strict mode requires a schema-3 capability-matrix grant")
647
+ return problems
648
+ if grant.get("matrix") != resolution["matrix"]:
649
+ problems.append("authority grant matrix version or digest has drifted")
650
+ if grant.get("role_bindings") != _role_bindings(resolution):
651
+ problems.append("authority grant role bindings have drifted")
652
+ if grant.get("implementer_identity") != resolution["implementer_identity"]:
653
+ problems.append("authority grant implementer identity has drifted")
654
+ reviewer_identity = grant.get("reviewer_identity")
655
+ if reviewer_identity is not None and not any(
656
+ route["eligible"] and route["identity"] == reviewer_identity
657
+ for route in resolution["reviewers"]
658
+ ):
659
+ problems.append("authority grant reviewer identity is no longer independently eligible")
660
+ return problems