File size: 27,267 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
from __future__ import annotations

import hashlib
import json
import os
import re
import subprocess
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

from packages.core.files import atomic_write_text

REFERENCE_PATTERN = re.compile(r"@([^@]+)@")
ISAAC_RUNTIME_ASSETS = {"OmniPBR.mdl"}
RUNTIME_SCENE_FILES = (
    "scene.usdc",
    "preview.mp4",
    "iteration_history.mp4",
    "iterations_manifest.json",
    "stage_manifest.json",
    "scene_request.json",
    "scene_context.json",
    "selected_assets.json",
    "effective_selected_assets.json",
    "compiled_prompt.txt",
    "timing.json",
    "cleanup_report.json",
    "cleanup_config.json",
    "context_assets_config.json",
    "agent_skill_policy.json",
    "scene_dependency_graph.json",
    "dependency_execution_plan.json",
    "agent_orchestration_effective.json",
    "planning_agent_output.json",
    "agent_execution_plan.json",
    "agent_execution_ledger.json",
    "global_critic.json",
    "agent_merge_result.json",
)


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


def refresh_checksums(root: Path) -> int:
    lines = []
    for path in sorted(root.rglob("*")):
        if path.is_file() and not path.is_symlink() and path.name != "checksums.sha256":
            lines.append(f"{sha256(path)}  {path.relative_to(root).as_posix()}")
    atomic_write_text(root / "checksums.sha256", "\n".join(lines) + "\n")
    return len(lines)


def _hardlink(source: Path, destination: Path) -> None:
    destination.parent.mkdir(parents=True, exist_ok=True)
    os.link(source, destination)


def _runtime_files(source: Path) -> list[tuple[Path, Path]]:
    files: list[tuple[Path, Path]] = []
    for relative_root in (Path("layers"), Path("manifests")):
        for path in sorted((source / relative_root).rglob("*")):
            if (
                path.is_file()
                and not path.is_symlink()
                and path.relative_to(source) != Path("manifests/portable_validation.json")
            ):
                files.append((path, path.relative_to(source)))
    files.append((source / "root.usda", Path("root.usda")))
    snapshot = source / "snapshot.jpg"
    if snapshot.is_file():
        files.append((snapshot, Path("snapshot.jpg")))
    # Stable public media entry. Keep the SceneSmith-native location as
    # provenance/backward compatibility, while portable consumers can always
    # open ``preview.mp4`` without knowing which scene backend produced it.
    root_preview = source / "preview.mp4"
    scenesmith_preview = source / "scenesmith" / "preview.mp4"
    preview = root_preview if root_preview.is_file() else scenesmith_preview
    if preview.is_file():
        files.append((preview, Path("preview.mp4")))
    root_history = source / "iteration_history.mp4"
    scenesmith_history = source / "scenesmith" / "iteration_history.mp4"
    history = root_history if root_history.is_file() else scenesmith_history
    if history.is_file():
        files.append((history, Path("iteration_history.mp4")))
    for name in RUNTIME_SCENE_FILES:
        path = source / "scenesmith" / name
        if path.is_file():
            files.append((path, Path("scenesmith") / name))
    texture_root = source / "scenesmith" / "textures"
    if texture_root.is_dir():
        for path in sorted(texture_root.rglob("*")):
            if path.is_file() and not path.is_symlink():
                files.append((path, path.relative_to(source)))
    robot_assets_root = source / "assets" / "robots"
    if robot_assets_root.is_dir():
        for path in sorted(robot_assets_root.rglob("*")):
            if path.is_file() and not path.is_symlink():
                files.append((path, path.relative_to(source)))
    postprocess_root = source / "scenesmith" / "postprocess_iterations"
    if postprocess_root.is_dir():
        for path in sorted(postprocess_root.rglob("*")):
            if path.is_file() and not path.is_symlink():
                files.append((path, path.relative_to(source)))
    subtree_root = source / "scenesmith" / "subtrees"
    if subtree_root.is_dir():
        for path in sorted(subtree_root.rglob("*")):
            if path.is_file() and not path.is_symlink():
                files.append((path, path.relative_to(source)))
    house_state = source / "scenesmith/upstream/scene_000/combined_house/house_state.json"
    stage_manifest = source / "scenesmith/stage_manifest.json"
    if stage_manifest.is_file():
        manifest = json.loads(stage_manifest.read_text(encoding="utf-8"))
        relative_state = manifest.get("house_state")
        if isinstance(relative_state, str) and relative_state:
            candidate = source / "scenesmith" / relative_state
            if candidate.is_file():
                house_state = candidate
    if house_state.is_file():
        files.append((house_state, Path("provenance/house_state.json")))
    return files


