@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,442 @@
1
+ """Deterministic, read-only ADR readiness and implementation-link analysis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import re
7
+ from datetime import date
8
+ from pathlib import Path
9
+ from typing import Dict, List, Optional, Sequence
10
+
11
+ from adr_catalog import build_relationships, load_adr_records, normalize_adr_id
12
+ from adr_format import all_open_questions
13
+ from adr_quality_core import QUALITY_THRESHOLD, score_path
14
+
15
+
16
+ def _open_questions_resolved(record: Dict, adr_dir: Optional[Path] = None) -> bool:
17
+ """True when this record has no question still open AND kept its answers.
18
+
19
+ The old reading was `not record["open_questions"]`, which an answered
20
+ question and a deleted one both satisfy -- so deleting was the cheap way to
21
+ score, while `bin/adr answer` was the expensive one (ADR-022).
22
+
23
+ A record that never carried a question is still resolved: there is nothing
24
+ to preserve. What changes is the record that HAD questions, where at least
25
+ one must survive in answered form.
26
+ """
27
+ if record.get("open_questions"):
28
+ return False
29
+ path = record.get("path")
30
+ if not path:
31
+ return True
32
+ try:
33
+ source = Path(path)
34
+ if not source.is_absolute() and adr_dir is not None:
35
+ source = Path(adr_dir) / source
36
+ text = source.read_text(encoding="utf-8", errors="replace")
37
+ except (OSError, TypeError, ValueError):
38
+ # Cannot read the body: fall back to the old reading rather than
39
+ # inventing a failure from a file-system problem.
40
+ return True
41
+ questions = all_open_questions(text)
42
+ if not questions:
43
+ return True
44
+ return any(questions.values())
45
+
46
+
47
+ def _scored_quality(record: Dict, adr_dir: Optional[Path] = None) -> Optional[float]:
48
+ """The weighted four-gate score for this record, or None if unreadable.
49
+
50
+ Records carry a bare filename, so the directory has to come from the
51
+ caller. Without it every score silently fell back to the three booleans --
52
+ a fallback that looks like a number and is not the one it claims to be.
53
+ """
54
+ raw = record.get("path")
55
+ if not raw:
56
+ return None
57
+ path = Path(str(raw))
58
+ if not path.is_absolute() and adr_dir is not None and not path.exists():
59
+ path = Path(adr_dir) / path.name
60
+ result = score_path(path)
61
+ if not result:
62
+ return None
63
+ try:
64
+ return round(float(result["overall"]), 3)
65
+ except (KeyError, TypeError, ValueError):
66
+ return None
67
+
68
+
69
+ READINESS_SCHEMA_VERSION = 1
70
+ READINESS_CLASSES = (
71
+ "not-an-adr",
72
+ "needs-human-input",
73
+ "needs-mechanical-fix",
74
+ "ready-for-confirmation",
75
+ "accepted",
76
+ "rejected",
77
+ "supersession-required",
78
+ )
79
+ FINDING_CODES = (
80
+ "ADR_FILE_CHANGED",
81
+ "ADR_ID_EXPLICIT",
82
+ "ARCHITECTURE_REVIEW_RECOMMENDED",
83
+ "DECISION_MISSING",
84
+ "ENFORCEMENT_SCOPE_CHANGED",
85
+ "FORMAT_UNKNOWN",
86
+ "FRONTMATTER_MALFORMED",
87
+ "OPEN_QUESTION",
88
+ "STATUS_UNKNOWN",
89
+ "SUPERSESSION_STATE_INCONSISTENT",
90
+ "VERIFIED_IN_CHANGED",
91
+ )
92
+
93
+ _ADR_TOKEN_RE = re.compile(r"\bADR-0*(\d{1,4})\b", re.IGNORECASE)
94
+ _ARCHITECTURE_PATH_RE = re.compile(
95
+ r"(^|/)(?:architecture|infra(?:structure)?|migrations?|schemas?|"
96
+ r"api|contracts?|config|deploy|security)(?:/|[-_.])|"
97
+ r"(^|/)(?:dockerfile|compose\.ya?ml|pyproject\.toml|package\.json|"
98
+ r"Cargo\.toml|go\.mod)$",
99
+ re.IGNORECASE,
100
+ )
101
+
102
+
103
+ class ReadinessError(ValueError):
104
+ """Raised when readiness input cannot be analyzed safely."""
105
+
106
+
107
+ def normalize_path(value: str) -> str:
108
+ """Return a portable repository-relative path representation."""
109
+ normalized = value.replace("\\", "/").strip()
110
+ while normalized.startswith("./"):
111
+ normalized = normalized[2:]
112
+ return re.sub(r"/+", "/", normalized)
113
+
114
+
115
+ def explicit_adr_ids(text: str) -> List[str]:
116
+ return sorted(
117
+ {f"ADR-{int(match.group(1)):03d}" for match in _ADR_TOKEN_RE.finditer(text)}
118
+ )
119
+
120
+
121
+ def implementation_evidence(
122
+ record: Dict,
123
+ changed_paths: Sequence[str],
124
+ source_text: str = "",
125
+ *,
126
+ paths_normalized: bool = False,
127
+ path_pairs: Optional[Sequence[tuple[str, str]]] = None,
128
+ cited_ids: Optional[Sequence[str]] = None,
129
+ adr_dir: Optional[Path] = None,
130
+ ) -> Dict:
131
+ """Return explicit, inspectable evidence for one ADR implementation link."""
132
+ adr_id = record["adr_id"]
133
+ paths = (
134
+ list(changed_paths)
135
+ if paths_normalized
136
+ else sorted(
137
+ {normalize_path(path) for path in changed_paths if path}, key=str.casefold
138
+ )
139
+ )
140
+ pairs = (
141
+ list(path_pairs)
142
+ if path_pairs is not None
143
+ else [(path, path.casefold()) for path in paths]
144
+ )
145
+ referenced_ids = (
146
+ set(cited_ids) if cited_ids is not None else set(explicit_adr_ids(source_text))
147
+ )
148
+ adr_filename = str(record["path"]).replace("\\", "/").rsplit("/", 1)[-1].casefold()
149
+ adr_file_changed = any(
150
+ path.rsplit("/", 1)[-1].casefold() == adr_filename for path in paths
151
+ )
152
+ verified_targets = tuple(
153
+ normalize_path(str(target)) for target in record.get("verified_in", [])
154
+ )
155
+ scope_targets = tuple(normalize_path(str(target)) for target in record.get("scope", []))
156
+
157
+ def matches(targets: Sequence[str]) -> List[str]:
158
+ exact = tuple(
159
+ (target.casefold(), target.rstrip("/").casefold() + "/")
160
+ for target in targets
161
+ if target and not any(char in target for char in "*?[")
162
+ )
163
+ patterns = tuple(
164
+ target.casefold()
165
+ for target in targets
166
+ if target and any(char in target for char in "*?[")
167
+ )
168
+ result = []
169
+ for path, folded in pairs:
170
+ if any(folded == target or folded.startswith(prefix) for target, prefix in exact):
171
+ result.append(path)
172
+ elif any(fnmatch.fnmatchcase(folded, pattern) for pattern in patterns):
173
+ result.append(path)
174
+ return result
175
+
176
+ verified_matches = matches(verified_targets)
177
+ scope_matches = matches(scope_targets)
178
+ implementation_paths = sorted(
179
+ {
180
+ path
181
+ for path in verified_matches + scope_matches
182
+ if not path.casefold().startswith("docs/adr/")
183
+ },
184
+ key=str.casefold,
185
+ )
186
+ explicit_reference = adr_id in referenced_ids
187
+ linked = bool(
188
+ implementation_paths
189
+ and (explicit_reference or adr_file_changed or verified_matches)
190
+ )
191
+ evidence: List[Dict[str, object]] = []
192
+ if explicit_reference:
193
+ evidence.append(
194
+ {"code": "ADR_ID_EXPLICIT", "adr_id": adr_id, "source": "diff-context"}
195
+ )
196
+ if adr_file_changed:
197
+ evidence.append(
198
+ {"code": "ADR_FILE_CHANGED", "path": normalize_path(str(record["path"]))}
199
+ )
200
+ for path in verified_matches:
201
+ evidence.append({"code": "VERIFIED_IN_CHANGED", "path": path})
202
+ for path in scope_matches:
203
+ evidence.append({"code": "ENFORCEMENT_SCOPE_CHANGED", "path": path})
204
+ evidence.sort(
205
+ key=lambda item: (
206
+ str(item.get("code", "")),
207
+ str(item.get("path", "")),
208
+ str(item.get("adr_id", "")),
209
+ )
210
+ )
211
+ return {
212
+ "linked": linked,
213
+ "implemented": bool(implementation_paths),
214
+ "blocking_proposed": linked and record.get("status") == "Proposed",
215
+ "changed_paths": implementation_paths,
216
+ "evidence": evidence,
217
+ }
218
+
219
+
220
+ def architecture_advisories(changed_paths: Sequence[str]) -> List[Dict[str, str]]:
221
+ """Return non-blocking review signals; heuristics never prove ADR linkage."""
222
+ paths = sorted({normalize_path(path) for path in changed_paths if path}, key=str.casefold)
223
+ return [
224
+ {
225
+ "code": "ARCHITECTURE_REVIEW_RECOMMENDED",
226
+ "path": path,
227
+ "classification": "not-an-adr",
228
+ "message": "Architecture-sensitive path changed; review whether a durable decision is present.",
229
+ "next_command": f'/adr-kit:grill --source "{path.replace(chr(34), chr(92) + chr(34))}"',
230
+ }
231
+ for path in paths
232
+ if _ARCHITECTURE_PATH_RE.search(path)
233
+ ]
234
+
235
+
236
+ def _mechanical_findings(record: Dict) -> List[Dict[str, str]]:
237
+ findings: List[Dict[str, str]] = list(record.get("metadata_findings", []))
238
+ if not str(record.get("decision_text", "")).strip():
239
+ findings.append(
240
+ {
241
+ "code": "DECISION_MISSING",
242
+ "message": "Record the chosen decision before confirmation.",
243
+ }
244
+ )
245
+ if record.get("superseded_by") and record.get("status") != "Superseded":
246
+ findings.append(
247
+ {
248
+ "code": "SUPERSESSION_STATE_INCONSISTENT",
249
+ "message": "Align superseded_by with lifecycle status.",
250
+ }
251
+ )
252
+ return sorted(findings, key=lambda item: item["code"])
253
+
254
+
255
+ def _classification(
256
+ record: Dict,
257
+ mechanical: Sequence[Dict[str, str]],
258
+ human: Sequence[Dict[str, str]],
259
+ ) -> str:
260
+ status = str(record.get("status", "")).casefold()
261
+ if status == "accepted":
262
+ return "accepted"
263
+ if status == "rejected":
264
+ return "rejected"
265
+ if status in {"superseded", "deprecated", "amended"} or record.get("superseded_by"):
266
+ return "supersession-required"
267
+ if mechanical:
268
+ return "needs-mechanical-fix"
269
+ if human:
270
+ return "needs-human-input"
271
+ if status == "proposed":
272
+ return "ready-for-confirmation"
273
+ return "not-an-adr"
274
+
275
+
276
+ def readiness_for_record(
277
+ record: Dict,
278
+ *,
279
+ evaluated_on: date,
280
+ changed_paths: Sequence[str] = (),
281
+ source_text: str = "",
282
+ relationships: Sequence[Dict] = (),
283
+ paths_normalized: bool = False,
284
+ path_pairs: Optional[Sequence[tuple[str, str]]] = None,
285
+ cited_ids: Optional[Sequence[str]] = None,
286
+ adr_dir: Optional[Path] = None,
287
+ ) -> Dict:
288
+ mechanical = _mechanical_findings(record)
289
+ human = [
290
+ {
291
+ "code": "OPEN_QUESTION",
292
+ "message": question,
293
+ }
294
+ for question in record.get("open_questions", [])
295
+ ]
296
+ # Three booleans used to stand in for quality here, which meant a vague ADR
297
+ # and a sharp one scored identically as long as both had a decision line and
298
+ # a verified_in. The real weighted scorer existed the whole time behind
299
+ # `bin/adr-quality`; it is now importable, so this reads it. The booleans
300
+ # stay in `checks` because they are cheap, specific, and say *what* is
301
+ # missing where a single number only says how much.
302
+ quality_checks = {
303
+ "decision": bool(str(record.get("decision_text", "")).strip()),
304
+ "evidence": bool(record.get("verified_in")),
305
+ # "Resolved" used to mean "the unresolved list is empty", which an
306
+ # answer and a deletion both produce. Requiring at least one ANSWERED
307
+ # item makes the two distinguishable: a record that was grilled and
308
+ # answered scores here, and one whose questions were quietly removed
309
+ # does not (ADR-022). A record that never had questions is unchanged --
310
+ # nothing to preserve, nothing to reward.
311
+ "open_questions_resolved": _open_questions_resolved(record, adr_dir),
312
+ }
313
+ quality_score = _scored_quality(record, adr_dir)
314
+ if quality_score is None:
315
+ # The scorer could not read the file. Fall back to the booleans rather
316
+ # than inventing a number, and say which one this is.
317
+ quality_score = round(
318
+ sum(1 for passed in quality_checks.values() if passed) / len(quality_checks), 3
319
+ )
320
+ quality_source = "structural-fallback"
321
+ else:
322
+ quality_source = "adr-quality"
323
+ classification = _classification(record, mechanical, human)
324
+ link = implementation_evidence(
325
+ record,
326
+ changed_paths,
327
+ source_text,
328
+ paths_normalized=paths_normalized,
329
+ path_pairs=path_pairs,
330
+ cited_ids=cited_ids,
331
+ )
332
+ related = sorted(
333
+ {
334
+ edge["target"] if edge["source"] == record["adr_id"] else edge["source"]
335
+ for edge in relationships
336
+ if record["adr_id"] in {edge["source"], edge["target"]}
337
+ }
338
+ )
339
+ next_commands = {
340
+ "needs-human-input": f"/adr-kit:grill {record['adr_id']}",
341
+ "needs-mechanical-fix": f"/adr-kit:grill {record['adr_id']}",
342
+ "ready-for-confirmation": f"/adr-kit:grill {record['adr_id']}",
343
+ "supersession-required": f"/adr-kit:grill --revalidate {record['adr_id']}",
344
+ }
345
+ return {
346
+ "adr_id": record["adr_id"],
347
+ "title": record["title"],
348
+ "path": normalize_path(str(record["path"])),
349
+ "status": record["status"],
350
+ "format": record["format"],
351
+ "evaluated_on": evaluated_on.isoformat(),
352
+ "classification": classification,
353
+ "mechanical_findings": mechanical,
354
+ "human_findings": human,
355
+ "mechanical_actions": [item["message"] for item in mechanical],
356
+ "human_decisions": [item["message"] for item in human],
357
+ "quality": {
358
+ "score": quality_score,
359
+ "checks": quality_checks,
360
+ "source": quality_source,
361
+ "threshold": QUALITY_THRESHOLD,
362
+ "below_threshold": quality_score < QUALITY_THRESHOLD,
363
+ },
364
+ "open_questions": list(record.get("open_questions", [])),
365
+ "documents_shipped": bool(record.get("documents_shipped")),
366
+ "verified_in": sorted(
367
+ {normalize_path(str(item)) for item in record.get("verified_in", [])},
368
+ key=str.casefold,
369
+ ),
370
+ "implementation_link": link,
371
+ "related_adrs": related,
372
+ "next_command": next_commands.get(classification),
373
+ }
374
+
375
+
376
+ def build_readiness_report(
377
+ adr_dir: Path,
378
+ *,
379
+ evaluated_on: date,
380
+ adr_id: Optional[str] = None,
381
+ all_proposed: bool = False,
382
+ changed_paths: Sequence[str] = (),
383
+ source_text: str = "",
384
+ ) -> Dict:
385
+ records = load_adr_records(adr_dir)
386
+ relationships = build_relationships(records)
387
+ normalized_changed_paths = sorted(
388
+ {normalize_path(path) for path in changed_paths if path}, key=str.casefold
389
+ )
390
+ path_pairs = [(path, path.casefold()) for path in normalized_changed_paths]
391
+ cited_ids = explicit_adr_ids(source_text)
392
+ normalized_id = normalize_adr_id(adr_id) if adr_id else None
393
+ if adr_id and normalized_id is None:
394
+ numeric = re.fullmatch(r"0*(\d{1,4})", str(adr_id).strip())
395
+ normalized_id = f"ADR-{int(numeric.group(1)):03d}" if numeric else None
396
+ if adr_id and normalized_id is None:
397
+ raise ReadinessError(f"invalid ADR id: {adr_id}")
398
+ selected = [
399
+ record
400
+ for record in records
401
+ if (
402
+ (normalized_id and record["adr_id"] == normalized_id)
403
+ or (all_proposed and record["status"] == "Proposed")
404
+ or (not normalized_id and not all_proposed)
405
+ )
406
+ ]
407
+ if normalized_id and not selected:
408
+ raise ReadinessError(f"ADR not found: {normalized_id}")
409
+ reports = [
410
+ readiness_for_record(
411
+ record,
412
+ evaluated_on=evaluated_on,
413
+ changed_paths=normalized_changed_paths,
414
+ source_text=source_text,
415
+ relationships=relationships,
416
+ paths_normalized=True,
417
+ path_pairs=path_pairs,
418
+ cited_ids=cited_ids,
419
+ adr_dir=adr_dir,
420
+ )
421
+ for record in selected
422
+ ]
423
+ reports.sort(key=lambda item: item["adr_id"])
424
+ blocking = [
425
+ item["adr_id"]
426
+ for item in reports
427
+ if item["implementation_link"]["blocking_proposed"]
428
+ ]
429
+ advisories = architecture_advisories(normalized_changed_paths)
430
+ return {
431
+ "schema_version": READINESS_SCHEMA_VERSION,
432
+ "evaluated_on": evaluated_on.isoformat(),
433
+ "adr_dir": normalize_path(str(adr_dir)),
434
+ "summary": {
435
+ "total": len(reports),
436
+ "blocking_proposed": blocking,
437
+ "blocking_count": len(blocking),
438
+ "advisory_count": len(advisories),
439
+ },
440
+ "advisories": advisories,
441
+ "adrs": reports,
442
+ }
@@ -0,0 +1,123 @@
1
+ """Safe GitHub reporting for a deterministic ADR readiness report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from pathlib import Path
8
+
9
+
10
+ def github_escape(value: object) -> str:
11
+ return (
12
+ str(value)
13
+ .replace("%", "%25")
14
+ .replace("\r", "%0D")
15
+ .replace("\n", "%0A")
16
+ )
17
+
18
+
19
+ def markdown_escape(value: object) -> str:
20
+ return (
21
+ re.sub(r"[\x00-\x1f\x7f]+", " ", str(value))
22
+ .replace("`", "'")
23
+ .replace("<", "&lt;")
24
+ .replace(">", "&gt;")
25
+ )
26
+
27
+
28
+ def _source_command(path: str) -> str:
29
+ clean = re.sub(r"[\x00-\x1f\x7f]+", " ", path).replace('"', '\\"')
30
+ return f'/adr-kit:grill --source "{clean}"'
31
+
32
+
33
+ def render_summary(report: dict) -> str:
34
+ lines = [
35
+ "## ADR readiness",
36
+ "",
37
+ f"Evaluated: `{markdown_escape(report.get('evaluated_on', 'unknown'))}`",
38
+ "",
39
+ ]
40
+ for item in report.get("adrs", []):
41
+ link = item.get("implementation_link", {})
42
+ if not link.get("linked") and item.get("status") != "Proposed":
43
+ continue
44
+ label = "BLOCK" if link.get("blocking_proposed") else "INFO"
45
+ command = item.get("next_command") or f"/adr-kit:grill {item.get('adr_id')}"
46
+ evidence = ", ".join(
47
+ str(entry.get("code", "")) for entry in link.get("evidence", [])
48
+ ) or "none"
49
+ lines.extend(
50
+ [
51
+ f"- [{label}] **{markdown_escape(item.get('adr_id'))}** - "
52
+ f"`{markdown_escape(item.get('classification'))}` - "
53
+ f"{markdown_escape(item.get('title'))}",
54
+ f" - Evidence: `{markdown_escape(evidence)}`",
55
+ f" - Next: `{markdown_escape(command)}`",
56
+ ]
57
+ )
58
+ for advisory in report.get("advisories", []):
59
+ command = advisory.get("next_command") or _source_command(
60
+ str(advisory.get("path", ""))
61
+ )
62
+ lines.extend(
63
+ [
64
+ f"- [ADVISORY] `{markdown_escape(advisory.get('code'))}` - "
65
+ f"`{markdown_escape(advisory.get('classification', 'not-an-adr'))}` - "
66
+ f"`{markdown_escape(advisory.get('path'))}`",
67
+ f" - Evidence: `{markdown_escape(advisory.get('message'))}`",
68
+ f" - Next: `{markdown_escape(command)}`",
69
+ ]
70
+ )
71
+ if len(lines) == 4:
72
+ lines.append("- No ADR readiness findings.")
73
+ return "\n".join(lines) + "\n"
74
+
75
+
76
+ def output_values(report: dict) -> dict[str, str]:
77
+ blocking = list(report.get("summary", {}).get("blocking_proposed", []))
78
+ return {
79
+ "blocking-count": str(len(blocking)),
80
+ "blocking-adrs": json.dumps(blocking, separators=(",", ":")),
81
+ "advisory-count": str(report.get("summary", {}).get("advisory_count", 0)),
82
+ "schema-version": str(report.get("schema_version", "")),
83
+ "conclusion": "blocked" if blocking else "advisory-or-clean",
84
+ }
85
+
86
+
87
+ def write_outputs(path: Path, values: dict[str, str]) -> None:
88
+ with path.open("a", encoding="utf-8", newline="\n") as stream:
89
+ for key in sorted(values):
90
+ value = values[key].replace("\r", "").replace("\n", "")
91
+ stream.write(f"{key}={value}\n")
92
+
93
+
94
+ def annotations(report: dict) -> list[str]:
95
+ lines = []
96
+ for item in report.get("adrs", []):
97
+ link = item.get("implementation_link", {})
98
+ if not link.get("blocking_proposed"):
99
+ continue
100
+ evidence = ",".join(
101
+ str(entry.get("code", "")) for entry in link.get("evidence", [])
102
+ )
103
+ message = (
104
+ f"{item.get('adr_id')} is {item.get('classification')}; "
105
+ f"evidence={evidence}; next={item.get('next_command')}"
106
+ )
107
+ lines.append(
108
+ f"::error title=ADR readiness block::{github_escape(message)}"
109
+ )
110
+ for advisory in report.get("advisories", []):
111
+ command = advisory.get("next_command") or _source_command(
112
+ str(advisory.get("path", ""))
113
+ )
114
+ message = (
115
+ f"{advisory.get('code')} "
116
+ f"classification={advisory.get('classification', 'not-an-adr')} "
117
+ f"path={advisory.get('path')}; "
118
+ f"evidence={advisory.get('message')}; next={command}"
119
+ )
120
+ lines.append(
121
+ f"::notice title=ADR review advisory::{github_escape(message)}"
122
+ )
123
+ return lines