@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,448 @@
1
+ """Shared ADR frontmatter schema helpers.
2
+
3
+ This module intentionally stays stdlib-only and YAML-subset-only. adr-kit
4
+ frontmatter is rendered in a simple shape that this parser can round-trip:
5
+ scalar fields plus string lists.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib.machinery
11
+ import importlib.util
12
+ import json
13
+ import re
14
+ import sys
15
+ from datetime import date
16
+ from pathlib import Path
17
+ from typing import Dict, List, Optional, Tuple
18
+
19
+ _BIN_DIR = Path(__file__).resolve().parent
20
+
21
+
22
+ def _load_sibling(name: str):
23
+ """Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
24
+
25
+ SEC-HIGH (TASK-62): this module used to `sys.path.insert(0, _BIN_DIR)`.
26
+ That made bin/ shadow the standard library for every subsequent import in
27
+ whatever process loaded it -- including the executables that load this
28
+ module by explicit path precisely to avoid that -- and it re-added the
29
+ directory CPython's -P / PYTHONSAFEPATH removes. See bin/adr-judge for the
30
+ full rationale. Registering under the bare name lets the plain
31
+ `from adr_format import ...` below resolve from sys.modules.
32
+ """
33
+ cached = sys.modules.get(name)
34
+ if cached is not None:
35
+ return cached
36
+ loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
37
+ spec = importlib.util.spec_from_loader(name, loader)
38
+ module = importlib.util.module_from_spec(spec)
39
+ sys.modules[name] = module
40
+ loader.exec_module(module)
41
+ return module
42
+
43
+
44
+ _load_sibling("adr_format")
45
+
46
+ from adr_format import SUPPORTED_PROFILES
47
+
48
+ FRONTMATTER_FIELD_ORDER = (
49
+ "id",
50
+ "title",
51
+ "status",
52
+ "date",
53
+ "binding",
54
+ "gate",
55
+ "documents_shipped",
56
+ "verified_in",
57
+ "supersedes",
58
+ "superseded_by",
59
+ )
60
+
61
+ OPTIONAL_FRONTMATTER_FIELD_ORDER = (
62
+ # `related` is the symmetric counterpart of supersedes/superseded_by: a
63
+ # declared, machine-written cross-reference rather than a prose mention.
64
+ # It lives in frontmatter for the same reason those two do -- writing a
65
+ # back-reference into an Accepted record is reference bookkeeping, which
66
+ # `bin/adr supersede` has always been allowed to do, while editing an
67
+ # Accepted body is not. `bin/adr relate` writes both sides at once.
68
+ "related",
69
+ "topics",
70
+ "aliases",
71
+ "components",
72
+ "symbols",
73
+ "context_scope",
74
+ "format",
75
+ )
76
+
77
+ VALID_STATUSES = {"Proposed", "Accepted", "Deprecated", "Superseded", "Amended", "Rejected"}
78
+ VALID_CONTEXT_SCOPES = {"global", "selective"}
79
+
80
+ ADR_ID_RE = re.compile(r"\bADR-(\d{1,4})\b", re.IGNORECASE)
81
+ ADR_FILENAME_RE = re.compile(r"(?i)^ADR-(\d{1,4})-")
82
+ LEGACY_FILENAME_RE = re.compile(
83
+ r"(?i)^(?:ADR[-_ ]?)?0*(\d{1,4})[-_. ]+(.+?)\.md$"
84
+ )
85
+ TITLE_RE = re.compile(r"^#\s+ADR-\d{1,4}\s+(.+?)\s*$", re.MULTILINE | re.IGNORECASE)
86
+ LEGACY_TITLE_RE = re.compile(
87
+ r"^#\s+(?:ADR[-_ ]?)?0*\d{1,4}[.:\s-]+(.+?)\s*$",
88
+ re.MULTILINE | re.IGNORECASE,
89
+ )
90
+ STATUS_SECTION_RE = re.compile(
91
+ r"^##\s+Status(?!\s+History)\s*$\n+([^\n]+)",
92
+ re.IGNORECASE | re.MULTILINE,
93
+ )
94
+ DATE_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b")
95
+ SUPERSEDES_RE = re.compile(r"\bSupersedes\s+ADR-(\d{1,4})\b", re.IGNORECASE)
96
+ SUPERSEDED_BY_RE = re.compile(r"\bSuperseded\s+by\s+ADR-(\d{1,4})\b", re.IGNORECASE)
97
+
98
+
99
+ class FrontmatterError(Exception):
100
+ """Raised when frontmatter uses unsupported syntax."""
101
+
102
+
103
+ def _normalize_adr_id(raw: str) -> str:
104
+ match = ADR_ID_RE.search(raw)
105
+ if not match:
106
+ return raw
107
+ return f"ADR-{int(match.group(1)):03d}"
108
+
109
+
110
+ def split_frontmatter(text: str) -> Tuple[Optional[str], str]:
111
+ """Return (raw_frontmatter, markdown_body).
112
+
113
+ If no leading frontmatter block exists, raw_frontmatter is None and body is
114
+ the original text unchanged.
115
+ """
116
+ lines = text.splitlines(keepends=True)
117
+ if not lines or lines[0].strip() != "---":
118
+ return None, text
119
+ for idx in range(1, len(lines)):
120
+ if lines[idx].strip() == "---":
121
+ return "".join(lines[1:idx]), "".join(lines[idx + 1 :])
122
+ return None, text
123
+
124
+
125
+ def _parse_scalar(raw: str):
126
+ value = raw.strip()
127
+ if value == "":
128
+ return ""
129
+ if value == "null":
130
+ return None
131
+ if value == "true":
132
+ return True
133
+ if value == "false":
134
+ return False
135
+ if value == "[]":
136
+ return []
137
+ if len(value) >= 2 and value[0] == value[-1] == '"':
138
+ try:
139
+ return json.loads(value)
140
+ except json.JSONDecodeError as exc:
141
+ raise FrontmatterError(f"invalid quoted scalar {value!r}: {exc}") from exc
142
+ if len(value) >= 2 and value[0] == value[-1] == "'":
143
+ return value[1:-1].replace("''", "'")
144
+ return value
145
+
146
+
147
+ def parse_frontmatter(raw: Optional[str]) -> Dict:
148
+ """Parse adr-kit frontmatter rendered by render_frontmatter()."""
149
+ if raw is None:
150
+ return {}
151
+ result: Dict = {}
152
+ current_list_key: Optional[str] = None
153
+ for lineno, line in enumerate(raw.splitlines(), start=1):
154
+ stripped = line.strip()
155
+ if not stripped or stripped.startswith("#"):
156
+ continue
157
+ if stripped.startswith("- "):
158
+ if current_list_key is None:
159
+ raise FrontmatterError(f"line {lineno}: list item without a key")
160
+ result[current_list_key].append(_parse_scalar(stripped[2:]))
161
+ continue
162
+ if ":" not in line:
163
+ raise FrontmatterError(f"line {lineno}: expected key: value")
164
+ key, value = line.split(":", 1)
165
+ key = key.strip()
166
+ if not key:
167
+ raise FrontmatterError(f"line {lineno}: empty key")
168
+ if value.strip() == "":
169
+ result[key] = []
170
+ current_list_key = key
171
+ else:
172
+ result[key] = _parse_scalar(value)
173
+ current_list_key = None
174
+ return result
175
+
176
+
177
+ def infer_frontmatter(body: str, path: Optional[Path] = None) -> Dict:
178
+ """Infer canonical frontmatter from legacy prose without editing the body."""
179
+ filename_id = None
180
+ if path is not None:
181
+ match = ADR_FILENAME_RE.match(path.name)
182
+ if match:
183
+ filename_id = f"ADR-{int(match.group(1)):03d}"
184
+ else:
185
+ legacy_match = LEGACY_FILENAME_RE.match(path.name)
186
+ if legacy_match:
187
+ filename_id = f"ADR-{int(legacy_match.group(1)):03d}"
188
+ heading_id = None
189
+ heading_match = re.search(
190
+ r"^#\s+(ADR-\d{1,4})\b", body, re.MULTILINE | re.IGNORECASE
191
+ )
192
+ if heading_match:
193
+ heading_id = _normalize_adr_id(heading_match.group(1))
194
+ else:
195
+ legacy_heading = re.search(
196
+ r"^#\s+(?:ADR[-_ ]?)?0*(\d{1,4})[.:\s-]+",
197
+ body,
198
+ re.MULTILINE | re.IGNORECASE,
199
+ )
200
+ if legacy_heading:
201
+ heading_id = f"ADR-{int(legacy_heading.group(1)):03d}"
202
+ adr_id = filename_id or heading_id or "ADR-000"
203
+
204
+ title_match = TITLE_RE.search(body) or LEGACY_TITLE_RE.search(body)
205
+ if title_match is None:
206
+ generic_title = re.search(r"^#\s+(.+?)\s*$", body, re.MULTILINE)
207
+ title_match = generic_title
208
+ title = title_match.group(1).strip() if title_match else ""
209
+
210
+ status_line = ""
211
+ status_match = STATUS_SECTION_RE.search(body)
212
+ if status_match:
213
+ status_line = status_match.group(1).strip()
214
+ status_word_match = re.match(r"([A-Za-z]+)", status_line)
215
+ status = status_word_match.group(1).capitalize() if status_word_match else "Proposed"
216
+ if status not in VALID_STATUSES:
217
+ status = "Proposed"
218
+
219
+ date_match = DATE_RE.search(status_line)
220
+ status_date = date_match.group(1) if date_match else None
221
+
222
+ supersedes = sorted({_normalize_adr_id(f"ADR-{n}") for n in SUPERSEDES_RE.findall(body)})
223
+ superseded_by_match = SUPERSEDED_BY_RE.search(status_line)
224
+ superseded_by = (
225
+ _normalize_adr_id(f"ADR-{superseded_by_match.group(1)}")
226
+ if superseded_by_match
227
+ else None
228
+ )
229
+
230
+ return {
231
+ "id": adr_id,
232
+ "title": title,
233
+ "status": status,
234
+ "date": status_date,
235
+ "binding": False,
236
+ "gate": None,
237
+ "documents_shipped": False,
238
+ "verified_in": [],
239
+ "supersedes": supersedes,
240
+ "superseded_by": superseded_by,
241
+ }
242
+
243
+
244
+ def _render_scalar(value) -> str:
245
+ if value is None:
246
+ return "null"
247
+ if value is True:
248
+ return "true"
249
+ if value is False:
250
+ return "false"
251
+ return json.dumps(str(value), ensure_ascii=False)
252
+
253
+
254
+ def render_frontmatter(data: Dict) -> str:
255
+ """Render canonical frontmatter with stable field order."""
256
+ lines: List[str] = ["---"]
257
+ rendered = set()
258
+ for key in FRONTMATTER_FIELD_ORDER:
259
+ value = data.get(key)
260
+ rendered.add(key)
261
+ if isinstance(value, list):
262
+ if value:
263
+ lines.append(f"{key}:")
264
+ lines.extend(f" - {_render_scalar(item)}" for item in value)
265
+ else:
266
+ lines.append(f"{key}: []")
267
+ else:
268
+ lines.append(f"{key}: {_render_scalar(value)}")
269
+ for key in OPTIONAL_FRONTMATTER_FIELD_ORDER:
270
+ if key not in data:
271
+ continue
272
+ value = data[key]
273
+ rendered.add(key)
274
+ if isinstance(value, list):
275
+ if value:
276
+ lines.append(f"{key}:")
277
+ lines.extend(f" - {_render_scalar(item)}" for item in value)
278
+ else:
279
+ lines.append(f"{key}: []")
280
+ else:
281
+ lines.append(f"{key}: {_render_scalar(value)}")
282
+ for key in sorted(k for k in data if k not in rendered):
283
+ value = data[key]
284
+ if isinstance(value, list):
285
+ if value:
286
+ lines.append(f"{key}:")
287
+ lines.extend(f" - {_render_scalar(item)}" for item in value)
288
+ else:
289
+ lines.append(f"{key}: []")
290
+ else:
291
+ lines.append(f"{key}: {_render_scalar(value)}")
292
+ lines.append("---")
293
+ lines.append("")
294
+ return "\n".join(lines)
295
+
296
+
297
+ def canonicalize_frontmatter(existing: Dict, inferred: Dict) -> Dict:
298
+ """Return existing frontmatter completed with canonical inferred fields."""
299
+ merged = dict(existing)
300
+ for key in FRONTMATTER_FIELD_ORDER:
301
+ if key not in merged:
302
+ merged[key] = inferred.get(key)
303
+ status = merged.get("status")
304
+ if isinstance(status, str):
305
+ normalized_status = {
306
+ item.casefold(): item for item in VALID_STATUSES
307
+ }.get(status.strip().casefold())
308
+ if normalized_status is not None:
309
+ merged["status"] = normalized_status
310
+ return merged
311
+
312
+
313
+ def _normalize_legacy_heading(
314
+ body: str,
315
+ path: Optional[Path],
316
+ inferred: Dict,
317
+ ) -> str:
318
+ """Normalize an identifiable legacy H1 without changing decision prose."""
319
+ if path is None or ADR_FILENAME_RE.match(path.name):
320
+ return body
321
+ adr_id = inferred.get("id")
322
+ title = inferred.get("title")
323
+ if (
324
+ not isinstance(adr_id, str)
325
+ or adr_id == "ADR-000"
326
+ or not isinstance(title, str)
327
+ or not title.strip()
328
+ ):
329
+ return body
330
+ heading = re.search(r"^#\s+.+?\s*$", body, re.MULTILINE)
331
+ if heading is None:
332
+ return body
333
+ normalized = f"# {adr_id} {title.strip()}"
334
+ return body[: heading.start()] + normalized + body[heading.end() :]
335
+
336
+
337
+ def validate_frontmatter(data: Dict) -> List[str]:
338
+ """Return human-readable schema issues; empty list means valid."""
339
+ issues: List[str] = []
340
+ missing = [key for key in FRONTMATTER_FIELD_ORDER if key not in data]
341
+ if missing:
342
+ issues.append(f"missing canonical field(s): {', '.join(missing)}")
343
+
344
+ adr_id = data.get("id")
345
+ if not isinstance(adr_id, str) or not re.fullmatch(r"ADR-\d{3,4}", adr_id):
346
+ issues.append("id must be an ADR-NNN string")
347
+
348
+ title = data.get("title")
349
+ if not isinstance(title, str) or not title.strip():
350
+ issues.append("title must be a non-empty string")
351
+
352
+ status = data.get("status")
353
+ if status not in VALID_STATUSES:
354
+ issues.append(f"status must be one of: {', '.join(sorted(VALID_STATUSES))}")
355
+
356
+ status_date = data.get("date")
357
+ if status_date is not None:
358
+ if not isinstance(status_date, str):
359
+ issues.append("date must be null or YYYY-MM-DD string")
360
+ else:
361
+ try:
362
+ date.fromisoformat(status_date)
363
+ except ValueError:
364
+ issues.append("date must be null or YYYY-MM-DD string")
365
+
366
+ if not isinstance(data.get("binding"), bool):
367
+ issues.append("binding must be a boolean")
368
+
369
+ gate = data.get("gate")
370
+ if gate is not None and (not isinstance(gate, str) or not gate.strip()):
371
+ issues.append("gate must be null or a non-empty string")
372
+
373
+ if not isinstance(data.get("documents_shipped"), bool):
374
+ issues.append("documents_shipped must be a boolean")
375
+
376
+ for list_key in ("verified_in", "supersedes"):
377
+ value = data.get(list_key)
378
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
379
+ issues.append(f"{list_key} must be a list of strings")
380
+
381
+ superseded_by = data.get("superseded_by")
382
+ if superseded_by is not None and (
383
+ not isinstance(superseded_by, str)
384
+ or not re.fullmatch(r"ADR-\d{3,4}", superseded_by)
385
+ ):
386
+ issues.append("superseded_by must be null or an ADR-NNN string")
387
+
388
+ for ref in data.get("supersedes", []) if isinstance(data.get("supersedes"), list) else []:
389
+ if not re.fullmatch(r"ADR-\d{3,4}", ref):
390
+ issues.append(f"supersedes entry {ref!r} must be an ADR-NNN string")
391
+
392
+ # `related` is optional, so an absent key is fine; a present one must hold
393
+ # ADR ids, because the whole point is that a machine can resolve it.
394
+ related = data.get("related")
395
+ if related is not None:
396
+ if not isinstance(related, list) or not all(isinstance(item, str) for item in related):
397
+ issues.append("related must be a list of strings")
398
+ else:
399
+ for ref in related:
400
+ if not re.fullmatch(r"ADR-\d{3,4}", ref):
401
+ issues.append(f"related entry {ref!r} must be an ADR-NNN string")
402
+
403
+ profile = data.get("format")
404
+ if profile is not None and profile not in SUPPORTED_PROFILES:
405
+ issues.append("format must be one of: " + ", ".join(SUPPORTED_PROFILES))
406
+
407
+ for list_key in ("topics", "aliases", "components", "symbols"):
408
+ value = data.get(list_key)
409
+ if value is None:
410
+ continue
411
+ if (
412
+ not isinstance(value, list)
413
+ or not all(
414
+ isinstance(item, str) and 0 < len(item.strip()) <= 120
415
+ for item in value
416
+ )
417
+ or len(value) > 32
418
+ ):
419
+ issues.append(
420
+ f"{list_key} must be a list of at most 32 non-empty strings "
421
+ "of at most 120 characters"
422
+ )
423
+ elif len({item.casefold() for item in value}) != len(value):
424
+ issues.append(f"{list_key} entries must be unique ignoring case")
425
+
426
+ context_scope = data.get("context_scope")
427
+ if context_scope is not None and context_scope not in VALID_CONTEXT_SCOPES:
428
+ issues.append("context_scope must be one of: global, selective")
429
+
430
+ return issues
431
+
432
+
433
+ def migrate_text(text: str, path: Optional[Path] = None) -> Tuple[str, bool, List[str]]:
434
+ """Add canonical metadata and normalize an identifiable legacy H1."""
435
+ raw_frontmatter, body = split_frontmatter(text)
436
+ inferred = infer_frontmatter(body, path)
437
+ try:
438
+ existing = parse_frontmatter(raw_frontmatter)
439
+ except FrontmatterError as exc:
440
+ return text, False, [str(exc)]
441
+ data = canonicalize_frontmatter(existing, inferred)
442
+ issues = validate_frontmatter(data)
443
+ if issues:
444
+ return text, False, issues
445
+ rendered = render_frontmatter(data)
446
+ normalized_body = _normalize_legacy_heading(body, path, inferred)
447
+ new_text = f"{rendered}{normalized_body}"
448
+ return new_text, new_text != text, []
@@ -0,0 +1,172 @@
1
+ """Cross-platform transactional JSON state updates for adr-kit hooks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import os
8
+ import tempfile
9
+ import time
10
+ from pathlib import Path
11
+ from typing import Callable, Dict, Optional, Tuple, TypeVar
12
+
13
+
14
+ T = TypeVar("T")
15
+ StateMutation = Callable[[Dict], Tuple[bool, T]]
16
+
17
+
18
+ def find_project_adr_dir() -> Optional[Path]:
19
+ """Return the project's docs/adr/ directory, or None when absent or empty.
20
+
21
+ Checks CLAUDE_PROJECT_DIR first (set by Claude Code for plugin-level hooks),
22
+ then falls back to the working directory. A candidate counts only when it
23
+ exists and holds at least one ADR-*.md file, so hook-side callers can
24
+ self-guard on a repository that does not use adr-kit. Shared by adr-guardian
25
+ and adr-watch; kept in this stdlib-only module so hook entry points pay no
26
+ extra import cost.
27
+ """
28
+ project_dir = os.environ.get("CLAUDE_PROJECT_DIR") or ""
29
+ candidates = []
30
+ if project_dir:
31
+ candidates.append(Path(project_dir) / "docs" / "adr")
32
+ candidates.append(Path.cwd() / "docs" / "adr")
33
+
34
+ for adr_dir in candidates:
35
+ if adr_dir.is_dir():
36
+ try:
37
+ has_adrs = any(True for _ in adr_dir.glob("ADR-*.md"))
38
+ except OSError:
39
+ continue
40
+ if has_adrs:
41
+ return adr_dir
42
+ return None
43
+
44
+
45
+ class StateLockTimeout(OSError):
46
+ """Raised when a state transaction cannot acquire its cross-process lock."""
47
+
48
+
49
+ @contextlib.contextmanager
50
+ def state_lock(state_path: Path, timeout_seconds: float = 2.0):
51
+ """Hold an exclusive cross-process lock for a complete state transaction."""
52
+ state_path.parent.mkdir(parents=True, exist_ok=True)
53
+ lock_path = state_path.parent / f"{state_path.name}.lock"
54
+ handle = open(lock_path, "a+b")
55
+ deadline = time.monotonic() + timeout_seconds
56
+ mechanism = None
57
+ try:
58
+ while mechanism is None:
59
+ try:
60
+ import fcntl
61
+
62
+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
63
+ mechanism = "fcntl"
64
+ except ImportError:
65
+ try:
66
+ import msvcrt
67
+
68
+ handle.seek(0, os.SEEK_END)
69
+ if handle.tell() == 0:
70
+ handle.write(b"\0")
71
+ handle.flush()
72
+ handle.seek(0)
73
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
74
+ mechanism = "msvcrt"
75
+ except OSError:
76
+ pass
77
+ except OSError:
78
+ pass
79
+
80
+ if mechanism is None:
81
+ if time.monotonic() >= deadline:
82
+ raise StateLockTimeout(
83
+ f"timed out locking state file {state_path}"
84
+ )
85
+ time.sleep(0.01)
86
+ yield
87
+ finally:
88
+ if mechanism == "fcntl":
89
+ try:
90
+ import fcntl
91
+
92
+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
93
+ except OSError:
94
+ pass
95
+ elif mechanism == "msvcrt":
96
+ try:
97
+ import msvcrt
98
+
99
+ handle.seek(0)
100
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
101
+ except OSError:
102
+ pass
103
+ handle.close()
104
+
105
+
106
+ def load_state(
107
+ state_path: Path,
108
+ default_factory: Callable[[], Dict],
109
+ warning: Optional[Callable[[str], None]] = None,
110
+ ) -> Dict:
111
+ """Load one JSON object, returning a fresh default on missing/corrupt data."""
112
+ if not state_path.exists():
113
+ return default_factory()
114
+ try:
115
+ data = json.loads(state_path.read_text(encoding="utf-8"))
116
+ if not isinstance(data, dict):
117
+ raise ValueError("state root is not a JSON object")
118
+ return data
119
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
120
+ if warning is not None:
121
+ warning(
122
+ f"state file {state_path} unreadable or corrupt "
123
+ f"({exc.__class__.__name__}); treating as empty state"
124
+ )
125
+ return default_factory()
126
+
127
+
128
+ def atomic_save_state(state_path: Path, state: Dict) -> None:
129
+ """Atomically replace state using a unique same-directory temporary file."""
130
+ state_path.parent.mkdir(parents=True, exist_ok=True)
131
+ temp_path = None
132
+ try:
133
+ with tempfile.NamedTemporaryFile(
134
+ mode="w",
135
+ encoding="utf-8",
136
+ newline="",
137
+ dir=state_path.parent,
138
+ prefix=f".{state_path.name}.",
139
+ suffix=".tmp",
140
+ delete=False,
141
+ ) as handle:
142
+ json.dump(state, handle, indent=2)
143
+ handle.write("\n")
144
+ handle.flush()
145
+ os.fsync(handle.fileno())
146
+ temp_path = Path(handle.name)
147
+ os.replace(temp_path, state_path)
148
+ temp_path = None
149
+ finally:
150
+ if temp_path is not None:
151
+ temp_path.unlink(missing_ok=True)
152
+
153
+
154
+ def update_state(
155
+ state_path: Path,
156
+ default_factory: Callable[[], Dict],
157
+ mutation: StateMutation[T],
158
+ warning: Optional[Callable[[str], None]] = None,
159
+ timeout_seconds: float = 2.0,
160
+ ) -> Optional[T]:
161
+ """Lock, load, mutate, and optionally save state as one transaction."""
162
+ try:
163
+ with state_lock(state_path, timeout_seconds=timeout_seconds):
164
+ state = load_state(state_path, default_factory, warning)
165
+ dirty, result = mutation(state)
166
+ if dirty:
167
+ atomic_save_state(state_path, state)
168
+ return result
169
+ except (OSError, StateLockTimeout) as exc:
170
+ if warning is not None:
171
+ warning(f"state update skipped: {exc}")
172
+ return None
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env python3
2
+ """bump-version: thin delegation to the canonical release writer.
3
+
4
+ Usage: bin/bump-version <new-version>
5
+ e.g. bin/bump-version 0.16.0
6
+ (on Windows: python bin/bump-version 0.16.0)
7
+
8
+ **This script implements nothing.** `scripts/bump-version.py` is the canonical
9
+ writer named by ADR-013 and `docs/RELEASING.md`; this entry point exists only
10
+ because `bin/` is where every other adr-kit command lives, and removing a path
11
+ people have in their shell history is a worse outcome than keeping four lines
12
+ that forward.
13
+
14
+ Why it stopped being a second implementation (TASK-139). Both scripts bumped the
15
+ version, and they did not do the same thing. This one knew how to rewrite the
16
+ CHANGELOG compare-link block; the one the runbook names did not. So the runbook
17
+ ran the weaker tool and the link block went stale on every single release --
18
+ after v0.46.0 the block still read `compare/v0.45.0...HEAD`, and checking the
19
+ rest of it found seven further headings with no target at all. Two files that
20
+ both claim to bump the version is the defect underneath the missing links, and
21
+ deleting one implementation is the only fix that does not reproduce it.
22
+
23
+ The link logic, the plugin-identity preflight and the marketplace-entry
24
+ validation that used to live here now live in `scripts/bump-version.py`, so the
25
+ runbook's tool performs them.
26
+
27
+ History: this was a bash script until v0.31.0. It shelled out to python3 for
28
+ each file edit, and on Windows the `python3` Store alias routes through the
29
+ Python Install Manager, which scans argv for a script file and dispatches on
30
+ ITS shebang: passing the bash-shebanged pre-commit template as an argument made
31
+ the launcher exec bash instead of python. Pure stdlib Python avoids the
32
+ launcher's argv scanning entirely, needs no Git Bash, and matches every other
33
+ bin in this repo.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import importlib.machinery
39
+ import importlib.util
40
+ import sys
41
+ from pathlib import Path
42
+
43
+ REPO_ROOT = Path(__file__).resolve().parent.parent
44
+
45
+
46
+ def _load_writer():
47
+ """Load scripts/bump-version.py by explicit path, WITHOUT touching sys.path.
48
+
49
+ SEC-HIGH (TASK-62): `sys.path.insert` from a file in bin/ puts that
50
+ directory ahead of the standard library for every import that follows, so
51
+ anything committed next to this script executes as code. Loading by file
52
+ location keeps bin/ non-importable. Same shape as bin/adr-judge._load_sibling,
53
+ aimed at scripts/ because the writer is shared with the release gate and must
54
+ not be mirrored into the client trees (bin/ is a copy root; scripts/ is not).
55
+ """
56
+ name = "adr_kit_bump_version"
57
+ cached = sys.modules.get(name)
58
+ if cached is not None:
59
+ return cached
60
+ loader = importlib.machinery.SourceFileLoader(
61
+ name, str(REPO_ROOT / "scripts" / "bump-version.py")
62
+ )
63
+ spec = importlib.util.spec_from_loader(name, loader)
64
+ module = importlib.util.module_from_spec(spec)
65
+ sys.modules[name] = module
66
+ loader.exec_module(module)
67
+ return module
68
+
69
+
70
+ if __name__ == "__main__":
71
+ sys.exit(_load_writer().main(sys.argv[1:]))