python-yama 0.10.7__tar.gz → 0.11.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. {python_yama-0.10.7 → python_yama-0.11.0}/PKG-INFO +1 -1
  2. {python_yama-0.10.7 → python_yama-0.11.0}/docs/agent-skill-test-framework-design.md +44 -59
  3. {python_yama-0.10.7 → python_yama-0.11.0}/skills/eval-plugin-with-yama/SKILL.md +5 -2
  4. {python_yama-0.10.7 → python_yama-0.11.0}/skills/eval-plugin-with-yama/references/case-schema.md +15 -5
  5. {python_yama-0.10.7 → python_yama-0.11.0}/skills/eval-plugin-with-yama/references/debugging.md +5 -3
  6. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_framework.py +130 -10
  7. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_report.py +98 -0
  8. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_tool_loader.py +6 -3
  9. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_usage.py +135 -6
  10. python_yama-0.11.0/yama/_matching.py +64 -0
  11. {python_yama-0.10.7 → python_yama-0.11.0}/yama/llm.py +26 -4
  12. {python_yama-0.10.7 → python_yama-0.11.0}/yama/loaders/tool_loader.py +18 -16
  13. {python_yama-0.10.7 → python_yama-0.11.0}/yama/mocks.py +19 -59
  14. {python_yama-0.10.7 → python_yama-0.11.0}/yama/report.py +45 -6
  15. {python_yama-0.10.7 → python_yama-0.11.0}/yama/runner.py +33 -3
  16. {python_yama-0.10.7 → python_yama-0.11.0}/yama/tools/bash/_cli_shim.py +5 -11
  17. {python_yama-0.10.7 → python_yama-0.11.0}/yama/tools/bash/bash.py +6 -2
  18. {python_yama-0.10.7 → python_yama-0.11.0}/yama/tools/bash/fs.py +233 -74
  19. {python_yama-0.10.7 → python_yama-0.11.0}/.github/workflows/publish.yml +0 -0
  20. {python_yama-0.10.7 → python_yama-0.11.0}/.gitignore +0 -0
  21. {python_yama-0.10.7 → python_yama-0.11.0}/CLAUDE.md +0 -0
  22. {python_yama-0.10.7 → python_yama-0.11.0}/LICENSE +0 -0
  23. {python_yama-0.10.7 → python_yama-0.11.0}/README.md +0 -0
  24. {python_yama-0.10.7 → python_yama-0.11.0}/README.zh-CN.md +0 -0
  25. {python_yama-0.10.7 → python_yama-0.11.0}/docs/case-schema-reference.md +0 -0
  26. {python_yama-0.10.7 → python_yama-0.11.0}/docs/superpowers/plans/2026-08-17-concurrency-defaults.md +0 -0
  27. {python_yama-0.10.7 → python_yama-0.11.0}/docs/superpowers/plans/2026-08-17-step-timeout-failure.md +0 -0
  28. {python_yama-0.10.7 → python_yama-0.11.0}/docs/superpowers/specs/2026-08-17-concurrency-defaults-design.md +0 -0
  29. {python_yama-0.10.7 → python_yama-0.11.0}/docs/superpowers/specs/2026-08-17-step-timeout-failure-design.md +0 -0
  30. {python_yama-0.10.7 → python_yama-0.11.0}/docs/yama-intro.html +0 -0
  31. {python_yama-0.10.7 → python_yama-0.11.0}/pyproject.toml +0 -0
  32. {python_yama-0.10.7 → python_yama-0.11.0}/skills/eval-plugin-with-yama/references/install-upgrade.md +0 -0
  33. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_assertions.py +0 -0
  34. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_cli.py +0 -0
  35. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_cli_shim.py +0 -0
  36. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_dashboard.py +0 -0
  37. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_judge_llm.py +0 -0
  38. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_llm.py +0 -0
  39. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_main_entrypoint.py +0 -0
  40. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_mocks.py +0 -0
  41. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_openai_llm.py +0 -0
  42. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_pr.py +0 -0
  43. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_preview.py +0 -0
  44. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_public_api.py +0 -0
  45. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_report_bundle.py +0 -0
  46. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_report_upload.py +0 -0
  47. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_run_plan.py +0 -0
  48. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_runner.py +0 -0
  49. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_skill_loader.py +0 -0
  50. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_skill_tool.py +0 -0
  51. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_thread_case.py +0 -0
  52. {python_yama-0.10.7 → python_yama-0.11.0}/tests/test_workspace.py +0 -0
  53. {python_yama-0.10.7 → python_yama-0.11.0}/uv.lock +0 -0
  54. {python_yama-0.10.7 → python_yama-0.11.0}/yama/__init__.py +0 -0
  55. {python_yama-0.10.7 → python_yama-0.11.0}/yama/__main__.py +0 -0
  56. {python_yama-0.10.7 → python_yama-0.11.0}/yama/assertions.py +0 -0
  57. {python_yama-0.10.7 → python_yama-0.11.0}/yama/cli.py +0 -0
  58. {python_yama-0.10.7 → python_yama-0.11.0}/yama/dashboard.py +0 -0
  59. {python_yama-0.10.7 → python_yama-0.11.0}/yama/judge_llm.py +0 -0
  60. {python_yama-0.10.7 → python_yama-0.11.0}/yama/judge_routing.py +0 -0
  61. {python_yama-0.10.7 → python_yama-0.11.0}/yama/loaders/__init__.py +0 -0
  62. {python_yama-0.10.7 → python_yama-0.11.0}/yama/loaders/case.py +0 -0
  63. {python_yama-0.10.7 → python_yama-0.11.0}/yama/loaders/common.py +0 -0
  64. {python_yama-0.10.7 → python_yama-0.11.0}/yama/loaders/skill_loader.py +0 -0
  65. {python_yama-0.10.7 → python_yama-0.11.0}/yama/models.py +0 -0
  66. {python_yama-0.10.7 → python_yama-0.11.0}/yama/openai_llm.py +0 -0
  67. {python_yama-0.10.7 → python_yama-0.11.0}/yama/pr.py +0 -0
  68. {python_yama-0.10.7 → python_yama-0.11.0}/yama/preview.py +0 -0
  69. {python_yama-0.10.7 → python_yama-0.11.0}/yama/report_bundle.py +0 -0
  70. {python_yama-0.10.7 → python_yama-0.11.0}/yama/report_upload.py +0 -0
  71. {python_yama-0.10.7 → python_yama-0.11.0}/yama/thread_case.py +0 -0
  72. {python_yama-0.10.7 → python_yama-0.11.0}/yama/tools/__init__.py +0 -0
  73. {python_yama-0.10.7 → python_yama-0.11.0}/yama/tools/base.py +0 -0
  74. {python_yama-0.10.7 → python_yama-0.11.0}/yama/tools/bash/__init__.py +0 -0
  75. {python_yama-0.10.7 → python_yama-0.11.0}/yama/tools/skill/__init__.py +0 -0
  76. {python_yama-0.10.7 → python_yama-0.11.0}/yama/tools/skill/skill.py +0 -0
  77. {python_yama-0.10.7 → python_yama-0.11.0}/yama/workspace.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-yama
3
- Version: 0.10.7
3
+ Version: 0.11.0
4
4
  Summary: A reproducible evaluation runner for tool-using Agent skills
5
5
  Project-URL: Repository, https://github.com/world-sim-dev/yama
6
6
  Project-URL: Issues, https://github.com/world-sim-dev/yama/issues
@@ -835,7 +835,7 @@ context:
835
835
  当前内置 Tool 有两个:
836
836
 
