easy-coding-harness 0.10.0-beta.1 → 0.10.0-beta.3

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.
@@ -0,0 +1,306 @@
1
+ #!/usr/bin/env python3
2
+ """Record and verify Easy Coding Java TDD infrastructure readiness.
3
+
4
+ This tool validates infrastructure only. It never measures repository-wide coverage and never
5
+ creates business tests. Coverage acceptance remains scoped to production lines changed after a
6
+ task's frozen baseline.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import re
16
+ import shlex
17
+ import sys
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+
21
+ SCHEMA = "easy-coding/tdd-readiness-v1"
22
+ COVERAGE_SCOPE = "changed-production-lines"
23
+ RECEIPT = Path(".easy-coding/tdd/readiness.json")
24
+ TDD_BASE_VARIABLE = "EASY_CODING_TDD_BASE_SHA"
25
+ TDD_THRESHOLD_VARIABLE = "EASY_CODING_TDD_THRESHOLD"
26
+ COVERAGE_TOOL_PATH = ".easy-coding/tools/easy_coding_java_coverage.py"
27
+ JAVA_BUILD_FILE_NAMES = {"pom.xml", "build.gradle", "build.gradle.kts"}
28
+ GITLAB_CI_ENTRY_FILES = {".gitlab-ci.yml", ".gitlab-ci.yaml"}
29
+
30
+
31
+ class ReadinessError(RuntimeError):
32
+ pass
33
+
34
+
35
+ def sha256(path: Path) -> str:
36
+ digest = hashlib.sha256()
37
+ with path.open("rb") as handle:
38
+ for chunk in iter(lambda: handle.read(65536), b""):
39
+ digest.update(chunk)
40
+ return digest.hexdigest()
41
+
42
+
43
+ def project_file(root: Path, value: str) -> tuple[str, Path]:
44
+ candidate = Path(value)
45
+ if candidate.is_absolute():
46
+ resolved = candidate.resolve()
47
+ else:
48
+ resolved = (root / candidate).resolve()
49
+ try:
50
+ relative = resolved.relative_to(root.resolve()).as_posix()
51
+ except ValueError as error:
52
+ raise ReadinessError(f"Path escapes project root: {value}") from error
53
+ if not resolved.is_file():
54
+ raise ReadinessError(f"Required file is missing: {relative}")
55
+ return relative, resolved
56
+
57
+
58
+ def file_record(root: Path, value: str) -> dict[str, str]:
59
+ relative, resolved = project_file(root, value)
60
+ return {"path": relative, "sha256": sha256(resolved)}
61
+
62
+
63
+ def safe_report_pattern(value: str) -> bool:
64
+ candidate = Path(value)
65
+ return bool(value.strip()) and not candidate.is_absolute() and ".." not in candidate.parts
66
+
67
+
68
+ def required_gate_variables(command: str) -> bool:
69
+ try:
70
+ tokens = shlex.split(command)
71
+ except ValueError:
72
+ return False
73
+ options: dict[str, str] = {}
74
+ for index, token in enumerate(tokens[:-1]):
75
+ if token in {"--base", "--threshold"}:
76
+ options[token] = tokens[index + 1]
77
+ return options.get("--base") in {
78
+ f"${TDD_BASE_VARIABLE}",
79
+ "$" + "{" + TDD_BASE_VARIABLE + "}",
80
+ } and options.get("--threshold") in {
81
+ f"${TDD_THRESHOLD_VARIABLE}",
82
+ "$" + "{" + TDD_THRESHOLD_VARIABLE + "}",
83
+ }
84
+
85
+
86
+ def ci_contract_reasons(contents: list[str]) -> list[str]:
87
+ combined = "\n".join(
88
+ re.sub(r"\s+#.*$", "", re.sub(r"^\s*#.*$", "", line))
89
+ for line in "\n".join(contents).splitlines()
90
+ )
91
+ lowered = combined.lower()
92
+ reasons: list[str] = []
93
+ for marker in (
94
+ "jacoco",
95
+ "artifacts",
96
+ COVERAGE_TOOL_PATH,
97
+ TDD_BASE_VARIABLE,
98
+ TDD_THRESHOLD_VARIABLE,
99
+ ):
100
+ if marker.lower() not in lowered:
101
+ reasons.append(f"CI files do not contain required marker: {marker}")
102
+ if not required_gate_variables(combined):
103
+ reasons.append(
104
+ "CI changed-line gate must use the task baseline and threshold variables"
105
+ )
106
+ if re.search(r"(?:^|\n)\s*stage\s*:\s*['\"]?test['\"]?\s*(?:#.*)?(?:\n|$)", combined, re.I) is None:
107
+ reasons.append("CI files do not declare a TEST-stage job")
108
+ return reasons
109
+
110
+
111
+ def parse_records(root: Path, value: object, field: str, reasons: list[str]) -> list[str]:
112
+ if not isinstance(value, list) or not value:
113
+ reasons.append(f"{field} must contain at least one file")
114
+ return []
115
+ contents: list[str] = []
116
+ for item in value:
117
+ if not isinstance(item, dict):
118
+ reasons.append(f"{field} contains an invalid record")
119
+ continue
120
+ file_name = item.get("path")
121
+ expected = item.get("sha256")
122
+ if not isinstance(file_name, str) or not isinstance(expected, str):
123
+ reasons.append(f"{field} contains an invalid path or SHA-256")
124
+ continue
125
+ try:
126
+ _, resolved = project_file(root, file_name)
127
+ if sha256(resolved) != expected:
128
+ reasons.append(f"readiness file changed: {file_name}")
129
+ contents.append(resolved.read_text(encoding="utf-8"))
130
+ except (OSError, UnicodeError, ReadinessError) as error:
131
+ reasons.append(str(error))
132
+ return contents
133
+
134
+
135
+ def inspect(root: Path) -> dict[str, object]:
136
+ receipt = root / RECEIPT
137
+ if not receipt.is_file():
138
+ return {
139
+ "status": "needs_init",
140
+ "coverage_scope": COVERAGE_SCOPE,
141
+ "reasons": ["TDD readiness receipt is missing"],
142
+ "receipt": RECEIPT.as_posix(),
143
+ }
144
+ try:
145
+ manifest = json.loads(receipt.read_text(encoding="utf-8"))
146
+ except (OSError, UnicodeError, json.JSONDecodeError):
147
+ return {
148
+ "status": "needs_init",
149
+ "coverage_scope": COVERAGE_SCOPE,
150
+ "reasons": ["TDD readiness receipt is invalid"],
151
+ "receipt": RECEIPT.as_posix(),
152
+ }
153
+
154
+ reasons: list[str] = []
155
+ if not isinstance(manifest, dict):
156
+ reasons.append("TDD readiness receipt must be a JSON object")
157
+ manifest = {}
158
+ if manifest.get("schema") != SCHEMA:
159
+ reasons.append("unsupported readiness schema")
160
+ if manifest.get("provider") != "gitlab":
161
+ reasons.append("readiness provider must be gitlab")
162
+ if manifest.get("coverage_scope") != COVERAGE_SCOPE:
163
+ reasons.append("coverage scope must be changed-production-lines")
164
+ if manifest.get("historical_coverage_required") is not False:
165
+ reasons.append("historical coverage must remain disabled")
166
+ patterns = manifest.get("coverage_report_patterns")
167
+ if not isinstance(patterns, list) or not patterns or not all(
168
+ isinstance(item, str) and safe_report_pattern(item) for item in patterns
169
+ ):
170
+ reasons.append(
171
+ "coverage_report_patterns must contain safe project-relative report patterns"
172
+ )
173
+ gate = manifest.get("changed_line_gate_command")
174
+ if not isinstance(gate, str) or COVERAGE_TOOL_PATH not in gate:
175
+ reasons.append("changed-line coverage gate command is missing")
176
+ elif not required_gate_variables(gate):
177
+ reasons.append(
178
+ "changed-line coverage gate must use the task baseline and threshold variables"
179
+ )
180
+
181
+ manifest_build_files = manifest.get("build_files")
182
+ manifest_ci_files = manifest.get("ci_files")
183
+ manifest_tool_files = manifest.get("tool_files")
184
+ build_contents = parse_records(root, manifest_build_files, "build_files", reasons)
185
+ ci_contents = parse_records(root, manifest_ci_files, "ci_files", reasons)
186
+ parse_records(root, manifest_tool_files, "tool_files", reasons)
187
+ build_paths = {
188
+ Path(item.get("path", "")).name
189
+ for item in manifest_build_files
190
+ if isinstance(item, dict) and isinstance(item.get("path"), str)
191
+ } if isinstance(manifest_build_files, list) else set()
192
+ ci_paths = {
193
+ item.get("path", "").replace("\\", "/")
194
+ for item in manifest_ci_files
195
+ if isinstance(item, dict) and isinstance(item.get("path"), str)
196
+ } if isinstance(manifest_ci_files, list) else set()
197
+ if not build_paths.intersection(JAVA_BUILD_FILE_NAMES):
198
+ reasons.append("build_files must include a Maven or Gradle Java build file")
199
+ if not ci_paths.intersection(GITLAB_CI_ENTRY_FILES):
200
+ reasons.append("ci_files must include the project-root GitLab CI entry file")
201
+ tool_paths = {
202
+ item.get("path", "").replace("\\", "/")
203
+ for item in manifest_tool_files
204
+ if isinstance(item, dict) and isinstance(item.get("path"), str)
205
+ } if isinstance(manifest_tool_files, list) else set()
206
+ if COVERAGE_TOOL_PATH not in tool_paths:
207
+ reasons.append(f"tool_files must include {COVERAGE_TOOL_PATH}")
208
+ if not any("jacoco" in content.lower() for content in build_contents):
209
+ reasons.append("build files do not configure JaCoCo")
210
+ reasons.extend(ci_contract_reasons(ci_contents))
211
+
212
+ return {
213
+ "status": "ready" if not reasons else "needs_init",
214
+ "coverage_scope": COVERAGE_SCOPE,
215
+ "reasons": list(dict.fromkeys(reasons)),
216
+ "receipt": RECEIPT.as_posix(),
217
+ }
218
+
219
+
220
+ def record(args: argparse.Namespace, root: Path) -> dict[str, object]:
221
+ if not args.build_file:
222
+ raise ReadinessError("At least one --build-file is required.")
223
+ if not args.ci_file:
224
+ raise ReadinessError("At least one --ci-file is required.")
225
+ if not args.coverage_report:
226
+ raise ReadinessError("At least one --coverage-report is required.")
227
+ if not all(safe_report_pattern(value) for value in args.coverage_report):
228
+ raise ReadinessError("--coverage-report values must be safe project-relative patterns.")
229
+ if COVERAGE_TOOL_PATH not in args.gate_command:
230
+ raise ReadinessError(f"--gate-command must invoke {COVERAGE_TOOL_PATH}.")
231
+ if not required_gate_variables(args.gate_command):
232
+ raise ReadinessError(
233
+ "--gate-command must use $EASY_CODING_TDD_BASE_SHA and "
234
+ "$EASY_CODING_TDD_THRESHOLD."
235
+ )
236
+
237
+ build_records = [file_record(root, value) for value in args.build_file]
238
+ ci_records = [file_record(root, value) for value in args.ci_file]
239
+ tool_records = [file_record(root, COVERAGE_TOOL_PATH)]
240
+ if not any(Path(item["path"]).name in JAVA_BUILD_FILE_NAMES for item in build_records):
241
+ raise ReadinessError("--build-file must include pom.xml, build.gradle, or build.gradle.kts.")
242
+ if not any(item["path"] in GITLAB_CI_ENTRY_FILES for item in ci_records):
243
+ raise ReadinessError(
244
+ "--ci-file must include the project-root .gitlab-ci.yml or .gitlab-ci.yaml."
245
+ )
246
+ build_contents = [
247
+ (root / record_item["path"]).read_text(encoding="utf-8")
248
+ for record_item in build_records
249
+ ]
250
+ ci_contents = [
251
+ (root / record_item["path"]).read_text(encoding="utf-8") for record_item in ci_records
252
+ ]
253
+ if not any("jacoco" in content.lower() for content in build_contents):
254
+ raise ReadinessError("Build files must configure JaCoCo before readiness can be recorded.")
255
+ ci_reasons = ci_contract_reasons(ci_contents)
256
+ if ci_reasons:
257
+ raise ReadinessError("; ".join(ci_reasons))
258
+
259
+ manifest = {
260
+ "schema": SCHEMA,
261
+ "provider": "gitlab",
262
+ "coverage_scope": COVERAGE_SCOPE,
263
+ "generated_at": datetime.now(timezone.utc).isoformat(),
264
+ "generated_by": args.agent,
265
+ "build_files": build_records,
266
+ "ci_files": ci_records,
267
+ "tool_files": tool_records,
268
+ "coverage_report_patterns": args.coverage_report,
269
+ "changed_line_gate_command": args.gate_command,
270
+ "historical_coverage_required": False,
271
+ }
272
+ receipt = root / RECEIPT
273
+ receipt.parent.mkdir(parents=True, exist_ok=True)
274
+ temporary = receipt.with_suffix(f".tmp-{os.getpid()}")
275
+ temporary.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
276
+ temporary.replace(receipt)
277
+ result = inspect(root)
278
+ if result["status"] != "ready":
279
+ raise ReadinessError("Recorded readiness receipt did not pass validation.")
280
+ return result
281
+
282
+
283
+ def main() -> int:
284
+ parser = argparse.ArgumentParser(description="Easy Coding Java TDD readiness tool")
285
+ parser.add_argument("--cwd", default=".")
286
+ subcommands = parser.add_subparsers(dest="command", required=True)
287
+ subcommands.add_parser("check")
288
+ record_parser = subcommands.add_parser("record")
289
+ record_parser.add_argument("--build-file", action="append", default=[])
290
+ record_parser.add_argument("--ci-file", action="append", default=[])
291
+ record_parser.add_argument("--coverage-report", action="append", default=[])
292
+ record_parser.add_argument("--gate-command", required=True)
293
+ record_parser.add_argument("--agent", required=True)
294
+ args = parser.parse_args()
295
+ root = Path(args.cwd).resolve()
296
+ try:
297
+ result = inspect(root) if args.command == "check" else record(args, root)
298
+ except (OSError, UnicodeError, ReadinessError) as error:
299
+ print(json.dumps({"status": "needs_init", "reasons": [str(error)]}, ensure_ascii=False))
300
+ return 2
301
+ print(json.dumps(result, ensure_ascii=False))
302
+ return 0 if result["status"] == "ready" else 1
303
+
304
+
305
+ if __name__ == "__main__":
306
+ raise SystemExit(main())