@rvdbreemen/adr-kit-opencode 0.52.0 → 0.53.0

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 (83) hide show
  1. package/.claude-plugin/plugin.json +29 -29
  2. package/README.md +865 -850
  3. package/bin/adr +0 -0
  4. package/bin/adr-audit +0 -0
  5. package/bin/adr-context +0 -0
  6. package/bin/adr-discover +0 -0
  7. package/bin/adr-doctor +0 -0
  8. package/bin/adr-generate-scripts +0 -0
  9. package/bin/adr-grill-signal +0 -0
  10. package/bin/adr-guardian +0 -0
  11. package/bin/adr-index +0 -0
  12. package/bin/adr-judge +0 -0
  13. package/bin/adr-judge-precommit +0 -0
  14. package/bin/adr-lint +0 -0
  15. package/bin/adr-mcp +96 -4
  16. package/bin/adr-migrate +0 -0
  17. package/bin/adr-quality +0 -0
  18. package/bin/adr-readiness +0 -0
  19. package/bin/adr-readiness-ci +0 -0
  20. package/bin/adr-related +0 -0
  21. package/bin/adr-renumber +254 -254
  22. package/bin/adr-retire +0 -0
  23. package/bin/adr-settings +0 -0
  24. package/bin/adr-status +0 -0
  25. package/bin/adr-suggest +0 -0
  26. package/bin/adr-watch +0 -0
  27. package/bin/adr_doctor_probes.py +2 -0
  28. package/bin/bump-version +0 -0
  29. package/clients/workflows.json +229 -229
  30. package/hooks/__init__.py +1 -1
  31. package/hooks/adapters/__init__.py +13 -13
  32. package/hooks/adapters/claude.py +27 -27
  33. package/hooks/adapters/codex.py +26 -26
  34. package/hooks/adapters/copilot.py +11 -11
  35. package/hooks/adr-hook.py +128 -128
  36. package/hooks/adr_hook_core.py +843 -843
  37. package/hooks/adr_pr_guard.py +367 -367
  38. package/instructions/ADR-guide.md +101 -48
  39. package/instructions/adr.coding.md +82 -82
  40. package/instructions/adr.review.md +182 -182
  41. package/opencode/plugin.ts +1 -4
  42. package/package.json +5 -2
  43. package/schemas/adr-context-probes.schema.json +56 -56
  44. package/schemas/adr-enforcement.schema.json +57 -57
  45. package/schemas/adr-frontmatter.schema.json +144 -144
  46. package/schemas/adr-index.schema.json +276 -276
  47. package/schemas/adr-kit-config.schema.json +371 -371
  48. package/schemas/adr-readiness.schema.json +41 -41
  49. package/schemas/client-capabilities.schema.json +503 -503
  50. package/schemas/client-certification.schema.json +101 -101
  51. package/schemas/doctor-output.schema.json +92 -92
  52. package/skills/adr/SKILL.md +780 -780
  53. package/skills/audit/SKILL.md +103 -103
  54. package/skills/context/SKILL.md +77 -77
  55. package/skills/grill/SKILL.md +84 -84
  56. package/skills/grill/agents/openai.yaml +4 -4
  57. package/skills/guardian/SKILL.md +316 -316
  58. package/skills/init/SKILL.md +499 -499
  59. package/skills/install-hooks/SKILL.md +154 -154
  60. package/skills/judge/SKILL.md +168 -168
  61. package/skills/lint/SKILL.md +321 -321
  62. package/skills/migrate/SKILL.md +313 -313
  63. package/skills/related/SKILL.md +62 -62
  64. package/skills/retire/SKILL.md +41 -41
  65. package/skills/review/SKILL.md +167 -167
  66. package/skills/settings/SKILL.md +73 -73
  67. package/skills/setup/SKILL.md +128 -128
  68. package/skills/supersede/SKILL.md +136 -136
  69. package/skills/upgrade/SKILL.md +273 -273
  70. package/templates/adr-kit-guide.md +354 -354
  71. package/templates/adr-template.canonical.md +115 -115
  72. package/templates/adr-template.madr.md +131 -131
  73. package/templates/adr-template.md +131 -131
  74. package/templates/adr-template.nygard.md +111 -111
  75. package/templates/cc-settings/guardian-hook-entry.json +9 -9
  76. package/templates/githooks/pre-commit +1 -1
  77. package/templates/github-workflows/adr-audit.yml +58 -58
  78. package/templates/github-workflows/adr-guardian-audit.yml +133 -133
  79. package/templates/github-workflows/adr-index-check.yml +30 -30
  80. package/templates/github-workflows/adr-judge.yml +31 -31
  81. package/templates/github-workflows/adr-readiness.yml +18 -18
  82. package/templates/validate_adr_template.py +38 -38
  83. package/templates/validate_adr_template.sh +74 -74