837
837
  - `skill`:暴露静态的 Skill 读取 Schema(`name`/`file?`/`call_reason?`,取自生产 skill 工具定义,见 6.4 节),并在未配置 `mocks.tools.skill` 时使用框架内置 Handler;启用集合的约束由默认 Mock 的 `match` 与 Handler 的 `enabled` 检查实现,不在 Schema 里。
838
- - `bash`:暴露一个命令执行 Tool。默认按 `mocks.cli` 声明的命令返回确定性的 stdout / stderr / exit code,未声明的命令一律 `command not found`(exit code 127),详见 8.4.1;需要模型执行任意命令(包括任意 Python 脚本)时改用 `mocks.fs`,在一个真实、隔离的工作目录里执行真实 shell,详见 8.4.3。二者互斥,一个 Case 只能选一种。
838
+ - `bash`:暴露一个命令执行 Tool。默认按 `mocks.cli` 声明的命令返回确定性的 stdout / stderr / exit code,未声明的命令一律 `command not found`(exit code 127),详见 8.4.1;需要模型执行任意命令(包括任意 Python 脚本)时改用 `mocks.fs`,在一个真实、隔离的工作目录里执行真实 shell,详见 8.4.3。可以同时用 `mocks.fs` 配置隔离与文件,并用 `mocks.cli` 声明模拟命令。
839
839
 
840
840
  内置 bash 的 Schema(`loaders/tool_loader.py:_bash_tool_schema`)参考生产 Agent Runner 的 Bash 工具编写:描述是一段完整的使用指引(用途、When to use、Arguments、Execution behavior、Safety constraints),参数为:
841
841
 
@@ -1491,7 +1491,7 @@ Runner 收到 bash Tool Call 后,把整条 `command` 字符串原样交给持
1491
1491
  - 命令未在 `mocks.cli` 中声明、不是 bash 内建命令、且未开启透传(见下)时,得到真实 bash 自己的 `command not found`(`bash: line 2: <name>: command not found\n`,exit code 127;见前述"行号固定为 2"的说明)。
1492
1492
  - Handler 返回值统一为 `{stdout, stderr, exit_code}`,由 8.4.3 节的 marker 协议从持久 shell 的真实 stdout/stderr 中截取;这份完整信封保留在 Mock Event 与 `tool_calls[].result` 中供断言使用。但 Runner 发给模型的 Tool Result Message 只取其中的 `stdout + stderr`(`runner.py:_tool_result_content`,不加分隔符地原样拼接,不再是三个字段的 JSON),贴近真实终端工具"给什么就是什么"的观感;`exit_code` 不出现在模型看到的内容里,模型只能通过输出文本本身判断命令是否成功。这个"bash 形状结果特判"逻辑位于 `runner.py`,而非 `mocks.py`。
1493
1493
 
1494
- `mocks.cli` 只服务于内置 bash 执行实现:Case 里没有任何 `handler: {builtin: bash}` Mock(既没声明 `{builtin: bash}`,也没有自定义 Tool 指向 builtin handler)时出现 `mocks.cli` 在 collection 阶段失败(`"mocks.cli requires a builtin bash handler: ..."`);声明了 `{builtin: bash}` 却用自定义 `mocks.tools.bash` Handler 覆盖其 Mock 时同样失败(`"mocks.cli cannot be combined with a custom mocks.tools.bash handler"`);与 `mocks.fs` 同时出现同样失败(8.4.3 节)。多个 Tool 的 Mock 都指向 `handler: {builtin: bash}` 时共享同一份 `mocks.cli`/`mocks.fs` 执行配置与同一个沙箱会话。
1494
+ `mocks.cli` 只服务于内置 bash 执行实现:Case 里没有任何 `handler: {builtin: bash}` Mock(既没声明 `{builtin: bash}`,也没有自定义 Tool 指向 builtin handler)时出现 `mocks.cli` 在 collection 阶段失败(`"mocks.cli requires a builtin bash handler: ..."`);声明了 `{builtin: bash}` 却用自定义 `mocks.tools.bash` Handler 覆盖其 Mock 时同样失败(`"mocks.cli cannot be combined with a custom mocks.tools.bash handler"`);可以与 `mocks.fs` 共用一个会话(8.4.3 节)。多个 Tool 的 Mock 都指向 `handler: {builtin: bash}` 时共享同一份 `mocks.cli`/`mocks.fs` 执行配置与同一个沙箱会话。
1495
1495
 
1496
1496
  #### 8.4.2 透传:找不到 Mock 时执行真实命令
1497
1497
 
@@ -1520,7 +1520,7 @@ mocks:
1520
1520
  节点/规则级 `passthrough: true`(与 `stdout`/`stderr`/`exit_code` 互斥,同时出现在 collection 阶段失败;`cat: { passthrough: true }` 这种命令级简写其实是一条"无 `match` 的透传规则",并非独立字段——是统一规则/节点语法的自然产物)编译进该命令的规则树后,由 `yama.tools.bash._cli_shim` 在匹配到这条规则时执行 `os.execvpe`,把自己替换成真实二进制——`exec` 时使用的 `PATH` 来自会话环境变量 `YAMA_REAL_PATH`(真实系统 PATH,与 `.mockbin/` 无关),避免二次调用又绕回自己的 shadow 脚本。
1521
1521
 
1522
1522
  - `mocks.cli.passthrough_timeout_seconds`(正数,默认 30):单条命令的超时时间;超时会杀掉整个进程组、重启一个新的沙箱会话(cwd 重置为初始值),以统一的 `BASH_TIMEOUT` 错误返回给模型——不再区分"mock 超时"和"透传超时",因为二者现在共用同一个执行引擎和同一个超时机制。仍受 `execution.timeout_seconds_per_step` 总预算约束。
1523
- - 会话的工作目录是 8.4.3 节描述的隔离沙箱工作目录(`.yama/fs-runs/<case-key>/run-{run_index:03d}/`),不再是 Plugin 根目录;普通 `yama` 运行下 `mocks.cli` 默认使用 `backend: none`(不做 OS 级隔离,`fs.py:compile_cli_config` 硬编码),因此像 `../escape.txt` 这样的写入不会被这一层拦截——它会落在沙箱工作目录的上一级(仍在框架自己的 `.yama/fs-runs/` 树内,不会碰到 Plugin 的真实源码目录),需要 OS 级写入边界时改用 `mocks.fs`,让 `backend: auto` 在 macOS/Linux 上选择对应 backend,或显式选择 `macos-sandbox-exec` / `linux-bubblewrap`。`yama pr-run` 是例外:它会把内置 bash 的执行 backend 统一覆盖为 `linux-bubblewrap`,包括由 `mocks.cli` 编译出来的执行配置。
1523
+ - 会话的工作目录是 8.4.3 节描述的隔离沙箱工作目录(`.yama/fs-runs/<case-key>/run-{run_index:03d}/`),不再是 Plugin 根目录;普通 `yama` 运行下 `mocks.cli` 默认使用 `backend: none`(不做 OS 级隔离,`fs.py:compile_cli_config` 硬编码),因此像 `../escape.txt` 这样的写入不会被这一层拦截——它会落在沙箱工作目录的上一级(仍在框架自己的 `.yama/fs-runs/` 树内,不会碰到 Plugin 的真实源码目录),需要 OS 级写入边界时改用 `mocks.fs`,让 `backend: auto` 在 macOS/Linux 上选择对应 backend,或显式选择 `macos-sandbox-exec` / `linux-bubblewrap`。`yama pr-run` 是例外:它会把内置 bash 的执行 backend 统一覆盖为 `linux-bubblewrap`,并启用 `read_scope: workspace`,包括由 `mocks.cli` 编译出来的执行配置。
1524
1524
  - 透传是显式的安全逃生舱:开启后,模型产生的 Tool Call 会执行真实子进程,不再是纯确定性回放。建议只在本地联调、且信任模型不会拿到危险命令时启用;CI 或需要严格可重复结果的场景应保持默认关闭,逐个命令补齐 Mock。
