python-yama 0.1.0__py3-none-any.whl → 0.3.0__py3-none-any.whl

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.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-yama
3
+ Version: 0.3.0
4
+ Summary: A reproducible evaluation runner for tool-using Agent skills
5
+ Project-URL: Repository, https://github.com/world-sim-dev/yama
6
+ Project-URL: Issues, https://github.com/world-sim-dev/yama/issues
7
+ Author-email: Farmer Sun <podpodiumapp@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: agent,evaluation,llm,skill,testing
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Software Development :: Testing
17
+ Requires-Python: >=3.12
18
+ Requires-Dist: fastapi>=0.139.0
19
+ Requires-Dist: jinja2>=3.1
20
+ Requires-Dist: litellm<2.0,>=1.80
21
+ Requires-Dist: orjson>=3.11.9
22
+ Requires-Dist: pyyaml>=6.0
23
+ Requires-Dist: rich<15.0,>=14.1
24
+ Description-Content-Type: text/markdown
25
+
26
+ # yama
27
+
28
+ English | [简体中文](https://github.com/world-sim-dev/yama/blob/main/README.zh-CN.md)
29
+
30
+ `yama` is a reproducible evaluation framework for tool-using Agent Skills: a declarative YAML Case describes what the model sees — the system prompt, Skill metadata, tool schemas, and multi-turn user messages — then yama calls the LLM through LiteLLM, drives the tool loop, and scores the transcript with deterministic hard checks or an LLM judge. See the [design doc](https://github.com/world-sim-dev/yama/blob/main/docs/agent-skill-test-framework-design.md) (Chinese) for the full Case schema and execution contract.
31
+
32
+ ## Quick start
33
+
34
+ ```bash
35
+ # Run from a plugin root; collects __evals__/cases/**/*.yaml by default
36
+ cd dingding-simple
37
+ OPENAI_API_KEY=... uv run --project yama yama
38
+
39
+ # Or, from a workspace root (a directory with yama.toml), pick a plugin by name
40
+ OPENAI_API_KEY=... uv run --project yama yama --plugin dingding-simple
41
+ ```
42
+
43
+ ## Writing a Case
44
+
45
+ A Case is a YAML file organized as `context` (what the model sees) → `mocks` (how tool calls get executed) → `steps` (user turns sent in order, each with assertions) → `outcome` (the pass bar for the whole Case):
46
+
47
+ ```yaml
48
+ description: The model reads the DSL before proposing creative directions
49
+
50
+ context:
51
+ system_prompt: { default: true } # use SYSTEM.md from the plugin root
52
+
53
+ tools:
54
+ - file: tools/read-dsl.yaml # tool schema, resolved relative to __evals__
55
+
56
+ mocks:
57
+ tools:
58
+ read_dsl:
59
+ respond:
60
+ result:
61
+ visualStyle: { name: Vintage Film }
62
+
63
+ steps:
64
+ - id: request-directions
65
+ user: Give me a few creative directions
66
+ assert:
67
+ hard:
68
+ - tool_called: { name: read_dsl }
69
+ - assistant_contains: creative direction
70
+
71
+ outcome:
72
+ require:
73
+ hard_checks: all_pass
74
+ ```
75
+
76
+ - `description` (optional) is a one-line summary of what the Case tests; it is shown in the CLI output and the HTML report.
77
+ - `context.tools` is the tool schema sent to the model; `mocks.tools` is how the runner responds when a tool call arrives. The two sets of tool names must match exactly.
78
+ - To use a Skill, declare it by name under `context.skills` and also declare `{builtin: skill}` under `context.tools`; the model reads the Skill body via `skill(name, file?)`.
79
+ - To simulate command-line tools, declare `{builtin: bash}` and configure per-command output under `mocks.cli`.
80
+ - `steps[].assert.hard` are deterministic checks (nine types, including `tool_called`, `tool_arguments`, and `assistant_contains`); add `assert.judge` for LLM scoring.
81
+
82
+ For the full schema (every Skill/tool/mock form, the `bash` sandbox, message injection, judge configuration, and more), see the [design doc](https://github.com/world-sim-dev/yama/blob/main/docs/agent-skill-test-framework-design.md) (Chinese).
83
+
84
+ ## CLI usage
85
+
86
+ ```bash
87
+ uv run --project yama yama --plugin dingding-simple --report
88
+ ```
89
+
90
+ | Flag | Meaning |
91
+ | --- | --- |
92
+ | `paths` (positional, repeatable) | Explicit Case YAML paths to run |
93
+ | `--plugin-root PATH` | Use the given path as the single plugin root |
94
+ | `--plugin NAME` (repeatable) | Select plugins by name from `yama.toml` |
95
+ | `--all-plugins` | Run every plugin configured in `yama.toml` |
96
+ | `--result-dir PATH` | Override the artifact root (default `<plugin_root>/.yama/runs`) |
97
+ | `--concurrency N` | Maximum number of cases running in parallel (default 10; `1` runs cases one at a time) |
98
+ | `--report [PATH]` | Also generate a single-file HTML report (default `.yama/reports/latest.html`) |
99
+ | `--list` | Only print the collected Cases, without running them |
100
+ | `--no-artifacts` | Write no artifact files at all |
101
+ | `--json` | Emit machine-readable JSON instead of Rich tables |
102
+
103
+ `--plugin`, `--all-plugins`, and `--plugin-root` are mutually exclusive. When none of them is given, yama walks up from the current directory to the nearest directory containing `yama.toml` and uses it as the workspace root (falling back to the cwd), running it as a single plugin root.
104
+
105
+ Cases run in parallel, up to 10 at a time by default (`--concurrency` changes the cap); runs within one case stay sequential, and results keep collection order regardless of completion order. While several cases run concurrently, a transient dashboard at the bottom of the terminal shows one row per case, updated in place — waiting, then a spinner with the run/step currently executing, then its ✓/✗ verdict — and each case's full run/step detail is printed above the dashboard as one block the moment it finishes, so blocks of different cases never interleave. With `--concurrency 1` (or a single collected case) it streams instead — a spinner marks the step currently executing (on a terminal), and each case, run, and assertion result is printed the moment it completes. Either way a per-case summary table closes the output, and with `--json` the progress stream goes to stderr so stdout stays valid JSON.
@@ -1,15 +1,15 @@
1
1
  yama/__init__.py,sha256=UYhoZTSu1HiMT54LOZCdvLKMQ_L0qec8RT8jDfde_cY,1156
2
2
  yama/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
3
  yama/assertions.py,sha256=0x1r82W2dtAY1mTk4LC86VulD5Q9blS7QeRCTysb4kE,21736
4
- yama/cli.py,sha256=0RsIDhv767oJ42-1FfkAxttJXqardA2UG33bSHDQH6w,11718
5
- yama/llm.py,sha256=RrgU2xO8J_AfiXwOJn1Dmb3OzjbwWFpW7mpQ6dlHYiQ,13352
6
- yama/mocks.py,sha256=v94SFa5VyTB3cvMMcuHMkiSL8HS962-0OmY5iWq9mxs,14256
7
- yama/models.py,sha256=-ry0QUI2e0ialL6A9NUEAM0QpwCQg8oXEfPBXn3CvNI,3964
8
- yama/report.py,sha256=qnLpp8yA2TdZw1UWHN_XtJWMVa0v9Z7f0ez9z9HViY0,37563
9
- yama/runner.py,sha256=GRg3VWZBw4bupDW6qMQO7TjE2VHjwo1hV8HYYw0_Mks,20661
4
+ yama/cli.py,sha256=Fsl-GROEQJx9hHs5qSlAtZTkEaeCU2TY6S8IhmJmmzM,23203
5
+ yama/llm.py,sha256=XqGE4aKPOimy9n3oNF5rUvqWdJlpi0EVzMlD-FBim6A,13570
6
+ yama/mocks.py,sha256=YyiU6Y7NgttxHYJBsqGPILKYlTsM4IMTIilMNRkUuzs,14973
7
+ yama/models.py,sha256=FeKOYS4MAQhDPyhAyd4pPvQH015w5hOJqhNzTZHYRgI,3990
8
+ yama/report.py,sha256=csceNtljXd--palHhvdVIXsPYs7uF_C1xUkLfoWPZbc,37824
9
+ yama/runner.py,sha256=9JXlJPSEFHKrZETdso5BCR_SQZ97lEzpP0ZwyYz5o0g,23823
10
10
  yama/workspace.py,sha256=rHQ9kQUkAo32gJpqRf7pSd5JhBc05xgxA1wPRC4bOQ8,3618
11
11
  yama/loaders/__init__.py,sha256=DIwfa8QlIlKt6NpFMZJ_OcqbJPPrmKLBzd9_e-BCuBs,174
12
- yama/loaders/case.py,sha256=gas5J9jtPuaqo43IO5gk-4uVJ49JWc7sNMXFI8I_7AA,14255
12
+ yama/loaders/case.py,sha256=Kh37rtT30lxkCRZ6wA3fo8_tTxeTeN0d0c-OTqkfSSY,14532
13
13
  yama/loaders/common.py,sha256=Fg71_vcnu5339QI_itvYPvRbk9LtBgEnzoA3t4Krb4U,754
14
14
  yama/loaders/tool_loader.py,sha256=BubcplVYKiJxgNsMKGRfiRiK1qVo0EvJfLOJzQEx9js,6388
15
15
  yama/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -17,11 +17,11 @@ yama/tools/base.py,sha256=ONFuGzTSWVsA0k4-UUREncqAHmyQI2uHpVOU2Dh_XiQ,446
17
17
  yama/tools/bash/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
18
  yama/tools/bash/_cli_shim.py,sha256=f3Rom5UipW0dA0KRYavqIa9HJDKT336ssDZGWeVmkvo,2494
19
19
  yama/tools/bash/bash.py,sha256=4GlFvmqTUS4k6DgJ5Io91YF5fB6wF6e3e7p2P-pmbEQ,10358
20
- yama/tools/bash/fs.py,sha256=CMPPAEfubt2kkaccxQaIYriJ497J2_CDfZm5l3evnaY,20674
20
+ yama/tools/bash/fs.py,sha256=ncLZf4_gErRP3HHXinLEQeN6chrf7JaSiaTuadVl8MY,21314
21
21
  yama/tools/skill/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
22
  yama/tools/skill/skill.py,sha256=P2rDz6VqRLfhiabWjOU3ZBaWLw30Eywf3o_OxVfFbPI,1992
23
- python_yama-0.1.0.dist-info/METADATA,sha256=klpVw1LaW-EsoGJQtvzH950HF4vLA5QmOehOX2sxWPI,4299
24
- python_yama-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
25
- python_yama-0.1.0.dist-info/entry_points.txt,sha256=N5se3y1FflUcDU3TmUrH2Tu9dzsrBBo7sUP-Gu_2cVs,39
26
- python_yama-0.1.0.dist-info/licenses/LICENSE,sha256=cMAJJAs7R1lemJPPc7qMNv4w_sqn5QncFf4aXKYyEc4,1067
27
- python_yama-0.1.0.dist-info/RECORD,,
23
+ python_yama-0.3.0.dist-info/METADATA,sha256=GK8pJCJR0KCRpRfc5FQ0YvAZ2Pym-HSGGnsSn8U30l8,5830
24
+ python_yama-0.3.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
25
+ python_yama-0.3.0.dist-info/entry_points.txt,sha256=N5se3y1FflUcDU3TmUrH2Tu9dzsrBBo7sUP-Gu_2cVs,39
26
+ python_yama-0.3.0.dist-info/licenses/LICENSE,sha256=cMAJJAs7R1lemJPPc7qMNv4w_sqn5QncFf4aXKYyEc4,1067
27
+ python_yama-0.3.0.dist-info/RECORD,,
yama/cli.py CHANGED
@@ -3,12 +3,17 @@ from __future__ import annotations
3
3
  import argparse
4
4
  import asyncio
5
5
  import json
6
+ import sys
6
7
  from io import StringIO
7
8
  from pathlib import Path
8
9
  from typing import Any
9
10
 
10
11
  from rich import box
11
12
  from rich.console import Console, Group
13
+ from rich.live import Live
14
+ from rich.padding import Padding
15
+ from rich.spinner import Spinner
16
+ from rich.status import Status
12
17
  from rich.table import Table
13
18
  from rich.text import Text
14
19
  from rich.tree import Tree
@@ -19,7 +24,7 @@ from .workspace import (
19
24
  load_workspace_config,
20
25
  resolve_plugin_root,
21
26
  )
22
- from .llm import LLMError, LiteLLMClient, ScriptedLLMClient
27
+ from .llm import LLMError, LiteLLMClient
23
28
  from .loaders import CollectionError, resolve_case
24
29
  from .report import write_html_report
25
30
  from .runner import YamaRunner
@@ -38,7 +43,109 @@ def _summary_case_key(case_key: str) -> str:
38
43
  return case_key.removeprefix(prefix)
39
44
 
40
45
 
41
- def build_results_renderable(results: list[Any]) -> Group:
46
+ def build_step_tree(step: Any) -> Tree:
47
+ """Per-step verdict subtree (hard checks + judge dimensions).
48
+
49
+ Shared by the live progress output (printed as soon as the step's
50
+ assertions settle) and the aggregated details of `format_text_results`.
51
+ """
52
+ failed = [
53
+ check for check in step.hard_checks if not check.get("passed", False)
54
+ ]
55
+ judge = step.judge_result
56
+ judge_passed = judge is None or bool(judge.get("passed", False))
57
+ step_passed = not failed and step.hard_pass and judge_passed
58
+ hard_passed = len(step.hard_checks) - len(failed)
59
+ step_label = Text.assemble(
60
+ _status(step_passed, compact=True),
61
+ " ",
62
+ (step.step_id, "bold"),
63
+ (
64
+ f" hard checks {hard_passed}/{len(step.hard_checks)}",
65
+ "dim",
66
+ ),
67
+ )
68
+ if judge is not None:
69
+ step_label.append(" judge ", style="dim")
70
+ step_label.append(
71
+ "passed" if judge_passed else "failed",
72
+ style="green" if judge_passed else "bold red",
73
+ )
74
+ if isinstance(judge.get("overall"), (int, float)):
75
+ step_label.append(f" {judge['overall']:.0%}", style="dim")
76
+ step_node = Tree(step_label, guide_style="dim")
77
+ if judge is not None and not judge_passed:
78
+ judge_node = step_node.add(Text("Judge dimensions", style="bold red"))
79
+ for dimension in judge.get("dimensions", []):
80
+ dimension_label = Text.assemble(
81
+ (str(dimension.get("name", "unnamed")), "bold"),
82
+ f": {dimension.get('score', '?')}/5",
83
+ )
84
+ if dimension.get("reason"):
85
+ dimension_label.append(
86
+ f" {dimension['reason']}", style="dim"
87
+ )
88
+ judge_node.add(dimension_label)
89
+ for index, check in enumerate(step.hard_checks, 1):
90
+ label = check.get("label") or check.get("type", "hard check")
91
+ if check.get("passed", False):
92
+ step_node.add(
93
+ Text.assemble(
94
+ _status(True, compact=True),
95
+ " ",
96
+ (f"{index:02d} {label}", "green"),
97
+ )
98
+ )
99
+ continue
100
+ expected = check.get("expected", "assertion passes")
101
+ actual = check.get("actual", check.get("detail", "unknown"))
102
+ reason = check.get("reason", check.get("detail", "assertion failed"))
103
+ check_node = step_node.add(
104
+ Text.assemble(
105
+ _status(False, compact=True),
106
+ " ",
107
+ (f"{index:02d} {label}", "bold red"),
108
+ )
109
+ )
110
+ check_node.add(
111
+ Text.assemble(("Expected ", "bold cyan"), str(expected))
112
+ )
113
+ check_node.add(
114
+ Text.assemble(("Actual ", "bold yellow"), str(actual))
115
+ )
116
+ check_node.add(
117
+ Text.assemble(("Reason ", "bold red"), str(reason))
118
+ )
119
+ return step_node
120
+
121
+
122
+ def build_case_tree(result: Any) -> Tree:
123
+ """Whole-case verdict tree (runs -> steps), shared by the aggregated
124
+ details of `format_text_results` and the parallel progress output."""
125
+ case_label = Text.assemble(
126
+ _status(result.passed, compact=True),
127
+ " ",
128
+ (result.case_key, "bold"),
129
+ (f" {result.pass_rate:.0%}", "dim"),
130
+ )
131
+ if result.description:
132
+ case_label.append(f"\n{result.description}", style="dim")
133
+ tree = Tree(case_label, guide_style="dim")
134
+ for run in result.runs:
135
+ run_node = tree.add(
136
+ Text.assemble(
137
+ _status(run.passed, compact=True),
138
+ " ",
139
+ (f"Run {run.run_index}", "bold"),
140
+ )
141
+ )
142
+ if run.error:
143
+ run_node.add(Text.assemble(("Error: ", "bold red"), (run.error, "red")))
144
+ run_node.children.extend(build_step_tree(step) for step in run.steps)
145
+ return tree
146
+
147
+
148
+ def build_summary_table(results: list[Any]) -> Table:
42
149
  table = Table(
43
150
  title="Yama Eval Results",
44
151
  box=box.SIMPLE_HEAVY,
@@ -57,9 +164,12 @@ def build_results_renderable(results: list[Any]) -> Group:
57
164
  case_passed_runs = sum(run.passed for run in result.runs)
58
165
  passed_runs += case_passed_runs
59
166
  total_runs += len(result.runs)
167
+ case_cell = Text(_summary_case_key(result.case_key))
168
+ if result.description:
169
+ case_cell.append(f"\n{result.description}", style="dim")
60
170
  table.add_row(
61
171
  _status(result.passed),
62
- Text(_summary_case_key(result.case_key)),
172
+ case_cell,
63
173
  f"{case_passed_runs}/{len(result.runs)}",
64
174
  f"{result.pass_rate:.0%}",
65
175
  )
@@ -70,97 +180,244 @@ def build_results_renderable(results: list[Any]) -> Group:
70
180
  f"{passed_runs}/{total_runs} runs passed"
71
181
  )
72
182
  table.caption_style = "green" if passed_cases == len(results) else "red"
183
+ return table
73
184
 
185
+
186
+ def build_results_renderable(results: list[Any]) -> Group:
187
+ table = build_summary_table(results)
74
188
  details = Tree(Text("Details", style="bold"), guide_style="dim")
75
- for result in results:
76
- case_label = Text.assemble(
77
- _status(result.passed, compact=True),
78
- " ",
79
- (result.case_key, "bold"),
80
- (f" {result.pass_rate:.0%}", "dim"),
81
- )
82
- case_node = details.add(case_label)
83
- for run in result.runs:
84
- run_label = Text.assemble(
85
- _status(run.passed, compact=True),
86
- " ",
87
- (f"Run {run.run_index}", "bold"),
189
+ details.children.extend(build_case_tree(result) for result in results)
190
+ return Group(table, Text(), details)
191
+
192
+
193
+ class ProgressPrinter:
194
+ """Print case/run/step results the moment YamaRunner completes them.
195
+
196
+ Wired into `YamaRunner(on_event=...)`. Completed results are append-only
197
+ lines, so they stay intact when piped or captured in CI logs; the only
198
+ live element is a transient spinner shown while a step is executing
199
+ (animated on a terminal, invisible in non-interactive output).
200
+ """
201
+
202
+ def __init__(self, console: Console, total_cases: int) -> None:
203
+ self.console = console
204
+ self.total_cases = total_cases
205
+ self._case_index = 0
206
+ self._spinner: Status | None = None
207
+
208
+ def _stop_spinner(self) -> None:
209
+ if self._spinner is not None:
210
+ self._spinner.stop()
211
+ self._spinner = None
212
+
213
+ def close(self) -> None:
214
+ """Stop the live element when no further events will arrive (a case
215
+ that dies before its case_end otherwise leaves the spinner running)."""
216
+ self._stop_spinner()
217
+
218
+ def __call__(self, event: str, payload: dict[str, Any]) -> None:
219
+ # Whatever comes in, the previous "step is executing" spinner is over.
220
+ self._stop_spinner()
221
+ if event == "step_start":
222
+ self._spinner = self.console.status(
223
+ Text.assemble(
224
+ ("running ", "dim"),
225
+ (payload["step_id"], "bold"),
226
+ (" …", "dim"),
227
+ ),
228
+ spinner="dots",
88
229
  )
89
- run_node = case_node.add(run_label)
230
+ self._spinner.start()
231
+ elif event == "case_start":
232
+ self._case_index += 1
233
+ self.console.print(
234
+ Text.assemble(
235
+ (f"[{self._case_index}/{self.total_cases}] ", "bold cyan"),
236
+ (payload["case_key"], "bold"),
237
+ )
238
+ )
239
+ if payload["description"]:
240
+ self.console.print(
241
+ Padding(Text(payload["description"], style="dim"), (0, 0, 0, 2))
242
+ )
243
+ elif event == "run_start":
244
+ self.console.print(
245
+ Padding(
246
+ Text(
247
+ f"Run {payload['run_index']}/{payload['repeat']}",
248
+ style="bold",
249
+ ),
250
+ (0, 0, 0, 2),
251
+ )
252
+ )
253
+ elif event == "step_end":
254
+ self.console.print(Padding(build_step_tree(payload["step"]), (0, 0, 0, 4)))
255
+ elif event == "run_end":
256
+ run = payload["run"]
90
257
  if run.error:
91
- run_node.add(Text.assemble(("Error: ", "bold red"), (run.error, "red")))
92
- for step in run.steps:
93
- failed = [
94
- check
95
- for check in step.hard_checks
96
- if not check.get("passed", False)
97
- ]
98
- judge = step.judge_result
99
- judge_passed = judge is None or bool(judge.get("passed", False))
100
- step_passed = not failed and step.hard_pass and judge_passed
101
- hard_passed = len(step.hard_checks) - len(failed)
102
- step_label = Text.assemble(
103
- _status(step_passed, compact=True),
258
+ self.console.print(
259
+ Padding(
260
+ Text.assemble(("Error: ", "bold red"), (run.error, "red")),
261
+ (0, 0, 0, 4),
262
+ )
263
+ )
264
+ elif event == "case_end":
265
+ result = payload["result"]
266
+ passed_runs = sum(run.passed for run in result.runs)
267
+ self.console.print(
268
+ Text.assemble(
269
+ _status(result.passed, compact=True),
104
270
  " ",
105
- (step.step_id, "bold"),
271
+ (result.case_key, "bold"),
106
272
  (
107
- f" hard checks {hard_passed}/{len(step.hard_checks)}",
273
+ f" {passed_runs}/{len(result.runs)} runs passed"
274
+ f" {result.pass_rate:.0%}",
108
275
  "dim",
109
276
  ),
110
277
  )
111
- if judge is not None:
112
- step_label.append(" judge ", style="dim")
113
- step_label.append(
114
- "passed" if judge_passed else "failed",
115
- style="green" if judge_passed else "bold red",
116
- )
117
- if isinstance(judge.get("overall"), (int, float)):
118
- step_label.append(f" {judge['overall']:.0%}", style="dim")
119
- step_node = run_node.add(step_label)
120
- if judge is not None and not judge_passed:
121
- judge_node = step_node.add(Text("Judge dimensions", style="bold red"))
122
- for dimension in judge.get("dimensions", []):
123
- dimension_label = Text.assemble(
124
- (str(dimension.get("name", "unnamed")), "bold"),
125
- f": {dimension.get('score', '?')}/5",
126
- )
127
- if dimension.get("reason"):
128
- dimension_label.append(
129
- f" {dimension['reason']}", style="dim"
130
- )
131
- judge_node.add(dimension_label)
132
- for index, check in enumerate(step.hard_checks, 1):
133
- label = check.get("label") or check.get("type", "hard check")
134
- if check.get("passed", False):
135
- step_node.add(
136
- Text.assemble(
137
- _status(True, compact=True),
138
- " ",
139
- (f"{index:02d} {label}", "green"),
140
- )
141
- )
142
- continue
143
- expected = check.get("expected", "assertion passes")
144
- actual = check.get("actual", check.get("detail", "unknown"))
145
- reason = check.get("reason", check.get("detail", "assertion failed"))
146
- check_node = step_node.add(
147
- Text.assemble(
148
- _status(False, compact=True),
149
- " ",
150
- (f"{index:02d} {label}", "bold red"),
151
- )
152
- )
153
- check_node.add(
154
- Text.assemble(("Expected ", "bold cyan"), str(expected))
155
- )
156
- check_node.add(
157
- Text.assemble(("Actual ", "bold yellow"), str(actual))
158
- )
159
- check_node.add(
160
- Text.assemble(("Reason ", "bold red"), str(reason))
278
+ )
279
+ self.console.print()
280
+
281
+
282
+ class ParallelProgressPrinter:
283
+ """Live per-case dashboard for concurrently running cases.
284
+
285
+ Wired into `YamaRunner(on_event=...)` when cases run concurrently
286
+ (--concurrency > 1 with several cases collected): ProgressPrinter's
287
+ per-step stream would interleave lines of unrelated cases under the
288
+ wrong case header. Instead, every collected case gets one row in a
289
+ transient live panel, updated in place as its state changes --
290
+ waiting for a slot, then a spinner with the run/step currently
291
+ executing, then its final compact verdict -- and a case's full
292
+ run/step detail is printed above the panel as one block the moment
293
+ its case_end verdict settles. The panel only renders on a terminal;
294
+ piped/CI output just gets the append-only case blocks.
295
+ """
296
+
297
+ def __init__(self, console: Console, cases: list[Any]) -> None:
298
+ self.console = console
299
+ self._rows: dict[str, dict[str, Any]] = {
300
+ case.case_key: {"status": "waiting"} for case in cases
301
+ }
302
+ self._finished = 0
303
+ self._live: Live | None = None
304
+ # One Spinner shared by every running row: recreating spinners on
305
+ # each refresh frame would reset their start_time every time and
306
+ # freeze the glyph on frame zero.
307
+ self._spinner = Spinner("dots", style="cyan")
308
+ self._saved_termios: list[Any] | None = None
309
+
310
+ def close(self) -> None:
311
+ """Stop the live panel when no further events will arrive (a case
312
+ that dies before its case_end otherwise leaves the panel running)."""
313
+ if self._live is not None:
314
+ self._live.stop()
315
+ self._live = None
316
+ self._set_input_echo(True)
317
+
318
+ def _set_input_echo(self, enabled: bool) -> None:
319
+ """Keystrokes echoed while the panel is live (a stray Enter) shift
320
+ the cursor under Live's feet, desyncing its repaint origin and
321
+ leaving stale copies of the panel's top line behind -- so terminal
322
+ echo is disabled while the panel is up and restored when it stops."""
323
+ try:
324
+ import termios
325
+ except ImportError: # pragma: no cover - non-POSIX platform
326
+ return
327
+ try:
328
+ if enabled:
329
+ if self._saved_termios is not None:
330
+ termios.tcsetattr(
331
+ sys.stdin.fileno(), termios.TCSADRAIN, self._saved_termios
161
332
  )
333
+ self._saved_termios = None
334
+ return
335
+ if not sys.stdin.isatty():
336
+ return
337
+ fd = sys.stdin.fileno()
338
+ self._saved_termios = termios.tcgetattr(fd)
339
+ mode = termios.tcgetattr(fd)
340
+ mode[3] &= ~(termios.ECHO | termios.ECHONL)
341
+ termios.tcsetattr(fd, termios.TCSADRAIN, mode)
342
+ except (ValueError, OSError, termios.error):
343
+ self._saved_termios = None
162
344
 
163
- return Group(table, Text(), details)
345
+ def _render(self) -> Table:
346
+ # Rows are rebuilt from scratch on every refresh tick; the tick runs
347
+ # on Live's refresh thread, so event handling only ever swaps whole
348
+ # row dicts (never mutates one in place) to keep reads consistent.
349
+ grid = Table.grid(padding=(0, 1))
350
+ for case_key, row in self._rows.items():
351
+ if row["status"] == "waiting":
352
+ grid.add_row(
353
+ Text("·", style="dim"),
354
+ Text.assemble((case_key, "dim"), (" waiting", "dim")),
355
+ )
356
+ elif row["status"] == "running":
357
+ progress = ""
358
+ if row.get("run_index"):
359
+ progress = f" Run {row['run_index']}/{row['repeat']}"
360
+ if row.get("step_id"):
361
+ progress += f" · {row['step_id']}"
362
+ grid.add_row(
363
+ self._spinner,
364
+ Text.assemble((case_key, "bold"), (progress, "dim")),
365
+ )
366
+ else:
367
+ result = row["result"]
368
+ passed_runs = sum(run.passed for run in result.runs)
369
+ grid.add_row(
370
+ _status(result.passed, compact=True),
371
+ Text.assemble(
372
+ (case_key, "bold"),
373
+ (
374
+ f" {passed_runs}/{len(result.runs)} runs"
375
+ f" {result.pass_rate:.0%}",
376
+ "dim",
377
+ ),
378
+ ),
379
+ )
380
+ return grid
381
+
382
+ def _ensure_live(self) -> None:
383
+ if self._live is None:
384
+ if self.console.is_terminal:
385
+ self._set_input_echo(False)
386
+ self._live = Live(
387
+ get_renderable=self._render,
388
+ console=self.console,
389
+ transient=True,
390
+ refresh_per_second=12.5,
391
+ )
392
+ self._live.start()
393
+
394
+ def __call__(self, event: str, payload: dict[str, Any]) -> None:
395
+ if event == "case_start":
396
+ self._ensure_live()
397
+ self._rows[payload["case_key"]] = {
398
+ "status": "running",
399
+ "repeat": payload["repeat"],
400
+ }
401
+ elif event in {"run_start", "step_start"}:
402
+ row = self._rows.get(payload["case_key"])
403
+ if row is None or row["status"] != "running":
404
+ return
405
+ row = dict(row)
406
+ if event == "run_start":
407
+ row["run_index"] = payload["run_index"]
408
+ row["repeat"] = payload["repeat"]
409
+ row["step_id"] = None
410
+ else:
411
+ row["step_id"] = payload["step_id"]
412
+ self._rows[payload["case_key"]] = row
413
+ elif event == "case_end":
414
+ result = payload["result"]
415
+ self._rows[result.case_key] = {"status": "done", "result": result}
416
+ self._finished += 1
417
+ self.console.print(build_case_tree(result))
418
+ self.console.print()
419
+ if self._finished >= len(self._rows):
420
+ self.close()
164
421
 
165
422
 
166
423
  def format_text_results(results: list[Any]) -> str:
@@ -176,6 +433,16 @@ def format_text_results(results: list[Any]) -> str:
176
433
  return output.getvalue().rstrip()
177
434
 
178
435
 
436
+ def _positive_int(value: str) -> int:
437
+ try:
438
+ number = int(value)
439
+ except ValueError:
440
+ raise argparse.ArgumentTypeError(f"invalid int value: {value!r}")
441
+ if number < 1:
442
+ raise argparse.ArgumentTypeError("must be at least 1")
443
+ return number
444
+
445
+
179
446
  def _parser() -> argparse.ArgumentParser:
180
447
  parser = argparse.ArgumentParser(
181
448
  prog="yama", description="Run Agent Skill eval cases"
@@ -190,10 +457,17 @@ def _parser() -> argparse.ArgumentParser:
190
457
  parser.add_argument(
191
458
  "--all-plugins", action="store_true", help="Run all configured plugins"
192
459
  )
460
+ parser.add_argument("--result-dir", type=Path, help="Override artifact directory")
193
461
  parser.add_argument(
194
- "--response-script", type=Path, help="Use deterministic scripted LLM responses"
462
+ "--concurrency",
463
+ type=_positive_int,
464
+ default=10,
465
+ metavar="N",
466
+ help=(
467
+ "Maximum number of cases to run in parallel"
468
+ " (default: 10; 1 runs cases sequentially with the live step stream)"
469
+ ),
195
470
  )
196
- parser.add_argument("--result-dir", type=Path, help="Override artifact directory")
197
471
  parser.add_argument(
198
472
  "--report",
199
473
  type=Path,
@@ -255,28 +529,52 @@ async def _run(args: argparse.Namespace) -> int:
255
529
  Console(stderr=True).print("[bold red]No eval cases collected.[/bold red]")
256
530
  return 2
257
531
 
258
- llm = (
259
- ScriptedLLMClient.from_file(args.response_script.resolve())
260
- if args.response_script
261
- else LiteLLMClient()
532
+ # With --json, stdout must stay valid JSON, so live progress moves to
533
+ # stderr instead of disappearing.
534
+ progress_console = Console(stderr=args.json)
535
+ parallel = args.concurrency > 1 and len(collected) > 1
536
+ progress: ProgressPrinter | ParallelProgressPrinter = (
537
+ ParallelProgressPrinter(progress_console, cases=collected)
538
+ if parallel
539
+ else ProgressPrinter(progress_console, total_cases=len(collected))
262
540
  )
263
- all_results = []
264
- result_roots = []
265
- for case in collected:
266
- result_root = (
267
- args.result_dir.resolve()
268
- if args.result_dir
269
- else case.plugin_root / workspace.result_dir
270
- )
271
- result_roots.append(result_root)
272
- runner = YamaRunner(
273
- llm,
274
- result_root=result_root,
275
- write_artifacts=not args.no_artifacts,
541
+ result_roots = [
542
+ args.result_dir.resolve()
543
+ if args.result_dir
544
+ else case.plugin_root / workspace.result_dir
545
+ for case in collected
546
+ ]
547
+ semaphore = asyncio.Semaphore(args.concurrency)
548
+
549
+ async def run_one(case: Any, result_root: Path) -> Any:
550
+ async with semaphore:
551
+ # One LLM client per case: the runner reads last_request /
552
+ # last_provider back after every complete(), which concurrently
553
+ # running cases would clobber on a shared client.
554
+ runner = YamaRunner(
555
+ LiteLLMClient(),
556
+ result_root=result_root,
557
+ write_artifacts=not args.no_artifacts,
558
+ on_event=progress,
559
+ )
560
+ return await runner.run_case(case)
561
+
562
+ try:
563
+ # return_exceptions lets every case finish (and write its artifacts)
564
+ # before the first failure is re-raised for main()'s error handling.
565
+ outcomes = await asyncio.gather(
566
+ *(
567
+ run_one(case, result_root)
568
+ for case, result_root in zip(collected, result_roots)
569
+ ),
570
+ return_exceptions=True,
276
571
  )
277
- all_results.append(await runner.run_case(case))
278
- if isinstance(llm, ScriptedLLMClient):
279
- llm.assert_consumed()
572
+ finally:
573
+ progress.close()
574
+ for outcome in outcomes:
575
+ if isinstance(outcome, BaseException):
576
+ raise outcome
577
+ all_results = list(outcomes)
280
578
  report_target = args.report
281
579
  if report_target == DEFAULT_REPORT:
282
580
  report_target = result_roots[0].parent / "reports" / "latest.html"
@@ -294,7 +592,9 @@ async def _run(args: argparse.Namespace) -> int:
294
592
  )
295
593
  )
296
594
  else:
297
- Console().print(build_results_renderable(all_results))
595
+ # Step/assert details already streamed above as they completed; close
596
+ # with the per-case summary table only.
597
+ Console().print(build_summary_table(all_results))
298
598
  if report_path:
299
599
  Console(stderr=args.json).print(
300
600
  Text.assemble(
@@ -309,10 +609,18 @@ def main(argv: list[str] | None = None) -> int:
309
609
  args = _parser().parse_args(argv)
310
610
  try:
311
611
  return asyncio.run(_run(args))
312
- except (ConfigurationError, CollectionError, LLMError, ValueError) as exc:
612
+ except (ConfigurationError, CollectionError, ValueError) as exc:
313
613
  Console(stderr=True).print(
314
614
  Text.assemble(("Collection error: ", "bold red"), (str(exc), "red"))
315
615
  )
316
616
  return 2
617
+ except LLMError as exc:
618
+ # Not a collection problem: cases were already collected (and possibly
619
+ # executed) when the LLM layer failed -- label it accordingly so the
620
+ # user debugs the right layer.
621
+ Console(stderr=True).print(
622
+ Text.assemble(("LLM error: ", "bold red"), (str(exc), "red"))
623
+ )
624
+ return 2
317
625
  except KeyboardInterrupt:
318
626
  return 130
yama/llm.py CHANGED
@@ -337,7 +337,10 @@ class ScriptedLLMClient(LLMClient):
337
337
  if not isinstance(expectation, dict):
338
338
  raise LLMError("script expect must be an object")
339
339
  if "tools" in expectation:
340
- actual = [tool["function"]["name"] for tool in request["tools"]]
340
+ # A request with no tools omits the "tools" key entirely (see
341
+ # _litellm_call_arguments), so expect: {tools: []} must read it
342
+ # as an empty list instead of raising KeyError.
343
+ actual = [tool["function"]["name"] for tool in request.get("tools", [])]
341
344
  if actual != expectation["tools"]:
342
345
  raise LLMError(
343
346
  f"script expected tools {expectation['tools']}, got {actual}"
yama/loaders/case.py CHANGED
@@ -235,6 +235,12 @@ def resolve_case(
235
235
  evals_root = (plugin_root / "__evals__").resolve()
236
236
  context = raw.get("context")
237
237
  steps = raw.get("steps")
238
+ description = raw.get("description")
239
+ if description is None:
240
+ description = ""
241
+ if not isinstance(description, str):
242
+ raise CollectionError(f"description must be a string: {path}")
243
+ description = description.strip()
238
244
  if not isinstance(context, dict):
239
245
  raise CollectionError(f"context is required: {path}")
240
246
  if "skill_tool" in context:
@@ -362,6 +368,7 @@ def resolve_case(
362
368
  return ResolvedCase(
363
369
  path=path.resolve(),
364
370
  case_key=case_key,
371
+ description=description,
365
372
  plugin_root=plugin_root.resolve(),
366
373
  evals_root=evals_root,
367
374
  model=model,
yama/mocks.py CHANGED
@@ -178,6 +178,27 @@ def _matches(actual: Any, expected: Any) -> bool:
178
178
  _MISSING = object()
179
179
 
180
180
 
181
+ def result_is_error(result: Any) -> bool:
182
+ """Semantic error status of a tool result envelope.
183
+
184
+ A result is an error only when it carries a non-null ``error`` payload,
185
+ or when it is a bash-style ``{stdout, stderr, exit_code}`` envelope with a
186
+ non-zero exit code. A literal ``error: null`` field is a successful result.
187
+ """
188
+ if not isinstance(result, dict):
189
+ return False
190
+ if result.get("error") is not None:
191
+ return True
192
+ if (
193
+ isinstance(result.get("stdout"), str)
194
+ and isinstance(result.get("stderr"), str)
195
+ and isinstance(result.get("exit_code"), int)
196
+ and not isinstance(result.get("exit_code"), bool)
197
+ ):
198
+ return result["exit_code"] != 0
199
+ return False
200
+
201
+
181
202
  def _state_diff(before: Any, after: Any, path: str = "$") -> list[dict[str, Any]]:
182
203
  if before == after:
183
204
  return []
@@ -353,7 +374,7 @@ class MockToolRegistry:
353
374
  "match_failed": match_failed,
354
375
  "arguments": arguments,
355
376
  "result": result,
356
- "is_error": is_error or (isinstance(result, dict) and "error" in result),
377
+ "is_error": is_error or result_is_error(result),
357
378
  "duration_ms": round((time.perf_counter() - started) * 1000, 3),
358
379
  "state_diff": _state_diff(before, after),
359
380
  }
yama/models.py CHANGED
@@ -156,4 +156,5 @@ class ResolvedCase:
156
156
  skills: list[LoadedSkill]
157
157
  tools: list[ToolSchema]
158
158
  initial_messages: list[Json]
159
+ description: str = ""
159
160
  fixture_manifest: list[Json] = field(default_factory=list)
yama/report.py CHANGED
@@ -418,7 +418,7 @@ def _render_step(
418
418
  "</span>"
419
419
  "</summary>"
420
420
  '<div class="step-body">'
421
- '<details class="subsection timeline-section" open>'
421
+ '<details class="subsection timeline-section">'
422
422
  '<summary><span>Execution timeline</span>'
423
423
  f'<span class="muted">{len(events)} events</span></summary>'
424
424
  f'<div class="timeline">{"".join(events)}</div></details>'
@@ -531,11 +531,17 @@ def _render_case(case: ResolvedCase, result: CaseResult) -> str:
531
531
  tools = ", ".join(tool.name for tool in case.tools) or "none"
532
532
  skills = ", ".join(skill.name for skill in case.skills) or "none"
533
533
  runs = "".join(_render_run(run) for run in result.runs)
534
+ description = (
535
+ f'<p class="case-description">{_text(case.description)}</p>'
536
+ if case.description
537
+ else ""
538
+ )
534
539
  return (
535
540
  '<section class="case">'
536
541
  '<header class="case-header">'
537
542
  '<div><div class="eyebrow">Case</div>'
538
543
  f'<h2>{_text(result.case_key)}</h2>'
544
+ f'{description}'
539
545
  f'<p class="path">{_text(case.path)}</p></div>'
540
546
  '<div class="case-outcome">'
541
547
  f'{_status(result.passed, kind="stamp", size="md", seed=result.case_key)}'
@@ -723,6 +729,7 @@ summary:focus-visible, a:focus-visible, .verdict:focus-visible {{ outline: 2px s
723
729
  .case {{ background: var(--surface); border: 1px solid var(--border); border-radius: 6px; margin-bottom: 20px; overflow: clip; }}
724
730
  .case-header {{ display: flex; justify-content: space-between; gap: 24px; padding: 20px; border-bottom: 1px solid var(--border); }}
725
731
  .case-header > div {{ min-width: 0; }}
732
+ .case-header .case-description {{ margin: 2px 0 6px; color: var(--muted); overflow-wrap: anywhere; }}
726
733
  .case-header .path {{ margin: 0; overflow-wrap: anywhere; font-family: var(--font-mono); font-size: 12px; }}
727
734
  .eyebrow {{ color: var(--muted); font-family: var(--font-display); text-transform: uppercase; letter-spacing: .12em; font-size: 11px; }}
728
735
  .case-outcome {{ min-width: 130px; display: grid; justify-items: end; align-content: start; gap: 5px; }}
yama/runner.py CHANGED
@@ -9,14 +9,20 @@ from copy import deepcopy
9
9
  from dataclasses import dataclass, field
10
10
  from datetime import datetime, timezone
11
11
  from pathlib import Path
12
- from typing import Any
12
+ from typing import Any, Callable
13
13
 
14
14
  import yaml
15
15
 
16
16
  from .assertions import run_hard_assertions, run_judge
17
- from .tools.bash.fs import cleanup_session
17
+ from .tools.bash.fs import case_workspace_root, cleanup_session
18
18
  from .llm import LLMClient
19
- from .mocks import MockToolRegistry, ToolMockContext, _matches, load_python_callable
19
+ from .mocks import (
20
+ MockToolRegistry,
21
+ ToolMockContext,
22
+ _matches,
23
+ load_python_callable,
24
+ result_is_error,
25
+ )
20
26
  from .models import ResolvedCase, StepResult, ToolCallRecord, sanitize_case_key
21
27
 
22
28
 
@@ -83,16 +89,29 @@ class CaseResult:
83
89
  passed: bool
84
90
  runs: list[RunResult]
85
91
  pass_rate: float
92
+ description: str = ""
86
93
 
87
94
  def to_dict(self) -> dict[str, Any]:
88
95
  return {
89
96
  "case_key": self.case_key,
97
+ "description": self.description,
90
98
  "passed": self.passed,
91
99
  "pass_rate": self.pass_rate,
92
100
  "runs": [run.to_dict() for run in self.runs],
93
101
  }
94
102
 
95
103
 
104
+ # Progress callback: (event name, payload). Events, in emission order per case:
105
+ # "case_start" {case_key, description, repeat} -> per run: "run_start"
106
+ # {case_key, run_index, repeat} -> per step: "step_start" {case_key,
107
+ # run_index, step_id} then "step_end" {case_key, run_index, step: StepResult}
108
+ # -> "run_end" {case_key, run: RunResult} -> "case_end" {result: CaseResult}.
109
+ # step_end fires after the step's hard checks and judge have settled, so
110
+ # payloads carry final verdicts. A run that dies mid-step (timeout, handler
111
+ # exception) skips that step's step_end but still gets its run_end.
112
+ RunnerEventCallback = Callable[[str, dict[str, Any]], None]
113
+
114
+
96
115
  class YamaRunner:
97
116
  def __init__(
98
117
  self,
@@ -100,28 +119,49 @@ class YamaRunner:
100
119
  *,
101
120
  result_root: Path | None = None,
102
121
  write_artifacts: bool = True,
122
+ on_event: RunnerEventCallback | None = None,
103
123
  ) -> None:
104
124
  self.llm = llm
105
125
  self.result_root = result_root
106
126
  self.write_artifacts = write_artifacts
127
+ self.on_event = on_event
128
+
129
+ def _emit(self, event: str, **payload: Any) -> None:
130
+ if self.on_event is not None:
131
+ self.on_event(event, payload)
107
132
 
108
133
  async def run_case(self, case: ResolvedCase) -> CaseResult:
109
134
  repeat = int(case.execution.get("repeat", 1))
110
135
  if repeat < 1:
111
136
  raise ValueError("execution.repeat must be at least 1")
137
+ self._emit(
138
+ "case_start",
139
+ case_key=case.case_key,
140
+ description=case.description,
141
+ repeat=repeat,
142
+ )
143
+ self._clean_case_dirs(case)
112
144
  runs = [
113
145
  await self._run_once(case, run_index) for run_index in range(1, repeat + 1)
114
146
  ]
115
147
  passed_count = sum(run.passed for run in runs)
116
148
  result = CaseResult(
117
149
  case_key=case.case_key,
150
+ description=case.description,
118
151
  passed=passed_count == repeat,
119
152
  runs=runs,
120
153
  pass_rate=passed_count / repeat,
121
154
  )
155
+ self._emit("case_end", result=result)
122
156
  return result
123
157
 
124
158
  async def _run_once(self, case: ResolvedCase, run_index: int) -> RunResult:
159
+ self._emit(
160
+ "run_start",
161
+ case_key=case.case_key,
162
+ run_index=run_index,
163
+ repeat=int(case.execution.get("repeat", 1)),
164
+ )
125
165
  artifact_dir = self._artifact_dir(case, run_index)
126
166
  registry: MockToolRegistry | None = None
127
167
  steps: list[StepResult] = []
@@ -135,6 +175,12 @@ class YamaRunner:
135
175
  )
136
176
  messages = await self._initial_messages(case, registry, run_index)
137
177
  for step in case.steps:
178
+ self._emit(
179
+ "step_start",
180
+ case_key=case.case_key,
181
+ run_index=run_index,
182
+ step_id=step["id"],
183
+ )
138
184
  transcript_before = deepcopy(messages)
139
185
  timeout = float(case.execution.get("timeout_seconds_per_step", 120))
140
186
  try:
@@ -151,8 +197,13 @@ class YamaRunner:
151
197
  )
152
198
  except MaxToolRoundsExceeded as exc:
153
199
  messages[:] = transcript_before
154
- steps.append(
155
- self._max_tool_rounds_step_result(case, step, exc)
200
+ step_result = self._max_tool_rounds_step_result(case, step, exc)
201
+ steps.append(step_result)
202
+ self._emit(
203
+ "step_end",
204
+ case_key=case.case_key,
205
+ run_index=run_index,
206
+ step=step_result,
156
207
  )
157
208
  continue
158
209
  assertion_config = step.get("assert", {})
@@ -181,6 +232,12 @@ class YamaRunner:
181
232
  default_model=case.model,
182
233
  )
183
234
  steps.append(step_result)
235
+ self._emit(
236
+ "step_end",
237
+ case_key=case.case_key,
238
+ run_index=run_index,
239
+ step=step_result,
240
+ )
184
241
  passed = self._case_passed(case, steps)
185
242
  run = RunResult(
186
243
  run_index=run_index,
@@ -208,6 +265,7 @@ class YamaRunner:
208
265
  await cleanup_session(registry.state)
209
266
  if self.write_artifacts:
210
267
  self._write_artifacts(case, run)
268
+ self._emit("run_end", case_key=case.case_key, run=run)
211
269
  return run
212
270
 
213
271
  def _max_tool_rounds_step_result(
@@ -351,7 +409,7 @@ class YamaRunner:
351
409
  call_index=call_index,
352
410
  call=call,
353
411
  result=result,
354
- is_error=isinstance(result, dict) and "error" in result,
412
+ is_error=result_is_error(result),
355
413
  )
356
414
  records.append(record)
357
415
  messages.append(
@@ -452,12 +510,32 @@ class YamaRunner:
452
510
  return False
453
511
  return True
454
512
 
513
+ def _clean_case_dirs(self, case: ResolvedCase) -> None:
514
+ """Drop leftovers of earlier executions before the first run starts.
515
+
516
+ Both the bash-sandbox workspaces (`.yama/fs-runs/<case>`) and the run
517
+ artifacts (`.yama/runs/<case>`) are keyed by run index, which restarts
518
+ at 1 on every execution -- without this wipe a later execution would
519
+ reuse stale workspaces (old .mockbin scripts, files written by a
520
+ previous model) and leave orphaned run-00N artifact dirs behind when
521
+ execution.repeat shrinks.
522
+ """
523
+ fs_root = case_workspace_root(case.plugin_root, case.case_key)
524
+ if fs_root.exists():
525
+ shutil.rmtree(fs_root)
526
+ if self.write_artifacts:
527
+ case_dir = self._case_artifact_root(case)
528
+ if case_dir.exists():
529
+ shutil.rmtree(case_dir)
530
+
531
+ def _case_artifact_root(self, case: ResolvedCase) -> Path:
532
+ root = self.result_root or case.plugin_root / ".yama" / "runs"
533
+ return root / sanitize_case_key(case.case_key)
534
+
455
535
  def _artifact_dir(self, case: ResolvedCase, run_index: int) -> Path | None:
456
536
  if not self.write_artifacts:
457
537
  return None
458
- root = self.result_root or case.plugin_root / ".yama" / "runs"
459
- key = sanitize_case_key(case.case_key)
460
- return root / key / f"run-{run_index:03d}"
538
+ return self._case_artifact_root(case) / f"run-{run_index:03d}"
461
539
 
462
540
  def _write_artifacts(self, case: ResolvedCase, run: RunResult) -> None:
463
541
  assert run.artifact_dir is not None
@@ -475,6 +553,7 @@ class YamaRunner:
475
553
  entry["materialized_path"] = str(target)
476
554
  resolved = {
477
555
  "case_key": case.case_key,
556
+ "description": case.description,
478
557
  "path": str(case.path),
479
558
  "plugin_root": str(case.plugin_root),
480
559
  "evals_root": str(case.evals_root),
yama/tools/bash/fs.py CHANGED
@@ -463,6 +463,15 @@ class ShellSession:
463
463
  pass
464
464
 
465
465
 
466
+ def case_workspace_root(plugin_root: Path, case_key: str) -> Path:
467
+ """Parent directory of all bash-sandbox workspaces of one case.
468
+
469
+ The runner wipes it before a case's first run so a fresh execution never
470
+ reuses stale workspaces from an earlier one.
471
+ """
472
+ return plugin_root / ".yama" / "fs-runs" / sanitize_case_key(case_key)
473
+
474
+
466
475
  def workspace_dir(context: ToolMockContext) -> Path:
467
476
  """Bash-sandbox workspace directory of the current run.
468
477
 
@@ -471,10 +480,7 @@ def workspace_dir(context: ToolMockContext) -> Path:
471
480
  first `bash` call actually materializes the directory.
472
481
  """
473
482
  return (
474
- context.plugin_root
475
- / ".yama"
476
- / "fs-runs"
477
- / sanitize_case_key(context.case_key)
483
+ case_workspace_root(context.plugin_root, context.case_key)
478
484
  / f"run-{context.run_index:03d}"
479
485
  )
480
486
 
@@ -485,7 +491,12 @@ async def _get_session(
485
491
  session = _SESSIONS.get(id(context.state))
486
492
  if session is None or session.closed:
487
493
  workspace = workspace_dir(context)
488
- if not workspace.exists():
494
+ # Keyed on the per-run state marker, not directory existence: a
495
+ # leftover directory from an earlier execution (or one pre-created by
496
+ # a python handler) must still get this run's files and .mockbin
497
+ # scripts, while a session restart mid-run must not clobber what the
498
+ # model already wrote.
499
+ if "__fs__" not in context.state:
489
500
  materialize_workspace(workspace, fs_config)
490
501
  session = ShellSession(workspace, fs_config)
491
502
  await session.start()
@@ -1,98 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: python-yama
3
- Version: 0.1.0
4
- Summary: A reproducible evaluation runner for tool-using Agent skills
5
- Project-URL: Repository, https://github.com/world-sim-dev/yama
6
- Project-URL: Issues, https://github.com/world-sim-dev/yama/issues
7
- Author-email: Farmer Sun <podpodiumapp@gmail.com>
8
- License-Expression: MIT
9
- License-File: LICENSE
10
- Keywords: agent,evaluation,llm,skill,testing
11
- Classifier: Development Status :: 3 - Alpha
12
- Classifier: Intended Audience :: Developers
13
- Classifier: Programming Language :: Python :: 3
14
- Classifier: Programming Language :: Python :: 3.12
15
- Classifier: Programming Language :: Python :: 3.13
16
- Classifier: Topic :: Software Development :: Testing
17
- Requires-Python: >=3.12
18
- Requires-Dist: fastapi>=0.139.0
19
- Requires-Dist: jinja2>=3.1
20
- Requires-Dist: litellm<2.0,>=1.80
21
- Requires-Dist: orjson>=3.11.9
22
- Requires-Dist: pyyaml>=6.0
23
- Requires-Dist: rich<15.0,>=14.1
24
- Description-Content-Type: text/markdown
25
-
26
- # yama
27
-
28
- `yama` 是一个可复现的 Agent Skill 评测框架:用声明式 YAML Case 描述模型看到的 System Prompt、Skill metadata、Tool Schema 与多轮 User Message,通过 LiteLLM 统一调用 LLM 并驱动 Tool Loop,再对 Transcript 做确定性 Hard Check 或 LLM Judge 评分。完整 Case Schema 与执行契约见[设计文档](docs/agent-skill-test-framework-design.md)。
29
-
30
- ## 快速开始
31
-
32
- ```bash
33
- # 在 Plugin 根目录下直接运行,默认收集 __evals__/cases/**/*.yaml
34
- cd dingding-simple
35
- OPENAI_API_KEY=... uv run --project yama yama
36
-
37
- # 在 Workspace 根目录(存在 yama.toml)按名字指定 Plugin
38
- OPENAI_API_KEY=... uv run --project yama yama --plugin dingding-simple
39
- ```
40
-
41
- ## 编写一个 Case
42
-
43
- 一个 Case 是一份 YAML 文件,按 `context`(模型看到什么)→ `mocks`(Tool 怎么被执行)→ `steps`(依次发送的用户回合与断言)→ `outcome`(整个 Case 的通过门槛)的结构组织:
44
-
45
- ```yaml
46
- context:
47
- system_prompt: { default: true } # 使用 Plugin 根目录下的 SYSTEM.md
48
-
49
- tools:
50
- - file: tools/read-dsl.yaml # Tool Schema,相对 __evals__ 目录解析
51
-
52
- mocks:
53
- tools:
54
- read_dsl:
55
- respond:
56
- result:
57
- visualStyle: { name: 复古胶片 }
58
-
59
- steps:
60
- - id: request-directions
61
- user: 给我几个创意方向
62
- assert:
63
- hard:
64
- - tool_called: { name: read_dsl }
65
- - assistant_contains: 创意方向
66
-
67
- outcome:
68
- require:
69
- hard_checks: all_pass
70
- ```
71
-
72
- - `context.tools` 是发给模型的 Tool Schema,`mocks.tools` 是 Runner 收到 Tool Call 后如何返回结果;两者的 Tool 名字集合必须完全一致。
73
- - 需要 Skill 时在 `context.skills` 中按名字声明,并在 `context.tools` 中同时声明 `{builtin: skill}`;模型通过 `skill(name, file?)` 读取正文。
74
- - 需要模拟命令行工具时声明 `{builtin: bash}`,在 `mocks.cli` 中按命令配置输出。
75
- - `steps[].assert.hard` 是确定性检查(`tool_called`、`tool_arguments`、`assistant_contains` 等九种类型);还可以加 `assert.judge` 做 LLM 打分。
76
-
77
- 完整 Schema(Skill/Tool/Mock 的全部写法、`bash` 沙箱、Message Injection、Judge 配置等)见[设计文档](docs/agent-skill-test-framework-design.md)。
78
-
79
- ## 命令行使用
80
-
81
- ```bash
82
- uv run --project yama yama --plugin dingding-simple --report
83
- ```
84
-
85
- | 参数 | 含义 |
86
- | --- | --- |
87
- | `paths`(位置参数,可多个) | 显式指定要跑的 Case YAML 路径 |
88
- | `--plugin-root PATH` | 以指定路径作为单一 Plugin Root |
89
- | `--plugin NAME`(可重复) | 按 `yama.toml` 中的 Plugin 名字选择 |
90
- | `--all-plugins` | 运行 `yama.toml` 中配置的全部 Plugin |
91
- | `--response-script PATH` | 用脚本化 LLM 响应回放,不调用真实模型 |
92
- | `--result-dir PATH` | 覆盖产物根目录(默认 `<plugin_root>/.yama/runs`) |
93
- | `--report [PATH]` | 额外生成单文件 HTML 报告(默认 `.yama/reports/latest.html`) |
94
- | `--list` | 只打印匹配到的 Case,不运行 |
95
- | `--no-artifacts` | 不写任何产物文件 |
96
- | `--json` | 输出机器可读 JSON 而不是 Rich 表格 |
97
-
98
- `--plugin`/`--all-plugins`/`--plugin-root` 三者互斥;都不提供时默认用当前目录向上搜索到的 `yama.toml` 所在目录作为 Workspace Root(找不到则用 cwd),把该目录当作单一 Plugin Root 运行。