openadapt-kernel 0.1.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,317 @@
1
+ """Independent cross-rail read-back oracles (SQLite RO, PDF content stream, cross-tab DOM).
2
+
3
+ Provides verifiable post-commit read-back channels without relying on same-screen
4
+ success banners:
5
+ - read_sqlite_ro: opens a SQLite database strictly read-only (URI mode=ro) and
6
+ verifies expected field values against queried rows.
7
+ - extract_pdf_visible_text / verify_pdf_readback: pure-stdlib PDF content-stream
8
+ extractor that filters invisible text render modes (3 Tr, 7 Tr) and checks
9
+ expected fields via token-boundary matching.
10
+ - verify_cross_tab_dom: inspects all open pages in a Playwright browser context
11
+ to find persisted confirmation evidence across multi-tab workflows.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ import sqlite3
18
+ import zlib
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+ from typing import Any, Dict, List, Optional, Sequence
22
+ from urllib.parse import urlparse
23
+
24
+ from openadapt_kernel.ledger import ReadBackProof
25
+
26
+ _STREAM_RE = re.compile(rb"stream\r?\n(.*?)\r?\nendstream", re.DOTALL)
27
+ _TOKEN_RE = re.compile(
28
+ r"\((?:\\.|[^\\()])*\)|\[(?:\\.|[^\\\[\]])*\]\s*TJ|\b\d+\s+Tr\b"
29
+ )
30
+ _DOM_EXTRACT_JS = """() => {
31
+ const bindings = [];
32
+ const labelFor = (el) => {
33
+ const aria = el.getAttribute && el.getAttribute('aria-label');
34
+ if (aria) return aria.trim();
35
+ if (el.id) {
36
+ const l = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
37
+ if (l) return (l.innerText || l.textContent || '').trim();
38
+ }
39
+ const p = el.closest && el.closest('label');
40
+ return p ? (p.innerText || p.textContent || '').trim() : '';
41
+ };
42
+ for (const el of document.querySelectorAll('input,textarea,select')) {
43
+ const val = el.tagName === 'SELECT' && el.selectedOptions && el.selectedOptions[0]
44
+ ? `${el.value} ${el.selectedOptions[0].text || ''}`.trim() : String(el.value || '');
45
+ bindings.push({key: [el.name, el.id, el.getAttribute('data-testid'), labelFor(el)].filter(Boolean).join(' '), val});
46
+ }
47
+ for (const dt of document.querySelectorAll('dt')) {
48
+ const dd = dt.nextElementSibling;
49
+ if (dd && dd.tagName === 'DD') bindings.push({key: (dt.innerText || '').trim(), val: (dd.innerText || '').trim()});
50
+ }
51
+ for (const tr of document.querySelectorAll('tr')) {
52
+ const cells = tr.querySelectorAll('th,td');
53
+ if (cells.length >= 2) bindings.push({key: (cells[0].innerText || '').trim(), val: (cells[1].innerText || '').trim()});
54
+ }
55
+ for (const el of document.querySelectorAll('[data-field],[data-testid]')) {
56
+ const k = el.getAttribute('data-field') || el.getAttribute('data-testid') || '';
57
+ const v = (el.innerText || el.textContent || '').trim();
58
+ if (k && v) bindings.push({key: k, val: v});
59
+ }
60
+ return { text: (document.body && document.body.innerText) || '', bindings };
61
+ }"""
62
+
63
+
64
+ @dataclass
65
+ class OracleVerdict:
66
+ verified: bool
67
+ channel: str
68
+ locator: str
69
+ cited_substrings: List[str] = field(default_factory=list)
70
+ missing_fields: List[str] = field(default_factory=list)
71
+ external_ref: Optional[str] = None
72
+
73
+ def to_proof(self) -> ReadBackProof:
74
+ if not self.verified:
75
+ raise ValueError("Cannot convert unverified OracleVerdict to ReadBackProof")
76
+ return ReadBackProof(
77
+ channel=self.channel, # type: ignore[arg-type]
78
+ url_or_locator=self.locator,
79
+ cited_substrings=self.cited_substrings,
80
+ external_ref=self.external_ref,
81
+ )
82
+
83
+
84
+ def _key_aliases(key: str) -> List[str]:
85
+ base = key.strip()
86
+ parts = [p for p in re.split(r"[\s_-]+", base) if len(p) >= 3]
87
+ out = [base, base.replace("_", " "), base.replace("-", " ")]
88
+ for p in parts:
89
+ if p.lower() not in {x.lower() for x in out}:
90
+ out.append(p)
91
+ return [a for a in out if a]
92
+
93
+
94
+ def _field_bound_match(key: str, val: str, compact: str, field_bindings: Sequence[Dict[str, str]]) -> bool:
95
+ v_re = rf"(?<!\w){re.escape(val)}(?!\w)"
96
+ aliases = _key_aliases(key)
97
+ key_toks = {t.lower() for t in re.findall(r"[a-z0-9]+", key) if len(t) >= 2}
98
+ for b in field_bindings:
99
+ bk = str(b.get("key") or "")
100
+ bv = " ".join(str(b.get("val") or "").split())
101
+ if not bk or not bv:
102
+ continue
103
+ btoks = {t.lower() for t in re.findall(r"[a-z0-9]+", bk)}
104
+ if (key.lower() in bk.lower() or (key_toks and len(key_toks & btoks) / len(key_toks) >= 0.5)) and re.search(v_re, bv):
105
+ return True
106
+ for alias in aliases:
107
+ if re.search(rf"(?<!\w){re.escape(alias)}[\s\"']{{0,3}}[:=][\s\"']{{0,3}}{re.escape(val)}(?!\w)", compact, re.IGNORECASE):
108
+ return True
109
+ return False
110
+
111
+
112
+ def token_boundary_check(
113
+ expected_fields: Dict[str, str],
114
+ text: str,
115
+ *,
116
+ field_bindings: Sequence[Dict[str, str]] = (),
117
+ ) -> tuple[List[str], List[str]]:
118
+ """Return (cited_values, missing_keys) with field-bound matching; bare 1-2 char values require binding."""
119
+ compact = " ".join((text or "").split())
120
+ cited: List[str] = []
121
+ missing: List[str] = []
122
+ for key, val in expected_fields.items():
123
+ v = str(val).strip()
124
+ if not v:
125
+ continue
126
+ if _field_bound_match(key, v, compact, field_bindings):
127
+ cited.append(v)
128
+ elif len(v) >= 3 and re.search(rf"(?<!\w){re.escape(v)}(?!\w)", compact):
129
+ cited.append(v)
130
+ else:
131
+ missing.append(key)
132
+ return cited, missing
133
+
134
+
135
+ def verify_sqlite_ro(
136
+ db_path: Path,
137
+ query: str,
138
+ params: Sequence[Any],
139
+ expected_fields: Dict[str, str],
140
+ *,
141
+ ref_column: Optional[str] = None,
142
+ ) -> OracleVerdict:
143
+ """Query a local SQLite database strictly in read-only mode (URI mode=ro)."""
144
+ uri = f"file:{db_path.resolve()}?mode=ro"
145
+ conn = sqlite3.connect(uri, uri=True)
146
+ conn.row_factory = sqlite3.Row
147
+ try:
148
+ cur = conn.execute(query, tuple(params))
149
+ rows = [dict(r) for r in cur.fetchall()]
150
+ finally:
151
+ conn.close()
152
+
153
+ if not rows:
154
+ return OracleVerdict(
155
+ verified=False,
156
+ channel="sql_read",
157
+ locator=f"sqlite://{db_path.name}",
158
+ missing_fields=list(expected_fields.keys()),
159
+ )
160
+
161
+ latest = rows[-1]
162
+ row_text = " ".join(f"{k}={v}" for k, v in latest.items() if v is not None)
163
+ cited, missing = token_boundary_check(expected_fields, row_text)
164
+ ext_ref = str(latest[ref_column]) if ref_column and ref_column in latest and latest[ref_column] is not None else None
165
+ return OracleVerdict(
166
+ verified=(len(missing) == 0 and len(cited) > 0),
167
+ channel="sql_read",
168
+ locator=f"sqlite://{db_path.name}",
169
+ cited_substrings=cited,
170
+ missing_fields=missing,
171
+ external_ref=ext_ref,
172
+ )
173
+
174
+
175
+ def _unescape_pdf_string(raw: str) -> str:
176
+ return (
177
+ raw.replace(r"\(", "(")
178
+ .replace(r"\)", ")")
179
+ .replace(r"\\", "\\")
180
+ .replace(r"\n", " ")
181
+ .replace(r"\r", " ")
182
+ )
183
+
184
+
185
+ def extract_pdf_visible_text(pdf_bytes: bytes) -> str:
186
+ """Extract visible text from raw or FlateDecode PDF streams, filtering 3 Tr / 7 Tr invisible text."""
187
+ chunks: List[str] = []
188
+ streams = _STREAM_RE.findall(pdf_bytes)
189
+ payloads: List[bytes] = list(streams) if streams else [pdf_bytes]
190
+
191
+ for raw_stream in payloads:
192
+ decoded_bytes = raw_stream
193
+ try:
194
+ decoded_bytes = zlib.decompress(raw_stream)
195
+ except zlib.error:
196
+ pass
197
+ text = decoded_bytes.decode("latin-1", errors="ignore")
198
+ render_mode = 0
199
+ for match in _TOKEN_RE.finditer(text):
200
+ tok = match.group(0)
201
+ if tok.endswith("Tr"):
202
+ try:
203
+ render_mode = int(tok.split()[0])
204
+ except ValueError:
205
+ render_mode = 0
206
+ continue
207
+ # Render mode 3 (invisible) and 7 (clip-only) are excluded to block hidden-text spoofing
208
+ if render_mode in (3, 7):
209
+ continue
210
+ if tok.startswith("(") and tok.endswith(")"):
211
+ chunks.append(_unescape_pdf_string(tok[1:-1]))
212
+ elif tok.startswith("["):
213
+ inner = re.findall(r"\((?:\\.|[^\\()])*\)", tok)
214
+ chunks.append("".join(_unescape_pdf_string(s[1:-1]) for s in inner))
215
+ return " ".join(c for c in chunks if c.strip())
216
+
217
+
218
+ def verify_pdf_readback(
219
+ pdf_path: Path,
220
+ expected_fields: Dict[str, str],
221
+ *,
222
+ ref_pattern: Optional[str] = None,
223
+ ) -> OracleVerdict:
224
+ """Verify expected fields against visible text extracted from a confirmation PDF."""
225
+ visible = extract_pdf_visible_text(pdf_path.read_bytes())
226
+ cited, missing = token_boundary_check(expected_fields, visible)
227
+ ext_ref: Optional[str] = None
228
+ if ref_pattern:
229
+ m = re.search(ref_pattern, visible)
230
+ if m:
231
+ ext_ref = m.group(1) if m.groups() else m.group(0)
232
+ return OracleVerdict(
233
+ verified=(len(missing) == 0 and len(cited) > 0),
234
+ channel="pdf_stream",
235
+ locator=f"pdf://{pdf_path.name}",
236
+ cited_substrings=cited,
237
+ missing_fields=missing,
238
+ external_ref=ext_ref,
239
+ )
240
+
241
+
242
+ def _origin_of(url: str) -> str:
243
+ p = urlparse(url or "")
244
+ return f"{p.scheme.lower()}://{p.netloc.lower()}" if p.scheme and p.netloc else ""
245
+
246
+
247
+ def _origin_matches(tab_url: str, target_origin: str) -> bool:
248
+ tp, op = urlparse(tab_url or ""), urlparse(target_origin or "")
249
+ if not tp.scheme or not tp.netloc or not op.scheme or not op.netloc:
250
+ return False
251
+ if op.port is not None:
252
+ return tp.scheme.lower() == op.scheme.lower() and tp.netloc.lower() == op.netloc.lower()
253
+ return tp.scheme.lower() == op.scheme.lower() and (tp.hostname or "").lower() == (op.hostname or "").lower()
254
+
255
+
256
+ def verify_cross_tab_dom(
257
+ page: Any,
258
+ expected_fields: Dict[str, str],
259
+ *,
260
+ reload_active: bool = True,
261
+ target_origin: Optional[str] = None,
262
+ structured_bindings: Optional[Dict[str, str]] = None,
263
+ ) -> OracleVerdict:
264
+ """Verify expected fields strictly on the mutated target tab/origin using field-bound matching."""
265
+ if reload_active:
266
+ page.reload(wait_until="domcontentloaded")
267
+ page.wait_for_timeout(120)
268
+
269
+ active_url = str(getattr(page, "url", "") or "")
270
+ active_origin = _origin_of(active_url)
271
+ if target_origin and active_origin and not _origin_matches(active_url, target_origin):
272
+ return OracleVerdict(
273
+ verified=False,
274
+ channel="fresh_reload",
275
+ locator=active_url,
276
+ missing_fields=list(expected_fields.keys()),
277
+ )
278
+
279
+ ctx = getattr(page, "context", None)
280
+ if ctx is not None and active_origin:
281
+ pages = [
282
+ p for p in ctx.pages
283
+ if not p.is_closed()
284
+ and _origin_of(str(getattr(p, "url", "") or "")) == active_origin
285
+ and (not target_origin or _origin_matches(str(getattr(p, "url", "") or ""), target_origin))
286
+ ]
287
+ else:
288
+ pages = [page]
289
+
290
+ texts: List[str] = []
291
+ urls: List[str] = []
292
+ bindings: List[Dict[str, str]] = [
293
+ {"key": k, "val": str(v)} for k, v in (structured_bindings or {}).items()
294
+ ]
295
+ for p in pages:
296
+ try:
297
+ if p.is_closed():
298
+ continue
299
+ snap = p.evaluate(_DOM_EXTRACT_JS) or {}
300
+ txt = str(snap.get("text") or "")
301
+ if txt.strip():
302
+ texts.append(txt)
303
+ urls.append(str(p.url))
304
+ bindings.extend(snap.get("bindings") or [])
305
+ except Exception:
306
+ continue
307
+
308
+ combined = "\n".join(texts)
309
+ cited, missing = token_boundary_check(expected_fields, combined, field_bindings=bindings)
310
+ channel = "cross_tab" if len(urls) > 1 else "fresh_reload"
311
+ return OracleVerdict(
312
+ verified=(len(missing) == 0 and len(cited) > 0),
313
+ channel=channel,
314
+ locator=urls[0] if urls else active_url,
315
+ cited_substrings=cited,
316
+ missing_fields=missing,
317
+ )
@@ -0,0 +1,100 @@
1
+ """Reversible pre-contact occlusion and hover/focus differential probe.
2
+
3
+ Checks whether a target control is actually the topmost hit-tested element at
4
+ its center coordinates (catching transparent overlays and modal click-jacking)
5
+ and verifies a reversible hover/focus state response before committing a click.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Any
12
+
13
+ _HIT_TEST_JS = """(selector) => {
14
+ const el = document.querySelector(selector);
15
+ if (!el) return { found: false, occluded: true, reason: 'not_found' };
16
+ el.scrollIntoView({ block: 'center', inline: 'center' });
17
+ const r = el.getBoundingClientRect();
18
+ if (r.width <= 0 || r.height <= 0) {
19
+ return { found: true, occluded: true, reason: 'zero_box' };
20
+ }
21
+ const cx = r.left + r.width / 2;
22
+ const cy = r.top + r.height / 2;
23
+ const stack = document.elementsFromPoint(cx, cy);
24
+ if (!stack || stack.length === 0) {
25
+ return { found: true, occluded: true, reason: 'empty_hit_stack' };
26
+ }
27
+ const top = stack[0];
28
+ const sameOrChild = top === el || el.contains(top) || top.contains(el);
29
+ const disabled = Boolean(el.disabled || el.getAttribute('aria-disabled') === 'true');
30
+ return {
31
+ found: true,
32
+ occluded: !sameOrChild,
33
+ disabled,
34
+ top_tag: top.tagName ? top.tagName.toLowerCase() : '',
35
+ top_id: top.id || '',
36
+ reason: !sameOrChild ? 'occluded_by_overlay' : (disabled ? 'control_disabled' : 'clear'),
37
+ };
38
+ }"""
39
+
40
+
41
+ @dataclass
42
+ class ProbeResult:
43
+ safe_to_click: bool
44
+ found: bool
45
+ occluded: bool
46
+ disabled: bool
47
+ focus_responded: bool
48
+ reason: str
49
+ top_blocker: str = ""
50
+
51
+
52
+ def probe_before_click(page: Any, selector: str) -> ProbeResult:
53
+ """Run zero-side-effect hit-test occlusion check + reversible hover/focus probe."""
54
+ hit = page.evaluate(_HIT_TEST_JS, selector) or {}
55
+ found = bool(hit.get("found", False))
56
+ occluded = bool(hit.get("occluded", True))
57
+ disabled = bool(hit.get("disabled", False))
58
+ reason = str(hit.get("reason") or "unknown")
59
+ blocker = ""
60
+ if occluded and found:
61
+ blocker = f"{hit.get('top_tag', '')}#{hit.get('top_id', '')}".rstrip("#")
62
+
63
+ if not found or occluded or disabled:
64
+ return ProbeResult(
65
+ safe_to_click=False,
66
+ found=found,
67
+ occluded=occluded,
68
+ disabled=disabled,
69
+ focus_responded=False,
70
+ reason=reason,
71
+ top_blocker=blocker,
72
+ )
73
+
74
+ focus_ok = False
75
+ try:
76
+ loc = page.locator(selector).first
77
+ loc.hover(timeout=800)
78
+ page.wait_for_timeout(80)
79
+ focus_ok = bool(
80
+ page.evaluate(
81
+ """(sel) => {
82
+ const el = document.querySelector(sel);
83
+ if (!el) return false;
84
+ el.focus({ preventScroll: true });
85
+ return document.activeElement === el || el.matches(':hover');
86
+ }""",
87
+ selector,
88
+ )
89
+ )
90
+ except Exception:
91
+ focus_ok = False
92
+
93
+ return ProbeResult(
94
+ safe_to_click=focus_ok,
95
+ found=True,
96
+ occluded=False,
97
+ disabled=False,
98
+ focus_responded=focus_ok,
99
+ reason="clear" if focus_ok else "hover_focus_probe_failed",
100
+ )
@@ -0,0 +1,145 @@
1
+ """Zero-PII content-addressed PortalPack registry and offline HTML audit card generator.
2
+
3
+ Enforces two commercial invariants:
4
+ 1. Shared PortalPack Network: any pack published for cross-tenant reuse is scanned
5
+ for PII (emails, SSNs, phone numbers, DOBs) and signed with Ed25519 so tenants
6
+ only pull verified, zero-PII structural updates.
7
+ 2. Proof-Carrying Automation: renders an offline, self-contained HTML audit card
8
+ from an Ed25519-signed openadapt.kernel.receipt/v1 bundle for compliance review.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import hashlib
15
+ import html
16
+ import json
17
+ import re
18
+ from dataclasses import asdict, dataclass
19
+ from pathlib import Path
20
+ from typing import Any, Dict, List
21
+
22
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
23
+ from cryptography.hazmat.primitives.serialization import load_pem_private_key, load_pem_public_key
24
+
25
+ from openadapt_kernel.copilot import PortalPack, verify_receipt
26
+
27
+ _PII_PATTERNS = {
28
+ "email": re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"),
29
+ "ssn": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
30
+ "phone": re.compile(r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}\b"),
31
+ "dob_iso": re.compile(r"\b(?:19|20)\d{2}-\d{2}-\d{2}\b"),
32
+ }
33
+
34
+
35
+ @dataclass
36
+ class SignedPackEnvelope:
37
+ schema: str
38
+ pack_sha256: str
39
+ pack: Dict[str, Any]
40
+ signature_b64: str
41
+
42
+
43
+ def scan_pack_for_pii(pack: PortalPack) -> List[str]:
44
+ """Return any PII pattern hits inside a PortalPack before cross-tenant publishing."""
45
+ blob = json.dumps(asdict(pack), sort_keys=True)
46
+ hits: List[str] = []
47
+ for label, pattern in _PII_PATTERNS.items():
48
+ if pattern.search(blob):
49
+ hits.append(label)
50
+ return hits
51
+
52
+
53
+ def publish_signed_pack(
54
+ pack: PortalPack,
55
+ private_key_pem: bytes,
56
+ registry_dir: Path,
57
+ ) -> Path:
58
+ """Validate zero PII, sign a PortalPack with Ed25519, and write to the local registry."""
59
+ pii_hits = scan_pack_for_pii(pack)
60
+ if pii_hits:
61
+ raise ValueError(f"Refusing to publish PortalPack with PII patterns: {pii_hits}")
62
+
63
+ pack_dict = asdict(pack)
64
+ canonical = json.dumps(pack_dict, sort_keys=True, separators=(",", ":")).encode("utf-8")
65
+ digest = hashlib.sha256(canonical).hexdigest()
66
+
67
+ priv = load_pem_private_key(private_key_pem, password=None)
68
+ assert isinstance(priv, Ed25519PrivateKey)
69
+ sig_b64 = base64.b64encode(priv.sign(canonical)).decode("ascii")
70
+
71
+ envelope = SignedPackEnvelope(
72
+ schema="openadapt.kernel.pack/v1",
73
+ pack_sha256=digest,
74
+ pack=pack_dict,
75
+ signature_b64=sig_b64,
76
+ )
77
+ registry_dir.mkdir(parents=True, exist_ok=True)
78
+ out = registry_dir / f"{pack.pack_id}-{digest[:12]}.pack.json"
79
+ out.write_text(json.dumps(asdict(envelope), indent=2), encoding="utf-8")
80
+ return out
81
+
82
+
83
+ def pull_verified_pack(pack_file: Path, public_key_pem: bytes) -> PortalPack:
84
+ """Verify Ed25519 signature, SHA-256 digest, and zero-PII invariant before loading."""
85
+ data = json.loads(pack_file.read_text(encoding="utf-8"))
86
+ pack_dict = data["pack"]
87
+ canonical = json.dumps(pack_dict, sort_keys=True, separators=(",", ":")).encode("utf-8")
88
+ if hashlib.sha256(canonical).hexdigest() != data.get("pack_sha256"):
89
+ raise ValueError("PortalPack SHA-256 digest mismatch")
90
+
91
+ pub = load_pem_public_key(public_key_pem)
92
+ assert isinstance(pub, Ed25519PublicKey)
93
+ pub.verify(base64.b64decode(data["signature_b64"]), canonical)
94
+
95
+ pack = PortalPack(
96
+ pack_id=pack_dict["pack_id"],
97
+ portal_origin=pack_dict["portal_origin"],
98
+ variable_fields=list(pack_dict.get("variable_fields") or []),
99
+ static_defaults=dict(pack_dict.get("static_defaults") or {}),
100
+ provenance_map=dict(pack_dict.get("provenance_map") or {}),
101
+ readback_url_pattern=str(pack_dict.get("readback_url_pattern") or ""),
102
+ stage=pack_dict.get("stage", "SHADOW"),
103
+ shadow_passes=int(pack_dict.get("shadow_passes", 0)),
104
+ edge_branches=dict(pack_dict.get("edge_branches") or {}),
105
+ )
106
+ if scan_pack_for_pii(pack):
107
+ raise ValueError("Pulled PortalPack failed zero-PII check")
108
+ return pack
109
+
110
+
111
+ def render_audit_card_html(receipt: Dict[str, Any], public_key_pem: bytes) -> str:
112
+ """Render a self-contained offline compliance HTML card for an Ed25519 receipt."""
113
+ sig_ok = verify_receipt(receipt, public_key_pem)
114
+ payload = receipt.get("payload", {})
115
+ obligations = payload.get("obligations", {})
116
+ rows = []
117
+ for oid, ob in obligations.items():
118
+ proof = ob.get("readback_proof") or ob.get("proof") or {}
119
+ evidence = ", ".join(
120
+ str(s) for s in (proof.get("cited_substrings") or proof.get("cited_value_sha256") or [])
121
+ )
122
+ locator = str(proof.get("origin_host") or proof.get("url_or_locator") or "")
123
+ rows.append(
124
+ f"<tr><td>{html.escape(str(oid))}</td>"
125
+ f"<td>{html.escape(str(ob.get('state', ob.get('status', ''))))}</td>"
126
+ f"<td>{html.escape(str(proof.get('channel', '')))}</td>"
127
+ f"<td><code>{html.escape(evidence or locator)}</code></td></tr>"
128
+ )
129
+ status_badge = "SIGNATURE VERIFIED" if sig_ok else "SIGNATURE INVALID"
130
+ color = "#0f766e" if sig_ok else "#b91c1c"
131
+ return (
132
+ "<!doctype html><html><head><meta charset='utf-8'>"
133
+ "<title>OpenAdapt Kernel Audit Receipt</title>"
134
+ "<style>body{font-family:system-ui,sans-serif;max-width:780px;margin:24px auto;color:#111}"
135
+ "table{border-collapse:collapse;width:100%;margin-top:12px}"
136
+ "th,td{border:1px solid #d1d5db;padding:8px;text-align:left;font-size:14px}"
137
+ ".badge{display:inline-block;padding:4px 10px;border-radius:6px;color:#fff;font-weight:600}</style>"
138
+ f"</head><body><h1>OpenAdapt Kernel Audit Receipt</h1>"
139
+ f"<span class='badge' style='background:{color}'>{status_badge}</span>"
140
+ f"<p><strong>Pack:</strong> {html.escape(str(payload.get('pack_id', '')))} | "
141
+ f"<strong>Episode:</strong> {html.escape(str(payload.get('episode_id', '')))} | "
142
+ f"<strong>Minted:</strong> {html.escape(str(payload.get('minted_at', '')))}</p>"
143
+ f"<table><thead><tr><th>Obligation</th><th>Status</th><th>Read-Back Channel</th><th>Evidence Hash</th></tr></thead>"
144
+ f"<tbody>{''.join(rows)}</tbody></table></body></html>"
145
+ )