python-yama 0.6.0__py3-none-any.whl → 0.8.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-yama
3
- Version: 0.6.0
3
+ Version: 0.8.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
@@ -72,15 +72,14 @@ steps:
72
72
  - assistant_contains: creative direction
73
73
 
74
74
  outcome:
75
- require:
76
- hard_checks: all_pass
75
+ require: {}
77
76
  ```
78
77
 
79
78
  - `description` (optional) is a one-line summary of what the Case tests; it is shown in the CLI output and the HTML report.
80
79
  - `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.
81
80
  - 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?, call_reason?)`.
82
81
  - To simulate command-line tools, declare `{builtin: bash}` and configure per-command output under `mocks.cli`.
83
- - `steps[].assert.hard` are deterministic checks (nine types, including `tool_called`, `tool_arguments`, and `assistant_contains`); add `assert.judge` for LLM scoring.
82
+ - `steps[].assert.hard` are deterministic checks (nine types, including `tool_called`, `tool_arguments`, and `assistant_contains`); untagged hard checks must all pass by default. Add `assert.judge` for LLM scoring.
84
83
 
85
84
  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).
86
85
 
@@ -115,6 +114,15 @@ uv run --project yama yama dashboard --plugin dingding-simple
115
114
 
116
115
  `yama dashboard` starts a local HTTP server (default `http://127.0.0.1:8765/`, change with `--host`/`--port`; it also accepts the same plugin selection flags as the main command plus `-k/--filter` and `--result-dir`). The index page lists the historical HTML reports accumulated under `.yama/reports/` (newest first, with the `latest` one flagged), `/reports/<name>` serves each report, and `/preview` renders the same case preview as `--preview` — re-collecting and re-resolving the case files on every refresh (collection errors render as an error page), so you can edit a Case YAML and just reload the browser. No LLM calls are ever made by the dashboard.
117
116
 
