File size: 31,055 Bytes
8ca7ba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
"""Export RoboHouseGen outputs through the RPArena generator interface v1."""

from __future__ import annotations

import hashlib
import json
import math
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Annotated, Any, Literal

from pydantic import BaseModel, ConfigDict, Field, model_validator

from packages.benchmark.packager import BenchmarkPackager
from packages.core.files import atomic_write_text
from packages.scene_generation.pick_move_place import PickMovePlaceTask
from packages.schemas.models import (
    DifficultyVector,
    PredicateSpec,
    SceneLayerPlan,
    SceneManifest,
    SkillInvocation,
    TaskEntity,
    TaskPlan,
    TaskSpec,
)
from packages.version import API_COMPAT_VERSION

INTERFACE_SCHEMA_VERSION = "rparena.generator-interface/1.0"
INTERFACE_MANIFEST = "manifests/rparena_interface.json"
ADAPTER_VERSION = "robothousegen.asset-first-pick-move-place/1.0"
EXPORT_RESULT_SCHEMA_VERSION = "robothousegen.rparena-export-result/1.0"
USD_INSPECTION_SCHEMA_VERSION = "robothousegen.rparena-usd-inspection/1.0"

_SHA256 = re.compile(r"^[0-9a-f]{64}$")
_NonEmptyString = Annotated[str, Field(min_length=1)]


class _StrictModel(BaseModel):
    model_config = ConfigDict(extra="forbid")


class RPArenaProducer(_StrictModel):
    name: str = Field(min_length=1)
    version: str = Field(min_length=1)
    adapter: str = Field(min_length=1)


class RPArenaBundlePaths(_StrictModel):
    root_usd: Literal["root.usda"]
    scene_usd: Literal["scenesmith/scene.usdc"]
    scene_manifest: Literal["manifests/scene.json"]
    task_manifest: Literal["manifests/task.json"]
    episode_manifest: Literal["manifests/episode.json"]
    evaluator_manifest: Literal["manifests/evaluator.json"]
    robot_manifest: Literal["manifests/robot.json"]


class RPArenaContract(_StrictModel):
    bundle_type: Literal["single_episode"]
    task_type: str = Field(pattern=r"^[a-z][a-z0-9_]*$")
    evaluator: Literal["predicate_graph_v1"]
    entity_binding: Literal["absolute_world_prim_paths"]
    physics_authoring: Literal["consumer"]
    robot_embodiment: Literal["consumer"]
    coordinate_system: Literal["usd_z_up_right_handed_metres"]
    checksums: Literal["sha256_complete"]


class RPArenaIdentity(_StrictModel):
    scene_id: str = Field(min_length=1)
    task_id: str = Field(min_length=1)
    episode_id: str = Field(min_length=1)
    entity_ids: list[_NonEmptyString] = Field(
        min_length=1,
        json_schema_extra={"uniqueItems": True},
    )
    manipulated_entity_ids: list[_NonEmptyString] = Field(
        min_length=1,
        json_schema_extra={"uniqueItems": True},
    )

    @model_validator(mode="after")
    def validate_entity_ids(self) -> RPArenaIdentity:
        if self.entity_ids != sorted(set(self.entity_ids)):
            raise ValueError("entity_ids must be sorted and unique")
        if self.manipulated_entity_ids != sorted(set(self.manipulated_entity_ids)):
            raise ValueError("manipulated_entity_ids must be sorted and unique")
        if not set(self.manipulated_entity_ids).issubset(self.entity_ids):
            raise ValueError("manipulated_entity_ids must be scene entities")
        return self


class RPArenaSource(_StrictModel):
    kind: str = Field(min_length=1)
    source_task_id: str = Field(min_length=1)
    source_digest: str = Field(pattern=r"^[0-9a-f]{64}$")


class RPArenaInterfaceV1(_StrictModel):
    model_config = ConfigDict(
        extra="forbid",
        json_schema_extra={"$schema": "https://json-schema.org/draft/2020-12/schema"},
    )

    schema_version: Literal["rparena.generator-interface/1.0"]
    producer: RPArenaProducer
    bundle: RPArenaBundlePaths
    contract: RPArenaContract
    identity: RPArenaIdentity
    source: RPArenaSource


