python-yama 0.7.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.7.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
@@ -114,6 +114,15 @@ uv run --project yama yama dashboard --plugin dingding-simple
114
114
 
115
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.
116
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
+
117
126
  ### Output
118
127
 
119
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=bM1w8AbSzLkaAKypznIfhGA0iWKbpN8BoS0a4G9vCpI,38032
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
8
  yama/models.py,sha256=zd8RIxvUoWa3OdCLIRtgLvYmCVtkAjhQECJheo3HmKE,4128
9
+ yama/pr.py,sha256=QDFhtDN6oKBPAGQzVZIuWhHKExQAdjKlvTEo5gBmogs,11325
9
10
  yama/preview.py,sha256=gVTMqArXQqOLktGnactK9c0kfX6oHd6fWGjhkB7-QLQ,14220
10
11
  yama/report.py,sha256=WVY4EWInVQbE-Pv2LFHcH-QMoPFpdOd5unDs4uGEq-w,64557
11
12
  yama/runner.py,sha256=e3vIBgYBAbhRzG7aUTb9YKw5HJlEUWdpASIDwav1RGQ,38942
12
- yama/thread_case.py,sha256=9TvZxbzqk3Klihq9ghyRcyhv63HSkjEMQgrOEf26L4g,13171
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.7.0.dist-info/METADATA,sha256=abnFJBim_JNAHsPiflJ6wn-OT8lhwBALIM9NrnzMsmw,7539
27
- python_yama-0.7.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
28
- python_yama-0.7.0.dist-info/entry_points.txt,sha256=N5se3y1FflUcDU3TmUrH2Tu9dzsrBBo7sUP-Gu_2cVs,39
29
- python_yama-0.7.0.dist-info/licenses/LICENSE,sha256=cMAJJAs7R1lemJPPc7qMNv4w_sqn5QncFf4aXKYyEc4,1067
30
- python_yama-0.7.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 (
@@ -824,6 +834,188 @@ async def _run(args: argparse.Namespace) -> int:
824
834
  return 0
825
835
 
826
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)
1017
+
1018
+
827
1019
  def _dashboard_parser() -> argparse.ArgumentParser:
828
1020
  parser = argparse.ArgumentParser(
829
1021
  prog="yama dashboard",
@@ -1010,6 +1202,10 @@ def main(argv: list[str] | None = None) -> int:
1010
1202
  return _run_dashboard(_dashboard_parser().parse_args(argv[1:]))
1011
1203
  if argv[:1] == ["from-thread"]:
1012
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:])))
1013
1209
  args = _parser().parse_args(argv)
1014
1210
  return asyncio.run(_run(args))