def portable_source_fingerprint(source: Path) -> str:
    """Hash every source artifact that is materialized into a portable bundle."""

    digest = hashlib.sha256()
    for path, relative in _runtime_files(source.resolve()):
        digest.update(relative.as_posix().encode("utf-8"))
        digest.update(b"\0")
        digest.update(sha256(path).encode("ascii"))
        digest.update(b"\n")
    return digest.hexdigest()


def _native_asset_bindings(source: Path) -> dict[str, Any]:
    manifest_path = source / "scenesmith/stage_manifest.json"
    if not manifest_path.is_file():
        return {}
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    bindings = manifest.get("native_asset_bindings") or {}
    if not isinstance(bindings, dict):
        raise ValueError(f"native_asset_bindings must be an object: {manifest_path}")
    return bindings


def _dependency_destination(root: Path, source: Path, kind: str) -> Path:
    path_digest = hashlib.sha256(str(source).encode("utf-8")).hexdigest()[:16]
    return root / "scenesmith" / "assets" / kind / f"{path_digest}-{source.name}"


def _is_isaac_runtime_asset(value: object) -> bool:
    """Recognize only named modules guaranteed by the declared Isaac runtime."""

    normalized = str(value).replace("\\", "/").rsplit("/", 1)[-1]
    return normalized in ISAAC_RUNTIME_ASSETS


def _stage_usd_dependencies(
    source_scene: Path,
    destination_scene: Path,
    destination_root: Path,
) -> dict[str, Any]:
    try:
        from pxr import Sdf, Usd, UsdUtils  # type: ignore[import-not-found]
    except ImportError as error:
        raise RuntimeError(
            "pxr is required to stage native USD dependencies for a portable bundle"
        ) from error

    layers, asset_paths, unresolved = UsdUtils.ComputeAllDependencies(str(source_scene))
    external_runtime_assets = sorted(
        {str(path).replace("\\", "/").rsplit("/", 1)[-1] for path in unresolved}
        & ISAAC_RUNTIME_ASSETS
    )
    unresolved_files = sorted(
        str(path) for path in unresolved if not _is_isaac_runtime_asset(path)
    )
    if unresolved_files:
        raise RuntimeError(
            "USD dependencies could not be resolved: " + ", ".join(unresolved_files)
        )

    source_scene = source_scene.resolve()
    layer_sources = {
        Path(layer.realPath).resolve(): layer
        for layer in layers
        if layer.realPath and Path(layer.realPath).is_file()
    }
    if source_scene not in layer_sources:
        raise RuntimeError(f"USD dependency traversal omitted root layer: {source_scene}")

    destination_by_source: dict[Path, Path] = {source_scene: destination_scene}
    for source in sorted(layer_sources, key=str):
        if source != source_scene:
            destination_by_source[source] = _dependency_destination(destination_root, source, "usd")
    non_layer_sources = {
        Path(path).resolve()
        for path in asset_paths
        if Path(path).is_file() and Path(path).resolve() not in layer_sources
    }
    missing_assets = sorted(
        str(path)
        for path in asset_paths
        if not Path(path).is_file() and not _is_isaac_runtime_asset(path)
    )
    if missing_assets:
        raise RuntimeError("USD asset files are missing: " + ", ".join(missing_assets))
    for source in sorted(non_layer_sources, key=str):
        destination_by_source[source] = _dependency_destination(destination_root, source, "files")

    hardlinked_assets = 0
    for source in sorted(non_layer_sources, key=str):
        target = destination_by_source[source]
        _hardlink(source, target)
        hardlinked_assets += 1

    rewritten_layers = 0
    for source, source_layer in sorted(layer_sources.items(), key=lambda item: str(item[0])):
        target = destination_by_source[source]
        target.parent.mkdir(parents=True, exist_ok=True)
        temporary = target.with_name(f".{target.name}.rewrite{target.suffix}")
        if not source_layer.Export(str(temporary)):
            raise RuntimeError(f"could not export USD dependency: {source}")
        output_layer = Sdf.Layer.FindOrOpen(str(temporary))
        if output_layer is None:
            raise RuntimeError(f"could not reopen staged USD layer: {temporary}")
        unstaged: list[str] = []

        def rebase(
            asset_path: str,
            *,
            source_layer: Any = source_layer,
            source: Path = source,
            target: Path = target,
            unstaged: list[str] = unstaged,
        ) -> str:
            if not asset_path:
                return asset_path
            resolved_text = Sdf.ComputeAssetPathRelativeToLayer(source_layer, asset_path)
            resolved = Path(resolved_text).resolve()
            dependency_target = destination_by_source.get(resolved)
            if dependency_target is None:
                if resolved.is_file():
                    unstaged.append(f"{source}: {asset_path} -> {resolved}")
                return asset_path
            return os.path.relpath(dependency_target, target.parent).replace(os.sep, "/")

        UsdUtils.ModifyAssetPaths(output_layer, rebase)
        if unstaged:
            raise RuntimeError("USD dependencies were not staged: " + ", ".join(unstaged))
        output_layer.Save()
        temporary.replace(target)
        rewritten_layers += 1

    stage = Usd.Stage.Open(str(destination_scene))
    if stage is None:
        raise RuntimeError(f"staged USD scene does not open: {destination_scene}")
    return {
        "rewritten_layers": rewritten_layers,
        "hardlinked_assets": hardlinked_assets,
        "dependency_count": len(destination_by_source) - 1,
        "external_runtime_assets": external_runtime_assets,
    }


