@rvdbreemen/adr-kit-opencode 0.59.0 → 0.60.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 (41) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +66 -24
  3. package/bin/adr-context +2 -1
  4. package/bin/adr-doctor +1 -1
  5. package/bin/adr-guardian +10 -1
  6. package/bin/adr-judge +12 -57
  7. package/bin/adr-settings +59 -8
  8. package/bin/adr-substance +15 -0
  9. package/bin/adr-suggest +8 -3
  10. package/bin/adr_config.py +33 -0
  11. package/bin/adr_doctor_checks.py +9 -3
  12. package/bin/adr_doctor_core.py +4 -4
  13. package/bin/adr_doctor_probes.py +100 -13
  14. package/bin/adr_llm.py +178 -3
  15. package/bin/adr_readiness.py +17 -1
  16. package/clients/workflows.json +10 -7
  17. package/hooks/adr_hook_core.py +176 -28
  18. package/instructions/ADR-guide.md +1 -1
  19. package/opencode/plugin.ts +52 -10
  20. package/package.json +1 -1
  21. package/schemas/adr-kit-config.schema.json +7 -2
  22. package/scripts/client_generation.py +2 -5
  23. package/scripts/client_generation_artifacts.py +13 -2
  24. package/scripts/client_generation_model.py +4 -0
  25. package/scripts/release_phases.py +7 -7
  26. package/skills/guardian/SKILL.md +6 -4
  27. package/skills/init/SKILL.md +32 -11
  28. package/skills/install-hooks/SKILL.md +10 -9
  29. package/skills/judge/SKILL.md +6 -3
  30. package/skills/lint/SKILL.md +2 -1
  31. package/skills/related/SKILL.md +2 -1
  32. package/skills/review/SKILL.md +2 -1
  33. package/skills/setup/SKILL.md +2 -1
  34. package/skills/supersede/SKILL.md +2 -1
  35. package/skills/upgrade/SKILL.md +22 -3
  36. package/templates/adr-kit-guide.md +3 -3
  37. package/templates/cc-settings/guardian-hook-entry.json +2 -2
  38. package/templates/githooks/pre-commit +60 -20
  39. package/templates/github-workflows/adr-index-check.yml +1 -1
  40. package/templates/github-workflows/adr-judge.yml +1 -1
  41. package/templates/github-workflows/adr-readiness.yml +1 -1
@@ -15,12 +15,14 @@ not a thing anyone should have to find by grepping. See `refresh_index`.
15
15
  from __future__ import annotations
16
16
 
17
17
  import fnmatch
18
+ import hashlib
18
19
  import json
19
20
  import os
20
21
  import re
21
22
  import tempfile
22
23
  import sys
23
24
  from dataclasses import dataclass
25
+ from datetime import datetime, timedelta, timezone
24
26
  from pathlib import Path
25
27
  from typing import Any
26
28
 
@@ -51,6 +53,14 @@ WRITE_TOOLS = {
51
53
  "notebookedit",
52
54
  }
53
55
  PLAN_EXIT_TOOLS = {"exitplanmode", "exitplan", "planexit"}
56
+ # The header lines of an apply_patch patch, one per file it touches.
57
+ PATCH_HEADER = re.compile(
58
+ r"^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+?)\s*$", re.MULTILINE
59
+ )
60
+ # query_adr_context takes at most 32 path filters of at most 240 characters,
61
+ # and raises on more, which would leave the whole edit without context.
62
+ MAX_EDIT_PATHS = 32
63
+ MAX_EDIT_PATH_CHARS = 240
54
64
 
55
65
  # Events this hook accepts and deliberately answers with nothing. Silence here
56
66
  # is a decision, not an oversight, so each entry carries its reason: a future
@@ -176,17 +186,31 @@ def parse_payload(raw: bytes, client: str, event: str | None = None) -> Envelope
176
186
 
177
187
 
178
188
  def duplicate_event(envelope: Envelope) -> bool:
179
- """Best-effort cross-process dedupe in OS temp; failures stay fail-open."""
189
+ """Best-effort cross-process dedupe in OS temp; failures stay fail-open.
190
+
191
+ Only the same event delivered twice is a duplicate, so the signature names
192
+ the whole tool input and the workspace. It used to name only a file path:
193
+ Bash has no PostToolUse hook, so `gh pr create` straight after `git push`
194
+ matched the push and was dropped before the PR guard ran, and so was every
195
+ apply_patch edit after another one, since a patch carries no file path.
196
+ """
180
197
  if not envelope.session_id:
