@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,123 @@
1
+ """Bounded index-only grilling advisories for hooks and pre-commit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import re
7
+ import shlex
8
+ from pathlib import Path
9
+ from typing import Sequence
10
+
11
+
12
+ SIGNAL_SCHEMA_VERSION = 1
13
+ MAX_SIGNALS = 3
14
+ _ADR_RE = re.compile(r"\bADR-0*(\d{1,4})\b", re.IGNORECASE)
15
+ _SENSITIVE_RE = re.compile(
16
+ r"(^|/)(?:architecture|infra(?:structure)?|migrations?|schemas?|"
17
+ r"api|contracts?|config|deploy|security)(?:/|[-_.])|"
18
+ r"(^|/)(?:dockerfile|compose\.ya?ml|pyproject\.toml|package\.json|"
19
+ r"Cargo\.toml|go\.mod)$",
20
+ re.IGNORECASE,
21
+ )
22
+
23
+
24
+ def normalize_path(value: object) -> str:
25
+ normalized = str(value).replace("\\", "/").strip()
26
+ normalized = re.sub(r"[\x00-\x1f\x7f]+", " ", normalized)
27
+ normalized = normalized.replace("::", "__")
28
+ while normalized.startswith("./"):
29
+ normalized = normalized[2:]
30
+ return re.sub(r"/+", "/", normalized)
31
+
32
+
33
+ def _matches(path: str, target: str) -> bool:
34
+ path = normalize_path(path).casefold()
35
+ target = normalize_path(target).casefold()
36
+ if not target:
37
+ return False
38
+ if any(char in target for char in "*?["):
39
+ return fnmatch.fnmatchcase(path, target)
40
+ return path == target or path.startswith(target.rstrip("/") + "/")
41
+
42
+
43
+ def _quote(value: str, shell: str) -> str:
44
+ clean = re.sub(r"[\r\n\x00-\x1f]+", " ", value)[:4096]
45
+ if shell == "powershell":
46
+ return "'" + clean.replace("'", "''") + "'"
47
+ return shlex.quote(clean)
48
+
49
+
50
+ def analyze_index(
51
+ index: dict,
52
+ changed_paths: Sequence[str],
53
+ source_text: str,
54
+ *,
55
+ shell: str = "posix",
56
+ ) -> dict:
57
+ paths = sorted({normalize_path(path) for path in changed_paths if path}, key=str.casefold)
58
+ cited = {f"ADR-{int(match.group(1)):03d}" for match in _ADR_RE.finditer(source_text)}
59
+ linked = []
60
+ for record in index.get("adrs", []):
61
+ if not isinstance(record, dict) or record.get("status") != "Proposed":
62
+ continue
63
+ adr_id = str(record.get("id", ""))
64
+ metadata = record.get("metadata", {})
65
+ verified = metadata.get("verified_in", []) if isinstance(metadata, dict) else []
66
+ scope = record.get("scope", {})
67
+ globs = scope.get("path_globs", []) if isinstance(scope, dict) else []
68
+ verified_matches = sorted(
69
+ {path for path in paths for target in verified if _matches(path, str(target))},
70
+ key=str.casefold,
71
+ )
72
+ scope_matches = sorted(
73
+ {path for path in paths for target in globs if _matches(path, str(target))},
74
+ key=str.casefold,
75
+ )
76
+ adr_changed = any(Path(path).name == str(record.get("path", "")) for path in paths)
77
+ implementation = sorted(
78
+ {
79
+ path
80
+ for path in verified_matches + scope_matches
81
+ if not path.casefold().startswith("docs/adr/")
82
+ },
83
+ key=str.casefold,
84
+ )
85
+ if not implementation or not (
86
+ verified_matches or adr_changed or adr_id in cited
87
+ ):
88
+ continue
89
+ evidence = []
90
+ if adr_id in cited:
91
+ evidence.append("ADR_ID_EXPLICIT")
92
+ if adr_changed:
93
+ evidence.append("ADR_FILE_CHANGED")
94
+ if verified_matches:
95
+ evidence.append("VERIFIED_IN_CHANGED")
96
+ if scope_matches:
97
+ evidence.append("ENFORCEMENT_SCOPE_CHANGED")
98
+ linked.append(
99
+ {
100
+ "code": "LINKED_PROPOSED_IMPLEMENTATION",
101
+ "adr_id": adr_id,
102
+ "paths": implementation,
103
+ "evidence": sorted(set(evidence)),
104
+ "command": f"/adr-kit:grill {adr_id}",
105
+ }
106
+ )
107
+ linked.sort(key=lambda item: item["adr_id"])
108
+ linked_paths = {path for item in linked for path in item["paths"]}
109
+ suspected = [
110
+ {
111
+ "code": "ARCHITECTURE_REVIEW_RECOMMENDED",
112
+ "path": path,
113
+ "command": f"/adr-kit:grill --source {_quote(path, shell)}",
114
+ }
115
+ for path in paths
116
+ if path not in linked_paths and _SENSITIVE_RE.search(path)
117
+ ]
118
+ return {
119
+ "schema_version": SIGNAL_SCHEMA_VERSION,
120
+ "linked_proposed": linked[:MAX_SIGNALS],
121
+ "suspected_decisions": suspected[:MAX_SIGNALS],
122
+ "signal_count": min(MAX_SIGNALS, len(linked) + len(suspected)),
123
+ }
@@ -0,0 +1,218 @@
1
+ """Deterministic Proposed-ADR work queue and disposable cache helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import threading
9
+ import time
10
+ from datetime import date, datetime, timedelta, timezone
11
+ from pathlib import Path
12
+
13
+
14
+ QUEUE_SCHEMA_VERSION = 1
15
+ QUEUE_CACHE_NAME = ".adr-kit-readiness.json"
16
+ QUEUE_MAX_ACTIONS = 3
17
+ QUEUE_MAX_BYTES = 256 * 1024
18
+ QUEUE_TTL_HOURS = 24
19
+ # Mirrors adr_quality_core.QUALITY_THRESHOLD. Duplicated as a literal rather
20
+ # than imported because this module is read on the hook path and must stay
21
+ # dependency-free; the readiness report carries the real threshold with each
22
+ # record, and that value wins when present.
23
+ QUALITY_QUEUE_THRESHOLD = 0.70
24
+ _COMMAND_RE = re.compile(r"^/adr-kit:grill ADR-\d{3,4}$")
25
+
26
+
27
+ def _parse_date(value: object) -> date | None:
28
+ try:
29
+ return date.fromisoformat(str(value))
30
+ except (TypeError, ValueError):
31
+ return None
32
+
33
+
34
+ def _age_days(item: dict, evaluated_on: date) -> int:
35
+ recorded = _parse_date(item.get("date"))
36
+ return max(0, (evaluated_on - recorded).days) if recorded else 0
37
+
38
+
39
+ def rank_proposed(report: dict) -> list[dict]:
40
+ """Rank explainable Proposed work without granting lifecycle authority."""
41
+ evaluated_on = _parse_date(report.get("evaluated_on")) or date.min
42
+ candidates = []
43
+ for item in report.get("adrs", []):
44
+ if not isinstance(item, dict) or item.get("status") != "Proposed":
45
+ continue
46
+ link = item.get("implementation_link", {})
47
+ linked = bool(isinstance(link, dict) and link.get("linked"))
48
+ shipped = bool(item.get("documents_shipped"))
49
+ ready = item.get("classification") == "ready-for-confirmation"
50
+ open_questions = bool(item.get("open_questions"))
51
+ age_days = _age_days(item, evaluated_on)
52
+ quality = item.get("quality", {})
53
+ quality_score = (
54
+ float(quality.get("score", 1.0)) if isinstance(quality, dict) else 1.0
55
+ )
56
+ threshold = (
57
+ float(quality.get("threshold", QUALITY_QUEUE_THRESHOLD))
58
+ if isinstance(quality, dict)
59
+ else QUALITY_QUEUE_THRESHOLD
60
+ )
61
+ below_threshold = quality_score < threshold
62
+
63
+ # Quality used to be the last tiebreaker in the sort, which meant a
64
+ # sharp ADR and an empty one were both enrolled and only their order
65
+ # differed. Being below the threshold is now a reason to be here in its
66
+ # own right, and the absence of every reason is a reason to leave: a
67
+ # Proposed ADR that is sharp, unlinked, unshipped, not ready and asking
68
+ # nothing has no work attached to it, and listing it teaches the reader
69
+ # to skim the queue.
70
+ signals = (linked, shipped, ready, open_questions, below_threshold)
71
+ if not any(signals):
72
+ continue
73
+
74
+ reasons = []
75
+ if linked:
76
+ reasons.append("active implementation link")
77
+ if shipped:
78
+ reasons.append("shipped but Proposed")
79
+ if ready:
80
+ reasons.append("ready for confirmation")
81
+ if open_questions:
82
+ reasons.append("open human questions")
83
+ if below_threshold:
84
+ reasons.append(f"quality {quality_score:.3f} below {threshold:.2f}")
85
+ reasons.append(f"age {age_days} days")
86
+ if not below_threshold:
87
+ reasons.append(f"quality {quality_score:.3f}")
88
+ candidates.append(
89
+ {
90
+ "adr_id": item["adr_id"],
91
+ "classification": item.get("classification"),
92
+ "command": f"/adr-kit:grill {item['adr_id']}",
93
+ "reasons": reasons,
94
+ "quality_score": round(quality_score, 3),
95
+ "below_threshold": below_threshold,
96
+ "_rank": (
97
+ -int(linked),
98
+ -int(shipped),
99
+ -int(ready),
100
+ -int(open_questions),
101
+ -int(below_threshold),
102
+ -age_days,
103
+ quality_score,
104
+ str(item["adr_id"]),
105
+ ),
106
+ }
107
+ )
108
+ candidates.sort(key=lambda item: item["_rank"])
109
+ for position, item in enumerate(candidates, 1):
110
+ item["rank"] = position
111
+ item.pop("_rank", None)
112
+ return candidates
113
+
114
+
115
+ def build_queue_cache(
116
+ report: dict,
117
+ *,
118
+ generated_at: datetime,
119
+ ttl_hours: int = QUEUE_TTL_HOURS,
120
+ ) -> dict:
121
+ if generated_at.tzinfo is None:
122
+ generated_at = generated_at.replace(tzinfo=timezone.utc)
123
+ generated_at = generated_at.astimezone(timezone.utc)
124
+ expires_at = generated_at + timedelta(hours=ttl_hours)
125
+ ranked = rank_proposed(report)
126
+ return {
127
+ "schema_version": QUEUE_SCHEMA_VERSION,
128
+ "generated_at": generated_at.isoformat(),
129
+ "expires_at": expires_at.isoformat(),
130
+ "evaluated_on": report.get("evaluated_on"),
131
+ "source_schema_version": report.get("schema_version"),
132
+ "authoritative": False,
133
+ "actions": ranked[:QUEUE_MAX_ACTIONS],
134
+ "total_proposed": len(ranked),
135
+ }
136
+
137
+
138
+ def write_queue_cache(path: Path, payload: dict) -> None:
139
+ """Atomically replace the derived cache; interruption leaves old bytes."""
140
+ path.parent.mkdir(parents=True, exist_ok=True)
141
+ encoded = (
142
+ json.dumps(payload, indent=2, ensure_ascii=False, sort_keys=True) + "\n"
143
+ ).encode("utf-8")
144
+ if len(encoded) > QUEUE_MAX_BYTES:
145
+ raise ValueError("guardian readiness cache exceeds size limit")
146
+ temporary = path.with_name(
147
+ f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp"
148
+ )
149
+ try:
150
+ with temporary.open("xb") as stream:
151
+ stream.write(encoded)
152
+ for attempt in range(8):
153
+ try:
154
+ os.replace(temporary, path)
155
+ break
156
+ except PermissionError:
157
+ if attempt == 7:
158
+ raise
159
+ time.sleep(0.005 * (attempt + 1))
160
+ except BaseException:
161
+ try:
162
+ temporary.unlink()
163
+ except FileNotFoundError:
164
+ pass
165
+ raise
166
+
167
+
168
+ def load_queue_actions(
169
+ path: Path,
170
+ *,
171
+ now: datetime | None = None,
172
+ ) -> list[dict]:
173
+ """Read at most three safe actions; invalid or stale cache fails open."""
174
+ try:
175
+ if not path.is_file() or path.stat().st_size > QUEUE_MAX_BYTES:
176
+ return []
177
+ payload = json.loads(path.read_text(encoding="utf-8"))
178
+ except (OSError, UnicodeError, json.JSONDecodeError):
179
+ return []
180
+ if not isinstance(payload, dict) or payload.get("schema_version") != 1:
181
+ return []
182
+ try:
183
+ expires_at = datetime.fromisoformat(str(payload["expires_at"]))
184
+ except (KeyError, TypeError, ValueError):
185
+ return []
186
+ current = now or datetime.now(timezone.utc)
187
+ if current.tzinfo is None:
188
+ current = current.replace(tzinfo=timezone.utc)
189
+ if expires_at.tzinfo is None:
190
+ expires_at = expires_at.replace(tzinfo=timezone.utc)
191
+ if current.astimezone(timezone.utc) >= expires_at.astimezone(timezone.utc):
192
+ return []
193
+ safe = []
194
+ for item in payload.get("actions", []):
195
+ if not isinstance(item, dict):
196
+ continue
197
+ adr_id = str(item.get("adr_id", ""))
198
+ command = str(item.get("command", ""))
199
+ if not re.fullmatch(r"ADR-\d{3,4}", adr_id) or not _COMMAND_RE.fullmatch(
200
+ command
201
+ ):
202
+ continue
203
+ reasons = [
204
+ re.sub(r"[\r\n]+", " ", str(reason))[:160]
205
+ for reason in item.get("reasons", [])
206
+ if str(reason)
207
+ ][:6]
208
+ safe.append(
209
+ {
210
+ "adr_id": adr_id,
211
+ "classification": str(item.get("classification", ""))[:80],
212
+ "command": command,
213
+ "reasons": reasons,
214
+ }
215
+ )
216
+ if len(safe) == QUEUE_MAX_ACTIONS:
217
+ break
218
+ return safe
@@ -0,0 +1,278 @@
1
+ """Read the git history for decision-shaped evidence (spec R1, TASK-80).
2
+
3
+ The bootstrap scanners walk the working tree, which shows what the project is.
4
+ The history shows how it got that way -- and the *why* of an existing codebase
5
+ lives there, in the commit that says "switch to X because Y", in the merge that
6
+ introduced a subsystem, and in the file everybody keeps rewriting.
7
+
8
+ `.git/**` sits in the scanner's skip list, so none of that reached the candidate
9
+ set. This module is the missing half. It is deliberately separate from the tree
10
+ scanners for one reason: its findings are *weaker*. A commit subject is a claim
11
+ someone typed once, in a hurry, possibly wrong, and possibly about a decision
12
+ that was reversed three commits later. A file that exists is a fact. Mixing the
13
+ two into one undifferentiated list would let the weaker evidence borrow the
14
+ authority of the stronger, so every candidate here is stamped `source:
15
+ "history"` and carries the commit it came from.
16
+
17
+ Everything fails open. No git, no repository, a shallow clone, a repository with
18
+ one commit -- each yields an empty list, never an error. A bootstrap scan that
19
+ refuses to run because the history is thin is worse than one that scans what it
20
+ can and says so.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import re
26
+ import shutil
27
+ import subprocess
28
+ from collections import Counter
29
+ from pathlib import Path
30
+ from typing import Dict, List, Optional, Tuple
31
+
32
+ # How far back to look. A bootstrap scan wants the shape of the project, not an
33
+ # exhaustive audit, and every additional thousand commits buys less signal than
34
+ # the last. Overridable by the caller.
35
+ DEFAULT_MAX_COMMITS = 2000
36
+
37
+ # A subject line reads as decision-shaped when it announces a change of
38
+ # direction rather than a change of code. These are matched on the subject only:
39
+ # a commit body is where people paste stack traces.
40
+ DECISION_SUBJECT_RE = re.compile(
41
+ r"(?ix)\b("
42
+ r"switch(?:ed|ing)?\s+to|migrat(?:e|ed|ing)\s+to|replac(?:e|ed|ing)\s+\w+\s+with|"
43
+ r"mov(?:e|ed|ing)\s+(?:to|off)|drop(?:ped|ping)?\s+support|"
44
+ r"adopt(?:ed|ing)?|standardi[sz]e(?:d|ing)?\s+on|"
45
+ r"rewrite|rewrote|revert(?:ed)?\s+to|"
46
+ r"introduc(?:e|ed|ing)\s+\w+|deprecat(?:e|ed|ing)|"
47
+ r"choose|chose|decide[d]?\s+to"
48
+ r")\b"
49
+ )
50
+
51
+ # Churn only means something above a floor. Two edits to a file over five years
52
+ # is not a contested area, it is a file.
53
+ CHURN_MIN_COMMITS = 8
54
+ CHURN_TOP_N = 8
55
+
56
+ # Merge subjects that say nothing. "Merge branch 'main'" is bookkeeping.
57
+ UNINTERESTING_MERGE_RE = re.compile(
58
+ r"(?i)^merge\s+(?:branch|remote-tracking\s+branch|pull\s+request)\b"
59
+ )
60
+
61
+ SKIP_PATH_RE = re.compile(
62
+ r"(?i)(^|/)(\.git|node_modules|vendor|dist|build|__pycache__|"
63
+ r"\.venv|venv|target|coverage)(/|$)"
64
+ )
65
+
66
+
67
+ def _git(root: Path, args: List[str], timeout: int = 30) -> Optional[str]:
68
+ """Run a read-only git command. Any failure is None, never an exception."""
69
+ if shutil.which("git") is None:
70
+ return None
71
+ try:
72
+ result = subprocess.run(
73
+ ["git", *args],
74
+ cwd=str(root),
75
+ capture_output=True,
76
+ text=True,
77
+ encoding="utf-8",
78
+ errors="replace",
79
+ timeout=timeout,
80
+ check=False,
81
+ )
82
+ except (OSError, subprocess.SubprocessError):
83
+ return None
84
+ if result.returncode != 0:
85
+ return None
86
+ return result.stdout
87
+
88
+
89
+ def is_git_repository(root: Path) -> bool:
90
+ out = _git(root, ["rev-parse", "--is-inside-work-tree"], timeout=10)
91
+ return bool(out and out.strip() == "true")
92
+
93
+
94
+ def _commits(root: Path, max_commits: int) -> List[Tuple[str, str, str]]:
95
+ """(short sha, iso date, subject) newest first. Empty on any problem."""
96
+ out = _git(
97
+ root,
98
+ ["log", f"--max-count={max_commits}", "--no-merges",
99
+ "--date=short", "--pretty=format:%h\x1f%ad\x1f%s"],
100
+ )
101
+ if not out:
102
+ return []
103
+ rows: List[Tuple[str, str, str]] = []
104
+ for line in out.splitlines():
105
+ parts = line.split("\x1f")
106
+ if len(parts) == 3 and parts[2].strip():
107
+ rows.append((parts[0], parts[1], parts[2].strip()))
108
+ return rows
109
+
110
+
111
+ def scan_decision_subjects(root: Path, max_commits: int) -> List[Dict]:
112
+ """Commits whose subject announces a change of direction."""
113
+ candidates: List[Dict] = []
114
+ seen_subjects: set[str] = set()
115
+ for sha, date, subject in _commits(root, max_commits):
116
+ if UNINTERESTING_MERGE_RE.match(subject):
117
+ continue
118
+ if not DECISION_SUBJECT_RE.search(subject):
119
+ continue
120
+ # Conventional-commit prefixes repeat forever; dedupe on the payload.
121
+ normalized = re.sub(r"^\w+(\([^)]*\))?!?:\s*", "", subject).casefold()
122
+ if normalized in seen_subjects:
123
+ continue
124
+ seen_subjects.add(normalized)
125
+ candidates.append(
126
+ {
127
+ "id": f"history-subject-{sha}",
128
+ "title": subject,
129
+ "decision_type": "history-claim",
130
+ "source": "history",
131
+ "evidence_files": [],
132
+ "details": {
133
+ "commit": sha,
134
+ "date": date,
135
+ "why_this_is_weak": (
136
+ "A commit subject is a claim typed once. It may be wrong, "
137
+ "and the decision may have been reversed since. Confirm "
138
+ "against the code before writing an ADR from it."
139
+ ),
140
+ },
141
+ }
142
+ )
143
+ return candidates
144
+
145
+
146
+ def scan_churn(root: Path, max_commits: int) -> List[Dict]:
147
+ """Files rewritten often enough to suggest a contested design area."""
148
+ out = _git(
149
+ root,
150
+ ["log", f"--max-count={max_commits}", "--no-merges",
151
+ "--name-only", "--pretty=format:"],
152
+ )
153
+ if not out:
154
+ return []
155
+ counter: Counter = Counter()
156
+ for line in out.splitlines():
157
+ path = line.strip()
158
+ if not path or SKIP_PATH_RE.search(path):
159
+ continue
160
+ counter[path] += 1
161
+
162
+ hot = [(path, n) for path, n in counter.most_common(CHURN_TOP_N) if n >= CHURN_MIN_COMMITS]
163
+ if not hot:
164
+ return []
165
+ return [
166
+ {
167
+ "id": "history-churn",
168
+ "title": (
169
+ "Some files are rewritten far more often than the rest, which "
170
+ "usually marks a design nobody has settled."
171
+ ),
172
+ "decision_type": "history-signal",
173
+ "source": "history",
174
+ "evidence_files": [path for path, _ in hot],
175
+ "details": {
176
+ "churn": [{"path": path, "commits": n} for path, n in hot],
177
+ "window_commits": max_commits,
178
+ "why_this_is_weak": (
179
+ "Churn shows where the effort went, not what was decided. "
180
+ "It points at a question worth asking, not at an answer."
181
+ ),
182
+ },
183
+ }
184
+ ]
185
+
186
+
187
+ def scan_first_appearance(root: Path, paths: List[str]) -> List[Dict]:
188
+ """When each dependency or tooling marker first entered the repository.
189
+
190
+ The order in which subsystems appeared is the closest thing a repository
191
+ has to a timeline of its decisions.
192
+
193
+ One `git log` for every path, not one per path. That distinction is the
194
+ whole cost of this function: at 21 paths the per-path form measured 2762 ms
195
+ against 123 ms batched, because each invocation pays a fresh git startup and
196
+ `--follow` re-runs rename detection over the entire history. The per-path
197
+ form also grew linearly with the number of candidates, which is what put
198
+ `adr-discover`'s default path over ADR-015's ceiling.
199
+
200
+ What the batch gives up is `--follow`: a file that arrived under a different
201
+ name reports the rename rather than the original creation. That is a
202
+ real loss and a small one -- this signal is about the ORDER subsystems
203
+ appeared, and a rename does not reorder anything.
204
+ """
205
+ if not paths:
206
+ return []
207
+ # \x02 marks a commit header so the name-only lines that follow can be
208
+ # attributed to it. \x1f separates fields, as elsewhere in this module.
209
+ out = _git(
210
+ root,
211
+ ["log", "--diff-filter=A", "--date=short",
212
+ "--pretty=format:\x02%h\x1f%ad\x1f%s", "--name-only", "--", *paths],
213
+ )
214
+ if not out:
215
+ return []
216
+ wanted = set(paths)
217
+ first: Dict[str, Dict] = {}
218
+ current: List[str] | None = None
219
+ for line in out.splitlines():
220
+ if line.startswith("\x02"):
221
+ parts = line[1:].split("\x1f")
222
+ current = parts if len(parts) == 3 else None
223
+ continue
224
+ name = line.strip()
225
+ if not name or current is None or name not in wanted:
226
+ continue
227
+ # git walks newest-first, so a later hit is an older commit: the last
228
+ # one seen for a path is its first appearance.
229
+ first[name] = {
230
+ "path": name,
231
+ "commit": current[0],
232
+ "date": current[1],
233
+ "subject": current[2],
234
+ }
235
+ rows = list(first.values())
236
+ if not rows:
237
+ return []
238
+ rows.sort(key=lambda row: row["date"])
239
+ return [
240
+ {
241
+ "id": "history-first-appearance",
242
+ "title": (
243
+ "The order in which the project's tooling and dependencies "
244
+ "arrived, which is the closest thing to a timeline of its decisions."
245
+ ),
246
+ "decision_type": "history-signal",
247
+ "source": "history",
248
+ "evidence_files": [row["path"] for row in rows],
249
+ "details": {"arrivals": rows},
250
+ }
251
+ ]
252
+
253
+
254
+ def scan_history(
255
+ root: Path,
256
+ tracked_paths: Optional[List[str]] = None,
257
+ max_commits: int = DEFAULT_MAX_COMMITS,
258
+ ) -> Dict:
259
+ """Return {"candidates": [...], "available": bool, "reason": str|None}.
260
+
261
+ Never raises. A repository without git, without history, or with git
262
+ unavailable yields an empty candidate list and a reason -- a bootstrap scan
263
+ that refuses to run because the history is thin is worse than one that
264
+ scans what it can and says which half is missing.
265
+ """
266
+ if shutil.which("git") is None:
267
+ return {"candidates": [], "available": False, "reason": "git is not on PATH"}
268
+ if not is_git_repository(root):
269
+ return {"candidates": [], "available": False, "reason": "not a git repository"}
270
+ if not _commits(root, 1):
271
+ return {"candidates": [], "available": False, "reason": "no commits to read"}
272
+
273
+ candidates: List[Dict] = []
274
+ candidates.extend(scan_decision_subjects(root, max_commits))
275
+ candidates.extend(scan_churn(root, max_commits))
276
+ if tracked_paths:
277
+ candidates.extend(scan_first_appearance(root, tracked_paths))
278
+ return {"candidates": candidates, "available": True, "reason": None}