117
+ ### PR evals
118
+
119
+ ```bash
120
+ uv run --project yama yama pr-plan --base origin/main --json
121
+ OPENAI_API_KEY=... uv run --project yama yama pr-run --base origin/main --report --json-summary yama-pr-summary.json
122
+ ```
123
+
124
+ `yama pr-plan` selects PR-scoped eval cases without model calls. `yama pr-run` executes the same selection and writes a JSON summary for external CI jobs to render or upload; credentials stay in environment variables or `.env`, not CLI flags. `pr-run` always forces builtin bash execution to the Linux `linux-bubblewrap` sandbox, regardless of Case backend settings, so the runner must be Linux with `bwrap`/`bubblewrap` installed. See the [CI integration guide](https://github.com/world-sim-dev/yama/blob/main/docs/pr-evals-ci-integration.zh-CN.md) for workflow examples and the summary JSON contract.
125
+
118
126
  ### Output
119
127
 
120
128
  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,30 +1,31 @@
1
1
  yama/__init__.py,sha256=UYhoZTSu1HiMT54LOZCdvLKMQ_L0qec8RT8jDfde_cY,1156
2
2
  yama/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
3
  yama/assertions.py,sha256=9tp_fuoFxqHPrClq_D1WF4i58TxgZUMnTdc-Kc9uKiw,23000
4
- yama/cli.py,sha256=ipNWX1_2o7jy5NmYU3LyKmoPo68VF-LO6A2F8QQw9Tk,34699
4
+ yama/cli.py,sha256=GDhKWyPFvZLJ8lyxl0ZAsRE6zWyaXiWfpw6Lxth1emI,45116
5
5
  yama/dashboard.py,sha256=0yxRh-j_5Mk6Ug_xgv9-VyBSEr1aVKxX-zJwxGfd_TU,11601
6
6
  yama/llm.py,sha256=JzQ4YHhBLd1WE8W_ipTVcoNK6f-nSqRKDzqEl5kmuis,16085
7
7
  yama/mocks.py,sha256=YyiU6Y7NgttxHYJBsqGPILKYlTsM4IMTIilMNRkUuzs,14973
8
- yama/models.py,sha256=0BMCWku5zWDOESrFUibiJShlfEhOAGlVKaNxfPB-9OM,4020
8
+ yama/models.py,sha256=zd8RIxvUoWa3OdCLIRtgLvYmCVtkAjhQECJheo3HmKE,4128
9
+ yama/pr.py,sha256=QDFhtDN6oKBPAGQzVZIuWhHKExQAdjKlvTEo5gBmogs,11325
9
10
  yama/preview.py,sha256=gVTMqArXQqOLktGnactK9c0kfX6oHd6fWGjhkB7-QLQ,14220
10
- yama/report.py,sha256=GyJ7oMKYwrLlt3hFXw6915er-6SWU4nr_Qhx37UJA2c,59590
11
- yama/runner.py,sha256=zACo6shEqV-9Y_bu4bZs2vjdgaPPr5qj0KylTlqevEs,33549
12
- yama/thread_case.py,sha256=ZaQvuu1uj9o9adTIbYghYp9iXEVqhEmoG4_b6duHYy0,13147
11
+ yama/report.py,sha256=WVY4EWInVQbE-Pv2LFHcH-QMoPFpdOd5unDs4uGEq-w,64557
12
+ yama/runner.py,sha256=e3vIBgYBAbhRzG7aUTb9YKw5HJlEUWdpASIDwav1RGQ,38942
13
+ yama/thread_case.py,sha256=WZzF4va44aRUkJ4DxP3m9F1A219AhwKQHG5fi9-tPqQ,13106
13
14
  yama/workspace.py,sha256=4GAe36Uj1-gjROMPwrQfTIg1TkzEIk9-gHEuezjbY_I,4614
14
15
  yama/loaders/__init__.py,sha256=DIwfa8QlIlKt6NpFMZJ_OcqbJPPrmKLBzd9_e-BCuBs,174
15
- yama/loaders/case.py,sha256=5uUpXm1t9EOmee2BZe7vDGXCrc4CSgcFGApSkuFe5tc,13954
16
+ yama/loaders/case.py,sha256=ADiaX6REgIMDlvIJWG4fV-Gj4RIy7TJ2Tr7eNrM3fq0,15190
16
17
  yama/loaders/common.py,sha256=Fg71_vcnu5339QI_itvYPvRbk9LtBgEnzoA3t4Krb4U,754
17
- yama/loaders/tool_loader.py,sha256=AaJwrFEjmfdUhKqXIlfl_jyvaKQ4ZoPPOpT8Wg5xuNU,12574
18
+ yama/loaders/tool_loader.py,sha256=J_p8jb_GgL_2X-_2teKHzLer9TWKh0FUuzXsEBZ8nTU,12917
18
19
  yama/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
20
  yama/tools/base.py,sha256=ONFuGzTSWVsA0k4-UUREncqAHmyQI2uHpVOU2Dh_XiQ,446
20
21
  yama/tools/bash/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
22
  yama/tools/bash/_cli_shim.py,sha256=f3Rom5UipW0dA0KRYavqIa9HJDKT336ssDZGWeVmkvo,2494
22
- yama/tools/bash/bash.py,sha256=4GlFvmqTUS4k6DgJ5Io91YF5fB6wF6e3e7p2P-pmbEQ,10358
23
- yama/tools/bash/fs.py,sha256=GChDwGe_Sgn73btZJDNp5nOwlVDhLfZyaMVqWSQwfOw,21859
23
+ yama/tools/bash/bash.py,sha256=dGKi2EvftnLs3CrJlbo4IYm6aicWrEnFzrXoH0vYqGw,10451
24
+ yama/tools/bash/fs.py,sha256=gPsdiTomnURzv1mTq6qWDlCg9IZNU_r-sYYk3S3NODQ,23706
24
25
  yama/tools/skill/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
26
  yama/tools/skill/skill.py,sha256=H2KdIBLkYhecYX7M2xbn79csDpDvougpRcAmlrwigEM,2235
26
- python_yama-0.6.0.dist-info/METADATA,sha256=z4vYMlK6PlFbY6ydnGbCKwJFHDFSfDxc2UyAMeJZnvA,7515
27
- python_yama-0.6.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
28
- python_yama-0.6.0.dist-info/entry_points.txt,sha256=N5se3y1FflUcDU3TmUrH2Tu9dzsrBBo7sUP-Gu_2cVs,39
29
- python_yama-0.6.0.dist-info/licenses/LICENSE,sha256=cMAJJAs7R1lemJPPc7qMNv4w_sqn5QncFf4aXKYyEc4,1067
30
- python_yama-0.6.0.dist-info/RECORD,,
27
+ python_yama-0.8.0.dist-info/METADATA,sha256=jbj_fzTF7kW-SuZTcnTBMEqU3l5QJMvSC9ZbHsmLT2g,8348
28
+ python_yama-0.8.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
29
+ python_yama-0.8.0.dist-info/entry_points.txt,sha256=N5se3y1FflUcDU3TmUrH2Tu9dzsrBBo7sUP-Gu_2cVs,39
30
+ python_yama-0.8.0.dist-info/licenses/LICENSE,sha256=cMAJJAs7R1lemJPPc7qMNv4w_sqn5QncFf4aXKYyEc4,1067
31
+ python_yama-0.8.0.dist-info/RECORD,,
yama/cli.py CHANGED
@@ -29,6 +29,16 @@ from .dashboard import create_dashboard_server
29
29
  from .llm import LLMError, LiteLLMClient
30
30
  from .loaders import CollectionError, resolve_case
31
31
  from .preview import preview_payload, write_preview_html
32
+ from .pr import (
33
+ apply_pr_repeat,
34
+ build_pr_plan,
35
+ parse_changed_file_lines,
36
+ plugin_result_key,
37
+ pr_plan_to_dict,
38
+ pr_run_exit_status,
39
+ pr_summary_to_dict,
40
+ read_changed_files_from_git,
41
+ )
32
42
  from .report import write_html_report, write_timestamped_report
33
43
  from .runner import YamaRunner, combine_usage
34
44
  from .thread_case import (
@@ -47,12 +57,48 @@ from .thread_case import (
47
57
  DEFAULT_REPORT = Path("__yama_default_report__")
48
58
 
49
59
 
50
- def _status(passed: bool, *, compact: bool = False) -> Text:
51
- if passed:
60
+ def _result_status(value: Any) -> str:
61
+ if isinstance(value, bool):
62
+ return "pass" if value else "fail"
63
+ if isinstance(value, str) and value in {"pass", "fail", "error"}:
64
+ return value
65
+ if hasattr(value, "status"):
66
+ return _result_status(getattr(value, "status"))
67
+ if hasattr(value, "passed"):
68
+ return _result_status(bool(getattr(value, "passed")))
69
+ return "fail"
70
+
71
+
72
+ def _status(value: Any, *, compact: bool = False) -> Text:
73
+ status = _result_status(value)
74
+ if status == "pass":
52
75
  return Text("✓" if compact else "PASS", style="bold green")
76
+ if status == "error":
77
+ return Text("!" if compact else "ERROR", style="bold yellow")
53
78
  return Text("✗" if compact else "FAIL", style="bold red")
54
79
 
55
80
 
81
+ def _evaluated_runs(result: Any) -> list[Any]:
82
+ return [run for run in result.runs if _result_status(run) != "error"]
83
+
84
+
85
+ def _error_kind(value: Any) -> str | None:
86
+ kind = getattr(value, "error_kind", None)
87
+ return kind if kind in {"llm", "framework"} else None
88
+
89
+
90
+ def _error_kind_label(kind: str | None) -> str:
91
+ if kind == "llm":
92
+ return "LLM error"
93
+ if kind == "framework":
94
+ return "Framework error"
95
+ return "Error"
96
+
97
+
98
+ def _plural(count: int, singular: str) -> str:
99
+ return f"{count} {singular}{'' if count == 1 else 's'}"
100
+
101
+
56
102
  def _usage_label(usage: dict[str, int] | None, *, split: bool = False) -> str:
57
103
  """`tokens 12,345`-style suffix for labels and captions; empty when no
58
104
  LLM call reported usage (scripted replays, runs that died early)."""
@@ -67,6 +113,13 @@ def _usage_label(usage: dict[str, int] | None, *, split: bool = False) -> str:
67
113
  return label
68
114
 
69
115
 
116
+ def _judge_required_label(judge: dict[str, Any]) -> str:
117
+ required = judge.get("overall_required")
118
+ if isinstance(required, (int, float)):
119
+ return f" (required >= {required:.0%})"
120
+ return ""
121
+
122
+
70
123
  def _summary_case_key(case_key: str) -> str:
71
124
  prefix = "__evals__/cases/"
72
125
  return case_key.removeprefix(prefix)
@@ -102,6 +155,7 @@ def build_step_tree(step: Any) -> Tree:
102
155
  )
103
156
  if isinstance(judge.get("overall"), (int, float)):
104
157
  step_label.append(f" {judge['overall']:.0%}", style="dim")
158
+ step_label.append(_judge_required_label(judge), style="dim")
105
159
  step_node = Tree(step_label, guide_style="dim")
106
160
  if judge is not None and not judge_passed:
107
161
  judge_node = step_node.add(Text("Judge dimensions", style="bold red"))
@@ -152,7 +206,7 @@ def build_case_tree(result: Any) -> Tree:
152
206
  """Whole-case verdict tree (runs -> steps), shared by the aggregated
153
207
  details of `format_text_results` and the parallel progress output."""
154
208
  case_label = Text.assemble(
155
- _status(result.passed, compact=True),
209
+ _status(result, compact=True),
156
210
  " ",
157
211
  (result.case_key, "bold"),
158
212
  (f" {result.pass_rate:.0%}", "dim"),
@@ -165,7 +219,7 @@ def build_case_tree(result: Any) -> Tree:
165
219
  tree = Tree(case_label, guide_style="dim")
166
220
  for run in result.runs:
167
221
  run_label = Text.assemble(
168
- _status(run.passed, compact=True),
222
+ _status(run, compact=True),
169
223
  " ",
170
224
  (f"Run {run.run_index}", "bold"),
171
225
  )
@@ -176,7 +230,12 @@ def build_case_tree(result: Any) -> Tree:
176
230
  run_label.append(f" {_usage_label(run_usage)}", style="dim")
177
231
  run_node = tree.add(run_label)
178
232
  if run.error:
179
- run_node.add(Text.assemble(("Error: ", "bold red"), (run.error, "red")))
233
+ run_node.add(
234
+ Text.assemble(
235
+ (f"{_error_kind_label(_error_kind(run))}: ", "bold yellow"),
236
+ (run.error, "yellow"),
237
+ )
238
+ )
180
239
  run_node.children.extend(build_step_tree(step) for step in run.steps)
181
240
  return tree
182
241
 
@@ -196,32 +255,65 @@ def build_summary_table(results: list[Any]) -> Table:
196
255
  table.add_column("Tokens", justify="right", no_wrap=True)
197
256
 
198
257
  passed_runs = 0
199
- total_runs = 0
258
+ evaluated_run_count = 0
259
+ error_runs = 0
260
+ llm_errors = 0
261
+ framework_errors = 0
200
262
  for result in results:
201
- case_passed_runs = sum(run.passed for run in result.runs)
263
+ evaluated_runs = _evaluated_runs(result)
264
+ case_passed_runs = sum(run.passed for run in evaluated_runs)
265
+ case_error_runs = len(result.runs) - len(evaluated_runs)
202
266
  passed_runs += case_passed_runs
203
- total_runs += len(result.runs)
267
+ evaluated_run_count += len(evaluated_runs)
268
+ error_runs += case_error_runs
269
+ llm_errors += sum(1 for run in result.runs if _error_kind(run) == "llm")
270
+ framework_errors += sum(
271
+ 1 for run in result.runs if _error_kind(run) == "framework"
272
+ )
204
273
  case_cell = Text(_summary_case_key(result.case_key))
205
274
  if result.description:
206
275
  case_cell.append(f"\n{result.description}", style="dim")
207
276
  usage = result.usage()
277
+ run_count = f"{case_passed_runs}/{len(evaluated_runs)}"
278
+ if case_error_runs:
279
+ run_count += f" (+{case_error_runs} error)"
208
280
  table.add_row(
209
- _status(result.passed),
281
+ _status(result),
210
282
  case_cell,
211
- f"{case_passed_runs}/{len(result.runs)}",
283
+ run_count,
212
284
  f"{result.pass_rate:.0%}",
213
285
  f"{usage['total_tokens']:,}" if usage else "–",
214
286
  )
215
287
 
216
- passed_cases = sum(result.passed for result in results)
288
+ error_cases = sum(1 for result in results if _result_status(result) == "error")
289
+ evaluated_cases = len(results) - error_cases
290
+ passed_cases = sum(
291
+ result.passed for result in results if _result_status(result) != "error"
292
+ )
217
293
  table.caption = (
218
- f"{passed_cases}/{len(results)} cases passed • "
219
- f"{passed_runs}/{total_runs} runs passed"
294
+ f"{passed_cases}/{evaluated_cases} cases passed • "
295
+ f"{passed_runs}/{evaluated_run_count} runs passed"
220
296
  )
297
+ if error_cases:
298
+ table.caption += f" • {error_cases} case error"
299
+ if error_cases != 1:
300
+ table.caption += "s"
301
+ if error_runs:
302
+ table.caption += f" • {_plural(error_runs, 'run error')}"
303
+ if llm_errors:
304
+ table.caption += f" • {_plural(llm_errors, 'llm error')}"
305
+ if framework_errors:
306
+ table.caption += f" • {_plural(framework_errors, 'framework error')}"
221
307
  total_usage = combine_usage(result.usage() for result in results)
222
308
  if total_usage:
223
309
  table.caption += f" • {_usage_label(total_usage, split=True)}"
224
- table.caption_style = "green" if passed_cases == len(results) else "red"
310
+ failed_cases = evaluated_cases - passed_cases
311
+ if failed_cases:
312
+ table.caption_style = "red"
313
+ elif error_cases:
314
+ table.caption_style = "yellow"
315
+ else:
316
+ table.caption_style = "green"
225
317
  return table
226
318
 
227
319
 
@@ -303,17 +395,21 @@ class ProgressPrinter:
303
395
  )
304
396
  elif event == "case_end":
305
397
  result = payload["result"]
306
- passed_runs = sum(run.passed for run in result.runs)
398
+ evaluated_runs = _evaluated_runs(result)
399
+ passed_runs = sum(run.passed for run in evaluated_runs)
400
+ error_runs = len(result.runs) - len(evaluated_runs)
307
401
  meta = (
308
- f" {passed_runs}/{len(result.runs)} runs passed"
402
+ f" {passed_runs}/{len(evaluated_runs)} runs passed"
309
403
  f" {result.pass_rate:.0%}"
310
404
  )
405
+ if error_runs:
406
+ meta += f" {error_runs} error"
311
407
  usage = result.usage()
312
408
  if usage:
313
409
  meta += f" {_usage_label(usage)}"
314
410
  self.console.print(
315
411
  Text.assemble(
316
- _status(result.passed, compact=True),
412
+ _status(result, compact=True),
317
413
  " ",
318
414
  (result.case_key, "bold"),
319
415
  (meta, "dim"),
@@ -410,16 +506,20 @@ class ParallelProgressPrinter:
410
506
  )
411
507
  else:
412
508
  result = row["result"]
413
- passed_runs = sum(run.passed for run in result.runs)
509
+ evaluated_runs = _evaluated_runs(result)
510
+ passed_runs = sum(run.passed for run in evaluated_runs)
511
+ error_runs = len(result.runs) - len(evaluated_runs)
414
512
  meta = (
415
- f" {passed_runs}/{len(result.runs)} runs"
513
+ f" {passed_runs}/{len(evaluated_runs)} runs"
416
514
  f" {result.pass_rate:.0%}"
417
515
  )
516
+ if error_runs:
517
+ meta += f" {error_runs} error"
418
518
  usage = result.usage()
419
519
  if usage:
420
520
  meta += f" {_usage_label(usage)}"
421
521
  grid.add_row(
422
- _status(result.passed, compact=True),
522
+ _status(result, compact=True),
423
523
  Text.assemble((case_key, "bold"), (meta, "dim")),
424
524
  )
425
525
  return grid
@@ -727,7 +827,193 @@ async def _run(args: argparse.Namespace) -> int:
727
827
  (str(report_path), f"cyan link {report_path.as_uri()}"),
728
828
  )
729
829
  )
730
- return 0 if all(result.passed for result in all_results) else 1
830
+ if any(_result_status(result) == "fail" for result in all_results):
831
+ return 1
832
+ if any(_result_status(result) == "error" for result in all_results):
833
+ return 2
834
+ return 0
835
+
836
+
837
+ def _pr_plan_parser() -> argparse.ArgumentParser:
838
+ parser = argparse.ArgumentParser(
839
+ prog="yama pr-plan",
840
+ description="Plan PR-scoped eval cases without running them.",
841
+ )
842
+ parser.add_argument(
843
+ "--base",
844
+ default=None,
845
+ help="git diff base ref; yama diffs <base>...<head>",
846
+ )
847
+ parser.add_argument(
848
+ "--head",
849
+ default="HEAD",
850
+ help="git diff head ref for the PR branch",
851
+ )
852
+ parser.add_argument(
853
+ "--changed-files",
854
+ type=Path,
855
+ help="File containing changed paths or git diff --name-status lines",
856
+ )
857
+ parser.add_argument("--json", action="store_true", help="Print machine-readable plan")
858
+ return parser
859
+
860
+
861
+ def _changed_files_for_args(args: argparse.Namespace) -> Any:
862
+ if args.changed_files:
863
+ return parse_changed_file_lines(
864
+ args.changed_files.read_text(encoding="utf-8").splitlines()
865
+ )
866
+ if not args.base:
867
+ raise ConfigurationError("--base is required unless --changed-files is provided")
868
+ return read_changed_files_from_git(args.base, args.head)
869
+
870
+
871
+ def _run_pr_plan(args: argparse.Namespace) -> int:
872
+ workspace = load_workspace_config(Path.cwd())
873
+ changed_files = _changed_files_for_args(args)
874
+ plan = build_pr_plan(workspace, changed_files, base=args.base, head=args.head)
875
+ payload = pr_plan_to_dict(plan, workspace.root)
876
+ if args.json:
877
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
878
+ else:
879
+ console = Console()
880
+ if not plan.plugins:
881
+ console.print("No PR eval cases selected.")
882
+ for plugin in plan.plugins:
883
+ console.print(f"{plugin.name or '<workspace>'}: {len(plugin.cases)} case(s)")
884
+ for case in plugin.cases:
885
+ console.print(f" - {case.case_key} ({', '.join(case.reasons)})")
886
+ for warning in plugin.warnings:
887
+ console.print(f" warning: {warning}", style="yellow")
888
+ return 0
889
+
890
+
891
+ def _pr_run_parser() -> argparse.ArgumentParser:
892
+ parser = argparse.ArgumentParser(
893
+ prog="yama pr-run",
894
+ description="Run PR-scoped eval cases and write yama-side summary JSON.",
895
+ )
896
+ parser.add_argument(
897
+ "--base",
898
+ default=None,
899
+ help="git diff base ref; yama diffs <base>...<head>",
900
+ )
901
+ parser.add_argument(
902
+ "--head",
903
+ default="HEAD",
904
+ help="git diff head ref for the PR branch",
905
+ )
906
+ parser.add_argument("--changed-files", type=Path)
907
+ parser.add_argument("--report", action="store_true")
908
+ parser.add_argument("--json-summary", type=Path, required=True)
909
+ parser.add_argument("--concurrency", type=_positive_int, default=10)
910
+ parser.add_argument("--no-artifacts", action="store_true")
911
+ return parser
912
+
913
+
914
+ async def _run_pr_run(args: argparse.Namespace) -> int:
915
+ workspace = load_workspace_config(Path.cwd())
916
+ changed_files = _changed_files_for_args(args)
917
+ plan = build_pr_plan(workspace, changed_files, base=args.base, head=args.head)
918
+ if not any(plugin.cases for plugin in plan.plugins):
919
+ payload = pr_summary_to_dict(plan, workspace_root=workspace.root, plugin_results={})
920
+ args.json_summary.parent.mkdir(parents=True, exist_ok=True)
921
+ args.json_summary.write_text(
922
+ json.dumps(payload, ensure_ascii=False, indent=2),
923
+ encoding="utf-8",
924
+ )
925
+ print("No PR eval cases selected.")
926
+ return 0
927
+
928
+ plugin_results: dict[str, dict[str, Any]] = {}
929
+ for plugin in plan.plugins:
930
+ if not plugin.cases:
931
+ continue
932
+ plugin_key = plugin_result_key(plugin, workspace.root)
933
+ result_root = plugin.root / workspace.result_dir
934
+ try:
935
+ cases = [
936
+ apply_pr_repeat(
937
+ resolve_case(
938
+ selected.path,
939
+ plugin.root,
940
+ workspace,
941
+ plugin.config,
942
+ force_bash_backend="linux-bubblewrap",
943
+ ),
944
+ plugin.repeat,
945
+ )
946
+ for selected in plugin.cases
947
+ ]
948
+ except (ConfigurationError, CollectionError, ValueError) as exc:
949
+ plugin_results[plugin_key] = {
950
+ "results": [],
951
+ "errors": [{"phase": "collection", "message": str(exc)}],
952
+ "report_path": None,
953
+ "latest_report_path": None,
954
+ "runs_root": result_root,
955
+ }
956
+ continue
957
+ progress_console = Console(stderr=True)
958
+ progress = (
959
+ ParallelProgressPrinter(progress_console, cases=cases)
960
+ if args.concurrency > 1 and len(cases) > 1
961
+ else ProgressPrinter(progress_console, total_cases=len(cases))
962
+ )
963
+ semaphore = asyncio.Semaphore(args.concurrency)
964
+
965
+ async def run_one(case: Any) -> Any:
966
+ async with semaphore:
967
+ runner = YamaRunner(
968
+ LiteLLMClient(),
969
+ result_root=result_root,
970
+ write_artifacts=not args.no_artifacts,
971
+ on_event=progress,
972
+ )
973
+ return await runner.run_case(case)
974
+
975
+ try:
976
+ outcomes = await asyncio.gather(
977
+ *(run_one(case) for case in cases),
978
+ return_exceptions=True,
979
+ )
980
+ finally:
981
+ progress.close()
982
+ plugin_errors = []
983
+ for outcome in outcomes:
984
+ if isinstance(outcome, BaseException):
985
+ plugin_errors.append({"phase": "execution", "message": str(outcome)})
986
+ results = [
987
+ outcome for outcome in outcomes if not isinstance(outcome, BaseException)
988
+ ]
989
+ report_path = None
990
+ if args.report:
991
+ report_path = write_timestamped_report(
992
+ cases,
993
+ results,
994
+ result_root.parent / "reports",
995
+ )
996
+ plugin_results[plugin_key] = {
997
+ "results": results,
998
+ "errors": plugin_errors,
999
+ "report_path": report_path,
1000
+ "latest_report_path": result_root.parent / "reports" / "latest.html"
1001
+ if report_path
1002
+ else None,
1003
+ "runs_root": result_root,
1004
+ }
1005
+
1006
+ payload = pr_summary_to_dict(
1007
+ plan,
1008
+ workspace_root=workspace.root,
1009
+ plugin_results=plugin_results,
1010
+ )
1011
+ args.json_summary.parent.mkdir(parents=True, exist_ok=True)
1012
+ args.json_summary.write_text(
1013
+ json.dumps(payload, ensure_ascii=False, indent=2),
1014
+ encoding="utf-8",
1015
+ )
1016
+ return pr_run_exit_status(plugin_results)
731
1017
 
732
1018
 
733
1019
  def _dashboard_parser() -> argparse.ArgumentParser:
@@ -916,6 +1202,10 @@ def main(argv: list[str] | None = None) -> int:
916
1202
  return _run_dashboard(_dashboard_parser().parse_args(argv[1:]))
917
1203
  if argv[:1] == ["from-thread"]:
918
1204
  return _run_thread_case(_thread_case_parser().parse_args(argv[1:]))
1205
+ if argv[:1] == ["pr-plan"]:
1206
+ return _run_pr_plan(_pr_plan_parser().parse_args(argv[1:]))
1207
+ if argv[:1] == ["pr-run"]:
1208
+ return asyncio.run(_run_pr_run(_pr_run_parser().parse_args(argv[1:])))
919
1209
  args = _parser().parse_args(argv)
920
1210
  return asyncio.run(_run(args))
921
1211
  except (ConfigurationError, CollectionError, ValueError) as exc:
yama/loaders/case.py CHANGED
@@ -230,6 +230,8 @@ def resolve_case(
230
230
  plugin_root: Path,
231
231
  workspace: WorkspaceConfig,
232
232
  plugin_config: dict[str, Any],
233
+ *,
234
+ force_bash_backend: str | None = None,
233
235
  ) -> ResolvedCase:
234
236
  raw = load_yaml(path)
235
237
  evals_root = (plugin_root / "__evals__").resolve()
@@ -256,18 +258,6 @@ def resolve_case(
256
258
  "skills_dir": plugin_config.get("skills_dir", "skills"),
257
259
  "skill_entry": plugin_config.get("skill_entry", "SKILL.md"),
258
260
  }
259
- system_config = context.get("system_prompt", {"default": True})
260
- if system_config is None or system_config == {"default": True}:
261
- system_path = plugin_root / conventions["system_prompt"]
262
- elif isinstance(system_config, dict) and isinstance(system_config.get("file"), str):
263
- system_path = evals_root / system_config["file"]
264
- else:
265
- raise CollectionError(
266
- "context.system_prompt must use {default: true} or {file: ...}"
267
- )
268
- if not system_path.is_file():
269
- raise CollectionError(f"system prompt does not exist: {system_path}")
270
-
271
261
  skills = [
272
262
  _load_skill(
273
263
  plugin_root, conventions["skills_dir"], conventions["skill_entry"], item
@@ -277,9 +267,48 @@ def resolve_case(
277
267
  names = [skill.name for skill in skills]
278
268
  if len(names) != len(set(names)):
279
269
  raise CollectionError("context.skills contains duplicate names")
280
- rendered_system = _render_system_prompt(
281
- system_path.read_text(encoding="utf-8"), skills
282
- )
270
+
271
+ context_messages = context.get("messages", [])
272
+ if not isinstance(context_messages, list):
273
+ raise CollectionError("context.messages must be a list")
274
+ recorded_system_message: dict[str, Any] | None = None
275
+ if context_messages and isinstance(context_messages[0], dict):
276
+ first_message = context_messages[0]
277
+ if first_message.get("role") == "system":
278
+ content = first_message.get("content")
279
+ if not isinstance(content, str) or not content:
280
+ raise CollectionError(
281
+ "context.messages[0] is a system message but its content "
282
+ "must be a non-empty string to replay as the recorded "
283
+ "system prompt"
284
+ )
285
+ recorded_system_message = first_message
286
+
287
+ if recorded_system_message is None:
288
+ system_config = context.get("system_prompt", {"default": True})
289
+ if system_config is None or system_config == {"default": True}:
290
+ system_path = plugin_root / conventions["system_prompt"]
291
+ elif isinstance(system_config, dict) and isinstance(
292
+ system_config.get("file"), str
293
+ ):
294
+ system_path = evals_root / system_config["file"]
295
+ else:
296
+ raise CollectionError(
297
+ "context.system_prompt must use {default: true} or {file: ...}"
298
+ )
299
+ if not system_path.is_file():
300
+ raise CollectionError(f"system prompt does not exist: {system_path}")
301
+ rendered_system = _render_system_prompt(
302
+ system_path.read_text(encoding="utf-8"), skills
303
+ )
304
+ initial_messages: list[dict[str, Any]] = [
305
+ {"role": "system", "content": rendered_system}
306
+ ]
307
+ history_messages = context_messages
308
+ else:
309
+ rendered_system = recorded_system_message["content"]
310
+ initial_messages = [deepcopy(recorded_system_message)]
311
+ history_messages = context_messages[1:]
283
312
 
284
313
  mocks = deepcopy(raw.get("mocks", {}))
285
314
  if not isinstance(mocks, dict):
@@ -298,13 +327,11 @@ def resolve_case(
298
327
  evals_root=evals_root,
299
328
  skills=skills,
300
329
  conventions=conventions,
330
+ force_bash_backend=force_bash_backend,
301
331
  )
302
332
 
303
333
  fixture_manifest: list[dict[str, Any]] = []
304
- initial_messages: list[dict[str, Any]] = [
305
- {"role": "system", "content": rendered_system}
306
- ]
307
- for message in context.get("messages", []):
334
+ for message in history_messages:
308
335
  if not isinstance(message, dict) or message.get("role") not in {
309
336
  "user",
310
337
  "assistant",
@@ -74,6 +74,7 @@ def resolve_builtin_handlers(
74
74
  evals_root: Path,
75
75
  skills: list[LoadedSkill],
76
76
  conventions: dict[str, str],
77
+ force_bash_backend: str | None = None,
77
78
  ) -> None:
78
79
  """Wire builtin tool declarations and expand ``handler: {builtin: ...}``.
79
80
 
@@ -140,6 +141,9 @@ def resolve_builtin_handlers(
140
141
  raise CollectionError("mocks.cli cannot be combined with mocks.fs")
141
142
  try:
142
143
  if fs_raw is not None:
144
+ if force_bash_backend is not None and isinstance(fs_raw, dict):
145
+ fs_raw = dict(fs_raw)
146
+ fs_raw["backend"] = force_bash_backend
143
147
  handler_with: dict[str, Any] = {
144
148
  "fs": normalize_fs_config(
145
149
  fs_raw, base_dir=evals_root, root=evals_root.parent
@@ -151,6 +155,8 @@ def resolve_builtin_handlers(
151
155
  cli_raw, base_dir=evals_root, root=evals_root.parent
152
156
  )
153
157
  }
158
+ if force_bash_backend is not None:
159
+ handler_with["fs_backend"] = force_bash_backend
154
160
  except MockConfigurationError as exc:
155
161
  raise CollectionError(str(exc)) from exc
156
162
  for entry in bash_entries: