@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,183 @@
1
+ #!/usr/bin/env python3
2
+ """Ask an installed client which lifecycle events it actually emits.
3
+
4
+ Every hook defect this kit has shipped was the same shape: an event registered
5
+ in `hooks/manifest.json` that did not reach the code behind it. Certification
6
+ could not catch any of them, because it certified against
7
+ `tests/certification/simulated-pass.json` -- a fixture that says what we believe
8
+ rather than what a client does.
9
+
10
+ This probe runs the real binary and reads its own event stream. Claude Code
11
+ emits `hook_started` frames carrying `hook_event` when asked for
12
+ `--output-format=stream-json --include-hook-events`, so the answer comes from
13
+ the client rather than from us.
14
+
15
+ Three properties, each of which is the point rather than a detail:
16
+
17
+ * **It never fails the build.** A runner with no client, no credentials or no
18
+ network records `not-run` and exits 0. A certification that fails when it
19
+ cannot measure is a certification people learn to skip, and `not-run` is an
20
+ honest evidence class -- the matrix already carries it for macOS and Linux.
21
+ * **It reports what it observed, not what it concluded.** An event that did not
22
+ appear is `not-observed`, never `unsupported`. A prompt that uses no tools
23
+ cannot produce `PreToolUse`, and reading that absence as a missing capability
24
+ would put a false claim in the document this exists to make true.
25
+ * **It costs one model call.** Deliberately one short prompt: the probe is
26
+ evidence gathering, and evidence that is expensive to collect is evidence
27
+ nobody collects.
28
+ * **It closes the client's stdin.** The prompt arrives through `-p` and stdout
29
+ is captured, so anything a client asked interactively would be invisible on
30
+ this end and unanswerable from the console that started the probe. Closing
31
+ stdin turns that into an immediate EOF instead of a wait no `timeout=` can
32
+ end: on Windows a client installed through npm is a `.CMD` shim, and a
33
+ timeout kills the shim while the grandchild holds the pipe open.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import argparse
39
+ import json
40
+ import shutil
41
+ import subprocess
42
+ import sys
43
+ import tempfile
44
+ from pathlib import Path
45
+
46
+ CLIENT_BINARIES = {
47
+ "claude-code-cli": "claude",
48
+ "codex-cli": "codex",
49
+ "github-copilot-cli": "copilot",
50
+ }
51
+
52
+ #: Only Claude Code documents a machine-readable hook-event stream today. The
53
+ #: other two are probed for presence and version, which is still more than a
54
+ #: fixture asserts, and their event coverage stays `not-run` until they offer
55
+ #: an equivalent. Claiming otherwise would be the failure this script exists to
56
+ #: stop, arriving from the other direction.
57
+ EVENT_STREAM_CLIENTS = {"claude-code-cli"}
58
+
59
+ PROBE_PROMPT = "Read probe.txt and reply with its contents. Nothing else."
60
+
61
+
62
+ def _binary(client: str) -> str | None:
63
+ return shutil.which(CLIENT_BINARIES[client])
64
+
65
+
66
+ def _version(binary: str) -> str | None:
67
+ try:
68
+ result = subprocess.run(
69
+ [binary, "--version"], capture_output=True, text=True,
70
+ stdin=subprocess.DEVNULL,
71
+ encoding="utf-8", errors="replace", timeout=60,
72
+ )
73
+ except (OSError, subprocess.SubprocessError):
74
+ return None
75
+ return result.stdout.strip().splitlines()[0] if result.stdout.strip() else None
76
+
77
+
78
+ def _observe_events(binary: str, timeout: int) -> tuple[list[str], str | None]:
79
+ """Run one prompt and collect the hook events the client reports.
80
+
81
+ The workspace is a throwaway directory holding one file, so the prompt has
82
+ something to read and the tool tier has a reason to fire. Nothing in the
83
+ caller's repository is touched.
84
+ """
85
+ with tempfile.TemporaryDirectory(prefix="adr-kit-probe-") as workspace:
86
+ root = Path(workspace)
87
+ (root / "probe.txt").write_text("probe\n", encoding="utf-8")
88
+ try:
89
+ result = subprocess.run(
90
+ [binary, "-p", PROBE_PROMPT,
91
+ "--output-format=stream-json", "--include-hook-events",
92
+ "--verbose", "--allowedTools", "Read"],
93
+ cwd=root, capture_output=True, text=True,
94
+ stdin=subprocess.DEVNULL,
95
+ encoding="utf-8", errors="replace", timeout=timeout,
96
+ )
97
+ except subprocess.TimeoutExpired:
98
+ return [], f"the client did not answer within {timeout}s"
99
+ except (OSError, subprocess.SubprocessError) as exc:
100
+ return [], f"the client could not be run ({exc})"
101
+
102
+ observed: set[str] = set()
103
+ for line in result.stdout.splitlines():
104
+ line = line.strip()
105
+ if not line.startswith("{"):
106
+ continue
107
+ try:
108
+ frame = json.loads(line)
109
+ except ValueError:
110
+ continue
111
+ event = frame.get("hook_event")
112
+ if isinstance(event, str) and event:
113
+ observed.add(event)
114
+ if not observed:
115
+ detail = (result.stderr or result.stdout).strip()[:200]
116
+ return [], f"no hook events in the stream ({detail or 'empty output'})"
117
+ return sorted(observed), None
118
+
119
+
120
+ def probe(client: str, timeout: int) -> dict:
121
+ binary = _binary(client)
122
+ if binary is None:
123
+ return {
124
+ "client": client,
125
+ "evidence_mode": "not-run",
126
+ "reason": f"{CLIENT_BINARIES[client]} is not on PATH",
127
+ }
128
+ record = {
129
+ "client": client,
130
+ "binary": binary,
131
+ "version": _version(binary),
132
+ "platform": sys.platform,
133
+ }
134
+ if client not in EVENT_STREAM_CLIENTS:
135
+ record.update(
136
+ evidence_mode="not-run",
137
+ reason="this client exposes no machine-readable hook-event stream",
138
+ )
139
+ return record
140
+ observed, failure = _observe_events(binary, timeout)
141
+ if failure:
142
+ record.update(evidence_mode="not-run", reason=failure)
143
+ return record
144
+ record.update(evidence_mode="native", observed_events=observed)
145
+ return record
146
+
147
+
148
+ def main(argv: list[str] | None = None) -> int:
149
+ parser = argparse.ArgumentParser(prog="adr-kit:probe-client-events")
150
+ parser.add_argument(
151
+ "--clients", default=",".join(CLIENT_BINARIES),
152
+ help="Comma-separated client ids to probe.",
153
+ )
154
+ parser.add_argument("--timeout", type=int, default=180)
155
+ parser.add_argument(
156
+ "--output", type=Path, default=None,
157
+ help="Write the evidence record here. Prints to stdout otherwise.",
158
+ )
159
+ args = parser.parse_args(argv)
160
+
161
+ selected = [item.strip() for item in args.clients.split(",") if item.strip()]
162
+ unknown = sorted(set(selected) - set(CLIENT_BINARIES))
163
+ if unknown:
164
+ print(f"unknown client(s): {', '.join(unknown)}", file=sys.stderr)
165
+ return 2
166
+
167
+ payload = {
168
+ "schema_version": 1,
169
+ "probe_id": "adr-kit-client-event-probe-v1",
170
+ "records": [probe(client, args.timeout) for client in selected],
171
+ }
172
+ text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
173
+ if args.output:
174
+ args.output.parent.mkdir(parents=True, exist_ok=True)
175
+ args.output.write_text(text, encoding="utf-8", newline="\n")
176
+ else:
177
+ sys.stdout.write(text)
178
+ # Exit 0 whatever was found. Absence of a client is a normal outcome.
179
+ return 0
180
+
181
+
182
+ if __name__ == "__main__":
183
+ raise SystemExit(main())
@@ -0,0 +1,379 @@
1
+ """Atomic, marker-owned ADR Kit project setup primitives."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import difflib
6
+ import hashlib
7
+ import os
8
+ import re
9
+ import stat
10
+ import subprocess
11
+ import tempfile
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Iterable
15
+
16
+
17
+ MARKER_RE = re.compile(
18
+ r"<!-- ADR-KIT (?P<label>[A-Z-]+) (?P<edge>START|END) -->"
19
+ )
20
+ CLIENT_FILES = {
21
+ "codex": (Path("AGENTS.md"), "CODEX"),
22
+ "claude": (Path("CLAUDE.md"), "CLAUDE"),
23
+ "copilot": (Path(".github/copilot-instructions.md"), "COPILOT"),
24
+ }
25
+ LEGACY_GUIDES = {
26
+ "codex": Path(".agents/adr-kit-guide.md"),
27
+ "claude": Path(".claude/adr-kit-guide.md"),
28
+ }
29
+
30
+
31
+ class SetupError(RuntimeError):
32
+ """Raised before setup writes when ownership or project state is unsafe."""
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class PlannedChange:
37
+ path: Path
38
+ old: bytes | None
39
+ new: bytes | None
40
+ action: str
41
+ mode: int | None = None
42
+
43
+
44
+ def marker_block(client: str) -> str:
45
+ label = CLIENT_FILES[client][1]
46
+ commands = {
47
+ "codex": (
48
+ "Use `$adr-kit:context` before implementation, `$adr-kit:adr` for "
49
+ "new decisions, and `$adr-kit:judge` before commit."
50
+ ),
51
+ "claude": (
52
+ "Use `/adr-kit:context` before implementation, `/adr-kit:adr` for "
53
+ "new decisions, and `/adr-kit:judge` before commit."
54
+ ),
55
+ "copilot": (
56
+ "Use the ADR Kit context, ADR authoring, and judge prompts before "
57
+ "implementation, architectural decisions, and commit."
58
+ ),
59
+ }
60
+ return (
61
+ f"<!-- ADR-KIT {label} START -->\n"
62
+ "## ADR Kit\n\n"
63
+ "Read `.adr-kit/ADR-guide.md` before architectural changes. "
64
+ "Architecture decisions live in `docs/adr/`. "
65
+ f"{commands[client]}\n"
66
+ f"<!-- ADR-KIT {label} END -->"
67
+ )
68
+
69
+
70
+ def _decode(data: bytes | None) -> tuple[str, str, bool]:
71
+ if data is None:
72
+ return "", "\n", False
73
+ bom = data.startswith(b"\xef\xbb\xbf")
74
+ text = data.decode("utf-8-sig")
75
+ newline = "\r\n" if "\r\n" in text else "\n"
76
+ return text, newline, bom
77
+
78
+
79
+ def _encode(text: str, newline: str, bom: bool) -> bytes:
80
+ normalized = text.replace("\r\n", "\n").replace("\r", "\n")
81
+ payload = normalized.replace("\n", newline).encode("utf-8")
82
+ return (b"\xef\xbb\xbf" + payload) if bom else payload
83
+
84
+
85
+ def validate_markers(text: str, path: Path) -> dict[str, tuple[int, int]]:
86
+ markers: dict[str, dict[str, list[re.Match[str]]]] = {}
87
+ for match in MARKER_RE.finditer(text):
88
+ label = match.group("label")
89
+ edge = match.group("edge")
90
+ markers.setdefault(label, {"START": [], "END": []})[edge].append(match)
91
+
92
+ intervals: dict[str, tuple[int, int]] = {}
93
+ for label, edges in markers.items():
94
+ starts, ends = edges["START"], edges["END"]
95
+ if len(starts) != 1 or len(ends) != 1:
96
+ raise SetupError(
97
+ f"{path}: malformed or duplicate ADR Kit markers for {label}"
98
+ )
99
+ if starts[0].start() >= ends[0].start():
100
+ raise SetupError(f"{path}: reversed ADR Kit markers for {label}")
101
+ intervals[label] = (starts[0].start(), ends[0].end())
102
+
103
+ ordered = sorted((start, end, label) for label, (start, end) in intervals.items())
104
+ for index, (start, end, label) in enumerate(ordered):
105
+ for other_start, other_end, other_label in ordered[index + 1 :]:
106
+ if other_start < end:
107
+ raise SetupError(
108
+ f"{path}: nested ADR Kit markers for {label}/{other_label}"
109
+ )
110
+ if other_start >= end:
111
+ break
112
+ return intervals
113
+
114
+
115
+ def update_instruction(
116
+ path: Path,
117
+ old: bytes | None,
118
+ client: str,
119
+ ) -> PlannedChange | None:
120
+ text, newline, bom = _decode(old)
121
+ intervals = validate_markers(text, path)
122
+ label = CLIENT_FILES[client][1]
123
+ candidates = [item for item in (label, "STUB" if client == "claude" else "") if item]
124
+ present = [item for item in candidates if item in intervals]
125
+ if len(present) > 1:
126
+ raise SetupError(f"{path}: both legacy and current ADR Kit blocks exist")
127
+
128
+ block = marker_block(client)
129
+ if present:
130
+ start, end = intervals[present[0]]
131
+ updated = text[:start] + block + text[end:]
132
+ action = "migrate-marker" if present[0] == "STUB" else "refresh-marker"
133
+ else:
134
+ separator = "" if not text else ("" if text.endswith(("\n", "\r")) else newline)
135
+ updated = text + separator + (newline if text else "") + block + newline
136
+ action = "create-marker"
137
+ new = _encode(updated, newline, bom)
138
+ if new == old:
139
+ return None
140
+ return PlannedChange(path, old, new, action)
141
+
142
+
143
+ def _backup_path(root: Path, source: Path, old: bytes, kind: str) -> Path:
144
+ digest = hashlib.sha256(old).hexdigest()[:12]
145
+ safe_name = source.as_posix().replace("/", "__")
146
+ return root / ".adr-kit" / "backups" / f"{safe_name}.{digest}.{kind}.bak"
147
+
148
+
149
+ def _backup_change(path: Path, payload: bytes, action: str) -> PlannedChange | None:
150
+ existing = path.read_bytes() if path.exists() else None
151
+ if existing == payload:
152
+ return None
153
+ if existing is not None:
154
+ raise SetupError(f"backup collision with different content: {path}")
155
+ return PlannedChange(path, None, payload, action)
156
+
157
+
158
+ def _git(root: Path, *args: str) -> subprocess.CompletedProcess[str]:
159
+ return subprocess.run(
160
+ ["git", "-C", str(root), *args],
161
+ text=True,
162
+ capture_output=True,
163
+ check=False,
164
+ timeout=5,
165
+ )
166
+
167
+
168
+ def _pre_commit_changes(
169
+ root: Path,
170
+ template: Path,
171
+ enabled: bool,
172
+ touch: bool = True,
173
+ ) -> tuple[list[PlannedChange], bool]:
174
+ """Plan the pre-commit hook: install it, remove ours, or leave it alone.
175
+
176
+ `touch=False` is the third state, and it was missing. Every invocation used
177
+ to either install this kit's hook or remove whatever was at that path, so a
178
+ project managing hooks another way could not be set up without its hook
179
+ being decided for it. Removal is bounded either way: a hook without this
180
+ kit's marker is never deleted, and never overwritten.
181
+ """
182
+ if not touch:
183
+ return [], False
184
+ git_dir = _git(root, "rev-parse", "--git-dir")
185
+ if git_dir.returncode != 0:
186
+ return [], False
187
+ hooks_path_result = _git(root, "config", "--get", "core.hooksPath")
188
+ hooks_path = (
189
+ hooks_path_result.stdout.strip()
190
+ if hooks_path_result.returncode == 0
191
+ else ""
192
+ )
193
+ if enabled and hooks_path not in {"", ".githooks"}:
194
+ raise SetupError(
195
+ f"custom core.hooksPath is owned by the user: {hooks_path}"
196
+ )
197
+
198
+ hook = root / ".githooks" / "pre-commit"
199
+ old = hook.read_bytes() if hook.exists() else None
200
+ owned = old is not None and b"adr-kit pre-commit hook" in old
201
+ if enabled:
202
+ new = template.read_bytes()
203
+ if old is not None and old != new and not owned:
204
+ raise SetupError(f"refusing to replace user pre-commit hook: {hook}")
205
+ change = (
206
+ None
207
+ if old == new
208
+ else PlannedChange(hook, old, new, "install-pre-commit", 0o755)
209
+ )
210
+ return ([change] if change else []), hooks_path == ""
211
+ if owned:
212
+ return [PlannedChange(hook, old, None, "disable-pre-commit")], False
213
+ return [], False
214
+
215
+
216
+ def collect_changes(
217
+ root: Path,
218
+ plugin_root: Path,
219
+ clients: Iterable[str],
220
+ *,
221
+ pre_commit_enabled: bool,
222
+ touch_pre_commit: bool = True,
223
+ ) -> tuple[list[PlannedChange], bool]:
224
+ selected = list(dict.fromkeys(clients))
225
+ unknown = sorted(set(selected) - set(CLIENT_FILES))
226
+ if unknown:
227
+ raise SetupError(f"unknown clients: {', '.join(unknown)}")
228
+
229
+ guide_source = plugin_root / "instructions" / "ADR-guide.md"
230
+ hook_source = plugin_root / "templates" / "githooks" / "pre-commit"
231
+ if not guide_source.is_file() or not hook_source.is_file():
232
+ raise SetupError(f"ADR Kit source is incomplete: {plugin_root}")
233
+
234
+ changes: list[PlannedChange] = []
235
+ guide = root / ".adr-kit" / "ADR-guide.md"
236
+ guide_old = guide.read_bytes() if guide.exists() else None
237
+ guide_new = guide_source.read_bytes()
238
+ if guide_old != guide_new:
239
+ if guide_old is not None:
240
+ backup = _backup_path(root, Path("ADR-guide.md"), guide_old, "generated")
241
+ backup_change = _backup_change(backup, guide_old, "backup-guide")
242
+ if backup_change:
243
+ changes.append(backup_change)
244
+ changes.append(
245
+ PlannedChange(
246
+ guide,
247
+ guide_old,
248
+ guide_new,
249
+ "create-guide" if guide_old is None else "replace-guide",
250
+ )
251
+ )
252
+
253
+ for client in selected:
254
+ relative, _ = CLIENT_FILES[client]
255
+ path = root / relative
256
+ old = path.read_bytes() if path.exists() else None
257
+ change = update_instruction(path, old, client)
258
+ if change:
259
+ if old is not None:
260
+ backup = _backup_path(root, relative, old, "instruction")
261
+ backup_change = _backup_change(
262
+ backup, old, "backup-instruction"
263
+ )
264
+ if backup_change:
265
+ changes.append(backup_change)
266
+ changes.append(change)
267
+
268
+ for client, legacy_relative in LEGACY_GUIDES.items():
269
+ if client not in selected:
270
+ continue
271
+ legacy = root / legacy_relative
272
+ if not legacy.exists():
273
+ continue
274
+ payload = legacy.read_bytes()
275
+ backup = _backup_path(root, legacy_relative, payload, "legacy")
276
+ backup_change = _backup_change(backup, payload, "backup-legacy-guide")
277
+ if backup_change:
278
+ changes.append(backup_change)
279
+ changes.append(
280
+ PlannedChange(legacy, payload, None, "remove-legacy-guide")
281
+ )
282
+
283
+ hook_changes, configure_hooks_path = _pre_commit_changes(
284
+ root, hook_source, pre_commit_enabled, touch_pre_commit
285
+ )
286
+ changes.extend(hook_changes)
287
+ return changes, configure_hooks_path
288
+
289
+
290
+ def render_diff(changes: Iterable[PlannedChange], root: Path) -> str:
291
+ output: list[str] = []
292
+ for change in changes:
293
+ old_text = _decode(change.old)[0].splitlines(keepends=True)
294
+ new_text = _decode(change.new)[0].splitlines(keepends=True)
295
+ relative = change.path.relative_to(root).as_posix()
296
+ output.extend(
297
+ difflib.unified_diff(
298
+ old_text,
299
+ new_text,
300
+ fromfile=f"a/{relative}",
301
+ tofile=f"b/{relative}",
302
+ )
303
+ )
304
+ return "".join(output)
305
+
306
+
307
+ def plan_uninstall(root: Path, clients: Iterable[str]) -> list[PlannedChange]:
308
+ """Remove generated guide/owned blocks while preserving all user guidance."""
309
+ changes: list[PlannedChange] = []
310
+ guide = root / ".adr-kit" / "ADR-guide.md"
311
+ if guide.is_file():
312
+ changes.append(PlannedChange(guide, guide.read_bytes(), None, "remove-guide"))
313
+ for client in clients:
314
+ relative, label = CLIENT_FILES[client]
315
+ path = root / relative
316
+ if not path.is_file():
317
+ continue
318
+ old = path.read_bytes()
319
+ text, newline, bom = _decode(old)
320
+ intervals = validate_markers(text, path)
321
+ if label not in intervals:
322
+ continue
323
+ start, end = intervals[label]
324
+ updated = (text[:start] + text[end:]).strip()
325
+ new = _encode(updated + (newline if updated else ""), newline, bom)
326
+ changes.append(PlannedChange(path, old, new or None, "remove-managed-block"))
327
+ return changes
328
+
329
+
330
+ def apply_changes(
331
+ root: Path,
332
+ changes: Iterable[PlannedChange],
333
+ *,
334
+ configure_hooks_path: bool,
335
+ ) -> None:
336
+ pending = list(changes)
337
+ if not pending and not configure_hooks_path:
338
+ return
339
+ state_dir = root / ".adr-kit"
340
+ state_dir.mkdir(parents=True, exist_ok=True)
341
+ lock = state_dir / "setup.lock"
342
+ try:
343
+ descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
344
+ except FileExistsError as exc:
345
+ raise SetupError(f"another ADR Kit setup owns {lock}") from exc
346
+ try:
347
+ os.close(descriptor)
348
+ for change in pending:
349
+ if change.new is None:
350
+ change.path.unlink(missing_ok=True)
351
+ continue
352
+ _atomic_write(change.path, change.new, change.mode)
353
+ if configure_hooks_path:
354
+ result = _git(root, "config", "core.hooksPath", ".githooks")
355
+ if result.returncode != 0:
356
+ raise SetupError(
357
+ f"git config core.hooksPath failed: {result.stderr.strip()}"
358
+ )
359
+ finally:
360
+ lock.unlink(missing_ok=True)
361
+
362
+
363
+ def _atomic_write(path: Path, payload: bytes, mode: int | None) -> None:
364
+ path.parent.mkdir(parents=True, exist_ok=True)
365
+ current_mode = stat.S_IMODE(path.stat().st_mode) if path.exists() else mode
366
+ descriptor, temporary_name = tempfile.mkstemp(
367
+ prefix=f".{path.name}.", suffix=".tmp", dir=path.parent
368
+ )
369
+ temporary = Path(temporary_name)
370
+ try:
371
+ with os.fdopen(descriptor, "wb") as out:
372
+ out.write(payload)
373
+ out.flush()
374
+ os.fsync(out.fileno())
375
+ if current_mode is not None:
376
+ os.chmod(temporary, current_mode)
377
+ os.replace(temporary, path)
378
+ finally:
379
+ temporary.unlink(missing_ok=True)