class RPArenaExportResult(_StrictModel):
    schema_version: Literal["robothousegen.rparena-export-result/1.0"] = (
        "robothousegen.rparena-export-result/1.0"
    )
    bundle_root: Path
    interface_manifest: Path
    scene_id: str
    task_id: str
    episode_id: str
    source_digest: str
    scene_usd_sha256: str
    entity_prim_paths: dict[str, str]
    checksummed_file_count: int


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _canonical_sha256(value: object) -> str:
    payload = json.dumps(
        value,
        ensure_ascii=False,
        sort_keys=True,
        separators=(",", ":"),
        allow_nan=False,
    ).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def _reject_constant(value: str) -> None:
    raise ValueError(f"JSON contains non-finite value {value!r}")


def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
    value: dict[str, Any] = {}
    for key, item in pairs:
        if key in value:
            raise ValueError(f"JSON contains duplicate key {key!r}")
        value[key] = item
    return value


def _regular_file(path: Path, *, label: str) -> Path:
    unresolved = path.expanduser()
    if unresolved.is_symlink():
        raise ValueError(f"{label} must be a non-symlink regular file: {path}")
    resolved = unresolved.resolve(strict=True)
    if not resolved.is_file():
        raise ValueError(f"{label} must be a non-symlink regular file: {path}")
    return resolved


def _executable_file(path: Path, *, label: str) -> Path:
    executable = path.expanduser().absolute()
    if not executable.is_file() or not os.access(executable, os.X_OK):
        raise ValueError(f"{label} must resolve to an executable file: {path}")
    return executable


def _source_directory(path: str | Path) -> Path:
    unresolved = Path(path).expanduser()
    if unresolved.is_symlink():
        raise ValueError(f"source must be a non-symlink directory: {path}")
    source = unresolved.resolve(strict=True)
    if not source.is_dir():
        raise ValueError(f"source must be a non-symlink directory: {path}")
    return source


def _json_object(path: Path, *, label: str) -> dict[str, Any]:
    source = _regular_file(path, label=label)
    try:
        value = json.loads(
            source.read_text(encoding="utf-8"),
            object_pairs_hook=_unique_object,
            parse_constant=_reject_constant,
        )
    except (OSError, UnicodeError, json.JSONDecodeError) as exc:
        raise ValueError(f"{label} is not valid UTF-8 JSON: {source}") from exc
    if not isinstance(value, dict):
        raise ValueError(f"{label} must contain a JSON object")
    return value


def _nonempty(value: object, *, field: str) -> str:
    text = value.strip() if isinstance(value, str) else ""
    if not text:
        raise ValueError(f"{field} must be a non-empty string")
    return text


def _finite(value: object, *, field: str) -> float:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError(f"{field} must be a finite number")
    result = float(value)
    if not math.isfinite(result):
        raise ValueError(f"{field} must be a finite number")
    return result


def _vector(value: object, *, field: str, length: int) -> list[float]:
    if not isinstance(value, (list, tuple)) or len(value) != length:
        raise ValueError(f"{field} must contain exactly {length} numbers")
    return [_finite(item, field=f"{field}[{index}]") for index, item in enumerate(value)]


def _slug(value: object) -> str:
    result = re.sub(r"[^a-z0-9]+", "-", _nonempty(value, field="id").casefold()).strip("-")
    if not result:
        raise ValueError("id cannot be normalized to an empty slug")
    return result


def _write_json(path: Path, value: object) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    payload: Any
    if isinstance(value, BaseModel):
        payload = value.model_dump(mode="json")
    else:
        payload = value
    atomic_write_text(
        path,
        json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
    )


