@rvdbreemen/adr-kit-opencode 0.52.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 (129) hide show
  1. package/.claude-plugin/plugin.json +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +850 -0
  4. package/bin/adr +1552 -0
  5. package/bin/adr-audit +454 -0
  6. package/bin/adr-context +584 -0
  7. package/bin/adr-discover +546 -0
  8. package/bin/adr-doctor +166 -0
  9. package/bin/adr-generate-scripts +421 -0
  10. package/bin/adr-grill-signal +131 -0
  11. package/bin/adr-guardian +1263 -0
  12. package/bin/adr-index +199 -0
  13. package/bin/adr-judge +2832 -0
  14. package/bin/adr-judge-precommit +87 -0
  15. package/bin/adr-lint +2087 -0
  16. package/bin/adr-mcp +1093 -0
  17. package/bin/adr-migrate +644 -0
  18. package/bin/adr-quality +275 -0
  19. package/bin/adr-readiness +211 -0
  20. package/bin/adr-readiness-ci +111 -0
  21. package/bin/adr-related +401 -0
  22. package/bin/adr-renumber +254 -0
  23. package/bin/adr-retire +467 -0
  24. package/bin/adr-settings +399 -0
  25. package/bin/adr-status +797 -0
  26. package/bin/adr-suggest +803 -0
  27. package/bin/adr-watch +674 -0
  28. package/bin/adr_catalog.py +536 -0
  29. package/bin/adr_config.py +280 -0
  30. package/bin/adr_doctor_checks.py +407 -0
  31. package/bin/adr_doctor_core.py +342 -0
  32. package/bin/adr_doctor_models.py +186 -0
  33. package/bin/adr_doctor_probes.py +216 -0
  34. package/bin/adr_format.py +786 -0
  35. package/bin/adr_grill_signal.py +123 -0
  36. package/bin/adr_guardian_queue.py +218 -0
  37. package/bin/adr_history_scan.py +278 -0
  38. package/bin/adr_index_core.py +443 -0
  39. package/bin/adr_llm.py +333 -0
  40. package/bin/adr_llm_judge_migration.py +314 -0
  41. package/bin/adr_quality_core.py +674 -0
  42. package/bin/adr_query.py +678 -0
  43. package/bin/adr_readiness.py +442 -0
  44. package/bin/adr_readiness_ci.py +123 -0
  45. package/bin/adr_regex.py +165 -0
  46. package/bin/adr_regex_worker.py +30 -0
  47. package/bin/adr_retrieval_health.py +385 -0
  48. package/bin/adr_schema.py +448 -0
  49. package/bin/adr_state.py +172 -0
  50. package/bin/bump-version +71 -0
  51. package/clients/workflows.json +229 -0
  52. package/hooks/__init__.py +1 -0
  53. package/hooks/adapters/__init__.py +13 -0
  54. package/hooks/adapters/claude.py +27 -0
  55. package/hooks/adapters/codex.py +26 -0
  56. package/hooks/adapters/copilot.py +11 -0
  57. package/hooks/adr-hook.py +128 -0
  58. package/hooks/adr_hook_core.py +843 -0
  59. package/hooks/adr_pr_guard.py +367 -0
  60. package/instructions/ADR-guide.md +48 -0
  61. package/instructions/adr.coding.md +82 -0
  62. package/instructions/adr.review.md +182 -0
  63. package/opencode/plugin.ts +451 -0
  64. package/package.json +41 -0
  65. package/schemas/adr-context-probes.schema.json +56 -0
  66. package/schemas/adr-enforcement.schema.json +57 -0
  67. package/schemas/adr-frontmatter.schema.json +144 -0
  68. package/schemas/adr-index.schema.json +276 -0
  69. package/schemas/adr-kit-config.schema.json +371 -0
  70. package/schemas/adr-readiness.schema.json +41 -0
  71. package/schemas/client-capabilities.schema.json +503 -0
  72. package/schemas/client-certification.schema.json +101 -0
  73. package/schemas/doctor-output.schema.json +92 -0
  74. package/schemas/marketplace.json.schema.json +70 -0
  75. package/schemas/plugin.json.schema.json +67 -0
  76. package/scripts/adr_settings.py +239 -0
  77. package/scripts/benchmark-adr-grilling.py +323 -0
  78. package/scripts/benchmark-client-generation.py +178 -0
  79. package/scripts/build-client-adapters.py +139 -0
  80. package/scripts/bump-version.py +304 -0
  81. package/scripts/check-branch-sync.py +243 -0
  82. package/scripts/check-release-version.py +81 -0
  83. package/scripts/client_certification.py +153 -0
  84. package/scripts/client_evidence.py +280 -0
  85. package/scripts/client_generation.py +288 -0
  86. package/scripts/client_generation_artifacts.py +351 -0
  87. package/scripts/client_generation_model.py +173 -0
  88. package/scripts/client_generation_state.py +260 -0
  89. package/scripts/client_support_matrix.py +360 -0
  90. package/scripts/install-agent-envs.py +300 -0
  91. package/scripts/probe-client-events.py +183 -0
  92. package/scripts/project_setup.py +379 -0
  93. package/scripts/refresh-otgw-corpus.py +219 -0
  94. package/scripts/settings.py +81 -0
  95. package/scripts/setup-project.py +205 -0
  96. package/scripts/sync-agent-plugins.py +17 -0
  97. package/scripts/version_sites.py +377 -0
  98. package/skills/adr/SKILL.md +780 -0
  99. package/skills/audit/SKILL.md +103 -0
  100. package/skills/context/SKILL.md +77 -0
  101. package/skills/grill/SKILL.md +84 -0
  102. package/skills/grill/agents/openai.yaml +4 -0
  103. package/skills/guardian/SKILL.md +316 -0
  104. package/skills/init/SKILL.md +499 -0
  105. package/skills/install-hooks/SKILL.md +154 -0
  106. package/skills/judge/SKILL.md +168 -0
  107. package/skills/lint/SKILL.md +321 -0
  108. package/skills/migrate/SKILL.md +313 -0
  109. package/skills/related/SKILL.md +62 -0
  110. package/skills/retire/SKILL.md +41 -0
  111. package/skills/review/SKILL.md +167 -0
  112. package/skills/settings/SKILL.md +73 -0
  113. package/skills/setup/SKILL.md +128 -0
  114. package/skills/supersede/SKILL.md +136 -0
  115. package/skills/upgrade/SKILL.md +273 -0
  116. package/templates/adr-kit-guide.md +354 -0
  117. package/templates/adr-template.canonical.md +115 -0
  118. package/templates/adr-template.madr.md +131 -0
  119. package/templates/adr-template.md +131 -0
  120. package/templates/adr-template.nygard.md +111 -0
  121. package/templates/cc-settings/guardian-hook-entry.json +9 -0
  122. package/templates/githooks/pre-commit +337 -0
  123. package/templates/github-workflows/adr-audit.yml +58 -0
  124. package/templates/github-workflows/adr-guardian-audit.yml +133 -0
  125. package/templates/github-workflows/adr-index-check.yml +30 -0
  126. package/templates/github-workflows/adr-judge.yml +31 -0
  127. package/templates/github-workflows/adr-readiness.yml +18 -0
  128. package/templates/validate_adr_template.py +38 -0
  129. package/templates/validate_adr_template.sh +74 -0
