@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-watch ADDED
@@ -0,0 +1,674 @@
1
+ #!/usr/bin/env python3
2
+ """adr-watch: in-flight ADR guidance for just-edited files (v0.21+).
3
+
4
+ The PostToolUse counterpart to the SessionStart guardian and the pre-commit
5
+ judge. Given one or more file paths that were just edited, it prints at most
6
+ three compact one-line nudges naming the Accepted ADRs that likely apply:
7
+
8
+ [adr-watch] ADR-007 (no direct DB calls outside repository layer) may apply to src/db/foo.py
9
+
10
+ Two invocation modes:
11
+
12
+ adr-watch <path> [<path> ...]
13
+ Plain CLI mode. Prints nudges as plain text lines, one per nudge.
14
+
15
+ adr-watch --hook
16
+ PostToolUse hook mode. Reads the Claude Code PostToolUse JSON payload
17
+ from stdin ({"tool_name": ..., "tool_input": {"file_path": ...}}),
18
+ extracts the edited path, and emits the nudges wrapped in the
19
+ hookSpecificOutput JSON envelope (additionalContext) when running
20
+ under Claude Code, or as plain text otherwise.
21
+
22
+ Design invariants (same posture as bin/adr-guardian):
23
+ - ALWAYS exits 0. Advisory only; never blocks an edit.
24
+ - Self-guard: silent exit 0 when there is no docs/adr/ with ADRs.
25
+ - No LLM, no network, stdlib only. Deterministic.
26
+ - Target <100ms for 50 ADRs: each ADR file is read exactly once and all
27
+ regexes are precompiled at module level. All regexes are linear-time
28
+ (no nested lazy quantifiers; see the v0.19.1/v0.19.2 ReDoS history).
29
+ - Per-session cooldown: the same ADR+file pair is not nudged again within
30
+ watch.cooldown_hours (default 4). State lives under the "watch" key of
31
+ docs/adr/.adr-kit-state.json, written atomically via os.replace.
32
+ Missing or corrupt state is tolerated (treated as empty).
33
+
34
+ Matching signals:
35
+ 1. Enforcement path_glob match: the edited path matches a path_glob of any
36
+ rule in the ADR's ## Enforcement block. Strongest signal (score 1.0).
37
+ 2. Keyword relevance (adr-context style): fraction of keywords derived
38
+ from the edited path (directory names, file stem) that appear in the
39
+ ADR title + Decision section. Scaled to at most 0.8 so a glob hit
40
+ always outranks a keyword-only hit.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import argparse
46
+ import importlib.machinery
47
+ import importlib.util
48
+ import io
49
+ import json
50
+ import os
51
+ import re
52
+ import sys
53
+ from datetime import datetime, timezone
54
+ from pathlib import Path
55
+ from typing import Dict, List, Optional
56
+
57
+ _BIN_DIR = Path(__file__).resolve().parent
58
+
59
+
60
+ def _load_sibling(name: str):
61
+ """Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
62
+
63
+ SEC-HIGH (TASK-62): `sys.path.insert(0, _BIN_DIR)` put this directory ahead
64
+ of the standard library for every import, so a module committed next to
65
+ this script executed as code -- and it re-added the very directory
66
+ CPython's -P / PYTHONSAFEPATH removes. Siblings are registered in
67
+ sys.modules under their bare name, so the plain `from adr_* import ...`
68
+ statements below (and the lazy ones inside functions) resolve from the
69
+ cache instead of the path. bin/adr-judge carries the full rationale.
70
+ """
71
+ cached = sys.modules.get(name)
72
+ if cached is not None:
73
+ return cached
74
+ loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
75
+ spec = importlib.util.spec_from_loader(name, loader)
76
+ module = importlib.util.module_from_spec(spec)
77
+ sys.modules[name] = module
78
+ loader.exec_module(module)
79
+ return module
80
+
81
+
82
+ # Dependency order: adr_catalog imports adr_format and adr_schema;
83
+ # adr_config and adr_state are standalone.
84
+ _load_sibling("adr_format")
85
+ _load_sibling("adr_schema")
86
+ _load_sibling("adr_catalog")
87
+ _load_sibling("adr_config")
88
+ _load_sibling("adr_state")
89
+
90
+ from adr_catalog import adr_status as _adr_status
91
+ from adr_catalog import enforcement_globs as _parse_enforcement_globs
92
+ from adr_format import section_text
93
+ from adr_config import load_json_config as _load_config
94
+ from adr_state import find_project_adr_dir as _find_adr_dir
95
+ from adr_state import load_state, update_state
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # Constants
99
+ # ---------------------------------------------------------------------------
100
+
101
+ MAX_NUDGES = 3
102
+ DEFAULT_COOLDOWN_HOURS = 4.0
103
+ KEYWORD_SCORE_THRESHOLD = 0.5 # at least half the path keywords must hit
104
+ KEYWORD_SCORE_SCALE = 0.8 # keyword-only hits never outrank a glob hit
105
+
106
+ # Edit-tier injector (ADR-004): inject the governing ADR's Decision text
107
+ # *before* an Edit/Write, bounded to a token budget, on the PreToolUse hook.
108
+ DEFAULT_INJECT_MAX_TOKENS = 400
109
+ DEFAULT_INJECT_COOLDOWN_HOURS = 4.0
110
+ _CHARS_PER_TOKEN = 4 # coarse estimate, matches the OpenWolf prose heuristic
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # Precompiled regexes (all linear-time; reused from adr-judge / adr-context)
114
+ # ---------------------------------------------------------------------------
115
+
116
+ TITLE_RE = re.compile(r"^#\s+ADR-\d+[:\s]\s*(.+)$", re.MULTILINE)
117
+ DECISION_SECTION_RE = re.compile(
118
+ r"^##\s+Decision(.*?)(?=^##|\Z)", re.IGNORECASE | re.MULTILINE | re.DOTALL
119
+ )
120
+ ADR_FILENAME_RE = re.compile(r"ADR-(\d{1,4})", re.IGNORECASE)
121
+ WORD_SPLIT_RE = re.compile(r"[^a-z0-9]+")
122
+
123
+ _GLOB_PATTERN_CACHE: Dict[str, re.Pattern] = {}
124
+
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # UTF-8 stream setup (mirrors adr-guardian._ensure_utf8_streams)
128
+ # ---------------------------------------------------------------------------
129
+
130
+ def _ensure_utf8_streams() -> None:
131
+ """Force stdout/stderr to UTF-8 on Windows where the console may default to cp1252."""
132
+ for stream in (sys.stdout, sys.stderr):
133
+ if hasattr(stream, "reconfigure"):
134
+ try:
135
+ stream.reconfigure(encoding="utf-8")
136
+ except (AttributeError, io.UnsupportedOperation):
137
+ pass
138
+
139
+
140
+ # ---------------------------------------------------------------------------
141
+ # Glob translation (same semantics as bin/adr-judge glob_to_regex)
142
+ # ---------------------------------------------------------------------------
143
+
144
+ def glob_to_regex(glob: str) -> re.Pattern:
145
+ """Translate a shell-style glob (with ** and {a,b}) to an anchored regex."""
146
+ cached = _GLOB_PATTERN_CACHE.get(glob)
147
+ if cached is not None:
148
+ return cached
149
+ out: List[str] = []
150
+ i = 0
151
+ while i < len(glob):
152
+ c = glob[i]
153
+ if c == "*":
154
+ if i + 1 < len(glob) and glob[i + 1] == "*":
155
+ if i + 2 < len(glob) and glob[i + 2] == "/":
156
+ out.append("(?:.*/)?")
157
+ i += 3
158
+ else:
159
+ out.append(".*")
160
+ i += 2
161
+ else:
162
+ out.append("[^/]*")
163
+ i += 1
164
+ elif c == "?":
165
+ out.append("[^/]")
166
+ i += 1
167
+ elif c == "{":
168
+ close = glob.find("}", i + 1)
169
+ if close == -1 or "{" in glob[i + 1:close]:
170
+ out.append(re.escape(c))
171
+ i += 1
172
+ else:
173
+ inner = glob[i + 1:close]
174
+ alts = inner.split(",")
175
+ alt_patterns = [
176
+ glob_to_regex(a).pattern.lstrip("^").rstrip("$") if a else ""
177
+ for a in alts
178
+ ]
179
+ out.append("(?:" + "|".join(alt_patterns) + ")")
180
+ i = close + 1
181
+ else:
182
+ out.append(re.escape(c))
183
+ i += 1
184
+ compiled = re.compile("^" + "".join(out) + "$")
185
+ _GLOB_PATTERN_CACHE[glob] = compiled
186
+ return compiled
187
+
188
+
189
+ # ---------------------------------------------------------------------------
190
+ # Project / ADR-dir discovery (same posture as adr-guardian)
191
+ # ---------------------------------------------------------------------------
192
+
193
+ def _project_root() -> Path:
194
+ project_dir = os.environ.get("CLAUDE_PROJECT_DIR") or ""
195
+ if project_dir:
196
+ return Path(project_dir)
197
+ return Path.cwd()
198
+
199
+
200
+ # ---------------------------------------------------------------------------
201
+ # Config (watch block of .adr-kit.json)
202
+ # ---------------------------------------------------------------------------
203
+
204
+ def watch_config(cfg: Dict) -> Dict:
205
+ """Return the watch sub-block with defaults filled in."""
206
+ defaults = {
207
+ "enabled": True,
208
+ "cooldown_hours": DEFAULT_COOLDOWN_HOURS,
209
+ }
210
+ watch = cfg.get("watch")
211
+ if not isinstance(watch, dict):
212
+ watch = {}
213
+ return {**defaults, **watch}
214
+
215
+
216
+ def inject_config(cfg: Dict) -> Dict:
217
+ """Return the inject sub-block with defaults filled in (ADR-004)."""
218
+ defaults = {
219
+ "enabled": True,
220
+ "max_tokens": DEFAULT_INJECT_MAX_TOKENS,
221
+ "cooldown_hours": DEFAULT_INJECT_COOLDOWN_HOURS,
222
+ }
223
+ inject = cfg.get("inject")
224
+ if not isinstance(inject, dict):
225
+ inject = {}
226
+ return {**defaults, **inject}
227
+
228
+
229
+ # ---------------------------------------------------------------------------
230
+ # State (cooldown bookkeeping under the "watch" key of .adr-kit-state.json)
231
+ # ---------------------------------------------------------------------------
232
+
233
+ def _load_state(state_path: Path) -> Dict:
234
+ """Read .adr-kit-state.json. Returns {} when missing or invalid."""
235
+ return load_state(state_path, dict)
236
+
237
+
238
+ def _update_state(state_path: Path, mutation):
239
+ """Run a fail-open, locked state read-modify-write transaction."""
240
+ return update_state(state_path, dict, mutation)
241
+
242
+
243
+ def _now_utc() -> datetime:
244
+ return datetime.now(tz=timezone.utc)
245
+
246
+
247
+ def _parse_iso(s: Optional[str]) -> Optional[datetime]:
248
+ if not s or not isinstance(s, str):
249
+ return None
250
+ try:
251
+ return datetime.fromisoformat(s.replace("Z", "+00:00"))
252
+ except (ValueError, AttributeError):
253
+ return None
254
+
255
+
256
+ def _section_nudges(state: Dict, section: str) -> Dict[str, str]:
257
+ """Return the nudges map ("ADR-NNN|path" -> ISO timestamp) for a section."""
258
+ block = state.get(section)
259
+ if not isinstance(block, dict):
260
+ return {}
261
+ nudges = block.get("nudges")
262
+ if not isinstance(nudges, dict):
263
+ return {}
264
+ return {k: v for k, v in nudges.items() if isinstance(k, str) and isinstance(v, str)}
265
+
266
+
267
+ def _watch_nudges(state: Dict) -> Dict[str, str]:
268
+ """Return the watch.nudges map ("ADR-NNN|path" -> ISO timestamp)."""
269
+ return _section_nudges(state, "watch")
270
+
271
+
272
+ def _within_cooldown(nudges: Dict[str, str], key: str, cooldown_hours: float,
273
+ now: datetime) -> bool:
274
+ ts = _parse_iso(nudges.get(key))
275
+ if ts is None:
276
+ return False
277
+ elapsed_h = (now - ts).total_seconds() / 3600.0
278
+ return elapsed_h < cooldown_hours
279
+
280
+
281
+ def _prune_nudges(nudges: Dict[str, str], cooldown_hours: float,
282
+ now: datetime) -> Dict[str, str]:
283
+ """Drop entries older than the cooldown window so state stays small."""
284
+ kept: Dict[str, str] = {}
285
+ for key, raw in nudges.items():
286
+ ts = _parse_iso(raw)
287
+ if ts is None:
288
+ continue
289
+ if (now - ts).total_seconds() / 3600.0 < cooldown_hours:
290
+ kept[key] = raw
291
+ return kept
292
+
293
+
294
+ # ---------------------------------------------------------------------------
295
+ # ADR loading (one read per file)
296
+ # ---------------------------------------------------------------------------
297
+
298
+ def load_adrs(adr_dir: Path) -> List[Dict]:
299
+ """Load Accepted ADRs from adr_dir. Each file is read exactly once."""
300
+ adrs: List[Dict] = []
301
+ for adr_file in sorted(adr_dir.glob("ADR-*.md")):
302
+ try:
303
+ text = adr_file.read_text(encoding="utf-8")
304
+ except OSError:
305
+ continue
306
+ status = _adr_status(text)
307
+ if not status or status.lower() != "accepted":
308
+ continue
309
+
310
+ id_match = ADR_FILENAME_RE.search(adr_file.name)
311
+ adr_id = f"ADR-{int(id_match.group(1)):03d}" if id_match else adr_file.stem
312
+
313
+ title_match = TITLE_RE.search(text)
314
+ title = title_match.group(1).strip() if title_match else adr_file.stem
315
+
316
+ decision_text = section_text(text, "decision")
317
+
318
+ adrs.append({
319
+ "adr_id": adr_id,
320
+ "title": title,
321
+ "search_text": f"{title} {decision_text}".lower(),
322
+ "decision": decision_text.strip(),
323
+ "globs": _parse_enforcement_globs(text),
324
+ })
325
+ return adrs
326
+
327
+
328
+ # ---------------------------------------------------------------------------
329
+ # Path normalisation and keyword extraction
330
+ # ---------------------------------------------------------------------------
331
+
332
+ def normalize_path(raw: str, project_root: Path) -> str:
333
+ """Return a forward-slash path relative to the project root when possible."""
334
+ cleaned = raw.strip().replace("\\", "/")
335
+ p = Path(cleaned)
336
+ if p.is_absolute():
337
+ try:
338
+ rel = p.resolve().relative_to(project_root.resolve())
339
+ return rel.as_posix()
340
+ except (ValueError, OSError):
341
+ return p.as_posix()
342
+ return Path(cleaned).as_posix()
343
+
344
+
345
+ def path_keywords(rel_path: str) -> List[str]:
346
+ """Extract keywords from a path: directory names + file stem fragments.
347
+
348
+ Mirrors adr-context.extract_keywords: lowercase, split on non-alphanumeric,
349
+ keep words of 3+ characters. The file extension is dropped (it is rarely
350
+ an architectural keyword).
351
+ """
352
+ p = Path(rel_path)
353
+ parts = list(p.parts[:-1]) + [p.stem]
354
+ words: List[str] = []
355
+ for part in parts:
356
+ words.extend(WORD_SPLIT_RE.split(part.lower()))
357
+ return sorted({w for w in words if len(w) >= 3})
358
+
359
+
360
+ # ---------------------------------------------------------------------------
361
+ # Matching
362
+ # ---------------------------------------------------------------------------
363
+
364
+ def match_adrs(rel_path: str, adrs: List[Dict]) -> List[Dict]:
365
+ """Score every ADR against one edited path. Returns hits sorted by score.
366
+
367
+ Score 1.0: Enforcement path_glob matches the path.
368
+ Score <= 0.8 (scaled): keyword fraction of path words found in the
369
+ ADR title + Decision text, when at least
370
+ KEYWORD_SCORE_THRESHOLD of the words hit.
371
+ """
372
+ keywords = path_keywords(rel_path)
373
+ hits: List[Dict] = []
374
+ for adr in adrs:
375
+ score = 0.0
376
+ for glob in adr["globs"]:
377
+ try:
378
+ if glob_to_regex(glob).match(rel_path):
379
+ score = 1.0
380
+ break
381
+ except re.error:
382
+ continue
383
+ if score == 0.0 and keywords:
384
+ found = sum(1 for kw in keywords if kw in adr["search_text"])
385
+ fraction = found / len(keywords)
386
+ if fraction >= KEYWORD_SCORE_THRESHOLD:
387
+ score = round(KEYWORD_SCORE_SCALE * fraction, 4)
388
+ if score > 0.0:
389
+ hits.append({"adr_id": adr["adr_id"], "title": adr["title"], "score": score})
390
+ hits.sort(key=lambda h: (-h["score"], h["adr_id"]))
391
+ return hits
392
+
393
+
394
+ # ---------------------------------------------------------------------------
395
+ # Core run
396
+ # ---------------------------------------------------------------------------
397
+
398
+ def run_watch(paths: List[str], adr_dir: Path, now: Optional[datetime] = None) -> List[str]:
399
+ """Compute nudge lines for the given edited paths and update cooldown state.
400
+
401
+ Returns the list of nudge lines (possibly empty). Never raises.
402
+ """
403
+ if now is None:
404
+ now = _now_utc()
405
+
406
+ cfg = _load_config(adr_dir / ".adr-kit.json")
407
+ wcfg = watch_config(cfg)
408
+ if not wcfg.get("enabled", True):
409
+ return []
410
+ try:
411
+ cooldown_hours = float(wcfg.get("cooldown_hours", DEFAULT_COOLDOWN_HOURS))
412
+ except (TypeError, ValueError):
413
+ cooldown_hours = DEFAULT_COOLDOWN_HOURS
414
+
415
+ adrs = load_adrs(adr_dir)
416
+ if not adrs:
417
+ return []
418
+
419
+ state_path = adr_dir / ".adr-kit-state.json"
420
+ project_root = _project_root()
421
+
422
+ def collect_and_stamp(state):
423
+ nudges = _watch_nudges(state)
424
+ lines: List[str] = []
425
+ emitted_keys: List[str] = []
426
+
427
+ for raw_path in paths:
428
+ if len(lines) >= MAX_NUDGES:
429
+ break
430
+ rel_path = normalize_path(raw_path, project_root)
431
+ if not rel_path:
432
+ continue
433
+ for hit in match_adrs(rel_path, adrs):
434
+ if len(lines) >= MAX_NUDGES:
435
+ break
436
+ key = f"{hit['adr_id']}|{rel_path}"
437
+ if key in emitted_keys:
438
+ continue
439
+ if cooldown_hours > 0 and _within_cooldown(
440
+ nudges, key, cooldown_hours, now
441
+ ):
442
+ continue
443
+ lines.append(
444
+ f"[adr-watch] {hit['adr_id']} ({hit['title']}) "
445
+ f"may apply to {rel_path}"
446
+ )
447
+ emitted_keys.append(key)
448
+
449
+ if not emitted_keys:
450
+ return False, lines
451
+ pruned = _prune_nudges(
452
+ nudges, max(cooldown_hours, DEFAULT_COOLDOWN_HOURS), now
453
+ )
454
+ for key in emitted_keys:
455
+ pruned[key] = now.isoformat()
456
+ watch_state = state.get("watch")
457
+ if not isinstance(watch_state, dict):
458
+ watch_state = {}
459
+ watch_state["nudges"] = pruned
460
+ state["watch"] = watch_state
461
+ return True, lines
462
+
463
+ return _update_state(state_path, collect_and_stamp) or []
464
+
465
+
466
+ # ---------------------------------------------------------------------------
467
+ # Edit-tier injector (ADR-004): inject the governing ADR's Decision text
468
+ # *before* an Edit/Write, bounded to a token budget, on the PreToolUse hook.
469
+ # ---------------------------------------------------------------------------
470
+
471
+ def _bound_decision(decision: str, max_tokens: int) -> str:
472
+ """Truncate decision text to a token budget (coarse chars/token estimate)."""
473
+ if max_tokens <= 0 or not decision:
474
+ return decision.strip()
475
+ max_chars = max_tokens * _CHARS_PER_TOKEN
476
+ if len(decision) <= max_chars:
477
+ return decision.strip()
478
+ cut = decision[:max_chars]
479
+ # Prefer to break on the last paragraph or sentence boundary in-budget.
480
+ for sep in ("\n\n", ". ", "\n"):
481
+ idx = cut.rfind(sep)
482
+ if idx >= max_chars // 2:
483
+ cut = cut[: idx + (1 if sep == ". " else 0)]
484
+ break
485
+ return cut.strip() + " […]"
486
+
487
+
488
+ def run_inject(paths: List[str], adr_dir: Path,
489
+ now: Optional[datetime] = None) -> Optional[str]:
490
+ """Return injectable context for the top governing ADR of an about-to-edit
491
+ path, or None when nothing applies. Updates the inject cooldown state.
492
+
493
+ Never raises. Injects only the single highest-scored Accepted ADR, so the
494
+ agent sees the governing decision before it writes, without flooding
495
+ context.
496
+ """
497
+ if now is None:
498
+ now = _now_utc()
499
+
500
+ cfg = _load_config(adr_dir / ".adr-kit.json")
501
+ icfg = inject_config(cfg)
502
+ if not icfg.get("enabled", True):
503
+ return None
504
+ try:
505
+ max_tokens = int(icfg.get("max_tokens", DEFAULT_INJECT_MAX_TOKENS))
506
+ except (TypeError, ValueError):
507
+ max_tokens = DEFAULT_INJECT_MAX_TOKENS
508
+ try:
509
+ cooldown_hours = float(icfg.get("cooldown_hours", DEFAULT_INJECT_COOLDOWN_HOURS))
510
+ except (TypeError, ValueError):
511
+ cooldown_hours = DEFAULT_INJECT_COOLDOWN_HOURS
512
+
513
+ adrs = load_adrs(adr_dir)
514
+ if not adrs:
515
+ return None
516
+ decisions = {a["adr_id"]: a.get("decision", "") for a in adrs}
517
+
518
+ state_path = adr_dir / ".adr-kit-state.json"
519
+ project_root = _project_root()
520
+
521
+ def select_and_stamp(state):
522
+ nudges = _section_nudges(state, "inject")
523
+ for raw_path in paths:
524
+ rel_path = normalize_path(raw_path, project_root)
525
+ if not rel_path:
526
+ continue
527
+ hits = match_adrs(rel_path, adrs)
528
+ if not hits:
529
+ continue
530
+ top = hits[0]
531
+ key = f"{top['adr_id']}|{rel_path}"
532
+ if cooldown_hours > 0 and _within_cooldown(
533
+ nudges, key, cooldown_hours, now
534
+ ):
535
+ continue
536
+ decision = _bound_decision(
537
+ decisions.get(top["adr_id"], ""), max_tokens
538
+ )
539
+ if not decision:
540
+ continue
541
+
542
+ pruned = _prune_nudges(
543
+ nudges,
544
+ max(cooldown_hours, DEFAULT_INJECT_COOLDOWN_HOURS),
545
+ now,
546
+ )
547
+ pruned[key] = now.isoformat()
548
+ inject_state = state.get("inject")
549
+ if not isinstance(inject_state, dict):
550
+ inject_state = {}
551
+ inject_state["nudges"] = pruned
552
+ state["inject"] = inject_state
553
+ return True, (
554
+ f"[adr-inject] {top['adr_id']} ({top['title']}) governs "
555
+ f"{rel_path}. Honour its decision before editing:\n{decision}"
556
+ )
557
+ return False, None
558
+
559
+ return _update_state(state_path, select_and_stamp)
560
+
561
+
562
+ # ---------------------------------------------------------------------------
563
+ # Output envelopes
564
+ # ---------------------------------------------------------------------------
565
+
566
+ def _emit_hook_output(text: str, event: str = "PostToolUse") -> None:
567
+ """Emit text in a Claude Code hookSpecificOutput envelope for `event`.
568
+
569
+ Mirrors adr-guardian._emit_context: Claude Code gets the nested
570
+ hookSpecificOutput form; anything else gets plain text.
571
+ """
572
+ if os.environ.get("CLAUDE_PLUGIN_ROOT") and not os.environ.get("COPILOT_CLI"):
573
+ payload = {
574
+ "suppressOutput": True,
575
+ "hookSpecificOutput": {
576
+ "hookEventName": event,
577
+ "additionalContext": text,
578
+ }
579
+ }
580
+ sys.stdout.write(json.dumps(payload) + "\n")
581
+ else:
582
+ sys.stdout.write(text + "\n")
583
+ sys.stdout.flush()
584
+
585
+
586
+ def _paths_from_hook_payload(raw: str) -> List[str]:
587
+ """Extract edited file path(s) from a PostToolUse JSON payload string."""
588
+ try:
589
+ payload = json.loads(raw)
590
+ except json.JSONDecodeError:
591
+ return []
592
+ if not isinstance(payload, dict):
593
+ return []
594
+ tool_input = payload.get("tool_input")
595
+ if not isinstance(tool_input, dict):
596
+ return []
597
+ for key in ("file_path", "notebook_path", "path"):
598
+ value = tool_input.get(key)
599
+ if isinstance(value, str) and value:
600
+ return [value]
601
+ return []
602
+
603
+
604
+ # ---------------------------------------------------------------------------
605
+ # Main
606
+ # ---------------------------------------------------------------------------
607
+
608
+ def main() -> int:
609
+ _ensure_utf8_streams()
610
+ parser = argparse.ArgumentParser(
611
+ prog="adr-watch",
612
+ description=(
613
+ "In-flight ADR guidance: print compact nudges naming the Accepted ADRs "
614
+ "that likely apply to just-edited files. Advisory only; always exits 0."
615
+ ),
616
+ )
617
+ parser.add_argument("paths", nargs="*",
618
+ help="File path(s) that were just edited (or about to be, "
619
+ "with --pre-edit).")
620
+ parser.add_argument("--hook", action="store_true",
621
+ help="PostToolUse hook mode: read the tool payload JSON "
622
+ "from stdin and emit a hookSpecificOutput envelope.")
623
+ parser.add_argument("--pre-edit", action="store_true",
624
+ help="PreToolUse edit-tier mode (ADR-004): inject the "
625
+ "governing ADR's Decision text before the edit. Reads "
626
+ "the tool payload JSON from stdin like --hook.")
627
+ args = parser.parse_args()
628
+
629
+ # Self-guard: no ADR dir means nothing to say, anywhere.
630
+ adr_dir = _find_adr_dir()
631
+ if adr_dir is None:
632
+ return 0
633
+
634
+ hook_mode = args.hook or args.pre_edit
635
+ if hook_mode:
636
+ try:
637
+ raw = sys.stdin.read()
638
+ except OSError:
639
+ return 0
640
+ paths = _paths_from_hook_payload(raw)
641
+ else:
642
+ paths = list(args.paths)
643
+
644
+ if not paths:
645
+ return 0
646
+
647
+ if args.pre_edit:
648
+ context = run_inject(paths, adr_dir)
649
+ if not context:
650
+ return 0
651
+ _emit_hook_output(context, event="PreToolUse")
652
+ return 0
653
+
654
+ lines = run_watch(paths, adr_dir)
655
+ if not lines:
656
+ return 0
657
+
658
+ if args.hook:
659
+ _emit_hook_output("\n".join(lines))
660
+ else:
661
+ for line in lines:
662
+ sys.stdout.write(line + "\n")
663
+ sys.stdout.flush()
664
+ return 0
665
+
666
+
667
+ if __name__ == "__main__":
668
+ try:
669
+ sys.exit(main())
670
+ except KeyboardInterrupt:
671
+ sys.exit(0)
672
+ except Exception:
673
+ # Advisory tool: never propagate an error to the hook layer.
674
+ sys.exit(0)