1525
1525
 
1526
1526
  #### 8.4.3 `mocks.fs`:真实沙箱工作区
@@ -1529,7 +1529,9 @@ mocks:
1529
1529
 
1530
1530
  `mocks.cli` 与 `mocks.fs` 底层是**同一套执行引擎**(`yama/tools/bash/fs.py` 的持久 shell 会话):区别只在于沙箱工作目录里预先放了什么——`mocks.fs.files`/`mocks.fs.bin` 是 Case 作者直接声明的内容,`mocks.cli` 是框架把声明式规则树编译成的 `.mockbin/` 脚本(8.4.1 节)。两者因此共享本节描述的生命周期、marker 协议、PATH shadow 机制、rlimit/环境变量护栏;普通 `yama` 运行下差别仅是 `mocks.cli` 固定用 `backend: none`(不叠加 OS 级 backend),而 `mocks.fs` 默认 `backend: auto`;`yama pr-run` 会把二者统一覆盖为 `linux-bubblewrap`。会话环境变量里始终有 `YAMA_WORKSPACE`(沙箱工作目录绝对路径)、`YAMA_PYTHON`(运行 yama 的解释器路径)、`YAMA_REAL_PATH`(未叠加 `.mockbin/` 的真实系统 PATH,供节点/规则级 `passthrough: true` 或用户自己的 `mocks.fs.bin` 脚本按需 `exec` 真实二进制)。
1531
1531
 
1532
- `mocks.fs` 与 `mocks.cli` **互斥**:一个 Case 要么用 `mocks.cli` 换取完全确定性回放,要么用 `mocks.fs` 换取真实执行能力,二者同时声明在 collection 阶段报错(`"mocks.cli cannot be combined with mocks.fs"`);同样,`mocks.fs` 只在 Case 里存在 `handler: {builtin: bash}` Mock(`{builtin: bash}` 声明或自定义 Tool 指向 builtin handler)时生效,缺失时报错。声明了 `{builtin: bash}` 却用自定义 `mocks.tools.bash` Handler 覆盖其 Mock 时同样报错(`"mocks.fs cannot be combined with a custom mocks.tools.bash handler"`)。
1532
+ `mocks.fs` 与 `mocks.cli` 可以同时使用。会话按 `mocks.fs` 读取文件和执行命令,
1533
+ 同时从 `.mockbin/` 查找声明式 CLI mock。重复定义同名命令会在 collection 阶段报错。
1534
+ 两个配置都要求 Case 使用 `{builtin: bash}` 或 `handler: {builtin: bash}`。
1533
1535
 
1534
1536
  **配置 Schema:**
1535
1537
 
@@ -1544,6 +1546,8 @@ mocks:
1544
1546
  network: false # 可选,默认 false,是否放行沙箱内的网络访问
1545
1547
  backend: auto # 可选:auto(默认)| macos-sandbox-exec | linux-bubblewrap | none
1546
1548
 
1549
+ read_scope: workspace # workspace | host;有 OS 沙箱时默认 workspace
1550
+
1547
1551
  files: # 相对路径 -> 初始内容
1548
1552
  project/README.md: |
1549
1553
  # Demo
@@ -1570,17 +1574,15 @@ mocks:
1570
1574
 
1571
1575
  **生命周期:** 每次 run(含 `execution.repeat` 的每一轮)的沙箱工作目录是
1572
1576
  `<plugin_root>/.yama/fs-runs/<sanitized-case-key>/run-{run_index:03d}/`(三位数字
1573
- 零填充,如 `run-001`),第一次调用 `bash` 工具时才懒加载物化并与一个贯穿整个 run 的
1574
- 持久 bash 子进程绑定。这个路径是 `plugin_root/case_key/run_index` 的纯函数,Python
1577
+ 零填充,如 `run-001`)。声明 `mocks.fs` 时,文件在首轮模型请求前物化。
1578
+ 持久 Bash 子进程在第一次调用时启动。这个路径是 `plugin_root/case_key/run_index` 的纯函数,Python
1575
1579
  Handler 可以在物化发生之前就用包根导出的 `workspace_dir(context)`(定义在
1576
1580
  `tools/bash/fs.py`)预先计算它;首次物化时同一路径也会写入共享 state 的
1577
1581
  `__fs__.workspace_dir`,供没有 `ToolMockContext` 的 Python Checker 读取。
1578
1582
 
1579
- 物化时机以每 run 共享 state 里的 `__fs__` 标记为准,而不是"目录是否已存在"
1580
- (`fs.py:_get_session`):run 的第一次 `bash` 调用总会执行 `materialize_workspace`
1581
- (即使 Python Handler 已提前创建了该目录),把当前 Case 配置声明的 `files`、
1582
- `.mockbin/` 假命令和编译后的 `mocks.cli` 规则文件全部写到最新状态;run 中途因超时/
1583
- 会话死亡而重建 shell 会话时则不再重复物化,模型已写入的文件得以保留。此外
1583
+ 每个 run 会展开初始消息、步骤、状态、mock 配置及自定义 Python mock 返回值中的
1584
+ `{{workspace}}`。例如 `{{workspace}}/work/input.json` 对应 `mocks.fs.files` 的相对路径
1585
+ `work/input.json`。`__fs__` 标记保证超时或会话死亡后的 shell 重启保留当前 run 的文件。此外
1584
1586
  `YamaRunner.run_case` 在一个 Case 的第一轮 run 开始前会整体删除
1585
1587
  `.yama/fs-runs/<sanitized-case-key>/`(`runner.py:_clean_case_dirs`)——run 编号每次
1586
1588
  执行都从 1 重新计数,不先清掉上一次执行遗留的同名工作目录,本次执行就会复用过期的
@@ -1622,44 +1624,16 @@ printf '%s %d\n' '<marker>' "$__yama_ec__" 1>&2
1622
1624
 
1623
1625
  **命令级拦截:PATH shadow 而不是 argv 匹配。** 真实执行下没法安全地在管道中间插入一段模拟结果(`real | mocked | real` 要求真的把标准流接起来喂给模拟阶段)。`mocks.fs.bin` 声明的脚本会被写到工作目录下 `.mockbin/` 并加执行权限,这个目录被 prepend 进沙箱的 `PATH`;任何位置——包括管道、`&&`、子 shell 内部——只要调用到这个命令名,系统真实的 PATH 解析就会找到这个"假二进制",不需要框架自己再解析一次命令行。
1624
1626
 