1015
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:
yama/pr.py ADDED
@@ -0,0 +1,350 @@
1
+ from __future__ import annotations
2
+
3
+ import subprocess
4
+ from dataclasses import dataclass, field, replace
5
+ from pathlib import Path
6
+ from typing import Any, Iterable, Mapping, Sequence
7
+
8
+ import yaml
9
+
10
+ from .models import ResolvedCase
11
+ from .workspace import WorkspaceConfig, case_key_for_path
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class ChangedFile:
16
+ path: str
17
+ status: str = "M"
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class SelectedCase:
22
+ path: Path
23
+ case_key: str
24
+ reasons: tuple[str, ...]
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class PluginSelection:
29
+ name: str | None
30
+ root: Path
31
+ cases: tuple[SelectedCase, ...]
32
+ warnings: tuple[str, ...] = ()
33
+ repeat: int | None = None
34
+ config: dict[str, Any] = field(default_factory=dict)
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class PrPlan:
39
+ base: str | None
40
+ head: str | None
41
+ changed_files: tuple[str, ...]
42
+ plugins: tuple[PluginSelection, ...]
43
+
44
+
45
+ def _normalize_status(raw: str) -> str:
46
+ if not raw:
47
+ return "M"
48
+ return raw[0].upper()
49
+
50
+
51
+ def parse_changed_file_lines(lines: Iterable[str]) -> tuple[ChangedFile, ...]:
52
+ changed: list[ChangedFile] = []
53
+ for line in lines:
54
+ stripped = line.strip()
55
+ if not stripped:
56
+ continue
57
+ parts = stripped.split("\t")
58
+ if len(parts) == 1:
59
+ changed.append(ChangedFile(path=parts[0], status="M"))
60
+ continue
61
+ status = _normalize_status(parts[0])
62
+ path = parts[-1] if status in {"R", "C"} else parts[1]
63
+ changed.append(ChangedFile(path=path, status=status))
64
+ return tuple(changed)
65
+
66
+
67
+ def git_diff_range(base: str, head: str = "HEAD") -> str:
68
+ return f"{base}...{head}"
69
+
70
+
71
+ def read_changed_files_from_git(base: str, head: str = "HEAD") -> tuple[ChangedFile, ...]:
72
+ result = subprocess.run(
73
+ ["git", "diff", "--name-status", git_diff_range(base, head)],
74
+ check=True,
75
+ text=True,
76
+ stdout=subprocess.PIPE,
77
+ stderr=subprocess.PIPE,
78
+ )
79
+ return parse_changed_file_lines(result.stdout.splitlines())
80
+
81
+
82
+ def _plugin_entries(
83
+ workspace: WorkspaceConfig,
84
+ ) -> tuple[tuple[str | None, Path, dict[str, Any]], ...]:
85
+ if not workspace.plugins:
86
+ return ((None, workspace.root.resolve(), {}),)
87
+ entries: list[tuple[str | None, Path, dict[str, Any]]] = []
88
+ for name, config in workspace.plugins.items():
89
+ path = config.get("path")
90
+ if not isinstance(path, str) or not path:
91
+ continue
92
+ entries.append((name, (workspace.root / path).resolve(), dict(config)))
93
+ return tuple(entries)
94
+
95
+
96
+ def _is_under(path: Path, root: Path) -> bool:
97
+ try:
98
+ path.resolve().relative_to(root.resolve())
99
+ except ValueError:
100
+ return False
101
+ return True
102
+
103
+
104
+ def _is_case_path(path: Path, plugin_root: Path) -> bool:
105
+ try:
106
+ rel = path.resolve().relative_to(plugin_root.resolve()).as_posix()
107
+ except ValueError:
108
+ return False
109
+ return (
110
+ rel.startswith("__evals__/cases/")
111
+ and (rel.endswith(".yaml") or rel.endswith(".yml"))
112
+ )
113
+
114
+
115
+ def _load_pr_config(plugin_root: Path) -> tuple[tuple[str, ...], int | None, tuple[str, ...]]:
116
+ path = plugin_root / "__evals__" / "config.yaml"
117
+ if not path.is_file():
118
+ return (), None, ()
119
+ raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
120
+ if not isinstance(raw, dict):
121
+ return (), None, (f"{path} root must be an object",)
122
+ pull_request = raw.get("pull_request", {})
123
+ if pull_request is None:
124
+ return (), None, ()
125
+ if not isinstance(pull_request, dict):
126
+ return (), None, (f"{path} pull_request must be an object",)
127
+ patterns = pull_request.get("cases", [])
128
+ warnings: list[str] = []
129
+ if not isinstance(patterns, list) or not all(isinstance(item, str) for item in patterns):
130
+ warnings.append(f"{path} pull_request.cases must be a list of strings")
131
+ patterns = []
132
+ repeat_raw = pull_request.get("repeat")
133
+ repeat = None
134
+ if repeat_raw is not None:
135
+ if isinstance(repeat_raw, bool) or not isinstance(repeat_raw, int) or repeat_raw < 1:
136
+ warnings.append(f"{path} pull_request.repeat must be a positive integer")
137
+ else:
138
+ repeat = repeat_raw
139
+ return tuple(patterns), repeat, tuple(warnings)
140
+
141
+
142
+ def _add_reason(selected: dict[Path, list[str]], path: Path, reason: str) -> None:
143
+ reasons = selected.setdefault(path.resolve(), [])
144
+ if reason not in reasons:
145
+ reasons.append(reason)
146
+
147
+
148
+ def _configured_cases(
149
+ plugin_root: Path,
150
+ patterns: Sequence[str],
151
+ ) -> tuple[tuple[Path, ...], tuple[str, ...]]:
152
+ evals_root = plugin_root / "__evals__"
153
+ paths: list[Path] = []
154
+ warnings: list[str] = []
155
+ for pattern in patterns:
156
+ matches = sorted(path.resolve() for path in evals_root.glob(pattern) if path.is_file())
157
+ if not matches:
158
+ warnings.append(f"pull_request.cases pattern {pattern!r} matched no cases")
159
+ paths.extend(matches)
160
+ return tuple(dict.fromkeys(paths)), tuple(warnings)
161
+
162
+
163
+ def build_pr_plan(
164
+ workspace: WorkspaceConfig,
165
+ changed_files: Sequence[ChangedFile],
166
+ *,
167
+ base: str | None = None,
168
+ head: str | None = None,
169
+ ) -> PrPlan:
170
+ changed_paths = tuple(item.path for item in changed_files)
171
+ plugins: list[PluginSelection] = []
172
+ for name, plugin_root, plugin_config in _plugin_entries(workspace):
173
+ selected: dict[Path, list[str]] = {}
174
+ affected = False
175
+ for item in changed_files:
176
+ absolute = (workspace.root / item.path).resolve()
177
+ if not _is_under(absolute, plugin_root):
178
+ continue
179
+ affected = True
180
+ if item.status == "D":
181
+ continue
182
+ if _is_case_path(absolute, plugin_root) and absolute.is_file():
183
+ _add_reason(selected, absolute, "changed_case")
184
+ if not affected:
185
+ continue
186
+ patterns, repeat, config_warnings = _load_pr_config(plugin_root)
187
+ configured, glob_warnings = _configured_cases(plugin_root, patterns)
188
+ for path in configured:
189
+ _add_reason(selected, path, "pull_request.config")
190
+ cases = tuple(
191
+ SelectedCase(
192
+ path=path,
193
+ case_key=case_key_for_path(path, plugin_root),
194
+ reasons=tuple(reasons),
195
+ )
196
+ for path, reasons in sorted(
197
+ selected.items(),
198
+ key=lambda item: case_key_for_path(item[0], plugin_root),
199
+ )
200
+ )
201
+ warnings = tuple(config_warnings) + tuple(glob_warnings)
202
+ if cases or warnings:
203
+ plugins.append(
204
+ PluginSelection(
205
+ name=name,
206
+ root=plugin_root,
207
+ cases=cases,
208
+ warnings=warnings,
209
+ repeat=repeat,
210
+ config=plugin_config,
211
+ )
212
+ )
213
+ return PrPlan(base=base, head=head, changed_files=changed_paths, plugins=tuple(plugins))
214
+
215
+
216
+ def apply_pr_repeat(case: ResolvedCase, repeat: int | None) -> ResolvedCase:
217
+ if repeat is None:
218
+ return case
219
+ execution = dict(case.execution)
220
+ execution["repeat"] = repeat
221
+ return replace(case, execution=execution)
222
+
223
+
224
+ def _relative(path: Path, root: Path) -> str:
225
+ try:
226
+ return path.resolve().relative_to(root.resolve()).as_posix()
227
+ except ValueError:
228
+ return str(path)
229
+
230
+
231
+ def pr_plan_to_dict(plan: PrPlan, workspace_root: Path) -> dict[str, Any]:
232
+ return {
233
+ "base": plan.base,
234
+ "head": plan.head,
235
+ "changed_files": list(plan.changed_files),
236
+ "plugins": [
237
+ {
238
+ "name": plugin.name,
239
+ "root": _relative(plugin.root, workspace_root),
240
+ "repeat": plugin.repeat,
241
+ "warnings": list(plugin.warnings),
242
+ "cases": [
243
+ {
244
+ "path": _relative(case.path, workspace_root),
245
+ "case_key": case.case_key,
246
+ "reasons": list(case.reasons),
247
+ }
248
+ for case in plugin.cases
249
+ ],
250
+ }
251
+ for plugin in plan.plugins
252
+ ],
253
+ }
254
+
255
+
256
+ def _result_status(result: Any) -> str:
257
+ status = getattr(result, "status", None)
258
+ if status in {"pass", "fail", "error"}:
259
+ return status
260
+ return "pass" if bool(getattr(result, "passed", False)) else "fail"
261
+
262
+
263
+ def _counts(results: Sequence[Any]) -> dict[str, int]:
264
+ counts = {"pass": 0, "fail": 0, "error": 0}
265
+ for result in results:
266
+ counts[_result_status(result)] += 1
267
+ return counts
268
+
269
+
270
+ def _entry_errors(entry: Mapping[str, Any]) -> list[dict[str, str]]:
271
+ errors = entry.get("errors", [])
272
+ if not isinstance(errors, list):
273
+ return []
274
+ normalized: list[dict[str, str]] = []
275
+ for error in errors:
276
+ if not isinstance(error, Mapping):
277
+ continue
278
+ normalized.append(
279
+ {
280
+ "phase": str(error.get("phase", "unknown")),
281
+ "message": str(error.get("message", "")),
282
+ }
283
+ )
284
+ return normalized
285
+
286
+
287
+ def _aggregate_status(counts: Mapping[str, int]) -> str:
288
+ if counts["fail"]:
289
+ return "fail"
290
+ if counts["error"]:
291
+ return "error"
292
+ return "pass"
293
+
294
+
295
+ def plugin_result_key(plugin: PluginSelection, workspace_root: Path) -> str:
296
+ return plugin.name if plugin.name is not None else _relative(plugin.root, workspace_root)
297
+
298
+
299
+ def pr_run_exit_status(plugin_results: Mapping[str, Mapping[str, Any]]) -> int:
300
+ has_fail = False
301
+ has_error = False
302
+ for entry in plugin_results.values():
303
+ counts = _counts(list(entry.get("results", [])))
304
+ has_fail = has_fail or bool(counts["fail"])
305
+ has_error = has_error or bool(counts["error"]) or bool(_entry_errors(entry))
306
+ if has_fail:
307
+ return 1
308
+ if has_error:
309
+ return 2
310
+ return 0
311
+
312
+
313
+ def pr_summary_to_dict(
314
+ plan: PrPlan,
315
+ *,
316
+ workspace_root: Path,
317
+ plugin_results: Mapping[str, Mapping[str, Any]],
318
+ ) -> dict[str, Any]:
319
+ payload = pr_plan_to_dict(plan, workspace_root)
320
+ plugins = []
321
+ for selection, plugin in zip(plan.plugins, payload["plugins"]):
322
+ key = plugin_result_key(selection, workspace_root)
323
+ result_entry = plugin_results.get(key, {})
324
+ results = list(result_entry.get("results", []))
325
+ errors = _entry_errors(result_entry)
326
+ counts = _counts(results)
327
+ if errors:
328
+ counts["error"] += len(errors)
329
+ plugin = dict(plugin)
330
+ plugin["status"] = _aggregate_status(counts) if results or errors else "skipped"
331
+ plugin["counts"] = counts
332
+ plugin["errors"] = errors
333
+ plugin["report_path"] = (
334
+ _relative(result_entry["report_path"], workspace_root)
335
+ if result_entry.get("report_path") is not None
336
+ else None
337
+ )
338
+ plugin["latest_report_path"] = (
339
+ _relative(result_entry["latest_report_path"], workspace_root)
340
+ if result_entry.get("latest_report_path") is not None
341
+ else None
342
+ )
343
+ plugin["runs_root"] = (
344
+ _relative(result_entry["runs_root"], workspace_root)
345
+ if result_entry.get("runs_root") is not None
346
+ else None
347
+ )
348
+ plugins.append(plugin)
349
+ payload["plugins"] = plugins
350
+ return payload
yama/thread_case.py CHANGED
@@ -179,8 +179,6 @@ def extract_skill_names(system_prompt_text: str | None) -> list[str]:
179
179
  def build_case_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