def _validate_source(
    source: Path,
) -> tuple[dict[str, Any], PickMovePlaceTask, list[dict[str, Any]], dict[str, str], str]:
    composition_path = source / "composition_manifest.json"
    task_path = source / "pick_move_place_task.json"
    blend_path = source / "asset_first_scene.blend"
    composition = _json_object(composition_path, label="asset-first composition manifest")
    if composition.get("schema_version") != "2.0":
        raise ValueError("composition_manifest.json schema_version must be 2.0")
    task_value = _json_object(task_path, label="asset-first pick-move-place task")
    task = PickMovePlaceTask.model_validate(task_value)
    if composition.get("task") != task.model_dump(mode="json"):
        raise ValueError("composition embedded task differs from pick_move_place_task.json")
    if task.passed is not True:
        raise ValueError("asset-first task did not pass its declared validation")

    raw_entities = composition.get("entities")
    if not isinstance(raw_entities, list) or not raw_entities:
        raise ValueError("composition manifest must contain entities")
    entities: list[dict[str, Any]] = []
    entity_ids: list[str] = []
    for index, raw_entity in enumerate(raw_entities):
        if not isinstance(raw_entity, dict):
            raise ValueError(f"composition entities[{index}] must be an object")
        entity = dict(raw_entity)
        entity_id = _nonempty(entity.get("entity_id"), field=f"entities[{index}].entity_id")
        dimensions = _vector(
            entity.get("dimensions_m"),
            field=f"{entity_id}.dimensions_m",
            length=3,
        )
        if any(value <= 0.0 for value in dimensions):
            raise ValueError(f"{entity_id}.dimensions_m must be positive")
        _vector(entity.get("center_xy_m"), field=f"{entity_id}.center_xy_m", length=2)
        _finite(entity.get("base_z_m"), field=f"{entity_id}.base_z_m")
        _finite(entity.get("yaw_deg"), field=f"{entity_id}.yaw_deg")
        for digest_field in ("asset_sha256", "runtime_sha256"):
            digest = entity.get(digest_field)
            if digest is not None and _SHA256.fullmatch(str(digest)) is None:
                raise ValueError(f"{entity_id}.{digest_field} must be a SHA-256 digest")
        entity_ids.append(entity_id)
        entities.append(entity)
    if entity_ids != list(dict.fromkeys(entity_ids)) or len(entity_ids) != len(set(entity_ids)):
        raise ValueError("composition entity IDs must be unique")

    critical = {
        task.movable_object_entity_id,
        task.source_support_entity_id,
        task.target_support_entity_id,
    }
    if len(critical) != 3 or not critical.issubset(entity_ids):
        raise ValueError("task critical entities are missing or not distinct")
    by_id = {str(item["entity_id"]): item for item in entities}
    if by_id[task.movable_object_entity_id].get("parent_entity_id") != (
        task.source_support_entity_id
    ):
        raise ValueError("movable object is not parented to the declared source support")

    source_hashes = {
        "asset_first_scene.blend": _sha256(
            _regular_file(blend_path, label="asset-first Blender scene")
        ),
        "composition_manifest.json": _sha256(composition_path),
        "pick_move_place_task.json": _sha256(task_path),
    }
    metric_path = source / "metric_layout_spec.json"
    if metric_path.exists() or metric_path.is_symlink():
        metric = _regular_file(metric_path, label="asset-first metric layout")
        metric_digest = _sha256(metric)
        declared_digest = composition.get("metric_layout_spec_sha256")
        if declared_digest is not None and declared_digest != metric_digest:
            raise ValueError("metric_layout_spec.json differs from composition identity")
        source_hashes["metric_layout_spec.json"] = metric_digest
    source_digest = _canonical_sha256(source_hashes)
    return composition, task, entities, source_hashes, source_digest


def _run_blender_export(
    source: Path,
    destination_scene: Path,
    *,
    blender_executable: str | Path,
    blender_export_script: str | Path,
    timeout_s: float,
) -> dict[str, Any]:
    blender = _executable_file(Path(blender_executable), label="Blender executable")
    exporter = _regular_file(Path(blender_export_script), label="Blender export script")
    blend = _regular_file(source / "asset_first_scene.blend", label="asset-first Blender scene")
    destination_scene.parent.mkdir(parents=True, exist_ok=True)
    command = [
        str(blender),
        "--background",
        "--python",
        str(exporter),
        "--",
        str(blend),
        str(destination_scene),
    ]
    completed = subprocess.run(
        command,
        cwd=source,
        stdin=subprocess.DEVNULL,
        capture_output=True,
        text=True,
        timeout=timeout_s,
        check=False,
    )
    if completed.returncode != 0:
        raise RuntimeError(
            "Blender USD export failed with exit code "
            f"{completed.returncode}:\n{completed.stderr[-4000:]}"
        )
    if not destination_scene.is_file() or destination_scene.stat().st_size == 0:
        raise RuntimeError("Blender exited successfully without producing scene.usdc")
    def sanitize(text: str) -> str:
        return text.replace(str(source), "<SOURCE>").replace(
            str(destination_scene.parent.parent), "<BUNDLE>"
        )
    return {
        "blender_sha256": _sha256(blender),
        "export_script_sha256": _sha256(exporter),
        "return_code": completed.returncode,
        "stdout_tail": sanitize(completed.stdout[-4000:]),
        "stderr_tail": sanitize(completed.stderr[-4000:]),
    }