1625
- **macOS 后端:`sandbox-exec`。** `backend: auto` 在 macOS 上解析为 `macos-sandbox-exec`:持久 shell 整体跑在 `sandbox-exec -f <profile.sb> bash --noprofile --norc` 之下(`profile.sb` 实际文件名固定为 `sandbox.sb`,写在 `workspace_dir` 的**上一级目录**,即 `.yama/fs-runs/<case-key>/sandbox.sb`,与该 run 的 `run-00N/` 目录同级而非其内部),子进程(含 `.mockbin/` 里的假命令、真实 Python 解释器)默认继承同一份限制。生成的 Seatbelt profile 遵循"读放开、写收紧到工作目录、网络默认拒绝"的策略:
1626
-
1627
- ```scheme
1628
- (version 1)
1629
- (deny default)
1630
-
1631
- (allow process-fork)
1632
- (allow process-exec)
1633
- (allow signal (target self))
1634
- (allow sysctl-read)
1635
- (allow mach-lookup)
1636
- (allow iokit-open)
1637
-
1638
- (allow file-read*)
1639
- (allow file-write* (subpath "<workspace>"))
1640
- (allow file-write-data (literal "/dev/null") (literal "/dev/tty") (literal "/dev/dtracehelper"))
1641
-
1642
- (deny file-read* (subpath "<home>/.ssh"))
1643
- (deny file-read* (subpath "<home>/.aws"))
1644
- (deny file-read* (subpath "<home>/.config/gcloud"))
1645
- (deny file-read* (subpath "<home>/.gnupg"))
1646
- (deny file-read* (subpath "<home>/Library/Keychains"))
1647
-
1648
- (deny network*) ; network: true 时省略这条
1649
- ```
1627
+ **macOS 后端 `sandbox-exec`。** 每个 run 的 profile 位于工作目录旁边,例如 `run-001.sb`。
1628
+ `workspace` 允许读取当前 run、系统依赖和解释器运行时,并限制写入当前 run 和必要的设备文件。
1629
+ `host` 保留原来的读取规则及敏感目录屏蔽。macOS 的绝对 `/tmp` 仍受写入限制。
1650
1630
 
1651
- 读权限故意放宽——Python/bash/coreutils 依赖大量系统库、Homebrew/pyenv 路径,逐条收紧读权限在实践中会不断踩坑;真正的边界放在**写**(只能写工作目录)和**网络**(默认整体拒绝)上,读权限只对几类敏感目录做定向拒绝兜底。Seatbelt 的规则解析是"更具体的规则优先于更宽泛的规则",因此 `allow file-read*` 之后追加针对性的 `deny` 是 Seatbelt 里公认可行的写法。Profile 按 run 生成并写入 `.yama/fs-runs/.../sandbox.sb`,排查权限拒绝问题时可以直接读。
1631
+ **Linux 后端 `bubblewrap`。** `workspace` 从空挂载空间开始,只读挂载系统和 Python
1632
+ 运行时,可写挂载当前 run,并提供独立 `/tmp`。`host` 保留宿主根目录的只读挂载,并遮住
1633
+ 原始 HOME 与 `/tmp`。两个模式默认使用独立的网络命名空间。
1652
1634
 
1653
- **Linux 后端:`bubblewrap`。** `backend: auto` 在 Linux 上解析为 `linux-bubblewrap`,
1654
- 持久 shell 跑在 `bwrap`/`bubblewrap` 之下。命令参数使用 PID/IPC namespace,`network:
1655
- false` 时加 `--unshare-net`,把宿主根目录只读挂载,把 yama 工作目录可写 bind 到同一路径,
1656
- 把 `/tmp` 和当前用户 `HOME` 覆盖成 tmpfs,并 `--chdir` 到 `mocks.fs.cwd` 指定的初始目录。
1657
- 这给 eval 提供写入边界和默认网络边界,同时保留足够的只读系统路径让 bash、Python 解释器
1658
- 和 `.mockbin` shim 正常运行。它不是面向任意不可信代码的强保密沙箱:宿主根目录大部分仍
1659
- 可只读访问,只是当前用户 HOME 被 tmpfs 遮住以避免常见凭据目录被读到。Linux runner 缺少
1660
- `bwrap`/`bubblewrap` 二进制时会报
1661
- `"mocks.fs.backend: linux-bubblewrap requires bubblewrap; install the bwrap package"`;
1662
- Ubuntu 系 CI 里通常需要先安装 `bubblewrap` 包。
1635
+ `workspace` 模式为每个 run 设置独立的 `HOME`、`TMPDIR` 和 Python 缓存目录。PR 评测
1636
+ 强制使用 `linux-bubblewrap` 和 `workspace`,需要提前安装 `bubblewrap`。
1663
1637
 
1664
1638
  其他平台的 `backend: auto` 在 collection 阶段直接报错(`"mocks.fs has no sandboxing
1665
1639
  backend on this platform; set mocks.fs.backend: none to run without OS-level isolation"`),
@@ -1678,7 +1652,7 @@ backend on this platform; set mocks.fs.backend: none to run without OS-level iso
1678
1652
  context.tools: [{builtin: bash}] # 或自定义 Tool + handler: {builtin: bash}
1679
1653
  │
1680
1654
  ▼
1681
- loaders.tool_loader.resolve_builtin_handlers # 校验+归一化 mocks.cli / mocks.fs,二选一
1655
+ loaders.tool_loader.resolve_builtin_handlers # 校验并归一化 mocks.cli 和 mocks.fs
1682
1656
  │ 把每条 handler: {builtin: bash} 展开为
1683
1657
  │ handler.python = "yama.tools.bash.bash:run_bash"
1684
1658
  ▼
@@ -2442,23 +2416,34 @@ class CaseResult:
2442
2416
  def request_duration_ms(self) -> float | None: ... # 各 run request_duration_ms() 之和