180
180
  result: list[dict[str, Any]] = []
181
181
  for message in messages:
182
- if message.get("role") == "system":
183
- continue
184
182
  resolved = deepcopy(message)
185
183
  if resolved.get("content") is None:
186
184
  resolved["content"] = ""
yama/tools/bash/bash.py CHANGED
@@ -279,7 +279,12 @@ class BashTool(Tool):
279
279
  raise ToolMockError("INVALID_COMMAND", "command must be a non-empty string")
280
280
  if "fs" in config:
281
281
  return await run_bash_fs(arguments, context, config["fs"])
282
- return await run_bash_cli(arguments, context, config.get("cli", {}))
282
+ return await run_bash_cli(
283
+ arguments,
284
+ context,
285
+ config.get("cli", {}),
286
+ backend=config.get("fs_backend"),
287
+ )
283
288
 
284
289
 
285
290
  run_bash = BashTool().run
yama/tools/bash/fs.py CHANGED
@@ -17,7 +17,7 @@ from ...models import sanitize_case_key
17
17
  _FS_FIELDS = {"cwd", "network", "backend", "files", "bin", "env", "limits"}
18
18
  _CONTENT_FIELDS = {"content", "file", "mode"}
19
19
  _LIMIT_FIELDS = {"cpu_seconds", "memory_mb", "max_processes", "timeout_seconds"}