@@ -0,0 +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)
@@ -0,0 +1,48 @@
1
+ <!-- adr-kit-guide v0.35.0 -->
2
+ <!-- Generated ADR Kit guidance. Local additions belong in .adr-kit/ADR-guide.local.md. -->
3
+
4
+ # ADR Kit agent guide
5
+
6
+ Architecture decisions live in `docs/adr/`. Read the source ADR before treating
7
+ a generated summary as binding.
8
+
9
+ ## Before implementation
10
+
11
+ 1. Query the task with `adr-kit:context` or `bin/adr-context`.
12
+ 2. Read the returned Accepted ADRs.
13
+ 3. If the work introduces or changes a long-lived decision, use `adr-kit:adr`
14
+ and keep the new record Proposed until a human accepts it.
15
+
16
+ ## During implementation
17
+
18
+ - Treat hook-provided ADR context as advisory steering. Hooks fail open.
19
+ - Treat deterministic pre-commit enforcement as the blocking floor.
20
+ - Never rewrite an Accepted ADR. Create a Proposed successor and use the
21
+ supersession lifecycle.
22
+ - Keep generated indexes and client artifacts deterministic; edit their
23
+ canonical sources instead.
24
+
25
+ ## Before completion
26
+
27
+ 1. Run strict ADR lint and the relevant focused tests.
28
+ 2. Regenerate `docs/adr/ADR-INDEX.md`, `docs/adr/ADR-INDEX.json`, and the
29
+ generated README block after ADR changes.
30
+ 3. Use `adr-kit:judge` or `bin/adr-judge` to check the staged diff.
31
+ 4. Record the decision, evidence, and verification in the project task.
32
+
33
+ ## Ownership
34
+
35
+ `.adr-kit/ADR-guide.md` is generated and may be replaced after backup.
36
+ Put project-specific guidance in `.adr-kit/ADR-guide.local.md` or outside ADR
37
+ Kit marker blocks in `AGENTS.md`, `CLAUDE.md`, and Copilot instructions.
38
+
39
+ If `.adr-kit/ADR-guide.local.md` exists, read it after this file. It is
40
+ user-owned and ADR Kit never overwrites or removes it.
41
+
42
+ ## Judgment
43
+
44
+ Deterministic ADR checks remain available without a model. Paid or cloud model
45
+ judgment is opt-in. Local judgment is active only when a configured or
46
+ unambiguously discovered provider/model identity has been verified. Missing,
47
+ ambiguous, or unreachable models are degraded optional judgment, never a
48
+ successful judgment result.
@@ -0,0 +1,82 @@
1
+ # ADR Rules for Coding Work
2
+
3
+ When you are about to implement or change code, run through these rules **before** writing.
4
+
5
+ ## Before implementing
6
+
7
+ - **Check for existing ADRs**: scan `docs/adr/` for an ADR that governs the area you are about to touch. The fastest path: read `docs/adr/README.md` index, then open the relevant ADRs.
8
+ - **Assess architectural significance**: does the change affect any of the following?
9
+ - Architecture: service or module boundaries, deployment topology, integration patterns
10
+ - Non-functional requirements: security, availability, performance, privacy, resilience
11
+ - Interfaces and contracts: public APIs, message topics, RPC contracts, breaking changes
12
+ - Dependencies: new framework, new library, swap-out with broad impact
13
+ - Build and tooling: build system, CI gates, development workflow
14
+
15
+ If yes, an ADR is in scope. If clearly no (bug fix, refactor that preserves contract, doc fix), skip the ADR work.
16
+ - **Use the canonical guide**: `docs/adr/README.md` is the source of truth for the project's ADR conventions. The ADR `SKILL.md` installed by Claude Code, Codex, or GitHub Copilot CLI is the comprehensive how-to.
17
+
18
+ ## Creating a new ADR
19
+
20
+ If no ADR exists and the change is architecturally significant:
21
+
22
+ 1. **Hand the work to the ADR generator subagent** (`adr-generator`). Provide it with the title, decision, alternatives, constraints, and any related ADRs. The agent writes a fully-formed ADR file at `docs/adr/ADR-XXX-title.md`.
23
+ 2. **Review the generated ADR yourself** before linking from code: confirm it passes the four verification gates (Completeness, Evidence, Clarity, Consistency) defined in the skill.
24
+ 3. **Reference the ADR** in your commit message and (if relevant) the PR description: `ADR: docs/adr/ADR-XXX-title.md`.
25
+ 4. **Add code comments** that point to the ADR at non-obvious enforcement sites: `// See ADR-XXX for why we use this pattern.`
26
+ 5. **Add an Enforcement block (v0.12+) when the rule has any code surface.** Accepted ADRs SHOULD carry an `## Enforcement` section. Three patterns:
27
+ - **Declarative** (`forbid_pattern` / `forbid_import` / `require_pattern`) — regex/glob rules that `bin/adr-judge` runs at commit time. Preferred when expressible; fast, no LLM round-trip.
28
+ - **`"llm_judge": true`** — for rules that need a model's judgement (semantic compliance, intent reading). The pre-commit hook batches all `llm_judge: true` ADRs into ONE Claude Sonnet call (`claude -p --model claude-sonnet-4-6`) and blocks the commit on `VIOLATION` when the LLM pass is active. As of v0.17.0 the LLM pass is opt-in: enable via `judge.llm_enabled:true` in `.adr-kit.json`, or `ADR_KIT_LLM=1` for a single commit. Falls back to declarative-only when the `claude` CLI is missing — never blocks on tooling drift. The same engine drives `/adr-kit:judge` (which always fires the LLM pass regardless of config) so verdicts are consistent across hook and skill.
29
+ - **Section omitted** — for governance / process ADRs with no code surface. Add a one-line explanation in the body so reviewers (Check 7) know it's intentional.
30
+
31
+ Schema: `schemas/adr-enforcement.schema.json`. Canonical guide: `.claude/adr-kit-guide.md` after `/adr-kit:init`.
32
+
33
+ ## Superseding an existing ADR
34
+
35
+ If your change reverses or replaces an `Accepted` ADR:
36
+
37
+ 1. **Do not modify the accepted ADR's decision text or reasoning.** ADRs are immutable once `Accepted`, except for the Status line and an appended `## Status History` transition.
38
+ 2. **Write a new superseding ADR** that explains: (a) what is changing, (b) why the original choice no longer fits, (c) what the new choice is, (d) the migration path if consumers are affected.
39
+ 3. **Update status without rewriting history**: set the old ADR's Status line to `Superseded by ADR-YYY` and append the matching `status_history` entry. Rationale lives in the new ADR.
40
+ 4. **Cross-link** in both ADRs' `## Related Decisions` sections.
41
+
42
+ ## Amending (vs superseding)
43
+
44
+ Some ADRs have a stable contract but a narrow scope-change. The toolkit distinguishes:
45
+
46
+ - **Supersede**: the old decision is no longer in force. Status line of old ADR: `Superseded by ADR-YYY`.
47
+ - **Amend**: the old decision still stands, but a specific aspect is narrowed or extended. Status line of old ADR: `Amended by ADR-YYY` (optional: leave `Accepted` if amend is content-additive only).
48
+
49
+ Use amend when the existing ADR's other consumers should not have to change. Use supersede when the contract itself is replaced.
50
+
51
+ ## Implementation checklist
52
+
53
+ For every commit that lands an architecturally significant change:
54
+
55
+ - [ ] An ADR exists or has been created via the adr-generator agent
56
+ - [ ] The ADR follows the project structure in `docs/adr/README.md`
57
+ - [ ] At least 2 alternatives are documented with rejection reasoning
58
+ - [ ] Consequences include both positive and negative impacts; risks have mitigations
59
+ - [ ] The four verification gates from the skill all pass
60
+ - [ ] Commit message and PR description link to the ADR
61
+ - [ ] If superseding, the old ADR's Status line and appended Status History entry are updated and cross-references are in place
62
+ - [ ] Code comments point at the ADR at non-obvious enforcement sites
63
+
64
+ ## Definition of Done
65
+
66
+ - ADR exists, is readable, and is reachable from `docs/adr/README.md`
67
+ - ADR focuses on rationale ("why"), not implementation detail ("how")
68
+ - The PR or commit links to the ADR by path
69
+ - Supersession or amendment chain is correct (if applicable)
70
+ - ADR has no placeholders, no `TODO:` markers, no em dashes
71
+
72
+ ## When the ADR rule does not apply
73
+
74
+ Skip the ADR work for:
75
+
76
+ - Bug fixes that do not change a contract
77
+ - Refactors that preserve external behaviour
78
+ - Documentation updates (unless the doc *is* an ADR)
79
+ - Configuration tweaks within an existing range
80
+ - Minor feature additions that fit an established pattern
81
+
82
+ If you are unsure, default to creating an ADR. The cost of writing one is 15 to 30 minutes; the cost of re-deriving the rationale 6 months from now is hours. (See the Anti-Rationalization Guards table in `SKILL.md`.)
@@ -0,0 +1,182 @@
1
+ # ADR Checks for Code Review
2
+
3
+ When you are reviewing a PR or a diff, run these seven checks for ADR compliance. The canonical guide is `docs/adr/README.md`; the comprehensive skill is `SKILL.md`. Check 7 was added in adr-kit v0.12.0 alongside the declarative Enforcement-block engine in `bin/adr-judge`.
4
+
5
+ ## Check 1: ADR exists for architecturally significant changes
6
+
7
+ If the diff touches any of:
8
+
9
+ - **Architecture**: service or module boundaries, deployment, integration patterns
10
+ - **Non-functional requirements**: security, availability, performance, privacy, resilience
11
+ - **Interfaces and contracts**: API behaviour, message topics, RPC contracts, breaking changes
12
+ - **Dependencies**: new frameworks or libraries with broad impact
13
+ - **Build and tooling**: build system, CI gates, development workflow
14
+
15
+ then there should be a linked ADR.
16
+
17
+ **Action if missing:**
18
+
19
+ - Request an ADR. Be specific about which decision should be captured.
20
+ - Suggest the `adr-generator` subagent for fast scaffolding.
21
+
22
+ ## Check 2: ADR is properly linked
23
+
24
+ Verify the PR description includes:
25
+
26
+ - A path to the ADR: `docs/adr/ADR-XXX-title.md`
27
+ - A clear explanation of how the diff relates to the ADR
28
+ - If implementing a `Proposed` ADR, check whether the Status should flip to `Accepted` in this PR
29
+
30
+ **Action if link is missing or unclear:**
31
+
32
+ - Request the ADR link in the PR description.
33
+ - Ask for one sentence connecting the code change to the ADR's decision.
34
+
35
+ ## Check 3: No ADR violations
36
+
37
+ Check whether the diff violates an `Accepted` ADR:
38
+
39
+ - Cross-reference `docs/adr/README.md` for relevant ADRs to the touched files
40
+ - Check ADR-specific compliance for ADRs that include enforcement rules
41
+ - Verify the change follows patterns established by `Accepted` ADRs
42
+
43
+ **Action if violation found:**
44
+
45
+ - *Option 1*: request alignment with the existing ADR.
46
+ - *Option 2*: request a new superseding ADR if the decision needs to change.
47
+ - Always explain *why* the change conflicts with the documented decision.
48
+
49
+ ## Check 4: Supersession is correct
50
+
51
+ If the PR supersedes an existing ADR:
52
+
53
+ - Verify the new ADR includes a `## Related Decisions` entry "Supersedes ADR-XXX"
54
+ - Verify the old ADR's Status line is updated to `Superseded by ADR-YYY` and its `## Status History` has a matching appended transition
55
+ - Verify the supersession rationale appears in the new ADR (not the old one)
56
+ - Verify the old ADR's content (context, decision, alternatives, consequences) and earlier history entries are **not modified**. Only the Status line and one appended transition may change.
57
+
58
+ **Action if supersession is incorrect:**
59
+
60
+ - Request proper supersession linking.
61
+ - If the old ADR's content was edited, request a revert of that part.
62
+
63
+ ## Check 5: ADR quality (the four verification gates)
64
+
65
+ Apply the four named gates from `SKILL.md`:
66
+
67
+ - **Completeness gate**: problem stated, decision unambiguous, 2+ alternatives with rejection reasoning, consequences in both directions, risks named with mitigations.
68
+ - **Evidence gate**: bare adjectives replaced with measurements; constraint claims anchored to a source; code references include `file:line`; external claims linked.
69
+ - **Clarity gate**: acronyms defined on first use, technical concepts explained when load-bearing, decision explainable in one paragraph at the top.
70
+ - **Consistency gate**: no conflict with another `Accepted` ADR (or explicit supersede), cross-references present, terminology matches other ADRs, ADR number sequential.
71
+
72
+ **Action if a gate fails:**
73
+
74
+ - Cite the failing gate by name: "This ADR fails the Evidence gate. Please add a measurement to back the 'reduces fragmentation' claim."
75
+ - Suggest a fix.
76
+ - Reference an existing ADR in the project as a positive example, if available.
77
+
78
+ ## Check 6: Legacy non-compliance
79
+
80
+ If existing code does not comply with a *new* ADR:
81
+
82
+ - Acknowledge the legacy non-compliance explicitly.
83
+ - Request a remediation plan: an incremental cleanup, a tech-debt issue with a target version, or an explicit "out of scope for this PR" note.
84
+ - Do not block the ADR adoption itself due to legacy issues.
85
+ - Ensure the *new* code in this PR complies.
86
+
87
+ ## Check 7: Enforcement block (v0.12+)
88
+
89
+ Every new `Accepted` ADR with a code surface SHOULD include an `## Enforcement` section so the pre-commit hook can guard the boundary. Three acceptable patterns:
90
+
91
+ - **Declarative rules.** A fenced JSON block with `forbid_pattern` / `forbid_import` / `require_pattern` arrays. `bin/adr-judge` runs them deterministically on the staged diff at commit time. Preferred when the rule is mechanically expressible — fastest path, no LLM round-trip.
92
+ - **`"llm_judge": true`.** Free-form ADRs whose rules cannot be expressed as regex but are still code-relevant. The pre-commit hook batches all `llm_judge` ADRs into ONE Claude Sonnet call and blocks the commit on `VIOLATION` when the LLM pass is active. As of v0.17.0 the LLM pass is opt-in (off by default); enable via `judge.llm_enabled:true` in `.adr-kit.json`, or `ADR_KIT_LLM=1` for a single commit. `/adr-kit:judge` always runs the LLM pass on demand regardless of that setting. Falls back to declarative-only when the `claude` CLI is missing — never blocks on tooling drift. Cost shape when enabled: ~$0.10–0.30 per commit on Sonnet 4.6 with prompt caching.
93
+ - **Section omitted.** ADRs with no code surface (governance, process, organisational decisions). The judge skips them silently. The PR author should explain in the ADR body *why* the rule isn't mechanically expressible.
94
+
95
+ **Action if missing on a code-touching ADR:**
96
+
97
+ - Request an Enforcement block. Suggest one of the three patterns based on the rule's shape.
98
+ - Reference an existing ADR in the project that already has a good declarative block, if available.
99
+ - Reject "we'll add it later" — adding the block is part of the original Definition of Done. Without it, drift is silent.
100
+
101
+ ## Review-comment templates
102
+
103
+ ### Missing ADR
104
+
105
+ ```
106
+ This change introduces a new caching pattern, which affects architecture.
107
+ Please create an ADR documenting:
108
+ - Why caching is needed (context, constraints)
109
+ - Cache options considered (Redis, Memcached, in-memory)
110
+ - Chosen approach and rationale
111
+ - Consequences (performance gains, memory and complexity costs)
112
+
113
+ The adr-generator subagent can scaffold this. See SKILL.md for the template.
114
+ ```
115
+
116
+ ### ADR violation
117
+
118
+ ```
119
+ This change uses pattern X in performance-critical code, which violates
120
+ ADR-NNN (Title). Two options:
121
+
122
+ 1. Refactor to follow ADR-NNN's pattern.
123
+ 2. Write a superseding ADR if the decision needs to change.
124
+
125
+ ADR-NNN: docs/adr/ADR-NNN-title.md
126
+ ```
127
+
128
+ ### Supersession issue
129
+
130
+ ```
131
+ This ADR supersedes ADR-OLD but ADR-OLD has not been updated.
132
+
133
+ Please:
134
+ 1. Update ADR-OLD Status line to "Superseded by ADR-NEW".
135
+ 2. Confirm ADR-OLD's content (context, decision, alternatives, consequences)
136
+ is unchanged. ADR immutability is the rule; only the Status line moves.
137
+ 3. Cross-reference both ADRs in their `## Related Decisions` sections.
138
+ ```
139
+
140
+ ### Verification gate failure
141
+
142
+ ```
143
+ This ADR's Evidence gate fails. Two specific spots:
144
+
145
+ 1. "Improves performance" (line N): replace with a measurement
146
+ ("reduces request latency from X to Y") or a benchmark reference.
147
+ 2. "Memory constraint requires this" (line M): cite where (datasheet,
148
+ measured, vendor doc) and how much.
149
+
150
+ ADR-NNN in this repo is a good positive reference for the Evidence gate.
151
+ ```
152
+
153
+ ### Missing Enforcement block
154
+
155
+ ```
156
+ This ADR has a clear code surface (touches src/X, governs Y) but no
157
+ ## Enforcement section. Without one, the pre-commit hook can't guard
158
+ the boundary and silent drift will accumulate.
159
+
160
+ Please add one of the three patterns:
161
+
162
+ - Declarative rules in a fenced JSON block (forbid_pattern, forbid_import,
163
+ require_pattern). Preferred if the rule can be expressed as regex/glob.
164
+ - `"llm_judge": true` — for nuanced rules that need a model's judgement.
165
+ Deep review still happens via /adr-kit:judge in a Claude Code session.
166
+ - Omit the section AND add a one-line explanation in the ADR body for
167
+ why the rule has no code surface (governance / process / etc.).
168
+
169
+ Schema: schemas/adr-enforcement.schema.json
170
+ Reference example: ADR-NNN in this repo.
171
+ ```
172
+
173
+ ## Definition of Done for review
174
+
175
+ - [ ] Architecturally significant changes have a linked ADR
176
+ - [ ] ADR link is in the PR description
177
+ - [ ] No `Accepted` ADR is violated, or a superseding ADR is in place
178
+ - [ ] Supersession chain is correct
179
+ - [ ] All four verification gates pass on the ADR
180
+ - [ ] Legacy non-compliance, if any, has a remediation plan
181
+ - [ ] Code comments at non-obvious enforcement sites point at the ADR
182
+ - [ ] New `Accepted` ADRs with a code surface include an `## Enforcement` block (declarative rules OR `"llm_judge": true` OR explicit "no code surface" note)