2443
2417
  ```
2444
2418
 
2445
- **Token 用量统计**没有独立的 `Usage` 类,而是一条贯穿各层的普通字典字段
2446
- (`{"prompt_tokens", "completion_tokens", "total_tokens"}`,值均为 int):
2419
+ **Token 用量统计**没有独立的 `Usage` 类,而是一条贯穿各层的普通字典字段。
2420
+ `prompt_tokens`、`completion_tokens`、`total_tokens` 是始终参与聚合的三个核心 int
2421
+ 计数器;Provider 返回缓存读取数据时,字典另带可选的 `cache_read_tokens` int:
2447
2422
 
2448
2423
  - **采集**:`llm.py:_normalized_usage` 把 Provider 返回的 usage 负载规范化成上述
2449
- 三个计数器(丢弃 `prompt_tokens_details` 等 Provider 特有的明细块;缺
2450
- `total_tokens` 时用 prompt+completion 补齐;三个计数器都缺时得到 `None`),挂在
2451
- `LLMResponse.usage`。`ScriptedLLMClient` 的脚本响应可带可选的 `usage` 键,走同一
2452
- 个规范化(用于测试与回放)。
2424
+ 三个核心计数器(缺 `total_tokens` 时仍用 prompt+completion 补齐;三个核心计数器
2425
+ 都缺时得到 `None`),挂在 `LLMResponse.usage`。输入、输出、总量完全沿用 Provider
2426
+ 的 `prompt_tokens` / `completion_tokens` / `total_tokens` 语义,不反推输入、不额外
2427
+ 累加 reasoning token。Cache Read 按 `prompt_tokens_details.cached_tokens`、
2428
+ `cache_read_input_tokens`、`cached_content_token_count`、`cache_tokens`、
2429
+ `prompt_cache_hit_tokens` 的顺序取第一个有效非负值;多个别名不相加,也不把 Cache
2430
+ Read 加入 prompt/total。`ScriptedLLMClient` 的脚本响应可带可选的 `usage` 键,走
2431
+ 同一个规范化(用于测试与回放)。
2453
2432
  - **记录**:tool-loop 的每次请求把非空 usage 写进对应请求记录
2454
2433
  (`requests[].usage`,见 `runner.py:_run_step`);Judge 调用不经过 `requests`
2455
2434
  记录,`assertions.py:run_judge` 把它的 usage 补在返回的 `judge_result["usage"]`
2456
2435
  上(Provider 未报用量时两处都没有该键)。
2457
- - **聚合**:`runner.py:combine_usage` 对多个 usage 字典逐键求和,全部无数据时返回
2436
+ - **聚合**:`runner.py:combine_usage` 对三个核心计数器逐键求和,全部无数据时返回
2458
2437
  `None`(「没有数据」与「0 token」必须可区分——脚本回放或中途死掉的 run 不应显示
2459
- 成 0)。`RunResult.usage()` = 该 run 全部 `requests[].usage` + 各 Step
2460
- `judge_result["usage"]` 之和;`CaseResult.usage()` = 各 run 之和。两者的
2461
- `to_dict()` 都带 `usage` 字段,因此 `result.json` 与 `--json` 输出天然携带。
2438
+ 成 0)。可选 `cache_read_tokens` 只累加实际返回的有效值:所有调用都缺失时聚合结果
2439
+ 继续缺失该键,明确返回 0 时则保留 0。`RunResult.usage()` = 该 run 全部
2440
+ `requests[].usage` + 各 Step `judge_result["usage"]` 之和;`CaseResult.usage()` = 各
2441
+ run 之和。两者的 `to_dict()` 都带 `usage` 字段,因此 `result.json` 与 `--json`
2442
+ 输出天然携带。HTML Run 标题、comparison 表和 Case 顶部 metadata 在
2443
+ `prompt_tokens > 0` 且 `0 <= cache_read_tokens <= prompt_tokens` 时展示两位小数的
2444
+ `cache_read_tokens / prompt_tokens`;Case 级比例直接使用 `CaseResult.usage()`,即
2445
+ `所有 Run 的 cache_read_tokens 之和 / 所有 Run 的 prompt_tokens 之和`,不是逐 Run
2446
+ 百分比的平均值。缺失或异常时显示 `–`。
2462
2447
  - **耗时**:tool-loop 的每次请求都会在 `requests[].duration_ms` 记录本轮
2463
2448
  `llm.complete()` 耗时。`runner.py:combine_duration_ms` 对这些毫秒数求和,
2464
2449
  全部无数据时返回 `None`。`RunResult.request_duration_ms()` =
@@ -2628,7 +2613,7 @@ def check(
2628
2613
  - `step_result` 是当前 Step 的 `StepResult`,其 `tool_calls` 是 `ToolCallRecord` 列表(`request_index`/`call_index`/`call: ToolCall`/`result`/`is_error`)。
2629
2614
  - `transcript` 是截至当前 Step 结束的完整消息序列的深拷贝元组(包含本 Step 的 user/assistant/tool 消息),只读。
2630
2615
  - `state` 与 Python Handler 共享同一个 run 级 Mock state dict(不是拷贝);`config` 是该断言 `with:` 的深拷贝,未写时为 `{}`。
2631
- - Checker 没有 `ToolMockContext`,需要 bash 沙箱工作目录时读 `state["__fs__"]["workspace_dir"]`(首次 `bash` 调用后由 8.4.3 的会话初始化写入)。
2616
+ - Checker 没有 `ToolMockContext`,需要 bash 沙箱工作目录时读 `state["__fs__"]["workspace_dir"]`(由 8.4.3 的工作区物化逻辑写入)。
2632
2617
 
2633
2618
  所有 Hard Assert 按声明顺序执行并分别保存结果,**不会短路**:任一失败都会令当前 Step 的 `hard_pass=false`;后续 Hard Assert 仍继续执行,以便一次报告全部确定性问题。
2634
2619
 
@@ -134,7 +134,7 @@ outcome:
134
134
  Skill 名或 Tool 名。
135
135
  4. 每个 Tool 条目在 `builtin` / `file` / `inline` 中三选一;`mocks.tools.<name>` 的
136
136
  `respond` 与 `handler` 二选一。
137
- 5. `mocks.cli` 与 `mocks.fs` 互斥,且都要求 Case 里存在内置 bash 执行——声明
137
+ 5. `mocks.cli` 和 `mocks.fs` 可共用一个沙箱会话,且都要求 Case 里存在内置 bash 执行——声明
138
138
  `{builtin: bash}`,或某个 Tool 的 Mock 使用 `handler: {builtin: bash}`;
139
139
  也不能与自定义 `mocks.tools.bash` Handler 并存。
140
140
  6. `steps` 至少一个,每个 Step 必须有 Case 内唯一的 `id` 和 `user`。
@@ -299,7 +299,10 @@ macOS 在 exFAT 等卷上生成的 AppleDouble `._*.yaml` 会在解析前被忽
299
299
  `LLM error` / `Framework error` 文本在对应 Case header 里看。每轮 LLM Request
300
300
  详情会展示 Method、Duration、Arguments、Response,Response 是完整 assistant
301
301
  message(含 tool_calls);Case/Run/Step 层级仍展示 tool-loop LLM Request
302
- 耗时总和。
302
+ 耗时总和。Provider 返回 Cache Read 时,Run 标题与 comparison 表还会展示输入、输出、
303
+ 总 Token 和 `Cache Read / prompt_tokens` 的缓存读取占比;Case 顶部 metadata 会按所有
304
+ Run 的 Token 总量计算同一口径的加权占比,而不是对各 Run 的百分比取平均。未返回或
305
+ 比例异常时显示 `–`。
303
306
 
304
307
  当仓库 CI 使用 `yama pr-run --report --upload-report --commit-id <sha>` 时,yama 会上传当前
305
308
  commit 报告、每个运行到的 Case 详情报告,并更新受影响 Plugin 的远端 latest 报告。
@@ -281,7 +281,9 @@ mocks:
281
281
 
282
282
  ### `{builtin: bash}` + mocks.fs:真实沙箱工作区
283
283
 
284
- 模型需要执行**任意**命令(尤其任意 Python 脚本)时用 `mocks.fs`(与 `mocks.cli` 互斥):
284
+ 用 `mocks.fs` 配置 Bash 的运行目录和读取权限,也可同时用 `mocks.cli` 声明模拟命令。
285
+ 组合使用时,未被模拟的命令仍可从系统 `PATH` 查找。同一个命令名只能在
286
+ `mocks.fs.bin` 和 `mocks.cli` 中声明一次。
285
287
 
286
288
  ```yaml
287
289
  mocks:
@@ -289,6 +291,7 @@ mocks:
289
291
  cwd: project # 初始 cwd,相对工作目录
290
292
  network: false # 默认拒绝网络
291
293
  backend: auto # macOS=sandbox-exec;Linux=bubblewrap;其它平台显式 none
294
+ read_scope: workspace # workspace | host
292
295
  files:
293
296
  project/README.md: "# Demo\n"
294
297
  project/src/main.py: { file: fixtures/main.py, mode: "0755" }
@@ -303,14 +306,21 @@ mocks:
303
306
  - 工作目录:`<plugin_root>/.yama/fs-runs/<case-key>/run-00N/`,run 结束**不清理**,
304
307
  供排查;下一次执行同一 Case 时才整体清掉重建(改 mock 配置后重跑不会复用旧
305
308
  `.mockbin` 脚本)。持久 bash 会话贯穿整个 run,`cd`/`export`/写文件状态自然延续。
309
+ - 有 OS 沙箱时,`read_scope` 默认 `workspace`,可读取当前 run、系统工具及 Python 运行时。
310
+ `HOME`、`TMPDIR` 和 Python 字节码缓存使用 run 内的目录。`host` 使用该后端原有的读取策略。
311
+ `backend: none` 仅支持 `host`。
312
+ - 字符串值可使用 `{{workspace}}`,例如 `{{workspace}}/work/input.json`。每个 run 会展开
313
+ 初始消息、步骤、`mocks.state` 和 mock 配置(包括声明式返回值和 `mocks.cli` 输出),
314
+ 也会展开自定义 Python mock 返回的字符串值。
315
+ 在 `mocks.fs.files` 中以相对路径 `work/input.json` 声明文件。
306
316
  - Python Handler 可用 `from yama import workspace_dir` 提前算出该路径