def _run_usd_inspection(
    scene_usd: Path,
    cleanup_layer: Path,
    entity_ids: list[str],
    *,
    usd_python: str | Path | None,
    timeout_s: float,
) -> dict[str, Any]:
    executable = _executable_file(
        Path(usd_python or os.environ.get("RHG_USD_PYTHON") or sys.executable),
        label="OpenUSD Python executable",
    )
    request_path = cleanup_layer.parent / ".rparena_usd_request.json"
    _write_json(
        request_path,
        {
            "scene_usd": str(scene_usd.resolve()),
            "cleanup_layer": str(cleanup_layer.resolve(strict=False)),
            "entity_ids": sorted(entity_ids),
        },
    )
    project_root = Path(__file__).resolve().parents[2]
    worker_script = Path(__file__).with_name("rparena_usd_worker.py").resolve(strict=True)
    try:
        completed = subprocess.run(
            [
                str(executable),
                str(worker_script),
                "--request",
                str(request_path),
            ],
            cwd=project_root,
            stdin=subprocess.DEVNULL,
            capture_output=True,
            text=True,
            timeout=timeout_s,
            check=False,
        )
    finally:
        request_path.unlink(missing_ok=True)
    if completed.returncode != 0:
        detail = completed.stderr.strip() or completed.stdout.strip() or "unknown error"
        raise RuntimeError(f"RPArena OpenUSD inspection failed: {detail[-4000:]}")
    try:
        report = json.loads(completed.stdout.strip().splitlines()[-1])
    except (IndexError, json.JSONDecodeError) as exc:
        raise RuntimeError("RPArena OpenUSD inspection returned invalid JSON") from exc
    if (
        not isinstance(report, dict)
        or report.get("schema_version") != USD_INSPECTION_SCHEMA_VERSION
    ):
        raise RuntimeError("RPArena OpenUSD inspection returned an unsupported schema")
    bindings = report.get("entity_prim_paths")
    if not isinstance(bindings, dict) or sorted(bindings) != sorted(entity_ids):
        raise RuntimeError("RPArena OpenUSD inspection returned incomplete entity bindings")
    if not cleanup_layer.is_file():
        raise RuntimeError("RPArena OpenUSD inspection did not create the cleanup layer")
    return report