def create_portable_bundle(
    source: Path,
    destination: Path,
    *,
    policy_path: Path | None = None,
) -> dict[str, Any]:
    source = source.resolve()
    destination = destination.resolve()
    if destination.exists():
        raise FileExistsError(destination)
    if not (source / "root.usda").is_file():
        raise FileNotFoundError(source / "root.usda")
    if source.stat().st_dev != destination.parent.stat().st_dev:
        raise RuntimeError("hard-link staging requires source and destination on one filesystem")
    destination.mkdir()
    linked = 0
    for path, relative in _runtime_files(source):
        if not path.is_file():
            raise FileNotFoundError(path)
        _hardlink(path, destination / relative)
        linked += 1
    if policy_path is not None:
        policy_path = policy_path.resolve()
        _hardlink(policy_path, destination / "runtime/policies" / policy_path.name)
        linked += 1

    usd_dependencies = {
        "rewritten_layers": 0,
        "hardlinked_assets": 0,
        "dependency_count": 0,
        "external_runtime_assets": [],
    }
    if _native_asset_bindings(source):
        usd_dependencies = _stage_usd_dependencies(
            source / "scenesmith/scene.usdc",
            destination / "scenesmith/scene.usdc",
            destination,
        )
        linked += usd_dependencies["hardlinked_assets"]

    furniture = destination / "layers/furniture.usda"
    text = furniture.read_text(encoding="utf-8")
    corrected = text.replace("@scenesmith/scene.usdc@", "@../scenesmith/scene.usdc@")
    if corrected != text:
        # Break the hard link before writing metadata that is specific to the portable layout.
        temporary = furniture.with_suffix(".tmp")
        temporary.write_text(corrected, encoding="utf-8")
        temporary.replace(furniture)

    manifest = {
        "schema_version": "1.0",
        "format": "robothousegen-portable-benchmark",
        "created_at": datetime.now(UTC).isoformat(),
        "source_run_name": source.name,
        "source_fingerprint": portable_source_fingerprint(source),
        "entrypoint": "root.usda",
        "episode": "manifests/episode.json",
        "evaluator": "manifests/evaluator.json",
        "hardlink_staging": True,
        "hardlinked_files": linked,
        "usd_dependencies": usd_dependencies,
        "runtime_requirements": {
            "simulator": "Isaac Sim 6.0.1",
            "benchmark_runtime": "Isaac Lab-Arena release/0.2.1",
            "robot_profile": "unitree_g1_43dof",
        },
    }
    atomic_write_text(
        destination / "portable_manifest.json",
        json.dumps(manifest, indent=2, sort_keys=True) + "\n",
    )
    manifest["checksummed_files"] = refresh_checksums(destination)
    return manifest


