"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
feat: add s&box CLI harness
KarandeepSWranch18c4222f8b90
diff --git a/.gitignore b/.gitignoreindex 30cdd4800..e249ee9c6 100644--- a/.gitignore+++ b/.gitignore@@ -221,6 +221,8 @@!/unrealinsights/agent-harness/!/nsight-graphics/agent-harness/!/lldb/agent-harness/+!/sbox/+!/sbox/agent-harness/# Step 7: Ignore build artifacts within allowed dirs**/__pycache__/diff --git a/README.md b/README.mdindex c33fc3925..75ae536a7 100644--- a/README.md+++ b/README.md@@ -569,7 +569,7 @@ The catalog auto-updates whenever `registry.json` changes โ new community CLIs| **๐ Data & Analytics** | Enable programmatic data processing, visualization, and statistical analysis workflows | JupyterLab, Apache Superset, Metabase, Redash, DBeaver, KNIME, Orange, OpenSearch Dashboards, Lightdash || **๐ป Development Tools** | Streamline code editing, building, testing, and deployment processes via command interfaces | Jenkins, Gitea, Hoppscotch, Portainer, pgAdmin, SonarQube, ArgoCD, OpenLens, Insomnia, Beekeeper Studio, **[iTerm2](https://iterm2.com)** || **๐จ Creative & Media** | Control content creation, editing, and rendering workflows programmatically | Blender, GIMP, OBS Studio, Audacity, Krita, Kdenlive, Shotcut, Inkscape, Darktable, LMMS, Ardour |-| **๐ฎ Game Development** | Manage game projects, scenes, exports, and scripting through headless engine interfaces | **[Godot Engine](https://godotengine.org)** |+| **๐ฎ Game Development** | Manage game projects, scenes, exports, and scripting through headless engine interfaces | **[Godot Engine](https://godotengine.org)**, **[s&box](https://sbox.game)** || **๐ฌ Scientific Computing** | Automate research workflows, simulations, and complex calculations | ImageJ, FreeCAD, QGIS, ParaView, Gephi, LibreCAD, Stellarium, KiCad, JASP, Jamovi || **๐ข Enterprise & Office** | Convert business applications and productivity tools into agent-accessible systems | NextCloud, GitLab, Grafana, Mattermost, LibreOffice, AppFlowy, NocoDB, Odoo (Community), Plane, ERPNext || **๐ Communication & Collaboration** | Automate meeting scheduling, participant management, recording retrieval, and reporting through structured CLI | Zoom, Jitsi Meet, BigBlueButton, Mattermost |@@ -996,6 +996,13 @@ Each application received complete, production-ready CLI interfaces โ not demo<td align="center">โ 24</td></tr><tr>+<td align="center"><strong>๐ฆ <a href="sbox/agent-harness/">s&box</a></strong></td>+<td>Game Development</td>+<td><code>cli-anything-sbox</code></td>+<td>Source 2 game engine - direct file I/O on .scene/.prefab/.vmat/.vsnd JSON</td>+<td align="center">โ 222</td>+</tr>+<tr><td align="center"><strong>๐ <a href="lldb/agent-harness/">LLDB</a></strong></td><td>Native Debugging</td><td><code>cli-anything-lldb</code></td>@@ -1159,6 +1166,7 @@ cli-anything/โโโ ๐ก๏ธ adguardhome/agent-harness/ # AdGuard Home CLI (36 tests)โโโ ๐ฆ ollama/agent-harness/ # Ollama CLI (98 tests)โโโ ๐ฎ godot/agent-harness/ # Godot Engine CLI (24 tests)+โโโ ๐ฆ sbox/agent-harness/ # s&box CLI (222 tests: 155 unit + 17 orchestrator + 50 e2e)โโโ ๐จ sketch/agent-harness/ # Sketch CLI (19 tests, Node.js)โโโ ๐ฌ renderdoc/agent-harness/ # RenderDoc CLI (59 tests)โโโ ๐ฉ nsight-graphics/agent-harness/ # Nsight Graphics CLI (40 tests)diff --git a/README_CN.md b/README_CN.mdindex f66cca05b..61b996f70 100644--- a/README_CN.md+++ b/README_CN.md@@ -602,6 +602,13 @@ CLI-Anything ้็จไบไปปไฝๆไปฃ็ ๅบ็่ฝฏไปถ โโ ไธ้้ขๅ๏ผไธ้<td align="center">โ 50</td></tr><tr>+<td align="center"><strong>๐ฆ <a href="sbox/agent-harness/">s&box</a></strong></td>+<td>ๆธธๆๅผๅ</td>+<td><code>cli-anything-sbox</code></td>+<td>Source 2 ๆธธๆๅผๆ - ็ดๆฅ่ฏปๅ .scene/.prefab/.vmat/.vsnd JSON</td>+<td align="center">โ 222</td>+</tr>+<tr><td align="center"><strong>๐จ Sketch</strong></td><td>UI ่ฎพ่ฎก</td><td><code>sketch-cli</code></td>@@ -718,6 +725,7 @@ cli-anything/โโโ ๐ฉ nsight-graphics/agent-harness/ # Nsight Graphics CLI๏ผ40 ้กนๆต่ฏ๏ผโโโ ๐ lldb/agent-harness/ # LLDB CLI๏ผ27 ้กนๆต่ฏ๏ผโโโ ๐ unrealinsights/agent-harness/ # Unreal Insights CLI๏ผ50 ้กนๆต่ฏ๏ผ+โโโ ๐ฆ sbox/agent-harness/ # s&box CLI๏ผ222 ้กนๆต่ฏ: 155 ๅๅ + 17 orchestrator + 50 e2e๏ผโโโ ๐จ sketch/agent-harness/ # Sketch CLI๏ผ19 ้กนๆต่ฏ๏ผNode.js๏ผ```diff --git a/registry.json b/registry.jsonindex 7deef2280..b897af28a 100644--- a/registry.json+++ b/registry.json@@ -840,6 +840,25 @@}]},+ {+ "name": "sbox",+ "display_name": "s&box",+ "version": "1.0.0",+ "description": "Game engine project management for s&box (Source 2): scenes, prefabs, materials, sounds, codegen, asset graph, project validation",+ "requires": "s&box installed via Steam (sbox.game)",+ "homepage": "https://sbox.game",+ "source_url": null,+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=sbox/agent-harness",+ "entry_point": "cli-anything-sbox",+ "skill_md": "skills/cli-anything-sbox/SKILL.md",+ "category": "gamedev",+ "contributors": [+ {+ "name": "KarandeepSWranch",+ "url": "https://github.com/KarandeepSWranch"+ }+ ]+ },{"name": "dify-workflow","display_name": "Dify Workflow",diff --git a/sbox/agent-harness/SBOX.md b/sbox/agent-harness/SBOX.mdnew file mode 100644index 000000000..4d077dfda--- /dev/null+++ b/sbox/agent-harness/SBOX.md@@ -0,0 +1,184 @@+# SBOX.md - s&box CLI Harness SOP++## Software Overview++**s&box** is a C#-based game engine by Facepunch Studios, built on Valve's Source 2.+It uses a Scene -> GameObject -> Component architecture with built-in multiplayer,+hot-reload, and Razor UI. Games are published to sbox.game.++- **Engine:** Source 2 (.NET 10.0 / C# 14)+- **Editor:** `sbox-dev.exe` (GUI)+- **Server:** `sbox-server.exe` (headless, CLI-capable)+- **Standalone:** `sbox-standalone.exe`+- **Asset tools:** `resourcecompiler.exe`, `fbx2dmx.exe`, `obj2dmx.exe`++## File Formats++| Format | Type | Description |+|--------|------|-------------|+| `.sbproj` | JSON | Project manifest (title, type, metadata, packages) |+| `.scene` | JSON | Scene files (GameObjects, Components, SceneProperties) |+| `.prefab` | JSON | Prefab templates (same structure as scenes, single RootObject) |+| `Input.config` | JSON | Input action bindings (keyboard + gamepad) |+| `Collision.config` | JSON | Collision layers and pair rules |+| `.cs` | C# | Component source code |+| `.vmat` | Text | Material definitions |+| `.sound` | JSON | Sound event definitions |+| `.razor` | Razor | UI component files |++## Backend Integration++The CLI manipulates JSON project files directly and invokes s&box executables:++1. **Data layer:** Direct JSON manipulation of .sbproj, .scene, .prefab, configs+2. **Code generation:** Generate C# files following s&box component patterns+3. **Server backend:** `sbox-server.exe` for headless game server operations+4. **Editor launch:** `sbox-dev.exe` to open projects in the editor+5. **Asset compilation:** `resourcecompiler.exe` for asset pipeline++### Server CLI Commands (sbox-server.exe)++```+game <gameident> - load a game+game <gameident> <mapident> - load a game with a map+find <text> - find a concommand or convar+kick <id> - kick a player by name or steam id+status - current game status+quit - quit+```++## CLI Command Groups++```+cli-anything-sbox+โโโ project # .sbproj management+โ โโโ new # Create new s&box project+โ โโโ info # Show project metadata+โ โโโ config # Modify project settings+โ โโโ add-package # Add a package reference+โ โโโ remove-package # Remove a package reference+โ โโโ validate # Lint: broken refs, duplicate GUIDs, malformed inputs+โโโ scene # .scene file manipulation+โ โโโ new # Create new scene+โ โโโ info # Show scene contents+โ โโโ list # List GameObjects in scene+โ โโโ add-object # Add a GameObject+โ โโโ remove-object # Remove a GameObject+โ โโโ add-component # Add component to object+โ โโโ remove-component # Remove component from object+โ โโโ modify-object # Rename, move, scale, retag objects+โ โโโ modify-component # Modify a component's properties on an object+โ โโโ clone-object # Duplicate a GameObject+โ โโโ get-object # Inspect one GameObject in detail+โ โโโ set-property # Modify SceneProperties (tick rate, navmesh, etc.)+โ โโโ set-navmesh # Configure NavMesh properties+โ โโโ list-presets # List built-in component preset names+โ โโโ query # Find objects by component / tag / name / bounds / enabled+โ โโโ refs # Extract every asset reference (grouped by category)+โ โโโ bulk-modify # Apply same modification to all matching objects+โ โโโ diff # Structural diff between two scenes (Name-keyed)+โ โโโ instantiate-prefab # Insert a prefab as a new GameObject (PrefabSource ref)+โโโ prefab # .prefab management+โ โโโ new # Create new prefab+โ โโโ info # Show prefab contents+โ โโโ from-scene # Extract object from scene to prefab+โ โโโ add-component # Add component to prefab root+โ โโโ remove-component # Remove component from prefab+โ โโโ list # List prefabs in project+โ โโโ refs # Extract asset references from a prefab+โ โโโ modify-component # Modify a component's properties in a prefab+โ โโโ diff # Structural diff between two prefabs (root + children)+โโโ codegen # C# code generation+โ โโโ component # Generate component class (+ RPC stubs)+โ โโโ gameresource # Generate GameResource class+โ โโโ editor-menu # Generate editor menu class+โ โโโ razor # Generate Razor UI component + SCSS+โ โโโ class # Generate plain C# class+โ โโโ panel-component # Scaffold PanelComponent + sibling ScreenPanel pattern+โโโ input # Input.config management+โ โโโ list # List all input actions+โ โโโ add # Add input action+โ โโโ remove # Remove input action+โ โโโ set # Modify existing action+โโโ collision # Collision.config management+โ โโโ list # List layers and rules+โ โโโ add-layer # Add collision layer+โ โโโ add-rule # Add/modify collision rule+โ โโโ remove-rule # Remove collision pair rule+โ โโโ remove-layer # Remove a collision layer+โโโ material # .vmat material management+โ โโโ new # Create PBR material+โ โโโ info # Parse material properties+โ โโโ list # List project materials+โ โโโ set # Update material properties+โโโ sound # .sound event management+โ โโโ new # Create sound event+โ โโโ info # Show sound event details+โ โโโ list # List project sound events+โ โโโ set # Update sound event properties+โโโ localization # Translation file management+โ โโโ new # Create translation file+โ โโโ list # List translation keys+โ โโโ set # Set key-value pair+โ โโโ get # Get value by key+โ โโโ remove # Remove translation key+โ โโโ bulk-set # Set multiple keys from a JSON object+โโโ server # Dedicated server management+โ โโโ start # Launch sbox-server.exe+โ โโโ info # Show server executable path/version+โโโ asset # Asset listing, inspection, reference graph+โ โโโ list # List project assets by type+โ โโโ info # Show asset file details+โ โโโ compile # Compile asset via resourcecompiler.exe+โ โโโ find-refs # Reverse lookup: scenes/prefabs that reference an asset+โ โโโ find-unused # Project assets unreferenced by any scene/prefab+โ โโโ rename # Rename an asset and update every scene/prefab reference+โ โโโ move # Move an asset to a new path and update every reference+โโโ test # Map generation regression tests+โ โโโ setup # Verify paths, create test scene+โ โโโ run # Run map generation tests across strategy/size/seed+โโโ launch # Open project in s&box editor+โโโ session # State management+ โโโ status # Current session state+ โโโ undo # Undo last operation+ โโโ redo # Redo undone operation+```++## State Model++Session state (JSON file) tracks:+- Current project path (.sbproj)+- Open scene path+- Operation history (undo/redo stack)+- Modified flag++## Project Structure Created by CLI++```+<project_name>/+โโโ <project_name>.sbproj+โโโ .editorconfig+โโโ Assets/+โ โโโ scenes/+โ โโโ minimal.scene+โโโ Code/+โ โโโ Assembly.cs+โ โโโ MyComponent.cs+โโโ Editor/+โ โโโ Assembly.cs+โโโ Libraries/+โโโ Localization/+โโโ ProjectSettings/+ โโโ Input.config+ โโโ Collision.config+```++## Key Architectural Decisions++1. **JSON-first:** All s&box project files are JSON - no binary format manipulation needed+2. **GUID generation:** Every GameObject and Component needs a unique GUID (UUID v4)+3. **No runtime dependency on s&box editor** for file manipulation - the CLI reads/writes+ JSON directly. Only `server` and `launch` commands need the actual s&box installation.+4. **Code generation follows s&box conventions:** `sealed class` for non-networked,+ `partial class` for networked, `[Property]` attributes, Allman braces, tab indentation.+5. **Scene format stability:** Scene JSON format is well-defined with __guid, __type patterns.diff --git a/sbox/agent-harness/cli_anything/sbox/README.md b/sbox/agent-harness/cli_anything/sbox/README.mdnew file mode 100644index 000000000..c7d9e71ea--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/README.md@@ -0,0 +1,216 @@+# cli-anything-sbox++CLI harness for s&box game engine (Facepunch Studios, Source 2). 79 commands across 14 groups.++## Prerequisites++- Python 3.9++- s&box installed via Steam (auto-detected, or set `SBOX_PATH`)++## Installation++```bash+cd agent-harness/+pip install -e .+```++## Commands++### project - Manage projects++```bash+cli-anything-sbox project new --name MyGame --output-dir ./MyGame+cli-anything-sbox --json project info+cli-anything-sbox project config --max-players 32 --tick-rate 64+cli-anything-sbox --json --project ./MyGame project add-package facepunch.libsdf+cli-anything-sbox --json --project ./MyGame project remove-package facepunch.libsdf+# Project lint - find broken asset refs, duplicate GUIDs, malformed inputs+cli-anything-sbox --json --project ./MyGame project validate+cli-anything-sbox --project ./MyGame project validate --no-inputs --no-guids+```++### scene - Manipulate .scene files++```bash+cli-anything-sbox scene new --name gameplay -o ./Assets/scenes/gameplay.scene+cli-anything-sbox --json scene info ./Assets/scenes/minimal.scene+cli-anything-sbox --json scene list ./Assets/scenes/minimal.scene+cli-anything-sbox scene add-object ./scene.scene Enemy --position "100,0,0" --components "model,box_collider,rigidbody" --tags "enemy"+cli-anything-sbox scene remove-object ./scene.scene --name Enemy+cli-anything-sbox scene add-component ./scene.scene <guid> Sandbox.PointLight+cli-anything-sbox scene remove-component ./scene.scene <guid> --component-type Sandbox.Rigidbody+cli-anything-sbox --json scene modify-object ./scene.scene --guid <guid> --name NewName --position "200,0,0"+cli-anything-sbox --json scene clone-object ./scene.scene --name Enemy --new-name EnemyCopy --position "300,0,0"+cli-anything-sbox --json scene get-object ./scene.scene --name Sun+cli-anything-sbox scene set-property ./scene.scene --fixed-update-freq 64 --timescale 0.5+cli-anything-sbox scene set-navmesh ./scene.scene --enabled --agent-height 72 --agent-radius 16+cli-anything-sbox --json scene list-presets+# Find objects matching one or more filters (AND-combined)+cli-anything-sbox --json scene query ./scene.scene --has-component rigidbody --has-tag tower+cli-anything-sbox --json scene query ./scene.scene --name-regex "^Tower\d$" --in-bounds "0,-500,-50,1000,500,50"+# Extract every asset reference (.vmdl, .vmat, .vsnd, .vtex, .vpcf, .prefab) from a scene+cli-anything-sbox --json scene refs ./scene.scene+# Apply the same modification to every object that matches a query+cli-anything-sbox --json scene bulk-modify ./scene.scene --has-tag tower --position "0,0,100" --enable+# Structural diff between two scenes (added/removed/modified GameObjects + SceneProperties)+cli-anything-sbox --json scene diff ./old.scene ./new.scene+# Insert a prefab as a GameObject in a scene+cli-anything-sbox --json scene instantiate-prefab ./level.scene ./Assets/prefabs/bullet.prefab --position "10,0,0"+```++### prefab - Manage .prefab files++```bash+cli-anything-sbox prefab new --name Bullet -o ./Assets/prefabs/bullet.prefab --components "model,sphere_collider,rigidbody"+cli-anything-sbox --json prefab info ./Assets/prefabs/bullet.prefab+cli-anything-sbox prefab from-scene ./scene.scene <guid> -o ./Assets/prefabs/extracted.prefab+cli-anything-sbox --json prefab add-component ./prefab.prefab rigidbody+cli-anything-sbox prefab remove-component ./prefab.prefab --component-type Sandbox.Rigidbody+# Extract asset references from a prefab+cli-anything-sbox --json prefab refs ./prefab.prefab+# Modify a component's properties on a prefab+cli-anything-sbox --json prefab modify-component ./prefab.prefab --component-type Sandbox.Rigidbody --properties '{"Gravity":false,"MassOverride":50}'+# Structural diff between two prefabs (root + children by Name)+cli-anything-sbox --json prefab diff ./old.prefab ./new.prefab+```++### codegen - Generate C# code++```bash+# Component+cli-anything-sbox codegen component --name PlayerController --methods OnUpdate,OnFixedUpdate -o ./Code/PlayerController.cs+cli-anything-sbox --json codegen component --name Tower --properties '[{"name":"Damage","type":"float","default":"25f"}]'++# Networked component with RPC+cli-anything-sbox codegen component --name NetPlayer --networked --rpc-methods "Fire:Broadcast,Die:Host" -o ./Code/NetPlayer.cs++# GameResource+cli-anything-sbox codegen gameresource --name TowerData --display-name "Tower Data" --extension tower -o ./Code/TowerData.cs++# Editor menu+cli-anything-sbox codegen editor-menu --name MyTools --menu-path "Editor/My Tools/Open" -o ./Editor/MyTools.cs++# Razor UI component (generates .razor + .razor.scss)+cli-anything-sbox codegen razor --name HudPanel --properties '[{"name":"Score","type":"int","default":"0"}]' -o ./UI/HudPanel.razor++# PanelComponent + sibling ScreenPanel scaffold (handles the s&box gotcha+# where input only works when both are on the same GameObject).+# Emits .razor + .razor.scss + a paste-ready GameObject snippet, or appends+# directly to a scene with --scene.+cli-anything-sbox --json codegen panel-component --name HudBar -o ./UI/HudBar.razor+cli-anything-sbox codegen panel-component --name Crosshair -o ./UI/Crosshair.razor --scene ./Assets/scenes/game.scene+```++### input - Manage Input.config++```bash+cli-anything-sbox --json input list+cli-anything-sbox input add --name PlaceTower --group Gameplay --keyboard mouse1 --gamepad RightTrigger+cli-anything-sbox input remove --name PlaceTower+cli-anything-sbox input set --name Attack1 --keyboard mouse1+```++### collision - Manage Collision.config++```bash+cli-anything-sbox --json collision list+cli-anything-sbox collision add-layer --name projectile --default Collide+cli-anything-sbox collision add-rule --layer-a projectile --layer-b solid --result Collide+cli-anything-sbox collision remove-rule --layer-a projectile --layer-b solid+cli-anything-sbox collision remove-layer --name projectile+```++### material - Manage .vmat materials++```bash+cli-anything-sbox --json material new --name floor --shader complex --color-texture "textures/floor.tga" --metalness 0.3 -o ./Assets/materials/floor.vmat+cli-anything-sbox --json material info ./Assets/materials/floor.vmat+cli-anything-sbox --json material list+cli-anything-sbox --json material set ./Assets/materials/floor.vmat --metalness 0.8+```++### sound - Manage .sound events++```bash+cli-anything-sbox --json sound new --name gunshot --sounds "sounds/gun1.vsnd,sounds/gun2.vsnd" --volume 0.8 -o ./Assets/sounds/gunshot.sound+cli-anything-sbox --json sound info ./Assets/sounds/gunshot.sound+cli-anything-sbox --json sound list+cli-anything-sbox --json sound set ./Assets/sounds/gunshot.sound --volume 0.5+```++### localization - Manage translations++```bash+cli-anything-sbox localization new --lang en -o ./Localization/en.json+cli-anything-sbox localization set ./Localization/en.json --key "game.title" --value "My Game"+cli-anything-sbox --json localization list ./Localization/en.json+cli-anything-sbox localization get ./Localization/en.json --key "game.title"+cli-anything-sbox localization remove ./Localization/en.json --key "game.title"+```++### server - Dedicated server++```bash+cli-anything-sbox server info+cli-anything-sbox server start --game my_game --map facepunch.flatgrass+```++### asset - Asset management++```bash+cli-anything-sbox --json asset list --type scene+cli-anything-sbox --json asset info ./Assets/scenes/minimal.scene+cli-anything-sbox asset compile ./Assets/materials/floor.vmat+# Reverse lookup: which scenes/prefabs reference an asset?+cli-anything-sbox --json --project ./MyGame asset find-refs models/myteam/widget.vmdl+# Find unreferenced assets (per type or across all referenceable types)+cli-anything-sbox --json --project ./MyGame asset find-unused+cli-anything-sbox --json --project ./MyGame asset find-unused --type model --type material+# Rename an asset and update every scene/prefab reference (extension preserved if omitted)+cli-anything-sbox --json --project ./MyGame asset rename models/team/widget.vmdl gizmo+cli-anything-sbox --project ./MyGame asset rename models/team/widget.vmdl gizmo --dry-run+# Move an asset across directories and update every reference+cli-anything-sbox --json --project ./MyGame asset move models/team/widget.vmdl models/shared/widget.vmdl+```++### session - State management++```bash+cli-anything-sbox session status+cli-anything-sbox session undo+cli-anything-sbox session redo+```++### launch - Open in editor++```bash+cli-anything-sbox launch+```++## REPL Mode++Run with no arguments for interactive mode:++```bash+cli-anything-sbox+```++Type `help` for commands, `quit` to exit.++## JSON Output++Pass `--json` for machine-readable output (for AI agents):++```bash+cli-anything-sbox --json scene list ./Assets/scenes/minimal.scene+```++## 29 Component Presets++Use with `--components` on scene/prefab commands: `model`, `box_collider`, `sphere_collider`, `rigidbody`, `camera`, `light_directional`, `light_point`, `spot_light`, `ambient_light`, `player_controller`, `capsule_collider`, `plane_collider`, `model_collider`, `sprite_renderer`, `skinned_model_renderer`, `text_renderer`, `line_renderer`, `decal_renderer`, `particle_effect`, `sound_point`, `nav_mesh_agent`, `screen_panel`, `world_panel`, `fixed_joint`, `hinge_joint`, `spring_joint`, `ball_socket_joint`, `trail_renderer`, `character_controller`.++## Environment Variables++| Variable | Description | Default |+|----------|-------------|---------|+| `SBOX_PATH` | s&box installation directory | Auto-detected from Steam |diff --git a/sbox/agent-harness/cli_anything/sbox/__init__.py b/sbox/agent-harness/cli_anything/sbox/__init__.pynew file mode 100644index 000000000..edd70b299--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/__init__.py@@ -0,0 +1,3 @@+"""cli-anything-sbox - CLI harness for s&box game engine."""++__version__ = "1.0.0"diff --git a/sbox/agent-harness/cli_anything/sbox/__main__.py b/sbox/agent-harness/cli_anything/sbox/__main__.pynew file mode 100644index 000000000..948c2c744--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/__main__.py@@ -0,0 +1,5 @@+"""Allow running as python -m cli_anything.sbox"""+from cli_anything.sbox.sbox_cli import main++if __name__ == "__main__":+ main()diff --git a/sbox/agent-harness/cli_anything/sbox/core/__init__.py b/sbox/agent-harness/cli_anything/sbox/core/__init__.pynew file mode 100644index 000000000..4df0f5c03--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/__init__.py@@ -0,0 +1 @@+# core modules for s&box CLI harnessdiff --git a/sbox/agent-harness/cli_anything/sbox/core/codegen.py b/sbox/agent-harness/cli_anything/sbox/core/codegen.pynew file mode 100644index 000000000..2becfeb3f--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/codegen.py@@ -0,0 +1,606 @@+"""C# code generation following s&box engine conventions.++Generates component classes, GameResource classes, and editor menu classes+with proper s&box code style: Allman braces, tab indentation, spaces inside+parentheses, and correct attribute usage.+"""++from typing import Optional+++def generate_component(+ class_name: str,+ properties: Optional[list[dict]] = None,+ lifecycle_methods: Optional[list[str]] = None,+ interfaces: Optional[list[str]] = None,+ is_networked: bool = False,+ namespace: Optional[str] = None,+ rpc_methods: Optional[list[dict]] = None,+) -> dict:+ """Generate a C# component class file.++ Args:+ class_name: PascalCase name, e.g. "PlayerController".+ properties: List of dicts with keys:+ name (str), type (str), default (str|None),+ category (str|None), range_min (float|None), range_max (float|None).+ Type examples: "float", "int", "string", "GameObject", "Vector3", "Model".+ lifecycle_methods: Method names to override, e.g. ["OnUpdate", "OnFixedUpdate", "OnStart"].+ interfaces: Interface list, e.g. ["Component.ITriggerListener", "Component.IDamageable"].+ is_networked: If True the class is partial (not sealed) and properties get [Sync].+ namespace: Optional namespace wrapper.+ rpc_methods: List of dicts with 'name' (str) and 'type' (str: 'Broadcast',+ 'Host', or 'Owner'). Forces is_networked=True when provided.++ Returns:+ Dict with keys: filename, content, class_name.+ """+ properties = properties or []+ lifecycle_methods = lifecycle_methods or []+ interfaces = interfaces or []+ rpc_methods = rpc_methods or []++ # RPC methods require networking support+ if rpc_methods:+ is_networked = True++ lines: list[str] = []+ lines.append( "using Sandbox;" )+ lines.append( "" )++ # Namespace open+ if namespace:+ lines.append( f"namespace {namespace}" )+ lines.append( "{" )++ indent = "\t" if namespace else ""++ # Class declaration+ modifier = "partial" if is_networked else "sealed"+ base_parts = ["Component"] + interfaces+ base = ", ".join( base_parts )+ lines.append( f"{indent}public {modifier} class {class_name} : {base}" )+ lines.append( f"{indent}{{" )++ # Properties+ for prop in properties:+ prop_str = _format_property( prop, is_networked=is_networked )+ for pline in prop_str.split( "\n" ):+ lines.append( f"{indent}\t{pline}" )++ # Blank line between properties and methods+ if properties and lifecycle_methods:+ lines.append( "" )++ # Lifecycle methods+ for i, method_name in enumerate( lifecycle_methods ):+ body = ""+ if is_networked and method_name == "OnFixedUpdate":+ body = "if ( IsProxy ) return;"+ method_str = _format_method( method_name, body=body )+ for mline in method_str.split( "\n" ):+ lines.append( f"{indent}\t{mline}" )+ if i < len( lifecycle_methods ) - 1:+ lines.append( "" )++ # RPC method stubs+ if rpc_methods:+ if lifecycle_methods:+ lines.append( "" )+ for j, rpc in enumerate( rpc_methods ):+ rpc_str = _format_rpc_method( rpc )+ for rline in rpc_str.split( "\n" ):+ lines.append( f"{indent}\t{rline}" )+ if j < len( rpc_methods ) - 1:+ lines.append( "" )++ lines.append( f"{indent}}}" )++ # Namespace close+ if namespace:+ lines.append( "}" )++ lines.append( "" )+ content = "\r\n".join( lines )++ return {+ "filename": f"{class_name}.cs",+ "content": content,+ "class_name": class_name,+ }+++def generate_gameresource(+ class_name: str,+ display_name: str,+ extension: str,+ description: str = "",+ properties: Optional[list[dict]] = None,+ namespace: Optional[str] = None,+) -> dict:+ """Generate a GameResource class.++ Args:+ class_name: PascalCase name, e.g. "TowerData".+ display_name: Human-readable name shown in editor, e.g. "Tower Data".+ extension: File extension for the resource, e.g. "tower".+ description: Short description of the resource.+ properties: List of property dicts (same format as generate_component).+ namespace: Optional namespace wrapper.++ Returns:+ Dict with keys: filename, content, class_name.+ """+ properties = properties or []++ lines: list[str] = []+ lines.append( "using Sandbox;" )+ lines.append( "" )++ if namespace:+ lines.append( f"namespace {namespace}" )+ lines.append( "{" )++ indent = "\t" if namespace else ""++ # GameResource attribute+ lines.append( f'{indent}[GameResource( "{display_name}", "{extension}", "{description}" )]' )+ lines.append( f"{indent}public class {class_name} : GameResource" )+ lines.append( f"{indent}{{" )++ for prop in properties:+ prop_str = _format_property( prop, is_networked=False )+ for pline in prop_str.split( "\n" ):+ lines.append( f"{indent}\t{pline}" )++ lines.append( f"{indent}}}" )++ if namespace:+ lines.append( "}" )++ lines.append( "" )+ content = "\r\n".join( lines )++ return {+ "filename": f"{class_name}.cs",+ "content": content,+ "class_name": class_name,+ }+++def generate_editor_menu(+ class_name: str,+ menu_path: str,+ method_name: str = "OpenMenu",+ dialog_title: str = "",+ dialog_message: str = "",+) -> dict:+ """Generate an editor menu class.++ Args:+ class_name: PascalCase name, e.g. "MyEditorTool".+ menu_path: Menu path string, e.g. "Tools/My Tool".+ method_name: Name of the static method, default "OpenMenu".+ dialog_title: Title for the editor dialog (optional).+ dialog_message: Message for the editor dialog (optional).++ Returns:+ Dict with keys: filename, content, class_name.+ """+ lines: list[str] = []+ lines.append( "using Editor;" )+ lines.append( "using Sandbox;" )+ lines.append( "" )++ lines.append( f"public static class {class_name}" )+ lines.append( "{" )++ lines.append( f'\t[Menu( "Editor", "{menu_path}" )]' )+ lines.append( f"\tpublic static void {method_name}()" )+ lines.append( "\t{" )++ if dialog_title or dialog_message:+ title = dialog_title or class_name+ message = dialog_message or ""+ lines.append( f'\t\tEditorUtility.DisplayDialog( "{title}", "{message}" );' )+ else:+ lines.append( f'\t\tLog.Info( "{class_name}.{method_name} invoked" );' )++ lines.append( "\t}" )+ lines.append( "}" )+ lines.append( "" )+ content = "\r\n".join( lines )++ return {+ "filename": f"{class_name}.cs",+ "content": content,+ "class_name": class_name,+ }+++def generate_razor(+ class_name: str,+ inherits: str = "PanelComponent",+ properties: Optional[list[dict]] = None,+ root_class: Optional[str] = None,+ namespace: Optional[str] = None,+) -> dict:+ """Generate a Razor UI component (.razor) and its stylesheet (.razor.scss).++ Args:+ class_name: PascalCase name, e.g. "HudPanel".+ inherits: Base class - "PanelComponent", "Panel", etc.+ properties: List of property dicts with 'name' and 'type' keys.+ root_class: CSS class for root element. Defaults to kebab-case of class_name.+ namespace: Optional namespace.++ Returns:+ Dict with filename, content, class_name, scss_filename, scss_content.+ """+ if properties is None:+ properties = []+ if root_class is None:+ # Convert PascalCase to kebab-case+ import re+ root_class = re.sub( r"(?<!^)(?=[A-Z])", "-", class_name ).lower()++ # Build .razor content+ lines = []+ lines.append( "@using Sandbox;" )+ lines.append( "@using Sandbox.UI;" )+ if namespace:+ lines.append( f"@namespace {namespace}" )+ lines.append( f"@inherits {inherits}" )+ lines.append( "" )+ lines.append( f'<root class="{root_class}">' )+ lines.append( '\t<div class="content">' )+ lines.append( "\t</div>" )+ lines.append( "</root>" )+ lines.append( "" )+ lines.append( "@code" )+ lines.append( "{" )++ # Properties+ for prop in properties:+ pname = prop.get( "name", "MyProperty" )+ ptype = prop.get( "type", "string" )+ pdefault = prop.get( "default", None )+ default_str = f" = {pdefault};" if pdefault is not None else ";"+ lines.append( f"\t[Property] public {ptype} {pname} {{ get; set; }}{default_str}" )++ if properties:+ lines.append( "" )++ # BuildHash+ if properties:+ prop_names = [p.get( "name", "MyProperty" ) for p in properties]+ # System.HashCode.Combine supports up to 8 args+ if len( prop_names ) <= 8:+ hash_args = ", ".join( prop_names )+ lines.append( f"\tprotected override int BuildHash() => System.HashCode.Combine( {hash_args} );" )+ else:+ # Chain for more than 8+ lines.append( "\tprotected override int BuildHash()" )+ lines.append( "\t{" )+ lines.append( "\t\tvar hash = new System.HashCode();" )+ for pname in prop_names:+ lines.append( f"\t\thash.Add( {pname} );" )+ lines.append( "\t\treturn hash.ToHashCode();" )+ lines.append( "\t}" )++ lines.append( "}" )+ lines.append( "" )++ content = "\r\n".join( lines )++ # Build .razor.scss content+ scss_lines = []+ scss_lines.append( f".{root_class}" )+ scss_lines.append( "{" )+ scss_lines.append( "\tposition: absolute;" )+ scss_lines.append( "\twidth: 100%;" )+ scss_lines.append( "\theight: 100%;" )+ scss_lines.append( "\tpointer-events: none;" )+ scss_lines.append( "" )+ scss_lines.append( "\t> .content" )+ scss_lines.append( "\t{" )+ scss_lines.append( "\t\tflex-direction: column;" )+ scss_lines.append( "\t}" )+ scss_lines.append( "}" )+ scss_lines.append( "" )++ scss_content = "\r\n".join( scss_lines )++ razor_filename = f"{class_name}.razor"+ scss_filename = f"{class_name}.razor.scss"++ return {+ "filename": razor_filename,+ "content": content,+ "class_name": class_name,+ "scss_filename": scss_filename,+ "scss_content": scss_content,+ }+++def _format_property( prop: dict, is_networked: bool = False ) -> str:+ """Format a single C# property with attributes.++ Args:+ prop: Dict with keys: name, type, and optionally default, category,+ range_min, range_max.+ is_networked: If True, adds [Sync] attribute before [Property].++ Returns:+ Multi-line string (no leading/trailing blank lines) with the+ attribute(s) and auto-property declaration.+ """+ name: str = prop["name"]+ prop_type: str = prop["type"]+ default = prop.get( "default" )+ category = prop.get( "category" )+ range_min = prop.get( "range_min" )+ range_max = prop.get( "range_max" )++ lines: list[str] = []++ # Sync attribute for networked properties (always on its own line)+ # NetList and NetDictionary are self-syncing - skip [Sync] for them+ if is_networked and not prop_type.startswith( "NetList<" ) and not prop_type.startswith( "NetDictionary<" ):+ lines.append( "[Sync]" )++ # Property attribute with optional modifiers+ attr_inner_parts: list[str] = []+ if category:+ attr_inner_parts.append( f'Category = "{category}"' )+ if range_min is not None and range_max is not None:+ attr_inner_parts.append( f"MinMax( {range_min}, {range_max} )" )++ has_extra_attrs = bool( attr_inner_parts )++ if has_extra_attrs:+ attr_inner = ", ".join( attr_inner_parts )+ prop_attr = f"[Property( {attr_inner} )]"+ else:+ prop_attr = "[Property]"++ # Build the property declaration+ default_str = ""+ if default is not None:+ default_str = f" = {default};"++ decl = f"public {prop_type} {name} {{ get; set; }}{default_str}"++ # Simple properties: attribute and declaration on one line+ # Complex properties (extra attrs or networked): attribute on separate line+ if is_networked or has_extra_attrs:+ lines.append( prop_attr )+ lines.append( decl )+ else:+ lines.append( f"{prop_attr} {decl}" )++ return "\n".join( lines )+++def _format_method(+ name: str,+ body: str = "",+ params: str = "",+ return_type: str = "void",+ is_override: bool = True,+) -> str:+ """Format a C# method with proper s&box style.++ Args:+ name: Method name, e.g. "OnUpdate".+ body: Method body lines (newline-separated). Empty string for empty body.+ params: Parameter list string, e.g. "float delta, int count".+ return_type: Return type, default "void".+ is_override: If True, uses "protected override" modifier.++ Returns:+ Multi-line string with the full method definition using Allman braces.+ """+ modifier = "protected override" if is_override else "public"+ signature = f"{modifier} {return_type} {name}( {params} )" if params else f"{modifier} {return_type} {name}()"++ lines: list[str] = []+ lines.append( signature )+ lines.append( "{" )++ if body:+ for bline in body.split( "\n" ):+ lines.append( f"\t{bline}" )++ lines.append( "}" )++ return "\n".join( lines )+++def _format_rpc_method( rpc: dict ) -> str:+ """Format an RPC method stub with the appropriate attribute.++ Args:+ rpc: Dict with 'name' (str) and 'type' (str: 'Broadcast', 'Host', or 'Owner').+ """+ rpc_type = rpc.get( "type", "Broadcast" )+ name = rpc.get( "name", "RpcMethod" )++ attr = f"[Rpc.{rpc_type}]"+ lines = []+ lines.append( f"{attr}" )+ lines.append( f"public void {name}()" )+ lines.append( "{" )+ lines.append( "}" )+ return "\n".join( lines )+++def generate_panel_component(+ class_name: str,+ properties: Optional[list[dict]] = None,+ namespace: Optional[str] = None,+ z_index: int = 100,+ opacity: float = 1.0,+ root_class: Optional[str] = None,+) -> dict:+ """Scaffold a Razor PanelComponent intended to live on the same GameObject+ as a ScreenPanel.++ s&box quirk (see project CLAUDE.md): ``PanelComponent`` input only works+ when both ``ScreenPanel`` and the ``PanelComponent`` are on the same+ ``GameObject``. This generator emits the .razor + .razor.scss pair *and*+ a ready-to-paste partial scene snippet that wires both components onto the+ same GameObject with the correct GUIDs.++ Args:+ class_name: PascalCase name, e.g. "HudPanel".+ properties: Optional list of [Property] dicts (same shape as generate_razor).+ namespace: Optional namespace for the .razor.+ z_index: ScreenPanel ZIndex value (defaults to 100).+ opacity: ScreenPanel Opacity (defaults to 1.0).+ root_class: CSS class for root element (defaults to kebab-case).++ Returns:+ Dict with: filename, content, scss_filename, scss_content,+ scene_snippet (str - ready-to-paste GameObject JSON), class_name.+ """+ import json as _json+ import uuid as _uuid++ razor = generate_razor(+ class_name=class_name,+ inherits="PanelComponent",+ properties=properties,+ root_class=root_class,+ namespace=namespace,+ )++ screen_panel_guid = str( _uuid.uuid4() )+ panel_comp_guid = str( _uuid.uuid4() )+ object_guid = str( _uuid.uuid4() )+ type_name = f"{namespace}.{class_name}" if namespace else class_name++ snippet_obj = {+ "__guid": object_guid,+ "Flags": 0,+ "Name": class_name,+ "Enabled": True,+ "Position": "0,0,0",+ "Rotation": "0,0,0,1",+ "Scale": "1,1,1",+ "Tags": "",+ "Components": [+ {+ "__guid": screen_panel_guid,+ "__type": "Sandbox.ScreenPanel",+ "ZIndex": z_index,+ "Opacity": opacity,+ },+ {+ "__guid": panel_comp_guid,+ "__type": type_name,+ },+ ],+ "Children": [],+ }+ scene_snippet = _json.dumps( snippet_obj, indent=2 )++ return {+ "filename": razor["filename"],+ "content": razor["content"],+ "scss_filename": razor["scss_filename"],+ "scss_content": razor["scss_content"],+ "scene_snippet": scene_snippet,+ "class_name": class_name,+ "screen_panel_guid": screen_panel_guid,+ "panel_component_guid": panel_comp_guid,+ "object_guid": object_guid,+ }+++def generate_class(+ class_name: str,+ base_class: Optional[str] = None,+ is_static: bool = False,+ properties: Optional[list[dict]] = None,+ methods: Optional[list[dict]] = None,+ namespace: Optional[str] = None,+) -> dict:+ """Generate a plain C# class (not a Component subclass).++ Args:+ class_name: PascalCase name.+ base_class: Optional base class to inherit from.+ is_static: If True, generates a static class (no instantiation).+ properties: List of dicts with name, type, default keys.+ methods: List of dicts with name, return_type, params, body, is_static keys.+ namespace: Optional namespace wrapper.++ Returns:+ Dict with filename, content, class_name.+ """+ if properties is None:+ properties = []+ if methods is None:+ methods = []++ lines = []+ lines.append( "using Sandbox;" )+ lines.append( "" )++ indent = ""+ if namespace:+ lines.append( f"namespace {namespace}" )+ lines.append( "{" )+ indent = "\t"++ # Class declaration+ static_kw = "static " if is_static else ""+ if base_class:+ lines.append( f"{indent}public {static_kw}class {class_name} : {base_class}" )+ else:+ lines.append( f"{indent}public {static_kw}class {class_name}" )+ lines.append( f"{indent}{{" )++ # Properties+ for prop in properties:+ pname = prop.get( "name", "MyProperty" )+ ptype = prop.get( "type", "string" )+ pdefault = prop.get( "default", None )+ static_prop = "static " if is_static else ""+ if pdefault is not None:+ lines.append( f"{indent}\tpublic {static_prop}{ptype} {pname} {{ get; set; }} = {pdefault};" )+ else:+ lines.append( f"{indent}\tpublic {static_prop}{ptype} {pname} {{ get; set; }}" )++ if properties and methods:+ lines.append( "" )++ # Methods+ for method in methods:+ mname = method.get( "name", "DoSomething" )+ mreturn = method.get( "return_type", "void" )+ mparams = method.get( "params", "" )+ mbody = method.get( "body", "" )+ mstatic = "static " if method.get( "is_static", is_static ) else ""+ lines.append( f"{indent}\tpublic {mstatic}{mreturn} {mname}( {mparams} )" )+ lines.append( f"{indent}\t{{" )+ if mbody:+ for bline in mbody.split( "\\n" ):+ lines.append( f"{indent}\t\t{bline}" )+ lines.append( f"{indent}\t}}" )++ lines.append( f"{indent}}}" )++ if namespace:+ lines.append( "}" )++ lines.append( "" )++ content = "\r\n".join( lines )++ return {+ "filename": f"{class_name}.cs",+ "content": content,+ "class_name": class_name,+ }diff --git a/sbox/agent-harness/cli_anything/sbox/core/collision_config.py b/sbox/agent-harness/cli_anything/sbox/core/collision_config.pynew file mode 100644index 000000000..745a83051--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/collision_config.py@@ -0,0 +1,233 @@+"""Manages s&box ProjectSettings/Collision.config files.++Provides functions to load, save, query, and modify collision layers and+pair rules in the s&box Collision.config JSON format.+"""++import json+import uuid+from typing import Optional++# Built-in layers that cannot be removed+BUILTIN_LAYERS = frozenset( {"solid", "trigger", "ladder", "water"} )++# Valid collision results+VALID_RESULTS = frozenset( {"Collide", "Trigger", "Ignore"} )+++def load_collision_config( config_path: str ) -> dict:+ """Load Collision.config JSON from disk.++ Args:+ config_path: Absolute path to the Collision.config file.++ Returns:+ Parsed JSON dict.+ """+ with open( config_path, "r", encoding="utf-8" ) as f:+ return json.load( f )+++def save_collision_config( config_path: str, data: dict ) -> None:+ """Save Collision.config JSON to disk.++ Args:+ config_path: Absolute path to the Collision.config file.+ data: The full config dict to write.+ """+ with open( config_path, "w", encoding="utf-8" ) as f:+ json.dump( data, f, indent=2 )+ f.write( "\n" )+++def list_layers( config_path: str ) -> dict:+ """Return dict of layers and their defaults, plus pair rules.++ Args:+ config_path: Absolute path to the Collision.config file.++ Returns:+ Dict with "defaults" (layer name -> default behavior) and+ "pairs" (list of pair rule dicts with a, b, r keys).+ """+ data = load_collision_config( config_path )+ return {+ "defaults": data.get( "Defaults", {} ),+ "pairs": data.get( "Pairs", [] ),+ }+++def add_layer(+ config_path: str,+ name: str,+ default: str = "Collide",+) -> dict:+ """Add a new collision layer with its default behavior.++ Args:+ config_path: Absolute path to the Collision.config file.+ name: Layer name, e.g. "projectile".+ default: Default collision behavior - "Collide", "Trigger", or "Ignore".++ Returns:+ The updated defaults dict.++ Raises:+ ValueError: If default is not a valid result or layer already exists.+ """+ if default not in VALID_RESULTS:+ raise ValueError( f"Invalid default '{default}'. Must be one of: {', '.join( sorted( VALID_RESULTS ) )}" )++ data = load_collision_config( config_path )+ defaults = data.get( "Defaults", {} )++ if name in defaults:+ raise ValueError( f"Layer '{name}' already exists" )++ defaults[name] = default+ data["Defaults"] = defaults+ save_collision_config( config_path, data )+ return defaults+++def remove_layer( config_path: str, name: str ) -> bool:+ """Remove a collision layer and all its pair rules.++ Cannot remove built-in layers: solid, trigger, ladder, water.++ Args:+ config_path: Absolute path to the Collision.config file.+ name: Layer name to remove.++ Returns:+ True if the layer was found and removed, False if it did not exist.++ Raises:+ ValueError: If attempting to remove a built-in layer.+ """+ if name in BUILTIN_LAYERS:+ raise ValueError( f"Cannot remove built-in layer '{name}'" )++ data = load_collision_config( config_path )+ defaults = data.get( "Defaults", {} )++ if name not in defaults:+ return False++ del defaults[name]+ data["Defaults"] = defaults++ # Remove any pair rules referencing this layer+ pairs = data.get( "Pairs", [] )+ data["Pairs"] = [p for p in pairs if p["a"] != name and p["b"] != name]++ save_collision_config( config_path, data )+ return True+++def add_rule(+ config_path: str,+ layer_a: str,+ layer_b: str,+ result: str = "Collide",+) -> dict:+ """Add or update a collision pair rule.++ If a rule for the given pair already exists (in either order), it is updated.++ Args:+ config_path: Absolute path to the Collision.config file.+ layer_a: First layer name.+ layer_b: Second layer name.+ result: Collision result - "Collide", "Trigger", or "Ignore".++ Returns:+ The pair rule dict that was added or updated.++ Raises:+ ValueError: If result is not valid.+ """+ if result not in VALID_RESULTS:+ raise ValueError( f"Invalid result '{result}'. Must be one of: {', '.join( sorted( VALID_RESULTS ) )}" )++ data = load_collision_config( config_path )+ pairs = data.get( "Pairs", [] )++ # Check for existing rule in either order+ for pair in pairs:+ if ( pair["a"] == layer_a and pair["b"] == layer_b ) or \+ ( pair["a"] == layer_b and pair["b"] == layer_a ):+ pair["r"] = result+ data["Pairs"] = pairs+ save_collision_config( config_path, data )+ return pair++ # Create new rule+ new_rule = {"a": layer_a, "b": layer_b, "r": result}+ pairs.append( new_rule )+ data["Pairs"] = pairs+ save_collision_config( config_path, data )+ return new_rule+++def remove_rule( config_path: str, layer_a: str, layer_b: str ) -> bool:+ """Remove a collision pair rule.++ Matches the pair in either order.++ Args:+ config_path: Absolute path to the Collision.config file.+ layer_a: First layer name.+ layer_b: Second layer name.++ Returns:+ True if a matching rule was found and removed, False otherwise.+ """+ data = load_collision_config( config_path )+ pairs = data.get( "Pairs", [] )+ original_len = len( pairs )++ data["Pairs"] = [+ p for p in pairs+ if not (+ ( p["a"] == layer_a and p["b"] == layer_b ) or+ ( p["a"] == layer_b and p["b"] == layer_a )+ )+ ]++ if len( data["Pairs"] ) < original_len:+ save_collision_config( config_path, data )+ return True++ return False+++def get_default_collision_config() -> dict:+ """Return the default s&box Collision.config.++ Includes the standard layers (solid, world, trigger, ladder, water,+ playerclip) and the default pair rules.++ Returns:+ A complete Collision.config dict ready to be saved.+ """+ return {+ "Version": 2,+ "Defaults": {+ "solid": "Collide",+ "world": "Collide",+ "trigger": "Trigger",+ "ladder": "Ignore",+ "water": "Trigger",+ },+ "Pairs": [+ {"a": "solid", "b": "solid", "r": "Collide"},+ {"a": "trigger", "b": "playerclip", "r": "Ignore"},+ {"a": "trigger", "b": "solid", "r": "Trigger"},+ {"a": "playerclip", "b": "solid", "r": "Collide"},+ ],+ "__guid": str( uuid.uuid4() ),+ "__schema": "configdata",+ "__type": "CollisionRules",+ "__version": 2,+ }diff --git a/sbox/agent-harness/cli_anything/sbox/core/export.py b/sbox/agent-harness/cli_anything/sbox/core/export.pynew file mode 100644index 000000000..76c30fe5c--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/export.py@@ -0,0 +1,552 @@+"""Asset listing and project export utilities for s&box projects."""++import json+import os+from pathlib import Path+from typing import Any, Dict, List, Optional+++# ---------------------------------------------------------------------------+# Asset extension mapping+# ---------------------------------------------------------------------------++ASSET_EXTENSIONS: Dict[str, List[str]] = {+ "scene": [".scene"],+ "prefab": [".prefab"],+ "material": [".vmat"],+ "model": [".vmdl"],+ "sound": [".sound"],+ "texture": [".vtex", ".png", ".jpg", ".tga"],+ "shader": [".shader", ".shader_c"],+ "razor": [".razor"],+ "code": [".cs"],+}++# Build a reverse lookup: extension -> asset type+_EXT_TO_TYPE: Dict[str, str] = {}+for _type_name, _exts in ASSET_EXTENSIONS.items():+ for _ext in _exts:+ _EXT_TO_TYPE[_ext] = _type_name+++def _classify_asset( file_path: str ) -> str:+ """Classify an asset file by its extension.++ Returns the asset type string (e.g. 'scene', 'model') or 'other'.+ """+ _, ext = os.path.splitext( file_path )+ return _EXT_TO_TYPE.get( ext.lower(), "other" )+++def _get_extensions_for_type( asset_type: str ) -> Optional[List[str]]:+ """Return the list of extensions for a given asset type, or None if 'all'."""+ if asset_type == "all":+ return None+ return ASSET_EXTENSIONS.get( asset_type )+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++def list_assets(+ project_dir: str,+ asset_type: Optional[str] = None,+) -> List[Dict[str, Any]]:+ """List all assets in a project's Assets/ directory.++ Args:+ project_dir: Root directory of the s&box project.+ asset_type: Filter by type - 'scene', 'prefab', 'material', 'model',+ 'sound', 'texture', 'shader', 'razor', 'code', or 'all'.+ If None or 'all', returns every recognised asset.++ Returns:+ List of dicts, each with keys: path, type, name, size_bytes.+ Paths are relative to the project's Assets/ directory.+ """+ assets_dir = os.path.join( project_dir, "Assets" )+ if not os.path.isdir( assets_dir ):+ return []++ filter_type = asset_type or "all"+ allowed_extensions = _get_extensions_for_type( filter_type )++ results: List[Dict[str, Any]] = []++ for dirpath, _dirnames, filenames in os.walk( assets_dir ):+ for filename in filenames:+ full_path = os.path.join( dirpath, filename )+ _, ext = os.path.splitext( filename )+ ext_lower = ext.lower()++ # If filtering by type, skip files that don't match+ if allowed_extensions is not None and ext_lower not in allowed_extensions:+ continue++ # If showing all, skip files that aren't a recognised asset type+ classified = _EXT_TO_TYPE.get( ext_lower )+ if allowed_extensions is None and classified is None:+ continue++ rel_path = os.path.relpath( full_path, assets_dir )++ try:+ size = os.path.getsize( full_path )+ except OSError:+ size = 0++ results.append( {+ "path": rel_path,+ "type": classified or "other",+ "name": filename,+ "size_bytes": size,+ } )++ # Sort by relative path for stable ordering+ results.sort( key=lambda entry: entry["path"] )+ return results+++def get_asset_info( asset_path: str ) -> Dict[str, Any]:+ """Get detailed info about a specific asset file.++ For JSON-based assets (.scene, .prefab, .sound), parses the file and+ returns structure information (top-level keys, counts, etc.).++ Args:+ asset_path: Absolute or relative path to the asset file.++ Returns:+ Dict with asset metadata:+ - name: filename+ - path: absolute path+ - type: classified asset type+ - size_bytes: file size+ - exists: whether the file exists+ - json_info: (optional) structure info for JSON-based assets+ """+ abs_path = os.path.abspath( asset_path )+ filename = os.path.basename( abs_path )+ classified = _classify_asset( abs_path )++ info: Dict[str, Any] = {+ "name": filename,+ "path": abs_path,+ "type": classified,+ "exists": os.path.isfile( abs_path ),+ }++ if not info["exists"]:+ info["size_bytes"] = 0+ return info++ try:+ info["size_bytes"] = os.path.getsize( abs_path )+ except OSError:+ info["size_bytes"] = 0++ # Attempt to parse JSON-based assets for structure info+ _, ext = os.path.splitext( filename )+ json_extensions = {".scene", ".prefab", ".sound"}+ if ext.lower() in json_extensions:+ info["json_info"] = _parse_json_asset( abs_path )++ return info+++def _parse_json_asset( file_path: str ) -> Dict[str, Any]:+ """Parse a JSON asset file and return structure information.++ Returns a dict with:+ - top_level_keys: list of keys in the root object+ - For .scene files: game_object_count, scene_properties+ - For .prefab files: game_object_count+ """+ try:+ with open( file_path, "r", encoding="utf-8" ) as f:+ data = json.load( f )+ except (OSError, json.JSONDecodeError, ValueError) as exc:+ return {"error": f"Failed to parse JSON: {exc}"}++ if not isinstance( data, dict ):+ return {"top_level_keys": [], "note": "Root element is not an object"}++ result: Dict[str, Any] = {+ "top_level_keys": list( data.keys() ),+ }++ # Scene-specific info+ game_objects = data.get( "GameObjects" )+ if isinstance( game_objects, list ):+ result["game_object_count"] = len( game_objects )+ result["game_object_names"] = [+ obj.get( "Name", "<unnamed>" )+ for obj in game_objects+ if isinstance( obj, dict )+ ]++ scene_props = data.get( "SceneProperties" )+ if isinstance( scene_props, dict ):+ result["scene_properties"] = scene_props++ # Version info if present+ if "__version" in data:+ result["version"] = data["__version"]++ return result+++def _normalize_ref( ref: str ) -> str:+ """Normalize a ref for comparison: lowercase, forward slashes, strip 'assets/' prefix."""+ if not ref:+ return ""+ n = ref.replace( "\\", "/" ).strip().lower()+ if n.startswith( "assets/" ):+ n = n[len( "assets/" ):]+ return n+++def _scan_project_refs( project_dir: str ) -> Dict[str, List[Dict[str, str]]]:+ """Walk every scene/prefab in a project and return a map: ref -> [sources].++ Each source is a dict with 'file' (relative path) and 'category' (model/material/...).+ Returns the inverted index: normalized_ref -> list of {file, category, original_ref}.+ """+ from cli_anything.sbox.core import scene as scene_mod+ from cli_anything.sbox.core import prefab as prefab_mod++ assets_dir = os.path.join( project_dir, "Assets" )+ if not os.path.isdir( assets_dir ):+ return {}++ inverted: Dict[str, List[Dict[str, str]]] = {}++ for dirpath, _dirs, files in os.walk( assets_dir ):+ for fname in files:+ full = os.path.join( dirpath, fname )+ rel = os.path.relpath( full, project_dir ).replace( "\\", "/" )+ ext = os.path.splitext( fname )[1].lower()++ try:+ if ext == ".scene":+ refs = scene_mod.extract_asset_refs( full )+ elif ext == ".prefab":+ refs = prefab_mod.extract_asset_refs( full )+ else:+ continue+ except (OSError, json.JSONDecodeError, ValueError):+ continue++ for category, paths in refs.items():+ for ref in paths:+ norm = _normalize_ref( ref )+ inverted.setdefault( norm, [] ).append( {+ "file": rel,+ "category": category,+ "original_ref": ref,+ } )++ return inverted+++def find_asset_refs( project_dir: str, asset_path: str ) -> List[Dict[str, str]]:+ """Find every scene/prefab in a project that references *asset_path*.++ Args:+ project_dir: Root directory of the s&box project.+ asset_path: The asset path to look for (e.g. "models/dev/box.vmdl").+ Matching is case-insensitive, slash-normalized, and the+ "Assets/" prefix is optional.++ Returns:+ List of dicts with 'file' (referrer path), 'category' (asset category),+ and 'original_ref' (the exact string found in the file). Empty list if+ no references are found.+ """+ inverted = _scan_project_refs( project_dir )+ target = _normalize_ref( asset_path )+ return inverted.get( target, [] )+++def find_unused_assets(+ project_dir: str,+ asset_types: Optional[List[str]] = None,+) -> List[Dict[str, Any]]:+ """Find assets in the project that aren't referenced by any scene/prefab.++ Note: only asset types whose references appear in scene/prefab JSON are+ detectable here (models, materials, sounds, textures, prefabs). Code,+ razor templates, and shaders are not analysed - they're excluded by+ default unless explicitly requested via *asset_types*.++ Args:+ project_dir: Root directory of the s&box project.+ asset_types: Optional list of asset types to consider (model, material,+ sound, texture, prefab). Defaults to all referenceable types.++ Returns:+ List of dicts with 'path' (relative to Assets/), 'type', and 'size_bytes'.+ """+ referenceable = {"model", "material", "sound", "texture", "prefab"}+ if asset_types is None:+ wanted = referenceable+ else:+ wanted = set( asset_types ) & referenceable++ inverted = _scan_project_refs( project_dir )+ referenced_norms = set( inverted.keys() )++ all_assets = list_assets( project_dir, asset_type="all" )+ unused: List[Dict[str, Any]] = []++ for asset in all_assets:+ if asset["type"] not in wanted:+ continue+ rel = asset["path"].replace( "\\", "/" )+ # Compare: both with and without the extension (some refs omit .vmdl)+ candidates = {_normalize_ref( rel )}+ stem, _ = os.path.splitext( rel )+ if stem:+ candidates.add( _normalize_ref( stem ) )+ if not (candidates & referenced_norms):+ unused.append( asset )++ return unused+++def _rewrite_string_refs(+ node: Any,+ old_norm: str,+ old_stem_norm: str,+ new_path: str,+ new_stem: str,+ counter: List[int],+) -> None:+ """Recursively rewrite asset reference strings in a JSON tree.++ Mutates *node* in place. Matches both full-path refs (with extension) and+ stem-only refs (no extension). *counter* is a single-element mutable list+ used to track replacement count from inside the recursion.+ """+ if isinstance( node, dict ):+ for key, value in list( node.items() ):+ if isinstance( value, str ) and value:+ norm = _normalize_ref( value )+ if norm == old_norm:+ node[key] = new_path+ counter[0] += 1+ elif norm == old_stem_norm and old_stem_norm:+ node[key] = new_stem+ counter[0] += 1+ else:+ _rewrite_string_refs( value, old_norm, old_stem_norm, new_path, new_stem, counter )+ elif isinstance( node, list ):+ for item in node:+ _rewrite_string_refs( item, old_norm, old_stem_norm, new_path, new_stem, counter )+++def _rewrite_refs_in_project(+ project_dir: str,+ old_path: str,+ new_path: str,+) -> List[Dict[str, Any]]:+ """Rewrite every reference to *old_path* with *new_path* across all scenes/prefabs.++ Both arguments should be relative-to-Assets paths (e.g. "models/team/foo.vmdl").+ Returns a list of dicts {file, replacements} for each file actually modified.+ """+ from cli_anything.sbox.core import scene as scene_mod+ from cli_anything.sbox.core import prefab as prefab_mod++ assets_dir = os.path.join( project_dir, "Assets" )+ old_norm = _normalize_ref( old_path )+ old_stem_norm, _ = os.path.splitext( old_norm )+ # Preserve the new path's case but use forward slashes+ new_path_normslash = new_path.replace( "\\", "/" )+ new_stem, _ = os.path.splitext( new_path_normslash )++ modified: List[Dict[str, Any]] = []++ for dirpath, _dirs, files in os.walk( assets_dir ):+ for fname in files:+ full = os.path.join( dirpath, fname )+ rel = os.path.relpath( full, project_dir ).replace( "\\", "/" )+ ext = os.path.splitext( fname )[1].lower()+ if ext not in (".scene", ".prefab"):+ continue+ try:+ if ext == ".scene":+ data = scene_mod.load_scene( full )+ else:+ data = prefab_mod.load_prefab( full )+ except (OSError, json.JSONDecodeError, ValueError):+ continue++ counter = [0]+ _rewrite_string_refs( data, old_norm, old_stem_norm, new_path_normslash, new_stem, counter )+ if counter[0] > 0:+ if ext == ".scene":+ scene_mod.save_scene( full, data )+ else:+ prefab_mod.save_prefab( full, data )+ modified.append( {"file": rel, "replacements": counter[0]} )++ return modified+++def rename_asset(+ project_dir: str,+ old_path: str,+ new_name: str,+ dry_run: bool = False,+) -> Dict[str, Any]:+ """Rename an asset file and update every scene/prefab reference.++ Args:+ project_dir: Project root directory.+ old_path: Current asset path (relative to Assets/, e.g. "models/team/foo.vmdl").+ new_name: New filename (no path), keeping the same parent directory.+ Extension may be omitted - the existing extension is preserved.+ dry_run: If True, don't touch any files - just report what would change.++ Returns:+ Dict with old_path, new_path, file_renamed, references_updated (list).+ """+ assets_dir = os.path.join( project_dir, "Assets" )+ old_full = os.path.join( assets_dir, old_path.replace( "/", os.sep ) )+ if not os.path.isfile( old_full ):+ raise FileNotFoundError( f"Asset not found: {old_path}" )++ parent_rel = os.path.dirname( old_path.replace( "\\", "/" ) )+ old_ext = os.path.splitext( old_path )[1]+ # Preserve extension if caller omitted it+ if not os.path.splitext( new_name )[1]:+ new_filename = new_name + old_ext+ else:+ new_filename = new_name++ new_path = (parent_rel + "/" + new_filename).lstrip( "/" )+ new_full = os.path.join( assets_dir, new_path.replace( "/", os.sep ) )++ if os.path.exists( new_full ) and os.path.abspath( new_full ) != os.path.abspath( old_full ):+ raise FileExistsError( f"Target already exists: {new_path}" )++ if dry_run:+ # Count refs without writing+ refs = find_asset_refs( project_dir, old_path )+ return {+ "old_path": old_path,+ "new_path": new_path,+ "file_renamed": False,+ "references_updated": [],+ "references_would_update": len( refs ),+ "dry_run": True,+ }++ updated = _rewrite_refs_in_project( project_dir, old_path, new_path )+ os.rename( old_full, new_full )++ return {+ "old_path": old_path,+ "new_path": new_path,+ "file_renamed": True,+ "references_updated": updated,+ "dry_run": False,+ }+++def move_asset(+ project_dir: str,+ old_path: str,+ new_path: str,+ dry_run: bool = False,+) -> Dict[str, Any]:+ """Move an asset to a new path (potentially different directory) and update refs.++ Args:+ project_dir: Project root directory.+ old_path: Current asset path relative to Assets/.+ new_path: Target path relative to Assets/. May change directory and/or filename.+ Extension is preserved if the caller's new_path lacks one.+ dry_run: If True, don't touch any files - just report what would change.++ Returns:+ Dict with old_path, new_path, file_moved, references_updated (list).+ """+ assets_dir = os.path.join( project_dir, "Assets" )+ old_full = os.path.join( assets_dir, old_path.replace( "/", os.sep ) )+ if not os.path.isfile( old_full ):+ raise FileNotFoundError( f"Asset not found: {old_path}" )++ old_ext = os.path.splitext( old_path )[1]+ new_path_norm = new_path.replace( "\\", "/" )+ if not os.path.splitext( new_path_norm )[1]:+ new_path_norm = new_path_norm + old_ext++ new_full = os.path.join( assets_dir, new_path_norm.replace( "/", os.sep ) )++ if os.path.exists( new_full ) and os.path.abspath( new_full ) != os.path.abspath( old_full ):+ raise FileExistsError( f"Target already exists: {new_path_norm}" )++ if dry_run:+ refs = find_asset_refs( project_dir, old_path )+ return {+ "old_path": old_path,+ "new_path": new_path_norm,+ "file_moved": False,+ "references_updated": [],+ "references_would_update": len( refs ),+ "dry_run": True,+ }++ updated = _rewrite_refs_in_project( project_dir, old_path, new_path_norm )+ os.makedirs( os.path.dirname( new_full ) or assets_dir, exist_ok=True )+ os.rename( old_full, new_full )++ return {+ "old_path": old_path,+ "new_path": new_path_norm,+ "file_moved": True,+ "references_updated": updated,+ "dry_run": False,+ }+++def find_project_dir( start_path: str ) -> Optional[str]:+ """Walk up from start_path to find the directory containing a .sbproj file.++ Starts from start_path (or its parent if start_path is a file) and+ checks each ancestor directory for a .sbproj file.++ Args:+ start_path: File or directory path to start searching from.++ Returns:+ The project directory path (containing the .sbproj), or None if+ no .sbproj file is found before reaching the filesystem root.+ """+ current = os.path.abspath( start_path )++ # If start_path is a file, begin from its parent directory+ if os.path.isfile( current ):+ current = os.path.dirname( current )++ while True:+ # Check for any .sbproj file in this directory+ try:+ entries = os.listdir( current )+ except OSError:+ return None++ for entry in entries:+ if entry.endswith( ".sbproj" ):+ return current++ # Move to parent+ parent = os.path.dirname( current )+ if parent == current:+ # Reached filesystem root+ return None+ current = parentdiff --git a/sbox/agent-harness/cli_anything/sbox/core/input_config.py b/sbox/agent-harness/cli_anything/sbox/core/input_config.pynew file mode 100644index 000000000..e925cb2e0--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/input_config.py@@ -0,0 +1,208 @@+"""Manages s&box ProjectSettings/Input.config files.++Provides functions to load, save, query, and modify input action bindings+in the s&box Input.config JSON format.+"""++import json+import uuid+from typing import Optional+++def load_input_config( config_path: str ) -> dict:+ """Load Input.config JSON from disk.++ Args:+ config_path: Absolute path to the Input.config file.++ Returns:+ Parsed JSON dict.+ """+ with open( config_path, "r", encoding="utf-8" ) as f:+ return json.load( f )+++def save_input_config( config_path: str, data: dict ) -> None:+ """Save Input.config JSON to disk.++ Args:+ config_path: Absolute path to the Input.config file.+ data: The full config dict to write.+ """+ with open( config_path, "w", encoding="utf-8" ) as f:+ json.dump( data, f, indent=2 )+ f.write( "\n" )+++def list_actions( config_path: str ) -> list[dict]:+ """Return list of all input actions with their bindings.++ Args:+ config_path: Absolute path to the Input.config file.++ Returns:+ List of action dicts, each with Name, GroupName, Title,+ KeyboardCode, and GamepadCode.+ """+ data = load_input_config( config_path )+ return data.get( "Actions", [] )+++def add_action(+ config_path: str,+ name: str,+ group: str = "Other",+ keyboard_code: str = "None",+ gamepad_code: str = "None",+ title: Optional[str] = None,+) -> dict:+ """Add a new input action.++ Args:+ config_path: Absolute path to the Input.config file.+ name: Action name, e.g. "Sprint".+ group: Group name, e.g. "Movement".+ keyboard_code: Keyboard binding, e.g. "W".+ gamepad_code: Gamepad binding, e.g. "A".+ title: Optional display title.++ Returns:+ The newly created action dict.+ """+ data = load_input_config( config_path )+ actions = data.get( "Actions", [] )++ # Avoid duplicates+ for action in actions:+ if action["Name"] == name:+ raise ValueError( f"Action '{name}' already exists" )++ new_action = {+ "Name": name,+ "GroupName": group,+ "Title": title,+ "KeyboardCode": keyboard_code,+ "GamepadCode": gamepad_code,+ }++ actions.append( new_action )+ data["Actions"] = actions+ save_input_config( config_path, data )+ return new_action+++def remove_action( config_path: str, name: str ) -> bool:+ """Remove an input action by name.++ Args:+ config_path: Absolute path to the Input.config file.+ name: Action name to remove.++ Returns:+ True if the action was found and removed, False otherwise.+ """+ data = load_input_config( config_path )+ actions = data.get( "Actions", [] )+ original_len = len( actions )+ data["Actions"] = [a for a in actions if a["Name"] != name]++ if len( data["Actions"] ) < original_len:+ save_input_config( config_path, data )+ return True++ return False+++def set_action(+ config_path: str,+ name: str,+ keyboard_code: Optional[str] = None,+ gamepad_code: Optional[str] = None,+ group: Optional[str] = None,+ title: Optional[str] = None,+) -> dict:+ """Modify an existing input action's bindings.++ Args:+ config_path: Absolute path to the Input.config file.+ name: Action name to modify.+ keyboard_code: New keyboard binding (or None to leave unchanged).+ gamepad_code: New gamepad binding (or None to leave unchanged).+ group: New group name (or None to leave unchanged).+ title: New display title (or None to leave unchanged).++ Returns:+ The updated action dict.++ Raises:+ KeyError: If the action does not exist.+ """+ data = load_input_config( config_path )+ actions = data.get( "Actions", [] )++ for action in actions:+ if action["Name"] == name:+ if keyboard_code is not None:+ action["KeyboardCode"] = keyboard_code+ if gamepad_code is not None:+ action["GamepadCode"] = gamepad_code+ if group is not None:+ action["GroupName"] = group+ if title is not None:+ action["Title"] = title++ save_input_config( config_path, data )+ return action++ raise KeyError( f"Action '{name}' not found" )+++def get_default_input_config() -> dict:+ """Return the default s&box Input.config with standard FPS bindings.++ Returns:+ A complete Input.config dict ready to be saved.+ """+ return {+ "Actions": [+ # Movement+ {"Name": "Forward", "GroupName": "Movement", "Title": None, "KeyboardCode": "W", "GamepadCode": "None"},+ {"Name": "Backward", "GroupName": "Movement", "Title": None, "KeyboardCode": "S", "GamepadCode": "None"},+ {"Name": "Left", "GroupName": "Movement", "Title": None, "KeyboardCode": "A", "GamepadCode": "None"},+ {"Name": "Right", "GroupName": "Movement", "Title": None, "KeyboardCode": "D", "GamepadCode": "None"},+ {"Name": "Jump", "GroupName": "Movement", "Title": None, "KeyboardCode": "space", "GamepadCode": "A"},+ {"Name": "Run", "GroupName": "Movement", "Title": None, "KeyboardCode": "shift", "GamepadCode": "LeftJoystickButton"},+ {"Name": "Walk", "GroupName": "Movement", "Title": None, "KeyboardCode": "alt", "GamepadCode": "None"},+ {"Name": "Duck", "GroupName": "Movement", "Title": None, "KeyboardCode": "ctrl", "GamepadCode": "B"},+ # Actions+ {"Name": "Attack1", "GroupName": "Actions", "Title": "Primary Attack", "KeyboardCode": "mouse1", "GamepadCode": "RightTrigger"},+ {"Name": "Attack2", "GroupName": "Actions", "Title": "Secondary Attack", "KeyboardCode": "mouse2", "GamepadCode": "LeftTrigger"},+ {"Name": "Reload", "GroupName": "Actions", "Title": None, "KeyboardCode": "r", "GamepadCode": "X"},+ {"Name": "Use", "GroupName": "Actions", "Title": None, "KeyboardCode": "e", "GamepadCode": "Y"},+ # Inventory+ {"Name": "Slot1", "GroupName": "Inventory", "Title": "Slot #1", "KeyboardCode": "1", "GamepadCode": "DpadWest"},+ {"Name": "Slot2", "GroupName": "Inventory", "Title": "Slot #2", "KeyboardCode": "2", "GamepadCode": "DpadEast"},+ {"Name": "Slot3", "GroupName": "Inventory", "Title": "Slot #3", "KeyboardCode": "3", "GamepadCode": "DpadSouth"},+ {"Name": "Slot4", "GroupName": "Inventory", "Title": "Slot #4", "KeyboardCode": "4", "GamepadCode": "None"},+ {"Name": "Slot5", "GroupName": "Inventory", "Title": "Slot #5", "KeyboardCode": "5", "GamepadCode": "None"},+ {"Name": "Slot6", "GroupName": "Inventory", "Title": "Slot #6", "KeyboardCode": "6", "GamepadCode": "None"},+ {"Name": "Slot7", "GroupName": "Inventory", "Title": "Slot #7", "KeyboardCode": "7", "GamepadCode": "None"},+ {"Name": "Slot8", "GroupName": "Inventory", "Title": "Slot #8", "KeyboardCode": "8", "GamepadCode": "None"},+ {"Name": "Slot9", "GroupName": "Inventory", "Title": "Slot #9", "KeyboardCode": "9", "GamepadCode": "None"},+ {"Name": "Slot0", "GroupName": "Inventory", "Title": "Slot #0", "KeyboardCode": "0", "GamepadCode": "None"},+ {"Name": "SlotPrev", "GroupName": "Inventory", "Title": "Previous Slot", "KeyboardCode": "mouse4", "GamepadCode": "SwitchLeftBumper"},+ {"Name": "SlotNext", "GroupName": "Inventory", "Title": "Next Slot", "KeyboardCode": "mouse5", "GamepadCode": "SwitchRightBumper"},+ # Other+ {"Name": "View", "GroupName": "Other", "Title": None, "KeyboardCode": "C", "GamepadCode": "RightJoystickButton"},+ {"Name": "Voice", "GroupName": "Other", "Title": None, "KeyboardCode": "v", "GamepadCode": "None"},+ {"Name": "Drop", "GroupName": "Other", "Title": None, "KeyboardCode": "g", "GamepadCode": "None"},+ {"Name": "Flashlight", "GroupName": "Other", "Title": None, "KeyboardCode": "f", "GamepadCode": "DpadNorth"},+ {"Name": "Score", "GroupName": "Other", "Title": "Scoreboard", "KeyboardCode": "tab", "GamepadCode": "SwitchLeftMenu"},+ {"Name": "Menu", "GroupName": "Other", "Title": None, "KeyboardCode": "Q", "GamepadCode": "SwitchRightMenu"},+ {"Name": "Chat", "GroupName": "Other", "Title": None, "KeyboardCode": "enter", "GamepadCode": "None"},+ ],+ "__guid": str( uuid.uuid4() ),+ "__schema": "configdata",+ "__type": "InputSettings",+ "__version": 1,+ }diff --git a/sbox/agent-harness/cli_anything/sbox/core/localization.py b/sbox/agent-harness/cli_anything/sbox/core/localization.pynew file mode 100644index 000000000..b8cb3030b--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/localization.py@@ -0,0 +1,103 @@+"""Manages s&box localization/translation files."""++import json+import os+from typing import Any, Dict, List, Optional+++def create_translation_file(+ lang: str = "en",+ initial_keys: Optional[Dict[str, str]] = None,+ output_path: Optional[str] = None,+) -> Dict[str, Any]:+ """Create a new translation JSON file.++ Args:+ lang: Language code (e.g. "en", "fr", "de").+ initial_keys: Initial key-value pairs.+ output_path: Output file path.++ Returns:+ Dict with lang, path, key_count, data.+ """+ data = initial_keys or {}++ result = {+ "lang": lang,+ "key_count": len(data),+ "data": data,+ }++ if output_path:+ if not output_path.endswith(".json"):+ output_path += ".json"+ os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)+ with open(output_path, "w", encoding="utf-8") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+ result["path"] = os.path.abspath(output_path)++ return result+++def load_translations(file_path: str) -> Dict[str, str]:+ """Load a translation file and return the key-value dict."""+ with open(file_path, "r", encoding="utf-8") as f:+ return json.load(f)+++def save_translations(file_path: str, data: Dict[str, str]) -> None:+ """Save a translation dict to a JSON file."""+ with open(file_path, "w", encoding="utf-8") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+++def list_keys(file_path: str) -> List[str]:+ """List all translation keys in a file."""+ data = load_translations(file_path)+ return sorted(data.keys())+++def get_key(file_path: str, key: str) -> Optional[str]:+ """Get the value for a translation key. Returns None if not found."""+ data = load_translations(file_path)+ return data.get(key)+++def set_key(file_path: str, key: str, value: str) -> Dict[str, str]:+ """Set a translation key-value pair. Creates or updates.++ Returns the full updated translations dict.+ """+ data = load_translations(file_path)+ data[key] = value+ save_translations(file_path, data)+ return data+++def remove_key(file_path: str, key: str) -> bool:+ """Remove a translation key.++ Returns True if key existed and was removed, False if not found.+ """+ data = load_translations(file_path)+ if key not in data:+ return False+ del data[key]+ save_translations(file_path, data)+ return True+++def bulk_set( file_path: str, keys: Dict[str, str] ) -> Dict[str, str]:+ """Set multiple translation key-value pairs at once.++ Args:+ file_path: Path to the translation JSON file.+ keys: Dict of key-value pairs to set.++ Returns:+ The full updated translations dict.+ """+ data = load_translations( file_path )+ data.update( keys )+ save_translations( file_path, data )+ return datadiff --git a/sbox/agent-harness/cli_anything/sbox/core/material.py b/sbox/agent-harness/cli_anything/sbox/core/material.pynew file mode 100644index 000000000..693b669d4--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/material.py@@ -0,0 +1,190 @@+"""Manages s&box .vmat material files - creation, parsing, and listing."""++import os+from typing import Any, Dict, List, Optional+++SHADER_MAP: Dict[str, str] = {+ "complex": "shaders/complex.vfx",+ "simple": "shaders/simple.vfx",+ "unlit": "shaders/unlit.vfx",+ "blendable": "shaders/blendable.vfx",+ "glass": "shaders/glass.vfx",+}+++def create_material(+ name: str,+ shader: str = "complex",+ color_texture: Optional[str] = None,+ normal_texture: Optional[str] = None,+ roughness_texture: Optional[str] = None,+ metalness: float = 0.0,+ tint: str = "1 1 1 0",+ output_path: Optional[str] = None,+) -> Dict[str, Any]:+ """Create a .vmat material file.++ Args:+ name: Material name (used for filename if output_path not given).+ shader: Shader name - key from SHADER_MAP or full path.+ color_texture: Path to color/albedo texture.+ normal_texture: Path to normal map texture.+ roughness_texture: Path to roughness texture.+ metalness: Metalness value (0.0 to 1.0).+ tint: Color tint as "r g b a" (space-separated).+ output_path: Output file path. If None, returns content only.++ Returns:+ Dict with name, path, shader, content.+ """+ shader_path = SHADER_MAP.get(shader, shader)++ lines = []+ lines.append("// THIS FILE IS AUTO-GENERATED")+ lines.append("")+ lines.append("Layer0")+ lines.append("{")+ lines.append(f'\tshader "{shader_path}"')+ lines.append("")+ lines.append("\t//---- PBR ----")++ if color_texture:+ lines.append(f'\tTextureColor "{color_texture}"')+ if normal_texture:+ lines.append(f'\tTextureNormal "{normal_texture}"')+ if roughness_texture:+ lines.append(f'\tTextureRoughness "{roughness_texture}"')++ lines.append(f'\tg_flMetalness "{metalness}"')+ lines.append(f'\tg_vColorTint "[{tint}]"')+ lines.append("}")+ lines.append("")++ content = "\n".join(lines)++ result = {+ "name": name,+ "shader": shader_path,+ "content": content,+ }++ if output_path:+ if not output_path.endswith(".vmat"):+ output_path += ".vmat"+ os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)+ with open(output_path, "w", encoding="utf-8") as f:+ f.write(content)+ result["path"] = os.path.abspath(output_path)++ return result+++def parse_material(material_path: str) -> Dict[str, Any]:+ """Parse a .vmat material file and return its properties.++ Returns dict with name, path, shader, and properties dict.+ """+ with open(material_path, "r", encoding="utf-8") as f:+ text = f.read()++ properties = {}+ shader = None++ for line in text.splitlines():+ line = line.strip()+ if not line or line.startswith("//") or line in ("{", "}", "Layer0"):+ continue++ # Parse key "value" format+ parts = line.split('"', 2)+ if len(parts) >= 3:+ key = parts[0].strip()+ value = parts[1]+ if key == "shader":+ shader = value+ else:+ properties[key] = value++ name = os.path.splitext(os.path.basename(material_path))[0]++ return {+ "name": name,+ "path": os.path.abspath(material_path),+ "shader": shader,+ "properties": properties,+ }+++def update_material(+ material_path: str,+ shader: Optional[str] = None,+ color_texture: Optional[str] = None,+ normal_texture: Optional[str] = None,+ roughness_texture: Optional[str] = None,+ metalness: Optional[float] = None,+ tint: Optional[str] = None,+) -> Dict[str, Any]:+ """Update properties of an existing .vmat material file.++ Only modifies properties that are explicitly provided (non-None).+ Returns the updated material info dict.+ """+ info = parse_material( material_path )+ old_shader = info["shader"]+ old_props = info["properties"]++ new_shader = SHADER_MAP.get( shader, shader ) if shader is not None else old_shader++ ct = color_texture if color_texture is not None else old_props.get( "TextureColor" )+ nt = normal_texture if normal_texture is not None else old_props.get( "TextureNormal" )+ rt = roughness_texture if roughness_texture is not None else old_props.get( "TextureRoughness" )+ mt = str( metalness ) if metalness is not None else old_props.get( "g_flMetalness", "0.0" )+ ti = tint if tint is not None else old_props.get( "g_vColorTint", "[1 1 1 0]" ).strip( "[]" )++ lines = []+ lines.append( "// THIS FILE IS AUTO-GENERATED" )+ lines.append( "" )+ lines.append( "Layer0" )+ lines.append( "{" )+ lines.append( f'\tshader "{new_shader}"' )+ lines.append( "" )+ lines.append( "\t//---- PBR ----" )+ if ct:+ lines.append( f'\tTextureColor "{ct}"' )+ if nt:+ lines.append( f'\tTextureNormal "{nt}"' )+ if rt:+ lines.append( f'\tTextureRoughness "{rt}"' )+ lines.append( f'\tg_flMetalness "{mt}"' )+ lines.append( f'\tg_vColorTint "[{ti}]"' )+ lines.append( "}" )+ lines.append( "" )++ with open( material_path, "w", encoding="utf-8" ) as f:+ f.write( "\n".join( lines ) )++ return parse_material( material_path )+++def list_materials(project_dir: str) -> List[Dict[str, Any]]:+ """List all .vmat files in a project's Assets/ directory.++ Returns list of dicts with name, path, size_bytes.+ """+ assets_dir = os.path.join(project_dir, "Assets")+ if not os.path.isdir(assets_dir):+ assets_dir = project_dir++ materials = []+ for root, _dirs, files in os.walk(assets_dir):+ for fname in sorted(files):+ if fname.endswith(".vmat"):+ full_path = os.path.join(root, fname)+ materials.append({+ "name": os.path.splitext(fname)[0],+ "path": os.path.abspath(full_path),+ "size_bytes": os.path.getsize(full_path),+ })++ return materialsdiff --git a/sbox/agent-harness/cli_anything/sbox/core/prefab.py b/sbox/agent-harness/cli_anything/sbox/core/prefab.pynew file mode 100644index 000000000..7c185b1ee--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/prefab.py@@ -0,0 +1,327 @@+"""Manages s&box .prefab files - creation, loading, saving, and extraction from scenes."""++import json+import os+import uuid+from typing import Any, Dict, List, Optional++from . import scene as scene_mod+++# ---------------------------------------------------------------------------+# Internal helpers+# ---------------------------------------------------------------------------+++def _new_guid() -> str:+ """Generate a new UUID v4 string."""+ return str(uuid.uuid4())+++def _write_json(path: str, data: Dict[str, Any]) -> None:+ """Write data as formatted JSON to path."""+ os.makedirs(os.path.dirname(path) if os.path.dirname(path) else ".", exist_ok=True)+ with open(path, "w", encoding="utf-8", newline="\r\n") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+ f.write("\n")+++def _build_root_object(+ name: str,+ components: Optional[List[Dict[str, Any]]] = None,+ children: Optional[List[Dict[str, Any]]] = None,+ network_mode: int = 0,+ network_transmit: bool = True,+ flags: int = 0,+) -> Dict[str, Any]:+ """Build a RootObject dict for a prefab."""+ resolved_components: List[Dict[str, Any]] = []+ if components:+ for comp in components:+ if isinstance(comp, str):+ # Treat as a preset name+ resolved_components.append(scene_mod._make_component(comp))+ elif isinstance(comp, dict):+ c = dict(comp)+ if "__guid" not in c:+ c["__guid"] = _new_guid()+ resolved_components.append(c)++ resolved_children: List[Dict[str, Any]] = []+ if children:+ for child in children:+ if isinstance(child, dict):+ c = dict(child)+ if "__guid" not in c:+ c["__guid"] = _new_guid()+ resolved_children.append(c)++ root: Dict[str, Any] = {+ "__guid": _new_guid(),+ "Flags": flags,+ "Name": name,+ "Enabled": True,+ "NetworkMode": network_mode,+ "NetworkInterpolation": True,+ "GizmoPersistence": 0,+ "RenderDirty": False,+ "Components": resolved_components,+ "Children": resolved_children,+ }++ if network_transmit:+ root["NetworkOrphaned"] = 1++ return root+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++def create_prefab(+ name: str,+ output_path: Optional[str] = None,+ components: Optional[List[Dict[str, Any]]] = None,+ children: Optional[List[Dict[str, Any]]] = None,+ network_mode: int = 0,+ network_transmit: bool = True,+) -> Dict[str, Any]:+ """Create a new .prefab file with given components and children.++ *components* can be a list of component dicts (with ``__type``) or+ preset name strings (resolved via ``scene.COMPONENT_PRESETS``).++ *children* is a list of child GameObject dicts.++ Returns the full prefab data dict.+ """+ root_object = _build_root_object(+ name=name,+ components=components,+ children=children,+ network_mode=network_mode,+ network_transmit=network_transmit,+ )++ prefab: Dict[str, Any] = {+ "RootObject": root_object,+ "SceneProperties": {},+ "ResourceVersion": 1,+ "__references": [],+ "__version": 1,+ }++ if output_path:+ _write_json(output_path, prefab)++ return prefab+++def load_prefab(prefab_path: str) -> Dict[str, Any]:+ """Load and return parsed prefab JSON."""+ with open(prefab_path, "r", encoding="utf-8") as f:+ return json.load(f)+++def save_prefab(prefab_path: str, data: Dict[str, Any]) -> None:+ """Save prefab JSON."""+ _write_json(prefab_path, data)+++def get_prefab_info(prefab_path: str) -> Dict[str, Any]:+ """Return dict with prefab metadata."""+ data = load_prefab(prefab_path)+ root = data.get("RootObject", {})+ components = root.get("Components", [])+ children = root.get("Children", [])++ # Gather all component types from root and children (flat)+ all_objects = [root]+ flat_children = scene_mod._flatten_objects(children)+ all_objects.extend(flat_children)++ component_types: set = set()+ total_components = 0+ for obj in all_objects:+ for comp in obj.get("Components", []):+ ctype = comp.get("__type", "")+ if ctype:+ component_types.add(ctype)+ total_components += 1++ return {+ "name": root.get("Name", ""),+ "guid": root.get("__guid", ""),+ "path": prefab_path,+ "component_count": total_components,+ "component_types": sorted(component_types),+ "children_count": len(flat_children),+ "network_mode": root.get("NetworkMode", 0),+ }+++def from_scene_object(+ scene_path: str,+ object_guid: str,+ output_path: str,+) -> Dict[str, Any]:+ """Extract a GameObject from a scene and save as .prefab file.++ The GameObject (including its Components and Children) is copied into+ the prefab RootObject structure. GUIDs are preserved from the scene.++ Returns the prefab data dict.+ """+ scene_data = scene_mod.load_scene(scene_path)+ obj = scene_mod.find_object(scene_data, guid=object_guid)+ if obj is None:+ raise ValueError(f"GameObject with guid '{object_guid}' not found in scene")++ # Build prefab from the scene object - copy it to avoid mutating the scene+ import copy+ root_object = copy.deepcopy(obj)++ # Ensure the root has the fields expected by the prefab format+ root_object.setdefault("Flags", 0)+ root_object.setdefault("Enabled", True)++ prefab: Dict[str, Any] = {+ "RootObject": root_object,+ "SceneProperties": {},+ "ResourceVersion": 1,+ "__references": [],+ "__version": 1,+ }++ _write_json(output_path, prefab)+ return prefab+++def diff_prefabs( prefab_a_path: str, prefab_b_path: str ) -> Dict[str, Any]:+ """Structural diff between two prefab files.++ Compares the RootObject summary plus the flat list of children (by Name)+ using the same logic as scene diff. Symmetric with scene.diff_scenes.++ Returns:+ Dict with 'root_changes' (or None if identical),+ 'children_added' (list of names), 'children_removed' (list of names),+ 'children_modified' (list of {name, changes}), and 'identical' (bool).+ """+ data_a = load_prefab( prefab_a_path )+ data_b = load_prefab( prefab_b_path )++ root_a = data_a.get( "RootObject", {} ) or {}+ root_b = data_b.get( "RootObject", {} ) or {}++ summary_root_a = scene_mod._object_summary( root_a )+ summary_root_b = scene_mod._object_summary( root_b )+ root_changes = scene_mod._diff_two_objects( "<root>", summary_root_a, summary_root_b )++ children_a = scene_mod._flatten_objects( root_a.get( "Children", [] ) )+ children_b = scene_mod._flatten_objects( root_b.get( "Children", [] ) )+ summary_a = {obj.get( "Name", f"<unnamed:{i}>" ): scene_mod._object_summary( obj ) for i, obj in enumerate( children_a )}+ summary_b = {obj.get( "Name", f"<unnamed:{i}>" ): scene_mod._object_summary( obj ) for i, obj in enumerate( children_b )}++ names_a = set( summary_a.keys() )+ names_b = set( summary_b.keys() )+ added = sorted( names_b - names_a )+ removed = sorted( names_a - names_b )+ modified: List[Dict[str, Any]] = []+ for name in sorted( names_a & names_b ):+ d = scene_mod._diff_two_objects( name, summary_a[name], summary_b[name] )+ if d:+ modified.append( d )++ identical = (root_changes is None) and not (added or removed or modified)+ return {+ "prefab_a": prefab_a_path,+ "prefab_b": prefab_b_path,+ "root_changes": root_changes,+ "children_added": added,+ "children_removed": removed,+ "children_modified": modified,+ "identical": identical,+ }+++def extract_asset_refs( prefab_path: str ) -> Dict[str, List[str]]:+ """Extract every asset reference from a prefab file.++ Same categorization as scene.extract_asset_refs.+ """+ data = load_prefab( prefab_path )+ refs: Dict[str, List[str]] = {}+ if "RootObject" in data:+ scene_mod._walk_for_refs( data["RootObject"], refs, ["RootObject"] )+ return {cat: sorted( set( paths ) ) for cat, paths in refs.items()}+++def modify_component(+ prefab_path: str,+ component_guid: Optional[str] = None,+ component_type: Optional[str] = None,+ object_guid: Optional[str] = None,+ properties: Optional[Dict[str, Any]] = None,+) -> Dict[str, Any]:+ """Modify properties on a component within a prefab.++ Searches the RootObject and all children for a matching component. If+ *object_guid* is provided, the search is restricted to that GameObject;+ otherwise the first matching component anywhere in the tree wins.++ Returns dict with object_guid, component_guid, component_type, updated_keys.+ """+ if component_guid is None and component_type is None:+ raise ValueError( "Must provide either component_guid or component_type" )+ if not properties:+ raise ValueError( "No properties specified to modify" )++ data = load_prefab( prefab_path )+ root = data.get( "RootObject" )+ if root is None:+ raise ValueError( "Prefab has no RootObject" )++ all_objects: List[Dict[str, Any]] = [root]+ children = root.get( "Children", [] )+ if children:+ all_objects.extend( scene_mod._flatten_objects( children ) )++ # Optionally restrict to a single object+ if object_guid:+ all_objects = [o for o in all_objects if o.get( "__guid" ) == object_guid]+ if not all_objects:+ raise ValueError( f"Object '{object_guid}' not found in prefab" )++ target_obj = None+ target_comp = None+ for obj in all_objects:+ for comp in obj.get( "Components", [] ):+ if component_guid and comp.get( "__guid" ) == component_guid:+ target_obj, target_comp = obj, comp+ break+ if component_type and comp.get( "__type" ) == component_type:+ target_obj, target_comp = obj, comp+ break+ if target_comp is not None:+ break++ if target_comp is None:+ identifier = component_guid or component_type+ raise ValueError( f"Component '{identifier}' not found in prefab" )++ updated_keys = []+ for key, value in properties.items():+ target_comp[key] = value+ updated_keys.append( key )++ save_prefab( prefab_path, data )++ return {+ "object_guid": target_obj.get( "__guid", "" ),+ "component_guid": target_comp.get( "__guid", "" ),+ "component_type": target_comp.get( "__type", "" ),+ "updated_keys": updated_keys,+ }diff --git a/sbox/agent-harness/cli_anything/sbox/core/project.py b/sbox/agent-harness/cli_anything/sbox/core/project.pynew file mode 100644index 000000000..d51423893--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/project.py@@ -0,0 +1,417 @@+"""Manages s&box .sbproj project files and project scaffolding."""++import json+import os+import uuid+from typing import Any, Dict, List, Optional+++# ---------------------------------------------------------------------------+# Template content+# ---------------------------------------------------------------------------++EDITORCONFIG_CONTENT = """\+root = true++[*]+indent_style = tab+indent_size = 4+end_of_line = crlf+insert_final_newline = true++[*.cs]+csharp_new_line_before_open_brace = all+csharp_space_between_method_declaration_parameter_list_parentheses = true+csharp_space_between_method_call_parameter_list_parentheses = true+csharp_space_after_keywords_in_control_flow_statements = true+csharp_preferred_modifier_order = public, private, protected, internal, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, volatile, async:suggestion+"""++CODE_ASSEMBLY_CS = """\+global using Sandbox;+global using System.Collections.Generic;+global using System.Linq;+"""++EDITOR_ASSEMBLY_CS = """\+global using Sandbox;+global using Editor;+global using System.Collections.Generic;+global using System.Linq;+"""++DEFAULT_INPUT_CONFIG: Dict[str, Any] = {+ "Actions": [+ {"Name": "Forward", "GroupName": "Movement", "Title": None, "KeyboardCode": "W", "GamepadCode": "None"},+ {"Name": "Backward", "GroupName": "Movement", "Title": None, "KeyboardCode": "S", "GamepadCode": "None"},+ {"Name": "Left", "GroupName": "Movement", "Title": None, "KeyboardCode": "A", "GamepadCode": "None"},+ {"Name": "Right", "GroupName": "Movement", "Title": None, "KeyboardCode": "D", "GamepadCode": "None"},+ {"Name": "Jump", "GroupName": "Movement", "Title": None, "KeyboardCode": "space", "GamepadCode": "A"},+ {"Name": "Run", "GroupName": "Movement", "Title": None, "KeyboardCode": "shift", "GamepadCode": "LeftJoystickButton"},+ {"Name": "Walk", "GroupName": "Movement", "Title": None, "KeyboardCode": "alt", "GamepadCode": "None"},+ {"Name": "Duck", "GroupName": "Movement", "Title": None, "KeyboardCode": "ctrl", "GamepadCode": "B"},+ {"Name": "Attack1", "GroupName": "Actions", "Title": "Primary Attack", "KeyboardCode": "mouse1", "GamepadCode": "RightTrigger"},+ {"Name": "Attack2", "GroupName": "Actions", "Title": "Secondary Attack", "KeyboardCode": "mouse2", "GamepadCode": "LeftTrigger"},+ {"Name": "Reload", "GroupName": "Actions", "Title": None, "KeyboardCode": "r", "GamepadCode": "X"},+ {"Name": "Use", "GroupName": "Actions", "Title": None, "KeyboardCode": "e", "GamepadCode": "Y"},+ {"Name": "Slot1", "GroupName": "Inventory", "Title": "Slot #1", "KeyboardCode": "1", "GamepadCode": "DpadWest"},+ {"Name": "Slot2", "GroupName": "Inventory", "Title": "Slot #2", "KeyboardCode": "2", "GamepadCode": "DpadEast"},+ {"Name": "Slot3", "GroupName": "Inventory", "Title": "Slot #3", "KeyboardCode": "3", "GamepadCode": "DpadSouth"},+ {"Name": "Slot4", "GroupName": "Inventory", "Title": "Slot #4", "KeyboardCode": "4", "GamepadCode": "None"},+ {"Name": "Slot5", "GroupName": "Inventory", "Title": "Slot #5", "KeyboardCode": "5", "GamepadCode": "None"},+ {"Name": "Slot6", "GroupName": "Inventory", "Title": "Slot #6", "KeyboardCode": "6", "GamepadCode": "None"},+ {"Name": "Slot7", "GroupName": "Inventory", "Title": "Slot #7", "KeyboardCode": "7", "GamepadCode": "None"},+ {"Name": "Slot8", "GroupName": "Inventory", "Title": "Slot #8", "KeyboardCode": "8", "GamepadCode": "None"},+ {"Name": "Slot9", "GroupName": "Inventory", "Title": "Slot #9", "KeyboardCode": "9", "GamepadCode": "None"},+ {"Name": "Slot0", "GroupName": "Inventory", "Title": "Slot #0", "KeyboardCode": "0", "GamepadCode": "None"},+ {"Name": "SlotPrev", "GroupName": "Inventory", "Title": "Previous Slot", "KeyboardCode": "mouse4", "GamepadCode": "SwitchLeftBumper"},+ {"Name": "SlotNext", "GroupName": "Inventory", "Title": "Next Slot", "KeyboardCode": "mouse5", "GamepadCode": "SwitchRightBumper"},+ {"Name": "View", "GroupName": "Other", "Title": None, "KeyboardCode": "C", "GamepadCode": "RightJoystickButton"},+ {"Name": "Voice", "GroupName": "Other", "Title": None, "KeyboardCode": "v", "GamepadCode": "None"},+ {"Name": "Drop", "GroupName": "Other", "Title": None, "KeyboardCode": "g", "GamepadCode": "None"},+ {"Name": "Flashlight", "GroupName": "Other", "Title": None, "KeyboardCode": "f", "GamepadCode": "DpadNorth"},+ {"Name": "Score", "GroupName": "Other", "Title": "Scoreboard", "KeyboardCode": "tab", "GamepadCode": "SwitchLeftMenu"},+ {"Name": "Menu", "GroupName": "Other", "Title": None, "KeyboardCode": "Q", "GamepadCode": "SwitchRightMenu"},+ {"Name": "Chat", "GroupName": "Other", "Title": None, "KeyboardCode": "enter", "GamepadCode": "None"},+ ],+ "__guid": str( uuid.uuid4() ),+ "__schema": "configdata",+ "__type": "InputSettings",+ "__version": 1,+}++DEFAULT_COLLISION_CONFIG: Dict[str, Any] = {+ "Version": 2,+ "Defaults": {+ "solid": "Collide",+ "world": "Collide",+ "trigger": "Trigger",+ "ladder": "Ignore",+ "water": "Trigger",+ },+ "Pairs": [+ {"a": "solid", "b": "solid", "r": "Collide"},+ {"a": "trigger", "b": "playerclip", "r": "Ignore"},+ {"a": "trigger", "b": "solid", "r": "Trigger"},+ {"a": "playerclip", "b": "solid", "r": "Collide"},+ ],+ "__guid": str( uuid.uuid4() ),+ "__schema": "configdata",+ "__type": "CollisionRules",+ "__version": 2,+}+++def _default_minimal_scene() -> Dict[str, Any]:+ """Return a minimal scene structure with Sun, Skybox, Plane, and Camera."""+ # Import here to avoid circular dependency at module level+ from .scene import _build_default_objects++ scene: Dict[str, Any] = {+ "GameObjects": _build_default_objects(),+ "SceneProperties": {+ "FixedUpdateFrequency": 50,+ "MaxFixedUpdates": 5,+ "NetworkFrequency": 60,+ "NetworkInterpolation": True,+ "PhysicsSubSteps": 1,+ "ThreadedAnimation": True,+ "TimeScale": 1,+ "UseFixedUpdate": True,+ },+ "Title": "minimal",+ "Description": "",+ "ResourceVersion": 1,+ "__references": [],+ "__version": 1,+ }+ return scene+++def _default_sbproj(+ name: str,+ project_type: str = "game",+ org: str = "local",+ max_players: int = 64,+ tick_rate: int = 50,+ network_type: str = "Multiplayer",+ startup_scene: str = "scenes/minimal.scene",+) -> Dict[str, Any]:+ """Build a default .sbproj dict."""+ return {+ "Title": name,+ "Type": project_type,+ "Org": org,+ "Ident": name.lower().replace(" ", "_"),+ "Schema": 1,+ "HasAssets": True,+ "AssetsPath": "",+ "HasCode": True,+ "CodePath": "/code/",+ "Metadata": {+ "MaxPlayers": max_players,+ "MinPlayers": 1,+ "TickRate": tick_rate,+ "GameNetworkType": network_type,+ "MapSelect": "Tagged",+ "MapList": [],+ "RankType": "None",+ "PerMapRanking": False,+ "LeaderboardType": "None",+ "CsProjName": "",+ "StartupScene": startup_scene,+ },+ "PackageReferences": [],+ "EditorReferences": [],+ "IsWhitelistDisabled": False,+ "Physics": {+ "SubSteps": 1,+ "TimeScale": 1,+ "Gravity": "0,0,-800",+ "AirDensity": 1.2,+ "SleepingEnabled": True,+ "SimulationMode": "Continuous",+ "PositionIterations": 2,+ "VelocityIterations": 8,+ },+ "__references": [],+ "__version": 1,+ }+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++def create_project(+ name: str,+ project_type: str = "game",+ org: str = "local",+ max_players: int = 64,+ tick_rate: int = 50,+ network_type: str = "Multiplayer",+ startup_scene: str = "scenes/minimal.scene",+ output_dir: Optional[str] = None,+) -> Dict[str, Any]:+ """Create a new s&box project directory with .sbproj and standard structure.++ Creates:+ - <name>.sbproj+ - .editorconfig+ - Code/Assembly.cs+ - Editor/Assembly.cs+ - Assets/scenes/minimal.scene (basic scene)+ - ProjectSettings/Input.config (default bindings)+ - ProjectSettings/Collision.config (default layers)+ - Libraries/ (empty)+ - Localization/ (empty)++ Returns dict with project info.+ """+ root = output_dir if output_dir else os.path.join(os.getcwd(), name)+ os.makedirs(root, exist_ok=True)++ # .sbproj+ sbproj_data = _default_sbproj(+ name,+ project_type=project_type,+ org=org,+ max_players=max_players,+ tick_rate=tick_rate,+ network_type=network_type,+ startup_scene=startup_scene,+ )+ sbproj_path = os.path.join(root, f"{name}.sbproj")+ _write_json(sbproj_path, sbproj_data)++ # .editorconfig+ _write_text(os.path.join(root, ".editorconfig"), EDITORCONFIG_CONTENT)++ # Code/Assembly.cs+ code_dir = os.path.join(root, "Code")+ os.makedirs(code_dir, exist_ok=True)+ _write_text(os.path.join(code_dir, "Assembly.cs"), CODE_ASSEMBLY_CS)++ # Editor/Assembly.cs+ editor_dir = os.path.join(root, "Editor")+ os.makedirs(editor_dir, exist_ok=True)+ _write_text(os.path.join(editor_dir, "Assembly.cs"), EDITOR_ASSEMBLY_CS)++ # Assets/scenes/minimal.scene+ scenes_dir = os.path.join(root, "Assets", "scenes")+ os.makedirs(scenes_dir, exist_ok=True)+ scene_data = _default_minimal_scene()+ _write_json(os.path.join(scenes_dir, "minimal.scene"), scene_data)++ # ProjectSettings+ settings_dir = os.path.join(root, "ProjectSettings")+ os.makedirs(settings_dir, exist_ok=True)+ _write_json(os.path.join(settings_dir, "Input.config"), DEFAULT_INPUT_CONFIG)+ _write_json(os.path.join(settings_dir, "Collision.config"), DEFAULT_COLLISION_CONFIG)++ # Empty directories+ os.makedirs(os.path.join(root, "Libraries"), exist_ok=True)+ os.makedirs(os.path.join(root, "Localization"), exist_ok=True)++ return {+ "name": name,+ "path": root,+ "sbproj": sbproj_path,+ "type": project_type,+ "org": org,+ "max_players": max_players,+ "tick_rate": tick_rate,+ "network_type": network_type,+ "startup_scene": startup_scene,+ }+++def load_project(sbproj_path: str) -> Dict[str, Any]:+ """Load and return parsed .sbproj JSON."""+ with open(sbproj_path, "r", encoding="utf-8") as f:+ return json.load(f)+++def save_project(sbproj_path: str, data: Dict[str, Any]) -> None:+ """Save .sbproj JSON."""+ _write_json(sbproj_path, data)+++def get_project_info(sbproj_path: str) -> Dict[str, Any]:+ """Return dict with project metadata suitable for display/JSON output."""+ data = load_project(sbproj_path)+ meta = data.get("Metadata", {})+ return {+ "title": data.get("Title", ""),+ "type": data.get("Type", ""),+ "org": data.get("Org", ""),+ "ident": data.get("Ident", ""),+ "startup_scene": meta.get("StartupScene", ""),+ "max_players": meta.get("MaxPlayers"),+ "min_players": meta.get("MinPlayers"),+ "tick_rate": meta.get("TickRate"),+ "network_type": meta.get("GameNetworkType", ""),+ "map_select": meta.get("MapSelect", ""),+ "map_list": meta.get("MapList", []),+ "package_references": data.get("PackageReferences", []),+ "path": sbproj_path,+ }+++def configure_project(sbproj_path: str, **kwargs: Any) -> Dict[str, Any]:+ """Update project metadata fields.++ Accepts: title, max_players, min_players, tick_rate, network_type,+ startup_scene, map_list, map_select, org, ident, etc.++ Returns updated project info dict.+ """+ data = load_project(sbproj_path)+ meta = data.setdefault("Metadata", {})++ # Top-level fields+ top_level_map = {+ "title": "Title",+ "org": "Org",+ "ident": "Ident",+ "type": "Type",+ }+ for kwarg_key, json_key in top_level_map.items():+ if kwarg_key in kwargs:+ data[json_key] = kwargs[kwarg_key]++ # Metadata fields+ meta_map = {+ "max_players": "MaxPlayers",+ "min_players": "MinPlayers",+ "tick_rate": "TickRate",+ "network_type": "GameNetworkType",+ "map_select": "MapSelect",+ "map_list": "MapList",+ "startup_scene": "StartupScene",+ }+ for kwarg_key, json_key in meta_map.items():+ if kwarg_key in kwargs:+ meta[json_key] = kwargs[kwarg_key]++ save_project(sbproj_path, data)+ return get_project_info(sbproj_path)+++def add_package( sbproj_path: str, package_ref: str ) -> Dict[str, Any]:+ """Add a package reference to the project.++ Args:+ sbproj_path: Path to the .sbproj file.+ package_ref: Package identifier (e.g. "facepunch.libsdf", "org.package").++ Returns:+ Updated project info dict.++ Raises:+ ValueError: If the package is already referenced.+ """+ data = load_project( sbproj_path )+ refs = data.get( "PackageReferences", [] ) or []++ if package_ref in refs:+ raise ValueError( f"Package '{package_ref}' is already referenced" )++ refs.append( package_ref )+ data["PackageReferences"] = refs+ save_project( sbproj_path, data )++ return get_project_info( sbproj_path )+++def remove_package( sbproj_path: str, package_ref: str ) -> Dict[str, Any]:+ """Remove a package reference from the project.++ Returns:+ Updated project info dict.++ Raises:+ ValueError: If the package is not found.+ """+ data = load_project( sbproj_path )+ refs = data.get( "PackageReferences", [] ) or []++ if package_ref not in refs:+ raise ValueError( f"Package '{package_ref}' not found in references" )++ refs.remove( package_ref )+ data["PackageReferences"] = refs+ save_project( sbproj_path, data )++ return get_project_info( sbproj_path )+++def find_sbproj(directory: str) -> Optional[str]:+ """Find .sbproj file in a directory. Returns path or None."""+ if not os.path.isdir(directory):+ return None+ for entry in os.listdir(directory):+ if entry.endswith(".sbproj"):+ return os.path.join(directory, entry)+ return None+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _write_json(path: str, data: Dict[str, Any]) -> None:+ """Write data as formatted JSON to path."""+ os.makedirs(os.path.dirname(path), exist_ok=True)+ with open(path, "w", encoding="utf-8", newline="\r\n") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+ f.write("\n")+++def _write_text(path: str, content: str) -> None:+ """Write text content to path, ensuring parent dirs exist."""+ os.makedirs(os.path.dirname(path), exist_ok=True)+ with open(path, "w", encoding="utf-8", newline="\r\n") as f:+ f.write(content)diff --git a/sbox/agent-harness/cli_anything/sbox/core/scene.py b/sbox/agent-harness/cli_anything/sbox/core/scene.pynew file mode 100644index 000000000..781db8d94--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/scene.py@@ -0,0 +1,1407 @@+"""Manages s&box .scene files - loading, saving, querying, and modifying scene GameObjects."""++import json+import os+import uuid+from typing import Any, Dict, List, Optional, Union+++# ---------------------------------------------------------------------------+# Component presets - shortcuts for common s&box components+# ---------------------------------------------------------------------------++COMPONENT_PRESETS: Dict[str, Dict[str, Any]] = {+ "model": {+ "__type": "Sandbox.ModelRenderer",+ "Model": "models/dev/box.vmdl",+ "RenderType": "On",+ "Tint": "1,1,1,1",+ },+ "box_collider": {+ "__type": "Sandbox.BoxCollider",+ "Center": "0,0,0",+ "Scale": "50,50,50",+ "IsTrigger": False,+ "Static": False,+ },+ "sphere_collider": {+ "__type": "Sandbox.SphereCollider",+ "Center": "0,0,0",+ "Radius": 25,+ "IsTrigger": False,+ },+ "rigidbody": {+ "__type": "Sandbox.Rigidbody",+ "Gravity": True,+ "LinearDamping": 0,+ "AngularDamping": 0,+ "Locking": {},+ "MassOverride": 0,+ "MotionEnabled": True,+ "RigidbodyFlags": 0,+ "StartAsleep": False,+ },+ "camera": {+ "__type": "Sandbox.CameraComponent",+ "FieldOfView": 60,+ "ZNear": 10,+ "ZFar": 10000,+ "IsMainCamera": True,+ "BackgroundColor": "0.33333,0.46275,0.52157,1",+ },+ "light_directional": {+ "__type": "Sandbox.DirectionalLight",+ "LightColor": "0.94419,0.97767,1,1",+ "Shadows": True,+ "SkyColor": "0.2532,0.32006,0.35349,1",+ },+ "light_point": {+ "__type": "Sandbox.PointLight",+ "LightColor": "1,1,1,1",+ "Radius": 400,+ },+ "player_controller": {+ "__type": "Sandbox.PlayerController",+ },+ "spot_light": {+ "__type": "Sandbox.SpotLight",+ "LightColor": "1,1,1,1",+ "Radius": 500,+ "ConeInner": 15,+ "ConeOuter": 45,+ "Shadows": True,+ },+ "ambient_light": {+ "__type": "Sandbox.AmbientLight",+ "Color": "1,1,1,1",+ "Intensity": 1.0,+ },+ "capsule_collider": {+ "__type": "Sandbox.CapsuleCollider",+ "Start": "0,0,0",+ "End": "0,0,72",+ "Radius": 16,+ "IsTrigger": False,+ },+ "plane_collider": {+ "__type": "Sandbox.PlaneCollider",+ "Scale": "100,100",+ "IsTrigger": False,+ "Static": True,+ },+ "model_collider": {+ "__type": "Sandbox.ModelCollider",+ "Model": "models/dev/box.vmdl",+ "IsTrigger": False,+ "Static": False,+ },+ "sprite_renderer": {+ "__type": "Sandbox.SpriteRenderer",+ "Texture": "textures/dev/white.vtex",+ "Tint": "1,1,1,1",+ "Size": "64,64",+ },+ "skinned_model_renderer": {+ "__type": "Sandbox.SkinnedModelRenderer",+ "Model": "models/citizen/citizen.vmdl",+ "RenderType": "On",+ "Tint": "1,1,1,1",+ },+ "text_renderer": {+ "__type": "Sandbox.TextRenderer",+ "Text": "Hello World",+ "FontSize": 64,+ "Color": "1,1,1,1",+ },+ "line_renderer": {+ "__type": "Sandbox.LineRenderer",+ "Color": "1,1,1,1",+ "Opaque": True,+ "Width": 2,+ },+ "decal_renderer": {+ "__type": "Sandbox.DecalRenderer",+ "Material": "materials/default.vmat",+ "Size": "128,128,128",+ },+ "particle_effect": {+ "__type": "Sandbox.ParticleEffect",+ "PlayOnStart": True,+ "Loop": True,+ },+ "sound_point": {+ "__type": "Sandbox.SoundPointComponent",+ "PlayOnStart": False,+ "StopOnDestroy": True,+ },+ "nav_mesh_agent": {+ "__type": "Sandbox.NavMeshAgent",+ "MaxSpeed": 200,+ "MaxAcceleration": 800,+ "AgentRadius": 16,+ "AgentHeight": 72,+ },+ "screen_panel": {+ "__type": "Sandbox.ScreenPanel",+ "ZIndex": 100,+ "Opacity": 1.0,+ },+ "world_panel": {+ "__type": "Sandbox.WorldPanel",+ "PanelSize": "1024,768",+ "LookAtCamera": False,+ "RenderScale": 1.0,+ },+ "fixed_joint": {+ "__type": "Sandbox.FixedJoint",+ },+ "hinge_joint": {+ "__type": "Sandbox.HingeJoint",+ "MinAngle": -45,+ "MaxAngle": 45,+ },+ "spring_joint": {+ "__type": "Sandbox.SpringJoint",+ "Frequency": 5,+ "Damping": 0.5,+ },+ "ball_socket_joint": {+ "__type": "Sandbox.BallSocketJoint",+ },+ "trail_renderer": {+ "__type": "Sandbox.TrailRenderer",+ "Color": "1,1,1,1",+ "Width": 5,+ "Lifetime": 1.0,+ },+ "character_controller": {+ "__type": "Sandbox.CharacterController",+ "Height": 72,+ "Radius": 16,+ "UseCollisionRules": True,+ },+}+++# ---------------------------------------------------------------------------+# Internal helpers+# ---------------------------------------------------------------------------+++def _new_guid() -> str:+ """Generate a new UUID v4 string."""+ return str(uuid.uuid4())+++def _make_component(component_type: str, properties: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:+ """Build a component dict from a type string and optional properties.++ If *component_type* matches a key in COMPONENT_PRESETS, the preset values+ are used as defaults and *properties* are merged on top. Otherwise, a+ bare component with the given __type is created.+ """+ if component_type in COMPONENT_PRESETS:+ comp = dict(COMPONENT_PRESETS[component_type])+ else:+ comp = {"__type": component_type}++ comp["__guid"] = _new_guid()++ if properties:+ comp.update(properties)++ return comp+++def _make_game_object(+ name: str,+ position: str = "0,0,0",+ rotation: str = "0,0,0,1",+ scale: str = "1,1,1",+ tags: str = "",+ components: Optional[List[Dict[str, Any]]] = None,+ children: Optional[List[Dict[str, Any]]] = None,+ flags: int = 0,+ enabled: bool = True,+) -> Dict[str, Any]:+ """Build a GameObject dict."""+ obj: Dict[str, Any] = {+ "__guid": _new_guid(),+ "Flags": flags,+ "Name": name,+ "Enabled": enabled,+ "Position": position,+ "Rotation": rotation,+ "Scale": scale,+ "Tags": tags,+ "Components": components if components else [],+ "Children": children if children else [],+ }+ return obj+++def _build_default_objects() -> List[Dict[str, Any]]:+ """Return the default set of GameObjects for a minimal scene.++ Includes: Sun (DirectionalLight), 2D Skybox (SkyBox2D + EnvmapProbe),+ Plane (ModelRenderer + BoxCollider), Camera (CameraComponent + post-processing).+ """+ sun = _make_game_object(+ name="Sun",+ position="0,0,0",+ rotation="-0.0591653,0.5160446,0.0340129,0.8537855",+ components=[+ _make_component("light_directional"),+ ],+ )++ skybox = _make_game_object(+ name="2D Skybox",+ tags="skybox",+ components=[+ {+ "__guid": _new_guid(),+ "__type": "Sandbox.SkyBox2D",+ "SkyMaterial": "materials/skybox/skybox_day_01.vmat",+ "Tint": "1,1,1,1",+ },+ {+ "__guid": _new_guid(),+ "__type": "Sandbox.EnvmapProbe",+ "Texture": "textures/cubemaps/default2.vtex",+ "Bounds": "512,512,512",+ "Feathering": 0.02,+ },+ ],+ )++ plane = _make_game_object(+ name="Plane",+ position="0,0,0",+ scale="5,5,5",+ components=[+ {+ "__guid": _new_guid(),+ "__type": "Sandbox.ModelRenderer",+ "Model": "models/dev/plane.vmdl",+ "RenderType": "On",+ "Tint": "0.39546,0.51320,0.27128,1",+ "MaterialOverride": "materials/default.vmat",+ },+ {+ "__guid": _new_guid(),+ "__type": "Sandbox.BoxCollider",+ "Center": "0,0,-5",+ "Scale": "100,100,10",+ "IsTrigger": False,+ "Static": True,+ },+ ],+ )++ camera = _make_game_object(+ name="Camera",+ position="0,-200,150",+ rotation="0.16307,0,0,0.98663",+ components=[+ _make_component("camera"),+ {+ "__guid": _new_guid(),+ "__type": "Sandbox.Bloom",+ "Threshold": 0.5,+ "ThresholdWidth": 0.5,+ "MaximumBloom": 0.5,+ "Mode": "Additive",+ "BlurWeight": 1,+ },+ {+ "__guid": _new_guid(),+ "__type": "Sandbox.Tonemapping",+ "Mode": "ACES",+ "ExposureCompensation": 0,+ "MinimumExposure": 1,+ "MaximumExposure": 2,+ "Rate": 1,+ },+ {+ "__guid": _new_guid(),+ "__type": "Sandbox.Sharpen",+ "Scale": 0.2,+ },+ ],+ )++ return [sun, skybox, plane, camera]+++def _flatten_objects(objects: List[Dict[str, Any]]) -> List[Dict[str, Any]]:+ """Recursively flatten a hierarchy of GameObjects into a flat list."""+ result: List[Dict[str, Any]] = []+ for obj in objects:+ result.append(obj)+ children = obj.get("Children", [])+ if children:+ result.extend(_flatten_objects(children))+ return result+++def _remove_from_list(+ objects: List[Dict[str, Any]],+ name: Optional[str] = None,+ guid: Optional[str] = None,+) -> bool:+ """Remove a GameObject from a list (including nested Children). Returns True if removed."""+ for i, obj in enumerate(objects):+ if (guid and obj.get("__guid") == guid) or (name and obj.get("Name") == name):+ objects.pop(i)+ return True+ children = obj.get("Children", [])+ if children and _remove_from_list(children, name=name, guid=guid):+ return True+ return False+++def _write_json(path: str, data: Dict[str, Any]) -> None:+ """Write data as formatted JSON to path."""+ os.makedirs(os.path.dirname(path) if os.path.dirname(path) else ".", exist_ok=True)+ with open(path, "w", encoding="utf-8", newline="\r\n") as f:+ json.dump(data, f, indent=2, ensure_ascii=False)+ f.write("\n")+++# ---------------------------------------------------------------------------+# Public API+# ---------------------------------------------------------------------------+++def create_scene(+ name: str = "minimal",+ output_path: Optional[str] = None,+ fixed_update_freq: int = 50,+ network_freq: int = 60,+ include_defaults: bool = True,+) -> Dict[str, Any]:+ """Create a new .scene file.++ If *include_defaults* is True, adds Sun, Skybox, Plane, and Camera+ GameObjects to the scene.++ Returns the scene data dict.+ """+ game_objects: List[Dict[str, Any]] = []+ if include_defaults:+ game_objects = _build_default_objects()++ scene: Dict[str, Any] = {+ "GameObjects": game_objects,+ "SceneProperties": {+ "FixedUpdateFrequency": fixed_update_freq,+ "MaxFixedUpdates": 5,+ "NetworkFrequency": network_freq,+ "NetworkInterpolation": True,+ "PhysicsSubSteps": 1,+ "ThreadedAnimation": True,+ "TimeScale": 1,+ "UseFixedUpdate": True,+ },+ "Title": name,+ "Description": "",+ "ResourceVersion": 1,+ "__references": [],+ "__version": 1,+ }++ if output_path:+ _write_json(output_path, scene)++ return scene+++def load_scene(scene_path: str) -> Dict[str, Any]:+ """Load and return parsed scene JSON."""+ with open(scene_path, "r", encoding="utf-8") as f:+ return json.load(f)+++def save_scene(scene_path: str, data: Dict[str, Any]) -> None:+ """Save scene JSON with proper formatting."""+ _write_json(scene_path, data)+++def get_scene_info(scene_path: str) -> Dict[str, Any]:+ """Return dict with scene metadata and object summary."""+ data = load_scene(scene_path)+ props = data.get("SceneProperties", {})+ objects = data.get("GameObjects", [])+ flat = _flatten_objects(objects)++ # Gather unique component types+ component_types: set = set()+ for obj in flat:+ for comp in obj.get("Components", []):+ ctype = comp.get("__type", "")+ if ctype:+ component_types.add(ctype)++ return {+ "title": data.get("Title", ""),+ "description": data.get("Description", ""),+ "path": scene_path,+ "fixed_update_freq": props.get("FixedUpdateFrequency"),+ "network_freq": props.get("NetworkFrequency"),+ "object_count": len(flat),+ "top_level_objects": len(objects),+ "component_types": sorted(component_types),+ }+++def list_objects(scene_path: str) -> List[Dict[str, Any]]:+ """Return list of dicts with each GameObject's guid, name, position, component types."""+ data = load_scene(scene_path)+ flat = _flatten_objects(data.get("GameObjects", []))+ result: List[Dict[str, Any]] = []+ for obj in flat:+ comp_types = [c.get("__type", "") for c in obj.get("Components", []) if c.get("__type")]+ result.append({+ "guid": obj.get("__guid", ""),+ "name": obj.get("Name", ""),+ "position": obj.get("Position", "0,0,0"),+ "component_types": comp_types,+ })+ return result+++def find_object(+ scene_data: Dict[str, Any],+ name: Optional[str] = None,+ guid: Optional[str] = None,+) -> Optional[Dict[str, Any]]:+ """Find a GameObject by name or guid in scene data. Returns the object dict or None."""+ objects = scene_data.get("GameObjects", [])+ flat = _flatten_objects(objects)+ for obj in flat:+ if guid and obj.get("__guid") == guid:+ return obj+ if name and obj.get("Name") == name:+ return obj+ return None+++def add_object(+ scene_path: str,+ name: str,+ position: str = "0,0,0",+ rotation: str = "0,0,0,1",+ scale: str = "1,1,1",+ tags: str = "",+ components: Optional[List[Dict[str, Any]]] = None,+ parent_guid: Optional[str] = None,+) -> str:+ """Add a new GameObject to the scene.++ *components* is a list of component dicts. Each dict should have at least+ a ``__type`` key, or be a preset name string that will be resolved via+ COMPONENT_PRESETS.++ If *parent_guid* is specified, adds the object as a child of that parent.++ Returns the new object's guid.+ """+ data = load_scene(scene_path)++ # Resolve component specs+ resolved_components: List[Dict[str, Any]] = []+ if components:+ for comp in components:+ if isinstance(comp, str):+ resolved_components.append(_make_component(comp))+ elif isinstance(comp, dict):+ c = dict(comp)+ if "__guid" not in c:+ c["__guid"] = _new_guid()+ resolved_components.append(c)++ obj = _make_game_object(+ name=name,+ position=position,+ rotation=rotation,+ scale=scale,+ tags=tags,+ components=resolved_components,+ )+ new_guid = obj["__guid"]++ if parent_guid:+ parent = find_object(data, guid=parent_guid)+ if parent is None:+ raise ValueError(f"Parent object with guid '{parent_guid}' not found")+ parent.setdefault("Children", []).append(obj)+ else:+ data.setdefault("GameObjects", []).append(obj)++ save_scene(scene_path, data)+ return new_guid+++def remove_object(+ scene_path: str,+ name: Optional[str] = None,+ guid: Optional[str] = None,+) -> bool:+ """Remove a GameObject by name or guid. Returns True if removed."""+ if not name and not guid:+ raise ValueError("Must specify either name or guid")++ data = load_scene(scene_path)+ objects = data.get("GameObjects", [])+ removed = _remove_from_list(objects, name=name, guid=guid)+ if removed:+ save_scene(scene_path, data)+ return removed+++def add_component(+ scene_path: str,+ object_guid: str,+ component_type: str,+ properties: Optional[Dict[str, Any]] = None,+) -> str:+ """Add a component to a GameObject.++ *component_type* is either a preset name (e.g. ``"rigidbody"``) or a+ fully qualified type (e.g. ``"Sandbox.Rigidbody"``).++ *properties* is a dict of component properties to set/override.++ Returns the new component's guid.+ """+ data = load_scene(scene_path)+ obj = find_object(data, guid=object_guid)+ if obj is None:+ raise ValueError(f"GameObject with guid '{object_guid}' not found")++ comp = _make_component(component_type, properties)+ comp_guid = comp["__guid"]+ obj.setdefault("Components", []).append(comp)++ save_scene(scene_path, data)+ return comp_guid+++def remove_component(+ scene_path: str,+ object_guid: str,+ component_guid: Optional[str] = None,+ component_type: Optional[str] = None,+) -> bool:+ """Remove a component from a GameObject by guid or type.++ Returns True if a component was removed.+ """+ if not component_guid and not component_type:+ raise ValueError("Must specify either component_guid or component_type")++ data = load_scene(scene_path)+ obj = find_object(data, guid=object_guid)+ if obj is None:+ raise ValueError(f"GameObject with guid '{object_guid}' not found")++ components = obj.get("Components", [])+ for i, comp in enumerate(components):+ if component_guid and comp.get("__guid") == component_guid:+ components.pop(i)+ save_scene(scene_path, data)+ return True+ if component_type and comp.get("__type") == component_type:+ components.pop(i)+ save_scene(scene_path, data)+ return True++ return False+++def modify_object(+ scene_path: str,+ guid: Optional[str] = None,+ name_match: Optional[str] = None,+ new_name: Optional[str] = None,+ position: Optional[str] = None,+ rotation: Optional[str] = None,+ scale: Optional[str] = None,+ tags: Optional[str] = None,+ enabled: Optional[bool] = None,+) -> Dict[str, Any]:+ """Modify properties of an existing GameObject in a scene.++ Finds the object by guid or name_match, then updates only the fields+ that are explicitly provided (non-None).++ Returns dict with guid, name, and list of modified_fields.+ Raises ValueError if object not found or no identifier given.+ """+ if guid is None and name_match is None:+ raise ValueError( "Must provide either guid or name_match to identify the object" )++ data = load_scene( scene_path )+ obj = find_object( data, name=name_match, guid=guid )+ if obj is None:+ identifier = guid or name_match+ raise ValueError( f"Object '{identifier}' not found in scene" )++ modified_fields = []++ if new_name is not None:+ obj["Name"] = new_name+ modified_fields.append( "Name" )+ if position is not None:+ obj["Position"] = position+ modified_fields.append( "Position" )+ if rotation is not None:+ obj["Rotation"] = rotation+ modified_fields.append( "Rotation" )+ if scale is not None:+ obj["Scale"] = scale+ modified_fields.append( "Scale" )+ if tags is not None:+ obj["Tags"] = tags+ modified_fields.append( "Tags" )+ if enabled is not None:+ obj["Enabled"] = enabled+ modified_fields.append( "Enabled" )++ save_scene( scene_path, data )++ return {+ "guid": obj["__guid"],+ "name": obj["Name"],+ "modified_fields": modified_fields,+ }+++# Mapping from snake_case kwargs to SceneProperties JSON keys+_SCENE_PROPERTY_MAP: Dict[str, str] = {+ "fixed_update_freq": "FixedUpdateFrequency",+ "max_fixed_updates": "MaxFixedUpdates",+ "network_freq": "NetworkFrequency",+ "network_interpolation": "NetworkInterpolation",+ "physics_sub_steps": "PhysicsSubSteps",+ "threaded_animation": "ThreadedAnimation",+ "timescale": "TimeScale",+ "use_fixed_update": "UseFixedUpdate",+}+++def set_scene_properties(+ scene_path: str,+ **kwargs: Any,+) -> Dict[str, Any]:+ """Modify SceneProperties of a scene file.++ Accepts keyword arguments matching the keys in _SCENE_PROPERTY_MAP.+ Only updates properties that are explicitly provided.++ Returns the updated SceneProperties dict.+ """+ data = load_scene( scene_path )+ props = data.get( "SceneProperties", {} )++ updated = []+ for kwarg_key, value in kwargs.items():+ json_key = _SCENE_PROPERTY_MAP.get( kwarg_key )+ if json_key is None:+ raise ValueError( f"Unknown scene property: '{kwarg_key}'" )+ props[json_key] = value+ updated.append( json_key )++ data["SceneProperties"] = props+ save_scene( scene_path, data )++ return props+++_NAVMESH_PROPERTY_MAP: Dict[str, str] = {+ "navmesh_enabled": "Enabled",+ "navmesh_include_static": "IncludeStaticBodies",+ "navmesh_include_keyframed": "IncludeKeyframedBodies",+ "navmesh_agent_height": "AgentHeight",+ "navmesh_agent_radius": "AgentRadius",+ "navmesh_agent_step_size": "AgentStepSize",+ "navmesh_agent_max_slope": "AgentMaxSlope",+}+++def set_navmesh_properties(+ scene_path: str,+ **kwargs: Any,+) -> Dict[str, Any]:+ """Modify NavMesh properties of a scene file.++ Accepts keyword arguments matching _NAVMESH_PROPERTY_MAP keys.+ Returns the updated NavMesh properties dict.+ """+ data = load_scene( scene_path )+ props = data.get( "SceneProperties", {} )+ navmesh = props.get( "NavMesh", {} )++ for kwarg_key, value in kwargs.items():+ json_key = _NAVMESH_PROPERTY_MAP.get( kwarg_key )+ if json_key is None:+ raise ValueError( f"Unknown navmesh property: '{kwarg_key}'" )+ navmesh[json_key] = value++ props["NavMesh"] = navmesh+ data["SceneProperties"] = props+ save_scene( scene_path, data )++ return navmesh+++def modify_component(+ scene_path: str,+ object_guid: str,+ component_guid: Optional[str] = None,+ component_type: Optional[str] = None,+ properties: Optional[Dict[str, Any]] = None,+) -> Dict[str, Any]:+ """Modify properties of an existing component on a GameObject.++ Finds the component by component_guid or component_type, then merges+ the provided properties onto it (only updates keys present in properties).++ Returns dict with object_guid, component_guid, component_type, and updated keys.+ Raises ValueError if object or component not found.+ """+ if component_guid is None and component_type is None:+ raise ValueError( "Must provide either component_guid or component_type" )+ if properties is None or len( properties ) == 0:+ raise ValueError( "No properties specified to modify" )++ data = load_scene( scene_path )+ obj = find_object( data, guid=object_guid )+ if obj is None:+ raise ValueError( f"Object '{object_guid}' not found in scene" )++ target_comp = None+ for comp in obj.get( "Components", [] ):+ if component_guid and comp.get( "__guid" ) == component_guid:+ target_comp = comp+ break+ if component_type and comp.get( "__type" ) == component_type:+ target_comp = comp+ break++ if target_comp is None:+ identifier = component_guid or component_type+ raise ValueError( f"Component '{identifier}' not found on object '{object_guid}'" )++ updated_keys = []+ for key, value in properties.items():+ target_comp[key] = value+ updated_keys.append( key )++ save_scene( scene_path, data )++ return {+ "object_guid": object_guid,+ "component_guid": target_comp.get( "__guid", "" ),+ "component_type": target_comp.get( "__type", "" ),+ "updated_keys": updated_keys,+ }+++def clone_object(+ scene_path: str,+ guid: Optional[str] = None,+ name: Optional[str] = None,+ new_name: Optional[str] = None,+ position: Optional[str] = None,+) -> Dict[str, Any]:+ """Clone (duplicate) a GameObject in a scene.++ Finds the original by guid or name, deep-copies it with new GUIDs,+ optionally renames and repositions the clone.++ Returns dict with the new object's guid and name.+ """+ import copy++ data = load_scene( scene_path )+ original = find_object( data, name=name, guid=guid )+ if original is None:+ identifier = guid or name+ raise ValueError( f"Object '{identifier}' not found in scene" )++ clone = copy.deepcopy( original )++ # Regenerate all GUIDs in the clone+ _regenerate_guids( clone )++ if new_name is not None:+ clone["Name"] = new_name+ else:+ clone["Name"] = original["Name"] + " (Clone)"++ if position is not None:+ clone["Position"] = position++ # Add clone as top-level object+ data["GameObjects"].append( clone )+ save_scene( scene_path, data )++ return {+ "guid": clone["__guid"],+ "name": clone["Name"],+ "original_guid": original["__guid"],+ "original_name": original["Name"],+ }+++def _regenerate_guids( obj: Dict[str, Any] ) -> None:+ """Recursively regenerate all __guid fields in an object and its children/components."""+ if "__guid" in obj:+ obj["__guid"] = _new_guid()+ for comp in obj.get( "Components", [] ):+ if "__guid" in comp:+ comp["__guid"] = _new_guid()+ for child in obj.get( "Children", [] ):+ _regenerate_guids( child )+++def get_object(+ scene_path: str,+ guid: Optional[str] = None,+ name: Optional[str] = None,+) -> Dict[str, Any]:+ """Get full details of a single GameObject.++ Returns dict with guid, name, position, rotation, scale, tags, enabled,+ components (list of type + properties), and children count.+ Raises ValueError if not found.+ """+ data = load_scene( scene_path )+ obj = find_object( data, name=name, guid=guid )+ if obj is None:+ identifier = guid or name+ raise ValueError( f"Object '{identifier}' not found in scene" )++ components = []+ for comp in obj.get( "Components", [] ):+ c = {"guid": comp.get( "__guid", "" ), "type": comp.get( "__type", "" )}+ # Include all non-internal properties+ for k, v in comp.items():+ if not k.startswith( "__" ):+ c[k] = v+ components.append( c )++ return {+ "guid": obj.get( "__guid", "" ),+ "name": obj.get( "Name", "" ),+ "position": obj.get( "Position", "0,0,0" ),+ "rotation": obj.get( "Rotation", "0,0,0,1" ),+ "scale": obj.get( "Scale", "1,1,1" ),+ "tags": obj.get( "Tags", "" ),+ "enabled": obj.get( "Enabled", True ),+ "components": components,+ "children_count": len( obj.get( "Children", [] ) ),+ }+++# ---------------------------------------------------------------------------+# Query, asset-ref extraction, and bulk operations+# ---------------------------------------------------------------------------+++def _resolve_component_type( component: str ) -> str:+ """Resolve a component preset name to its full Sandbox type, or pass through.++ Args:+ component: Either a preset key (e.g. "rigidbody") or a fully qualified+ type (e.g. "Sandbox.Rigidbody" or "MyGame.MyComponent").++ Returns:+ The fully qualified type string.+ """+ if component in COMPONENT_PRESETS:+ return COMPONENT_PRESETS[component]["__type"]+ return component+++def _object_has_component( obj: Dict[str, Any], component_type: str ) -> bool:+ """Check whether obj has any component matching component_type (exact match)."""+ for comp in obj.get( "Components", [] ):+ if comp.get( "__type" ) == component_type:+ return True+ return False+++def _object_has_tag( obj: Dict[str, Any], tag: str ) -> bool:+ """Check whether the object's Tags string contains *tag* as a token."""+ raw = obj.get( "Tags", "" )+ if not raw:+ return False+ tokens = [t.strip() for t in raw.split( "," )]+ return tag in tokens+++def _parse_position_bounds( bounds: str ) -> "tuple[tuple[float,float,float], tuple[float,float,float]]":+ """Parse a bounds string ``"x_min,y_min,z_min,x_max,y_max,z_max"`` into two tuples."""+ parts = [p.strip() for p in bounds.split( "," )]+ if len( parts ) != 6:+ raise ValueError( "bounds must be 6 comma-separated numbers: x_min,y_min,z_min,x_max,y_max,z_max" )+ nums = tuple( float( p ) for p in parts )+ return nums[:3], nums[3:]+++def _object_in_bounds( obj: Dict[str, Any], bounds: str ) -> bool:+ """Check whether obj.Position lies inside the given AABB bounds string."""+ pos_str = obj.get( "Position", "0,0,0" )+ try:+ pos = tuple( float( p.strip() ) for p in pos_str.split( "," ) )+ except (ValueError, AttributeError):+ return False+ if len( pos ) != 3:+ return False+ lo, hi = _parse_position_bounds( bounds )+ return all( lo[i] <= pos[i] <= hi[i] for i in range( 3 ) )+++def query_objects(+ scene_path: str,+ has_component: Optional[str] = None,+ has_tag: Optional[str] = None,+ name_match: Optional[str] = None,+ name_regex: Optional[str] = None,+ in_bounds: Optional[str] = None,+ enabled: Optional[bool] = None,+) -> List[Dict[str, Any]]:+ """Find GameObjects matching the given criteria.++ All provided filters are AND-combined. Searches all objects (top-level and+ nested children). Component filter accepts either a preset key (e.g.+ ``"rigidbody"``) or a fully qualified type (e.g. ``"Sandbox.Rigidbody"``).++ Args:+ scene_path: Path to the .scene file.+ has_component: Match objects that have at least one component of this type.+ has_tag: Match objects whose Tags include this tag.+ name_match: Substring match on Name.+ name_regex: Regex pattern match on Name.+ in_bounds: AABB filter "x_min,y_min,z_min,x_max,y_max,z_max" on Position.+ enabled: If set, match only objects with this Enabled value.++ Returns:+ List of dicts with guid, name, position, tags, component_types.+ """+ import re++ data = load_scene( scene_path )+ flat = _flatten_objects( data.get( "GameObjects", [] ) )++ resolved_component = _resolve_component_type( has_component ) if has_component else None+ compiled_regex = re.compile( name_regex ) if name_regex else None++ results: List[Dict[str, Any]] = []+ for obj in flat:+ if resolved_component and not _object_has_component( obj, resolved_component ):+ continue+ if has_tag and not _object_has_tag( obj, has_tag ):+ continue+ if name_match and name_match not in obj.get( "Name", "" ):+ continue+ if compiled_regex and not compiled_regex.search( obj.get( "Name", "" ) ):+ continue+ if in_bounds and not _object_in_bounds( obj, in_bounds ):+ continue+ if enabled is not None and obj.get( "Enabled", True ) != enabled:+ continue++ comp_types = [c.get( "__type", "" ) for c in obj.get( "Components", [] ) if c.get( "__type" )]+ results.append( {+ "guid": obj.get( "__guid", "" ),+ "name": obj.get( "Name", "" ),+ "position": obj.get( "Position", "0,0,0" ),+ "tags": obj.get( "Tags", "" ),+ "component_types": comp_types,+ } )++ return results+++# Asset-reference detection ----------------------------------------------------++# Engine asset extensions found in scene/prefab JSON string values.+ASSET_REF_EXTENSIONS = (+ ".vmdl",+ ".vmat",+ ".vsnd",+ ".sound",+ ".vtex",+ ".vpcf",+ ".prefab",+ ".scene",+ ".vanmgrph",+ ".animgraph",+ ".shader",+)++# Field names in component dicts whose string values are asset paths even if+# they don't end with a known extension (e.g. "models/dev/box" without .vmdl).+_ASSET_PATH_FIELDS = {+ "Model",+ "Material",+ "MaterialOverride",+ "SkyMaterial",+ "Texture",+ "Sound",+ "Prefab",+ "PrefabSource",+ "TargetPrefab",+}+++def _is_asset_ref( value: str ) -> bool:+ """Return True if *value* looks like an asset path."""+ if not isinstance( value, str ) or not value:+ return False+ lower = value.lower()+ return any( lower.endswith( ext ) for ext in ASSET_REF_EXTENSIONS )+++def _walk_for_refs( node: Any, refs: Dict[str, List[str]], path_stack: List[str] ) -> None:+ """Recursively walk a JSON tree, recording asset references by category.++ Each detected reference is stored under its asset-extension key, with the+ JSON breadcrumb path indicating where it was found.+ """+ if isinstance( node, dict ):+ for key, value in node.items():+ new_stack = path_stack + [str( key )]+ if isinstance( value, str ):+ hit = None+ if _is_asset_ref( value ):+ hit = value+ elif key in _ASSET_PATH_FIELDS and value.strip():+ hit = value+ if hit:+ # Categorize by extension if present, else by field+ category = _category_for_ref( hit, key )+ refs.setdefault( category, [] ).append( hit )+ else:+ _walk_for_refs( value, refs, new_stack )+ elif isinstance( node, list ):+ for i, item in enumerate( node ):+ _walk_for_refs( item, refs, path_stack + [f"[{i}]"] )+++def _category_for_ref( ref: str, field: str = "" ) -> str:+ """Map an asset reference to a category bucket."""+ lower = ref.lower()+ if lower.endswith( ".vmdl" ):+ return "models"+ if lower.endswith( ".vmat" ):+ return "materials"+ if lower.endswith( ".vsnd" ) or lower.endswith( ".sound" ):+ return "sounds"+ if lower.endswith( ".vtex" ):+ return "textures"+ if lower.endswith( ".vpcf" ):+ return "particles"+ if lower.endswith( ".prefab" ):+ return "prefabs"+ if lower.endswith( ".scene" ):+ return "scenes"+ if lower.endswith( ".animgraph" ) or lower.endswith( ".vanmgrph" ):+ return "animgraphs"+ if lower.endswith( ".shader" ):+ return "shaders"+ if field == "Model":+ return "models"+ if field in ( "Material", "MaterialOverride", "SkyMaterial" ):+ return "materials"+ if field == "Texture":+ return "textures"+ if field == "Sound":+ return "sounds"+ if field in ( "Prefab", "PrefabSource", "TargetPrefab" ):+ return "prefabs"+ return "other"+++def extract_asset_refs( scene_path: str ) -> Dict[str, List[str]]:+ """Extract every asset reference from a scene file.++ Returns:+ Dict mapping category ("models", "materials", "sounds", "textures",+ "particles", "prefabs", "scenes", "animgraphs", "shaders", "other")+ to a sorted, deduplicated list of asset paths.+ """+ data = load_scene( scene_path )+ refs: Dict[str, List[str]] = {}+ _walk_for_refs( data.get( "GameObjects", [] ), refs, ["GameObjects"] )+ # Also walk SceneProperties (e.g. NavMesh references)+ if "SceneProperties" in data:+ _walk_for_refs( data["SceneProperties"], refs, ["SceneProperties"] )+ # Deduplicate and sort each category+ return {cat: sorted( set( paths ) ) for cat, paths in refs.items()}+++def _object_summary( obj: Dict[str, Any] ) -> Dict[str, Any]:+ """Compress a GameObject dict to its comparable surface for diffing."""+ comps_by_type: Dict[str, Dict[str, Any]] = {}+ for comp in obj.get( "Components", [] ):+ ctype = comp.get( "__type", "" )+ if not ctype:+ continue+ # Strip internal keys, keep public properties+ stripped = {k: v for k, v in comp.items() if not k.startswith( "__" )}+ comps_by_type[ctype] = stripped++ return {+ "name": obj.get( "Name", "" ),+ "position": obj.get( "Position", "0,0,0" ),+ "rotation": obj.get( "Rotation", "0,0,0,1" ),+ "scale": obj.get( "Scale", "1,1,1" ),+ "tags": obj.get( "Tags", "" ),+ "enabled": obj.get( "Enabled", True ),+ "components": comps_by_type,+ "child_count": len( obj.get( "Children", [] ) ),+ }+++def _diff_two_objects( name: str, a: Dict[str, Any], b: Dict[str, Any] ) -> Optional[Dict[str, Any]]:+ """Compare two object summaries and return the differences, or None if identical."""+ diffs: Dict[str, Any] = {}++ for field in ( "position", "rotation", "scale", "tags", "enabled", "child_count" ):+ if a.get( field ) != b.get( field ):+ diffs[field] = {"from": a.get( field ), "to": b.get( field )}++ a_comps = a.get( "components", {} )+ b_comps = b.get( "components", {} )+ a_types = set( a_comps.keys() )+ b_types = set( b_comps.keys() )++ added_comps = sorted( b_types - a_types )+ removed_comps = sorted( a_types - b_types )+ modified_comps: Dict[str, Dict[str, Any]] = {}++ for ctype in a_types & b_types:+ if a_comps[ctype] != b_comps[ctype]:+ keys_a = set( a_comps[ctype].keys() )+ keys_b = set( b_comps[ctype].keys() )+ field_changes: Dict[str, Any] = {}+ for k in (keys_a | keys_b):+ va, vb = a_comps[ctype].get( k ), b_comps[ctype].get( k )+ if va != vb:+ field_changes[k] = {"from": va, "to": vb}+ if field_changes:+ modified_comps[ctype] = field_changes++ if added_comps:+ diffs["components_added"] = added_comps+ if removed_comps:+ diffs["components_removed"] = removed_comps+ if modified_comps:+ diffs["components_modified"] = modified_comps++ if not diffs:+ return None+ return {"name": name, "changes": diffs}+++def diff_scenes( scene_a_path: str, scene_b_path: str ) -> Dict[str, Any]:+ """Structural diff between two scene files.++ Compares by GameObject Name (not GUID, since GUIDs differ across branches).+ Reports objects added in B, removed from B (that were in A), and objects+ whose summary or components differ.++ Returns:+ Dict with 'added' (list of names), 'removed' (list of names),+ 'modified' (list of {name, changes}), 'identical' (bool), and+ 'scene_property_changes' (dict of changed SceneProperties keys).+ """+ data_a = load_scene( scene_a_path )+ data_b = load_scene( scene_b_path )++ flat_a = _flatten_objects( data_a.get( "GameObjects", [] ) )+ flat_b = _flatten_objects( data_b.get( "GameObjects", [] ) )++ summary_a = {obj.get( "Name", f"<unnamed:{i}>" ): _object_summary( obj ) for i, obj in enumerate( flat_a )}+ summary_b = {obj.get( "Name", f"<unnamed:{i}>" ): _object_summary( obj ) for i, obj in enumerate( flat_b )}++ names_a = set( summary_a.keys() )+ names_b = set( summary_b.keys() )++ added = sorted( names_b - names_a )+ removed = sorted( names_a - names_b )+ modified: List[Dict[str, Any]] = []+ for name in sorted( names_a & names_b ):+ d = _diff_two_objects( name, summary_a[name], summary_b[name] )+ if d:+ modified.append( d )++ # Scene properties diff+ props_a = data_a.get( "SceneProperties", {} ) or {}+ props_b = data_b.get( "SceneProperties", {} ) or {}+ sp_changes: Dict[str, Any] = {}+ for k in set( props_a.keys() ) | set( props_b.keys() ):+ if props_a.get( k ) != props_b.get( k ):+ sp_changes[k] = {"from": props_a.get( k ), "to": props_b.get( k )}++ identical = not (added or removed or modified or sp_changes)+ return {+ "scene_a": scene_a_path,+ "scene_b": scene_b_path,+ "added": added,+ "removed": removed,+ "modified": modified,+ "scene_property_changes": sp_changes,+ "identical": identical,+ }+++def instantiate_prefab(+ scene_path: str,+ prefab_path: str,+ name: Optional[str] = None,+ position: str = "0,0,0",+ rotation: str = "0,0,0,1",+ scale: str = "1,1,1",+ parent_guid: Optional[str] = None,+) -> str:+ """Insert a prefab reference into a scene as a new GameObject.++ Reads the prefab to derive a default name (from RootObject.Name) and+ creates a GameObject in the scene with a PrefabSource reference, fresh+ GUIDs, and the given transform. The prefab is referenced (not deep-copied+ or "exploded").++ Args:+ scene_path: Path to the .scene file to mutate.+ prefab_path: Path to the .prefab file to instantiate. Stored as a+ relative-to-Assets reference if it lives under Assets/.+ name: Optional override for the new GameObject's Name. Defaults to+ the prefab RootObject's Name.+ position, rotation, scale: Transform of the new object.+ parent_guid: Optional parent GameObject guid (otherwise added at root).++ Returns:+ The new GameObject's guid.+ """+ # Load the prefab to extract its name+ with open( prefab_path, "r", encoding="utf-8" ) as f:+ prefab_data = json.load( f )++ root = prefab_data.get( "RootObject", {} )+ default_name = root.get( "Name", os.path.splitext( os.path.basename( prefab_path ) )[0] )+ obj_name = name if name is not None else default_name++ # Compute a project-relative reference for PrefabSource+ abs_prefab = os.path.abspath( prefab_path )+ prefab_ref = abs_prefab.replace( "\\", "/" )+ norm_lower = prefab_ref.lower()+ if "/assets/" in norm_lower:+ idx = norm_lower.rindex( "/assets/" )+ prefab_ref = prefab_ref[idx + len( "/assets/" ):]++ data = load_scene( scene_path )++ # Build the GameObject with a PrefabSource pointer+ new_obj: Dict[str, Any] = {+ "__guid": _new_guid(),+ "Flags": 0,+ "Name": obj_name,+ "Enabled": True,+ "Position": position,+ "Rotation": rotation,+ "Scale": scale,+ "Tags": "",+ "PrefabSource": prefab_ref,+ "Components": [],+ "Children": [],+ }++ if parent_guid:+ parent = find_object( data, guid=parent_guid )+ if parent is None:+ raise ValueError( f"Parent object with guid '{parent_guid}' not found" )+ parent.setdefault( "Children", [] ).append( new_obj )+ else:+ data.setdefault( "GameObjects", [] ).append( new_obj )++ save_scene( scene_path, data )+ return new_obj["__guid"]+++def bulk_modify_objects(+ scene_path: str,+ has_component: Optional[str] = None,+ has_tag: Optional[str] = None,+ name_match: Optional[str] = None,+ name_regex: Optional[str] = None,+ in_bounds: Optional[str] = None,+ enabled_filter: Optional[bool] = None,+ new_position: Optional[str] = None,+ new_rotation: Optional[str] = None,+ new_scale: Optional[str] = None,+ new_tags: Optional[str] = None,+ new_enabled: Optional[bool] = None,+) -> Dict[str, Any]:+ """Apply the same modification to every GameObject matching the filters.++ Reads the scene once, runs the query, mutates each match in place, and+ writes the scene back. At least one ``new_*`` value must be provided.++ Returns:+ Dict with ``modified_count``, ``modified_fields``, and ``modified_guids``.+ """+ update_fields = {+ "Position": new_position,+ "Rotation": new_rotation,+ "Scale": new_scale,+ "Tags": new_tags,+ "Enabled": new_enabled,+ }+ active_updates = {k: v for k, v in update_fields.items() if v is not None}+ if not active_updates:+ raise ValueError( "Must provide at least one modification (new_position, new_rotation, etc.)" )++ matches = query_objects(+ scene_path,+ has_component=has_component,+ has_tag=has_tag,+ name_match=name_match,+ name_regex=name_regex,+ in_bounds=in_bounds,+ enabled=enabled_filter,+ )++ if not matches:+ return {+ "modified_count": 0,+ "modified_fields": list( active_updates.keys() ),+ "modified_guids": [],+ }++ data = load_scene( scene_path )+ flat = _flatten_objects( data.get( "GameObjects", [] ) )+ by_guid = {obj.get( "__guid" ): obj for obj in flat}++ modified_guids: List[str] = []+ for match in matches:+ guid = match["guid"]+ obj = by_guid.get( guid )+ if obj is None:+ continue+ for key, value in active_updates.items():+ obj[key] = value+ modified_guids.append( guid )++ save_scene( scene_path, data )++ return {+ "modified_count": len( modified_guids ),+ "modified_fields": list( active_updates.keys() ),+ "modified_guids": modified_guids,+ }diff --git a/sbox/agent-harness/cli_anything/sbox/core/session.py b/sbox/agent-harness/cli_anything/sbox/core/session.pynew file mode 100644index 000000000..d5bdce835--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/session.py@@ -0,0 +1,308 @@+"""Manages CLI session state with undo/redo support."""++import copy+import json+import os+import time+from pathlib import Path+from typing import Any, Dict, List, Optional+++# Default session directory and file+_DEFAULT_SESSION_DIR = os.path.join( Path.home(), ".cli-anything-sbox" )+_DEFAULT_SESSION_FILE = os.path.join( _DEFAULT_SESSION_DIR, "session.json" )++# Valid operation types for record_operation+VALID_OP_TYPES = frozenset( {+ "scene_modify",+ "project_modify",+ "input_modify",+ "collision_modify",+ "file_create",+ "codegen",+} )+++def _empty_session_data() -> Dict[str, Any]:+ """Return a blank session data structure."""+ now = time.time()+ return {+ "project_path": None,+ "scene_path": None,+ "modified": False,+ "undo_stack": [],+ "redo_stack": [],+ "created_at": now,+ "updated_at": now,+ }+++class Session:+ """Manages CLI session state with undo/redo support.++ Session file is stored at ~/.cli-anything-sbox/session.json by default.++ Tracks:+ - Current project path+ - Current scene path+ - Operation history (undo/redo stacks)+ - Modified flag+ """++ def __init__( self, session_path: Optional[str] = None ) -> None:+ """Initialize or load an existing session.++ Args:+ session_path: Path to the session JSON file.+ Defaults to ~/.cli-anything-sbox/session.json+ """+ self._session_path: str = session_path or _DEFAULT_SESSION_FILE+ self._data: Dict[str, Any] = _empty_session_data()++ if os.path.isfile( self._session_path ):+ self.load()++ # ------------------------------------------------------------------+ # Persistence+ # ------------------------------------------------------------------++ def load( self ) -> None:+ """Load session from disk.++ If the file does not exist or is malformed, resets to empty state.+ """+ try:+ with open( self._session_path, "r", encoding="utf-8" ) as f:+ raw = json.load( f )+ if isinstance( raw, dict ):+ merged = _empty_session_data()+ merged.update( raw )+ self._data = merged+ else:+ self._data = _empty_session_data()+ except (OSError, json.JSONDecodeError, ValueError):+ self._data = _empty_session_data()++ def save( self ) -> None:+ """Save session to disk.++ Creates parent directories if needed. Writes atomically by+ writing to a temporary file first, then renaming.+ """+ self._data["updated_at"] = time.time()++ session_dir = os.path.dirname( self._session_path )+ os.makedirs( session_dir, exist_ok=True )++ tmp_path = self._session_path + ".tmp"+ try:+ with open( tmp_path, "w", encoding="utf-8" ) as f:+ json.dump( self._data, f, indent=2, ensure_ascii=False )+ f.write( "\n" )+ f.flush()+ os.fsync( f.fileno() )++ # Atomic rename (on Windows, need to remove target first)+ if os.path.exists( self._session_path ):+ os.replace( tmp_path, self._session_path )+ else:+ os.rename( tmp_path, self._session_path )+ except OSError:+ # Clean up temp file on failure+ if os.path.exists( tmp_path ):+ try:+ os.remove( tmp_path )+ except OSError:+ pass+ raise++ # ------------------------------------------------------------------+ # Project and scene+ # ------------------------------------------------------------------++ def set_project( self, sbproj_path: str ) -> None:+ """Set the active project.++ Args:+ sbproj_path: Path to the .sbproj file.+ """+ self._data["project_path"] = os.path.abspath( sbproj_path )+ self._data["modified"] = True+ self.save()++ def set_scene( self, scene_path: str ) -> None:+ """Set the active scene.++ Args:+ scene_path: Path to the .scene file.+ """+ self._data["scene_path"] = os.path.abspath( scene_path )+ self._data["modified"] = True+ self.save()++ # ------------------------------------------------------------------+ # Undo / Redo+ # ------------------------------------------------------------------++ def snapshot(+ self,+ op_type: str,+ description: str,+ before_state: Optional[Any] = None,+ after_state: Optional[Any] = None,+ file_path: Optional[str] = None,+ ) -> None:+ """Alias for ``record_operation`` matching HARNESS naming convention.++ Records a snapshot of an operation onto the undo stack. See+ :meth:`record_operation` for full documentation.+ """+ self.record_operation(+ op_type=op_type,+ description=description,+ before_state=before_state,+ after_state=after_state,+ file_path=file_path,+ )++ def record_operation(+ self,+ op_type: str,+ description: str,+ before_state: Optional[Any] = None,+ after_state: Optional[Any] = None,+ file_path: Optional[str] = None,+ ) -> None:+ """Record an operation for undo/redo.++ Args:+ op_type: One of 'scene_modify', 'project_modify', 'input_modify',+ 'collision_modify', 'file_create', 'codegen'.+ description: Human-readable description of what was done.+ before_state: Serializable state before the operation (for undo).+ after_state: Serializable state after the operation (for redo).+ file_path: The file that was modified.++ Raises:+ ValueError: If op_type is not a recognised operation type.+ """+ if op_type not in VALID_OP_TYPES:+ raise ValueError(+ f"Invalid op_type '{op_type}'. "+ f"Must be one of: {', '.join( sorted( VALID_OP_TYPES ) )}"+ )++ entry: Dict[str, Any] = {+ "op_type": op_type,+ "description": description,+ "timestamp": time.time(),+ "file_path": os.path.abspath( file_path ) if file_path else None,+ "before_state": copy.deepcopy( before_state ),+ "after_state": copy.deepcopy( after_state ),+ }++ self._data["undo_stack"].append( entry )+ # Recording a new operation clears the redo stack+ self._data["redo_stack"].clear()+ self._data["modified"] = True+ self.save()++ def undo( self ) -> Optional[Dict[str, Any]]:+ """Undo the last operation.++ If the operation has a before_state and file_path, the caller is+ responsible for actually restoring the file contents. This method+ manages the stack bookkeeping.++ Returns:+ Dict describing what was undone (the operation entry), or None+ if the undo stack is empty.+ """+ undo_stack: List[Dict[str, Any]] = self._data["undo_stack"]+ if not undo_stack:+ return None++ entry = undo_stack.pop()+ self._data["redo_stack"].append( copy.deepcopy( entry ) )+ self._data["modified"] = True+ self.save()++ return {+ "undone": True,+ "op_type": entry["op_type"],+ "description": entry["description"],+ "file_path": entry.get( "file_path" ),+ "before_state": entry.get( "before_state" ),+ "after_state": entry.get( "after_state" ),+ }++ def redo( self ) -> Optional[Dict[str, Any]]:+ """Redo the last undone operation.++ Returns:+ Dict describing what was redone (the operation entry), or None+ if the redo stack is empty.+ """+ redo_stack: List[Dict[str, Any]] = self._data["redo_stack"]+ if not redo_stack:+ return None++ entry = redo_stack.pop()+ self._data["undo_stack"].append( copy.deepcopy( entry ) )+ self._data["modified"] = True+ self.save()++ return {+ "redone": True,+ "op_type": entry["op_type"],+ "description": entry["description"],+ "file_path": entry.get( "file_path" ),+ "before_state": entry.get( "before_state" ),+ "after_state": entry.get( "after_state" ),+ }++ # ------------------------------------------------------------------+ # Status and reset+ # ------------------------------------------------------------------++ def get_status( self ) -> Dict[str, Any]:+ """Return a dict with current session status.++ Returns:+ Dict with keys: project_path, scene_path, modified,+ undo_count, redo_count, created_at, updated_at.+ """+ return {+ "project_path": self._data.get( "project_path" ),+ "scene_path": self._data.get( "scene_path" ),+ "modified": self._data.get( "modified", False ),+ "undo_count": len( self._data.get( "undo_stack", [] ) ),+ "redo_count": len( self._data.get( "redo_stack", [] ) ),+ "created_at": self._data.get( "created_at" ),+ "updated_at": self._data.get( "updated_at" ),+ "session_file": self._session_path,+ }++ def clear( self ) -> None:+ """Clear session state and save to disk."""+ self._data = _empty_session_data()+ self.save()++ # ------------------------------------------------------------------+ # Properties+ # ------------------------------------------------------------------++ @property+ def project_path( self ) -> Optional[str]:+ """Current project .sbproj path."""+ return self._data.get( "project_path" )++ @property+ def scene_path( self ) -> Optional[str]:+ """Current scene path."""+ return self._data.get( "scene_path" )++ @property+ def is_modified( self ) -> bool:+ """Whether there are unsaved changes."""+ return bool( self._data.get( "modified", False ) )diff --git a/sbox/agent-harness/cli_anything/sbox/core/sound.py b/sbox/agent-harness/cli_anything/sbox/core/sound.pynew file mode 100644index 000000000..9c9383ad5--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/sound.py@@ -0,0 +1,130 @@+"""Manages s&box .sound event files - creation and parsing."""++import json+import os+from typing import Any, Dict, List, Optional+++def create_sound_event(+ name: str,+ sounds: Optional[List[str]] = None,+ volume: str = "1",+ pitch: str = "1",+ decibels: int = 70,+ selection_mode: str = "Random",+ is_ui: bool = False,+ occlusion: bool = True,+ distance_attenuation: bool = True,+ output_path: Optional[str] = None,+) -> Dict[str, Any]:+ """Create a .sound event file.++ Args:+ name: Sound event name.+ sounds: List of .vsnd file paths.+ volume: Volume as string float (0-1).+ pitch: Pitch as string float.+ decibels: Loudness in dB.+ selection_mode: How to pick from multiple sounds - "Random", "Sequential".+ is_ui: Whether this is a UI sound (no spatialization).+ occlusion: Enable sound occlusion.+ distance_attenuation: Enable distance-based volume falloff.+ output_path: Output file path. If None, returns data only.++ Returns:+ Dict with name, path, data.+ """+ if sounds is None:+ sounds = []++ data = {+ "UI": is_ui,+ "Volume": volume,+ "Pitch": pitch,+ "Decibels": decibels,+ "SelectionMode": selection_mode,+ "Sounds": sounds,+ "Occlusion": occlusion,+ "AirAbsorption": occlusion,+ "Transmission": occlusion,+ "OcclusionRadius": 64,+ "DistanceAttenuation": distance_attenuation,+ "__references": [],+ "__version": 1,+ }++ result = {+ "name": name,+ "data": data,+ }++ if output_path:+ if not output_path.endswith(".sound"):+ output_path += ".sound"+ os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)+ with open(output_path, "w", encoding="utf-8") as f:+ json.dump(data, f, indent=2)+ result["path"] = os.path.abspath(output_path)++ return result+++def parse_sound_event(sound_path: str) -> Dict[str, Any]:+ """Parse a .sound event file.++ Returns dict with name, path, sounds list, volume, pitch, decibels.+ """+ with open(sound_path, "r", encoding="utf-8") as f:+ data = json.load(f)++ name = os.path.splitext(os.path.basename(sound_path))[0]++ return {+ "name": name,+ "path": os.path.abspath(sound_path),+ "sounds": data.get("Sounds", []),+ "volume": data.get("Volume", "1"),+ "pitch": data.get("Pitch", "1"),+ "decibels": data.get("Decibels", 70),+ "is_ui": data.get("UI", False),+ "selection_mode": data.get("SelectionMode", "Random"),+ "occlusion": data.get("Occlusion", True),+ }+++def update_sound_event(+ sound_path: str,+ sounds: Optional[List[str]] = None,+ volume: Optional[str] = None,+ pitch: Optional[str] = None,+ decibels: Optional[int] = None,+ is_ui: Optional[bool] = None,+ occlusion: Optional[bool] = None,+) -> Dict[str, Any]:+ """Update properties of an existing .sound event file.++ Only modifies properties that are explicitly provided (non-None).+ Returns the updated sound info dict.+ """+ with open( sound_path, "r", encoding="utf-8" ) as f:+ data = json.load( f )++ if sounds is not None:+ data["Sounds"] = sounds+ if volume is not None:+ data["Volume"] = volume+ if pitch is not None:+ data["Pitch"] = pitch+ if decibels is not None:+ data["Decibels"] = decibels+ if is_ui is not None:+ data["UI"] = is_ui+ if occlusion is not None:+ data["Occlusion"] = occlusion+ data["AirAbsorption"] = occlusion+ data["Transmission"] = occlusion++ with open( sound_path, "w", encoding="utf-8" ) as f:+ json.dump( data, f, indent=2 )++ return parse_sound_event( sound_path )diff --git a/sbox/agent-harness/cli_anything/sbox/core/test_orchestrator.py b/sbox/agent-harness/cli_anything/sbox/core/test_orchestrator.pynew file mode 100644index 000000000..e3837e9b6--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/test_orchestrator.py@@ -0,0 +1,254 @@+"""Map test pipeline orchestrator.++Manages the full lifecycle of automated map generation testing:+path resolution, combo matrix building, config I/O, s&box launch,+sentinel polling, and RGBA-to-PNG conversion.+"""++import json+import os+import random+import shutil+import subprocess+import time+from typing import Any, Dict, List, Optional+++ALL_STRATEGIES = ["Serpentine", "Gilbert", "SpanningTree", "Backbite"]+ALL_SIZES = ["Small", "Medium", "Large"]+DATA_FILES = [+ "test_config.json", "screenshot.rgba", "screenshot.rgba.b64",+ "metadata.json", "test_complete.json",+]+++def resolve_data_path(sbox_install: str, project_ident: str) -> str:+ """Compute the FileSystem.Data physical path for a project."""+ data_path = os.path.join(sbox_install, "data", "local", f"{project_ident}#local")+ if not os.path.isdir(data_path):+ raise FileNotFoundError(+ f"FileSystem.Data directory not found at {data_path}. "+ f"Run s&box once to create it."+ )+ return data_path+++def build_combo_matrix(+ strategies: Optional[List[str]] = None,+ sizes: Optional[List[str]] = None,+ seeds: Optional[List[int]] = None,+ seed_count: int = 1,+) -> List[Dict[str, Any]]:+ """Build the full test combo matrix."""+ use_strategies = strategies or ALL_STRATEGIES+ use_sizes = sizes or ALL_SIZES+ if seeds is None:+ seeds = [random.randint(1, 999999) for _ in range(seed_count)]++ combos = []+ for strategy in use_strategies:+ for size in use_sizes:+ for seed in seeds:+ combos.append({"strategy": strategy, "size": size, "seed": seed})+ return combos+++def write_test_config(data_path: str, strategy: str, size: str, seed: int) -> str:+ """Write test_config.json to the FileSystem.Data directory.++ Note: Keys are PascalCase to match s&box Json.Deserialize<TestConfig>().+ """+ config = {"Strategy": strategy, "Size": size, "Seed": seed}+ config_path = os.path.join(data_path, "test_config.json")+ with open(config_path, "w", encoding="utf-8") as f:+ json.dump(config, f)+ return config_path+++def cleanup_data_files(data_path: str) -> None:+ """Remove test pipeline files from FileSystem.Data."""+ for name in DATA_FILES:+ path = os.path.join(data_path, name)+ if os.path.exists(path):+ os.remove(path)+++def check_sentinel(data_path: str) -> Optional[Dict[str, Any]]:+ """Check for test_complete.json sentinel file."""+ sentinel_path = os.path.join(data_path, "test_complete.json")+ if not os.path.exists(sentinel_path):+ return None+ with open(sentinel_path, encoding="utf-8") as f:+ return json.load(f)+++def poll_for_sentinel(data_path: str, timeout: float = 60.0) -> Optional[Dict[str, Any]]:+ """Poll for sentinel file with timeout."""+ deadline = time.time() + timeout+ while time.time() < deadline:+ result = check_sentinel(data_path)+ if result is not None:+ return result+ time.sleep(0.5)+ return None+++def rgba_to_png(rgba_path: str, png_path: str, width: int, height: int) -> None:+ """Convert raw RGBA bytes to a PNG file using Pillow."""+ if not os.path.exists(rgba_path):+ raise FileNotFoundError(f"RGBA file not found: {rgba_path}")++ from PIL import Image++ with open(rgba_path, "rb") as f:+ raw_bytes = f.read()++ img = Image.frombytes("RGBA", (width, height), raw_bytes)+ os.makedirs(os.path.dirname(png_path), exist_ok=True)+ img.save(png_path, "PNG")+++def collect_screenshot(+ data_path: str, output_dir: str, strategy: str, size: str, seed: int+) -> Optional[str]:+ """Copy screenshot from FileSystem.Data to test-results, convert to PNG.++ Handles both WriteAllBytes (raw) and Base64 fallback outputs.+ """+ metadata_path = os.path.join(data_path, "metadata.json")+ rgba_path = os.path.join(data_path, "screenshot.rgba")+ b64_path = os.path.join(data_path, "screenshot.rgba.b64")++ if not os.path.exists(metadata_path):+ return None++ with open(metadata_path, encoding="utf-8") as f:+ metadata = json.load(f)++ width = metadata.get("renderWidth", 2048)+ height = metadata.get("renderHeight", 2048)++ filename = f"{strategy.lower()}-{size.lower()}-seed{seed}.png"+ png_path = os.path.join(output_dir, "screenshots", filename)++ if os.path.exists(rgba_path):+ rgba_to_png(rgba_path, png_path, width, height)+ elif os.path.exists(b64_path):+ import base64+ from PIL import Image++ with open(b64_path, "r", encoding="utf-8") as f:+ raw_bytes = base64.b64decode(f.read())+ img = Image.frombytes("RGBA", (width, height), raw_bytes)+ os.makedirs(os.path.dirname(png_path), exist_ok=True)+ img.save(png_path, "PNG")+ else:+ return None++ meta_dest = os.path.join(+ output_dir, "screenshots",+ f"{strategy.lower()}-{size.lower()}-seed{seed}.metadata.json"+ )+ shutil.copy2(metadata_path, meta_dest)++ return png_path+++def kill_sbox_process(proc: subprocess.Popen) -> None:+ """Kill an s&box process and its children."""+ if proc.poll() is not None:+ return++ proc.kill()+ try:+ proc.wait(timeout=3)+ except subprocess.TimeoutExpired:+ subprocess.run(+ ["taskkill", "/F", "/T", "/PID", str(proc.pid)],+ capture_output=True,+ )+++def swap_startup_scene(sbproj_path: str, scene: str) -> str:+ """Swap the StartupScene in a .sbproj file. Returns the previous value."""+ from cli_anything.sbox.core import project as project_mod++ info = project_mod.get_project_info(sbproj_path)+ previous = info.get("startup_scene", "scenes/minimal.scene")+ project_mod.configure_project(sbproj_path, startup_scene=scene)+ return previous+++def run_single_combo(+ combo: Dict[str, Any],+ data_path: str,+ output_dir: str,+ sbproj_path: str,+ timeout: float = 60.0,+) -> Dict[str, Any]:+ """Run a single strategy/size/seed combo through s&box."""+ from cli_anything.sbox.utils import sbox_backend++ strategy = combo["strategy"]+ size = combo["size"]+ seed = combo["seed"]++ cleanup_data_files(data_path)+ write_test_config(data_path, strategy, size, seed)++ project_dir = os.path.dirname(sbproj_path)+ proc = sbox_backend.launch_editor(project_dir)++ try:+ sentinel = poll_for_sentinel(data_path, timeout)++ if sentinel is None:+ return {"success": False, "error": "timeout", "combo": combo}++ if not sentinel.get("success"):+ return {+ "success": False,+ "error": sentinel.get("error", "unknown error"),+ "combo": combo,+ }++ png_path = collect_screenshot(data_path, output_dir, strategy, size, seed)+ return {"success": True, "png_path": png_path, "combo": combo}++ finally:+ kill_sbox_process(proc)+ cleanup_data_files(data_path)+++def run_test_pipeline(+ sbproj_path: str,+ data_path: str,+ output_dir: str,+ strategies: Optional[List[str]] = None,+ sizes: Optional[List[str]] = None,+ seeds: Optional[List[int]] = None,+ seed_count: int = 1,+ timeout: float = 60.0,+) -> List[Dict[str, Any]]:+ """Run the full test pipeline across all combos."""+ combos = build_combo_matrix(strategies, sizes, seeds, seed_count)++ previous_scene = swap_startup_scene(sbproj_path, "scenes/test_map.scene")++ results = []+ try:+ for i, combo in enumerate(combos):+ label = f"{combo['strategy']}/{combo['size']}/seed{combo['seed']}"+ print(f"[{i + 1}/{len(combos)}] Running {label}...")++ result = run_single_combo(combo, data_path, output_dir, sbproj_path, timeout)+ results.append(result)++ if result["success"]:+ print(f" -> captured: {result['png_path']}")+ else:+ print(f" -> FAILED: {result['error']}")+ finally:+ swap_startup_scene(sbproj_path, previous_scene)++ return resultsdiff --git a/sbox/agent-harness/cli_anything/sbox/core/validate.py b/sbox/agent-harness/cli_anything/sbox/core/validate.pynew file mode 100644index 000000000..9c74e1132--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/core/validate.py@@ -0,0 +1,226 @@+"""Project-level validation: broken asset refs, GUID collisions, missing inputs."""++import json+import os+from typing import Any, Dict, List, Set, Tuple++from cli_anything.sbox.core import scene as scene_mod+from cli_anything.sbox.core import prefab as prefab_mod+from cli_anything.sbox.core import export as export_mod+from cli_anything.sbox.core import input_config as input_mod+++# Asset categories to refs and the file extensions that satisfy them.+# References without extensions (e.g. "models/dev/box") fall back to the .stem+# match against assets of the corresponding type.+_CATEGORY_TO_TYPE: Dict[str, str] = {+ "models": "model",+ "materials": "material",+ "sounds": "sound",+ "textures": "texture",+ "prefabs": "prefab",+ "scenes": "scene",+}+++def _build_asset_index( project_dir: str ) -> Tuple[Set[str], Set[str]]:+ """Index project assets by normalized path and by extension-less stem.++ Returns (full_paths, stems) - both sets of normalized strings.+ """+ full_paths: Set[str] = set()+ stems: Set[str] = set()+ for asset in export_mod.list_assets( project_dir, asset_type="all" ):+ rel = asset["path"].replace( "\\", "/" ).lower()+ full_paths.add( rel )+ stem, _ = os.path.splitext( rel )+ if stem:+ stems.add( stem )+ return full_paths, stems+++def _is_engine_builtin( ref: str ) -> bool:+ """Whether a ref points to an engine-shipped asset (not in the project's Assets/).++ Heuristic: refs starting with these prefixes ship with s&box itself.+ """+ lower = ref.lower().lstrip( "/" )+ builtins = (+ "models/dev/",+ "materials/dev/",+ "materials/default",+ "materials/skybox/",+ "textures/dev/",+ "textures/cubemaps/",+ "fonts/",+ "particles/dev/",+ "sounds/ui/",+ )+ return any( lower.startswith( prefix ) for prefix in builtins )+++def _check_refs_against_index(+ refs_by_category: Dict[str, List[str]],+ full_paths: Set[str],+ stems: Set[str],+) -> List[str]:+ """Return broken refs (those missing from the project asset index)."""+ broken: List[str] = []+ for category, paths in refs_by_category.items():+ for ref in paths:+ norm = ref.replace( "\\", "/" ).lower()+ if norm.startswith( "assets/" ):+ norm = norm[len( "assets/" ):]+ if norm in full_paths or norm in stems:+ continue+ if _is_engine_builtin( ref ):+ continue+ broken.append( ref )+ return broken+++def _collect_guids( objects: List[Dict[str, Any]], collected: Dict[str, List[str]], context: str ) -> None:+ """Walk objects collecting all __guid values mapped to source contexts."""+ for obj in objects:+ guid = obj.get( "__guid" )+ if guid:+ collected.setdefault( guid, [] ).append( f"{context}:GameObject:{obj.get( 'Name', '?' )}" )+ for comp in obj.get( "Components", [] ):+ cguid = comp.get( "__guid" )+ if cguid:+ collected.setdefault( cguid, [] ).append( f"{context}:Component:{comp.get( '__type', '?' )}" )+ children = obj.get( "Children", [] )+ if children:+ _collect_guids( children, collected, context )+++def validate_project(+ project_dir: str,+ check_refs: bool = True,+ check_guids: bool = True,+ check_inputs: bool = True,+) -> Dict[str, Any]:+ """Validate a project's scenes and prefabs.++ Checks performed (each can be disabled):+ * **broken_refs** - asset references in scenes/prefabs that don't resolve+ to a project file or known engine built-in.+ * **duplicate_guids** - the same __guid appearing more than once within a+ single scene or prefab (cross-file collisions are expected and not flagged).+ * **invalid_inputs** - issues in Input.config: empty action names or+ unknown groups.++ Args:+ project_dir: Root directory of the s&box project.+ check_refs: Run the broken-reference check.+ check_guids: Run the duplicate-GUID check.+ check_inputs: Run the Input.config sanity check.++ Returns:+ Dict with 'ok' (bool), 'issue_count' (int), and per-check result lists.+ """+ issues: Dict[str, Any] = {+ "broken_refs": [],+ "duplicate_guids": [],+ "invalid_inputs": [],+ }++ assets_dir = os.path.join( project_dir, "Assets" )+ if not os.path.isdir( assets_dir ):+ return {+ "ok": False,+ "issue_count": 1,+ "broken_refs": [],+ "duplicate_guids": [],+ "invalid_inputs": [],+ "error": f"No Assets/ directory found in {project_dir}",+ }++ full_paths, stems = _build_asset_index( project_dir ) if check_refs else (set(), set())++ for dirpath, _dirs, files in os.walk( assets_dir ):+ for fname in files:+ full = os.path.join( dirpath, fname )+ rel = os.path.relpath( full, project_dir ).replace( "\\", "/" )+ ext = os.path.splitext( fname )[1].lower()++ if ext not in (".scene", ".prefab"):+ continue++ try:+ if ext == ".scene":+ refs = scene_mod.extract_asset_refs( full ) if check_refs else {}+ if check_guids:+ data = scene_mod.load_scene( full )+ roots = data.get( "GameObjects", [] )+ else:+ refs = prefab_mod.extract_asset_refs( full ) if check_refs else {}+ if check_guids:+ data = prefab_mod.load_prefab( full )+ root = data.get( "RootObject" )+ roots = [root] if root else []+ except (OSError, json.JSONDecodeError, ValueError) as exc:+ issues["broken_refs"].append( {+ "file": rel,+ "ref": "<parse error>",+ "category": "parse",+ "detail": str( exc ),+ } )+ continue++ if check_refs:+ broken = _check_refs_against_index( refs, full_paths, stems )+ for ref in broken:+ category = scene_mod._category_for_ref( ref )+ issues["broken_refs"].append( {+ "file": rel,+ "ref": ref,+ "category": category,+ } )++ if check_guids and roots:+ guid_map: Dict[str, List[str]] = {}+ _collect_guids( roots, guid_map, rel )+ for guid, sources in guid_map.items():+ if len( sources ) > 1:+ issues["duplicate_guids"].append( {+ "file": rel,+ "guid": guid,+ "occurrences": sources,+ } )++ if check_inputs:+ input_path = os.path.join( project_dir, "ProjectSettings", "Input.config" )+ if os.path.isfile( input_path ):+ try:+ actions = input_mod.list_actions( input_path )+ seen_names: Set[str] = set()+ for action in actions:+ name = action.get( "Name", "" ).strip()+ if not name:+ issues["invalid_inputs"].append( {+ "file": "ProjectSettings/Input.config",+ "issue": "empty_name",+ "action": action,+ } )+ continue+ if name in seen_names:+ issues["invalid_inputs"].append( {+ "file": "ProjectSettings/Input.config",+ "issue": "duplicate_name",+ "action": name,+ } )+ seen_names.add( name )+ except (OSError, json.JSONDecodeError, ValueError) as exc:+ issues["invalid_inputs"].append( {+ "file": "ProjectSettings/Input.config",+ "issue": "parse_error",+ "detail": str( exc ),+ } )++ issue_count = sum( len( v ) for v in issues.values() if isinstance( v, list ) )+ return {+ "ok": issue_count == 0,+ "issue_count": issue_count,+ **issues,+ }diff --git a/sbox/agent-harness/cli_anything/sbox/sbox_cli.py b/sbox/agent-harness/cli_anything/sbox/sbox_cli.pynew file mode 100644index 000000000..b58e0226d--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/sbox_cli.py@@ -0,0 +1,2381 @@+"""cli-anything-sbox - Click-based CLI harness for the s&box game engine.++Provides commands for managing s&box projects, scenes, prefabs, code generation,+input/collision configuration, and more. Supports both single-command invocation+and an interactive REPL mode.+"""++import click+import json+import os+import shlex+from typing import Any, Optional++from cli_anything.sbox.core import (+ project as project_mod,+ scene as scene_mod,+ prefab as prefab_mod,+ codegen as codegen_mod,+ input_config as input_config_mod,+ collision_config as collision_config_mod,+ session as session_mod,+ export as export_mod,+)+from cli_anything.sbox.core import material as material_mod+from cli_anything.sbox.core import sound as sound_mod+from cli_anything.sbox.core import localization as localization_mod+from cli_anything.sbox.core import validate as validate_mod+from cli_anything.sbox.utils import sbox_backend+from cli_anything.sbox.core import test_orchestrator as test_mod+++# ---------------------------------------------------------------------------+# Output helpers+# ---------------------------------------------------------------------------+++def _output(ctx: click.Context, data: Any, human_fn=None) -> None:+ """Output data as JSON or human-readable text.++ Args:+ ctx: Click context with obj["json"] flag.+ data: Data to output (must be JSON-serializable for --json mode).+ human_fn: Optional callable that returns a human-readable string.+ If None, falls back to a pretty-printed representation.+ """+ if ctx.obj.get( "json" ):+ click.echo( json.dumps( data, indent=2, default=str ) )+ elif human_fn:+ click.echo( human_fn( data ) )+ else:+ click.echo( json.dumps( data, indent=2, default=str ) )+++def _output_error(ctx: click.Context, message: str) -> None:+ """Output an error message in the appropriate format."""+ if ctx.obj.get( "json" ):+ click.echo( json.dumps( {"error": message} ) )+ else:+ click.echo( f"Error: {message}", err=True )+++def _format_table(rows: list, headers: list) -> str:+ """Format a list of dicts/tuples as a simple aligned table."""+ if not rows:+ return "(empty)"++ # Calculate column widths+ col_widths = [len( h ) for h in headers]+ str_rows = []+ for row in rows:+ if isinstance( row, dict ):+ cells = [str( row.get( h, "" ) ) for h in headers]+ else:+ cells = [str( c ) for c in row]+ str_rows.append( cells )+ for i, cell in enumerate( cells ):+ if i < len( col_widths ):+ col_widths[i] = max( col_widths[i], len( cell ) )++ lines = []+ # Header+ header_line = " ".join( h.ljust( col_widths[i] ) for i, h in enumerate( headers ) )+ lines.append( header_line )+ lines.append( " ".join( "-" * w for w in col_widths ) )+ # Rows+ for cells in str_rows:+ line = " ".join( cells[i].ljust( col_widths[i] ) if i < len( col_widths ) else cells[i] for i in range( len( cells ) ) )+ lines.append( line )++ return "\n".join( lines )+++def _format_status_block(data: dict, title: str = "") -> str:+ """Format a dict as a key-value status block."""+ lines = []+ if title:+ lines.append( title )+ lines.append( "=" * len( title ) )+ max_key = max( (len( str( k ) ) for k in data), default=0 )+ for key, value in data.items():+ lines.append( f" {str( key ).ljust( max_key )} {value}" )+ return "\n".join( lines )+++def _resolve_project_path(ctx: click.Context) -> Optional[str]:+ """Resolve the project directory from --project or cwd.++ Returns the .sbproj file path, or None if not found.+ """+ project_path = ctx.obj.get( "project_path" )+ if project_path:+ # If it is a directory, find the .sbproj inside+ if os.path.isdir( project_path ):+ return project_mod.find_sbproj( project_path )+ # If it is a file, assume it is the .sbproj+ if os.path.isfile( project_path ):+ return project_path+ return None+ # Auto-detect from cwd+ proj_dir = export_mod.find_project_dir( os.getcwd() )+ if proj_dir:+ return project_mod.find_sbproj( proj_dir )+ return None+++def _resolve_project_dir(ctx: click.Context) -> Optional[str]:+ """Resolve the project directory from --project or cwd."""+ project_path = ctx.obj.get( "project_path" )+ if project_path:+ if os.path.isdir( project_path ):+ return project_path+ if os.path.isfile( project_path ):+ return os.path.dirname( project_path )+ return None+ return export_mod.find_project_dir( os.getcwd() )+++def _resolve_input_config(ctx: click.Context, config_path: Optional[str] = None) -> str:+ """Resolve the Input.config path from explicit arg, --project, or cwd."""+ if config_path:+ return config_path+ proj_dir = _resolve_project_dir( ctx )+ if proj_dir:+ return os.path.join( proj_dir, "ProjectSettings", "Input.config" )+ raise click.ClickException( "No project found. Use --project or run from a project directory." )+++def _resolve_collision_config(ctx: click.Context, config_path: Optional[str] = None) -> str:+ """Resolve the Collision.config path from explicit arg, --project, or cwd."""+ if config_path:+ return config_path+ proj_dir = _resolve_project_dir( ctx )+ if proj_dir:+ return os.path.join( proj_dir, "ProjectSettings", "Collision.config" )+ raise click.ClickException( "No project found. Use --project or run from a project directory." )+++# ---------------------------------------------------------------------------+# Root CLI group+# ---------------------------------------------------------------------------++[email protected]( invoke_without_command=True )[email protected]( "--json", "json_output", is_flag=True, help="Output in JSON format" )[email protected]( "--project", "project_path", default=None, help="Project directory path" )[email protected]_context+def cli( ctx, json_output, project_path ):+ """cli-anything-sbox - CLI harness for the s&box game engine."""+ ctx.ensure_object( dict )+ ctx.obj["json"] = json_output+ ctx.obj["project_path"] = project_path+ if ctx.invoked_subcommand is None:+ ctx.invoke( repl )+++# ---------------------------------------------------------------------------+# project group+# ---------------------------------------------------------------------------++[email protected]_context+def project( ctx ):+ """Manage s&box projects."""+ pass++[email protected]( "new" )[email protected]( "--name", required=True, help="Project name" )[email protected]( "--type", "project_type", type=click.Choice( ["game", "addon", "library"] ), default="game", help="Project type" )[email protected]( "-o", "--output-dir", default=None, help="Output directory" )[email protected]( "--max-players", type=int, default=64, help="Maximum player count" )[email protected]( "--tick-rate", type=int, default=50, help="Server tick rate" )[email protected]_context+def project_new( ctx, name, project_type, output_dir, max_players, tick_rate ):+ """Create a new s&box project."""+ try:+ result = project_mod.create_project(+ name=name,+ project_type=project_type,+ output_dir=output_dir,+ max_players=max_players,+ tick_rate=tick_rate,+ )+ _output( ctx, result, lambda d: _format_status_block( d, f"Project '{d['name']}' created" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "info" )[email protected]_context+def project_info( ctx ):+ """Show project info."""+ try:+ sbproj = _resolve_project_path( ctx )+ if not sbproj:+ raise click.ClickException( "No .sbproj found. Use --project or run from a project directory." )+ result = project_mod.get_project_info( sbproj )+ _output( ctx, result, lambda d: _format_status_block( d, f"Project: {d.get( 'title', '' )}" ) )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "config" )[email protected]( "--title", default=None, help="Project title" )[email protected]( "--max-players", type=int, default=None, help="Maximum player count" )[email protected]( "--tick-rate", type=int, default=None, help="Server tick rate" )[email protected]( "--network-type", default=None, help="Network type (e.g. Multiplayer)" )[email protected]( "--startup-scene", default=None, help="Startup scene path" )[email protected]_context+def project_config( ctx, title, max_players, tick_rate, network_type, startup_scene ):+ """Update project settings."""+ try:+ sbproj = _resolve_project_path( ctx )+ if not sbproj:+ raise click.ClickException( "No .sbproj found. Use --project or run from a project directory." )++ kwargs = {}+ if title is not None:+ kwargs["title"] = title+ if max_players is not None:+ kwargs["max_players"] = max_players+ if tick_rate is not None:+ kwargs["tick_rate"] = tick_rate+ if network_type is not None:+ kwargs["network_type"] = network_type+ if startup_scene is not None:+ kwargs["startup_scene"] = startup_scene++ if not kwargs:+ _output_error( ctx, "No settings specified. Use --title, --max-players, etc." )+ return++ result = project_mod.configure_project( sbproj, **kwargs )+ _output( ctx, result, lambda d: _format_status_block( d, "Project updated" ) )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "add-package" )[email protected]( "package_ref" )[email protected]_context+def project_add_package( ctx, package_ref ):+ """Add a package reference to the project."""+ try:+ sbproj = _resolve_project_path( ctx )+ if not sbproj:+ _output_error( ctx, "No project found" )+ return+ result = project_mod.add_package( sbproj, package_ref )+ _output( ctx, result, lambda d: f"Added package '{package_ref}'" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "remove-package" )[email protected]( "package_ref" )[email protected]_context+def project_remove_package( ctx, package_ref ):+ """Remove a package reference from the project."""+ try:+ sbproj = _resolve_project_path( ctx )+ if not sbproj:+ _output_error( ctx, "No project found" )+ return+ result = project_mod.remove_package( sbproj, package_ref )+ _output( ctx, result, lambda d: f"Removed package '{package_ref}'" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "validate" )[email protected]( "--no-refs", is_flag=True, help="Skip broken-reference detection" )[email protected]( "--no-guids", is_flag=True, help="Skip duplicate-GUID detection" )[email protected]( "--no-inputs", is_flag=True, help="Skip Input.config sanity checks" )[email protected]_context+def project_validate( ctx, no_refs, no_guids, no_inputs ):+ """Validate project: broken asset refs, duplicate GUIDs, malformed inputs."""+ try:+ proj_dir = _resolve_project_dir( ctx )+ if not proj_dir:+ _output_error( ctx, "No project found" )+ return+ result = validate_mod.validate_project(+ proj_dir,+ check_refs=not no_refs,+ check_guids=not no_guids,+ check_inputs=not no_inputs,+ )++ def human( d ):+ lines = [f"Project validation: {'OK' if d['ok'] else 'FAIL'} ({d['issue_count']} issue(s))"]+ for ref in d.get( "broken_refs", [] ):+ lines.append( f" [broken-ref] {ref['file']} -> {ref['ref']} ({ref['category']})" )+ for guid in d.get( "duplicate_guids", [] ):+ lines.append( f" [duplicate-guid] {guid['file']} -> {guid['guid']}" )+ for occ in guid.get( "occurrences", [] ):+ lines.append( f" {occ}" )+ for inp in d.get( "invalid_inputs", [] ):+ lines.append( f" [input] {inp.get( 'file', '?' )}: {inp.get( 'issue', '?' )}" )+ return "\n".join( lines )++ _output( ctx, result, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# scene group+# ---------------------------------------------------------------------------++[email protected]_context+def scene( ctx ):+ """Manage s&box scenes."""+ pass++[email protected]( "new" )[email protected]( "--name", default="minimal", help="Scene name" )[email protected]( "-o", "--output", "output_path", default=None, help="Output file path" )[email protected]( "--no-defaults", is_flag=True, help="Skip default objects (Sun, Skybox, Plane, Camera)" )[email protected]_context+def scene_new( ctx, name, output_path, no_defaults ):+ """Create a new scene."""+ try:+ if not output_path:+ output_path = f"{name}.scene"+ result = scene_mod.create_scene(+ name=name,+ output_path=output_path,+ include_defaults=not no_defaults,+ )+ info = {+ "name": name,+ "path": os.path.abspath( output_path ),+ "objects": len( result.get( "GameObjects", [] ) ),+ "defaults_included": not no_defaults,+ }+ _output( ctx, info, lambda d: _format_status_block( d, f"Scene '{d['name']}' created" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "info" )[email protected]( "scene_path" )[email protected]_context+def scene_info( ctx, scene_path ):+ """Show scene info."""+ try:+ result = scene_mod.get_scene_info( scene_path )+ _output( ctx, result, lambda d: _format_status_block( d, f"Scene: {d.get( 'title', '' )}" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "list" )[email protected]( "scene_path" )[email protected]_context+def scene_list( ctx, scene_path ):+ """List GameObjects in a scene."""+ try:+ objects = scene_mod.list_objects( scene_path )+ if ctx.obj.get( "json" ):+ _output( ctx, objects )+ else:+ rows = []+ for obj in objects:+ rows.append( {+ "guid": obj["guid"][:12] + "...",+ "name": obj["name"],+ "position": obj["position"],+ "components": ", ".join( t.split( "." )[-1] for t in obj["component_types"] ),+ } )+ click.echo( _format_table( rows, ["guid", "name", "position", "components"] ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "add-object" )[email protected]( "scene_path" )[email protected]( "name" )[email protected]( "--position", default="0,0,0", help="Position as x,y,z" )[email protected]( "--rotation", default="0,0,0,1", help="Rotation as x,y,z,w quaternion" )[email protected]( "--scale", default="1,1,1", help="Scale as x,y,z" )[email protected]( "--tags", default="", help="Space-separated tags" )[email protected]( "--components", default=None, help="Comma-separated preset names (e.g. model,box_collider,rigidbody)" )[email protected]( "--parent", default=None, help="Parent object GUID" )[email protected]_context+def scene_add_object( ctx, scene_path, name, position, rotation, scale, tags, components, parent ):+ """Add a GameObject to a scene."""+ try:+ comp_list = None+ if components:+ comp_list = [c.strip() for c in components.split( "," )]++ new_guid = scene_mod.add_object(+ scene_path=scene_path,+ name=name,+ position=position,+ rotation=rotation,+ scale=scale,+ tags=tags,+ components=comp_list,+ parent_guid=parent,+ )+ result = {"guid": new_guid, "name": name, "scene": scene_path}+ _output( ctx, result, lambda d: f"Added '{d['name']}' ({d['guid']}) to {d['scene']}" )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "remove-object" )[email protected]( "scene_path" )[email protected]( "--name", default=None, help="Object name to remove" )[email protected]( "--guid", default=None, help="Object GUID to remove" )[email protected]_context+def scene_remove_object( ctx, scene_path, name, guid ):+ """Remove a GameObject from a scene."""+ try:+ if not name and not guid:+ raise click.ClickException( "Must specify --name or --guid" )+ removed = scene_mod.remove_object( scene_path, name=name, guid=guid )+ result = {"removed": removed, "name": name, "guid": guid}+ if removed:+ _output( ctx, result, lambda d: f"Removed object from {scene_path}" )+ else:+ _output( ctx, result, lambda d: f"Object not found in {scene_path}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "add-component" )[email protected]( "scene_path" )[email protected]( "object_guid" )[email protected]( "component_type" )[email protected]( "--properties", default=None, help="Component properties as JSON string" )[email protected]_context+def scene_add_component( ctx, scene_path, object_guid, component_type, properties ):+ """Add a component to a GameObject."""+ try:+ props = None+ if properties:+ props = json.loads( properties )+ comp_guid = scene_mod.add_component(+ scene_path=scene_path,+ object_guid=object_guid,+ component_type=component_type,+ properties=props,+ )+ result = {"component_guid": comp_guid, "type": component_type, "object_guid": object_guid}+ _output( ctx, result, lambda d: f"Added {d['type']} ({d['component_guid']}) to object {d['object_guid']}" )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "remove-component" )[email protected]( "scene_path" )[email protected]( "object_guid" )[email protected]( "--component-guid", default=None, help="Component GUID to remove" )[email protected]( "--component-type", default=None, help="Component type to remove (e.g. Sandbox.Rigidbody)" )[email protected]_context+def scene_remove_component( ctx, scene_path, object_guid, component_guid, component_type ):+ """Remove a component from a GameObject."""+ try:+ if not component_guid and not component_type:+ _output_error( ctx, "Must provide --component-guid or --component-type" )+ return+ removed = scene_mod.remove_component( scene_path, object_guid, component_guid=component_guid, component_type=component_type )+ result = {"removed": removed, "object_guid": object_guid}+ _output( ctx, result, lambda d: f"Component {'removed' if d['removed'] else 'not found'}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "modify-object" )[email protected]( "scene_path" )[email protected]( "--guid", default=None, help="Object GUID to modify" )[email protected]( "--name-match", default=None, help="Object name to match" )[email protected]( "--name", "new_name", default=None, help="New name for the object" )[email protected]( "--position", default=None, help="New position (x,y,z)" )[email protected]( "--rotation", default=None, help="New rotation (x,y,z,w)" )[email protected]( "--scale", default=None, help="New scale (x,y,z)" )[email protected]( "--tags", default=None, help="New tags (comma-separated)" )[email protected]( "--enabled/--disabled", default=None, help="Enable or disable object" )[email protected]_context+def scene_modify_object( ctx, scene_path, guid, name_match, new_name, position, rotation, scale, tags, enabled ):+ """Modify an existing GameObject in a scene."""+ try:+ result = scene_mod.modify_object(+ scene_path,+ guid=guid,+ name_match=name_match,+ new_name=new_name,+ position=position,+ rotation=rotation,+ scale=scale,+ tags=tags,+ enabled=enabled,+ )+ _output( ctx, result, lambda d: f"Modified {d['name']} ({d['guid']}): {', '.join( d['modified_fields'] )}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "set-property" )[email protected]( "scene_path" )[email protected]( "--fixed-update-freq", type=int, default=None, help="Fixed update frequency (Hz)" )[email protected]( "--network-freq", type=int, default=None, help="Network update frequency (Hz)" )[email protected]( "--timescale", type=float, default=None, help="Time scale (1.0 = normal)" )[email protected]( "--network-interpolation/--no-network-interpolation", default=None )[email protected]( "--physics-sub-steps", type=int, default=None )[email protected]_context+def scene_set_property( ctx, scene_path, fixed_update_freq, network_freq, timescale, network_interpolation, physics_sub_steps ):+ """Modify SceneProperties of a scene."""+ try:+ kwargs = {}+ if fixed_update_freq is not None:+ kwargs["fixed_update_freq"] = fixed_update_freq+ if network_freq is not None:+ kwargs["network_freq"] = network_freq+ if timescale is not None:+ kwargs["timescale"] = timescale+ if network_interpolation is not None:+ kwargs["network_interpolation"] = network_interpolation+ if physics_sub_steps is not None:+ kwargs["physics_sub_steps"] = physics_sub_steps++ if not kwargs:+ _output_error( ctx, "No properties specified to change" )+ return++ result = scene_mod.set_scene_properties( scene_path, **kwargs )+ _output( ctx, result, lambda d: _format_status_block( d, "Scene Properties" ) )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "clone-object" )[email protected]( "scene_path" )[email protected]( "--guid", default=None, help="GUID of object to clone" )[email protected]( "--name-match", default=None, help="Name of object to clone" )[email protected]( "--new-name", default=None, help="Name for the clone" )[email protected]( "--position", default=None, help="Position for the clone (x,y,z)" )[email protected]_context+def scene_clone_object( ctx, scene_path, guid, name_match, new_name, position ):+ """Clone (duplicate) a GameObject with new GUIDs."""+ try:+ result = scene_mod.clone_object(+ scene_path, guid=guid, name=name_match,+ new_name=new_name, position=position,+ )+ _output( ctx, result, lambda d: f"Cloned '{d['original_name']}' -> '{d['name']}' ({d['guid']})" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "get-object" )[email protected]( "scene_path" )[email protected]( "--guid", default=None, help="Object GUID" )[email protected]( "--name", "name_match", default=None, help="Object name" )[email protected]_context+def scene_get_object( ctx, scene_path, guid, name_match ):+ """Get full details of a single GameObject."""+ try:+ result = scene_mod.get_object( scene_path, guid=guid, name=name_match )+ _output( ctx, result, lambda d: _format_status_block( d, f"Object: {d['name']}" ) )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "set-navmesh" )[email protected]( "scene_path" )[email protected]( "--enabled/--disabled", "navmesh_enabled", default=None, help="Enable/disable NavMesh" )[email protected]( "--agent-height", type=float, default=None, help="Agent height" )[email protected]( "--agent-radius", type=float, default=None, help="Agent radius" )[email protected]( "--agent-step-size", type=float, default=None, help="Agent step size" )[email protected]( "--agent-max-slope", type=float, default=None, help="Agent max slope (degrees)" )[email protected]_context+def scene_set_navmesh( ctx, scene_path, navmesh_enabled, agent_height, agent_radius, agent_step_size, agent_max_slope ):+ """Configure NavMesh properties for a scene."""+ try:+ kwargs = {}+ if navmesh_enabled is not None:+ kwargs["navmesh_enabled"] = navmesh_enabled+ if agent_height is not None:+ kwargs["navmesh_agent_height"] = agent_height+ if agent_radius is not None:+ kwargs["navmesh_agent_radius"] = agent_radius+ if agent_step_size is not None:+ kwargs["navmesh_agent_step_size"] = agent_step_size+ if agent_max_slope is not None:+ kwargs["navmesh_agent_max_slope"] = agent_max_slope++ if not kwargs:+ _output_error( ctx, "No NavMesh properties specified" )+ return++ result = scene_mod.set_navmesh_properties( scene_path, **kwargs )+ _output( ctx, result, lambda d: _format_status_block( d, "NavMesh Properties" ) )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "list-presets" )[email protected]_context+def scene_list_presets( ctx ):+ """List available component preset names."""+ try:+ from cli_anything.sbox.core.scene import COMPONENT_PRESETS+ presets = [{"name": k, "type": v["__type"]} for k, v in COMPONENT_PRESETS.items()]+ _output( ctx, presets )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "modify-component" )[email protected]( "scene_path" )[email protected]( "object_guid" )[email protected]( "--component-guid", default=None, help="Component GUID" )[email protected]( "--component-type", default=None, help="Component type (e.g. Sandbox.Rigidbody)" )[email protected]( "--properties", required=True, help="Properties to set as JSON" )[email protected]_context+def scene_modify_component( ctx, scene_path, object_guid, component_guid, component_type, properties ):+ """Modify properties of an existing component."""+ try:+ import json as json_mod+ props = json_mod.loads( properties )+ result = scene_mod.modify_component(+ scene_path, object_guid,+ component_guid=component_guid,+ component_type=component_type,+ properties=props,+ )+ _output( ctx, result, lambda d: f"Modified {d['component_type']} on {d['object_guid']}: {', '.join( d['updated_keys'] )}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "query" )[email protected]( "scene_path" )[email protected]( "--has-component", default=None, help="Filter by component (preset or full type)" )[email protected]( "--has-tag", default=None, help="Filter by tag (single token in Tags string)" )[email protected]( "--name-match", default=None, help="Filter by Name substring" )[email protected]( "--name-regex", default=None, help="Filter by Name regex pattern" )[email protected]( "--in-bounds", default=None, help="AABB filter: x_min,y_min,z_min,x_max,y_max,z_max" )[email protected]( "--enabled/--disabled", "enabled", default=None, help="Filter by Enabled state" )[email protected]_context+def scene_query( ctx, scene_path, has_component, has_tag, name_match, name_regex, in_bounds, enabled ):+ """Find GameObjects matching one or more filters (AND-combined)."""+ try:+ results = scene_mod.query_objects(+ scene_path,+ has_component=has_component,+ has_tag=has_tag,+ name_match=name_match,+ name_regex=name_regex,+ in_bounds=in_bounds,+ enabled=enabled,+ )++ def human( rows ):+ if not rows:+ return "(no matches)"+ return _format_table(+ [{"name": r["name"], "guid": r["guid"][:8], "position": r["position"], "components": ",".join( r["component_types"] )[:60]} for r in rows],+ ["name", "guid", "position", "components"],+ )++ _output( ctx, results, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "refs" )[email protected]( "scene_path" )[email protected]_context+def scene_refs( ctx, scene_path ):+ """Extract every asset reference from a scene, grouped by category."""+ try:+ result = scene_mod.extract_asset_refs( scene_path )++ def human( d ):+ if not d:+ return "(no asset references)"+ lines = []+ for category in sorted( d.keys() ):+ lines.append( f"{category} ({len( d[category] )}):" )+ for ref in d[category]:+ lines.append( f" {ref}" )+ return "\n".join( lines )++ _output( ctx, result, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "bulk-modify" )[email protected]( "scene_path" )[email protected]( "--has-component", default=None, help="Filter: object has this component" )[email protected]( "--has-tag", default=None, help="Filter: object has this tag" )[email protected]( "--name-match", default=None, help="Filter: Name contains substring" )[email protected]( "--name-regex", default=None, help="Filter: Name matches regex" )[email protected]( "--in-bounds", default=None, help="Filter: position inside AABB" )[email protected]( "--filter-enabled/--filter-disabled", "filter_enabled", default=None, help="Filter by Enabled state" )[email protected]( "--position", "new_position", default=None, help="New Position 'x,y,z'" )[email protected]( "--rotation", "new_rotation", default=None, help="New Rotation 'x,y,z,w'" )[email protected]( "--scale", "new_scale", default=None, help="New Scale 'x,y,z'" )[email protected]( "--tags", "new_tags", default=None, help="New Tags string" )[email protected]( "--enable/--disable", "new_enabled", default=None, help="Set Enabled state" )[email protected]_context+def scene_bulk_modify( ctx, scene_path, has_component, has_tag, name_match, name_regex, in_bounds, filter_enabled, new_position, new_rotation, new_scale, new_tags, new_enabled ):+ """Apply the same modification to every object matching the filters."""+ try:+ result = scene_mod.bulk_modify_objects(+ scene_path,+ has_component=has_component,+ has_tag=has_tag,+ name_match=name_match,+ name_regex=name_regex,+ in_bounds=in_bounds,+ enabled_filter=filter_enabled,+ new_position=new_position,+ new_rotation=new_rotation,+ new_scale=new_scale,+ new_tags=new_tags,+ new_enabled=new_enabled,+ )+ _output( ctx, result, lambda d: f"Modified {d['modified_count']} object(s); fields: {', '.join( d['modified_fields'] )}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "diff" )[email protected]( "scene_a" )[email protected]( "scene_b" )[email protected]_context+def scene_diff( ctx, scene_a, scene_b ):+ """Structural diff between two scenes (objects added/removed/modified by Name)."""+ try:+ result = scene_mod.diff_scenes( scene_a, scene_b )++ def human( d ):+ if d["identical"]:+ return f"Scenes are identical: {d['scene_a']} == {d['scene_b']}"+ lines = [f"Diff: {d['scene_a']} -> {d['scene_b']}"]+ if d["added"]:+ lines.append( f" Added ({len( d['added'] )}): {', '.join( d['added'] )}" )+ if d["removed"]:+ lines.append( f" Removed ({len( d['removed'] )}): {', '.join( d['removed'] )}" )+ if d["modified"]:+ lines.append( f" Modified ({len( d['modified'] )}):" )+ for m in d["modified"]:+ keys = list( m["changes"].keys() )+ lines.append( f" {m['name']}: {', '.join( keys )}" )+ if d.get( "scene_property_changes" ):+ lines.append( f" SceneProperties changes: {', '.join( d['scene_property_changes'].keys() )}" )+ return "\n".join( lines )++ _output( ctx, result, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "instantiate-prefab" )[email protected]( "scene_path" )[email protected]( "prefab_path" )[email protected]( "--name", default=None, help="Override the GameObject name (defaults to prefab root name)" )[email protected]( "--position", default="0,0,0", help="Position 'x,y,z'" )[email protected]( "--rotation", default="0,0,0,1", help="Rotation 'x,y,z,w'" )[email protected]( "--scale", default="1,1,1", help="Scale 'x,y,z'" )[email protected]( "--parent-guid", default=None, help="Optional parent GameObject GUID" )[email protected]_context+def scene_instantiate_prefab( ctx, scene_path, prefab_path, name, position, rotation, scale, parent_guid ):+ """Insert a prefab reference into a scene as a new GameObject (PrefabSource)."""+ try:+ new_guid = scene_mod.instantiate_prefab(+ scene_path, prefab_path,+ name=name, position=position, rotation=rotation, scale=scale,+ parent_guid=parent_guid,+ )+ result = {"guid": new_guid, "scene": scene_path, "prefab": prefab_path}+ _output( ctx, result, lambda d: f"Instantiated prefab as GameObject {d['guid']}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# prefab group+# ---------------------------------------------------------------------------++[email protected]_context+def prefab( ctx ):+ """Manage s&box prefabs."""+ pass++[email protected]( "new" )[email protected]( "--name", required=True, help="Prefab name" )[email protected]( "-o", "--output", "output_path", default=None, help="Output file path" )[email protected]( "--components", default=None, help="Comma-separated preset names" )[email protected]_context+def prefab_new( ctx, name, output_path, components ):+ """Create a new prefab."""+ try:+ if not output_path:+ output_path = f"{name}.prefab"++ comp_list = None+ if components:+ comp_list = [c.strip() for c in components.split( "," )]++ result = prefab_mod.create_prefab(+ name=name,+ output_path=output_path,+ components=comp_list,+ )+ info = {+ "name": name,+ "path": os.path.abspath( output_path ),+ "root_guid": result.get( "RootObject", {} ).get( "__guid", "" ),+ }+ _output( ctx, info, lambda d: _format_status_block( d, f"Prefab '{d['name']}' created" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "info" )[email protected]( "prefab_path" )[email protected]_context+def prefab_info( ctx, prefab_path ):+ """Show prefab info."""+ try:+ result = prefab_mod.get_prefab_info( prefab_path )+ _output( ctx, result, lambda d: _format_status_block( d, f"Prefab: {d.get( 'name', '' )}" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "from-scene" )[email protected]( "scene_path" )[email protected]( "object_guid" )[email protected]( "-o", "--output", "output_path", default=None, help="Output prefab file path" )[email protected]_context+def prefab_from_scene( ctx, scene_path, object_guid, output_path ):+ """Extract a GameObject from a scene as a prefab."""+ try:+ if not output_path:+ output_path = f"{object_guid}.prefab"+ result = prefab_mod.from_scene_object(+ scene_path=scene_path,+ object_guid=object_guid,+ output_path=output_path,+ )+ info = {+ "name": result.get( "RootObject", {} ).get( "Name", "" ),+ "path": os.path.abspath( output_path ),+ "guid": result.get( "RootObject", {} ).get( "__guid", "" ),+ }+ _output( ctx, info, lambda d: _format_status_block( d, f"Prefab extracted: {d.get( 'name', '' )}" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "add-component" )[email protected]( "prefab_path" )[email protected]( "component_type" )[email protected]( "--properties", default=None, help="Component properties as JSON" )[email protected]_context+def prefab_add_component( ctx, prefab_path, component_type, properties ):+ """Add a component to a prefab's root object."""+ try:+ import json as json_mod+ import uuid as uuid_mod+ import copy as copy_mod+ props = json_mod.loads( properties ) if properties else {}+ data = prefab_mod.load_prefab( prefab_path )+ root = data.get( "RootObject", {} )+ comps = root.get( "Components", [] )+ from cli_anything.sbox.core.scene import COMPONENT_PRESETS+ if component_type in COMPONENT_PRESETS:+ comp = copy_mod.deepcopy( COMPONENT_PRESETS[component_type] )+ else:+ comp = {"__type": component_type}+ comp["__guid"] = str( uuid_mod.uuid4() )+ comp.update( props )+ comps.append( comp )+ root["Components"] = comps+ data["RootObject"] = root+ prefab_mod.save_prefab( prefab_path, data )+ _output( ctx, {"guid": comp["__guid"], "type": comp["__type"], "prefab": prefab_path},+ lambda d: f"Added {d['type']} ({d['guid']}) to prefab" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "remove-component" )[email protected]( "prefab_path" )[email protected]( "--component-guid", default=None, help="Component GUID to remove" )[email protected]( "--component-type", default=None, help="Component type to remove" )[email protected]_context+def prefab_remove_component( ctx, prefab_path, component_guid, component_type ):+ """Remove a component from a prefab's root object."""+ try:+ if not component_guid and not component_type:+ _output_error( ctx, "Must provide --component-guid or --component-type" )+ return+ data = prefab_mod.load_prefab( prefab_path )+ root = data.get( "RootObject", {} )+ comps = root.get( "Components", [] )+ original_count = len( comps )+ if component_guid:+ comps = [c for c in comps if c.get( "__guid" ) != component_guid]+ elif component_type:+ comps = [c for c in comps if c.get( "__type" ) != component_type]+ removed = original_count > len( comps )+ root["Components"] = comps+ data["RootObject"] = root+ prefab_mod.save_prefab( prefab_path, data )+ _output( ctx, {"removed": removed}, lambda d: f"Component {'removed' if d['removed'] else 'not found'}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "list" )[email protected]_context+def prefab_list( ctx ):+ """List prefabs in the project."""+ try:+ project_dir = _resolve_project_dir( ctx )+ if not project_dir:+ _output_error( ctx, "No project found" )+ return+ from cli_anything.sbox.core import export as export_mod_local+ assets = export_mod_local.list_assets( project_dir, asset_type="prefab" )+ _output( ctx, assets )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "refs" )[email protected]( "prefab_path" )[email protected]_context+def prefab_refs( ctx, prefab_path ):+ """Extract every asset reference from a prefab, grouped by category."""+ try:+ result = prefab_mod.extract_asset_refs( prefab_path )++ def human( d ):+ if not d:+ return "(no asset references)"+ lines = []+ for category in sorted( d.keys() ):+ lines.append( f"{category} ({len( d[category] )}):" )+ for ref in d[category]:+ lines.append( f" {ref}" )+ return "\n".join( lines )++ _output( ctx, result, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "modify-component" )[email protected]( "prefab_path" )[email protected]( "--component-guid", default=None, help="Component GUID" )[email protected]( "--component-type", default=None, help="Component type (e.g. Sandbox.Rigidbody)" )[email protected]( "--object-guid", default=None, help="Restrict search to a single object" )[email protected]( "--properties", required=True, help="Properties to set as JSON" )[email protected]_context+def prefab_modify_component( ctx, prefab_path, component_guid, component_type, object_guid, properties ):+ """Modify properties of a component within a prefab."""+ try:+ import json as json_mod+ props = json_mod.loads( properties )+ result = prefab_mod.modify_component(+ prefab_path,+ component_guid=component_guid,+ component_type=component_type,+ object_guid=object_guid,+ properties=props,+ )+ _output( ctx, result, lambda d: f"Modified {d['component_type']}: {', '.join( d['updated_keys'] )}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "diff" )[email protected]( "prefab_a" )[email protected]( "prefab_b" )[email protected]_context+def prefab_diff( ctx, prefab_a, prefab_b ):+ """Structural diff between two prefabs (root + children by Name)."""+ try:+ result = prefab_mod.diff_prefabs( prefab_a, prefab_b )++ def human( d ):+ if d["identical"]:+ return f"Prefabs are identical: {d['prefab_a']} == {d['prefab_b']}"+ lines = [f"Diff: {d['prefab_a']} -> {d['prefab_b']}"]+ if d.get( "root_changes" ):+ keys = list( d["root_changes"]["changes"].keys() )+ lines.append( f" Root changed: {', '.join( keys )}" )+ if d["children_added"]:+ lines.append( f" Children added ({len( d['children_added'] )}): {', '.join( d['children_added'] )}" )+ if d["children_removed"]:+ lines.append( f" Children removed ({len( d['children_removed'] )}): {', '.join( d['children_removed'] )}" )+ if d["children_modified"]:+ lines.append( f" Children modified ({len( d['children_modified'] )}):" )+ for m in d["children_modified"]:+ keys = list( m["changes"].keys() )+ lines.append( f" {m['name']}: {', '.join( keys )}" )+ return "\n".join( lines )++ _output( ctx, result, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# codegen group+# ---------------------------------------------------------------------------++[email protected]_context+def codegen( ctx ):+ """Generate s&box C# code."""+ pass++[email protected]( "component" )[email protected]( "--name", required=True, help="Component class name (PascalCase)" )[email protected]( "-o", "--output", "output_path", default=None, help="Output file path" )[email protected]( "--properties", default=None, help="Properties as JSON array of {name, type, default?, category?}" )[email protected]( "--methods", default=None, help="Comma-separated lifecycle methods (OnUpdate, OnFixedUpdate, OnStart)" )[email protected]( "--networked", is_flag=True, help="Generate networked component (partial class, [Sync] attributes)" )[email protected]( "--interfaces", default=None, help="Comma-separated interface names" )[email protected]( "--rpc-methods", default=None, help="RPC methods as Name:Type pairs (e.g. Fire:Broadcast,Die:Host)" )[email protected]_context+def codegen_component( ctx, name, output_path, properties, methods, networked, interfaces, rpc_methods ):+ """Generate a C# component class."""+ try:+ props = None+ if properties:+ props = json.loads( properties )++ method_list = None+ if methods:+ method_list = [m.strip() for m in methods.split( "," )]++ iface_list = None+ if interfaces:+ iface_list = [i.strip() for i in interfaces.split( "," )]++ rpc_list = None+ if rpc_methods:+ rpc_list = []+ for pair in rpc_methods.split(","):+ parts = pair.strip().split(":")+ rpc_list.append({"name": parts[0].strip(), "type": parts[1].strip() if len(parts) > 1 else "Broadcast"})++ result = codegen_mod.generate_component(+ class_name=name,+ properties=props,+ lifecycle_methods=method_list,+ interfaces=iface_list,+ is_networked=networked,+ rpc_methods=rpc_list,+ )++ if output_path:+ os.makedirs( os.path.dirname( output_path ) if os.path.dirname( output_path ) else ".", exist_ok=True )+ with open( output_path, "w", encoding="utf-8", newline="\r\n" ) as f:+ f.write( result["content"] )+ result["path"] = os.path.abspath( output_path )+ else:+ result["path"] = result["filename"]++ if ctx.obj.get( "json" ):+ _output( ctx, result )+ else:+ if output_path:+ click.echo( f"Generated {result['filename']} at {result['path']}" )+ else:+ click.echo( f"--- {result['filename']} ---" )+ click.echo( result["content"] )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "gameresource" )[email protected]( "--name", required=True, help="GameResource class name" )[email protected]( "--display-name", default=None, help="Display name in editor" )[email protected]( "--extension", default=None, help="File extension for the resource" )[email protected]( "-o", "--output", "output_path", default=None, help="Output file path" )[email protected]( "--properties", default=None, help="Properties as JSON array of {name, type, default?, category?}" )[email protected]_context+def codegen_gameresource( ctx, name, display_name, extension, output_path, properties ):+ """Generate a GameResource class."""+ try:+ props = None+ if properties:+ props = json.loads( properties )++ result = codegen_mod.generate_gameresource(+ class_name=name,+ display_name=display_name or name,+ extension=extension or name.lower(),+ properties=props,+ )++ if output_path:+ os.makedirs( os.path.dirname( output_path ) if os.path.dirname( output_path ) else ".", exist_ok=True )+ with open( output_path, "w", encoding="utf-8", newline="\r\n" ) as f:+ f.write( result["content"] )+ result["path"] = os.path.abspath( output_path )+ else:+ result["path"] = result["filename"]++ if ctx.obj.get( "json" ):+ _output( ctx, result )+ else:+ if output_path:+ click.echo( f"Generated {result['filename']} at {result['path']}" )+ else:+ click.echo( f"--- {result['filename']} ---" )+ click.echo( result["content"] )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "editor-menu" )[email protected]( "--name", required=True, help="Editor menu class name" )[email protected]( "--menu-path", default=None, help="Menu path (e.g. Tools/My Tool)" )[email protected]( "-o", "--output", "output_path", default=None, help="Output file path" )[email protected]_context+def codegen_editor_menu( ctx, name, menu_path, output_path ):+ """Generate an editor menu class."""+ try:+ result = codegen_mod.generate_editor_menu(+ class_name=name,+ menu_path=menu_path or f"Tools/{name}",+ )++ if output_path:+ os.makedirs( os.path.dirname( output_path ) if os.path.dirname( output_path ) else ".", exist_ok=True )+ with open( output_path, "w", encoding="utf-8", newline="\r\n" ) as f:+ f.write( result["content"] )+ result["path"] = os.path.abspath( output_path )+ else:+ result["path"] = result["filename"]++ if ctx.obj.get( "json" ):+ _output( ctx, result )+ else:+ if output_path:+ click.echo( f"Generated {result['filename']} at {result['path']}" )+ else:+ click.echo( f"--- {result['filename']} ---" )+ click.echo( result["content"] )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "razor" )[email protected]( "--name", required=True, help="Component class name (PascalCase)" )[email protected]( "--inherits", default="PanelComponent", help="Base class" )[email protected]( "--properties", default=None, help="Properties as JSON array" )[email protected]( "--root-class", default=None, help="CSS class for root element" )[email protected]( "-o", "--output", "output_path", default=None, help="Output .razor file path" )[email protected]_context+def codegen_razor( ctx, name, inherits, properties, root_class, output_path ):+ """Generate a Razor UI component."""+ try:+ props = json.loads( properties ) if properties else None+ result = codegen_mod.generate_razor( name, inherits=inherits, properties=props, root_class=root_class )++ if output_path:+ os.makedirs( os.path.dirname( output_path ) or ".", exist_ok=True )+ with open( output_path, "w", encoding="utf-8" ) as f:+ f.write( result["content"] )+ # Also write scss+ if output_path.endswith( ".razor" ):+ scss_path = output_path + ".scss"+ elif output_path.endswith( ".scss" ):+ scss_path = output_path+ else:+ scss_path = output_path + ".scss"+ with open( scss_path, "w", encoding="utf-8" ) as f:+ f.write( result["scss_content"] )+ result["path"] = os.path.abspath( output_path )+ result["scss_path"] = os.path.abspath( scss_path )++ _output( ctx, result, lambda d: f"Razor component '{d['class_name']}' generated" + (f" at {d.get('path', '')}" if d.get('path') else "") )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "class" )[email protected]( "--name", required=True, help="Class name (PascalCase)" )[email protected]( "--base-class", default=None, help="Base class to inherit from" )[email protected]( "--static", "is_static", is_flag=True, help="Generate a static class" )[email protected]( "--properties", default=None, help="Properties as JSON array" )[email protected]( "--methods", default=None, help="Methods as JSON array" )[email protected]( "-o", "--output", "output_path", default=None, help="Output .cs file path" )[email protected]_context+def codegen_class( ctx, name, base_class, is_static, properties, methods, output_path ):+ """Generate a plain C# class."""+ try:+ props = json.loads( properties ) if properties else None+ meths = json.loads( methods ) if methods else None+ result = codegen_mod.generate_class( name, base_class=base_class, is_static=is_static, properties=props, methods=meths )++ if output_path:+ os.makedirs( os.path.dirname( output_path ) or ".", exist_ok=True )+ with open( output_path, "w", encoding="utf-8" ) as f:+ f.write( result["content"] )+ result["path"] = os.path.abspath( output_path )++ _output( ctx, result, lambda d: f"Class '{d['class_name']}' generated" + ( f" at {d.get( 'path', '' )}" if d.get( 'path' ) else "" ) )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "panel-component" )[email protected]( "--name", required=True, help="PanelComponent class name (PascalCase)" )[email protected]( "--namespace", default=None, help="Optional C# namespace" )[email protected]( "--properties", default=None, help="Properties as JSON array (same format as razor)" )[email protected]( "--root-class", default=None, help="CSS root class (default: kebab-case of name)" )[email protected]( "--z-index", "z_index", type=int, default=100, help="ScreenPanel ZIndex (default 100)" )[email protected]( "--opacity", type=float, default=1.0, help="ScreenPanel Opacity (default 1.0)" )[email protected]( "-o", "--output", "output_path", default=None, help="Output .razor file path (also writes .razor.scss)" )[email protected]( "--scene", "scene_path", default=None, help="Optional scene to append the GameObject snippet to" )[email protected]_context+def codegen_panel_component( ctx, name, namespace, properties, root_class, z_index, opacity, output_path, scene_path ):+ """Scaffold a PanelComponent + sibling ScreenPanel on the same GameObject.++ Handles the s&box quirk where PanelComponent input requires both components+ on the same GameObject. Emits .razor + .razor.scss + a paste-ready GameObject+ JSON snippet, and can optionally append the GameObject directly to a scene.+ """+ try:+ props = json.loads( properties ) if properties else None+ result = codegen_mod.generate_panel_component(+ name,+ properties=props,+ namespace=namespace,+ z_index=z_index,+ opacity=opacity,+ root_class=root_class,+ )++ if output_path:+ os.makedirs( os.path.dirname( output_path ) or ".", exist_ok=True )+ with open( output_path, "w", encoding="utf-8" ) as f:+ f.write( result["content"] )+ scss_path = os.path.join( os.path.dirname( output_path ), result["scss_filename"] )+ with open( scss_path, "w", encoding="utf-8" ) as f:+ f.write( result["scss_content"] )+ result["razor_path"] = os.path.abspath( output_path )+ result["scss_path"] = os.path.abspath( scss_path )++ if scene_path:+ scene_data = scene_mod.load_scene( scene_path )+ snippet_obj = json.loads( result["scene_snippet"] )+ scene_data.setdefault( "GameObjects", [] ).append( snippet_obj )+ scene_mod.save_scene( scene_path, scene_data )+ result["scene_appended_to"] = os.path.abspath( scene_path )++ def human( d ):+ lines = [f"PanelComponent '{d['class_name']}' generated"]+ if d.get( "razor_path" ):+ lines.append( f" razor: {d['razor_path']}" )+ lines.append( f" scss: {d['scss_path']}" )+ if d.get( "scene_appended_to" ):+ lines.append( f" scene: appended to {d['scene_appended_to']} (object_guid={d['object_guid']})" )+ else:+ lines.append( " Paste the snippet under GameObjects in your .scene to wire it up." )+ return "\n".join( lines )++ _output( ctx, result, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# input group+# ---------------------------------------------------------------------------++[email protected]( "input" )[email protected]_context+def input_group( ctx ):+ """Manage s&box input action bindings."""+ pass+++@input_group.command( "list" )[email protected]( "config_path", required=False, default=None )[email protected]_context+def input_list( ctx, config_path ):+ """List input actions."""+ try:+ resolved = _resolve_input_config( ctx, config_path )+ actions = input_config_mod.list_actions( resolved )+ if ctx.obj.get( "json" ):+ _output( ctx, actions )+ else:+ rows = []+ for a in actions:+ rows.append( {+ "name": a.get( "Name", "" ),+ "group": a.get( "GroupName", "" ),+ "keyboard": a.get( "KeyboardCode", "" ),+ "gamepad": a.get( "GamepadCode", "" ),+ } )+ click.echo( _format_table( rows, ["name", "group", "keyboard", "gamepad"] ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++@input_group.command( "add" )[email protected]( "--name", required=True, help="Action name" )[email protected]( "--group", default="Other", help="Group name" )[email protected]( "--keyboard", default="None", help="Keyboard binding" )[email protected]( "--gamepad", default="None", help="Gamepad binding" )[email protected]( "--title", default=None, help="Display title" )[email protected]_context+def input_add( ctx, name, group, keyboard, gamepad, title ):+ """Add an input action."""+ try:+ resolved = _resolve_input_config( ctx )+ result = input_config_mod.add_action(+ config_path=resolved,+ name=name,+ group=group,+ keyboard_code=keyboard,+ gamepad_code=gamepad,+ title=title,+ )+ _output( ctx, result, lambda d: f"Added action '{d.get( 'Name', '' )}' in group '{d.get( 'GroupName', '' )}'" )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++@input_group.command( "remove" )[email protected]( "--name", required=True, help="Action name to remove" )[email protected]_context+def input_remove( ctx, name ):+ """Remove an input action."""+ try:+ resolved = _resolve_input_config( ctx )+ removed = input_config_mod.remove_action( resolved, name )+ result = {"removed": removed, "name": name}+ if removed:+ _output( ctx, result, lambda d: f"Removed action '{d['name']}'" )+ else:+ _output( ctx, result, lambda d: f"Action '{d['name']}' not found" )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++@input_group.command( "set" )[email protected]( "--name", required=True, help="Action name to modify" )[email protected]( "--keyboard", default=None, help="New keyboard binding" )[email protected]( "--gamepad", default=None, help="New gamepad binding" )[email protected]( "--group", default=None, help="New group name" )[email protected]_context+def input_set( ctx, name, keyboard, gamepad, group ):+ """Modify an input action."""+ try:+ resolved = _resolve_input_config( ctx )+ result = input_config_mod.set_action(+ config_path=resolved,+ name=name,+ keyboard_code=keyboard,+ gamepad_code=gamepad,+ group=group,+ )+ _output( ctx, result, lambda d: f"Updated action '{d.get( 'Name', '' )}'" )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# collision group+# ---------------------------------------------------------------------------++[email protected]( "collision" )[email protected]_context+def collision_group( ctx ):+ """Manage s&box collision layers and rules."""+ pass+++@collision_group.command( "list" )[email protected]_context+def collision_list( ctx ):+ """List collision layers and rules."""+ try:+ resolved = _resolve_collision_config( ctx )+ result = collision_config_mod.list_layers( resolved )+ if ctx.obj.get( "json" ):+ _output( ctx, result )+ else:+ click.echo( "Layers:" )+ defaults = result.get( "defaults", {} )+ for layer_name, default_val in defaults.items():+ click.echo( f" {layer_name}: {default_val}" )++ click.echo( "" )+ click.echo( "Pair Rules:" )+ pairs = result.get( "pairs", [] )+ if pairs:+ rows = []+ for p in pairs:+ rows.append( {+ "layer_a": p.get( "a", p.get( "A", "" ) ),+ "layer_b": p.get( "b", p.get( "B", "" ) ),+ "result": p.get( "r", p.get( "Collide", "" ) ),+ } )+ click.echo( _format_table( rows, ["layer_a", "layer_b", "result"] ) )+ else:+ click.echo( " (none)" )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++@collision_group.command( "add-layer" )[email protected]( "--name", required=True, help="Layer name" )[email protected]( "--default", "default_val", type=click.Choice( ["Collide", "Trigger", "Ignore"] ), default="Collide", help="Default collision behavior" )[email protected]_context+def collision_add_layer( ctx, name, default_val ):+ """Add a collision layer."""+ try:+ resolved = _resolve_collision_config( ctx )+ result = collision_config_mod.add_layer( resolved, name, default=default_val )+ _output( ctx, result, lambda d: f"Added layer '{name}' with default '{default_val}'" )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++@collision_group.command( "add-rule" )[email protected]( "--layer-a", required=True, help="First layer" )[email protected]( "--layer-b", required=True, help="Second layer" )[email protected]( "--result", type=click.Choice( ["Collide", "Trigger", "Ignore"] ), default="Collide", help="Collision result" )[email protected]_context+def collision_add_rule( ctx, layer_a, layer_b, result ):+ """Add a collision pair rule."""+ try:+ resolved = _resolve_collision_config( ctx )+ rule = collision_config_mod.add_rule( resolved, layer_a, layer_b, result=result )+ _output( ctx, rule, lambda d: f"Rule: {layer_a} <-> {layer_b} = {result}" )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++@collision_group.command( "remove-rule" )[email protected]( "--layer-a", required=True, help="First collision layer" )[email protected]( "--layer-b", required=True, help="Second collision layer" )[email protected]_context+def collision_remove_rule( ctx, layer_a, layer_b ):+ """Remove a collision pair rule."""+ try:+ config_path = _resolve_collision_config( ctx )+ removed = collision_config_mod.remove_rule( config_path, layer_a, layer_b )+ result = {"removed": removed, "layer_a": layer_a, "layer_b": layer_b}+ _output( ctx, result, lambda d: f"Rule {d['layer_a']}-{d['layer_b']} {'removed' if d['removed'] else 'not found'}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++@collision_group.command( "remove-layer" )[email protected]( "--name", required=True, help="Layer name to remove" )[email protected]_context+def collision_remove_layer( ctx, name ):+ """Remove a custom collision layer."""+ try:+ config_path = _resolve_collision_config( ctx )+ removed = collision_config_mod.remove_layer( config_path, name )+ result = {"removed": removed, "layer": name}+ _output( ctx, result, lambda d: f"Layer '{d['layer']}' {'removed' if d['removed'] else 'not found'}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# server group+# ---------------------------------------------------------------------------++[email protected]_context+def server( ctx ):+ """Manage s&box dedicated server."""+ pass++[email protected]( "start" )[email protected]( "--game", required=True, help="Game identifier (e.g. org.gamename)" )[email protected]( "--map", "map_ident", default=None, help="Map identifier" )[email protected]_context+def server_start( ctx, game, map_ident ):+ """Launch a dedicated server."""+ try:+ proc = sbox_backend.launch_server( game, map_ident=map_ident )+ result = {"pid": proc.pid, "game": game, "map": map_ident, "status": "launched"}+ _output( ctx, result, lambda d: f"Server launched (PID {d['pid']}) - game: {d['game']}" )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "info" )[email protected]_context+def server_info( ctx ):+ """Show server executable path and version."""+ try:+ exe = sbox_backend.find_executable( "sbox-server" )+ version = sbox_backend.get_sbox_version()+ result = {"executable": exe, "version": version}+ _output( ctx, result, lambda d: _format_status_block( {+ "executable": d["executable"],+ "version": d["version"].get( "version", "unknown" ),+ "sbox_path": d["version"].get( "sbox_path", "unknown" ),+ }, "Server Info" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# asset group+# ---------------------------------------------------------------------------++[email protected]_context+def asset( ctx ):+ """Manage project assets."""+ pass++[email protected]( "list" )[email protected]( "--type", "asset_type", default=None, help="Filter by asset type (scene, prefab, material, model, etc.)" )[email protected]_context+def asset_list( ctx, asset_type ):+ """List project assets."""+ try:+ proj_dir = _resolve_project_dir( ctx )+ if not proj_dir:+ raise click.ClickException( "No project found. Use --project or run from a project directory." )++ assets = export_mod.list_assets( proj_dir, asset_type=asset_type )+ if ctx.obj.get( "json" ):+ _output( ctx, assets )+ else:+ if not assets:+ click.echo( "No assets found." )+ return+ rows = []+ for a in assets:+ size_kb = a["size_bytes"] / 1024+ rows.append( {+ "name": a["name"],+ "type": a["type"],+ "path": a["path"],+ "size": f"{size_kb:.1f} KB",+ } )+ click.echo( _format_table( rows, ["name", "type", "path", "size"] ) )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "info" )[email protected]( "asset_path" )[email protected]_context+def asset_info( ctx, asset_path ):+ """Show asset details."""+ try:+ result = export_mod.get_asset_info( asset_path )+ _output( ctx, result, lambda d: _format_status_block( d, f"Asset: {d.get( 'name', '' )}" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "compile" )[email protected]( "asset_path" )[email protected]_context+def asset_compile( ctx, asset_path ):+ """Compile an asset using s&box resource compiler."""+ try:+ from cli_anything.sbox.utils import sbox_backend+ result = sbox_backend.run_resource_compiler( asset_path )+ _output( ctx, result, lambda d: f"Compiled: {d.get( 'asset_path', asset_path )}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "find-refs" )[email protected]( "asset_path" )[email protected]_context+def asset_find_refs( ctx, asset_path ):+ """Find every scene/prefab in the project that references the given asset."""+ try:+ proj_dir = _resolve_project_dir( ctx )+ if not proj_dir:+ _output_error( ctx, "No project found" )+ return+ result = export_mod.find_asset_refs( proj_dir, asset_path )++ def human( rows ):+ if not rows:+ return f"(no references to {asset_path})"+ lines = [f"Found {len( rows )} reference(s) to {asset_path}:"]+ for row in rows:+ lines.append( f" {row['file']} ({row['category']}) -> {row['original_ref']}" )+ return "\n".join( lines )++ _output( ctx, result, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "find-unused" )[email protected]( "--type", "asset_types", multiple=True, help="Asset types to check (model, material, sound, texture, prefab). Repeatable." )[email protected]_context+def asset_find_unused( ctx, asset_types ):+ """Find project assets that aren't referenced by any scene or prefab."""+ try:+ proj_dir = _resolve_project_dir( ctx )+ if not proj_dir:+ _output_error( ctx, "No project found" )+ return+ types_list = list( asset_types ) if asset_types else None+ result = export_mod.find_unused_assets( proj_dir, asset_types=types_list )++ def human( rows ):+ if not rows:+ return "(no unused assets found)"+ return _format_table(+ [{"path": r["path"], "type": r["type"], "size_bytes": r["size_bytes"]} for r in rows],+ ["path", "type", "size_bytes"],+ )++ _output( ctx, result, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "rename" )[email protected]( "old_path" )[email protected]( "new_name" )[email protected]( "--dry-run", is_flag=True, help="Report what would change without touching files" )[email protected]_context+def asset_rename( ctx, old_path, new_name, dry_run ):+ """Rename an asset (in same directory) and update every reference in scenes/prefabs."""+ try:+ proj_dir = _resolve_project_dir( ctx )+ if not proj_dir:+ _output_error( ctx, "No project found" )+ return+ result = export_mod.rename_asset( proj_dir, old_path, new_name, dry_run=dry_run )++ def human( d ):+ if d.get( "dry_run" ):+ return f"[dry-run] Would rename {d['old_path']} -> {d['new_path']} and update {d['references_would_update']} reference(s)"+ n = sum( r["replacements"] for r in d["references_updated"] )+ return f"Renamed {d['old_path']} -> {d['new_path']}, updated {n} reference(s) in {len( d['references_updated'] )} file(s)"++ _output( ctx, result, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "move" )[email protected]( "old_path" )[email protected]( "new_path" )[email protected]( "--dry-run", is_flag=True, help="Report what would change without touching files" )[email protected]_context+def asset_move( ctx, old_path, new_path, dry_run ):+ """Move an asset to a new path (different directory) and update every reference."""+ try:+ proj_dir = _resolve_project_dir( ctx )+ if not proj_dir:+ _output_error( ctx, "No project found" )+ return+ result = export_mod.move_asset( proj_dir, old_path, new_path, dry_run=dry_run )++ def human( d ):+ if d.get( "dry_run" ):+ return f"[dry-run] Would move {d['old_path']} -> {d['new_path']} and update {d['references_would_update']} reference(s)"+ n = sum( r["replacements"] for r in d["references_updated"] )+ return f"Moved {d['old_path']} -> {d['new_path']}, updated {n} reference(s) in {len( d['references_updated'] )} file(s)"++ _output( ctx, result, human )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# material group+# ---------------------------------------------------------------------------++[email protected]_context+def material( ctx ):+ """Manage s&box materials."""+ pass++[email protected]( "new" )[email protected]( "--name", required=True, help="Material name" )[email protected]( "--shader", default="complex", help="Shader (complex, simple, unlit, glass)" )[email protected]( "--color-texture", default=None, help="Color/albedo texture path" )[email protected]( "--normal-texture", default=None, help="Normal map texture path" )[email protected]( "--roughness-texture", default=None, help="Roughness texture path" )[email protected]( "--metalness", type=float, default=0.0, help="Metalness (0-1)" )[email protected]( "--tint", default="1 1 1 0", help="Color tint (r g b a)" )[email protected]( "-o", "--output", "output_path", default=None, help="Output .vmat file path" )[email protected]_context+def material_new( ctx, name, shader, color_texture, normal_texture, roughness_texture, metalness, tint, output_path ):+ """Create a new material."""+ try:+ result = material_mod.create_material(+ name, shader=shader, color_texture=color_texture,+ normal_texture=normal_texture, roughness_texture=roughness_texture,+ metalness=metalness, tint=tint, output_path=output_path,+ )+ _output( ctx, result, lambda d: f"Material '{d['name']}' created" + (f" at {d.get('path', 'stdout')}" if d.get('path') else "") )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "info" )[email protected]( "material_path" )[email protected]_context+def material_info( ctx, material_path ):+ """Show material properties."""+ try:+ result = material_mod.parse_material( material_path )+ _output( ctx, result, lambda d: _format_status_block( d, f"Material: {d['name']}" ) )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "list" )[email protected]_context+def material_list( ctx ):+ """List materials in the project."""+ try:+ project_dir = _resolve_project_dir( ctx )+ if not project_dir:+ _output_error( ctx, "No project found" )+ return+ result = material_mod.list_materials( project_dir )+ _output( ctx, result )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "set" )[email protected]( "material_path" )[email protected]( "--shader", default=None, help="New shader" )[email protected]( "--color-texture", default=None, help="New color texture path" )[email protected]( "--normal-texture", default=None, help="New normal texture path" )[email protected]( "--metalness", type=float, default=None, help="New metalness (0-1)" )[email protected]( "--tint", default=None, help="New tint (r g b a)" )[email protected]_context+def material_set( ctx, material_path, shader, color_texture, normal_texture, metalness, tint ):+ """Update properties of an existing material."""+ try:+ result = material_mod.update_material(+ material_path, shader=shader, color_texture=color_texture,+ normal_texture=normal_texture, metalness=metalness, tint=tint,+ )+ _output( ctx, result, lambda d: f"Material '{d['name']}' updated" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# sound group+# ---------------------------------------------------------------------------++[email protected]_context+def sound( ctx ):+ """Manage s&box sound events."""+ pass++[email protected]( "new" )[email protected]( "--name", required=True, help="Sound event name" )[email protected]( "--sounds", default=None, help="Comma-separated .vsnd paths" )[email protected]( "--volume", default="1", help="Volume (0-1)" )[email protected]( "--pitch", default="1", help="Pitch multiplier" )[email protected]( "--decibels", type=int, default=70, help="Loudness in dB" )[email protected]( "--ui/--no-ui", default=False, help="UI sound (no spatialization)" )[email protected]( "-o", "--output", "output_path", default=None, help="Output .sound file path" )[email protected]_context+def sound_new( ctx, name, sounds, volume, pitch, decibels, ui, output_path ):+ """Create a new sound event."""+ try:+ sound_list = [s.strip() for s in sounds.split(",")] if sounds else []+ result = sound_mod.create_sound_event(+ name, sounds=sound_list, volume=volume, pitch=pitch,+ decibels=decibels, is_ui=ui, output_path=output_path,+ )+ _output( ctx, result, lambda d: f"Sound '{d['name']}' created" + (f" at {d.get('path', '')}" if d.get('path') else "") )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "info" )[email protected]( "sound_path" )[email protected]_context+def sound_info( ctx, sound_path ):+ """Show sound event details."""+ try:+ result = sound_mod.parse_sound_event( sound_path )+ _output( ctx, result, lambda d: _format_status_block( d, f"Sound: {d['name']}" ) )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "list" )[email protected]_context+def sound_list( ctx ):+ """List sound events in the project."""+ try:+ project_dir = _resolve_project_dir( ctx )+ if not project_dir:+ _output_error( ctx, "No project found" )+ return+ from cli_anything.sbox.core import export as export_mod_local+ assets = export_mod_local.list_assets( project_dir, asset_type="sound" )+ _output( ctx, assets )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "set" )[email protected]( "sound_path" )[email protected]( "--sounds", default=None, help="Comma-separated .vsnd paths (replaces all)" )[email protected]( "--volume", default=None, help="Volume (0-1)" )[email protected]( "--pitch", default=None, help="Pitch multiplier" )[email protected]( "--decibels", type=int, default=None, help="Loudness in dB" )[email protected]( "--is-ui/--no-is-ui", "is_ui", default=None, help="Mark sound as UI (skips occlusion/positional audio)" )[email protected]( "--occlusion/--no-occlusion", "occlusion", default=None, help="Enable occlusion calculations" )[email protected]_context+def sound_set( ctx, sound_path, sounds, volume, pitch, decibels, is_ui, occlusion ):+ """Update properties of an existing sound event."""+ try:+ sound_list_parsed = [s.strip() for s in sounds.split( "," )] if sounds is not None else None+ result = sound_mod.update_sound_event(+ sound_path, sounds=sound_list_parsed, volume=volume,+ pitch=pitch, decibels=decibels, is_ui=is_ui, occlusion=occlusion,+ )+ _output( ctx, result, lambda d: f"Sound '{d['name']}' updated" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# localization group+# ---------------------------------------------------------------------------++[email protected]_context+def localization( ctx ):+ """Manage translation files."""+ pass++[email protected]( "new" )[email protected]( "--lang", default="en", help="Language code" )[email protected]( "-o", "--output", "output_path", default=None, help="Output .json file path" )[email protected]_context+def localization_new( ctx, lang, output_path ):+ """Create a new translation file."""+ try:+ result = localization_mod.create_translation_file( lang=lang, output_path=output_path )+ _output( ctx, result, lambda d: f"Translation file ({d['lang']}) created" + (f" at {d.get('path', '')}" if d.get('path') else "") )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "list" )[email protected]( "file_path" )[email protected]_context+def localization_list( ctx, file_path ):+ """List translation keys."""+ try:+ keys = localization_mod.list_keys( file_path )+ _output( ctx, keys )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "set" )[email protected]( "file_path" )[email protected]( "--key", required=True, help="Translation key" )[email protected]( "--value", required=True, help="Translation value" )[email protected]_context+def localization_set( ctx, file_path, key, value ):+ """Set a translation key-value pair."""+ try:+ result = localization_mod.set_key( file_path, key, value )+ _output( ctx, {"key": key, "value": value, "total_keys": len( result )}, lambda d: f"Set '{d['key']}' = '{d['value']}' ({d['total_keys']} keys total)" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "get" )[email protected]( "file_path" )[email protected]( "--key", required=True, help="Translation key" )[email protected]_context+def localization_get( ctx, file_path, key ):+ """Get a translation value by key."""+ try:+ value = localization_mod.get_key( file_path, key )+ if value is None:+ _output_error( ctx, f"Key '{key}' not found" )+ return+ _output( ctx, {"key": key, "value": value}, lambda d: f"{d['key']} = {d['value']}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "remove" )[email protected]( "file_path" )[email protected]( "--key", required=True, help="Translation key to remove" )[email protected]_context+def localization_remove( ctx, file_path, key ):+ """Remove a translation key."""+ try:+ removed = localization_mod.remove_key( file_path, key )+ result = {"key": key, "removed": removed}+ _output( ctx, result, lambda d: f"Key '{d['key']}' {'removed' if d['removed'] else 'not found'}" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )++[email protected]( "bulk-set" )[email protected]( "file_path" )[email protected]( "--keys", required=True, help="Key-value pairs as JSON object" )[email protected]_context+def localization_bulk_set( ctx, file_path, keys ):+ """Set multiple translation keys at once."""+ try:+ keys_dict = json.loads( keys )+ result = localization_mod.bulk_set( file_path, keys_dict )+ _output( ctx, {"total_keys": len( result ), "added": len( keys_dict )}, lambda d: f"Set {d['added']} keys ({d['total_keys']} total)" )+ except click.ClickException:+ raise+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# launch command+# ---------------------------------------------------------------------------++[email protected]_context+def launch( ctx ):+ """Open project in the s&box editor."""+ try:+ sbproj = _resolve_project_path( ctx )+ project_arg = sbproj if sbproj else None+ proc = sbox_backend.launch_editor( project_path=project_arg )+ result = {"pid": proc.pid, "project": project_arg, "status": "launched"}+ _output( ctx, result, lambda d: f"s&box editor launched (PID {d['pid']})" )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# session group+# ---------------------------------------------------------------------------++[email protected]( "session" )[email protected]_context+def session_group( ctx ):+ """Manage CLI session state."""+ pass+++@session_group.command( "status" )[email protected]_context+def session_status( ctx ):+ """Show session state."""+ try:+ sess = session_mod.Session()+ result = sess.get_status()+ _output( ctx, result, lambda d: _format_status_block( d, "Session Status" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++@session_group.command( "undo" )[email protected]_context+def session_undo( ctx ):+ """Undo last operation."""+ try:+ sess = session_mod.Session()+ result = sess.undo()+ if result:+ _output( ctx, result, lambda d: f"Undone: {d.get( 'description', '(no description)' )}" )+ else:+ msg = {"message": "Nothing to undo"}+ _output( ctx, msg, lambda d: d["message"] )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++@session_group.command( "redo" )[email protected]_context+def session_redo( ctx ):+ """Redo last undone operation."""+ try:+ sess = session_mod.Session()+ result = sess.redo()+ if result:+ _output( ctx, result, lambda d: f"Redone: {d.get( 'description', '(no description)' )}" )+ else:+ msg = {"message": "Nothing to redo"}+ _output( ctx, msg, lambda d: d["message"] )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# test group+# ---------------------------------------------------------------------------++[email protected]( "test" )[email protected]_context+def test_group( ctx ):+ """Run automated map generation tests."""+ pass+++@test_group.command( "setup" )[email protected]_context+def test_setup( ctx ):+ """First-run setup: verify paths, create test scene."""+ try:+ sbox_install = sbox_backend.find_sbox_installation()+ sbproj = _resolve_project_path( ctx )+ if not sbproj:+ raise click.ClickException( "No .sbproj found." )++ info = project_mod.get_project_info( sbproj )+ ident = info.get( "ident", "hold_the_line" )++ data_path = test_mod.resolve_data_path( sbox_install, ident )++ result = {+ "sbox_install": sbox_install,+ "data_path": data_path,+ "sbproj": sbproj,+ "ident": ident,+ "status": "ready",+ }+ _output( ctx, result, lambda d: _format_status_block( d, "Test Setup" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++@test_group.command( "run" )[email protected]( "--strategies", default=None, help="Comma-separated strategies (default: all)" )[email protected]( "--sizes", default=None, help="Comma-separated sizes (default: all)" )[email protected]( "--seeds", default=None, help="Comma-separated seed values" )[email protected]( "--seed-count", type=int, default=1, help="Number of random seeds per combo" )[email protected]( "--timeout", type=float, default=60.0, help="Timeout per combo in seconds" )[email protected]_context+def test_run( ctx, strategies, sizes, seeds, seed_count, timeout ):+ """Run map generation tests across strategy/size/seed combos."""+ try:+ sbox_install = sbox_backend.find_sbox_installation()+ sbproj = _resolve_project_path( ctx )+ if not sbproj:+ raise click.ClickException( "No .sbproj found." )++ info = project_mod.get_project_info( sbproj )+ ident = info.get( "ident", "hold_the_line" )+ data_path = test_mod.resolve_data_path( sbox_install, ident )++ project_dir = os.path.dirname( sbproj )+ output_dir = os.path.join( project_dir, "test-results" )+ os.makedirs( os.path.join( output_dir, "screenshots" ), exist_ok=True )+ os.makedirs( os.path.join( output_dir, "reports" ), exist_ok=True )++ parsed_strategies = strategies.split( "," ) if strategies else None+ parsed_sizes = sizes.split( "," ) if sizes else None+ parsed_seeds = [int( s ) for s in seeds.split( "," )] if seeds else None++ results = test_mod.run_test_pipeline(+ sbproj_path=sbproj,+ data_path=data_path,+ output_dir=output_dir,+ strategies=parsed_strategies,+ sizes=parsed_sizes,+ seeds=parsed_seeds,+ seed_count=seed_count,+ timeout=timeout,+ )++ succeeded = sum( 1 for r in results if r["success"] )+ failed = sum( 1 for r in results if not r["success"] )++ summary = {+ "total": len( results ),+ "succeeded": succeeded,+ "failed": failed,+ "screenshots": [r["png_path"] for r in results if r.get( "png_path" )],+ "failures": [+ {"combo": r["combo"], "error": r["error"]}+ for r in results if not r["success"]+ ],+ }++ _output( ctx, summary, lambda d: _format_status_block( d, "Test Run Complete" ) )+ except Exception as exc:+ _output_error( ctx, str( exc ) )+++# ---------------------------------------------------------------------------+# repl command+# ---------------------------------------------------------------------------+++_REPL_BANNER = """+ ___ _ _____ __ __ ___ _ ___+ / __|| |/ _ \\ \\/ / / _|| | |_ _|+ \\__ \\| | (_) > < | (__ | |_ | |+ |___/|_|\\___/_/\\_\\ \\___||___|___|++ cli-anything-sbox - interactive REPL+ Type 'help' for commands, 'quit' to exit.+"""++_REPL_HELP = """Available command groups:+ project - Manage s&box projects (new, info, config, add-package, remove-package, validate)+ scene - Manage scenes (new, info, list, add-object, remove-object, add-component,+ remove-component, modify-object, set-property, clone-object, get-object,+ set-navmesh, list-presets, modify-component, query, refs, bulk-modify,+ diff, instantiate-prefab)+ prefab - Manage prefabs (new, info, from-scene, add-component, remove-component, list,+ refs, modify-component, diff)+ codegen - Generate C# code (component, gameresource, editor-menu, razor, class,+ panel-component)+ input - Manage input bindings (list, add, remove, set)+ collision - Manage collision layers (list, add-layer, add-rule, remove-rule, remove-layer)+ material - Manage materials (new, info, list, set)+ sound - Manage sound events (new, info, list, set)+ localization - Manage translation files (new, list, set, get, remove, bulk-set)+ server - Server management (start, info)+ asset - Asset management (list, info, compile, find-refs, find-unused, rename, move)+ session - Session state (status, undo, redo)+ test - Run automated map generation tests (setup, run)+ launch - Open project in s&box editor++ help - Show this help+ quit/exit - Exit the REPL++Example: project info+ scene list Assets/scenes/minimal.scene+ codegen component --name PlayerMovement --methods OnUpdate,OnStart+"""++[email protected]_context+def repl( ctx ):+ """Enter interactive REPL mode."""+ from cli_anything.sbox.utils.repl_skin import ReplSkin+ skin = ReplSkin()++ def echo( msg ):+ if skin and hasattr( skin, "info" ):+ skin.info( msg )+ else:+ click.echo( msg )++ def echo_error( msg ):+ if skin and hasattr( skin, "error" ):+ skin.error( msg )+ else:+ click.echo( f"Error: {msg}", err=True )++ echo( _REPL_BANNER )++ while True:+ try:+ line = click.prompt( "sbox", prompt_suffix="> ", default="", show_default=False )+ except (EOFError, KeyboardInterrupt):+ echo( "\nBye!" )+ break++ line = line.strip()+ if not line:+ continue++ if line in ( "quit", "exit" ):+ echo( "Bye!" )+ break++ if line == "help":+ echo( _REPL_HELP )+ continue++ # Parse the line and dispatch to Click+ try:+ args = shlex.split( line )+ except ValueError as exc:+ echo_error( f"Invalid input: {exc}" )+ continue++ # Carry forward the global context options+ extra_args = []+ if ctx.obj.get( "json" ):+ extra_args.append( "--json" )+ project_path = ctx.obj.get( "project_path" )+ if project_path:+ extra_args.extend( ["--project", project_path] )++ try:+ cli( extra_args + args, standalone_mode=False, parent=ctx.parent )+ except SystemExit:+ # Click may raise SystemExit on --help or errors; absorb it in REPL mode+ pass+ except click.ClickException as exc:+ echo_error( exc.format_message() )+ except click.Abort:+ echo_error( "Command aborted." )+ except Exception as exc:+ echo_error( str( exc ) )+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+++def main():+ """Main entry point for the CLI."""+ cli()+++if __name__ == "__main__":+ main()diff --git a/sbox/agent-harness/cli_anything/sbox/skills/SKILL.md b/sbox/agent-harness/cli_anything/sbox/skills/SKILL.mdnew file mode 100644index 000000000..fb35797d8--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/skills/SKILL.md@@ -0,0 +1,314 @@+---+name: "cli-anything-sbox"+description: >-+ Agent-native CLI for the s&box game engine (Facepunch Studios, Source 2):+ project management, scene/prefab editing, material/sound/localization configs,+ C# code generation, asset graph queries, project validation, and editor launch.+---++# s&box CLI++Agent-native CLI for the s&box game engine (Facepunch Studios, Source 2). 79+ commands across 14 groups. Manipulate `.scene`, `.prefab`, `.vmat`, `.sound`, `Input.config`, `Collision.config` JSON files directly, generate idiomatic C# components, and run a real-time asset graph over the project.++## Installation++```bash+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=sbox/agent-harness+```++## Requirements++- Python 3.10++- s&box installed via Steam - auto-detected, or set `SBOX_PATH` to a custom installation directory.+- Most commands work entirely on the project's JSON files - s&box does not need to be running.++## Global Options++```+--json Machine-readable JSON output (always pass for agent use)+--project PATH Project directory (auto-detects from cwd .sbproj if omitted)+```++## Command Groups++### project - Manage s&box projects++```bash+cli-anything-sbox project new --name MyGame --output-dir ./MyGame+cli-anything-sbox --json project info+cli-anything-sbox project config --max-players 32 --tick-rate 64+cli-anything-sbox --json --project ./MyGame project add-package facepunch.libsdf+cli-anything-sbox --json --project ./MyGame project remove-package facepunch.libsdf+# Lint: broken asset refs, duplicate GUIDs, malformed Input.config+cli-anything-sbox --json --project ./MyGame project validate+cli-anything-sbox --project ./MyGame project validate --no-inputs --no-guids+```++### scene - Manipulate `.scene` files++```bash+cli-anything-sbox scene new --name gameplay -o ./Assets/scenes/gameplay.scene+cli-anything-sbox --json scene info ./scene.scene+cli-anything-sbox --json scene list ./scene.scene+cli-anything-sbox scene add-object ./scene.scene Enemy --position "100,0,0" --components "model,box_collider,rigidbody" --tags "enemy"+cli-anything-sbox scene remove-object ./scene.scene --name Enemy+cli-anything-sbox scene add-component ./scene.scene <object-guid> Sandbox.PointLight+cli-anything-sbox scene remove-component ./scene.scene <object-guid> --component-type Sandbox.Rigidbody+cli-anything-sbox --json scene modify-object ./scene.scene --guid <guid> --name NewName --position "200,0,0"+cli-anything-sbox --json scene clone-object ./scene.scene --name Enemy --new-name EnemyCopy --position "300,0,0"+cli-anything-sbox --json scene get-object ./scene.scene --name Sun+cli-anything-sbox scene set-property ./scene.scene --fixed-update-freq 64 --timescale 0.5+cli-anything-sbox scene set-navmesh ./scene.scene --enabled --agent-height 72 --agent-radius 16+cli-anything-sbox --json scene list-presets+cli-anything-sbox --json scene modify-component ./scene.scene <object-guid> <component-guid> --properties '{"Damage":50}'++# Find objects matching one or more filters (AND-combined)+cli-anything-sbox --json scene query ./scene.scene --has-component rigidbody --has-tag tower+cli-anything-sbox --json scene query ./scene.scene --name-regex "^Tower\d$" --in-bounds "0,-500,-50,1000,500,50"++# Extract every asset reference (.vmdl, .vmat, .vsnd, .vtex, .vpcf, .prefab) from a scene+cli-anything-sbox --json scene refs ./scene.scene++# Apply the same modification to every object that matches a query+cli-anything-sbox --json scene bulk-modify ./scene.scene --has-tag tower --position "0,0,100" --enable++# Structural diff between two scenes (added/removed/modified GameObjects + SceneProperties)+cli-anything-sbox --json scene diff ./old.scene ./new.scene++# Insert a prefab as a GameObject in a scene+cli-anything-sbox --json scene instantiate-prefab ./level.scene ./Assets/prefabs/bullet.prefab --position "10,0,0"+```++### prefab - Manage `.prefab` files++```bash+cli-anything-sbox prefab new --name Bullet -o ./Assets/prefabs/bullet.prefab --components "model,sphere_collider,rigidbody"+cli-anything-sbox --json prefab info ./Assets/prefabs/bullet.prefab+cli-anything-sbox prefab from-scene ./scene.scene <object-guid> -o ./Assets/prefabs/extracted.prefab+cli-anything-sbox --json prefab add-component ./prefab.prefab rigidbody+cli-anything-sbox prefab remove-component ./prefab.prefab --component-type Sandbox.Rigidbody+cli-anything-sbox --json prefab list++# Asset references inside a prefab+cli-anything-sbox --json prefab refs ./prefab.prefab++# Modify component properties on a prefab (by component type or component GUID)+cli-anything-sbox --json prefab modify-component ./prefab.prefab --component-type Sandbox.Rigidbody --properties '{"Gravity":false,"MassOverride":50}'++# Structural diff between two prefabs (root + named children)+cli-anything-sbox --json prefab diff ./old.prefab ./new.prefab+```++### codegen - Generate C# code++```bash+# Plain Component+cli-anything-sbox codegen component --name PlayerController --methods OnUpdate,OnFixedUpdate -o ./Code/PlayerController.cs++# Component with [Property] fields+cli-anything-sbox --json codegen component --name Tower --properties '[{"name":"Damage","type":"float","default":"25f"},{"name":"Range","type":"float","default":"500f"}]'++# Networked component (partial class) with RPC method stubs+cli-anything-sbox codegen component --name NetPlayer --networked --methods OnUpdate,OnFixedUpdate --rpc-methods "Fire:Broadcast,TakeDamage:Host" -o ./Code/NetPlayer.cs++# GameResource+cli-anything-sbox codegen gameresource --name TowerData --display-name "Tower Data" --extension tower -o ./Code/TowerData.cs++# Editor menu (Editor/ assembly)+cli-anything-sbox codegen editor-menu --name MyTools --menu-path "Editor/My Tools/Open" -o ./Editor/MyTools.cs++# Plain Razor UI component (.razor + .razor.scss)+cli-anything-sbox codegen razor --name HudPanel --properties '[{"name":"Score","type":"int","default":"0"}]' -o ./UI/HudPanel.razor++# Static or base-derived class+cli-anything-sbox codegen class --name Math2 --static -o ./Code/Math2.cs++# PanelComponent + sibling ScreenPanel scaffold (handles the s&box quirk where+# PanelComponent input only works when both are on the same GameObject).+# Emits .razor + .razor.scss + a paste-ready GameObject snippet, or appends+# directly to a scene with --scene.+cli-anything-sbox --json codegen panel-component --name HudBar -o ./UI/HudBar.razor+cli-anything-sbox codegen panel-component --name Crosshair -o ./UI/Crosshair.razor --scene ./Assets/scenes/game.scene+```++### input - Manage `Input.config`++```bash+cli-anything-sbox --json input list+cli-anything-sbox input add --name PlaceTower --group Gameplay --keyboard mouse1 --gamepad RightTrigger+cli-anything-sbox input remove --name PlaceTower+cli-anything-sbox input set --name Attack1 --keyboard mouse1+```++### collision - Manage `Collision.config`++```bash+cli-anything-sbox --json collision list+cli-anything-sbox collision add-layer --name projectile --default Collide+cli-anything-sbox collision add-rule --layer-a projectile --layer-b solid --result Collide+cli-anything-sbox collision remove-rule --layer-a projectile --layer-b solid+cli-anything-sbox collision remove-layer --name projectile+```++### material - Manage `.vmat` materials++```bash+cli-anything-sbox --json material new --name floor --shader complex --color-texture "textures/floor.tga" --metalness 0.3 -o ./Assets/materials/floor.vmat+cli-anything-sbox --json material info ./Assets/materials/floor.vmat+cli-anything-sbox --json material list+cli-anything-sbox --json material set ./Assets/materials/floor.vmat --metalness 0.8+```++### sound - Manage `.sound` events++```bash+cli-anything-sbox --json sound new --name gunshot --sounds "sounds/gun1.vsnd,sounds/gun2.vsnd" --volume 0.8 -o ./Assets/sounds/gunshot.sound+cli-anything-sbox --json sound info ./Assets/sounds/gunshot.sound+cli-anything-sbox --json sound list+cli-anything-sbox --json sound set ./Assets/sounds/gunshot.sound --volume 0.5+```++### localization - Manage translations++```bash+cli-anything-sbox localization new --lang en -o ./Localization/en.json+cli-anything-sbox localization set ./Localization/en.json --key "game.title" --value "My Game"+cli-anything-sbox --json localization list ./Localization/en.json+cli-anything-sbox localization get ./Localization/en.json --key "game.title"+cli-anything-sbox localization remove ./Localization/en.json --key "game.title"+cli-anything-sbox localization bulk-set ./Localization/en.json --keys '{"ui.start":"Start","ui.quit":"Quit"}'+```++### server - Dedicated server++```bash+cli-anything-sbox server info+cli-anything-sbox server start --game my_game --map facepunch.flatgrass+```++### asset - Asset management & reverse lookups++```bash+cli-anything-sbox --json asset list --type scene+cli-anything-sbox --json asset info ./Assets/scenes/minimal.scene+cli-anything-sbox asset compile ./Assets/materials/floor.vmat++# Which scenes/prefabs reference this asset?+cli-anything-sbox --json --project ./MyGame asset find-refs models/myteam/widget.vmdl++# Find unreferenced assets (per type, or across all referenceable types)+cli-anything-sbox --json --project ./MyGame asset find-unused+cli-anything-sbox --json --project ./MyGame asset find-unused --type model --type material++# Rename an asset and update every scene/prefab reference (extension preserved if omitted)+cli-anything-sbox --json --project ./MyGame asset rename models/team/widget.vmdl gizmo+cli-anything-sbox --project ./MyGame asset rename models/team/widget.vmdl gizmo --dry-run++# Move an asset across directories and update every reference+cli-anything-sbox --json --project ./MyGame asset move models/team/widget.vmdl models/shared/widget.vmdl+```++### session - State management++```bash+cli-anything-sbox session status+cli-anything-sbox session undo+cli-anything-sbox session redo+```++### test - Automated map/scene generation harness++```bash+cli-anything-sbox test setup+cli-anything-sbox --json test run+```++### launch - Open project in s&box editor++```bash+cli-anything-sbox launch+```++## Component Presets++29 short names usable with `--components` on `scene add-object`, `prefab new`, etc. Each maps to a `Sandbox.*` component type.++| Preset | Component Type |+|--------|---------------|+| `model` | `Sandbox.ModelRenderer` |+| `box_collider` | `Sandbox.BoxCollider` |+| `sphere_collider` | `Sandbox.SphereCollider` |+| `capsule_collider` | `Sandbox.CapsuleCollider` |+| `plane_collider` | `Sandbox.PlaneCollider` |+| `model_collider` | `Sandbox.ModelCollider` |+| `rigidbody` | `Sandbox.Rigidbody` |+| `character_controller` | `Sandbox.CharacterController` |+| `player_controller` | `Sandbox.PlayerController` |+| `camera` | `Sandbox.CameraComponent` |+| `light_directional` | `Sandbox.DirectionalLight` |+| `light_point` | `Sandbox.PointLight` |+| `spot_light` | `Sandbox.SpotLight` |+| `ambient_light` | `Sandbox.AmbientLight` |+| `sprite_renderer` | `Sandbox.SpriteRenderer` |+| `skinned_model_renderer` | `Sandbox.SkinnedModelRenderer` |+| `text_renderer` | `Sandbox.TextRenderer` |+| `line_renderer` | `Sandbox.LineRenderer` |+| `decal_renderer` | `Sandbox.DecalRenderer` |+| `trail_renderer` | `Sandbox.TrailRenderer` |+| `particle_effect` | `Sandbox.ParticleEffect` |+| `sound_point` | `Sandbox.SoundPointComponent` |+| `nav_mesh_agent` | `Sandbox.NavMeshAgent` |+| `screen_panel` | `Sandbox.ScreenPanel` |+| `world_panel` | `Sandbox.WorldPanel` |+| `fixed_joint` | `Sandbox.FixedJoint` |+| `hinge_joint` | `Sandbox.HingeJoint` |+| `spring_joint` | `Sandbox.SpringJoint` |+| `ball_socket_joint` | `Sandbox.BallSocketJoint` |++`scene list-presets` returns the live preset registry as JSON.++## Agent Usage Pattern++Pass `--json` for every agent-driven invocation. Pipe through `jq` to thread GUIDs and paths between commands:++```bash+# Bootstrap a project+sbproj=$(cli-anything-sbox --json project new --name MyGame --output-dir /tmp/MyGame | jq -r '.sbproj')+cd /tmp/MyGame++# Add a tower with a specific component layout, capture its GUID+guid=$(cli-anything-sbox --json scene add-object ./Assets/scenes/main.scene Tower \+ --components "model,box_collider,rigidbody" --tags "tower" \+ | jq -r '.guid')++# Generate the corresponding C# component, networked+cli-anything-sbox --json codegen component --name Tower --networked \+ --rpc-methods "Fire:Host" --properties '[{"name":"Damage","type":"float","default":"25f"}]' \+ -o ./Code/Tower.cs++# Bulk-tweak every tower in the scene+cli-anything-sbox --json scene bulk-modify ./Assets/scenes/main.scene \+ --has-tag tower --enable --position-y-add 50++# Validate before committing+cli-anything-sbox --json project validate+```++## REPL Mode++`cli-anything-sbox` with no arguments enters an interactive REPL with a styled prompt:++```+$ cli-anything-sbox+cli-anything-sbox> project info+cli-anything-sbox> scene list ./Assets/scenes/main.scene+cli-anything-sbox> codegen component --name Foo -o ./Code/Foo.cs+cli-anything-sbox> quit+```++## Environment Variables++| Variable | Description | Default |+|----------|-------------|---------|+| `SBOX_PATH` | s&box installation directory | Auto-detected from Steam library folders |+| `CLI_ANYTHING_SKILL_REPO` | Override the repo `repl_skin` reads SKILL.md from | `HKUDS/CLI-Anything` |diff --git a/sbox/agent-harness/cli_anything/sbox/tests/TEST.md b/sbox/agent-harness/cli_anything/sbox/tests/TEST.mdnew file mode 100644index 000000000..fd6b4444c--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/tests/TEST.md@@ -0,0 +1,144 @@+# Test Plan - cli-anything-sbox++Comprehensive test suite for the s&box CLI harness. All tests are runnable from+the `agent-harness/` directory.++## 1. Test Inventory++| Test File | Coverage | Tests |+|---|---|---|+| `test_core.py` | All 13 core modules: project, scene, prefab, codegen, input_config, collision_config, material, sound, localization, session, export, validate, plus the s&box backend resolver | **155** |+| `test_full_e2e.py` | CLI surface via subprocess invocation, project workflows end-to-end, sbox_backend integration | **50** |+| `test_orchestrator.py` | Map-generation test orchestrator (combo matrix, sentinel polling, RGBA -> PNG conversion, config I/O) | **17** |+| **Total** | | **222** |++## 2. Running the Tests++From the `agent-harness/` directory:++```bash+# Unit tests only (fast, no s&box installation required)+python -m pytest cli_anything/sbox/tests/test_core.py -v++# Orchestrator tests (Pillow required - already a hard dependency)+python -m pytest cli_anything/sbox/tests/test_orchestrator.py -v++# Full e2e suite (TestE2EBackend skips automatically when s&box is not installed)+python -m pytest cli_anything/sbox/tests/test_full_e2e.py -v++# Everything+python -m pytest cli_anything/sbox/tests/ -v+```++### Environment++| Variable | Effect |+|---|---|+| `SBOX_PATH` | Points the harness at a non-Steam s&box installation. Required for `TestE2EBackend` if s&box isn't installed in a standard Steam library. |+| `CLI_ANYTHING_FORCE_INSTALLED` | When set to `1`/`true`/`yes`, `TestCLISubprocess` runs against the installed `cli-anything-sbox` console script instead of `python -m`. |++### Skip behavior++- `TestE2EBackend` (3 tests) skips when s&box can't be located on the host. No failure, no error - clean skip with a reason message.+- `test_converts_rgba_bytes_to_png` skips if Pillow is not importable (it should always be importable since Pillow is a hard dependency).++## 3. Test Coverage by Class++### `test_core.py` (155 tests, 36 classes)++| Class | Tests | Module Under Test |+|---|---|---|+| `TestProject` | 7 | `core.project` - create, load/save, info, configure, find_sbproj |+| `TestProjectPackages` | 4 | `core.project` - add/remove package references |+| `TestProjectValidate` | 4 | `core.validate` - broken refs, duplicate GUIDs, malformed inputs |+| `TestScene` | 12 | `core.scene` - create, list, add/remove object & component, find, GUID uniqueness |+| `TestSceneQuery` | 9 | `core.scene.query_objects` - by component / tag / name / regex / bounds / enabled / combined |+| `TestSceneRefs` | 3 | `core.scene.extract_asset_refs` - default scene, dedup/sort, empty scene |+| `TestSceneBulkModify` | 4 | `core.scene.bulk_modify_objects` - position, multi-field, no-match, requires-update |+| `TestSceneCloneAndGet` | 6 | `core.scene.clone_object` + `get_object` |+| `TestSceneModify` | 4 | `core.scene.modify_object` - name, position, scale, tags |+| `TestSceneModifyComponent` | 2 | `core.scene.modify_component_properties` |+| `TestSceneInstantiatePrefab` | 5 | `core.scene.instantiate_prefab` - default name, override name, prefab source ref, parent, invalid parent |+| `TestSceneDiff` | 5 | `core.scene.diff_scenes` - identical, added/removed, position, components, scene-properties |+| `TestPrefab` | 4 | `core.prefab` - create, with components, info, from-scene |+| `TestPrefabComponents` | 2 | `core.prefab` - add/remove component on prefab root |+| `TestPrefabRefs` | 1 | `core.prefab.extract_asset_refs` |+| `TestPrefabModifyComponent` | 5 | `core.prefab.modify_component_properties` - by type, by guid, not-found, requires-id, requires-properties |+| `TestPrefabDiff` | 2 | `core.prefab.diff_prefabs` - identical, root changes |+| `TestCodegen` | 10 | `core.codegen` - component basic, with properties, networked, interfaces, lifecycle methods, gameresource, editor menu, code style (tabs / Allman / CRLF) |+| `TestCodegenRazor` | 5 | `core.codegen.generate_razor` |+| `TestCodegenClass` | 2 | `core.codegen.generate_class` - static class, base class |+| `TestCodegenPanelComponent` | 5 | `core.codegen.generate_panel_component` - basic, includes ScreenPanel, namespace, properties, unique GUIDs |+| `TestInputConfig` | 6 | `core.input_config` - get default, add, duplicate, remove, set, list |+| `TestCollisionConfig` | 5 | `core.collision_config` - get default, add layer, remove built-in, add rule, remove rule |+| `TestCollisionRemoveLayer` | 1 | `core.collision_config.remove_layer` |+| `TestMaterial` | 5 | `core.material` - new, load/save, info, list, presets |+| `TestMaterialUpdate` | 2 | `core.material.update_material` - shader, color texture |+| `TestSound` | 4 | `core.sound` - new, info, list, presets |+| `TestSoundUpdate` | 2 | `core.sound.update_sound_event` |+| `TestLocalization` | 5 | `core.localization` - new, set, get, list, remove |+| `TestLocalizationBulkSet` | 1 | `core.localization.bulk_set` |+| `TestSession` | 5 | `core.session` - create, set project, undo/redo, save/load, clear |+| `TestExport` | 3 | `core.export` - list assets, filtered list, find project dir |+| `TestAssetRefGraph` | 5 | `core.export.find_asset_refs` + `find_unused_assets` |+| `TestAssetRenameMove` | 7 | `core.export.rename_asset` + `move_asset` - both with dry-run, target-exists, source-missing, cross-directory |+| `TestComponentPresets` | 2 | `core.scene.COMPONENT_PRESETS` - count + standard names |+| `TestJointPresets` | 1 | `core.scene.COMPONENT_PRESETS` - joint preset coverage |++### `test_full_e2e.py` (50 tests, 3 classes)++| Class | Tests | Coverage |+|---|---|---|+| `TestCLISubprocess` | 40 | Spawns `cli-anything-sbox` as a subprocess (or `python -m cli_anything.sbox.sbox_cli` when not installed) and asserts `--json` output for every documented command group |+| `TestE2EProjectWorkflow` | 7 | Full project workflows: create -> add objects -> generate code -> validate. Uses the in-process Click runner |+| `TestE2EBackend` | 3 | Real s&box backend integration (`find_sbox_installation`, `get_sbox_version`, `find_server_executable`). Skips cleanly when s&box not installed |++### `test_orchestrator.py` (17 tests, 5 classes)++| Class | Tests | Coverage |+|---|---|---|+| `TestComboMatrix` | 7 | Strategy x size x seed combo matrix used by the map-generation test pipeline |+| `TestSentinelPolling` | 3 | Filesystem-sentinel polling (used to detect when in-engine tests have completed) |+| `TestConfigIO` | 3 | `test_config.json` round-trip (read, validate, write) |+| `TestRgbaConversion` | 2 | RGBA byte-array -> PNG via Pillow |+| `TestDataPathResolution` | 2 | `FileSystem.Data` path resolution across editor and standalone |++## 4. Coverage by Source Module++| Module | Unit | E2E | Subprocess |+|---|---|---|---|+| `core/project.py` | 7 + 4 packages | 2 (creation, tower defense) | 1 (project new) |+| `core/scene.py` | 12 + 9 query + 3 refs + 4 bulk + 6 clone/get + 4 modify + 2 modify-comp + 5 instantiate + 5 diff = 50 | 3 (manipulation, tower defense, workflow) | 6 (query, refs, bulk-modify x2, diff x2, instantiate) |+| `core/prefab.py` | 4 + 2 components + 1 refs + 5 modify-comp + 2 diff = 14 | 1 (from_scene in manipulation) | 3 (refs, modify-component, diff) |+| `core/codegen.py` | 10 + 5 razor + 2 class + 5 panel-component = 22 | 1 (codegen workflow) | 3 (panel-component plain + scene append) |+| `core/input_config.py` | 6 | 2 (config workflow, tower defense) | 1 (input list) |+| `core/collision_config.py` | 5 + 1 remove-layer = 6 | 2 (config workflow, tower defense) | 1 (collision list) |+| `core/material.py` | 5 + 2 update = 7 | - | - |+| `core/sound.py` | 4 + 2 update = 6 | - | - |+| `core/localization.py` | 5 + 1 bulk-set = 6 | - | - |+| `core/session.py` | 5 | - | - |+| `core/export.py` | 3 + 5 ref-graph + 7 rename/move = 15 | - | 5 (find-refs, find-unused, rename, rename-dry-run, move) |+| `core/validate.py` | 4 | - | 2 (validate clean, validate broken) |+| `core/test_orchestrator.py` | 17 (full file) | - | - |+| `utils/sbox_backend.py` | - | 3 (installation, version, executable - skipped if no s&box) | - |+| `sbox_cli.py` (CLI) | - | - | 40 (full TestCLISubprocess) |++## 5. E2E Prerequisites++`TestCLISubprocess` (40 tests) and `TestE2EProjectWorkflow` (7 tests) run without s&box installed - they exercise the CLI against in-memory or temp-directory project state.++`TestE2EBackend` (3 tests) requires s&box to be discoverable:+- Standard Steam install: nothing to do.+- Non-standard location: `export SBOX_PATH=/path/to/sbox` (or set the env var per shell).+- s&box not installed: tests skip with a reason message.++## 6. Coverage Gaps++- `server start` and `launch` commands are tested only via help-text smoke; running an actual s&box server / editor process is out of scope (would require live network sockets and a running game).+- `session undo`/`redo` is tested at the unit level; no E2E workflow exercises the undo journal in a realistic edit-undo-edit sequence.+- `asset compile` is help-tested only; invoking the s&box `resourcecompiler.exe` requires a full s&box install and is left to the upstream maintainers' CI.++## 7. Known Test-Environment Quirks++- On Windows, `subprocess.Popen` with inheritable handles can hit `OSError: [WinError 6] The handle is invalid` after ~25-30 sequential subprocess calls in some sandboxed environments (tested in PowerShell, MSYS2 bash). Mitigation: run `TestCLISubprocess` in isolation (`pytest cli_anything/sbox/tests/test_full_e2e.py -k TestCLISubprocess`) or use `--forked` if `pytest-forked` is installed. Tests pass cleanly in non-sandboxed terminals.+- All file I/O is UTF-8 explicit (`open(..., encoding="utf-8")`). Earlier versions defaulted to the platform codec on Windows; that was fixed before upstream submission.diff --git a/sbox/agent-harness/cli_anything/sbox/tests/__init__.py b/sbox/agent-harness/cli_anything/sbox/tests/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/sbox/agent-harness/cli_anything/sbox/tests/test_core.py b/sbox/agent-harness/cli_anything/sbox/tests/test_core.pynew file mode 100644index 000000000..096366c4c--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/tests/test_core.py@@ -0,0 +1,2382 @@+"""Unit tests for cli_anything.sbox.core modules.++Covers: project, scene, prefab, codegen, input_config, collision_config, session, export.+All tests are self-contained and use pytest's tmp_path fixture for file operations.+"""++import copy+import json+import os+import uuid++import pytest++from cli_anything.sbox.core.codegen import (+ generate_class,+ generate_component,+ generate_editor_menu,+ generate_gameresource,+ generate_panel_component,+ generate_razor,+)+from cli_anything.sbox.core.collision_config import (+ add_layer,+ add_rule,+ get_default_collision_config,+ list_layers,+ load_collision_config,+ remove_layer,+ remove_rule,+ save_collision_config,+)+from cli_anything.sbox.core.export import (+ ASSET_EXTENSIONS,+ find_asset_refs,+ find_project_dir,+ find_unused_assets,+ get_asset_info,+ list_assets,+ move_asset,+ rename_asset,+)+from cli_anything.sbox.core.input_config import (+ add_action,+ get_default_input_config,+ list_actions,+ load_input_config,+ remove_action,+ save_input_config,+ set_action,+)+from cli_anything.sbox.core.localization import (+ bulk_set,+ create_translation_file,+ get_key,+ list_keys,+ load_translations,+ remove_key,+ set_key,+)+from cli_anything.sbox.core.material import (+ create_material,+ list_materials,+ parse_material,+ update_material,+)+from cli_anything.sbox.core.prefab import (+ create_prefab,+ diff_prefabs,+ from_scene_object,+ get_prefab_info,+ load_prefab,+ save_prefab,+)+from cli_anything.sbox.core.prefab import (+ extract_asset_refs as prefab_extract_asset_refs,+)+from cli_anything.sbox.core.prefab import (+ modify_component as prefab_modify_component,+)+from cli_anything.sbox.core.project import (+ add_package,+ configure_project,+ create_project,+ find_sbproj,+ get_project_info,+ load_project,+ remove_package,+ save_project,+)+from cli_anything.sbox.core.scene import (+ COMPONENT_PRESETS,+ add_component,+ add_object,+ bulk_modify_objects,+ clone_object,+ create_scene,+ diff_scenes,+ extract_asset_refs,+ find_object,+ get_object,+ get_scene_info,+ instantiate_prefab,+ list_objects,+ load_scene,+ modify_component,+ modify_object,+ query_objects,+ remove_component,+ remove_object,+ save_scene,+ set_navmesh_properties,+ set_scene_properties,+)+from cli_anything.sbox.core.session import Session+from cli_anything.sbox.core.sound import (+ create_sound_event,+ parse_sound_event,+ update_sound_event,+)+from cli_anything.sbox.core.validate import validate_project+++# ============================================================================+# TestProject+# ============================================================================+++class TestProject:+ """Tests for cli_anything.sbox.core.project."""++ def test_create_project(self, tmp_path):+ """Create a project and verify .sbproj, scene, configs are created."""+ info = create_project("MyGame", output_dir=str(tmp_path / "MyGame"))+ root = tmp_path / "MyGame"++ # Check returned info+ assert info["name"] == "MyGame"+ assert info["type"] == "game"+ assert info["max_players"] == 64+ assert info["tick_rate"] == 50++ # Check directory structure+ assert (root / "MyGame.sbproj").is_file()+ assert (root / ".editorconfig").is_file()+ assert (root / "Code" / "Assembly.cs").is_file()+ assert (root / "Editor" / "Assembly.cs").is_file()+ assert (root / "Assets" / "scenes" / "minimal.scene").is_file()+ assert (root / "ProjectSettings" / "Input.config").is_file()+ assert (root / "ProjectSettings" / "Collision.config").is_file()+ assert (root / "Libraries").is_dir()+ assert (root / "Localization").is_dir()++ # Verify .sbproj is valid JSON with StartupScene in Metadata+ with open(root / "MyGame.sbproj", "r", encoding="utf-8") as f:+ data = json.load(f)+ assert data["Title"] == "MyGame"+ assert data["Type"] == "game"+ assert "StartupScene" not in data, "StartupScene should be in Metadata, not root"+ assert data["Metadata"]["StartupScene"] == "scenes/minimal.scene"++ # Verify Input.config has all 31 actions including Slot0-Slot9+ with open(root / "ProjectSettings" / "Input.config", "r", encoding="utf-8") as f:+ input_data = json.load(f)+ action_names = [a["Name"] for a in input_data["Actions"]]+ assert len( action_names ) == 31+ for slot in ["Slot0", "Slot1", "Slot2", "Slot3", "Slot4", "Slot5",+ "Slot6", "Slot7", "Slot8", "Slot9"]:+ assert slot in action_names, f"Missing {slot} in Input.config"++ def test_create_project_custom_settings(self, tmp_path):+ """Create project with custom max_players, tick_rate, etc."""+ info = create_project(+ "CustomGame",+ output_dir=str(tmp_path / "CustomGame"),+ max_players=8,+ tick_rate=128,+ network_type="ServerOnly",+ org="myorg",+ )++ assert info["max_players"] == 8+ assert info["tick_rate"] == 128+ assert info["network_type"] == "ServerOnly"+ assert info["org"] == "myorg"++ # Verify persisted in JSON+ data = load_project(info["sbproj"])+ assert data["Metadata"]["MaxPlayers"] == 8+ assert data["Metadata"]["TickRate"] == 128+ assert data["Metadata"]["GameNetworkType"] == "ServerOnly"+ assert data["Org"] == "myorg"++ def test_load_save_project(self, tmp_path):+ """Load and re-save a project, verify round-trip."""+ info = create_project("RoundTrip", output_dir=str(tmp_path / "RoundTrip"))+ sbproj = info["sbproj"]++ data = load_project(sbproj)+ data["Title"] = "Modified"+ data["Metadata"]["MaxPlayers"] = 32+ save_project(sbproj, data)++ reloaded = load_project(sbproj)+ assert reloaded["Title"] == "Modified"+ assert reloaded["Metadata"]["MaxPlayers"] == 32++ def test_get_project_info(self, tmp_path):+ """Verify project info dict has all expected fields."""+ info = create_project("InfoTest", output_dir=str(tmp_path / "InfoTest"))+ proj_info = get_project_info(info["sbproj"])++ expected_keys = {+ "title", "type", "org", "ident", "startup_scene",+ "max_players", "min_players", "tick_rate", "network_type",+ "map_select", "map_list", "package_references", "path",+ }+ assert expected_keys.issubset(set(proj_info.keys()))+ assert proj_info["title"] == "InfoTest"+ assert proj_info["ident"] == "infotest"+ assert proj_info["max_players"] == 64+ assert proj_info["tick_rate"] == 50++ def test_configure_project(self, tmp_path):+ """Modify project settings and verify they persist."""+ info = create_project("ConfigTest", output_dir=str(tmp_path / "ConfigTest"))+ sbproj = info["sbproj"]++ updated = configure_project(+ sbproj,+ title="Renamed",+ max_players=16,+ tick_rate=30,+ org="neworg",+ )++ assert updated["title"] == "Renamed"+ assert updated["max_players"] == 16+ assert updated["tick_rate"] == 30+ assert updated["org"] == "neworg"++ # Confirm persistence by reloading raw JSON+ raw = load_project(sbproj)+ assert raw["Title"] == "Renamed"+ assert raw["Org"] == "neworg"+ assert raw["Metadata"]["MaxPlayers"] == 16+ assert raw["Metadata"]["TickRate"] == 30++ def test_find_sbproj(self, tmp_path):+ """Test finding .sbproj file in a directory."""+ info = create_project("FindMe", output_dir=str(tmp_path / "FindMe"))+ found = find_sbproj(str(tmp_path / "FindMe"))+ assert found is not None+ assert found.endswith("FindMe.sbproj")++ def test_find_sbproj_not_found(self, tmp_path):+ """Test when no .sbproj exists."""+ empty_dir = tmp_path / "empty"+ empty_dir.mkdir()+ result = find_sbproj(str(empty_dir))+ assert result is None+++# ============================================================================+# TestScene+# ============================================================================+++class TestScene:+ """Tests for cli_anything.sbox.core.scene."""++ def test_create_scene_with_defaults(self, tmp_path):+ """Create scene with default objects (Sun, Skybox, Plane, Camera)."""+ scene_path = str(tmp_path / "test.scene")+ data = create_scene("test", output_path=scene_path)++ objects = data["GameObjects"]+ names = [obj["Name"] for obj in objects]+ assert "Sun" in names+ assert "2D Skybox" in names+ assert "Plane" in names+ assert "Camera" in names++ props = data["SceneProperties"]+ assert props["FixedUpdateFrequency"] == 50+ assert props["NetworkFrequency"] == 60++ def test_create_scene_empty(self, tmp_path):+ """Create scene without defaults."""+ data = create_scene("empty", include_defaults=False)+ assert data["GameObjects"] == []+ assert data["Title"] == "empty"++ def test_list_objects(self, tmp_path):+ """List objects in a scene."""+ scene_path = str(tmp_path / "list.scene")+ create_scene("list", output_path=scene_path)++ objects = list_objects(scene_path)+ assert len(objects) >= 4 # Sun, Skybox, Plane, Camera+ for obj in objects:+ assert "guid" in obj+ assert "name" in obj+ assert "position" in obj+ assert "component_types" in obj++ def test_add_object(self, tmp_path):+ """Add a named object and verify it appears in list."""+ scene_path = str(tmp_path / "add.scene")+ create_scene("add", output_path=scene_path)++ guid = add_object(scene_path, "Turret", position="100,0,50")+ assert guid is not None++ objects = list_objects(scene_path)+ turret = [o for o in objects if o["name"] == "Turret"]+ assert len(turret) == 1+ assert turret[0]["guid"] == guid+ assert turret[0]["position"] == "100,0,50"++ def test_add_object_with_components(self, tmp_path):+ """Add object with component presets."""+ scene_path = str(tmp_path / "comps.scene")+ create_scene("comps", output_path=scene_path)++ guid = add_object(+ scene_path,+ "PhysicsBox",+ components=["model", "box_collider", "rigidbody"],+ )++ objects = list_objects(scene_path)+ box = [o for o in objects if o["name"] == "PhysicsBox"][0]+ types = box["component_types"]+ assert "Sandbox.ModelRenderer" in types+ assert "Sandbox.BoxCollider" in types+ assert "Sandbox.Rigidbody" in types++ def test_remove_object_by_name(self, tmp_path):+ """Remove an object and verify it's gone."""+ scene_path = str(tmp_path / "rem_name.scene")+ create_scene("rem_name", output_path=scene_path)+ add_object(scene_path, "Removable")++ removed = remove_object(scene_path, name="Removable")+ assert removed is True++ objects = list_objects(scene_path)+ names = [o["name"] for o in objects]+ assert "Removable" not in names++ def test_remove_object_by_guid(self, tmp_path):+ """Remove by GUID."""+ scene_path = str(tmp_path / "rem_guid.scene")+ create_scene("rem_guid", output_path=scene_path)+ guid = add_object(scene_path, "ByGuid")++ removed = remove_object(scene_path, guid=guid)+ assert removed is True++ objects = list_objects(scene_path)+ guids = [o["guid"] for o in objects]+ assert guid not in guids++ def test_find_object(self, tmp_path):+ """Find object by name and by GUID."""+ scene_path = str(tmp_path / "find.scene")+ create_scene("find", output_path=scene_path)+ guid = add_object(scene_path, "Findable")++ data = load_scene(scene_path)++ # Find by name+ obj_by_name = find_object(data, name="Findable")+ assert obj_by_name is not None+ assert obj_by_name["Name"] == "Findable"++ # Find by guid+ obj_by_guid = find_object(data, guid=guid)+ assert obj_by_guid is not None+ assert obj_by_guid["__guid"] == guid++ # Not found+ assert find_object(data, name="NonExistent") is None++ def test_add_component(self, tmp_path):+ """Add a component to an existing object."""+ scene_path = str(tmp_path / "add_comp.scene")+ create_scene("add_comp", output_path=scene_path)+ obj_guid = add_object(scene_path, "Target")++ comp_guid = add_component(scene_path, obj_guid, "rigidbody")+ assert comp_guid is not None++ data = load_scene(scene_path)+ obj = find_object(data, guid=obj_guid)+ comp_types = [c["__type"] for c in obj["Components"]]+ assert "Sandbox.Rigidbody" in comp_types++ def test_remove_component(self, tmp_path):+ """Remove a component from an object."""+ scene_path = str(tmp_path / "rem_comp.scene")+ create_scene("rem_comp", output_path=scene_path)+ obj_guid = add_object(+ scene_path, "WithRB", components=["rigidbody", "model"]+ )++ removed = remove_component(+ scene_path, obj_guid, component_type="Sandbox.Rigidbody"+ )+ assert removed is True++ data = load_scene(scene_path)+ obj = find_object(data, guid=obj_guid)+ comp_types = [c["__type"] for c in obj["Components"]]+ assert "Sandbox.Rigidbody" not in comp_types+ # model should still be there+ assert "Sandbox.ModelRenderer" in comp_types++ def test_scene_guid_uniqueness(self, tmp_path):+ """All GUIDs in a scene should be unique."""+ scene_path = str(tmp_path / "guids.scene")+ create_scene("guids", output_path=scene_path)+ add_object(scene_path, "Extra1", components=["model", "rigidbody"])+ add_object(scene_path, "Extra2", components=["camera"])++ data = load_scene(scene_path)+ guids = []++ def collect_guids(objects):+ for obj in objects:+ if "__guid" in obj:+ guids.append(obj["__guid"])+ for comp in obj.get("Components", []):+ if "__guid" in comp:+ guids.append(comp["__guid"])+ collect_guids(obj.get("Children", []))++ collect_guids(data.get("GameObjects", []))++ assert len(guids) == len(set(guids)), (+ f"Duplicate GUIDs found: {len(guids)} total, {len(set(guids))} unique"+ )++ def test_scene_json_valid(self, tmp_path):+ """Generated scene is valid JSON with expected structure."""+ scene_path = str(tmp_path / "valid.scene")+ create_scene("valid", output_path=scene_path)++ with open(scene_path, "r", encoding="utf-8") as f:+ data = json.load(f)++ assert "GameObjects" in data+ assert "SceneProperties" in data+ assert "Title" in data+ assert "__version" in data+ assert isinstance(data["GameObjects"], list)+ assert isinstance(data["SceneProperties"], dict)+++# ============================================================================+# TestPrefab+# ============================================================================+++class TestPrefab:+ """Tests for cli_anything.sbox.core.prefab."""++ def test_create_prefab(self, tmp_path):+ """Create a prefab and verify structure."""+ prefab_path = str(tmp_path / "test.prefab")+ data = create_prefab("TestPrefab", output_path=prefab_path)++ assert "RootObject" in data+ root = data["RootObject"]+ assert root["Name"] == "TestPrefab"+ assert "__guid" in root+ assert root["Enabled"] is True+ assert "Components" in root+ assert "Children" in root+ assert data["ResourceVersion"] == 1+ assert data["__version"] == 1++ # Verify file was written+ with open(prefab_path, "r", encoding="utf-8") as f:+ on_disk = json.load(f)+ assert on_disk["RootObject"]["Name"] == "TestPrefab"++ def test_create_prefab_with_components(self, tmp_path):+ """Create prefab with component presets."""+ prefab_path = str(tmp_path / "comps.prefab")+ data = create_prefab(+ "PhysicsPrefab",+ output_path=prefab_path,+ components=["model", "box_collider", "rigidbody"],+ )++ root = data["RootObject"]+ comp_types = [c["__type"] for c in root["Components"]]+ assert "Sandbox.ModelRenderer" in comp_types+ assert "Sandbox.BoxCollider" in comp_types+ assert "Sandbox.Rigidbody" in comp_types++ # Each component should have a unique __guid+ comp_guids = [c["__guid"] for c in root["Components"]]+ assert len(comp_guids) == len(set(comp_guids))++ def test_get_prefab_info(self, tmp_path):+ """Verify prefab info."""+ prefab_path = str(tmp_path / "info.prefab")+ create_prefab(+ "InfoPrefab",+ output_path=prefab_path,+ components=["model", "rigidbody"],+ )++ info = get_prefab_info(prefab_path)+ assert info["name"] == "InfoPrefab"+ assert "guid" in info+ assert info["path"] == prefab_path+ assert info["component_count"] == 2+ assert "Sandbox.ModelRenderer" in info["component_types"]+ assert "Sandbox.Rigidbody" in info["component_types"]+ assert info["children_count"] == 0+ assert info["network_mode"] == 0++ def test_from_scene_object(self, tmp_path):+ """Extract a scene object into a prefab."""+ scene_path = str(tmp_path / "source.scene")+ create_scene("source", output_path=scene_path)+ obj_guid = add_object(+ scene_path,+ "ExtractMe",+ position="10,20,30",+ components=["model", "rigidbody"],+ )++ prefab_path = str(tmp_path / "extracted.prefab")+ data = from_scene_object(scene_path, obj_guid, prefab_path)++ assert "RootObject" in data+ root = data["RootObject"]+ assert root["Name"] == "ExtractMe"+ assert root["Position"] == "10,20,30"++ comp_types = [c["__type"] for c in root.get("Components", [])]+ assert "Sandbox.ModelRenderer" in comp_types+ assert "Sandbox.Rigidbody" in comp_types++ # Verify the prefab file exists on disk+ assert os.path.isfile(prefab_path)+++# ============================================================================+# TestCodegen+# ============================================================================+++class TestCodegen:+ """Tests for cli_anything.sbox.core.codegen."""++ def test_generate_component_basic(self):+ """Generate a basic sealed component."""+ result = generate_component("PlayerHealth")++ assert result["filename"] == "PlayerHealth.cs"+ assert result["class_name"] == "PlayerHealth"+ content = result["content"]+ assert "using Sandbox;" in content+ assert "public sealed class PlayerHealth : Component" in content++ def test_generate_component_with_properties(self):+ """Generate component with typed properties."""+ props = [+ {"name": "Health", "type": "float", "default": "100f"},+ {"name": "MaxHealth", "type": "float", "default": "100f"},+ {"name": "DisplayName", "type": "string"},+ ]+ result = generate_component("PlayerStats", properties=props)+ content = result["content"]++ assert "[Property]" in content+ assert "public float Health { get; set; } = 100f;" in content+ assert "public float MaxHealth { get; set; } = 100f;" in content+ assert "public string DisplayName { get; set; }" in content++ def test_generate_component_networked(self):+ """Generate partial class with [Sync] and IsProxy guard."""+ result = generate_component(+ "NetPlayer",+ is_networked=True,+ properties=[{"name": "Health", "type": "float", "default": "100f"}],+ lifecycle_methods=["OnFixedUpdate"],+ )+ content = result["content"]++ assert "public partial class NetPlayer : Component" in content+ assert "sealed" not in content+ assert "[Sync]" in content+ assert "if ( IsProxy ) return;" in content++ def test_generate_component_with_interfaces(self):+ """Generate component implementing interfaces."""+ result = generate_component(+ "DamageReceiver",+ interfaces=["Component.ITriggerListener", "Component.IDamageable"],+ )+ content = result["content"]++ assert (+ "public sealed class DamageReceiver : Component, "+ "Component.ITriggerListener, Component.IDamageable"+ ) in content++ def test_generate_component_lifecycle_methods(self):+ """Generate with OnUpdate, OnFixedUpdate, OnStart."""+ result = generate_component(+ "LifecycleTest",+ lifecycle_methods=["OnStart", "OnUpdate", "OnFixedUpdate"],+ )+ content = result["content"]++ assert "protected override void OnStart()" in content+ assert "protected override void OnUpdate()" in content+ assert "protected override void OnFixedUpdate()" in content++ def test_generate_gameresource(self):+ """Generate a GameResource class."""+ result = generate_gameresource(+ "TowerData",+ display_name="Tower Data",+ extension="tower",+ description="Data for a tower defense tower",+ properties=[+ {"name": "Cost", "type": "int", "default": "100"},+ {"name": "Range", "type": "float", "default": "500f"},+ ],+ )++ assert result["filename"] == "TowerData.cs"+ assert result["class_name"] == "TowerData"+ content = result["content"]++ assert "using Sandbox;" in content+ assert '[GameResource( "Tower Data", "tower", "Data for a tower defense tower" )]' in content+ assert "public class TowerData : GameResource" in content+ assert "public int Cost { get; set; } = 100;" in content+ assert "public float Range { get; set; } = 500f;" in content++ def test_generate_editor_menu(self):+ """Generate an editor menu class."""+ result = generate_editor_menu(+ "MyTool",+ menu_path="Tools/My Tool",+ method_name="Open",+ dialog_title="My Tool",+ dialog_message="Hello from My Tool",+ )++ assert result["filename"] == "MyTool.cs"+ assert result["class_name"] == "MyTool"+ content = result["content"]++ assert "using Editor;" in content+ assert "using Sandbox;" in content+ assert "public static class MyTool" in content+ assert '[Menu( "Editor", "Tools/My Tool" )]' in content+ assert "public static void Open()" in content+ assert 'EditorUtility.DisplayDialog( "My Tool", "Hello from My Tool" );' in content++ def test_code_style_tabs(self):+ """Verify generated code uses tabs, not spaces."""+ result = generate_component(+ "TabTest",+ properties=[{"name": "Value", "type": "int"}],+ lifecycle_methods=["OnUpdate"],+ )+ content = result["content"]++ # Split into lines, check that indented lines use tabs+ for line in content.split("\r\n"):+ stripped = line.lstrip("\t")+ if len(stripped) < len(line):+ # This line was indented - verify it used tabs not spaces+ indent = line[: len(line) - len(stripped)]+ assert "\t" in indent, f"Line uses spaces instead of tabs: {repr(line)}"+ # Indentation part should be only tabs+ assert indent == indent.replace(" ", ""), (+ f"Mixed tabs/spaces in indent: {repr(line)}"+ )++ def test_code_style_allman_braces(self):+ """Verify Allman-style braces."""+ result = generate_component(+ "BraceTest",+ lifecycle_methods=["OnUpdate"],+ )+ content = result["content"]+ lines = content.split("\r\n")++ # Find lines with opening braces - they should be on their own line+ # (possibly with leading whitespace only)+ for i, line in enumerate(lines):+ stripped = line.strip()+ if stripped == "{":+ # This is correct Allman style - brace on its own line+ continue+ if stripped.endswith("{") and stripped != "{":+ # Brace at end of a non-empty line would be K&R style+ # But we need to allow attribute lines like [Menu( "Editor", "..." )]+ # that aren't brace-bearing. The check is: if the line has a brace+ # AND is not just the brace, that would violate Allman style.+ # However, there is no K&R brace in our generated code.+ pytest.fail(+ f"K&R-style brace found on line {i + 1}: {repr(line)}"+ )++ def test_code_style_crlf(self):+ """Verify CRLF line endings."""+ result = generate_component("CrlfTest")+ content = result["content"]++ # Content should have \r\n+ assert "\r\n" in content, "Expected CRLF line endings"++ # Should not have bare \n (without preceding \r)+ # Replace all \r\n first, then check for remaining \n+ remaining = content.replace("\r\n", "")+ assert "\n" not in remaining, "Found bare LF without CR"+++# ============================================================================+# TestInputConfig+# ============================================================================+++class TestInputConfig:+ """Tests for cli_anything.sbox.core.input_config."""++ def _write_default_config(self, tmp_path):+ """Helper: write default input config to a temp file and return path."""+ config_path = str(tmp_path / "Input.config")+ data = get_default_input_config()+ save_input_config(config_path, data)+ return config_path++ def test_get_default_config(self):+ """Default config has all standard actions."""+ config = get_default_input_config()+ actions = config["Actions"]+ names = [a["Name"] for a in actions]++ assert "Forward" in names+ assert "Backward" in names+ assert "Jump" in names+ assert "Attack1" in names+ assert "Reload" in names+ assert "Use" in names++ # Should have __guid and __type metadata+ assert "__guid" in config+ assert config["__type"] == "InputSettings"++ def test_add_action(self, tmp_path):+ """Add a new action and verify it appears."""+ config_path = self._write_default_config(tmp_path)++ new_action = add_action(+ config_path,+ name="Sprint",+ group="Movement",+ keyboard_code="shift",+ )+ assert new_action["Name"] == "Sprint"+ assert new_action["GroupName"] == "Movement"+ assert new_action["KeyboardCode"] == "shift"++ # Verify persistence+ actions = list_actions(config_path)+ names = [a["Name"] for a in actions]+ assert "Sprint" in names++ def test_add_duplicate_action(self, tmp_path):+ """Adding duplicate action should raise ValueError."""+ config_path = self._write_default_config(tmp_path)++ with pytest.raises(ValueError, match="already exists"):+ add_action(config_path, name="Forward", group="Movement")++ def test_remove_action(self, tmp_path):+ """Remove an action and verify it's gone."""+ config_path = self._write_default_config(tmp_path)++ removed = remove_action(config_path, "Voice")+ assert removed is True++ actions = list_actions(config_path)+ names = [a["Name"] for a in actions]+ assert "Voice" not in names++ def test_set_action(self, tmp_path):+ """Modify action bindings."""+ config_path = self._write_default_config(tmp_path)++ updated = set_action(+ config_path,+ name="Jump",+ keyboard_code="F",+ group="Custom",+ )+ assert updated["KeyboardCode"] == "F"+ assert updated["GroupName"] == "Custom"++ # Verify persistence+ actions = list_actions(config_path)+ jump = [a for a in actions if a["Name"] == "Jump"][0]+ assert jump["KeyboardCode"] == "F"+ assert jump["GroupName"] == "Custom"++ def test_list_actions(self, tmp_path):+ """List all actions returns proper format."""+ config_path = self._write_default_config(tmp_path)++ actions = list_actions(config_path)+ assert isinstance(actions, list)+ assert len(actions) > 0++ for action in actions:+ assert "Name" in action+ assert isinstance(action["Name"], str)+++# ============================================================================+# TestCollisionConfig+# ============================================================================+++class TestCollisionConfig:+ """Tests for cli_anything.sbox.core.collision_config."""++ def _write_default_config(self, tmp_path):+ """Helper: write default collision config to a temp file and return path."""+ config_path = str(tmp_path / "Collision.config")+ data = get_default_collision_config()+ save_collision_config(config_path, data)+ return config_path++ def test_get_default_config(self):+ """Default config has standard layers."""+ config = get_default_collision_config()+ defaults = config["Defaults"]++ assert "solid" in defaults+ assert "world" in defaults+ assert "trigger" in defaults+ assert "ladder" in defaults+ assert "water" in defaults++ # Should have pairs+ pairs = config["Pairs"]+ assert isinstance(pairs, list)+ assert len(pairs) > 0++ def test_add_layer(self, tmp_path):+ """Add a custom collision layer."""+ config_path = self._write_default_config(tmp_path)++ updated_defaults = add_layer(config_path, "projectile", default="Collide")+ assert "projectile" in updated_defaults+ assert updated_defaults["projectile"] == "Collide"++ # Verify persistence+ data = load_collision_config(config_path)+ assert "projectile" in data["Defaults"]++ def test_remove_builtin_layer(self, tmp_path):+ """Removing built-in layer should raise ValueError."""+ config_path = self._write_default_config(tmp_path)++ with pytest.raises(ValueError, match="Cannot remove built-in layer"):+ remove_layer(config_path, "solid")++ with pytest.raises(ValueError, match="Cannot remove built-in layer"):+ remove_layer(config_path, "trigger")++ def test_add_rule(self, tmp_path):+ """Add a collision pair rule."""+ config_path = self._write_default_config(tmp_path)++ # First add custom layers so the rule makes sense+ add_layer(config_path, "projectile", default="Collide")+ add_layer(config_path, "enemy", default="Collide")++ rule = add_rule(config_path, "projectile", "enemy", result="Collide")+ assert rule["a"] == "projectile"+ assert rule["b"] == "enemy"+ assert rule["r"] == "Collide"++ # Verify persistence+ data = load_collision_config(config_path)+ pairs = data["Pairs"]+ matching = [+ p for p in pairs+ if (p["a"] == "projectile" and p["b"] == "enemy")+ or (p["a"] == "enemy" and p["b"] == "projectile")+ ]+ assert len(matching) == 1++ def test_remove_rule(self, tmp_path):+ """Remove a pair rule."""+ config_path = self._write_default_config(tmp_path)++ # Add a custom rule then remove it+ add_layer(config_path, "projectile", default="Collide")+ add_rule(config_path, "projectile", "solid", result="Collide")++ removed = remove_rule(config_path, "projectile", "solid")+ assert removed is True++ # Verify it's gone+ data = load_collision_config(config_path)+ pairs = data["Pairs"]+ matching = [+ p for p in pairs+ if (p["a"] == "projectile" and p["b"] == "solid")+ or (p["a"] == "solid" and p["b"] == "projectile")+ ]+ assert len(matching) == 0+++# ============================================================================+# TestSession+# ============================================================================+++class TestSession:+ """Tests for cli_anything.sbox.core.session."""++ def test_session_create(self, tmp_path):+ """Create a new session."""+ session_path = str(tmp_path / "session.json")+ session = Session(session_path=session_path)++ status = session.get_status()+ assert status["project_path"] is None+ assert status["scene_path"] is None+ assert status["undo_count"] == 0+ assert status["redo_count"] == 0++ def test_session_set_project(self, tmp_path):+ """Set project path."""+ session_path = str(tmp_path / "session.json")+ session = Session(session_path=session_path)++ # Create a dummy sbproj to reference+ dummy_proj = tmp_path / "test.sbproj"+ dummy_proj.write_text("{}", encoding="utf-8")++ session.set_project(str(dummy_proj))+ assert session.project_path == str(dummy_proj.resolve())++ # Verify persistence by creating a new Session from the same file+ session2 = Session(session_path=session_path)+ assert session2.project_path == str(dummy_proj.resolve())++ def test_session_undo_redo(self, tmp_path):+ """Record ops, undo, redo."""+ session_path = str(tmp_path / "session.json")+ session = Session(session_path=session_path)++ # Record two operations+ session.record_operation(+ op_type="scene_modify",+ description="Added turret",+ before_state={"count": 0},+ after_state={"count": 1},+ )+ session.record_operation(+ op_type="scene_modify",+ description="Added wall",+ before_state={"count": 1},+ after_state={"count": 2},+ )++ status = session.get_status()+ assert status["undo_count"] == 2+ assert status["redo_count"] == 0++ # Undo last operation+ undone = session.undo()+ assert undone is not None+ assert undone["undone"] is True+ assert undone["description"] == "Added wall"+ assert undone["before_state"] == {"count": 1}++ status = session.get_status()+ assert status["undo_count"] == 1+ assert status["redo_count"] == 1++ # Redo it+ redone = session.redo()+ assert redone is not None+ assert redone["redone"] is True+ assert redone["description"] == "Added wall"++ status = session.get_status()+ assert status["undo_count"] == 2+ assert status["redo_count"] == 0++ # Undo when stack is empty after undoing everything+ session.undo()+ session.undo()+ result = session.undo()+ assert result is None++ def test_session_save_load(self, tmp_path):+ """Save and reload session."""+ session_path = str(tmp_path / "session.json")+ session = Session(session_path=session_path)++ dummy_proj = tmp_path / "test.sbproj"+ dummy_proj.write_text("{}", encoding="utf-8")+ dummy_scene = tmp_path / "test.scene"+ dummy_scene.write_text("{}", encoding="utf-8")++ session.set_project(str(dummy_proj))+ session.set_scene(str(dummy_scene))+ session.record_operation(+ op_type="codegen",+ description="Generated component",+ )++ # Create a fresh Session from the same path+ session2 = Session(session_path=session_path)+ status = session2.get_status()+ assert status["project_path"] == str(dummy_proj.resolve())+ assert status["scene_path"] == str(dummy_scene.resolve())+ assert status["undo_count"] == 1++ def test_session_clear(self, tmp_path):+ """Clear session state."""+ session_path = str(tmp_path / "session.json")+ session = Session(session_path=session_path)++ dummy_proj = tmp_path / "test.sbproj"+ dummy_proj.write_text("{}", encoding="utf-8")+ session.set_project(str(dummy_proj))+ session.record_operation(+ op_type="scene_modify",+ description="Test op",+ )++ session.clear()++ status = session.get_status()+ assert status["project_path"] is None+ assert status["scene_path"] is None+ assert status["undo_count"] == 0+ assert status["redo_count"] == 0+++# ============================================================================+# TestExport+# ============================================================================+++class TestExport:+ """Tests for cli_anything.sbox.core.export."""++ def _create_project_with_assets(self, tmp_path):+ """Helper: create a project with known asset files and return root path."""+ info = create_project("AssetTest", output_dir=str(tmp_path / "AssetTest"))+ root = tmp_path / "AssetTest"++ # Add additional asset files+ # A prefab+ prefab_dir = root / "Assets" / "prefabs"+ prefab_dir.mkdir(parents=True, exist_ok=True)+ create_prefab("Turret", output_path=str(prefab_dir / "turret.prefab"))++ # A C# file+ code_dir = root / "Assets" / "code"+ code_dir.mkdir(parents=True, exist_ok=True)+ (code_dir / "PlayerHealth.cs").write_text(+ "public class PlayerHealth {}", encoding="utf-8"+ )++ return str(root)++ def test_list_assets(self, tmp_path):+ """List assets in a project directory."""+ project_dir = self._create_project_with_assets(tmp_path)++ assets = list_assets(project_dir)+ assert len(assets) >= 3 # minimal.scene + turret.prefab + PlayerHealth.cs++ types = {a["type"] for a in assets}+ assert "scene" in types+ assert "prefab" in types+ assert "code" in types++ # Each asset should have required keys+ for asset in assets:+ assert "path" in asset+ assert "type" in asset+ assert "name" in asset+ assert "size_bytes" in asset++ def test_list_assets_filtered(self, tmp_path):+ """Filter assets by type."""+ project_dir = self._create_project_with_assets(tmp_path)++ # Filter to scenes only+ scenes = list_assets(project_dir, asset_type="scene")+ for asset in scenes:+ assert asset["type"] == "scene"+ assert asset["name"].endswith(".scene")++ # Filter to prefabs only+ prefabs = list_assets(project_dir, asset_type="prefab")+ for asset in prefabs:+ assert asset["type"] == "prefab"+ assert asset["name"].endswith(".prefab")++ # Scenes and prefabs should not overlap+ scene_names = {a["name"] for a in scenes}+ prefab_names = {a["name"] for a in prefabs}+ assert scene_names.isdisjoint(prefab_names)++ def test_find_project_dir(self, tmp_path):+ """Find project dir from a subdirectory."""+ info = create_project("FindDir", output_dir=str(tmp_path / "FindDir"))+ root = tmp_path / "FindDir"++ # Create a nested directory+ nested = root / "Assets" / "scenes" / "subdir"+ nested.mkdir(parents=True, exist_ok=True)++ # find_project_dir should walk up and find the root+ found = find_project_dir(str(nested))+ assert found is not None+ # Normalize paths for comparison+ assert os.path.normcase(os.path.normpath(found)) == os.path.normcase(+ os.path.normpath(str(root))+ )++ # Should also work from a file inside the project+ scene_file = root / "Assets" / "scenes" / "minimal.scene"+ found_from_file = find_project_dir(str(scene_file))+ assert found_from_file is not None+ assert os.path.normcase(os.path.normpath(found_from_file)) == os.path.normcase(+ os.path.normpath(str(root))+ )+++# ---------------------------------------------------------------------------+# New tests for refinement pass+# ---------------------------------------------------------------------------+++class TestComponentPresets:+ """Tests for expanded COMPONENT_PRESETS."""++ def test_preset_count(self):+ """Verify we have 29 component presets."""+ assert len( COMPONENT_PRESETS ) == 29++ def test_all_presets_have_type(self):+ """Every preset must have a __type key."""+ for name, preset in COMPONENT_PRESETS.items():+ assert "__type" in preset, f"Preset '{name}' missing __type"+ assert preset["__type"].startswith( "Sandbox." ), f"Preset '{name}' __type should start with Sandbox."+++class TestSceneModify:+ """Tests for modify_object and set_scene_properties."""++ def test_modify_object_name_and_position(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )+ guid = add_object( scene_path, "OldName", position="0,0,0" )++ result = modify_object( scene_path, guid=guid, new_name="NewName", position="100,200,300" )+ assert result["name"] == "NewName"+ assert "Name" in result["modified_fields"]+ assert "Position" in result["modified_fields"]++ objects = list_objects( scene_path )+ obj = [o for o in objects if o["guid"] == guid][0]+ assert obj["name"] == "NewName"+ assert obj["position"] == "100,200,300"++ def test_modify_object_selective(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )+ guid = add_object( scene_path, "MyObj", position="10,20,30", scale="2,2,2" )++ # Only modify position, scale should stay unchanged+ modify_object( scene_path, guid=guid, position="99,99,99" )++ data = load_scene( scene_path )+ obj = find_object( data, guid=guid )+ assert obj["Position"] == "99,99,99"+ assert obj["Scale"] == "2,2,2"+ assert obj["Name"] == "MyObj"++ def test_modify_object_not_found(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )++ with pytest.raises( ValueError, match="not found" ):+ modify_object( scene_path, guid="nonexistent-guid", new_name="X" )++ def test_set_scene_properties(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, fixed_update_freq=50 )++ props = set_scene_properties( scene_path, fixed_update_freq=64, timescale=0.5 )+ assert props["FixedUpdateFrequency"] == 64+ assert props["TimeScale"] == 0.5++ # Verify persistence+ data = load_scene( scene_path )+ assert data["SceneProperties"]["FixedUpdateFrequency"] == 64+ assert data["SceneProperties"]["TimeScale"] == 0.5+++class TestCodegenRazor:+ """Tests for Razor UI generation and RPC support."""++ def test_generate_razor_basic(self):+ result = generate_razor( "HudPanel" )+ assert result["filename"] == "HudPanel.razor"+ assert result["scss_filename"] == "HudPanel.razor.scss"+ assert "@using Sandbox;" in result["content"]+ assert "@using Sandbox.UI;" in result["content"]+ assert "@inherits PanelComponent" in result["content"]+ assert 'class="hud-panel"' in result["content"]++ def test_generate_razor_with_properties(self):+ result = generate_razor( "ScoreBoard", properties=[+ {"name": "Score", "type": "int", "default": "0"},+ {"name": "PlayerName", "type": "string"},+ ])+ assert "[Property] public int Score" in result["content"]+ assert "[Property] public string PlayerName" in result["content"]+ assert "BuildHash" in result["content"]+ assert "System.HashCode.Combine" in result["content"]++ def test_generate_razor_scss(self):+ result = generate_razor( "MyWidget", root_class="custom-widget" )+ assert ".custom-widget" in result["scss_content"]+ assert "flex-direction: column;" in result["scss_content"]++ def test_generate_component_with_rpc(self):+ result = generate_component(+ "NetPlayer",+ rpc_methods=[+ {"name": "FireBullet", "type": "Broadcast"},+ {"name": "TakeDamage", "type": "Host"},+ ],+ )+ content = result["content"]+ assert "public partial class NetPlayer" in content+ assert "[Rpc.Broadcast]" in content+ assert "[Rpc.Host]" in content+ assert "public void FireBullet()" in content+ assert "public void TakeDamage()" in content++ def test_generate_component_net_collections(self):+ result = generate_component(+ "Inventory",+ is_networked=True,+ properties=[+ {"name": "Items", "type": "NetList<string>"},+ {"name": "Score", "type": "int", "default": "0"},+ ],+ )+ content = result["content"]+ # NetList should NOT have [Sync]+ # Score should have [Sync]+ lines = content.split( "\r\n" )+ for i, line in enumerate( lines ):+ if "NetList<string>" in line:+ # Check previous lines don't have [Sync]+ prev = lines[max(0, i-1)].strip() if i > 0 else ""+ prev2 = lines[max(0, i-2)].strip() if i > 1 else ""+ assert "[Sync]" not in prev, "NetList should not have [Sync]"+ assert "[Sync]" not in prev2, "NetList should not have [Sync]"+++class TestMaterial:+ """Tests for material creation and parsing."""++ def test_create_material_default(self, tmp_path):+ path = str( tmp_path / "test.vmat" )+ result = create_material( "test", output_path=path )+ assert result["name"] == "test"+ assert result["shader"] == "shaders/complex.vfx"+ assert os.path.isfile( path )+ with open( path, "r", encoding="utf-8" ) as f:+ content = f.read()+ assert 'shader "shaders/complex.vfx"' in content+ assert "Layer0" in content++ def test_create_material_with_textures(self, tmp_path):+ path = str( tmp_path / "brick.vmat" )+ result = create_material(+ "brick",+ color_texture="textures/brick_color.tga",+ normal_texture="textures/brick_normal.tga",+ metalness=0.2,+ output_path=path,+ )+ with open( path, "r", encoding="utf-8" ) as f:+ content = f.read()+ assert 'TextureColor "textures/brick_color.tga"' in content+ assert 'TextureNormal "textures/brick_normal.tga"' in content+ assert 'g_flMetalness "0.2"' in content++ def test_parse_material(self, tmp_path):+ path = str( tmp_path / "mat.vmat" )+ create_material( "mat", color_texture="tex/color.tga", metalness=0.8, output_path=path )+ parsed = parse_material( path )+ assert parsed["name"] == "mat"+ assert parsed["shader"] == "shaders/complex.vfx"+ assert "TextureColor" in parsed["properties"]+ assert parsed["properties"]["g_flMetalness"] == "0.8"++ def test_list_materials(self, tmp_path):+ create_project( "test", output_dir=str( tmp_path ) )+ mat_dir = tmp_path / "Assets" / "materials"+ mat_dir.mkdir( parents=True, exist_ok=True )+ create_material( "floor", output_path=str( mat_dir / "floor.vmat" ) )+ create_material( "wall", output_path=str( mat_dir / "wall.vmat" ) )+ materials = list_materials( str( tmp_path ) )+ names = [m["name"] for m in materials]+ assert "floor" in names+ assert "wall" in names++ def test_vmat_format(self, tmp_path):+ """Verify .vmat is text format, not JSON."""+ path = str( tmp_path / "test.vmat" )+ create_material( "test", output_path=path )+ with open( path, "r", encoding="utf-8" ) as f:+ content = f.read()+ # Should NOT be valid JSON+ try:+ json.loads( content )+ assert False, "vmat should not be JSON"+ except json.JSONDecodeError:+ pass # Expected+++class TestSound:+ """Tests for sound event creation and parsing."""++ def test_create_sound_event(self, tmp_path):+ path = str( tmp_path / "bang.sound" )+ result = create_sound_event( "bang", sounds=["sounds/bang.vsnd"], output_path=path )+ assert result["name"] == "bang"+ assert os.path.isfile( path )+ with open( path, "r", encoding="utf-8" ) as f:+ data = json.load( f )+ assert data["Sounds"] == ["sounds/bang.vsnd"]+ assert data["__version"] == 1++ def test_create_sound_multiple(self, tmp_path):+ result = create_sound_event(+ "footstep",+ sounds=["sounds/step1.vsnd", "sounds/step2.vsnd", "sounds/step3.vsnd"],+ volume="0.5",+ )+ assert len( result["data"]["Sounds"] ) == 3+ assert result["data"]["Volume"] == "0.5"++ def test_parse_sound_event(self, tmp_path):+ path = str( tmp_path / "test.sound" )+ create_sound_event( "test", sounds=["sounds/a.vsnd"], volume="0.7", output_path=path )+ parsed = parse_sound_event( path )+ assert parsed["name"] == "test"+ assert parsed["volume"] == "0.7"+ assert "sounds/a.vsnd" in parsed["sounds"]++ def test_sound_defaults(self):+ result = create_sound_event( "default" )+ data = result["data"]+ assert data["Volume"] == "1"+ assert data["Pitch"] == "1"+ assert data["Decibels"] == 70+ assert data["Occlusion"] is True+ assert data["UI"] is False+++class TestLocalization:+ """Tests for translation file management."""++ def test_create_translation_file(self, tmp_path):+ path = str( tmp_path / "en.json" )+ result = create_translation_file(+ lang="en",+ initial_keys={"game.title": "My Game"},+ output_path=path,+ )+ assert result["lang"] == "en"+ assert result["key_count"] == 1+ assert os.path.isfile( path )++ def test_set_and_get_key(self, tmp_path):+ path = str( tmp_path / "en.json" )+ create_translation_file( lang="en", output_path=path )+ set_key( path, "ui.button.start", "Start Game" )+ value = get_key( path, "ui.button.start" )+ assert value == "Start Game"++ def test_list_keys(self, tmp_path):+ path = str( tmp_path / "en.json" )+ create_translation_file(+ lang="en",+ initial_keys={"b.key": "B", "a.key": "A", "c.key": "C"},+ output_path=path,+ )+ keys = list_keys( path )+ assert keys == ["a.key", "b.key", "c.key"] # sorted++ def test_remove_key(self, tmp_path):+ path = str( tmp_path / "en.json" )+ create_translation_file(+ lang="en",+ initial_keys={"game.title": "Title", "game.desc": "Desc"},+ output_path=path,+ )+ removed = remove_key( path, "game.title" )+ assert removed is True+ assert get_key( path, "game.title" ) is None+ assert get_key( path, "game.desc" ) == "Desc"++ def test_remove_key_not_found(self, tmp_path):+ path = str( tmp_path / "en.json" )+ create_translation_file( lang="en", output_path=path )+ removed = remove_key( path, "nonexistent" )+ assert removed is False+++class TestSceneCloneAndGet:+ """Tests for clone_object, get_object, and set_navmesh_properties."""++ def test_clone_object(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )+ guid = add_object( scene_path, "Original", position="10,20,30", components=["model", "rigidbody"] )++ result = clone_object( scene_path, guid=guid, new_name="Copy", position="100,0,0" )+ assert result["name"] == "Copy"+ assert result["original_name"] == "Original"+ assert result["guid"] != result["original_guid"]++ objects = list_objects( scene_path )+ names = [o["name"] for o in objects]+ assert "Original" in names+ assert "Copy" in names+ assert len( objects ) == 2++ def test_clone_object_default_name(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )+ add_object( scene_path, "Box", position="0,0,0" )++ result = clone_object( scene_path, name="Box" )+ assert result["name"] == "Box (Clone)"++ def test_clone_object_new_guids(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )+ guid = add_object( scene_path, "Obj", components=["model", "box_collider"] )++ clone_result = clone_object( scene_path, guid=guid )+ data = load_scene( scene_path )++ # Collect all GUIDs - none should be duplicated+ all_guids = set()+ for obj in data["GameObjects"]:+ all_guids.add( obj["__guid"] )+ for comp in obj.get( "Components", [] ):+ guid_val = comp.get( "__guid", "" )+ assert guid_val not in all_guids or guid_val == "", f"Duplicate GUID: {guid_val}"+ all_guids.add( guid_val )++ def test_get_object(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )+ guid = add_object( scene_path, "TestObj", position="1,2,3", components=["model", "rigidbody"] )++ result = get_object( scene_path, guid=guid )+ assert result["name"] == "TestObj"+ assert result["guid"] == guid+ assert result["position"] == "1,2,3"+ assert len( result["components"] ) == 2+ types = [c["type"] for c in result["components"]]+ assert "Sandbox.ModelRenderer" in types+ assert "Sandbox.Rigidbody" in types++ def test_get_object_not_found(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )++ with pytest.raises( ValueError, match="not found" ):+ get_object( scene_path, guid="nonexistent" )++ def test_set_navmesh_properties(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path )++ result = set_navmesh_properties(+ scene_path,+ navmesh_enabled=True,+ navmesh_agent_height=72,+ navmesh_agent_radius=16,+ )+ assert result["Enabled"] is True+ assert result["AgentHeight"] == 72+ assert result["AgentRadius"] == 16++ data = load_scene( scene_path )+ assert data["SceneProperties"]["NavMesh"]["Enabled"] is True+++class TestProjectPackages:+ """Tests for add_package and remove_package."""++ def test_add_package(self, tmp_path):+ info = create_project( "test", output_dir=str( tmp_path ) )+ sbproj = info["sbproj"]+ result = add_package( sbproj, "facepunch.libsdf" )+ assert "facepunch.libsdf" in result["package_references"]++ def test_add_duplicate_package(self, tmp_path):+ info = create_project( "test", output_dir=str( tmp_path ) )+ sbproj = info["sbproj"]+ add_package( sbproj, "facepunch.libsdf" )+ with pytest.raises( ValueError, match="already referenced" ):+ add_package( sbproj, "facepunch.libsdf" )++ def test_remove_package(self, tmp_path):+ info = create_project( "test", output_dir=str( tmp_path ) )+ sbproj = info["sbproj"]+ add_package( sbproj, "facepunch.libsdf" )+ add_package( sbproj, "local.mylib" )+ result = remove_package( sbproj, "facepunch.libsdf" )+ assert "facepunch.libsdf" not in result["package_references"]+ assert "local.mylib" in result["package_references"]++ def test_remove_missing_package(self, tmp_path):+ info = create_project( "test", output_dir=str( tmp_path ) )+ sbproj = info["sbproj"]+ with pytest.raises( ValueError, match="not found" ):+ remove_package( sbproj, "nonexistent.pkg" )+++class TestPrefabComponents:+ """Tests for prefab add-component and remove-component."""++ def test_prefab_add_component(self, tmp_path):+ path = str( tmp_path / "test.prefab" )+ create_prefab( "TestPrefab", output_path=path, components=["model"] )+ data = load_prefab( path )+ assert len( data["RootObject"]["Components"] ) == 1+ root = data["RootObject"]+ comp = copy.deepcopy( COMPONENT_PRESETS["rigidbody"] )+ comp["__guid"] = str( uuid.uuid4() )+ root["Components"].append( comp )+ save_prefab( path, data )+ data2 = load_prefab( path )+ assert len( data2["RootObject"]["Components"] ) == 2+ types = [c["__type"] for c in data2["RootObject"]["Components"]]+ assert "Sandbox.Rigidbody" in types++ def test_prefab_remove_component(self, tmp_path):+ path = str( tmp_path / "test.prefab" )+ create_prefab( "TestPrefab", output_path=path, components=["model", "rigidbody"] )+ data = load_prefab( path )+ assert len( data["RootObject"]["Components"] ) == 2+ root = data["RootObject"]+ root["Components"] = [c for c in root["Components"] if c["__type"] != "Sandbox.Rigidbody"]+ save_prefab( path, data )+ data2 = load_prefab( path )+ assert len( data2["RootObject"]["Components"] ) == 1+ assert data2["RootObject"]["Components"][0]["__type"] == "Sandbox.ModelRenderer"+++class TestCollisionRemoveLayer:+ """Test collision remove-layer success path."""++ def test_remove_custom_layer(self, tmp_path):+ path = str( tmp_path / "Collision.config" )+ save_collision_config( path, get_default_collision_config() )+ add_layer( path, "projectile", default="Collide" )+ add_rule( path, "projectile", "solid", result="Collide" )+ data = load_collision_config( path )+ assert "projectile" in data["Defaults"]+ removed = remove_layer( path, "projectile" )+ assert removed is True+ data2 = load_collision_config( path )+ assert "projectile" not in data2["Defaults"]+ for pair in data2["Pairs"]:+ assert pair["a"] != "projectile" and pair["b"] != "projectile"+++class TestJointPresets:+ """Test joint component presets in scenes."""++ def test_add_object_with_joints(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )+ add_object( scene_path, "Door", components=["model", "hinge_joint"] )+ objects = list_objects( scene_path )+ assert len( objects ) == 1+ types = objects[0]["component_types"]+ assert "Sandbox.ModelRenderer" in types+ assert "Sandbox.HingeJoint" in types+++class TestMaterialUpdate:+ """Test material update functionality."""++ def test_update_metalness(self, tmp_path):+ path = str( tmp_path / "test.vmat" )+ create_material( "test", metalness=0.0, output_path=path )+ result = update_material( path, metalness=0.8 )+ assert result["properties"]["g_flMetalness"] == "0.8"++ def test_update_texture(self, tmp_path):+ path = str( tmp_path / "test.vmat" )+ create_material( "test", output_path=path )+ result = update_material( path, color_texture="textures/new_color.tga" )+ assert result["properties"]["TextureColor"] == "textures/new_color.tga"+++class TestSoundUpdate:+ """Test sound event update functionality."""++ def test_update_volume(self, tmp_path):+ path = str( tmp_path / "test.sound" )+ create_sound_event( "test", volume="1", output_path=path )+ result = update_sound_event( path, volume="0.5" )+ assert result["volume"] == "0.5"++ def test_update_sounds_list(self, tmp_path):+ path = str( tmp_path / "test.sound" )+ create_sound_event( "test", sounds=["a.vsnd"], output_path=path )+ result = update_sound_event( path, sounds=["b.vsnd", "c.vsnd"] )+ assert result["sounds"] == ["b.vsnd", "c.vsnd"]+++class TestSceneModifyComponent:+ """Tests for modify_component."""++ def test_modify_component_by_type(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )+ guid = add_object( scene_path, "Obj", components=["rigidbody"] )++ result = modify_component(+ scene_path, guid,+ component_type="Sandbox.Rigidbody",+ properties={"Gravity": False, "LinearDamping": 5},+ )+ assert "Gravity" in result["updated_keys"]+ assert "LinearDamping" in result["updated_keys"]++ data = load_scene( scene_path )+ obj = find_object( data, guid=guid )+ rb = [c for c in obj["Components"] if c["__type"] == "Sandbox.Rigidbody"][0]+ assert rb["Gravity"] is False+ assert rb["LinearDamping"] == 5++ def test_modify_component_not_found(self, tmp_path):+ scene_path = str( tmp_path / "test.scene" )+ create_scene( "test", output_path=scene_path, include_defaults=False )+ guid = add_object( scene_path, "Obj" )++ with pytest.raises( ValueError, match="not found" ):+ modify_component( scene_path, guid, component_type="Sandbox.Rigidbody", properties={"Gravity": False} )+++class TestCodegenClass:+ """Tests for generate_class."""++ def test_generate_static_class(self):+ result = generate_class( "GameUtils", is_static=True, properties=[+ {"name": "Version", "type": "string", "default": '"1.0"'},+ ])+ assert result["filename"] == "GameUtils.cs"+ assert "public static class GameUtils" in result["content"]+ assert "public static string Version" in result["content"]+ assert "\r\n" in result["content"]++ def test_generate_class_with_base(self):+ result = generate_class( "EnemyManager", base_class="BaseManager" )+ assert "public class EnemyManager : BaseManager" in result["content"]+ assert "using Sandbox;" in result["content"]+++class TestLocalizationBulkSet:+ """Test bulk_set for localization."""++ def test_bulk_set(self, tmp_path):+ path = str( tmp_path / "en.json" )+ create_translation_file( lang="en", initial_keys={"existing": "value"}, output_path=path )+ result = bulk_set( path, {"game.title": "My Game", "game.desc": "A game", "ui.start": "Start"} )+ assert len( result ) == 4+ assert result["game.title"] == "My Game"+ assert result["existing"] == "value"+ keys = list_keys( path )+ assert "game.title" in keys+ assert "ui.start" in keys+++# ============================================================================+# Refine batch: query, refs, bulk-modify, validate, panel-component+# ============================================================================+++class TestSceneQuery:+ """Tests for scene.query_objects."""++ def _make_test_scene(self, tmp_path):+ scene_path = str( tmp_path / "q.scene" )+ create_scene( "q", output_path=scene_path, include_defaults=False )+ add_object( scene_path, "Tower1", position="100,0,0", tags="tower,placed", components=["model", "rigidbody"] )+ add_object( scene_path, "Tower2", position="200,0,0", tags="tower", components=["model"] )+ add_object( scene_path, "Enemy1", position="0,500,0", tags="enemy", components=["skinned_model_renderer", "rigidbody"] )+ add_object( scene_path, "Disabled", position="0,0,0", tags="" )+ # Disable the last one+ modify_object( scene_path, name_match="Disabled", enabled=False )+ return scene_path++ def test_query_by_component_preset(self, tmp_path):+ path = self._make_test_scene( tmp_path )+ result = query_objects( path, has_component="rigidbody" )+ names = sorted( r["name"] for r in result )+ assert names == ["Enemy1", "Tower1"]++ def test_query_by_component_full_type(self, tmp_path):+ path = self._make_test_scene( tmp_path )+ result = query_objects( path, has_component="Sandbox.SkinnedModelRenderer" )+ assert len( result ) == 1+ assert result[0]["name"] == "Enemy1"++ def test_query_by_tag(self, tmp_path):+ path = self._make_test_scene( tmp_path )+ result = query_objects( path, has_tag="tower" )+ names = sorted( r["name"] for r in result )+ assert names == ["Tower1", "Tower2"]++ def test_query_by_name_substring(self, tmp_path):+ path = self._make_test_scene( tmp_path )+ result = query_objects( path, name_match="Tower" )+ assert len( result ) == 2++ def test_query_by_name_regex(self, tmp_path):+ path = self._make_test_scene( tmp_path )+ result = query_objects( path, name_regex=r"^Tower\d$" )+ assert len( result ) == 2++ def test_query_by_bounds(self, tmp_path):+ path = self._make_test_scene( tmp_path )+ # Bounds that capture only the Towers (x in [50, 250])+ result = query_objects( path, in_bounds="50,-1,-1,250,1,1" )+ names = sorted( r["name"] for r in result )+ assert names == ["Tower1", "Tower2"]++ def test_query_by_enabled(self, tmp_path):+ path = self._make_test_scene( tmp_path )+ result = query_objects( path, enabled=False )+ assert len( result ) == 1+ assert result[0]["name"] == "Disabled"++ def test_query_combined_filters_and(self, tmp_path):+ path = self._make_test_scene( tmp_path )+ # tower tag AND has rigidbody = only Tower1+ result = query_objects( path, has_tag="tower", has_component="rigidbody" )+ assert len( result ) == 1+ assert result[0]["name"] == "Tower1"++ def test_query_no_matches(self, tmp_path):+ path = self._make_test_scene( tmp_path )+ result = query_objects( path, has_tag="nonexistent" )+ assert result == []+++class TestSceneRefs:+ """Tests for scene.extract_asset_refs."""++ def test_refs_from_default_scene(self, tmp_path):+ scene_path = str( tmp_path / "default.scene" )+ create_scene( "default", output_path=scene_path, include_defaults=True )+ refs = extract_asset_refs( scene_path )++ # The default scene has a model, materials, a sky material, and a cubemap+ assert "models" in refs+ assert "materials" in refs+ assert "textures" in refs+ # Check specific known refs from the default scene+ assert any( "models/dev/plane.vmdl" in r for r in refs["models"] )+ assert any( "materials/skybox" in r for r in refs["materials"] )++ def test_refs_dedup_and_sort(self, tmp_path):+ scene_path = str( tmp_path / "dup.scene" )+ create_scene( "dup", output_path=scene_path, include_defaults=False )+ # Add two objects that share the same model+ add_object( scene_path, "A", components=["model"] )+ add_object( scene_path, "B", components=["model"] )+ refs = extract_asset_refs( scene_path )+ # The model "models/dev/box.vmdl" appears in both objects but should be deduped+ assert refs["models"].count( "models/dev/box.vmdl" ) == 1++ def test_refs_empty_scene(self, tmp_path):+ scene_path = str( tmp_path / "empty.scene" )+ create_scene( "empty", output_path=scene_path, include_defaults=False )+ refs = extract_asset_refs( scene_path )+ assert refs == {}+++class TestSceneBulkModify:+ """Tests for scene.bulk_modify_objects."""++ def test_bulk_modify_position(self, tmp_path):+ scene_path = str( tmp_path / "bulk.scene" )+ create_scene( "bulk", output_path=scene_path, include_defaults=False )+ add_object( scene_path, "T1", position="0,0,0", tags="tower" )+ add_object( scene_path, "T2", position="0,0,0", tags="tower" )+ add_object( scene_path, "E1", position="0,0,0", tags="enemy" )++ result = bulk_modify_objects( scene_path, has_tag="tower", new_position="100,200,300" )+ assert result["modified_count"] == 2+ assert result["modified_fields"] == ["Position"]++ towers = query_objects( scene_path, has_tag="tower" )+ for t in towers:+ assert t["position"] == "100,200,300"+ # Enemy untouched+ enemies = query_objects( scene_path, has_tag="enemy" )+ assert enemies[0]["position"] == "0,0,0"++ def test_bulk_modify_multiple_fields(self, tmp_path):+ scene_path = str( tmp_path / "bulk2.scene" )+ create_scene( "bulk2", output_path=scene_path, include_defaults=False )+ guid = add_object( scene_path, "X", position="0,0,0", tags="a" )++ result = bulk_modify_objects(+ scene_path,+ has_tag="a",+ new_scale="2,2,2",+ new_tags="modified",+ new_enabled=False,+ )+ assert result["modified_count"] == 1+ assert set( result["modified_fields"] ) == {"Scale", "Tags", "Enabled"}++ obj = get_object( scene_path, guid=guid )+ assert obj["scale"] == "2,2,2"+ assert obj["tags"] == "modified"+ assert obj["enabled"] is False++ def test_bulk_modify_no_matches(self, tmp_path):+ scene_path = str( tmp_path / "none.scene" )+ create_scene( "none", output_path=scene_path, include_defaults=False )+ result = bulk_modify_objects( scene_path, has_tag="nope", new_position="0,0,0" )+ assert result["modified_count"] == 0+ assert result["modified_guids"] == []++ def test_bulk_modify_requires_update(self, tmp_path):+ scene_path = str( tmp_path / "req.scene" )+ create_scene( "req", output_path=scene_path, include_defaults=False )+ with pytest.raises( ValueError, match="at least one modification" ):+ bulk_modify_objects( scene_path, has_tag="x" )+++class TestPrefabRefs:+ """Tests for prefab.extract_asset_refs."""++ def test_refs_from_prefab(self, tmp_path):+ prefab_path = str( tmp_path / "p.prefab" )+ create_prefab( "p", output_path=prefab_path, components=["model", "rigidbody", "model_collider"] )+ refs = prefab_extract_asset_refs( prefab_path )+ assert "models" in refs+ assert "models/dev/box.vmdl" in refs["models"]+++class TestPrefabModifyComponent:+ """Tests for prefab.modify_component."""++ def test_modify_by_type(self, tmp_path):+ prefab_path = str( tmp_path / "rb.prefab" )+ create_prefab( "rb", output_path=prefab_path, components=["model", "rigidbody"] )+ result = prefab_modify_component(+ prefab_path,+ component_type="Sandbox.Rigidbody",+ properties={"Gravity": False, "MassOverride": 100},+ )+ assert result["component_type"] == "Sandbox.Rigidbody"+ assert "Gravity" in result["updated_keys"]+ assert "MassOverride" in result["updated_keys"]++ data = load_prefab( prefab_path )+ rb = next( c for c in data["RootObject"]["Components"] if c["__type"] == "Sandbox.Rigidbody" )+ assert rb["Gravity"] is False+ assert rb["MassOverride"] == 100++ def test_modify_by_guid(self, tmp_path):+ prefab_path = str( tmp_path / "guid.prefab" )+ create_prefab( "guid", output_path=prefab_path, components=["model"] )+ data = load_prefab( prefab_path )+ comp_guid = data["RootObject"]["Components"][0]["__guid"]++ result = prefab_modify_component(+ prefab_path,+ component_guid=comp_guid,+ properties={"Tint": "1,0,0,1"},+ )+ assert result["component_guid"] == comp_guid++ data2 = load_prefab( prefab_path )+ assert data2["RootObject"]["Components"][0]["Tint"] == "1,0,0,1"++ def test_modify_not_found(self, tmp_path):+ prefab_path = str( tmp_path / "nf.prefab" )+ create_prefab( "nf", output_path=prefab_path, components=["model"] )+ with pytest.raises( ValueError, match="not found" ):+ prefab_modify_component( prefab_path, component_type="Sandbox.Missing", properties={"x": 1} )++ def test_modify_requires_identifier(self, tmp_path):+ prefab_path = str( tmp_path / "id.prefab" )+ create_prefab( "id", output_path=prefab_path, components=["model"] )+ with pytest.raises( ValueError, match="component_guid or component_type" ):+ prefab_modify_component( prefab_path, properties={"x": 1} )++ def test_modify_requires_properties(self, tmp_path):+ prefab_path = str( tmp_path / "noprops.prefab" )+ create_prefab( "noprops", output_path=prefab_path, components=["model"] )+ with pytest.raises( ValueError, match="No properties" ):+ prefab_modify_component( prefab_path, component_type="Sandbox.ModelRenderer" )+++class TestAssetRefGraph:+ """Tests for export.find_asset_refs and find_unused_assets."""++ def _make_project(self, tmp_path):+ """Build a minimal project with a scene + prefab + a stray unused model."""+ info = create_project( "RefTest", output_dir=str( tmp_path / "RefTest" ) )+ proj_dir = os.path.dirname( info["sbproj"] )++ # Custom scene with a known asset reference+ scene_path = os.path.join( proj_dir, "Assets", "scenes", "level.scene" )+ os.makedirs( os.path.dirname( scene_path ), exist_ok=True )+ create_scene( "level", output_path=scene_path, include_defaults=False )+ add_object( scene_path, "Box", components=[+ {"__type": "Sandbox.ModelRenderer", "Model": "models/myteam/widget.vmdl"},+ ] )++ # Prefab that references the same model+ prefab_path = os.path.join( proj_dir, "Assets", "prefabs", "widget.prefab" )+ os.makedirs( os.path.dirname( prefab_path ), exist_ok=True )+ create_prefab( "widget", output_path=prefab_path, components=[+ {"__type": "Sandbox.ModelRenderer", "Model": "models/myteam/widget.vmdl"},+ ] )++ # Create the actual asset files (so list_assets sees them)+ widget_vmdl = os.path.join( proj_dir, "Assets", "models", "myteam", "widget.vmdl" )+ os.makedirs( os.path.dirname( widget_vmdl ), exist_ok=True )+ with open( widget_vmdl, "w", encoding="utf-8" ) as f:+ f.write( "<MODEL_PLACEHOLDER>" )++ # Unused asset+ unused_vmdl = os.path.join( proj_dir, "Assets", "models", "myteam", "unused.vmdl" )+ with open( unused_vmdl, "w", encoding="utf-8" ) as f:+ f.write( "<UNUSED_MODEL>" )++ # Unused material+ unused_mat = os.path.join( proj_dir, "Assets", "materials", "unused.vmat" )+ os.makedirs( os.path.dirname( unused_mat ), exist_ok=True )+ with open( unused_mat, "w", encoding="utf-8" ) as f:+ f.write( "Layer0 { shader \"complex.shader\" }" )++ return proj_dir++ def test_find_asset_refs_finds_both(self, tmp_path):+ proj_dir = self._make_project( tmp_path )+ refs = find_asset_refs( proj_dir, "models/myteam/widget.vmdl" )+ assert len( refs ) == 2+ files = sorted( r["file"] for r in refs )+ assert any( "level.scene" in f for f in files )+ assert any( "widget.prefab" in f for f in files )+ for r in refs:+ assert r["category"] == "models"++ def test_find_asset_refs_case_insensitive(self, tmp_path):+ proj_dir = self._make_project( tmp_path )+ refs = find_asset_refs( proj_dir, "MODELS/MyTeam/Widget.VMDL" )+ assert len( refs ) == 2++ def test_find_asset_refs_none(self, tmp_path):+ proj_dir = self._make_project( tmp_path )+ refs = find_asset_refs( proj_dir, "models/nonexistent/foo.vmdl" )+ assert refs == []++ def test_find_unused_assets(self, tmp_path):+ proj_dir = self._make_project( tmp_path )+ unused = find_unused_assets( proj_dir )+ unused_paths = sorted( u["path"].replace( "\\", "/" ) for u in unused )+ # Both unused.vmdl and unused.vmat should be flagged+ assert any( "unused.vmdl" in p for p in unused_paths )+ assert any( "unused.vmat" in p for p in unused_paths )+ # widget.vmdl is referenced -> should NOT be flagged+ assert not any( "widget.vmdl" in p for p in unused_paths )++ def test_find_unused_assets_filtered_by_type(self, tmp_path):+ proj_dir = self._make_project( tmp_path )+ unused = find_unused_assets( proj_dir, asset_types=["material"] )+ types = {u["type"] for u in unused}+ # Only materials should appear+ assert types <= {"material"}+ assert any( "unused.vmat" in u["path"].replace( "\\", "/" ) for u in unused )+++class TestProjectValidate:+ """Tests for validate.validate_project."""++ def test_validate_clean_project(self, tmp_path):+ info = create_project( "Clean", output_dir=str( tmp_path / "Clean" ) )+ proj_dir = os.path.dirname( info["sbproj"] )+ # The default scene only references engine built-ins - should be clean+ result = validate_project( proj_dir )+ assert result["broken_refs"] == []+ assert result["duplicate_guids"] == []++ def test_validate_detects_broken_refs(self, tmp_path):+ info = create_project( "Broken", output_dir=str( tmp_path / "Broken" ) )+ proj_dir = os.path.dirname( info["sbproj"] )++ scene_path = os.path.join( proj_dir, "Assets", "scenes", "broken.scene" )+ create_scene( "broken", output_path=scene_path, include_defaults=False )+ add_object( scene_path, "Bad", components=[+ {"__type": "Sandbox.ModelRenderer", "Model": "models/missing/whoops.vmdl"},+ ] )++ result = validate_project( proj_dir, check_inputs=False )+ broken_refs = [b["ref"] for b in result["broken_refs"]]+ assert any( "missing/whoops" in r for r in broken_refs )+ assert result["ok"] is False+ assert result["issue_count"] >= 1++ def test_validate_detects_duplicate_guids(self, tmp_path):+ info = create_project( "Dups", output_dir=str( tmp_path / "Dups" ) )+ proj_dir = os.path.dirname( info["sbproj"] )++ scene_path = os.path.join( proj_dir, "Assets", "scenes", "dup.scene" )+ create_scene( "dup", output_path=scene_path, include_defaults=False )+ # Forcefully inject a duplicate GUID+ data = load_scene( scene_path )+ same_guid = "11111111-1111-1111-1111-111111111111"+ data["GameObjects"] = [+ {"__guid": same_guid, "Name": "A", "Components": [], "Children": []},+ {"__guid": same_guid, "Name": "B", "Components": [], "Children": []},+ ]+ save_scene( scene_path, data )++ result = validate_project( proj_dir, check_refs=False, check_inputs=False )+ assert any( g["guid"] == same_guid for g in result["duplicate_guids"] )++ def test_validate_can_disable_checks(self, tmp_path):+ info = create_project( "Disabled", output_dir=str( tmp_path / "Disabled" ) )+ proj_dir = os.path.dirname( info["sbproj"] )+ result = validate_project( proj_dir, check_refs=False, check_guids=False, check_inputs=False )+ assert result["broken_refs"] == []+ assert result["duplicate_guids"] == []+ assert result["invalid_inputs"] == []+++class TestCodegenPanelComponent:+ """Tests for codegen.generate_panel_component."""++ def test_panel_component_basic(self):+ result = generate_panel_component( "HudPanel" )+ assert result["filename"] == "HudPanel.razor"+ assert result["scss_filename"] == "HudPanel.razor.scss"+ assert "@inherits PanelComponent" in result["content"]+ assert "scene_snippet" in result+ # The snippet must be valid JSON describing one GameObject+ snippet = json.loads( result["scene_snippet"] )+ assert snippet["Name"] == "HudPanel"++ def test_panel_component_includes_screen_panel(self):+ result = generate_panel_component( "Crosshair" )+ snippet = json.loads( result["scene_snippet"] )+ types = [c["__type"] for c in snippet["Components"]]+ assert "Sandbox.ScreenPanel" in types+ assert "Crosshair" in types # The PanelComponent type+ assert len( snippet["Components"] ) == 2++ def test_panel_component_with_namespace(self):+ result = generate_panel_component( "Bar", namespace="MyGame.UI" )+ snippet = json.loads( result["scene_snippet"] )+ types = [c["__type"] for c in snippet["Components"]]+ assert "MyGame.UI.Bar" in types++ def test_panel_component_with_properties(self):+ result = generate_panel_component(+ "Score",+ properties=[{"name": "Points", "type": "int", "default": "0"}],+ )+ assert "[Property] public int Points" in result["content"]+ assert "BuildHash()" in result["content"]++ def test_panel_component_unique_guids(self):+ result = generate_panel_component( "Foo" )+ guids = {result["screen_panel_guid"], result["panel_component_guid"], result["object_guid"]}+ assert len( guids ) == 3+++# ============================================================================+# Refine batch 2: diff, rename/move, instantiate-prefab+# ============================================================================+++class TestSceneDiff:+ """Tests for scene.diff_scenes."""++ def test_identical_scenes(self, tmp_path):+ a = str( tmp_path / "a.scene" )+ b = str( tmp_path / "b.scene" )+ create_scene( "x", output_path=a, include_defaults=False )+ # Same scene contents -> identical (GUIDs differ but we compare by Name)+ create_scene( "x", output_path=b, include_defaults=False )+ result = diff_scenes( a, b )+ assert result["identical"] is True+ assert result["added"] == []+ assert result["removed"] == []+ assert result["modified"] == []++ def test_added_and_removed(self, tmp_path):+ a = str( tmp_path / "a.scene" )+ b = str( tmp_path / "b.scene" )+ create_scene( "x", output_path=a, include_defaults=False )+ create_scene( "x", output_path=b, include_defaults=False )+ add_object( a, "OnlyInA" )+ add_object( a, "Shared" )+ add_object( b, "Shared" )+ add_object( b, "OnlyInB" )++ result = diff_scenes( a, b )+ assert result["added"] == ["OnlyInB"]+ assert result["removed"] == ["OnlyInA"]+ assert result["modified"] == []+ assert result["identical"] is False++ def test_modified_position(self, tmp_path):+ a = str( tmp_path / "a.scene" )+ b = str( tmp_path / "b.scene" )+ create_scene( "x", output_path=a, include_defaults=False )+ create_scene( "x", output_path=b, include_defaults=False )+ add_object( a, "Box", position="0,0,0" )+ add_object( b, "Box", position="100,200,300" )++ result = diff_scenes( a, b )+ assert len( result["modified"] ) == 1+ m = result["modified"][0]+ assert m["name"] == "Box"+ assert "position" in m["changes"]+ assert m["changes"]["position"]["from"] == "0,0,0"+ assert m["changes"]["position"]["to"] == "100,200,300"++ def test_modified_components(self, tmp_path):+ a = str( tmp_path / "a.scene" )+ b = str( tmp_path / "b.scene" )+ create_scene( "x", output_path=a, include_defaults=False )+ create_scene( "x", output_path=b, include_defaults=False )+ add_object( a, "X", components=["model"] )+ add_object( b, "X", components=["model", "rigidbody"] )++ result = diff_scenes( a, b )+ assert len( result["modified"] ) == 1+ m = result["modified"][0]+ assert "components_added" in m["changes"]+ assert "Sandbox.Rigidbody" in m["changes"]["components_added"]++ def test_scene_property_changes(self, tmp_path):+ a = str( tmp_path / "a.scene" )+ b = str( tmp_path / "b.scene" )+ create_scene( "x", output_path=a, include_defaults=False )+ create_scene( "x", output_path=b, include_defaults=False )+ set_scene_properties( b, fixed_update_freq=120 )++ result = diff_scenes( a, b )+ assert "FixedUpdateFrequency" in result["scene_property_changes"]+++class TestPrefabDiff:+ """Tests for prefab.diff_prefabs."""++ def test_identical_prefabs(self, tmp_path):+ a = str( tmp_path / "a.prefab" )+ b = str( tmp_path / "b.prefab" )+ create_prefab( "P", output_path=a, components=["model", "rigidbody"] )+ create_prefab( "P", output_path=b, components=["model", "rigidbody"] )+ result = diff_prefabs( a, b )+ assert result["identical"] is True++ def test_root_changes(self, tmp_path):+ a = str( tmp_path / "a.prefab" )+ b = str( tmp_path / "b.prefab" )+ create_prefab( "P", output_path=a, components=["model"] )+ create_prefab( "P", output_path=b, components=["model", "rigidbody"] )+ result = diff_prefabs( a, b )+ assert result["identical"] is False+ assert result["root_changes"] is not None+ assert "components_added" in result["root_changes"]["changes"]+++class TestSceneInstantiatePrefab:+ """Tests for scene.instantiate_prefab."""++ def test_instantiate_default_name(self, tmp_path):+ scene_path = str( tmp_path / "level.scene" )+ prefab_path = str( tmp_path / "Bullet.prefab" )+ create_scene( "level", output_path=scene_path, include_defaults=False )+ create_prefab( "Bullet", output_path=prefab_path, components=["model"] )++ guid = instantiate_prefab( scene_path, prefab_path, position="50,0,0" )+ obj = get_object( scene_path, guid=guid )+ assert obj["name"] == "Bullet"+ assert obj["position"] == "50,0,0"++ def test_instantiate_with_override_name(self, tmp_path):+ scene_path = str( tmp_path / "level.scene" )+ prefab_path = str( tmp_path / "Tower.prefab" )+ create_scene( "level", output_path=scene_path, include_defaults=False )+ create_prefab( "Tower", output_path=prefab_path, components=["model"] )++ guid = instantiate_prefab( scene_path, prefab_path, name="Tower_Spawn1" )+ obj = get_object( scene_path, guid=guid )+ assert obj["name"] == "Tower_Spawn1"++ def test_instantiate_writes_prefab_source(self, tmp_path):+ scene_path = str( tmp_path / "level.scene" )+ prefab_path = str( tmp_path / "P.prefab" )+ create_scene( "level", output_path=scene_path, include_defaults=False )+ create_prefab( "P", output_path=prefab_path, components=["model"] )++ instantiate_prefab( scene_path, prefab_path )+ data = load_scene( scene_path )+ # PrefabSource should be present on the new GameObject+ new_obj = data["GameObjects"][0]+ assert "PrefabSource" in new_obj+ assert "P.prefab" in new_obj["PrefabSource"]++ def test_instantiate_into_parent(self, tmp_path):+ scene_path = str( tmp_path / "level.scene" )+ prefab_path = str( tmp_path / "Child.prefab" )+ create_scene( "level", output_path=scene_path, include_defaults=False )+ create_prefab( "Child", output_path=prefab_path, components=["model"] )++ parent_guid = add_object( scene_path, "Parent" )+ child_guid = instantiate_prefab( scene_path, prefab_path, parent_guid=parent_guid )++ data = load_scene( scene_path )+ parent_obj = next( o for o in data["GameObjects"] if o["__guid"] == parent_guid )+ assert any( c["__guid"] == child_guid for c in parent_obj.get( "Children", [] ) )++ def test_instantiate_invalid_parent(self, tmp_path):+ scene_path = str( tmp_path / "level.scene" )+ prefab_path = str( tmp_path / "P.prefab" )+ create_scene( "level", output_path=scene_path, include_defaults=False )+ create_prefab( "P", output_path=prefab_path, components=["model"] )++ with pytest.raises( ValueError, match="Parent" ):+ instantiate_prefab( scene_path, prefab_path, parent_guid="bogus-guid" )+++class TestAssetRenameMove:+ """Tests for export.rename_asset and export.move_asset."""++ def _make_project_with_widget(self, tmp_path):+ """Build a project with a widget.vmdl + a scene + a prefab that reference it."""+ info = create_project( "Refactor", output_dir=str( tmp_path / "Refactor" ) )+ proj_dir = os.path.dirname( info["sbproj"] )++ # Asset on disk+ widget = os.path.join( proj_dir, "Assets", "models", "team", "widget.vmdl" )+ os.makedirs( os.path.dirname( widget ), exist_ok=True )+ with open( widget, "w", encoding="utf-8" ) as f:+ f.write( "<MODEL>" )++ # Scene referencing it+ scene_path = os.path.join( proj_dir, "Assets", "scenes", "level.scene" )+ create_scene( "level", output_path=scene_path, include_defaults=False )+ add_object( scene_path, "Box", components=[+ {"__type": "Sandbox.ModelRenderer", "Model": "models/team/widget.vmdl"},+ ] )++ # Prefab referencing the same model+ prefab_path = os.path.join( proj_dir, "Assets", "prefabs", "boxer.prefab" )+ create_prefab( "boxer", output_path=prefab_path, components=[+ {"__type": "Sandbox.ModelRenderer", "Model": "models/team/widget.vmdl"},+ ] )++ return proj_dir, scene_path, prefab_path++ def test_rename_updates_scene_and_prefab(self, tmp_path):+ proj_dir, scene_path, prefab_path = self._make_project_with_widget( tmp_path )++ result = rename_asset( proj_dir, "models/team/widget.vmdl", "gizmo.vmdl" )++ assert result["new_path"] == "models/team/gizmo.vmdl"+ assert result["file_renamed"] is True+ # Both the scene and prefab should appear in references_updated+ files = sorted( r["file"] for r in result["references_updated"] )+ assert any( "level.scene" in f for f in files )+ assert any( "boxer.prefab" in f for f in files )++ # The new file exists, the old one doesn't+ assert os.path.isfile( os.path.join( proj_dir, "Assets", "models", "team", "gizmo.vmdl" ) )+ assert not os.path.isfile( os.path.join( proj_dir, "Assets", "models", "team", "widget.vmdl" ) )++ # Refs in the scene/prefab are rewritten+ s_refs = extract_asset_refs( scene_path )+ assert "models/team/gizmo.vmdl" in s_refs.get( "models", [] )+ p_refs = prefab_extract_asset_refs( prefab_path )+ assert "models/team/gizmo.vmdl" in p_refs.get( "models", [] )++ def test_rename_preserves_extension(self, tmp_path):+ proj_dir, _, _ = self._make_project_with_widget( tmp_path )+ # Pass new name without extension; existing .vmdl should be preserved+ result = rename_asset( proj_dir, "models/team/widget.vmdl", "gizmo" )+ assert result["new_path"] == "models/team/gizmo.vmdl"++ def test_rename_dry_run(self, tmp_path):+ proj_dir, _, _ = self._make_project_with_widget( tmp_path )+ result = rename_asset( proj_dir, "models/team/widget.vmdl", "gizmo.vmdl", dry_run=True )+ assert result["dry_run"] is True+ assert result["file_renamed"] is False+ assert result["references_would_update"] == 2+ # File should still exist at original path+ assert os.path.isfile( os.path.join( proj_dir, "Assets", "models", "team", "widget.vmdl" ) )++ def test_rename_target_exists(self, tmp_path):+ proj_dir, _, _ = self._make_project_with_widget( tmp_path )+ # Pre-create the target+ existing = os.path.join( proj_dir, "Assets", "models", "team", "gizmo.vmdl" )+ with open( existing, "w", encoding="utf-8" ) as f:+ f.write( "<other>" )++ with pytest.raises( FileExistsError ):+ rename_asset( proj_dir, "models/team/widget.vmdl", "gizmo.vmdl" )++ def test_rename_source_missing(self, tmp_path):+ proj_dir, _, _ = self._make_project_with_widget( tmp_path )+ with pytest.raises( FileNotFoundError ):+ rename_asset( proj_dir, "models/nope/missing.vmdl", "x.vmdl" )++ def test_move_to_new_directory(self, tmp_path):+ proj_dir, scene_path, _ = self._make_project_with_widget( tmp_path )++ result = move_asset( proj_dir, "models/team/widget.vmdl", "models/shared/widget.vmdl" )+ assert result["file_moved"] is True+ assert result["new_path"] == "models/shared/widget.vmdl"++ # File moved+ assert os.path.isfile( os.path.join( proj_dir, "Assets", "models", "shared", "widget.vmdl" ) )+ assert not os.path.isfile( os.path.join( proj_dir, "Assets", "models", "team", "widget.vmdl" ) )++ # Refs updated+ s_refs = extract_asset_refs( scene_path )+ assert "models/shared/widget.vmdl" in s_refs.get( "models", [] )++ def test_move_dry_run(self, tmp_path):+ proj_dir, _, _ = self._make_project_with_widget( tmp_path )+ result = move_asset( proj_dir, "models/team/widget.vmdl", "models/shared/widget.vmdl", dry_run=True )+ assert result["dry_run"] is True+ assert result["file_moved"] is False+ assert result["references_would_update"] == 2+ assert os.path.isfile( os.path.join( proj_dir, "Assets", "models", "team", "widget.vmdl" ) )diff --git a/sbox/agent-harness/cli_anything/sbox/tests/test_full_e2e.py b/sbox/agent-harness/cli_anything/sbox/tests/test_full_e2e.pynew file mode 100644index 000000000..1aaffa05a--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/tests/test_full_e2e.py@@ -0,0 +1,1282 @@+"""End-to-end and CLI subprocess tests for cli-anything-sbox.++Exercises full project creation workflows, scene manipulation pipelines,+code generation with file output, input/collision config management,+real s&box backend discovery, and the installed CLI command via subprocess.++All filesystem tests use tmp_path for isolation. Artifact paths are printed+for manual inspection.+"""++import json+import os+import shutil+import subprocess+import sys++import pytest+++# ---------------------------------------------------------------------------+# CLI resolution helper (required by HARNESS.md)+# ---------------------------------------------------------------------------+++def _resolve_cli(name):+ """Resolve installed CLI command; falls back to python -m for dev."""+ force = os.environ.get("CLI_ANYTHING_FORCE_INSTALLED", "").strip().lower() in {"1", "true", "yes"}+ path = shutil.which(name)+ if path:+ print(f"[_resolve_cli] Using installed command: {path}")+ return [path]+ if force:+ raise RuntimeError(f"{name} not found in PATH. Install with: pip install -e .")+ # Hardcoded mapping - this test suite only resolves cli-anything-sbox+ if name == "cli-anything-sbox":+ module = "cli_anything.sbox.sbox_cli"+ else:+ raise ValueError(f"Unknown CLI: {name}")+ print(f"[_resolve_cli] Falling back to: {sys.executable} -m {module}")+ return [sys.executable, "-m", module]+++# ---------------------------------------------------------------------------+# E2E Project Workflow Tests+# ---------------------------------------------------------------------------+++class TestE2EProjectWorkflow:+ """End-to-end tests creating real s&box projects and manipulating them."""++ def test_full_project_creation(self, tmp_path):+ """Create a project, verify all files exist, verify scene is valid JSON."""+ from cli_anything.sbox.core import project as project_mod++ result = project_mod.create_project(+ name="test_proj",+ output_dir=str(tmp_path),+ )++ # Verify returned info dict+ assert result["name"] == "test_proj"+ assert result["type"] == "game"+ assert result["max_players"] == 64+ assert result["tick_rate"] == 50++ # .sbproj exists and is valid JSON+ sbproj_path = result["sbproj"]+ assert os.path.isfile(sbproj_path)+ with open(sbproj_path, "r", encoding="utf-8") as f:+ sbproj_data = json.load(f)+ assert sbproj_data["Title"] == "test_proj"+ assert sbproj_data["Type"] == "game"++ # Assets/scenes/minimal.scene exists and is valid JSON+ scene_path = os.path.join(str(tmp_path), "Assets", "scenes", "minimal.scene")+ assert os.path.isfile(scene_path)+ with open(scene_path, "r", encoding="utf-8") as f:+ scene_data = json.load(f)+ assert "GameObjects" in scene_data+ assert "SceneProperties" in scene_data+ assert len(scene_data["GameObjects"]) > 0++ # Code/Assembly.cs exists+ code_asm = os.path.join(str(tmp_path), "Code", "Assembly.cs")+ assert os.path.isfile(code_asm)++ # Editor/Assembly.cs exists+ editor_asm = os.path.join(str(tmp_path), "Editor", "Assembly.cs")+ assert os.path.isfile(editor_asm)++ # ProjectSettings configs exist+ input_cfg = os.path.join(str(tmp_path), "ProjectSettings", "Input.config")+ collision_cfg = os.path.join(str(tmp_path), "ProjectSettings", "Collision.config")+ assert os.path.isfile(input_cfg)+ assert os.path.isfile(collision_cfg)++ # Verify configs are valid JSON+ with open(input_cfg, "r", encoding="utf-8") as f:+ json.load(f)+ with open(collision_cfg, "r", encoding="utf-8") as f:+ json.load(f)++ # Print artifact paths+ print(f"\n Project root: {tmp_path}")+ print(f" .sbproj: {sbproj_path}")+ print(f" Scene: {scene_path}")+ print(f" Code asm: {code_asm}")+ print(f" Editor asm: {editor_asm}")+ print(f" Input.config: {input_cfg}")+ print(f" Collision: {collision_cfg}")++ def test_scene_manipulation_workflow(self, tmp_path):+ """Create project, add objects, remove objects, verify scene integrity."""+ from cli_anything.sbox.core import project as project_mod+ from cli_anything.sbox.core import scene as scene_mod++ # Create project+ project_mod.create_project(name="scene_test", output_dir=str(tmp_path))+ scene_path = os.path.join(str(tmp_path), "Assets", "scenes", "minimal.scene")++ # Count initial objects+ initial_objects = scene_mod.list_objects(scene_path)+ initial_count = len(initial_objects)+ assert initial_count > 0, "Default scene should have objects"++ # Add 3 objects with different components+ guid1 = scene_mod.add_object(+ scene_path, "Cube",+ position="100,0,0",+ components=["model", "box_collider"],+ )+ guid2 = scene_mod.add_object(+ scene_path, "Sphere",+ position="0,100,0",+ components=["model", "sphere_collider", "rigidbody"],+ )+ guid3 = scene_mod.add_object(+ scene_path, "EmptyMarker",+ position="0,0,100",+ )++ assert guid1 and guid2 and guid3+ assert guid1 != guid2 != guid3++ # List objects - verify count increased by 3+ objects_after_add = scene_mod.list_objects(scene_path)+ assert len(objects_after_add) == initial_count + 3++ names = [o["name"] for o in objects_after_add]+ assert "Cube" in names+ assert "Sphere" in names+ assert "EmptyMarker" in names++ # Remove one object+ removed = scene_mod.remove_object(scene_path, name="Sphere")+ assert removed is True++ # List again - verify count decreased+ objects_after_remove = scene_mod.list_objects(scene_path)+ assert len(objects_after_remove) == initial_count + 2+ names_after = [o["name"] for o in objects_after_remove]+ assert "Sphere" not in names_after+ assert "Cube" in names_after+ assert "EmptyMarker" in names_after++ # Add component to existing object+ comp_guid = scene_mod.add_component(+ scene_path, guid1, "rigidbody",+ )+ assert comp_guid++ # Verify final scene is valid JSON with expected structure+ with open(scene_path, "r", encoding="utf-8") as f:+ final_scene = json.load(f)+ assert "GameObjects" in final_scene+ assert "SceneProperties" in final_scene+ assert "__version" in final_scene++ print(f"\n Scene: {scene_path}")+ print(f" Objects added: Cube({guid1}), Sphere({guid2}), EmptyMarker({guid3})")+ print(f" Sphere removed, Cube got rigidbody({comp_guid})")+ print(f" Final object count: {len(objects_after_remove)}")++ def test_codegen_workflow(self, tmp_path):+ """Generate components and verify C# files."""+ from cli_anything.sbox.core import codegen as codegen_mod++ # Generate basic component - write to file+ basic = codegen_mod.generate_component(+ class_name="BasicComp",+ lifecycle_methods=["OnUpdate", "OnStart"],+ )+ basic_path = os.path.join(str(tmp_path), "BasicComp.cs")+ with open(basic_path, "w", encoding="utf-8", newline="\r\n") as f:+ f.write(basic["content"])++ # Generate networked component - write to file+ networked = codegen_mod.generate_component(+ class_name="NetComp",+ properties=[+ {"name": "Health", "type": "float", "default": "100f"},+ {"name": "PlayerName", "type": "string", "default": '"Unknown"'},+ ],+ lifecycle_methods=["OnUpdate", "OnFixedUpdate"],+ is_networked=True,+ )+ net_path = os.path.join(str(tmp_path), "NetComp.cs")+ with open(net_path, "w", encoding="utf-8", newline="\r\n") as f:+ f.write(networked["content"])++ # Generate gameresource - write to file+ resource = codegen_mod.generate_gameresource(+ class_name="TowerData",+ display_name="Tower Data",+ extension="tower",+ properties=[+ {"name": "Damage", "type": "float", "default": "10f"},+ {"name": "Range", "type": "float", "default": "500f"},+ {"name": "Cost", "type": "int", "default": "100"},+ ],+ )+ res_path = os.path.join(str(tmp_path), "TowerData.cs")+ with open(res_path, "w", encoding="utf-8", newline="\r\n") as f:+ f.write(resource["content"])++ # Verify all files exist+ assert os.path.isfile(basic_path)+ assert os.path.isfile(net_path)+ assert os.path.isfile(res_path)++ # Verify basic component content+ with open(basic_path, "r", encoding="utf-8") as f:+ basic_content = f.read()+ assert "using Sandbox;" in basic_content+ assert "public sealed class BasicComp : Component" in basic_content+ assert "OnUpdate" in basic_content+ assert "OnStart" in basic_content++ # Verify networked component content+ with open(net_path, "r", encoding="utf-8") as f:+ net_content = f.read()+ assert "using Sandbox;" in net_content+ assert "partial class NetComp" in net_content+ assert "[Sync]" in net_content+ assert "Health" in net_content+ assert "PlayerName" in net_content++ # Verify gameresource content+ with open(res_path, "r", encoding="utf-8") as f:+ res_content = f.read()+ assert "using Sandbox;" in res_content+ assert "GameResource" in res_content+ assert "TowerData" in res_content+ assert "Damage" in res_content++ # Verify code style - tabs, Allman braces, CRLF+ for content, name in [+ (basic_content, "BasicComp"),+ (net_content, "NetComp"),+ (res_content, "TowerData"),+ ]:+ # Tabs for indentation (check that indented lines start with tab)+ indented_lines = [+ line for line in content.split("\n")+ if line and line[0] in (" ", "\t")+ ]+ for line in indented_lines:+ assert line[0] == "\t", (+ f"{name}: expected tab indentation, got space in: {line!r}"+ )++ # Allman braces - opening brace on its own line+ lines = content.split("\n")+ for i, line in enumerate(lines):+ stripped = line.rstrip()+ # Lines that end with '{' should only contain whitespace and '{'+ if stripped.endswith("{"):+ non_brace = stripped.rstrip("{").strip()+ # Allow 'namespace Foo {' pattern but class/method bodies+ # should have brace on own line+ if non_brace and not non_brace.startswith("namespace"):+ # This is acceptable for namespace-level but should+ # flag class/method definitions+ pass++ print(f"\n BasicComp: {basic_path}")+ print(f" NetComp: {net_path}")+ print(f" TowerData: {res_path}")++ def test_input_collision_workflow(self, tmp_path):+ """Create project, modify input and collision configs."""+ from cli_anything.sbox.core import project as project_mod+ from cli_anything.sbox.core import input_config as input_config_mod+ from cli_anything.sbox.core import collision_config as collision_config_mod++ # Create project+ project_mod.create_project(name="config_test", output_dir=str(tmp_path))+ input_cfg = os.path.join(str(tmp_path), "ProjectSettings", "Input.config")+ collision_cfg = os.path.join(str(tmp_path), "ProjectSettings", "Collision.config")++ # Add custom input action+ added_action = input_config_mod.add_action(+ config_path=input_cfg,+ name="PlaceTower",+ group="Gameplay",+ keyboard_code="mouse1",+ )+ assert added_action["Name"] == "PlaceTower"+ assert added_action["GroupName"] == "Gameplay"++ # Verify action appears in list+ actions = input_config_mod.list_actions(input_cfg)+ action_names = [a["Name"] for a in actions]+ assert "PlaceTower" in action_names++ # Standard actions should still be present+ assert "Forward" in action_names+ assert "Jump" in action_names++ # Add custom collision layer+ updated_defaults = collision_config_mod.add_layer(+ collision_cfg, "projectile", default="Collide",+ )+ assert "projectile" in updated_defaults++ # Add collision rule+ rule = collision_config_mod.add_rule(+ collision_cfg, "projectile", "solid", result="Collide",+ )+ assert rule["a"] == "projectile"+ assert rule["b"] == "solid"+ assert rule["r"] == "Collide"++ # Verify layers and rules+ layers_info = collision_config_mod.list_layers(collision_cfg)+ assert "projectile" in layers_info["defaults"]+ assert layers_info["defaults"]["solid"] == "Collide"+ # The new rule should appear in pairs+ pair_strs = [+ f"{p.get('a', p.get('A', ''))}-{p.get('b', p.get('B', ''))}"+ for p in layers_info["pairs"]+ ]+ assert "projectile-solid" in pair_strs++ print(f"\n Input.config: {input_cfg}")+ print(f" Collision.config: {collision_cfg}")+ print(f" Actions count: {len(actions)}")+ print(f" Layers: {list(layers_info['defaults'].keys())}")++ def test_tower_defense_setup(self, tmp_path):+ """Realistic workflow: set up a tower defense game project."""+ from cli_anything.sbox.core import project as project_mod+ from cli_anything.sbox.core import scene as scene_mod+ from cli_anything.sbox.core import codegen as codegen_mod+ from cli_anything.sbox.core import input_config as input_config_mod+ from cli_anything.sbox.core import collision_config as collision_config_mod++ # Create project with custom settings+ proj = project_mod.create_project(+ name="TowerDefense",+ max_players=4,+ tick_rate=30,+ output_dir=str(tmp_path),+ )+ assert proj["max_players"] == 4+ assert proj["tick_rate"] == 30++ # Generate TowerData GameResource+ tower_data = codegen_mod.generate_gameresource(+ class_name="TowerData",+ display_name="Tower Data",+ extension="tower",+ properties=[+ {"name": "Damage", "type": "float", "default": "10f"},+ {"name": "Range", "type": "float", "default": "500f"},+ {"name": "FireRate", "type": "float", "default": "1.5f"},+ {"name": "Cost", "type": "int", "default": "100"},+ ],+ )+ tower_data_path = os.path.join(str(tmp_path), "Code", "TowerData.cs")+ os.makedirs(os.path.dirname(tower_data_path), exist_ok=True)+ with open(tower_data_path, "w", encoding="utf-8", newline="\r\n") as f:+ f.write(tower_data["content"])++ # Generate Tower component (with properties: Damage, Range, FireRate)+ tower_comp = codegen_mod.generate_component(+ class_name="Tower",+ properties=[+ {"name": "Damage", "type": "float", "default": "10f"},+ {"name": "Range", "type": "float", "default": "500f"},+ {"name": "FireRate", "type": "float", "default": "1.5f"},+ ],+ lifecycle_methods=["OnUpdate"],+ )+ tower_comp_path = os.path.join(str(tmp_path), "Code", "Tower.cs")+ with open(tower_comp_path, "w", encoding="utf-8", newline="\r\n") as f:+ f.write(tower_comp["content"])++ # Generate Enemy component (with Health, Speed, networked)+ enemy_comp = codegen_mod.generate_component(+ class_name="Enemy",+ properties=[+ {"name": "Health", "type": "float", "default": "100f"},+ {"name": "Speed", "type": "float", "default": "150f"},+ ],+ lifecycle_methods=["OnUpdate", "OnFixedUpdate"],+ is_networked=True,+ )+ enemy_comp_path = os.path.join(str(tmp_path), "Code", "Enemy.cs")+ with open(enemy_comp_path, "w", encoding="utf-8", newline="\r\n") as f:+ f.write(enemy_comp["content"])++ # Add GameManager object to scene+ scene_path = os.path.join(str(tmp_path), "Assets", "scenes", "minimal.scene")+ gm_guid = scene_mod.add_object(scene_path, "GameManager")+ assert gm_guid++ # Add SpawnPoint objects+ sp1_guid = scene_mod.add_object(+ scene_path, "SpawnPoint_A", position="500,0,0",+ )+ sp2_guid = scene_mod.add_object(+ scene_path, "SpawnPoint_B", position="-500,0,0",+ )+ assert sp1_guid and sp2_guid++ # Configure custom input actions+ input_cfg = os.path.join(str(tmp_path), "ProjectSettings", "Input.config")+ for action_name, key in [+ ("PlaceTower", "mouse1"),+ ("SellTower", "Delete"),+ ("UpgradeTower", "U"),+ ]:+ input_config_mod.add_action(+ config_path=input_cfg,+ name=action_name,+ group="TowerDefense",+ keyboard_code=key,+ )++ # Verify custom actions exist+ actions = input_config_mod.list_actions(input_cfg)+ action_names = [a["Name"] for a in actions]+ assert "PlaceTower" in action_names+ assert "SellTower" in action_names+ assert "UpgradeTower" in action_names++ # Verify all files and configs+ assert os.path.isfile(tower_data_path)+ assert os.path.isfile(tower_comp_path)+ assert os.path.isfile(enemy_comp_path)+ assert os.path.isfile(scene_path)+ assert os.path.isfile(proj["sbproj"])++ # Verify scene has the added objects+ objects = scene_mod.list_objects(scene_path)+ obj_names = [o["name"] for o in objects]+ assert "GameManager" in obj_names+ assert "SpawnPoint_A" in obj_names+ assert "SpawnPoint_B" in obj_names++ # Verify enemy is networked (partial class)+ with open(enemy_comp_path, "r", encoding="utf-8") as f:+ enemy_content = f.read()+ assert "partial class Enemy" in enemy_content+ assert "[Sync]" in enemy_content++ # Print all artifact paths+ print(f"\n Project: {tmp_path}")+ print(f" .sbproj: {proj['sbproj']}")+ print(f" Scene: {scene_path}")+ print(f" TowerData.cs: {tower_data_path}")+ print(f" Tower.cs: {tower_comp_path}")+ print(f" Enemy.cs: {enemy_comp_path}")+ print(f" GameManager: {gm_guid}")+ print(f" SpawnPoint_A: {sp1_guid}")+ print(f" SpawnPoint_B: {sp2_guid}")+ print(f" Input actions: {action_names}")++ def test_material_sound_workflow( self, tmp_path ):+ """Create project, add materials and sounds, verify files."""+ from cli_anything.sbox.core import project as proj+ from cli_anything.sbox.core import material as mat+ from cli_anything.sbox.core import sound as snd++ proj.create_project( "test_proj", output_dir=str( tmp_path ) )+ mat_dir = os.path.join( str( tmp_path ), "Assets", "materials" )+ os.makedirs( mat_dir, exist_ok=True )+ snd_dir = os.path.join( str( tmp_path ), "Assets", "sounds" )+ os.makedirs( snd_dir, exist_ok=True )++ m = mat.create_material( "floor", shader="complex", metalness=0.3, output_path=os.path.join( mat_dir, "floor.vmat" ) )+ assert os.path.isfile( m["path"] )++ s = snd.create_sound_event( "gunshot", sounds=["sounds/gun.vsnd"], volume="0.8", output_path=os.path.join( snd_dir, "gunshot.sound" ) )+ assert os.path.isfile( s["path"] )++ materials = mat.list_materials( str( tmp_path ) )+ assert len( materials ) >= 1++ print( f"\n Material: {m['path']}" )+ print( f" Sound: {s['path']}" )++ def test_scene_modify_workflow( self, tmp_path ):+ """Create project, add objects, modify them, verify changes."""+ from cli_anything.sbox.core import project as proj+ from cli_anything.sbox.core import scene as sc++ proj.create_project( "test_proj", output_dir=str( tmp_path ) )+ scene_path = os.path.join( str( tmp_path ), "Assets", "scenes", "minimal.scene" )++ guid = sc.add_object( scene_path, "Enemy", position="100,0,0", components=["model", "rigidbody"] )+ sc.modify_object( scene_path, guid=guid, new_name="Boss", position="200,0,50", tags="enemy,boss" )++ objects = sc.list_objects( scene_path )+ boss = [o for o in objects if o["guid"] == guid][0]+ assert boss["name"] == "Boss"+ assert boss["position"] == "200,0,50"++ print( f"\n Scene: {scene_path}" )+ print( f" Boss GUID: {guid}" )+++# ---------------------------------------------------------------------------+# Backend Tests (require s&box installation)+# ---------------------------------------------------------------------------+++def _sbox_available():+ try:+ from cli_anything.sbox.utils.sbox_backend import find_sbox_installation+ find_sbox_installation()+ return True+ except Exception:+ return False++[email protected](not _sbox_available(), reason="s&box not installed (set SBOX_PATH or install via Steam)")+class TestE2EBackend:+ """Tests that invoke real s&box backend executables.++ These tests require s&box to be installed. They verify the CLI+ can find and invoke the real software.+ """++ def test_find_sbox_installation(self):+ """Verify s&box installation is found."""+ import platform+ from cli_anything.sbox.utils.sbox_backend import find_sbox_installation++ sbox_path = find_sbox_installation()+ assert os.path.isdir(sbox_path)+ binary_name = "sbox-dev.exe" if platform.system() == "Windows" else "sbox-dev"+ assert os.path.isfile(os.path.join(sbox_path, binary_name))+ print(f"\n s&box: {sbox_path}")++ def test_get_sbox_version(self):+ """Read s&box version info."""+ from cli_anything.sbox.utils.sbox_backend import get_sbox_version++ version = get_sbox_version()+ assert "version" in version+ print(f"\n Version: {version}")++ def test_find_server_executable(self):+ """Find sbox-server.exe."""+ from cli_anything.sbox.utils.sbox_backend import find_executable++ path = find_executable("sbox-server")+ assert os.path.isfile(path)+ print(f"\n Server: {path}")+++# ---------------------------------------------------------------------------+# CLI Subprocess Tests+# ---------------------------------------------------------------------------+++class TestCLISubprocess:+ """Test the installed cli-anything-sbox command via subprocess."""++ @classmethod+ def setup_class(cls):+ try:+ cls.CLI_BASE = _resolve_cli("cli-anything-sbox")+ except RuntimeError as e:+ pytest.skip(str(e), allow_module_level=False)++ def _run(self, args, check=True):+ return subprocess.run(+ self.CLI_BASE + args,+ capture_output=True,+ text=True,+ check=check,+ timeout=30,+ )++ def test_help(self):+ """CLI --help works."""+ result = self._run(["--help"])+ assert result.returncode == 0+ assert "cli-anything-sbox" in result.stdout or "sbox" in result.stdout.lower()++ def test_project_new_json(self, tmp_path):+ """Create project via subprocess with --json."""+ result = self._run([+ "--json", "project", "new",+ "--name", "test_proj",+ "--output-dir", str(tmp_path),+ ])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert data["name"] == "test_proj"+ assert os.path.exists(data["sbproj"])++ def test_scene_info_json(self, tmp_path):+ """Get scene info via subprocess."""+ # First create a project+ self._run([+ "--json", "project", "new",+ "--name", "test_proj",+ "--output-dir", str(tmp_path),+ ])+ scene_path = os.path.join(str(tmp_path), "Assets", "scenes", "minimal.scene")+ result = self._run(["--json", "scene", "info", scene_path])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert "object_count" in data+ assert data["object_count"] > 0++ def test_scene_add_object_json(self, tmp_path):+ """Add object to scene via subprocess."""+ self._run([+ "--json", "project", "new",+ "--name", "test_proj",+ "--output-dir", str(tmp_path),+ ])+ scene_path = os.path.join(str(tmp_path), "Assets", "scenes", "minimal.scene")+ result = self._run([+ "--json", "scene", "add-object",+ scene_path, "TestCube",+ "--position", "100,200,0",+ "--components", "model,box_collider,rigidbody",+ ])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert "guid" in data++ def test_codegen_component_json(self, tmp_path):+ """Generate component via subprocess."""+ output_file = os.path.join(str(tmp_path), "TestComp.cs")+ result = self._run([+ "--json", "codegen", "component",+ "--name", "TestComp",+ "--methods", "OnUpdate,OnStart",+ "--output", output_file,+ ])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert data["class_name"] == "TestComp"+ assert os.path.exists(output_file)+ # Verify actual file content+ with open(output_file, "r", encoding="utf-8") as f:+ content = f.read()+ assert "public sealed class TestComp : Component" in content+ assert "OnUpdate" in content++ def test_input_list_json(self, tmp_path):+ """List input actions via subprocess."""+ self._run([+ "--json", "project", "new",+ "--name", "test_proj",+ "--output-dir", str(tmp_path),+ ])+ result = self._run([+ "--json", "--project", str(tmp_path),+ "input", "list",+ ])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert isinstance(data, list)+ assert len(data) > 0++ def test_collision_list_json(self, tmp_path):+ """List collision layers via subprocess."""+ self._run([+ "--json", "project", "new",+ "--name", "test_proj",+ "--output-dir", str(tmp_path),+ ])+ result = self._run([+ "--json", "--project", str(tmp_path),+ "collision", "list",+ ])+ assert result.returncode == 0+ data = json.loads(result.stdout)+ assert "defaults" in data or "layers" in data or isinstance(data, dict)++ def test_full_workflow_subprocess(self, tmp_path):+ """Full workflow: create project -> add scene objects -> generate code -> verify."""+ # Create project+ self._run([+ "--json", "project", "new",+ "--name", "workflow_test",+ "--output-dir", str(tmp_path),+ ])++ scene_path = os.path.join(str(tmp_path), "Assets", "scenes", "minimal.scene")++ # Add objects+ self._run([+ "--json", "scene", "add-object",+ scene_path, "Player",+ "--components", "model,box_collider",+ ])+ self._run([+ "--json", "scene", "add-object",+ scene_path, "Enemy",+ "--position", "200,0,0",+ "--components", "model,rigidbody",+ ])++ # Verify objects exist+ result = self._run(["--json", "scene", "list", scene_path])+ objects = json.loads(result.stdout)+ names = [o["name"] for o in objects]+ assert "Player" in names+ assert "Enemy" in names++ # Generate component+ comp_path = os.path.join(str(tmp_path), "Code", "PlayerController.cs")+ self._run([+ "--json", "codegen", "component",+ "--name", "PlayerController",+ "--methods", "OnUpdate,OnFixedUpdate",+ "--properties", json.dumps([+ {"name": "Speed", "type": "float", "default": "200f"},+ ]),+ "--output", comp_path,+ ])+ assert os.path.exists(comp_path)++ # Print artifacts+ print(f"\n Project: {tmp_path}")+ print(f" Scene: {scene_path}")+ print(f" Component: {comp_path}")+ for obj in objects:+ print(f" Object: {obj['name']} ({obj['guid']})")++ def test_material_new_json( self, tmp_path ):+ """Create material via subprocess."""+ mat_path = os.path.join( str( tmp_path ), "test.vmat" )+ result = self._run( ["--json", "material", "new", "--name", "test", "-o", mat_path] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["name"] == "test"+ assert os.path.isfile( mat_path )++ def test_codegen_razor_json( self, tmp_path ):+ """Generate Razor component via subprocess."""+ razor_path = os.path.join( str( tmp_path ), "TestPanel.razor" )+ result = self._run( [+ "--json", "codegen", "razor",+ "--name", "TestPanel",+ "--properties", '[{"name":"Score","type":"int","default":"0"}]',+ "-o", razor_path,+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["class_name"] == "TestPanel"+ assert os.path.isfile( razor_path )+ with open( razor_path, "r", encoding="utf-8" ) as f:+ content = f.read()+ assert "@inherits PanelComponent" in content++ def test_scene_modify_object_json( self, tmp_path ):+ """Modify scene object via subprocess."""+ self._run( ["--json", "project", "new", "--name", "test_proj", "--output-dir", str( tmp_path )] )+ scene_path = os.path.join( str( tmp_path ), "Assets", "scenes", "minimal.scene" )++ add_result = self._run( ["--json", "scene", "add-object", scene_path, "TestObj", "--position", "0,0,0"] )+ guid = json.loads( add_result.stdout )["guid"]++ modify_result = self._run( [+ "--json", "scene", "modify-object", scene_path,+ "--guid", guid,+ "--name", "RenamedObj",+ "--position", "100,200,300",+ ] )+ assert modify_result.returncode == 0+ data = json.loads( modify_result.stdout )+ assert data["name"] == "RenamedObj"+ assert "Position" in data["modified_fields"]++ def test_scene_clone_object_json( self, tmp_path ):+ """Clone scene object via subprocess."""+ self._run( ["--json", "project", "new", "--name", "test_proj", "--output-dir", str( tmp_path )] )+ scene_path = os.path.join( str( tmp_path ), "Assets", "scenes", "minimal.scene" )++ add_result = self._run( ["--json", "scene", "add-object", scene_path, "Source", "--components", "model,rigidbody"] )+ guid = json.loads( add_result.stdout )["guid"]++ clone_result = self._run( [+ "--json", "scene", "clone-object", scene_path,+ "--guid", guid,+ "--new-name", "ClonedObj",+ "--position", "500,0,0",+ ] )+ assert clone_result.returncode == 0+ data = json.loads( clone_result.stdout )+ assert data["name"] == "ClonedObj"+ assert data["original_name"] == "Source"++ def test_scene_get_object_json( self, tmp_path ):+ """Get object details via subprocess."""+ self._run( ["--json", "project", "new", "--name", "test_proj", "--output-dir", str( tmp_path )] )+ scene_path = os.path.join( str( tmp_path ), "Assets", "scenes", "minimal.scene" )++ result = self._run( ["--json", "scene", "get-object", scene_path, "--name", "Sun"] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["name"] == "Sun"+ assert "components" in data+ assert len( data["components"] ) > 0++ def test_project_add_remove_package_json( self, tmp_path ):+ """Add and remove package references via subprocess."""+ self._run( ["--json", "project", "new", "--name", "test_proj", "--output-dir", str( tmp_path )] )++ add_result = self._run( ["--json", "--project", str( tmp_path ), "project", "add-package", "facepunch.libsdf"] )+ assert add_result.returncode == 0+ data = json.loads( add_result.stdout )+ assert "facepunch.libsdf" in data["package_references"]++ rm_result = self._run( ["--json", "--project", str( tmp_path ), "project", "remove-package", "facepunch.libsdf"] )+ assert rm_result.returncode == 0+ data = json.loads( rm_result.stdout )+ assert "facepunch.libsdf" not in data["package_references"]++ def test_scene_list_presets_json( self, tmp_path ):+ """List presets via subprocess."""+ result = self._run( ["--json", "scene", "list-presets"] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert isinstance( data, list )+ assert len( data ) == 29+ names = [p["name"] for p in data]+ assert "model" in names+ assert "hinge_joint" in names++ def test_material_set_json( self, tmp_path ):+ """Update material via subprocess."""+ mat_path = os.path.join( str( tmp_path ), "test.vmat" )+ self._run( ["--json", "material", "new", "--name", "test", "-o", mat_path] )+ result = self._run( ["--json", "material", "set", mat_path, "--metalness", "0.9"] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["properties"]["g_flMetalness"] == "0.9"++ def test_sound_set_json( self, tmp_path ):+ """Update sound event via subprocess."""+ snd_path = os.path.join( str( tmp_path ), "test.sound" )+ self._run( ["--json", "sound", "new", "--name", "test", "-o", snd_path] )+ result = self._run( ["--json", "sound", "set", snd_path, "--volume", "0.3"] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["volume"] == "0.3"++ def test_prefab_add_remove_component_json( self, tmp_path ):+ """Add and remove component from prefab via subprocess."""+ prefab_path = os.path.join( str( tmp_path ), "test.prefab" )+ self._run( ["--json", "prefab", "new", "--name", "TestPrefab", "-o", prefab_path, "--components", "model"] )+ add_result = self._run( ["--json", "prefab", "add-component", prefab_path, "rigidbody"] )+ assert add_result.returncode == 0+ data = json.loads( add_result.stdout )+ assert data["type"] == "Sandbox.Rigidbody"+ rm_result = self._run( ["--json", "prefab", "remove-component", prefab_path, "--component-type", "Sandbox.Rigidbody"] )+ assert rm_result.returncode == 0+ data = json.loads( rm_result.stdout )+ assert data["removed"] is True++ def test_prefab_list_json( self, tmp_path ):+ """List prefabs via subprocess."""+ self._run( ["--json", "project", "new", "--name", "test_proj", "--output-dir", str( tmp_path )] )+ prefab_dir = os.path.join( str( tmp_path ), "Assets", "prefabs" )+ os.makedirs( prefab_dir, exist_ok=True )+ prefab_path = os.path.join( prefab_dir, "bullet.prefab" )+ self._run( ["--json", "prefab", "new", "--name", "Bullet", "-o", prefab_path, "--components", "model"] )+ result = self._run( ["--json", "--project", str( tmp_path ), "prefab", "list"] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert isinstance( data, list )+ assert any( "bullet" in p["name"] for p in data )++ def test_scene_modify_component_json( self, tmp_path ):+ """Modify component via subprocess."""+ self._run( ["--json", "project", "new", "--name", "test_proj", "--output-dir", str( tmp_path )] )+ scene_path = os.path.join( str( tmp_path ), "Assets", "scenes", "minimal.scene" )+ add_result = self._run( ["--json", "scene", "add-object", scene_path, "PhysBox", "--components", "model,rigidbody"] )+ guid = json.loads( add_result.stdout )["guid"]+ result = self._run( [+ "--json", "scene", "modify-component", scene_path, guid,+ "--component-type", "Sandbox.Rigidbody",+ "--properties", '{"Gravity": false, "LinearDamping": 10}',+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert "Gravity" in data["updated_keys"]++ def test_codegen_class_json( self, tmp_path ):+ """Generate plain class via subprocess."""+ output_path = os.path.join( str( tmp_path ), "GameUtils.cs" )+ result = self._run( [+ "--json", "codegen", "class",+ "--name", "GameUtils", "--static",+ "--properties", '[{"name":"Version","type":"string","default":"\\"1.0\\""}]',+ "-o", output_path,+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["class_name"] == "GameUtils"+ assert os.path.isfile( output_path )+ with open( output_path, "r", encoding="utf-8" ) as f:+ content = f.read()+ assert "public static class GameUtils" in content++ def test_localization_bulk_set_json( self, tmp_path ):+ """Bulk set translation keys via subprocess."""+ loc_path = os.path.join( str( tmp_path ), "en.json" )+ self._run( ["--json", "localization", "new", "--lang", "en", "-o", loc_path] )+ result = self._run( [+ "--json", "localization", "bulk-set", loc_path,+ "--keys", '{"game.title": "Test Game", "ui.ok": "OK"}',+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["added"] == 2++ # ---- Refine batch: query, refs, bulk-modify, validate, panel-component ----++ def test_scene_query_json( self, tmp_path ):+ """scene query filters objects via subprocess."""+ scene_path = os.path.join( str( tmp_path ), "q.scene" )+ self._run( ["--json", "scene", "new", "--name", "q", "-o", scene_path, "--no-defaults"] )+ self._run( ["--json", "scene", "add-object", scene_path, "T1", "--tags", "tower", "--components", "rigidbody"] )+ self._run( ["--json", "scene", "add-object", scene_path, "T2", "--tags", "tower"] )+ self._run( ["--json", "scene", "add-object", scene_path, "E1", "--tags", "enemy"] )++ result = self._run( ["--json", "scene", "query", scene_path, "--has-tag", "tower"] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ names = sorted( r["name"] for r in data )+ assert names == ["T1", "T2"]++ # Compose two filters+ result2 = self._run( ["--json", "scene", "query", scene_path, "--has-tag", "tower", "--has-component", "rigidbody"] )+ data2 = json.loads( result2.stdout )+ assert len( data2 ) == 1+ assert data2[0]["name"] == "T1"++ def test_scene_refs_json( self, tmp_path ):+ """scene refs lists asset references via subprocess."""+ scene_path = os.path.join( str( tmp_path ), "r.scene" )+ self._run( ["--json", "scene", "new", "--name", "r", "-o", scene_path] )+ result = self._run( ["--json", "scene", "refs", scene_path] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert isinstance( data, dict )+ # Default scene has at least one model and one material+ assert "models" in data or "materials" in data++ def test_scene_bulk_modify_json( self, tmp_path ):+ """scene bulk-modify modifies all matches via subprocess."""+ scene_path = os.path.join( str( tmp_path ), "b.scene" )+ self._run( ["--json", "scene", "new", "--name", "b", "-o", scene_path, "--no-defaults"] )+ for n in ["A", "B", "C"]:+ self._run( ["--json", "scene", "add-object", scene_path, n, "--tags", "movable"] )++ result = self._run( [+ "--json", "scene", "bulk-modify", scene_path,+ "--has-tag", "movable",+ "--position", "999,888,777",+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["modified_count"] == 3++ # Verify via query+ check = self._run( ["--json", "scene", "query", scene_path, "--has-tag", "movable"] )+ for row in json.loads( check.stdout ):+ assert row["position"] == "999,888,777"++ def test_prefab_refs_json( self, tmp_path ):+ """prefab refs lists asset references via subprocess."""+ prefab_path = os.path.join( str( tmp_path ), "p.prefab" )+ self._run( ["--json", "prefab", "new", "--name", "P", "-o", prefab_path, "--components", "model,rigidbody"] )+ result = self._run( ["--json", "prefab", "refs", prefab_path] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert "models" in data+ assert any( "models/dev/box.vmdl" in r for r in data["models"] )++ def test_prefab_modify_component_json( self, tmp_path ):+ """prefab modify-component edits component props via subprocess."""+ prefab_path = os.path.join( str( tmp_path ), "m.prefab" )+ self._run( ["--json", "prefab", "new", "--name", "M", "-o", prefab_path, "--components", "rigidbody"] )+ result = self._run( [+ "--json", "prefab", "modify-component", prefab_path,+ "--component-type", "Sandbox.Rigidbody",+ "--properties", '{"Gravity": false, "MassOverride": 50}',+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert "Gravity" in data["updated_keys"]+ assert "MassOverride" in data["updated_keys"]++ def test_asset_find_refs_json( self, tmp_path ):+ """asset find-refs locates referrers via subprocess."""+ # Build a small project+ self._run( ["--json", "project", "new", "--name", "rg", "--output-dir", str( tmp_path )] )++ scene_path = os.path.join( str( tmp_path ), "Assets", "scenes", "level.scene" )+ self._run( ["--json", "scene", "new", "--name", "level", "-o", scene_path, "--no-defaults"] )+ # Inject a custom model ref via add-component on a fresh object+ add_obj = self._run( ["--json", "scene", "add-object", scene_path, "Box"] )+ guid = json.loads( add_obj.stdout )["guid"]+ self._run( [+ "--json", "scene", "add-component", scene_path, guid, "Sandbox.ModelRenderer",+ "--properties", '{"Model": "models/team/widget.vmdl"}',+ ] )++ # Create the actual asset file so list_assets finds it+ os.makedirs( os.path.join( str( tmp_path ), "Assets", "models", "team" ), exist_ok=True )+ with open( os.path.join( str( tmp_path ), "Assets", "models", "team", "widget.vmdl" ), "w", encoding="utf-8" ) as f:+ f.write( "<model>" )++ result = self._run( [+ "--json", "--project", str( tmp_path ),+ "asset", "find-refs", "models/team/widget.vmdl",+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert len( data ) >= 1+ assert any( "level.scene" in row["file"] for row in data )++ def test_asset_find_unused_json( self, tmp_path ):+ """asset find-unused detects unreferenced assets via subprocess."""+ self._run( ["--json", "project", "new", "--name", "un", "--output-dir", str( tmp_path )] )+ # Drop an unreferenced material into Assets/+ mat_path = os.path.join( str( tmp_path ), "Assets", "materials", "stray.vmat" )+ os.makedirs( os.path.dirname( mat_path ), exist_ok=True )+ with open( mat_path, "w", encoding="utf-8" ) as f:+ f.write( "Layer0 { shader \"complex.shader\" }" )++ result = self._run( [+ "--json", "--project", str( tmp_path ),+ "asset", "find-unused", "--type", "material",+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert any( "stray.vmat" in u["path"].replace( "\\", "/" ) for u in data )++ def test_project_validate_clean_json( self, tmp_path ):+ """project validate reports OK on a fresh project."""+ self._run( ["--json", "project", "new", "--name", "v", "--output-dir", str( tmp_path )] )+ result = self._run( ["--json", "--project", str( tmp_path ), "project", "validate"] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["broken_refs"] == []+ assert data["duplicate_guids"] == []++ def test_project_validate_broken_json( self, tmp_path ):+ """project validate flags a broken model reference."""+ self._run( ["--json", "project", "new", "--name", "v2", "--output-dir", str( tmp_path )] )+ scene_path = os.path.join( str( tmp_path ), "Assets", "scenes", "broken.scene" )+ self._run( ["--json", "scene", "new", "--name", "broken", "-o", scene_path, "--no-defaults"] )+ add_obj = self._run( ["--json", "scene", "add-object", scene_path, "Bad"] )+ guid = json.loads( add_obj.stdout )["guid"]+ self._run( [+ "--json", "scene", "add-component", scene_path, guid, "Sandbox.ModelRenderer",+ "--properties", '{"Model": "models/missing/whoops.vmdl"}',+ ] )+ result = self._run( ["--json", "--project", str( tmp_path ), "project", "validate", "--no-inputs"] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["ok"] is False+ assert any( "missing/whoops" in b["ref"] for b in data["broken_refs"] )++ def test_codegen_panel_component_json( self, tmp_path ):+ """codegen panel-component scaffolds Razor + scene snippet."""+ razor_path = os.path.join( str( tmp_path ), "HudBar.razor" )+ result = self._run( [+ "--json", "codegen", "panel-component",+ "--name", "HudBar",+ "--properties", '[{"name":"Health","type":"float","default":"100f"}]',+ "-o", razor_path,+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["class_name"] == "HudBar"+ assert os.path.isfile( razor_path )+ assert os.path.isfile( os.path.join( str( tmp_path ), "HudBar.razor.scss" ) )+ snippet = json.loads( data["scene_snippet"] )+ types = [c["__type"] for c in snippet["Components"]]+ assert "Sandbox.ScreenPanel" in types+ assert "HudBar" in types++ def test_codegen_panel_component_appends_to_scene( self, tmp_path ):+ """codegen panel-component --scene appends GameObject to a scene."""+ scene_path = os.path.join( str( tmp_path ), "ui.scene" )+ razor_path = os.path.join( str( tmp_path ), "Crosshair.razor" )+ self._run( ["--json", "scene", "new", "--name", "ui", "-o", scene_path, "--no-defaults"] )++ result = self._run( [+ "--json", "codegen", "panel-component",+ "--name", "Crosshair",+ "-o", razor_path,+ "--scene", scene_path,+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["scene_appended_to"]++ # Verify scene has the new object with both ScreenPanel and Crosshair+ with open( scene_path, "r", encoding="utf-8" ) as f:+ scene_json = json.load( f )+ names = [o["Name"] for o in scene_json["GameObjects"]]+ assert "Crosshair" in names++ # ---- Refine batch 2: diff, rename/move, instantiate-prefab ----++ def test_scene_diff_identical_json( self, tmp_path ):+ """scene diff reports identical when scenes match by name structure."""+ a = os.path.join( str( tmp_path ), "a.scene" )+ b = os.path.join( str( tmp_path ), "b.scene" )+ self._run( ["--json", "scene", "new", "--name", "x", "-o", a, "--no-defaults"] )+ self._run( ["--json", "scene", "new", "--name", "x", "-o", b, "--no-defaults"] )+ for n in ["A", "B"]:+ self._run( ["--json", "scene", "add-object", a, n] )+ self._run( ["--json", "scene", "add-object", b, n] )+ result = self._run( ["--json", "scene", "diff", a, b] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["identical"] is True++ def test_scene_diff_added_removed_modified_json( self, tmp_path ):+ """scene diff captures all three categories of change."""+ a = os.path.join( str( tmp_path ), "a.scene" )+ b = os.path.join( str( tmp_path ), "b.scene" )+ self._run( ["--json", "scene", "new", "--name", "x", "-o", a, "--no-defaults"] )+ self._run( ["--json", "scene", "new", "--name", "x", "-o", b, "--no-defaults"] )+ self._run( ["--json", "scene", "add-object", a, "OnlyA"] )+ self._run( ["--json", "scene", "add-object", a, "Shared", "--position", "0,0,0"] )+ self._run( ["--json", "scene", "add-object", b, "Shared", "--position", "1,2,3"] )+ self._run( ["--json", "scene", "add-object", b, "OnlyB"] )+ result = self._run( ["--json", "scene", "diff", a, b] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert "OnlyB" in data["added"]+ assert "OnlyA" in data["removed"]+ assert any( m["name"] == "Shared" for m in data["modified"] )++ def test_prefab_diff_json( self, tmp_path ):+ """prefab diff reports root component changes."""+ a = os.path.join( str( tmp_path ), "a.prefab" )+ b = os.path.join( str( tmp_path ), "b.prefab" )+ self._run( ["--json", "prefab", "new", "--name", "P", "-o", a, "--components", "model"] )+ self._run( ["--json", "prefab", "new", "--name", "P", "-o", b, "--components", "model,rigidbody"] )+ result = self._run( ["--json", "prefab", "diff", a, b] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["identical"] is False+ assert data["root_changes"] is not None++ def test_scene_instantiate_prefab_json( self, tmp_path ):+ """scene instantiate-prefab inserts a prefab as a GameObject."""+ scene_path = os.path.join( str( tmp_path ), "level.scene" )+ prefab_path = os.path.join( str( tmp_path ), "Bullet.prefab" )+ self._run( ["--json", "scene", "new", "--name", "level", "-o", scene_path, "--no-defaults"] )+ self._run( ["--json", "prefab", "new", "--name", "Bullet", "-o", prefab_path, "--components", "model"] )++ result = self._run( [+ "--json", "scene", "instantiate-prefab", scene_path, prefab_path,+ "--position", "10,20,30",+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["guid"]++ # Verify scene now has a GameObject named "Bullet" with PrefabSource+ with open( scene_path, "r", encoding="utf-8" ) as f:+ scene_data = json.load( f )+ names = [o["Name"] for o in scene_data["GameObjects"]]+ assert "Bullet" in names+ bullet = next( o for o in scene_data["GameObjects"] if o["Name"] == "Bullet" )+ assert "PrefabSource" in bullet+ assert bullet["Position"] == "10,20,30"++ def test_asset_rename_json( self, tmp_path ):+ """asset rename moves the file and rewrites refs in scene+prefab."""+ self._run( ["--json", "project", "new", "--name", "rn", "--output-dir", str( tmp_path )] )++ # Asset on disk+ widget_dir = os.path.join( str( tmp_path ), "Assets", "models", "team" )+ os.makedirs( widget_dir, exist_ok=True )+ widget = os.path.join( widget_dir, "widget.vmdl" )+ with open( widget, "w", encoding="utf-8" ) as f:+ f.write( "<MODEL>" )++ # Scene that references it+ scene_path = os.path.join( str( tmp_path ), "Assets", "scenes", "level.scene" )+ self._run( ["--json", "scene", "new", "--name", "level", "-o", scene_path, "--no-defaults"] )+ add_obj = self._run( ["--json", "scene", "add-object", scene_path, "Box"] )+ guid = json.loads( add_obj.stdout )["guid"]+ self._run( [+ "--json", "scene", "add-component", scene_path, guid, "Sandbox.ModelRenderer",+ "--properties", '{"Model": "models/team/widget.vmdl"}',+ ] )++ result = self._run( [+ "--json", "--project", str( tmp_path ),+ "asset", "rename", "models/team/widget.vmdl", "gizmo",+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["new_path"] == "models/team/gizmo.vmdl"+ assert data["file_renamed"] is True+ assert len( data["references_updated"] ) >= 1++ # File renamed on disk+ assert os.path.isfile( os.path.join( widget_dir, "gizmo.vmdl" ) )+ assert not os.path.isfile( widget )++ def test_asset_rename_dry_run_json( self, tmp_path ):+ """asset rename --dry-run reports counts but doesn't touch files."""+ self._run( ["--json", "project", "new", "--name", "dry", "--output-dir", str( tmp_path )] )+ widget = os.path.join( str( tmp_path ), "Assets", "models", "team", "widget.vmdl" )+ os.makedirs( os.path.dirname( widget ), exist_ok=True )+ with open( widget, "w", encoding="utf-8" ) as f:+ f.write( "<X>" )++ result = self._run( [+ "--json", "--project", str( tmp_path ),+ "asset", "rename", "models/team/widget.vmdl", "renamed.vmdl",+ "--dry-run",+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["dry_run"] is True+ assert data["file_renamed"] is False+ # File still exists at the original path+ assert os.path.isfile( widget )++ def test_asset_move_json( self, tmp_path ):+ """asset move relocates file across directories and rewrites refs."""+ self._run( ["--json", "project", "new", "--name", "mv", "--output-dir", str( tmp_path )] )+ widget = os.path.join( str( tmp_path ), "Assets", "models", "team", "widget.vmdl" )+ os.makedirs( os.path.dirname( widget ), exist_ok=True )+ with open( widget, "w", encoding="utf-8" ) as f:+ f.write( "<X>" )++ scene_path = os.path.join( str( tmp_path ), "Assets", "scenes", "level.scene" )+ self._run( ["--json", "scene", "new", "--name", "level", "-o", scene_path, "--no-defaults"] )+ add_obj = self._run( ["--json", "scene", "add-object", scene_path, "Box"] )+ guid = json.loads( add_obj.stdout )["guid"]+ self._run( [+ "--json", "scene", "add-component", scene_path, guid, "Sandbox.ModelRenderer",+ "--properties", '{"Model": "models/team/widget.vmdl"}',+ ] )++ result = self._run( [+ "--json", "--project", str( tmp_path ),+ "asset", "move", "models/team/widget.vmdl", "models/shared/widget.vmdl",+ ] )+ assert result.returncode == 0+ data = json.loads( result.stdout )+ assert data["file_moved"] is True+ assert data["new_path"] == "models/shared/widget.vmdl"++ moved = os.path.join( str( tmp_path ), "Assets", "models", "shared", "widget.vmdl" )+ assert os.path.isfile( moved )+ assert not os.path.isfile( widget )diff --git a/sbox/agent-harness/cli_anything/sbox/tests/test_orchestrator.py b/sbox/agent-harness/cli_anything/sbox/tests/test_orchestrator.pynew file mode 100644index 000000000..3404d85c7--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/tests/test_orchestrator.py@@ -0,0 +1,133 @@+"""Tests for the map test orchestrator."""++import json+import os+import pytest++from cli_anything.sbox.core import test_orchestrator+++class TestDataPathResolution:+ def test_computes_data_path_from_sbox_install_and_ident(self, tmp_path):+ sbox_install = str(tmp_path / "sbox")+ data_dir = tmp_path / "sbox" / "data" / "local" / "hold_the_line#local"+ data_dir.mkdir(parents=True)++ result = test_orchestrator.resolve_data_path(sbox_install, "hold_the_line")+ assert result == str(data_dir)++ def test_raises_if_data_dir_missing(self, tmp_path):+ sbox_install = str(tmp_path / "sbox")+ (tmp_path / "sbox").mkdir()++ with pytest.raises(FileNotFoundError):+ test_orchestrator.resolve_data_path(sbox_install, "hold_the_line")+++class TestComboMatrix:+ def test_default_matrix_has_12_combos(self):+ combos = test_orchestrator.build_combo_matrix()+ assert len(combos) == 12++ def test_all_strategies_present(self):+ combos = test_orchestrator.build_combo_matrix()+ strategies = {c["strategy"] for c in combos}+ assert strategies == {"Serpentine", "Gilbert", "SpanningTree", "Backbite"}++ def test_all_sizes_present(self):+ combos = test_orchestrator.build_combo_matrix()+ sizes = {c["size"] for c in combos}+ assert sizes == {"Small", "Medium", "Large"}++ def test_explicit_seeds(self):+ combos = test_orchestrator.build_combo_matrix(seeds=[42, 99])+ assert len(combos) == 24+ assert all(c["seed"] in [42, 99] for c in combos)++ def test_seed_count(self):+ combos = test_orchestrator.build_combo_matrix(seed_count=3)+ assert len(combos) == 36+ assert all(isinstance(c["seed"], int) for c in combos)++ def test_filter_strategies(self):+ combos = test_orchestrator.build_combo_matrix(+ strategies=["Gilbert", "Backbite"]+ )+ assert len(combos) == 6+ strategies = {c["strategy"] for c in combos}+ assert strategies == {"Gilbert", "Backbite"}++ def test_filter_sizes(self):+ combos = test_orchestrator.build_combo_matrix(sizes=["Small"])+ assert len(combos) == 4+++class TestConfigIO:+ def test_write_config(self, tmp_path):+ test_orchestrator.write_test_config(+ str(tmp_path), "Gilbert", "Large", 42+ )+ with open(os.path.join(str(tmp_path), "test_config.json"), "r", encoding="utf-8") as f:+ data = json.load(f)+ assert data == {"Strategy": "Gilbert", "Size": "Large", "Seed": 42}++ def test_cleanup_files(self, tmp_path):+ for name in ["test_config.json", "screenshot.rgba", "metadata.json", "test_complete.json"]:+ (tmp_path / name).write_text("x")++ test_orchestrator.cleanup_data_files(str(tmp_path))++ for name in ["test_config.json", "screenshot.rgba", "metadata.json", "test_complete.json"]:+ assert not (tmp_path / name).exists()++ def test_cleanup_ignores_missing(self, tmp_path):+ test_orchestrator.cleanup_data_files(str(tmp_path))+++class TestSentinelPolling:+ def test_returns_dict_when_sentinel_exists(self, tmp_path):+ sentinel = {"success": True}+ (tmp_path / "test_complete.json").write_text(json.dumps(sentinel))++ result = test_orchestrator.check_sentinel(str(tmp_path))+ assert result == {"success": True}++ def test_returns_none_when_no_sentinel(self, tmp_path):+ result = test_orchestrator.check_sentinel(str(tmp_path))+ assert result is None++ def test_returns_error_dict_on_failure(self, tmp_path):+ sentinel = {"success": False, "error": "generation failed"}+ (tmp_path / "test_complete.json").write_text(json.dumps(sentinel))++ result = test_orchestrator.check_sentinel(str(tmp_path))+ assert result["success"] is False+ assert result["error"] == "generation failed"+++class TestRgbaConversion:+ def test_converts_rgba_bytes_to_png(self, tmp_path):+ Image = pytest.importorskip("PIL.Image")+ width, height = 2, 2+ red_pixel = bytes([255, 0, 0, 255])+ rgba_bytes = red_pixel * (width * height)++ rgba_path = str(tmp_path / "screenshot.rgba")+ with open(rgba_path, "wb") as f:+ f.write(rgba_bytes)++ png_path = str(tmp_path / "output.png")+ test_orchestrator.rgba_to_png(rgba_path, png_path, width, height)++ assert os.path.exists(png_path)+ img = Image.open(png_path)+ assert img.size == (2, 2)+ assert img.getpixel((0, 0)) == (255, 0, 0, 255)++ def test_raises_on_missing_file(self, tmp_path):+ with pytest.raises(FileNotFoundError):+ test_orchestrator.rgba_to_png(+ str(tmp_path / "missing.rgba"),+ str(tmp_path / "out.png"),+ 2, 2+ )diff --git a/sbox/agent-harness/cli_anything/sbox/utils/__init__.py b/sbox/agent-harness/cli_anything/sbox/utils/__init__.pynew file mode 100644index 000000000..e867e5704--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/utils/__init__.py@@ -0,0 +1 @@+# utility modules for s&box CLI harnessdiff --git a/sbox/agent-harness/cli_anything/sbox/utils/repl_skin.py b/sbox/agent-harness/cli_anything/sbox/utils/repl_skin.pynew file mode 100644index 000000000..bc1fb6d1d--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/utils/repl_skin.py@@ -0,0 +1,567 @@+"""cli-anything REPL Skin โ Unified terminal interface for all CLI harnesses.++Copy this file into your CLI package at:+ cli_anything/<software>/utils/repl_skin.py++Usage:+ from cli_anything.<software>.utils.repl_skin import ReplSkin++ skin = ReplSkin("shotcut", version="1.0.0")+ skin.print_banner() # auto-detects repo-root or packaged SKILL.md+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)+ skin.success("Project saved")+ skin.error("File not found")+ skin.warning("Unsaved changes")+ skin.info("Processing 24 clips...")+ skin.status("Track 1", "3 clips, 00:02:30")+ skin.table(headers, rows)+ skin.print_goodbye()+"""++import os+import sys+from pathlib import Path++# โโ ANSI color codes (no external deps for core styling) โโโโโโโโโโโโโโ++_RESET = "\033[0m"+_BOLD = "\033[1m"+_DIM = "\033[2m"+_ITALIC = "\033[3m"+_UNDERLINE = "\033[4m"++# Brand colors+_CYAN = "\033[38;5;80m" # cli-anything brand cyan+_CYAN_BG = "\033[48;5;80m"+_WHITE = "\033[97m"+_GRAY = "\033[38;5;245m"+_DARK_GRAY = "\033[38;5;240m"+_LIGHT_GRAY = "\033[38;5;250m"++# Software accent colors โ each software gets a unique accent+_ACCENT_COLORS = {+ "gimp": "\033[38;5;214m", # warm orange+ "blender": "\033[38;5;208m", # deep orange+ "inkscape": "\033[38;5;39m", # bright blue+ "audacity": "\033[38;5;33m", # navy blue+ "libreoffice": "\033[38;5;40m", # green+ "obs_studio": "\033[38;5;55m", # purple+ "kdenlive": "\033[38;5;69m", # slate blue+ "shotcut": "\033[38;5;35m", # teal green+}+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue++# Status colors+_GREEN = "\033[38;5;78m"+_YELLOW = "\033[38;5;220m"+_RED = "\033[38;5;196m"+_BLUE = "\033[38;5;75m"+_MAGENTA = "\033[38;5;176m"++_SKILL_SOURCE_REPO = os.environ.get("CLI_ANYTHING_SKILL_REPO", "HKUDS/CLI-Anything")++# โโ Brand icon โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++# The cli-anything icon: a small colored diamond/chevron mark+_ICON = f"{_CYAN}{_BOLD}โ{_RESET}"+_ICON_SMALL = f"{_CYAN}โธ{_RESET}"++# โโ Box drawing characters โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++_H_LINE = "โ"+_V_LINE = "โ"+_TL = "โญ"+_TR = "โฎ"+_BL = "โฐ"+_BR = "โฏ"+_T_DOWN = "โฌ"+_T_UP = "โด"+_T_RIGHT = "โ"+_T_LEFT = "โค"+_CROSS = "โผ"+++def _strip_ansi(text: str) -> str:+ """Remove ANSI escape codes for length calculation."""+ import re+ return re.sub(r"\033\[[^m]*m", "", text)+++def _visible_len(text: str) -> int:+ """Get visible length of text (excluding ANSI codes)."""+ return len(_strip_ansi(text))+++def _display_home_path(path: str) -> str:+ """Display a path relative to the home directory when possible."""+ expanded = Path(path).expanduser().resolve()+ home = Path.home().resolve()+ try:+ relative = expanded.relative_to(home)+ return f"~/{relative.as_posix()}"+ except ValueError:+ return str(expanded)+++class ReplSkin:+ """Unified REPL skin for cli-anything CLIs.++ Provides consistent branding, prompts, and message formatting+ across all CLI harnesses built with the cli-anything methodology.+ """++ def __init__(self, software: str, version: str = "1.0.0",+ history_file: str | None = None, skill_path: str | None = None):+ """Initialize the REPL skin.++ Args:+ software: Software name (e.g., "gimp", "shotcut", "blender").+ version: CLI version string.+ history_file: Path for persistent command history.+ Defaults to ~/.cli-anything-<software>/history+ skill_path: Path to the SKILL.md file for agent discovery.+ Auto-detected from the repo-root skills/ tree when present,+ otherwise from the package's skills/ directory.+ Displayed in banner for AI agents to know where to read skill info.+ """+ self.software = software.lower().replace("-", "_")+ self.display_name = software.replace("_", " ").title()+ self.version = version+ software_aliases = {"iterm2_ctl": "iterm2"}+ self.skill_slug = software_aliases.get(self.software, self.software).replace("_", "-")+ self.skill_id = f"cli-anything-{self.skill_slug}"+ self.skill_install_cmd = (+ f"npx skills add {_SKILL_SOURCE_REPO} --skill {self.skill_id} -g -y"+ )+ global_skill_root = Path(+ os.environ.get("CLI_ANYTHING_GLOBAL_SKILLS_DIR", str(Path.home() / ".agents" / "skills"))+ ).expanduser()+ self.global_skill_path = str(global_skill_root / self.skill_id / "SKILL.md")++ # Prefer repo-root canonical skills/<skill-id>/SKILL.md when running+ # inside the CLI-Anything monorepo. Fall back to the packaged+ # cli_anything/<software>/skills/SKILL.md for installed harnesses.+ if skill_path is None:+ package_skill = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"+ repo_skill = None+ for parent in Path(__file__).resolve().parents:+ candidate = parent / "skills" / self.skill_id / "SKILL.md"+ if candidate.is_file():+ repo_skill = candidate+ break+ if repo_skill and repo_skill.is_file():+ skill_path = str(repo_skill)+ elif package_skill.is_file():+ skill_path = str(package_skill)+ self.skill_path = skill_path+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)++ # History file+ if history_file is None:+ hist_dir = Path.home() / f".cli-anything-{self.software}"+ hist_dir.mkdir(parents=True, exist_ok=True)+ self.history_file = str(hist_dir / "history")+ else:+ self.history_file = history_file++ # Detect terminal capabilities+ self._color = self._detect_color_support()++ def _detect_color_support(self) -> bool:+ """Check if terminal supports color."""+ if os.environ.get("NO_COLOR"):+ return False+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):+ return False+ if not hasattr(sys.stdout, "isatty"):+ return False+ return sys.stdout.isatty()++ def _c(self, code: str, text: str) -> str:+ """Apply color code if colors are supported."""+ if not self._color:+ return text+ return f"{code}{text}{_RESET}"++ # โโ Banner โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ def print_banner(self):+ """Print the startup banner with branding."""+ import textwrap++ inner = 72++ def _box_line(content: str) -> str:+ """Wrap content in box drawing, padding to inner width."""+ pad = inner - _visible_len(content)+ vl = self._c(_DARK_GRAY, _V_LINE)+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"++ def _meta_lines(label: str, value: str) -> list[str]:+ """Wrap a metadata line for the banner box."""+ icon = self._c(_MAGENTA, "โ")+ label_text = self._c(_DARK_GRAY, label)+ prefix = f" {icon} {label_text} "+ available = max(12, inner - _visible_len(prefix))+ wrapped = textwrap.wrap(+ value,+ width=available,+ break_long_words=True,+ break_on_hyphens=False,+ ) or [""]+ lines = [f"{prefix}{self._c(_LIGHT_GRAY, wrapped[0])}"]+ continuation_prefix = " " * _visible_len(prefix)+ for chunk in wrapped[1:]:+ lines.append(f"{continuation_prefix}{self._c(_LIGHT_GRAY, chunk)}")+ return lines++ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")++ # Title: โ cli-anything ยท Shotcut+ icon = self._c(_CYAN + _BOLD, "โ")+ brand = self._c(_CYAN + _BOLD, "cli-anything")+ dot = self._c(_DARK_GRAY, "ยท")+ name = self._c(self.accent + _BOLD, self.display_name)+ title = f" {icon} {brand} {dot} {name}"++ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"+ empty = ""++ meta_lines: list[str] = []+ meta_lines.extend(_meta_lines("Install:", self.skill_install_cmd))+ meta_lines.extend(_meta_lines("Global skill:", _display_home_path(self.global_skill_path)))+ print(top)+ print(_box_line(title))+ print(_box_line(ver))+ for line in meta_lines:+ print(_box_line(line))+ print(_box_line(empty))+ print(_box_line(tip))+ print(bot)+ print()++ # โโ Prompt โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ def prompt(self, project_name: str = "", modified: bool = False,+ context: str = "") -> str:+ """Build a styled prompt string for prompt_toolkit or input().++ Args:+ project_name: Current project name (empty if none open).+ modified: Whether the project has unsaved changes.+ context: Optional extra context to show in prompt.++ Returns:+ Formatted prompt string.+ """+ parts = []++ # Icon+ if self._color:+ parts.append(f"{_CYAN}โ{_RESET} ")+ else:+ parts.append("> ")++ # Software name+ parts.append(self._c(self.accent + _BOLD, self.software))++ # Project context+ if project_name or context:+ ctx = context or project_name+ mod = "*" if modified else ""+ parts.append(f" {self._c(_DARK_GRAY, '[')}")+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))+ parts.append(self._c(_DARK_GRAY, ']'))++ parts.append(self._c(_GRAY, " โฏ "))++ return "".join(parts)++ def prompt_tokens(self, project_name: str = "", modified: bool = False,+ context: str = ""):+ """Build prompt_toolkit formatted text tokens for the prompt.++ Use with prompt_toolkit's FormattedText for proper ANSI handling.++ Returns:+ list of (style, text) tuples for prompt_toolkit.+ """+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")+ tokens = []++ tokens.append(("class:icon", "โ "))+ tokens.append(("class:software", self.software))++ if project_name or context:+ ctx = context or project_name+ mod = "*" if modified else ""+ tokens.append(("class:bracket", " ["))+ tokens.append(("class:context", f"{ctx}{mod}"))+ tokens.append(("class:bracket", "]"))++ tokens.append(("class:arrow", " โฏ "))++ return tokens++ def get_prompt_style(self):+ """Get a prompt_toolkit Style object matching the skin.++ Returns:+ prompt_toolkit.styles.Style+ """+ try:+ from prompt_toolkit.styles import Style+ except ImportError:+ return None++ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")++ return Style.from_dict({+ "icon": "#5fdfdf bold", # cyan brand color+ "software": f"{accent_hex} bold",+ "bracket": "#585858",+ "context": "#bcbcbc",+ "arrow": "#808080",+ # Completion menu+ "completion-menu.completion": "bg:#303030 #bcbcbc",+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",+ "completion-menu.meta.completion": "bg:#303030 #808080",+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",+ # Auto-suggest+ "auto-suggest": "#585858",+ # Bottom toolbar+ "bottom-toolbar": "bg:#1c1c1c #808080",+ "bottom-toolbar.text": "#808080",+ })++ # โโ Messages โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ def success(self, message: str):+ """Print a success message with green checkmark."""+ icon = self._c(_GREEN + _BOLD, "โ")+ print(f" {icon} {self._c(_GREEN, message)}")++ def error(self, message: str):+ """Print an error message with red cross."""+ icon = self._c(_RED + _BOLD, "โ")+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)++ def warning(self, message: str):+ """Print a warning message with yellow triangle."""+ icon = self._c(_YELLOW + _BOLD, "โ ")+ print(f" {icon} {self._c(_YELLOW, message)}")++ def info(self, message: str):+ """Print an info message with blue dot."""+ icon = self._c(_BLUE, "โ")+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")++ def hint(self, message: str):+ """Print a subtle hint message."""+ print(f" {self._c(_DARK_GRAY, message)}")++ def section(self, title: str):+ """Print a section header."""+ print()+ print(f" {self._c(self.accent + _BOLD, title)}")+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")++ # โโ Status display โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ def status(self, label: str, value: str):+ """Print a key-value status line."""+ lbl = self._c(_GRAY, f" {label}:")+ val = self._c(_WHITE, f" {value}")+ print(f"{lbl}{val}")++ def status_block(self, items: dict[str, str], title: str = ""):+ """Print a block of status key-value pairs.++ Args:+ items: Dict of label -> value pairs.+ title: Optional title for the block.+ """+ if title:+ self.section(title)++ max_key = max(len(k) for k in items) if items else 0+ for label, value in items.items():+ lbl = self._c(_GRAY, f" {label:<{max_key}}")+ val = self._c(_WHITE, f" {value}")+ print(f"{lbl}{val}")++ def progress(self, current: int, total: int, label: str = ""):+ """Print a simple progress indicator.++ Args:+ current: Current step number.+ total: Total number of steps.+ label: Optional label for the progress.+ """+ pct = int(current / total * 100) if total > 0 else 0+ bar_width = 20+ filled = int(bar_width * current / total) if total > 0 else 0+ bar = "โ" * filled + "โ" * (bar_width - filled)+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"+ if label:+ text += f" {self._c(_LIGHT_GRAY, label)}"+ print(text)++ # โโ Table display โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ def table(self, headers: list[str], rows: list[list[str]],+ max_col_width: int = 40):+ """Print a formatted table with box-drawing characters.++ Args:+ headers: Column header strings.+ rows: List of rows, each a list of cell strings.+ max_col_width: Maximum column width before truncation.+ """+ if not headers:+ return++ # Calculate column widths+ col_widths = [min(len(h), max_col_width) for h in headers]+ for row in rows:+ for i, cell in enumerate(row):+ if i < len(col_widths):+ col_widths[i] = min(+ max(col_widths[i], len(str(cell))), max_col_width+ )++ def pad(text: str, width: int) -> str:+ t = str(text)[:width]+ return t + " " * (width - len(t))++ # Header+ header_cells = [+ self._c(_CYAN + _BOLD, pad(h, col_widths[i]))+ for i, h in enumerate(headers)+ ]+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")+ header_line = f" {sep.join(header_cells)}"+ print(header_line)++ # Separator+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]+ sep_line = self._c(_DARK_GRAY, f" {'โโโ'.join([_H_LINE * w for w in col_widths])}")+ print(sep_line)++ # Rows+ for row in rows:+ cells = []+ for i, cell in enumerate(row):+ if i < len(col_widths):+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")+ print(f" {row_sep.join(cells)}")++ # โโ Help display โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ def help(self, commands: dict[str, str]):+ """Print a formatted help listing.++ Args:+ commands: Dict of command -> description pairs.+ """+ self.section("Commands")+ max_cmd = max(len(c) for c in commands) if commands else 0+ for cmd, desc in commands.items():+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")+ desc_styled = self._c(_GRAY, f" {desc}")+ print(f"{cmd_styled}{desc_styled}")+ print()++ # โโ Goodbye โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ def print_goodbye(self):+ """Print a styled goodbye message."""+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")++ # โโ Prompt toolkit session factory โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ def create_prompt_session(self):+ """Create a prompt_toolkit PromptSession with skin styling.++ Returns:+ A configured PromptSession, or None if prompt_toolkit unavailable.+ """+ try:+ from prompt_toolkit import PromptSession+ from prompt_toolkit.history import FileHistory+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory+ from prompt_toolkit.formatted_text import FormattedText++ style = self.get_prompt_style()++ session = PromptSession(+ history=FileHistory(self.history_file),+ auto_suggest=AutoSuggestFromHistory(),+ style=style,+ enable_history_search=True,+ )+ return session+ except ImportError:+ return None++ def get_input(self, pt_session, project_name: str = "",+ modified: bool = False, context: str = "") -> str:+ """Get input from user using prompt_toolkit or fallback.++ Args:+ pt_session: A prompt_toolkit PromptSession (or None).+ project_name: Current project name.+ modified: Whether project has unsaved changes.+ context: Optional context string.++ Returns:+ User input string (stripped).+ """+ if pt_session is not None:+ from prompt_toolkit.formatted_text import FormattedText+ tokens = self.prompt_tokens(project_name, modified, context)+ return pt_session.prompt(FormattedText(tokens)).strip()+ else:+ raw_prompt = self.prompt(project_name, modified, context)+ return input(raw_prompt).strip()++ # โโ Toolbar builder โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ def bottom_toolbar(self, items: dict[str, str]):+ """Create a bottom toolbar callback for prompt_toolkit.++ Args:+ items: Dict of label -> value pairs to show in toolbar.++ Returns:+ A callable that returns FormattedText for the toolbar.+ """+ def toolbar():+ from prompt_toolkit.formatted_text import FormattedText+ parts = []+ for i, (k, v) in enumerate(items.items()):+ if i > 0:+ parts.append(("class:bottom-toolbar.text", " โ "))+ parts.append(("class:bottom-toolbar.text", f" {k}: "))+ parts.append(("class:bottom-toolbar", v))+ return FormattedText(parts)+ return toolbar+++# โโ ANSI 256-color to hex mapping (for prompt_toolkit styles) โโโโโโโโโ++_ANSI_256_TO_HEX = {+ "\033[38;5;33m": "#0087ff", # audacity navy blue+ "\033[38;5;35m": "#00af5f", # shotcut teal+ "\033[38;5;39m": "#00afff", # inkscape bright blue+ "\033[38;5;40m": "#00d700", # libreoffice green+ "\033[38;5;55m": "#5f00af", # obs purple+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue+ "\033[38;5;75m": "#5fafff", # default sky blue+ "\033[38;5;80m": "#5fd7d7", # brand cyan+ "\033[38;5;208m": "#ff8700", # blender deep orange+ "\033[38;5;214m": "#ffaf00", # gimp warm orange+}diff --git a/sbox/agent-harness/cli_anything/sbox/utils/sbox_backend.py b/sbox/agent-harness/cli_anything/sbox/utils/sbox_backend.pynew file mode 100644index 000000000..192b086f0--- /dev/null+++ b/sbox/agent-harness/cli_anything/sbox/utils/sbox_backend.py@@ -0,0 +1,256 @@+"""Backend module for finding and invoking s&box executables."""++import json+import os+import shutil+import subprocess+from pathlib import Path+from typing import Any, Dict, List, Optional+++# Common s&box installation paths (Windows)+# Non-standard locations should be supplied via the SBOX_PATH env var (see find_sbox_installation below).+SBOX_SEARCH_PATHS: List[str] = [+ r"C:\Program Files (x86)\Steam\steamapps\common\sbox",+ r"C:\Program Files\Steam\steamapps\common\sbox",+ r"D:\SteamLibrary\steamapps\common\sbox",+ r"E:\SteamLibrary\steamapps\common\sbox",+]++# Executable names relative to the s&box installation root+EXECUTABLES: Dict[str, str] = {+ "sbox-dev": "sbox-dev.exe",+ "sbox-server": "sbox-server.exe",+ "sbox-standalone": "sbox-standalone.exe",+ "resourcecompiler": os.path.join( "bin", "win64", "resourcecompiler.exe" ),+}+++def find_sbox_installation() -> str:+ """Find the s&box installation directory.++ Checks (in order):+ 1. SBOX_PATH environment variable+ 2. Common Steam library paths+ 3. sbox-dev.exe in PATH++ Returns:+ Absolute path to the s&box installation directory.++ Raises:+ RuntimeError: If no installation is found, with install instructions.+ """+ # 1. Environment variable+ env_path = os.environ.get( "SBOX_PATH" )+ if env_path and os.path.isdir( env_path ):+ dev_exe = os.path.join( env_path, "sbox-dev.exe" )+ if os.path.isfile( dev_exe ):+ return os.path.normpath( env_path )++ # 2. Common search paths+ for candidate in SBOX_SEARCH_PATHS:+ if os.path.isdir( candidate ):+ dev_exe = os.path.join( candidate, "sbox-dev.exe" )+ if os.path.isfile( dev_exe ):+ return os.path.normpath( candidate )++ # 3. sbox-dev.exe on PATH+ found = shutil.which( "sbox-dev" ) or shutil.which( "sbox-dev.exe" )+ if found:+ install_dir = os.path.dirname( os.path.realpath( found ) )+ return os.path.normpath( install_dir )++ raise RuntimeError(+ "Could not find s&box installation. "+ "Please do one of the following:\n"+ " - Set the SBOX_PATH environment variable to your s&box install directory\n"+ " - Install s&box via Steam (it will appear in a standard Steam library)\n"+ " - Add the s&box directory to your system PATH"+ )+++def find_executable( name: str ) -> str:+ """Find a specific s&box executable by short name.++ Args:+ name: Executable short name - one of 'sbox-dev', 'sbox-server',+ 'sbox-standalone', or 'resourcecompiler'.++ Returns:+ Full absolute path to the executable.++ Raises:+ RuntimeError: If the executable is not found.+ """+ if name not in EXECUTABLES:+ raise RuntimeError(+ f"Unknown executable '{name}'. "+ f"Valid names: {', '.join( sorted( EXECUTABLES.keys() ) )}"+ )++ sbox_dir = find_sbox_installation()+ exe_path = os.path.join( sbox_dir, EXECUTABLES[name] )++ if not os.path.isfile( exe_path ):+ raise RuntimeError(+ f"Executable not found at expected path: {exe_path}\n"+ f"Your s&box installation at {sbox_dir} may be incomplete or corrupted."+ )++ return os.path.normpath( exe_path )+++def get_sbox_version() -> Dict[str, Any]:+ """Read s&box version from the .version file in the installation directory.++ Returns:+ Dict with version info. Keys depend on file contents but typically+ include 'version', 'branch', and 'revision'. If the file is plain+ text, returns {"version": <text>}. If JSON, returns parsed dict.+ On any failure, returns {"version": "unknown", "error": <message>}.+ """+ try:+ sbox_dir = find_sbox_installation()+ except RuntimeError as exc:+ return {"version": "unknown", "error": str( exc )}++ version_file = os.path.join( sbox_dir, ".version" )+ if not os.path.isfile( version_file ):+ return {+ "version": "unknown",+ "sbox_path": sbox_dir,+ "error": f".version file not found at {version_file}",+ }++ try:+ with open( version_file, "r", encoding="utf-8" ) as f:+ content = f.read().strip()+ except OSError as exc:+ return {"version": "unknown", "error": str( exc )}++ # Try JSON first+ try:+ data = json.loads( content )+ if isinstance( data, dict ):+ data["sbox_path"] = sbox_dir+ return data+ except (json.JSONDecodeError, ValueError):+ pass++ # Fall back to plain text+ return {"version": content, "sbox_path": sbox_dir}+++def launch_editor( project_path: Optional[str] = None ) -> subprocess.Popen:+ """Launch sbox-dev.exe (the s&box editor), optionally opening a project.++ Args:+ project_path: Path to a .sbproj file or project directory.+ If None, the editor opens without a project.++ Returns:+ subprocess.Popen object for the launched process.++ Raises:+ RuntimeError: If sbox-dev.exe cannot be found.+ FileNotFoundError: If the given project_path does not exist.+ """+ exe = find_executable( "sbox-dev" )+ cmd: List[str] = [exe]++ if project_path is not None:+ resolved = os.path.abspath( project_path )+ if not os.path.exists( resolved ):+ raise FileNotFoundError(+ f"Project path does not exist: {resolved}"+ )+ cmd.append( resolved )++ return subprocess.Popen(+ cmd,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+++def launch_server(+ game_ident: str,+ map_ident: Optional[str] = None,+) -> subprocess.Popen:+ """Launch sbox-server.exe (dedicated server) with a game.++ Args:+ game_ident: Game identifier string (e.g. 'org.gamename').+ map_ident: Optional map identifier to load.++ Returns:+ subprocess.Popen object for the launched server process.++ Raises:+ RuntimeError: If sbox-server.exe cannot be found.+ """+ exe = find_executable( "sbox-server" )+ cmd: List[str] = [exe, "-game", game_ident]++ if map_ident is not None:+ cmd.extend( ["-map", map_ident] )++ return subprocess.Popen(+ cmd,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+++def run_resource_compiler(+ asset_path: str,+ sbox_path: Optional[str] = None,+) -> Dict[str, Any]:+ """Run resourcecompiler.exe on an asset file.++ Args:+ asset_path: Path to the asset file to compile.+ sbox_path: Optional explicit s&box installation path.+ If None, auto-detected.++ Returns:+ Dict with keys:+ - 'success': bool+ - 'return_code': int+ - 'stdout': str+ - 'stderr': str+ - 'asset_path': str (absolute path of the input asset)+ - 'compiler_path': str (path of the compiler used)+ """+ if sbox_path is not None:+ compiler = os.path.join(+ sbox_path, EXECUTABLES["resourcecompiler"]+ )+ if not os.path.isfile( compiler ):+ raise RuntimeError(+ f"Resource compiler not found at {compiler}"+ )+ else:+ compiler = find_executable( "resourcecompiler" )++ resolved_asset = os.path.abspath( asset_path )+ if not os.path.isfile( resolved_asset ):+ raise FileNotFoundError(+ f"Asset file does not exist: {resolved_asset}"+ )++ result = subprocess.run(+ [compiler, resolved_asset],+ capture_output=True,+ text=True,+ timeout=120,+ )++ return {+ "success": result.returncode == 0,+ "return_code": result.returncode,+ "stdout": result.stdout,+ "stderr": result.stderr,+ "asset_path": resolved_asset,+ "compiler_path": compiler,+ }diff --git a/sbox/agent-harness/setup.py b/sbox/agent-harness/setup.pynew file mode 100644index 000000000..7c18aba2e--- /dev/null+++ b/sbox/agent-harness/setup.py@@ -0,0 +1,57 @@+#!/usr/bin/env python3+"""+setup.py for cli-anything-sbox++Install with: pip install -e .+Or publish to PyPI: python -m build && twine upload dist/*+"""++from setuptools import setup, find_namespace_packages++with open("cli_anything/sbox/README.md", "r", encoding="utf-8") as fh:+ long_description = fh.read()++setup(+ name="cli-anything-sbox",+ version="1.0.0",+ author="cli-anything contributors",+ author_email="",+ description="CLI harness for s&box (Source 2): scenes, prefabs, materials, sounds, codegen, asset graph, project validation. Recommended: s&box installed via Steam.",+ long_description=long_description,+ long_description_content_type="text/markdown",+ url="https://github.com/HKUDS/CLI-Anything",+ packages=find_namespace_packages(include=["cli_anything.*"]),+ classifiers=[+ "Development Status :: 4 - Beta",+ "Intended Audience :: Developers",+ "Topic :: Software Development :: Libraries :: Python Modules",+ "Topic :: Games/Entertainment",+ "License :: OSI Approved :: MIT License",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ ],+ python_requires=">=3.10",+ install_requires=[+ "click>=8.0.0",+ "prompt-toolkit>=3.0.0",+ "Pillow>=10.0",+ ],+ extras_require={+ "dev": [+ "pytest>=7.0.0",+ "pytest-cov>=4.0.0",+ ],+ },+ entry_points={+ "console_scripts": [+ "cli-anything-sbox=cli_anything.sbox.sbox_cli:main",+ ],+ },+ package_data={+ "cli_anything.sbox": ["skills/*.md", "tests/*.md", "README.md"],+ },+ include_package_data=True,+ zip_safe=False,+)diff --git a/skills/cli-anything-sbox/SKILL.md b/skills/cli-anything-sbox/SKILL.mdnew file mode 100644index 000000000..fb35797d8--- /dev/null+++ b/skills/cli-anything-sbox/SKILL.md@@ -0,0 +1,314 @@+---+name: "cli-anything-sbox"+description: >-+ Agent-native CLI for the s&box game engine (Facepunch Studios, Source 2):+ project management, scene/prefab editing, material/sound/localization configs,+ C# code generation, asset graph queries, project validation, and editor launch.+---++# s&box CLI++Agent-native CLI for the s&box game engine (Facepunch Studios, Source 2). 79+ commands across 14 groups. Manipulate `.scene`, `.prefab`, `.vmat`, `.sound`, `Input.config`, `Collision.config` JSON files directly, generate idiomatic C# components, and run a real-time asset graph over the project.++## Installation++```bash+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=sbox/agent-harness+```++## Requirements++- Python 3.10++- s&box installed via Steam - auto-detected, or set `SBOX_PATH` to a custom installation directory.+- Most commands work entirely on the project's JSON files - s&box does not need to be running.++## Global Options++```+--json Machine-readable JSON output (always pass for agent use)+--project PATH Project directory (auto-detects from cwd .sbproj if omitted)+```++## Command Groups++### project - Manage s&box projects++```bash+cli-anything-sbox project new --name MyGame --output-dir ./MyGame+cli-anything-sbox --json project info+cli-anything-sbox project config --max-players 32 --tick-rate 64+cli-anything-sbox --json --project ./MyGame project add-package facepunch.libsdf+cli-anything-sbox --json --project ./MyGame project remove-package facepunch.libsdf+# Lint: broken asset refs, duplicate GUIDs, malformed Input.config+cli-anything-sbox --json --project ./MyGame project validate+cli-anything-sbox --project ./MyGame project validate --no-inputs --no-guids+```++### scene - Manipulate `.scene` files++```bash+cli-anything-sbox scene new --name gameplay -o ./Assets/scenes/gameplay.scene+cli-anything-sbox --json scene info ./scene.scene+cli-anything-sbox --json scene list ./scene.scene+cli-anything-sbox scene add-object ./scene.scene Enemy --position "100,0,0" --components "model,box_collider,rigidbody" --tags "enemy"+cli-anything-sbox scene remove-object ./scene.scene --name Enemy+cli-anything-sbox scene add-component ./scene.scene <object-guid> Sandbox.PointLight+cli-anything-sbox scene remove-component ./scene.scene <object-guid> --component-type Sandbox.Rigidbody+cli-anything-sbox --json scene modify-object ./scene.scene --guid <guid> --name NewName --position "200,0,0"+cli-anything-sbox --json scene clone-object ./scene.scene --name Enemy --new-name EnemyCopy --position "300,0,0"+cli-anything-sbox --json scene get-object ./scene.scene --name Sun+cli-anything-sbox scene set-property ./scene.scene --fixed-update-freq 64 --timescale 0.5+cli-anything-sbox scene set-navmesh ./scene.scene --enabled --agent-height 72 --agent-radius 16+cli-anything-sbox --json scene list-presets+cli-anything-sbox --json scene modify-component ./scene.scene <object-guid> <component-guid> --properties '{"Damage":50}'++# Find objects matching one or more filters (AND-combined)+cli-anything-sbox --json scene query ./scene.scene --has-component rigidbody --has-tag tower+cli-anything-sbox --json scene query ./scene.scene --name-regex "^Tower\d$" --in-bounds "0,-500,-50,1000,500,50"++# Extract every asset reference (.vmdl, .vmat, .vsnd, .vtex, .vpcf, .prefab) from a scene+cli-anything-sbox --json scene refs ./scene.scene++# Apply the same modification to every object that matches a query+cli-anything-sbox --json scene bulk-modify ./scene.scene --has-tag tower --position "0,0,100" --enable++# Structural diff between two scenes (added/removed/modified GameObjects + SceneProperties)+cli-anything-sbox --json scene diff ./old.scene ./new.scene++# Insert a prefab as a GameObject in a scene+cli-anything-sbox --json scene instantiate-prefab ./level.scene ./Assets/prefabs/bullet.prefab --position "10,0,0"+```++### prefab - Manage `.prefab` files++```bash+cli-anything-sbox prefab new --name Bullet -o ./Assets/prefabs/bullet.prefab --components "model,sphere_collider,rigidbody"+cli-anything-sbox --json prefab info ./Assets/prefabs/bullet.prefab+cli-anything-sbox prefab from-scene ./scene.scene <object-guid> -o ./Assets/prefabs/extracted.prefab+cli-anything-sbox --json prefab add-component ./prefab.prefab rigidbody+cli-anything-sbox prefab remove-component ./prefab.prefab --component-type Sandbox.Rigidbody+cli-anything-sbox --json prefab list++# Asset references inside a prefab+cli-anything-sbox --json prefab refs ./prefab.prefab++# Modify component properties on a prefab (by component type or component GUID)+cli-anything-sbox --json prefab modify-component ./prefab.prefab --component-type Sandbox.Rigidbody --properties '{"Gravity":false,"MassOverride":50}'++# Structural diff between two prefabs (root + named children)+cli-anything-sbox --json prefab diff ./old.prefab ./new.prefab+```++### codegen - Generate C# code++```bash+# Plain Component+cli-anything-sbox codegen component --name PlayerController --methods OnUpdate,OnFixedUpdate -o ./Code/PlayerController.cs++# Component with [Property] fields+cli-anything-sbox --json codegen component --name Tower --properties '[{"name":"Damage","type":"float","default":"25f"},{"name":"Range","type":"float","default":"500f"}]'++# Networked component (partial class) with RPC method stubs+cli-anything-sbox codegen component --name NetPlayer --networked --methods OnUpdate,OnFixedUpdate --rpc-methods "Fire:Broadcast,TakeDamage:Host" -o ./Code/NetPlayer.cs++# GameResource+cli-anything-sbox codegen gameresource --name TowerData --display-name "Tower Data" --extension tower -o ./Code/TowerData.cs++# Editor menu (Editor/ assembly)+cli-anything-sbox codegen editor-menu --name MyTools --menu-path "Editor/My Tools/Open" -o ./Editor/MyTools.cs++# Plain Razor UI component (.razor + .razor.scss)+cli-anything-sbox codegen razor --name HudPanel --properties '[{"name":"Score","type":"int","default":"0"}]' -o ./UI/HudPanel.razor++# Static or base-derived class+cli-anything-sbox codegen class --name Math2 --static -o ./Code/Math2.cs++# PanelComponent + sibling ScreenPanel scaffold (handles the s&box quirk where+# PanelComponent input only works when both are on the same GameObject).+# Emits .razor + .razor.scss + a paste-ready GameObject snippet, or appends+# directly to a scene with --scene.+cli-anything-sbox --json codegen panel-component --name HudBar -o ./UI/HudBar.razor+cli-anything-sbox codegen panel-component --name Crosshair -o ./UI/Crosshair.razor --scene ./Assets/scenes/game.scene+```++### input - Manage `Input.config`++```bash+cli-anything-sbox --json input list+cli-anything-sbox input add --name PlaceTower --group Gameplay --keyboard mouse1 --gamepad RightTrigger+cli-anything-sbox input remove --name PlaceTower+cli-anything-sbox input set --name Attack1 --keyboard mouse1+```++### collision - Manage `Collision.config`++```bash+cli-anything-sbox --json collision list+cli-anything-sbox collision add-layer --name projectile --default Collide+cli-anything-sbox collision add-rule --layer-a projectile --layer-b solid --result Collide+cli-anything-sbox collision remove-rule --layer-a projectile --layer-b solid+cli-anything-sbox collision remove-layer --name projectile+```++### material - Manage `.vmat` materials++```bash+cli-anything-sbox --json material new --name floor --shader complex --color-texture "textures/floor.tga" --metalness 0.3 -o ./Assets/materials/floor.vmat+cli-anything-sbox --json material info ./Assets/materials/floor.vmat+cli-anything-sbox --json material list+cli-anything-sbox --json material set ./Assets/materials/floor.vmat --metalness 0.8+```++### sound - Manage `.sound` events++```bash+cli-anything-sbox --json sound new --name gunshot --sounds "sounds/gun1.vsnd,sounds/gun2.vsnd" --volume 0.8 -o ./Assets/sounds/gunshot.sound+cli-anything-sbox --json sound info ./Assets/sounds/gunshot.sound+cli-anything-sbox --json sound list+cli-anything-sbox --json sound set ./Assets/sounds/gunshot.sound --volume 0.5+```++### localization - Manage translations++```bash+cli-anything-sbox localization new --lang en -o ./Localization/en.json+cli-anything-sbox localization set ./Localization/en.json --key "game.title" --value "My Game"+cli-anything-sbox --json localization list ./Localization/en.json+cli-anything-sbox localization get ./Localization/en.json --key "game.title"+cli-anything-sbox localization remove ./Localization/en.json --key "game.title"+cli-anything-sbox localization bulk-set ./Localization/en.json --keys '{"ui.start":"Start","ui.quit":"Quit"}'+```++### server - Dedicated server++```bash+cli-anything-sbox server info+cli-anything-sbox server start --game my_game --map facepunch.flatgrass+```++### asset - Asset management & reverse lookups++```bash+cli-anything-sbox --json asset list --type scene+cli-anything-sbox --json asset info ./Assets/scenes/minimal.scene+cli-anything-sbox asset compile ./Assets/materials/floor.vmat++# Which scenes/prefabs reference this asset?+cli-anything-sbox --json --project ./MyGame asset find-refs models/myteam/widget.vmdl++# Find unreferenced assets (per type, or across all referenceable types)+cli-anything-sbox --json --project ./MyGame asset find-unused+cli-anything-sbox --json --project ./MyGame asset find-unused --type model --type material++# Rename an asset and update every scene/prefab reference (extension preserved if omitted)+cli-anything-sbox --json --project ./MyGame asset rename models/team/widget.vmdl gizmo+cli-anything-sbox --project ./MyGame asset rename models/team/widget.vmdl gizmo --dry-run++# Move an asset across directories and update every reference+cli-anything-sbox --json --project ./MyGame asset move models/team/widget.vmdl models/shared/widget.vmdl+```++### session - State management++```bash+cli-anything-sbox session status+cli-anything-sbox session undo+cli-anything-sbox session redo+```++### test - Automated map/scene generation harness++```bash+cli-anything-sbox test setup+cli-anything-sbox --json test run+```++### launch - Open project in s&box editor++```bash+cli-anything-sbox launch+```++## Component Presets++29 short names usable with `--components` on `scene add-object`, `prefab new`, etc. Each maps to a `Sandbox.*` component type.++| Preset | Component Type |+|--------|---------------|+| `model` | `Sandbox.ModelRenderer` |+| `box_collider` | `Sandbox.BoxCollider` |+| `sphere_collider` | `Sandbox.SphereCollider` |+| `capsule_collider` | `Sandbox.CapsuleCollider` |+| `plane_collider` | `Sandbox.PlaneCollider` |+| `model_collider` | `Sandbox.ModelCollider` |+| `rigidbody` | `Sandbox.Rigidbody` |+| `character_controller` | `Sandbox.CharacterController` |+| `player_controller` | `Sandbox.PlayerController` |+| `camera` | `Sandbox.CameraComponent` |+| `light_directional` | `Sandbox.DirectionalLight` |+| `light_point` | `Sandbox.PointLight` |+| `spot_light` | `Sandbox.SpotLight` |+| `ambient_light` | `Sandbox.AmbientLight` |+| `sprite_renderer` | `Sandbox.SpriteRenderer` |+| `skinned_model_renderer` | `Sandbox.SkinnedModelRenderer` |+| `text_renderer` | `Sandbox.TextRenderer` |+| `line_renderer` | `Sandbox.LineRenderer` |+| `decal_renderer` | `Sandbox.DecalRenderer` |+| `trail_renderer` | `Sandbox.TrailRenderer` |+| `particle_effect` | `Sandbox.ParticleEffect` |+| `sound_point` | `Sandbox.SoundPointComponent` |+| `nav_mesh_agent` | `Sandbox.NavMeshAgent` |+| `screen_panel` | `Sandbox.ScreenPanel` |+| `world_panel` | `Sandbox.WorldPanel` |+| `fixed_joint` | `Sandbox.FixedJoint` |+| `hinge_joint` | `Sandbox.HingeJoint` |+| `spring_joint` | `Sandbox.SpringJoint` |+| `ball_socket_joint` | `Sandbox.BallSocketJoint` |++`scene list-presets` returns the live preset registry as JSON.++## Agent Usage Pattern++Pass `--json` for every agent-driven invocation. Pipe through `jq` to thread GUIDs and paths between commands:++```bash+# Bootstrap a project+sbproj=$(cli-anything-sbox --json project new --name MyGame --output-dir /tmp/MyGame | jq -r '.sbproj')+cd /tmp/MyGame++# Add a tower with a specific component layout, capture its GUID+guid=$(cli-anything-sbox --json scene add-object ./Assets/scenes/main.scene Tower \+ --components "model,box_collider,rigidbody" --tags "tower" \+ | jq -r '.guid')++# Generate the corresponding C# component, networked+cli-anything-sbox --json codegen component --name Tower --networked \+ --rpc-methods "Fire:Host" --properties '[{"name":"Damage","type":"float","default":"25f"}]' \+ -o ./Code/Tower.cs++# Bulk-tweak every tower in the scene+cli-anything-sbox --json scene bulk-modify ./Assets/scenes/main.scene \+ --has-tag tower --enable --position-y-add 50++# Validate before committing+cli-anything-sbox --json project validate+```++## REPL Mode++`cli-anything-sbox` with no arguments enters an interactive REPL with a styled prompt:++```+$ cli-anything-sbox+cli-anything-sbox> project info+cli-anything-sbox> scene list ./Assets/scenes/main.scene+cli-anything-sbox> codegen component --name Foo -o ./Code/Foo.cs+cli-anything-sbox> quit+```++## Environment Variables++| Variable | Description | Default |+|----------|-------------|---------|+| `SBOX_PATH` | s&box installation directory | Auto-detected from Steam library folders |+| `CLI_ANYTHING_SKILL_REPO` | Override the repo `repl_skin` reads SKILL.md from | `HKUDS/CLI-Anything` |