181
198
  return False
182
- path_value = _first(
183
- envelope.tool_input, "file_path", "filePath", "path", "notebook_path"
184
- )
199
+ tool_input = hashlib.sha256(
200
+ json.dumps(
201
+ envelope.tool_input,
202
+ ensure_ascii=False,
203
+ sort_keys=True,
204
+ separators=(",", ":"),
205
+ default=str,
206
+ ).encode("utf-8")
207
+ ).hexdigest()
185
208
  signature = json.dumps(
186
209
  [
210
+ str(envelope.workspace),
187
211
  envelope.event,
188
212
  envelope.tool_name,
189
- path_value,
213
+ tool_input,
190
214
  envelope.prompt,
191
215
  envelope.agent_id,
192
216
  ],
@@ -602,7 +626,7 @@ def _query(
602
626
  workspace: Path,
603
627
  query: str,
604
628
  *,
605
- path: str | None = None,
629
+ paths: tuple[str, ...] = (),
606
630
  ) -> list[dict[str, Any]]:
607
631
  """Rank the ADRs for this query, lexically over the generated index.
608
632
 
@@ -622,7 +646,9 @@ def _query(
622
646
  strict_index=True,
623
647
  include_history=False,
624
648
  statuses=("Accepted", "Proposed"),
625
- paths=(path,) if path else (),
649
+ paths=tuple(
650
+ path for path in paths if len(path) <= MAX_EDIT_PATH_CHARS
651
+ )[:MAX_EDIT_PATHS],
626
652
  )
627
653
  except (IndexQueryError, OSError, UnicodeError, ValueError):
628
654
  return []
@@ -633,11 +659,8 @@ def _query(
633
659
  ][:limit]
634
660
 
635
661
 
636
- def _safe_edit_path(envelope: Envelope) -> Path | None:
637
- value = _first(
638
- envelope.tool_input, "file_path", "filePath", "path", "notebook_path"
639
- )
640
- if not isinstance(value, str) or len(value) > 4096:
662
+ def _safe_path(envelope: Envelope, value: object) -> Path | None:
663
+ if not isinstance(value, str) or not value or len(value) > 4096:
641
664
  return None
642
665
  candidate = Path(value).expanduser()
643
666
  if not candidate.is_absolute():
@@ -650,6 +673,33 @@ def _safe_edit_path(envelope: Envelope) -> Path | None:
650
673
  return resolved
651
674
 
652
675
 
676
+ def _safe_edit_paths(envelope: Envelope) -> list[Path]:
677
+ """The in-workspace files an edit touches, at most MAX_EDIT_PATHS.
678
+
679
+ Most edit tools name one file. An apply_patch edit names none: Codex sends
680
+ the patch as `command` and OpenCode as `patchText`, and each header line
681
+ names a file it adds, updates, deletes or moves to. Hunk lines start with
682
+ `+`, `-`, a space or `@@`, so their text can never pass for a header.
683
+ """
684
+ value = _first(
685
+ envelope.tool_input, "file_path", "filePath", "path", "notebook_path"
686
+ )
687
+ if value is not None:
688
+ path = _safe_path(envelope, value)
689
+ return [path] if path else []
690
+ patch = _first(envelope.tool_input, "command", "patchText")
691
+ if not isinstance(patch, str):
692
+ return []
693
+ paths: list[Path] = []
694
+ for match in PATCH_HEADER.finditer(patch):
695
+ path = _safe_path(envelope, match.group(1))
696
+ if path and path not in paths:
697
+ paths.append(path)
698
+ if len(paths) == MAX_EDIT_PATHS:
699
+ break
700
+ return paths
701
+
702
+
653
703
  def _matching_path_records(
654
704
  records: list[dict[str, Any]], workspace: Path, path: Path
655
705
  ) -> list[dict[str, Any]]:
@@ -695,7 +745,7 @@ def _safe_source_argument(path: str) -> str | None:
695
745
 
696
746
  def _proposed_advisory(
697
747
  proposed: list[dict[str, Any]],
698
- relative: str,
748
+ relatives: list[str],
699
749
  client: str,
700
750
  ) -> str:
701
751
  linked = []
@@ -707,6 +757,7 @@ def _proposed_advisory(
707
757
  if any(
708
758
  fnmatch.fnmatchcase(relative.casefold(), str(value).casefold())
709
759
  or relative.casefold() == str(value).replace("\\", "/").casefold()
760
+ for relative in relatives
710
761
  for value in list(verified) + list(globs)
711
762
  ):
712
763
  linked.append(record)
@@ -718,15 +769,21 @@ def _proposed_advisory(
718
769
  f"Proposed ADR implementation link: {adr_id} -> "
719
770
  f"{_client_grill(client, adr_id)}"
720
771
  )
721
- if not lines and re.search(
722
- r"(^|/)(?:architecture|infra(?:structure)?|migrations?|schemas?|"
723
- r"api|contracts?|config|deploy|security)(?:/|[-_.])|"
724
- r"(^|/)(?:dockerfile|compose\.ya?ml|pyproject\.toml|package\.json|"
725
- r"Cargo\.toml|go\.mod)$",
726
- relative,
727
- re.IGNORECASE,
728
- ):
729
- quoted = _safe_source_argument(relative)
772
+ # At most one suggestion: the first file that looks architectural.
773
+ architectural = (
774
+ relative
775
+ for relative in relatives
776
+ if re.search(
777
+ r"(^|/)(?:architecture|infra(?:structure)?|migrations?|schemas?|"
778
+ r"api|contracts?|config|deploy|security)(?:/|[-_.])|"
779
+ r"(^|/)(?:dockerfile|compose\.ya?ml|pyproject\.toml|package\.json|"
780
+ r"Cargo\.toml|go\.mod)$",
781
+ relative,
782
+ re.IGNORECASE,
783
+ )
784
+ )
785
+ if not lines:
786
+ quoted = _safe_source_argument(next(architectural, ""))
730
787
  if quoted:
731
788
  lines.append(
732
789
  "Possible durable architecture decision -> "
@@ -810,14 +867,100 @@ def evaluate(envelope: Envelope) -> tuple[str, str]:
810
867
  except Exception: # noqa: BLE001 -- fail-open is this file's contract
811
868
  notice = STALE_INDEX_MESSAGE
812
869
 
870
+ try:
871
+ onboarding = llm_onboarding(envelope)
872
+ except Exception: # noqa: BLE001 -- fail-open is this file's contract
873
+ onboarding = ""
874
+
813
875
  context, kind = _evaluate_context(envelope)
876
+ if onboarding:
877
+ context = "\n\n".join(part for part in (context, onboarding) if part)
878
+ kind = kind if kind != "noop" else "llm-onboarding"
814
879
  if not notice:
815
- return context, kind
880
+ return context[:MAX_CONTEXT_CHARS], kind
816
881
  if not context:
817
882
  return notice, "stale-index"
818
883
  return "\n\n".join((notice, context))[:MAX_CONTEXT_CHARS], kind
819
884
 
820
885
 
886
+ ONBOARDING_EVENTS = {"SessionStart", "UserPromptSubmit"}
887
+ ONBOARDING_COOLDOWN_HOURS = 24
888
+
889
+
890
+ def llm_onboarding(envelope: Envelope) -> str:
891
+ """Turn the LLM layers on for a default install, and ask once (ADR-049).
892
+
893
+ Records the client this session runs in as the judge's host when nothing
894
+ is recorded yet, on the session-scoped events only (ADR-021 is the
895
+ precedent for a session hook that writes; the edit-tier hooks stay
896
+ read-only). On a real prompt it then asks the user, through the session
897
+ model, whether to keep the layers on, until a confirmation is recorded,
898
+ at most once per ONBOARDING_COOLDOWN_HOURS.
899
+ """
900
+ if envelope.event not in ONBOARDING_EVENTS:
901
+ return ""
902
+ adr_dir = envelope.workspace / "docs" / "adr"
903
+ if not adr_dir.is_dir():
904
+ return ""
905
+ import adr_llm
906
+
907
+ # A client whose hook output borrows another client's shape (OpenCode
908
+ # renders as claude-code-cli) names its own host through this variable.
909
+ host_client = os.environ.get("ADR_KIT_HOST_CLIENT") or envelope.client
910
+ adr_llm.record_host_client_if_absent(adr_dir, host_client)
911
+ if envelope.event != "UserPromptSubmit" or not (envelope.prompt or "").strip():
912
+ return ""
913
+ if os.environ.get("ADR_KIT_NO_LLM") == "1":
914
+ return ""
915
+ local_path = adr_dir / adr_llm.LOCAL_CONFIG_NAME
916
+ try:
917
+ local = json.loads(local_path.read_text(encoding="utf-8")) if local_path.exists() else {}
918
+ except (OSError, UnicodeError, json.JSONDecodeError):
919
+ return ""
920
+ llm_block = local.get("llm") if isinstance(local, dict) and isinstance(local.get("llm"), dict) else {}
921
+ if llm_block.get("confirmed"):
922
+ return ""
923
+ now = datetime.now(timezone.utc)
924
+ asked = _parse_utc(llm_block.get("asked_at"))
925
+ if asked is not None and now - asked < timedelta(hours=ONBOARDING_COOLDOWN_HOURS):
926
+ return ""
927
+ adr_llm.write_local_value(adr_dir, "llm", "asked_at", now.isoformat())
928
+ host = ((local.get("judge") or {}) if isinstance(local.get("judge"), dict) else {}).get("host_client")
929
+ return _onboarding_question(host or host_client)
930
+
931
+
932
+ def _parse_utc(value: object):
933
+ if not isinstance(value, str):
934
+ return None
935
+ try:
936
+ parsed = datetime.fromisoformat(value)
937
+ except ValueError:
938
+ return None
939
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
940
+
941
+
942
+ def _onboarding_question(host: str) -> str:
943
+ # The interpreter running this hook exists by construction; a bare `python`
944
+ # does not on macOS and most Linux distributions (DEF-34).
945
+ settings = (
946
+ f'"{Path(sys.executable).as_posix()}" '
947
+ f'"{(_BIN_DIR / "adr-settings").as_posix()}" --adr-dir docs/adr'
948
+ )
949
+ return (
950
+ "[adr-kit] The LLM layers are on by default and run on this coding "
951
+ f"assistant's own model ({host}); no API key is involved:\n"
952
+ "- the per-commit judge pass (judge.llm_enabled), which can block a commit;\n"
953
+ "- the missing-decision nudge, adr-suggest (suggest.enabled), which never blocks;\n"
954
+ "- the guardian's LLM tier (guardian.llm_enabled), which asks before each run.\n"
955
+ "Before continuing with the user's request, ask the user once whether to "
956
+ "keep them on (recommended) or turn any of them off for this machine. "
957
+ "Apply only what the user answers: for each layer to turn off run "
958
+ f"`{settings} --set <switch>=false --local`. Then record the answer, also "
959
+ f"when everything stays on, with `{settings} --set llm.confirmed=<today, "
960
+ "YYYY-MM-DD> --local`. Until that is recorded this question returns once a day."
961
+ )
962
+
963
+
821
964
  def _evaluate_context(envelope: Envelope) -> tuple[str, str]:
822
965
  """Render the context for this moment."""
823
966
  compact_event = re.sub(r"[^a-z]", "", envelope.event.lower())
@@ -934,11 +1077,16 @@ def _evaluate_context(envelope: Envelope) -> tuple[str, str]:
934
1077
  "inject" if envelope.event == "PreToolUse" else "watch",
935
1078
  ):
936
1079
  return "", "noop"
937
- path = _safe_edit_path(envelope)
938
- if path is None:
1080
+ paths = _safe_edit_paths(envelope)
1081
+ if not paths:
939
1082
  return "", "noop"
940
- relative = path.relative_to(envelope.workspace).as_posix()
941
- selected = _query(envelope.workspace, relative, path=relative)
1083
+ relatives = [path.relative_to(envelope.workspace).as_posix() for path in paths]
1084
+ # One query ranks the decisions for all the files a patch touches. The
1085
+ # hook shows the same few either way, and one index load per file costs
1086
+ # about ten times as much.
1087
+ selected = _query(
1088
+ envelope.workspace, " ".join(relatives), paths=tuple(relatives)
1089
+ )
942
1090
  governing = [item for item in selected if item.get("status") == "Accepted"]
943
1091
  advisory = [item for item in selected if item.get("status") == "Proposed"]
944
1092
  heading = (
@@ -952,7 +1100,7 @@ def _evaluate_context(envelope: Envelope) -> tuple[str, str]:
952
1100
  _render(governing, heading),
953
1101
  _render(advisory, "Advisory Proposed ADRs for this edit:"),
954
1102
  _proposed_advisory(
955
- proposed, relative, envelope.client
1103
+ proposed, relatives, envelope.client
956
1104
  ),
957
1105
  )
958
1106
  if part
@@ -1,4 +1,4 @@
1
- <!-- adr-kit-guide v0.59.0 -->
1
+ <!-- adr-kit-guide v0.60.0 -->
2
2
  <!-- Generated ADR Kit guidance. Local additions belong in .adr-kit/ADR-guide.local.md. -->
3
3
 
4
4
  # ADR Kit agent guide
@@ -107,6 +107,31 @@ function unique(values: string[]): string[] {
107
107
  return Array.from(new Set(values.filter(Boolean)))
108
108
  }
109
109
 
110
+ // ADR-044's order: ADR_KIT_PYTHON, then the interpreter this plugin was
111
+ // configured with (an installer's pin), then the first of python3, python and,
112
+ // on Windows, py -3 that runs Python 3.10 or newer. A bare python is missing on
113
+ // macOS and most Linux distributions, and macOS's own python3 is 3.9.
114
+ function resolvePython(options: PluginOptions): string[] {
115
+ const pinned = process.env.ADR_KIT_PYTHON || options.python
116
+ if (pinned) return [pinned]
117
+ const candidates = [["python3"], ["python"]]
118
+ if (process.platform === "win32") candidates.push(["py", "-3"])
119
+ for (const [name, ...args] of candidates) {
120
+ const executable = Bun.which(name)
121
+ if (!executable) continue
122
+ try {
123
+ const probe = Bun.spawnSync(
124
+ [executable, ...args, "-c", "import sys; sys.exit(sys.version_info < (3, 10))"],
125
+ { stdout: "ignore", stderr: "ignore", timeout: 5000 },
126
+ )
127
+ if (probe.exitCode === 0) return [executable, ...args]
128
+ } catch {
129
+ // Not runnable here; try the next candidate.
130
+ }
131
+ }
132
+ return [candidates[0][0]]
133
+ }
134
+
110
135
  function bounded(value: unknown, limit: number): string {
111
136
  return typeof value === "string" ? value.slice(0, limit) : ""
112
137
  }
@@ -179,7 +204,7 @@ function normalizeAutoGrillCommand(context: string): string {
179
204
 
180
205
  async function runHook(
181
206
  runtimeRoot: string | undefined,
182
- python: string,
207
+ python: string[],
183
208
  cwd: string,
184
209
  event: string,
185
210
  sessionID: string | undefined,
@@ -193,8 +218,16 @@ async function runHook(
193
218
  let child: ReturnType<typeof Bun.spawn>
194
219
  try {
195
220
  child = Bun.spawn(
196
- [python, hook, "--client", "claude-code-cli", "--event", event],
197
- { cwd, stdin: "pipe", stdout: "pipe", stderr: "ignore" },
221
+ [...python, hook, "--client", "claude-code-cli", "--event", event],
222
+ {
223
+ cwd,
224
+ stdin: "pipe",
225
+ stdout: "pipe",
226
+ stderr: "ignore",
227
+ // The hook renders Claude-shaped output for this plugin, but the LLM
228
+ // layers must run on OpenCode's own model (ADR-049, TASK-233).
229
+ env: { ...process.env, ADR_KIT_HOST_CLIENT: "opencode-cli" },
230
+ },
198
231
  )
199
232
  child.stdin.write(JSON.stringify({
200
233
  cwd,
@@ -244,6 +277,12 @@ function toolPath(args: AnyRecord): string {
244
277
  return ""
245
278
  }
246
279
 
280
+ // apply_patch names no file path: its files are in the patch's header lines,
281
+ // which the hook core reads from patchText.
282
+ function editsFiles(args: AnyRecord): boolean {
283
+ return Boolean(toolPath(args)) || typeof args.patchText === "string"
284
+ }
285
+
247
286
  function hookTimeout(options: PluginOptions, fallback: number): number {
248
287
  const configured = options.hookTimeoutMs
249
288
  if (!Number.isInteger(configured)) return fallback
@@ -257,9 +296,12 @@ function addContext(sessions: Map<string, SessionState>, sessionID: string | und
257
296
  state.contextKind = kind
258
297
  }
259
298
 
260
- function commandTemplate(root: string, workflow: AnyRecord): string {
299
+ function commandTemplate(root: string, python: string[], workflow: AnyRecord): string {
300
+ const interpreter = python.map((part) => (/\s/.test(part) ? `"${part}"` : part)).join(" ")
261
301
  const procedure = Array.isArray(workflow.procedure)
262
- ? workflow.procedure.map((item) => `- ${String(item).replaceAll("<plugin-root>", root)}`).join("\n")
302
+ ? workflow.procedure
303
+ .map((item) => `- ${String(item).replaceAll("<plugin-root>", root).replaceAll("<python>", interpreter)}`)
304
+ .join("\n")
263
305
  : "- Follow the ADR Kit documentation and use the adr-kit MCP tools."
264
306
  return [
265
307
  `Run the ADR Kit '${workflow.id}' workflow in OpenCode.`,
@@ -280,7 +322,7 @@ export default async function AdrKitOpenCodePlugin(
280
322
  ) {
281
323
  const options = rawOptions as PluginOptions
282
324
  const runtimeRoot = findRuntimeRoot(options.root, input.directory, input.worktree)
283
- const python = options.python || process.env.ADR_KIT_PYTHON || "python"
325
+ const python = resolvePython(options)
284
326
  const sessions = new Map<string, SessionState>()
285
327
 
286
328
  return {
@@ -316,7 +358,7 @@ export default async function AdrKitOpenCodePlugin(
316
358
  if (!config.mcp["adr-kit"]) {
317
359
  config.mcp["adr-kit"] = {
318
360
  type: "local",
319
- command: [python, join(runtimeRoot, "bin", "adr-mcp"), "--root", input.directory],
361
+ command: [...python, join(runtimeRoot, "bin", "adr-mcp"), "--root", input.directory],
320
362
  cwd: input.directory,
321
363
  enabled: true,
322
364
  timeout: 60000,
@@ -335,7 +377,7 @@ export default async function AdrKitOpenCodePlugin(
335
377
  if (config.command[name]) continue
336
378
  config.command[name] = {
337
379
  description: `ADR Kit: ${workflow.description || workflow.title || workflow.id}`,
338
- template: commandTemplate(runtimeRoot, workflow),
380
+ template: commandTemplate(runtimeRoot, python, workflow),
339
381
  }
340
382
  }
341
383
  }
@@ -417,7 +459,7 @@ export default async function AdrKitOpenCodePlugin(
417
459
  if (result.denied) throw new Error(result.reason || "ADR Kit blocked this pull-request command.")
418
460
  return
419
461
  }
420
- if (!WRITE_TOOLS.has(normalized) || !toolPath(args)) return
462
+ if (!WRITE_TOOLS.has(normalized) || !editsFiles(args)) return
421
463
  const result = await runHook(
422
464
  runtimeRoot,
423
465
  python,
@@ -435,7 +477,7 @@ export default async function AdrKitOpenCodePlugin(
435
477
  ) => {
436
478
  if (options.hooks === false) return
437
479
  const normalized = toolName(hookInput.tool)
438
- if (!WRITE_TOOLS.has(normalized) || !toolPath(hookInput.args || {})) return
480
+ if (!WRITE_TOOLS.has(normalized) || !editsFiles(hookInput.args || {})) return
439
481
  const result = await runHook(
440
482
  runtimeRoot,
441
483
  python,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rvdbreemen/adr-kit-opencode",
3
- "version": "0.59.0",
3
+ "version": "0.60.0",
4
4
  "description": "Native OpenCode plugin for ADR Kit, backed by the shared deterministic Python engines.",
5
5
  "type": "module",
6
6
  "main": "./opencode/plugin.ts",
@@ -197,9 +197,9 @@
197
197
  },
198
198
  "llm_timeout_seconds": {
199
199
  "type": "integer",
200
- "description": "Per-call timeout for the suggestion LLM pass in seconds. Defaults to judge.llm_timeout_seconds, then 120.",
200
+ "description": "Per-call timeout for the suggestion LLM pass in seconds. When unset: judge.llm_timeout_seconds if set, otherwise 30 (TASK-122: a nudge must not outlast what a person will wait for).",
201
201
  "minimum": 1,
202
- "default": 120
202
+ "default": 30
203
203
  }
204
204
  }
205
205
  },
@@ -366,6 +366,11 @@
366
366
  "minimum": 0,
367
367
  "default": 24
368
368
  },
369
+ "llm_enabled": {
370
+ "type": "boolean",
371
+ "description": "When false, the guardian's LLM tier (adr-substance and the full audit) is never due and calls no model. Defaults to true. An init or upgrade answer sets it for this machine only in .adr-kit.local.json (TASK-233); the cheap tier is unaffected.",
372
+ "default": true
373
+ },
369
374
  "llm_autorun": {
370
375
  "type": "boolean",
371
376
  "description": "When false (default), the /adr-kit:guardian skill always asks the user to confirm cost before running the LLM tier (adr-suggest + full audit). Set true only if you want the LLM tier to run without an interactive confirmation \u2014 consistent with ADR-001's opt-in posture, this defaults to false. The cheap tier (drift + retire + lint) is always free and unaffected by this flag.",
@@ -69,8 +69,7 @@ def _same_content(actual: bytes | None, expected: bytes) -> bool:
69
69
  Only the EOL dimension is relaxed. Content is still compared byte for byte,
70
70
  so a single changed character is still drift.
71
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,
72
+ A binary output would be compared byte-exactly and never normalised: a 0x0D 0x0A pair inside a binary is data,
74
73
  not a line ending, and collapsing it would make two genuinely different
75
74
  binaries compare equal. A NUL byte on either side is the binary signal --
76
75
  the same heuristic git itself uses.
@@ -140,9 +139,7 @@ def generate(
140
139
 
141
140
  for relative in HOOK_RUNTIME_FILES:
142
141
  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")
142
+ content = read(source, stats).replace(b"\r\n", b"\n")
146
143
  suffix = relative.removeprefix("hooks/")
147
144
  mode = stat.S_IMODE(source.stat().st_mode)
148
145
  for client_dir in GENERATED_CLIENTS.values():
@@ -244,8 +244,19 @@ def render_skill(workflow: dict, client_id: str) -> bytes:
244
244
  f"# {workflow['title']}",
245
245
  "",
246
246
  invocation,
247
- "Resolve `<plugin-root>` from this installed skill. Use only bundled,",
248
- "local ADR Kit tools and follow this canonical workflow:",
247
+ *(
248
+ [
249
+ "Resolve `<plugin-root>` from this installed skill, and `<python>` to the",
250
+ "first of `python3`, `python` or, on Windows, `py -3` that runs Python 3.10",
251
+ "or newer. Use only bundled, local ADR Kit tools and follow this canonical",
252
+ "workflow:",
253
+ ]
254
+ if any("<python>" in step for step in workflow["procedure"])
255
+ else [
256
+ "Resolve `<plugin-root>` from this installed skill. Use only bundled,",
257
+ "local ADR Kit tools and follow this canonical workflow:",
258
+ ]
259
+ ),
249
260
  "",
250
261
  ]
251
262
  lines.extend(f"{index}. {step}" for index, step in enumerate(workflow["procedure"], 1))
@@ -80,6 +80,10 @@ RUNTIME_SUPPORT_FILES = (
80
80
  "hooks/hook_benchmark.py",
81
81
  "scripts/adr_settings.py",
82
82
  "scripts/project_setup.py",
83
+ # The setup workflow runs <plugin-root>/scripts/setup-project.py, and an
84
+ # installed skill's <plugin-root> is its own tree. It imports only the two
85
+ # modules above and reads instructions/ and templates/, both mirrored.
86
+ "scripts/setup-project.py",
83
87
  )
84
88
  SOURCE_FILES = (
85
89
  "clients/capabilities.json",
@@ -49,7 +49,7 @@ from release_shell import ( # noqa: E402
49
49
  )
50
50
 
51
51
 
52
- # --- phase 0: preflight -----------------------------------------------------
52
+ # --- step 0: preflight ------------------------------------------------------
53
53
 
54
54
 
55
55
  def preflight_done(ctx: Context) -> bool:
@@ -109,7 +109,7 @@ def preflight(ctx: Context) -> List[str]:
109
109
  return notes
110
110
 
111
111
 
112
- # --- phase 1: prepare the version and the release notes ---------------------
112
+ # --- step 1: prepare the version and the release notes ----------------------
113
113
 
114
114
 
115
115
  def prepare_done(ctx: Context) -> bool:
@@ -165,7 +165,7 @@ def prepare(ctx: Context) -> List[str]:
165
165
  return notes
166
166
 
167
167
 
168
- # --- phase 2: the gates CI will run anyway ----------------------------------
168
+ # --- step 2: the gates CI will run anyway -----------------------------------
169
169
 
170
170
 
171
171
  def verify_done(ctx: Context) -> bool:
@@ -204,7 +204,7 @@ def verify(ctx: Context) -> List[str]:
204
204
  return notes
205
205
 
206
206
 
207
- # --- phase 3: land on main --------------------------------------------------
207
+ # --- step 3: land on main ---------------------------------------------------
208
208
 
209
209
 
210
210
  def land_done(ctx: Context) -> bool:
@@ -252,7 +252,7 @@ def land(ctx: Context) -> List[str]:
252
252
  return notes
253
253
 
254
254
 
255
- # --- phase 4: the tag the workflow creates ----------------------------------
255
+ # --- step 3: the tag the workflow creates -----------------------------------
256
256
 
257
257
 
258
258
  def verify_tag_done(ctx: Context) -> bool:
@@ -277,7 +277,7 @@ def verify_tag(ctx: Context) -> List[str]:
277
277
  return [f"{ctx.tag} resolves to {peeled[:7]}, equal to origin/main"]
278
278
 
279
279
 
280
- # --- phase 5: merge back into dev -------------------------------------------
280
+ # --- step 4: merge back into dev --------------------------------------------
281
281
 
282
282
 
283
283
  def syncback_done(ctx: Context) -> bool:
@@ -311,7 +311,7 @@ def syncback(ctx: Context) -> List[str]:
311
311
  return [f"sync pull request #{number} opened and armed"]
312
312
 
313
313
 
314
- # --- phase 6: this machine's prepared-directory marketplace -----------------
314
+ # --- step 6: this machine's prepared-directory marketplace ------------------
315
315
 
316
316
 
317
317
 
@@ -17,7 +17,7 @@ You are running the ADR-set health sweep. Your job is to run whichever tier(s) a
17
17
  Resolve the plugin bin path (same resolver used in /adr-kit:judge and /adr-kit:init):
18
18
 
19
19
  ```bash
20
- ADR_KIT=$(ls -d ~/.claude/plugins/cache/rvdbreemen-adr-kit/adr-kit/*/ 2>/dev/null | sort -V | tail -1)
20
+ ADR_KIT="${ADR_KIT_ROOT:-${CLAUDE_PLUGIN_ROOT}}"
21
21
  ```
22
22
 
23
23
  If `ADR_KIT` is empty (plugin not installed), fall back to a local checkout:
@@ -159,13 +159,15 @@ Enforcement coverage percent (from 2c) in the append-only trend log.
159
159
 
160
160
  ## Step 3 — LLM tier (suggest + audit) — ALWAYS confirm cost first
161
161
 
162
- **MANDATORY cost confirmation gate.** Before running this tier, read `docs/adr/.adr-kit.json`:
162
+ **MANDATORY cost confirmation gate.** Before running this tier, read the effective settings with `"$ADR_KIT/bin/adr-settings" --adr-dir docs/adr` (a value in the gitignored `.adr-kit.local.json` wins over `.adr-kit.json` for the LLM switches):
163
+
164
+ - If `guardian.llm_enabled` is `false`, skip this tier and stop at Step 4: the user switched it off (for the project or this machine).
163
165
 
164
166
  - If `guardian.llm_autorun` is `false` (default), print:
165
167
 
166
168
  ```
167
- [adr-guardian] LLM tier: adr-suggest + full audit will invoke claude-sonnet-4-6.
168
- Estimated cost: ~$0.10–0.30. Run now? (y/N)
169
+ [adr-guardian] LLM tier: adr-suggest + full audit will run on this client's own model
170
+ (the recorded judge host; no model is pinned, ADR-036/ADR-043). Run now? (y/N)
169
171
  ```
170
172
 
171
173
  Before printing it, run `"$ADR_KIT/bin/adr-substance" --estimate` and add