@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.
- package/.claude-plugin/plugin.json +29 -0
- package/LICENSE +21 -0
- package/README.md +850 -0
- package/bin/adr +1552 -0
- package/bin/adr-audit +454 -0
- package/bin/adr-context +584 -0
- package/bin/adr-discover +546 -0
- package/bin/adr-doctor +166 -0
- package/bin/adr-generate-scripts +421 -0
- package/bin/adr-grill-signal +131 -0
- package/bin/adr-guardian +1263 -0
- package/bin/adr-index +199 -0
- package/bin/adr-judge +2832 -0
- package/bin/adr-judge-precommit +87 -0
- package/bin/adr-lint +2087 -0
- package/bin/adr-mcp +1093 -0
- package/bin/adr-migrate +644 -0
- package/bin/adr-quality +275 -0
- package/bin/adr-readiness +211 -0
- package/bin/adr-readiness-ci +111 -0
- package/bin/adr-related +401 -0
- package/bin/adr-renumber +254 -0
- package/bin/adr-retire +467 -0
- package/bin/adr-settings +399 -0
- package/bin/adr-status +797 -0
- package/bin/adr-suggest +803 -0
- package/bin/adr-watch +674 -0
- package/bin/adr_catalog.py +536 -0
- package/bin/adr_config.py +280 -0
- package/bin/adr_doctor_checks.py +407 -0
- package/bin/adr_doctor_core.py +342 -0
- package/bin/adr_doctor_models.py +186 -0
- package/bin/adr_doctor_probes.py +216 -0
- package/bin/adr_format.py +786 -0
- package/bin/adr_grill_signal.py +123 -0
- package/bin/adr_guardian_queue.py +218 -0
- package/bin/adr_history_scan.py +278 -0
- package/bin/adr_index_core.py +443 -0
- package/bin/adr_llm.py +333 -0
- package/bin/adr_llm_judge_migration.py +314 -0
- package/bin/adr_quality_core.py +674 -0
- package/bin/adr_query.py +678 -0
- package/bin/adr_readiness.py +442 -0
- package/bin/adr_readiness_ci.py +123 -0
- package/bin/adr_regex.py +165 -0
- package/bin/adr_regex_worker.py +30 -0
- package/bin/adr_retrieval_health.py +385 -0
- package/bin/adr_schema.py +448 -0
- package/bin/adr_state.py +172 -0
- package/bin/bump-version +71 -0
- package/clients/workflows.json +229 -0
- package/hooks/__init__.py +1 -0
- package/hooks/adapters/__init__.py +13 -0
- package/hooks/adapters/claude.py +27 -0
- package/hooks/adapters/codex.py +26 -0
- package/hooks/adapters/copilot.py +11 -0
- package/hooks/adr-hook.py +128 -0
- package/hooks/adr_hook_core.py +843 -0
- package/hooks/adr_pr_guard.py +367 -0
- package/instructions/ADR-guide.md +48 -0
- package/instructions/adr.coding.md +82 -0
- package/instructions/adr.review.md +182 -0
- package/opencode/plugin.ts +451 -0
- package/package.json +41 -0
- package/schemas/adr-context-probes.schema.json +56 -0
- package/schemas/adr-enforcement.schema.json +57 -0
- package/schemas/adr-frontmatter.schema.json +144 -0
- package/schemas/adr-index.schema.json +276 -0
- package/schemas/adr-kit-config.schema.json +371 -0
- package/schemas/adr-readiness.schema.json +41 -0
- package/schemas/client-capabilities.schema.json +503 -0
- package/schemas/client-certification.schema.json +101 -0
- package/schemas/doctor-output.schema.json +92 -0
- package/schemas/marketplace.json.schema.json +70 -0
- package/schemas/plugin.json.schema.json +67 -0
- package/scripts/adr_settings.py +239 -0
- package/scripts/benchmark-adr-grilling.py +323 -0
- package/scripts/benchmark-client-generation.py +178 -0
- package/scripts/build-client-adapters.py +139 -0
- package/scripts/bump-version.py +304 -0
- package/scripts/check-branch-sync.py +243 -0
- package/scripts/check-release-version.py +81 -0
- package/scripts/client_certification.py +153 -0
- package/scripts/client_evidence.py +280 -0
- package/scripts/client_generation.py +288 -0
- package/scripts/client_generation_artifacts.py +351 -0
- package/scripts/client_generation_model.py +173 -0
- package/scripts/client_generation_state.py +260 -0
- package/scripts/client_support_matrix.py +360 -0
- package/scripts/install-agent-envs.py +300 -0
- package/scripts/probe-client-events.py +183 -0
- package/scripts/project_setup.py +379 -0
- package/scripts/refresh-otgw-corpus.py +219 -0
- package/scripts/settings.py +81 -0
- package/scripts/setup-project.py +205 -0
- package/scripts/sync-agent-plugins.py +17 -0
- package/scripts/version_sites.py +377 -0
- package/skills/adr/SKILL.md +780 -0
- package/skills/audit/SKILL.md +103 -0
- package/skills/context/SKILL.md +77 -0
- package/skills/grill/SKILL.md +84 -0
- package/skills/grill/agents/openai.yaml +4 -0
- package/skills/guardian/SKILL.md +316 -0
- package/skills/init/SKILL.md +499 -0
- package/skills/install-hooks/SKILL.md +154 -0
- package/skills/judge/SKILL.md +168 -0
- package/skills/lint/SKILL.md +321 -0
- package/skills/migrate/SKILL.md +313 -0
- package/skills/related/SKILL.md +62 -0
- package/skills/retire/SKILL.md +41 -0
- package/skills/review/SKILL.md +167 -0
- package/skills/settings/SKILL.md +73 -0
- package/skills/setup/SKILL.md +128 -0
- package/skills/supersede/SKILL.md +136 -0
- package/skills/upgrade/SKILL.md +273 -0
- package/templates/adr-kit-guide.md +354 -0
- package/templates/adr-template.canonical.md +115 -0
- package/templates/adr-template.madr.md +131 -0
- package/templates/adr-template.md +131 -0
- package/templates/adr-template.nygard.md +111 -0
- package/templates/cc-settings/guardian-hook-entry.json +9 -0
- package/templates/githooks/pre-commit +337 -0
- package/templates/github-workflows/adr-audit.yml +58 -0
- package/templates/github-workflows/adr-guardian-audit.yml +133 -0
- package/templates/github-workflows/adr-index-check.yml +30 -0
- package/templates/github-workflows/adr-judge.yml +31 -0
- package/templates/github-workflows/adr-readiness.yml +18 -0
- package/templates/validate_adr_template.py +38 -0
- package/templates/validate_adr_template.sh +74 -0
package/bin/adr-guardian
ADDED
|
@@ -0,0 +1,1263 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""adr-guardian: periodic ADR-set health detector for adr-kit (v0.18.0+).
|
|
3
|
+
|
|
4
|
+
Three subcommands:
|
|
5
|
+
|
|
6
|
+
adr-guardian check
|
|
7
|
+
The SessionStart hook entry point. Reads docs/adr/.adr-kit-state.json and
|
|
8
|
+
docs/adr/.adr-kit.json, computes which health tiers are due, and prints the
|
|
9
|
+
[adr-guardian] block as JSON additionalContext for Claude Code's SessionStart
|
|
10
|
+
hook. ALWAYS exits 0. NEVER runs an LLM. NEVER spawns subprocesses.
|
|
11
|
+
Prints nothing when no tier is due or when the guardian is disabled.
|
|
12
|
+
|
|
13
|
+
adr-guardian stamp <cheap|llm> [--violations N] [--retire N] [--suggest N] [--audit N] [--lint STR] [--coverage PCT]
|
|
14
|
+
Record that a sweep tier completed. Updates .adr-kit-state.json and appends
|
|
15
|
+
an entry to the append-only trend list (capped at 52 entries). Called by
|
|
16
|
+
the /adr-kit:guardian skill after a sweep completes.
|
|
17
|
+
|
|
18
|
+
adr-guardian stamp llm --adr ADR-NNN --verdict <ok|violation>
|
|
19
|
+
Record ONE ADR's verdict mid-sweep (ADR-037). Does not touch the tier
|
|
20
|
+
timestamp or the trend; an interrupted sweep keeps every verdict it
|
|
21
|
+
reached, and a recorded violation keeps the llm tier due until a
|
|
22
|
+
re-judge stamps that ADR ok. Only real verdicts stamp: a timeout or
|
|
23
|
+
error is not a verdict.
|
|
24
|
+
|
|
25
|
+
adr-guardian state
|
|
26
|
+
Print the current .adr-kit-state.json as formatted JSON to stdout. Exits 0
|
|
27
|
+
even when the file is missing (prints a default-empty state).
|
|
28
|
+
|
|
29
|
+
Design invariants (match spec §3 / §12):
|
|
30
|
+
- check: pure read-only on ADRs (just counts files); never spawns; always exit 0.
|
|
31
|
+
- stamp: writes only .adr-kit-state.json; exit 0 on valid input
|
|
32
|
+
(invalid flag combinations are refused with exit 2, same as argparse).
|
|
33
|
+
- cwd-guard: check exits 0 silently when cwd has no docs/adr/ with ADRs.
|
|
34
|
+
- nudge_cooldown_hours: check skips output if last_nudged is within the window.
|
|
35
|
+
|
|
36
|
+
Multi-session safety (task-9):
|
|
37
|
+
- .adr-kit-state.json is per-machine ADVISORY data, not a ledger. Concurrent
|
|
38
|
+
sessions may stamp at the same time; a cross-process lock serializes each
|
|
39
|
+
complete read-modify-write transaction so unrelated updates are preserved.
|
|
40
|
+
- Writes are atomic: state is written to a unique temp file in the same
|
|
41
|
+
directory, then moved into place with os.replace (atomic on both POSIX and
|
|
42
|
+
NTFS). A reader can never observe a partial file.
|
|
43
|
+
- Corrupt or partial state files are tolerated on read: they are treated as
|
|
44
|
+
empty state, one warning line goes to stderr, and the next stamp overwrites
|
|
45
|
+
the file with valid JSON. The guardian never crashes on a bad state file.
|
|
46
|
+
- Blocking advisory locking uses fcntl on POSIX and msvcrt on Windows.
|
|
47
|
+
Failure to acquire the lock skips the advisory update instead of writing
|
|
48
|
+
unlocked and risking lost state.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
import argparse
|
|
54
|
+
import importlib.machinery
|
|
55
|
+
import importlib.util
|
|
56
|
+
import json
|
|
57
|
+
import os
|
|
58
|
+
import re
|
|
59
|
+
import subprocess
|
|
60
|
+
import sys
|
|
61
|
+
from datetime import datetime, timezone
|
|
62
|
+
from pathlib import Path
|
|
63
|
+
import io
|
|
64
|
+
from typing import Dict, List, Optional, Tuple
|
|
65
|
+
|
|
66
|
+
_BIN_DIR = Path(__file__).resolve().parent
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _load_sibling(name: str):
|
|
70
|
+
"""Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
|
|
71
|
+
|
|
72
|
+
SEC-HIGH (TASK-62): `sys.path.insert(0, _BIN_DIR)` put this directory ahead
|
|
73
|
+
of the standard library for every import, so a module committed next to
|
|
74
|
+
this script executed as code -- and it re-added the very directory
|
|
75
|
+
CPython's -P / PYTHONSAFEPATH removes. Siblings are registered in
|
|
76
|
+
sys.modules under their bare name, so the plain `from adr_* import ...`
|
|
77
|
+
statements below (and the lazy ones inside functions) resolve from the
|
|
78
|
+
cache instead of the path. bin/adr-judge carries the full rationale.
|
|
79
|
+
"""
|
|
80
|
+
cached = sys.modules.get(name)
|
|
81
|
+
if cached is not None:
|
|
82
|
+
return cached
|
|
83
|
+
loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
|
|
84
|
+
spec = importlib.util.spec_from_loader(name, loader)
|
|
85
|
+
module = importlib.util.module_from_spec(spec)
|
|
86
|
+
sys.modules[name] = module
|
|
87
|
+
loader.exec_module(module)
|
|
88
|
+
return module
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# Dependency order: adr_catalog needs adr_format + adr_schema; adr_query
|
|
92
|
+
# lazily needs adr_catalog; adr_retrieval_health needs adr_query. The
|
|
93
|
+
# remaining three are standalone.
|
|
94
|
+
_load_sibling("adr_format")
|
|
95
|
+
_load_sibling("adr_schema")
|
|
96
|
+
_load_sibling("adr_catalog")
|
|
97
|
+
_load_sibling("adr_query")
|
|
98
|
+
_load_sibling("adr_retrieval_health")
|
|
99
|
+
_load_sibling("adr_config")
|
|
100
|
+
_load_sibling("adr_state")
|
|
101
|
+
_load_sibling("adr_guardian_queue")
|
|
102
|
+
|
|
103
|
+
from adr_config import load_json_config as _load_config
|
|
104
|
+
from adr_state import find_project_adr_dir as _find_adr_dir
|
|
105
|
+
from adr_state import load_state, update_state
|
|
106
|
+
from adr_guardian_queue import (
|
|
107
|
+
QUEUE_CACHE_NAME,
|
|
108
|
+
build_queue_cache,
|
|
109
|
+
write_queue_cache,
|
|
110
|
+
)
|
|
111
|
+
from adr_catalog import adr_id_from_filename, normalize_adr_id
|
|
112
|
+
from adr_retrieval_health import render_retrieval_health, run_retrieval_health
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ---------------------------------------------------------------------------
|
|
116
|
+
# UTF-8 stream setup (mirrors adr-suggest._ensure_utf8_streams)
|
|
117
|
+
# ---------------------------------------------------------------------------
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _ensure_utf8_streams() -> None:
|
|
121
|
+
"""Force stdout/stderr to UTF-8 on Windows where the console may default to cp1252."""
|
|
122
|
+
for stream in (sys.stdout, sys.stderr):
|
|
123
|
+
if hasattr(stream, "reconfigure"):
|
|
124
|
+
try:
|
|
125
|
+
stream.reconfigure(encoding="utf-8")
|
|
126
|
+
except (AttributeError, io.UnsupportedOperation):
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# ---------------------------------------------------------------------------
|
|
131
|
+
# State-file helpers
|
|
132
|
+
# ---------------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
DEFAULT_STATE: Dict = {
|
|
135
|
+
"cheap_tier": {
|
|
136
|
+
"last_run": None,
|
|
137
|
+
"drift_violations": 0,
|
|
138
|
+
"retire_candidates": 0,
|
|
139
|
+
"lint": "0F/0A",
|
|
140
|
+
},
|
|
141
|
+
"llm_tier": {
|
|
142
|
+
"last_run": None,
|
|
143
|
+
"suggest_hits": 0,
|
|
144
|
+
"audit_findings": 0,
|
|
145
|
+
# Per-ADR verdicts (ADR-037): {"ADR-NNN": {"last_run": iso, "verdict":
|
|
146
|
+
# "ok"|"violation"}}. Advisory and per-machine like the rest of this
|
|
147
|
+
# file; lets an interrupted sweep keep what it established and lets a
|
|
148
|
+
# recorded violation hold the tier open until a re-judge clears it.
|
|
149
|
+
"adrs": {},
|
|
150
|
+
},
|
|
151
|
+
"retire_seen": [],
|
|
152
|
+
"last_nudged": None,
|
|
153
|
+
"trend": [],
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
# Maximum number of entries kept in the append-only trend list (oldest dropped).
|
|
157
|
+
TREND_MAX_ENTRIES = 52
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _load_state(state_path: Path) -> Dict:
|
|
161
|
+
"""Read .adr-kit-state.json. Returns DEFAULT_STATE when missing or invalid.
|
|
162
|
+
|
|
163
|
+
A corrupt or partial file is tolerated: it is treated as empty state and a
|
|
164
|
+
single warning line is written to stderr. The file itself is left in place;
|
|
165
|
+
the next stamp overwrites it with valid JSON (last-writer-wins).
|
|
166
|
+
"""
|
|
167
|
+
return load_state(
|
|
168
|
+
state_path,
|
|
169
|
+
lambda: json.loads(json.dumps(DEFAULT_STATE)),
|
|
170
|
+
lambda message: sys.stderr.write(f"[adr-guardian] warning: {message}\n"),
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _update_state(state_path: Path, mutation):
|
|
175
|
+
return update_state(
|
|
176
|
+
state_path,
|
|
177
|
+
lambda: json.loads(json.dumps(DEFAULT_STATE)),
|
|
178
|
+
mutation,
|
|
179
|
+
lambda message: sys.stderr.write(f"[adr-guardian] warning: {message}\n"),
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _guardian_config(cfg: Dict) -> Dict:
|
|
184
|
+
"""Return the guardian sub-block with defaults filled in."""
|
|
185
|
+
defaults = {
|
|
186
|
+
"enabled": True,
|
|
187
|
+
"drift_stale_days": 1,
|
|
188
|
+
"llm_stale_days": 14,
|
|
189
|
+
"nudge_cooldown_hours": 24,
|
|
190
|
+
"llm_autorun": False,
|
|
191
|
+
}
|
|
192
|
+
guardian = cfg.get("guardian") or {}
|
|
193
|
+
merged = {**defaults, **guardian}
|
|
194
|
+
return merged
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# ---------------------------------------------------------------------------
|
|
198
|
+
# Time helpers
|
|
199
|
+
# ---------------------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
def _now_utc() -> datetime:
|
|
202
|
+
return datetime.now(tz=timezone.utc)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _parse_iso(s: Optional[str]) -> Optional[datetime]:
|
|
206
|
+
"""Parse an ISO-8601 timestamp string, returning None on failure."""
|
|
207
|
+
if not s:
|
|
208
|
+
return None
|
|
209
|
+
try:
|
|
210
|
+
# Python 3.11+ handles Z; for 3.9/3.10 replace Z with +00:00
|
|
211
|
+
s_clean = s.replace("Z", "+00:00")
|
|
212
|
+
return datetime.fromisoformat(s_clean)
|
|
213
|
+
except (ValueError, AttributeError):
|
|
214
|
+
return None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _hours_since(ts: Optional[datetime]) -> Optional[float]:
|
|
218
|
+
"""Return hours elapsed since ts (UTC), or None when ts is None."""
|
|
219
|
+
if ts is None:
|
|
220
|
+
return None
|
|
221
|
+
delta = _now_utc() - ts
|
|
222
|
+
return delta.total_seconds() / 3600.0
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _days_since(ts: Optional[datetime]) -> Optional[float]:
|
|
226
|
+
"""Return days elapsed since ts (UTC), or None when ts is None."""
|
|
227
|
+
if ts is None:
|
|
228
|
+
return None
|
|
229
|
+
delta = _now_utc() - ts
|
|
230
|
+
return delta.total_seconds() / 86400.0
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# ---------------------------------------------------------------------------
|
|
234
|
+
# CWD guard
|
|
235
|
+
# ---------------------------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
def _count_adrs(adr_dir: Path) -> int:
|
|
238
|
+
"""Count ADR-*.md files in adr_dir."""
|
|
239
|
+
try:
|
|
240
|
+
return sum(1 for _ in adr_dir.glob("ADR-*.md"))
|
|
241
|
+
except OSError:
|
|
242
|
+
return 0
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# ---------------------------------------------------------------------------
|
|
246
|
+
# Copied-artifact staleness (task-15, v0.27.0+)
|
|
247
|
+
#
|
|
248
|
+
# Plugin-level hooks refresh automatically on plugin update, but artifacts
|
|
249
|
+
# COPIED into a project freeze at install time: the git pre-commit wrapper
|
|
250
|
+
# and the project-scoped guardian hook entry in .claude/settings.json. Their
|
|
251
|
+
# engines self-upgrade (they resolve the newest plugin cache version per
|
|
252
|
+
# run), but the wrapper's own feature surface lags until refreshed. The
|
|
253
|
+
# checks below are pure file reads (no subprocesses, per the check
|
|
254
|
+
# invariant) and compare embedded version stamps against this plugin's own
|
|
255
|
+
# version.
|
|
256
|
+
#
|
|
257
|
+
# Staleness rules (no false positives when up to date, AC#3):
|
|
258
|
+
# - git wrapper stamped older than the plugin -> stale
|
|
259
|
+
# - git wrapper clearly adr-kit's but unstamped -> stale (pre-0.27)
|
|
260
|
+
# - non-adr-kit pre-commit hook -> ignored
|
|
261
|
+
# - settings entry stamped older than the plugin -> stale
|
|
262
|
+
# - settings entry without a stamp -> ignored (it only
|
|
263
|
+
# re-resolves engines; entry-shape changes are rare and nagging every
|
|
264
|
+
# pre-0.27 install from a settings snapshot would be noise)
|
|
265
|
+
# ---------------------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
_WRAPPER_STAMP_RE = re.compile(r'^ADR_KIT_WRAPPER_VERSION="([0-9]+\.[0-9]+\.[0-9]+)"', re.MULTILINE)
|
|
268
|
+
_ARTIFACT_READ_CAP = 64 * 1024 # wrappers are a few KB; cap defends against odd files
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _own_version() -> Optional[str]:
|
|
272
|
+
"""Version of the native client plugin this script ships with.
|
|
273
|
+
|
|
274
|
+
The hook resolvers always execute the newest installed adr-guardian, so
|
|
275
|
+
this is the newest installed plugin version by construction.
|
|
276
|
+
"""
|
|
277
|
+
root = Path(__file__).resolve().parent.parent
|
|
278
|
+
for manifest in (
|
|
279
|
+
root / ".claude-plugin" / "plugin.json",
|
|
280
|
+
root / ".codex-plugin" / "plugin.json",
|
|
281
|
+
root / "plugin.json",
|
|
282
|
+
):
|
|
283
|
+
try:
|
|
284
|
+
data = json.loads(manifest.read_text(encoding="utf-8"))
|
|
285
|
+
version = data.get("version")
|
|
286
|
+
if isinstance(version, str):
|
|
287
|
+
return version
|
|
288
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
289
|
+
continue
|
|
290
|
+
return None
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _parse_semver(s: Optional[str]) -> Optional[Tuple[int, int, int]]:
|
|
294
|
+
"""Parse 'X.Y.Z' into an int tuple; None for anything else."""
|
|
295
|
+
if not s:
|
|
296
|
+
return None
|
|
297
|
+
m = re.fullmatch(r"([0-9]+)\.([0-9]+)\.([0-9]+)", s.strip())
|
|
298
|
+
if not m:
|
|
299
|
+
return None
|
|
300
|
+
return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _read_capped(path: Path) -> Optional[str]:
|
|
304
|
+
try:
|
|
305
|
+
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
306
|
+
return fh.read(_ARTIFACT_READ_CAP)
|
|
307
|
+
except OSError:
|
|
308
|
+
return None
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _check_git_wrapper(path: Path, plugin_semver: Tuple[int, int, int]) -> Optional[Dict]:
|
|
312
|
+
"""Inspect one candidate pre-commit file. None when absent or not ours."""
|
|
313
|
+
content = _read_capped(path)
|
|
314
|
+
if content is None:
|
|
315
|
+
return None
|
|
316
|
+
if "adr-kit" not in content and "adr-judge" not in content:
|
|
317
|
+
return None # someone else's hook; never report it
|
|
318
|
+
m = _WRAPPER_STAMP_RE.search(content)
|
|
319
|
+
version = m.group(1) if m else None
|
|
320
|
+
wrapper_semver = _parse_semver(version)
|
|
321
|
+
stale = wrapper_semver is None or wrapper_semver < plugin_semver
|
|
322
|
+
return {
|
|
323
|
+
"kind": "git-pre-commit-wrapper",
|
|
324
|
+
"path": str(path),
|
|
325
|
+
"version": version,
|
|
326
|
+
"stale": stale,
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _check_settings_entry(path: Path, plugin_semver: Tuple[int, int, int]) -> Optional[Dict]:
|
|
331
|
+
"""Inspect .claude/settings.json for a stamped guardian hook entry."""
|
|
332
|
+
content = _read_capped(path)
|
|
333
|
+
if content is None or "adr-guardian" not in content:
|
|
334
|
+
return None
|
|
335
|
+
try:
|
|
336
|
+
data = json.loads(content)
|
|
337
|
+
except json.JSONDecodeError:
|
|
338
|
+
return None
|
|
339
|
+
|
|
340
|
+
def _walk(node) -> Optional[str]:
|
|
341
|
+
if isinstance(node, dict):
|
|
342
|
+
cmd = node.get("command")
|
|
343
|
+
if isinstance(cmd, str) and "adr-guardian" in cmd:
|
|
344
|
+
wv = node.get("_wrapper_version")
|
|
345
|
+
return wv if isinstance(wv, str) else ""
|
|
346
|
+
for value in node.values():
|
|
347
|
+
found = _walk(value)
|
|
348
|
+
if found is not None:
|
|
349
|
+
return found
|
|
350
|
+
elif isinstance(node, list):
|
|
351
|
+
for item in node:
|
|
352
|
+
found = _walk(item)
|
|
353
|
+
if found is not None:
|
|
354
|
+
return found
|
|
355
|
+
return None
|
|
356
|
+
|
|
357
|
+
stamp = _walk(data)
|
|
358
|
+
if stamp is None:
|
|
359
|
+
return None # no guardian entry in this settings file
|
|
360
|
+
if stamp == "":
|
|
361
|
+
# Unstamped entry: pre-0.27 snapshot, but it self-resolves engines.
|
|
362
|
+
# Reported as present, never as stale (AC#3: no noise).
|
|
363
|
+
return {
|
|
364
|
+
"kind": "settings-guardian-entry",
|
|
365
|
+
"path": str(path),
|
|
366
|
+
"version": None,
|
|
367
|
+
"stale": False,
|
|
368
|
+
}
|
|
369
|
+
entry_semver = _parse_semver(stamp)
|
|
370
|
+
stale = entry_semver is None or entry_semver < plugin_semver
|
|
371
|
+
return {
|
|
372
|
+
"kind": "settings-guardian-entry",
|
|
373
|
+
"path": str(path),
|
|
374
|
+
"version": stamp,
|
|
375
|
+
"stale": stale,
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _artifact_report(project_root: Path) -> Dict:
|
|
380
|
+
"""Compare copied artifacts in project_root against the plugin version."""
|
|
381
|
+
plugin_version = _own_version()
|
|
382
|
+
plugin_semver = _parse_semver(plugin_version)
|
|
383
|
+
report: Dict = {"plugin_version": plugin_version, "artifacts": []}
|
|
384
|
+
if plugin_semver is None:
|
|
385
|
+
return report # cannot judge staleness without our own version
|
|
386
|
+
for candidate in (
|
|
387
|
+
project_root / ".githooks" / "pre-commit",
|
|
388
|
+
project_root / ".git" / "hooks" / "pre-commit",
|
|
389
|
+
):
|
|
390
|
+
found = _check_git_wrapper(candidate, plugin_semver)
|
|
391
|
+
if found is not None:
|
|
392
|
+
report["artifacts"].append(found)
|
|
393
|
+
settings = _check_settings_entry(project_root / ".claude" / "settings.json", plugin_semver)
|
|
394
|
+
if settings is not None:
|
|
395
|
+
report["artifacts"].append(settings)
|
|
396
|
+
return report
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _stale_artifact_lines(report: Dict) -> List[str]:
|
|
400
|
+
"""Nudge lines for stale artifacts; empty list when everything is fresh."""
|
|
401
|
+
lines: List[str] = []
|
|
402
|
+
plugin_version = report.get("plugin_version") or "?"
|
|
403
|
+
for art in report.get("artifacts", []):
|
|
404
|
+
if not art.get("stale"):
|
|
405
|
+
continue
|
|
406
|
+
version_label = art.get("version") or "pre-0.27 (unstamped)"
|
|
407
|
+
rel = art.get("path", "")
|
|
408
|
+
lines.append(
|
|
409
|
+
f" • wrapper: {rel} is {version_label}, plugin is {plugin_version}"
|
|
410
|
+
" STALE → /adr-kit:upgrade"
|
|
411
|
+
)
|
|
412
|
+
return lines
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _refresh_queue_if_stale(adr_dir: Path, project_root: Path) -> None:
|
|
416
|
+
"""Rebuild the Proposed work queue when its cache is missing or expired.
|
|
417
|
+
|
|
418
|
+
The SessionStart grill nudge reads `docs/adr/.adr-kit-readiness.json`, which
|
|
419
|
+
was written only by `adr-guardian refresh-readiness` -- a command invoked by
|
|
420
|
+
nothing but a sentence in the guardian skill. The cache is gitignored with a
|
|
421
|
+
24 h TTL, so on a fresh clone the nudge stayed silent until some model
|
|
422
|
+
happened to run the sweep and think to run that step. A guarantee that
|
|
423
|
+
depends on a model reading prose is not a guarantee.
|
|
424
|
+
|
|
425
|
+
This makes it a mechanism. It runs in-process rather than spawning, because
|
|
426
|
+
`check` may not spawn: `build_readiness_report` is pure Python over the ADR
|
|
427
|
+
files, and it is skipped entirely while a valid cache exists, so the common
|
|
428
|
+
case costs one `stat`.
|
|
429
|
+
|
|
430
|
+
Fails open in every direction. This is a convenience for a nudge; a session
|
|
431
|
+
must never fail to start because a queue could not be computed.
|
|
432
|
+
"""
|
|
433
|
+
cache_path = adr_dir / QUEUE_CACHE_NAME
|
|
434
|
+
now = _now_utc()
|
|
435
|
+
try:
|
|
436
|
+
if cache_path.is_file():
|
|
437
|
+
payload = json.loads(cache_path.read_text(encoding="utf-8"))
|
|
438
|
+
expires_at = datetime.fromisoformat(str(payload["expires_at"]))
|
|
439
|
+
if expires_at.tzinfo is None:
|
|
440
|
+
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
|
441
|
+
if expires_at > now:
|
|
442
|
+
return
|
|
443
|
+
except (OSError, ValueError, KeyError, json.JSONDecodeError):
|
|
444
|
+
pass # unreadable is the same as absent: rebuild it
|
|
445
|
+
|
|
446
|
+
try:
|
|
447
|
+
_load_sibling("adr_format")
|
|
448
|
+
_load_sibling("adr_schema")
|
|
449
|
+
_load_sibling("adr_catalog")
|
|
450
|
+
_load_sibling("adr_quality_core")
|
|
451
|
+
readiness = _load_sibling("adr_readiness")
|
|
452
|
+
report = readiness.build_readiness_report(
|
|
453
|
+
adr_dir, evaluated_on=now.date(), all_proposed=True
|
|
454
|
+
)
|
|
455
|
+
write_queue_cache(cache_path, build_queue_cache(report, generated_at=now))
|
|
456
|
+
except Exception:
|
|
457
|
+
return
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _stale_index_lines(adr_dir: Path) -> List[str]:
|
|
461
|
+
"""Nudge lines when the generated indexes no longer match the ADRs.
|
|
462
|
+
|
|
463
|
+
The lifecycle CLI regenerates all three artefacts inside its own
|
|
464
|
+
transaction, so anything written through `bin/adr` keeps them true. An ADR
|
|
465
|
+
edited by hand -- or written straight to disk by a model with a Write tool,
|
|
466
|
+
which is the common case in a coding harness -- leaves them stale with
|
|
467
|
+
nothing to say so until CI notices. This is the cheapest place to notice.
|
|
468
|
+
|
|
469
|
+
In-process by contract: `check` never spawns. The mtime precondition is a
|
|
470
|
+
fast skip, not proof; a hand-edited index is newer than every ADR and still
|
|
471
|
+
wrong, so when the timestamps look fresh this stays silent and the real
|
|
472
|
+
check (`adr-index --check`, run by the sweep, the commit hook and CI) is
|
|
473
|
+
what certifies. Any failure to read is silence, never a false alarm.
|
|
474
|
+
"""
|
|
475
|
+
try:
|
|
476
|
+
core = _load_sibling("adr_index_core")
|
|
477
|
+
# A project with none of the three artefacts never generated an index
|
|
478
|
+
# and is not asking to be nagged into starting. One present means the
|
|
479
|
+
# project keeps an index, and then all three have to stay true.
|
|
480
|
+
if not any((adr_dir / name).exists() for name in core.INDEX_ARTIFACTS):
|
|
481
|
+
return []
|
|
482
|
+
if core.index_probably_fresh(adr_dir):
|
|
483
|
+
return []
|
|
484
|
+
stale = core.stale_index_artifacts(adr_dir)
|
|
485
|
+
except Exception:
|
|
486
|
+
return []
|
|
487
|
+
if not stale:
|
|
488
|
+
return []
|
|
489
|
+
return [
|
|
490
|
+
f" • index: {', '.join(stale)} no longer matches the ADRs"
|
|
491
|
+
" STALE → bin/adr-index docs/adr"
|
|
492
|
+
]
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
# ---------------------------------------------------------------------------
|
|
496
|
+
# Due-tier computation
|
|
497
|
+
# ---------------------------------------------------------------------------
|
|
498
|
+
|
|
499
|
+
def _compute_due_tiers(
|
|
500
|
+
state: Dict,
|
|
501
|
+
gcfg: Dict,
|
|
502
|
+
now: datetime,
|
|
503
|
+
) -> Tuple[bool, bool]:
|
|
504
|
+
"""Return (cheap_due, llm_due) booleans.
|
|
505
|
+
|
|
506
|
+
cheap_due: True when cheap-tier has never run OR last_run > drift_stale_days ago.
|
|
507
|
+
llm_due: True when llm-tier has never run OR last_run > llm_stale_days ago.
|
|
508
|
+
"""
|
|
509
|
+
cheap_tier = state.get("cheap_tier") or {}
|
|
510
|
+
llm_tier = state.get("llm_tier") or {}
|
|
511
|
+
|
|
512
|
+
drift_stale_days = float(gcfg.get("drift_stale_days", 1))
|
|
513
|
+
llm_stale_days = float(gcfg.get("llm_stale_days", 14))
|
|
514
|
+
|
|
515
|
+
cheap_last_run = _parse_iso(cheap_tier.get("last_run"))
|
|
516
|
+
llm_last_run = _parse_iso(llm_tier.get("last_run"))
|
|
517
|
+
|
|
518
|
+
cheap_days = _days_since(cheap_last_run)
|
|
519
|
+
llm_days = _days_since(llm_last_run)
|
|
520
|
+
|
|
521
|
+
cheap_due = cheap_days is None or cheap_days >= drift_stale_days
|
|
522
|
+
llm_due = llm_days is None or llm_days >= llm_stale_days
|
|
523
|
+
|
|
524
|
+
# ADR-037: a recorded per-ADR violation keeps the llm tier due regardless
|
|
525
|
+
# of how fresh the tier timestamp is. The tier goes quiet only when a
|
|
526
|
+
# re-judge overwrites the entry with "ok".
|
|
527
|
+
if not llm_due and _outstanding_violations(llm_tier):
|
|
528
|
+
llm_due = True
|
|
529
|
+
|
|
530
|
+
return cheap_due, llm_due
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _outstanding_violations(llm_tier: Dict) -> List[str]:
|
|
534
|
+
"""ADR ids whose recorded per-ADR verdict is "violation" (ADR-037)."""
|
|
535
|
+
adrs = llm_tier.get("adrs")
|
|
536
|
+
if not isinstance(adrs, dict):
|
|
537
|
+
return []
|
|
538
|
+
return sorted(
|
|
539
|
+
adr_id
|
|
540
|
+
for adr_id, entry in adrs.items()
|
|
541
|
+
if isinstance(entry, dict) and entry.get("verdict") == "violation"
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _is_throttled(state: Dict, gcfg: Dict) -> bool:
|
|
546
|
+
"""Return True if we nudged within nudge_cooldown_hours."""
|
|
547
|
+
cooldown_h = float(gcfg.get("nudge_cooldown_hours", 24))
|
|
548
|
+
last_nudged = _parse_iso(state.get("last_nudged"))
|
|
549
|
+
h = _hours_since(last_nudged)
|
|
550
|
+
if h is None:
|
|
551
|
+
return False
|
|
552
|
+
return h < cooldown_h
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
# ---------------------------------------------------------------------------
|
|
556
|
+
# Trend history helpers
|
|
557
|
+
# ---------------------------------------------------------------------------
|
|
558
|
+
|
|
559
|
+
def _trend_list(state: Dict) -> List:
|
|
560
|
+
"""Return state['trend'] as a list, tolerating corrupt or missing values."""
|
|
561
|
+
trend = state.get("trend")
|
|
562
|
+
if not isinstance(trend, list):
|
|
563
|
+
return []
|
|
564
|
+
return trend
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _is_number(v) -> bool:
|
|
568
|
+
"""True for int/float metric values (bool excluded)."""
|
|
569
|
+
return isinstance(v, (int, float)) and not isinstance(v, bool)
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def _fmt_pct(v) -> str:
|
|
573
|
+
"""Format a coverage percent compactly: 40.0 -> '40%', 45.5 -> '45.5%'."""
|
|
574
|
+
return f"{v:g}%"
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def _format_trend_delta(state: Dict) -> Optional[str]:
|
|
578
|
+
"""One-line delta vs the previous sweep, or None when not enough trend data.
|
|
579
|
+
|
|
580
|
+
Example: 'trend: drift 2 -> 0, retire 1 -> 2, coverage 40% -> 45%'
|
|
581
|
+
Requires at least two well-formed trend entries; corrupt entries are skipped.
|
|
582
|
+
"""
|
|
583
|
+
trend = _trend_list(state)
|
|
584
|
+
if len(trend) < 2:
|
|
585
|
+
return None
|
|
586
|
+
prev, last = trend[-2], trend[-1]
|
|
587
|
+
if not isinstance(prev, dict) or not isinstance(last, dict):
|
|
588
|
+
return None
|
|
589
|
+
|
|
590
|
+
parts: List[str] = []
|
|
591
|
+
for label, key in (
|
|
592
|
+
("drift", "drift_violations"),
|
|
593
|
+
("retire", "retire_candidates"),
|
|
594
|
+
("suggest", "suggest_hits"),
|
|
595
|
+
("audit", "audit_findings"),
|
|
596
|
+
):
|
|
597
|
+
a, b = prev.get(key), last.get(key)
|
|
598
|
+
if _is_number(a) and _is_number(b):
|
|
599
|
+
parts.append(f"{label} {a} -> {b}")
|
|
600
|
+
a, b = prev.get("coverage_percent"), last.get("coverage_percent")
|
|
601
|
+
if _is_number(a) and _is_number(b):
|
|
602
|
+
parts.append(f"coverage {_fmt_pct(a)} -> {_fmt_pct(b)}")
|
|
603
|
+
|
|
604
|
+
if not parts:
|
|
605
|
+
return None
|
|
606
|
+
return "trend: " + ", ".join(parts)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def _append_trend_entry(
|
|
610
|
+
state: Dict,
|
|
611
|
+
tier: str,
|
|
612
|
+
now_iso: str,
|
|
613
|
+
total_adrs: Optional[int],
|
|
614
|
+
coverage: Optional[float],
|
|
615
|
+
) -> None:
|
|
616
|
+
"""Append a sweep entry to the append-only trend list (capped at 52).
|
|
617
|
+
|
|
618
|
+
Fields for the tier that did not run are carried from the last known
|
|
619
|
+
tier-state values; coverage and total_adrs carry from the previous trend
|
|
620
|
+
entry when not freshly supplied. Corrupt trend values are reset to [].
|
|
621
|
+
"""
|
|
622
|
+
trend = _trend_list(state)
|
|
623
|
+
prev = trend[-1] if trend and isinstance(trend[-1], dict) else {}
|
|
624
|
+
|
|
625
|
+
cheap = state.get("cheap_tier") or {}
|
|
626
|
+
llm = state.get("llm_tier") or {}
|
|
627
|
+
|
|
628
|
+
if total_adrs is None:
|
|
629
|
+
total_adrs = prev.get("total_adrs")
|
|
630
|
+
if coverage is None:
|
|
631
|
+
coverage = prev.get("coverage_percent")
|
|
632
|
+
|
|
633
|
+
entry = {
|
|
634
|
+
"date": now_iso,
|
|
635
|
+
"tier": tier,
|
|
636
|
+
"total_adrs": total_adrs,
|
|
637
|
+
"drift_violations": cheap.get("drift_violations"),
|
|
638
|
+
"retire_candidates": cheap.get("retire_candidates"),
|
|
639
|
+
"suggest_hits": llm.get("suggest_hits"),
|
|
640
|
+
"audit_findings": llm.get("audit_findings"),
|
|
641
|
+
"coverage_percent": coverage,
|
|
642
|
+
}
|
|
643
|
+
trend.append(entry)
|
|
644
|
+
state["trend"] = trend[-TREND_MAX_ENTRIES:]
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
# ---------------------------------------------------------------------------
|
|
648
|
+
# Block formatting (spec §9)
|
|
649
|
+
# ---------------------------------------------------------------------------
|
|
650
|
+
|
|
651
|
+
def _format_guardian_block(
|
|
652
|
+
cheap_due: bool,
|
|
653
|
+
llm_due: bool,
|
|
654
|
+
state: Dict,
|
|
655
|
+
adr_count: int,
|
|
656
|
+
now: datetime,
|
|
657
|
+
) -> str:
|
|
658
|
+
"""Return the [adr-guardian] block as a plain string.
|
|
659
|
+
|
|
660
|
+
Format:
|
|
661
|
+
[adr-guardian] ADR health — N item(s) due
|
|
662
|
+
• drift: last Xd ago (daily) DUE
|
|
663
|
+
• llm-tier: last Xd ago (bi-weekly) DUE (suggest + audit, costs $)
|
|
664
|
+
state: NN ADRs · last sweep: D drift · S suggestion · R retire candidates
|
|
665
|
+
→ /adr-kit:guardian (LLM tier asks before spending)
|
|
666
|
+
"""
|
|
667
|
+
due_count = (1 if cheap_due else 0) + (1 if llm_due else 0)
|
|
668
|
+
|
|
669
|
+
cheap_tier = state.get("cheap_tier") or {}
|
|
670
|
+
llm_tier = state.get("llm_tier") or {}
|
|
671
|
+
|
|
672
|
+
cheap_last_run = _parse_iso(cheap_tier.get("last_run"))
|
|
673
|
+
llm_last_run = _parse_iso(llm_tier.get("last_run"))
|
|
674
|
+
|
|
675
|
+
cheap_days = _days_since(cheap_last_run)
|
|
676
|
+
llm_days = _days_since(llm_last_run)
|
|
677
|
+
|
|
678
|
+
def _age_label(days: Optional[float]) -> str:
|
|
679
|
+
if days is None:
|
|
680
|
+
return "never"
|
|
681
|
+
if days < 1.0:
|
|
682
|
+
h = days * 24.0
|
|
683
|
+
return f"{h:.0f}h ago"
|
|
684
|
+
return f"{days:.0f}d ago"
|
|
685
|
+
|
|
686
|
+
lines = [f"[adr-guardian] ADR health — {due_count} item(s) due"]
|
|
687
|
+
|
|
688
|
+
cheap_tag = "DUE" if cheap_due else "ok"
|
|
689
|
+
llm_tag = "DUE" if llm_due else "ok"
|
|
690
|
+
|
|
691
|
+
lines.append(
|
|
692
|
+
f" • drift: last {_age_label(cheap_days)} (daily) {cheap_tag}"
|
|
693
|
+
)
|
|
694
|
+
outstanding = _outstanding_violations(llm_tier)
|
|
695
|
+
llm_suffix = ""
|
|
696
|
+
if outstanding:
|
|
697
|
+
# ADR-037: a violation is why the tier is (still) due; say so instead
|
|
698
|
+
# of letting the line read as ordinary staleness.
|
|
699
|
+
llm_suffix = f" ({len(outstanding)} violation(s) outstanding: " f"{', '.join(outstanding[:3])}" f"{', ...' if len(outstanding) > 3 else ''})"
|
|
700
|
+
elif llm_due:
|
|
701
|
+
llm_suffix = " (suggest + audit, costs $)"
|
|
702
|
+
lines.append(
|
|
703
|
+
f" • llm-tier: last {_age_label(llm_days)} (bi-weekly) {llm_tag}"
|
|
704
|
+
+ llm_suffix
|
|
705
|
+
)
|
|
706
|
+
|
|
707
|
+
drift_violations = cheap_tier.get("drift_violations", 0)
|
|
708
|
+
retire_candidates = cheap_tier.get("retire_candidates", 0)
|
|
709
|
+
suggest_hits = llm_tier.get("suggest_hits", 0)
|
|
710
|
+
|
|
711
|
+
lines.append(
|
|
712
|
+
f" state: {adr_count} ADRs · last sweep: {drift_violations} drift"
|
|
713
|
+
f" · {suggest_hits} suggestion · {retire_candidates} retire candidates"
|
|
714
|
+
)
|
|
715
|
+
delta_line = _format_trend_delta(state)
|
|
716
|
+
if delta_line is not None:
|
|
717
|
+
lines.append(f" {delta_line}")
|
|
718
|
+
lines.append(" → /adr-kit:guardian (LLM tier asks before spending)")
|
|
719
|
+
|
|
720
|
+
return "\n".join(lines)
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
# ---------------------------------------------------------------------------
|
|
724
|
+
# JSON envelope (SessionStart additionalContext contract)
|
|
725
|
+
# ---------------------------------------------------------------------------
|
|
726
|
+
|
|
727
|
+
def _escape_for_json(s: str) -> str:
|
|
728
|
+
"""Escape a plain string for embedding as a JSON string value."""
|
|
729
|
+
s = s.replace("\\", "\\\\")
|
|
730
|
+
s = s.replace('"', '\\"')
|
|
731
|
+
s = s.replace("\n", "\\n")
|
|
732
|
+
s = s.replace("\r", "\\r")
|
|
733
|
+
s = s.replace("\t", "\\t")
|
|
734
|
+
return s
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def _emit_context(text: str) -> None:
|
|
738
|
+
"""Print the SessionStart context-injection JSON envelope.
|
|
739
|
+
|
|
740
|
+
Claude Code receives its event-specific envelope. Other supported SDK
|
|
741
|
+
clients receive the common top-level context field. Both forms request
|
|
742
|
+
suppression of raw hook output while preserving model context.
|
|
743
|
+
"""
|
|
744
|
+
escaped = _escape_for_json(text)
|
|
745
|
+
if os.environ.get("CLAUDE_PLUGIN_ROOT") and not os.environ.get("COPILOT_CLI"):
|
|
746
|
+
out = (
|
|
747
|
+
'{"suppressOutput": true, "hookSpecificOutput": {'
|
|
748
|
+
'"hookEventName": "SessionStart", '
|
|
749
|
+
f'"additionalContext": "{escaped}"'
|
|
750
|
+
"}}"
|
|
751
|
+
)
|
|
752
|
+
else:
|
|
753
|
+
out = f'{{"suppressOutput": true, "additionalContext": "{escaped}"}}'
|
|
754
|
+
sys.stdout.write(out + "\n")
|
|
755
|
+
sys.stdout.flush()
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
# ---------------------------------------------------------------------------
|
|
759
|
+
# Subcommand: check
|
|
760
|
+
# ---------------------------------------------------------------------------
|
|
761
|
+
|
|
762
|
+
def cmd_check(args: argparse.Namespace) -> int:
|
|
763
|
+
"""Staleness detector. Always exits 0. Prints nothing when nothing is due."""
|
|
764
|
+
# cwd-guard: bail silently when there are no ADRs in this project.
|
|
765
|
+
adr_dir = _find_adr_dir()
|
|
766
|
+
if adr_dir is None:
|
|
767
|
+
return 0
|
|
768
|
+
|
|
769
|
+
state_path = adr_dir / ".adr-kit-state.json"
|
|
770
|
+
config_path = adr_dir / ".adr-kit.json"
|
|
771
|
+
|
|
772
|
+
cfg = _load_config(config_path)
|
|
773
|
+
gcfg = _guardian_config(cfg)
|
|
774
|
+
|
|
775
|
+
# Respect guardian.enabled (default True).
|
|
776
|
+
if not gcfg.get("enabled", True):
|
|
777
|
+
return 0
|
|
778
|
+
|
|
779
|
+
# Copied-artifact staleness (task-15): pure file reads, never subprocesses.
|
|
780
|
+
# A stale wrapper counts as a due item so it surfaces even when both
|
|
781
|
+
# sweep tiers are fresh; it rides the same nudge cooldown as the tiers.
|
|
782
|
+
artifact_lines = _stale_artifact_lines(_artifact_report(adr_dir.parent.parent))
|
|
783
|
+
artifact_lines.extend(_stale_index_lines(adr_dir))
|
|
784
|
+
_refresh_queue_if_stale(adr_dir, project_root=adr_dir.parent.parent)
|
|
785
|
+
now = _now_utc()
|
|
786
|
+
adr_count = _count_adrs(adr_dir)
|
|
787
|
+
|
|
788
|
+
def check_and_stamp_nudge(state):
|
|
789
|
+
cheap_due, llm_due = _compute_due_tiers(state, gcfg, now)
|
|
790
|
+
if not cheap_due and not llm_due and not artifact_lines:
|
|
791
|
+
return False, False
|
|
792
|
+
if _is_throttled(state, gcfg):
|
|
793
|
+
return False, False
|
|
794
|
+
|
|
795
|
+
block = _format_guardian_block(
|
|
796
|
+
cheap_due, llm_due, state, adr_count, now
|
|
797
|
+
)
|
|
798
|
+
if artifact_lines:
|
|
799
|
+
block_lines = block.split("\n")
|
|
800
|
+
due_count = (
|
|
801
|
+
(1 if cheap_due else 0)
|
|
802
|
+
+ (1 if llm_due else 0)
|
|
803
|
+
+ len(artifact_lines)
|
|
804
|
+
)
|
|
805
|
+
head = f"[adr-guardian] ADR health — {due_count} item(s) due"
|
|
806
|
+
block = "\n".join(
|
|
807
|
+
[head] + block_lines[1:-1] + artifact_lines + [block_lines[-1]]
|
|
808
|
+
)
|
|
809
|
+
_emit_context(block)
|
|
810
|
+
state["last_nudged"] = now.isoformat()
|
|
811
|
+
return True, True
|
|
812
|
+
|
|
813
|
+
_update_state(state_path, check_and_stamp_nudge)
|
|
814
|
+
|
|
815
|
+
return 0
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def cmd_retrieval_health(args: argparse.Namespace) -> int:
|
|
819
|
+
"""Report selective-context health without editing state or blocking."""
|
|
820
|
+
adr_dir = Path(args.adr_dir) if args.adr_dir else _find_adr_dir()
|
|
821
|
+
if adr_dir is None:
|
|
822
|
+
return 0
|
|
823
|
+
probe_path = Path(args.probes_file) if args.probes_file else None
|
|
824
|
+
if probe_path is not None and not probe_path.is_absolute():
|
|
825
|
+
probe_path = adr_dir / probe_path
|
|
826
|
+
payload = run_retrieval_health(adr_dir, probe_path=probe_path)
|
|
827
|
+
if args.format == "json":
|
|
828
|
+
sys.stdout.write(json.dumps(payload, indent=2, sort_keys=True) + "\n")
|
|
829
|
+
else:
|
|
830
|
+
sys.stdout.write(render_retrieval_health(payload) + "\n")
|
|
831
|
+
return 0
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
# ---------------------------------------------------------------------------
|
|
835
|
+
# Subcommand: stamp
|
|
836
|
+
# ---------------------------------------------------------------------------
|
|
837
|
+
|
|
838
|
+
def cmd_stamp(args: argparse.Namespace) -> int:
|
|
839
|
+
"""Record completion of a sweep tier. Always exits 0 on valid input."""
|
|
840
|
+
tier = args.tier # "cheap" or "llm"
|
|
841
|
+
|
|
842
|
+
# ADR-037: the per-ADR form is llm-only and needs an explicit verdict.
|
|
843
|
+
# Refusing here (not silently ignoring) keeps "stamped" meaning "judged".
|
|
844
|
+
if args.adr is not None and (tier != "llm" or args.verdict is None):
|
|
845
|
+
sys.stderr.write(
|
|
846
|
+
"[adr-guardian] ERROR: --adr requires tier 'llm' and --verdict "
|
|
847
|
+
"{ok|violation}.\n"
|
|
848
|
+
)
|
|
849
|
+
return 2
|
|
850
|
+
if args.verdict is not None and args.adr is None:
|
|
851
|
+
sys.stderr.write(
|
|
852
|
+
"[adr-guardian] ERROR: --verdict only makes sense with --adr.\n"
|
|
853
|
+
)
|
|
854
|
+
return 2
|
|
855
|
+
if args.adr is not None:
|
|
856
|
+
# The per-ADR form records exactly one verdict and nothing else. The
|
|
857
|
+
# tier-level metrics ride the tier stamp; accepting them here and then
|
|
858
|
+
# returning before the tier writes dropped them silently (exit 0, data
|
|
859
|
+
# gone). Refuse the combination so the caller learns immediately.
|
|
860
|
+
conflicting = [
|
|
861
|
+
flag for flag, value in (
|
|
862
|
+
("--suggest", args.suggest), ("--audit", args.audit),
|
|
863
|
+
("--coverage", args.coverage), ("--lint", args.lint),
|
|
864
|
+
("--violations", args.violations), ("--retire", args.retire),
|
|
865
|
+
("--retire-seen", args.retire_seen),
|
|
866
|
+
) if value is not None
|
|
867
|
+
]
|
|
868
|
+
if conflicting:
|
|
869
|
+
sys.stderr.write(
|
|
870
|
+
f"[adr-guardian] ERROR: {', '.join(conflicting)} are tier-level "
|
|
871
|
+
f"flags; a per-ADR stamp (--adr) records one verdict only. "
|
|
872
|
+
f"Stamp the tier separately.\n"
|
|
873
|
+
)
|
|
874
|
+
return 2
|
|
875
|
+
if args.adr is not None and not args.adr.strip():
|
|
876
|
+
# An empty string is not None, so it passed the check above -- and it
|
|
877
|
+
# is falsy, so the dispatch below would fall through to the TIER branch
|
|
878
|
+
# and stamp a completed sweep. Observed before this guard existed.
|
|
879
|
+
sys.stderr.write("[adr-guardian] ERROR: --adr must name an ADR.\n")
|
|
880
|
+
return 2
|
|
881
|
+
|
|
882
|
+
adr_dir = _find_adr_dir()
|
|
883
|
+
if adr_dir is None:
|
|
884
|
+
# No ADR dir — can happen if skill is invoked outside a project context.
|
|
885
|
+
# Honour the state-dir flag if provided.
|
|
886
|
+
if args.state_dir:
|
|
887
|
+
state_path = Path(args.state_dir) / ".adr-kit-state.json"
|
|
888
|
+
else:
|
|
889
|
+
return 0
|
|
890
|
+
else:
|
|
891
|
+
state_path = adr_dir / ".adr-kit-state.json"
|
|
892
|
+
if args.state_dir:
|
|
893
|
+
state_path = Path(args.state_dir) / ".adr-kit-state.json"
|
|
894
|
+
|
|
895
|
+
now_iso = _now_utc().isoformat()
|
|
896
|
+
total_adrs = _count_adrs(adr_dir) if adr_dir is not None else None
|
|
897
|
+
|
|
898
|
+
if args.adr is not None:
|
|
899
|
+
# Resolve the id against the real ADR set BEFORE any state write. The
|
|
900
|
+
# pruning step bounds the map to existing ADR files, so an id that does
|
|
901
|
+
# not resolve (a typo like ADR-999, an unpadded ADR-1) used to be
|
|
902
|
+
# written and then pruned inside the same transaction: exit 0, verdict
|
|
903
|
+
# silently lost. A lost "violation" is exactly the false state ADR-037
|
|
904
|
+
# exists to prevent, so an unresolvable id is refused, loudly.
|
|
905
|
+
if adr_dir is None:
|
|
906
|
+
sys.stderr.write(
|
|
907
|
+
"[adr-guardian] ERROR: --adr needs an ADR directory to "
|
|
908
|
+
"validate against; none was found from the cwd.\n"
|
|
909
|
+
)
|
|
910
|
+
return 2
|
|
911
|
+
# One id reader for the whole kit (adr_catalog): re-implementing the
|
|
912
|
+
# parse locally is what allowed the silent-prune mismatch, because a
|
|
913
|
+
# fourth regex disagreed with the other three on normalization.
|
|
914
|
+
# normalize_adr_id also zero-pads, so "ADR-1" resolves to ADR-001
|
|
915
|
+
# instead of being refused over a formatting difference.
|
|
916
|
+
existing_ids = {
|
|
917
|
+
catalog_id
|
|
918
|
+
for f in adr_dir.glob("ADR-*.md")
|
|
919
|
+
if (catalog_id := adr_id_from_filename(f.name))
|
|
920
|
+
}
|
|
921
|
+
adr_id = normalize_adr_id(args.adr)
|
|
922
|
+
if adr_id is None or adr_id not in existing_ids:
|
|
923
|
+
sys.stderr.write(
|
|
924
|
+
f"[adr-guardian] ERROR: {args.adr.strip()!r} does not resolve "
|
|
925
|
+
f"to any ADR file in {adr_dir}. Nothing was stamped.\n"
|
|
926
|
+
)
|
|
927
|
+
return 2
|
|
928
|
+
|
|
929
|
+
def stamp_state(state):
|
|
930
|
+
if tier == "cheap":
|
|
931
|
+
cheap = dict(state.get("cheap_tier") or {})
|
|
932
|
+
cheap["last_run"] = now_iso
|
|
933
|
+
if args.violations is not None:
|
|
934
|
+
cheap["drift_violations"] = args.violations
|
|
935
|
+
if args.retire is not None:
|
|
936
|
+
cheap["retire_candidates"] = args.retire
|
|
937
|
+
if args.lint is not None:
|
|
938
|
+
cheap["lint"] = args.lint
|
|
939
|
+
state["cheap_tier"] = cheap
|
|
940
|
+
if args.retire_seen is not None:
|
|
941
|
+
try:
|
|
942
|
+
seen_list = json.loads(args.retire_seen)
|
|
943
|
+
if isinstance(seen_list, list):
|
|
944
|
+
state["retire_seen"] = seen_list
|
|
945
|
+
except json.JSONDecodeError:
|
|
946
|
+
pass
|
|
947
|
+
elif tier == "llm" and args.adr is not None:
|
|
948
|
+
# ADR-037: incremental per-ADR stamp. Records one verdict the
|
|
949
|
+
# moment it exists so an interrupted sweep keeps what it
|
|
950
|
+
# established. Deliberately does NOT touch llm_tier.last_run (that
|
|
951
|
+
# timestamp means "a completed sweep") and appends no trend entry.
|
|
952
|
+
# The id was validated against existing_ids above, so the prune
|
|
953
|
+
# below can only remove entries for files deleted since their stamp.
|
|
954
|
+
llm = dict(state.get("llm_tier") or {})
|
|
955
|
+
adrs = dict(llm.get("adrs") or {})
|
|
956
|
+
adrs[adr_id] = {
|
|
957
|
+
"last_run": now_iso,
|
|
958
|
+
"verdict": args.verdict,
|
|
959
|
+
}
|
|
960
|
+
adrs = {k: v for k, v in adrs.items() if k in existing_ids}
|
|
961
|
+
llm["adrs"] = adrs
|
|
962
|
+
state["llm_tier"] = llm
|
|
963
|
+
return True, None
|
|
964
|
+
elif tier == "llm":
|
|
965
|
+
llm = dict(state.get("llm_tier") or {})
|
|
966
|
+
llm["last_run"] = now_iso
|
|
967
|
+
if args.suggest is not None:
|
|
968
|
+
llm["suggest_hits"] = args.suggest
|
|
969
|
+
if args.audit is not None:
|
|
970
|
+
llm["audit_findings"] = args.audit
|
|
971
|
+
# ADR-037: a tier-level stamp marks a completed sweep; it must not
|
|
972
|
+
# erase or rewrite the per-ADR map.
|
|
973
|
+
state["llm_tier"] = llm
|
|
974
|
+
|
|
975
|
+
_append_trend_entry(state, tier, now_iso, total_adrs, args.coverage)
|
|
976
|
+
return True, None
|
|
977
|
+
|
|
978
|
+
_update_state(state_path, stamp_state)
|
|
979
|
+
return 0
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
# ---------------------------------------------------------------------------
|
|
983
|
+
# Subcommand: artifacts
|
|
984
|
+
# ---------------------------------------------------------------------------
|
|
985
|
+
|
|
986
|
+
def cmd_artifacts(args: argparse.Namespace) -> int:
|
|
987
|
+
"""Report copied-artifact freshness vs the installed plugin. Always exits 0.
|
|
988
|
+
|
|
989
|
+
Used by /adr-kit:upgrade as its detection step and available for manual
|
|
990
|
+
inspection. Pure file reads.
|
|
991
|
+
"""
|
|
992
|
+
if args.project_root:
|
|
993
|
+
project_root = Path(args.project_root)
|
|
994
|
+
else:
|
|
995
|
+
adr_dir = _find_adr_dir()
|
|
996
|
+
project_root = adr_dir.parent.parent if adr_dir is not None else Path.cwd()
|
|
997
|
+
|
|
998
|
+
report = _artifact_report(project_root)
|
|
999
|
+
|
|
1000
|
+
if args.format == "json":
|
|
1001
|
+
json.dump(report, sys.stdout, indent=2)
|
|
1002
|
+
sys.stdout.write("\n")
|
|
1003
|
+
return 0
|
|
1004
|
+
|
|
1005
|
+
plugin_version = report.get("plugin_version") or "unknown"
|
|
1006
|
+
sys.stdout.write(f"[adr-guardian] plugin version: {plugin_version}\n")
|
|
1007
|
+
artifacts = report.get("artifacts", [])
|
|
1008
|
+
if not artifacts:
|
|
1009
|
+
sys.stdout.write(" no copied adr-kit artifacts found in this project\n")
|
|
1010
|
+
return 0
|
|
1011
|
+
for art in artifacts:
|
|
1012
|
+
version_label = art.get("version") or "unstamped"
|
|
1013
|
+
tag = "STALE" if art.get("stale") else "ok"
|
|
1014
|
+
sys.stdout.write(
|
|
1015
|
+
f" {art.get('kind')}: {art.get('path')} ({version_label}) {tag}\n"
|
|
1016
|
+
)
|
|
1017
|
+
if any(a.get("stale") for a in artifacts):
|
|
1018
|
+
sys.stdout.write(" → refresh with /adr-kit:upgrade (or /adr-kit:install-hooks)\n")
|
|
1019
|
+
return 0
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
# ---------------------------------------------------------------------------
|
|
1023
|
+
# Subcommand: state
|
|
1024
|
+
# ---------------------------------------------------------------------------
|
|
1025
|
+
|
|
1026
|
+
def cmd_state(args: argparse.Namespace) -> int:
|
|
1027
|
+
"""Print current state JSON to stdout. Always exits 0."""
|
|
1028
|
+
adr_dir = _find_adr_dir()
|
|
1029
|
+
if adr_dir is None:
|
|
1030
|
+
if args.state_dir:
|
|
1031
|
+
state_path = Path(args.state_dir) / ".adr-kit-state.json"
|
|
1032
|
+
else:
|
|
1033
|
+
json.dump(json.loads(json.dumps(DEFAULT_STATE)), sys.stdout, indent=2)
|
|
1034
|
+
sys.stdout.write("\n")
|
|
1035
|
+
return 0
|
|
1036
|
+
else:
|
|
1037
|
+
state_path = adr_dir / ".adr-kit-state.json"
|
|
1038
|
+
if args.state_dir:
|
|
1039
|
+
state_path = Path(args.state_dir) / ".adr-kit-state.json"
|
|
1040
|
+
|
|
1041
|
+
state = _load_state(state_path)
|
|
1042
|
+
json.dump(state, sys.stdout, indent=2)
|
|
1043
|
+
sys.stdout.write("\n")
|
|
1044
|
+
return 0
|
|
1045
|
+
|
|
1046
|
+
|
|
1047
|
+
def cmd_refresh_readiness(args: argparse.Namespace) -> int:
|
|
1048
|
+
"""Calculate the Proposed work queue outside SessionStart and cache it."""
|
|
1049
|
+
project_root = Path(args.project_root or Path.cwd()).expanduser().resolve()
|
|
1050
|
+
adr_dir = (
|
|
1051
|
+
Path(args.adr_dir).expanduser().resolve()
|
|
1052
|
+
if args.adr_dir
|
|
1053
|
+
else project_root / "docs" / "adr"
|
|
1054
|
+
)
|
|
1055
|
+
if not project_root.is_dir() or not adr_dir.is_dir():
|
|
1056
|
+
sys.stderr.write("[adr-guardian] readiness refresh skipped: ADR directory missing\n")
|
|
1057
|
+
return 0
|
|
1058
|
+
command = [
|
|
1059
|
+
sys.executable,
|
|
1060
|
+
str(Path(__file__).resolve().with_name("adr-readiness")),
|
|
1061
|
+
"--all-proposed",
|
|
1062
|
+
"--format",
|
|
1063
|
+
"json",
|
|
1064
|
+
"--repo-root",
|
|
1065
|
+
str(project_root),
|
|
1066
|
+
"--adr-dir",
|
|
1067
|
+
str(adr_dir),
|
|
1068
|
+
]
|
|
1069
|
+
if args.today:
|
|
1070
|
+
command.extend(["--today", args.today])
|
|
1071
|
+
if args.diff:
|
|
1072
|
+
command.append("--diff")
|
|
1073
|
+
if args.base or args.head:
|
|
1074
|
+
if not (args.base and args.head):
|
|
1075
|
+
sys.stderr.write("[adr-guardian] readiness refresh requires --base and --head together\n")
|
|
1076
|
+
return 0
|
|
1077
|
+
command.extend(["--base", args.base, "--head", args.head])
|
|
1078
|
+
try:
|
|
1079
|
+
result = subprocess.run(
|
|
1080
|
+
command,
|
|
1081
|
+
cwd=project_root,
|
|
1082
|
+
capture_output=True,
|
|
1083
|
+
text=True,
|
|
1084
|
+
encoding="utf-8",
|
|
1085
|
+
errors="replace",
|
|
1086
|
+
timeout=10,
|
|
1087
|
+
)
|
|
1088
|
+
if result.returncode != 0:
|
|
1089
|
+
sys.stderr.write(
|
|
1090
|
+
"[adr-guardian] readiness refresh skipped: "
|
|
1091
|
+
+ (result.stderr.strip() or f"exit {result.returncode}")
|
|
1092
|
+
+ "\n"
|
|
1093
|
+
)
|
|
1094
|
+
return 0
|
|
1095
|
+
report = json.loads(result.stdout)
|
|
1096
|
+
generated_at = (
|
|
1097
|
+
datetime.fromisoformat(args.generated_at)
|
|
1098
|
+
if args.generated_at
|
|
1099
|
+
else _now_utc()
|
|
1100
|
+
)
|
|
1101
|
+
payload = build_queue_cache(
|
|
1102
|
+
report, generated_at=generated_at, ttl_hours=args.ttl_hours
|
|
1103
|
+
)
|
|
1104
|
+
cache_path = adr_dir / QUEUE_CACHE_NAME
|
|
1105
|
+
write_queue_cache(cache_path, payload)
|
|
1106
|
+
sys.stdout.write(
|
|
1107
|
+
f"[adr-guardian] cached {len(payload['actions'])} of "
|
|
1108
|
+
f"{payload['total_proposed']} Proposed ADR action(s)\n"
|
|
1109
|
+
)
|
|
1110
|
+
except (OSError, ValueError, json.JSONDecodeError, subprocess.TimeoutExpired) as exc:
|
|
1111
|
+
sys.stderr.write(f"[adr-guardian] readiness refresh skipped: {exc}\n")
|
|
1112
|
+
return 0
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
# ---------------------------------------------------------------------------
|
|
1116
|
+
# Main
|
|
1117
|
+
# ---------------------------------------------------------------------------
|
|
1118
|
+
|
|
1119
|
+
def main() -> int:
|
|
1120
|
+
_ensure_utf8_streams()
|
|
1121
|
+
p = argparse.ArgumentParser(
|
|
1122
|
+
prog="adr-guardian",
|
|
1123
|
+
description=(
|
|
1124
|
+
"ADR-set health detector for adr-kit (v0.18.0+). "
|
|
1125
|
+
"Three subcommands: check (SessionStart hook), stamp (record sweep), state (inspect)."
|
|
1126
|
+
),
|
|
1127
|
+
)
|
|
1128
|
+
sub = p.add_subparsers(dest="command")
|
|
1129
|
+
|
|
1130
|
+
# check
|
|
1131
|
+
check_p = sub.add_parser(
|
|
1132
|
+
"check",
|
|
1133
|
+
help=(
|
|
1134
|
+
"Staleness detector for SessionStart hook. Prints nothing when nothing is due. "
|
|
1135
|
+
"Always exits 0."
|
|
1136
|
+
),
|
|
1137
|
+
)
|
|
1138
|
+
check_p.add_argument(
|
|
1139
|
+
"--adr-dir",
|
|
1140
|
+
default=None,
|
|
1141
|
+
help="Override docs/adr directory (default: auto-detect from CLAUDE_PROJECT_DIR or cwd).",
|
|
1142
|
+
)
|
|
1143
|
+
|
|
1144
|
+
# stamp
|
|
1145
|
+
stamp_p = sub.add_parser(
|
|
1146
|
+
"stamp",
|
|
1147
|
+
help="Record that a sweep tier completed. Updates .adr-kit-state.json.",
|
|
1148
|
+
)
|
|
1149
|
+
stamp_p.add_argument(
|
|
1150
|
+
"tier",
|
|
1151
|
+
choices=["cheap", "llm"],
|
|
1152
|
+
help="Which tier completed.",
|
|
1153
|
+
)
|
|
1154
|
+
stamp_p.add_argument("--violations", type=int, default=None,
|
|
1155
|
+
help="Number of drift violations found (cheap tier).")
|
|
1156
|
+
stamp_p.add_argument("--retire", type=int, default=None,
|
|
1157
|
+
help="Number of retire candidates found (cheap tier).")
|
|
1158
|
+
stamp_p.add_argument("--retire-seen", dest="retire_seen", default=None,
|
|
1159
|
+
help="JSON array of ADR ids in the retire candidate set (cheap tier).")
|
|
1160
|
+
stamp_p.add_argument("--lint", default=None,
|
|
1161
|
+
help="Lint summary string, e.g. '2F/5A' (cheap tier).")
|
|
1162
|
+
stamp_p.add_argument("--suggest", type=int, default=None,
|
|
1163
|
+
help="Number of missing-ADR suggestions (llm tier).")
|
|
1164
|
+
stamp_p.add_argument("--audit", type=int, default=None,
|
|
1165
|
+
help="Number of audit findings (llm tier).")
|
|
1166
|
+
stamp_p.add_argument("--coverage", type=float, default=None,
|
|
1167
|
+
help="Enforcement coverage percent of Accepted ADRs "
|
|
1168
|
+
"(from adr-status --format json, summary.coverage_pct). "
|
|
1169
|
+
"Carried from the previous trend entry when omitted.")
|
|
1170
|
+
stamp_p.add_argument("--adr", default=None,
|
|
1171
|
+
help="Stamp ONE ADR's verdict instead of the whole tier "
|
|
1172
|
+
"(llm tier only; ADR-037). Requires --verdict. Does "
|
|
1173
|
+
"not update the tier timestamp or the trend.")
|
|
1174
|
+
stamp_p.add_argument("--verdict", choices=["ok", "violation"], default=None,
|
|
1175
|
+
help="The verdict for --adr. Only real verdicts stamp: "
|
|
1176
|
+
"a timeout or error is not a verdict (ADR-037).")
|
|
1177
|
+
stamp_p.add_argument("--state-dir", dest="state_dir", default=None,
|
|
1178
|
+
help="Override directory for .adr-kit-state.json (tests/CI).")
|
|
1179
|
+
|
|
1180
|
+
# state
|
|
1181
|
+
state_p = sub.add_parser(
|
|
1182
|
+
"state",
|
|
1183
|
+
help="Print current .adr-kit-state.json as formatted JSON. Always exits 0.",
|
|
1184
|
+
)
|
|
1185
|
+
state_p.add_argument("--state-dir", dest="state_dir", default=None,
|
|
1186
|
+
help="Override directory for .adr-kit-state.json (tests/CI).")
|
|
1187
|
+
|
|
1188
|
+
# artifacts
|
|
1189
|
+
artifacts_p = sub.add_parser(
|
|
1190
|
+
"artifacts",
|
|
1191
|
+
help=(
|
|
1192
|
+
"Report copied-artifact freshness (git pre-commit wrapper, settings "
|
|
1193
|
+
"guardian entry) vs the installed plugin version. Always exits 0."
|
|
1194
|
+
),
|
|
1195
|
+
)
|
|
1196
|
+
artifacts_p.add_argument("--project-root", dest="project_root", default=None,
|
|
1197
|
+
help="Project root to inspect (default: auto-detect).")
|
|
1198
|
+
artifacts_p.add_argument("--format", choices=["human", "json"], default="human",
|
|
1199
|
+
help="Output format (default: human).")
|
|
1200
|
+
|
|
1201
|
+
refresh_p = sub.add_parser(
|
|
1202
|
+
"refresh-readiness",
|
|
1203
|
+
help="Calculate Proposed ADR readiness outside hooks and atomically cache three actions.",
|
|
1204
|
+
)
|
|
1205
|
+
refresh_p.add_argument("--project-root", default=None)
|
|
1206
|
+
refresh_p.add_argument("--adr-dir", default=None)
|
|
1207
|
+
refresh_p.add_argument("--diff", action="store_true")
|
|
1208
|
+
refresh_p.add_argument("--base", default=None)
|
|
1209
|
+
refresh_p.add_argument("--head", default=None)
|
|
1210
|
+
refresh_p.add_argument("--today", default=None)
|
|
1211
|
+
refresh_p.add_argument("--generated-at", default=None)
|
|
1212
|
+
refresh_p.add_argument("--ttl-hours", type=int, default=24)
|
|
1213
|
+
|
|
1214
|
+
retrieval_p = sub.add_parser(
|
|
1215
|
+
"retrieval-health",
|
|
1216
|
+
help=(
|
|
1217
|
+
"Report deterministic selective-context probes and metadata health. "
|
|
1218
|
+
"Read-only and always exits 0."
|
|
1219
|
+
),
|
|
1220
|
+
)
|
|
1221
|
+
retrieval_p.add_argument("--adr-dir", default=None)
|
|
1222
|
+
retrieval_p.add_argument("--probes-file", default=None)
|
|
1223
|
+
retrieval_p.add_argument(
|
|
1224
|
+
"--format",
|
|
1225
|
+
choices=["human", "json"],
|
|
1226
|
+
default="human",
|
|
1227
|
+
)
|
|
1228
|
+
|
|
1229
|
+
args = p.parse_args()
|
|
1230
|
+
|
|
1231
|
+
if args.command is None:
|
|
1232
|
+
p.print_help(sys.stderr)
|
|
1233
|
+
return 2
|
|
1234
|
+
|
|
1235
|
+
# Apply --adr-dir override for check (patch env var so _find_adr_dir picks it up).
|
|
1236
|
+
if args.command == "check" and getattr(args, "adr_dir", None):
|
|
1237
|
+
os.environ["CLAUDE_PROJECT_DIR"] = str(Path(args.adr_dir).resolve().parent.parent)
|
|
1238
|
+
|
|
1239
|
+
try:
|
|
1240
|
+
if args.command == "check":
|
|
1241
|
+
return cmd_check(args)
|
|
1242
|
+
elif args.command == "stamp":
|
|
1243
|
+
return cmd_stamp(args)
|
|
1244
|
+
elif args.command == "state":
|
|
1245
|
+
return cmd_state(args)
|
|
1246
|
+
elif args.command == "artifacts":
|
|
1247
|
+
return cmd_artifacts(args)
|
|
1248
|
+
elif args.command == "refresh-readiness":
|
|
1249
|
+
return cmd_refresh_readiness(args)
|
|
1250
|
+
elif args.command == "retrieval-health":
|
|
1251
|
+
return cmd_retrieval_health(args)
|
|
1252
|
+
except KeyboardInterrupt:
|
|
1253
|
+
return 0
|
|
1254
|
+
except Exception:
|
|
1255
|
+
# The check subcommand must NEVER propagate an exception — guardian must
|
|
1256
|
+
# not block a session start. Other subcommands: same policy for safety.
|
|
1257
|
+
return 0
|
|
1258
|
+
|
|
1259
|
+
return 0
|
|
1260
|
+
|
|
1261
|
+
|
|
1262
|
+
if __name__ == "__main__":
|
|
1263
|
+
sys.exit(main())
|