def _verify_checksums(root: Path) -> list[str]:
    failures = []
    checksum_path = root / "checksums.sha256"
    if not checksum_path.is_file():
        return ["checksums.sha256 is missing"]
    for line in checksum_path.read_text(encoding="utf-8").splitlines():
        expected, separator, relative = line.partition("  ")
        path = root / relative
        if not separator or not path.is_file() or sha256(path) != expected:
            failures.append(relative or line)
    return failures


def _verify_text_references(root: Path, *, allowed_root: Path | None = None) -> list[str]:
    allowed_root = (allowed_root or root).resolve()
    failures = []
    for layer in [root / "root.usda", *(root / "layers").glob("*.usda")]:
        for reference in REFERENCE_PATTERN.findall(layer.read_text(encoding="utf-8")):
            if reference.startswith(("http://", "https://", "omniverse://")):
                failures.append(f"external URI in {layer.relative_to(root)}: {reference}")
                continue
            target = (layer.parent / reference).resolve()
            if not target.is_relative_to(allowed_root) or not target.is_file():
                failures.append(f"broken reference in {layer.relative_to(root)}: {reference}")
    return failures


def _verify_usd(
    root: Path, *, allowed_root: Path | None = None
) -> tuple[dict[str, Any], list[str]]:
    allowed_root = (allowed_root or root).resolve()
    try:
        from pxr import Sdf, Usd, UsdPhysics
    except ImportError:
        return {"pxr_available": False}, []
    stage = Usd.Stage.Open(str(root / "root.usda"))
    if stage is None:
        return {"pxr_available": True, "stage_open": False}, ["USD stage did not open"]
    failures: list[str] = []
    external_paths: list[str] = []
    for layer in stage.GetLayerStack():
        if not layer.realPath:
            continue
        for reference in layer.GetExternalReferences():
            target = Path(layer.ComputeAbsolutePath(reference)).resolve()
            external_paths.append(str(target))
            if not target.is_relative_to(allowed_root) or not target.is_file():
                failures.append(f"USD dependency escapes bundle: {target}")
    asset_paths = 0
    for prim in stage.Traverse():
        for attribute in prim.GetAttributes():
            value = attribute.Get()
            values = value if isinstance(value, (list, tuple)) else [value]
            for item in values:
                if isinstance(item, Sdf.AssetPath) and item.path:
                    asset_paths += 1
                    if item.path in ISAAC_RUNTIME_ASSETS:
                        continue
                    asset_target = Path(item.resolvedPath).resolve() if item.resolvedPath else None
                    if (
                        asset_target is None
                        or not asset_target.is_relative_to(allowed_root)
                        or not asset_target.is_file()
                    ):
                        failures.append(f"USD asset dependency is missing or external: {item.path}")
    evaluator = json.loads((root / "manifests/evaluator.json").read_text(encoding="utf-8"))
    missing_prims = [
        path
        for path in [
            *evaluator.get("entity_prim_paths", {}).values(),
            evaluator.get("robot_prim_path"),
        ]
        if path and not stage.GetPrimAtPath(path)
    ]
    failures.extend(f"evaluator prim is missing: {path}" for path in missing_prims)
    task = json.loads((root / "manifests/task.json").read_text(encoding="utf-8"))
    entity_paths = evaluator.get("entity_prim_paths", {})
    manipulation_physics: dict[str, Any] = {}
    for entity in task.get("entities", []):
        if not isinstance(entity, dict) or entity.get("role") != "MANIPULATED":
            continue
        entity_id = str(entity.get("entity_id", ""))
        prim_path = entity_paths.get(entity_id)
        prim = stage.GetPrimAtPath(prim_path) if isinstance(prim_path, str) else None
        rigid = bool(prim and prim.HasAPI(UsdPhysics.RigidBodyAPI))
        collisions = (
            [
                str(descendant.GetPath())
                for descendant in Usd.PrimRange(prim)
                if descendant.HasAPI(UsdPhysics.CollisionAPI)
            ]
            if prim
            else []
        )
        manipulation_physics[entity_id] = {
            "prim_path": prim_path,
            "rigid_body_api": rigid,
            "collision_prim_paths": collisions,
        }
        if not rigid:
            failures.append(f"manipulated entity lacks RigidBodyAPI: {entity_id}")
        if not collisions:
            failures.append(f"manipulated entity lacks CollisionAPI geometry: {entity_id}")
    return {
        "pxr_available": True,
        "stage_open": True,
        "traversed_prims": sum(1 for _ in stage.Traverse()),
        "external_layers": len(external_paths),
        "asset_paths": asset_paths,
        "missing_evaluator_prims": missing_prims,
        "manipulation_physics": manipulation_physics,
    }, failures


