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/__init__.py +14 -0
- robot_gate/audit.py +128 -0
- robot_gate/bounded_bridge.py +719 -0
- robot_gate/cli.py +2267 -0
- robot_gate/compliance_pack.py +1528 -0
- robot_gate/device_discovery.py +412 -0
- robot_gate/fingerprint.py +64 -0
- robot_gate/gate.py +580 -0
- robot_gate/intent.py +560 -0
- robot_gate/manifest.py +535 -0
- robot_gate/mcp_server.py +931 -0
- robot_gate/mechanics.py +2018 -0
- robot_gate/microduck_mapper.py +2615 -0
- robot_gate/onboard.py +1881 -0
- robot_gate/ros2_adapter.py +3232 -0
- robot_gate/semantic_guard.py +523 -0
- robot_gate/server.py +5330 -0
- robot_gate/set_kit.py +1216 -0
- robot_gate/shop_swarm.py +1944 -0
- robot_gate/skillpacks.py +344 -0
- robot_gate/telemetry.py +333 -0
- robot_gate/trust.py +337 -0
- robot_gate/ui.py +2642 -0
- robot_gate/vault_client.py +669 -0
- robot_gate/world_model.py +658 -0
- robot_gate-0.2.0.dist-info/METADATA +195 -0
- robot_gate-0.2.0.dist-info/RECORD +29 -0
- robot_gate-0.2.0.dist-info/WHEEL +4 -0
- robot_gate-0.2.0.dist-info/entry_points.txt +2 -0
robot_gate/intent.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
"""Structured Intent Plans, Swept-Path Sim Dry-Run, Postcondition Verification & Skill Freeze.
|
|
2
|
+
|
|
3
|
+
Closes the LLM -> Accuracy & Intent loop:
|
|
4
|
+
1. LLM submits a structured IntentPlan (goal + multi-step waypoints + sensor postconditions).
|
|
5
|
+
2. `dry_run_plan()` validates EVERY step AND interpolated swept segments between steps against
|
|
6
|
+
ROBOT.md workspace/exclusion bounds, force/velocity limits, tool allowlist, and optional
|
|
7
|
+
MuJoCo 4.0 forward physics on the measured-friction model.
|
|
8
|
+
3. `execute_verified_plan()` enforces that the plan passed dry-run, invokes each bounded step,
|
|
9
|
+
verifies deterministic sensor postconditions (gripper width, load, TCP accuracy, vision),
|
|
10
|
+
auto-retries up to `max_retries`, and returns actionable recovery hints instead of
|
|
11
|
+
hallucinated success.
|
|
12
|
+
4. `freeze_verified_skill()` saves a 100%-verified plan to `skills/<name>.yaml` for fast,
|
|
13
|
+
repeatable, zero-LLM-jitter production execution.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import time
|
|
22
|
+
from dataclasses import asdict, dataclass, field
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, Callable
|
|
25
|
+
|
|
26
|
+
import yaml
|
|
27
|
+
|
|
28
|
+
from .audit import append_audit_record
|
|
29
|
+
from .gate import GateConfig, _run_optional_mujoco_smoke
|
|
30
|
+
from .manifest import EmbodimentSpec, load_manifest
|
|
31
|
+
from .server import RobotGateRuntime
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class Postcondition:
|
|
36
|
+
"""Deterministic post-step sensor verification contract."""
|
|
37
|
+
|
|
38
|
+
gripper_width_mm: tuple[float, float] | None = None
|
|
39
|
+
min_load_ratio: float | None = None
|
|
40
|
+
tcp_tolerance_mm: float | None = None
|
|
41
|
+
max_contact_force_n: float | None = None
|
|
42
|
+
camera_object_detected: str | None = None
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def from_dict(cls, d: dict[str, Any] | None) -> Postcondition | None:
|
|
46
|
+
if not d:
|
|
47
|
+
return None
|
|
48
|
+
gw = d.get("gripper_width_mm")
|
|
49
|
+
return cls(
|
|
50
|
+
gripper_width_mm=(float(gw[0]), float(gw[1])) if gw is not None else None,
|
|
51
|
+
min_load_ratio=float(d["min_load_ratio"]) if d.get("min_load_ratio") is not None else None,
|
|
52
|
+
tcp_tolerance_mm=float(d["tcp_tolerance_mm"]) if d.get("tcp_tolerance_mm") is not None else None,
|
|
53
|
+
max_contact_force_n=(
|
|
54
|
+
float(d["max_contact_force_n"]) if d.get("max_contact_force_n") is not None else None
|
|
55
|
+
),
|
|
56
|
+
camera_object_detected=(
|
|
57
|
+
str(d["camera_object_detected"]) if d.get("camera_object_detected") else None
|
|
58
|
+
),
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class PlanStep:
|
|
64
|
+
name: str
|
|
65
|
+
tool: str
|
|
66
|
+
target_xyz_m: tuple[float, float, float]
|
|
67
|
+
force_n: float = 0.0
|
|
68
|
+
velocity_mps: float = 0.15
|
|
69
|
+
postcondition: Postcondition | None = None
|
|
70
|
+
max_retries: int = 1
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def from_dict(cls, d: dict[str, Any]) -> PlanStep:
|
|
74
|
+
xyz = d["target_xyz_m"]
|
|
75
|
+
if not isinstance(xyz, (list, tuple)) or len(xyz) != 3:
|
|
76
|
+
raise ValueError(f"Step '{d.get('name', '?')}' target_xyz_m must be [x, y, z]")
|
|
77
|
+
return cls(
|
|
78
|
+
name=str(d.get("name", "step")),
|
|
79
|
+
tool=str(d.get("tool", "arm.move_bounded")),
|
|
80
|
+
target_xyz_m=(float(xyz[0]), float(xyz[1]), float(xyz[2])),
|
|
81
|
+
force_n=float(d.get("force_n", 0.0)),
|
|
82
|
+
velocity_mps=float(d.get("velocity_mps", 0.15)),
|
|
83
|
+
postcondition=Postcondition.from_dict(d.get("postcondition")),
|
|
84
|
+
max_retries=max(0, int(d.get("max_retries", 1))),
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class IntentPlan:
|
|
90
|
+
goal: str
|
|
91
|
+
steps: list[PlanStep]
|
|
92
|
+
|
|
93
|
+
def plan_hash(self) -> str:
|
|
94
|
+
payload = {
|
|
95
|
+
"goal": self.goal,
|
|
96
|
+
"steps": [asdict(s) for s in self.steps],
|
|
97
|
+
}
|
|
98
|
+
raw = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
|
99
|
+
return hashlib.sha256(raw).hexdigest()
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def from_dict(cls, d: dict[str, Any]) -> IntentPlan:
|
|
103
|
+
raw_steps = d.get("steps")
|
|
104
|
+
if not isinstance(raw_steps, list) or not raw_steps:
|
|
105
|
+
raise ValueError("IntentPlan must contain a non-empty 'steps' list")
|
|
106
|
+
return cls(
|
|
107
|
+
goal=str(d.get("goal", "unnamed_intent")),
|
|
108
|
+
steps=[PlanStep.from_dict(s) for s in raw_steps],
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@dataclass(frozen=True)
|
|
113
|
+
class DryRunResult:
|
|
114
|
+
approved: bool
|
|
115
|
+
plan_hash: str
|
|
116
|
+
embodiment: str
|
|
117
|
+
checked_steps: int
|
|
118
|
+
swept_samples_checked: int
|
|
119
|
+
failures: list[str] = field(default_factory=list)
|
|
120
|
+
min_cbf_margin_m: float = 0.0
|
|
121
|
+
mujoco_status: str = "not_configured"
|
|
122
|
+
ts_utc: str = ""
|
|
123
|
+
|
|
124
|
+
def to_dict(self) -> dict[str, Any]:
|
|
125
|
+
return asdict(self)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(frozen=True)
|
|
129
|
+
class PostconditionResult:
|
|
130
|
+
passed: bool
|
|
131
|
+
code: str
|
|
132
|
+
checks: list[str] = field(default_factory=list)
|
|
133
|
+
failures: list[str] = field(default_factory=list)
|
|
134
|
+
recovery_hint: str = ""
|
|
135
|
+
|
|
136
|
+
def to_dict(self) -> dict[str, Any]:
|
|
137
|
+
return asdict(self)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass(frozen=True)
|
|
141
|
+
class StepExecutionRecord:
|
|
142
|
+
step_name: str
|
|
143
|
+
attempts: int
|
|
144
|
+
decision: str
|
|
145
|
+
postcondition_passed: bool
|
|
146
|
+
postcondition_code: str
|
|
147
|
+
recovery_hint: str = ""
|
|
148
|
+
failures: list[str] = field(default_factory=list)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass(frozen=True)
|
|
152
|
+
class PlanExecutionResult:
|
|
153
|
+
succeeded: bool
|
|
154
|
+
plan_hash: str
|
|
155
|
+
goal: str
|
|
156
|
+
completed_steps: int
|
|
157
|
+
total_steps: int
|
|
158
|
+
step_records: list[StepExecutionRecord] = field(default_factory=list)
|
|
159
|
+
error: str | None = None
|
|
160
|
+
recovery_hint: str = ""
|
|
161
|
+
|
|
162
|
+
def to_dict(self) -> dict[str, Any]:
|
|
163
|
+
return {
|
|
164
|
+
"succeeded": self.succeeded,
|
|
165
|
+
"plan_hash": self.plan_hash,
|
|
166
|
+
"goal": self.goal,
|
|
167
|
+
"completed_steps": self.completed_steps,
|
|
168
|
+
"total_steps": self.total_steps,
|
|
169
|
+
"step_records": [asdict(r) for r in self.step_records],
|
|
170
|
+
"error": self.error,
|
|
171
|
+
"recovery_hint": self.recovery_hint,
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _interpolate_segment(
|
|
176
|
+
p0: tuple[float, float, float],
|
|
177
|
+
p1: tuple[float, float, float],
|
|
178
|
+
samples: int = 10,
|
|
179
|
+
) -> list[tuple[float, float, float]]:
|
|
180
|
+
pts: list[tuple[float, float, float]] = []
|
|
181
|
+
for i in range(1, samples):
|
|
182
|
+
t = i / samples
|
|
183
|
+
pts.append(
|
|
184
|
+
(
|
|
185
|
+
p0[0] + t * (p1[0] - p0[0]),
|
|
186
|
+
p0[1] + t * (p1[1] - p0[1]),
|
|
187
|
+
p0[2] + t * (p1[2] - p0[2]),
|
|
188
|
+
)
|
|
189
|
+
)
|
|
190
|
+
return pts
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def dry_run_plan(
|
|
194
|
+
workspace_root: Path,
|
|
195
|
+
config: GateConfig,
|
|
196
|
+
plan: IntentPlan,
|
|
197
|
+
*,
|
|
198
|
+
swept_samples: int = 10,
|
|
199
|
+
) -> DryRunResult:
|
|
200
|
+
"""Validate every waypoint + swept segments + optional MuJoCo 4.0 physics before any motion."""
|
|
201
|
+
root = workspace_root.resolve()
|
|
202
|
+
manifest = load_manifest(root / config.manifest_path)
|
|
203
|
+
emb: EmbodimentSpec = manifest.get_embodiment(config.embodiment)
|
|
204
|
+
|
|
205
|
+
failures: list[str] = []
|
|
206
|
+
min_h = float("inf")
|
|
207
|
+
swept_count = 0
|
|
208
|
+
|
|
209
|
+
prev_xyz: tuple[float, float, float] | None = None
|
|
210
|
+
for idx, step in enumerate(plan.steps):
|
|
211
|
+
ok, h_val, reason = emb.evaluate_point(
|
|
212
|
+
step.target_xyz_m,
|
|
213
|
+
force_n=step.force_n,
|
|
214
|
+
velocity_mps=step.velocity_mps,
|
|
215
|
+
tool_name=step.tool,
|
|
216
|
+
)
|
|
217
|
+
min_h = min(min_h, h_val)
|
|
218
|
+
if not ok:
|
|
219
|
+
failures.append(f"step[{idx}] '{step.name}' blocked: {reason}")
|
|
220
|
+
|
|
221
|
+
# Check swept straight-line path from previous step to catch mid-flight exclusion collisions
|
|
222
|
+
if prev_xyz is not None:
|
|
223
|
+
for s_idx, mid in enumerate(_interpolate_segment(prev_xyz, step.target_xyz_m, swept_samples), start=1):
|
|
224
|
+
swept_count += 1
|
|
225
|
+
m_ok, m_h, m_reason = emb.evaluate_point(
|
|
226
|
+
mid,
|
|
227
|
+
force_n=step.force_n,
|
|
228
|
+
velocity_mps=step.velocity_mps,
|
|
229
|
+
tool_name=step.tool,
|
|
230
|
+
)
|
|
231
|
+
min_h = min(min_h, m_h)
|
|
232
|
+
if not m_ok:
|
|
233
|
+
failures.append(
|
|
234
|
+
f"swept path step[{idx - 1}]->step[{idx}] ('{step.name}', sample {s_idx}/{swept_samples}) collision: {m_reason}"
|
|
235
|
+
)
|
|
236
|
+
break
|
|
237
|
+
prev_xyz = step.target_xyz_m
|
|
238
|
+
|
|
239
|
+
mj_status = "not_configured"
|
|
240
|
+
if config.mjcf_path:
|
|
241
|
+
mjcf_full = root / config.mjcf_path
|
|
242
|
+
if not mjcf_full.exists():
|
|
243
|
+
mj_status = f"missing:{config.mjcf_path}"
|
|
244
|
+
failures.append(f"configured mjcf_path missing: {config.mjcf_path}")
|
|
245
|
+
else:
|
|
246
|
+
mj_ok, mj_msg = _run_optional_mujoco_smoke(mjcf_full)
|
|
247
|
+
mj_status = mj_msg
|
|
248
|
+
if not mj_ok:
|
|
249
|
+
failures.append(mj_msg)
|
|
250
|
+
|
|
251
|
+
approved = len(failures) == 0
|
|
252
|
+
res = DryRunResult(
|
|
253
|
+
approved=approved,
|
|
254
|
+
plan_hash=plan.plan_hash(),
|
|
255
|
+
embodiment=emb.name,
|
|
256
|
+
checked_steps=len(plan.steps),
|
|
257
|
+
swept_samples_checked=swept_count,
|
|
258
|
+
failures=failures,
|
|
259
|
+
min_cbf_margin_m=round(0.0 if min_h == float("inf") else min_h, 4),
|
|
260
|
+
mujoco_status=mj_status,
|
|
261
|
+
ts_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
append_audit_record(
|
|
265
|
+
root / config.audit_path,
|
|
266
|
+
event="intent.dry_run",
|
|
267
|
+
decision="ALLOW" if approved else "DENY",
|
|
268
|
+
details={
|
|
269
|
+
"goal": plan.goal,
|
|
270
|
+
"plan_hash": res.plan_hash[:16],
|
|
271
|
+
"steps": len(plan.steps),
|
|
272
|
+
"swept_samples": swept_count,
|
|
273
|
+
"failures": failures[:5],
|
|
274
|
+
},
|
|
275
|
+
)
|
|
276
|
+
return res
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def verify_postcondition(
|
|
280
|
+
postcondition: Postcondition | None,
|
|
281
|
+
target_xyz_m: tuple[float, float, float],
|
|
282
|
+
observed: dict[str, Any],
|
|
283
|
+
) -> PostconditionResult:
|
|
284
|
+
"""Deterministically verify real post-step sensor readings against expected task intent."""
|
|
285
|
+
if postcondition is None:
|
|
286
|
+
return PostconditionResult(passed=True, code="NO_POSTCONDITION", checks=["none_required"])
|
|
287
|
+
|
|
288
|
+
checks: list[str] = []
|
|
289
|
+
failures: list[str] = []
|
|
290
|
+
code = "VERIFIED"
|
|
291
|
+
hints: list[str] = []
|
|
292
|
+
|
|
293
|
+
if postcondition.gripper_width_mm is not None:
|
|
294
|
+
lo, hi = postcondition.gripper_width_mm
|
|
295
|
+
gw = observed.get("gripper_width_mm")
|
|
296
|
+
if gw is None:
|
|
297
|
+
failures.append("missing observed gripper_width_mm")
|
|
298
|
+
code = "MISSING_TELEMETRY"
|
|
299
|
+
hints.append("Ensure gripper encoder telemetry is enabled before verifying grasps.")
|
|
300
|
+
else:
|
|
301
|
+
gw_f = float(gw)
|
|
302
|
+
checks.append(f"gripper_width={gw_f:.1f}mm in [{lo:.1f}, {hi:.1f}]mm")
|
|
303
|
+
if gw_f < lo:
|
|
304
|
+
failures.append(f"EMPTY_GRASP: gripper closed to {gw_f:.1f}mm (< min part width {lo:.1f}mm)")
|
|
305
|
+
code = "EMPTY_GRASP"
|
|
306
|
+
hints.append(
|
|
307
|
+
f"Gripper closed on empty air ({gw_f:.1f}mm < {lo:.1f}mm). Re-check camera pose, lower approach Z by 3mm, and re-dry-run."
|
|
308
|
+
)
|
|
309
|
+
elif gw_f > hi:
|
|
310
|
+
failures.append(f"OVERSIZE_OBSTRUCTION: gripper stopped at {gw_f:.1f}mm (> max {hi:.1f}mm)")
|
|
311
|
+
code = "OBSTRUCTION"
|
|
312
|
+
hints.append(
|
|
313
|
+
f"Gripper hit an obstruction ({gw_f:.1f}mm > {hi:.1f}mm). Retract +20mm Z and inspect alignment."
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
if postcondition.min_load_ratio is not None:
|
|
317
|
+
lr = observed.get("load_ratio")
|
|
318
|
+
if lr is None:
|
|
319
|
+
failures.append("missing observed load_ratio")
|
|
320
|
+
code = "MISSING_TELEMETRY" if code == "VERIFIED" else code
|
|
321
|
+
else:
|
|
322
|
+
lr_f = float(lr)
|
|
323
|
+
checks.append(f"load_ratio={lr_f:.3f} >= {postcondition.min_load_ratio:.3f}")
|
|
324
|
+
if lr_f < postcondition.min_load_ratio:
|
|
325
|
+
failures.append(
|
|
326
|
+
f"LOW_LOAD: actuator load {lr_f:.3f} < min expected {postcondition.min_load_ratio:.3f} (part likely not held)"
|
|
327
|
+
)
|
|
328
|
+
code = "EMPTY_GRASP" if code == "VERIFIED" else code
|
|
329
|
+
hints.append("Servo load did not rise after grasp — part may have slipped or been missed.")
|
|
330
|
+
|
|
331
|
+
if postcondition.tcp_tolerance_mm is not None:
|
|
332
|
+
obs_tcp = observed.get("tcp_mm")
|
|
333
|
+
if obs_tcp is None or len(obs_tcp) != 3:
|
|
334
|
+
failures.append("missing observed tcp_mm")
|
|
335
|
+
code = "MISSING_TELEMETRY" if code == "VERIFIED" else code
|
|
336
|
+
else:
|
|
337
|
+
tgt_mm = (target_xyz_m[0] * 1000.0, target_xyz_m[1] * 1000.0, target_xyz_m[2] * 1000.0)
|
|
338
|
+
dx = float(obs_tcp[0]) - tgt_mm[0]
|
|
339
|
+
dy = float(obs_tcp[1]) - tgt_mm[1]
|
|
340
|
+
dz = float(obs_tcp[2]) - tgt_mm[2]
|
|
341
|
+
err_mm = math.sqrt(dx * dx + dy * dy + dz * dz)
|
|
342
|
+
checks.append(f"tcp_err={err_mm:.2f}mm <= {postcondition.tcp_tolerance_mm:.2f}mm")
|
|
343
|
+
if err_mm > postcondition.tcp_tolerance_mm:
|
|
344
|
+
failures.append(
|
|
345
|
+
f"TCP_MISMATCH: error {err_mm:.2f}mm > limit {postcondition.tcp_tolerance_mm:.2f}mm (delta=[{dx:+.1f}, {dy:+.1f}, {dz:+.1f}]mm)"
|
|
346
|
+
)
|
|
347
|
+
code = "TCP_MISMATCH" if code == "VERIFIED" else code
|
|
348
|
+
hints.append(
|
|
349
|
+
f"Arm missed target by {err_mm:.2f}mm (dx={dx:+.1f}, dy={dy:+.1f}, dz={dz:+.1f}mm). Run 60s calibration check or compensate offset."
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
if postcondition.max_contact_force_n is not None:
|
|
353
|
+
obs_f = observed.get("contact_force_n")
|
|
354
|
+
if obs_f is not None:
|
|
355
|
+
f_val = float(obs_f)
|
|
356
|
+
checks.append(f"contact_force={f_val:.1f}N <= {postcondition.max_contact_force_n:.1f}N")
|
|
357
|
+
if f_val > postcondition.max_contact_force_n:
|
|
358
|
+
failures.append(
|
|
359
|
+
f"FORCE_EXCEEDED: contact force {f_val:.1f}N > {postcondition.max_contact_force_n:.1f}N"
|
|
360
|
+
)
|
|
361
|
+
code = "FORCE_EXCEEDED" if code == "VERIFIED" else code
|
|
362
|
+
hints.append("Excessive contact force detected — back off along approach axis and reduce velocity.")
|
|
363
|
+
|
|
364
|
+
if postcondition.camera_object_detected is not None:
|
|
365
|
+
detected = observed.get("detected_objects") or []
|
|
366
|
+
checks.append(f"vision_contains('{postcondition.camera_object_detected}')")
|
|
367
|
+
if postcondition.camera_object_detected not in detected:
|
|
368
|
+
failures.append(
|
|
369
|
+
f"VISION_UNCONFIRMED: '{postcondition.camera_object_detected}' not seen in camera detections {detected}"
|
|
370
|
+
)
|
|
371
|
+
code = "VISION_UNCONFIRMED" if code == "VERIFIED" else code
|
|
372
|
+
hints.append(
|
|
373
|
+
f"Camera did not confirm '{postcondition.camera_object_detected}'. Re-acquire scene pose before continuing."
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
passed = len(failures) == 0
|
|
377
|
+
return PostconditionResult(
|
|
378
|
+
passed=passed,
|
|
379
|
+
code="VERIFIED" if passed else code,
|
|
380
|
+
checks=checks,
|
|
381
|
+
failures=failures,
|
|
382
|
+
recovery_hint=" ".join(hints),
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
SensorObserver = Callable[[PlanStep, int], dict[str, Any]]
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _default_sim_observer(step: PlanStep, _attempt: int) -> dict[str, Any]:
|
|
390
|
+
"""Synthetic nominal sensor reading used when running in SIM mode without live sensors."""
|
|
391
|
+
obs: dict[str, Any] = {
|
|
392
|
+
"tcp_mm": [
|
|
393
|
+
round(step.target_xyz_m[0] * 1000.0, 2),
|
|
394
|
+
round(step.target_xyz_m[1] * 1000.0, 2),
|
|
395
|
+
round(step.target_xyz_m[2] * 1000.0, 2),
|
|
396
|
+
],
|
|
397
|
+
"contact_force_n": step.force_n,
|
|
398
|
+
"load_ratio": 0.18,
|
|
399
|
+
}
|
|
400
|
+
if step.postcondition is not None:
|
|
401
|
+
if step.postcondition.gripper_width_mm is not None:
|
|
402
|
+
lo, hi = step.postcondition.gripper_width_mm
|
|
403
|
+
obs["gripper_width_mm"] = round(0.5 * (lo + hi), 2)
|
|
404
|
+
if step.postcondition.min_load_ratio is not None:
|
|
405
|
+
obs["load_ratio"] = round(max(0.18, step.postcondition.min_load_ratio + 0.05), 3)
|
|
406
|
+
if step.postcondition.camera_object_detected is not None:
|
|
407
|
+
obs["detected_objects"] = [step.postcondition.camera_object_detected]
|
|
408
|
+
return obs
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def execute_verified_plan(
|
|
412
|
+
runtime: RobotGateRuntime,
|
|
413
|
+
plan: IntentPlan,
|
|
414
|
+
*,
|
|
415
|
+
dry_run: DryRunResult,
|
|
416
|
+
sensor_observer: SensorObserver | None = None,
|
|
417
|
+
) -> PlanExecutionResult:
|
|
418
|
+
"""Execute a dry-run-approved plan step-by-step with postcondition checks & retries."""
|
|
419
|
+
p_hash = plan.plan_hash()
|
|
420
|
+
audit_path = runtime.root / runtime.config.audit_path
|
|
421
|
+
|
|
422
|
+
if not dry_run.approved or dry_run.plan_hash != p_hash:
|
|
423
|
+
err = "plan was not dry-run approved or changed after dry-run; call dry_run_plan first"
|
|
424
|
+
append_audit_record(
|
|
425
|
+
audit_path,
|
|
426
|
+
event="intent.execute",
|
|
427
|
+
decision="DENY",
|
|
428
|
+
details={"goal": plan.goal, "plan_hash": p_hash[:16], "reason": err},
|
|
429
|
+
)
|
|
430
|
+
return PlanExecutionResult(
|
|
431
|
+
succeeded=False,
|
|
432
|
+
plan_hash=p_hash,
|
|
433
|
+
goal=plan.goal,
|
|
434
|
+
completed_steps=0,
|
|
435
|
+
total_steps=len(plan.steps),
|
|
436
|
+
error=err,
|
|
437
|
+
recovery_hint="Run robot_dry_run_plan on the current plan and resolve any collisions first.",
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
observer = sensor_observer or _default_sim_observer
|
|
441
|
+
records: list[StepExecutionRecord] = []
|
|
442
|
+
completed = 0
|
|
443
|
+
|
|
444
|
+
for step in plan.steps:
|
|
445
|
+
attempts = 0
|
|
446
|
+
step_ok = False
|
|
447
|
+
last_decision = "DENY"
|
|
448
|
+
last_post = PostconditionResult(passed=False, code="NOT_RUN")
|
|
449
|
+
|
|
450
|
+
while attempts <= step.max_retries:
|
|
451
|
+
attempts += 1
|
|
452
|
+
inv = runtime.invoke(
|
|
453
|
+
tool=step.tool,
|
|
454
|
+
target_xyz_m=step.target_xyz_m,
|
|
455
|
+
force_n=step.force_n,
|
|
456
|
+
velocity_mps=step.velocity_mps,
|
|
457
|
+
)
|
|
458
|
+
last_decision = str(inv.get("decision", "DENY"))
|
|
459
|
+
if last_decision != "ALLOW":
|
|
460
|
+
last_post = PostconditionResult(
|
|
461
|
+
passed=False,
|
|
462
|
+
code="GATE_DENIED",
|
|
463
|
+
failures=[str(inv.get("reason", "denied by gateway"))],
|
|
464
|
+
recovery_hint="Action blocked by deterministic gate; re-check latch/estop/bounds.",
|
|
465
|
+
)
|
|
466
|
+
break # Never retry a hard safety gate refusal
|
|
467
|
+
|
|
468
|
+
obs = observer(step, attempts)
|
|
469
|
+
last_post = verify_postcondition(step.postcondition, step.target_xyz_m, obs)
|
|
470
|
+
append_audit_record(
|
|
471
|
+
audit_path,
|
|
472
|
+
event="intent.postcondition",
|
|
473
|
+
decision="ALLOW" if last_post.passed else "DENY",
|
|
474
|
+
details={
|
|
475
|
+
"step": step.name,
|
|
476
|
+
"attempt": attempts,
|
|
477
|
+
"code": last_post.code,
|
|
478
|
+
"failures": last_post.failures,
|
|
479
|
+
},
|
|
480
|
+
)
|
|
481
|
+
if last_post.passed:
|
|
482
|
+
step_ok = True
|
|
483
|
+
break
|
|
484
|
+
|
|
485
|
+
records.append(
|
|
486
|
+
StepExecutionRecord(
|
|
487
|
+
step_name=step.name,
|
|
488
|
+
attempts=attempts,
|
|
489
|
+
decision=last_decision,
|
|
490
|
+
postcondition_passed=last_post.passed,
|
|
491
|
+
postcondition_code=last_post.code,
|
|
492
|
+
recovery_hint=last_post.recovery_hint,
|
|
493
|
+
failures=last_post.failures,
|
|
494
|
+
)
|
|
495
|
+
)
|
|
496
|
+
if not step_ok:
|
|
497
|
+
return PlanExecutionResult(
|
|
498
|
+
succeeded=False,
|
|
499
|
+
plan_hash=p_hash,
|
|
500
|
+
goal=plan.goal,
|
|
501
|
+
completed_steps=completed,
|
|
502
|
+
total_steps=len(plan.steps),
|
|
503
|
+
step_records=records,
|
|
504
|
+
error=f"Step '{step.name}' failed ({last_post.code}) after {attempts} attempt(s)",
|
|
505
|
+
recovery_hint=last_post.recovery_hint,
|
|
506
|
+
)
|
|
507
|
+
completed += 1
|
|
508
|
+
|
|
509
|
+
append_audit_record(
|
|
510
|
+
audit_path,
|
|
511
|
+
event="intent.complete",
|
|
512
|
+
decision="ALLOW",
|
|
513
|
+
details={"goal": plan.goal, "plan_hash": p_hash[:16], "steps": completed},
|
|
514
|
+
)
|
|
515
|
+
return PlanExecutionResult(
|
|
516
|
+
succeeded=True,
|
|
517
|
+
plan_hash=p_hash,
|
|
518
|
+
goal=plan.goal,
|
|
519
|
+
completed_steps=completed,
|
|
520
|
+
total_steps=len(plan.steps),
|
|
521
|
+
step_records=records,
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def freeze_verified_skill(
|
|
526
|
+
workspace_root: Path,
|
|
527
|
+
config: GateConfig,
|
|
528
|
+
plan: IntentPlan,
|
|
529
|
+
exec_result: PlanExecutionResult,
|
|
530
|
+
skill_name: str,
|
|
531
|
+
) -> Path:
|
|
532
|
+
"""Freeze a 100%-verified plan into `skills/<skill_name>.yaml` for repeatable playback."""
|
|
533
|
+
if not exec_result.succeeded or exec_result.plan_hash != plan.plan_hash():
|
|
534
|
+
raise ValueError("Cannot freeze skill: execution did not succeed or plan_hash does not match")
|
|
535
|
+
safe_name = "".join(c if (c.isalnum() or c in "-_") else "_" for c in skill_name.strip())
|
|
536
|
+
if not safe_name:
|
|
537
|
+
raise ValueError("skill_name must contain alphanumeric characters")
|
|
538
|
+
|
|
539
|
+
root = workspace_root.resolve()
|
|
540
|
+
skills_dir = root / "skills"
|
|
541
|
+
skills_dir.mkdir(parents=True, exist_ok=True)
|
|
542
|
+
out_path = skills_dir / f"{safe_name}.yaml"
|
|
543
|
+
|
|
544
|
+
doc = {
|
|
545
|
+
"schema_version": "1.0",
|
|
546
|
+
"skill_name": safe_name,
|
|
547
|
+
"goal": plan.goal,
|
|
548
|
+
"embodiment": config.embodiment,
|
|
549
|
+
"verified_plan_hash": plan.plan_hash(),
|
|
550
|
+
"frozen_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
551
|
+
"steps": [asdict(s) for s in plan.steps],
|
|
552
|
+
}
|
|
553
|
+
out_path.write_text(yaml.safe_dump(doc, sort_keys=False), encoding="utf-8")
|
|
554
|
+
append_audit_record(
|
|
555
|
+
root / config.audit_path,
|
|
556
|
+
event="skill.frozen",
|
|
557
|
+
decision="ALLOW",
|
|
558
|
+
details={"skill": safe_name, "plan_hash": plan.plan_hash()[:16], "path": str(out_path.name)},
|
|
559
|
+
)
|
|
560
|
+
return out_path
|