307
- (`workspace_dir(context)`,纯函数,物化前即可调用);首次 bash 调用后同一路径
308
- 写入共享 state 的 `__fs__.workspace_dir`,供没有 context 的 Python Checker 读取。
317
+ (`workspace_dir(context)`,物化前即可调用)。显式配置 `mocks.fs` 时,yama 在模型首轮
318
+ 请求前物化文件并写入共享 state 的 `__fs__.workspace_dir`,供 Python Checker 读取。
309
319
  - 单条命令超时(默认 30s;模型通过 bash Tool 的 `timeout_seconds` 参数请求更短
310
320
  超时会生效,超过配置上限被钳到上限)→ `BASH_TIMEOUT` 错误返回给模型并重启会话。
311
321
  - 会话内可用环境变量:`YAMA_WORKSPACE`、`YAMA_PYTHON`、`YAMA_REAL_PATH`。
312
- - `yama pr-run` 面向 Linux CI runner:它会忽略 Case 里的 backend 设置,统一强制内置
313
- bash 使用 `linux-bubblewrap`。因此 PR CI 环境必须安装 `bwrap`/`bubblewrap`;普通
322
+ - `yama pr-run` 面向 Linux CI runner:它会统一强制内置 bash 使用
323
+ `linux-bubblewrap` 和 `read_scope: workspace`。因此 PR CI 环境必须安装 `bwrap`/`bubblewrap`;普通
314
324
  `yama` 运行仍按这里声明的 `backend` / `auto` 规则执行。
315
325
  - 远端 Plugin latest 报告里的 Case 身份就是 `case_key`(相对 Plugin Root 的 Case 路径)。
316
326
  `yama pr-run --report --upload-report --commit-id <sha>` 合并远端报告时,会用相同
@@ -32,11 +32,11 @@
32
32
 
33
33
  | 文件 | 内容 | 什么时候看 |
34
34
  | --- | --- | --- |
35
- | `result.json` | run 是否通过、`status`(`pass`/`fail`/`error`)、`error`/`traceback`、全量数据汇总(含 run 级 `usage` token 汇总、`request_duration_ms` LLM Request 耗时汇总、`runs[].tag_summary` 与每个 Step 的 `tag_summary`,Provider 未报用量时 usage 为 null) | **永远先看**:status/error 决定排查层级 |
35
+ | `result.json` | run 是否通过、`status`(`pass`/`fail`/`error`)、`error`/`traceback`、全量数据汇总(含 run 级 `usage` token 汇总、`request_duration_ms` LLM Request 耗时汇总、`runs[].tag_summary` 与每个 Step 的 `tag_summary`,Provider 未报用量时 usage 为 null;Provider 返回缓存读取时 usage 另带可选 `cache_read_tokens`) | **永远先看**:status/error 决定排查层级 |
36
36
  | `hard-checks.json` | `{step_id: [每条断言的 type/passed/label/expected/actual/reason/detail]}` | Step 断言失败时 |
37
37
  | `mock-events.json` | 每次 Tool 调用:`tool/arguments/result/is_error/match_failed/state_diff/duration_ms`。`is_error` 是语义判定:结果带**非 null** `error`,或 bash 信封 `exit_code != 0`;成功结果里的 `error: null` 不算错误 | 怀疑 Mock 匹配 / Tool 行为时 |
38
38
  | `mock-state.json` | run 结束时的最终共享 state | 有状态 Handler / Python Checker 断言失败时 |
39
- | `requests/request-00N.json` | 每次真实 LLM 调用的完整入参(messages/tools)、完整 assistant response 与 `duration_ms`;请求失败时带 `error` 字段,Provider 报了用量时带 `usage`(prompt/completion/total tokens) | 怀疑「模型到底看到了什么」或哪一轮慢时 |
39
+ | `requests/request-00N.json` | 每次真实 LLM 调用的完整入参(messages/tools)、完整 assistant response 与 `duration_ms`;请求失败时带 `error` 字段,Provider 报了用量时带 `usage`(prompt/completion/total tokens,以及可选的 Cache Read) | 怀疑「模型到底看到了什么」或哪一轮慢时 |
40
40
  | `transcript.json` | 每个 Step 结束后的完整对话快照(含注入消息、Tool Result) | 复盘模型行为时 |
41
41
  | `rendered-system-prompt.txt` | 实际发送的 System Prompt(含 `<available_skills>`) | 怀疑 Skill 没暴露 / 渲染不对时 |
42
42
  | `case.resolved.yaml` | Case 展开后的编译产物 | 怀疑路径 / 默认值解析不符合预期时 |
@@ -45,7 +45,9 @@
45
45
 
46
46
  `--report` 生成自包含 HTML,逐 Case/Run/Step 展示 transcript、Tool Call、断言、
47
47
  LLM token 用量与 LLM Request 耗时(顶部 `CASES PASSED` / `CASES ERRORS` /
48
- `LLM TOKENS` 汇总卡片 + 各层级耗时明细)。每轮 LLM Request
48
+ `LLM TOKENS` 汇总卡片 + 各层级耗时明细;每个 Run 还会展示输入、输出、总 Token,
49
+ Provider 返回 Cache Read 时展示 `Cache Read / prompt_tokens` 的缓存读取占比;Case 顶部
50
+ metadata 按所有 Run 的 Cache Read 与 prompt token 总和计算加权占比)。每轮 LLM Request
49
51
  详情会同时展示 Method、Duration、Arguments、Response,Response 是完整 assistant
50
52
  message(含 tool_calls),适合人工浏览;省略路径时默认写带
51
53
  时间戳的 `.yama/reports/report-<ts>.html`(历史累积,`latest.html` 是指向最新
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import json
4
+ import shlex
4
5
  import shutil
5
6
  import sys
6
7
  import tempfile
@@ -15,7 +16,7 @@ import yaml
15
16
  from yama.assertions import run_hard_assertions
16
17
  from yama.cli import format_text_results
17
18
  from yama.workspace import DEFAULT_CASE_PATTERNS, WorkspaceConfig, load_workspace_config
18
- from yama.tools.bash.fs import _SESSIONS, cleanup_session
19
+ from yama.tools.bash.fs import _SESSIONS, cleanup_session, run_workspace
19
20
  from yama.llm import LLMClient, LiteLLMClient, LLMError, ScriptedLLMClient
20
21
  from yama.loaders import CollectionError, resolve_case
21
22
  from yama.mocks import MockConfigurationError, MockToolRegistry, ToolMockContext
@@ -2743,7 +2744,7 @@ class BashFsBackendSelectionTests(unittest.TestCase):
2743
2744
  self.assertEqual(executable, "/usr/bin/bwrap")
2744
2745
  self.assertIn("--unshare-net", argv)
2745
2746
  self.assertIn("--bind", argv)
2746
- self.assertIn("/tmp/yama-workspace", argv)
2747
+ self.assertIn(str(Path("/tmp/yama-workspace").resolve()), argv)
2747
2748
  self.assertIn("--tmpfs", argv)
2748
2749
  self.assertIn(str(Path.home()), argv)
2749
2750
 
@@ -2792,7 +2793,24 @@ class BashFsBackendSelectionTests(unittest.TestCase):
2792
2793
  argv, _ = session._command_argv()
2793
2794
 
2794
2795
  chdir_index = argv.index("--chdir")
2795
- self.assertEqual(argv[chdir_index + 1], "/tmp/yama-workspace/project")
2796
+ self.assertEqual(argv[chdir_index + 1], str(Path("/tmp/yama-workspace/project").resolve()))
2797
+
2798
+ def test_bubblewrap_workspace_scope_mounts_only_runtime_and_run(self) -> None:
2799
+ from yama.tools.bash.fs import _bubblewrap_argv
2800
+
2801
+ workspace = Path("/tmp/yama-workspace")
2802
+ with patch("yama.tools.bash.fs.shutil.which", return_value="/usr/bin/bwrap"):
2803
+ argv, _ = _bubblewrap_argv(
2804
+ workspace, cwd=workspace, network=False,
2805
+ bash_path="/bin/bash", read_scope="workspace",
2806
+ )
2807
+
2808
+ read_binds = [(argv[index + 1], argv[index + 2]) for index, flag in enumerate(argv) if flag == "--ro-bind"]
2809
+ self.assertIn(("/usr", "/usr"), read_binds)
2810
+ self.assertNotIn(("/", "/"), read_binds)
2811
+ self.assertNotIn(("/etc", "/etc"), read_binds)
2812
+ self.assertNotIn(str(Path.home()), argv)
2813
+ self.assertLess(argv.index("--tmpfs"), argv.index("--bind"))
2796
2814
 
2797
2815
 
2798
2816
  class BashFsMockTests(unittest.IsolatedAsyncioTestCase):
@@ -2858,17 +2876,22 @@ class BashFsMockTests(unittest.IsolatedAsyncioTestCase):
2858
2876
  ):