def verify_portable_bundle(root: Path, *, require_pxr: bool = False) -> dict[str, Any]:
    root = root.resolve()
    failures: list[str] = []
    required = [
        "root.usda",
        "portable_manifest.json",
        "manifests/task.json",
        "manifests/scene.json",
        "manifests/evaluator.json",
        "manifests/episode.json",
    ]
    if (root / "scenesmith/stage_manifest.json").is_file() or (
        root / "scenesmith/scene.usdc"
    ).is_file():
        required.append("scenesmith/scene.usdc")
    failures.extend(relative for relative in required if not (root / relative).is_file())
    symlinks = [str(path.relative_to(root)) for path in root.rglob("*") if path.is_symlink()]
    failures.extend(f"symlink is not portable: {path}" for path in symlinks)
    failures.extend(f"checksum mismatch: {path}" for path in _verify_checksums(root))
    failures.extend(_verify_text_references(root))
    usd_report, usd_failures = _verify_usd(root)
    failures.extend(usd_failures)
    if require_pxr and not usd_report.get("pxr_available"):
        failures.append("pxr is required for full USD validation")
    return {
        "schema_version": "1.0",
        "root": str(root),
        "passed": not failures,
        "failures": failures,
        "file_count": sum(1 for path in root.rglob("*") if path.is_file()),
        "size_bytes": sum(path.stat().st_size for path in root.rglob("*") if path.is_file()),
        "symlink_count": len(symlinks),
        "usd": usd_report,
    }


def _link_tree(source: Path, destination: Path) -> int:
    linked = 0
    for path in sorted(source.rglob("*")):
        if path.is_symlink():
            raise RuntimeError(f"portable source contains a symlink: {path}")
        if path.is_file():
            _hardlink(path, destination / path.relative_to(source))
            linked += 1
    return linked


def create_portable_suite_bundle(source: Path, destination: Path) -> dict[str, Any]:
    """Stage a shared-scene benchmark suite with every dependency inside one directory."""

    source = source.resolve()
    destination = destination.resolve()
    if destination.exists():
        raise FileExistsError(destination)
    suite_manifest_path = source / "manifests/suite.json"
    if not suite_manifest_path.is_file():
        raise FileNotFoundError(suite_manifest_path)
    if source.stat().st_dev != destination.parent.stat().st_dev:
        raise RuntimeError("hard-link staging requires source and destination on one filesystem")
    suite_manifest = json.loads(suite_manifest_path.read_text(encoding="utf-8"))
    episodes = suite_manifest.get("episodes")
    if not isinstance(episodes, list) or not episodes:
        raise ValueError("suite manifest must contain episodes")

    destination.mkdir()
    linked = 0
    for relative in (Path("inputs"), Path("manifests")):
        root = source / relative
        if root.is_dir():
            linked += _link_tree(root, destination / relative)
    for episode in episodes:
        if not isinstance(episode, dict) or not isinstance(episode.get("episode_id"), str):
            raise ValueError("suite episode entries require episode_id")
        episode_id = episode["episode_id"]
        episode_root = source / "episodes" / episode_id
        if not episode_root.is_dir():
            raise FileNotFoundError(episode_root)
        linked += _link_tree(episode_root, destination / "episodes" / episode_id)

    shared_source = source / "shared_scene"
    shared_destination = destination / "shared_scene"
    for path, relative in _runtime_files(shared_source):
        if not path.is_file():
            raise FileNotFoundError(path)
        _hardlink(path, shared_destination / relative)
        linked += 1

    usd_dependencies = {
        "rewritten_layers": 0,
        "hardlinked_assets": 0,
        "dependency_count": 0,
    }
    if _native_asset_bindings(shared_source):
        usd_dependencies = _stage_usd_dependencies(
            shared_source / "scenesmith/scene.usdc",
            shared_destination / "scenesmith/scene.usdc",
            shared_destination,
        )
        linked += usd_dependencies["hardlinked_assets"]

    manifest = {
        "schema_version": "1.0",
        "format": "robothousegen-portable-suite",
        "created_at": datetime.now(UTC).isoformat(),
        "source_run_name": source.name,
        "suite": "manifests/suite.json",
        "shared_scene_entrypoint": "shared_scene/root.usda",
        "shared_scene_usd": (
            "shared_scene/scenesmith/scene.usdc"
            if (shared_destination / "scenesmith/scene.usdc").is_file()
            else None
        ),
        "episode_count": len(episodes),
        "hardlink_staging": True,
        "hardlinked_files": linked,
        "usd_dependencies": usd_dependencies,
        "runtime_requirements": {
            "simulator": "Isaac Sim 6.0.1",
            "benchmark_runtime": "Isaac Lab-Arena release/0.2.1",
        },
    }
    atomic_write_text(
        destination / "portable_manifest.json",
        json.dumps(manifest, indent=2, sort_keys=True) + "\n",
    )
    manifest["checksummed_files"] = refresh_checksums(destination)
    return manifest


