@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,275 @@
1
+ #!/usr/bin/env python3
2
+ """adr-quality: Score an ADR file on quality via 4 gates, each 0.0-1.0.
3
+
4
+ Usage:
5
+ adr-quality docs/adr/ADR-042-foo.md
6
+ adr-quality --format json docs/adr/ADR-042-foo.md
7
+ adr-quality --format text docs/adr/ADR-042-foo.md # default
8
+
9
+ Exit codes:
10
+ 0 overall >= 0.70 (grade B or better)
11
+ 1 overall < 0.70 (grade C or D)
12
+ 2 file not found or unreadable
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import importlib.machinery
19
+ import importlib.util
20
+ import json
21
+ import re
22
+ import sys
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from typing import Dict, List, Optional
26
+
27
+ _BIN_DIR = Path(__file__).resolve().parent
28
+
29
+
30
+ def _load_sibling(name: str):
31
+ """Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
32
+
33
+ SEC-HIGH (TASK-62): `sys.path.insert(0, _BIN_DIR)` put this directory ahead
34
+ of the standard library for every import, so a module committed next to
35
+ this script executed as code -- and it re-added the very directory
36
+ CPython's -P / PYTHONSAFEPATH removes. Siblings are registered in
37
+ sys.modules under their bare name, so the plain `from adr_* import ...`
38
+ statements below (and the lazy ones inside functions) resolve from the
39
+ cache instead of the path. bin/adr-judge carries the full rationale.
40
+ """
41
+ cached = sys.modules.get(name)
42
+ if cached is not None:
43
+ return cached
44
+ loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
45
+ spec = importlib.util.spec_from_loader(name, loader)
46
+ module = importlib.util.module_from_spec(spec)
47
+ sys.modules[name] = module
48
+ loader.exec_module(module)
49
+ return module
50
+
51
+
52
+ _load_sibling("adr_format")
53
+
54
+ from adr_format import detect_profile, required_headings, section_text
55
+
56
+ _load_sibling("adr_quality_core")
57
+
58
+ from adr_quality_core import ( # noqa: E402
59
+ QUALITY_THRESHOLD,
60
+ REQUIRED_SECTIONS,
61
+ QualityIssue,
62
+ _extract_adr_id,
63
+ _grade,
64
+ _recommendations_from_issues,
65
+ _section_text,
66
+ gate_clarity,
67
+ gate_completeness,
68
+ gate_consistency,
69
+ gate_evidence,
70
+ score_adr_quality,
71
+ score_directory,
72
+ score_path,
73
+ )
74
+
75
+
76
+ def _count_checks_passed(gate_result: Dict) -> str:
77
+ checks = gate_result.get("checks", {})
78
+ if not checks:
79
+ return "0/0"
80
+ passed = sum(1 for v in checks.values() if v)
81
+ total = len(checks)
82
+ return f"{passed}/{total}"
83
+
84
+
85
+ def _render_text(adr_id: str, result: Dict) -> str:
86
+ overall = result["overall"]
87
+ grade = result["grade"]
88
+ gates = result["gates"]
89
+
90
+ lines = [
91
+ f"Quality Score: {adr_id} -- {overall:.2f} ({grade})",
92
+ "=" * 46,
93
+ ]
94
+
95
+ gate_order = [
96
+ ("completeness", "Completeness"),
97
+ ("evidence", "Evidence"),
98
+ ("clarity", "Clarity"),
99
+ ("consistency", "Consistency"),
100
+ ]
101
+ for key, label in gate_order:
102
+ g = gates[key]
103
+ score_str = f"{g['score']:.2f}"
104
+ checks_str = _count_checks_passed(g)
105
+ if g["issues"]:
106
+ issue_msgs = [issue.message() for issue in g["issues"][:2]]
107
+ issue_summary = "; ".join(issue_msgs)
108
+ else:
109
+ issue_summary = "ok"
110
+ if len(issue_summary) > 50:
111
+ issue_summary = issue_summary[:47] + "..."
112
+ lines.append(f" {label:<16} {score_str} [{checks_str} checks passed] {issue_summary}")
113
+
114
+ if result["issues"]:
115
+ lines.append("")
116
+ lines.append("Issues:")
117
+ for issue in result["issues"]:
118
+ lines.append(f" [{issue.severity.upper()}] {issue.message()}")
119
+
120
+ if result["recommendations"]:
121
+ lines.append("")
122
+ lines.append("Recommendations:")
123
+ for rec in result["recommendations"]:
124
+ lines.append(f" - {rec}")
125
+
126
+ return "\n".join(lines)
127
+
128
+
129
+ def _serialize_gates(gates: Dict) -> Dict:
130
+ """Convert QualityIssue objects in each gate to plain dicts for JSON."""
131
+ out: Dict = {}
132
+ for name, gate_result in gates.items():
133
+ out[name] = {
134
+ "score": gate_result["score"],
135
+ "issues": [issue.to_dict() for issue in gate_result["issues"]],
136
+ "checks": gate_result["checks"],
137
+ }
138
+ return out
139
+
140
+
141
+ def _render_json(adr_id: str, result: Dict) -> str:
142
+ output = {
143
+ "adr_id": adr_id,
144
+ "overall": result["overall"],
145
+ "grade": result["grade"],
146
+ "gates": _serialize_gates(result["gates"]),
147
+ "issues": [issue.to_dict() for issue in result["issues"]],
148
+ "recommendations": result["recommendations"],
149
+ }
150
+ return json.dumps(output, indent=2, ensure_ascii=False)
151
+
152
+
153
+ def _run_sweep(args) -> int:
154
+ """Score a whole directory and report what has decayed.
155
+
156
+ Quality is checked once, at acceptance, and then frozen. An ADR does not
157
+ stay sharp on its own: the code moves, the references rot, the alternatives
158
+ stop being the live ones. This is how that becomes visible instead of
159
+ assumed, and it is free -- four deterministic gates, no model.
160
+
161
+ Exit 1 when anything is under the threshold, so a caller can gate on it.
162
+ """
163
+ adr_dir = Path(args.adr_dir)
164
+ if not adr_dir.is_dir():
165
+ print(f"adr-quality: not a directory: {adr_dir}", file=sys.stderr)
166
+ return 2
167
+ threshold = args.below if args.below is not None else QUALITY_THRESHOLD
168
+ scores = score_directory(adr_dir, statuses=args.status)
169
+ rows = sorted(
170
+ (
171
+ {
172
+ "adr_id": adr_id,
173
+ "overall": round(float(result["overall"]), 3),
174
+ "grade": result["grade"],
175
+ "below_threshold": float(result["overall"]) < threshold,
176
+ }
177
+ for adr_id, result in scores.items()
178
+ ),
179
+ key=lambda row: (row["overall"], row["adr_id"]),
180
+ )
181
+ decayed = [row for row in rows if row["below_threshold"]]
182
+
183
+ if args.format == "json":
184
+ print(json.dumps(
185
+ {
186
+ "adr_dir": str(adr_dir),
187
+ "threshold": threshold,
188
+ "statuses": args.status,
189
+ "scored": len(rows),
190
+ "below_threshold": len(decayed),
191
+ "results": rows,
192
+ },
193
+ indent=2, ensure_ascii=False,
194
+ ))
195
+ else:
196
+ scope = ", ".join(args.status) if args.status else "every status"
197
+ print(f"adr-quality sweep: {len(rows)} ADR(s) ({scope}), threshold {threshold:.2f}")
198
+ for row in rows:
199
+ marker = "DECAYED" if row["below_threshold"] else "ok "
200
+ print(f" {marker} {row['adr_id']} {row['overall']:.2f} {row['grade']}")
201
+ if decayed:
202
+ print(
203
+ f" {len(decayed)} record(s) below threshold: grill or supersede them."
204
+ )
205
+ return 1 if decayed else 0
206
+
207
+
208
+ def main(argv: Optional[List[str]] = None) -> int:
209
+ parser = argparse.ArgumentParser(
210
+ prog="adr-quality",
211
+ description="Score an ADR file on quality via 4 gates.",
212
+ )
213
+ parser.add_argument(
214
+ "file",
215
+ nargs="?",
216
+ help="Path to the ADR file to score",
217
+ )
218
+ parser.add_argument(
219
+ "--adr-dir",
220
+ default=None,
221
+ help=(
222
+ "Score every ADR in this directory instead of one file. This is the "
223
+ "decay sweep: an Accepted record is scored once, at acceptance, and "
224
+ "then never again unless something asks."
225
+ ),
226
+ )
227
+ parser.add_argument(
228
+ "--status",
229
+ action="append",
230
+ default=None,
231
+ help="With --adr-dir, restrict to these statuses. Repeatable.",
232
+ )
233
+ parser.add_argument(
234
+ "--below",
235
+ type=float,
236
+ default=None,
237
+ help=f"With --adr-dir, report only scores under this (default {QUALITY_THRESHOLD}).",
238
+ )
239
+ parser.add_argument(
240
+ "--format", choices=["text", "json"], default="text",
241
+ help="Output format (default: text)",
242
+ )
243
+ parser.add_argument(
244
+ "--version", action="version", version="adr-quality 0.15.0",
245
+ )
246
+ args = parser.parse_args(argv)
247
+
248
+ if args.adr_dir:
249
+ return _run_sweep(args)
250
+ if not args.file:
251
+ parser.error("give a file, or --adr-dir to sweep a directory")
252
+
253
+ adr_path = Path(args.file)
254
+ if not adr_path.exists():
255
+ print(f"adr-quality: file not found: {adr_path}", file=sys.stderr)
256
+ return 2
257
+ try:
258
+ content = adr_path.read_text(encoding="utf-8", errors="replace")
259
+ except OSError as e:
260
+ print(f"adr-quality: cannot read {adr_path}: {e}", file=sys.stderr)
261
+ return 2
262
+
263
+ adr_id = _extract_adr_id(adr_path)
264
+ result = score_adr_quality(content, adr_path)
265
+
266
+ if args.format == "json":
267
+ print(_render_json(adr_id, result))
268
+ else:
269
+ print(_render_text(adr_id, result))
270
+
271
+ return 0 if result["overall"] >= 0.70 else 1
272
+
273
+
274
+ if __name__ == "__main__":
275
+ sys.exit(main())
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env python3
2
+ """Inspect ADR readiness without mutating repository or lifecycle state."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import importlib.machinery
8
+ import importlib.util
9
+ import io
10
+ import json
11
+ import subprocess
12
+ import sys
13
+ from datetime import date
14
+ from pathlib import Path
15
+ from typing import List, Sequence, Tuple
16
+
17
+ _BIN_DIR = Path(__file__).resolve().parent
18
+
19
+
20
+ def _load_sibling(name: str):
21
+ """Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
22
+
23
+ SEC-HIGH (TASK-62): this script carried no sys.path.insert, but it still
24
+ resolved its siblings through CPython's implicit sys.path[0] -- the script's
25
+ own directory. That is the same shadowing surface the insert created (a
26
+ module committed next to this file wins over the standard library), and it
27
+ meant the script could not run under -P / PYTHONSAFEPATH at all. Siblings
28
+ are registered in sys.modules under their bare name so the plain
29
+ `from adr_* import ...` below resolves from the cache instead of the path.
30
+ bin/adr-judge carries the full rationale.
31
+ """
32
+ cached = sys.modules.get(name)
33
+ if cached is not None:
34
+ return cached
35
+ loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
36
+ spec = importlib.util.spec_from_loader(name, loader)
37
+ module = importlib.util.module_from_spec(spec)
38
+ sys.modules[name] = module
39
+ loader.exec_module(module)
40
+ return module
41
+
42
+
43
+ # Dependency order: adr_catalog needs adr_format + adr_schema;
44
+ # adr_readiness needs adr_catalog.
45
+ _load_sibling("adr_format")
46
+ _load_sibling("adr_schema")
47
+ _load_sibling("adr_catalog")
48
+ _load_sibling("adr_quality_core")
49
+ _load_sibling("adr_readiness")
50
+
51
+
52
+ from adr_readiness import ReadinessError, build_readiness_report, normalize_path
53
+
54
+
55
+ def _ensure_utf8_streams() -> None:
56
+ for stream in (sys.stdout, sys.stderr):
57
+ if hasattr(stream, "reconfigure"):
58
+ try:
59
+ stream.reconfigure(encoding="utf-8")
60
+ except (AttributeError, io.UnsupportedOperation):
61
+ pass
62
+
63
+
64
+ def _git_diff(root: Path, base: str | None, head: str | None) -> Tuple[List[str], str]:
65
+ if base or head:
66
+ if not (base and head):
67
+ raise ReadinessError("--base and --head must be supplied together")
68
+ range_args: Sequence[str] = (f"{base}...{head}",)
69
+ else:
70
+ range_args = ("--cached",)
71
+ names = subprocess.run(
72
+ ["git", "diff", "--name-only", "-M", *range_args],
73
+ cwd=root,
74
+ capture_output=True,
75
+ text=True,
76
+ encoding="utf-8",
77
+ errors="replace",
78
+ timeout=10,
79
+ )
80
+ diff = subprocess.run(
81
+ ["git", "diff", "--unified=0", "-M", *range_args],
82
+ cwd=root,
83
+ capture_output=True,
84
+ text=True,
85
+ encoding="utf-8",
86
+ errors="replace",
87
+ timeout=10,
88
+ )
89
+ if names.returncode != 0 or diff.returncode != 0:
90
+ error = names.stderr.strip() or diff.stderr.strip() or "git diff failed"
91
+ raise ReadinessError(error)
92
+ paths = sorted(
93
+ {normalize_path(line) for line in names.stdout.splitlines() if line.strip()},
94
+ key=str.casefold,
95
+ )
96
+ return paths, diff.stdout
97
+
98
+
99
+ def _human(report: dict) -> str:
100
+ lines = [
101
+ f"ADR readiness ({report['evaluated_on']}): {report['summary']['total']} record(s)"
102
+ ]
103
+ for item in report["adrs"]:
104
+ lines.append(
105
+ f"- {item['adr_id']} [{item['status']}] {item['classification']}: "
106
+ f"{item['title']}"
107
+ )
108
+ for finding in item["mechanical_findings"] + item["human_findings"]:
109
+ lines.append(f" {finding['code']}: {finding['message']}")
110
+ if item["implementation_link"]["blocking_proposed"]:
111
+ lines.append(" LINKED_PROPOSED_IMPLEMENTATION: merge readiness is blocked")
112
+ if item["next_command"]:
113
+ lines.append(f" Next: {item['next_command']}")
114
+ for advisory in report["advisories"]:
115
+ lines.append(
116
+ f"- {advisory['code']}: {advisory['path']}: {advisory['message']}"
117
+ )
118
+ return "\n".join(lines)
119
+
120
+
121
+ def _safe_markdown(value: object) -> str:
122
+ return (
123
+ str(value)
124
+ .replace("\r", " ")
125
+ .replace("\n", " ")
126
+ .replace("`", "'")
127
+ .replace("<", "&lt;")
128
+ .replace(">", "&gt;")
129
+ )
130
+
131
+
132
+ def _github(report: dict) -> str:
133
+ lines = ["## ADR readiness", "", f"Evaluated: `{report['evaluated_on']}`", ""]
134
+ for item in report["adrs"]:
135
+ icon = "[BLOCK]" if item["implementation_link"]["blocking_proposed"] else "[INFO]"
136
+ lines.append(
137
+ f"- {icon} **{item['adr_id']}** - `{item['classification']}` - "
138
+ f"{_safe_markdown(item['title'])}"
139
+ )
140
+ if item["next_command"]:
141
+ lines.append(f" - Next: `{_safe_markdown(item['next_command'])}`")
142
+ for advisory in report["advisories"]:
143
+ lines.append(
144
+ f"- [ADVISORY] `{advisory['code']}` - `{_safe_markdown(advisory['path'])}` - "
145
+ f"{_safe_markdown(advisory['message'])}"
146
+ )
147
+ if not report["adrs"]:
148
+ lines.append("- No ADR readiness findings.")
149
+ return "\n".join(lines)
150
+
151
+
152
+ def build_parser() -> argparse.ArgumentParser:
153
+ parser = argparse.ArgumentParser(description=__doc__)
154
+ parser.add_argument("adr", nargs="?", help="ADR identifier such as ADR-011")
155
+ parser.add_argument("--all-proposed", action="store_true")
156
+ parser.add_argument("--diff", action="store_true", help="analyze the staged diff")
157
+ parser.add_argument("--base")
158
+ parser.add_argument("--head")
159
+ parser.add_argument("--format", choices=("human", "json", "github"), default="human")
160
+ parser.add_argument("--repo-root", default=".")
161
+ parser.add_argument("--adr-dir", default="docs/adr")
162
+ parser.add_argument("--today", help="evaluation date in YYYY-MM-DD format")
163
+ return parser
164
+
165
+
166
+ def main(argv: List[str] | None = None) -> int:
167
+ _ensure_utf8_streams()
168
+ args = build_parser().parse_args(argv)
169
+ try:
170
+ if args.adr and args.all_proposed:
171
+ raise ReadinessError("ADR id and --all-proposed are mutually exclusive")
172
+ root = Path(args.repo_root).expanduser().resolve()
173
+ if not root.is_dir():
174
+ raise ReadinessError(f"repository root not found: {root}")
175
+ adr_dir_input = Path(args.adr_dir).expanduser()
176
+ adr_dir = (
177
+ adr_dir_input.resolve()
178
+ if adr_dir_input.is_absolute()
179
+ else (root / adr_dir_input).resolve()
180
+ )
181
+ if not adr_dir.is_dir():
182
+ raise ReadinessError(f"ADR directory not found: {adr_dir}")
183
+ evaluated_on = date.fromisoformat(args.today) if args.today else date.today()
184
+ use_diff = args.diff or args.base is not None or args.head is not None
185
+ paths, diff_text = _git_diff(root, args.base, args.head) if use_diff else ([], "")
186
+ report = build_readiness_report(
187
+ adr_dir,
188
+ evaluated_on=evaluated_on,
189
+ adr_id=args.adr,
190
+ all_proposed=args.all_proposed,
191
+ changed_paths=paths,
192
+ source_text=diff_text,
193
+ )
194
+ try:
195
+ report["adr_dir"] = normalize_path(str(adr_dir.relative_to(root)))
196
+ except ValueError:
197
+ report["adr_dir"] = normalize_path(adr_dir.name)
198
+ except (ReadinessError, ValueError, OSError, subprocess.TimeoutExpired) as exc:
199
+ print(f"adr-readiness: {exc}", file=sys.stderr)
200
+ return 2
201
+ if args.format == "json":
202
+ print(json.dumps(report, indent=2, ensure_ascii=False, sort_keys=True))
203
+ elif args.format == "github":
204
+ print(_github(report))
205
+ else:
206
+ print(_human(report))
207
+ return 0
208
+
209
+
210
+ if __name__ == "__main__":
211
+ sys.exit(main())
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env python3
2
+ """Run PR readiness and publish GitHub summary, annotations, and outputs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import importlib.machinery
8
+ import importlib.util
9
+ import json
10
+ import subprocess
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ _BIN_DIR = Path(__file__).resolve().parent
15
+
16
+
17
+ def _load_sibling(name: str):
18
+ """Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
19
+
20
+ SEC-HIGH (TASK-62): this script carried no sys.path.insert, but it still
21
+ resolved its siblings through CPython's implicit sys.path[0] -- the script's
22
+ own directory. That is the same shadowing surface the insert created (a
23
+ module committed next to this file wins over the standard library), and it
24
+ meant the script could not run under -P / PYTHONSAFEPATH at all. Siblings
25
+ are registered in sys.modules under their bare name so the plain
26
+ `from adr_* import ...` below resolves from the cache instead of the path.
27
+ bin/adr-judge carries the full rationale.
28
+ """
29
+ cached = sys.modules.get(name)
30
+ if cached is not None:
31
+ return cached
32
+ loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
33
+ spec = importlib.util.spec_from_loader(name, loader)
34
+ module = importlib.util.module_from_spec(spec)
35
+ sys.modules[name] = module
36
+ loader.exec_module(module)
37
+ return module
38
+
39
+
40
+ _load_sibling("adr_readiness_ci")
41
+
42
+
43
+ from adr_readiness_ci import annotations, output_values, render_summary, write_outputs
44
+
45
+
46
+ def main() -> int:
47
+ parser = argparse.ArgumentParser(description=__doc__)
48
+ parser.add_argument("--repo-root", default=".")
49
+ parser.add_argument("--adr-dir", default="docs/adr")
50
+ parser.add_argument("--base", required=True)
51
+ parser.add_argument("--head", required=True)
52
+ parser.add_argument("--today", default=None)
53
+ parser.add_argument("--summary-file", default=None)
54
+ parser.add_argument("--output-file", default=None)
55
+ args = parser.parse_args()
56
+ root = Path(args.repo_root).expanduser().resolve()
57
+ command = [
58
+ sys.executable,
59
+ str(Path(__file__).resolve().with_name("adr-readiness")),
60
+ "--all-proposed",
61
+ "--base",
62
+ args.base,
63
+ "--head",
64
+ args.head,
65
+ "--repo-root",
66
+ str(root),
67
+ "--adr-dir",
68
+ args.adr_dir,
69
+ "--format",
70
+ "json",
71
+ ]
72
+ if args.today:
73
+ command.extend(["--today", args.today])
74
+ try:
75
+ result = subprocess.run(
76
+ command,
77
+ cwd=root,
78
+ capture_output=True,
79
+ text=True,
80
+ encoding="utf-8",
81
+ errors="replace",
82
+ timeout=30,
83
+ )
84
+ if result.returncode != 0:
85
+ message = result.stderr.strip() or f"adr-readiness exited {result.returncode}"
86
+ print(f"::error title=ADR readiness infrastructure::{message}")
87
+ return 2
88
+ report = json.loads(result.stdout)
89
+ summary = render_summary(report)
90
+ if args.summary_file:
91
+ with Path(args.summary_file).open("a", encoding="utf-8", newline="\n") as stream:
92
+ stream.write(summary)
93
+ else:
94
+ print(summary, end="")
95
+ if args.output_file:
96
+ write_outputs(Path(args.output_file), output_values(report))
97
+ for line in annotations(report):
98
+ print(line)
99
+ return 1 if report.get("summary", {}).get("blocking_count", 0) else 0
100
+ except (
101
+ OSError,
102
+ ValueError,
103
+ json.JSONDecodeError,
104
+ subprocess.TimeoutExpired,
105
+ ) as exc:
106
+ print(f"::error title=ADR readiness infrastructure::{exc}")
107
+ return 2
108
+
109
+
110
+ if __name__ == "__main__":
111
+ raise SystemExit(main())