robot-gate 0.2.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,1528 @@
1
+ """1-Click ISO 10218:2025 & EU Machinery Regulation (EU) 2023/1230 Compliance Dossier Generator.
2
+
3
+ Inspects a `robot-gate` workspace offline and produces a self-contained, tamper-evident
4
+ compliance bundle for notified bodies, EHS officers, and insurance underwriters:
5
+ - `compliance_manifest.json` — RFC 8785 JCS canonical SHA-256 digest (`robot_gate.audit.sha256_canonical`)
6
+ with clause-by-clause readiness mapping for:
7
+ * ISO 10218-1:2025 Clause 5.1.16 & ISO 10218-2:2025 Clause 5.2.16 (Safety Cybersecurity)
8
+ * EU Machinery Regulation (EU) 2023/1230 (effective January 20, 2027)
9
+ * ISO 13850 & ISO 13849-1:2023 Mandatory Hardware Boundary Attestation (zero PL/SIL credit)
10
+ - `compliance_dossier.html` — Warm Workshop printable HTML audit report (zero external CDN deps)
11
+ - `graft-compliance-pack.zip` — Offline-verifiable ZIP bundling manifest, HTML dossier, and hashed
12
+ snapshots of workspace evidence artifacts (strictly excluding ALL private keys).
13
+
14
+ Offline verification via `verify_compliance_pack(zip_or_dir)` fails closed on any missing,
15
+ unexpected, tampered, or private-key-contaminated file.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import html
22
+ import json
23
+ import re
24
+ import time
25
+ import zipfile
26
+ from dataclasses import asdict, dataclass, field
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ import yaml
31
+
32
+ from . import SAFETY_BOUNDARY_STATEMENT, __version__
33
+ from .audit import sha256_canonical, verify_audit_chain
34
+ from .bounded_bridge import (
35
+ bounded_embodiment_version,
36
+ graft_core_version,
37
+ public_pem_to_jwk,
38
+ rust_kernel_active,
39
+ validate_envelope_doc,
40
+ verify_envelope_signature,
41
+ )
42
+ from .fingerprint import compute_fingerprint, sha256_file
43
+ from .gate import GateConfig, GateReceipt, verify_receipt_signature
44
+ from .manifest import load_manifest, verify_manifest_signature
45
+ from .trust import TRUST_POLICIES, TrustLevel
46
+
47
+ COMPLIANCE_SCHEMA_VERSION = "1.0.0"
48
+ DEFAULT_ZIP_FILENAME = "graft-compliance-pack.zip"
49
+
50
+ ISO_13850_HARDWARE_BOUNDARY_ATTESTATION = (
51
+ "MANDATORY HARDWARE SAFETY BOUNDARY (ISO 13850 / ISO 13849-1:2023 / ANSI R15.06-2025 / ISO 12100): "
52
+ "Graft Robotics (`robot-gate`, `robot-md-gateway`, and `graft-core`) is strictly a deterministic "
53
+ "software pre-flight boundary, CI regression gate, and offline-verifiable audit layer. "
54
+ "It claims ZERO Performance Level (PL) and ZERO Safety Integrity Level (SIL) risk-reduction credit. "
55
+ "Hardwired ISO 13850 emergency stops, ISO 13849-1:2023 safety relays/contactors, physical guarding, "
56
+ "and an application-specific ANSI/A3 R15.06-2025 & ISO 12100 risk assessment remain mandatory for "
57
+ "every deployed robot cell."
58
+ )
59
+
60
+ _PRIVATE_KEY_MARKERS: tuple[bytes, ...] = (
61
+ b"-----BEGIN PRIVATE KEY-----",
62
+ b"-----BEGIN ENCRYPTED PRIVATE KEY-----",
63
+ b"-----BEGIN RSA PRIVATE KEY-----",
64
+ b"-----BEGIN EC PRIVATE KEY-----",
65
+ b"-----BEGIN DSA PRIVATE KEY-----",
66
+ b"-----BEGIN OPENSSH PRIVATE KEY-----",
67
+ b"-----BEGIN PGP PRIVATE KEY BLOCK-----",
68
+ )
69
+
70
+ _PRIVATE_KEY_NAME_RE = re.compile(
71
+ r"(?:^|[._/-])(private|privkey|secret)(?:[._/-]|$)|\.(?:key|key\.pem|p12|pfx|jks)$|^id_(?:ed25519|rsa|ecdsa)$",
72
+ re.IGNORECASE,
73
+ )
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class CompliancePackResult:
78
+ output_dir: Path
79
+ manifest_path: Path
80
+ dossier_html_path: Path
81
+ zip_path: Path
82
+ manifest_sha256: str
83
+ overall_status: str
84
+ readiness_score_pct: int
85
+ evidence_count: int
86
+ manifest: dict[str, Any]
87
+
88
+ def to_dict(self) -> dict[str, Any]:
89
+ return {
90
+ "output_dir": str(self.output_dir),
91
+ "manifest_path": str(self.manifest_path),
92
+ "dossier_html_path": str(self.dossier_html_path),
93
+ "zip_path": str(self.zip_path),
94
+ "manifest_sha256": self.manifest_sha256,
95
+ "overall_status": self.overall_status,
96
+ "readiness_score_pct": self.readiness_score_pct,
97
+ "evidence_count": self.evidence_count,
98
+ "clauses": {
99
+ k: {
100
+ "standard": v.get("standard"),
101
+ "status": v.get("status"),
102
+ }
103
+ for k, v in self.manifest.get("clauses", {}).items()
104
+ },
105
+ }
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class ComplianceVerifyResult:
110
+ valid: bool
111
+ target: str
112
+ manifest_sha256: str | None
113
+ files_verified: int
114
+ errors: list[str] = field(default_factory=list)
115
+ warnings: list[str] = field(default_factory=list)
116
+
117
+ def to_dict(self) -> dict[str, Any]:
118
+ return asdict(self)
119
+
120
+
121
+ def _sha256_bytes(raw: bytes) -> str:
122
+ return hashlib.sha256(raw).hexdigest()
123
+
124
+
125
+ def _is_private_key_name(rel_posix: str) -> bool:
126
+ lower = rel_posix.lower()
127
+ name = Path(rel_posix).name.lower()
128
+ if lower.endswith(".pem"):
129
+ # Never bundle ANY .pem private key (and exclude all .pem files from evidence bundles)
130
+ if "private" in name or name.endswith(".key.pem") or "priv" in name:
131
+ return True
132
+ if _PRIVATE_KEY_NAME_RE.search(name):
133
+ return True
134
+ return False
135
+
136
+
137
+ def _contains_private_key_material(raw: bytes) -> bool:
138
+ for marker in _PRIVATE_KEY_MARKERS:
139
+ if marker in raw:
140
+ return True
141
+ # Detect Ed25519 / OKP JWK containing private scalar "d"
142
+ if b'"crv"' in raw and b'"Ed25519"' in raw and b'"d"' in raw:
143
+ try:
144
+ parsed = json.loads(raw.decode("utf-8"))
145
+ if isinstance(parsed, dict) and parsed.get("kty") == "OKP" and parsed.get("d"):
146
+ return True
147
+ except Exception:
148
+ pass
149
+ return False
150
+
151
+
152
+ def _is_prohibited_key_artifact(rel_posix: str, raw: bytes | None = None) -> bool:
153
+ """Return True if a file is a private key or any .pem key file that must never enter the ZIP."""
154
+ if rel_posix.lower().endswith(".pem"):
155
+ return True
156
+ if _is_private_key_name(rel_posix):
157
+ return True
158
+ if raw is not None and _contains_private_key_material(raw):
159
+ return True
160
+ return False
161
+
162
+
163
+ def _find_public_key(root: Path, cfg: GateConfig) -> Path | None:
164
+ candidates: list[Path] = []
165
+ if cfg.public_key_path:
166
+ candidates.append(root / cfg.public_key_path)
167
+ candidates.extend(
168
+ [
169
+ root / ".robot-gate" / "keys" / "robot_gate.pub.pem",
170
+ root / ".robot-gate" / "keys" / "ed25519_public.pem",
171
+ root / "ed25519_public.pem",
172
+ ]
173
+ )
174
+ for cand in candidates:
175
+ if cand.is_file():
176
+ try:
177
+ raw = cand.read_bytes()
178
+ if not _contains_private_key_material(raw):
179
+ return cand
180
+ except OSError:
181
+ continue
182
+ return None
183
+
184
+
185
+ def _count_excluded_private_keys(root: Path) -> int:
186
+ count = 0
187
+ for p in sorted(root.rglob("*")):
188
+ if not p.is_file():
189
+ continue
190
+ if any(part in {"__pycache__", ".git", ".venv", "compliance_pack"} for part in p.parts):
191
+ continue
192
+ rel = p.resolve().relative_to(root).as_posix()
193
+ if _is_private_key_name(rel):
194
+ count += 1
195
+ continue
196
+ if p.suffix.lower() in {".pem", ".key", ".json", ".yaml", ".yml", ".txt"}:
197
+ try:
198
+ if p.stat().st_size <= 256_000 and _contains_private_key_material(p.read_bytes()):
199
+ count += 1
200
+ except OSError:
201
+ continue
202
+ return count
203
+
204
+
205
+ def _collect_evidence_candidates(
206
+ root: Path,
207
+ cfg: GateConfig,
208
+ ) -> tuple[list[tuple[Path, str, str]], int]:
209
+ """Collect (abs_path, workspace_rel_posix, category) for compliance evidence.
210
+
211
+ Strictly excludes any private key or `.pem` file. Returns `(items, excluded_key_count)`.
212
+ """
213
+ seen_rel: set[str] = set()
214
+ items: list[tuple[Path, str, str]] = []
215
+ excluded_keys = 0
216
+
217
+ def _add(path: Path, category: str) -> None:
218
+ nonlocal excluded_keys
219
+ if not path.is_file():
220
+ return
221
+ try:
222
+ rel = path.resolve().relative_to(root).as_posix()
223
+ except ValueError:
224
+ return
225
+ if rel in seen_rel:
226
+ return
227
+ try:
228
+ raw = path.read_bytes()
229
+ except OSError:
230
+ return
231
+ if _is_prohibited_key_artifact(rel, raw):
232
+ excluded_keys += 1
233
+ return
234
+ seen_rel.add(rel)
235
+ items.append((path.resolve(), rel, category))
236
+
237
+ # Core workspace files
238
+ _add(root / cfg.manifest_path, "manifest")
239
+ _add(root / "gate.yaml", "gate_config")
240
+ _add(root / "envelope.json", "envelope")
241
+ _add(root / ".robot-gate" / "envelope.json", "envelope")
242
+ _add(root / cfg.hardware_profile_path, "hardware_profile")
243
+ _add(root / ".robot-gate" / "hardware_profile.json", "hardware_profile")
244
+ _add(root / "hardware_profile.json", "hardware_profile")
245
+ _add(root / cfg.receipt_path, "gate_receipt")
246
+ _add(root / ".robot-gate" / "gate_receipt.json", "gate_receipt")
247
+ _add(root / ".robot-gate" / "trust_ladder.json", "trust_ladder")
248
+ _add(root / ".robot-gate" / "trust_state.json", "trust_ladder")
249
+ _add(root / cfg.audit_path, "audit_log")
250
+ _add(root / ".robot-gate" / "audit_log.jsonl", "audit_log")
251
+ _add(root / "datums.yaml", "calibration")
252
+ _add(root / "skill_pack.yaml", "skill_pack")
253
+
254
+ # Skills (*.yaml / *.yml)
255
+ skills_dir = root / "skills"
256
+ if skills_dir.is_dir():
257
+ for child in sorted(skills_dir.rglob("*")):
258
+ if child.is_file() and "__pycache__" not in child.parts:
259
+ if child.suffix.lower() in {".yaml", ".yml", ".json"}:
260
+ _add(child, "skill")
261
+ elif _is_prohibited_key_artifact(child.resolve().relative_to(root).as_posix()):
262
+ excluded_keys += 1
263
+
264
+ # Policies (*.yaml / *.yml / *.json)
265
+ policies_dir = root / "policies"
266
+ if policies_dir.is_dir():
267
+ for child in sorted(policies_dir.rglob("*")):
268
+ if child.is_file() and "__pycache__" not in child.parts:
269
+ if child.suffix.lower() in {".yaml", ".yml", ".json"}:
270
+ _add(child, "policy")
271
+ elif _is_prohibited_key_artifact(child.resolve().relative_to(root).as_posix()):
272
+ excluded_keys += 1
273
+
274
+ # Also count any private keys present anywhere in workspace (e.g. .robot-gate/keys/ or root)
275
+ workspace_priv_count = _count_excluded_private_keys(root)
276
+ return items, max(excluded_keys, workspace_priv_count)
277
+
278
+
279
+ def _verify_trust_ladder_file(trust_path: Path) -> dict[str, Any]:
280
+ if not trust_path.is_file():
281
+ return {
282
+ "present": False,
283
+ "path": None,
284
+ "chain_valid": False,
285
+ "head_sha256": None,
286
+ "robots": {},
287
+ "history_count": 0,
288
+ "error": "trust_ladder.json not found",
289
+ }
290
+ try:
291
+ raw = json.loads(trust_path.read_text(encoding="utf-8"))
292
+ except Exception as exc:
293
+ return {
294
+ "present": True,
295
+ "path": trust_path.name,
296
+ "chain_valid": False,
297
+ "head_sha256": None,
298
+ "robots": {},
299
+ "history_count": 0,
300
+ "error": f"invalid JSON: {exc}",
301
+ }
302
+
303
+ history = list(raw.get("history", []))
304
+ chain_valid = True
305
+ chain_error: str | None = None
306
+ if history:
307
+ prev = str(history[0].get("prev_sha256", "0" * 64))
308
+ for idx, entry in enumerate(history):
309
+ if str(entry.get("prev_sha256")) != prev:
310
+ chain_valid = False
311
+ chain_error = f"history[{idx}] broken prev_sha256 link"
312
+ break
313
+ body = {k: v for k, v in entry.items() if k != "sha256"}
314
+ expected = sha256_canonical(body)
315
+ if str(entry.get("sha256")) != expected:
316
+ chain_valid = False
317
+ chain_error = f"history[{idx}] sha256 mismatch"
318
+ break
319
+ prev = expected
320
+ if chain_valid and raw.get("head_sha256") and str(raw.get("head_sha256")) != prev:
321
+ chain_valid = False
322
+ chain_error = "head_sha256 does not match final history entry"
323
+
324
+ robots_out: dict[str, Any] = {}
325
+ for rid, rec in (raw.get("robots") or {}).items():
326
+ lvl_int = int(rec.get("level", 0))
327
+ lvl = TrustLevel(lvl_int)
328
+ pol = TRUST_POLICIES[lvl]
329
+ robots_out[str(rid)] = {
330
+ "level": lvl_int,
331
+ "level_name": lvl.name,
332
+ "label": pol.label,
333
+ "speed_scale": pol.speed_scale,
334
+ "force_scale": pol.force_scale,
335
+ "requires_hitl": pol.requires_hitl_approval,
336
+ "clean_runs_at_level": int(rec.get("clean_runs_at_level", 0)),
337
+ "total_verified_runs": int(rec.get("total_verified_runs", 0)),
338
+ "demotions": int(rec.get("demotions", 0)),
339
+ "unlocked_skills": list(rec.get("unlocked_skills", [])),
340
+ "last_event": str(rec.get("last_event", "")),
341
+ }
342
+
343
+ return {
344
+ "present": True,
345
+ "chain_valid": chain_valid,
346
+ "head_sha256": str(raw.get("head_sha256", "")),
347
+ "robots": robots_out,
348
+ "history_count": len(history),
349
+ "error": chain_error,
350
+ }
351
+
352
+
353
+ def _inspect_skills(root: Path, evidence_items: list[tuple[Path, str, str]]) -> list[dict[str, Any]]:
354
+ skills_out: list[dict[str, Any]] = []
355
+ for abs_p, rel, cat in evidence_items:
356
+ if cat != "skill":
357
+ continue
358
+ skill_name = abs_p.stem
359
+ step_count = 0
360
+ frozen_l3 = skill_name.lower().startswith("l3_") or "autonomous" in skill_name.lower() or "shift" in skill_name.lower()
361
+ pack_id: str | None = None
362
+ try:
363
+ doc = yaml.safe_load(abs_p.read_text(encoding="utf-8"))
364
+ if isinstance(doc, dict):
365
+ skill_name = str(doc.get("skill") or doc.get("name") or skill_name)
366
+ pack_id = str(doc["pack_id"]) if doc.get("pack_id") else None
367
+ steps = doc.get("steps")
368
+ if isinstance(steps, list):
369
+ step_count = len(steps)
370
+ if str(doc.get("trust_level", "")).upper().startswith("L3") or doc.get("frozen") is True:
371
+ frozen_l3 = True
372
+ except Exception:
373
+ pass
374
+ skills_out.append(
375
+ {
376
+ "path": rel,
377
+ "skill_name": skill_name,
378
+ "pack_id": pack_id,
379
+ "step_count": step_count,
380
+ "frozen_l3_candidate": frozen_l3,
381
+ "sha256": sha256_file(abs_p),
382
+ }
383
+ )
384
+ return skills_out
385
+
386
+
387
+ def _read_recent_audit_events(audit_path: Path, limit: int = 12) -> list[dict[str, Any]]:
388
+ if not audit_path.is_file():
389
+ return []
390
+ records: list[dict[str, Any]] = []
391
+ for line in audit_path.read_text(encoding="utf-8").splitlines():
392
+ if not line.strip():
393
+ continue
394
+ try:
395
+ rec = json.loads(line)
396
+ records.append(
397
+ {
398
+ "ts": rec.get("ts"),
399
+ "event": rec.get("event"),
400
+ "decision": rec.get("decision"),
401
+ "hash": str(rec.get("hash", ""))[:16],
402
+ "details": rec.get("details", {}),
403
+ }
404
+ )
405
+ except json.JSONDecodeError:
406
+ break
407
+ return records[-limit:]
408
+
409
+
410
+ def _badge_class(status: str) -> str:
411
+ s = status.upper()
412
+ if s in {"PASS", "READY", "VALID", "ATTESTED", "VERIFIED", "INTACT"}:
413
+ return "badge-pass"
414
+ if s in {"PARTIAL", "NEEDS_ATTENTION", "WARN"}:
415
+ return "badge-warn"
416
+ return "badge-fail"
417
+
418
+
419
+ def _render_compliance_dossier_html(manifest: dict[str, Any]) -> str:
420
+ """Render a Warm Workshop printable HTML audit report with ZERO external CDN dependencies."""
421
+ e = html.escape
422
+ ws = manifest["workspace"]
423
+ gen = manifest["generator"]
424
+ clauses = manifest["clauses"]
425
+ iso = clauses["iso_10218_2025_cybersecurity"]
426
+ eu = clauses["eu_2023_1230_machinery_regulation"]
427
+ hw = clauses["iso_13850_13849_hardware_boundary"]
428
+ sec = manifest["security_exclusions"]
429
+
430
+ iso_ctrl = iso["controls"]
431
+ eu_ctrl = eu["controls"]
432
+ sig = iso_ctrl["ed25519_manifest_signature"]
433
+ latch = iso_ctrl["hard_receipt_latch"]
434
+ audit_c = iso_ctrl["tamper_evident_audit_chain"]
435
+ env_c = iso_ctrl["envelope_provenance"]
436
+ sbom = iso_ctrl["software_sbom_sha256_inventory"]
437
+ annex = eu_ctrl["annex_iii_software_traceability"]
438
+ ai_b = eu_ctrl["ai_self_evolving_behavior_bounding"]
439
+ mod = eu_ctrl["substantial_modification_change_control"]
440
+
441
+ # Build 4-stage gate table rows
442
+ stage_rows = ""
443
+ for st in latch.get("stages_summary") or []:
444
+ st_status = "PASS" if st.get("passed") else "FAIL"
445
+ stage_rows += (
446
+ f"<tr>"
447
+ f"<td><code>{e(str(st.get('name', '')))}</code></td>"
448
+ f"<td><span class='badge {_badge_class(st_status)}'>{e(st_status)}</span></td>"
449
+ f"<td>{e(str(st.get('summary', '')))}</td>"
450
+ f"</tr>"
451
+ )
452
+ if not stage_rows:
453
+ stage_rows = "<tr><td colspan='3' class='muted'>No signed gate_receipt.json stages recorded yet. Run <code>robot-gate check --sim-only</code>.</td></tr>"
454
+
455
+ # Build SBOM rows
456
+ sbom_rows = ""
457
+ for item in sbom.get("items") or []:
458
+ sbom_rows += (
459
+ f"<tr>"
460
+ f"<td><code>{e(str(item['path']))}</code></td>"
461
+ f"<td><span class='pill'>{e(str(item['category']))}</span></td>"
462
+ f"<td class='mono'>{e(str(item['sha256']))}</td>"
463
+ f"<td class='num'>{int(item['size_bytes']):,} B</td>"
464
+ f"</tr>"
465
+ )
466
+ if not sbom_rows:
467
+ sbom_rows = "<tr><td colspan='4' class='muted'>No workspace artifacts found.</td></tr>"
468
+
469
+ # Build Trust Ladder robot rows
470
+ trust_rows = ""
471
+ for rid, rinfo in (ai_b.get("robots") or {}).items():
472
+ trust_rows += (
473
+ f"<tr>"
474
+ f"<td><code>{e(str(rid))}</code></td>"
475
+ f"<td><strong>{e(str(rinfo.get('label', rinfo.get('level_name', ''))))}</strong></td>"
476
+ f"<td class='num'>{int(round(float(rinfo.get('speed_scale', 0.0)) * 100))}% / {int(round(float(rinfo.get('force_scale', 0.0)) * 100))}%</td>"
477
+ f"<td>{'Required' if rinfo.get('requires_hitl') else 'Frozen L3'}</td>"
478
+ f"<td class='num'>{int(rinfo.get('total_verified_runs', 0))} ({int(rinfo.get('demotions', 0))} demotions)</td>"
479
+ f"</tr>"
480
+ )
481
+ if not trust_rows:
482
+ trust_rows = "<tr><td colspan='5' class='muted'>No trust_ladder.json records present (defaults fail-closed to L0_OBSERVE).</td></tr>"
483
+
484
+ # Build Frozen / YAML skills rows
485
+ skill_rows = ""
486
+ for sk in ai_b.get("frozen_skills") or []:
487
+ tier_label = "L3 Frozen Candidate" if sk.get("frozen_l3_candidate") else "Bounded YAML Skill"
488
+ skill_rows += (
489
+ f"<tr>"
490
+ f"<td><code>{e(str(sk['path']))}</code></td>"
491
+ f"<td>{e(str(sk['skill_name']))}</td>"
492
+ f"<td><span class='pill'>{e(tier_label)}</span></td>"
493
+ f"<td class='num'>{int(sk.get('step_count', 0))}</td>"
494
+ f"<td class='mono'>{e(str(sk['sha256'])[:24])}…</td>"
495
+ f"</tr>"
496
+ )
497
+ if not skill_rows:
498
+ skill_rows = "<tr><td colspan='5' class='muted'>No YAML skills found under <code>skills/</code>.</td></tr>"
499
+
500
+ # Build Change-Control audit rows
501
+ change_rows = ""
502
+ for ev in mod.get("recent_audit_events") or []:
503
+ dec = str(ev.get("decision", ""))
504
+ change_rows += (
505
+ f"<tr>"
506
+ f"<td class='mono'>{e(str(ev.get('ts', '')))}</td>"
507
+ f"<td><code>{e(str(ev.get('event', '')))}</code></td>"
508
+ f"<td><span class='badge {_badge_class(dec)}'>{e(dec)}</span></td>"
509
+ f"<td class='mono'>{e(str(ev.get('hash', '')))}…</td>"
510
+ f"</tr>"
511
+ )
512
+ if not change_rows:
513
+ change_rows = "<tr><td colspan='4' class='muted'>No audit_log.jsonl events recorded yet.</td></tr>"
514
+
515
+ # Build Integrator checklist items
516
+ checklist_li = "".join(
517
+ f"<li><span class='checkbox'>&#9744;</span> {e(str(item))}</li>"
518
+ for item in hw.get("checklist_for_integrator") or []
519
+ )
520
+
521
+ overall_status = str(manifest["overall_status"])
522
+ score_pct = int(manifest["readiness_score_pct"])
523
+ fp_diff = mod.get("fingerprint_diff") or {}
524
+ diff_summary = (
525
+ f"added={len(fp_diff.get('added', []))}, "
526
+ f"changed={len(fp_diff.get('changed', []))}, "
527
+ f"removed={len(fp_diff.get('removed', []))}"
528
+ )
529
+
530
+ return f"""<!DOCTYPE html>
531
+ <html lang="en">
532
+ <head>
533
+ <meta charset="utf-8" />
534
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
535
+ <title>Graft Robotics — Compliance Dossier ({e(str(ws['embodiment']))})</title>
536
+ <style>
537
+ :root {{
538
+ --gr-paper: #f5f2eb;
539
+ --gr-card: #fffdf9;
540
+ --gr-sand: #eae4d7;
541
+ --gr-line: #dad2c3;
542
+ --gr-line-strong: #bfb5a3;
543
+ --gr-ink: #181715;
544
+ --gr-ink-soft: #57524a;
545
+ --gr-ink-muted: #847d72;
546
+ --gr-moss: #1f6f4a;
547
+ --gr-moss-soft: #e3f2ea;
548
+ --gr-vermilion: #e85d2a;
549
+ --gr-vermilion-soft: #fdebe4;
550
+ --gr-ochre: #c27803;
551
+ --gr-ochre-soft: #fef3db;
552
+ --gr-cobalt: #2563eb;
553
+ --gr-cobalt-soft: #e8f0fe;
554
+ --gr-font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
555
+ --gr-font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
556
+ }}
557
+ * {{ box-sizing: border-box; }}
558
+ html {{ overflow-x: hidden; }}
559
+ body {{
560
+ margin: 0;
561
+ padding: 28px 20px 56px;
562
+ background: var(--gr-paper);
563
+ color: var(--gr-ink);
564
+ font-family: var(--gr-font-sans);
565
+ font-size: 14px;
566
+ line-height: 1.55;
567
+ overflow-x: hidden;
568
+ max-width: 100%;
569
+ }}
570
+ .container {{ width: 100%; max-width: 1020px; margin: 0 auto; }}
571
+ header.hero {{
572
+ background: var(--gr-card);
573
+ border: 1px solid var(--gr-line);
574
+ border-top: 4px solid var(--gr-ink);
575
+ border-radius: 14px;
576
+ padding: 24px 28px;
577
+ margin-bottom: 18px;
578
+ display: flex;
579
+ flex-wrap: wrap;
580
+ justify-content: space-between;
581
+ gap: 16px;
582
+ }}
583
+ header.hero > div {{ min-width: 0; max-width: 100%; }}
584
+ .eyebrow {{
585
+ font-family: var(--gr-font-mono);
586
+ font-size: 11px;
587
+ letter-spacing: 0.08em;
588
+ text-transform: uppercase;
589
+ color: var(--gr-ink-muted);
590
+ margin: 0 0 6px;
591
+ }}
592
+ h1 {{ margin: 0 0 6px; font-size: 24px; line-height: 1.2; overflow-wrap: break-word; }}
593
+ h2 {{
594
+ margin: 0 0 12px;
595
+ font-size: 17px;
596
+ display: flex;
597
+ flex-wrap: wrap;
598
+ align-items: center;
599
+ justify-content: space-between;
600
+ gap: 10px;
601
+ border-bottom: 1px solid var(--gr-line);
602
+ padding-bottom: 8px;
603
+ }}
604
+ h3 {{ margin: 16px 0 8px; font-size: 13px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--gr-ink-soft); }}
605
+ .subtitle {{ margin: 0; color: var(--gr-ink-soft); overflow-wrap: anywhere; }}
606
+ .scorebox {{
607
+ min-width: 210px;
608
+ max-width: 100%;
609
+ background: var(--gr-sand);
610
+ border: 1px solid var(--gr-line-strong);
611
+ border-radius: 10px;
612
+ padding: 14px 16px;
613
+ text-align: right;
614
+ }}
615
+ .score-num {{ font-size: 28px; font-weight: 700; line-height: 1.1; margin: 4px 0; }}
616
+ .boundary-banner {{
617
+ background: var(--gr-vermilion-soft);
618
+ border: 1.5px solid var(--gr-vermilion);
619
+ border-radius: 12px;
620
+ padding: 16px 20px;
621
+ margin-bottom: 18px;
622
+ overflow-wrap: break-word;
623
+ }}
624
+ .boundary-banner strong {{ color: #9a2f0c; }}
625
+ .card {{
626
+ background: var(--gr-card);
627
+ border: 1px solid var(--gr-line);
628
+ border-radius: 14px;
629
+ padding: 20px 24px;
630
+ margin-bottom: 18px;
631
+ break-inside: avoid;
632
+ min-width: 0;
633
+ max-width: 100%;
634
+ }}
635
+ .meta-grid {{
636
+ display: grid;
637
+ grid-template-columns: repeat(auto-fit, minmax(min(210px, 100%), 1fr));
638
+ gap: 10px;
639
+ margin-top: 12px;
640
+ }}
641
+ .kv {{
642
+ background: var(--gr-paper);
643
+ border: 1px solid var(--gr-line);
644
+ border-radius: 8px;
645
+ padding: 10px 12px;
646
+ min-width: 0;
647
+ }}
648
+ .kv .k {{ font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--gr-ink-muted); }}
649
+ .kv .v {{ font-weight: 600; margin-top: 2px; overflow-wrap: anywhere; word-break: break-word; }}
650
+ .badge {{
651
+ display: inline-block;
652
+ padding: 2px 9px;
653
+ border-radius: 999px;
654
+ font-family: var(--gr-font-mono);
655
+ font-size: 11px;
656
+ font-weight: 700;
657
+ letter-spacing: 0.04em;
658
+ border: 1px solid transparent;
659
+ max-width: 100%;
660
+ }}
661
+ .badge-pass {{ background: var(--gr-moss-soft); color: var(--gr-moss); border-color: #b7dec9; }}
662
+ .badge-warn {{ background: var(--gr-ochre-soft); color: var(--gr-ochre); border-color: #f2d59b; }}
663
+ .badge-fail {{ background: var(--gr-vermilion-soft); color: #b53810; border-color: #f3b59f; }}
664
+ .pill {{
665
+ display: inline-block;
666
+ padding: 1px 7px;
667
+ border-radius: 6px;
668
+ background: var(--gr-sand);
669
+ color: var(--gr-ink-soft);
670
+ font-family: var(--gr-font-mono);
671
+ font-size: 11px;
672
+ }}
673
+ .table-wrap {{
674
+ width: 100%;
675
+ max-width: 100%;
676
+ overflow-x: auto;
677
+ -webkit-overflow-scrolling: touch;
678
+ }}
679
+ table {{ width: 100%; border-collapse: collapse; margin-top: 8px; font-size: 13px; }}
680
+ th, td {{ text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--gr-line); vertical-align: top; }}
681
+ th {{ font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--gr-ink-muted); background: var(--gr-paper); }}
682
+ td.num {{ text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }}
683
+ pre, code, .mono {{ font-family: var(--gr-font-mono); font-size: 12px; overflow-wrap: anywhere; word-break: break-word; }}
684
+ pre {{ max-width: 100%; overflow-x: auto; }}
685
+ .muted {{ color: var(--gr-ink-muted); }}
686
+ ul.checklist {{ list-style: none; padding: 0; margin: 10px 0 0; }}
687
+ ul.checklist li {{ padding: 6px 0; border-bottom: 1px dashed var(--gr-line); }}
688
+ .checkbox {{ font-family: var(--gr-font-mono); margin-right: 8px; color: var(--gr-vermilion); }}
689
+ .signoff {{
690
+ display: grid;
691
+ grid-template-columns: repeat(3, 1fr);
692
+ gap: 16px;
693
+ margin-top: 18px;
694
+ }}
695
+ .signoff-box {{
696
+ border-top: 1px solid var(--gr-ink);
697
+ padding-top: 6px;
698
+ font-size: 12px;
699
+ color: var(--gr-ink-soft);
700
+ min-width: 0;
701
+ }}
702
+ footer {{
703
+ margin-top: 24px;
704
+ font-size: 12px;
705
+ color: var(--gr-ink-muted);
706
+ text-align: center;
707
+ }}
708
+ @media (max-width: 640px) {{
709
+ body {{ padding: 14px 12px 36px; font-size: 13px; }}
710
+ header.hero {{ padding: 16px; flex-direction: column; align-items: stretch; gap: 12px; }}
711
+ .scorebox {{ min-width: 0; width: 100%; text-align: left; }}
712
+ h1 {{ font-size: 20px; }}
713
+ h2 {{ font-size: 15px; gap: 6px; }}
714
+ .card {{ padding: 14px; border-radius: 10px; }}
715
+ .boundary-banner {{ padding: 12px 14px; }}
716
+ .meta-grid {{ grid-template-columns: 1fr; }}
717
+ .signoff {{ grid-template-columns: 1fr; gap: 12px; }}
718
+ th, td {{ padding: 6px 8px; font-size: 12px; }}
719
+ }}
720
+ @media print {{
721
+ body {{ background: #ffffff; padding: 0; }}
722
+ .card, header.hero, .boundary-banner {{ box-shadow: none; }}
723
+ .card {{ break-inside: avoid; }}
724
+ .table-wrap {{ overflow-x: visible; }}
725
+ }}
726
+ </style>
727
+ </head>
728
+ <body>
729
+ <div class="container">
730
+
731
+ <header class="hero">
732
+ <div>
733
+ <p class="eyebrow">GRAFT ROBOTICS · OFFLINE-VERIFIABLE COMPLIANCE DOSSIER</p>
734
+ <h1>ISO 10218:2025 &amp; EU (2023/1230) Technical Readiness Report</h1>
735
+ <p class="subtitle">
736
+ Workspace: <code>{e(str(ws['name']))}</code> ·
737
+ Embodiment: <strong>{e(str(ws['embodiment']))}</strong> ·
738
+ Organization: <strong>{e(str(ws['organization']))}</strong>
739
+ </p>
740
+ <p class="subtitle muted" style="margin-top:6px;">
741
+ Generated UTC: <code>{e(str(manifest['generated_at_utc']))}</code> ·
742
+ Generator: <code>robot-gate {e(str(gen['version']))}</code> (<code>bounded-embodiment {e(str(gen['bounded_embodiment_version']))}</code>)
743
+ </p>
744
+ </div>
745
+ <div class="scorebox">
746
+ <div class="eyebrow" style="margin:0;">OVERALL STATUS</div>
747
+ <div class="score-num">{score_pct}%</div>
748
+ <span class="badge {_badge_class(overall_status)}">{e(overall_status)}</span>
749
+ <div class="muted" style="font-size:11px;margin-top:6px;">FP: <code>{e(str(ws['fingerprint'])[:16])}…</code></div>
750
+ </div>
751
+ </header>
752
+
753
+ <section class="boundary-banner" aria-label="Mandatory ISO 13850 and ISO 13849-1 Hardware Boundary">
754
+ <strong>MANDATORY HARDWARE SAFETY BOUNDARY — ZERO PL/SIL CREDIT CLAIMED:</strong>
755
+ <p style="margin:6px 0 0;">{e(ISO_13850_HARDWARE_BOUNDARY_ATTESTATION)}</p>
756
+ </section>
757
+
758
+ <section class="card">
759
+ <h2>
760
+ <span>1. {e(str(iso['standard']))} — Safety Cybersecurity</span>
761
+ <span class="badge {_badge_class(str(iso['status']))}">{e(str(iso['status']))}</span>
762
+ </h2>
763
+ <div class="meta-grid">
764
+ <div class="kv">
765
+ <div class="k">Ed25519 Manifest Signature</div>
766
+ <div class="v"><span class="badge {_badge_class(str(sig['status']))}">{e(str(sig['status']))}</span> · kid=<code>{e(str(sig.get('kid') or 'none'))}</code></div>
767
+ <div class="muted" style="font-size:12px;margin-top:4px;">{e(str(sig.get('reason', '')))}</div>
768
+ </div>
769
+ <div class="kv">
770
+ <div class="k">Hard Receipt Latch</div>
771
+ <div class="v"><span class="badge {_badge_class(str(latch['status']))}">{e(str(latch['status']))}</span> · alg=<code>{e(str(latch.get('signature_alg') or 'none'))}</code></div>
772
+ <div class="muted" style="font-size:12px;margin-top:4px;">Live fingerprint match: <strong>{e('YES' if latch.get('fingerprint_matches_live_workspace') else 'NO')}</strong> · {e(str(latch.get('signature_reason', '')))}</div>
773
+ </div>
774
+ <div class="kv">
775
+ <div class="k">Tamper-Evident Audit Chain</div>
776
+ <div class="v"><span class="badge {_badge_class(str(audit_c['status']))}">{e(str(audit_c['status']))}</span> · {int(audit_c.get('record_count', 0))} records</div>
777
+ <div class="muted" style="font-size:12px;margin-top:4px;">Head: <code>{e(str(audit_c.get('head_hash', ''))[:16])}…</code></div>
778
+ </div>
779
+ <div class="kv">
780
+ <div class="k">Envelope 0.2 Provenance</div>
781
+ <div class="v"><span class="badge {_badge_class(str(env_c['status']))}">{e(str(env_c['status']))}</span></div>
782
+ <div class="muted" style="font-size:12px;margin-top:4px;">{e(str(env_c.get('note', '')))}</div>
783
+ </div>
784
+ </div>
785
+
786
+ <h3>4-Stage Pre-Flight Gate Receipt Evidence</h3>
787
+ <div class="table-wrap">
788
+ <table>
789
+ <thead><tr><th>Stage</th><th>Status</th><th>Summary</th></tr></thead>
790
+ <tbody>{stage_rows}</tbody>
791
+ </table>
792
+ </div>
793
+
794
+ <h3>Software, Skill &amp; Policy SHA-256 Inventory (SBOM)</h3>
795
+ <div class="table-wrap">
796
+ <table>
797
+ <thead><tr><th>Workspace Artifact</th><th>Category</th><th>SHA-256 Digest</th><th style="text-align:right;">Size</th></tr></thead>
798
+ <tbody>{sbom_rows}</tbody>
799
+ </table>
800
+ </div>
801
+ </section>
802
+
803
+ <section class="card">
804
+ <h2>
805
+ <span>2. {e(str(eu['standard']))} — Annex III &amp; AI Behavior Bounding</span>
806
+ <span class="badge {_badge_class(str(eu['status']))}">{e(str(eu['status']))}</span>
807
+ </h2>
808
+ <div class="meta-grid">
809
+ <div class="kv">
810
+ <div class="k">Annex III Software Traceability</div>
811
+ <div class="v"><span class="badge {_badge_class(str(annex['status']))}">{e(str(annex['status']))}</span></div>
812
+ <div class="muted" style="font-size:12px;margin-top:4px;">Manifest={e(str(annex['manifest_present']))}, Envelope={e(str(annex['envelope_present']))}, Profile={e(str(annex['hardware_profile_present']))}, Receipt={e(str(annex['receipt_present']))}</div>
813
+ </div>
814
+ <div class="kv">
815
+ <div class="k">AI / Self-Evolving Bounding</div>
816
+ <div class="v"><span class="badge {_badge_class(str(ai_b['status']))}">{e(str(ai_b['status']))}</span> · {int(ai_b.get('frozen_l3_skills_count', 0))} L3 skills</div>
817
+ <div class="muted" style="font-size:12px;margin-top:4px;">Trust chain valid: <strong>{e(str(ai_b.get('trust_chain_valid')))}</strong> · Max vel={e(str(ai_b.get('bounds_summary', {}).get('max_tcp_velocity_mps', 'n/a')))} m/s, Max force={e(str(ai_b.get('bounds_summary', {}).get('max_contact_force_n', 'n/a')))} N</div>
818
+ </div>
819
+ <div class="kv">
820
+ <div class="k">Substantial Modification Control</div>
821
+ <div class="v"><span class="badge {_badge_class(str(mod['status']))}">{e(str(mod['status']))}</span></div>
822
+ <div class="muted" style="font-size:12px;margin-top:4px;">Diff: {e(diff_summary)} · Re-verification required: <strong>{e('YES' if mod.get('requires_re_verification') else 'NO')}</strong></div>
823
+ </div>
824
+ </div>
825
+
826
+ <h3>L0–L3 Progressive Trust Ladder State</h3>
827
+ <div class="table-wrap">
828
+ <table>
829
+ <thead><tr><th>Robot ID</th><th>Trust Level</th><th style="text-align:right;">Speed / Force Cap</th><th>HiTL Gate</th><th style="text-align:right;">Verified Runs</th></tr></thead>
830
+ <tbody>{trust_rows}</tbody>
831
+ </table>
832
+ </div>
833
+
834
+ <h3>Bounded &amp; Frozen YAML Skills Inventory</h3>
835
+ <div class="table-wrap">
836
+ <table>
837
+ <thead><tr><th>Skill File</th><th>Skill Name</th><th>Tier</th><th style="text-align:right;">Steps</th><th>SHA-256</th></tr></thead>
838
+ <tbody>{skill_rows}</tbody>
839
+ </table>
840
+ </div>
841
+
842
+ <h3>Substantial Modification &amp; Gate Change-Control Audit Log</h3>
843
+ <div class="table-wrap">
844
+ <table>
845
+ <thead><tr><th>UTC Timestamp</th><th>Event</th><th>Decision</th><th>Record SHA-256</th></tr></thead>
846
+ <tbody>{change_rows}</tbody>
847
+ </table>
848
+ </div>
849
+ </section>
850
+
851
+ <section class="card">
852
+ <h2>
853
+ <span>3. {e(str(hw['standard']))} — Hardware Boundary &amp; Integrator Sign-Off</span>
854
+ <span class="badge {_badge_class(str(hw['status']))}">{e(str(hw['status']))}</span>
855
+ </h2>
856
+ <p>{e(str(hw['attestation']))}</p>
857
+ <p class="muted"><strong>Software PL / SIL Credit Claimed:</strong> <code>{e(str(hw['pl_sil_credit_claimed']))}</code> (deterministic software boundary &amp; audit layer only).</p>
858
+ <h3>Mandatory Integrator &amp; EHS Verification Checklist</h3>
859
+ <ul class="checklist">{checklist_li}</ul>
860
+ <div class="signoff">
861
+ <div class="signoff-box">Systems Integrator / Controls Engineer<br />Signature &amp; Date</div>
862
+ <div class="signoff-box">EHS / Plant Safety Officer<br />Signature &amp; Date</div>
863
+ <div class="signoff-box">Notified Body / Insurer Reviewer<br />Signature &amp; Date</div>
864
+ </div>
865
+ </section>
866
+
867
+ <section class="card">
868
+ <h2>
869
+ <span>4. Offline Cryptographic Verification &amp; Key Hygiene</span>
870
+ <span class="badge badge-pass">AIR-GAPPED</span>
871
+ </h2>
872
+ <p>
873
+ <strong>Private Key Exclusion Policy:</strong> {e(str(sec['policy']))}<br />
874
+ Private keys detected in workspace and strictly excluded from this bundle: <strong>{int(sec['excluded_count'])}</strong>.
875
+ Zero <code>.pem</code> or private key files are packaged in <code>{e(str(manifest.get('bundle_filename', DEFAULT_ZIP_FILENAME)))}</code>.
876
+ </p>
877
+ <p>
878
+ <strong>Offline Verification Command:</strong>
879
+ <code>python3 -c "from robot_gate.compliance_pack import verify_compliance_pack; print(verify_compliance_pack('graft-compliance-pack.zip'))"</code>
880
+ </p>
881
+ </section>
882
+
883
+ <footer>
884
+ Graft Robotics · Deterministic Physical AI Deployment Gate · Generated offline with zero external CDN dependencies.
885
+ </footer>
886
+ </div>
887
+ </body>
888
+ </html>
889
+ """
890
+
891
+
892
+ def generate_compliance_pack(
893
+ workspace_dir: Path | str,
894
+ output_dir: Path | str | None = None,
895
+ *,
896
+ zip_filename: str = DEFAULT_ZIP_FILENAME,
897
+ organization: str | None = None,
898
+ embodiment: str | None = None,
899
+ ) -> CompliancePackResult:
900
+ """Generate an offline-verifiable ISO 10218:2025 & EU 2023/1230 compliance pack.
901
+
902
+ Produces:
903
+ - `output_dir/compliance_manifest.json` (with RFC 8785 JCS SHA-256 `manifest_sha256`)
904
+ - `output_dir/compliance_dossier.html` (printable Warm Workshop HTML report, 0 CDN deps)
905
+ - `output_dir/evidence/<rel_path>` (hashed copies of workspace evidence, 0 private keys)
906
+ - `output_dir/<zip_filename>` (self-contained ZIP verified by `verify_compliance_pack()`)
907
+ """
908
+ root = Path(workspace_dir).resolve()
909
+ if not root.is_dir():
910
+ raise FileNotFoundError(f"Workspace directory does not exist: {root}")
911
+
912
+ gate_yaml_path = root / "gate.yaml"
913
+ gate_yaml_present = gate_yaml_path.is_file()
914
+ cfg = GateConfig.load(gate_yaml_path) if gate_yaml_present else GateConfig()
915
+
916
+ out_dir = Path(output_dir).resolve() if output_dir is not None else (root / ".robot-gate" / "compliance_pack")
917
+ out_dir.mkdir(parents=True, exist_ok=True)
918
+ evidence_out_dir = out_dir / "evidence"
919
+
920
+ # 1. Inspect manifest (ROBOT.md) and Ed25519 signature
921
+ manifest_path = root / cfg.manifest_path
922
+ pub_key_path = _find_public_key(root, cfg)
923
+ pub_key_sha256: str | None = None
924
+ pub_key_jwk: dict[str, str] | None = None
925
+ if pub_key_path is not None:
926
+ pub_key_sha256 = sha256_file(pub_key_path)
927
+ try:
928
+ pub_key_jwk = public_pem_to_jwk(pub_key_path)
929
+ except Exception:
930
+ pub_key_jwk = None
931
+
932
+ emb_name = embodiment or cfg.embodiment or "unknown"
933
+ org_name = organization or "Unspecified Organization"
934
+ bounds_summary: dict[str, Any] = {}
935
+ manifest_loaded = False
936
+ manifest_error: str | None = None
937
+ sig_verified = False
938
+ sig_kid: str | None = None
939
+ sig_reason = "ROBOT.md not found"
940
+ sig_verified_via = "none"
941
+
942
+ if manifest_path.is_file():
943
+ try:
944
+ loaded_manifest = load_manifest(manifest_path)
945
+ manifest_loaded = True
946
+ if organization is None and loaded_manifest.data.get("organization"):
947
+ org_name = str(loaded_manifest.data["organization"])
948
+ emb_spec = loaded_manifest.get_embodiment(embodiment or cfg.embodiment)
949
+ emb_name = emb_spec.name
950
+ bounds_summary = {
951
+ "embodiment": emb_spec.name,
952
+ "hal_driver": emb_spec.hal_driver,
953
+ "dof": emb_spec.dof,
954
+ "workspace_min_m": list(emb_spec.workspace.bmin),
955
+ "workspace_max_m": list(emb_spec.workspace.bmax),
956
+ "exclusion_count": len(emb_spec.exclusions),
957
+ "max_tcp_velocity_mps": emb_spec.max_tcp_velocity_mps,
958
+ "max_contact_force_n": emb_spec.max_contact_force_n,
959
+ "allowed_tools_count": len(emb_spec.allowed_tools),
960
+ }
961
+ expected_kid = cfg.signing_kid if gate_yaml_present else loaded_manifest.signature_kid
962
+ sig_res = verify_manifest_signature(
963
+ manifest_path,
964
+ pub_key_path,
965
+ expected_kid=expected_kid,
966
+ )
967
+ sig_verified = sig_res.valid
968
+ sig_kid = sig_res.kid or loaded_manifest.signature_kid
969
+ sig_reason = sig_res.reason
970
+ sig_verified_via = sig_res.verified_via
971
+ except Exception as exc:
972
+ manifest_error = str(exc)
973
+ sig_reason = f"failed to parse ROBOT.md: {exc}"
974
+
975
+ # 2. Inspect Envelope 0.2 (prefer signed .robot-gate/envelope.json if present, else root envelope.json)
976
+ env_candidates = [root / ".robot-gate" / "envelope.json", root / "envelope.json"]
977
+ chosen_env_path: Path | None = None
978
+ for ec in env_candidates:
979
+ if ec.is_file():
980
+ chosen_env_path = ec
981
+ break
982
+ env_present = chosen_env_path is not None
983
+ env_valid = False
984
+ env_sig_verified = False
985
+ env_note = "envelope.json not found"
986
+ env_rel_path: str | None = None
987
+ if chosen_env_path is not None:
988
+ env_rel_path = chosen_env_path.resolve().relative_to(root).as_posix()
989
+ try:
990
+ env_doc = json.loads(chosen_env_path.read_text(encoding="utf-8"))
991
+ env_valid, env_note = validate_envelope_doc(env_doc)
992
+ if pub_key_path is not None and isinstance(env_doc, dict) and "signature" in env_doc:
993
+ env_sig_verified, env_sig_note = verify_envelope_signature(env_doc, pub_key_path)
994
+ env_note = f"{env_note}; {env_sig_note}"
995
+ except Exception as exc:
996
+ env_note = f"envelope.json unreadable/invalid: {exc}"
997
+
998
+ # 3. Inspect hardware profile
999
+ hw_candidates = [
1000
+ root / cfg.hardware_profile_path,
1001
+ root / ".robot-gate" / "hardware_profile.json",
1002
+ root / "hardware_profile.json",
1003
+ ]
1004
+ hw_profile_path = next((p for p in hw_candidates if p.is_file()), None)
1005
+ hw_profile_present = hw_profile_path is not None
1006
+
1007
+ # 4. Compute live workspace fingerprint & inspect GateReceipt hard latch
1008
+ watched = [Path(p) for p in cfg.watched_paths]
1009
+ fp = compute_fingerprint(root, watched)
1010
+ receipt_candidates = [root / cfg.receipt_path, root / ".robot-gate" / "gate_receipt.json"]
1011
+ receipt_path = next((p for p in receipt_candidates if p.is_file()), None)
1012
+
1013
+ receipt_present = receipt_path is not None
1014
+ receipt_passed = False
1015
+ receipt_sig_alg: str | None = None
1016
+ receipt_sig_ok = False
1017
+ receipt_sig_reason = "gate_receipt.json not found"
1018
+ receipt_ts_utc: str | None = None
1019
+ receipt_fp_matches = False
1020
+ receipt_diff: dict[str, list[str]] = {"added": [], "removed": [], "changed": []}
1021
+ receipt_stages: list[dict[str, Any]] = []
1022
+ if receipt_path is not None:
1023
+ try:
1024
+ rec = GateReceipt.load(receipt_path)
1025
+ receipt_passed = bool(rec.passed)
1026
+ receipt_sig_alg = rec.signature_alg
1027
+ receipt_ts_utc = rec.ts_utc
1028
+ receipt_fp_matches = rec.fingerprint == fp.digest
1029
+ receipt_diff = dict(rec.fingerprint_diff)
1030
+ receipt_stages = [
1031
+ {"name": s.name, "passed": s.passed, "summary": s.summary, "failures": list(s.failures)}
1032
+ for s in rec.stages
1033
+ ]
1034
+ receipt_sig_ok, receipt_sig_reason = verify_receipt_signature(rec, pub_key_path)
1035
+ if emb_name == "unknown" and rec.embodiment:
1036
+ emb_name = rec.embodiment
1037
+ except Exception as exc:
1038
+ receipt_sig_reason = f"failed to load gate_receipt.json: {exc}"
1039
+
1040
+ # 5. Inspect SHA-256 hash-chained audit log
1041
+ audit_candidates = [root / cfg.audit_path, root / ".robot-gate" / "audit_log.jsonl"]
1042
+ audit_path = next((p for p in audit_candidates if p.is_file()), root / cfg.audit_path)
1043
+ audit_present = audit_path.is_file()
1044
+ audit_res = verify_audit_chain(audit_path)
1045
+ recent_audit = _read_recent_audit_events(audit_path)
1046
+
1047
+ # 6. Inspect Trust Ladder
1048
+ trust_candidates = [
1049
+ root / ".robot-gate" / "trust_ladder.json",
1050
+ root / ".robot-gate" / "trust_state.json",
1051
+ ]
1052
+ trust_path = next((p for p in trust_candidates if p.is_file()), root / ".robot-gate" / "trust_ladder.json")
1053
+ trust_info = _verify_trust_ladder_file(trust_path)
1054
+
1055
+ # 7. Collect allowlisted evidence files (strictly excluding ALL private keys / .pem)
1056
+ evidence_items, excluded_key_count = _collect_evidence_candidates(root, cfg)
1057
+ skills_info = _inspect_skills(root, evidence_items)
1058
+ frozen_l3_skills = [s for s in skills_info if s["frozen_l3_candidate"]]
1059
+
1060
+ # 8. Evaluate clause readiness
1061
+ # ISO 10218:2025 Clause 5.1.16 & 5.2.16
1062
+ sig_status = "PASS" if sig_verified else ("PARTIAL" if manifest_loaded else "FAIL")
1063
+ latch_ready = receipt_present and receipt_passed and receipt_sig_ok and receipt_fp_matches
1064
+ latch_status = (
1065
+ "PASS"
1066
+ if latch_ready
1067
+ else ("PARTIAL" if (receipt_present and receipt_passed and receipt_sig_ok) else "FAIL")
1068
+ )
1069
+ audit_status = (
1070
+ "PASS"
1071
+ if (audit_present and audit_res.valid and audit_res.record_count > 0)
1072
+ else ("PARTIAL" if (audit_res.valid and not audit_present) else "FAIL")
1073
+ )
1074
+ env_status = (
1075
+ "PASS"
1076
+ if (env_present and env_valid and (env_sig_verified or pub_key_path is None))
1077
+ else ("PARTIAL" if (env_present and env_valid) else "FAIL")
1078
+ )
1079
+ sbom_status = "PASS" if (manifest_loaded and len(evidence_items) >= 2) else "FAIL"
1080
+
1081
+ iso_checks = [sig_status, latch_status, audit_status, env_status, sbom_status]
1082
+ if all(s == "PASS" for s in iso_checks):
1083
+ iso_status = "PASS"
1084
+ elif "FAIL" in iso_checks and iso_checks.count("PASS") == 0:
1085
+ iso_status = "FAIL"
1086
+ else:
1087
+ iso_status = "PARTIAL"
1088
+
1089
+ # EU Machinery Regulation (EU) 2023/1230 (effective Jan 20, 2027)
1090
+ annex_ok = manifest_loaded and env_present and env_valid and hw_profile_present and receipt_present and audit_res.valid
1091
+ annex_status = "PASS" if annex_ok else ("PARTIAL" if manifest_loaded else "FAIL")
1092
+
1093
+ ai_bounded_pass = (
1094
+ manifest_loaded
1095
+ and trust_info["present"]
1096
+ and trust_info["chain_valid"]
1097
+ and len(skills_info) > 0
1098
+ )
1099
+ ai_bounded_partial = manifest_loaded and (trust_info["present"] or len(skills_info) > 0)
1100
+ ai_status = "PASS" if ai_bounded_pass else ("PARTIAL" if ai_bounded_partial else "FAIL")
1101
+
1102
+ requires_re_verification = (not receipt_present) or (not receipt_fp_matches) or (not receipt_passed)
1103
+ mod_status = (
1104
+ "PASS"
1105
+ if (receipt_present and receipt_passed and receipt_fp_matches and audit_res.valid)
1106
+ else ("PARTIAL" if (receipt_present and audit_res.valid) else "FAIL")
1107
+ )
1108
+
1109
+ eu_checks = [annex_status, ai_status, mod_status]
1110
+ if all(s == "PASS" for s in eu_checks):
1111
+ eu_status = "PASS"
1112
+ elif "FAIL" in eu_checks and eu_checks.count("PASS") == 0:
1113
+ eu_status = "FAIL"
1114
+ else:
1115
+ eu_status = "PARTIAL"
1116
+
1117
+ # Overall readiness score (out of 8 software controls)
1118
+ all_controls = iso_checks + eu_checks
1119
+ points = sum(1.0 if s == "PASS" else (0.5 if s == "PARTIAL" else 0.0) for s in all_controls)
1120
+ readiness_score_pct = int(round((points / len(all_controls)) * 100))
1121
+ if all(s == "PASS" for s in all_controls):
1122
+ overall_status = "READY"
1123
+ elif any(s == "FAIL" for s in [sig_status, latch_status, audit_status]) and not receipt_passed:
1124
+ overall_status = "NON_COMPLIANT"
1125
+ else:
1126
+ overall_status = "NEEDS_ATTENTION"
1127
+
1128
+ # 9. Stage evidence snapshots into output_dir/evidence/ and compute hashes
1129
+ if evidence_out_dir.exists():
1130
+ # Clean stale files from prior runs so directory verification stays exact
1131
+ for existing in sorted(evidence_out_dir.rglob("*"), reverse=True):
1132
+ if existing.is_file():
1133
+ existing.unlink()
1134
+ elif existing.is_dir():
1135
+ try:
1136
+ existing.rmdir()
1137
+ except OSError:
1138
+ pass
1139
+ evidence_out_dir.mkdir(parents=True, exist_ok=True)
1140
+
1141
+ evidence_files_meta: list[dict[str, Any]] = []
1142
+ sbom_items: list[dict[str, Any]] = []
1143
+ bundle_files: dict[str, dict[str, Any]] = {}
1144
+
1145
+ for abs_p, rel, cat in evidence_items:
1146
+ raw = abs_p.read_bytes()
1147
+ # Defense-in-depth assertion: NEVER allow private key material into evidence
1148
+ if _is_prohibited_key_artifact(rel, raw):
1149
+ excluded_key_count += 1
1150
+ continue
1151
+ digest = _sha256_bytes(raw)
1152
+ size_b = len(raw)
1153
+ bundle_rel = f"evidence/{rel}"
1154
+ dest = out_dir / bundle_rel
1155
+ dest.parent.mkdir(parents=True, exist_ok=True)
1156
+ dest.write_bytes(raw)
1157
+
1158
+ evidence_files_meta.append(
1159
+ {
1160
+ "bundle_path": bundle_rel,
1161
+ "workspace_rel_path": rel,
1162
+ "category": cat,
1163
+ "sha256": digest,
1164
+ "size_bytes": size_b,
1165
+ }
1166
+ )
1167
+ sbom_items.append(
1168
+ {
1169
+ "path": rel,
1170
+ "category": cat,
1171
+ "sha256": digest,
1172
+ "size_bytes": size_b,
1173
+ }
1174
+ )
1175
+ bundle_files[bundle_rel] = {
1176
+ "sha256": digest,
1177
+ "size_bytes": size_b,
1178
+ "category": cat,
1179
+ }
1180
+
1181
+ # 10. Assemble manifest body (before compliance_dossier.html hash & manifest_sha256)
1182
+ generated_at_utc = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
1183
+ manifest_body: dict[str, Any] = {
1184
+ "schema_version": COMPLIANCE_SCHEMA_VERSION,
1185
+ "dossier_type": "graft.compliance_pack",
1186
+ "bundle_filename": zip_filename,
1187
+ "generated_at_utc": generated_at_utc,
1188
+ "generator": {
1189
+ "package": "robot-gate",
1190
+ "version": __version__,
1191
+ "bounded_embodiment_version": bounded_embodiment_version(),
1192
+ "rust_kernel_active": rust_kernel_active(),
1193
+ "graft_core_version": graft_core_version(),
1194
+ },
1195
+ "workspace": {
1196
+ "name": root.name,
1197
+ "embodiment": emb_name,
1198
+ "organization": org_name,
1199
+ "fingerprint": fp.digest,
1200
+ "gate_yaml_present": gate_yaml_present,
1201
+ "manifest_error": manifest_error,
1202
+ },
1203
+ "overall_status": overall_status,
1204
+ "readiness_score_pct": readiness_score_pct,
1205
+ "safety_boundary_attestation": {
1206
+ "statement": ISO_13850_HARDWARE_BOUNDARY_ATTESTATION,
1207
+ "canonical_safety_boundary": SAFETY_BOUNDARY_STATEMENT,
1208
+ "software_pl_sil_credit": 0,
1209
+ "mandatory_hardware_controls": [
1210
+ "Hardwired ISO 13850 emergency stop pushbuttons with Category 0/1 power removal",
1211
+ "ISO 13849-1:2023 safety relays / safety PLC (PLd/PLe as required by risk assessment)",
1212
+ "ANSI/A3 R15.06-2025 & ISO 12100 application-level cell risk assessment",
1213
+ "Physical safeguarding, perimeter interlocks, or certified safety-rated light curtains",
1214
+ ],
1215
+ },
1216
+ "clauses": {
1217
+ "iso_10218_2025_cybersecurity": {
1218
+ "standard": "ISO 10218-1:2025 Clause 5.1.16 & ISO 10218-2:2025 Clause 5.2.16",
1219
+ "title": "Industrial Robot Safety Cybersecurity & Cryptographic Provenance",
1220
+ "status": iso_status,
1221
+ "controls": {
1222
+ "ed25519_manifest_signature": {
1223
+ "status": sig_status,
1224
+ "manifest_loaded": manifest_loaded,
1225
+ "verified": sig_verified,
1226
+ "kid": sig_kid,
1227
+ "verified_via": sig_verified_via,
1228
+ "reason": sig_reason,
1229
+ "public_key_sha256": pub_key_sha256,
1230
+ "public_key_jwk": pub_key_jwk,
1231
+ },
1232
+ "software_sbom_sha256_inventory": {
1233
+ "status": sbom_status,
1234
+ "artifact_count": len(sbom_items),
1235
+ "items": sbom_items,
1236
+ },
1237
+ "tamper_evident_audit_chain": {
1238
+ "status": audit_status,
1239
+ "present": audit_present,
1240
+ "valid": audit_res.valid,
1241
+ "record_count": audit_res.record_count,
1242
+ "head_hash": audit_res.head_hash,
1243
+ "error": audit_res.error,
1244
+ },
1245
+ "hard_receipt_latch": {
1246
+ "status": latch_status,
1247
+ "present": receipt_present,
1248
+ "passed": receipt_passed,
1249
+ "signature_alg": receipt_sig_alg,
1250
+ "signature_verified": receipt_sig_ok,
1251
+ "signature_reason": receipt_sig_reason,
1252
+ "fingerprint_matches_live_workspace": receipt_fp_matches,
1253
+ "receipt_ts_utc": receipt_ts_utc,
1254
+ "stages_summary": receipt_stages,
1255
+ },
1256
+ "envelope_provenance": {
1257
+ "status": env_status,
1258
+ "present": env_present,
1259
+ "path": env_rel_path,
1260
+ "schema_valid": env_valid,
1261
+ "signature_verified": env_sig_verified,
1262
+ "note": env_note,
1263
+ },
1264
+ },
1265
+ },
1266
+ "eu_2023_1230_machinery_regulation": {
1267
+ "standard": "EU Machinery Regulation (EU) 2023/1230 (effective January 20, 2027)",
1268
+ "title": "Annex III Software Safety Component Traceability, AI Behavior Bounding & Substantial Modification Control",
1269
+ "effective_date": "2027-01-20",
1270
+ "status": eu_status,
1271
+ "controls": {
1272
+ "annex_iii_software_traceability": {
1273
+ "status": annex_status,
1274
+ "manifest_present": manifest_loaded,
1275
+ "envelope_present": env_present and env_valid,
1276
+ "hardware_profile_present": hw_profile_present,
1277
+ "receipt_present": receipt_present,
1278
+ "audit_chain_valid": audit_res.valid,
1279
+ "recommended_operational_retention_years": 5,
1280
+ "technical_file_retention_years": 10,
1281
+ },
1282
+ "ai_self_evolving_behavior_bounding": {
1283
+ "status": ai_status,
1284
+ "trust_ladder_present": trust_info["present"],
1285
+ "trust_chain_valid": trust_info["chain_valid"],
1286
+ "trust_head_sha256": trust_info["head_sha256"],
1287
+ "robots": trust_info["robots"],
1288
+ "skills_count": len(skills_info),
1289
+ "frozen_l3_skills_count": len(frozen_l3_skills),
1290
+ "frozen_skills": skills_info,
1291
+ "bounds_summary": bounds_summary,
1292
+ },
1293
+ "substantial_modification_change_control": {
1294
+ "status": mod_status,
1295
+ "workspace_fingerprint": fp.digest,
1296
+ "tracked_files_count": len(fp.files),
1297
+ "fingerprint_diff": receipt_diff,
1298
+ "requires_re_verification": requires_re_verification,
1299
+ "recent_audit_events": recent_audit,
1300
+ },
1301
+ },
1302
+ },
1303
+ "iso_13850_13849_hardware_boundary": {
1304
+ "standard": "ISO 13850 & ISO 13849-1:2023 (with ANSI/A3 R15.06-2025 / ISO 12100)",
1305
+ "title": "Mandatory Hardware Safety Boundary & Zero PL/SIL Risk-Reduction Credit Attestation",
1306
+ "status": "ATTESTED",
1307
+ "pl_sil_credit_claimed": 0,
1308
+ "attestation": ISO_13850_HARDWARE_BOUNDARY_ATTESTATION,
1309
+ "checklist_for_integrator": [
1310
+ "Verify hardwired ISO 13850 E-stop removes actuator power independently of host OS and robot-gate.",
1311
+ "Verify ISO 13849-1:2023 safety relays / safety PLC wiring and Performance Level (PLd/PLe) calculations.",
1312
+ "Complete application-specific ANSI/A3 R15.06-2025 / ISO 12100 hazard & risk assessment for the physical cell.",
1313
+ "Confirm notified body / EU 2023/1230 Annex I conformity assessment obligations if AI/self-evolving software alters safety functions.",
1314
+ ],
1315
+ },
1316
+ },
1317
+ "evidence_files": evidence_files_meta,
1318
+ "security_exclusions": {
1319
+ "private_keys_excluded": True,
1320
+ "excluded_count": excluded_key_count,
1321
+ "policy": "Private keys (*.pem, *.key, *private*, PKCS8/OpenSSH/PGP PEM blocks, OKP JWK 'd') are strictly prohibited from compliance packs.",
1322
+ },
1323
+ "manifest_digest_alg": "rfc8785-jcs-sha256",
1324
+ }
1325
+
1326
+ # 11. Render Warm Workshop HTML dossier, hash it, and finalize bundle_files + manifest_sha256
1327
+ dossier_html = _render_compliance_dossier_html(manifest_body)
1328
+ dossier_bytes = dossier_html.encode("utf-8")
1329
+ dossier_path = out_dir / "compliance_dossier.html"
1330
+ dossier_path.write_bytes(dossier_bytes)
1331
+
1332
+ bundle_files["compliance_dossier.html"] = {
1333
+ "sha256": _sha256_bytes(dossier_bytes),
1334
+ "size_bytes": len(dossier_bytes),
1335
+ "category": "compliance_dossier_html",
1336
+ }
1337
+ manifest_body["bundle_files"] = bundle_files
1338
+ manifest_digest = sha256_canonical(manifest_body)
1339
+ manifest_full = {**manifest_body, "manifest_sha256": manifest_digest}
1340
+
1341
+ manifest_bytes = (json.dumps(manifest_full, indent=2, sort_keys=True) + "\n").encode("utf-8")
1342
+ manifest_out_path = out_dir / "compliance_manifest.json"
1343
+ manifest_out_path.write_bytes(manifest_bytes)
1344
+
1345
+ # 12. Assemble deterministic ZIP bundle and assert ZERO private keys inside ZIP
1346
+ zip_path = out_dir / zip_filename
1347
+ with zipfile.ZipFile(zip_path, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
1348
+ zf.writestr("compliance_manifest.json", manifest_bytes)
1349
+ zf.writestr("compliance_dossier.html", dossier_bytes)
1350
+ for ev in evidence_files_meta:
1351
+ rel_bundle = ev["bundle_path"]
1352
+ file_bytes = (out_dir / rel_bundle).read_bytes()
1353
+ if _is_prohibited_key_artifact(rel_bundle, file_bytes):
1354
+ raise RuntimeError(f"SECURITY VIOLATION: prohibited key file blocked from ZIP: {rel_bundle}")
1355
+ zf.writestr(rel_bundle, file_bytes)
1356
+
1357
+ # Final airtight assertion on the written ZIP archive
1358
+ with zipfile.ZipFile(zip_path, mode="r") as zf:
1359
+ for info in zf.infolist():
1360
+ member_bytes = zf.read(info.filename)
1361
+ if _is_prohibited_key_artifact(info.filename, member_bytes):
1362
+ zip_path.unlink(missing_ok=True)
1363
+ raise RuntimeError(f"SECURITY ASSERTION FAILED: private key material found in ZIP member '{info.filename}'")
1364
+
1365
+ return CompliancePackResult(
1366
+ output_dir=out_dir,
1367
+ manifest_path=manifest_out_path,
1368
+ dossier_html_path=dossier_path,
1369
+ zip_path=zip_path,
1370
+ manifest_sha256=manifest_digest,
1371
+ overall_status=overall_status,
1372
+ readiness_score_pct=readiness_score_pct,
1373
+ evidence_count=len(evidence_files_meta),
1374
+ manifest=manifest_full,
1375
+ )
1376
+
1377
+
1378
+ def verify_compliance_pack(zip_or_dir: Path | str) -> ComplianceVerifyResult:
1379
+ """Offline fail-closed verification of a compliance pack ZIP or directory.
1380
+
1381
+ Verifies:
1382
+ 1. `compliance_manifest.json` exists and its RFC 8785 JCS `manifest_sha256` matches.
1383
+ 2. Every file listed in `bundle_files` (including `compliance_dossier.html` and every
1384
+ `evidence/*` snapshot) exists and matches exact SHA-256 and byte length.
1385
+ 3. Zero unexpected/unlisted files exist in the bundle.
1386
+ 4. Zero private key files or PEM private key blocks exist anywhere in the bundle.
1387
+ """
1388
+ target_path = Path(zip_or_dir).resolve()
1389
+ target_str = str(target_path)
1390
+ errors: list[str] = []
1391
+ warnings: list[str] = []
1392
+
1393
+ if not target_path.exists():
1394
+ return ComplianceVerifyResult(
1395
+ valid=False,
1396
+ target=target_str,
1397
+ manifest_sha256=None,
1398
+ files_verified=0,
1399
+ errors=[f"target does not exist: {target_path}"],
1400
+ )
1401
+
1402
+ files_map: dict[str, bytes] = {}
1403
+ is_zip = target_path.is_file()
1404
+
1405
+ if is_zip:
1406
+ try:
1407
+ with zipfile.ZipFile(target_path, mode="r") as zf:
1408
+ for info in zf.infolist():
1409
+ if info.is_dir():
1410
+ continue
1411
+ norm = info.filename.lstrip("/")
1412
+ if ".." in Path(norm).parts:
1413
+ errors.append(f"unsafe path traversal member in ZIP: {info.filename}")
1414
+ continue
1415
+ files_map[norm] = zf.read(info.filename)
1416
+ except Exception as exc:
1417
+ return ComplianceVerifyResult(
1418
+ valid=False,
1419
+ target=target_str,
1420
+ manifest_sha256=None,
1421
+ files_verified=0,
1422
+ errors=[f"invalid ZIP archive: {exc}"],
1423
+ )
1424
+ else:
1425
+ for child in sorted(target_path.rglob("*")):
1426
+ if child.is_file():
1427
+ rel = child.resolve().relative_to(target_path).as_posix()
1428
+ files_map[rel] = child.read_bytes()
1429
+
1430
+ if "compliance_manifest.json" not in files_map:
1431
+ return ComplianceVerifyResult(
1432
+ valid=False,
1433
+ target=target_str,
1434
+ manifest_sha256=None,
1435
+ files_verified=0,
1436
+ errors=errors + ["compliance_manifest.json missing from compliance pack"],
1437
+ )
1438
+
1439
+ try:
1440
+ manifest = json.loads(files_map["compliance_manifest.json"].decode("utf-8"))
1441
+ if not isinstance(manifest, dict):
1442
+ raise ValueError("manifest root must be a JSON object")
1443
+ except Exception as exc:
1444
+ return ComplianceVerifyResult(
1445
+ valid=False,
1446
+ target=target_str,
1447
+ manifest_sha256=None,
1448
+ files_verified=0,
1449
+ errors=errors + [f"compliance_manifest.json unreadable: {exc}"],
1450
+ )
1451
+
1452
+ # For directory verification, ignore the sibling ZIP archive itself if present at top level
1453
+ bundle_filename = str(manifest.get("bundle_filename", DEFAULT_ZIP_FILENAME))
1454
+ if not is_zip and bundle_filename in files_map:
1455
+ del files_map[bundle_filename]
1456
+
1457
+ # 1. Verify canonical RFC 8785 JCS manifest_sha256 (format: "sha256:<64-hex>" from sha256_canonical)
1458
+ recorded_digest = manifest.get("manifest_sha256")
1459
+ if not isinstance(recorded_digest, str) or not re.fullmatch(r"(?:sha256:)?[0-9a-f]{64}", recorded_digest):
1460
+ errors.append("compliance_manifest.json missing valid SHA-256 manifest_sha256")
1461
+ computed_digest = None
1462
+ else:
1463
+ body = {k: v for k, v in manifest.items() if k != "manifest_sha256"}
1464
+ computed_digest = sha256_canonical(body)
1465
+ if computed_digest != recorded_digest:
1466
+ errors.append(
1467
+ f"manifest_sha256 mismatch (tampering detected): expected {recorded_digest}, computed {computed_digest}"
1468
+ )
1469
+
1470
+ # 2. Private key contamination scan across EVERY member in the pack
1471
+ for rel, raw in sorted(files_map.items()):
1472
+ if rel == "compliance_manifest.json":
1473
+ if _contains_private_key_material(raw):
1474
+ errors.append(f"SECURITY VIOLATION: private key material detected in {rel}")
1475
+ continue
1476
+ if _is_prohibited_key_artifact(rel, raw):
1477
+ errors.append(f"SECURITY VIOLATION: private key or .pem file found in bundle: {rel}")
1478
+
1479
+ # 3. Verify every file listed in bundle_files
1480
+ bundle_files = manifest.get("bundle_files")
1481
+ if not isinstance(bundle_files, dict) or "compliance_dossier.html" not in bundle_files:
1482
+ errors.append("compliance_manifest.json missing valid bundle_files map or compliance_dossier.html entry")
1483
+ bundle_files = {}
1484
+
1485
+ verified_count = 0
1486
+ for rel, meta in sorted(bundle_files.items()):
1487
+ if rel not in files_map:
1488
+ errors.append(f"missing bundle file: {rel}")
1489
+ continue
1490
+ raw = files_map[rel]
1491
+ actual_sha = _sha256_bytes(raw)
1492
+ expected_sha = str(meta.get("sha256", ""))
1493
+ expected_size = meta.get("size_bytes")
1494
+ if actual_sha != expected_sha:
1495
+ errors.append(
1496
+ f"SHA-256 mismatch for '{rel}' (tampering detected): expected {expected_sha}, got {actual_sha}"
1497
+ )
1498
+ continue
1499
+ if expected_size is not None and len(raw) != int(expected_size):
1500
+ errors.append(f"size mismatch for '{rel}': expected {expected_size}, got {len(raw)}")
1501
+ continue
1502
+ verified_count += 1
1503
+
1504
+ # 4. Fail closed on any unexpected / unlisted files
1505
+ expected_members = set(bundle_files.keys()) | {"compliance_manifest.json"}
1506
+ unexpected = sorted(set(files_map.keys()) - expected_members)
1507
+ for extra in unexpected:
1508
+ errors.append(f"unexpected unlisted file in compliance pack: {extra}")
1509
+
1510
+ return ComplianceVerifyResult(
1511
+ valid=(len(errors) == 0),
1512
+ target=target_str,
1513
+ manifest_sha256=recorded_digest if isinstance(recorded_digest, str) else None,
1514
+ files_verified=verified_count,
1515
+ errors=errors,
1516
+ warnings=warnings,
1517
+ )
1518
+
1519
+
1520
+ __all__ = [
1521
+ "COMPLIANCE_SCHEMA_VERSION",
1522
+ "CompliancePackResult",
1523
+ "ComplianceVerifyResult",
1524
+ "DEFAULT_ZIP_FILENAME",
1525
+ "ISO_13850_HARDWARE_BOUNDARY_ATTESTATION",
1526
+ "generate_compliance_pack",
1527
+ "verify_compliance_pack",
1528
+ ]