cyber-agent-kit 0.0.1__py3-none-any.whl

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.
cyb/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
cyb/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
cyb/cli.py ADDED
@@ -0,0 +1,297 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from datetime import datetime, timezone
7
+
8
+ from .config import load_config
9
+ from .findings import SORTS, load_findings, sort_findings
10
+ from .insights import compare_runs, project_summaries, run_metrics
11
+ from .runs import discover_runs, find_run
12
+ from .verify import build_payload, exit_code
13
+
14
+
15
+ def _roots():
16
+ return load_config()["lab_roots"]
17
+
18
+
19
+ def cmd_runs(args) -> int:
20
+ runs = discover_runs(_roots())
21
+ if args.project:
22
+ runs = [run for run in runs if run.root.name == args.project]
23
+ metrics = [run_metrics(run) for run in runs]
24
+ if args.json:
25
+ print(json.dumps(metrics, ensure_ascii=False, indent=2))
26
+ return 0
27
+ if not runs:
28
+ print("no runs found; set CYB_LAB_ROOT or lab_roots in config", file=sys.stderr)
29
+ return 2
30
+ print(f"{'run':<20} {'project':<22} {'verdict':<8} {'stages':<12} {'crit':>4} {'high':>4}")
31
+ for item in metrics:
32
+ stages = f"{item['passed']}/{item['stages']}"
33
+ if item["skipped"]:
34
+ stages += f" (+{item['skipped']} skip)"
35
+ print(
36
+ f"{item['run_id']:<20} {item['project']:<22} {item['verdict']:<8} {stages:<12}"
37
+ f" {item['totals']['CRITICAL']:>4} {item['totals']['HIGH']:>4}"
38
+ )
39
+ return 0
40
+
41
+
42
+ def cmd_projects(args) -> int:
43
+ summaries = project_summaries(discover_runs(_roots()))
44
+ if args.json:
45
+ print(json.dumps(summaries, ensure_ascii=False, indent=2))
46
+ return 0
47
+ if not summaries:
48
+ print("no projects found", file=sys.stderr)
49
+ return 2
50
+ print(f"{'project':<22} {'runs':>4} {'latest':<18} {'verdict':<8} {'crit':>4} {'high':>4}")
51
+ for item in summaries:
52
+ print(
53
+ f"{item['project']:<22} {item['runs']:>4} {item['latest']:<18} {item['verdict']:<8}"
54
+ f" {item['critical']:>4} {item['high']:>4}"
55
+ )
56
+ return 0
57
+
58
+
59
+ def cmd_findings(args) -> int:
60
+ run = find_run(_roots(), args.run)
61
+ if run is None:
62
+ print("run not found", file=sys.stderr)
63
+ return 2
64
+ items = []
65
+ for source, values in load_findings(run).items():
66
+ if args.source and source != args.source:
67
+ continue
68
+ for item in values:
69
+ if args.severity and item.get("severity") != args.severity:
70
+ continue
71
+ if args.query:
72
+ needle = args.query.lower()
73
+ haystack = " ".join(
74
+ str(item.get(key, "")) for key in ("title", "message", "package", "file", "rule", "cve", "url")
75
+ ).lower()
76
+ if needle not in haystack:
77
+ continue
78
+ items.append(item)
79
+ if args.dedupe:
80
+ seen = set()
81
+ unique = []
82
+ for item in items:
83
+ key = (
84
+ item.get("cve") or item.get("rule") or item.get("id"),
85
+ item.get("package") or item.get("file") or item.get("url"),
86
+ )
87
+ if key in seen:
88
+ continue
89
+ seen.add(key)
90
+ unique.append(item)
91
+ items = unique
92
+ items = sort_findings(items, args.sort)
93
+ shown = items[: args.limit]
94
+ if args.json:
95
+ print(
96
+ json.dumps(
97
+ {
98
+ "run_id": run.run_id,
99
+ "filters": {"source": args.source, "severity": args.severity, "q": args.query, "sort": args.sort},
100
+ "total": len(items),
101
+ "findings": shown,
102
+ },
103
+ ensure_ascii=False,
104
+ indent=2,
105
+ )
106
+ )
107
+ return 0
108
+ print(f"run {run.run_id} | {len(items)} matching findings (showing {len(shown)})")
109
+ for item in shown:
110
+ location = item.get("package") or item.get("file") or item.get("url") or item.get("rule") or ""
111
+ print(f" {item['severity']:<8} {item['source']:<6} {item['title'][:64]:<64} {location} {item['id']}")
112
+ return 0
113
+
114
+
115
+ def cmd_compare(args) -> int:
116
+ roots = _roots()
117
+ a = find_run(roots, args.a)
118
+ b = find_run(roots, args.b)
119
+ if a is None or b is None:
120
+ print("run not found", file=sys.stderr)
121
+ return 2
122
+ payload = compare_runs(a, b)
123
+ if args.json:
124
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
125
+ return 0
126
+ ma, mb, delta = payload["a"], payload["b"], payload["delta"]
127
+ if not payload["same_project"]:
128
+ print(f"warning: comparing across projects ({ma['project']} vs {mb['project']})", file=sys.stderr)
129
+ print(f"{'metric':<12} {ma['run_id']:<18} {mb['run_id']:<18} delta")
130
+ for label, key, delta_key in (
131
+ ("findings", "findings", "findings"),
132
+ ("failed", "failed", "failed_stages"),
133
+ ):
134
+ print(f"{label:<12} {ma[key]:<18} {mb[key]:<18} {delta[delta_key]:+d}")
135
+ for severity in ("CRITICAL", "HIGH"):
136
+ print(
137
+ f"{severity.lower():<12} {ma['totals'][severity]:<18} {mb['totals'][severity]:<18}"
138
+ f" {delta[severity.lower()]:+d}"
139
+ )
140
+ return 0
141
+
142
+
143
+ def cmd_verify(args) -> int:
144
+ config = load_config()
145
+ run = find_run(config["lab_roots"], args.run)
146
+ if run is None:
147
+ print("run not found", file=sys.stderr)
148
+ return 2
149
+ payload = build_payload(run, config.get("policy_level", "L0"))
150
+ if args.record:
151
+ _record(config, payload)
152
+ if args.json:
153
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
154
+ else:
155
+ metrics = run_metrics(run)
156
+ print(f"run {payload['run_id']} ({metrics['project']})")
157
+ print(f"verdict {payload['verdict']}")
158
+ print(
159
+ f"stages {metrics['passed']} passed | {metrics['failed']} failed | "
160
+ f"{metrics['skipped']} skipped"
161
+ )
162
+ for stage in payload["stages"]:
163
+ print(f" {stage['name']:<9} {stage['status']}")
164
+ for source, counts in payload["findings"].items():
165
+ print(
166
+ f" {source:<9} total={counts['total']} CRITICAL={counts['CRITICAL']} HIGH={counts['HIGH']}"
167
+ )
168
+ for failure in payload["gate_failures"]:
169
+ print(f" gate: {failure}")
170
+ return exit_code(payload)
171
+
172
+
173
+ def _record(config, payload) -> None:
174
+ line = {
175
+ "at": datetime.now(timezone.utc).isoformat(),
176
+ "run_id": payload["run_id"],
177
+ "verdict": payload["verdict"],
178
+ "policy": payload["policy"],
179
+ "gate_failures": payload["gate_failures"],
180
+ }
181
+ path = config["config_path"].parent / "audit.jsonl"
182
+ path.parent.mkdir(parents=True, exist_ok=True)
183
+ with open(path, "a", encoding="utf-8") as handle:
184
+ handle.write(json.dumps(line, ensure_ascii=False) + "\n")
185
+
186
+
187
+ def _code_context(run, item) -> str:
188
+ from .context import code_context
189
+
190
+ return "\n".join(code_context(run, item))
191
+
192
+
193
+ def cmd_explain(args) -> int:
194
+ run = find_run(_roots(), args.run)
195
+ if run is None:
196
+ print("run not found", file=sys.stderr)
197
+ return 2
198
+ for items in load_findings(run).values():
199
+ for item in items:
200
+ if item["id"] == args.finding:
201
+ print(json.dumps(item, ensure_ascii=False, indent=2))
202
+ context = _code_context(run, item)
203
+ if context:
204
+ print(context)
205
+ return 0
206
+ print("finding not found", file=sys.stderr)
207
+ return 2
208
+
209
+
210
+ def cmd_doctor(args) -> int:
211
+ config = load_config()
212
+ print(f"config {config['config_path']}")
213
+ if not config["lab_roots"]:
214
+ print("lab roots none; set CYB_LAB_ROOT or config lab_roots", file=sys.stderr)
215
+ return 2
216
+ for root in config["lab_roots"]:
217
+ runs = discover_runs([root])
218
+ latest = runs[0].run_id if runs else "-"
219
+ print(f"root {root} runs={len(runs)} latest={latest}")
220
+ print("status ok")
221
+ return 0
222
+
223
+
224
+ def cmd_audit(args) -> int:
225
+ config = load_config()
226
+ print("network none (local files only)")
227
+ print("binds 127.0.0.1 (cyb serve)")
228
+ print("deps none (python stdlib)")
229
+ for root in config["lab_roots"]:
230
+ print(f"reads {root}")
231
+ print(f"writes {config['config_path'].parent / 'audit.jsonl'} (only with verify --record)")
232
+ return 0
233
+
234
+
235
+ def cmd_serve(args) -> int:
236
+ from .server import serve
237
+
238
+ return serve(port=args.port, run_id=args.run)
239
+
240
+
241
+ def build_parser() -> argparse.ArgumentParser:
242
+ parser = argparse.ArgumentParser(prog="cyb", description="Read-only CLI over cyber-flow pipeline runs")
243
+ sub = parser.add_subparsers(dest="command", required=True)
244
+
245
+ runs = sub.add_parser("runs", help="list local pipeline runs")
246
+ runs.add_argument("--project", help="filter by project (root directory name)")
247
+ runs.add_argument("--json", action="store_true")
248
+ runs.set_defaults(func=cmd_runs)
249
+
250
+ projects = sub.add_parser("projects", help="per-project rollup")
251
+ projects.add_argument("--json", action="store_true")
252
+ projects.set_defaults(func=cmd_projects)
253
+
254
+ findings = sub.add_parser("findings", help="list findings for a run with filters")
255
+ findings.add_argument("--run")
256
+ findings.add_argument("--source")
257
+ findings.add_argument("--severity")
258
+ findings.add_argument("--q", dest="query")
259
+ findings.add_argument("--sort", choices=SORTS, default="severity")
260
+ findings.add_argument("--limit", type=int, default=20)
261
+ findings.add_argument("--dedupe", action="store_true", help="collapse duplicate CVE/rule across targets")
262
+ findings.add_argument("--json", action="store_true")
263
+ findings.set_defaults(func=cmd_findings)
264
+
265
+ compare = sub.add_parser("compare", help="compare two runs")
266
+ compare.add_argument("a")
267
+ compare.add_argument("b")
268
+ compare.add_argument("--json", action="store_true")
269
+ compare.set_defaults(func=cmd_compare)
270
+
271
+ verify = sub.add_parser("verify", help="aggregate scan and test results into a verdict")
272
+ verify.add_argument("--run")
273
+ verify.add_argument("--json", action="store_true")
274
+ verify.add_argument("--record", action="store_true", help="append the verdict to the local audit log")
275
+ verify.set_defaults(func=cmd_verify)
276
+
277
+ explain = sub.add_parser("explain", help="show one finding with local code context")
278
+ explain.add_argument("finding")
279
+ explain.add_argument("--run")
280
+ explain.set_defaults(func=cmd_explain)
281
+
282
+ serve = sub.add_parser("serve", help="local read-only dashboard")
283
+ serve.add_argument("--port", type=int, default=8766)
284
+ serve.add_argument("--run")
285
+ serve.set_defaults(func=cmd_serve)
286
+
287
+ doctor = sub.add_parser("doctor", help="check configuration and lab roots")
288
+ doctor.set_defaults(func=cmd_doctor)
289
+
290
+ audit = sub.add_parser("audit", help="print data-access inventory")
291
+ audit.set_defaults(func=cmd_audit)
292
+ return parser
293
+
294
+
295
+ def main(argv=None) -> int:
296
+ args = build_parser().parse_args(argv)
297
+ return args.func(args)
cyb/config.py ADDED
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+
7
+ APP_NAME = "cyber-agent-kit"
8
+
9
+
10
+ def default_config_path() -> Path:
11
+ base = os.environ.get("APPDATA")
12
+ root = Path(base) if base else Path.home() / ".config"
13
+ return root / APP_NAME / "config.json"
14
+
15
+
16
+ def discover_lab_roots() -> list[Path]:
17
+ candidates = []
18
+ env = os.environ.get("CYB_LAB_ROOT")
19
+ if env:
20
+ candidates.append(env)
21
+ cwd = Path.cwd()
22
+ candidates += [
23
+ cwd / "cyber-pipeline-lab",
24
+ cwd.parent / "cyber-pipeline-lab",
25
+ Path("D:/GitHub/cyber-pipeline-lab"),
26
+ ]
27
+ return [p for p in dict.fromkeys(Path(c) for c in candidates) if p.is_dir()]
28
+
29
+
30
+ def load_config() -> dict:
31
+ path = default_config_path()
32
+ data: dict = {}
33
+ if path.exists():
34
+ try:
35
+ data = json.loads(path.read_text(encoding="utf-8"))
36
+ except (OSError, json.JSONDecodeError):
37
+ data = {}
38
+ roots = [Path(r) for r in data.get("lab_roots", [])]
39
+ roots = [r for r in roots if r.is_dir()]
40
+ if not roots:
41
+ roots = discover_lab_roots()
42
+ policy_level = (data.get("policy") or {}).get("level", "L0")
43
+ return {"lab_roots": roots, "config_path": path, "policy_level": policy_level}
cyb/context.py ADDED
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+
6
+ def code_context(run, item, radius: int = 3) -> list[str]:
7
+ file = item.get("file")
8
+ line = item.get("line")
9
+ if not file or not line:
10
+ return []
11
+ try:
12
+ root = Path(run.root).resolve()
13
+ target = (root / file).resolve()
14
+ target.relative_to(root)
15
+ lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
16
+ except (OSError, ValueError):
17
+ return []
18
+ line = int(line)
19
+ start = max(1, line - radius)
20
+ end = min(len(lines), line + radius)
21
+ return [f"{'>' if number == line else ' '} {number:>4} {lines[number - 1]}" for number in range(start, end + 1)]
cyb/findings.py ADDED
@@ -0,0 +1,168 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+
7
+ SEVERITIES = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO", "UNKNOWN"]
8
+ RANK = {severity: index for index, severity in enumerate(SEVERITIES)}
9
+ SORTS = ("severity", "source", "title")
10
+ SEVERITY_ALIASES = {"BLOCKER": "CRITICAL", "MAJOR": "MEDIUM", "MINOR": "LOW"}
11
+
12
+
13
+ def _read(path: Path):
14
+ try:
15
+ return json.loads(Path(path).read_text(encoding="utf-8"))
16
+ except (OSError, json.JSONDecodeError):
17
+ return None
18
+
19
+
20
+ def _id(*parts) -> str:
21
+ raw = "|".join("" if part is None else str(part) for part in parts)
22
+ return "f-" + hashlib.sha1(raw.encode("utf-8")).hexdigest()[:10]
23
+
24
+
25
+ def _line(text: str, limit: int = 260) -> str:
26
+ return " ".join((text or "").split())[:limit]
27
+
28
+
29
+ def _trivy(path: Path, source: str) -> list[dict]:
30
+ data = _read(path)
31
+ out = []
32
+ for result in (data or {}).get("Results") or []:
33
+ target = result.get("Target", "")
34
+ for vuln in result.get("Vulnerabilities") or []:
35
+ package = vuln.get("PkgName", "")
36
+ cve = vuln.get("VulnerabilityID", "")
37
+ fixed = vuln.get("FixedVersion") or ""
38
+ out.append(
39
+ {
40
+ "id": _id(source, cve, package, target),
41
+ "source": source,
42
+ "category": "dependency",
43
+ "severity": (vuln.get("Severity") or "UNKNOWN").upper(),
44
+ "title": f"{package} {vuln.get('InstalledVersion', '')} / {cve}",
45
+ "message": _line(vuln.get("Title") or vuln.get("Description", "")),
46
+ "package": package,
47
+ "version": vuln.get("InstalledVersion", ""),
48
+ "cve": cve,
49
+ "target": target,
50
+ "remediation_hint": f"upgrade {package} to >= {fixed}" if fixed else "",
51
+ }
52
+ )
53
+ return out
54
+
55
+
56
+ def _bandit(path: Path) -> list[dict]:
57
+ data = _read(path)
58
+ out = []
59
+ for issue in (data or {}).get("results") or []:
60
+ out.append(
61
+ {
62
+ "id": _id("sast", issue.get("test_id"), issue.get("filename"), issue.get("line_number")),
63
+ "source": "sast",
64
+ "category": "sast",
65
+ "severity": (issue.get("issue_severity") or "LOW").upper(),
66
+ "title": issue.get("test_name", ""),
67
+ "message": _line(issue.get("issue_text", "")),
68
+ "file": issue.get("filename", ""),
69
+ "line": issue.get("line_number"),
70
+ "rule": issue.get("test_id", ""),
71
+ "remediation_hint": "review and fix the flagged pattern",
72
+ }
73
+ )
74
+ return out
75
+
76
+
77
+ def _zap(path: Path) -> list[dict]:
78
+ data = _read(path)
79
+ out = []
80
+ for site in (data or {}).get("site") or []:
81
+ for alert in site.get("alerts") or []:
82
+ risk = int(alert.get("riskcode") or 0)
83
+ severity = {3: "HIGH", 2: "MEDIUM", 1: "LOW", 0: "INFO"}.get(risk, "INFO")
84
+ instances = alert.get("instances") or []
85
+ url = instances[0].get("uri", "") if instances else site.get("@name", "")
86
+ out.append(
87
+ {
88
+ "id": _id("dast", alert.get("pluginid"), url),
89
+ "source": "dast",
90
+ "category": "dast",
91
+ "severity": severity,
92
+ "title": alert.get("alert", ""),
93
+ "message": _line(alert.get("desc", "")),
94
+ "url": url,
95
+ "rule": str(alert.get("pluginid", "")),
96
+ "remediation_hint": _line(alert.get("solution", ""), 200),
97
+ }
98
+ )
99
+ return out
100
+
101
+
102
+ def _sonar(path: Path) -> list[dict]:
103
+ data = _read(path)
104
+ out = []
105
+ for issue in (data or {}).get("issues") or []:
106
+ component = issue.get("component", "")
107
+ file = component.split(":", 1)[1] if ":" in component else component
108
+ out.append(
109
+ {
110
+ "id": _id("sonar", issue.get("key")),
111
+ "source": "sonar",
112
+ "category": "sonar",
113
+ "severity": (issue.get("severity") or "MEDIUM").upper(),
114
+ "title": issue.get("rule", ""),
115
+ "message": _line(issue.get("message", "")),
116
+ "file": file,
117
+ "line": issue.get("line"),
118
+ "rule": issue.get("rule", ""),
119
+ "remediation_hint": "",
120
+ }
121
+ )
122
+ return out
123
+
124
+
125
+ def load_findings(run) -> dict[str, list[dict]]:
126
+ reports = run.reports
127
+ return {
128
+ "foss": _trivy(reports / "trivy-fs.json", "foss"),
129
+ "cont": _trivy(reports / "trivy-image.json", "cont"),
130
+ "sast": _bandit(reports / "bandit.json"),
131
+ "dast": _zap(reports / "zap.json"),
132
+ "sonar": _sonar(reports / "sonar-issues.json"),
133
+ }
134
+
135
+
136
+ def severity_counts(items) -> dict[str, int]:
137
+ counts = {severity: 0 for severity in SEVERITIES}
138
+ for item in items:
139
+ severity = item.get("severity", "UNKNOWN")
140
+ severity = SEVERITY_ALIASES.get(severity, severity)
141
+ counts[severity] = counts.get(severity, 0) + 1
142
+ return counts
143
+
144
+
145
+ def sort_by_severity(items) -> list[dict]:
146
+ return sorted(items, key=lambda item: (RANK.get(item.get("severity", "UNKNOWN"), 99), item.get("source", "")))
147
+
148
+
149
+ def sort_findings(items, key: str = "severity") -> list[dict]:
150
+ if key == "source":
151
+ return sorted(
152
+ items,
153
+ key=lambda item: (
154
+ item.get("source", ""),
155
+ RANK.get(item.get("severity", "UNKNOWN"), 99),
156
+ (item.get("title") or "").lower(),
157
+ ),
158
+ )
159
+ if key == "title":
160
+ return sorted(
161
+ items,
162
+ key=lambda item: (
163
+ (item.get("title") or "").lower(),
164
+ RANK.get(item.get("severity", "UNKNOWN"), 99),
165
+ item.get("source", ""),
166
+ ),
167
+ )
168
+ return sort_by_severity(items)
cyb/insights.py ADDED
@@ -0,0 +1,67 @@
1
+ from __future__ import annotations
2
+
3
+ from .findings import SEVERITIES, load_findings, severity_counts
4
+
5
+
6
+ def run_metrics(run) -> dict:
7
+ findings = load_findings(run)
8
+ counts = {source: severity_counts(items) for source, items in findings.items()}
9
+ totals = {
10
+ severity: sum(counts[source].get(severity, 0) for source in counts) for severity in SEVERITIES
11
+ }
12
+ stages = run.stage_map or {}
13
+ statuses = [(info or {}).get("status", "unknown") for info in stages.values()]
14
+ return {
15
+ "run_id": run.run_id,
16
+ "project": run.root.name,
17
+ "root": str(run.root),
18
+ "verdict": run.verdict,
19
+ "stages": len(stages),
20
+ "passed": statuses.count("pass"),
21
+ "failed": statuses.count("fail"),
22
+ "skipped": statuses.count("skipped"),
23
+ "findings": sum(len(items) for items in findings.values()),
24
+ "totals": totals,
25
+ "by_source": {
26
+ source: {"total": len(items), **counts[source]} for source, items in findings.items()
27
+ },
28
+ "gate_failures": run.gate.get("failures") or [],
29
+ }
30
+
31
+
32
+ def compare_runs(a, b) -> dict:
33
+ ma, mb = run_metrics(a), run_metrics(b)
34
+ return {
35
+ "a": ma,
36
+ "b": mb,
37
+ "delta": {
38
+ "findings": ma["findings"] - mb["findings"],
39
+ "critical": ma["totals"]["CRITICAL"] - mb["totals"]["CRITICAL"],
40
+ "high": ma["totals"]["HIGH"] - mb["totals"]["HIGH"],
41
+ "failed_stages": ma["failed"] - mb["failed"],
42
+ },
43
+ "same_project": ma["project"] == mb["project"],
44
+ }
45
+
46
+
47
+ def project_summaries(runs) -> list[dict]:
48
+ groups: dict[str, list] = {}
49
+ for run in runs:
50
+ groups.setdefault(run.root.name, []).append(run)
51
+ summaries = []
52
+ for project, project_runs in groups.items():
53
+ latest = project_runs[0]
54
+ metrics = run_metrics(latest)
55
+ summaries.append(
56
+ {
57
+ "project": project,
58
+ "root": str(latest.root),
59
+ "runs": len(project_runs),
60
+ "latest": latest.run_id,
61
+ "verdict": latest.verdict,
62
+ "critical": metrics["totals"]["CRITICAL"],
63
+ "high": metrics["totals"]["HIGH"],
64
+ }
65
+ )
66
+ summaries.sort(key=lambda item: item["project"])
67
+ return summaries
cyb/runs.py ADDED
@@ -0,0 +1,66 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+
7
+
8
+ @dataclass
9
+ class Run:
10
+ run_id: str
11
+ path: Path
12
+ root: Path
13
+
14
+ @property
15
+ def reports(self) -> Path:
16
+ return self.path / "reports"
17
+
18
+ def _json(self, name: str):
19
+ try:
20
+ return json.loads((self.path / name).read_text(encoding="utf-8"))
21
+ except (OSError, json.JSONDecodeError):
22
+ return None
23
+
24
+ @property
25
+ def state(self) -> dict:
26
+ return self._json("state.json") or {}
27
+
28
+ @property
29
+ def summary(self):
30
+ return self._json("reports/summary.json")
31
+
32
+ @property
33
+ def stage_map(self) -> dict:
34
+ summary = self.summary or {}
35
+ return summary.get("stages") or self.state.get("stages") or {}
36
+
37
+ @property
38
+ def verdict(self) -> str:
39
+ return (self.summary or {}).get("verdict") or "unknown"
40
+
41
+ @property
42
+ def gate(self) -> dict:
43
+ return (self.summary or {}).get("gate") or {}
44
+
45
+
46
+ def discover_runs(roots) -> list[Run]:
47
+ runs: list[Run] = []
48
+ for root in roots:
49
+ runs_dir = Path(root) / "runs"
50
+ if not runs_dir.is_dir():
51
+ continue
52
+ for entry in runs_dir.iterdir():
53
+ if entry.is_dir() and (entry / "reports").is_dir():
54
+ runs.append(Run(entry.name, entry, Path(root)))
55
+ runs.sort(key=lambda run: run.path.stat().st_mtime, reverse=True)
56
+ return runs
57
+
58
+
59
+ def find_run(roots, run_id: str | None = None) -> Run | None:
60
+ runs = discover_runs(roots)
61
+ if run_id:
62
+ for run in runs:
63
+ if run.run_id == run_id:
64
+ return run
65
+ return None
66
+ return runs[0] if runs else None