def verify_portable_suite_bundle(root: Path, *, require_pxr: bool = False) -> dict[str, Any]:
    root = root.resolve()
    failures: list[str] = []
    required = [
        "portable_manifest.json",
        "manifests/suite.json",
        "manifests/build_timing.json",
        "shared_scene/root.usda",
        "shared_scene/manifests/scene.json",
    ]
    portable_path = root / "portable_manifest.json"
    if portable_path.is_file():
        portable = json.loads(portable_path.read_text(encoding="utf-8"))
        shared_scene_usd = portable.get("shared_scene_usd")
        if isinstance(shared_scene_usd, str):
            required.append(shared_scene_usd)
    failures.extend(relative for relative in required if not (root / relative).is_file())
    symlinks = [str(path.relative_to(root)) for path in root.rglob("*") if path.is_symlink()]
    failures.extend(f"symlink is not portable: {path}" for path in symlinks)
    failures.extend(f"checksum mismatch: {path}" for path in _verify_checksums(root))

    suite_path = root / "manifests/suite.json"
    episodes: list[dict[str, Any]] = []
    if suite_path.is_file():
        payload = json.loads(suite_path.read_text(encoding="utf-8"))
        raw_episodes = payload.get("episodes", [])
        if isinstance(raw_episodes, list):
            episodes = [item for item in raw_episodes if isinstance(item, dict)]
        else:
            failures.append("suite manifest episodes must be a list")
    usd_reports: dict[str, Any] = {}
    for episode in episodes:
        episode_id = episode.get("episode_id")
        if not isinstance(episode_id, str):
            failures.append("suite episode is missing episode_id")
            continue
        episode_root = root / "episodes" / episode_id
        for relative in (
            "root.usda",
            "manifests/task.json",
            "manifests/episode.json",
            "manifests/evaluator.json",
            "manifests/scene_overrides.json",
        ):
            if not (episode_root / relative).is_file():
                failures.append(f"episodes/{episode_id}/{relative} is missing")
        if not (episode_root / "root.usda").is_file():
            continue
        failures.extend(_verify_text_references(episode_root, allowed_root=root))
        if (episode_root / "manifests/evaluator.json").is_file():
            usd_report, usd_failures = _verify_usd(episode_root, allowed_root=root)
            usd_reports[episode_id] = usd_report
            failures.extend(f"{episode_id}: {failure}" for failure in usd_failures)
            if require_pxr and not usd_report.get("pxr_available"):
                failures.append(f"{episode_id}: pxr is required for full USD validation")

    return {
        "schema_version": "1.0",
        "root": str(root),
        "passed": not failures,
        "failures": failures,
        "episode_count": len(episodes),
        "file_count": sum(1 for path in root.rglob("*") if path.is_file()),
        "size_bytes": sum(path.stat().st_size for path in root.rglob("*") if path.is_file()),
        "symlink_count": len(symlinks),
        "usd": usd_reports,
    }


def create_zstd_archive(bundle: Path, archive: Path) -> None:
    archive.parent.mkdir(parents=True, exist_ok=True)
    subprocess.run(
        ["tar", "--zstd", "-cf", str(archive), "-C", str(bundle.parent), bundle.name],
        check=True,
    )