@@ -1,367 +1,367 @@
1
- """Judge the branch before a pull request exists (spec R2, TASK-76).
2
-
3
- The commit hook judges one commit. CI judges the pull request, but only once the
4
- pull request is there. Between those two sits the moment the change actually
5
- becomes a proposal: the agent runs `gh pr create`. In a coding harness that is a
6
- tool call, so a pre-tool hook can intercept it and judge the whole branch
7
- *before* the PR exists - earlier than CI can ever be.
8
-
9
- **Why this lives outside adr_hook_core.** The retrieval hooks are
10
- injection-only, model-free and forbidden by ADR-018's gate from importing
11
- anything that can reach a model or the network - `subprocess` included, because
12
- spawning a CLI is how this toolkit reaches a model. This guard must spawn
13
- `adr-judge`, so it lives in its own module with its own budget rather than
14
- weakening that assertion. Separate concerns, separate files, one gate that still
15
- means what it says.
16
-
17
- **This one may block, and that is the point.** Every other hook injects context
18
- and never interferes. A violation here is precisely the case where the coding
19
- agent should fix the code before proceeding, so a deny is the useful answer. It
20
- still fails open on anything that is not a violation: no judge, no git, no
21
- branch, a timeout - all let the command through, because a tool that cannot
22
- check must not pretend it did.
23
- """
24
-
25
- from __future__ import annotations
26
-
27
- import json
28
- import os
29
- import re
30
- import shutil
31
- import subprocess
32
- import time
33
- from pathlib import Path
34
- from typing import Dict, List, Optional, Tuple
35
-
36
- # Matching is on the command shape, not a substring. `gh pr create` must fire;
37
- # `gh pr list`, `gh pr view`, and a comment mentioning gh pr create must not.
38
- PR_CREATE_RE = re.compile(r"(?:^|[;&|]\s*)gh\s+pr\s+create\b")
39
-
40
- # The branch diff is the whole development branch, not one commit, so it needs
41
- # the CI-sized budget from TASK-73 rather than judge.max_diff_bytes.
42
- CI_DIFF_BUDGET = 33_554_432
43
-
44
- #: Seconds kept back from the runner budget for the time the guard does not
45
- #: control or measure: interpreter start, imports and the stdin read before
46
- #: `judge_branch` is reached, plus parsing the verdict and rendering the reason
47
- #: afterwards. Measured end to end on the Windows certification machine, a hook
48
- #: process that does no subprocess work costs 218 ms p50 and 257 ms p95, so one
49
- #: second is the reserve with room rather than a guess.
50
- #:
51
- #: The deadline deliberately starts at `judge_branch` rather than at import. An
52
- #: import-time origin measures the startup exactly and makes the module usable
53
- #: only once per process -- correct for a hook, wrong for anything that calls it
54
- #: twice, and the second call silently gets no budget at all. Paying for the
55
- #: startup out of a constant keeps the bound without that trap.
56
- GUARD_OVERHEAD_S = 1
57
-
58
- #: Below this a subprocess cannot usefully start, so the guard stops instead of
59
- #: launching one it will kill immediately.
60
- MIN_SUBPROCESS_S = 1
61
-
62
- #: Share of the remaining budget `git diff` may take. The judge is the part that
63
- #: produces a verdict, so it keeps the majority; reading the diff is setup.
64
- DIFF_BUDGET_SHARE = 0.4
65
-
66
- #: Used when the manifest cannot be read or declares no budget for this event.
67
- #: One second, because that is what the generator writes into hooks.json when
68
- #: `runner_timeout_sec` is absent (scripts/client_generation_artifacts.py), and
69
- #: that is the number the client actually enforces. Five of the eight manifest
70
- #: events omit the key today, so this is the live path rather than a corner.
71
- FALLBACK_BUDGET_S = 1
72
-
73
- #: The generator validates `runner_timeout_sec` as an int in 1..30 and refuses
74
- #: anything else. The guard reads the same field at run time from a file that
75
- #: may have been edited or shipped out of step with hooks.json, so it applies
76
- #: the same bounds -- otherwise `runner_timeout_sec: 600` hands the guard a
77
- #: 599 s deadline against whatever the client actually enforces, which is the
78
- #: original defect restored at a larger multiple.
79
- MAX_RUNNER_S = 30
80
-
81
-
82
- class Deadline:
83
- """One budget for the whole guard, spent down by each subprocess.
84
-
85
- Deriving the judge timeout alone was not enough, and the sweep that found
86
- the rest is the reason this class exists. Every call site carried its own
87
- constant -- `git diff` at 60 s, five `base_ref` probes at 10 s each -- so the
88
- worst case was 114 s of subprocess inside a 5 s budget, all of it invisible
89
- because the client kills the process before any of the fail-open branches
90
- run.
91
-
92
- A deadline makes the bound structural rather than a set of numbers somebody
93
- has to keep in agreement. `remaining()` is what is left of the budget; a
94
- call site that would start with nothing left gets `None` and the guard stops
95
- with a reason instead of launching a subprocess it is about to kill.
96
- """
97
-
98
- def __init__(self, seconds: int, start: Optional[float] = None) -> None:
99
- self._end = (time.monotonic() if start is None else start) + seconds
100
-
101
- def remaining(self) -> Optional[int]:
102
- left = int(self._end - time.monotonic())
103
- return left if left >= MIN_SUBPROCESS_S else None
104
-
105
-
106
- def guard_budget_s() -> int:
107
- """How long the whole guard may run, from the budget the client enforces.
108
-
109
- This was a standalone 120 s constant while `hooks/manifest.json` declared
110
- `runner_timeout_sec: 5` for `pr-create`, and the two could not both be
111
- right. The client kills the hook at its own timeout, so a judge allowed
112
- twenty-four times that never reaches the `except SubprocessError` branch
113
- below -- the process dies mid-call and the carefully written fail-open path
114
- never runs. The user sees nothing at all, which is indistinguishable from a
115
- clean branch.
116
-
117
- Deriving it removes the possibility of disagreement: whoever changes the
118
- manifest changes this, and a fail-open stays something this module does
119
- rather than something that happens to it.
120
-
121
- Note what this does not do. A 5 s budget cannot hold an LLM judge pass, so a
122
- project that has enabled one will see this time out and allow, with the
123
- reason stated. That is the honest outcome of the budget `hooks/manifest.json`
124
- declares for this event, and moving the budget is a decision rather than a
125
- patch.
126
- """
127
- manifest = Path(__file__).resolve().parent / "manifest.json"
128
- try:
129
- events = json.loads(manifest.read_text(encoding="utf-8"))["events"]
130
- runner = next(
131
- event["runner_timeout_sec"]
132
- for event in events
133
- if event.get("id") == "pr-create"
134
- )
135
- except (OSError, ValueError, KeyError, TypeError, StopIteration):
136
- return FALLBACK_BUDGET_S
137
- if isinstance(runner, bool) or not isinstance(runner, int):
138
- return FALLBACK_BUDGET_S
139
- if not 1 <= runner <= MAX_RUNNER_S:
140
- return FALLBACK_BUDGET_S
141
- return max(MIN_SUBPROCESS_S, runner - GUARD_OVERHEAD_S)
142
-
143
-
144
- def looks_like_pr_create(command: str) -> bool:
145
- return bool(PR_CREATE_RE.search(command or ""))
146
-
147
-
148
- def _run(argv: List[str], cwd: Path, timeout: int, stdin_text: Optional[str] = None):
149
- return subprocess.run(
150
- argv,
151
- cwd=str(cwd),
152
- input=stdin_text,
153
- capture_output=True,
154
- text=True,
155
- encoding="utf-8",
156
- errors="replace",
157
- timeout=timeout,
158
- check=False,
159
- )
160
-
161
-
162
- def base_ref(cwd: Path, deadline: "Deadline") -> Optional[str]:
163
- """The branch this PR would target, from the repository's own configuration."""
164
- for argv in (
165
- ["git", "symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"],
166
- ["git", "config", "--get", "init.defaultBranch"],
167
- ):
168
- left = deadline.remaining()
169
- if left is None:
170
- return None
171
- try:
172
- result = _run(argv, cwd, left)
173
- except (OSError, subprocess.SubprocessError):
174
- continue
175
- value = (result.stdout or "").strip()
176
- if result.returncode == 0 and value:
177
- return value.split("/")[-1]
178
- for candidate in ("main", "master", "dev"):
179
- try:
180
- left = deadline.remaining()
181
- if left is None:
182
- return None
183
- probe = _run(["git", "rev-parse", "--verify", f"origin/{candidate}"], cwd, left)
184
- except (OSError, subprocess.SubprocessError):
185
- return None
186
- if probe.returncode == 0:
187
- return candidate
188
- return None
189
-
190
-
191
- def _nudge(cwd: Path, adr_dir: Path, suggest: Path, diff_text: str, left: int) -> str:
192
- """The missing-decision half of R2, asked at the same moment as the verdict.
193
-
194
- Advisory by construction: this returns text or nothing, and no caller may
195
- turn it into a denial (ADR-024). A suggestion is a question about a decision
196
- nobody recorded, and blocking on one teaches people to write an empty ADR to
197
- get past it -- the failure mode that produced six rule-less Enforcement
198
- blocks in this very repository.
199
-
200
- It reuses the diff the judge already read and what is left of the same
201
- Deadline. A second `git diff` here would spend the budget twice on the same
202
- bytes, and the branches with the largest diffs are the ones most worth
203
- asking about.
204
- """
205
- import sys
206
-
207
- try:
208
- result = _run(
209
- [
210
- sys.executable, str(suggest),
211
- "--diff", "-",
212
- "--adr-dir", str(adr_dir),
213
- # Same reason as the judge's: killing the child does not reach
214
- # the model CLI it spawned.
215
- "--llm-timeout", str(left),
216
- ],
217
- cwd,
218
- left,
219
- stdin_text=diff_text,
220
- )
221
- except (OSError, subprocess.SubprocessError):
222
- return ""
223
- # stderr, not stdout. `emit_advisory` writes every line of the advisory to
224
- # stderr on purpose -- stdout stays pipe-clean so `--json` is usable in a
225
- # pipeline -- so filtering stdout matched nothing and the nudge could never
226
- # reach the user. ADR-024's feature was wired, tested at the unit level, and
227
- # dead end to end: the guard asked, adr-suggest answered, and the answer was
228
- # read from the wrong stream.
229
- lines = [
230
- line
231
- for line in (result.stderr or "").splitlines()
232
- if line.startswith("[adr-suggest] This change") or line.startswith("[adr-suggest] ")
233
- ]
234
- return "\n".join(lines)
235
-
236
-
237
- def judge_branch(
238
- cwd: Path, adr_dir: Path, judge: Path, suggest: Optional[Path] = None
239
- ) -> Dict:
240
- """Return a verdict dict. Every non-violation outcome is 'allow'."""
241
- if not judge.is_file():
242
- return {"decision": "allow", "reason": "adr-judge not found", "checked": False}
243
- if shutil.which("git") is None:
244
- return {"decision": "allow", "reason": "git not on PATH", "checked": False}
245
- deadline = Deadline(guard_budget_s())
246
- base = base_ref(cwd, deadline)
247
- if not base:
248
- return {"decision": "allow", "reason": "no base branch to compare against", "checked": False}
249
-
250
- left = deadline.remaining()
251
- if left is None:
252
- return {"decision": "allow", "reason": "ran out of budget before the diff", "checked": False}
253
- # Capped rather than given the remainder. Handing `git diff` everything left
254
- # lets a large branch consume the whole budget and starve the judge -- and
255
- # the branches with the largest diffs are the ones most worth checking, so
256
- # the failure would scale with how much it matters.
257
- try:
258
- diff = _run(
259
- ["git", "diff", "--unified=0", f"origin/{base}...HEAD"],
260
- cwd,
261
- max(MIN_SUBPROCESS_S, int(left * DIFF_BUDGET_SHARE)),
262
- )
263
- except (OSError, subprocess.SubprocessError) as exc:
264
- return {"decision": "allow", "reason": f"git diff failed ({exc})", "checked": False}
265
- if diff.returncode != 0:
266
- return {"decision": "allow", "reason": "git diff failed", "checked": False}
267
- if not (diff.stdout or "").strip():
268
- return {"decision": "allow", "reason": "empty branch diff", "checked": True}
269
-
270
- import sys
271
-
272
- left = deadline.remaining()
273
- if left is None:
274
- return {"decision": "allow", "reason": "ran out of budget before the judge", "checked": False}
275
- try:
276
- verdict = _run(
277
- [
278
- sys.executable, str(judge),
279
- "--diff", "-",
280
- "--adr-dir", str(adr_dir),
281
- "--repo-root", str(cwd),
282
- "--snapshot", "worktree",
283
- "--max-diff-bytes", str(CI_DIFF_BUDGET),
284
- # Bound the child's own model call by what is left of our
285
- # budget. Without it adr-judge starts an LLM call with a 120 s
286
- # default, and subprocess timeouts do not reach grandchildren:
287
- # killing the judge leaves the model CLI running, billing a
288
- # verdict nobody will read.
289
- "--llm-timeout", str(left),
290
- "--json",
291
- ],
292
- cwd,
293
- left,
294
- stdin_text=diff.stdout,
295
- )
296
- except (OSError, subprocess.SubprocessError) as exc:
297
- return {"decision": "allow", "reason": f"judge did not run ({exc})", "checked": False}
298
-
299
- def _with_nudge(result: Dict) -> Dict:
300
- """Attach the advisory nudge, never touching the decision."""
301
- if suggest is None or not suggest.is_file():
302
- return result
303
- left_now = deadline.remaining()
304
- if left_now is None:
305
- return result
306
- text = _nudge(cwd, adr_dir, suggest, diff.stdout, left_now)
307
- if text:
308
- result["nudge"] = text
309
- return result
310
-
311
- if verdict.returncode == 0:
312
- return _with_nudge(
313
- {"decision": "allow", "reason": "no violations on the branch", "checked": True}
314
- )
315
- if verdict.returncode != 1:
316
- # Exit 2 is a configuration or input problem, including a diff over the
317
- # cap. That is a fact about the invocation, not about the code, and
318
- # blocking on it would punish the wrong thing.
319
- return {
320
- "decision": "allow",
321
- "reason": f"judge could not complete (exit {verdict.returncode})",
322
- "checked": False,
323
- "stderr": (verdict.stderr or "").strip()[:400],
324
- }
325
-
326
- findings = _violations(verdict.stdout)
327
- return _with_nudge({
328
- "decision": "deny",
329
- "reason": _explain(findings, base),
330
- "checked": True,
331
- "violations": findings,
332
- })
333
-
334
-
335
- def _violations(stdout: str) -> List[Dict]:
336
- try:
337
- payload = json.loads(stdout or "{}")
338
- except (json.JSONDecodeError, ValueError):
339
- return []
340
- findings = payload.get("findings")
341
- if not isinstance(findings, list):
342
- return []
343
- return [f for f in findings if isinstance(f, dict) and f.get("severity") == "violation"]
344
-
345
-
346
- def _explain(findings: List[Dict], base: str) -> str:
347
- if not findings:
348
- return (
349
- f"The branch violates an Accepted ADR against origin/{base}. "
350
- "Run `adr-judge` on the branch diff for the detail."
351
- )
352
- lines = [
353
- f"This branch violates {len(findings)} Accepted ADR rule(s) against "
354
- f"origin/{base}. Fix the code before opening the pull request:",
355
- ]
356
- for finding in findings[:5]:
357
- where = finding.get("path") or "?"
358
- line = finding.get("line")
359
- location = f"{where}:{line}" if line else where
360
- lines.append(f" {finding.get('adr', '?')} {location} {finding.get('message', '')}".rstrip())
361
- if len(findings) > 5:
362
- lines.append(f" ... and {len(findings) - 5} more")
363
- lines.append(
364
- "If the decision itself is wrong, supersede it rather than working around "
365
- "it; if this is a deliberate exception, ADR_KIT_OVERRIDE records it."
366
- )
367
- return "\n".join(lines)
1
+ """Judge the branch before a pull request exists (spec R2, TASK-76).
2
+
3
+ The commit hook judges one commit. CI judges the pull request, but only once the
4
+ pull request is there. Between those two sits the moment the change actually
5
+ becomes a proposal: the agent runs `gh pr create`. In a coding harness that is a
6
+ tool call, so a pre-tool hook can intercept it and judge the whole branch
7
+ *before* the PR exists - earlier than CI can ever be.
8
+
9
+ **Why this lives outside adr_hook_core.** The retrieval hooks are
10
+ injection-only, model-free and forbidden by ADR-018's gate from importing
11
+ anything that can reach a model or the network - `subprocess` included, because
12
+ spawning a CLI is how this toolkit reaches a model. This guard must spawn
13
+ `adr-judge`, so it lives in its own module with its own budget rather than
14
+ weakening that assertion. Separate concerns, separate files, one gate that still
15
+ means what it says.
16
+
17
+ **This one may block, and that is the point.** Every other hook injects context
18
+ and never interferes. A violation here is precisely the case where the coding
19
+ agent should fix the code before proceeding, so a deny is the useful answer. It
20
+ still fails open on anything that is not a violation: no judge, no git, no
21
+ branch, a timeout - all let the command through, because a tool that cannot
22
+ check must not pretend it did.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import os
29
+ import re
30
+ import shutil
31
+ import subprocess
32
+ import time
33
+ from pathlib import Path
34
+ from typing import Dict, List, Optional, Tuple
35
+
36
+ # Matching is on the command shape, not a substring. `gh pr create` must fire;
37
+ # `gh pr list`, `gh pr view`, and a comment mentioning gh pr create must not.
38
+ PR_CREATE_RE = re.compile(r"(?:^|[;&|]\s*)gh\s+pr\s+create\b")
39
+
40
+ # The branch diff is the whole development branch, not one commit, so it needs
41
+ # the CI-sized budget from TASK-73 rather than judge.max_diff_bytes.
42
+ CI_DIFF_BUDGET = 33_554_432
43
+
44
+ #: Seconds kept back from the runner budget for the time the guard does not
45
+ #: control or measure: interpreter start, imports and the stdin read before
46
+ #: `judge_branch` is reached, plus parsing the verdict and rendering the reason
47
+ #: afterwards. Measured end to end on the Windows certification machine, a hook
48
+ #: process that does no subprocess work costs 218 ms p50 and 257 ms p95, so one
49
+ #: second is the reserve with room rather than a guess.
50
+ #:
51
+ #: The deadline deliberately starts at `judge_branch` rather than at import. An
52
+ #: import-time origin measures the startup exactly and makes the module usable
53
+ #: only once per process -- correct for a hook, wrong for anything that calls it
54
+ #: twice, and the second call silently gets no budget at all. Paying for the
55
+ #: startup out of a constant keeps the bound without that trap.
56
+ GUARD_OVERHEAD_S = 1
57
+
58
+ #: Below this a subprocess cannot usefully start, so the guard stops instead of
59
+ #: launching one it will kill immediately.
60
+ MIN_SUBPROCESS_S = 1
61
+
62
+ #: Share of the remaining budget `git diff` may take. The judge is the part that
63
+ #: produces a verdict, so it keeps the majority; reading the diff is setup.
64
+ DIFF_BUDGET_SHARE = 0.4
65
+
66
+ #: Used when the manifest cannot be read or declares no budget for this event.
67
+ #: One second, because that is what the generator writes into hooks.json when
68
+ #: `runner_timeout_sec` is absent (scripts/client_generation_artifacts.py), and
69
+ #: that is the number the client actually enforces. Five of the eight manifest
70
+ #: events omit the key today, so this is the live path rather than a corner.
71
+ FALLBACK_BUDGET_S = 1
72
+
73
+ #: The generator validates `runner_timeout_sec` as an int in 1..30 and refuses
74
+ #: anything else. The guard reads the same field at run time from a file that
75
+ #: may have been edited or shipped out of step with hooks.json, so it applies
76
+ #: the same bounds -- otherwise `runner_timeout_sec: 600` hands the guard a
77
+ #: 599 s deadline against whatever the client actually enforces, which is the
78
+ #: original defect restored at a larger multiple.
79
+ MAX_RUNNER_S = 30
80
+
81
+
82
+ class Deadline:
83
+ """One budget for the whole guard, spent down by each subprocess.
84
+
85
+ Deriving the judge timeout alone was not enough, and the sweep that found
86
+ the rest is the reason this class exists. Every call site carried its own
87
+ constant -- `git diff` at 60 s, five `base_ref` probes at 10 s each -- so the
88
+ worst case was 114 s of subprocess inside a 5 s budget, all of it invisible
89
+ because the client kills the process before any of the fail-open branches
90
+ run.
91
+
92
+ A deadline makes the bound structural rather than a set of numbers somebody
93
+ has to keep in agreement. `remaining()` is what is left of the budget; a
94
+ call site that would start with nothing left gets `None` and the guard stops
95
+ with a reason instead of launching a subprocess it is about to kill.
96
+ """
97
+
98
+ def __init__(self, seconds: int, start: Optional[float] = None) -> None:
99
+ self._end = (time.monotonic() if start is None else start) + seconds
100
+
101
+ def remaining(self) -> Optional[int]:
102
+ left = int(self._end - time.monotonic())
103
+ return left if left >= MIN_SUBPROCESS_S else None
104
+
105
+
106
+ def guard_budget_s() -> int:
107
+ """How long the whole guard may run, from the budget the client enforces.
108
+
109
+ This was a standalone 120 s constant while `hooks/manifest.json` declared
110
+ `runner_timeout_sec: 5` for `pr-create`, and the two could not both be
111
+ right. The client kills the hook at its own timeout, so a judge allowed
112
+ twenty-four times that never reaches the `except SubprocessError` branch
113
+ below -- the process dies mid-call and the carefully written fail-open path
114
+ never runs. The user sees nothing at all, which is indistinguishable from a
115
+ clean branch.
116
+
117
+ Deriving it removes the possibility of disagreement: whoever changes the
118
+ manifest changes this, and a fail-open stays something this module does
119
+ rather than something that happens to it.
120
+
121
+ Note what this does not do. A 5 s budget cannot hold an LLM judge pass, so a
122
+ project that has enabled one will see this time out and allow, with the
123
+ reason stated. That is the honest outcome of the budget `hooks/manifest.json`
124
+ declares for this event, and moving the budget is a decision rather than a
125
+ patch.
126
+ """
127
+ manifest = Path(__file__).resolve().parent / "manifest.json"
128
+ try:
129
+ events = json.loads(manifest.read_text(encoding="utf-8"))["events"]
130
+ runner = next(
131
+ event["runner_timeout_sec"]
132
+ for event in events
133
+ if event.get("id") == "pr-create"
134
+ )
135
+ except (OSError, ValueError, KeyError, TypeError, StopIteration):
136
+ return FALLBACK_BUDGET_S
137
+ if isinstance(runner, bool) or not isinstance(runner, int):
138
+ return FALLBACK_BUDGET_S
139
+ if not 1 <= runner <= MAX_RUNNER_S:
140
+ return FALLBACK_BUDGET_S
141
+ return max(MIN_SUBPROCESS_S, runner - GUARD_OVERHEAD_S)
142
+
143
+
144
+ def looks_like_pr_create(command: str) -> bool:
145
+ return bool(PR_CREATE_RE.search(command or ""))
146
+
147
+
148
+ def _run(argv: List[str], cwd: Path, timeout: int, stdin_text: Optional[str] = None):
149
+ return subprocess.run(
150
+ argv,
151
+ cwd=str(cwd),
152
+ input=stdin_text,
153
+ capture_output=True,
154
+ text=True,
155
+ encoding="utf-8",
156
+ errors="replace",
157
+ timeout=timeout,
158
+ check=False,
159
+ )
160
+
161
+
162
+ def base_ref(cwd: Path, deadline: "Deadline") -> Optional[str]:
163
+ """The branch this PR would target, from the repository's own configuration."""
164
+ for argv in (
165
+ ["git", "symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"],
166
+ ["git", "config", "--get", "init.defaultBranch"],
167
+ ):
168
+ left = deadline.remaining()
169
+ if left is None:
170
+ return None
171
+ try:
172
+ result = _run(argv, cwd, left)
173
+ except (OSError, subprocess.SubprocessError):
174
+ continue
175
+ value = (result.stdout or "").strip()
176
+ if result.returncode == 0 and value:
177
+ return value.split("/")[-1]
178
+ for candidate in ("main", "master", "dev"):
179
+ try:
180
+ left = deadline.remaining()
181
+ if left is None:
182
+ return None
183
+ probe = _run(["git", "rev-parse", "--verify", f"origin/{candidate}"], cwd, left)
184
+ except (OSError, subprocess.SubprocessError):
185
+ return None
186
+ if probe.returncode == 0:
187
+ return candidate
188
+ return None
189
+
190
+
191
+ def _nudge(cwd: Path, adr_dir: Path, suggest: Path, diff_text: str, left: int) -> str:
192
+ """The missing-decision half of R2, asked at the same moment as the verdict.
193
+
194
+ Advisory by construction: this returns text or nothing, and no caller may
195
+ turn it into a denial (ADR-024). A suggestion is a question about a decision
196
+ nobody recorded, and blocking on one teaches people to write an empty ADR to
197
+ get past it -- the failure mode that produced six rule-less Enforcement
198
+ blocks in this very repository.
199
+
200
+ It reuses the diff the judge already read and what is left of the same
201
+ Deadline. A second `git diff` here would spend the budget twice on the same
202
+ bytes, and the branches with the largest diffs are the ones most worth
203
+ asking about.
204
+ """
205
+ import sys
206
+
207
+ try:
208
+ result = _run(
209
+ [
210
+ sys.executable, str(suggest),
211
+ "--diff", "-",
212
+ "--adr-dir", str(adr_dir),
213
+ # Same reason as the judge's: killing the child does not reach
214
+ # the model CLI it spawned.
215
+ "--llm-timeout", str(left),
216
+ ],
217
+ cwd,
218
+ left,
219
+ stdin_text=diff_text,
220
+ )
221
+ except (OSError, subprocess.SubprocessError):
222
+ return ""
223
+ # stderr, not stdout. `emit_advisory` writes every line of the advisory to
224
+ # stderr on purpose -- stdout stays pipe-clean so `--json` is usable in a
225
+ # pipeline -- so filtering stdout matched nothing and the nudge could never
226
+ # reach the user. ADR-024's feature was wired, tested at the unit level, and
227
+ # dead end to end: the guard asked, adr-suggest answered, and the answer was
228
+ # read from the wrong stream.
229
+ lines = [
230
+ line
231
+ for line in (result.stderr or "").splitlines()
232
+ if line.startswith("[adr-suggest] This change") or line.startswith("[adr-suggest] ")
233
+ ]
234
+ return "\n".join(lines)
235
+
236
+
237
+ def judge_branch(
238
+ cwd: Path, adr_dir: Path, judge: Path, suggest: Optional[Path] = None
239
+ ) -> Dict:
240
+ """Return a verdict dict. Every non-violation outcome is 'allow'."""
241
+ if not judge.is_file():
242
+ return {"decision": "allow", "reason": "adr-judge not found", "checked": False}
243
+ if shutil.which("git") is None:
244
+ return {"decision": "allow", "reason": "git not on PATH", "checked": False}
245
+ deadline = Deadline(guard_budget_s())
246
+ base = base_ref(cwd, deadline)
247
+ if not base:
248
+ return {"decision": "allow", "reason": "no base branch to compare against", "checked": False}
249
+
250
+ left = deadline.remaining()
251
+ if left is None:
252
+ return {"decision": "allow", "reason": "ran out of budget before the diff", "checked": False}
253
+ # Capped rather than given the remainder. Handing `git diff` everything left
254
+ # lets a large branch consume the whole budget and starve the judge -- and
255
+ # the branches with the largest diffs are the ones most worth checking, so
256
+ # the failure would scale with how much it matters.
257
+ try:
258
+ diff = _run(
259
+ ["git", "diff", "--unified=0", f"origin/{base}...HEAD"],
260
+ cwd,
261
+ max(MIN_SUBPROCESS_S, int(left * DIFF_BUDGET_SHARE)),
262
+ )
263
+ except (OSError, subprocess.SubprocessError) as exc:
264
+ return {"decision": "allow", "reason": f"git diff failed ({exc})", "checked": False}
265
+ if diff.returncode != 0:
266
+ return {"decision": "allow", "reason": "git diff failed", "checked": False}
267
+ if not (diff.stdout or "").strip():
268
+ return {"decision": "allow", "reason": "empty branch diff", "checked": True}
269
+
270
+ import sys
271
+
272
+ left = deadline.remaining()
273
+ if left is None:
274
+ return {"decision": "allow", "reason": "ran out of budget before the judge", "checked": False}
275
+ try:
276
+ verdict = _run(
277
+ [
278
+ sys.executable, str(judge),
279
+ "--diff", "-",
280
+ "--adr-dir", str(adr_dir),
281
+ "--repo-root", str(cwd),
282
+ "--snapshot", "worktree",
283
+ "--max-diff-bytes", str(CI_DIFF_BUDGET),
284
+ # Bound the child's own model call by what is left of our
285
+ # budget. Without it adr-judge starts an LLM call with a 120 s
286
+ # default, and subprocess timeouts do not reach grandchildren:
287
+ # killing the judge leaves the model CLI running, billing a
288
+ # verdict nobody will read.
289
+ "--llm-timeout", str(left),
290
+ "--json",
291
+ ],
292
+ cwd,
293
+ left,
294
+ stdin_text=diff.stdout,
295
+ )
296
+ except (OSError, subprocess.SubprocessError) as exc:
297
+ return {"decision": "allow", "reason": f"judge did not run ({exc})", "checked": False}
298
+
299
+ def _with_nudge(result: Dict) -> Dict:
300
+ """Attach the advisory nudge, never touching the decision."""
301
+ if suggest is None or not suggest.is_file():
302
+ return result
303
+ left_now = deadline.remaining()
304
+ if left_now is None:
305
+ return result
306
+ text = _nudge(cwd, adr_dir, suggest, diff.stdout, left_now)
307
+ if text:
308
+ result["nudge"] = text
309
+ return result
310
+
311
+ if verdict.returncode == 0:
312
+ return _with_nudge(
313
+ {"decision": "allow", "reason": "no violations on the branch", "checked": True}
314
+ )
315
+ if verdict.returncode != 1:
316
+ # Exit 2 is a configuration or input problem, including a diff over the
317
+ # cap. That is a fact about the invocation, not about the code, and
318
+ # blocking on it would punish the wrong thing.
319
+ return {
320
+ "decision": "allow",
321
+ "reason": f"judge could not complete (exit {verdict.returncode})",
322
+ "checked": False,
323
+ "stderr": (verdict.stderr or "").strip()[:400],
324
+ }
325
+
326
+ findings = _violations(verdict.stdout)
327
+ return _with_nudge({
328
+ "decision": "deny",
329
+ "reason": _explain(findings, base),
330
+ "checked": True,
331
+ "violations": findings,
332
+ })
333
+
334
+
335
+ def _violations(stdout: str) -> List[Dict]:
336
+ try:
337
+ payload = json.loads(stdout or "{}")
338
+ except (json.JSONDecodeError, ValueError):
339
+ return []
340
+ findings = payload.get("findings")
341
+ if not isinstance(findings, list):
342
+ return []
343
+ return [f for f in findings if isinstance(f, dict) and f.get("severity") == "violation"]
344
+
345
+
346
+ def _explain(findings: List[Dict], base: str) -> str:
347
+ if not findings:
348
+ return (
349
+ f"The branch violates an Accepted ADR against origin/{base}. "
350
+ "Run `adr-judge` on the branch diff for the detail."
351
+ )
352
+ lines = [
353
+ f"This branch violates {len(findings)} Accepted ADR rule(s) against "
354
+ f"origin/{base}. Fix the code before opening the pull request:",
355
+ ]
356
+ for finding in findings[:5]:
357
+ where = finding.get("path") or "?"
358
+ line = finding.get("line")
359
+ location = f"{where}:{line}" if line else where
360
+ lines.append(f" {finding.get('adr', '?')} {location} {finding.get('message', '')}".rstrip())
361
+ if len(findings) > 5:
362
+ lines.append(f" ... and {len(findings) - 5} more")
363
+ lines.append(
364
+ "If the decision itself is wrong, supersede it rather than working around "
365
+ "it; if this is a deliberate exception, ADR_KIT_OVERRIDE records it."
366
+ )
367
+ return "\n".join(lines)