def _task_spec(
    task: PickMovePlaceTask,
    entities: list[dict[str, Any]],
    *,
    task_id: str,
    seed: int,
    manipulated_mass_kg: float,
) -> TaskSpec:
    movable = task.movable_object_entity_id
    source_support = task.source_support_entity_id
    target_support = task.target_support_entity_id
    task_entities: list[TaskEntity] = []
    for entity in entities:
        entity_id = str(entity["entity_id"])
        role: Literal["MANIPULATED", "TARGET", "CONTEXT"] = (
            "MANIPULATED"
            if entity_id == movable
            else "TARGET"
            if entity_id == target_support
            else "CONTEXT"
        )
        attributes = {
            key: entity[key]
            for key in (
                "asset_id",
                "asset_sha256",
                "runtime_sha256",
                "dimensions_m",
                "center_xy_m",
                "base_z_m",
                "yaw_deg",
                "parent_entity_id",
                "support_type",
            )
            if entity.get(key) is not None
        }
        if role == "MANIPULATED":
            attributes.update(
                {
                    "mass_kg": manipulated_mass_kg,
                    "rigid_body": True,
                    "collision": "convex_hull",
                    "require_collision": True,
                }
            )
        task_entities.append(
            TaskEntity(
                entity_id=entity_id,
                role=role,
                category=_nonempty(entity.get("category"), field=f"{entity_id}.category"),
                attributes=attributes,
                required=True,
            )
        )

    instruction = (
        f"Navigate from the generated start pose to {source_support}, grasp {movable}, "
        f"follow the generated route, place it on {target_support}, release it, and "
        "finish in a stable stance."
    )
    plan = TaskPlan(
        plan_id=f"plan-{task_id.removeprefix('task-')}",
        natural_language=instruction,
        skills=[
            SkillInvocation(
                invocation_id="navigate_to_source",
                skill_id="navigate",
                parameters={"target": source_support},
            ),
            SkillInvocation(
                invocation_id="grasp_object",
                skill_id="grasp",
                parameters={"object": movable},
                depends_on=["navigate_to_source"],
            ),
            SkillInvocation(
                invocation_id="carry_to_target",
                skill_id="carry",
                parameters={"object": movable, "target": target_support},
                depends_on=["grasp_object"],
            ),
            SkillInvocation(
                invocation_id="place_object",
                skill_id="place",
                parameters={"object": movable, "support": target_support},
                depends_on=["carry_to_target"],
            ),
            SkillInvocation(
                invocation_id="release_object",
                skill_id="release",
                parameters={"object": movable},
                depends_on=["place_object"],
            ),
        ],
        required_capabilities={"locomotion", "grasp", "carry", "place", "release"},
        difficulty=DifficultyVector(
            body=0.65,
            manipulation=0.8,
            cognition=0.35,
            body_reason="Navigate a generated indoor route while carrying an object.",
            manipulation_reason="Grasp, transport, place, and release a generated object.",
            cognition_reason="Follow a fixed pick-move-place sequence.",
        ),
    )
    return TaskSpec(
        task_id=task_id,
        natural_language=instruction,
        task_type="object_transfer",
        required_rooms=["generated_room"],
        entities=task_entities,
        initial_predicates=[
            PredicateSpec(name="supported_by", subject=movable, object=source_support)
        ],
        goal_predicates=[
            PredicateSpec(
                name="supported_by",
                subject=movable,
                object=target_support,
                hold_seconds=2.0,
            ),
            PredicateSpec(name="released", subject=movable),
            PredicateSpec(name="stable", subject=movable, hold_seconds=1.0),
            PredicateSpec(name="robot_stable", subject="robot", hold_seconds=1.0),
        ],
        safety_predicates=[PredicateSpec(name="no_safety_event", subject="robot")],
        plan=plan,
        random_seed=seed,
        metadata={
            "generator": "RoboHouseGen",
            "source_task_id": task.task_id,
            "source_task_type": task.task_type,
            "description_en": task.description_en,
            "description_zh": task.description_zh,
            "route_waypoints_xy_m": task.route_waypoints_xy_m,
            "route_length_m": task.route_length_m,
            "pick": task.pick.model_dump(mode="json"),
            "place": task.place.model_dump(mode="json"),
        },
    )


def _write_complete_checksums(root: Path) -> int:
    checksum_path = root / "checksums.sha256"
    checksum_path.unlink(missing_ok=True)
    entries: list[str] = []
    for path in sorted(root.rglob("*")):
        if path.is_symlink():
            raise ValueError(f"RPArena export contains a symlink: {path}")
        if path.is_file():
            relative = path.relative_to(root).as_posix()
            entries.append(f"{_sha256(path)}  {relative}")
    atomic_write_text(checksum_path, "\n".join(entries) + "\n")
    return len(entries)


