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,719 @@
1
+ """Direct integration bridge to the public `bounded-embodiment` package.
2
+
3
+ Delegates all 4 core RRF Bounded Embodiment primitives directly to the public package:
4
+ 1. Canonical JSON (RFC 8785 JCS): `bounded_embodiment.canonical.{canonicalize, sha256_jcs}`
5
+ 2. Ed25519 Envelope Signing & Keyring Verification: `bounded_embodiment.signing.{sign, verify, key_entry, keyring_from_entries, thumbprint}`
6
+ 3. Hostile Command Generator: `bounded_embodiment.commandspace.load_command_space` + `bounded_embodiment.generator.{hostile_stream, stream_sha256}`
7
+ 4. Report Verifier: `bounded_embodiment.report.verify` + `bounded_embodiment.envelope.{load, geometry.box_signed_distance}`
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import json
14
+ import math
15
+ import time
16
+ from collections.abc import Iterable, Sequence
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import bounded_embodiment
21
+ from bounded_embodiment.canonical import canonicalize as _be_canonicalize
22
+ from bounded_embodiment.canonical import sha256_jcs as _be_sha256_jcs
23
+ from bounded_embodiment.commandspace import CommandSpace, load_command_space
24
+ from bounded_embodiment.envelope import load as _be_load_envelope
25
+ from bounded_embodiment.envelope.geometry import (
26
+ box_signed_distance as _be_box_signed_distance,
27
+ )
28
+ from bounded_embodiment.findings import errors as _be_errors
29
+ from bounded_embodiment.generator import (
30
+ GENERATOR_VERSION,
31
+ STRATEGIES,
32
+ hostile_stream,
33
+ stream_sha256,
34
+ )
35
+ from bounded_embodiment.report import verify as _be_verify_report
36
+ from bounded_embodiment.signing import (
37
+ key_entry as _be_key_entry,
38
+ keyring_from_entries as _be_keyring_from_entries,
39
+ sign as _be_sign,
40
+ thumbprint as _be_thumbprint,
41
+ verify as _be_verify_sig,
42
+ )
43
+ from cryptography.hazmat.primitives import serialization
44
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
45
+ Ed25519PrivateKey,
46
+ Ed25519PublicKey,
47
+ )
48
+
49
+ try:
50
+ import graft_core as _graft_core # Optional PyO3 Rust hot-path accelerator
51
+ except ImportError:
52
+ _graft_core = None
53
+
54
+
55
+ def _b64url(data: bytes) -> str:
56
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
57
+
58
+
59
+ def bounded_embodiment_version() -> str:
60
+ return str(getattr(bounded_embodiment, "__version__", "unknown"))
61
+
62
+
63
+ def rust_kernel_active() -> bool:
64
+ """Return True when the native PyO3 `graft_core` Rust extension is loaded."""
65
+ return _graft_core is not None
66
+
67
+
68
+ def graft_core_version() -> str | None:
69
+ if _graft_core is None:
70
+ return None
71
+ return str(_graft_core.version())
72
+
73
+
74
+ # --------------------------------------------------------------------------- 1. Canonical JSON (RFC 8785)
75
+ def canonical_json_bytes(obj: Any) -> bytes:
76
+ """Serialize `obj` using public `bounded_embodiment.canonical.canonicalize` (RFC 8785 JCS)."""
77
+ return _be_canonicalize(obj)
78
+
79
+
80
+ def sha256_canonical(obj: Any) -> str:
81
+ """Compute SHA-256 hex digest using public `bounded_embodiment.canonical.sha256_jcs`."""
82
+ return _be_sha256_jcs(obj)
83
+
84
+
85
+ # --------------------------------------------------------------------------- 2. Exact Euclidean Box Geometry
86
+ def _is_finite_vec3(v: Sequence[float]) -> bool:
87
+ if len(v) < 3:
88
+ return False
89
+ try:
90
+ return all(math.isfinite(float(v[i])) for i in range(3))
91
+ except (TypeError, ValueError):
92
+ return False
93
+
94
+
95
+ def _is_valid_box(bmin: Sequence[float], bmax: Sequence[float]) -> bool:
96
+ if len(bmin) < 3 or len(bmax) < 3:
97
+ return False
98
+ try:
99
+ for i in range(3):
100
+ lo = float(bmin[i])
101
+ hi = float(bmax[i])
102
+ if not (math.isfinite(lo) and math.isfinite(hi) and lo <= hi):
103
+ return False
104
+ except (TypeError, ValueError):
105
+ return False
106
+ return True
107
+
108
+
109
+ def box_signed_distance_inside(
110
+ bmin: Sequence[float], bmax: Sequence[float], p: Sequence[float]
111
+ ) -> float:
112
+ """Signed distance positive inside [bmin, bmax], negative outside.
113
+
114
+ Uses the native Rust `graft_core.box_signed_distance` kernel when installed,
115
+ with bit-identical fallback to `bounded_embodiment.envelope.geometry.box_signed_distance`.
116
+ Fails closed (`-inf`) on any NaN/Inf coordinate or inverted box (`bmin[i] > bmax[i]`).
117
+ """
118
+ if not _is_valid_box(bmin, bmax) or not _is_finite_vec3(p):
119
+ return float("-inf")
120
+ if _graft_core is not None:
121
+ return float(
122
+ _graft_core.box_signed_distance(
123
+ [float(bmin[0]), float(bmin[1]), float(bmin[2])],
124
+ [float(bmax[0]), float(bmax[1]), float(bmax[2])],
125
+ [float(p[0]), float(p[1]), float(p[2])],
126
+ )
127
+ )
128
+ sd = float(_be_box_signed_distance(bmin, bmax, p))
129
+ return sd if math.isfinite(sd) else float("-inf")
130
+
131
+
132
+ def _eval_segment(
133
+ p0: tuple[float, float, float],
134
+ p1: tuple[float, float, float],
135
+ t: float,
136
+ ) -> tuple[float, float, float]:
137
+ if t <= 0.0:
138
+ return p0
139
+ if t >= 1.0:
140
+ return p1
141
+ omt = 1.0 - t
142
+ return (
143
+ omt * p0[0] + t * p1[0],
144
+ omt * p0[1] + t * p1[1],
145
+ omt * p0[2] + t * p1[2],
146
+ )
147
+
148
+
149
+ def _segment_aabb_slab_intersection(
150
+ p0: tuple[float, float, float],
151
+ p1: tuple[float, float, float],
152
+ bmin: tuple[float, float, float],
153
+ bmax: tuple[float, float, float],
154
+ ) -> tuple[float, float] | None:
155
+ """Exact continuous Kay-Kajiya segment-vs-AABB slab intersection on t in [0, 1]."""
156
+ t_min = 0.0
157
+ t_max = 1.0
158
+ for i in range(3):
159
+ d = p1[i] - p0[i]
160
+ if not math.isfinite(d):
161
+ return (0.0, 1.0)
162
+ if d == 0.0:
163
+ if p0[i] < bmin[i] or p0[i] > bmax[i]:
164
+ return None
165
+ else:
166
+ t1 = (bmin[i] - p0[i]) / d
167
+ t2 = (bmax[i] - p0[i]) / d
168
+ t_lo, t_hi = (t1, t2) if t1 <= t2 else (t2, t1)
169
+ if t_lo > t_min:
170
+ t_min = t_lo
171
+ if t_hi < t_max:
172
+ t_max = t_hi
173
+ if t_min > t_max:
174
+ return None
175
+ return (t_min, t_max)
176
+
177
+
178
+ def _segment_keep_in_min_signed_distance(
179
+ p0: tuple[float, float, float],
180
+ p1: tuple[float, float, float],
181
+ bmin: tuple[float, float, float],
182
+ bmax: tuple[float, float, float],
183
+ ) -> float:
184
+ """Exact minimum signed distance of segment [p0, p1] inside keep-in box [bmin, bmax]."""
185
+ if not _is_valid_box(bmin, bmax) or not (_is_finite_vec3(p0) and _is_finite_vec3(p1)):
186
+ return float("-inf")
187
+ if not all(math.isfinite(p1[i] - p0[i]) for i in range(3)):
188
+ return float("-inf")
189
+ sd0 = float(_be_box_signed_distance(bmin, bmax, p0))
190
+ sd1 = float(_be_box_signed_distance(bmin, bmax, p1))
191
+ if not (math.isfinite(sd0) and math.isfinite(sd1)):
192
+ return float("-inf")
193
+ return sd0 if sd0 <= sd1 else sd1
194
+
195
+
196
+ def _segment_keepout_min_clearance(
197
+ p0: tuple[float, float, float],
198
+ p1: tuple[float, float, float],
199
+ bmin: tuple[float, float, float],
200
+ bmax: tuple[float, float, float],
201
+ ) -> float:
202
+ """Exact continuous minimum clearance of segment [p0, p1] against keep-out box [bmin, bmax].
203
+
204
+ Mirrors Rust `graft_core::kernel::segment_keepout_min_clearance` 1-to-1:
205
+ - > 0.0: exact Euclidean clearance when strictly disjoint
206
+ - = 0.0: boundary grazing contact only
207
+ - < 0.0: exact -max_penetration_depth when intersecting interior
208
+ - -inf : fail-closed on invalid box or non-finite coordinates
209
+ """
210
+ if not _is_valid_box(bmin, bmax) or not (_is_finite_vec3(p0) and _is_finite_vec3(p1)):
211
+ return float("-inf")
212
+ d = (p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2])
213
+ if not all(math.isfinite(di) for di in d):
214
+ return float("-inf")
215
+
216
+ slab = _segment_aabb_slab_intersection(p0, p1, bmin, bmax)
217
+ if slab is not None:
218
+ t_enter, t_exit = slab
219
+ max_depth = 0.0
220
+ t_mid = 0.5 * (t_enter + t_exit)
221
+ for tc in (t_enter, t_exit, t_mid):
222
+ sd = float(_be_box_signed_distance(bmin, bmax, _eval_segment(p0, p1, tc)))
223
+ if not math.isfinite(sd):
224
+ return float("-inf")
225
+ if sd > max_depth:
226
+ max_depth = sd
227
+
228
+ lines = (
229
+ (d[0], p0[0] - bmin[0]),
230
+ (-d[0], bmax[0] - p0[0]),
231
+ (d[1], p0[1] - bmin[1]),
232
+ (-d[1], bmax[1] - p0[1]),
233
+ (d[2], p0[2] - bmin[2]),
234
+ (-d[2], bmax[2] - p0[2]),
235
+ )
236
+ for j in range(6):
237
+ aj, cj = lines[j]
238
+ for k in range(j + 1, 6):
239
+ ak, ck = lines[k]
240
+ denom = aj - ak
241
+ if denom != 0.0:
242
+ t_star = (ck - cj) / denom
243
+ if math.isfinite(t_star) and t_enter <= t_star <= t_exit:
244
+ sd = float(_be_box_signed_distance(bmin, bmax, _eval_segment(p0, p1, t_star)))
245
+ if not math.isfinite(sd):
246
+ return float("-inf")
247
+ if sd > max_depth:
248
+ max_depth = sd
249
+ return -max_depth + 0.0
250
+
251
+ # Strictly disjoint: exact piecewise-quadratic Euclidean distance minimization
252
+ breaks = [0.0, 1.0]
253
+ for i in range(3):
254
+ if d[i] != 0.0:
255
+ t1 = (bmin[i] - p0[i]) / d[i]
256
+ if math.isfinite(t1) and 0.0 < t1 < 1.0:
257
+ breaks.append(t1)
258
+ t2 = (bmax[i] - p0[i]) / d[i]
259
+ if math.isfinite(t2) and 0.0 < t2 < 1.0:
260
+ breaks.append(t2)
261
+ breaks.sort()
262
+
263
+ min_clearance = float("inf")
264
+ for tb in breaks:
265
+ sd = float(_be_box_signed_distance(bmin, bmax, _eval_segment(p0, p1, tb)))
266
+ if not math.isfinite(sd):
267
+ return float("-inf")
268
+ h = -sd
269
+ if h < min_clearance:
270
+ min_clearance = h
271
+
272
+ for r in range(len(breaks) - 1):
273
+ ta = breaks[r]
274
+ tb = breaks[r + 1]
275
+ if tb <= ta:
276
+ continue
277
+ tm = 0.5 * (ta + tb)
278
+ pm = _eval_segment(p0, p1, tm)
279
+ num = 0.0
280
+ den = 0.0
281
+ for i in range(3):
282
+ if pm[i] < bmin[i]:
283
+ c = p0[i] - bmin[i]
284
+ num += d[i] * c
285
+ den += d[i] * d[i]
286
+ elif pm[i] > bmax[i]:
287
+ c = p0[i] - bmax[i]
288
+ num += d[i] * c
289
+ den += d[i] * d[i]
290
+ if den > 0.0:
291
+ t_star = -num / den
292
+ if math.isfinite(t_star) and ta < t_star < tb:
293
+ sd = float(_be_box_signed_distance(bmin, bmax, _eval_segment(p0, p1, t_star)))
294
+ if not math.isfinite(sd):
295
+ return float("-inf")
296
+ h = -sd
297
+ if h < min_clearance:
298
+ min_clearance = h
299
+ return min_clearance
300
+
301
+
302
+ def check_swept_path_fast(
303
+ waypoints: Sequence[Sequence[float]],
304
+ workspace_min: Sequence[float],
305
+ workspace_max: Sequence[float],
306
+ exclusions: Sequence[tuple[str, Sequence[float], Sequence[float]]] = (),
307
+ samples_per_segment: int = 10,
308
+ ) -> tuple[bool, float, str | None, int, str]:
309
+ """Deterministic continuous swept-path workspace + keep-out check (Rust `graft_core` or Python fallback)."""
310
+ if _graft_core is not None:
311
+ wp = [[float(p[0]), float(p[1]), float(p[2])] for p in waypoints]
312
+ ko = [
313
+ (
314
+ str(name),
315
+ [float(lo[0]), float(lo[1]), float(lo[2])],
316
+ [float(hi[0]), float(hi[1]), float(hi[2])],
317
+ )
318
+ for name, lo, hi in exclusions
319
+ ]
320
+ allowed, min_margin, violator, checked = _graft_core.check_swept_path(
321
+ wp,
322
+ [float(workspace_min[0]), float(workspace_min[1]), float(workspace_min[2])],
323
+ [float(workspace_max[0]), float(workspace_max[1]), float(workspace_max[2])],
324
+ ko,
325
+ int(samples_per_segment),
326
+ )
327
+ return bool(allowed), float(min_margin), violator, int(checked), f"rust:graft_core:{_graft_core.version()}"
328
+
329
+ # Pure-Python exact continuous fallback (100% behavioral & reason-string parity with Rust kernel)
330
+ if not waypoints:
331
+ return False, -1.0, "EMPTY_WAYPOINTS", 0, "python:bounded_embodiment"
332
+ if not _is_valid_box(workspace_min, workspace_max):
333
+ return False, float("-inf"), "INVALID_WORKSPACE_BOX", 0, "python:bounded_embodiment"
334
+ ws_lo = (float(workspace_min[0]), float(workspace_min[1]), float(workspace_min[2]))
335
+ ws_hi = (float(workspace_max[0]), float(workspace_max[1]), float(workspace_max[2]))
336
+
337
+ parsed_exclusions: list[tuple[str, tuple[float, float, float], tuple[float, float, float]]] = []
338
+ for name, elo, ehi in exclusions:
339
+ if not _is_valid_box(elo, ehi):
340
+ return False, float("-inf"), f"INVALID_KEEPOUT:{name}", 0, "python:bounded_embodiment"
341
+ parsed_exclusions.append(
342
+ (
343
+ str(name),
344
+ (float(elo[0]), float(elo[1]), float(elo[2])),
345
+ (float(ehi[0]), float(ehi[1]), float(ehi[2])),
346
+ )
347
+ )
348
+
349
+ seg_samples = max(2, int(samples_per_segment))
350
+ min_h = float("inf")
351
+ violator: str | None = None
352
+ checked = 0
353
+
354
+ n = len(waypoints)
355
+ segs = 1 if n == 1 else n - 1
356
+
357
+ for seg in range(segs):
358
+ raw_p0 = waypoints[seg]
359
+ raw_p1 = raw_p0 if n == 1 else waypoints[seg + 1]
360
+ if not (_is_finite_vec3(raw_p0) and _is_finite_vec3(raw_p1)):
361
+ return False, float("-inf"), "NON_FINITE_COORDINATE", checked, "python:bounded_embodiment"
362
+ p0 = (float(raw_p0[0]), float(raw_p0[1]), float(raw_p0[2]))
363
+ p1 = (float(raw_p1[0]), float(raw_p1[1]), float(raw_p1[2]))
364
+ if not all(math.isfinite(p1[i] - p0[i]) for i in range(3)):
365
+ return False, float("-inf"), "NON_FINITE_COORDINATE", checked, "python:bounded_embodiment"
366
+
367
+ checked += 1 if n == 1 else seg_samples
368
+
369
+ h_ws = _segment_keep_in_min_signed_distance(p0, p1, ws_lo, ws_hi)
370
+ if not math.isfinite(h_ws):
371
+ return False, float("-inf"), "WORKSPACE_BOUNDARY", checked, "python:bounded_embodiment"
372
+ if h_ws < min_h:
373
+ min_h = h_ws
374
+ if h_ws < 0.0 and violator is None:
375
+ violator = "WORKSPACE_BOUNDARY"
376
+
377
+ for name, elo, ehi in parsed_exclusions:
378
+ h_ko = _segment_keepout_min_clearance(p0, p1, elo, ehi)
379
+ if not math.isfinite(h_ko):
380
+ return False, float("-inf"), f"INVALID_KEEPOUT:{name}", checked, "python:bounded_embodiment"
381
+ if h_ko < min_h:
382
+ min_h = h_ko
383
+ if h_ko < 0.0 and violator is None:
384
+ violator = f"KEEPOUT:{name}"
385
+
386
+ allowed = (min_h >= 0.0) and (violator is None)
387
+ return allowed, min_h, violator, checked, "python:bounded_embodiment"
388
+
389
+
390
+ # --------------------------------------------------------------------------- 3. Envelope 0.2 + Ed25519 Signing
391
+ def private_pem_to_jwk(private_key_path: Path) -> dict[str, str]:
392
+ """Convert an Ed25519 PKCS8 PEM private key into an RFC 8037 OKP JWK for `bounded_embodiment.signing`."""
393
+ priv = serialization.load_pem_private_key(private_key_path.read_bytes(), password=None)
394
+ if not isinstance(priv, Ed25519PrivateKey):
395
+ raise ValueError("Key must be Ed25519")
396
+ d_raw = priv.private_bytes(
397
+ encoding=serialization.Encoding.Raw,
398
+ format=serialization.PrivateFormat.Raw,
399
+ encryption_algorithm=serialization.NoEncryption(),
400
+ )
401
+ x_raw = priv.public_key().public_bytes(
402
+ encoding=serialization.Encoding.Raw,
403
+ format=serialization.PublicFormat.Raw,
404
+ )
405
+ return {"kty": "OKP", "crv": "Ed25519", "x": _b64url(x_raw), "d": _b64url(d_raw)}
406
+
407
+
408
+ def public_pem_to_jwk(public_key_path: Path) -> dict[str, str]:
409
+ """Convert an Ed25519 SPKI PEM public key into an RFC 8037 OKP JWK."""
410
+ pub = serialization.load_pem_public_key(public_key_path.read_bytes())
411
+ if not isinstance(pub, Ed25519PublicKey):
412
+ raise ValueError("Public key must be Ed25519")
413
+ x_raw = pub.public_bytes(
414
+ encoding=serialization.Encoding.Raw,
415
+ format=serialization.PublicFormat.Raw,
416
+ )
417
+ return {"kty": "OKP", "crv": "Ed25519", "x": _b64url(x_raw)}
418
+
419
+
420
+ def keyring_from_public_pem(
421
+ public_key_path: Path,
422
+ *,
423
+ lab: str = "graft-local",
424
+ contact: str = "ops@graftrobotics.ai",
425
+ ) -> dict[str, dict[str, Any]]:
426
+ pub_jwk = public_pem_to_jwk(public_key_path)
427
+ today = time.strftime("%Y-%m-%d", time.gmtime())
428
+ entry = _be_key_entry(pub_jwk, lab=lab, contact=contact, added=today)
429
+ return _be_keyring_from_entries([entry])
430
+
431
+
432
+ def build_envelope_doc(
433
+ *,
434
+ machine_id: str,
435
+ workspace_min: Sequence[float],
436
+ workspace_max: Sequence[float],
437
+ exclusions: Sequence[tuple[str, Sequence[float], Sequence[float]]],
438
+ max_tcp_velocity_mps: float,
439
+ max_contact_force_n: float | None = None,
440
+ frame: str = "base_link",
441
+ ) -> dict[str, Any]:
442
+ """Build an official bounded-embodiment Envelope 0.2 document from ROBOT.md bounds."""
443
+ zones: list[dict[str, Any]] = [
444
+ {
445
+ "id": "workspace_keep_in",
446
+ "kind": "keep_in",
447
+ "applies_to": ["tool"],
448
+ "box": {
449
+ "min_m": [float(v) for v in workspace_min],
450
+ "max_m": [float(v) for v in workspace_max],
451
+ },
452
+ }
453
+ ]
454
+ for name, lo, hi in exclusions:
455
+ zones.append(
456
+ {
457
+ "id": str(name),
458
+ "kind": "keep_out",
459
+ "applies_to": ["tool"],
460
+ "box": {
461
+ "min_m": [float(v) for v in lo],
462
+ "max_m": [float(v) for v in hi],
463
+ },
464
+ }
465
+ )
466
+ doc: dict[str, Any] = {
467
+ "envelope_version": "0.2",
468
+ "machine": {
469
+ "id": machine_id,
470
+ "class": "arm",
471
+ },
472
+ "frame": frame,
473
+ "points": [
474
+ {"id": "tool", "description": "Active tool center point (TCP)"}
475
+ ],
476
+ "workspace": {"zones": zones},
477
+ "motion": {"max_speed_mps": float(max_tcp_velocity_mps)},
478
+ "stop": {"category": 1, "max_time_ms": 500, "max_distance_m": 0.05},
479
+ "heartbeat": {
480
+ "model_timeout_ms": 1000,
481
+ "gate_timeout_ms": 1000,
482
+ "on_loss": "stop",
483
+ },
484
+ }
485
+ if max_contact_force_n is not None and max_contact_force_n > 0:
486
+ doc["force"] = {"max_contact_force_n": float(max_contact_force_n)}
487
+ return doc
488
+
489
+
490
+ def sign_envelope_doc(doc: dict[str, Any], private_key_path: Path) -> tuple[dict[str, Any], str]:
491
+ """Sign an Envelope 0.2 document with `bounded_embodiment.signing.sign` (Ed25519 over RFC 8785 JCS)."""
492
+ priv_jwk = private_pem_to_jwk(private_key_path)
493
+ pub_jwk = {"kty": "OKP", "crv": "Ed25519", "x": priv_jwk["x"]}
494
+ signed = _be_sign(doc, priv_jwk)
495
+ return signed, _be_thumbprint(pub_jwk)
496
+
497
+
498
+ def verify_envelope_signature(doc: dict[str, Any], public_key_path: Path) -> tuple[bool, str]:
499
+ """Verify an Envelope 0.2 signature strictly against `public_key_path` via `bounded_embodiment.signing.verify`."""
500
+ keyring = keyring_from_public_pem(public_key_path)
501
+ findings = _be_verify_sig(doc, keyring)
502
+ errs = _be_errors(findings)
503
+ if errs:
504
+ return False, "; ".join(f"{f.code}: {f.detail}" for f in errs)
505
+ kid = next(iter(keyring.keys()))
506
+ return True, f"ed25519-jcs-verified (kid={kid[:12]}...)"
507
+
508
+
509
+ def validate_envelope_doc(doc: dict[str, Any]) -> tuple[bool, str]:
510
+ """Validate an envelope document via `bounded_embodiment.envelope.load`."""
511
+ try:
512
+ _be_load_envelope(doc)
513
+ return True, f"envelope-0.2-verified (bounded-embodiment {bounded_embodiment_version()})"
514
+ except Exception as exc:
515
+ return False, f"bounded-embodiment envelope validation failed: {exc}"
516
+
517
+
518
+ # --------------------------------------------------------------------------- 4. Hostile Command Generator
519
+ def build_cartesian_command_space(
520
+ *,
521
+ workspace_min: Sequence[float],
522
+ workspace_max: Sequence[float],
523
+ exclusions: Sequence[tuple[str, Sequence[float], Sequence[float]]] = (),
524
+ description: str = "robot-gate Cartesian TCP command space",
525
+ ) -> CommandSpace:
526
+ """Build & validate a `bounded-embodiment` command-space-0.1 covering workspace + out-of-bounds margin."""
527
+ margin = 0.25
528
+ axes = []
529
+ for key, lo, hi in zip(("x", "y", "z"), workspace_min, workspace_max):
530
+ alo = round(float(lo) - margin, 4)
531
+ ahi = round(float(hi) + margin, 4)
532
+ home = round(0.5 * (float(lo) + float(hi)), 4)
533
+ axes.append({"key": key, "unit": "m", "lo": alo, "hi": ahi, "home": home})
534
+
535
+ far_targets: list[dict[str, Any]] = [
536
+ {
537
+ "id": "outside_x_max",
538
+ "values": {
539
+ "x": round(float(workspace_max[0]) + 0.20, 4),
540
+ "y": axes[1]["home"],
541
+ "z": axes[2]["home"],
542
+ },
543
+ "description": "Past +X workspace wall",
544
+ },
545
+ {
546
+ "id": "below_z_min",
547
+ "values": {
548
+ "x": axes[0]["home"],
549
+ "y": axes[1]["home"],
550
+ "z": round(float(workspace_min[2]) - 0.15, 4),
551
+ },
552
+ "description": "Below -Z floor limit",
553
+ },
554
+ ]
555
+ for name, elo, ehi in exclusions:
556
+ safe_id = "".join(c if (c.isalnum() or c in "_.-") else "_" for c in str(name))[:48]
557
+ far_targets.append(
558
+ {
559
+ "id": f"keepout_{safe_id}",
560
+ "values": {
561
+ "x": round(0.5 * (float(elo[0]) + float(ehi[0])), 4),
562
+ "y": round(0.5 * (float(elo[1]) + float(ehi[1])), 4),
563
+ "z": round(0.5 * (float(elo[2]) + float(ehi[2])), 4),
564
+ },
565
+ "description": f"Inside exclusion zone {name}",
566
+ }
567
+ )
568
+
569
+ doc = {
570
+ "command_space_version": "0.1",
571
+ "kind": "cartesian_position",
572
+ "axes": axes,
573
+ "far_targets": far_targets,
574
+ "description": description,
575
+ }
576
+ return load_command_space(doc)
577
+
578
+
579
+ def evaluate_hostile_stream(
580
+ embodiment: Any,
581
+ *,
582
+ seed: int = 42,
583
+ seconds: float = 2.0,
584
+ base_hz: float = 25.0,
585
+ ) -> dict[str, Any]:
586
+ """Run the official `bounded_embodiment.generator.hostile_stream` against an EmbodimentSpec.
587
+
588
+ Verifies that EVERY malformed, non-finite, missing-axis, or out-of-envelope hostile command
589
+ is deterministically DENIED (0 unsafe leaks).
590
+ """
591
+ space = build_cartesian_command_space(
592
+ workspace_min=embodiment.workspace.bmin,
593
+ workspace_max=embodiment.workspace.bmax,
594
+ exclusions=[(ex.name, ex.bmin, ex.bmax) for ex in embodiment.exclusions],
595
+ description=f"robot-gate hostile regression command space for {embodiment.name}",
596
+ )
597
+ params = {
598
+ "seconds": float(seconds),
599
+ "base_hz": float(base_hz),
600
+ "burst_hz": float(base_hz * 2.0),
601
+ "segment_s": [0.25, 0.5],
602
+ "strategies": list(STRATEGIES),
603
+ }
604
+ digest = stream_sha256(space, seed=seed, params=params)
605
+
606
+ total = 0
607
+ malformed_denied = 0
608
+ oob_denied = 0
609
+ safe_allowed = 0
610
+ unsafe_leaks: list[str] = []
611
+ seen_strategies: set[str] = set()
612
+
613
+ for prop in hostile_stream(space, seed=seed, params=params):
614
+ total += 1
615
+ seen_strategies.add(prop.strategy)
616
+ payload = prop.payload
617
+
618
+ # Default-deny schema / finiteness check (catches malformed, partial, NaN/Inf, unknown_axis)
619
+ keys = set(payload.keys())
620
+ if keys != {"x", "y", "z"}:
621
+ malformed_denied += 1
622
+ continue
623
+ coords: list[float] = []
624
+ bad_val = False
625
+ for k in ("x", "y", "z"):
626
+ v = payload[k]
627
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(float(v)):
628
+ bad_val = True
629
+ break
630
+ coords.append(float(v))
631
+ if bad_val:
632
+ malformed_denied += 1
633
+ continue
634
+
635
+ xyz = (coords[0], coords[1], coords[2])
636
+ allowed, h_margin, _ = embodiment.evaluate_point(
637
+ xyz, force_n=5.0, velocity_mps=0.1, tool_name="arm.move_bounded"
638
+ )
639
+ # Independently check ground-truth geometry via bounded_embodiment.envelope.geometry
640
+ gt_inside_ws = box_signed_distance_inside(embodiment.workspace.bmin, embodiment.workspace.bmax, xyz) >= 0.0
641
+ gt_outside_ex = all(
642
+ box_signed_distance_inside(ex.bmin, ex.bmax, xyz) <= 0.0 for ex in embodiment.exclusions
643
+ )
644
+ gt_safe = gt_inside_ws and gt_outside_ex
645
+
646
+ if allowed and not gt_safe:
647
+ unsafe_leaks.append(f"seq={prop.seq} strategy={prop.strategy} xyz={xyz} leaked (h={h_margin})")
648
+ elif allowed:
649
+ safe_allowed += 1
650
+ else:
651
+ oob_denied += 1
652
+
653
+ return {
654
+ "generator_version": GENERATOR_VERSION,
655
+ "seed": seed,
656
+ "stream_sha256": digest,
657
+ "total_proposals": total,
658
+ "strategies_exercised": sorted(seen_strategies),
659
+ "malformed_denied": malformed_denied,
660
+ "out_of_bounds_denied": oob_denied,
661
+ "in_bounds_allowed": safe_allowed,
662
+ "unsafe_leaks": unsafe_leaks,
663
+ "passed": len(unsafe_leaks) == 0 and total > 0 and (malformed_denied + oob_denied) > 0,
664
+ }
665
+
666
+
667
+ # --------------------------------------------------------------------------- 5. Official Report Verifier
668
+ def verify_bounded_report_dir(
669
+ run_dir: Path,
670
+ *,
671
+ public_key_path: Path | None = None,
672
+ keyring_entries: Iterable[dict[str, Any]] | None = None,
673
+ ) -> dict[str, Any]:
674
+ """Verify an official `bounded-embodiment` run directory using `bounded_embodiment.report.verify`."""
675
+ if keyring_entries is not None:
676
+ keyring = _be_keyring_from_entries(keyring_entries)
677
+ elif public_key_path is not None:
678
+ if public_key_path.suffix.lower() == ".json":
679
+ raw = json.loads(public_key_path.read_text(encoding="utf-8"))
680
+ entries = raw.get("keys", [raw]) if isinstance(raw, dict) else list(raw)
681
+ keyring = _be_keyring_from_entries(entries)
682
+ else:
683
+ keyring = keyring_from_public_pem(public_key_path)
684
+ else:
685
+ keyring = {}
686
+
687
+ res = _be_verify_report(run_dir, keyring)
688
+ errs = [f"{f.code}: {f.detail}" for f in res.findings if f.severity == "error"]
689
+ warns = [f"{f.code}: {f.detail}" for f in res.findings if f.severity != "error"]
690
+ return {
691
+ "consistent": bool(res.consistent),
692
+ "verdict": getattr(res, "verdict", None),
693
+ "error_count": len(errs),
694
+ "warning_count": len(warns),
695
+ "errors": errs,
696
+ "warnings": warns,
697
+ "verified_via": f"bounded_embodiment.report.verify ({bounded_embodiment_version()})",
698
+ }
699
+
700
+
701
+ __all__ = [
702
+ "bounded_embodiment_version",
703
+ "box_signed_distance_inside",
704
+ "build_cartesian_command_space",
705
+ "build_envelope_doc",
706
+ "canonical_json_bytes",
707
+ "check_swept_path_fast",
708
+ "evaluate_hostile_stream",
709
+ "graft_core_version",
710
+ "keyring_from_public_pem",
711
+ "private_pem_to_jwk",
712
+ "public_pem_to_jwk",
713
+ "rust_kernel_active",
714
+ "sha256_canonical",
715
+ "sign_envelope_doc",
716
+ "validate_envelope_doc",
717
+ "verify_bounded_report_dir",
718
+ "verify_envelope_signature",
719
+ ]