Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

fix(sbox): silent failures caught by audit follow-up

KarandeepSWranch6417d118f1a1
diff --git a/README.md b/README.md
index b8a9d348d..7753b55bd 100644
--- a/README.md
+++ b/README.md
@@ -1000,7 +1000,7 @@ Each application received complete, production-ready CLI interfaces — not demo
<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">✅ 238</td>
+<td align="center">✅ 244</td>
</tr>
<tr>
<td align="center"><strong>🐞 <a href="lldb/agent-harness/">LLDB</a></strong></td>
@@ -1166,7 +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 (238 tests: 155 unit + 17 orchestrator + 50 e2e + 16 exit-code)
+├── 📦 sbox/agent-harness/ # s&box CLI (244 tests: 157 unit + 17 orchestrator + 50 e2e + 20 exit-code)
├── 🎨 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.md
index 2b0d7013d..1c73fcc2c 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -374,7 +374,7 @@ AI Agent 推理能力很强,但操控真实专业软件的能力很弱。现
| 💸 "GUI 自动化三天两头崩" | 告别截图、点击和 RPA 的脆弱性,纯命令行操控,结构化接口 |
| 📊 "Agent 需要结构化数据" | 内置 JSON 输出供 Agent 直接消费,同时保留可读格式方便调试 |
| 🔧 "定制集成太贵了" | 一个插件就能为任意代码库自动生成 CLI,经过验证的 7 阶段流水线 |
-| ⚡ "原型和生产之间差十万八千里" | 1,757+ 测试用例,全部在真实软件上验证通过,覆盖 13 款主流应用 |
+| ⚡ "原型和生产之间差十万八千里" | 1,763+ 测试用例,全部在真实软件上验证通过,覆盖 13 款主流应用 |
---
@@ -606,7 +606,7 @@ CLI-Anything 适用于任何有代码库的软件 —— 不限领域,不限
<td>游戏开发</td>
<td><code>cli-anything-sbox</code></td>
<td>Source 2 游戏引擎 - 直接读写 .scene/.prefab/.vmat/.vsnd JSON</td>
-<td align="center">✅ 238</td>
+<td align="center">✅ 244</td>
</tr>
<tr>
<td align="center"><strong>🎨 Sketch</strong></td>
@@ -617,11 +617,11 @@ CLI-Anything 适用于任何有代码库的软件 —— 不限领域,不限
</tr>
<tr>
<td align="center" colspan="4"><strong>合计</strong></td>
-<td align="center"><strong>✅ 1,757</strong></td>
+<td align="center"><strong>✅ 1,763</strong></td>
</tr>
</table>
-> 全部 1,741 项测试 **100% 通过** —— 1,256 项单元测试 + 466 项端到端测试 + 19 项 Node.js 测试。
+> 全部 1,763 项测试 **100% 通过** - 1,258 项单元测试 + 486 项端到端测试 + 19 项 Node.js 测试。
---
@@ -655,7 +655,7 @@ nsight-graphics 40 passed ✅ (36 unit + 4 e2e)
unrealinsights 50 passed ✅ (49 unit + 1 e2e, 9 backend-gated e2e skipped)
sketch 19 passed ✅ (19 jest, Node.js)
──────────────────────────────────────────────────────────────────────────────
-TOTAL 1,757 passed ✅ 100% pass rate
+TOTAL 1,763 passed ✅ 100% pass rate
```
---
@@ -725,7 +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(238 项测试: 155 单元 + 17 orchestrator + 50 e2e + 16 exit-code)
+├── 📦 sbox/agent-harness/ # s&box CLI(244 项测试: 157 单元 + 17 orchestrator + 50 e2e + 20 exit-code)
└── 🎨 sketch/agent-harness/ # Sketch CLI(19 项测试,Node.js)
```
@@ -962,7 +962,7 @@ MIT License — 可自由使用、修改和分发。
**CLI-Anything** — *一行命令,让任何软件成为 Agent 的原生工具。*
-<sub>为 AI Agent 时代而生 | 13 款专业软件实测 | 1,757 项测试全部通过</sub>
+<sub>为 AI Agent 时代而生 | 13 款专业软件实测 | 1,763 项测试全部通过</sub>
<br>
diff --git a/sbox/agent-harness/cli_anything/sbox/core/codegen.py b/sbox/agent-harness/cli_anything/sbox/core/codegen.py
index 2becfeb3f..c8e0323b3 100644
--- a/sbox/agent-harness/cli_anything/sbox/core/codegen.py
+++ b/sbox/agent-harness/cli_anything/sbox/core/codegen.py
@@ -586,7 +586,7 @@ def generate_class(
lines.append( f"{indent}\tpublic {mstatic}{mreturn} {mname}( {mparams} )" )
lines.append( f"{indent}\t{{" )
if mbody:
- for bline in mbody.split( "\\n" ):
+ for bline in mbody.split( "\n" ):
lines.append( f"{indent}\t\t{bline}" )
lines.append( f"{indent}\t}}" )
diff --git a/sbox/agent-harness/cli_anything/sbox/core/session.py b/sbox/agent-harness/cli_anything/sbox/core/session.py
index 577c0c04c..4e17916e8 100644
--- a/sbox/agent-harness/cli_anything/sbox/core/session.py
+++ b/sbox/agent-harness/cli_anything/sbox/core/session.py
@@ -86,17 +86,34 @@ class Session:
except (OSError, json.JSONDecodeError, ValueError) as exc:
# Preserve the malformed file before resetting so the user can
# recover state if needed; emit a stderr warning so the reset is
- # not silent.
+ # not silent. Use a timestamp suffix so a second corruption does
+ # not silently overwrite the first preserved copy.
+ backup = f"{self._session_path}.corrupt.{int( time.time() )}"
+ preserved = False
try:
- backup = self._session_path + ".corrupt"
if os.path.isfile( self._session_path ):
os.replace( self._session_path, backup )
- sys.stderr.write(
- f"warning: session file at {self._session_path} could not be read "
- f"({exc}); preserved as {backup} and reset to empty state\n"
- )
- except OSError:
- pass
+ preserved = True
+ except OSError as backup_exc:
+ # Couldn't move the file - still warn the user that the
+ # session is being reset, just note the preservation failed.
+ try:
+ sys.stderr.write(
+ f"warning: session file at {self._session_path} could not be "
+ f"read ({exc}) and preservation failed ({backup_exc}); "
+ f"resetting to empty state\n"
+ )
+ except (OSError, ValueError):
+ pass
+ else:
+ try:
+ location = backup if preserved else self._session_path
+ sys.stderr.write(
+ f"warning: session file at {self._session_path} could not be read "
+ f"({exc}); preserved as {location} and reset to empty state\n"
+ )
+ except (OSError, ValueError):
+ pass
self._data = _empty_session_data()
def save( self ) -> None:
diff --git a/sbox/agent-harness/cli_anything/sbox/tests/TEST.md b/sbox/agent-harness/cli_anything/sbox/tests/TEST.md
index fd807cab6..6cf9bf8d5 100644
--- a/sbox/agent-harness/cli_anything/sbox/tests/TEST.md
+++ b/sbox/agent-harness/cli_anything/sbox/tests/TEST.md
@@ -7,11 +7,11 @@ the `agent-harness/` directory.
| 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_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 | **157** |
| `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** |
-| `test_exit_codes.py` | One-shot CLI exit-code contract: failures exit 1 (human + JSON modes), success exits 0, validation failure exits 1, REPL absorbs SystemExit | **16** |
-| **Total** | | **238** |
+| `test_exit_codes.py` | One-shot CLI exit-code contract: failures exit 1 (human + JSON modes), success exits 0, validation failure exits 1, REPL absorbs SystemExit. Plus monkeypatched coverage of audited dict-returning failure paths (asset compile, server info) | **20** |
+| **Total** | | **244** |
## 2. Running the Tests
@@ -45,7 +45,7 @@ python -m pytest cli_anything/sbox/tests/ -v
## 3. Test Coverage by Class
-### `test_core.py` (155 tests, 36 classes)
+### `test_core.py` (157 tests, 36 classes)
| Class | Tests | Module Under Test |
|---|---|---|
@@ -68,7 +68,7 @@ python -m pytest cli_anything/sbox/tests/ -v
| `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 |
+| `TestCodegenClass` | 3 | `core.codegen.generate_class` - static class, base class, multiline method body regression |
| `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 |
@@ -79,7 +79,7 @@ python -m pytest cli_anything/sbox/tests/ -v
| `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 |
+| `TestSession` | 6 | `core.session` - create, set project, undo/redo, save/load, clear, corrupt-file warning + timestamped backup |
| `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 |
@@ -104,13 +104,14 @@ python -m pytest cli_anything/sbox/tests/ -v
| `TestRgbaConversion` | 2 | RGBA byte-array -> PNG via Pillow |
| `TestDataPathResolution` | 2 | `FileSystem.Data` path resolution across editor and standalone |
-### `test_exit_codes.py` (16 tests, 3 classes)
+### `test_exit_codes.py` (20 tests, 5 classes)
| Class | Tests | Coverage |
|---|---|---|
-| `TestOneShotFailureExitsNonZero` | 9 | Failure paths in one-shot mode return exit 1: missing scene/project file (human + JSON), missing localization key, missing required args, invalid JSON in `--properties`, asset compile without s&box install. Includes the `--help` exit-0 baseline. |
+| `TestOneShotFailureExitsNonZero` | 11 | Failure paths in one-shot mode return exit 1: missing scene/project file (human + JSON), missing localization key, missing required args, invalid JSON in `--properties`, asset compile without s&box install, scene list on missing file (true gate of the bare `except Exception` path), asset info on corrupt JSON (json_info.error surface). Includes the `--help` exit-0 baseline. |
| `TestOneShotSuccessExitsZero` | 2 | Confirms the success path was not regressed by the exit-1-on-failure change |
| `TestProjectValidateExitsNonZero` | 2 | `project validate` exits 1 when `ok=False` (broken refs) so CI can gate on it; clean project still exits 0 |
+| `TestAuditedFailurePaths` | 2 | Monkeypatched coverage for dict-returning failure paths: `asset compile` with `success=False` from resourcecompiler, `server info` with `error` field in `get_sbox_version()`. These can't be triggered without s&box installed, so a CliRunner + monkeypatch combination pins the contract. |
| `TestReplModeAbsorbsExit` | 3 | `_output_error` does not call `sys.exit` when `ctx.obj["repl"] = True`; one-shot is the safe default when the key is absent |
## 4. Coverage by Source Module
@@ -131,7 +132,7 @@ python -m pytest cli_anything/sbox/tests/ -v
| `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) + 16 (test_exit_codes: failure exit-code contract + REPL absorb) |
+| `sbox_cli.py` (CLI) | - | - | 40 (full TestCLISubprocess) + 20 (test_exit_codes: failure exit-code contract + audited-path monkeypatch coverage + REPL absorb) |
## 5. E2E Prerequisites
diff --git a/sbox/agent-harness/cli_anything/sbox/tests/test_core.py b/sbox/agent-harness/cli_anything/sbox/tests/test_core.py
index 096366c4c..d7821c9ce 100644
--- a/sbox/agent-harness/cli_anything/sbox/tests/test_core.py
+++ b/sbox/agent-harness/cli_anything/sbox/tests/test_core.py
@@ -1057,6 +1057,33 @@ class TestSession:
assert status["undo_count"] == 0
assert status["redo_count"] == 0
+ def test_session_load_corrupt_file_warns_and_preserves_backup(self, tmp_path, capsys):
+ """A malformed session file is preserved as .corrupt.<ts> and warned about.
+
+ Reset must not be silent: the user's undo history could otherwise be
+ destroyed without any signal. The backup uses a timestamp suffix so a
+ second corruption does not silently overwrite the first.
+ """
+ session_path = tmp_path / "session.json"
+ session_path.write_text("not valid json{{{", encoding="utf-8")
+
+ session = Session(session_path=str(session_path))
+
+ captured = capsys.readouterr()
+ assert "could not be read" in captured.err
+ assert "preserved as" in captured.err
+
+ # Original file moved aside
+ assert not session_path.exists()
+
+ # Backup exists with timestamp suffix and contains the original bytes
+ backups = list(tmp_path.glob("session.json.corrupt.*"))
+ assert len(backups) == 1
+ assert backups[0].read_text(encoding="utf-8") == "not valid json{{{"
+
+ # Session is reset to empty state
+ assert session.get_status()["project_path"] is None
+
# ============================================================================
# TestExport
@@ -1699,6 +1726,28 @@ class TestCodegenClass:
assert "public class EnemyManager : BaseManager" in result["content"]
assert "using Sandbox;" in result["content"]
+ def test_generate_class_method_with_multiline_body(self):
+ """Method body containing newlines must be split into separate output lines.
+
+ Regression test for a bug where the body was split on the literal
+ two-character string ``\\n`` instead of an actual newline, collapsing
+ every multi-line method body into a single line of malformed C#.
+ """
+ result = generate_class( "Counter", methods=[
+ {
+ "name": "Tick",
+ "return_type": "void",
+ "body": "var x = 1;\nvar y = 2;\nreturn;",
+ }
+ ])
+ content = result["content"]
+ assert "\t\tvar x = 1;" in content
+ assert "\t\tvar y = 2;" in content
+ assert "\t\treturn;" in content
+ # The literal two-character sequence \n must NOT appear as a body
+ # line - that would mean the buggy split was still in effect.
+ assert "\t\tvar x = 1;\\nvar y = 2;" not in content
+
class TestLocalizationBulkSet:
"""Test bulk_set for localization."""
diff --git a/sbox/agent-harness/cli_anything/sbox/tests/test_exit_codes.py b/sbox/agent-harness/cli_anything/sbox/tests/test_exit_codes.py
index 462867f79..f7cb7ee4b 100644
--- a/sbox/agent-harness/cli_anything/sbox/tests/test_exit_codes.py
+++ b/sbox/agent-harness/cli_anything/sbox/tests/test_exit_codes.py
@@ -113,6 +113,25 @@ class TestOneShotFailureExitsNonZero:
result = _run(["asset", "compile", str(tmp_path / "nope.vmat")])
assert result.returncode == 1
+ def test_scene_list_missing_file_exits_one(self, tmp_path):
+ """scene list on a missing file: bare except Exception path.
+
+ Direct gate of the _output_error sys.exit fix - this handler does
+ ``except Exception as exc: _output_error(ctx, str(exc))`` with no
+ ClickException re-raise short-circuit, so without the fix the
+ FileNotFoundError would print and exit 0.
+ """
+ result = _run(["scene", "list", str(tmp_path / "missing.scene")])
+ assert result.returncode == 1
+
+ def test_asset_info_corrupt_json_exits_one(self, tmp_path):
+ """asset info on a corrupt .scene surfaces _parse_json_asset's error
+ and exits 1, instead of burying the error in nested json_info."""
+ bad_scene = tmp_path / "broken.scene"
+ bad_scene.write_text("{not valid json", encoding="utf-8")
+ result = _run(["asset", "info", str(bad_scene)])
+ assert result.returncode == 1
+
class TestOneShotSuccessExitsZero:
"""Successful one-shot commands still exit 0 after the fix."""
@@ -196,6 +215,61 @@ class TestProjectValidateExitsNonZero:
# ---------------------------------------------------------------------------
+class TestAuditedFailurePaths:
+ """Coverage for failure paths added during the silent-failure audit.
+
+ These paths return dicts (not exceptions) on failure, so the standard
+ ``except Exception`` path doesn't catch them. The audit added explicit
+ success/error checks to surface them; these tests pin those checks.
+ """
+
+ def test_asset_compile_returns_success_false_exits_one(self, monkeypatch):
+ """asset compile sees ``success=False`` from run_resource_compiler
+ and exits 1 with the compiler's stderr in the error message."""
+ from click.testing import CliRunner
+ from cli_anything.sbox import sbox_cli
+ from cli_anything.sbox.utils import sbox_backend
+
+ def fake_compile(asset_path):
+ return {
+ "success": False,
+ "return_code": 1,
+ "stdout": "",
+ "stderr": "mock compiler error: bad shader",
+ "asset_path": asset_path,
+ "compiler_path": "/fake/resourcecompiler",
+ }
+
+ monkeypatch.setattr(sbox_backend, "run_resource_compiler", fake_compile)
+
+ runner = CliRunner()
+ result = runner.invoke(sbox_cli.cli, ["asset", "compile", "/fake/path.vmat"])
+
+ assert result.exit_code == 1
+ # The error message includes both rc and stderr context.
+ assert "Resource compilation failed" in result.output
+ assert "mock compiler error" in result.output
+
+ def test_server_info_version_error_exits_one(self, monkeypatch):
+ """server info sees ``error`` field in get_sbox_version() and exits 1
+ instead of reporting "version: unknown" with exit 0."""
+ from click.testing import CliRunner
+ from cli_anything.sbox import sbox_cli
+ from cli_anything.sbox.utils import sbox_backend
+
+ monkeypatch.setattr(sbox_backend, "find_executable", lambda name: "/fake/sbox-server.exe")
+ monkeypatch.setattr(sbox_backend, "get_sbox_version", lambda: {
+ "version": "unknown",
+ "error": "mock: .version file unreadable",
+ })
+
+ runner = CliRunner()
+ result = runner.invoke(sbox_cli.cli, ["server", "info"])
+
+ assert result.exit_code == 1
+ assert "Failed to read s&box version" in result.output
+
+
class TestReplModeAbsorbsExit:
"""Direct unit tests on _output_error to prove REPL mode doesn't exit.