2859
2877
  self.resolve(plugin_root, case_path)
2860
2878
 
2861
- def test_fs_mock_conflicts_with_cli_mock(self) -> None:
2879
+ async def test_fs_and_cli_mocks_share_the_workspace(self) -> None:
2862
2880
  with tempfile.TemporaryDirectory() as temporary:
2863
2881
  plugin_root = Path(temporary)
2864
- case_path = self.write_case(plugin_root, {"backend": "none"})
2882
+ case_path = self.write_case(plugin_root, {
2883
+ "backend": "none", "files": {"fixture.txt": "inside\n"},
2884
+ })
2865
2885
  raw = yaml.safe_load(case_path.read_text(encoding="utf-8"))
2866
- raw["mocks"]["cli"] = {"passthrough": True}
2886
+ raw["mocks"]["cli"] = {"vidmuse": "mocked\n"}
2867
2887
  case_path.write_text(yaml.safe_dump(raw, allow_unicode=True), encoding="utf-8")
2868
- with self.assertRaisesRegex(
2869
- CollectionError, "cannot be combined with mocks.fs"
2870
- ):
2871
- self.resolve(plugin_root, case_path)
2888
+ case = self.resolve(plugin_root, case_path)
2889
+ registry, call = self.open_session(case)
2890
+ try:
2891
+ result = await call("cat fixture.txt && vidmuse")
2892
+ self.assertEqual(result, {"stdout": "inside\nmocked\n", "stderr": "", "exit_code": 0})
2893
+ finally:
2894
+ await cleanup_session(registry.state)
2872
2895
 
2873
2896
  def test_fs_mock_conflicts_with_custom_bash_handler(self) -> None:
2874
2897
  with tempfile.TemporaryDirectory() as temporary:
@@ -2885,6 +2908,8 @@ class BashFsMockTests(unittest.IsolatedAsyncioTestCase):
2885
2908
  def test_invalid_fs_mock_configs_fail_collection(self) -> None:
2886
2909
  for fs, message in [
2887
2910
  ({"backend": "docker"}, "backend must be one of"),
2911
+ ({"read_scope": "unknown"}, "read_scope must be workspace or host"),
2912
+ ({"backend": "none", "read_scope": "workspace"}, "workspace requires a sandbox backend"),
2888
2913
  ({"cwd": "../escape"}, "cannot contain '..'"),
2889
2914
  ({"files": {"a.txt": {}}}, "must set exactly one of content or file"),
2890
2915
  (
@@ -2904,6 +2929,101 @@ class BashFsMockTests(unittest.IsolatedAsyncioTestCase):
2904
2929
  with self.assertRaisesRegex(CollectionError, message):
2905
2930
  self.resolve(plugin_root, case_path)
2906
2931
 
2932
+ async def test_workspace_placeholder_is_resolved_per_run(self) -> None:
2933
+ with tempfile.TemporaryDirectory(prefix="yama workspace ") as temporary:
2934
+ plugin_root = Path(temporary)
2935
+ case_path = self.write_case(plugin_root, {
2936
+ "backend": "none", "files": {"work/fixture.txt": "content\n"},
2937
+ })
2938
+ raw = yaml.safe_load(case_path.read_text(encoding="utf-8"))
2939
+ template = "{{workspace}}/work/fixture.txt"
2940
+ raw["execution"] = {"repeat": 2}
2941
+ raw["context"]["messages"] = [{"role": "user", "content": f"Earlier: {template}"}]
2942
+ raw["context"]["tools"].append({"inline": {
2943
+ "name": "lookup", "description": "Look up the fixture",
2944
+ "parameters": {"type": "object", "properties": {}},
2945
+ }})
2946
+ raw["context"]["tools"].append({"inline": {
2947
+ "name": "python_lookup", "description": "Check the fixture from a Python mock",
2948
+ "parameters": {"type": "object", "properties": {}},
2949
+ }})
2950
+ (case_path.parent.parent / "fixture_mock.py").write_text(
2951
+ "from pathlib import Path\n"
2952
+ "def lookup(*, arguments, context, config):\n"
2953
+ " return {'path': '{{workspace}}/work/fixture.txt',\n"
2954
+ " 'content': Path(context.state['path']).read_text()}\n",
2955
+ encoding="utf-8",
2956
+ )
2957
+ raw["mocks"]["state"] = {"path": template}
2958
+ raw["mocks"]["tools"] = {
2959
+ "lookup": {"respond": {"result": {"path": template}}},
2960
+ "python_lookup": {"handler": {"python": "fixture_mock.py:lookup"}},
2961
+ }
2962
+ raw["mocks"]["cli"] = {"list-fixture": {"stdout": template}}
2963
+ raw["steps"][0]["user"] = f"Read: {template}"
2964
+ raw["steps"][0]["message_inject"] = [{
2965
+ "position": "before_user_message",
2966
+ "message": {"role": "user", "content": f"Injected: {template}"},
2967
+ }]
2968
+ case_path.write_text(yaml.safe_dump(raw), encoding="utf-8")
2969
+ case = self.resolve(plugin_root, case_path)
2970
+ paths = [str(run_workspace(case.plugin_root, case.case_key, number) / "work/fixture.txt") for number in (1, 2)]
2971
+ responses = []
2972
+ for path in paths:
2973
+ responses.extend([
2974
+ {"tool_calls": [
2975
+ {"name": "lookup", "arguments": {}},
2976
+ {"name": "python_lookup", "arguments": {}},
2977
+ {"name": "bash", "arguments": {"command": f"cat {shlex.quote(path)} && list-fixture"}},
2978
+ {"name": "bash", "arguments": {"command": "printf '%s' '{{workspace}}'"}},
2979
+ ]},
2980
+ {"content": "done"},
2981
+ ])
2982
+ llm = ScriptedLLMClient(responses)
2983
+ result = await YamaRunner(llm, write_artifacts=False).run_case(case)
2984
+
2985
+ self.assertTrue(result.passed, result.to_dict())
2986
+ for index, (run, path) in enumerate(zip(result.runs, paths)):
2987
+ self.assertEqual(run.mock_state["path"], path)
2988
+ self.assertEqual(run.mock_events[0]["result"], {"path": path})
2989
+ self.assertEqual(run.mock_events[1]["result"], {"path": path, "content": "content\n"})
2990
+ self.assertEqual(run.mock_events[2]["result"]["stdout"], f"content\n{path}")
2991
+ self.assertEqual(run.mock_events[3]["result"]["stdout"], "{{workspace}}")
2992
+ contents = [message["content"] for message in llm.requests[index * 2]["messages"]]
2993
+ self.assertIn(f"Earlier: {path}", contents)
2994
+ self.assertIn(f"Injected: {path}", contents)
2995
+ self.assertIn(f"Read: {path}", contents)
2996
+ self.assertEqual(case.mocks["state"]["path"], template)
2997
+
2998
+ @unittest.skipUnless(
2999
+ sys.platform == "darwin" or (sys.platform.startswith("linux") and shutil.which("bwrap")),
3000
+ "requires a native Bash sandbox backend",
3001
+ )
3002
+ async def test_workspace_scope_hides_cases_and_other_runs_with_cli_mock_enabled(self) -> None:
3003
+ with tempfile.TemporaryDirectory() as temporary:
3004
+ plugin_root = Path(temporary)
3005
+ case_path = self.write_case(plugin_root, {
3006
+ "files": {"work/fixture.txt": "fixture\n"},
3007
+ })
3008
+ raw = yaml.safe_load(case_path.read_text(encoding="utf-8"))
3009
+ raw["mocks"]["cli"] = {"vidmuse": "mock available\n"}
3010
+ case_path.write_text(yaml.safe_dump(raw), encoding="utf-8")
3011
+ case = self.resolve(plugin_root, case_path)
3012
+ second_run = run_workspace(case.plugin_root, case.case_key, 2)
3013
+ second_run.mkdir(parents=True)
3014
+ outside_file = second_run / "sentinel.txt"
3015
+ outside_file.write_text("another run\n", encoding="utf-8")
3016
+ registry, call = self.open_session(case)
3017
+ try:
3018
+ inside = await call('cat work/fixture.txt && vidmuse && printf ok > "$TMPDIR/probe"')
3019
+ self.assertEqual(inside, {"stdout": "fixture\nmock available\n", "stderr": "", "exit_code": 0})
3020
+ for outside in (case_path, outside_file):
3021
+ result = await call(f"cat {shlex.quote(str(outside))}")
3022
+ self.assertNotEqual(result["exit_code"], 0, result)
3023
+ self.assertEqual(result["stdout"], "")
3024
+ finally:
3025
+ await cleanup_session(registry.state)
3026
+
2907
3027
  async def test_fs_mock_materializes_files_and_persists_state_across_calls(
2908
3028
  self,
2909
3029
  ) -> None:
@@ -537,6 +537,7 @@ class TokenUsageReportTests(unittest.TestCase):
537
537
  "prompt_tokens": 50,
538
538
  "completion_tokens": 10,
539
539
  "total_tokens": 60,
540
+ "cache_read_tokens": 40,
540
541
  },
541
542
  },
