@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-doctor
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Fast, evidence-backed ADR Kit health checks and bounded deep probes."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import importlib.machinery
|
|
8
|
+
import importlib.util
|
|
9
|
+
import json
|
|
10
|
+
import sys
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
ROOT = Path(__file__).resolve().parent.parent
|
|
14
|
+
_BIN_DIR = ROOT / "bin"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _is_bin_dir(entry: str) -> bool:
|
|
18
|
+
"""True when a sys.path entry resolves to this script's own directory.
|
|
19
|
+
|
|
20
|
+
Compared resolved, not textually: CPython only guarantees an absolute
|
|
21
|
+
sys.path[0] from 3.11 onward, and "" (cwd) must also be caught when bin/
|
|
22
|
+
happens to be the working directory.
|
|
23
|
+
"""
|
|
24
|
+
try:
|
|
25
|
+
return Path(entry or ".").resolve() == _BIN_DIR
|
|
26
|
+
except (OSError, ValueError):
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# SEC-HIGH (TASK-62): ROOT/"bin" used to go on sys.path at position 0 together
|
|
31
|
+
# with these two, which let any module committed next to this script shadow the
|
|
32
|
+
# standard library. The bin siblings are now loaded by explicit file location
|
|
33
|
+
# (below), so that entry is gone.
|
|
34
|
+
#
|
|
35
|
+
# ROOT and ROOT/"scripts" must stay importable: adr_doctor_checks and
|
|
36
|
+
# adr_doctor_probes reach into scripts/adr_settings.py, scripts/project_setup.py,
|
|
37
|
+
# clients.installer.* and hooks.hook_benchmark, which are packages and flat
|
|
38
|
+
# modules in OTHER directories, not siblings. They are APPENDED so the standard
|
|
39
|
+
# library and site-packages still resolve first.
|
|
40
|
+
#
|
|
41
|
+
# In a generated client tree those same relative paths exist because
|
|
42
|
+
# client_generation_model.RUNTIME_SUPPORT_FILES declares them, which is what
|
|
43
|
+
# lets this file run from codex/ and copilot/ at all (TASK-125).
|
|
44
|
+
# scripts/client_generation.py is deliberately NOT among them -- a mirror has no
|
|
45
|
+
# canonical inputs to diff -- so adr_doctor_checks imports it lazily, behind
|
|
46
|
+
# adr_doctor_models.generated_tree_owner().
|
|
47
|
+
#
|
|
48
|
+
# That alone is not enough here. CPython puts this script's own directory at
|
|
49
|
+
# sys.path[0] regardless, ahead of these appends, so a committed
|
|
50
|
+
# bin/adr_settings.py shadowed scripts/adr_settings.py and executed --
|
|
51
|
+
# reproduced against this file after the sibling conversion. The bin entry is
|
|
52
|
+
# therefore masked for the duration of the import block below and restored
|
|
53
|
+
# afterwards; restoring is safe because nothing in that dependency tree imports
|
|
54
|
+
# lazily, and it keeps an in-process importer (pytest) from losing an entry
|
|
55
|
+
# other test modules put there deliberately.
|
|
56
|
+
for import_root in (ROOT, ROOT / "scripts"):
|
|
57
|
+
if str(import_root) not in sys.path:
|
|
58
|
+
sys.path.append(str(import_root))
|
|
59
|
+
|
|
60
|
+
_SAVED_SYS_PATH = list(sys.path)
|
|
61
|
+
sys.path[:] = [entry for entry in _SAVED_SYS_PATH if not _is_bin_dir(entry)]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _load_sibling(name: str):
|
|
65
|
+
"""Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
|
|
66
|
+
|
|
67
|
+
Registered in sys.modules under the bare name so each module's own sibling
|
|
68
|
+
imports (adr_doctor_core -> adr_schema + adr_retrieval_health, and so on)
|
|
69
|
+
resolve from the cache. 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 needs adr_format + adr_schema; adr_query lazily
|
|
83
|
+
# needs adr_catalog; adr_retrieval_health needs adr_query; adr_doctor_core needs
|
|
84
|
+
# adr_schema + adr_retrieval_health; adr_doctor_checks and adr_doctor_probes
|
|
85
|
+
# need adr_doctor_models (plus the scripts/ packages appended above).
|
|
86
|
+
for _sibling in (
|
|
87
|
+
"adr_format",
|
|
88
|
+
"adr_schema",
|
|
89
|
+
"adr_catalog",
|
|
90
|
+
"adr_query",
|
|
91
|
+
"adr_retrieval_health",
|
|
92
|
+
"adr_doctor_models",
|
|
93
|
+
"adr_doctor_core",
|
|
94
|
+
"adr_doctor_checks",
|
|
95
|
+
"adr_doctor_probes",
|
|
96
|
+
):
|
|
97
|
+
_load_sibling(_sibling)
|
|
98
|
+
|
|
99
|
+
from adr_doctor_checks import run_client_checks
|
|
100
|
+
from adr_doctor_probes import run_deep_extensions
|
|
101
|
+
from adr_doctor_core import render_text as render_adr_text
|
|
102
|
+
from adr_doctor_core import run_doctor as run_adr_doctor
|
|
103
|
+
from adr_doctor_models import build_report, render_human
|
|
104
|
+
|
|
105
|
+
sys.path[:] = _SAVED_SYS_PATH
|
|
106
|
+
del _SAVED_SYS_PATH
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _parser() -> argparse.ArgumentParser:
|
|
110
|
+
parser = argparse.ArgumentParser(
|
|
111
|
+
prog="adr-doctor",
|
|
112
|
+
description="Check ADR state and Claude/Codex/Copilot integration.",
|
|
113
|
+
)
|
|
114
|
+
parser.add_argument("adr_dir", nargs="?", default="docs/adr")
|
|
115
|
+
parser.add_argument("--repo-root")
|
|
116
|
+
parser.add_argument("--plugin-root", type=Path, default=ROOT)
|
|
117
|
+
parser.add_argument("--config")
|
|
118
|
+
parser.add_argument("--global-settings", type=Path)
|
|
119
|
+
parser.add_argument("--stale-days", type=int)
|
|
120
|
+
parser.add_argument("--format", choices=("text", "human", "json"), default="text")
|
|
121
|
+
parser.add_argument("--check", action="store_true", help="Diagnose without repair.")
|
|
122
|
+
parser.add_argument("--fix", action="store_true", help="Permit backed-up managed rewrites.")
|
|
123
|
+
parser.add_argument("--deep", action="store_true", help="Run bounded native, MCP, and model probes.")
|
|
124
|
+
parser.add_argument("--fix-index", action="store_true", help=argparse.SUPPRESS)
|
|
125
|
+
return parser
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def main(argv: list[str] | None = None) -> int:
|
|
129
|
+
args = _parser().parse_args(argv)
|
|
130
|
+
root = Path(args.repo_root).resolve() if args.repo_root else Path.cwd().resolve()
|
|
131
|
+
# Backward compatibility: --fix-index is an explicit safe-repair request.
|
|
132
|
+
# Default mode also repairs safe owned state; --check is the read-only gate.
|
|
133
|
+
args.fix_index = bool(args.fix_index or not args.check)
|
|
134
|
+
adr = run_adr_doctor(args)
|
|
135
|
+
checks, repairs = run_client_checks(
|
|
136
|
+
root,
|
|
137
|
+
args.plugin_root.resolve(),
|
|
138
|
+
global_settings=args.global_settings,
|
|
139
|
+
check_only=args.check,
|
|
140
|
+
allow_fix=args.fix,
|
|
141
|
+
)
|
|
142
|
+
extensions = run_deep_extensions(
|
|
143
|
+
root,
|
|
144
|
+
args.plugin_root.resolve(),
|
|
145
|
+
checks=checks,
|
|
146
|
+
global_settings=args.global_settings,
|
|
147
|
+
check_only=args.check,
|
|
148
|
+
) if args.deep else []
|
|
149
|
+
report = build_report(
|
|
150
|
+
root=root,
|
|
151
|
+
mode="deep" if args.deep else "fast",
|
|
152
|
+
adr=adr,
|
|
153
|
+
checks=[*checks, *extensions],
|
|
154
|
+
repairs=repairs,
|
|
155
|
+
)
|
|
156
|
+
if args.format == "json":
|
|
157
|
+
print(json.dumps(report, indent=2, sort_keys=True))
|
|
158
|
+
elif args.format == "text" and not checks and not extensions:
|
|
159
|
+
print(render_adr_text(adr))
|
|
160
|
+
else:
|
|
161
|
+
print(render_human(report))
|
|
162
|
+
return int(report["exit_code"])
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
if __name__ == "__main__":
|
|
166
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""adr-generate-scripts: generate standalone validation scripts from ADR Enforcement blocks.
|
|
3
|
+
|
|
4
|
+
Creates executable scripts (Python, Shell) that validate code against ADR Enforcement
|
|
5
|
+
rules without requiring adr-kit. Generated scripts read from stdin and exit 0 on clean,
|
|
6
|
+
1 on violation.
|
|
7
|
+
|
|
8
|
+
Usage:
|
|
9
|
+
adr-generate-scripts
|
|
10
|
+
adr-generate-scripts --output .generated/
|
|
11
|
+
adr-generate-scripts --lang shell
|
|
12
|
+
adr-generate-scripts --lang python
|
|
13
|
+
adr-generate-scripts --lang all
|
|
14
|
+
adr-generate-scripts --adr-dir docs/decisions
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import importlib.machinery
|
|
21
|
+
import importlib.util
|
|
22
|
+
import json
|
|
23
|
+
import re
|
|
24
|
+
import sys
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Dict, List, Optional, Tuple
|
|
27
|
+
|
|
28
|
+
_BIN_DIR = Path(__file__).resolve().parent
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _load_sibling(name: str):
|
|
32
|
+
"""Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
|
|
33
|
+
|
|
34
|
+
SEC-HIGH (TASK-62): `sys.path.insert(0, _BIN_DIR)` put this directory ahead
|
|
35
|
+
of the standard library for every import, so a module committed next to
|
|
36
|
+
this script executed as code -- and it re-added the very directory
|
|
37
|
+
CPython's -P / PYTHONSAFEPATH removes. Siblings are registered in
|
|
38
|
+
sys.modules under their bare name, so the plain `from adr_* import ...`
|
|
39
|
+
statements below (and the lazy ones inside functions) resolve from the
|
|
40
|
+
cache instead of the path. bin/adr-judge carries the full rationale.
|
|
41
|
+
"""
|
|
42
|
+
cached = sys.modules.get(name)
|
|
43
|
+
if cached is not None:
|
|
44
|
+
return cached
|
|
45
|
+
loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
|
|
46
|
+
spec = importlib.util.spec_from_loader(name, loader)
|
|
47
|
+
module = importlib.util.module_from_spec(spec)
|
|
48
|
+
sys.modules[name] = module
|
|
49
|
+
loader.exec_module(module)
|
|
50
|
+
return module
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# Dependency order: adr_catalog imports adr_format and adr_schema.
|
|
54
|
+
_load_sibling("adr_format")
|
|
55
|
+
_load_sibling("adr_schema")
|
|
56
|
+
_load_sibling("adr_catalog")
|
|
57
|
+
|
|
58
|
+
# The generated scripts stay dependency-free; the generator itself shares the
|
|
59
|
+
# repository's single Enforcement and filename readers.
|
|
60
|
+
from adr_catalog import ENFORCEMENT_BLOCK_RE, adr_id_from_filename
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def extract_enforcement(content: str) -> Optional[Dict]:
|
|
64
|
+
"""Extract and parse the Enforcement JSON block from an ADR.
|
|
65
|
+
|
|
66
|
+
Returns None when no Enforcement section is present.
|
|
67
|
+
Raises ValueError when the section exists but contains malformed JSON.
|
|
68
|
+
"""
|
|
69
|
+
m = ENFORCEMENT_BLOCK_RE.search(content)
|
|
70
|
+
if not m:
|
|
71
|
+
return None
|
|
72
|
+
raw = m.group(1)
|
|
73
|
+
try:
|
|
74
|
+
data = json.loads(raw)
|
|
75
|
+
except json.JSONDecodeError as e:
|
|
76
|
+
raise ValueError(f"malformed JSON in ## Enforcement block: {e}")
|
|
77
|
+
if not isinstance(data, dict):
|
|
78
|
+
raise ValueError(f"Enforcement JSON must be an object, got {type(data).__name__}")
|
|
79
|
+
return data
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _collect_rules(enforcement: Dict) -> Tuple[List[Dict], List[str]]:
|
|
83
|
+
"""Compile the standalone-safe rule subset and list unsupported semantics."""
|
|
84
|
+
rules: List[Dict] = []
|
|
85
|
+
unsupported: List[str] = []
|
|
86
|
+
for kind in ("forbid_pattern", "forbid_import", "require_pattern"):
|
|
87
|
+
for index, rule in enumerate(enforcement.get(kind, [])):
|
|
88
|
+
pattern = rule.get("pattern", "")
|
|
89
|
+
message = rule.get("message") or f"{kind}: {pattern}"
|
|
90
|
+
if rule.get("path_glob"):
|
|
91
|
+
unsupported.append(f"{kind}[{index}].path_glob")
|
|
92
|
+
continue
|
|
93
|
+
if not pattern:
|
|
94
|
+
unsupported.append(f"{kind}[{index}].pattern")
|
|
95
|
+
continue
|
|
96
|
+
try:
|
|
97
|
+
re.compile(pattern)
|
|
98
|
+
except re.error as exc:
|
|
99
|
+
unsupported.append(f"{kind}[{index}].pattern ({exc})")
|
|
100
|
+
continue
|
|
101
|
+
rules.append({"kind": kind, "pattern": pattern, "message": message})
|
|
102
|
+
if enforcement.get("llm_judge"):
|
|
103
|
+
unsupported.append("llm_judge")
|
|
104
|
+
return rules, unsupported
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def generate_python_script(adr_id: str, rules: List[Dict]) -> str:
|
|
108
|
+
"""Generate a standalone validator with killable per-rule regex workers."""
|
|
109
|
+
template = """\
|
|
110
|
+
#!/usr/bin/env python3
|
|
111
|
+
# Generated by adr-kit for __ADR_ID__. Do not edit manually.
|
|
112
|
+
# Validates stdin against __ADR_ID__ enforcement rules.
|
|
113
|
+
# Usage: cat file.py | python validate.py
|
|
114
|
+
# Exit 0 = clean, exit 1 = violations, exit 2 = incomplete enforcement.
|
|
115
|
+
|
|
116
|
+
import json
|
|
117
|
+
import re
|
|
118
|
+
import subprocess
|
|
119
|
+
import sys
|
|
120
|
+
|
|
121
|
+
RULES = __RULES__
|
|
122
|
+
MAX_INPUT_BYTES = 2 * 1024 * 1024
|
|
123
|
+
REGEX_TIMEOUT_SECONDS = 1.0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _regex_worker():
|
|
127
|
+
try:
|
|
128
|
+
request = json.load(sys.stdin)
|
|
129
|
+
pattern = re.compile(request["pattern"], re.MULTILINE)
|
|
130
|
+
match = pattern.search(request["text"])
|
|
131
|
+
response = {"ok": True, "matched": match is not None}
|
|
132
|
+
if match is not None:
|
|
133
|
+
response["line"] = request["text"].count("\\n", 0, match.start()) + 1
|
|
134
|
+
response["snippet"] = request["text"].splitlines()[
|
|
135
|
+
response["line"] - 1
|
|
136
|
+
][:200]
|
|
137
|
+
json.dump(response, sys.stdout)
|
|
138
|
+
return 0
|
|
139
|
+
except (KeyError, TypeError, ValueError, re.error) as exc:
|
|
140
|
+
json.dump({"ok": False, "error": str(exc)}, sys.stdout)
|
|
141
|
+
return 2
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _search(pattern, text):
|
|
145
|
+
request = json.dumps({"pattern": pattern, "text": text})
|
|
146
|
+
try:
|
|
147
|
+
result = subprocess.run(
|
|
148
|
+
[sys.executable, __file__, "--regex-worker"],
|
|
149
|
+
input=request,
|
|
150
|
+
capture_output=True,
|
|
151
|
+
text=True,
|
|
152
|
+
encoding="utf-8",
|
|
153
|
+
errors="replace",
|
|
154
|
+
timeout=REGEX_TIMEOUT_SECONDS,
|
|
155
|
+
check=False,
|
|
156
|
+
)
|
|
157
|
+
except subprocess.TimeoutExpired:
|
|
158
|
+
return None, (
|
|
159
|
+
f"regex exceeded {REGEX_TIMEOUT_SECONDS:.3f}s wall-clock budget"
|
|
160
|
+
)
|
|
161
|
+
try:
|
|
162
|
+
response = json.loads(result.stdout)
|
|
163
|
+
except json.JSONDecodeError:
|
|
164
|
+
return None, "isolated regex worker returned invalid JSON"
|
|
165
|
+
if result.returncode != 0 or not response.get("ok"):
|
|
166
|
+
return None, response.get("error", "isolated regex worker failed")
|
|
167
|
+
return response, None
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def main():
|
|
171
|
+
text = sys.stdin.read()
|
|
172
|
+
input_bytes = len(text.encode("utf-8", errors="replace"))
|
|
173
|
+
if input_bytes > MAX_INPUT_BYTES:
|
|
174
|
+
print(
|
|
175
|
+
f"ERROR: input is {input_bytes} bytes; safety budget is "
|
|
176
|
+
f"{MAX_INPUT_BYTES} bytes",
|
|
177
|
+
file=sys.stderr,
|
|
178
|
+
)
|
|
179
|
+
return 2
|
|
180
|
+
violations = 0
|
|
181
|
+
for rule in RULES:
|
|
182
|
+
response, error = _search(rule["pattern"], text)
|
|
183
|
+
if error is not None:
|
|
184
|
+
print(
|
|
185
|
+
f"ERROR: {rule['kind']} pattern {rule['pattern']!r} could not "
|
|
186
|
+
f"be evaluated safely: {error}",
|
|
187
|
+
file=sys.stderr,
|
|
188
|
+
)
|
|
189
|
+
return 2
|
|
190
|
+
matched = response["matched"]
|
|
191
|
+
if rule["kind"] == "require_pattern":
|
|
192
|
+
if not matched:
|
|
193
|
+
print(f"VIOLATION: {rule['message']}", file=sys.stderr)
|
|
194
|
+
violations += 1
|
|
195
|
+
elif matched:
|
|
196
|
+
print(
|
|
197
|
+
f"VIOLATION line {response['line']}: {rule['message']}",
|
|
198
|
+
file=sys.stderr,
|
|
199
|
+
)
|
|
200
|
+
print(f" {response['snippet']}", file=sys.stderr)
|
|
201
|
+
violations += 1
|
|
202
|
+
return 1 if violations else 0
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
if __name__ == "__main__":
|
|
206
|
+
if len(sys.argv) == 2 and sys.argv[1] == "--regex-worker":
|
|
207
|
+
raise SystemExit(_regex_worker())
|
|
208
|
+
raise SystemExit(main())
|
|
209
|
+
"""
|
|
210
|
+
return template.replace("__ADR_ID__", adr_id).replace(
|
|
211
|
+
"__RULES__",
|
|
212
|
+
json.dumps(rules, indent=2, ensure_ascii=False),
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def generate_shell_script(adr_id: str, rules: List[Dict]) -> str:
|
|
217
|
+
"""Generate a POSIX launcher for the parity-preserving Python validator."""
|
|
218
|
+
del rules
|
|
219
|
+
return f"""\
|
|
220
|
+
#!/bin/bash
|
|
221
|
+
# Generated by adr-kit for {adr_id}. Do not edit manually.
|
|
222
|
+
# Launches the bounded Python validator so regex semantics remain identical.
|
|
223
|
+
# Usage: cat file.py | bash validate.sh
|
|
224
|
+
# Exit 0 = clean, exit 1 = violations, exit 2 = incomplete enforcement.
|
|
225
|
+
|
|
226
|
+
set -euo pipefail
|
|
227
|
+
|
|
228
|
+
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
|
229
|
+
if command -v python3 >/dev/null 2>&1; then
|
|
230
|
+
PYTHON=python3
|
|
231
|
+
elif command -v python >/dev/null 2>&1; then
|
|
232
|
+
PYTHON=python
|
|
233
|
+
else
|
|
234
|
+
printf '%s\\n' '[adr-validate] ERROR: Python 3.10+ is required.' >&2
|
|
235
|
+
exit 2
|
|
236
|
+
fi
|
|
237
|
+
exec "$PYTHON" "$SCRIPT_DIR/validate.py"
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _make_executable(path: Path) -> None:
|
|
242
|
+
"""Add user-execute bit to path. No-op on Windows.
|
|
243
|
+
|
|
244
|
+
Deliberately user-only (S_IXUSR) — generated scripts may live in shared
|
|
245
|
+
work-trees; world/group +x is unnecessary and a mild SEC concern.
|
|
246
|
+
"""
|
|
247
|
+
try:
|
|
248
|
+
import stat
|
|
249
|
+
current = path.stat().st_mode
|
|
250
|
+
path.chmod(current | stat.S_IXUSR)
|
|
251
|
+
except (AttributeError, NotImplementedError):
|
|
252
|
+
pass # Windows — chmod is a no-op
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def generate_scripts_for_adr(
|
|
256
|
+
adr_id: str,
|
|
257
|
+
enforcement: Dict,
|
|
258
|
+
output_dir: Path,
|
|
259
|
+
langs: List[str],
|
|
260
|
+
) -> Tuple[List[Path], List[str]]:
|
|
261
|
+
"""Generate scripts plus capability metadata for one ADR."""
|
|
262
|
+
rules, unsupported = _collect_rules(enforcement)
|
|
263
|
+
if not rules and not unsupported:
|
|
264
|
+
return [], []
|
|
265
|
+
|
|
266
|
+
adr_output = output_dir / adr_id
|
|
267
|
+
adr_output.mkdir(parents=True, exist_ok=True)
|
|
268
|
+
|
|
269
|
+
capabilities = {
|
|
270
|
+
"schema_version": 1,
|
|
271
|
+
"adr_id": adr_id,
|
|
272
|
+
"status": "unsupported" if unsupported else "supported",
|
|
273
|
+
"rule_types": sorted({rule["kind"] for rule in rules}),
|
|
274
|
+
"regex_engine": "python-re-isolated-subprocess",
|
|
275
|
+
"regex_timeout_seconds": 1.0,
|
|
276
|
+
"max_input_bytes": 2 * 1024 * 1024,
|
|
277
|
+
"path_scope": False,
|
|
278
|
+
"shell_mode": "python-launcher" if "shell" in langs else None,
|
|
279
|
+
"unsupported": unsupported,
|
|
280
|
+
}
|
|
281
|
+
capability_path = adr_output / "capabilities.json"
|
|
282
|
+
capability_path.write_text(
|
|
283
|
+
json.dumps(capabilities, indent=2, ensure_ascii=False) + "\n",
|
|
284
|
+
encoding="utf-8",
|
|
285
|
+
)
|
|
286
|
+
written = [capability_path]
|
|
287
|
+
if unsupported:
|
|
288
|
+
return written, unsupported
|
|
289
|
+
|
|
290
|
+
if "python" in langs or "shell" in langs:
|
|
291
|
+
p = adr_output / "validate.py"
|
|
292
|
+
p.write_text(generate_python_script(adr_id, rules), encoding="utf-8")
|
|
293
|
+
_make_executable(p)
|
|
294
|
+
written.append(p)
|
|
295
|
+
|
|
296
|
+
if "shell" in langs:
|
|
297
|
+
p = adr_output / "validate.sh"
|
|
298
|
+
p.write_bytes(generate_shell_script(adr_id, rules).encode("utf-8"))
|
|
299
|
+
_make_executable(p)
|
|
300
|
+
written.append(p)
|
|
301
|
+
|
|
302
|
+
return written, []
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def main() -> int:
|
|
306
|
+
parser = argparse.ArgumentParser(
|
|
307
|
+
description="Generate standalone ADR enforcement validation scripts."
|
|
308
|
+
)
|
|
309
|
+
parser.add_argument(
|
|
310
|
+
"--output",
|
|
311
|
+
type=Path,
|
|
312
|
+
default=Path(".generated"),
|
|
313
|
+
help="Output directory (default: .generated)",
|
|
314
|
+
)
|
|
315
|
+
parser.add_argument(
|
|
316
|
+
"--lang",
|
|
317
|
+
choices=["python", "shell", "all"],
|
|
318
|
+
default="all",
|
|
319
|
+
help="Language(s) to generate (default: all)",
|
|
320
|
+
)
|
|
321
|
+
parser.add_argument(
|
|
322
|
+
"--adr-dir",
|
|
323
|
+
type=Path,
|
|
324
|
+
default=None,
|
|
325
|
+
help="Directory containing ADR-*.md files (default: docs/adr)",
|
|
326
|
+
)
|
|
327
|
+
parser.add_argument(
|
|
328
|
+
"adr_dir_positional",
|
|
329
|
+
nargs="?",
|
|
330
|
+
default=None,
|
|
331
|
+
metavar="adr_dir",
|
|
332
|
+
help="Directory containing ADR-*.md files (positional alternative to --adr-dir)",
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
args = parser.parse_args()
|
|
336
|
+
|
|
337
|
+
# Resolve ADR dir: --adr-dir wins over positional, then default.
|
|
338
|
+
if args.adr_dir is not None:
|
|
339
|
+
adr_dir = args.adr_dir
|
|
340
|
+
elif args.adr_dir_positional is not None:
|
|
341
|
+
adr_dir = Path(args.adr_dir_positional)
|
|
342
|
+
else:
|
|
343
|
+
adr_dir = Path("docs/adr")
|
|
344
|
+
|
|
345
|
+
if args.lang == "all":
|
|
346
|
+
langs = ["python", "shell"]
|
|
347
|
+
else:
|
|
348
|
+
langs = [args.lang]
|
|
349
|
+
|
|
350
|
+
output_dir = args.output
|
|
351
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
352
|
+
|
|
353
|
+
if not adr_dir.is_dir():
|
|
354
|
+
print(f"[adr-generate-scripts] ERROR: ADR directory not found: {adr_dir}", file=sys.stderr)
|
|
355
|
+
return 2
|
|
356
|
+
|
|
357
|
+
adr_files = sorted(adr_dir.glob("ADR-*.md"))
|
|
358
|
+
if not adr_files:
|
|
359
|
+
print(f"[adr-generate-scripts] No ADR-*.md files found in {adr_dir}", file=sys.stderr)
|
|
360
|
+
return 0
|
|
361
|
+
|
|
362
|
+
total_written: List[Path] = []
|
|
363
|
+
skipped_no_enforcement = 0
|
|
364
|
+
skipped_no_rules = 0
|
|
365
|
+
errors = 0
|
|
366
|
+
|
|
367
|
+
for adr_path in adr_files:
|
|
368
|
+
adr_id = adr_id_from_filename(adr_path.name)
|
|
369
|
+
if not adr_id:
|
|
370
|
+
continue
|
|
371
|
+
|
|
372
|
+
try:
|
|
373
|
+
content = adr_path.read_text(encoding="utf-8")
|
|
374
|
+
except OSError as e:
|
|
375
|
+
print(f"[adr-generate-scripts] WARN: cannot read {adr_path}: {e}", file=sys.stderr)
|
|
376
|
+
errors += 1
|
|
377
|
+
continue
|
|
378
|
+
|
|
379
|
+
try:
|
|
380
|
+
enforcement = extract_enforcement(content)
|
|
381
|
+
except ValueError as e:
|
|
382
|
+
print(f"[adr-generate-scripts] WARN: {adr_path.name}: {e}", file=sys.stderr)
|
|
383
|
+
errors += 1
|
|
384
|
+
continue
|
|
385
|
+
|
|
386
|
+
if enforcement is None:
|
|
387
|
+
skipped_no_enforcement += 1
|
|
388
|
+
continue
|
|
389
|
+
|
|
390
|
+
written, unsupported = generate_scripts_for_adr(
|
|
391
|
+
adr_id, enforcement, output_dir, langs
|
|
392
|
+
)
|
|
393
|
+
if unsupported:
|
|
394
|
+
print(
|
|
395
|
+
f"[adr-generate-scripts] ERROR: {adr_path.name}: standalone "
|
|
396
|
+
f"validator cannot preserve: {', '.join(unsupported)}; see "
|
|
397
|
+
f"{output_dir / adr_id / 'capabilities.json'}",
|
|
398
|
+
file=sys.stderr,
|
|
399
|
+
)
|
|
400
|
+
errors += 1
|
|
401
|
+
total_written.extend(written)
|
|
402
|
+
continue
|
|
403
|
+
if not written:
|
|
404
|
+
skipped_no_rules += 1
|
|
405
|
+
continue
|
|
406
|
+
|
|
407
|
+
total_written.extend(written)
|
|
408
|
+
for p in written:
|
|
409
|
+
print(f" generated {p}")
|
|
410
|
+
|
|
411
|
+
print(
|
|
412
|
+
f"\n[adr-generate-scripts] done: {len(total_written)} file(s) written, "
|
|
413
|
+
f"{skipped_no_enforcement} ADR(s) without Enforcement skipped, "
|
|
414
|
+
f"{skipped_no_rules} ADR(s) with no forbid rules skipped"
|
|
415
|
+
+ (f", {errors} error(s)" if errors else "")
|
|
416
|
+
)
|
|
417
|
+
return 0 if errors == 0 else 2
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
if __name__ == "__main__":
|
|
421
|
+
sys.exit(main())
|