def export_asset_first_rparena_bundle(
    source_dir: str | Path,
    output_dir: str | Path,
    *,
    blender_executable: str | Path,
    usd_python: str | Path | None = None,
    blender_export_script: str | Path | None = None,
    robot_profile: str = "unitree_g1_43dof",
    robot_base_height_m: float = 0.78,
    manipulated_mass_kg: float = 0.25,
    max_duration_s: float = 180.0,
    seed: int = 0,
    timeout_s: float = 900.0,
) -> RPArenaExportResult:
    """Export one certified asset-first task as a standard RPArena bundle."""

    source = _source_directory(source_dir)
    output = Path(output_dir).expanduser().resolve(strict=False)
    if output.exists():
        raise FileExistsError(f"output already exists: {output}")
    output.parent.mkdir(parents=True, exist_ok=True)
    height = _finite(robot_base_height_m, field="robot_base_height_m")
    mass = _finite(manipulated_mass_kg, field="manipulated_mass_kg")
    duration = _finite(max_duration_s, field="max_duration_s")
    timeout = _finite(timeout_s, field="timeout_s")
    if height <= 0.0 or mass <= 0.0 or duration <= 0.0 or timeout <= 0.0:
        raise ValueError("robot height, mass, duration, and timeout must be positive")
    if isinstance(seed, bool) or not isinstance(seed, int):
        raise ValueError("seed must be an integer")
    profile = _nonempty(robot_profile, field="robot_profile")
    composition, source_task, entities, source_hashes, source_digest = _validate_source(source)

    project_root = Path(__file__).resolve().parents[2]
    export_script = blender_export_script or project_root / "scripts/blender_export_usd.py"
    source_slug = _slug(source_task.task_id)
    task_id = f"task-rhg-{source_slug}-v1"
    scene_id = f"scene-rhg-{source_slug}-v1"
    episode_id = f"episode-rhg-{source_slug}-{_slug(profile)}"

    with tempfile.TemporaryDirectory(prefix=f".{output.name}.staging-", dir=output.parent) as temp:
        staging = Path(temp) / "bundle"
        scene_usd = staging / "scenesmith/scene.usdc"
        export_evidence = _run_blender_export(
            source,
            scene_usd,
            blender_executable=blender_executable,
            blender_export_script=export_script,
            timeout_s=timeout,
        )
        cleanup_layer = staging / "layers/asset_first_cleanup.usda"
        usd_report = _run_usd_inspection(
            scene_usd,
            cleanup_layer,
            [str(entity["entity_id"]) for entity in entities],
            usd_python=usd_python,
            timeout_s=timeout,
        )
        bindings = {str(key): str(value) for key, value in usd_report["entity_prim_paths"].items()}
        scene_usd_sha256 = _sha256(scene_usd)
        root_usd = staging / "root.usda"
        atomic_write_text(
            root_usd,
            '#usda 1.0\n(\n    defaultPrim = "World"\n    metersPerUnit = 1\n'
            '    upAxis = "Z"\n    subLayers = [\n'
            '        @layers/asset_first_cleanup.usda@,\n'
            '        @scenesmith/scene.usdc@\n    ]\n)\n',
        )

        task = _task_spec(
            source_task,
            entities,
            task_id=task_id,
            seed=seed,
            manipulated_mass_kg=mass,
        )
        content_hash = _canonical_sha256(
            {
                "entity_prim_paths": bindings,
                "scene_usd_sha256": scene_usd_sha256,
                "source_digest": source_digest,
                "task_visual_roots_disabled": usd_report["task_visual_roots_disabled"],
            }
        )
        scene = SceneManifest(
            scene_id=scene_id,
            task_id=task_id,
            random_seed=seed,
            layer_plan=SceneLayerPlan(
                root_layer="root.usda",
                layers={
                    "asset_first_cleanup": "layers/asset_first_cleanup.usda",
                    "scene": "scenesmith/scene.usdc",
                },
            ),
            entity_prim_paths=bindings,
            robot_prim_path="/World/Robot",
            source_checkpoints={
                "adapter": ADAPTER_VERSION,
                "generator": "RoboHouseGen",
                "source_digest": source_digest,
            },
            content_hash=content_hash,
        )
        episode = BenchmarkPackager().package(
            task,
            scene,
            profile,
            staging,
            episode_id=episode_id,
            max_duration_s=duration,
            split="test",
            factor_values={
                "source_task_id": source_task.task_id,
                "source_digest": source_digest,
            },
        )
        _write_json(staging / "manifests/scene.json", scene)
        _write_json(
            staging / "manifests/robot.json",
            {
                "schema_version": "1.0",
                "translation_m": [
                    source_task.robot_start_pose.x_m,
                    source_task.robot_start_pose.y_m,
                    height,
                ],
                "rotation_rpy_deg": [0.0, 0.0, source_task.robot_start_pose.yaw_deg],
            },
        )

        provenance = staging / "provenance"
        provenance.mkdir(parents=True, exist_ok=True)
        shutil.copy2(source / "composition_manifest.json", provenance / "composition_manifest.json")
        shutil.copy2(
            source / "pick_move_place_task.json",
            provenance / "pick_move_place_task.json",
        )
        metric_path = source / "metric_layout_spec.json"
        if metric_path.is_file() and not metric_path.is_symlink():
            shutil.copy2(metric_path, provenance / "metric_layout_spec.json")
        texture_files = sorted(
            path.relative_to(staging).as_posix()
            for path in (scene_usd.parent / "textures").rglob("*")
            if path.is_file() and not path.is_symlink()
        ) if (scene_usd.parent / "textures").is_dir() else []
        export_report = {
            "schema_version": "robothousegen.rparena-export/1.0",
            "adapter": ADAPTER_VERSION,
            "source_hashes": source_hashes,
            "source_digest": source_digest,
            "scene_usd_sha256": scene_usd_sha256,
            "entity_prim_paths": bindings,
            "entity_mesh_counts": usd_report["entity_mesh_counts"],
            "task_visual_roots_disabled": usd_report["task_visual_roots_disabled"],
            "source_default_prim": usd_report["source_default_prim"],
            "copied_textures": texture_files,
            "blender": export_evidence,
            "assumptions": {
                "robot_base_height_m": height,
                "manipulated_mass_kg": mass,
                "physics_authoring": "consumer",
                "robot_embodiment": "consumer",
            },
            "room_dimensions_m": composition.get("room_dimensions_m"),
        }
        _write_json(provenance / "rparena_export.json", export_report)

        interface = RPArenaInterfaceV1(
            schema_version="rparena.generator-interface/1.0",
            producer=RPArenaProducer(
                name="RoboHouseGen",
                version=API_COMPAT_VERSION,
                adapter=ADAPTER_VERSION,
            ),
            bundle=RPArenaBundlePaths(
                root_usd="root.usda",
                scene_usd="scenesmith/scene.usdc",
                scene_manifest="manifests/scene.json",
                task_manifest="manifests/task.json",
                episode_manifest="manifests/episode.json",
                evaluator_manifest="manifests/evaluator.json",
                robot_manifest="manifests/robot.json",
            ),
            contract=RPArenaContract(
                bundle_type="single_episode",
                task_type=task.task_type,
                evaluator="predicate_graph_v1",
                entity_binding="absolute_world_prim_paths",
                physics_authoring="consumer",
                robot_embodiment="consumer",
                coordinate_system="usd_z_up_right_handed_metres",
                checksums="sha256_complete",
            ),
            identity=RPArenaIdentity(
                scene_id=scene.scene_id,
                task_id=task.task_id,
                episode_id=episode.episode_id,
                entity_ids=sorted(bindings),
                manipulated_entity_ids=[source_task.movable_object_entity_id],
            ),
            source=RPArenaSource(
                kind="robothousegen.asset-first",
                source_task_id=source_task.task_id,
                source_digest=source_digest,
            ),
        )
        _write_json(staging / INTERFACE_MANIFEST, interface)
        checksummed_file_count = _write_complete_checksums(staging)
        staging.replace(output)

    return RPArenaExportResult(
        bundle_root=output,
        interface_manifest=output / INTERFACE_MANIFEST,
        scene_id=scene_id,
        task_id=task_id,
        episode_id=episode_id,
        source_digest=source_digest,
        scene_usd_sha256=scene_usd_sha256,
        entity_prim_paths=bindings,
        checksummed_file_count=checksummed_file_count,
    )


__all__ = [
    "ADAPTER_VERSION",
    "EXPORT_RESULT_SCHEMA_VERSION",
    "INTERFACE_MANIFEST",
    "INTERFACE_SCHEMA_VERSION",
    "RPArenaExportResult",
    "RPArenaInterfaceV1",
    "export_asset_first_rparena_bundle",
]