datapi-selfheal 0.3.0__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.
@@ -0,0 +1,145 @@
1
+ """Zero-dependency RS256 JWT minting for GitHub App authentication.
2
+
3
+ Implements just enough RSA (PKCS#1 v1.5 + SHA-256) and DER parsing to
4
+ sign GitHub App JWTs without adding a crypto dependency. Supports
5
+ PKCS#1 (``BEGIN RSA PRIVATE KEY``) and PKCS#8 (``BEGIN PRIVATE KEY``)
6
+ PEM keys.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import hashlib
13
+ import json
14
+ import re
15
+ import time
16
+ from typing import Any
17
+
18
+ _SHA256_DER_PREFIX = bytes.fromhex("3031300d060960864801650304020105000420")
19
+ _PEM_RE = re.compile(
20
+ r"-----BEGIN (?:RSA )?PRIVATE KEY-----([A-Za-z0-9+/=\s]+)-----END (?:RSA )?PRIVATE KEY-----"
21
+ )
22
+
23
+
24
+ class JwtError(ValueError):
25
+ """Raised when a private key cannot be parsed or a JWT cannot be minted."""
26
+
27
+
28
+ def _b64url(data: bytes) -> str:
29
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
30
+
31
+
32
+ def _read_tlv(data: bytes, offset: int) -> tuple[int, bytes, int]:
33
+ if offset >= len(data):
34
+ raise JwtError("DER: truncated tag")
35
+ tag = data[offset]
36
+ offset += 1
37
+ if offset >= len(data):
38
+ raise JwtError("DER: truncated length")
39
+ length_byte = data[offset]
40
+ offset += 1
41
+ if length_byte & 0x80 == 0:
42
+ length = length_byte
43
+ else:
44
+ num_len = length_byte & 0x7F
45
+ if num_len == 0 or num_len > 4 or offset + num_len > len(data):
46
+ raise JwtError("DER: invalid long-form length")
47
+ length = int.from_bytes(data[offset : offset + num_len], "big")
48
+ offset += num_len
49
+ if offset + length > len(data):
50
+ raise JwtError("DER: truncated value")
51
+ return tag, data[offset : offset + length], offset + length
52
+
53
+
54
+ def _der_int(value: bytes) -> int:
55
+ stripped = value.lstrip(b"\x00") or b"\x00"
56
+ return int.from_bytes(stripped, "big")
57
+
58
+
59
+ def _parse_pkcs1_rsakey(der: bytes) -> tuple[int, int, int]:
60
+ tag, seq, _ = _read_tlv(der, 0)
61
+ if tag != 0x30:
62
+ raise JwtError("DER: expected SEQUENCE for RSAPrivateKey")
63
+ offset = 0
64
+ fields: list[int] = []
65
+ while offset < len(seq) and len(fields) < 4:
66
+ ftag, fval, offset = _read_tlv(seq, offset)
67
+ if ftag != 0x02:
68
+ break
69
+ fields.append(_der_int(fval))
70
+ if len(fields) < 4:
71
+ raise JwtError("DER: RSAPrivateKey missing n/e/d")
72
+ _version, n, e, d = fields[0], fields[1], fields[2], fields[3]
73
+ return n, e, d
74
+
75
+
76
+ def _parse_private_key_der(der: bytes) -> tuple[int, int, int]:
77
+ tag, seq, _ = _read_tlv(der, 0)
78
+ if tag != 0x30:
79
+ raise JwtError("DER: expected SEQUENCE")
80
+ # PKCS#1 starts with INTEGER version; PKCS#8 starts with INTEGER version
81
+ # then an algorithm SEQUENCE then an OCTET STRING.
82
+ offset = 0
83
+ first_tag, _, next_off = _read_tlv(seq, offset)
84
+ second_tag, _, _ = _read_tlv(seq, next_off)
85
+ if first_tag == 0x02 and second_tag == 0x30:
86
+ # PKCS#8 PrivateKeyInfo: unwrap the privateKey OCTET STRING.
87
+ cursor = 0
88
+ pkcs8_fields: list[tuple[int, bytes]] = []
89
+ while cursor < len(seq):
90
+ ftag, fval, cursor = _read_tlv(seq, cursor)
91
+ pkcs8_fields.append((ftag, fval))
92
+ for ftag, fval in pkcs8_fields:
93
+ if ftag == 0x04:
94
+ return _parse_pkcs1_rsakey(fval)
95
+ raise JwtError("DER: PKCS#8 missing privateKey OCTET STRING")
96
+ if first_tag == 0x02:
97
+ return _parse_pkcs1_rsakey(der)
98
+ raise JwtError("DER: unrecognized private key structure")
99
+
100
+
101
+ def parse_rsa_private_key(pem: str) -> tuple[int, int, int]:
102
+ """Parse a PEM RSA private key, returning (n, e, d)."""
103
+ match = _PEM_RE.search(pem)
104
+ if match is None:
105
+ raise JwtError("PEM: no RSA/PRIVATE KEY block found")
106
+ der = base64.b64decode("".join(match.group(1).split()))
107
+ return _parse_private_key_der(der)
108
+
109
+
110
+ def _rs256_sign(private_key_pem: str, data: bytes) -> bytes:
111
+ n, _e, d = parse_rsa_private_key(private_key_pem)
112
+ k = (n.bit_length() + 7) // 8
113
+ digest_info = _SHA256_DER_PREFIX + hashlib.sha256(data).digest()
114
+ ps_len = k - len(digest_info) - 3
115
+ if ps_len < 8:
116
+ raise JwtError("RSA key too small for RS256")
117
+ em = b"\x00\x01" + b"\xff" * ps_len + b"\x00" + digest_info
118
+ signature_int = pow(int.from_bytes(em, "big"), d, n)
119
+ return signature_int.to_bytes(k, "big")
120
+
121
+
122
+ def mint_app_jwt(
123
+ app_id: str | int,
124
+ private_key_pem: str,
125
+ *,
126
+ now: float | None = None,
127
+ ttl_seconds: int = 600,
128
+ ) -> str:
129
+ """Mint a GitHub App JWT (RS256, 10-minute max lifetime)."""
130
+ if ttl_seconds <= 0 or ttl_seconds > 600:
131
+ raise JwtError("ttl_seconds must be in (0, 600]")
132
+ issued_at = int(now if now is not None else time.time())
133
+ header = {"alg": "RS256", "typ": "JWT"}
134
+ payload: dict[str, Any] = {
135
+ "iat": issued_at - 30,
136
+ "exp": issued_at + ttl_seconds,
137
+ "iss": str(app_id),
138
+ }
139
+ signing_input = (
140
+ _b64url(json.dumps(header, separators=(",", ":")).encode("utf-8"))
141
+ + "."
142
+ + _b64url(json.dumps(payload, separators=(",", ":")).encode("utf-8"))
143
+ ).encode("ascii")
144
+ signature = _rs256_sign(private_key_pem, signing_input)
145
+ return signing_input.decode("ascii") + "." + _b64url(signature)
selfheal_api/ledger.py ADDED
@@ -0,0 +1,305 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sqlite3
5
+ import threading
6
+ import time
7
+ from pathlib import Path
8
+
9
+ from pydantic import BaseModel, ConfigDict
10
+
11
+
12
+ class DriftEventRecord(BaseModel):
13
+ """Immutable structural record of a single drift evaluation (zero PII)."""
14
+
15
+ model_config = ConfigDict(frozen=True)
16
+
17
+ event_id: int | None = None
18
+ org_id: str
19
+ model_name: str
20
+ fingerprint: str
21
+ has_drift: bool
22
+ issue_count: int
23
+ issue_kinds: tuple[str, ...] = ()
24
+ pr_url: str | None = None
25
+ created_at: float
26
+
27
+
28
+ class OrgDriftSummary(BaseModel):
29
+ """Aggregated drift metrics for a single organization."""
30
+
31
+ model_config = ConfigDict(frozen=True)
32
+
33
+ org_id: str
34
+ total_events: int
35
+ drifted_events: int
36
+ unique_fingerprints: int
37
+ prs_opened: int
38
+ top_models: dict[str, int]
39
+
40
+
41
+ class DriftLedger:
42
+ """Thread-safe SQLite-backed ledger for zero-PII schema drift events."""
43
+
44
+ def __init__(self, db_path: str | Path = ":memory:") -> None:
45
+ resolved_path = str(db_path)
46
+ if resolved_path != ":memory:" and not resolved_path.startswith("file:"):
47
+ Path(resolved_path).parent.mkdir(parents=True, exist_ok=True)
48
+
49
+ self._lock = threading.Lock()
50
+ self._closed = False
51
+ self._conn = sqlite3.connect(resolved_path, check_same_thread=False)
52
+ self._initialize_schema()
53
+
54
+ def _initialize_schema(self) -> None:
55
+ with self._lock:
56
+ self._conn.execute("PRAGMA busy_timeout=5000;")
57
+ self._conn.execute("PRAGMA journal_mode=WAL")
58
+ self._conn.execute(
59
+ """
60
+ CREATE TABLE IF NOT EXISTS drift_events (
61
+ event_id INTEGER PRIMARY KEY AUTOINCREMENT,
62
+ org_id TEXT NOT NULL,
63
+ model_name TEXT NOT NULL,
64
+ fingerprint TEXT NOT NULL,
65
+ has_drift INTEGER NOT NULL,
66
+ issue_count INTEGER NOT NULL,
67
+ issue_kinds_json TEXT NOT NULL,
68
+ pr_url TEXT,
69
+ created_at REAL NOT NULL
70
+ )
71
+ """
72
+ )
73
+ self._conn.execute(
74
+ """
75
+ CREATE INDEX IF NOT EXISTS idx_drift_events_org_created
76
+ ON drift_events (org_id, created_at DESC)
77
+ """
78
+ )
79
+ self._conn.commit()
80
+
81
+ def record_event(
82
+ self,
83
+ org_id: str,
84
+ model_name: str,
85
+ fingerprint: str,
86
+ has_drift: bool,
87
+ issue_count: int,
88
+ issue_kinds: tuple[str, ...] | list[str] = (),
89
+ pr_url: str | None = None,
90
+ created_at: float | None = None,
91
+ ) -> DriftEventRecord:
92
+ """Persist a structural drift event and return the stored record."""
93
+ created = time.time() if created_at is None else created_at
94
+ kinds_tuple = tuple(issue_kinds)
95
+ kinds_json = json.dumps(list(kinds_tuple))
96
+
97
+ with self._lock:
98
+ if self._closed:
99
+ raise RuntimeError("DriftLedger is closed")
100
+ cursor = self._conn.execute(
101
+ """
102
+ INSERT INTO drift_events (
103
+ org_id,
104
+ model_name,
105
+ fingerprint,
106
+ has_drift,
107
+ issue_count,
108
+ issue_kinds_json,
109
+ pr_url,
110
+ created_at
111
+ )
112
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
113
+ """,
114
+ (
115
+ org_id,
116
+ model_name,
117
+ fingerprint,
118
+ 1 if has_drift else 0,
119
+ issue_count,
120
+ kinds_json,
121
+ pr_url,
122
+ created,
123
+ ),
124
+ )
125
+ self._conn.commit()
126
+ event_id = cursor.lastrowid
127
+
128
+ return DriftEventRecord(
129
+ event_id=event_id,
130
+ org_id=org_id,
131
+ model_name=model_name,
132
+ fingerprint=fingerprint,
133
+ has_drift=has_drift,
134
+ issue_count=issue_count,
135
+ issue_kinds=kinds_tuple,
136
+ pr_url=pr_url,
137
+ created_at=created,
138
+ )
139
+
140
+ def list_events(
141
+ self,
142
+ org_id: str | None = None,
143
+ model_name: str | None = None,
144
+ limit: int = 50,
145
+ offset: int = 0,
146
+ since: float | None = None,
147
+ ) -> list[DriftEventRecord]:
148
+ """List recent drift events, optionally filtered by org_id and model_name."""
149
+ if limit < 1:
150
+ raise ValueError("limit must be >= 1")
151
+ if offset < 0:
152
+ raise ValueError("offset must be >= 0")
153
+
154
+ clauses: list[str] = []
155
+ params: list[object] = []
156
+
157
+ if org_id is not None:
158
+ clauses.append("org_id = ?")
159
+ params.append(org_id)
160
+ if model_name is not None:
161
+ clauses.append("model_name = ?")
162
+ params.append(model_name)
163
+ if since is not None:
164
+ clauses.append("created_at >= ?")
165
+ params.append(since)
166
+
167
+ where_sql = f"WHERE {' AND '.join(clauses)}" if clauses else ""
168
+ params.append(limit)
169
+ params.append(offset)
170
+
171
+ query = f"""
172
+ SELECT
173
+ event_id,
174
+ org_id,
175
+ model_name,
176
+ fingerprint,
177
+ has_drift,
178
+ issue_count,
179
+ issue_kinds_json,
180
+ pr_url,
181
+ created_at
182
+ FROM drift_events
183
+ {where_sql}
184
+ ORDER BY created_at DESC, event_id DESC
185
+ LIMIT ? OFFSET ?
186
+ """
187
+
188
+ with self._lock:
189
+ if self._closed:
190
+ raise RuntimeError("DriftLedger is closed")
191
+ rows = self._conn.execute(query, params).fetchall()
192
+
193
+ return [
194
+ DriftEventRecord(
195
+ event_id=int(row[0]),
196
+ org_id=str(row[1]),
197
+ model_name=str(row[2]),
198
+ fingerprint=str(row[3]),
199
+ has_drift=bool(row[4]),
200
+ issue_count=int(row[5]),
201
+ issue_kinds=tuple(str(item) for item in json.loads(str(row[6]))),
202
+ pr_url=str(row[7]) if row[7] is not None else None,
203
+ created_at=float(row[8]),
204
+ )
205
+ for row in rows
206
+ ]
207
+
208
+ def get_org_summary(self, org_id: str) -> OrgDriftSummary:
209
+ """Compute aggregated drift statistics for a single organization."""
210
+ with self._lock:
211
+ if self._closed:
212
+ raise RuntimeError("DriftLedger is closed")
213
+ agg_row = self._conn.execute(
214
+ """
215
+ SELECT
216
+ COUNT(*),
217
+ COALESCE(SUM(CASE WHEN has_drift = 1 THEN 1 ELSE 0 END), 0),
218
+ COUNT(DISTINCT fingerprint),
219
+ COUNT(CASE WHEN pr_url IS NOT NULL AND pr_url != '' THEN 1 END)
220
+ FROM drift_events
221
+ WHERE org_id = ?
222
+ """,
223
+ (org_id,),
224
+ ).fetchone()
225
+
226
+ model_rows = self._conn.execute(
227
+ """
228
+ SELECT model_name, COUNT(*) AS event_count
229
+ FROM drift_events
230
+ WHERE org_id = ?
231
+ GROUP BY model_name
232
+ ORDER BY event_count DESC, model_name ASC
233
+ LIMIT 10
234
+ """,
235
+ (org_id,),
236
+ ).fetchall()
237
+
238
+ assert agg_row is not None
239
+ top_models = {str(row[0]): int(row[1]) for row in model_rows}
240
+
241
+ return OrgDriftSummary(
242
+ org_id=org_id,
243
+ total_events=int(agg_row[0]),
244
+ drifted_events=int(agg_row[1]),
245
+ unique_fingerprints=int(agg_row[2]),
246
+ prs_opened=int(agg_row[3]),
247
+ top_models=top_models,
248
+ )
249
+
250
+ def ping(self) -> bool:
251
+ """Check database connectivity, returning False if closed or on SQLite errors."""
252
+ with self._lock:
253
+ if self._closed:
254
+ return False
255
+ try:
256
+ self._conn.execute("SELECT 1").fetchone()
257
+ except sqlite3.Error:
258
+ return False
259
+ return True
260
+
261
+ def global_totals(self) -> dict[str, int]:
262
+ """Return global event counts across all organizations."""
263
+ with self._lock:
264
+ if self._closed:
265
+ raise RuntimeError("DriftLedger is closed")
266
+ row = self._conn.execute(
267
+ """
268
+ SELECT
269
+ COUNT(*),
270
+ COALESCE(SUM(CASE WHEN has_drift = 1 THEN 1 ELSE 0 END), 0),
271
+ COUNT(CASE WHEN pr_url IS NOT NULL AND pr_url != '' THEN 1 END)
272
+ FROM drift_events
273
+ """
274
+ ).fetchone()
275
+ assert row is not None
276
+ return {
277
+ "total_events": int(row[0]),
278
+ "drifted_events": int(row[1]),
279
+ "prs_opened": int(row[2]),
280
+ }
281
+
282
+ def prune_older_than(
283
+ self, max_age_seconds: float, *, now: float | None = None
284
+ ) -> int:
285
+ """Delete drift events older than max_age_seconds and return deleted row count."""
286
+ if max_age_seconds <= 0:
287
+ raise ValueError("max_age_seconds must be > 0")
288
+ ref_now = time.time() if now is None else now
289
+ cutoff = ref_now - max_age_seconds
290
+ with self._lock:
291
+ if self._closed:
292
+ raise RuntimeError("DriftLedger is closed")
293
+ cursor = self._conn.execute(
294
+ "DELETE FROM drift_events WHERE created_at < ?",
295
+ (cutoff,),
296
+ )
297
+ self._conn.commit()
298
+ return int(cursor.rowcount)
299
+
300
+ def close(self) -> None:
301
+ """Close the underlying SQLite connection."""
302
+ with self._lock:
303
+ if not self._closed:
304
+ self._conn.close()
305
+ self._closed = True
@@ -0,0 +1,259 @@
1
+ """EXP-17/T18 — SelfHeal quality metrics.
2
+
3
+ Five metrics required by the CREOVA directive:
4
+
5
+ - **detection precision** — of payloads flagged as drift, fraction that were
6
+ truly drift (computed offline over the labeled eval corpus in
7
+ ``evaluations/``; see ``run_detection_eval``).
8
+ - **false-positive rate** — fraction of clean payloads flagged as drift.
9
+ - **patch correctness** — fraction of auto-heal runs whose synthesized patch
10
+ verified and produced a PR (``pr_opened`` / decided runs).
11
+ - **regression rate** — fraction of opened remediation PRs later reverted.
12
+ - **time-to-remediation (TTR)** — mean seconds from drift event to opened PR.
13
+
14
+ Remediation metrics are computed from ``autoheal_runs`` provenance rows joined
15
+ against ``drift_ledger`` events; detection metrics come from the labeled
16
+ corpus so they never conflate unlabeled production traffic with ground truth.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ from collections.abc import Iterable
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from pydantic import BaseModel, Field
27
+
28
+ from sentinel.detector import detect_drift
29
+
30
+
31
+ class DetectionEvalResult(BaseModel, frozen=True):
32
+ """Aggregate detection scores over a labeled corpus."""
33
+
34
+ total: int
35
+ true_positives: int
36
+ false_positives: int
37
+ false_negatives: int
38
+ true_negatives: int
39
+ precision: float
40
+ recall: float
41
+ false_positive_rate: float
42
+
43
+
44
+ class RemediationMetrics(BaseModel, frozen=True):
45
+ """Per-org (or global) remediation quality rollup."""
46
+
47
+ runs_total: int = 0
48
+ pr_opened: int = 0
49
+ escalated: int = 0
50
+ failed: int = 0
51
+ reverted: int = 0
52
+ patch_correctness: float | None = None
53
+ regression_rate: float | None = None
54
+ ttr_seconds_mean: float | None = None
55
+ ttr_samples: int = 0
56
+
57
+ def as_dict(self) -> dict[str, Any]:
58
+ return {
59
+ "runs_total": self.runs_total,
60
+ "pr_opened": self.pr_opened,
61
+ "escalated": self.escalated,
62
+ "failed": self.failed,
63
+ "reverted": self.reverted,
64
+ "patch_correctness": self.patch_correctness,
65
+ "regression_rate": self.regression_rate,
66
+ "ttr_seconds_mean": self.ttr_seconds_mean,
67
+ "ttr_samples": self.ttr_samples,
68
+ }
69
+
70
+
71
+ def run_detection_eval(
72
+ model_cls: type[BaseModel],
73
+ samples: Iterable[dict[str, Any]],
74
+ ) -> DetectionEvalResult:
75
+ """Score ``detect_drift`` against labeled samples.
76
+
77
+ Each sample: ``{"expect_drift": bool, "payload": <json-able>}``.
78
+ Payloads may be dicts or raw strings (raw strings exercise the
79
+ invalid-JSON path).
80
+ """
81
+ tp = fp = fn = tn = 0
82
+ for sample in samples:
83
+ expected = bool(sample.get("expect_drift"))
84
+ payload = sample.get("payload")
85
+ if payload is None:
86
+ raise ValueError("eval sample missing 'payload'")
87
+ report = detect_drift(model_cls, payload)
88
+ observed = bool(report.has_drift)
89
+ if observed and expected:
90
+ tp += 1
91
+ elif observed and not expected:
92
+ fp += 1
93
+ elif not observed and expected:
94
+ fn += 1
95
+ else:
96
+ tn += 1
97
+ total = tp + fp + fn + tn
98
+ precision = tp / (tp + fp) if (tp + fp) else 0.0
99
+ recall = tp / (tp + fn) if (tp + fn) else 0.0
100
+ fpr = fp / (fp + tn) if (fp + tn) else 0.0
101
+ return DetectionEvalResult(
102
+ total=total,
103
+ true_positives=tp,
104
+ false_positives=fp,
105
+ false_negatives=fn,
106
+ true_negatives=tn,
107
+ precision=precision,
108
+ recall=recall,
109
+ false_positive_rate=fpr,
110
+ )
111
+
112
+
113
+ def load_detection_corpus(
114
+ corpus_path: str | Path,
115
+ model_registry: dict[str, type[BaseModel]],
116
+ ) -> list[tuple[type[BaseModel], list[dict[str, Any]]]]:
117
+ """Load a JSONL eval corpus grouped by model name.
118
+
119
+ Each line: ``{"model": "<registry key>", "expect_drift": bool,
120
+ "payload": {...}}``. Returns ``(model_cls, samples)`` pairs.
121
+ """
122
+ grouped: dict[str, list[dict[str, Any]]] = {}
123
+ order: list[str] = []
124
+ with open(corpus_path, encoding="utf-8") as fh:
125
+ for line in fh:
126
+ line = line.strip()
127
+ if not line or line.startswith("#"):
128
+ continue
129
+ entry = json.loads(line)
130
+ name = str(entry["model"])
131
+ if name not in grouped:
132
+ grouped[name] = []
133
+ order.append(name)
134
+ grouped[name].append(
135
+ {
136
+ "expect_drift": bool(entry.get("expect_drift")),
137
+ "payload": entry.get("payload"),
138
+ }
139
+ )
140
+ pairs: list[tuple[type[BaseModel], list[dict[str, Any]]]] = []
141
+ for name in order:
142
+ model_cls = model_registry.get(name)
143
+ if model_cls is None:
144
+ raise KeyError(f"corpus references unknown model {name!r}")
145
+ pairs.append((model_cls, grouped[name]))
146
+ return pairs
147
+
148
+
149
+ def evaluate_corpus(
150
+ corpus_path: str | Path,
151
+ model_registry: dict[str, type[BaseModel]],
152
+ ) -> DetectionEvalResult:
153
+ """Run the full labeled corpus and return aggregate detection metrics."""
154
+ tp = fp = fn = tn = 0
155
+ for model_cls, samples in load_detection_corpus(corpus_path, model_registry):
156
+ result = run_detection_eval(model_cls, samples)
157
+ tp += result.true_positives
158
+ fp += result.false_positives
159
+ fn += result.false_negatives
160
+ tn += result.true_negatives
161
+ total = tp + fp + fn + tn
162
+ precision = tp / (tp + fp) if (tp + fp) else 0.0
163
+ recall = tp / (tp + fn) if (tp + fn) else 0.0
164
+ fpr = fp / (fp + tn) if (fp + tn) else 0.0
165
+ return DetectionEvalResult(
166
+ total=total,
167
+ true_positives=tp,
168
+ false_positives=fp,
169
+ false_negatives=fn,
170
+ true_negatives=tn,
171
+ precision=precision,
172
+ recall=recall,
173
+ false_positive_rate=fpr,
174
+ )
175
+
176
+
177
+ # Statuses that represent a decided patch attempt (correctness denominator).
178
+ _DECIDED_STATUSES = frozenset({"pr_opened", "failed_verification"})
179
+
180
+
181
+ def compute_remediation_metrics(
182
+ runs: Iterable[dict[str, Any]],
183
+ events: Iterable[Any] = (),
184
+ ) -> RemediationMetrics:
185
+ """Roll up auto-heal runs (+ optional drift events) into T18 metrics.
186
+
187
+ ``runs`` are ``autoheal_runs`` rows (dicts with ``status``,
188
+ ``fingerprint``, ``created_at``); ``events`` are drift ledger records or
189
+ dicts with ``fingerprint``/``created_at`` used for TTR.
190
+ """
191
+ runs_list = list(runs)
192
+ counts = {"pr_opened": 0, "escalated": 0, "reverted": 0}
193
+ decided = 0
194
+ for run in runs_list:
195
+ status = str(run.get("status") or "")
196
+ if status in counts:
197
+ counts[status] += 1
198
+ if status in _DECIDED_STATUSES:
199
+ decided += 1
200
+ # "failed" = everything that is neither a PR, an escalation, nor a revert
201
+ # (verification failures, sandbox errors, fetch failures, ...).
202
+ failed = len(runs_list) - counts["pr_opened"] - counts["escalated"] - counts["reverted"]
203
+
204
+ pr_opened = counts["pr_opened"]
205
+ patch_correctness = (
206
+ pr_opened / decided if decided else None
207
+ )
208
+ regression_rate = (
209
+ counts["reverted"] / pr_opened if pr_opened else None
210
+ )
211
+
212
+ # TTR: match each pr_opened run to the earliest drift event with the
213
+ # same (org_id, fingerprint); only count non-negative deltas.
214
+ def _key(org: Any, fp: Any) -> tuple[str, str] | None:
215
+ if not fp:
216
+ return None
217
+ return (str(org or ""), str(fp))
218
+
219
+ event_times: dict[tuple[str, str], float] = {}
220
+ for ev in events:
221
+ org = ev.get("org_id") if isinstance(ev, dict) else getattr(ev, "org_id", None)
222
+ fp = ev.get("fingerprint") if isinstance(ev, dict) else getattr(ev, "fingerprint", None)
223
+ ts = ev.get("created_at") if isinstance(ev, dict) else getattr(ev, "created_at", None)
224
+ key = _key(org, fp)
225
+ if key is not None and ts is not None:
226
+ t = float(ts)
227
+ if key not in event_times or t < event_times[key]:
228
+ event_times[key] = t
229
+ deltas: list[float] = []
230
+ for run in runs_list:
231
+ if str(run.get("status") or "") != "pr_opened":
232
+ continue
233
+ key = _key(run.get("org_id"), run.get("fingerprint"))
234
+ event_ts = event_times.get(key) if key is not None else None
235
+ run_ts = run.get("created_at")
236
+ if event_ts is not None and run_ts is not None:
237
+ delta = float(run_ts) - event_ts
238
+ if delta >= 0:
239
+ deltas.append(delta)
240
+ ttr_mean = sum(deltas) / len(deltas) if deltas else None
241
+
242
+ return RemediationMetrics(
243
+ runs_total=len(runs_list),
244
+ pr_opened=pr_opened,
245
+ escalated=counts["escalated"],
246
+ failed=max(failed, 0),
247
+ reverted=counts["reverted"],
248
+ patch_correctness=patch_correctness,
249
+ regression_rate=regression_rate,
250
+ ttr_seconds_mean=ttr_mean,
251
+ ttr_samples=len(deltas),
252
+ )
253
+
254
+
255
+ class OrgQualityMetrics(BaseModel, frozen=True):
256
+ """Console-facing per-org quality rollup (T18)."""
257
+
258
+ detection: DetectionEvalResult | None = None
259
+ remediation: RemediationMetrics = Field(default_factory=RemediationMetrics)