20
- _BACKENDS = {"auto", "macos-sandbox-exec", "none"}
20
+ _BACKENDS = {"auto", "macos-sandbox-exec", "linux-bubblewrap", "none"}
21
21
  _ENV_ALLOWLIST = ("PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "USER", "SHELL")
22
22
  DEFAULT_TIMEOUT_SECONDS = 30.0
23
23
 
@@ -38,9 +38,15 @@ def _resolve_backend(requested: str) -> str:
38
38
  raise MockConfigurationError(
39
39
  "mocks.fs.backend: macos-sandbox-exec requires macOS"
40
40
  )
41
+ if requested == "linux-bubblewrap" and not sys.platform.startswith("linux"):
42
+ raise MockConfigurationError(
43
+ "mocks.fs.backend: linux-bubblewrap requires Linux"
44
+ )
41
45
  if requested == "auto":
42
46
  if sys.platform == "darwin":
43
47
  return "macos-sandbox-exec"
48
+ if sys.platform.startswith("linux"):
49
+ return "linux-bubblewrap"
44
50
  raise MockConfigurationError(
45
51
  "mocks.fs has no sandboxing backend on this platform; set "
46
52
  "mocks.fs.backend: none to run without OS-level isolation"
@@ -265,6 +271,42 @@ def build_macos_profile(workspace_dir: Path, *, network: bool) -> str:
265
271
  {network_rule}"""
266
272
 
267
273
 
274
+ def _bubblewrap_argv(
275
+ workspace_dir: Path,
276
+ *,
277
+ cwd: Path,
278
+ network: bool,
279
+ bash_path: str,
280
+ ) -> tuple[list[str], str]:
281
+ bwrap_path = shutil.which("bwrap") or shutil.which("bubblewrap")
282
+ if bwrap_path is None:
283
+ raise MockConfigurationError(
284
+ "mocks.fs.backend: linux-bubblewrap requires bubblewrap; install the bwrap package"
285
+ )
286
+ home = Path.home()
287
+ argv = [
288
+ "bwrap",
289
+ "--die-with-parent",
290
+ "--unshare-pid",
291
+ "--unshare-ipc",
292
+ # Keep host binaries/libraries readable enough for bash and Python
293
+ # shims, but do not leave the user's real HOME readable by default.
294
+ "--ro-bind", "/", "/",
295
+ "--tmpfs", str(home),
296
+ "--dev", "/dev",
297
+ "--proc", "/proc",
298
+ "--tmpfs", "/tmp",
299
+ "--bind", str(workspace_dir), str(workspace_dir),
300
+ "--chdir", str(cwd),
301
+ bash_path,
302
+ "--noprofile",
303
+ "--norc",
304
+ ]
305
+ if not network:
306
+ argv.insert(1, "--unshare-net")
307
+ return argv, bwrap_path
308
+
309
+
268
310
  def _make_preexec(limits: Mapping[str, float]):
269
311
  def _apply() -> None:
270
312
  os.setsid()
@@ -372,6 +414,16 @@ class ShellSession:
372
414
  ],
373
415
  sandbox_exec_path,
374
416
  )
417
+ if backend == "linux-bubblewrap":
418
+ cwd = self.workspace_dir
419
+ if self.fs_config["cwd"]:
420
+ cwd = cwd / self.fs_config["cwd"]
421
+ return _bubblewrap_argv(
422
+ self.workspace_dir,
423
+ cwd=cwd,
424
+ network=self.fs_config["network"],
425
+ bash_path=bash_path,
426
+ )
375
427
  return (["bash", "--noprofile", "--norc"], bash_path)
376
428
 
377
429
  async def start(self) -> None:
@@ -536,11 +588,16 @@ async def run_bash_cli(
536
588
  arguments: Mapping[str, Any],
537
589
  context: ToolMockContext | None,
538
590
  cli_config: Mapping[str, Any],
591
+ *,
592
+ backend: str | None = None,
539
593
  ) -> dict[str, Any]:
540
594
  if context is None:
541
595
  raise MockInvocationError("mocks.cli requires a ToolMockContext")
542
596
  command = arguments["command"]
543
597
  fs_config = compile_cli_config(cli_config)
598
+ if backend is not None:
599
+ fs_config = dict(fs_config)
600
+ fs_config["backend"] = backend
544
601
  session = await _get_session(context, fs_config)
545
602
  timeout = cli_config.get("passthrough_timeout_seconds", DEFAULT_TIMEOUT_SECONDS)
546
603
  return await session.run(command, timeout=_effective_timeout(arguments, timeout))