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.
robot_gate/cli.py ADDED
@@ -0,0 +1,2267 @@
1
+ """CLI entry point for `robot-gate`.
2
+
3
+ Commands:
4
+ robot-gate init Scaffold ROBOT.md, gate.yaml, optional Ed25519 keys, and baseline profile
5
+ robot-gate connect 3-click LLM-to-Robot connect kit (connect-graft.sh, AI client config, ROBOT.md, FIRST_PROMPT.md)
6
+ robot-gate onboard Guided offline self-serve onboarding wizard (6 personas incl. ros2, ROBOT.md v1.1, L0 self-test)
7
+ robot-gate demo 1-command local demo (Mission Control UI or `--ros2` zero-ROS-install ROS 2 + compliance demo)
8
+ robot-gate set Safe L0_OBSERVE RoboCurve Six Easy Tasks (SET) verification & portable bundle export
9
+ robot-gate plan Deterministic Shop Swarm & CapEx ROI planner (20-asset catalog, bottleneck & payback)
10
+ robot-gate snapshot Capture measured hardware telemetry (and optionally patch MuJoCo MJCF)
11
+ robot-gate check Run 4-stage deterministic gate ("0 wrong moves") and sign gate_receipt.json
12
+ robot-gate why Explain the latest gate receipt, failing stages, and changed files
13
+ robot-gate verify-audit Offline cryptographic verification of SHA-256 audit_log.jsonl
14
+ robot-gate install-hook Install local git pre-commit hook (runs `robot-gate check --sim-only` locally)
15
+ robot-gate install-systemd Generate a clean parameterized systemd unit file for on-robot deployment
16
+ robot-gate serve Start the offline on-robot FastAPI harness & Graft Cell Console with hard receipt latch
17
+ robot-gate ros2-bridge Generate ROS 2 launch bundles or run the ROS 2 pre-flight boundary interceptor node
18
+ robot-gate compliance-pack Generate or offline-verify ISO 10218:2025 & EU 2023/1230 compliance dossiers
19
+ robot-gate vault Opt-in Hosted Fleet Receipt Vault sync (`push` / `status`; zero phone-home without key)
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import shlex
27
+ import stat
28
+ import sys
29
+ import tempfile
30
+ import time
31
+ from dataclasses import replace
32
+ from pathlib import Path
33
+
34
+ import yaml
35
+
36
+
37
+ def _c(text: str, code: str) -> str:
38
+ if not sys.stdout.isatty():
39
+ return text
40
+ return f"\033[{code}m{text}\033[0m"
41
+
42
+ from . import SAFETY_BOUNDARY_STATEMENT, __version__
43
+ from .audit import verify_audit_chain
44
+ from .bounded_bridge import (
45
+ build_envelope_doc,
46
+ sign_envelope_doc,
47
+ validate_envelope_doc,
48
+ verify_bounded_report_dir,
49
+ )
50
+ from .compliance_pack import (
51
+ DEFAULT_ZIP_FILENAME,
52
+ generate_compliance_pack,
53
+ verify_compliance_pack,
54
+ )
55
+ from .device_discovery import discover_environment_devices
56
+ from .gate import GateConfig, GateReceipt, run_gate_check
57
+ from .ros2_adapter import (
58
+ ROS2BoundaryGate,
59
+ ROS2GateNode,
60
+ generate_ros2_launch_bundle,
61
+ load_ros2_gate_config_from_params,
62
+ rclpy_available,
63
+ run_ros2_gate_node,
64
+ )
65
+ from .trust import TrustLadder, TrustLevel
66
+ from .vault_client import fetch_vault_status, push_receipt_to_vault
67
+ from .onboard import (
68
+ AI_TIER_CHOICES,
69
+ HAND_FAMILY_CHOICES,
70
+ MODE_CHOICES,
71
+ PERSONA_CHOICES,
72
+ build_end_effector_dict,
73
+ run_onboard_cli,
74
+ )
75
+ from .skillpacks import SKILL_PACK_CATALOG, install_skill_pack, list_skill_packs
76
+ from .set_kit import (
77
+ ARM_SETUPS,
78
+ SET_TASK_ORDER,
79
+ export_set_bundle,
80
+ resolve_arm_setup,
81
+ validate_all_tasks_for_arm,
82
+ validate_set_task_for_arm,
83
+ )
84
+ from .shop_swarm import (
85
+ ISO_13850_SAFETY_BOUNDARY,
86
+ PLANNING_ESTIMATE_DISCLOSURE,
87
+ SHOP_CATALOG,
88
+ ShopParams,
89
+ ShopProfitabilityPlanner,
90
+ create_default_shop_swarm,
91
+ )
92
+ from .manifest import (
93
+ PRESET_EMBODIMENTS,
94
+ generate_ed25519_keypair,
95
+ load_manifest,
96
+ render_preset_manifest,
97
+ sign_manifest,
98
+ )
99
+ from .telemetry import (
100
+ SOArm101LiveProvider,
101
+ StaticBaselineProvider,
102
+ patch_mjcf_with_measured_profile,
103
+ )
104
+
105
+
106
+ def _cmd_init(args: argparse.Namespace) -> int:
107
+ root = Path(args.dir).resolve()
108
+ root.mkdir(parents=True, exist_ok=True)
109
+ manifest_path = root / "ROBOT.md"
110
+ gate_yaml = root / "gate.yaml"
111
+
112
+ if manifest_path.exists() and not args.force:
113
+ print(f"error: {manifest_path} already exists (pass --force to overwrite)", file=sys.stderr)
114
+ return 2
115
+
116
+ manifest_path.write_text(
117
+ render_preset_manifest(args.preset, organization=args.org), encoding="utf-8"
118
+ )
119
+ cfg = GateConfig(
120
+ embodiment=args.preset.replace("-", "_"),
121
+ require_signed_manifest=bool(args.sign),
122
+ signing_kid=args.kid,
123
+ )
124
+ if args.sign:
125
+ priv = root / cfg.private_key_path # type: ignore[operator]
126
+ pub = root / cfg.public_key_path # type: ignore[operator]
127
+ generate_ed25519_keypair(priv, pub)
128
+ sign_manifest(manifest_path, priv, cfg.signing_kid)
129
+ cfg.save(gate_yaml)
130
+
131
+ # Also capture an initial offline baseline snapshot so `robot-gate check --sim-only` works immediately
132
+ manifest = load_manifest(manifest_path)
133
+ emb = manifest.get_embodiment(cfg.embodiment)
134
+ snap = StaticBaselineProvider().read_snapshot(emb)
135
+ snap.save(root / cfg.hardware_profile_path)
136
+
137
+ print(f"Initialized robot-gate workspace in {root}")
138
+ print(f" Preset: {args.preset} ({emb.dof}-DoF)")
139
+ print(f" Manifest: {manifest_path} ({'Ed25519 signed' if args.sign else 'unsigned'})")
140
+ print(f" Config: {gate_yaml}")
141
+ print(f" Baseline: {root / cfg.hardware_profile_path}")
142
+ print(f"\nNext: run `robot-gate check --dir {root} --sim-only`")
143
+ return 0
144
+
145
+
146
+ def _cmd_snapshot(args: argparse.Namespace) -> int:
147
+ root = Path(args.dir).resolve()
148
+ cfg = GateConfig.load(root / "gate.yaml")
149
+ manifest = load_manifest(root / cfg.manifest_path)
150
+ emb = manifest.get_embodiment(cfg.embodiment)
151
+
152
+ if args.live:
153
+ provider = SOArm101LiveProvider(root / cfg.manifest_path, port=args.port, baud=args.baud)
154
+ else:
155
+ provider = StaticBaselineProvider()
156
+
157
+ snap = provider.read_snapshot(emb)
158
+ out_path = root / cfg.hardware_profile_path
159
+ snap.save(out_path)
160
+ print(f"Saved hardware snapshot ({snap.source}) -> {out_path} ({len(snap.actuators)} actuators)")
161
+
162
+ if args.mjcf_in:
163
+ mjcf_in = Path(args.mjcf_in)
164
+ mjcf_out = Path(args.mjcf_out) if args.mjcf_out else mjcf_in.with_suffix(".measured.xml")
165
+ count = patch_mjcf_with_measured_profile(mjcf_in, snap, mjcf_out)
166
+ print(f"Patched {count} MuJoCo joints with measured damping/friction -> {mjcf_out}")
167
+ return 0
168
+
169
+
170
+ def _cmd_check(args: argparse.Namespace) -> int:
171
+ t0 = time.perf_counter()
172
+ root = Path(args.dir).resolve()
173
+ cfg = GateConfig.load(root / "gate.yaml")
174
+ provider = None
175
+ if args.live:
176
+ provider = SOArm101LiveProvider(root / cfg.manifest_path, port=args.port, baud=args.baud)
177
+
178
+ receipt = run_gate_check(root, cfg, telemetry_provider=provider, sim_only=args.sim_only)
179
+ elapsed_ms = int((time.perf_counter() - t0) * 1000)
180
+
181
+ if args.json:
182
+ print(json.dumps(receipt.to_dict(), indent=2))
183
+ else:
184
+ status = _c("PASS", "32;1") if receipt.passed else _c("FAIL", "31;1")
185
+ print(
186
+ f"robot-gate check: {status} "
187
+ f"(embodiment={receipt.embodiment}, fp={receipt.fingerprint[:12]}, {elapsed_ms}ms)"
188
+ )
189
+ for s in receipt.stages:
190
+ mark = _c("PASS", "32") if s.passed else _c("FAIL", "31")
191
+ print(f" [{mark}] {s.name:20s} — {s.summary}")
192
+ for fail in s.failures:
193
+ print(f" -> {_c(fail, '31')}")
194
+ print(f"Receipt ({receipt.signature_alg}): {root / cfg.receipt_path}")
195
+ return 0 if receipt.passed else 1
196
+
197
+
198
+ def _cmd_why(args: argparse.Namespace) -> int:
199
+ root = Path(args.dir).resolve()
200
+ cfg = GateConfig.load(root / "gate.yaml")
201
+ receipt_path = root / cfg.receipt_path
202
+ if not receipt_path.exists():
203
+ print("No gate_receipt.json found yet. Run `robot-gate check` first.", file=sys.stderr)
204
+ return 1
205
+ receipt = GateReceipt.load(receipt_path)
206
+ print(f"Last receipt: {'PASS' if receipt.passed else 'FAIL'} at {receipt.ts_utc} (fp={receipt.fingerprint[:12]})")
207
+ diff = receipt.fingerprint_diff
208
+ if any(diff.get(k) for k in ("added", "removed", "changed")):
209
+ print("Changes since prior receipt:")
210
+ for k in ("added", "changed", "removed"):
211
+ if diff.get(k):
212
+ print(f" {k}: {', '.join(diff[k])}")
213
+ failed = [s for s in receipt.stages if not s.passed]
214
+ if not failed:
215
+ print("All 4 gate stages passed.")
216
+ else:
217
+ print("Blocking failures:")
218
+ for s in failed:
219
+ print(f" [{s.name}]")
220
+ for f in s.failures:
221
+ print(f" - {f}")
222
+ return 0 if receipt.passed else 1
223
+
224
+
225
+ def _cmd_verify_audit(args: argparse.Namespace) -> int:
226
+ root = Path(args.dir).resolve()
227
+ cfg = GateConfig.load(root / "gate.yaml")
228
+ res = verify_audit_chain(root / cfg.audit_path)
229
+ if res.valid:
230
+ print(f"INTACT: {res.record_count} audit records verified (head={res.head_hash[:16]})")
231
+ return 0
232
+ print(f"TAMPERED/INVALID: {res.error}", file=sys.stderr)
233
+ return 1
234
+
235
+
236
+ def _cmd_verify_report(args: argparse.Namespace) -> int:
237
+ key_path = Path(args.key).resolve() if args.key else None
238
+ res = verify_bounded_report_dir(Path(args.run_dir).resolve(), public_key_path=key_path)
239
+ if args.json:
240
+ print(json.dumps(res, indent=2))
241
+ elif res["consistent"]:
242
+ print(f"CONSISTENT ({res['verified_via']}): verdict={res['verdict']} warnings={res['warning_count']}")
243
+ else:
244
+ print(f"INCONSISTENT ({res['verified_via']}): {res['error_count']} error(s)", file=sys.stderr)
245
+ for err in res["errors"]:
246
+ print(f" - {err}", file=sys.stderr)
247
+ return 0 if res["consistent"] else 1
248
+
249
+
250
+ def _cmd_install_hook(args: argparse.Namespace) -> int:
251
+ root = Path(args.dir).resolve()
252
+ git_dir = root / ".git"
253
+ if not git_dir.is_dir():
254
+ print(f"error: no .git directory found in {root}", file=sys.stderr)
255
+ return 2
256
+ hook_path = git_dir / "hooks" / "pre-commit"
257
+ hook_path.parent.mkdir(parents=True, exist_ok=True)
258
+ hook_path.write_text(
259
+ "#!/usr/bin/env bash\n"
260
+ "set -euo pipefail\n"
261
+ 'echo "[robot-gate] Running local change-triggered regression gate..."\n'
262
+ 'robot-gate check --dir "$(git rev-parse --show-toplevel)" --sim-only\n',
263
+ encoding="utf-8",
264
+ )
265
+ hook_path.chmod(hook_path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
266
+ print(f"Installed local git pre-commit hook -> {hook_path}")
267
+ return 0
268
+
269
+
270
+ def _render_systemd_unit(
271
+ *,
272
+ workspace_dir: Path,
273
+ port: int,
274
+ host: str = "127.0.0.1",
275
+ user: str | None = None,
276
+ ) -> str:
277
+ ws_str = str(workspace_dir)
278
+ if any(ch in ws_str for ch in ("\n", "\r")):
279
+ raise ValueError("Workspace directory path must not contain newlines")
280
+ if not (1 <= int(port) <= 65535):
281
+ raise ValueError(f"Port must be between 1 and 65535 (got {port})")
282
+ user_line = ""
283
+ if user is not None:
284
+ cleaned_user = user.strip()
285
+ if not cleaned_user or any(ch in cleaned_user for ch in ("\n", "\r", " ", "\t")):
286
+ raise ValueError(f"Invalid systemd --user value: {user!r}")
287
+ user_line = f"User={cleaned_user}\n"
288
+
289
+ return (
290
+ "[Unit]\n"
291
+ "Description=Graft Robotics robot-gate offline on-robot deployment harness\n"
292
+ "Documentation=https://graftrobotics.ai/docs/\n"
293
+ "After=local-fs.target network.target\n"
294
+ "Wants=local-fs.target\n"
295
+ "\n"
296
+ "[Service]\n"
297
+ "Type=simple\n"
298
+ f"{user_line}"
299
+ f"WorkingDirectory={ws_str}\n"
300
+ "Environment=PYTHONDONTWRITEBYTECODE=1\n"
301
+ "# Run 4-stage deterministic pre-flight gate before starting harness (fails closed on non-zero)\n"
302
+ f'ExecStartPre=/usr/bin/env robot-gate check --dir "{ws_str}" --sim-only\n'
303
+ f'ExecStart=/usr/bin/env robot-gate serve --dir "{ws_str}" --host {host} --port {int(port)}\n'
304
+ "Restart=on-failure\n"
305
+ "RestartSec=3\n"
306
+ "NoNewPrivileges=true\n"
307
+ "PrivateTmp=true\n"
308
+ "\n"
309
+ "[Install]\n"
310
+ "WantedBy=multi-user.target\n"
311
+ )
312
+
313
+
314
+ def _cmd_install_systemd(args: argparse.Namespace) -> int:
315
+ root = Path(args.dir).resolve()
316
+ try:
317
+ unit_text = _render_systemd_unit(
318
+ workspace_dir=root,
319
+ port=int(args.port),
320
+ host=str(args.host),
321
+ user=args.user,
322
+ )
323
+ except ValueError as exc:
324
+ if args.json:
325
+ print(json.dumps({"ok": False, "error": str(exc)}, indent=2))
326
+ else:
327
+ print(f"error: {exc}", file=sys.stderr)
328
+ return 2
329
+
330
+ out_path: Path | None = None
331
+ if args.out:
332
+ out_path = Path(args.out).resolve()
333
+ out_path.parent.mkdir(parents=True, exist_ok=True)
334
+ out_path.write_text(unit_text, encoding="utf-8")
335
+
336
+ payload = {
337
+ "ok": True,
338
+ "workspace_dir": str(root),
339
+ "host": str(args.host),
340
+ "port": int(args.port),
341
+ "user": args.user,
342
+ "out_file": str(out_path) if out_path is not None else None,
343
+ "unit": unit_text,
344
+ "safety_boundary": SAFETY_BOUNDARY_STATEMENT,
345
+ }
346
+ if args.json:
347
+ print(json.dumps(payload, indent=2))
348
+ elif out_path is not None:
349
+ print(f"Generated systemd unit -> {out_path}")
350
+ print(f" Workspace : {root}")
351
+ print(f" Listen : http://{args.host}:{int(args.port)}/")
352
+ if args.user:
353
+ print(f" User : {args.user}")
354
+ print(
355
+ f" Install : sudo cp \"{out_path}\" /etc/systemd/system/robot-gate.service && "
356
+ "sudo systemctl daemon-reload && sudo systemctl enable --now robot-gate"
357
+ )
358
+ else:
359
+ print(unit_text, end="")
360
+ return 0
361
+
362
+
363
+ def _cmd_serve(args: argparse.Namespace) -> int:
364
+ import os
365
+ import uvicorn
366
+
367
+ from .server import _is_loopback_host, create_app
368
+
369
+ if not _is_loopback_host(args.host) and not (os.environ.get("GRAFT_API_TOKEN") or "").strip():
370
+ print(
371
+ "ERROR: Non-loopback --host binding requires GRAFT_API_TOKEN to be set for mutating /v1/* routes."
372
+ )
373
+ return 2
374
+
375
+ root = Path(args.dir).resolve()
376
+ cfg = GateConfig.load(root / "gate.yaml")
377
+ app = create_app(root, cfg, bind_host=args.host)
378
+ print(f"Graft Robotics robot-gate Mission Control -> http://{args.host}:{args.port}/")
379
+ print(SAFETY_BOUNDARY_STATEMENT)
380
+ uvicorn.run(app, host=args.host, port=args.port)
381
+ return 0
382
+
383
+
384
+ def _run_ros2_zero_install_demo(args: argparse.Namespace) -> int:
385
+ """<10s zero-ROS-install Wedge A demo: signed UR5e -> 4-stage gate -> ROS 2 stream -> compliance pack."""
386
+ t0 = time.perf_counter()
387
+ if args.dir:
388
+ root = Path(args.dir).resolve()
389
+ root.mkdir(parents=True, exist_ok=True)
390
+ temp_created = False
391
+ else:
392
+ root = Path(tempfile.mkdtemp(prefix="graft-ros2-demo-")).resolve()
393
+ temp_created = True
394
+
395
+ emb_name = "ur5e"
396
+ organization = "Graft Robotics ROS 2 Demo"
397
+ kid = "demo-ros2-ur5e-1"
398
+
399
+ # 1. Scaffold signed UR5e ROBOT.md v1.1 + Ed25519 keys + gate.yaml + baseline + signed envelope.json
400
+ manifest_doc = {
401
+ "schema_version": "1.1",
402
+ "organization": organization,
403
+ "hardware_safety_boundary": {
404
+ "statement": SAFETY_BOUNDARY_STATEMENT,
405
+ "iso_13850_hardwired_estop_required": True,
406
+ "iso_13849_safety_relay_required": True,
407
+ "software_hold_is_not_estop": True,
408
+ },
409
+ "embodiments": {
410
+ emb_name: {
411
+ "hal_driver": "castor_hal.drivers.ur_rtde",
412
+ "dof": 6,
413
+ "starting_trust_level": TrustLevel.L0_OBSERVE.name,
414
+ "workspace_box_m": {"x": [-0.75, 0.75], "y": [-0.65, 0.65], "z": [0.05, 0.95]},
415
+ "exclusion_boxes_m": [
416
+ {
417
+ "name": "cnc_spindle_head",
418
+ "min": [0.32, -0.25, 0.55],
419
+ "max": [0.75, 0.25, 0.95],
420
+ },
421
+ {
422
+ "name": "operator_front_aisle",
423
+ "min": [-0.75, -0.65, 0.05],
424
+ "max": [-0.50, 0.65, 0.95],
425
+ },
426
+ ],
427
+ "max_tcp_velocity_mps": 0.50,
428
+ "max_contact_force_n": 60.0,
429
+ "min_bus_voltage_v": 46.0,
430
+ "max_temp_c": 60.0,
431
+ "max_joint_drift_rad": 0.01,
432
+ "max_tcp_drift_mm": 0.10,
433
+ "end_effector": build_end_effector_dict("parallel_2f", persona="ros2"),
434
+ }
435
+ },
436
+ }
437
+ manifest_path = root / "ROBOT.md"
438
+ manifest_path.write_text(yaml.safe_dump(manifest_doc, sort_keys=False), encoding="utf-8")
439
+
440
+ cfg = GateConfig(
441
+ embodiment=emb_name,
442
+ require_signed_manifest=True,
443
+ signing_kid=kid,
444
+ )
445
+ priv = root / str(cfg.private_key_path)
446
+ pub = root / str(cfg.public_key_path)
447
+ generate_ed25519_keypair(priv, pub)
448
+ sign_manifest(manifest_path, priv, cfg.signing_kid)
449
+ cfg.save(root / "gate.yaml")
450
+
451
+ manifest = load_manifest(manifest_path)
452
+ emb = manifest.get_embodiment(emb_name)
453
+ StaticBaselineProvider().read_snapshot(emb).save(root / cfg.hardware_profile_path)
454
+
455
+ env_doc = build_envelope_doc(
456
+ machine_id=emb.name,
457
+ workspace_min=emb.workspace.bmin,
458
+ workspace_max=emb.workspace.bmax,
459
+ exclusions=[(ex.name, ex.bmin, ex.bmax) for ex in emb.exclusions],
460
+ max_tcp_velocity_mps=emb.max_tcp_velocity_mps,
461
+ max_contact_force_n=emb.max_contact_force_n,
462
+ frame="base_link",
463
+ )
464
+ env_ok, env_note = validate_envelope_doc(env_doc)
465
+ if not env_ok:
466
+ raise RuntimeError(f"Demo Envelope 0.2 failed validation: {env_note}")
467
+ signed_env, _ = sign_envelope_doc(env_doc, priv)
468
+ (root / "envelope.json").write_text(json.dumps(signed_env, indent=2) + "\n", encoding="utf-8")
469
+
470
+ # 2. Run 4-stage deterministic gate check (latches Ed25519-signed gate_receipt.json)
471
+ receipt = run_gate_check(root, cfg, sim_only=True)
472
+
473
+ # 3. Feed realistic ROS 2 mock command stream through ROS2BoundaryGate (ZERO rclpy required!)
474
+ gate = ROS2BoundaryGate(root, embodiment=emb_name, expected_frame_id="base_link")
475
+ stream_results: list[dict[str, object]] = []
476
+
477
+ # 3a. L0_OBSERVE shadow block (cell starts safely at L0_OBSERVE: 0% physical republish)
478
+ v_shadow = gate.evaluate_pose_stamped(
479
+ {
480
+ "header": {"frame_id": "base_link"},
481
+ "pose": {
482
+ "position": {"x": 0.10, "y": 0.0, "z": 0.35},
483
+ "orientation": {"x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0},
484
+ },
485
+ },
486
+ velocity_mps=0.12,
487
+ )
488
+ stream_results.append(
489
+ {
490
+ "scenario": "l0_observe_shadow_block",
491
+ "expected_decision": "DENY",
492
+ "expected_reason_code": "L0_OBSERVE_SHADOW_DENY",
493
+ "matched": (
494
+ v_shadow.decision == "DENY"
495
+ and v_shadow.reason_code == "L0_OBSERVE_SHADOW_DENY"
496
+ and v_shadow.republish_allowed is False
497
+ and v_shadow.shadow_would_allow is True
498
+ ),
499
+ "verdict": v_shadow.to_dict(),
500
+ }
501
+ )
502
+
503
+ # Promote Trust Ladder L0_OBSERVE -> L1_ATOMIC_ASSIST (30% bounded speed cap) for live checks
504
+ ladder = TrustLadder(state_path=root / ".robot-gate" / "trust_ladder.json")
505
+ for idx in range(3):
506
+ ladder.record_verified_run(emb_name, f"demo_preflight_{idx}")
507
+ promoted, promo_msg = ladder.promote(emb_name, operator="demo_safety_engineer")
508
+
509
+ # 3b. Nominal PoseStamped -> ALLOW (clamped/verified inside workspace)
510
+ v_nominal = gate.evaluate_pose_stamped(
511
+ {
512
+ "header": {"frame_id": "base_link"},
513
+ "pose": {
514
+ "position": {"x": 0.10, "y": 0.0, "z": 0.35},
515
+ "orientation": {"x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0},
516
+ },
517
+ },
518
+ velocity_mps=0.12,
519
+ )
520
+ stream_results.append(
521
+ {
522
+ "scenario": "nominal_pose_stamped",
523
+ "expected_decision": "ALLOW",
524
+ "expected_reason_code": "OK",
525
+ "matched": (
526
+ v_nominal.decision == "ALLOW"
527
+ and v_nominal.reason_code == "OK"
528
+ and v_nominal.republish_allowed is True
529
+ ),
530
+ "verdict": v_nominal.to_dict(),
531
+ }
532
+ )
533
+
534
+ # 3c. Spindle keep-out violation -> DENY (KEEPOUT_VIOLATION)
535
+ v_keepout = gate.evaluate_pose_stamped(
536
+ {
537
+ "header": {"frame_id": "base_link"},
538
+ "pose": {
539
+ "position": {"x": 0.50, "y": 0.0, "z": 0.72},
540
+ "orientation": {"x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0},
541
+ },
542
+ },
543
+ velocity_mps=0.12,
544
+ )
545
+ stream_results.append(
546
+ {
547
+ "scenario": "spindle_keepout_violation",
548
+ "expected_decision": "DENY",
549
+ "expected_reason_code": "KEEPOUT_VIOLATION",
550
+ "matched": (
551
+ v_keepout.decision == "DENY"
552
+ and v_keepout.reason_code == "KEEPOUT_VIOLATION"
553
+ and v_keepout.republish_allowed is False
554
+ and bool(v_keepout.violator and "cnc_spindle_head" in v_keepout.violator)
555
+ ),
556
+ "verdict": v_keepout.to_dict(),
557
+ }
558
+ )
559
+
560
+ # 3d. NaN coordinate injection -> fail-closed DENY (NON_FINITE_COMMAND)
561
+ v_nan = gate.evaluate_pose_stamped(
562
+ {
563
+ "header": {"frame_id": "base_link"},
564
+ "pose": {
565
+ "position": {"x": float("nan"), "y": 0.0, "z": 0.35},
566
+ "orientation": {"x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0},
567
+ },
568
+ },
569
+ velocity_mps=0.10,
570
+ )
571
+ stream_results.append(
572
+ {
573
+ "scenario": "nan_coordinate_injection",
574
+ "expected_decision": "DENY",
575
+ "expected_reason_code": "NON_FINITE_COMMAND",
576
+ "matched": (
577
+ v_nan.decision == "DENY"
578
+ and v_nan.reason_code == "NON_FINITE_COMMAND"
579
+ and v_nan.republish_allowed is False
580
+ ),
581
+ "verdict": v_nan.to_dict(),
582
+ }
583
+ )
584
+
585
+ # 3e. Overspeed Twist -> DENY (TWIST_LINEAR_VELOCITY_EXCEEDED)
586
+ v_overspeed = gate.evaluate_twist(
587
+ {
588
+ "linear": {"x": 0.85, "y": 0.0, "z": 0.0},
589
+ "angular": {"x": 0.0, "y": 0.0, "z": 0.0},
590
+ }
591
+ )
592
+ stream_results.append(
593
+ {
594
+ "scenario": "overspeed_twist",
595
+ "expected_decision": "DENY",
596
+ "expected_reason_code": "TWIST_LINEAR_VELOCITY_EXCEEDED",
597
+ "matched": (
598
+ v_overspeed.decision == "DENY"
599
+ and v_overspeed.reason_code == "TWIST_LINEAR_VELOCITY_EXCEEDED"
600
+ and v_overspeed.republish_allowed is False
601
+ ),
602
+ "verdict": v_overspeed.to_dict(),
603
+ }
604
+ )
605
+
606
+ # 4. Verify SHA-256 hash-chained audit ledger
607
+ audit_res = verify_audit_chain(root / cfg.audit_path)
608
+
609
+ # 5. Generate & offline-verify ISO 10218:2025 & EU 2023/1230 graft-compliance-pack.zip
610
+ pack = generate_compliance_pack(
611
+ root,
612
+ output_dir=root / ".robot-gate" / "compliance",
613
+ zip_filename=DEFAULT_ZIP_FILENAME,
614
+ organization=organization,
615
+ embodiment=emb_name,
616
+ )
617
+ verify_res = verify_compliance_pack(pack.zip_path)
618
+
619
+ elapsed_ms = int((time.perf_counter() - t0) * 1000)
620
+ stream_all_matched = all(bool(item["matched"]) for item in stream_results)
621
+ overall_passed = bool(
622
+ receipt.passed and promoted and stream_all_matched and audit_res.valid and verify_res.valid
623
+ )
624
+
625
+ payload: dict[str, object] = {
626
+ "demo": "ros2_zero_install",
627
+ "passed": overall_passed,
628
+ "elapsed_ms": elapsed_ms,
629
+ "ros2_required": False,
630
+ "hardware_required": False,
631
+ "workspace": str(root),
632
+ "temp_workspace": temp_created,
633
+ "embodiment": emb_name,
634
+ "trust_promotion": {"promoted_to": "L1_ATOMIC_ASSIST", "ok": promoted, "detail": promo_msg},
635
+ "gate_check": {
636
+ "passed": receipt.passed,
637
+ "fingerprint": receipt.fingerprint,
638
+ "signature_alg": receipt.signature_alg,
639
+ "stages": [
640
+ {"name": s.name, "passed": s.passed, "summary": s.summary} for s in receipt.stages
641
+ ],
642
+ },
643
+ "ros2_stream": stream_results,
644
+ "audit_chain": {
645
+ "valid": audit_res.valid,
646
+ "record_count": audit_res.record_count,
647
+ "head_hash": audit_res.head_hash,
648
+ "error": audit_res.error,
649
+ },
650
+ "compliance_pack": pack.to_dict(),
651
+ "compliance_verify": verify_res.to_dict(),
652
+ "safety_boundary": SAFETY_BOUNDARY_STATEMENT,
653
+ }
654
+
655
+ if args.json:
656
+ print(json.dumps(payload, indent=2))
657
+ else:
658
+ status_lbl = _c("PASS", "32;1") if overall_passed else _c("FAIL", "31;1")
659
+ print("=" * 76)
660
+ print(f" Graft Robotics — Zero-ROS-Install Demo (`robot-gate demo --ros2`): {status_lbl}")
661
+ print(f" Workspace : {root} (UR5e, 0 ROS 2 / 0 hardware required, {elapsed_ms} ms)")
662
+ print("=" * 76)
663
+ print(
664
+ f" [1/4] Signed ROBOT.md + envelope.json & 4-stage gate : "
665
+ f"{'PASS' if receipt.passed else 'FAIL'} (fp={receipt.fingerprint[:12]}, {receipt.signature_alg})"
666
+ )
667
+ print(" [2/4] ROS 2 Mock Command Stream via ROS2BoundaryGate:")
668
+ for item in stream_results:
669
+ v = item["verdict"]
670
+ assert isinstance(v, dict)
671
+ mark = _c("OK", "32") if item["matched"] else _c("ERR", "31")
672
+ print(
673
+ f" [{mark}] {str(item['scenario']):28s} -> {v['decision']:5s} "
674
+ f"({v['reason_code']}, republish={v['republish_allowed']}, kernel={v['kernel']})"
675
+ )
676
+ print(
677
+ f" [3/4] SHA-256 Audit Ledger Verification : "
678
+ f"{'INTACT' if audit_res.valid else 'TAMPERED'} ({audit_res.record_count} records, head={audit_res.head_hash[:16]})"
679
+ )
680
+ print(
681
+ f" [4/4] ISO 10218:2025 / EU 2023/1230 Compliance Pack : "
682
+ f"{'VERIFIED' if verify_res.valid else 'FAILED'} ({pack.overall_status} · {pack.readiness_score_pct}%, "
683
+ f"{verify_res.files_verified} files verified, 0 private keys)"
684
+ )
685
+ print(f" ZIP archive : {pack.zip_path}")
686
+ print(f" Safety Boundary: {SAFETY_BOUNDARY_STATEMENT}")
687
+ print("=" * 76)
688
+
689
+ return 0 if overall_passed else 1
690
+
691
+
692
+ def _cmd_demo(args: argparse.Namespace) -> int:
693
+ """Zero-friction 1-command local demo: Mission Control UI or `--ros2` zero-ROS-install demo."""
694
+ if getattr(args, "ros2", False):
695
+ return _run_ros2_zero_install_demo(args)
696
+
697
+ root = Path(args.dir or "./.robot-gate-demo").resolve()
698
+ if not (root / "gate.yaml").exists():
699
+ init_ns = argparse.Namespace(
700
+ dir=str(root),
701
+ preset=args.preset,
702
+ org="Graft Robotics (graftrobotics.ai)",
703
+ kid="demo-local-1",
704
+ sign=True,
705
+ force=True,
706
+ )
707
+ rc = _cmd_init(init_ns)
708
+ if rc != 0:
709
+ return rc
710
+ cfg = GateConfig.load(root / "gate.yaml")
711
+ run_gate_check(root, cfg, sim_only=True)
712
+ return _cmd_serve(argparse.Namespace(dir=str(root), host=args.host, port=args.port))
713
+
714
+
715
+ def _cmd_mcp(args: argparse.Namespace) -> int:
716
+ from .mcp_server import RobotGateMCPServer
717
+
718
+ root = Path(args.dir).resolve()
719
+ cfg = GateConfig.load(root / "gate.yaml")
720
+ RobotGateMCPServer(root, cfg).serve_stdio()
721
+ return 0
722
+
723
+
724
+ def _cmd_devices_scan(args: argparse.Namespace) -> int:
725
+ res = discover_environment_devices(include_local=not args.lan_only, include_lan=not args.local_only)
726
+ if args.json:
727
+ print(json.dumps(res, indent=2))
728
+ return 0
729
+ print(f"Discovered {res['discovered_count']} helpful environment device(s): {res['by_modality']}")
730
+ for d in res["devices"]:
731
+ print(f" [{d['modality']:13s}] {d['device_id']:22s} ({d['endpoint']}) — {d['robot_benefit']}")
732
+ return 0
733
+
734
+
735
+ def _cmd_packs_list(args: argparse.Namespace) -> int:
736
+ packs = list_skill_packs(robot=args.robot, job=args.job)
737
+ if args.json:
738
+ print(json.dumps(packs, indent=2))
739
+ return 0
740
+ for p in packs:
741
+ print(f"{p['pack_id']:36s} | ~{p['setup_time_min']:2d}m | robots={','.join(p['supported_robots'])} | {p['title']}")
742
+ return 0
743
+
744
+
745
+ def _cmd_packs_install(args: argparse.Namespace) -> int:
746
+ res = install_skill_pack(args.pack_id, Path(args.dir), organization=args.org, sign=bool(args.sign))
747
+ if args.json:
748
+ print(json.dumps(res, indent=2))
749
+ else:
750
+ print(f"Installed Skill Pack '{res['pack_id']}' -> {res['workspace']} (~{res['setup_time_min']} min onboarding)")
751
+ print(f" Envelope: {res['envelope_check']}")
752
+ print(f" Teach {len(res['datums_to_teach'])} datums in datums.yaml: {', '.join(res['datums_to_teach'])}")
753
+ print(f" Trust start: {res['starting_trust_level']} | Skills: {', '.join(res['skills_written'])}")
754
+ return 0
755
+
756
+
757
+ def _cmd_onboard(args: argparse.Namespace) -> int:
758
+ return run_onboard_cli(
759
+ persona=args.persona,
760
+ mode=args.mode,
761
+ quick=bool(args.quick),
762
+ advanced=bool(args.advanced),
763
+ out_dir=args.out,
764
+ organization=args.org,
765
+ robot_name=args.robot_name,
766
+ hand_family=args.hand_family,
767
+ ai_tier=args.ai_tier,
768
+ non_interactive=bool(args.non_interactive),
769
+ probe_hardware=bool(args.probe_hardware),
770
+ with_ros2=bool(getattr(args, "with_ros2", False)),
771
+ as_json=bool(args.json),
772
+ )
773
+
774
+
775
+ _BASELINE_CNC_MACHINES: frozenset[str] = frozenset(
776
+ {
777
+ "haas_vf2",
778
+ "haas_vf3",
779
+ "haas_vf4",
780
+ "haas_umc750",
781
+ "haas_st10",
782
+ "haas_st20",
783
+ "cnc_mill",
784
+ "cnc_lathe",
785
+ "tormach_1100mx",
786
+ "mazak_vcn",
787
+ "okuma_genosm",
788
+ "dmg_mori",
789
+ }
790
+ )
791
+
792
+
793
+ def _cmd_set(args: argparse.Namespace) -> int:
794
+ """Strictly safe L0_OBSERVE / rehearsal verification for RoboCurve Six Easy Tasks (SET)."""
795
+ setup = resolve_arm_setup(args.arm)
796
+ if args.task == "all":
797
+ validations = validate_all_tasks_for_arm(setup)
798
+ else:
799
+ validations = {args.task: validate_set_task_for_arm(args.task, setup)}
800
+
801
+ bundle_info: dict[str, str] | None = None
802
+ if args.export_bundle:
803
+ bundle_path = Path(args.export_bundle).resolve()
804
+ bundle = export_set_bundle(setup, out_path=bundle_path)
805
+ bundle_info = {
806
+ "path": str(bundle_path),
807
+ "schema": str(bundle["schema"]),
808
+ "bundle_sha256": str(bundle["bundle_sha256"]),
809
+ }
810
+
811
+ all_passed = all(v.preflight_safety_passed for v in validations.values())
812
+ supported_tasks = [tid for tid, v in validations.items() if v.supported_for_live_execution]
813
+ bimanual_required_tasks = [tid for tid, v in validations.items() if not v.supported_for_live_execution]
814
+ engine = next(iter(validations.values())).swept_path_engine
815
+
816
+ payload: dict[str, object] = {
817
+ "mode": "L0_OBSERVE_REHEARSAL",
818
+ "motion_executed": False,
819
+ "arm_preset": setup.preset_id,
820
+ "arm_display_name": setup.display_name,
821
+ "bimanual": setup.bimanual,
822
+ "end_effector_family": setup.end_effector.family,
823
+ "engine": engine,
824
+ "task_filter": args.task,
825
+ "tasks_checked": len(validations),
826
+ "all_preflight_passed": all_passed,
827
+ "supported_for_live_execution": supported_tasks,
828
+ "bimanual_required_tasks": bimanual_required_tasks,
829
+ "tasks": {tid: v.to_dict() for tid, v in validations.items()},
830
+ "safety_boundary_statement": SAFETY_BOUNDARY_STATEMENT,
831
+ }
832
+ if bundle_info is not None:
833
+ payload["exported_bundle"] = bundle_info
834
+
835
+ if args.json:
836
+ print(json.dumps(payload, indent=2))
837
+ else:
838
+ status = _c("PASS", "32;1") if all_passed else _c("FAIL", "31;1")
839
+ print(
840
+ f"robot-gate set [L0_OBSERVE rehearsal]: {status} "
841
+ f"(arm={setup.preset_id}, tasks={len(validations)}, engine={engine})"
842
+ )
843
+ for tid, v in validations.items():
844
+ mark = _c("PASS", "32") if v.preflight_safety_passed else _c("FAIL", "31")
845
+ print(
846
+ f" [{mark}] {tid:10s} | margin={v.swept_path_min_margin_m:.4f}m | "
847
+ f"hand={v.hand_hal_verdict.decision} | {v.honesty_verdict}"
848
+ )
849
+ print(
850
+ f"Live-supported on {setup.preset_id}: {len(supported_tasks)}/{len(validations)} "
851
+ f"({', '.join(supported_tasks) if supported_tasks else 'none'})"
852
+ )
853
+ if bimanual_required_tasks:
854
+ print(
855
+ f"Bimanual required (honestly unsupported single-arm): "
856
+ f"{', '.join(bimanual_required_tasks)}"
857
+ )
858
+ if bundle_info is not None:
859
+ print(f"Exported portable SET bundle ({bundle_info['bundle_sha256'][:20]}...) -> {bundle_info['path']}")
860
+ print(f"Safety boundary: {SAFETY_BOUNDARY_STATEMENT}")
861
+
862
+ return 0 if all_passed else 1
863
+
864
+
865
+ def _cmd_plan(args: argparse.Namespace) -> int:
866
+ """Deterministic Shop Swarm & CapEx ROI planner (fail-closed validation)."""
867
+ raw_tokens = [tok.strip() for tok in str(args.acquired or "").split(",") if tok.strip()]
868
+ catalog_acquired: list[str] = []
869
+ baseline_machines: list[str] = []
870
+ unknown_tokens: list[str] = []
871
+ seen: set[str] = set()
872
+ for tok in raw_tokens:
873
+ if tok in seen:
874
+ continue
875
+ seen.add(tok)
876
+ if tok in SHOP_CATALOG:
877
+ catalog_acquired.append(tok)
878
+ elif tok in _BASELINE_CNC_MACHINES:
879
+ baseline_machines.append(tok)
880
+ else:
881
+ unknown_tokens.append(tok)
882
+
883
+ if unknown_tokens:
884
+ print(
885
+ f"error: unknown --acquired item(s): {', '.join(unknown_tokens)}. "
886
+ f"Valid catalog IDs: {', '.join(sorted(SHOP_CATALOG))}; "
887
+ f"baseline CNC machines: {', '.join(sorted(_BASELINE_CNC_MACHINES))}",
888
+ file=sys.stderr,
889
+ )
890
+ return 2
891
+
892
+ try:
893
+ shifts = float(args.shifts)
894
+ base_shifts = min(1.0, shifts) if shifts > 0.0 else shifts
895
+ params = ShopParams(
896
+ billing_rate_usd_hr=float(args.hourly_rate),
897
+ base_shifts_per_day=base_shifts,
898
+ target_shifts_per_day=shifts,
899
+ cnc_machine_count=max(1, len(baseline_machines)),
900
+ )
901
+ params.validate()
902
+ board = create_default_shop_swarm()
903
+ planner = ShopProfitabilityPlanner(board=board)
904
+ evaluation = planner.evaluate_shop(catalog_acquired, params)
905
+ rec_report = (
906
+ planner.recommend_next_acquisition(
907
+ catalog_acquired,
908
+ params,
909
+ max_budget_usd=args.budget,
910
+ )
911
+ if args.recommend
912
+ else None
913
+ )
914
+ except ValueError as exc:
915
+ print(f"error: {exc}", file=sys.stderr)
916
+ return 2
917
+
918
+ payload: dict[str, object] = {
919
+ "baseline_machines": baseline_machines,
920
+ "acquired_catalog_items": catalog_acquired,
921
+ "params": params.to_dict(),
922
+ "budget_usd": args.budget,
923
+ "evaluation": evaluation.to_dict(),
924
+ "disclosure": PLANNING_ESTIMATE_DISCLOSURE,
925
+ "safety_boundary": dict(ISO_13850_SAFETY_BOUNDARY),
926
+ }
927
+ if rec_report is not None:
928
+ payload["recommendation"] = rec_report.to_dict()
929
+ payload["top_recommendation"] = (
930
+ rec_report.top_recommendation.to_dict()
931
+ if rec_report.top_recommendation is not None
932
+ else None
933
+ )
934
+ payload["ranked_candidates"] = [c.to_dict() for c in rec_report.ranked_candidates]
935
+
936
+ if args.json:
937
+ print(json.dumps(payload, indent=2))
938
+ else:
939
+ owned_desc = ", ".join([*baseline_machines, *catalog_acquired]) or "none (manual baseline)"
940
+ print(f"robot-gate plan — Shop Swarm & CapEx ROI Planner")
941
+ print(
942
+ f" Owned: {owned_desc}\n"
943
+ f" Parameters: ${params.billing_rate_usd_hr:,.2f}/hr | "
944
+ f"target {params.target_shifts_per_day:g} shift(s)/day | "
945
+ f"{params.cnc_machine_count} CNC machine(s)"
946
+ )
947
+ print(
948
+ f" Utilization: {evaluation.spindle_utilization * 100:.1f}% "
949
+ f"(lights-out={'UNLOCKED' if evaluation.lights_out_unlocked else 'LOCKED'})"
950
+ )
951
+ print(
952
+ f" Throughput: {evaluation.parts_per_week:.1f} parts/wk "
953
+ f"(baseline {evaluation.baseline_parts_per_week:.1f})"
954
+ )
955
+ print(
956
+ f" Economics: +${evaluation.monthly_revenue_lift:,.2f}/mo rev | "
957
+ f"${evaluation.monthly_net_profit_lift:+,.2f}/mo net profit | "
958
+ f"CapEx=${evaluation.total_capex:,.0f} | "
959
+ f"Payback={evaluation.payback_months if evaluation.payback_months is not None else 'N/A'} mo"
960
+ )
961
+ if evaluation.active_bottlenecks:
962
+ print(" Bottlenecks:")
963
+ for b in evaluation.active_bottlenecks:
964
+ print(f" - {b}")
965
+ if rec_report is not None:
966
+ budget_label = f"<= ${args.budget:,.0f}" if args.budget is not None else "unbounded"
967
+ print(f" Recommendations (budget {budget_label}):")
968
+ if not rec_report.ranked_candidates:
969
+ print(" (no unowned catalog assets fit within budget)")
970
+ for c in rec_report.ranked_candidates:
971
+ pb = f"{c.incremental_payback_months} mo" if c.incremental_payback_months is not None else "N/A"
972
+ print(
973
+ f" #{c.rank} {c.item_id:20s} | CapEx=${c.capex_usd:8,.0f} | "
974
+ f"Delta=${c.delta_monthly_net_profit_usd:+8,.2f}/mo | Payback={pb:8s} | {c.name}"
975
+ )
976
+ print(f" Note: {PLANNING_ESTIMATE_DISCLOSURE}")
977
+
978
+ return 0
979
+
980
+
981
+ def _cmd_mcp_config(args: argparse.Namespace) -> int:
982
+ root = Path(args.dir).resolve()
983
+ snippet = {
984
+ "mcpServers": {
985
+ "graft-robot-gate": {
986
+ "command": "robot-gate",
987
+ "args": ["mcp", "--dir", str(root)],
988
+ }
989
+ }
990
+ }
991
+ print(json.dumps(snippet, indent=2))
992
+ return 0
993
+
994
+
995
+ class _ShadowTrustLadderProxy:
996
+ """Read-only TrustLadder proxy enforcing L0_OBSERVE (zero physical republish) in `--mode shadow`."""
997
+
998
+ def __init__(self, inner: TrustLadder) -> None:
999
+ self._inner = inner
1000
+
1001
+ def get(self, robot_id: str):
1002
+ rec = self._inner.get(robot_id)
1003
+ return replace(rec, level=TrustLevel.L0_OBSERVE)
1004
+
1005
+ def __getattr__(self, name: str):
1006
+ return getattr(self._inner, name)
1007
+
1008
+
1009
+ def _enforce_shadow_mode_on_gate(gate: ROS2BoundaryGate) -> ROS2BoundaryGate:
1010
+ """Ensure a `ROS2BoundaryGate` enforces L0_OBSERVE / zero physical republish without mutating disk state."""
1011
+ gate.trust_ladder = _ShadowTrustLadderProxy(gate.trust_ladder) # type: ignore[assignment]
1012
+ gate._refresh_trust_ladder_if_changed = lambda: None # type: ignore[method-assign]
1013
+ return gate
1014
+
1015
+
1016
+ def _cmd_ros2_bridge(args: argparse.Namespace) -> int:
1017
+ root = Path(args.dir).resolve()
1018
+ raw_mode = str(getattr(args, "mode", "shadow") or "shadow").lower()
1019
+ mode = "enforce" if raw_mode in ("enforce", "live") else "shadow"
1020
+
1021
+ if args.generate_bundle:
1022
+ res = generate_ros2_launch_bundle(
1023
+ root,
1024
+ Path(args.generate_bundle).resolve(),
1025
+ embodiment=args.embodiment,
1026
+ stack=args.stack,
1027
+ frame_id=args.frame_id or "base_link",
1028
+ )
1029
+ res["mode"] = mode
1030
+ if args.json:
1031
+ print(json.dumps(res, indent=2))
1032
+ else:
1033
+ print(
1034
+ f"Generated ROS 2 launch bundle ({res['stack']} / {res['embodiment']} / mode={mode}) "
1035
+ f"-> {res['output_dir']}"
1036
+ )
1037
+ for label, fpath in res["files"].items():
1038
+ print(f" {label:12s}: {fpath}")
1039
+ print(f"Safety boundary: {res['safety_boundary']}")
1040
+ return 0
1041
+
1042
+ if not rclpy_available():
1043
+ suggestions = [
1044
+ f'robot-gate ros2-bridge --dir "{root}" --generate-bundle "{root / "ros2"}" --stack {args.stack}',
1045
+ "robot-gate demo --ros2",
1046
+ "source /opt/ros/<distro>/setup.bash # On a ROS 2 Humble/Iron/Jazzy host",
1047
+ ]
1048
+ if mode == "shadow":
1049
+ latch_ok = False
1050
+ latch_msg = "workspace not initialized (ROBOT.md missing)"
1051
+ emb_name = args.embodiment
1052
+ if (root / "ROBOT.md").exists():
1053
+ try:
1054
+ gate = _enforce_shadow_mode_on_gate(
1055
+ ROS2BoundaryGate(
1056
+ root,
1057
+ embodiment=args.embodiment,
1058
+ expected_frame_id=args.frame_id,
1059
+ )
1060
+ )
1061
+ emb_name = gate.active_robot_id
1062
+ latch_ok, latch_msg, _ = gate.validate_latch()
1063
+ except Exception as exc:
1064
+ latch_msg = str(exc)
1065
+
1066
+ payload = {
1067
+ "ok": True,
1068
+ "mode": "shadow",
1069
+ "rclpy_available": False,
1070
+ "effective_trust_level": TrustLevel.L0_OBSERVE.name,
1071
+ "republish_allowed": False,
1072
+ "workspace": str(root),
1073
+ "embodiment": emb_name,
1074
+ "latch_valid": latch_ok,
1075
+ "latch_status": latch_msg,
1076
+ "guidance": (
1077
+ "ROS 2 `rclpy` is not installed in this Python environment. "
1078
+ "`--mode shadow` enforces L0_OBSERVE (zero physical republish). "
1079
+ "Generate a ROS 2 launch bundle with `--generate-bundle` or run `robot-gate demo --ros2` "
1080
+ "for an immediate zero-ROS-install boundary verification."
1081
+ ),
1082
+ "suggestions": suggestions,
1083
+ "safety_boundary": SAFETY_BOUNDARY_STATEMENT,
1084
+ }
1085
+ if args.json:
1086
+ print(json.dumps(payload, indent=2))
1087
+ else:
1088
+ print(
1089
+ "robot-gate ros2-bridge [SHADOW MODE — L0_OBSERVE / ZERO PHYSICAL REPUBLISH]"
1090
+ )
1091
+ print(
1092
+ " Notice: ROS 2 `rclpy` is not installed in this environment (no live ROS 2 DDS node started)."
1093
+ )
1094
+ print(
1095
+ f" Workspace: {root} (embodiment={emb_name or 'auto'}, latch={'PASS' if latch_ok else 'HOLD'}: {latch_msg})"
1096
+ )
1097
+ print(" Recommended next steps (no ROS 2 install required):")
1098
+ print(f" 1. Emit ROS 2 launch bundle : {suggestions[0]}")
1099
+ print(f" 2. Run <10s zero-ROS demo : {suggestions[1]}")
1100
+ print(f" 3. Run live on a ROS 2 host : {suggestions[2]}")
1101
+ print(f" Safety boundary: {SAFETY_BOUNDARY_STATEMENT}")
1102
+ return 0
1103
+
1104
+ err_msg = (
1105
+ "ROS 2 `rclpy` is not installed; cannot start `--mode enforce` live interceptor. "
1106
+ "Source `/opt/ros/<distro>/setup.bash` on a ROS 2 host, emit launch files via "
1107
+ "`--generate-bundle`, or run `robot-gate demo --ros2`."
1108
+ )
1109
+ if args.json:
1110
+ print(
1111
+ json.dumps(
1112
+ {
1113
+ "ok": False,
1114
+ "mode": mode,
1115
+ "rclpy_available": False,
1116
+ "error": err_msg,
1117
+ "suggestions": suggestions,
1118
+ },
1119
+ indent=2,
1120
+ )
1121
+ )
1122
+ else:
1123
+ print(f"error: {err_msg}", file=sys.stderr)
1124
+ return 2
1125
+
1126
+ try:
1127
+ if mode == "shadow":
1128
+ import rclpy as _rclpy # type: ignore[import-not-found]
1129
+
1130
+ if args.params is not None and Path(args.params).exists():
1131
+ ros_cfg = load_ros2_gate_config_from_params(
1132
+ args.params,
1133
+ workspace_dir=root,
1134
+ embodiment=args.embodiment,
1135
+ expected_frame_id=args.frame_id,
1136
+ )
1137
+ gate = ROS2BoundaryGate(root, ros_config=ros_cfg)
1138
+ else:
1139
+ gate = ROS2BoundaryGate(
1140
+ root,
1141
+ embodiment=args.embodiment,
1142
+ expected_frame_id=args.frame_id,
1143
+ )
1144
+ _enforce_shadow_mode_on_gate(gate)
1145
+ _rclpy.init()
1146
+ gate_node = ROS2GateNode(gate, node_name=args.node_name)
1147
+ try:
1148
+ _rclpy.spin(gate_node.node)
1149
+ except KeyboardInterrupt:
1150
+ pass
1151
+ finally:
1152
+ gate_node.destroy()
1153
+ if _rclpy.ok():
1154
+ _rclpy.shutdown()
1155
+ else:
1156
+ run_ros2_gate_node(
1157
+ root,
1158
+ embodiment=args.embodiment,
1159
+ node_name=args.node_name,
1160
+ expected_frame_id=args.frame_id,
1161
+ params_file=args.params,
1162
+ )
1163
+ except Exception as exc:
1164
+ if args.json:
1165
+ print(json.dumps({"ok": False, "mode": mode, "error": str(exc)}, indent=2))
1166
+ else:
1167
+ print(f"error: {exc}", file=sys.stderr)
1168
+ return 2
1169
+ return 0
1170
+
1171
+
1172
+ def _cmd_compliance_pack(args: argparse.Namespace) -> int:
1173
+ if args.verify:
1174
+ res = verify_compliance_pack(Path(args.verify).resolve())
1175
+ if args.json:
1176
+ print(json.dumps(res.to_dict(), indent=2))
1177
+ elif res.valid:
1178
+ print(
1179
+ f"[VERIFIED] {res.files_verified} file(s) verified · "
1180
+ f"manifest_sha256={res.manifest_sha256} ({res.target})"
1181
+ )
1182
+ else:
1183
+ print(f"[FAILED] Compliance pack verification failed ({res.target}):", file=sys.stderr)
1184
+ for err in res.errors:
1185
+ print(f" - {err}", file=sys.stderr)
1186
+ return 0 if res.valid else 1
1187
+
1188
+ root = Path(args.dir).resolve()
1189
+ out_dir: Path | None = None
1190
+ zip_name = args.zip_name or DEFAULT_ZIP_FILENAME
1191
+ if args.out:
1192
+ out_path = Path(args.out).resolve()
1193
+ if out_path.suffix.lower() == ".zip":
1194
+ out_dir = out_path.parent
1195
+ if not args.zip_name:
1196
+ zip_name = out_path.name
1197
+ else:
1198
+ out_dir = out_path
1199
+
1200
+ try:
1201
+ pack = generate_compliance_pack(
1202
+ root,
1203
+ output_dir=out_dir,
1204
+ zip_filename=zip_name,
1205
+ organization=args.org,
1206
+ embodiment=args.embodiment,
1207
+ )
1208
+ except Exception as exc:
1209
+ if args.json:
1210
+ print(json.dumps({"ok": False, "error": str(exc)}, indent=2))
1211
+ else:
1212
+ print(f"error: {exc}", file=sys.stderr)
1213
+ return 2
1214
+
1215
+ if args.json:
1216
+ print(json.dumps(pack.to_dict(), indent=2))
1217
+ else:
1218
+ print(
1219
+ f"Generated ISO 10218:2025 & EU 2023/1230 compliance pack "
1220
+ f"[{pack.overall_status} · {pack.readiness_score_pct}%]"
1221
+ )
1222
+ print(f" ZIP archive : {pack.zip_path}")
1223
+ print(f" Manifest : {pack.manifest_path} ({pack.manifest_sha256})")
1224
+ print(f" HTML dossier: {pack.dossier_html_path}")
1225
+ print(f" Evidence : {pack.evidence_count} hashed artifact(s) · 0 private keys bundled")
1226
+ print(f" Verify : robot-gate compliance-pack --verify {pack.zip_path}")
1227
+ return 0
1228
+
1229
+
1230
+ def _cmd_vault_push(args: argparse.Namespace) -> int:
1231
+ root = Path(args.dir).resolve()
1232
+ res = push_receipt_to_vault(
1233
+ root,
1234
+ robot_id=args.robot_id,
1235
+ cell_name=args.cell_name,
1236
+ compliance_standard=args.standard,
1237
+ vault_url=args.vault_url,
1238
+ )
1239
+ if args.json:
1240
+ print(json.dumps(res.to_dict(), indent=2))
1241
+ elif res.ok:
1242
+ print(
1243
+ f"Vault push [{res.status.upper()}]: receipt_id={res.receipt_id} "
1244
+ f"sha256={str(res.receipt_sha256 or '')[:16]} retention_until={res.retention_until} "
1245
+ f"alerts={len(res.alerts)}"
1246
+ )
1247
+ for alert in res.alerts:
1248
+ print(f" [{alert.severity.upper()}] {alert.metric}: {alert.message}")
1249
+ elif res.offline:
1250
+ print(f"Vault push [OFFLINE]: {res.error}")
1251
+ else:
1252
+ print(f"Vault push [ERROR]: {res.error}", file=sys.stderr)
1253
+ return 0 if (res.ok or res.offline) else 1
1254
+
1255
+
1256
+ def _cmd_vault_status(args: argparse.Namespace) -> int:
1257
+ res = fetch_vault_status(
1258
+ limit=args.limit,
1259
+ robot_id=args.robot_id,
1260
+ vault_url=args.vault_url,
1261
+ )
1262
+ if args.json:
1263
+ print(json.dumps(res.to_dict(), indent=2))
1264
+ elif res.ok:
1265
+ org_name = res.org.get("org_name") or res.org.get("name") or "fleet"
1266
+ print(
1267
+ f"Vault status [OK] ({org_name}): receipts={len(res.receipts)} "
1268
+ f"active_alerts={len(res.alerts)} summary={json.dumps(res.summary)}"
1269
+ )
1270
+ for alert in res.alerts:
1271
+ print(f" [{alert.severity.upper()}] {alert.robot_id} {alert.metric}: {alert.message}")
1272
+ elif res.offline:
1273
+ print(f"Vault status [OFFLINE]: {res.error}")
1274
+ else:
1275
+ print(f"Vault status [ERROR]: {res.error}", file=sys.stderr)
1276
+ return 0 if (res.ok or res.offline) else 1
1277
+
1278
+
1279
+ _CONNECT_CLOUD_CLIENTS: frozenset[str] = frozenset({"claude", "antigravity", "codex", "gemini"})
1280
+
1281
+ _CONNECT_CLIENTS: dict[str, dict[str, str]] = {
1282
+ "claude": {
1283
+ "label": "Claude Code",
1284
+ "config_filename": ".mcp.json",
1285
+ "transport": "MCP v0.5.0 (19 tools / 7 playbooks)",
1286
+ },
1287
+ "antigravity": {
1288
+ "label": "Google Antigravity",
1289
+ "config_filename": "mcp_config.json",
1290
+ "transport": "Side-Pane MCP App Workbench v0.5.0",
1291
+ },
1292
+ "codex": {
1293
+ "label": "OpenAI Codex CLI",
1294
+ "config_filename": "codex-config.toml",
1295
+ "transport": "Codex MCP Server (~/.codex/config.toml)",
1296
+ },
1297
+ "gemini": {
1298
+ "label": "Gemini CLI",
1299
+ "config_filename": "gemini-extension.json",
1300
+ "transport": "Gemini CLI Extension + MCP v0.5.0",
1301
+ },
1302
+ "mlx": {
1303
+ "label": "Apple Silicon MLX (Air-Gapped LAN)",
1304
+ "config_filename": "mlx-client-config.json",
1305
+ "transport": "Local OpenAI-Compatible mlx_lm.server ($0/mo LAN)",
1306
+ },
1307
+ "gemma4": {
1308
+ "label": "Google Gemma 4 / Ollama (Air-Gapped)",
1309
+ "config_filename": "gemma4-ollama-config.json",
1310
+ "transport": "Local Ollama Gemma 4 Multimodal + MCP ($0/mo LAN)",
1311
+ },
1312
+ }
1313
+
1314
+ _CONNECT_ROBOTS: dict[str, dict[str, object]] = {
1315
+ "ros2": {
1316
+ "label": "ROS 2 / MoveIt 2 Arm",
1317
+ "embodiment": "ros2_arm",
1318
+ "preset": "ur5e",
1319
+ "hal_driver": "castor_hal.drivers.ros2_moveit2",
1320
+ "ros2_stack": "moveit2",
1321
+ "hand_family": "parallel_2f",
1322
+ "persona": "ros2",
1323
+ },
1324
+ "ur5e": {
1325
+ "label": "Universal Robots UR5e",
1326
+ "embodiment": "ur5e",
1327
+ "preset": "ur5e",
1328
+ "hal_driver": "castor_hal.drivers.ur_rtde",
1329
+ "ros2_stack": "ur",
1330
+ "hand_family": "parallel_2f",
1331
+ "persona": "ros2",
1332
+ },
1333
+ "fr5": {
1334
+ "label": "FAIRINO FR5",
1335
+ "embodiment": "fairino_fr5",
1336
+ "preset": "fairino-fr5",
1337
+ "hal_driver": "castor_hal.drivers.fairino_fr5",
1338
+ "ros2_stack": "fr5",
1339
+ "hand_family": "parallel_2f",
1340
+ "persona": "cnc",
1341
+ },
1342
+ "xarm6": {
1343
+ "label": "xArm 6",
1344
+ "embodiment": "xarm6",
1345
+ "preset": "xarm6",
1346
+ "hal_driver": "castor_hal.drivers.ufactory_xarm",
1347
+ "ros2_stack": "xarm",
1348
+ "hand_family": "parallel_2f",
1349
+ "persona": "lab",
1350
+ },
1351
+ "soarm101": {
1352
+ "label": 'SO-ARM101 ("Bob")',
1353
+ "embodiment": "so_arm101",
1354
+ "preset": "so-arm101",
1355
+ "hal_driver": "castor_hal.drivers.feetech_sts3215",
1356
+ "ros2_stack": "moveit2",
1357
+ "hand_family": "parallel_2f",
1358
+ "persona": "benchtop",
1359
+ },
1360
+ "asimov1": {
1361
+ "label": "Asimov 1 Humanoid",
1362
+ "embodiment": "asimov_1",
1363
+ "preset": "asimov-1",
1364
+ "hal_driver": "castor_hal.drivers.menlo_asimov_radxa_pi5",
1365
+ "ros2_stack": None,
1366
+ "hand_family": "dexterous_5f",
1367
+ "persona": "oem",
1368
+ },
1369
+ }
1370
+
1371
+ _CONNECT_ENVIRONMENTS: dict[str, dict[str, object]] = {
1372
+ "lab": {
1373
+ "label": "Lab Bench / Desk",
1374
+ "max_velocity_cap_mps": 0.30,
1375
+ "max_force_cap_n": 25.0,
1376
+ "exclusions": [
1377
+ {"name": "table_surface_keepout", "min": [-0.60, -0.60, -0.25], "max": [0.60, 0.60, 0.00]},
1378
+ {"name": "operator_bench_front", "min": [-0.85, -0.70, 0.00], "max": [-0.55, 0.70, 1.10]},
1379
+ ],
1380
+ },
1381
+ "industrial": {
1382
+ "label": "Industrial CNC / Workcell",
1383
+ "max_velocity_cap_mps": 0.50,
1384
+ "max_force_cap_n": 60.0,
1385
+ "exclusions": [
1386
+ {"name": "cnc_spindle_head", "min": [0.32, -0.25, 0.55], "max": [0.85, 0.25, 1.15]},
1387
+ {"name": "operator_front_aisle", "min": [-0.85, -0.75, 0.00], "max": [-0.52, 0.75, 1.25]},
1388
+ ],
1389
+ },
1390
+ "warehouse": {
1391
+ "label": "Warehouse / Mobile Zone",
1392
+ "max_velocity_cap_mps": 0.40,
1393
+ "max_force_cap_n": 45.0,
1394
+ "exclusions": [
1395
+ {"name": "human_pedestrian_aisle", "min": [-0.85, -0.80, 0.00], "max": [-0.48, 0.80, 1.40]},
1396
+ {"name": "racking_clearance_keepout", "min": [0.45, -0.70, 0.00], "max": [0.95, 0.70, 1.40]},
1397
+ ],
1398
+ },
1399
+ }
1400
+
1401
+
1402
+ def _render_connect_client_config(
1403
+ *,
1404
+ client: str,
1405
+ workspace_dir: Path,
1406
+ embodiment: str,
1407
+ robot_label: str,
1408
+ env_label: str,
1409
+ airgapped: bool,
1410
+ vault_enabled: bool,
1411
+ ) -> tuple[str, str]:
1412
+ ws_str = str(workspace_dir)
1413
+ if client == "claude":
1414
+ doc = {
1415
+ "mcpServers": {
1416
+ "graft-robotics": {
1417
+ "command": "robot-gate",
1418
+ "args": ["mcp", "--dir", ws_str],
1419
+ "env": {
1420
+ "GRAFT_PLUGIN_VERSION": "0.5.0",
1421
+ "GRAFT_TRUST_START": "L0_OBSERVE",
1422
+ "GRAFT_AIRGAPPED": "0",
1423
+ },
1424
+ }
1425
+ },
1426
+ "_graft_meta": {
1427
+ "plugin": "graft-robotics@robotregistryfoundation",
1428
+ "version": "0.5.0",
1429
+ "tools": 19,
1430
+ "playbooks": 7,
1431
+ "robot": robot_label,
1432
+ "environment": env_label,
1433
+ "vault_opt_in": vault_enabled,
1434
+ "safety_boundary": SAFETY_BOUNDARY_STATEMENT,
1435
+ },
1436
+ }
1437
+ return ".mcp.json", json.dumps(doc, indent=2) + "\n"
1438
+
1439
+ if client == "antigravity":
1440
+ doc = {
1441
+ "mcpServers": {
1442
+ "graft-robotics": {
1443
+ "command": "robot-gate",
1444
+ "args": ["mcp", "--dir", ws_str],
1445
+ "env": {
1446
+ "GRAFT_CELL_URL": "http://127.0.0.1:8785",
1447
+ "GRAFT_PLUGIN_VERSION": "0.5.0",
1448
+ "GRAFT_TRUST_START": "L0_OBSERVE",
1449
+ },
1450
+ }
1451
+ },
1452
+ "workbench": {
1453
+ "app": "graft-robotics",
1454
+ "version": "0.5.0",
1455
+ "robot": robot_label,
1456
+ "environment": env_label,
1457
+ "vault_opt_in": vault_enabled,
1458
+ },
1459
+ }
1460
+ return "mcp_config.json", json.dumps(doc, indent=2) + "\n"
1461
+
1462
+ if client == "codex":
1463
+ ws_toml = json.dumps(ws_str)
1464
+ text = (
1465
+ "# Graft Robotics MCP Server for OpenAI Codex CLI (~/.codex/config.toml)\n"
1466
+ f"# Robot: {robot_label} | Environment: {env_label} | MCP v0.5.0 | Starting Tier: L0_OBSERVE\n"
1467
+ "[mcp_servers.graft_robotics]\n"
1468
+ 'command = "robot-gate"\n'
1469
+ f'args = ["mcp", "--dir", {ws_toml}]\n'
1470
+ "\n"
1471
+ "[mcp_servers.graft_robotics.env]\n"
1472
+ 'GRAFT_PLUGIN_VERSION = "0.5.0"\n'
1473
+ 'GRAFT_TRUST_START = "L0_OBSERVE"\n'
1474
+ )
1475
+ return "codex-config.toml", text
1476
+
1477
+ if client == "gemini":
1478
+ doc = {
1479
+ "name": "graft-robotics",
1480
+ "version": "0.5.0",
1481
+ "description": f"Deterministic L0 OBSERVE pre-flight safety boundary for {robot_label} ({env_label})",
1482
+ "mcpServers": {
1483
+ "graft_robotics": {
1484
+ "command": "robot-gate",
1485
+ "args": ["mcp", "--dir", ws_str],
1486
+ }
1487
+ },
1488
+ "contextFileName": "FIRST_PROMPT.md",
1489
+ }
1490
+ return "gemini-extension.json", json.dumps(doc, indent=2) + "\n"
1491
+
1492
+ if client == "mlx":
1493
+ doc = {
1494
+ "mode": "airgapped_lan" if airgapped else "local_lan",
1495
+ "itar_ear_cloud_disabled": airgapped,
1496
+ "vault_disabled": True if airgapped else (not vault_enabled),
1497
+ "llm_backend": {
1498
+ "provider": "apple_silicon_mlx",
1499
+ "base_url": "http://127.0.0.1:11434/v1",
1500
+ "model": "mlx-community/gemma-4-e4b-it-4bit",
1501
+ "launch_command": "mlx_lm.server --model mlx-community/gemma-4-e4b-it-4bit --host 127.0.0.1 --port 11434",
1502
+ },
1503
+ "mcp_server": {
1504
+ "command": "robot-gate",
1505
+ "args": ["mcp", "--dir", ws_str],
1506
+ },
1507
+ "embodiment": embodiment,
1508
+ "starting_trust_level": "L0_OBSERVE",
1509
+ "safety_boundary": SAFETY_BOUNDARY_STATEMENT,
1510
+ }
1511
+ return "mlx-client-config.json", json.dumps(doc, indent=2) + "\n"
1512
+
1513
+ # gemma4 (Ollama local air-gapped)
1514
+ doc = {
1515
+ "mode": "airgapped_lan" if airgapped else "local_lan",
1516
+ "itar_ear_cloud_disabled": airgapped,
1517
+ "vault_disabled": True if airgapped else (not vault_enabled),
1518
+ "llm_backend": {
1519
+ "provider": "ollama_gemma4",
1520
+ "base_url": "http://127.0.0.1:11434",
1521
+ "model": "gemma4:e4b-it-qat",
1522
+ "launch_command": "ollama run gemma4:e4b-it-qat",
1523
+ },
1524
+ "mcp_server": {
1525
+ "command": "robot-gate",
1526
+ "args": ["mcp", "--dir", ws_str],
1527
+ },
1528
+ "embodiment": embodiment,
1529
+ "starting_trust_level": "L0_OBSERVE",
1530
+ "safety_boundary": SAFETY_BOUNDARY_STATEMENT,
1531
+ }
1532
+ return "gemma4-ollama-config.json", json.dumps(doc, indent=2) + "\n"
1533
+
1534
+
1535
+ def _render_connect_script(
1536
+ *,
1537
+ client: str,
1538
+ robot: str,
1539
+ env_key: str,
1540
+ workspace_dir: Path,
1541
+ embodiment: str,
1542
+ ros2_stack: str | None,
1543
+ config_filename: str,
1544
+ airgapped: bool,
1545
+ vault_enabled: bool,
1546
+ ) -> str:
1547
+ q_ws = shlex.quote(str(workspace_dir))
1548
+ q_ros2 = shlex.quote(str(workspace_dir / "ros2"))
1549
+ q_zip = shlex.quote(str(workspace_dir / "artifacts" / "graft-compliance-pack.zip"))
1550
+ q_cfg = shlex.quote(str(workspace_dir / config_filename))
1551
+ q_emb = shlex.quote(embodiment)
1552
+
1553
+ lines = [
1554
+ "#!/usr/bin/env bash",
1555
+ "set -euo pipefail",
1556
+ "",
1557
+ f"# Graft Robotics 1-Command Connect Script ({client} -> {robot} / {env_key})",
1558
+ "# Starting Tier: L0_OBSERVE (0% physical motor actuation until verified & graduated)",
1559
+ "# Mandatory Safety Boundary (ISO 13850 / ISO 13849-1): software pre-flight boundary only —",
1560
+ "# claims zero PL/SIL safety credit and NEVER replaces a hardwired physical E-stop.",
1561
+ "",
1562
+ f"WORKSPACE_DIR={q_ws}",
1563
+ 'mkdir -p "$WORKSPACE_DIR/artifacts"',
1564
+ "",
1565
+ ]
1566
+
1567
+ if airgapped:
1568
+ lines.extend(
1569
+ [
1570
+ "# 1. ITAR / Air-Gapped Offline Install (strictly zero cloud downloads or phone-home)",
1571
+ 'if [ -d "$WORKSPACE_DIR/wheelhouse" ]; then',
1572
+ ' uv pip install --no-index --find-links "$WORKSPACE_DIR/wheelhouse" robot-md bounded-embodiment robot-md-gateway castor-hal',
1573
+ "fi",
1574
+ "unset GRAFT_VAULT_API_KEY || true",
1575
+ "",
1576
+ ]
1577
+ )
1578
+ else:
1579
+ lines.extend(
1580
+ [
1581
+ "# 1. Install published PyPI RRF tools (exposes robot-md-gateway + robot-md) & robot-gate[server]",
1582
+ "if ! command -v robot-md-gateway >/dev/null 2>&1; then",
1583
+ " uv tool install --upgrade robot-md-gateway --with bounded-embodiment --with castor-hal --with robot-md --with-executables-from robot-md",
1584
+ "fi",
1585
+ 'if ! command -v robot-gate >/dev/null 2>&1 && [ -d "./robot-gate" ]; then',
1586
+ " uv tool install --editable './robot-gate[server]'",
1587
+ "fi",
1588
+ "",
1589
+ ]
1590
+ )
1591
+
1592
+ lines.extend(
1593
+ [
1594
+ "# 2. Verify signed ROBOT.md & run 4-stage deterministic pre-flight gate in L0_OBSERVE",
1595
+ 'robot-gate check --dir "$WORKSPACE_DIR" --sim-only',
1596
+ "",
1597
+ ]
1598
+ )
1599
+
1600
+ if ros2_stack is not None:
1601
+ q_stack = shlex.quote(ros2_stack)
1602
+ lines.extend(
1603
+ [
1604
+ "# 3. Refresh ROS 2 / MoveIt 2 pre-flight boundary launch bundle",
1605
+ f'robot-gate ros2-bridge --dir "$WORKSPACE_DIR" --generate-bundle {q_ros2} --stack {q_stack} --embodiment {q_emb}',
1606
+ "",
1607
+ ]
1608
+ )
1609
+
1610
+ lines.extend(
1611
+ [
1612
+ "# 4. Generate & offline-verify ISO 10218:2025 / EU 2023/1230 compliance dossier ZIP (0 private keys)",
1613
+ f'robot-gate compliance-pack --dir "$WORKSPACE_DIR" --out {q_zip}',
1614
+ f'robot-gate compliance-pack --verify {q_zip}',
1615
+ "",
1616
+ ]
1617
+ )
1618
+
1619
+ if vault_enabled and not airgapped:
1620
+ lines.extend(
1621
+ [
1622
+ "# 5. Opt-In Cloudflare D1 Fleet Receipt Vault push (skips offline if GRAFT_VAULT_API_KEY unset)",
1623
+ 'if [ -n "${GRAFT_VAULT_API_KEY:-}" ]; then',
1624
+ ' robot-gate vault push --dir "$WORKSPACE_DIR"',
1625
+ "else",
1626
+ ' echo "[graft] GRAFT_VAULT_API_KEY unset — staying 100% offline (zero phone-home)."',
1627
+ "fi",
1628
+ "",
1629
+ ]
1630
+ )
1631
+
1632
+ if not airgapped:
1633
+ lines.extend(
1634
+ [
1635
+ "# 6. Cloudflare Workers/Pages CI Gate hook (Zero GitHub Actions):",
1636
+ f'echo "Cloudflare CI Hook: WORKSPACE_DIR={q_ws} ./robot-gate/ci/cloudflare-build.sh"',
1637
+ ]
1638
+ )
1639
+ else:
1640
+ if client == "mlx":
1641
+ lines.append('echo "Start Air-Gapped Apple MLX LAN server: mlx_lm.server --model mlx-community/gemma-4-e4b-it-4bit --host 127.0.0.1 --port 11434"')
1642
+ else:
1643
+ lines.append('echo "Start Air-Gapped Gemma 4 / Ollama server: ollama run gemma4:e4b-it-qat"')
1644
+
1645
+ lines.extend(
1646
+ [
1647
+ f'echo "Client config ready: {q_cfg}"',
1648
+ 'echo "First L0 OBSERVE prompt ready: $WORKSPACE_DIR/FIRST_PROMPT.md"',
1649
+ 'echo "Start local MCP stdio gate: robot-gate mcp --dir \\"$WORKSPACE_DIR\\""',
1650
+ ]
1651
+ )
1652
+ return "\n".join(lines) + "\n"
1653
+
1654
+
1655
+ def _render_first_prompt(
1656
+ *,
1657
+ client_label: str,
1658
+ robot_label: str,
1659
+ env_label: str,
1660
+ embodiment: str,
1661
+ workspace_dir: Path,
1662
+ airgapped: bool,
1663
+ vault_enabled: bool,
1664
+ ) -> str:
1665
+ mode_note = (
1666
+ "Air-Gapped LAN / ITAR-EAR mode (zero cloud calls, zero Vault uploads)."
1667
+ if airgapped
1668
+ else (
1669
+ "Opt-in Cloudflare D1 Fleet Vault enabled (requires GRAFT_VAULT_API_KEY)."
1670
+ if vault_enabled
1671
+ else "100% Offline Local Core (zero phone-home)."
1672
+ )
1673
+ )
1674
+ return (
1675
+ f"# First Safe L0 OBSERVE Prompt — {client_label} -> {robot_label}\n\n"
1676
+ f"> **Environment:** {env_label} (`{embodiment}`) \n"
1677
+ f"> **Mode:** {mode_note} \n"
1678
+ f"> **Safety Boundary (ISO 13850 / ISO 13849-1):** {SAFETY_BOUNDARY_STATEMENT}\n\n"
1679
+ "Paste this prompt directly into your AI client after loading the generated MCP config:\n\n"
1680
+ "```text\n"
1681
+ f"You are connected to my {robot_label} cell in {env_label} through the Graft Robotics pre-flight safety gate.\n"
1682
+ f"Workspace directory: {workspace_dir}\n"
1683
+ "Stay strictly in L0_OBSERVE (0% physical motor actuation). Do NOT command or unlock any motor.\n\n"
1684
+ "Run these read-only checks in order and report a concise summary:\n"
1685
+ "1. Read ROBOT.md and confirm the signed workspace bounds, exclusion keep-outs, velocity/force limits, and ISO 13850 hardwired E-stop requirement.\n"
1686
+ "2. Check available read-only sensors / environment devices without commanding motion.\n"
1687
+ "3. Run a zero-motion L0 swept-path simulation check for one nominal target inside bounds and one deliberately out-of-bounds keep-out target, confirming ALLOW vs DENY.\n"
1688
+ "4. Verify gate_receipt.json and check ISO 10218:2025 / EU 2023/1230 compliance pack readiness.\n"
1689
+ "5. Wait for my explicit physical E-stop verification before proposing any L1_ATOMIC promotion.\n"
1690
+ "```\n"
1691
+ )
1692
+
1693
+
1694
+ def _cmd_connect(args: argparse.Namespace) -> int:
1695
+ """3-click LLM-to-Robot connect kit generator (`robot-gate connect`)."""
1696
+ client = str(args.client)
1697
+ robot = str(args.robot)
1698
+ env_key = str(args.env)
1699
+ airgapped = bool(args.airgapped)
1700
+
1701
+ if airgapped and client in _CONNECT_CLOUD_CLIENTS:
1702
+ err = (
1703
+ f"--airgapped (ITAR/EAR offline mode) prohibits cloud LLM client '{client}'. "
1704
+ "Use --client mlx or --client gemma4 for 100% air-gapped LAN operation."
1705
+ )
1706
+ if args.json:
1707
+ print(json.dumps({"ok": False, "error": err}, indent=2))
1708
+ else:
1709
+ print(f"error: {err}", file=sys.stderr)
1710
+ return 2
1711
+
1712
+ vault_enabled = bool(args.vault) and (not airgapped)
1713
+ root = Path(args.out).resolve()
1714
+ root.mkdir(parents=True, exist_ok=True)
1715
+
1716
+ client_meta = _CONNECT_CLIENTS[client]
1717
+ robot_meta = _CONNECT_ROBOTS[robot]
1718
+ env_meta = _CONNECT_ENVIRONMENTS[env_key]
1719
+
1720
+ preset_key = str(robot_meta["preset"])
1721
+ emb_name = str(robot_meta["embodiment"])
1722
+ base_preset = dict(PRESET_EMBODIMENTS[preset_key])
1723
+ max_vel = min(float(base_preset["max_tcp_velocity_mps"]), float(env_meta["max_velocity_cap_mps"]))
1724
+ max_force = min(float(base_preset["max_contact_force_n"]), float(env_meta["max_force_cap_n"]))
1725
+
1726
+ # Merge preset + environment exclusions cleanly (deduplicated by name)
1727
+ exclusions: list[dict[str, object]] = []
1728
+ seen_ex: set[str] = set()
1729
+ for ex in list(base_preset.get("exclusion_boxes_m", [])) + list(env_meta["exclusions"]): # type: ignore[arg-type]
1730
+ ex_name = str(ex["name"])
1731
+ if ex_name not in seen_ex:
1732
+ seen_ex.add(ex_name)
1733
+ exclusions.append(dict(ex))
1734
+
1735
+ manifest_doc: dict[str, object] = {
1736
+ "schema_version": "1.1",
1737
+ "organization": str(args.org),
1738
+ "connect_profile": {
1739
+ "client": client,
1740
+ "robot": robot,
1741
+ "environment": env_key,
1742
+ "airgapped": airgapped,
1743
+ "vault_opt_in": vault_enabled,
1744
+ },
1745
+ "hardware_safety_boundary": {
1746
+ "statement": SAFETY_BOUNDARY_STATEMENT,
1747
+ "iso_13850_hardwired_estop_required": True,
1748
+ "iso_13849_safety_relay_required": True,
1749
+ "software_hold_is_not_estop": True,
1750
+ },
1751
+ "embodiments": {
1752
+ emb_name: {
1753
+ "hal_driver": str(robot_meta["hal_driver"]),
1754
+ "dof": int(base_preset["dof"]),
1755
+ "starting_trust_level": TrustLevel.L0_OBSERVE.name,
1756
+ "workspace_box_m": base_preset["workspace_box_m"],
1757
+ "exclusion_boxes_m": exclusions,
1758
+ "max_tcp_velocity_mps": max_vel,
1759
+ "max_contact_force_n": max_force,
1760
+ "min_bus_voltage_v": float(base_preset["min_bus_voltage_v"]),
1761
+ "max_temp_c": float(base_preset["max_temp_c"]),
1762
+ "max_joint_drift_rad": float(base_preset["max_joint_drift_rad"]),
1763
+ "max_tcp_drift_mm": float(base_preset["max_tcp_drift_mm"]),
1764
+ "end_effector": build_end_effector_dict(
1765
+ str(robot_meta["hand_family"]),
1766
+ persona=str(robot_meta["persona"]),
1767
+ ),
1768
+ }
1769
+ },
1770
+ }
1771
+
1772
+ manifest_path = root / "ROBOT.md"
1773
+ manifest_path.write_text(yaml.safe_dump(manifest_doc, sort_keys=False), encoding="utf-8")
1774
+
1775
+ cfg = GateConfig(
1776
+ embodiment=emb_name,
1777
+ require_signed_manifest=True,
1778
+ signing_kid=f"connect-{robot}-1",
1779
+ )
1780
+ priv = root / str(cfg.private_key_path)
1781
+ pub = root / str(cfg.public_key_path)
1782
+ generate_ed25519_keypair(priv, pub)
1783
+ sign_manifest(manifest_path, priv, cfg.signing_kid)
1784
+ cfg.save(root / "gate.yaml")
1785
+
1786
+ manifest = load_manifest(manifest_path)
1787
+ emb = manifest.get_embodiment(emb_name)
1788
+ StaticBaselineProvider().read_snapshot(emb).save(root / cfg.hardware_profile_path)
1789
+
1790
+ env_doc = build_envelope_doc(
1791
+ machine_id=emb.name,
1792
+ workspace_min=emb.workspace.bmin,
1793
+ workspace_max=emb.workspace.bmax,
1794
+ exclusions=[(ex.name, ex.bmin, ex.bmax) for ex in emb.exclusions],
1795
+ max_tcp_velocity_mps=emb.max_tcp_velocity_mps,
1796
+ max_contact_force_n=emb.max_contact_force_n,
1797
+ frame="base_link",
1798
+ )
1799
+ env_ok, env_note = validate_envelope_doc(env_doc)
1800
+ if not env_ok:
1801
+ raise RuntimeError(f"Generated Envelope 0.2 failed validation: {env_note}")
1802
+ signed_env, _ = sign_envelope_doc(env_doc, priv)
1803
+ envelope_path = root / "envelope.json"
1804
+ envelope_path.write_text(json.dumps(signed_env, indent=2) + "\n", encoding="utf-8")
1805
+
1806
+ # Initialize Trust Ladder explicitly in L0_OBSERVE
1807
+ TrustLadder(state_path=root / ".robot-gate" / "trust_ladder.json").get(emb_name)
1808
+
1809
+ # Run offline sim-only pre-flight check to latch initial Ed25519 receipt
1810
+ receipt = run_gate_check(root, cfg, sim_only=True)
1811
+
1812
+ # Emit ROS 2 launch bundle for ROS 2 / arm targets
1813
+ ros2_stack = robot_meta["ros2_stack"]
1814
+ ros2_files: dict[str, str] | None = None
1815
+ if ros2_stack is not None:
1816
+ ros2_bundle = generate_ros2_launch_bundle(
1817
+ root,
1818
+ root / "ros2",
1819
+ embodiment=emb_name,
1820
+ stack=str(ros2_stack),
1821
+ frame_id="base_link",
1822
+ )
1823
+ ros2_files = dict(ros2_bundle["files"])
1824
+
1825
+ # Emit tailored AI client config
1826
+ config_filename, config_text = _render_connect_client_config(
1827
+ client=client,
1828
+ workspace_dir=root,
1829
+ embodiment=emb_name,
1830
+ robot_label=str(robot_meta["label"]),
1831
+ env_label=str(env_meta["label"]),
1832
+ airgapped=airgapped,
1833
+ vault_enabled=vault_enabled,
1834
+ )
1835
+ config_path = root / config_filename
1836
+ config_path.write_text(config_text, encoding="utf-8")
1837
+
1838
+ # Emit executable connect-graft.sh with strict shlex.quote escaping
1839
+ script_text = _render_connect_script(
1840
+ client=client,
1841
+ robot=robot,
1842
+ env_key=env_key,
1843
+ workspace_dir=root,
1844
+ embodiment=emb_name,
1845
+ ros2_stack=str(ros2_stack) if ros2_stack is not None else None,
1846
+ config_filename=config_filename,
1847
+ airgapped=airgapped,
1848
+ vault_enabled=vault_enabled,
1849
+ )
1850
+ script_path = root / "connect-graft.sh"
1851
+ script_path.write_text(script_text, encoding="utf-8")
1852
+ script_path.chmod(script_path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
1853
+
1854
+ # Emit plain-English FIRST_PROMPT.md
1855
+ prompt_text = _render_first_prompt(
1856
+ client_label=client_meta["label"],
1857
+ robot_label=str(robot_meta["label"]),
1858
+ env_label=str(env_meta["label"]),
1859
+ embodiment=emb_name,
1860
+ workspace_dir=root,
1861
+ airgapped=airgapped,
1862
+ vault_enabled=vault_enabled,
1863
+ )
1864
+ prompt_path = root / "FIRST_PROMPT.md"
1865
+ prompt_path.write_text(prompt_text, encoding="utf-8")
1866
+
1867
+ payload: dict[str, object] = {
1868
+ "ok": bool(receipt.passed),
1869
+ "client": client,
1870
+ "client_label": client_meta["label"],
1871
+ "robot": robot,
1872
+ "robot_label": str(robot_meta["label"]),
1873
+ "embodiment": emb_name,
1874
+ "environment": env_key,
1875
+ "environment_label": str(env_meta["label"]),
1876
+ "starting_trust_level": TrustLevel.L0_OBSERVE.name,
1877
+ "airgapped": airgapped,
1878
+ "vault_enabled": vault_enabled,
1879
+ "workspace": str(root),
1880
+ "gate_check_passed": receipt.passed,
1881
+ "files": {
1882
+ "connect_script": str(script_path),
1883
+ "client_config": str(config_path),
1884
+ "manifest": str(manifest_path),
1885
+ "envelope": str(envelope_path),
1886
+ "first_prompt": str(prompt_path),
1887
+ "ros2_bundle": ros2_files,
1888
+ },
1889
+ "safety_boundary": SAFETY_BOUNDARY_STATEMENT,
1890
+ }
1891
+
1892
+ if args.json:
1893
+ print(json.dumps(payload, indent=2))
1894
+ else:
1895
+ print(
1896
+ f"Generated Graft Connect Kit ({client_meta['label']} -> {robot_meta['label']} / {env_meta['label']})"
1897
+ )
1898
+ print(f" Workspace : {root} (Trust: L0_OBSERVE · 0% motion)")
1899
+ print(f" Mode : {'ITAR / Air-Gapped LAN (zero cloud/vault)' if airgapped else ('Cloudflare Fleet Vault opt-in' if vault_enabled else '100% Offline Local Core')}")
1900
+ print(f" Connect script: {script_path} (executable)")
1901
+ print(f" Client config : {config_path}")
1902
+ print(f" ROBOT.md : {manifest_path} (Ed25519 signed · gate={'PASS' if receipt.passed else 'FAIL'})")
1903
+ if ros2_files:
1904
+ print(f" ROS 2 bundle : {root / 'ros2'}")
1905
+ print(f" First prompt : {prompt_path}")
1906
+ print(f" Safety : {SAFETY_BOUNDARY_STATEMENT}")
1907
+ return 0 if receipt.passed else 1
1908
+
1909
+
1910
+ def build_parser() -> argparse.ArgumentParser:
1911
+ parser = argparse.ArgumentParser(
1912
+ prog="robot-gate",
1913
+ description="Deterministic on-robot deployment harness and change-triggered regression gate.",
1914
+ )
1915
+ parser.add_argument("-v", "--version", action="version", version=f"robot-gate {__version__}")
1916
+ sub = parser.add_subparsers(dest="cmd", required=True)
1917
+
1918
+ p_init = sub.add_parser("init", help="Initialize ROBOT.md, gate.yaml, keys, and baseline profile")
1919
+ p_init.add_argument("--dir", default=".", help="Target workspace directory")
1920
+ p_init.add_argument("--preset", choices=sorted(PRESET_EMBODIMENTS), default="so-arm101")
1921
+ p_init.add_argument("--org", default="Graft Robotics")
1922
+ p_init.add_argument("--kid", default="local-dev-1")
1923
+ p_init.add_argument("--sign", action="store_true", help="Generate Ed25519 keypair and sign ROBOT.md")
1924
+ p_init.add_argument("--force", action="store_true", help="Overwrite existing ROBOT.md")
1925
+ p_init.set_defaults(func=_cmd_init)
1926
+
1927
+ p_conn = sub.add_parser(
1928
+ "connect",
1929
+ help="3-click LLM-to-Robot connect kit (connect-graft.sh, AI client config, signed ROBOT.md, ROS 2 bundle, FIRST_PROMPT.md)",
1930
+ )
1931
+ p_conn.add_argument(
1932
+ "--client",
1933
+ choices=list(_CONNECT_CLIENTS.keys()),
1934
+ default="claude",
1935
+ help="Target AI brain / MCP client",
1936
+ )
1937
+ p_conn.add_argument(
1938
+ "--robot",
1939
+ choices=list(_CONNECT_ROBOTS.keys()),
1940
+ default="ur5e",
1941
+ help="Target robot embodiment",
1942
+ )
1943
+ p_conn.add_argument(
1944
+ "--env",
1945
+ choices=list(_CONNECT_ENVIRONMENTS.keys()),
1946
+ default="industrial",
1947
+ help="Target environment & safety guardrail profile",
1948
+ )
1949
+ p_conn.add_argument("--out", default="./graft-connect-cell", help="Output directory for the generated connect kit")
1950
+ p_conn.add_argument("--org", default="Graft Robotics Shop", help="Organization or shop name")
1951
+ p_conn.add_argument("--vault", action="store_true", help="Include opt-in Cloudflare D1 Fleet Vault push step")
1952
+ p_conn.add_argument(
1953
+ "--airgapped",
1954
+ action="store_true",
1955
+ help="ITAR/EAR 100% air-gapped LAN mode (prohibits cloud LLMs & disables Vault)",
1956
+ )
1957
+ p_conn.add_argument("--json", action="store_true", help="Output structured JSON")
1958
+ p_conn.set_defaults(func=_cmd_connect)
1959
+
1960
+ p_onb = sub.add_parser(
1961
+ "onboard",
1962
+ help="Guided offline self-serve cell onboarding wizard (ROBOT.md v1.1 + LLM coach + L0 self-test)",
1963
+ )
1964
+ p_onb.add_argument("--persona", choices=list(PERSONA_CHOICES), default=None, help="Cell persona profile")
1965
+ p_onb.add_argument("--mode", choices=list(MODE_CHOICES), default=None, help="Setup depth: quick or advanced")
1966
+ p_onb.add_argument("--quick", action="store_true", help="Shorthand for --mode quick")
1967
+ p_onb.add_argument("--advanced", action="store_true", help="Shorthand for --mode advanced")
1968
+ p_onb.add_argument("--out", default="./graft-cell", help="Output directory for generated cell folder")
1969
+ p_onb.add_argument("--org", default=None, help="Shop or organization name")
1970
+ p_onb.add_argument("--robot-name", default=None, help="Robot / cell identifier")
1971
+ p_onb.add_argument(
1972
+ "--hand-family",
1973
+ choices=list(HAND_FAMILY_CHOICES),
1974
+ default=None,
1975
+ help="6-family Hand HAL end-effector type",
1976
+ )
1977
+ p_onb.add_argument(
1978
+ "--ai-tier",
1979
+ choices=list(AI_TIER_CHOICES),
1980
+ default=None,
1981
+ help="Preferred AI coach runtime for photo-guided cell setup",
1982
+ )
1983
+ p_onb.add_argument(
1984
+ "--non-interactive",
1985
+ action="store_true",
1986
+ help="Skip interactive prompts and use flags + conservative defaults",
1987
+ )
1988
+ p_onb.add_argument(
1989
+ "--probe-hardware",
1990
+ action="store_true",
1991
+ help="Run strictly read-only device discovery via device_discovery.py (never commands motion)",
1992
+ )
1993
+ p_onb.add_argument(
1994
+ "--with-ros2",
1995
+ action="store_true",
1996
+ help="Also generate ROS 2 pre-flight launch bundle (`ros2/graft_ros2_gate.launch.py` & `ros2/graft_ros2_params.yaml`)",
1997
+ )
1998
+ p_onb.add_argument("--json", action="store_true", help="Output structured onboarding & self-test JSON")
1999
+ p_onb.set_defaults(func=_cmd_onboard)
2000
+
2001
+ p_snap = sub.add_parser("snapshot", help="Capture hardware telemetry snapshot and optional MJCF patch")
2002
+ p_snap.add_argument("--dir", default=".")
2003
+ p_snap.add_argument("--live", action="store_true", help="Read live telemetry from SO-ARM101 serial bus")
2004
+ p_snap.add_argument("--port", default="/dev/ttyACM0")
2005
+ p_snap.add_argument("--baud", type=int, default=1_000_000)
2006
+ p_snap.add_argument("--mjcf-in", help="Optional input MuJoCo MJCF XML to patch with measured dynamics")
2007
+ p_snap.add_argument("--mjcf-out", help="Output path for patched MuJoCo MJCF XML")
2008
+ p_snap.set_defaults(func=_cmd_snapshot)
2009
+
2010
+ p_chk = sub.add_parser("check", help="Run 4-stage deterministic gate and emit signed gate_receipt.json")
2011
+ p_chk.add_argument("--dir", default=".")
2012
+ p_chk.add_argument("--sim-only", action="store_true", help="Skip live bus probe; validate baseline & sim")
2013
+ p_chk.add_argument("--live", action="store_true", help="Probe live hardware bus for calibration drift")
2014
+ p_chk.add_argument("--port", default="/dev/ttyACM0")
2015
+ p_chk.add_argument("--baud", type=int, default=1_000_000)
2016
+ p_chk.add_argument("--json", action="store_true", help="Output full JSON receipt")
2017
+ p_chk.set_defaults(func=_cmd_check)
2018
+
2019
+ p_why = sub.add_parser("why", help="Explain latest gate receipt failures and changed files")
2020
+ p_why.add_argument("--dir", default=".")
2021
+ p_why.set_defaults(func=_cmd_why)
2022
+
2023
+ p_aud = sub.add_parser("verify-audit", help="Verify offline SHA-256 hash-chained audit ledger")
2024
+ p_aud.add_argument("--dir", default=".")
2025
+ p_aud.set_defaults(func=_cmd_verify_audit)
2026
+
2027
+ p_rep = sub.add_parser(
2028
+ "verify-report",
2029
+ help="Verify a signed bounded-embodiment test run directory using bounded_embodiment.report.verify",
2030
+ )
2031
+ p_rep.add_argument("--run-dir", required=True, help="Path to bounded-embodiment run directory")
2032
+ p_rep.add_argument("--key", help="Public Ed25519 PEM or lab keyring JSON")
2033
+ p_rep.add_argument("--json", action="store_true", help="Output verification result as JSON")
2034
+ p_rep.set_defaults(func=_cmd_verify_report)
2035
+
2036
+ p_hook = sub.add_parser("install-hook", help="Install local git pre-commit hook (no cloud CI needed)")
2037
+ p_hook.add_argument("--dir", default=".")
2038
+ p_hook.set_defaults(func=_cmd_install_hook)
2039
+
2040
+ p_sysd = sub.add_parser(
2041
+ "install-systemd",
2042
+ help="Generate a clean parameterized systemd unit file for on-robot deployment",
2043
+ )
2044
+ p_sysd.add_argument("--dir", required=True, help="Target robot-gate workspace directory")
2045
+ p_sysd.add_argument("--port", type=int, default=8785, help="Local listen port (default: 8785)")
2046
+ p_sysd.add_argument("--host", default="127.0.0.1", help="Bind host (default: 127.0.0.1)")
2047
+ p_sysd.add_argument("--user", default=None, help="Optional Linux service user (e.g. robot)")
2048
+ p_sysd.add_argument("--out", default=None, help="Write unit file to PATH (prints to stdout if omitted)")
2049
+ p_sysd.add_argument("--json", action="store_true", help="Output structured JSON")
2050
+ p_sysd.set_defaults(func=_cmd_install_systemd)
2051
+
2052
+ p_srv = sub.add_parser("serve", help="Run offline on-robot FastAPI harness + Mission Control UI")
2053
+ p_srv.add_argument("--dir", default=".")
2054
+ p_srv.add_argument("--host", default="127.0.0.1")
2055
+ p_srv.add_argument("--port", type=int, default=8785)
2056
+ p_srv.set_defaults(func=_cmd_serve)
2057
+
2058
+ p_demo = sub.add_parser(
2059
+ "demo",
2060
+ help="Initialize a signed cell, run gate, and open Mission Control UI (or `--ros2` zero-ROS demo)",
2061
+ )
2062
+ p_demo.add_argument("--dir", default=None, help="Target workspace directory (temp dir when --ros2 omitted)")
2063
+ p_demo.add_argument("--preset", choices=sorted(PRESET_EMBODIMENTS), default="fairino-fr5")
2064
+ p_demo.add_argument("--host", default="127.0.0.1")
2065
+ p_demo.add_argument("--port", type=int, default=8785)
2066
+ p_demo.add_argument(
2067
+ "--ros2",
2068
+ action="store_true",
2069
+ help="Run <10s zero-ROS-install UR5e ROS 2 boundary + compliance pack demo (no server/hardware needed)",
2070
+ )
2071
+ p_demo.add_argument("--json", action="store_true", help="Output structured JSON (for `--ros2` demo)")
2072
+ p_demo.set_defaults(func=_cmd_demo)
2073
+
2074
+ p_mcp = sub.add_parser("mcp", help="Run zero-dependency MCP stdio server for Claude / Gemini / Codex")
2075
+ p_mcp.add_argument("--dir", default=".")
2076
+ p_mcp.set_defaults(func=_cmd_mcp)
2077
+
2078
+ p_mcp_cfg = sub.add_parser("mcp-config", help="Print drop-in MCP JSON config for Claude Code / Antigravity")
2079
+ p_mcp_cfg.add_argument("--dir", default=".")
2080
+ p_mcp_cfg.set_defaults(func=_cmd_mcp_config)
2081
+
2082
+ p_packs = sub.add_parser("packs", help="List or install vertical Job Skill Packs matched to robot + job")
2083
+ packs_sub = p_packs.add_subparsers(dest="packs_cmd", required=True)
2084
+ p_pl = packs_sub.add_parser("list", help="List available Skill Packs")
2085
+ p_pl.add_argument("--robot", default=None, help="Filter by robot (e.g. ur5e, asimov-1, so-arm101)")
2086
+ p_pl.add_argument("--job", default=None, help="Filter by job (e.g. cnc, logistics, kitting, agriculture)")
2087
+ p_pl.add_argument("--json", action="store_true")
2088
+ p_pl.set_defaults(func=_cmd_packs_list)
2089
+
2090
+ p_pi = packs_sub.add_parser("install", help="Scaffold a robot workspace from a vertical Skill Pack")
2091
+ p_pi.add_argument("pack_id", choices=sorted(SKILL_PACK_CATALOG))
2092
+ p_pi.add_argument("--dir", required=True, help="Target workspace directory")
2093
+ p_pi.add_argument("--org", default="Graft Robotics Shop")
2094
+ p_pi.add_argument("--sign", action="store_true", default=True, help="Sign ROBOT.md with Ed25519")
2095
+ p_pi.add_argument("--json", action="store_true")
2096
+ p_pi.set_defaults(func=_cmd_packs_install)
2097
+
2098
+ p_dev = sub.add_parser("devices", help="Discover local and LAN devices (Wi-Fi, webcams, audio, LiDAR, buses)")
2099
+ dev_sub = p_dev.add_subparsers(dest="dev_cmd", required=True)
2100
+ p_ds = dev_sub.add_parser("scan", help="Scan authorized local hardware and LAN mDNS/neighbor devices")
2101
+ p_ds.add_argument("--local-only", action="store_true")
2102
+ p_ds.add_argument("--lan-only", action="store_true")
2103
+ p_ds.add_argument("--json", action="store_true")
2104
+ p_ds.set_defaults(func=_cmd_devices_scan)
2105
+
2106
+ p_set = sub.add_parser(
2107
+ "set",
2108
+ help="Safe L0_OBSERVE rehearsal & Rust graft-core + Hand HAL verification for RoboCurve SET tasks",
2109
+ )
2110
+ p_set.add_argument(
2111
+ "--arm",
2112
+ choices=list(ARM_SETUPS.keys()),
2113
+ default="so_arm101_home",
2114
+ help="Portable arm preset to verify against",
2115
+ )
2116
+ p_set.add_argument(
2117
+ "--task",
2118
+ choices=[*SET_TASK_ORDER, "all"],
2119
+ default="all",
2120
+ help="RoboCurve SET task to verify (or 'all' for all 6 tasks)",
2121
+ )
2122
+ p_set.add_argument(
2123
+ "--export-bundle",
2124
+ default=None,
2125
+ help="Optional file path to export an RFC 8785 SHA-256 signed portable SET bundle JSON",
2126
+ )
2127
+ p_set.add_argument("--json", action="store_true", help="Output structured verification JSON")
2128
+ p_set.set_defaults(func=_cmd_set)
2129
+
2130
+ p_plan = sub.add_parser(
2131
+ "plan",
2132
+ help="Deterministic Shop Swarm & CapEx ROI planner (bottlenecks, utilization, payback, recommendations)",
2133
+ )
2134
+ p_plan.add_argument(
2135
+ "--acquired",
2136
+ default="",
2137
+ help="Comma-separated owned shop assets and/or baseline CNC machines (e.g. haas_vf2,auto_vise)",
2138
+ )
2139
+ p_plan.add_argument(
2140
+ "--budget",
2141
+ type=float,
2142
+ default=None,
2143
+ help="Optional maximum CapEx budget in USD for --recommend filtering",
2144
+ )
2145
+ p_plan.add_argument(
2146
+ "--hourly-rate",
2147
+ type=float,
2148
+ default=110.0,
2149
+ help="CNC shop spindle billing rate in USD/hour (default: 110.0)",
2150
+ )
2151
+ p_plan.add_argument(
2152
+ "--shifts",
2153
+ type=float,
2154
+ default=2.0,
2155
+ help="Target shifts per day, 0 < shifts <= 3.0 (default: 2.0)",
2156
+ )
2157
+ p_plan.add_argument(
2158
+ "--recommend",
2159
+ action="store_true",
2160
+ help="Rank highest-ROI next acquisitions within --budget and detect prerequisite unlocks",
2161
+ )
2162
+ p_plan.add_argument("--json", action="store_true", help="Output structured planner JSON")
2163
+ p_plan.set_defaults(func=_cmd_plan)
2164
+
2165
+ p_ros2 = sub.add_parser(
2166
+ "ros2-bridge",
2167
+ help="Generate ROS 2 launch bundles or run the ROS 2 pre-flight boundary interceptor node",
2168
+ )
2169
+ p_ros2.add_argument("--dir", default=".", help="Workspace containing ROBOT.md, gate.yaml, and .robot-gate/")
2170
+ p_ros2.add_argument(
2171
+ "--generate-bundle",
2172
+ "--emit-launch",
2173
+ dest="generate_bundle",
2174
+ default=None,
2175
+ metavar="OUT_DIR",
2176
+ help="Emit graft_ros2_gate.launch.py, graft_ros2_params.yaml, and README_ROS2.md into OUT_DIR",
2177
+ )
2178
+ p_ros2.add_argument(
2179
+ "--stack",
2180
+ choices=["moveit2", "ur", "fr5", "xarm"],
2181
+ default="moveit2",
2182
+ help="Target ROS 2 robot stack remapping preset (default: moveit2)",
2183
+ )
2184
+ p_ros2.add_argument("--embodiment", default=None, help="Embodiment name declared in ROBOT.md")
2185
+ p_ros2.add_argument("--frame-id", default=None, help="Expected base reference frame_id (bundle default: base_link)")
2186
+ p_ros2.add_argument("--node-name", default="graft_ros2_gate", help="ROS 2 node name (default: graft_ros2_gate)")
2187
+ p_ros2.add_argument(
2188
+ "--params",
2189
+ "--params-file",
2190
+ dest="params",
2191
+ default=None,
2192
+ help="Optional path to graft_ros2_params.yaml",
2193
+ )
2194
+ p_ros2.add_argument(
2195
+ "--mode",
2196
+ choices=["shadow", "enforce", "live"],
2197
+ default="shadow",
2198
+ help="Operational mode: `shadow` (L0_OBSERVE zero physical republish) or `enforce` (Trust Ladder gated)",
2199
+ )
2200
+ p_ros2.add_argument("--json", action="store_true", help="Output structured JSON")
2201
+ p_ros2.set_defaults(func=_cmd_ros2_bridge)
2202
+
2203
+ p_comp = sub.add_parser(
2204
+ "compliance-pack",
2205
+ help="Generate or offline-verify an ISO 10218:2025 & EU 2023/1230 compliance dossier bundle",
2206
+ )
2207
+ p_comp.add_argument("--dir", default=".", help="Target robot-gate workspace directory")
2208
+ p_comp.add_argument(
2209
+ "--out",
2210
+ default=None,
2211
+ help="Output directory or .zip file path (default: <dir>/.robot-gate/compliance)",
2212
+ )
2213
+ p_comp.add_argument(
2214
+ "--zip-name",
2215
+ default=None,
2216
+ help=f"Override ZIP filename (default: {DEFAULT_ZIP_FILENAME})",
2217
+ )
2218
+ p_comp.add_argument("--org", default=None, help="Organization name override for the compliance dossier")
2219
+ p_comp.add_argument("--embodiment", default=None, help="Embodiment name override")
2220
+ p_comp.add_argument(
2221
+ "--verify",
2222
+ default=None,
2223
+ metavar="PATH",
2224
+ help="Offline fail-closed verification of a compliance pack ZIP or directory",
2225
+ )
2226
+ p_comp.add_argument("--json", action="store_true", help="Output structured JSON")
2227
+ p_comp.set_defaults(func=_cmd_compliance_pack)
2228
+
2229
+ p_vault = sub.add_parser(
2230
+ "vault",
2231
+ help="Opt-in Hosted Fleet Receipt Vault sync & multi-robot drift status (zero phone-home when key unset)",
2232
+ )
2233
+ vault_sub = p_vault.add_subparsers(dest="vault_cmd", required=True)
2234
+
2235
+ p_vp = vault_sub.add_parser(
2236
+ "push",
2237
+ help="Push latest signed gate_receipt.json to the Hosted Fleet Vault (opt-in via GRAFT_VAULT_API_KEY)",
2238
+ )
2239
+ p_vp.add_argument("--dir", default=".", help="Workspace directory or gate_receipt.json path")
2240
+ p_vp.add_argument("--robot-id", default=None, help="Override robot identifier")
2241
+ p_vp.add_argument("--cell-name", default=None, help="Optional shop/cell label")
2242
+ p_vp.add_argument("--standard", default=None, help="Compliance standard label (default: ISO-10218:2025,EU-2023/1230)")
2243
+ p_vp.add_argument("--vault-url", default=None, help="Override Vault API URL")
2244
+ p_vp.add_argument("--json", action="store_true", help="Output structured JSON")
2245
+ p_vp.set_defaults(func=_cmd_vault_push)
2246
+
2247
+ p_vs = vault_sub.add_parser(
2248
+ "status",
2249
+ help="Fetch Hosted Fleet Vault summary, recent receipts, and active drift alerts",
2250
+ )
2251
+ p_vs.add_argument("--limit", type=int, default=25, help="Maximum receipts to fetch (1-100, default: 25)")
2252
+ p_vs.add_argument("--robot-id", default=None, help="Filter by robot_id")
2253
+ p_vs.add_argument("--vault-url", default=None, help="Override Vault API URL")
2254
+ p_vs.add_argument("--json", action="store_true", help="Output structured JSON")
2255
+ p_vs.set_defaults(func=_cmd_vault_status)
2256
+
2257
+ return parser
2258
+
2259
+
2260
+ def main(argv: list[str] | None = None) -> int:
2261
+ parser = build_parser()
2262
+ args = parser.parse_args(argv)
2263
+ return int(args.func(args))
2264
+
2265
+
2266
+ if __name__ == "__main__":
2267
+ raise SystemExit(main())