542
543
  )
@@ -553,6 +554,7 @@ class TokenUsageReportTests(unittest.TestCase):
553
554
  "prompt_tokens": 1000,
554
555
  "completion_tokens": 200,
555
556
  "total_tokens": 1200,
557
+ "cache_read_tokens": 800,
556
558
  },
557
559
  }
558
560
  ],
@@ -575,6 +577,101 @@ class TokenUsageReportTests(unittest.TestCase):
575
577
  # Judge section shows its own call's consumption.
576
578
  self.assertIn("60 tokens (50 in / 10 out)", html)
577
579
 
580
+ def test_run_summary_shows_aggregate_cache_read_share(self) -> None:
581
+ case = _make_case("")
582
+ html = render_html_report([case], [self.make_result(case)])
583
+ self.assertIn(
584
+ "1,260 tokens (1,050 in / 210 out) · cache read 80.00%",
585
+ html,
586
+ )
587
+
588
+ def test_case_metadata_uses_weighted_cache_read_share_across_runs(self) -> None:
589
+ case = _make_case("")
590
+ result = self.make_result(case)
591
+ result.runs.append(
592
+ RunResult(
593
+ run_index=2,
594
+ passed=True,
595
+ requests=[
596
+ {
597
+ "step_id": "greet",
598
+ "request_index": 0,
599
+ "usage": {
600
+ "prompt_tokens": 150,
601
+ "completion_tokens": 10,
602
+ "total_tokens": 160,
603
+ "cache_read_tokens": 30,
604
+ },
605
+ }
606
+ ],
607
+ )
608
+ )
609
+
610
+ html = render_html_report([case], [result])
611
+
612
+ # Weighted case share: (840 + 30) / (1,050 + 150), not (80% + 20%) / 2.
613
+ self.assertIn(
614
+ "<div><span>Cache read</span><strong>72.50%</strong></div>",
615
+ html,
616
+ )
617
+
618
+ def test_run_comparison_separates_total_input_output_and_cache_read(self) -> None:
619
+ case = _make_case("")
620
+ result = self.make_result(case)
621
+ result.runs.append(replace(result.runs[0], run_index=2))
622
+
623
+ html = render_html_report([case], [result])
624
+
625
+ self.assertIn(
626
+ "<th>Total tokens</th><th>Input tokens</th>"
627
+ "<th>Output tokens</th><th>Cache read</th>",
628
+ html,
629
+ )
630
+ self.assertIn(
631
+ "<td>1,260</td><td>1,050</td><td>210</td><td>80.00%</td>",
632
+ html,
633
+ )
634
+
635
+ def test_run_cache_read_share_preserves_zero(self) -> None:
636
+ case = _make_case("")
637
+ result = self.make_result(case)
638
+ result.runs[0].requests[0]["usage"]["cache_read_tokens"] = 0
639
+ result.runs[0].steps[0].judge_result["usage"]["cache_read_tokens"] = 0
640
+
641
+ html = render_html_report([case], [result])
642
+
643
+ self.assertIn("cache read 0.00%", html)
644
+
645
+ def test_run_cache_read_share_is_unavailable_when_not_reported(self) -> None:
646
+ case = _make_case("")
647
+ result = self.make_result(case)
648
+ result.runs[0].requests[0]["usage"].pop("cache_read_tokens")
649
+ result.runs[0].steps[0].judge_result["usage"].pop("cache_read_tokens")
650
+ result.runs.append(replace(result.runs[0], run_index=2))
651
+
652
+ html = render_html_report([case], [result])
653
+
654
+ self.assertNotIn("cache read ", html)
655
+ self.assertIn(
656
+ "<td>1,260</td><td>1,050</td><td>210</td><td>–</td>",
657
+ html,
658
+ )
659
+
660
+ def test_run_cache_read_share_rejects_values_above_input(self) -> None:
661
+ case = _make_case("")
662
+ result = self.make_result(case)
663
+ result.runs[0].requests[0]["usage"]["cache_read_tokens"] = 1001
664
+ result.runs[0].steps[0].judge_result["usage"]["cache_read_tokens"] = 50
665
+ result.runs.append(replace(result.runs[0], run_index=2))
666
+
667
+ html = render_html_report([case], [result])
668
+
669
+ self.assertNotIn("cache read ", html)
670
+ self.assertIn(
671
+ "<td>1,260</td><td>1,050</td><td>210</td><td>–</td>",
672
+ html,
673
+ )
674
+
578
675
  def test_step_summaries_carry_a_step_number_prefix_and_id_chip(self) -> None:
579
676
  case = _make_case("")
580
677
  html = render_html_report([case], [self.make_result(case)])
@@ -607,6 +704,7 @@ class TokenUsageReportTests(unittest.TestCase):
607
704
  )
608
705
  html = render_html_report([case], [result])
609
706
  self.assertIn("<div><span>LLM tokens</span><strong>–</strong></div>", html)
707
+ self.assertIn("<div><span>Cache read</span><strong>–</strong></div>", html)
610
708
  self.assertIn('<div class="summary-card"><span>LLM TOKENS</span><strong>–</strong></div>', html)
611
709
 
612
710