@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
package/bin/adr ADDED
@@ -0,0 +1,1552 @@
1
+ #!/usr/bin/env python3
2
+ """adr: local lifecycle commands for adr-kit ADRs."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import importlib.machinery
8
+ import importlib.util
9
+ import json
10
+ import os
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ from datetime import date
17
+ from pathlib import Path
18
+ from typing import Dict, List, Optional, Tuple
19
+
20
+ _BIN_DIR = Path(__file__).resolve().parent
21
+
22
+
23
+ def _load_sibling(name: str):
24
+ """Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
25
+
26
+ SEC-HIGH (TASK-62): `sys.path.insert(0, _BIN_DIR)` put this directory ahead
27
+ of the standard library for every import, so a module committed next to
28
+ this script executed as code -- and it re-added the very directory
29
+ CPython's -P / PYTHONSAFEPATH removes. Siblings are registered in
30
+ sys.modules under their bare name, so the plain `from adr_* import ...`
31
+ statements below (and the lazy ones inside functions) resolve from the
32
+ cache instead of the path. bin/adr-judge carries the full rationale.
33
+ """
34
+ cached = sys.modules.get(name)
35
+ if cached is not None:
36
+ return cached
37
+ loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
38
+ spec = importlib.util.spec_from_loader(name, loader)
39
+ module = importlib.util.module_from_spec(spec)
40
+ sys.modules[name] = module
41
+ loader.exec_module(module)
42
+ return module
43
+
44
+
45
+ # Dependency order: adr_schema imports adr_format.
46
+ _load_sibling("adr_format")
47
+ _load_sibling("adr_schema")
48
+
49
+ from adr_format import (
50
+ DEFAULT_PROFILE,
51
+ SUPPORTED_PROFILES,
52
+ AdrFormatError,
53
+ configured_profile,
54
+ normalize_profile,
55
+ profile_catalog,
56
+ profile_template_path,
57
+ unresolved_open_questions,
58
+ )
59
+ from adr_schema import (
60
+ DATE_RE,
61
+ VALID_STATUSES,
62
+ migrate_text,
63
+ parse_frontmatter,
64
+ render_frontmatter,
65
+ split_frontmatter,
66
+ )
67
+
68
+
69
+ STATUS_RE = re.compile(
70
+ r"(^##\s+Status(?!\s+History)\s*$\n+)([^\n]*)",
71
+ re.IGNORECASE | re.MULTILINE,
72
+ )
73
+ HISTORY_START_RE = re.compile(r"^\s*status_history\s*:\s*$", re.IGNORECASE | re.MULTILINE)
74
+ LEGAL_TRANSITIONS = {
75
+ "Proposed": {"Proposed", "Accepted", "Rejected"},
76
+ "Accepted": {"Accepted", "Superseded"},
77
+ "Rejected": {"Rejected"},
78
+ "Deprecated": {"Deprecated", "Superseded"},
79
+ "Amended": {"Amended", "Superseded"},
80
+ "Superseded": {"Superseded"},
81
+ }
82
+
83
+
84
+ class AdrLifecycleError(Exception):
85
+ """Raised on lifecycle command input or mutation errors."""
86
+
87
+
88
+ def normalize_adr_id(value: str) -> str:
89
+ match = re.search(r"(\d{1,4})", value)
90
+ if not match:
91
+ raise AdrLifecycleError(f"invalid ADR id: {value}")
92
+ return f"ADR-{int(match.group(1)):03d}"
93
+
94
+
95
+ def find_adr_file(adr_dir: Path, adr_id: str) -> Path:
96
+ num = int(re.search(r"\d+", adr_id).group(0))
97
+ matches = sorted(adr_dir.glob(f"ADR-{num:03d}-*.md"))
98
+ if len(matches) != 1:
99
+ raise AdrLifecycleError(
100
+ f"expected one file for {adr_id} in {adr_dir}, found {len(matches)}"
101
+ )
102
+ return matches[0]
103
+
104
+
105
+ def load_adr(path: Path) -> Tuple[Dict, str]:
106
+ text = path.read_text(encoding="utf-8")
107
+ migrated, _changed, issues = migrate_text(text, path)
108
+ if issues:
109
+ raise AdrLifecycleError(f"{path}: cannot normalize frontmatter: {issues}")
110
+ raw_frontmatter, body = split_frontmatter(migrated)
111
+ if raw_frontmatter is None:
112
+ raise AdrLifecycleError(f"{path}: frontmatter normalization failed")
113
+ return parse_frontmatter(raw_frontmatter), body
114
+
115
+
116
+ def _atomic_write_text(path: Path, text: str) -> None:
117
+ """Write one file through a unique same-directory temporary and replace."""
118
+ path.parent.mkdir(parents=True, exist_ok=True)
119
+ temp_path: Path | None = None
120
+ try:
121
+ with tempfile.NamedTemporaryFile(
122
+ mode="w",
123
+ encoding="utf-8",
124
+ newline="",
125
+ dir=path.parent,
126
+ prefix=f".{path.name}.",
127
+ suffix=".tmp",
128
+ delete=False,
129
+ ) as handle:
130
+ handle.write(text)
131
+ handle.flush()
132
+ os.fsync(handle.fileno())
133
+ temp_path = Path(handle.name)
134
+ os.replace(temp_path, path)
135
+ temp_path = None
136
+ finally:
137
+ if temp_path is not None:
138
+ temp_path.unlink(missing_ok=True)
139
+
140
+
141
+ def write_adr(path: Path, data: Dict, body: str) -> None:
142
+ _atomic_write_text(path, render_frontmatter(data) + body)
143
+
144
+
145
+ def _snapshot_files(paths: List[Path]) -> Dict[Path, Optional[bytes]]:
146
+ return {
147
+ path: path.read_bytes() if path.exists() else None
148
+ for path in dict.fromkeys(paths)
149
+ }
150
+
151
+
152
+ def _restore_snapshot(snapshot: Dict[Path, Optional[bytes]]) -> None:
153
+ errors = []
154
+ for path, content in snapshot.items():
155
+ try:
156
+ if content is None:
157
+ path.unlink(missing_ok=True)
158
+ else:
159
+ _atomic_write_text(path, content.decode("utf-8"))
160
+ except BaseException as exc: # pragma: no cover - catastrophic filesystem failure
161
+ errors.append(f"{path}: {exc}")
162
+ if errors:
163
+ raise AdrLifecycleError("snapshot restore failed: " + "; ".join(errors))
164
+
165
+
166
+ def _write_transaction(changes: List[Tuple[Path, str]]) -> None:
167
+ """Apply multiple atomic replacements and restore originals on any failure."""
168
+ originals = _snapshot_files([path for path, _ in changes])
169
+ try:
170
+ for path, text in changes:
171
+ _atomic_write_text(path, text)
172
+ except BaseException as exc:
173
+ try:
174
+ _restore_snapshot(originals)
175
+ except AdrLifecycleError as rollback_exc:
176
+ raise AdrLifecycleError(
177
+ f"transaction failed ({exc}); rollback also failed: {rollback_exc}"
178
+ ) from exc
179
+ raise AdrLifecycleError(f"transaction failed and was rolled back: {exc}") from exc
180
+
181
+
182
+ def assert_legal_transition(current: str, target: str) -> None:
183
+ legal = LEGAL_TRANSITIONS.get(current)
184
+ if legal is None or target not in legal:
185
+ allowed = ", ".join(sorted(legal or set())) or "none"
186
+ raise AdrLifecycleError(
187
+ f"illegal lifecycle transition {current} -> {target}; allowed: {allowed}"
188
+ )
189
+
190
+
191
+ def set_status_line(body: str, status_line: str) -> str:
192
+ if STATUS_RE.search(body):
193
+ return STATUS_RE.sub(rf"\g<1>{status_line}", body, count=1)
194
+ return f"\n## Status\n\n{status_line}\n\n{body}"
195
+
196
+
197
+ # A plain (unquoted) YAML scalar cannot contain ": ", cannot end in ":", and
198
+ # cannot begin with an indicator character. Emitting one anyway does not fail
199
+ # loudly: it re-reads as a nested mapping and takes the WHOLE status_history
200
+ # block down with it (TASK-70). Three ADRs in this repository were written that
201
+ # way before this guard existed, all through a `reason` holding free text like
202
+ # "Human approval: records the ...", and the recommended
203
+ # `--changed-by "User: <name>"` produces the same shape.
204
+ #
205
+ # It stayed invisible because adr-kit reads these blocks with its own
206
+ # line-oriented mini-parser, which takes everything after the first colon as
207
+ # the value. Only an external consumer with a real YAML parser sees the damage.
208
+ _YAML_INDICATORS = "-?:,[]{}#&*!|>'\"%@`"
209
+
210
+
211
+ def _yaml_scalar(value: str) -> str:
212
+ """Render a string as YAML, quoting only when a plain scalar would not survive."""
213
+ text = "" if value is None else str(value)
214
+ needs_quotes = (
215
+ text == ""
216
+ or text != text.strip()
217
+ or ": " in text
218
+ or text.endswith(":")
219
+ or " #" in text
220
+ or text[0] in _YAML_INDICATORS
221
+ )
222
+ if not needs_quotes:
223
+ return text
224
+ # Double-quoted style: the only YAML style that can represent every scalar.
225
+ escaped = text.replace("\\", "\\\\").replace('"', '\\"')
226
+ return f'"{escaped}"'
227
+
228
+
229
+ def history_entry(status: str, changed_by: str, reason: str, changed_via: str, when: str) -> str:
230
+ return (
231
+ f" - date: {_yaml_scalar(when)}\n"
232
+ f" status: {_yaml_scalar(status)}\n"
233
+ f" changed_by: {_yaml_scalar(changed_by)}\n"
234
+ f" reason: {_yaml_scalar(reason)}\n"
235
+ f" changed_via: {_yaml_scalar(changed_via)}\n"
236
+ )
237
+
238
+
239
+ def append_status_history(
240
+ body: str,
241
+ status: str,
242
+ changed_by: str,
243
+ reason: str,
244
+ changed_via: str,
245
+ when: str,
246
+ ) -> str:
247
+ entry = history_entry(status, changed_by, reason, changed_via, when)
248
+ start = HISTORY_START_RE.search(body)
249
+ if start:
250
+ closing = body.find("```", start.end())
251
+ if closing != -1:
252
+ return body[:closing] + entry + body[closing:]
253
+
254
+ section = (
255
+ "\n## Status History\n\n"
256
+ "```yaml\n"
257
+ "status_history:\n"
258
+ f"{entry}"
259
+ "```\n"
260
+ )
261
+ match = STATUS_RE.search(body)
262
+ if match:
263
+ insert_at = body.find("\n", match.end())
264
+ if insert_at == -1:
265
+ insert_at = match.end()
266
+ return body[:insert_at] + section + body[insert_at:]
267
+ return body + section
268
+
269
+
270
+ def read_status_line(body: str) -> Tuple[Optional[str], Optional[str]]:
271
+ """Return the (status, date) written in the body's Status section line."""
272
+ match = STATUS_RE.search(body)
273
+ if not match:
274
+ return None, None
275
+ line = match.group(2).strip()
276
+ word = re.match(r"([A-Za-z]+)", line)
277
+ status = word.group(1).capitalize() if word else None
278
+ if status not in VALID_STATUSES:
279
+ status = None
280
+ found_date = DATE_RE.search(line)
281
+ return status, (found_date.group(1) if found_date else None)
282
+
283
+
284
+ def prior_transition(path: Path, data: Dict, body: str) -> Tuple[str, str]:
285
+ """Return the (status, date) this ADR carried before the current mutation.
286
+
287
+ The Status line comes first because it is the half a lifecycle command is
288
+ about to overwrite; frontmatter fills in whichever field the prose omits.
289
+ Both are consulted before giving up: an ADR whose frontmatter plainly
290
+ records `status: "Accepted"` and `date: "2026-05-31"` has a recoverable
291
+ transition even when its Status line is unparseable prose.
292
+ """
293
+ status, when = read_status_line(body)
294
+ if status is None and data.get("status") in VALID_STATUSES:
295
+ status = str(data["status"])
296
+ if when is None and isinstance(data.get("date"), str):
297
+ when = data["date"]
298
+ if status is None or when is None:
299
+ missing = " and ".join(
300
+ name
301
+ for name, value in (("status", status), ("date", when))
302
+ if value is None
303
+ )
304
+ raise AdrLifecycleError(
305
+ f"{path}: refusing to mutate: this ADR has no '## Status History' "
306
+ f"block and its existing transition cannot be recovered (no {missing} "
307
+ "in the Status line or the frontmatter). Writing a history that "
308
+ "starts at this transition would drop the earlier one. Add a "
309
+ "'## Status History' block, or a Status line such as "
310
+ "'Accepted, YYYY-MM-DD.', and rerun."
311
+ )
312
+ return status, when
313
+
314
+
315
+ def ensure_status_history(
316
+ path: Path,
317
+ data: Dict,
318
+ body: str,
319
+ pending: Tuple[str, str],
320
+ ) -> str:
321
+ """Seed a missing status_history block with the transition already on file.
322
+
323
+ ADRs authored before the status_history convention record their acceptance
324
+ in exactly two places, the frontmatter `date` and the Status line, and a
325
+ lifecycle command overwrites both. Appending the new entry to a freshly
326
+ created block then loses that earlier transition for good (TASK-68), so it
327
+ is recovered here, from the record as it stands, before anything is
328
+ rewritten. Call this BEFORE set_status_line: afterwards the line it reads
329
+ is already the new one.
330
+ """
331
+ if HISTORY_START_RE.search(body):
332
+ return body
333
+ status, when = prior_transition(path, data, body)
334
+ if (status, when) == pending:
335
+ # Same status on the same day: there is no earlier transition to keep.
336
+ return body
337
+ return append_status_history(
338
+ body,
339
+ status,
340
+ # The actor genuinely was never recorded. Naming the current user or
341
+ # "adr-kit" would put a signature on a transition neither performed.
342
+ "unknown",
343
+ "Recovered from the record as it stood before this transition; this "
344
+ "ADR predates the status_history convention. The actor was never "
345
+ "recorded and is not guessed here.",
346
+ "unrecorded",
347
+ when,
348
+ )
349
+
350
+
351
+ def mutate_status(
352
+ path: Path,
353
+ status: str,
354
+ status_line: str,
355
+ when: str,
356
+ changed_by: str,
357
+ reason: str,
358
+ changed_via: str,
359
+ ) -> str:
360
+ data, body = load_adr(path)
361
+ assert_legal_transition(str(data.get("status")), status)
362
+ # Signer resolution comes after legality on purpose: an illegal transition
363
+ # must report that it is illegal, not that it is unsigned. Validate the act
364
+ # before validating the actor.
365
+ changed_by = resolve_signer(path.parent, changed_by)
366
+ body = ensure_status_history(path, data, body, (status, when))
367
+ data["status"] = status
368
+ data["date"] = when
369
+ if status != "Superseded":
370
+ data["superseded_by"] = None
371
+ body = set_status_line(body, status_line)
372
+ body = append_status_history(body, status, changed_by, reason, changed_via, when)
373
+ return render_frontmatter(data) + body
374
+
375
+
376
+ def run_index(adr_dir: Path) -> None:
377
+ script = Path(__file__).resolve().with_name("adr-index")
378
+ result = subprocess.run(
379
+ [sys.executable, str(script), str(adr_dir)],
380
+ capture_output=True,
381
+ text=True,
382
+ )
383
+ if result.returncode != 0:
384
+ raise AdrLifecycleError(result.stderr or result.stdout)
385
+
386
+
387
+ def _commit_lifecycle_changes(
388
+ adr_dir: Path,
389
+ changes: List[Tuple[Path, str]],
390
+ ) -> None:
391
+ """Commit ADR and generated-index changes as one recoverable operation."""
392
+ snapshot = _snapshot_files(
393
+ [path for path, _ in changes]
394
+ + [
395
+ adr_dir / "README.md",
396
+ adr_dir / "ADR-INDEX.md",
397
+ adr_dir / "ADR-INDEX.json",
398
+ ]
399
+ )
400
+ try:
401
+ _write_transaction(changes)
402
+ run_index(adr_dir)
403
+ except BaseException as exc:
404
+ try:
405
+ _restore_snapshot(snapshot)
406
+ except AdrLifecycleError as rollback_exc:
407
+ raise AdrLifecycleError(
408
+ f"lifecycle transaction failed ({exc}); rollback also failed: "
409
+ f"{rollback_exc}"
410
+ ) from exc
411
+ raise AdrLifecycleError(
412
+ "lifecycle transaction failed; ADRs and generated indexes were "
413
+ f"rolled back: {exc}"
414
+ ) from exc
415
+
416
+
417
+ def load_config(adr_dir: Path, explicit: str | None = None) -> Dict:
418
+ candidates = []
419
+ if explicit:
420
+ candidates.append(Path(explicit))
421
+ candidates.extend([adr_dir / ".adr-kit.json", adr_dir.parent.parent / ".adr-kit.json"])
422
+ for path in candidates:
423
+ if path.exists():
424
+ try:
425
+ return json.loads(path.read_text(encoding="utf-8"))
426
+ except json.JSONDecodeError as exc:
427
+ raise AdrLifecycleError(f"malformed config {path}: {exc}") from exc
428
+ return {}
429
+
430
+
431
+ def _slugify(title: str) -> str:
432
+ slug = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")
433
+ if not slug:
434
+ raise AdrLifecycleError("title must contain at least one letter or number")
435
+ return slug
436
+
437
+
438
+ def command_new(args) -> List[str]:
439
+ adr_dir = Path(args.adr_dir)
440
+ cfg = load_config(adr_dir, args.config)
441
+ try:
442
+ profile = normalize_profile(args.profile) if args.profile else configured_profile(cfg)
443
+ template_dir = Path(__file__).resolve().parent.parent / "templates"
444
+ template = profile_template_path(profile, template_dir)
445
+ except AdrFormatError as exc:
446
+ raise AdrLifecycleError(str(exc)) from exc
447
+
448
+ adr_dir.mkdir(parents=True, exist_ok=True)
449
+ used = []
450
+ for path in adr_dir.glob("ADR-*.md"):
451
+ match = re.match(r"(?i)^ADR-(\d{1,4})-", path.name)
452
+ if match:
453
+ used.append(int(match.group(1)))
454
+ number = max(used, default=0) + 1
455
+ adr_id = f"ADR-{number:03d}"
456
+ destination = adr_dir / f"{adr_id}-{_slugify(args.title)}.md"
457
+ if destination.exists():
458
+ raise AdrLifecycleError(f"ADR already exists: {destination}")
459
+
460
+ body = template.read_text(encoding="utf-8")
461
+ body = body.replace("ADR-NNN", adr_id)
462
+ body = body.replace('"Short Imperative Title"', json.dumps(args.title, ensure_ascii=False))
463
+ body = body.replace("Short Imperative Title", args.title)
464
+ body = body.replace("YYYY-MM-DD", args.date)
465
+ # The placeholder sits inside the status_history YAML block, so the actor
466
+ # has to survive as a YAML scalar. "User: Robert" - the very shape R8 of
467
+ # spec.md prescribes - is a mapping to a YAML parser, and an unquoted one
468
+ # makes the whole block unparseable. accept/supersede already route through
469
+ # _yaml_scalar; creation did not.
470
+ body = body.replace("user@example.com", _yaml_scalar(resolve_signer(adr_dir, args.changed_by)))
471
+ _commit_lifecycle_changes(adr_dir, [(destination, body)])
472
+ # Say it now, while the author is here. Retrieval metadata is optional
473
+ # frontmatter that nothing used to ask about, and 12 of this repository's
474
+ # 28 records ended up with none -- including the one that defines context
475
+ # injection, which a query about context injection therefore did not return.
476
+ # The tool cannot fill these in without inventing them, so it names them
477
+ # instead, in the same shape the signer proposal uses.
478
+ print(
479
+ f"[adr-kit] {destination.name} has no retrieval metadata yet. Fill in "
480
+ f"topics, aliases and components before accepting it, or an agent's "
481
+ f"query will not surface this decision. Components name what the ADR "
482
+ f"*defines*, not everything it touches.",
483
+ file=sys.stderr,
484
+ )
485
+ return [f"created: {destination} ({profile})"]
486
+
487
+
488
+ def command_profiles(args) -> List[str]:
489
+ template_dir = Path(__file__).resolve().parent.parent / "templates"
490
+ catalog = profile_catalog(template_dir)
491
+ if args.format == "json":
492
+ return [
493
+ json.dumps(
494
+ {
495
+ "default": DEFAULT_PROFILE,
496
+ "all_templates_available": all(
497
+ item["available"] for item in catalog
498
+ ),
499
+ "profiles": catalog,
500
+ },
501
+ indent=2,
502
+ )
503
+ ]
504
+
505
+ lines = [
506
+ "Shipped ADR profiles (only these identifiers are selectable):",
507
+ ]
508
+ for item in catalog:
509
+ preference = " (preferred)" if item["preferred"] else ""
510
+ availability = "available" if item["available"] else "MISSING"
511
+ lines.extend(
512
+ [
513
+ f"- {item['id']}{preference}: {item['label']} [{availability}]",
514
+ f" Template: {item['template']}",
515
+ f" Best for: {item['best_for']}",
516
+ f" Trade-off: {item['trade_off']}",
517
+ ]
518
+ )
519
+ lines.append(
520
+ "Select with `adr new --profile <id>` or "
521
+ '`template.profile: "<id>"`; do not invent profile names.'
522
+ )
523
+ return lines
524
+
525
+
526
+ def _auto_accept_config(args, adr_dir: Path) -> Tuple[str, float]:
527
+ cfg = load_config(adr_dir, getattr(args, "config", None))
528
+ auto_cfg = cfg.get("lifecycle", {}).get("auto_accept", {})
529
+ mode = args.auto_mode or auto_cfg.get("mode", "assist")
530
+ if mode not in {"auto", "assist"}:
531
+ raise AdrLifecycleError("auto_accept mode must be 'auto' or 'assist'")
532
+ threshold = (
533
+ args.quality_threshold
534
+ if args.quality_threshold is not None
535
+ else float(auto_cfg.get("quality_threshold", 0.70))
536
+ )
537
+ return mode, threshold
538
+
539
+
540
+ def _run_json_tool(command: List[str]) -> Tuple[int, Dict]:
541
+ result = subprocess.run(command, capture_output=True, text=True)
542
+ if result.returncode != 0 and not result.stdout.strip():
543
+ # A non-zero exit with no stdout is a crash, not a gate verdict: the
544
+ # tool never reached its JSON writer. Surface stderr instead of
545
+ # swallowing it behind an empty payload (which read as "{}" downstream).
546
+ stderr = result.stderr.strip() or "<no stderr>"
547
+ raise AdrLifecycleError(
548
+ f"tool crashed (exit {result.returncode}): {' '.join(command)}: {stderr}"
549
+ )
550
+ try:
551
+ payload = json.loads(result.stdout) if result.stdout.strip() else {}
552
+ except json.JSONDecodeError as exc:
553
+ raise AdrLifecycleError(
554
+ f"tool returned non-JSON output: {' '.join(command)}: {exc}"
555
+ ) from exc
556
+ return result.returncode, payload
557
+
558
+
559
+ def _scaffold_residue(text: str) -> List[str]:
560
+ """Instruction lines from the shipped templates that survived authoring.
561
+
562
+ Every gate the auto path runs is structural: is the section present, does
563
+ the frontmatter parse, does the quality heuristic score high enough. An
564
+ untouched scaffold satisfies all three -- it is a complete, well-formed ADR
565
+ that happens to decide nothing, and it scored 0.88 against a 0.70 default.
566
+ Auto-accepting that would put "Chosen option: **Option A**, because state
567
+ the decisive rationale" into the record as an Accepted decision.
568
+
569
+ These strings are literal instructions to the author. Their presence is not
570
+ a heuristic about quality; it is proof that a section was never written.
571
+ """
572
+ markers = (
573
+ "because state the decisive rationale",
574
+ "State how implementation of the decision will be verified.",
575
+ "Describe the context and problem statement",
576
+ "{Describe",
577
+ "<!-- adr-kit:template-placeholder -->",
578
+ )
579
+ return [marker for marker in markers if marker in text]
580
+
581
+
582
+ def _assert_auto_accept_eligible(path: Path, args, threshold: float) -> Dict:
583
+ data, _body = load_adr(path)
584
+ if data.get("documents_shipped") is not True:
585
+ raise AdrLifecycleError("auto accept requires documents_shipped:true")
586
+ if not data.get("verified_in"):
587
+ raise AdrLifecycleError("auto accept requires at least one verified_in pointer")
588
+
589
+ residue = _scaffold_residue(path.read_text(encoding="utf-8"))
590
+ if residue:
591
+ raise AdrLifecycleError(
592
+ "auto accept blocked: the record still contains template instructions "
593
+ f"({'; '.join(repr(item) for item in residue)}). A scaffold is "
594
+ "structurally complete and decides nothing; write the sections, then "
595
+ "accept."
596
+ )
597
+
598
+ lint_summary = _assert_acceptance_gates(path, args)
599
+ quality_script = Path(__file__).resolve().with_name("adr-quality")
600
+ _quality_code, quality_payload = _run_json_tool(
601
+ [sys.executable, str(quality_script), "--format", "json", str(path)]
602
+ )
603
+ overall = float(quality_payload.get("overall", 0.0))
604
+ if overall < threshold:
605
+ raise AdrLifecycleError(
606
+ f"auto accept blocked: quality {overall:.2f} below threshold {threshold:.2f}"
607
+ )
608
+ return {"quality": overall, "threshold": threshold, "lint": lint_summary}
609
+
610
+
611
+ def _assert_acceptance_gates(path: Path, args) -> Dict:
612
+ """Require deterministic versions of all four named gates before acceptance."""
613
+ open_questions = unresolved_open_questions(path.read_text(encoding="utf-8"))
614
+ if open_questions:
615
+ raise AdrLifecycleError(
616
+ "acceptance blocked: unresolved Open Questions: "
617
+ + "; ".join(open_questions)
618
+ )
619
+ root = Path(args.repo_root).resolve() if args.repo_root else Path.cwd().resolve()
620
+ lint_script = Path(__file__).resolve().with_name("adr-lint")
621
+ # --context-dir hands the lint the sibling ADRs to resolve cross-references
622
+ # against while it still reports on this file alone. Without it a
623
+ # `supersedes` entry could never find its target and every acceptance of a
624
+ # correctly linked successor failed with "target not found" (TASK-67).
625
+ lint_code, lint_payload = _run_json_tool(
626
+ [
627
+ sys.executable,
628
+ str(lint_script),
629
+ "--strict",
630
+ "--format",
631
+ "json",
632
+ "--gates",
633
+ "schema,completeness,audit,evidence,clarity,consistency,policy",
634
+ "--repo-root",
635
+ str(root),
636
+ "--context-dir",
637
+ str(path.parent),
638
+ str(path),
639
+ ]
640
+ )
641
+ if lint_code != 0:
642
+ # Report what failed, not just how many did. The counts alone sent
643
+ # readers back to adr-lint to find out what the blocker actually was.
644
+ failures = [
645
+ f"{finding.get('gate', '?')}: {finding.get('summary', '')}".strip()
646
+ for entry in lint_payload.get("files", [])
647
+ for finding in entry.get("findings", [])
648
+ if finding.get("level") == "FAIL"
649
+ ]
650
+ detail = "; ".join(failures) if failures else "see adr-lint output"
651
+ raise AdrLifecycleError(
652
+ "acceptance blocked: strict lint failed ("
653
+ + json.dumps(lint_payload.get("summary", {}), sort_keys=True)
654
+ + f"): {detail}"
655
+ )
656
+ return lint_payload.get("summary", {})
657
+
658
+
659
+ def command_document(args) -> List[str]:
660
+ adr_dir = Path(args.adr_dir)
661
+ adr_id = normalize_adr_id(args.adr)
662
+ path = find_adr_file(adr_dir, adr_id)
663
+ if not args.verified_in:
664
+ raise AdrLifecycleError("document requires at least one --verified-in pointer")
665
+ data, body = load_adr(path)
666
+ # `document` writes a history entry like every other lifecycle command, so
667
+ # it has to resolve a signer like every other lifecycle command. It did not,
668
+ # and wrote `changed_by: ""` -- which the audit gate then rejected, so an
669
+ # ADR that had just been correctly marked as documenting shipped behaviour
670
+ # could never be accepted. The failure surfaced two commands later, blaming
671
+ # acceptance for a defect introduced here.
672
+ changed_by = resolve_signer(adr_dir, args.changed_by)
673
+ body = ensure_status_history(
674
+ path, data, body, (str(data["status"]), args.date)
675
+ )
676
+ data["documents_shipped"] = True
677
+ data["verified_in"] = args.verified_in
678
+ body = append_status_history(
679
+ body,
680
+ data["status"],
681
+ changed_by,
682
+ args.reason or "Documented already-shipped behavior",
683
+ "adr-kit lifecycle",
684
+ args.date,
685
+ )
686
+ _commit_lifecycle_changes(
687
+ adr_dir,
688
+ [(path, render_frontmatter(data) + body)],
689
+ )
690
+ return [f"documented shipped behavior: {path.name}"]
691
+
692
+
693
+ def command_auto_accept(args) -> List[str]:
694
+ adr_dir = Path(args.adr_dir)
695
+ adr_id = normalize_adr_id(args.adr)
696
+ path = find_adr_file(adr_dir, adr_id)
697
+ mode, threshold = _auto_accept_config(args, adr_dir)
698
+ eligibility = _assert_auto_accept_eligible(path, args, threshold)
699
+ if mode == "assist" and not args.confirm:
700
+ return [
701
+ f"assist: {path.name} is eligible for auto accept "
702
+ f"(quality={eligibility['quality']:.2f}, threshold={threshold:.2f}); "
703
+ "rerun with --confirm to mutate"
704
+ ]
705
+ changed = mutate_status(
706
+ path,
707
+ "Accepted",
708
+ f"Accepted, {args.date}.",
709
+ args.date,
710
+ args.changed_by,
711
+ args.reason or "Auto-accepted already-shipped ADR with verified evidence",
712
+ "adr-kit lifecycle",
713
+ )
714
+ _commit_lifecycle_changes(adr_dir, [(path, changed)])
715
+ return [f"auto-accepted: {path.name}"]
716
+
717
+
718
+ def _assert_acceptance_was_asked_for(path: Path, args) -> None:
719
+ """Acceptance is the one transition that must be typed on purpose.
720
+
721
+ Every other lifecycle command records something. This one *decides*, and it
722
+ writes a name and a date into a history that is immutable from that moment
723
+ on. With `lifecycle.signer` configured -- the common case now that the signer
724
+ is derived rather than demanded -- a call that nobody meant to make wrote the
725
+ user's own name, a plausible reason and today's date into a record they never
726
+ saw. A false attribution is worse than a missing one; that is spec R8's own
727
+ argument, turned against the command that implements it.
728
+
729
+ So acceptance requires `--confirm`, the same shape auto-accept's assist mode
730
+ already uses. What that buys is narrow and worth stating exactly: an
731
+ acceptance can no longer happen *by accident* -- from a script written for an
732
+ older interface, from a CI job, from an agent following a stale instruction.
733
+ It does not stop a caller who deliberately passes the flag, and nothing at
734
+ the process level could: an agent runs with the user's own terminal, working
735
+ directory and environment, so there is no signal that distinguishes it from
736
+ the user typing.
737
+
738
+ Inferring presence from `sys.stdin.isatty()` was tried first and is wrong on
739
+ the platform this kit marks release-required. Measured: a Windows subprocess
740
+ with `stdin=DEVNULL` reports `isatty() == True`, because `NUL` is a character
741
+ device and the C runtime answers about the device rather than about a
742
+ terminal. A presence test that returns "someone is there" for /dev/null is
743
+ worse than no test, because it reads as a guarantee.
744
+
745
+ `accept --auto` is untouched. spec R1 grants the init flow that exception
746
+ explicitly: there the user asked for a batch of records covering code that
747
+ already exists, and that request is the consent.
748
+ """
749
+ if args.confirm:
750
+ return
751
+ signer = resolve_signer(Path(args.adr_dir), args.changed_by, announce=False)
752
+ raise AdrLifecycleError(
753
+ f"acceptance blocked: {path.name} would be signed as {signer!r}.\n"
754
+ " Acceptance writes that name into a history that is immutable "
755
+ "afterwards,\n"
756
+ " so it has to be asked for rather than arrived at.\n"
757
+ " Re-run with --confirm once a human has agreed to this decision."
758
+ )
759
+
760
+
761
+ def command_accept(args) -> List[str]:
762
+ adr_dir = Path(args.adr_dir)
763
+ adr_id = normalize_adr_id(args.adr)
764
+ path = find_adr_file(adr_dir, adr_id)
765
+ # Gates first, then the flag. A record that cannot be accepted should say
766
+ # why it cannot be accepted; telling the author to add --confirm and only
767
+ # then telling them the record is incomplete costs a round trip and buries
768
+ # the actual problem. The flag is the last thing checked before the write,
769
+ # which is also where it means what it says.
770
+ _assert_acceptance_gates(path, args)
771
+ _assert_acceptance_was_asked_for(path, args)
772
+ changed = mutate_status(
773
+ path,
774
+ "Accepted",
775
+ f"Accepted, {args.date}.",
776
+ args.date,
777
+ args.changed_by,
778
+ args.reason or "Accepted decision after all four verification gates passed",
779
+ "adr-kit lifecycle",
780
+ )
781
+ _commit_lifecycle_changes(adr_dir, [(path, changed)])
782
+ return [f"accepted: {path.name}"]
783
+
784
+
785
+ def command_set_status(args, status: str, status_line: str, default_reason: str) -> List[str]:
786
+ adr_dir = Path(args.adr_dir)
787
+ adr_id = normalize_adr_id(args.adr)
788
+ path = find_adr_file(adr_dir, adr_id)
789
+ changed = mutate_status(
790
+ path,
791
+ status,
792
+ status_line,
793
+ args.date,
794
+ args.changed_by,
795
+ args.reason or default_reason,
796
+ "adr-kit lifecycle",
797
+ )
798
+ _commit_lifecycle_changes(adr_dir, [(path, changed)])
799
+ return [f"{status.lower()}: {path.name}"]
800
+
801
+
802
+ ANSWERED_LINE_RE = re.compile(
803
+ r"^\s*[-*+]\s*\[[xX]\]\s+(?P<question>.+?)\s+—\s+\*\*Answered\b", re.MULTILINE
804
+ )
805
+
806
+
807
+ def _open_questions_section(body: str) -> Tuple[int, int, str]:
808
+ """(start, end, text) of the Open Questions section body. Raises if absent."""
809
+ match = re.search(
810
+ r"^##\s+Open Questions\s*$\n(?P<body>.*?)(?=\n##\s+|\Z)",
811
+ body,
812
+ re.MULTILINE | re.DOTALL,
813
+ )
814
+ if not match:
815
+ raise AdrLifecycleError(
816
+ "this ADR has no `## Open Questions` section; add one, or the answer "
817
+ "has nowhere durable to live"
818
+ )
819
+ return match.start("body"), match.end("body"), match.group("body")
820
+
821
+
822
+ def command_answer(args) -> List[str]:
823
+ """Resolve an open question in place, keeping both halves of the exchange.
824
+
825
+ Grilling asks a question and gets an answer, and until now only one of the
826
+ two survived. `## Open Questions` holds unresolved items by design, and
827
+ acceptance requires the list to be empty, so an author who answered a
828
+ question had to *delete* it to accept the ADR. What remained was the Status
829
+ History: who flipped the status and when, never what they were asked.
830
+
831
+ That reasoning is exactly what a future reader needs to re-evaluate a
832
+ decision, and re-evaluation is what supersession depends on.
833
+
834
+ Nothing new had to be invented to fix it. `unresolved_open_questions`
835
+ already skips a `[x]` item, so a checked line with the answer written into
836
+ it survives acceptance untouched and stays in the record forever. This
837
+ command writes that line, so the convention is a mechanism rather than a
838
+ hope, and the signer and date come from the same resolution every other
839
+ lifecycle command uses.
840
+ """
841
+ adr_dir = Path(args.adr_dir)
842
+ adr_id = normalize_adr_id(args.adr)
843
+ path = find_adr_file(adr_dir, adr_id)
844
+ if not str(args.answer).strip():
845
+ raise AdrLifecycleError("an answer with no text is a deletion with extra steps")
846
+
847
+ data, body = load_adr(path)
848
+ start, end, section = _open_questions_section(body)
849
+
850
+ lines = section.splitlines()
851
+ unresolved = [
852
+ (index, line)
853
+ for index, line in enumerate(lines)
854
+ if re.match(r"^\s*[-*+]\s*(?:\[\s\]\s+)?\S", line)
855
+ and not re.match(r"^\s*[-*+]\s*\[[xX]\]", line)
856
+ and re.sub(r"^\s*[-*+]\s*(?:\[\s\]\s+)?", "", line).strip().casefold().rstrip(".")
857
+ not in {"none", "no open questions", "no unresolved questions"}
858
+ ]
859
+ if not unresolved:
860
+ raise AdrLifecycleError(f"{adr_id} has no unresolved question to answer")
861
+
862
+ target = _select_question(unresolved, args.question)
863
+ index, line = target
864
+ question_text = re.sub(r"^\s*[-*+]\s*(?:\[\s\]\s+)?", "", line).strip()
865
+ changed_by = resolve_signer(adr_dir, args.changed_by)
866
+ lines[index] = (
867
+ f"- [x] {question_text} — **Answered {args.date} by {changed_by}:** "
868
+ f"{str(args.answer).strip()}"
869
+ )
870
+
871
+ # splitlines() drops the section's trailing newline; putting it back is what
872
+ # keeps the blank line before the next heading, and a heading that loses its
873
+ # blank line stops being a heading to some Markdown readers.
874
+ rewritten = "\n".join(lines) + ("\n" if section.endswith("\n") else "")
875
+ body = body[:start] + rewritten + body[end:]
876
+ _commit_lifecycle_changes(adr_dir, [(path, render_frontmatter(data) + body)])
877
+ return [
878
+ f"answered in {path.name}: {question_text[:70]}",
879
+ "the question and its answer stay in the record; acceptance is no longer blocked by it",
880
+ ]
881
+
882
+
883
+ def _select_question(unresolved: List[Tuple[int, str]], wanted: Optional[str]):
884
+ """Pick the question to answer: the only one, an index, or a substring."""
885
+ if wanted is None:
886
+ if len(unresolved) > 1:
887
+ listing = "; ".join(
888
+ f"{position}: "
889
+ + re.sub(r"^\s*[-*+]\s*(?:\[\s\]\s+)?", "", line).strip()[:60]
890
+ for position, (_index, line) in enumerate(unresolved, 1)
891
+ )
892
+ raise AdrLifecycleError(
893
+ f"{len(unresolved)} unresolved questions; name one with "
894
+ f"--question <number|text>. {listing}"
895
+ )
896
+ return unresolved[0]
897
+
898
+ if re.fullmatch(r"\d+", str(wanted).strip()):
899
+ position = int(str(wanted).strip())
900
+ if not 1 <= position <= len(unresolved):
901
+ raise AdrLifecycleError(
902
+ f"--question {position} is out of range (1..{len(unresolved)})"
903
+ )
904
+ return unresolved[position - 1]
905
+
906
+ needle = str(wanted).casefold()
907
+ matches = [item for item in unresolved if needle in item[1].casefold()]
908
+ if not matches:
909
+ raise AdrLifecycleError(f"no unresolved question matches {wanted!r}")
910
+ if len(matches) > 1:
911
+ raise AdrLifecycleError(
912
+ f"{wanted!r} matches {len(matches)} unresolved questions; be more specific"
913
+ )
914
+ return matches[0]
915
+
916
+
917
+ def command_relate(args) -> List[str]:
918
+ """Write a cross-reference on both sides, or remove it from both.
919
+
920
+ Supersession has always been reciprocal: `bin/adr supersede` writes the
921
+ predecessor's `superseded_by` and the successor's `supersedes` in one
922
+ transaction, so neither side can carry half a link. A plain cross-reference
923
+ had no such writer. An ADR could cite ADR-009 forever while ADR-009 never
924
+ learned it was cited, which is exactly the half-link the supersession check
925
+ refuses to tolerate.
926
+
927
+ The link goes in frontmatter, next to `supersedes`, not into the prose. That
928
+ keeps this inside the mutation envelope the kit already permits on an
929
+ Accepted record -- reference bookkeeping, never the decision itself. The
930
+ body of an Accepted ADR stays untouched here, as it must.
931
+
932
+ A pair that already has a supersession relationship is refused rather than
933
+ doubled: superseded-by is the stronger and more specific edge, and recording
934
+ both would let a reader believe there are two relationships where there is
935
+ one.
936
+ """
937
+ adr_dir = Path(args.adr_dir)
938
+ left_id = normalize_adr_id(args.adr)
939
+ right_id = normalize_adr_id(args.to)
940
+ if left_id == right_id:
941
+ raise AdrLifecycleError("an ADR cannot be related to itself")
942
+ left_path = find_adr_file(adr_dir, left_id)
943
+ right_path = find_adr_file(adr_dir, right_id)
944
+
945
+ left_data, left_body = load_adr(left_path)
946
+ right_data, right_body = load_adr(right_path)
947
+
948
+ for this_id, this_data, other_id in (
949
+ (left_id, left_data, right_id),
950
+ (right_id, right_data, left_id),
951
+ ):
952
+ if other_id in (this_data.get("supersedes") or []):
953
+ raise AdrLifecycleError(
954
+ f"{this_id} already supersedes {other_id}; supersession is the "
955
+ "stronger relationship and is already recorded on both sides"
956
+ )
957
+ if this_data.get("superseded_by") == other_id:
958
+ raise AdrLifecycleError(
959
+ f"{this_id} is already superseded by {other_id}; supersession is "
960
+ "the stronger relationship and is already recorded on both sides"
961
+ )
962
+
963
+ def apply(data: Dict, other_id: str) -> bool:
964
+ current = [normalize_adr_id(item) or item for item in (data.get("related") or [])]
965
+ wanted = [item for item in current if item != other_id]
966
+ if not args.remove:
967
+ wanted.append(other_id)
968
+ wanted = sorted(set(wanted))
969
+ if wanted == sorted(set(current)):
970
+ return False
971
+ # An empty list would be an assertion that the question was asked and
972
+ # the answer was none. It was not: the link was simply removed. Drop the
973
+ # key so absent keeps meaning "nothing declared here".
974
+ if wanted:
975
+ data["related"] = wanted
976
+ else:
977
+ data.pop("related", None)
978
+ return True
979
+
980
+ left_changed = apply(left_data, right_id)
981
+ right_changed = apply(right_data, left_id)
982
+ if not left_changed and not right_changed:
983
+ verb = "not related" if args.remove else "already related"
984
+ return [f"{left_id} and {right_id} are {verb}; nothing to do"]
985
+
986
+ # The signer is resolved once, before any write, so a machine with no
987
+ # configured signer refuses the whole operation instead of half of it.
988
+ changed_by = resolve_signer(adr_dir, args.changed_by)
989
+ action = "Unrelated" if args.remove else "Related"
990
+ changes: List[Tuple[Path, str]] = []
991
+ for path, data, body, other_id in (
992
+ (left_path, left_data, left_body, right_id),
993
+ (right_path, right_data, right_body, left_id),
994
+ ):
995
+ body = ensure_status_history(path, data, body, (str(data.get("status")), args.date))
996
+ body = append_status_history(
997
+ body,
998
+ str(data.get("status")),
999
+ changed_by,
1000
+ args.reason or f"{action} to {other_id}",
1001
+ "adr-kit lifecycle",
1002
+ args.date,
1003
+ )
1004
+ changes.append((path, render_frontmatter(data) + body))
1005
+ _commit_lifecycle_changes(adr_dir, changes)
1006
+ joiner = "no longer related to" if args.remove else "related to"
1007
+ return [
1008
+ f"{left_path.name}: {joiner} {right_id}",
1009
+ f"{right_path.name}: {joiner} {left_id}",
1010
+ ]
1011
+
1012
+
1013
+ def command_supersede(args) -> List[str]:
1014
+ adr_dir = Path(args.adr_dir)
1015
+ old_id = normalize_adr_id(args.old)
1016
+ new_id = normalize_adr_id(args.by)
1017
+ old_path = find_adr_file(adr_dir, old_id)
1018
+ new_path = find_adr_file(adr_dir, new_id)
1019
+ if old_id == new_id:
1020
+ raise AdrLifecycleError("an ADR cannot supersede itself")
1021
+
1022
+ old_data, old_body = load_adr(old_path)
1023
+ new_data, new_body = load_adr(new_path)
1024
+ assert_legal_transition(str(old_data.get("status")), "Superseded")
1025
+ if old_data.get("superseded_by") not in (None, new_id):
1026
+ raise AdrLifecycleError(
1027
+ f"{old_id} already has superseded_by={old_data.get('superseded_by')}"
1028
+ )
1029
+ if new_data.get("status") not in {"Proposed", "Accepted"}:
1030
+ raise AdrLifecycleError(f"{new_id} must be Proposed or Accepted")
1031
+ if new_data.get("superseded_by") is not None:
1032
+ raise AdrLifecycleError(
1033
+ f"{new_id} is itself superseded by {new_data.get('superseded_by')}"
1034
+ )
1035
+ # A successor may supersede several predecessors: `supersedes` is a list in
1036
+ # the schema, the index and the lint both resolve every entry, and one
1037
+ # decision can legitimately retire more than one record. What stays
1038
+ # exclusive is the other direction, enforced below: each predecessor gets
1039
+ # exactly one successor.
1040
+ for candidate in sorted(adr_dir.glob("ADR-*.md")):
1041
+ if candidate in {old_path, new_path}:
1042
+ continue
1043
+ candidate_data, _candidate_body = load_adr(candidate)
1044
+ if old_id in candidate_data.get("supersedes", []):
1045
+ raise AdrLifecycleError(
1046
+ f"{old_id} already has competing successor "
1047
+ f"{candidate_data.get('id', candidate.name)}"
1048
+ )
1049
+
1050
+ # Both files are seeded before either is mutated: prior_transition reads the
1051
+ # frontmatter status and date that the lines below overwrite.
1052
+ old_body = ensure_status_history(
1053
+ old_path, old_data, old_body, ("Superseded", args.date)
1054
+ )
1055
+ new_body = ensure_status_history(
1056
+ new_path, new_data, new_body, (str(new_data["status"]), args.date)
1057
+ )
1058
+
1059
+ # Resolved here, after both seeds. Every other lifecycle command gets its
1060
+ # signer inside `mutate_status`; supersede appends to the history directly
1061
+ # and so has to resolve it itself, or both entries land with an empty
1062
+ # `changed_by` -- which the audit gate rejects on the successor, at the
1063
+ # exact moment someone tries to accept it.
1064
+ #
1065
+ # After, not before: `ensure_status_history` above refuses a record whose
1066
+ # prior transition cannot be recovered, and that is a fact about the record,
1067
+ # not about who is asking. Resolving the actor first makes an unconfigured
1068
+ # machine report a missing signer for a record that could not be superseded
1069
+ # by anyone. Validate the act, then the actor.
1070
+ changed_by = resolve_signer(adr_dir, args.changed_by)
1071
+
1072
+ old_data["status"] = "Superseded"
1073
+ old_data["date"] = args.date
1074
+ old_data["superseded_by"] = new_id
1075
+ old_body = set_status_line(old_body, f"Superseded by {new_id}, {args.date}.")
1076
+ old_body = append_status_history(
1077
+ old_body,
1078
+ "Superseded",
1079
+ changed_by,
1080
+ args.reason or f"Superseded by {new_id}",
1081
+ "adr-kit lifecycle",
1082
+ args.date,
1083
+ )
1084
+ supersedes = list(new_data.get("supersedes", []))
1085
+ if old_id not in supersedes:
1086
+ supersedes.append(old_id)
1087
+ new_data["supersedes"] = sorted(supersedes)
1088
+ new_body = append_status_history(
1089
+ new_body,
1090
+ new_data["status"],
1091
+ changed_by,
1092
+ args.reason or f"Supersedes {old_id}",
1093
+ "adr-kit lifecycle",
1094
+ args.date,
1095
+ )
1096
+ changes = [
1097
+ (new_path, render_frontmatter(new_data) + new_body),
1098
+ (old_path, render_frontmatter(old_data) + old_body),
1099
+ ]
1100
+ _commit_lifecycle_changes(adr_dir, changes)
1101
+ return [f"superseded: {old_path.name} -> {new_id}", f"updated successor: {new_path.name}"]
1102
+
1103
+
1104
+
1105
+ # --- Signer resolution (spec R8/R8.1) -------------------------------------
1106
+ #
1107
+ # The actor written into Status History used to default to the literal
1108
+ # "adr-kit", so forgetting the flag produced a durable record saying the tool
1109
+ # accepted its own ADR. That is worse than an unsigned record: it is a false
1110
+ # attribution in the one place an auditor looks.
1111
+ #
1112
+ # The signer lives in the gitignored machine-local config, not in the tracked
1113
+ # one. A committed signer would put one person's name on every teammate's
1114
+ # acceptance.
1115
+ #
1116
+ # What this does NOT do, stated so nobody mistakes it: it does not prove a human
1117
+ # was present, and it authenticates nothing. It makes the signature attributable
1118
+ # and deliberate. Real non-repudiation needs signed commits, which is a separate
1119
+ # decision nobody has taken yet.
1120
+
1121
+ LOCAL_CONFIG_NAME = ".adr-kit.local.json"
1122
+
1123
+
1124
+ def read_local_config(adr_dir: Path) -> dict:
1125
+ """Read the machine-local config, or {} when absent or unreadable."""
1126
+ try:
1127
+ data = json.loads((Path(adr_dir) / LOCAL_CONFIG_NAME).read_text(encoding="utf-8"))
1128
+ except (OSError, json.JSONDecodeError, ValueError):
1129
+ return {}
1130
+ return data if isinstance(data, dict) else {}
1131
+
1132
+
1133
+ def configured_signer(adr_dir: Path) -> Optional[str]:
1134
+ signer = (read_local_config(adr_dir).get("lifecycle") or {}).get("signer")
1135
+ return signer.strip() if isinstance(signer, str) and signer.strip() else None
1136
+
1137
+
1138
+ def git_user_name() -> Optional[str]:
1139
+ """`git config user.name`, or None."""
1140
+ try:
1141
+ out = subprocess.run(
1142
+ ["git", "config", "user.name"],
1143
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
1144
+ timeout=5, check=False,
1145
+ )
1146
+ except (OSError, subprocess.SubprocessError):
1147
+ return None
1148
+ name = (out.stdout or "").strip()
1149
+ return name or None
1150
+
1151
+
1152
+ # Identities that are configured but are not a person. Adopting one would put a
1153
+ # machine's name under a human acceptance, which is the exact thing R8 exists to
1154
+ # prevent -- so these fall through to the refusal, where a human is asked.
1155
+ _NON_PERSON_SIGNER_RE = re.compile(
1156
+ r"(?i)^(?:"
1157
+ r".*\[bot\]|"
1158
+ r"github[-_ ]?actions?|dependabot|renovate(?:\[bot\])?|"
1159
+ r"semantic-release|release[-_ ]?bot|.*\bbot\b|"
1160
+ r"ci|build|builder|runner|jenkins|buildkite|circleci|travis|"
1161
+ r"root|admin|administrator|user|unknown|your name|"
1162
+ r"adr-kit"
1163
+ r")$"
1164
+ )
1165
+
1166
+
1167
+ def github_identity() -> List[Dict[str, str]]:
1168
+ """The signed-in GitHub account's real name and login, if `gh` can say.
1169
+
1170
+ Asked for at install and upgrade time, never on the lifecycle hot path: it
1171
+ is a network call through someone else's CLI, and a tool that blocks an ADR
1172
+ write on GitHub being reachable would be trading a good property for a bad
1173
+ one.
1174
+ """
1175
+ if shutil.which("gh") is None:
1176
+ return []
1177
+ try:
1178
+ out = subprocess.run(
1179
+ ["gh", "api", "user", "--jq", "{name: .name, login: .login}"],
1180
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
1181
+ timeout=10, check=False,
1182
+ )
1183
+ except (OSError, subprocess.SubprocessError):
1184
+ return []
1185
+ if out.returncode != 0:
1186
+ return []
1187
+ try:
1188
+ payload = json.loads(out.stdout or "{}")
1189
+ except (json.JSONDecodeError, ValueError):
1190
+ return []
1191
+ found: List[Dict[str, str]] = []
1192
+ if isinstance(payload, dict):
1193
+ if payload.get("name"):
1194
+ found.append({"name": str(payload["name"]).strip(),
1195
+ "source": "gh api user (.name)"})
1196
+ if payload.get("login"):
1197
+ found.append({"name": str(payload["login"]).strip(),
1198
+ "source": "gh api user (.login)"})
1199
+ return found
1200
+
1201
+
1202
+ def signer_candidates() -> List[Dict[str, str]]:
1203
+ """Ranked identities to propose at install or upgrade time.
1204
+
1205
+ Ordered by how well each names a human: the GitHub profile name first
1206
+ because it is the one a person actually chose to be called, then the git
1207
+ identity that already signs their commits, then the GitHub login. Each
1208
+ carries its source, because a proposal the user cannot trace is one they
1209
+ cannot judge -- and this value ends up in an immutable Status History.
1210
+
1211
+ Duplicates collapse: on most machines the GitHub name and `git config
1212
+ user.name` are the same string, and offering it twice would look like two
1213
+ different options.
1214
+ """
1215
+ raw: List[Dict[str, str]] = []
1216
+ github = github_identity()
1217
+ raw.extend(entry for entry in github if entry["source"].endswith("(.name)"))
1218
+ name = git_user_name()
1219
+ if name:
1220
+ raw.append({"name": name, "source": "git config user.name"})
1221
+ raw.extend(entry for entry in github if entry["source"].endswith("(.login)"))
1222
+
1223
+ seen: set[str] = set()
1224
+ candidates: List[Dict[str, str]] = []
1225
+ for entry in raw:
1226
+ key = entry["name"].casefold()
1227
+ if key in seen or not person_shaped(entry["name"]):
1228
+ continue
1229
+ seen.add(key)
1230
+ candidates.append({
1231
+ "name": entry["name"],
1232
+ "source": entry["source"],
1233
+ "actor": f"User: {entry['name']}",
1234
+ })
1235
+ return candidates
1236
+
1237
+
1238
+ def person_shaped(name: Optional[str]) -> bool:
1239
+ """Does this identity plausibly name a human who could accept a decision?"""
1240
+ if not name or not name.strip():
1241
+ return False
1242
+ candidate = name.strip()
1243
+ if _NON_PERSON_SIGNER_RE.match(candidate):
1244
+ return False
1245
+ # An email-only identity is a person, but a bare address reads badly in a
1246
+ # history line; git's user.name is expected to be a name.
1247
+ return not candidate.startswith("<") and "@" not in candidate.split()[0]
1248
+
1249
+
1250
+ def resolve_signer(
1251
+ adr_dir: Path,
1252
+ explicit: Optional[str],
1253
+ announce: bool = True,
1254
+ ) -> str:
1255
+ """Explicit flag, then configured signer, then git, then refuse.
1256
+
1257
+ Reading `git config user.name` is not the tool signing on someone's behalf.
1258
+ R8.1 forbids "a default that names the tool" -- the old `adr-kit` actor,
1259
+ where the toolkit wrote itself into the record as the decider. A git
1260
+ identity is the opposite of that: it is a value the human configured on
1261
+ this machine, and every commit in the repository already carries it.
1262
+
1263
+ What survives from the stricter version is the *silence*, not the refusal.
1264
+ A derived actor is announced on stderr the first time it is used, because a
1265
+ name that lands in an immutable Status History should never be one the user
1266
+ did not know was being written. And an identity that is configured but is
1267
+ not a person -- `github-actions[bot]`, `runner`, a bare `user` -- is refused
1268
+ rather than adopted, since R8 asks for evidence of which *human* accepted.
1269
+ """
1270
+ if explicit and explicit.strip():
1271
+ return explicit.strip()
1272
+ signer = configured_signer(adr_dir)
1273
+ if signer:
1274
+ return signer
1275
+
1276
+ proposal = git_user_name()
1277
+ if person_shaped(proposal):
1278
+ actor = f"User: {proposal.strip()}"
1279
+ if announce:
1280
+ print(
1281
+ f"[adr-kit] signing as {actor!r}, from git config user.name.\n"
1282
+ f'[adr-kit] set a different one with: python bin/adr signer --set "User: <name>"',
1283
+ file=sys.stderr,
1284
+ )
1285
+ return actor
1286
+
1287
+ if proposal:
1288
+ hint = (
1289
+ f' python bin/adr signer --set "User: <your name>"\n'
1290
+ f" (git config user.name is {proposal!r}, which does not name a person)"
1291
+ )
1292
+ else:
1293
+ hint = ' python bin/adr signer --set "User: <your name>"'
1294
+ raise AdrLifecycleError(
1295
+ "no signer configured, so this transition would be unsigned. "
1296
+ "A Status History entry records who decided and when, and the tool must "
1297
+ "not fill that in on your behalf. Set it once for this machine:"
1298
+ f"\n{hint}\n"
1299
+ "or pass --changed-by for a single command."
1300
+ )
1301
+
1302
+
1303
+ def command_signer(args) -> List[str]:
1304
+ """Show, set, or audit the machine-local signer."""
1305
+ adr_dir = Path(args.adr_dir)
1306
+ if args.set:
1307
+ value = args.set.strip()
1308
+ if not value:
1309
+ raise AdrLifecycleError("--set needs a non-empty name")
1310
+ path = adr_dir / LOCAL_CONFIG_NAME
1311
+ data = read_local_config(adr_dir)
1312
+ data.setdefault("lifecycle", {})["signer"] = value
1313
+ _atomic_write_text(path, json.dumps(data, indent=2, ensure_ascii=False) + "\n")
1314
+ return [
1315
+ f"signer set: {value}",
1316
+ f"written to {path} (machine-local, gitignored)",
1317
+ ]
1318
+
1319
+ if args.audit:
1320
+ offenders = []
1321
+ for path in sorted(adr_dir.glob("ADR-*.md")):
1322
+ try:
1323
+ body = path.read_text(encoding="utf-8")
1324
+ except OSError:
1325
+ continue
1326
+ for match in re.finditer(r"^\s*changed_by:\s*(.+)$", body, re.MULTILINE):
1327
+ actor = match.group(1).strip().strip('"')
1328
+ if actor in {"adr-kit", "unknown"}:
1329
+ offenders.append(f"{path.name}: changed_by {actor!r}")
1330
+ if not offenders:
1331
+ return ["no self-signed or unknown actors found"]
1332
+ return [
1333
+ "Status History entries with no human actor:",
1334
+ *(f" {line}" for line in offenders),
1335
+ "",
1336
+ "These predate the signer requirement. Correcting one means editing",
1337
+ "history, so it is a deliberate act, not something this command does.",
1338
+ ]
1339
+
1340
+ if args.suggest:
1341
+ candidates = signer_candidates()
1342
+ current = configured_signer(adr_dir)
1343
+ if getattr(args, "format", "text") == "json":
1344
+ print(json.dumps(
1345
+ {"configured": current, "candidates": candidates},
1346
+ indent=2, ensure_ascii=False,
1347
+ ))
1348
+ return []
1349
+ if current:
1350
+ return [
1351
+ f"already configured: {current}",
1352
+ f" in {adr_dir / LOCAL_CONFIG_NAME}",
1353
+ "Re-run with --set to change it.",
1354
+ ]
1355
+ if not candidates:
1356
+ return [
1357
+ "no signer candidate found on this machine.",
1358
+ " git config user.name is unset or does not name a person,",
1359
+ " and the GitHub CLI is unavailable or not signed in.",
1360
+ 'Set one: python bin/adr signer --set "User: <your name>"',
1361
+ ]
1362
+ lines = ["Signer candidates found on this machine:"]
1363
+ for index, candidate in enumerate(candidates, 1):
1364
+ lines.append(f" {index}. {candidate['actor']} [{candidate['source']}]")
1365
+ lines.append("")
1366
+ lines.append("Nothing is written until you choose. To adopt the first:")
1367
+ lines.append(f" python bin/adr signer --set \"{candidates[0]['actor']}\"")
1368
+ return lines
1369
+
1370
+ signer = configured_signer(adr_dir)
1371
+ if signer:
1372
+ return [
1373
+ f"signer: {signer}",
1374
+ f"source: {adr_dir / LOCAL_CONFIG_NAME} (machine-local, gitignored)",
1375
+ ]
1376
+
1377
+ proposal = git_user_name()
1378
+ if person_shaped(proposal):
1379
+ return [
1380
+ f"signer: User: {proposal.strip()}",
1381
+ "source: git config user.name (derived, not written to any file)",
1382
+ 'override for this machine: python bin/adr signer --set "User: <name>"',
1383
+ ]
1384
+
1385
+ lines = ["signer: (unset) - lifecycle commands will refuse to write history"]
1386
+ if proposal:
1387
+ lines.append(
1388
+ f"git config user.name is {proposal!r}, which does not name a person, "
1389
+ "so it is not adopted"
1390
+ )
1391
+ lines.append('set one with: python bin/adr signer --set "User: <your name>"')
1392
+ return lines
1393
+
1394
+
1395
+ def add_common_args(parser: argparse.ArgumentParser) -> None:
1396
+ parser.add_argument("--adr-dir", default="docs/adr", help="ADR directory")
1397
+ parser.add_argument("--date", default=date.today().isoformat(), help="transition date")
1398
+ parser.add_argument(
1399
+ "--changed-by",
1400
+ default=None,
1401
+ help=(
1402
+ "status history actor. Defaults to lifecycle.signer from the "
1403
+ "machine-local config; with neither, the command refuses rather "
1404
+ "than signing on your behalf."
1405
+ ),
1406
+ )
1407
+ parser.add_argument("--reason", default=None, help="status history reason")
1408
+
1409
+
1410
+ def build_parser() -> argparse.ArgumentParser:
1411
+ parser = argparse.ArgumentParser(prog="adr", description="adr-kit lifecycle commands")
1412
+ sub = parser.add_subparsers(dest="command", required=True)
1413
+
1414
+ signer = sub.add_parser("signer", help="show, set, or audit the status-history signer")
1415
+ signer.add_argument("--adr-dir", default="docs/adr", help="ADR directory")
1416
+ signer.add_argument("--set", default=None, metavar="NAME", help='e.g. "User: Robert van den Breemen"')
1417
+ signer.add_argument("--audit", action="store_true", help="list history entries with no human actor")
1418
+ signer.add_argument(
1419
+ "--suggest",
1420
+ action="store_true",
1421
+ help=(
1422
+ "propose signer candidates found on this machine (git config, and the "
1423
+ "signed-in GitHub account when `gh` is available). Read-only: it writes "
1424
+ "nothing, so a setup flow can show them and let the user choose."
1425
+ ),
1426
+ )
1427
+ signer.add_argument("--format", choices=["text", "json"], default="text")
1428
+
1429
+ new = sub.add_parser("new", help="create a Proposed ADR from a selected profile")
1430
+ new.add_argument("title")
1431
+ add_common_args(new)
1432
+ new.add_argument("--profile", choices=list(SUPPORTED_PROFILES), default=None)
1433
+ new.add_argument("--config", default=None, help="config path")
1434
+
1435
+ profiles = sub.add_parser(
1436
+ "profiles",
1437
+ help="list selectable profiles and verify their shipped templates",
1438
+ )
1439
+ profiles.add_argument(
1440
+ "--format",
1441
+ choices=["human", "json"],
1442
+ default="human",
1443
+ help="output format",
1444
+ )
1445
+
1446
+ propose = sub.add_parser("propose", help="mark an ADR Proposed")
1447
+ propose.add_argument("adr")
1448
+ add_common_args(propose)
1449
+
1450
+ accept = sub.add_parser("accept", help="mark an ADR Accepted")
1451
+ accept.add_argument("adr")
1452
+ add_common_args(accept)
1453
+ accept.add_argument("--auto", action="store_true", help="require after-the-fact evidence checks before accepting")
1454
+ accept.add_argument("--auto-mode", choices=["auto", "assist"], default=None, help="override lifecycle.auto_accept.mode")
1455
+ accept.add_argument("--confirm", action="store_true", help="mutate in assist mode after eligibility is shown")
1456
+ accept.add_argument("--quality-threshold", type=float, default=None, help="minimum adr-quality score")
1457
+ accept.add_argument("--config", default=None, help="config path")
1458
+ accept.add_argument("--repo-root", default=None, help="consuming repo root for verified_in/gate checks")
1459
+
1460
+ reject = sub.add_parser("reject", help="mark an ADR Rejected")
1461
+ reject.add_argument("adr")
1462
+ add_common_args(reject)
1463
+
1464
+ answer = sub.add_parser(
1465
+ "answer",
1466
+ help="resolve an open question in place, keeping the question and the answer",
1467
+ )
1468
+ answer.add_argument("adr")
1469
+ answer.add_argument("--answer", required=True, help="the settled answer")
1470
+ answer.add_argument(
1471
+ "--question",
1472
+ default=None,
1473
+ help="which unresolved question: a 1-based number or distinctive text",
1474
+ )
1475
+ add_common_args(answer)
1476
+
1477
+ relate = sub.add_parser(
1478
+ "relate",
1479
+ help="record a cross-reference between two ADRs on both sides at once",
1480
+ )
1481
+ relate.add_argument("adr")
1482
+ relate.add_argument("--to", required=True, help="the other ADR id")
1483
+ relate.add_argument(
1484
+ "--remove",
1485
+ action="store_true",
1486
+ help="drop the cross-reference from both sides instead of adding it",
1487
+ )
1488
+ add_common_args(relate)
1489
+
1490
+ supersede = sub.add_parser("supersede", help="supersede an ADR by another ADR")
1491
+ supersede.add_argument("old")
1492
+ supersede.add_argument("--by", required=True, help="successor ADR id")
1493
+ add_common_args(supersede)
1494
+
1495
+ document = sub.add_parser("document", help="mark an ADR as documenting shipped behavior")
1496
+ document.add_argument("adr")
1497
+ document.add_argument("--verified-in", action="append", required=True, help="local evidence pointer")
1498
+ add_common_args(document)
1499
+
1500
+ return parser
1501
+
1502
+
1503
+ def main(argv: List[str] | None = None) -> int:
1504
+ parser = build_parser()
1505
+ args = parser.parse_args(argv)
1506
+ try:
1507
+ if args.command == "signer":
1508
+ lines = command_signer(args)
1509
+ elif args.command == "new":
1510
+ lines = command_new(args)
1511
+ elif args.command == "profiles":
1512
+ lines = command_profiles(args)
1513
+ elif args.command == "propose":
1514
+ lines = command_set_status(
1515
+ args,
1516
+ "Proposed",
1517
+ f"Proposed, {args.date}.",
1518
+ "Marked Proposed",
1519
+ )
1520
+ elif args.command == "accept":
1521
+ if args.auto:
1522
+ lines = command_auto_accept(args)
1523
+ else:
1524
+ lines = command_accept(args)
1525
+ elif args.command == "reject":
1526
+ lines = command_set_status(
1527
+ args,
1528
+ "Rejected",
1529
+ f"Rejected, {args.date}.",
1530
+ "Rejected decision",
1531
+ )
1532
+ elif args.command == "answer":
1533
+ lines = command_answer(args)
1534
+ elif args.command == "relate":
1535
+ lines = command_relate(args)
1536
+ elif args.command == "supersede":
1537
+ lines = command_supersede(args)
1538
+ elif args.command == "document":
1539
+ lines = command_document(args)
1540
+ else:
1541
+ parser.error(f"unknown command {args.command}")
1542
+ return 2
1543
+ except AdrLifecycleError as exc:
1544
+ print(f"adr: {exc}", file=sys.stderr)
1545
+ return 2
1546
+ for line in lines:
1547
+ print(line)
1548
+ return 0
1549
+
1550
+
1551
+ if __name__ == "__main__":
1552
+ sys.exit(main())