@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,288 @@
1
+ """Bounded, deterministic client-adapter generation for ADR Kit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import stat
6
+ import sys
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from pathlib import Path
9
+
10
+ SCRIPT_DIR = str(Path(__file__).resolve().parent)
11
+ if SCRIPT_DIR not in sys.path:
12
+ sys.path.insert(0, SCRIPT_DIR)
13
+
14
+ from client_generation_artifacts import (
15
+ declared_source_files,
16
+ dependencies,
17
+ inventory,
18
+ native_hook_config,
19
+ render_prompt,
20
+ render_skill,
21
+ validate_capabilities,
22
+ validate_manifests,
23
+ validate_workflows,
24
+ )
25
+ from client_generation_model import (
26
+ CLIENT_IDS,
27
+ COPY_EXCLUSIONS,
28
+ COPY_ROOTS,
29
+ GENERATED_CLIENTS,
30
+ HOOK_RUNTIME_FILES,
31
+ PROVENANCE,
32
+ RUNTIME_SUPPORT_FILES,
33
+ SOURCE_FILES,
34
+ GenerationError,
35
+ Stats,
36
+ expected_version,
37
+ read,
38
+ read_json,
39
+ write,
40
+ )
41
+ from client_generation_state import (
42
+ collect_release_files,
43
+ load_early_state,
44
+ load_fast_state,
45
+ save_fast_state,
46
+ validate_release_paths,
47
+ )
48
+
49
+ # Preserve the focused validation surface used by contract tests and downstream
50
+ # maintainers while implementation lives in bounded support modules.
51
+ _validate_capabilities = validate_capabilities
52
+ _validate_workflows = validate_workflows
53
+ _validate_manifests = validate_manifests
54
+ _native_hook_config = native_hook_config
55
+ _render_skill = render_skill
56
+
57
+
58
+ def _same_content(actual: bytes | None, expected: bytes) -> bool:
59
+ """True when the file on disk matches, ignoring line-ending style only.
60
+
61
+ The generator emits LF. On a Windows checkout with core.autocrlf=true git
62
+ materialises CRLF for any path .gitattributes does not pin, so a byte-exact
63
+ comparison reported drift on 13 generated files while `git diff` was empty
64
+ (TASK-57). That made the release runbook's drift gate unusable on the
65
+ certification machine, and "fixing" it rewrote those files as LF, which then
66
+ showed as phantom modifications until the next checkout -- noise that can
67
+ mask real drift.
68
+
69
+ Only the EOL dimension is relaxed. Content is still compared byte for byte,
70
+ so a single changed character is still drift.
71
+
72
+ Binary outputs (the prebuilt native hooks under hooks/bin/) are compared
73
+ byte-exactly and never normalised: a 0x0D 0x0A pair inside a binary is data,
74
+ not a line ending, and collapsing it would make two genuinely different
75
+ binaries compare equal. A NUL byte on either side is the binary signal --
76
+ the same heuristic git itself uses.
77
+ """
78
+ if actual is None:
79
+ return False
80
+ if actual == expected:
81
+ return True
82
+ if b"\x00" in actual or b"\x00" in expected:
83
+ return False
84
+ return actual.replace(b"\r\n", b"\n") == expected.replace(b"\r\n", b"\n")
85
+
86
+
87
+ def generate(
88
+ source_root: Path,
89
+ output_root: Path | None = None,
90
+ check: bool = False,
91
+ ) -> tuple[Stats, list[str]]:
92
+ source_root = source_root.resolve()
93
+ output_root = (output_root or source_root).resolve()
94
+ stats = Stats()
95
+ source_paths = declared_source_files(source_root)
96
+ if not check and load_early_state(source_root, output_root, source_paths, stats):
97
+ return stats, []
98
+
99
+ inputs = {name: read_json(source_root / name, stats) for name in SOURCE_FILES}
100
+ version = expected_version(source_root, stats)
101
+ validate_capabilities(
102
+ inputs["clients/capabilities.json"],
103
+ inputs["clients/exceptions.json"],
104
+ )
105
+ workflows = validate_workflows(inputs["clients/workflows.json"])
106
+ validate_manifests(inputs, version)
107
+ hook_manifest = inputs["hooks/manifest.json"]
108
+ if hook_manifest.get("schema_version") != 1:
109
+ raise GenerationError("hook manifest schema_version must be 1")
110
+
111
+ expected: dict[str, tuple[bytes, int | None]] = {}
112
+ for source in source_paths:
113
+ relative = source.relative_to(source_root).as_posix()
114
+ if relative in COPY_EXCLUSIONS:
115
+ continue
116
+ content = read(source, stats).replace(b"\r\n", b"\n")
117
+ if relative == "instructions/ADR-guide.md":
118
+ content = f"<!-- {PROVENANCE}; schema v1. -->\n".encode() + content
119
+ mode = stat.S_IMODE(source.stat().st_mode)
120
+ for client_dir in GENERATED_CLIENTS.values():
121
+ expected[f"{client_dir}/{relative}"] = (content, mode)
122
+
123
+ for workflow in workflows["workflows"]:
124
+ for client_id, client in workflows["clients"].items():
125
+ expected[f"{client['prompt_root']}/{workflow['id']}.md"] = (
126
+ render_prompt(workflow, client["label"], client_id),
127
+ None,
128
+ )
129
+ if client_id in GENERATED_CLIENTS:
130
+ expected[f"{client['skill_root']}/{workflow['id']}/SKILL.md"] = (
131
+ render_skill(workflow, client_id),
132
+ None,
133
+ )
134
+ elif not (
135
+ source_root / client["skill_root"] / workflow["id"] / "SKILL.md"
136
+ ).is_file():
137
+ raise GenerationError(
138
+ f"missing canonical rich skill: {workflow['id']}"
139
+ )
140
+
141
+ for relative in HOOK_RUNTIME_FILES:
142
+ source = source_root / relative
143
+ content = read(source, stats)
144
+ if source.suffix.casefold() not in {".exe", ".dll"}:
145
+ content = content.replace(b"\r\n", b"\n")
146
+ suffix = relative.removeprefix("hooks/")
147
+ mode = stat.S_IMODE(source.stat().st_mode)
148
+ for client_dir in GENERATED_CLIENTS.values():
149
+ expected[f"{client_dir}/hooks/{suffix}"] = (content, mode)
150
+
151
+ # Path-preserving, unlike the hook loop above which strips the "hooks/"
152
+ # prefix and re-roots. bin/adr-doctor resolves these by appending ROOT and
153
+ # ROOT/"scripts" to sys.path, so the mirror has to reproduce the layout and
154
+ # not merely the files.
155
+ for relative in RUNTIME_SUPPORT_FILES:
156
+ source = source_root / relative
157
+ # Load-bearing: without the newline normalisation these arrive with CRLF
158
+ # on a Windows checkout and --check reports phantom drift (TASK-57).
159
+ content = read(source, stats).replace(b"\r\n", b"\n")
160
+ mode = stat.S_IMODE(source.stat().st_mode)
161
+ for client_dir in GENERATED_CLIENTS.values():
162
+ expected[f"{client_dir}/{relative}"] = (content, mode)
163
+
164
+ native_hook_targets = {
165
+ "claude-code-cli": "hooks/hooks.json",
166
+ "codex-cli": "codex/hooks/hooks.json",
167
+ "github-copilot-cli": "copilot/hooks.json",
168
+ }
169
+ for client_id, target in native_hook_targets.items():
170
+ expected[target] = (native_hook_config(hook_manifest, client_id), None)
171
+ expected["packaging/dependencies.json"] = (
172
+ dependencies(inputs["packaging/dependencies-source.json"]),
173
+ None,
174
+ )
175
+ expected["packaging/executables.json"] = (
176
+ inventory(
177
+ source_root,
178
+ source_paths,
179
+ inputs["packaging/executables-source.json"],
180
+ ),
181
+ None,
182
+ )
183
+
184
+ generated_roots = [
185
+ *(
186
+ f"{directory}/{root}"
187
+ for directory in GENERATED_CLIENTS.values()
188
+ for root in COPY_ROOTS
189
+ ),
190
+ *(f"{directory}/skills" for directory in GENERATED_CLIENTS.values()),
191
+ *(client["prompt_root"] for client in workflows["clients"].values()),
192
+ "codex/hooks",
193
+ "copilot/hooks",
194
+ # So the orphan sweep owns the directories RUNTIME_SUPPORT_FILES creates.
195
+ *(
196
+ f"{directory}/{root}"
197
+ for directory in GENERATED_CLIENTS.values()
198
+ for root in ("scripts", "clients")
199
+ ),
200
+ ]
201
+ if not check and load_fast_state(output_root, expected, generated_roots):
202
+ stats.unchanged = len(expected)
203
+ return stats, []
204
+
205
+ ordered_outputs = sorted(expected.items())
206
+
207
+ def read_output(item: tuple[str, tuple[bytes, int | None]]) -> bytes | None:
208
+ try:
209
+ return (output_root / item[0]).read_bytes()
210
+ except FileNotFoundError:
211
+ return None
212
+
213
+ if output_root.exists():
214
+ # Windows file-open latency dominates existing-output validation. Reads
215
+ # are independent, bounded, and joined in deterministic path order.
216
+ with ThreadPoolExecutor(
217
+ max_workers=min(16, max(1, len(ordered_outputs)))
218
+ ) as pool:
219
+ actual_outputs = list(pool.map(read_output, ordered_outputs))
220
+ else:
221
+ # A clean destination cannot contain an output. Avoid creating and
222
+ # joining a thread pool only to raise FileNotFoundError for every path.
223
+ actual_outputs = [None] * len(ordered_outputs)
224
+
225
+ drift: list[str] = []
226
+ pending_writes: list[tuple[Path, bytes, int | None]] = []
227
+ # Guard: only relax the EOL dimension, and only for text. See _same_content.
228
+ for (relative, (content, mode)), actual in zip(
229
+ ordered_outputs,
230
+ actual_outputs,
231
+ ):
232
+ destination = output_root / relative
233
+ if actual is not None:
234
+ stats.files_read += 1
235
+ stats.bytes_read += len(actual)
236
+ mode_matches = (
237
+ mode is None
238
+ or (
239
+ destination.is_file()
240
+ and stat.S_IMODE(destination.stat().st_mode) == mode
241
+ )
242
+ )
243
+ if _same_content(actual, content) and mode_matches:
244
+ stats.unchanged += 1
245
+ continue
246
+ drift.append(relative)
247
+ if not check:
248
+ pending_writes.append((destination, content, mode))
249
+
250
+ if pending_writes:
251
+ def write_output(item: tuple[Path, bytes, int | None]) -> None:
252
+ write(item[0], item[1], item[2], stats)
253
+
254
+ with ThreadPoolExecutor(max_workers=min(16, len(pending_writes))) as pool:
255
+ list(pool.map(write_output, pending_writes))
256
+
257
+ expected_set = set(expected)
258
+ for root_name in generated_roots:
259
+ root_path = output_root / root_name
260
+ if not root_path.is_dir():
261
+ continue
262
+ for path in root_path.rglob("*"):
263
+ if not path.is_file() or "__pycache__" in path.parts:
264
+ continue
265
+ relative = path.relative_to(output_root).as_posix()
266
+ if "/hooks/bin/" in f"/{relative}" or relative in expected_set:
267
+ continue
268
+ drift.append(relative)
269
+ if not check:
270
+ path.unlink()
271
+
272
+ forbidden = validate_release_paths(
273
+ expected,
274
+ inputs["packaging/public-artifacts.json"],
275
+ )
276
+ if forbidden:
277
+ raise GenerationError(
278
+ "generated output outside public allowlist: " + ", ".join(forbidden)
279
+ )
280
+ if not check:
281
+ save_fast_state(
282
+ source_root,
283
+ output_root,
284
+ source_paths,
285
+ expected,
286
+ generated_roots,
287
+ )
288
+ return stats, sorted(set(drift))
@@ -0,0 +1,351 @@
1
+ """Validation and rendering for deterministic native client artifacts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Iterable
8
+
9
+ from client_generation_model import (
10
+ CLIENT_IDS,
11
+ COPY_ROOTS,
12
+ HOOK_RUNTIME_FILES,
13
+ PROVENANCE,
14
+ RUNTIME_SUPPORT_FILES,
15
+ WORKFLOW_IDS,
16
+ GenerationError,
17
+ encoded_json,
18
+ )
19
+
20
+
21
+ def validate_capabilities(value: object, exception_registry: object) -> dict:
22
+ if not isinstance(value, dict) or value.get("schema_version") != 1:
23
+ raise GenerationError("capability registry schema_version must be 1")
24
+ if value.get("program_scope", {}).get("first_class_clients") != list(CLIENT_IDS):
25
+ raise GenerationError("capability registry must contain exactly the three native clients")
26
+ clients = value.get("clients")
27
+ if not isinstance(clients, list) or [item.get("id") for item in clients] != list(CLIENT_IDS):
28
+ raise GenerationError("capability client order or membership is invalid")
29
+ for client in clients:
30
+ for exception in client.get("degradations", []):
31
+ required = {"id", "reason", "user_effect", "backstop", "blocks_certification"}
32
+ if not required.issubset(exception):
33
+ raise GenerationError(f"undocumented exception for {client['id']}")
34
+ registered = {
35
+ item.get("id"): item
36
+ for item in (
37
+ exception_registry.get("exceptions", [])
38
+ if isinstance(exception_registry, dict)
39
+ else []
40
+ )
41
+ }
42
+ used = {
43
+ item["id"]
44
+ for client in clients
45
+ for item in client.get("degradations", [])
46
+ }
47
+ if used != set(registered):
48
+ raise GenerationError("capability exceptions differ from fixture registry")
49
+ for exception in registered.values():
50
+ fixture = Path(str(exception.get("fixture", "")))
51
+ if fixture.is_absolute() or ".." in fixture.parts:
52
+ raise GenerationError("exception fixture must be repository-relative")
53
+ return value
54
+
55
+
56
+ def validate_workflows(value: object) -> dict:
57
+ if not isinstance(value, dict) or value.get("schema_version") != 1:
58
+ raise GenerationError("workflow registry schema_version must be 1")
59
+ if tuple(value.get("clients", {})) != CLIENT_IDS:
60
+ raise GenerationError("workflow registry must contain exactly the three native clients")
61
+ workflows = value.get("workflows")
62
+ if not isinstance(workflows, list) or not workflows:
63
+ raise GenerationError("workflow registry is empty")
64
+ ids = [item.get("id") for item in workflows]
65
+ if tuple(ids) != WORKFLOW_IDS:
66
+ raise GenerationError(
67
+ "workflow ids must match the complete canonical workflow set "
68
+ f"({len(WORKFLOW_IDS)} entries)"
69
+ )
70
+ for item in workflows:
71
+ if not re.fullmatch(r"[a-z][a-z0-9-]*", str(item.get("id", ""))):
72
+ raise GenerationError(f"invalid workflow id: {item.get('id')!r}")
73
+ if not item.get("description") or not item.get("procedure"):
74
+ raise GenerationError(f"incomplete workflow metadata: {item['id']}")
75
+ return value
76
+
77
+
78
+ def _manifest_version(value: object, path: str) -> str:
79
+ if not isinstance(value, dict) or value.get("name") != "adr-kit":
80
+ raise GenerationError(f"invalid native manifest name: {path}")
81
+ version = value.get("version")
82
+ repository = str(value.get("repository", ""))
83
+ if not isinstance(version, str) or value.get("license") != "MIT":
84
+ raise GenerationError(f"invalid native manifest version/license: {path}")
85
+ if "github.com/rvdbreemen/adr-kit" not in repository:
86
+ raise GenerationError(f"native manifest lacks repository provenance: {path}")
87
+ return version
88
+
89
+
90
+ def _marketplace_version(value: object, path: str) -> str | None:
91
+ if not isinstance(value, dict) or value.get("name") is None:
92
+ raise GenerationError(f"invalid marketplace manifest: {path}")
93
+ plugins = value.get("plugins")
94
+ if not isinstance(plugins, list) or len(plugins) != 1 or plugins[0].get("name") != "adr-kit":
95
+ raise GenerationError(f"marketplace must declare only adr-kit: {path}")
96
+ version = plugins[0].get("version")
97
+ return version if isinstance(version, str) else None
98
+
99
+
100
+ def validate_manifests(inputs: dict[str, object], version: str) -> None:
101
+ # Collect every stale manifest before failing: aborting on the first one turns
102
+ # a bump into a fix-one-rerun loop. packaging/version-sites.json is the shared
103
+ # registry; scripts/bump-version.py writes them all in one command.
104
+ stale: list[str] = []
105
+ for path in (".claude-plugin/plugin.json", "codex/.codex-plugin/plugin.json", "copilot/plugin.json"):
106
+ if _manifest_version(inputs[path], path) != version:
107
+ stale.append(path)
108
+ for path in (".claude-plugin/marketplace.json", ".github/plugin/marketplace.json"):
109
+ if _marketplace_version(inputs[path], path) != version:
110
+ stale.append(path)
111
+ if stale:
112
+ raise GenerationError(
113
+ "stale version reference: "
114
+ + ", ".join(stale)
115
+ + f" (fix them all: python scripts/bump-version.py {version})"
116
+ )
117
+ if _marketplace_version(inputs[".agents/plugins/marketplace.json"], ".agents/plugins/marketplace.json") is not None:
118
+ raise GenerationError("Codex local marketplace must inherit plugin version")
119
+ claude = inputs[".claude-plugin/plugin.json"]
120
+ codex = inputs["codex/.codex-plugin/plugin.json"]
121
+ copilot = inputs["copilot/plugin.json"]
122
+ if "hooks" in claude:
123
+ raise GenerationError("Claude must use plugin-root hooks/hooks.json")
124
+ if codex.get("hooks") != "./hooks/hooks.json":
125
+ raise GenerationError("Codex manifest must reference ./hooks/hooks.json")
126
+ if copilot.get("hooks") != "hooks.json":
127
+ raise GenerationError("Copilot manifest must reference hooks.json")
128
+ if codex.get("skills") != "./skills/" or copilot.get("skills") != "skills/":
129
+ raise GenerationError("native manifest skill root is invalid")
130
+ for path in (".mcp.json", "codex/.mcp.json", "copilot/.mcp.json"):
131
+ value = inputs[path]
132
+ if not isinstance(value, dict) or "adr-kit" not in value.get("mcpServers", {}):
133
+ raise GenerationError(f"missing required MCP artifact: {path}")
134
+
135
+
136
+ def _runner_timeout(event: dict) -> int:
137
+ value = event.get("runner_timeout_sec", 1)
138
+ if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 30:
139
+ raise GenerationError(
140
+ f"hook {event.get('id', '<unknown>')} runner_timeout_sec must be an integer from 1 to 30"
141
+ )
142
+ return value
143
+
144
+
145
+ def _codex_windows_command(event: dict) -> str:
146
+ """Run Codex hooks fail-open when its plugin-root env is unavailable."""
147
+ return (
148
+ "cmd.exe /d /c if defined PLUGIN_ROOT if exist "
149
+ '"%PLUGIN_ROOT%\\hooks\\run-hook.cmd" '
150
+ 'call "%PLUGIN_ROOT%\\hooks\\run-hook.cmd" '
151
+ f'{event["command"]} codex-cli & exit /b 0'
152
+ )
153
+
154
+
155
+ def _nested_hook_config(manifest: dict, client_id: str) -> dict:
156
+ hooks: dict[str, list[dict]] = {}
157
+ for event in manifest.get("events", []):
158
+ native = event.get("clients", {}).get(client_id)
159
+ if not native:
160
+ continue
161
+ runner_timeout = _runner_timeout(event)
162
+ if client_id == "claude-code-cli":
163
+ handler = {
164
+ "type": "command",
165
+ "command": (
166
+ '"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd" '
167
+ f'{event["command"]} claude-code-cli'
168
+ ),
169
+ "timeout": runner_timeout,
170
+ }
171
+ else:
172
+ codex_timeout = max(runner_timeout, 5)
173
+ handler = {
174
+ "type": "command",
175
+ "command": (
176
+ '"$PLUGIN_ROOT/hooks/run-hook.cmd" '
177
+ f'{event["command"]} codex-cli'
178
+ ),
179
+ "commandWindows": _codex_windows_command(event),
180
+ "timeout": codex_timeout,
181
+ }
182
+ entry: dict[str, object] = {"hooks": [handler]}
183
+ if event.get("matcher"):
184
+ entry["matcher"] = event["matcher"]
185
+ hooks.setdefault(native, []).append(entry)
186
+ return {
187
+ "description": "ADR Kit deterministic fail-open lifecycle hooks.",
188
+ "hooks": hooks,
189
+ }
190
+
191
+
192
+ def _copilot_hook_config(manifest: dict) -> dict:
193
+ hooks: dict[str, list[dict]] = {}
194
+ for event in manifest.get("events", []):
195
+ native = event.get("clients", {}).get("github-copilot-cli")
196
+ if not native:
197
+ continue
198
+ command = event["command"]
199
+ runner_timeout = _runner_timeout(event)
200
+ hooks.setdefault(native, []).append({
201
+ "type": "command",
202
+ "bash": (
203
+ 'python3 "${PLUGIN_ROOT}/hooks/adr-hook.py" '
204
+ f"--client github-copilot-cli --event {command} || true"
205
+ ),
206
+ "powershell": (
207
+ # The native exe is opt-in via ADR_KIT_NATIVE_HOOK=1, exactly as
208
+ # hooks/run-hook.cmd gates it: preferring it by default silently
209
+ # narrowed governance on Windows (the host is not
210
+ # parity-certified), and Copilot was the one client that did.
211
+ '$native = "${PLUGIN_ROOT}/hooks/bin/windows-x64/adr-hook.exe"; '
212
+ f'if ($env:ADR_KIT_NATIVE_HOOK -eq "1" -and (Test-Path $native)) '
213
+ f'{{ & $native --client github-copilot-cli --event {command} }} '
214
+ "else { $python = Get-Command python -ErrorAction SilentlyContinue; "
215
+ f'if ($python) {{ & $python.Source "${{PLUGIN_ROOT}}/hooks/adr-hook.py" '
216
+ f"--client github-copilot-cli --event {command} }} }}; exit 0"
217
+ ),
218
+ "cwd": "${PLUGIN_ROOT}",
219
+ "timeoutSec": runner_timeout,
220
+ })
221
+ return {"version": 1, "hooks": hooks}
222
+
223
+
224
+ def native_hook_config(manifest: dict, client_id: str) -> bytes:
225
+ if client_id == "github-copilot-cli":
226
+ return encoded_json(_copilot_hook_config(manifest))
227
+ return encoded_json(_nested_hook_config(manifest, client_id))
228
+
229
+
230
+ def render_skill(workflow: dict, client_id: str) -> bytes:
231
+ invocation = (
232
+ f"Invoke explicitly with `$adr-kit:{workflow['id']}` when needed."
233
+ if client_id == "codex-cli"
234
+ else (
235
+ f"Select `adr-kit:{workflow['id']}` from `/skills`, or ask Copilot "
236
+ f"to use the `{workflow['id']}` ADR Kit skill."
237
+ )
238
+ )
239
+ lines = [
240
+ "---",
241
+ f"name: {workflow['id']}",
242
+ f"description: {workflow['description']}",
243
+ "license: MIT",
244
+ "---",
245
+ "",
246
+ f"<!-- {PROVENANCE}; schema v1; client {client_id}. -->",
247
+ f"# {workflow['title']}",
248
+ "",
249
+ invocation,
250
+ "Resolve `<plugin-root>` from this installed skill. Use only bundled,",
251
+ "local ADR Kit tools and follow this canonical workflow:",
252
+ "",
253
+ ]
254
+ lines.extend(f"{index}. {step}" for index, step in enumerate(workflow["procedure"], 1))
255
+ lines.extend([
256
+ "",
257
+ "Do not contact another model or mutate user-owned instructions.",
258
+ "",
259
+ ])
260
+ return "\n".join(lines).encode("utf-8")
261
+
262
+
263
+ def render_prompt(workflow: dict, label: str, client_id: str) -> bytes:
264
+ mutation = (
265
+ "This workflow may write files; show material changes before applying them."
266
+ if workflow["mutates"]
267
+ else "This workflow is read-only."
268
+ )
269
+ return (
270
+ f"<!-- {PROVENANCE}; schema v1; client {client_id}. -->\n"
271
+ f"# {workflow['title']}\n\n"
272
+ f"Use ADR Kit's `{workflow['id']}` skill in {label}. {mutation}\n"
273
+ "Pass the remaining prompt as the workflow topic or target. Preserve the "
274
+ "skill's confirmation and fail-open boundaries.\n"
275
+ ).encode("utf-8")
276
+
277
+
278
+ def declared_source_files(root: Path) -> list[Path]:
279
+ paths: list[Path] = []
280
+ for name in COPY_ROOTS:
281
+ source = root / name
282
+ if not source.is_dir():
283
+ raise GenerationError(f"missing declared input root: {name}")
284
+ paths.extend(path for path in source.rglob("*") if path.is_file() and "__pycache__" not in path.parts)
285
+ paths.extend(
286
+ root / relative
287
+ for relative in (*HOOK_RUNTIME_FILES, *RUNTIME_SUPPORT_FILES)
288
+ )
289
+ missing = [path for path in paths if not path.is_file()]
290
+ if missing:
291
+ raise GenerationError(
292
+ "missing declared runtime input: "
293
+ + ", ".join(str(path.relative_to(root)) for path in missing)
294
+ )
295
+ return sorted(paths, key=lambda path: path.relative_to(root).as_posix())
296
+
297
+
298
+ def inventory(root: Path, source_paths: Iterable[Path], source: dict) -> bytes:
299
+ entries = []
300
+ for path in source_paths:
301
+ relative = path.relative_to(root).as_posix()
302
+ if relative.startswith("bin/") and path.suffix == "" and path.name != "bump-version":
303
+ entries.append({
304
+ "path": relative,
305
+ "ownership": "runtime",
306
+ "purpose": f"ADR Kit {path.name} command",
307
+ "invocation": "direct-or-python",
308
+ "expected_mode": "100755",
309
+ "provenance": "declared bin entrypoint",
310
+ })
311
+ direct_scripts = source.get("direct_scripts", [])
312
+ if sum(bool(item.get("task_40_added")) for item in direct_scripts) > 4:
313
+ raise GenerationError("TASK-40 direct-script budget exceeded")
314
+ for item in sorted(direct_scripts, key=lambda value: value["path"]):
315
+ relative = item["path"]
316
+ if (root / relative).is_file():
317
+ entries.append({
318
+ "path": relative,
319
+ "ownership": item["owner"],
320
+ "purpose": item["purpose"],
321
+ "invocation": "python",
322
+ "expected_mode": "100644",
323
+ "provenance": "packaging/executables-source.json",
324
+ })
325
+ return encoded_json({
326
+ "schema_version": 1,
327
+ "provenance": "Generated by scripts/build-client-adapters.py",
328
+ "task_40_added_public_entrypoints": sorted(
329
+ item["path"] for item in direct_scripts if item.get("task_40_added")
330
+ ),
331
+ "entries": sorted(entries, key=lambda item: item["path"]),
332
+ })
333
+
334
+
335
+ def dependencies(source: dict) -> bytes:
336
+ if source.get("runtime") != [] or source.get("policy", {}).get("runtime_dependency_budget") != 0:
337
+ raise GenerationError("ADR Kit runtime dependency set must remain empty")
338
+ if source.get("policy", {}).get("coverage_is_runtime") is not False:
339
+ raise GenerationError("coverage/test tooling cannot be runtime metadata")
340
+ for dependency in source.get("development", []):
341
+ if dependency.get("exact_pin") is not None:
342
+ required = {"compatibility_reason", "review_after", "update_mechanism", "removal_test", "adr"}
343
+ if not required.issubset(dependency):
344
+ raise GenerationError(f"exact dependency pin lacks exception evidence: {dependency.get('name')}")
345
+ return encoded_json({
346
+ "schema_version": 1,
347
+ "provenance": "Generated by scripts/build-client-adapters.py from packaging/dependencies-source.json",
348
+ "runtime": [],
349
+ "development": source.get("development", []),
350
+ "licenses": sorted({item["license"] for item in source.get("development", [])}),
351
+ })