python-yama 0.3.0__py3-none-any.whl → 0.5.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.3.0
3
+ Version: 0.5.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
@@ -19,6 +19,7 @@ Requires-Dist: fastapi>=0.139.0
19
19
  Requires-Dist: jinja2>=3.1
20
20
  Requires-Dist: litellm<2.0,>=1.80
21
21
  Requires-Dist: orjson>=3.11.9
22
+ Requires-Dist: python-dotenv>=1.0
22
23
  Requires-Dist: pyyaml>=6.0
23
24
  Requires-Dist: rich<15.0,>=14.1
24
25
  Description-Content-Type: text/markdown
@@ -40,6 +41,8 @@ OPENAI_API_KEY=... uv run --project yama yama
40
41
  OPENAI_API_KEY=... uv run --project yama yama --plugin dingding-simple
41
42
  ```
42
43
 
44
+ Instead of prefixing every command, you can put credentials in a `.env` file: on startup the CLI loads the nearest `.env` found from the working directory upward (variables already set in the environment are not overridden).
45
+
43
46
  ## Writing a Case
44
47
 
45
48
  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):
@@ -75,7 +78,7 @@ outcome:
75
78
 
76
79
  - `description` (optional) is a one-line summary of what the Case tests; it is shown in the CLI output and the HTML report.
77
80
  - `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?)`.
81
+ - 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?)`.
79
82
  - To simulate command-line tools, declare `{builtin: bash}` and configure per-command output under `mocks.cli`.
80
83
  - `steps[].assert.hard` are deterministic checks (nine types, including `tool_called`, `tool_arguments`, and `assistant_contains`); add `assert.judge` for LLM scoring.
81
84
 
@@ -93,13 +96,25 @@ uv run --project yama yama --plugin dingding-simple --report
93
96
  | `--plugin-root PATH` | Use the given path as the single plugin root |
94
97
  | `--plugin NAME` (repeatable) | Select plugins by name from `yama.toml` |
95
98
  | `--all-plugins` | Run every plugin configured in `yama.toml` |
99
+ | `-k, --filter PATTERN` (repeatable) | Only run cases whose case key (path relative to the plugin root) matches — a substring, or an fnmatch glob when the pattern contains `*` `?` `[`; with several patterns a case runs if any matches |
96
100
  | `--result-dir PATH` | Override the artifact root (default `<plugin_root>/.yama/runs`) |
97
101
  | `--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`) |
102
+ | `--report [PATH]` | Also generate a single-file HTML report. Without PATH it writes a timestamped `.yama/reports/report-<ts>.html` (history accumulates) and keeps `.yama/reports/latest.html` as a symlink to the newest one; an explicit PATH writes exactly that file |
103
+ | `--preview` | Don't run anything (no LLM calls): resolve the collected Cases and write an HTML case preview (default `.yama/reports/preview.html`; `--report PATH` overrides), or print a JSON preview to stdout when combined with `--json` |
99
104
  | `--list` | Only print the collected Cases, without running them |
100
105
  | `--no-artifacts` | Write no artifact files at all |
101
106
  | `--json` | Emit machine-readable JSON instead of Rich tables |
102
107
 
103
108
  `--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
109
 
110
+ ### Dashboard
111
+
112
+ ```bash
113
+ uv run --project yama yama dashboard --plugin dingding-simple
114
+ ```
115
+
116
+ `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
+
118
+ ### Output
119
+
105
120
  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.
@@ -0,0 +1,29 @@
1
+ yama/__init__.py,sha256=UYhoZTSu1HiMT54LOZCdvLKMQ_L0qec8RT8jDfde_cY,1156
2
+ yama/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ yama/assertions.py,sha256=_PXx-yCTbTqVI-upyPFVxDu3EQC1aSoGtTP3A10q47k,21968
4
+ yama/cli.py,sha256=ZDMb1zbHQPp0LPb-K58aYA7vdU6iJYx13Pzb_8OnDLE,30698
5
+ yama/dashboard.py,sha256=0yxRh-j_5Mk6Ug_xgv9-VyBSEr1aVKxX-zJwxGfd_TU,11601
6
+ yama/llm.py,sha256=JzQ4YHhBLd1WE8W_ipTVcoNK6f-nSqRKDzqEl5kmuis,16085
7
+ yama/mocks.py,sha256=YyiU6Y7NgttxHYJBsqGPILKYlTsM4IMTIilMNRkUuzs,14973
8
+ yama/models.py,sha256=0BMCWku5zWDOESrFUibiJShlfEhOAGlVKaNxfPB-9OM,4020
9
+ yama/preview.py,sha256=gVTMqArXQqOLktGnactK9c0kfX6oHd6fWGjhkB7-QLQ,14220
10
+ yama/report.py,sha256=qZr94njFDSRA5MTLhb2wvw8PgmK1kWuO-cCb-Nv3G4I,56829
11
+ yama/runner.py,sha256=BEKXuHAnvizgMStWuPaudHr1omgGtbYqK2sgg9pUrcs,29319
12
+ yama/workspace.py,sha256=4GAe36Uj1-gjROMPwrQfTIg1TkzEIk9-gHEuezjbY_I,4614
13
+ yama/loaders/__init__.py,sha256=DIwfa8QlIlKt6NpFMZJ_OcqbJPPrmKLBzd9_e-BCuBs,174
14
+ yama/loaders/case.py,sha256=5uUpXm1t9EOmee2BZe7vDGXCrc4CSgcFGApSkuFe5tc,13954
15
+ yama/loaders/common.py,sha256=Fg71_vcnu5339QI_itvYPvRbk9LtBgEnzoA3t4Krb4U,754
16
+ yama/loaders/tool_loader.py,sha256=AaJwrFEjmfdUhKqXIlfl_jyvaKQ4ZoPPOpT8Wg5xuNU,12574
17
+ yama/tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ yama/tools/base.py,sha256=ONFuGzTSWVsA0k4-UUREncqAHmyQI2uHpVOU2Dh_XiQ,446
19
+ yama/tools/bash/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ yama/tools/bash/_cli_shim.py,sha256=f3Rom5UipW0dA0KRYavqIa9HJDKT336ssDZGWeVmkvo,2494
21
+ yama/tools/bash/bash.py,sha256=4GlFvmqTUS4k6DgJ5Io91YF5fB6wF6e3e7p2P-pmbEQ,10358
22
+ yama/tools/bash/fs.py,sha256=GChDwGe_Sgn73btZJDNp5nOwlVDhLfZyaMVqWSQwfOw,21859
23
+ yama/tools/skill/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ yama/tools/skill/skill.py,sha256=H2KdIBLkYhecYX7M2xbn79csDpDvougpRcAmlrwigEM,2235
25
+ python_yama-0.5.0.dist-info/METADATA,sha256=WYeLjsFPHKklsIUfLRRjZy3KQbJyxp_uQzrY8MiQA7U,7515
26
+ python_yama-0.5.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
27
+ python_yama-0.5.0.dist-info/entry_points.txt,sha256=N5se3y1FflUcDU3TmUrH2Tu9dzsrBBo7sUP-Gu_2cVs,39
28
+ python_yama-0.5.0.dist-info/licenses/LICENSE,sha256=cMAJJAs7R1lemJPPc7qMNv4w_sqn5QncFf4aXKYyEc4,1067
29
+ python_yama-0.5.0.dist-info/RECORD,,
yama/assertions.py CHANGED
@@ -574,4 +574,8 @@ async def run_judge(
574
574
  passed = False
575
575
  judged["overall"] = weighted / total_weight
576
576
  judged["passed"] = passed
577
+ if response.usage is not None:
578
+ # Judge calls bypass the runner's per-request records, so their
579
+ # token usage rides on the judge result to reach run aggregation.
580
+ judged["usage"] = deepcopy(response.usage)
577
581
  return judged
yama/cli.py CHANGED
@@ -8,6 +8,7 @@ from io import StringIO
8
8
  from pathlib import Path
9
9
  from typing import Any
10
10
 
11
+ from dotenv import find_dotenv, load_dotenv
11
12
  from rich import box
12
13
  from rich.console import Console, Group
13
14
  from rich.live import Live
@@ -24,10 +25,12 @@ from .workspace import (
24
25
  load_workspace_config,
25
26
  resolve_plugin_root,
26
27
  )
28
+ from .dashboard import create_dashboard_server
27
29
  from .llm import LLMError, LiteLLMClient
28
30
  from .loaders import CollectionError, resolve_case
29
- from .report import write_html_report
30
- from .runner import YamaRunner
31
+ from .preview import preview_payload, write_preview_html
32
+ from .report import write_html_report, write_timestamped_report
33
+ from .runner import YamaRunner, combine_usage
31
34
 
32
35
  DEFAULT_REPORT = Path("__yama_default_report__")
33
36
 
@@ -38,6 +41,20 @@ def _status(passed: bool, *, compact: bool = False) -> Text:
38
41
  return Text("✗" if compact else "FAIL", style="bold red")
39
42
 
40
43
 
44
+ def _usage_label(usage: dict[str, int] | None, *, split: bool = False) -> str:
45
+ """`tokens 12,345`-style suffix for labels and captions; empty when no
46
+ LLM call reported usage (scripted replays, runs that died early)."""
47
+ if not usage:
48
+ return ""
49
+ label = f"tokens {usage['total_tokens']:,}"
50
+ if split:
51
+ label += (
52
+ f" (in {usage['prompt_tokens']:,}"
53
+ f" / out {usage['completion_tokens']:,})"
54
+ )
55
+ return label
56
+
57
+
41
58
  def _summary_case_key(case_key: str) -> str:
42
59
  prefix = "__evals__/cases/"
43
60
  return case_key.removeprefix(prefix)
@@ -128,17 +145,24 @@ def build_case_tree(result: Any) -> Tree:
128
145
  (result.case_key, "bold"),
129
146
  (f" {result.pass_rate:.0%}", "dim"),
130
147
  )
148
+ case_usage = result.usage()
149
+ if case_usage:
150
+ case_label.append(f" {_usage_label(case_usage, split=True)}", style="dim")
131
151
  if result.description:
132
152
  case_label.append(f"\n{result.description}", style="dim")
133
153
  tree = Tree(case_label, guide_style="dim")
134
154
  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
- )
155
+ run_label = Text.assemble(
156
+ _status(run.passed, compact=True),
157
+ " ",
158
+ (f"Run {run.run_index}", "bold"),
141
159
  )
160
+ if getattr(run, "label", None):
161
+ run_label.append(f" · {run.label}", style="cyan")
162
+ run_usage = run.usage()
163
+ if run_usage:
164
+ run_label.append(f" {_usage_label(run_usage)}", style="dim")
165
+ run_node = tree.add(run_label)
142
166
  if run.error:
143
167
  run_node.add(Text.assemble(("Error: ", "bold red"), (run.error, "red")))
144
168
  run_node.children.extend(build_step_tree(step) for step in run.steps)
@@ -157,6 +181,7 @@ def build_summary_table(results: list[Any]) -> Table:
157
181
  table.add_column("Case", ratio=1, overflow="fold")
158
182
  table.add_column("Runs", justify="right", no_wrap=True)
159
183
  table.add_column("Pass rate", justify="right", no_wrap=True)
184
+ table.add_column("Tokens", justify="right", no_wrap=True)
160
185
 
161
186
  passed_runs = 0
162
187
  total_runs = 0
@@ -167,11 +192,13 @@ def build_summary_table(results: list[Any]) -> Table:
167
192
  case_cell = Text(_summary_case_key(result.case_key))
168
193
  if result.description:
169
194
  case_cell.append(f"\n{result.description}", style="dim")
195
+ usage = result.usage()
170
196
  table.add_row(
171
197
  _status(result.passed),
172
198
  case_cell,
173
199
  f"{case_passed_runs}/{len(result.runs)}",
174
200
  f"{result.pass_rate:.0%}",
201
+ f"{usage['total_tokens']:,}" if usage else "–",
175
202
  )
176
203
 
177
204
  passed_cases = sum(result.passed for result in results)
@@ -179,6 +206,9 @@ def build_summary_table(results: list[Any]) -> Table:
179
206
  f"{passed_cases}/{len(results)} cases passed • "
180
207
  f"{passed_runs}/{total_runs} runs passed"
181
208
  )
209
+ total_usage = combine_usage(result.usage() for result in results)
210
+ if total_usage:
211
+ table.caption += f" • {_usage_label(total_usage, split=True)}"
182
212
  table.caption_style = "green" if passed_cases == len(results) else "red"
183
213
  return table
184
214
 
@@ -241,15 +271,13 @@ class ProgressPrinter:
241
271
  Padding(Text(payload["description"], style="dim"), (0, 0, 0, 2))
242
272
  )
243
273
  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
- )
274
+ run_line = Text(
275
+ f"Run {payload['run_index']}/{payload['repeat']}",
276
+ style="bold",
252
277
  )
278
+ if payload.get("label"):
279
+ run_line.append(f" · {payload['label']}", style="cyan")
280
+ self.console.print(Padding(run_line, (0, 0, 0, 2)))
253
281
  elif event == "step_end":
254
282
  self.console.print(Padding(build_step_tree(payload["step"]), (0, 0, 0, 4)))
255
283
  elif event == "run_end":
@@ -264,16 +292,19 @@ class ProgressPrinter:
264
292
  elif event == "case_end":
265
293
  result = payload["result"]
266
294
  passed_runs = sum(run.passed for run in result.runs)
295
+ meta = (
296
+ f" {passed_runs}/{len(result.runs)} runs passed"
297
+ f" {result.pass_rate:.0%}"
298
+ )
299
+ usage = result.usage()
300
+ if usage:
301
+ meta += f" {_usage_label(usage)}"
267
302
  self.console.print(
268
303
  Text.assemble(
269
304
  _status(result.passed, compact=True),
270
305
  " ",
271
306
  (result.case_key, "bold"),
272
- (
273
- f" {passed_runs}/{len(result.runs)} runs passed"
274
- f" {result.pass_rate:.0%}",
275
- "dim",
276
- ),
307
+ (meta, "dim"),
277
308
  )
278
309
  )
279
310
  self.console.print()
@@ -357,6 +388,8 @@ class ParallelProgressPrinter:
357
388
  progress = ""
358
389
  if row.get("run_index"):
359
390
  progress = f" Run {row['run_index']}/{row['repeat']}"
391
+ if row.get("label"):
392
+ progress += f" · {row['label']}"
360
393
  if row.get("step_id"):
361
394
  progress += f" · {row['step_id']}"
362
395
  grid.add_row(
@@ -366,16 +399,16 @@ class ParallelProgressPrinter:
366
399
  else:
367
400
  result = row["result"]
368
401
  passed_runs = sum(run.passed for run in result.runs)
402
+ meta = (
403
+ f" {passed_runs}/{len(result.runs)} runs"
404
+ f" {result.pass_rate:.0%}"
405
+ )
406
+ usage = result.usage()
407
+ if usage:
408
+ meta += f" {_usage_label(usage)}"
369
409
  grid.add_row(
370
410
  _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
- ),
411
+ Text.assemble((case_key, "bold"), (meta, "dim")),
379
412
  )
380
413
  return grid
381
414
 
@@ -406,6 +439,7 @@ class ParallelProgressPrinter:
406
439
  if event == "run_start":
407
440
  row["run_index"] = payload["run_index"]
408
441
  row["repeat"] = payload["repeat"]
442
+ row["label"] = payload.get("label")
409
443
  row["step_id"] = None
410
444
  else:
411
445
  row["step_id"] = payload["step_id"]
@@ -445,7 +479,12 @@ def _positive_int(value: str) -> int:
445
479
 
446
480
  def _parser() -> argparse.ArgumentParser:
447
481
  parser = argparse.ArgumentParser(
448
- prog="yama", description="Run Agent Skill eval cases"
482
+ prog="yama",
483
+ description="Run Agent Skill eval cases",
484
+ epilog=(
485
+ "Subcommand: `yama dashboard` serves historical reports and a"
486
+ " live case preview over HTTP (see `yama dashboard --help`)."
487
+ ),
449
488
  )
450
489
  parser.add_argument("paths", nargs="*", type=Path, help="Explicit YAML case paths")
451
490
  parser.add_argument(
@@ -457,6 +496,18 @@ def _parser() -> argparse.ArgumentParser:
457
496
  parser.add_argument(
458
497
  "--all-plugins", action="store_true", help="Run all configured plugins"
459
498
  )
499
+ parser.add_argument(
500
+ "-k",
501
+ "--filter",
502
+ action="append",
503
+ dest="filters",
504
+ metavar="PATTERN",
505
+ help=(
506
+ "Only run cases whose case key (path relative to the plugin root)"
507
+ " matches PATTERN -- a substring, or an fnmatch glob when it"
508
+ " contains * ? [. Repeatable; a case runs if any pattern matches."
509
+ ),
510
+ )
460
511
  parser.add_argument("--result-dir", type=Path, help="Override artifact directory")
461
512
  parser.add_argument(
462
513
  "--concurrency",
@@ -475,8 +526,20 @@ def _parser() -> argparse.ArgumentParser:
475
526
  const=DEFAULT_REPORT,
476
527
  metavar="PATH",
477
528
  help=(
478
- "Write a standalone HTML execution report"
479
- " (default: reports/latest.html beside the artifact runs directory)"
529
+ "Write a standalone HTML execution report (default: a timestamped"
530
+ " report-<ts>.html under reports/ beside the artifact runs"
531
+ " directory, with latest.html as a symlink to it)"
532
+ ),
533
+ )
534
+ parser.add_argument(
535
+ "--preview",
536
+ action="store_true",
537
+ help=(
538
+ "Do not run anything; resolve the collected cases and emit a"
539
+ " case preview instead -- an HTML page styled like the report"
540
+ " (default: reports/preview.html beside the artifact runs"
541
+ " directory; --report PATH overrides the target), or JSON on"
542
+ " stdout when combined with --json"
480
543
  ),
481
544
  )
482
545
  parser.add_argument(
@@ -489,7 +552,12 @@ def _parser() -> argparse.ArgumentParser:
489
552
  return parser
490
553
 
491
554
 
492
- async def _run(args: argparse.Namespace) -> int:
555
+ def _resolve_targets(
556
+ args: argparse.Namespace,
557
+ ) -> tuple[Any, list[tuple[str | None, Path, dict[str, Any]]]]:
558
+ """Expand the plugin-selection flags (--plugin-root / --plugin /
559
+ --all-plugins / cwd fallback) into concrete plugin roots. Shared by the
560
+ run command and the dashboard."""
493
561
  workspace = load_workspace_config(Path.cwd())
494
562
  targets: list[tuple[str | None, Path, dict[str, Any]]] = []
495
563
  if args.plugin_root:
@@ -510,25 +578,71 @@ async def _run(args: argparse.Namespace) -> int:
510
578
  else:
511
579
  root, plugin_config = resolve_plugin_root(workspace)
512
580
  targets.append((None, root, plugin_config))
581
+ return workspace, targets
513
582
 
583
+
584
+ def _collect_cases(args: argparse.Namespace) -> tuple[Any, list[Any]]:
585
+ """Re-resolve everything the CLI selection addresses, from scratch --
586
+ the dashboard calls this per /preview request so edits to yama.toml and
587
+ the case files are picked up without a restart."""
588
+ workspace, targets = _resolve_targets(args)
514
589
  collected = []
515
590
  for _, plugin_root, plugin_config in targets:
516
591
  paths = collect_case_paths(
517
592
  plugin_root,
518
593
  workspace,
519
594
  plugin_config,
520
- explicit_paths=args.paths or None,
595
+ explicit_paths=getattr(args, "paths", None) or None,
596
+ filters=args.filters,
521
597
  )
522
598
  for path in paths:
523
599
  collected.append(resolve_case(path, plugin_root, workspace, plugin_config))
600
+ return workspace, collected
601
+
602
+
603
+ async def _run(args: argparse.Namespace) -> int:
604
+ workspace, collected = _collect_cases(args)
524
605
  if args.list:
525
606
  for case in collected:
526
607
  print(case.case_key)
527
608
  return 0
528
609
  if not collected:
529
- Console(stderr=True).print("[bold red]No eval cases collected.[/bold red]")
610
+ message = (
611
+ "No eval cases matched the case filter."
612
+ if args.filters
613
+ else "No eval cases collected."
614
+ )
615
+ Console(stderr=True).print(f"[bold red]{message}[/bold red]")
530
616
  return 2
531
617
 
618
+ result_roots = [
619
+ args.result_dir.resolve()
620
+ if args.result_dir
621
+ else case.plugin_root / workspace.result_dir
622
+ for case in collected
623
+ ]
624
+ if args.preview:
625
+ if args.json:
626
+ print(
627
+ json.dumps(
628
+ [preview_payload(case) for case in collected],
629
+ ensure_ascii=False,
630
+ indent=2,
631
+ )
632
+ )
633
+ return 0
634
+ target = args.report
635
+ if target is None or target == DEFAULT_REPORT:
636
+ target = result_roots[0].parent / "reports" / "preview.html"
637
+ preview_path = write_preview_html(collected, target)
638
+ Console().print(
639
+ Text.assemble(
640
+ ("Case preview: ", "bold"),
641
+ (str(preview_path), f"cyan link {preview_path.as_uri()}"),
642
+ )
643
+ )
644
+ return 0
645
+
532
646
  # With --json, stdout must stay valid JSON, so live progress moves to
533
647
  # stderr instead of disappearing.
534
648
  progress_console = Console(stderr=args.json)
@@ -538,12 +652,6 @@ async def _run(args: argparse.Namespace) -> int:
538
652
  if parallel
539
653
  else ProgressPrinter(progress_console, total_cases=len(collected))
540
654
  )
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
655
  semaphore = asyncio.Semaphore(args.concurrency)
548
656
 
549
657
  async def run_one(case: Any, result_root: Path) -> Any:
@@ -577,12 +685,17 @@ async def _run(args: argparse.Namespace) -> int:
577
685
  all_results = list(outcomes)
578
686
  report_target = args.report
579
687
  if report_target == DEFAULT_REPORT:
580
- report_target = result_roots[0].parent / "reports" / "latest.html"
581
- report_path = (
582
- write_html_report(collected, all_results, report_target)
583
- if report_target
584
- else None
585
- )
688
+ # Default reports accumulate as history: a timestamped file per
689
+ # execution, with latest.html left as a symlink to the newest one
690
+ # (the dashboard's index lists that history). An explicit --report
691
+ # PATH still writes exactly the requested file.
692
+ report_path = write_timestamped_report(
693
+ collected, all_results, result_roots[0].parent / "reports"
694
+ )
695
+ elif report_target:
696
+ report_path = write_html_report(collected, all_results, report_target)
697
+ else:
698
+ report_path = None
586
699
  if args.json:
587
700
  print(
588
701
  json.dumps(
@@ -605,9 +718,92 @@ async def _run(args: argparse.Namespace) -> int:
605
718
  return 0 if all(result.passed for result in all_results) else 1
606
719
 
607
720
 
721
+ def _dashboard_parser() -> argparse.ArgumentParser:
722
+ parser = argparse.ArgumentParser(
723
+ prog="yama dashboard",
724
+ description=(
725
+ "Serve a local dashboard over HTTP: the index lists the"
726
+ " historical HTML reports (written by `yama --report`), and"
727
+ " /preview renders a live case preview that re-resolves the"
728
+ " case files on every refresh -- no LLM calls are made."
729
+ ),
730
+ )
731
+ parser.add_argument(
732
+ "--plugin-root", type=Path, help="Serve a single plugin by root path"
733
+ )
734
+ parser.add_argument(
735
+ "--plugin", action="append", help="Plugin name from yama.toml"
736
+ )
737
+ parser.add_argument(
738
+ "--all-plugins", action="store_true", help="Preview all configured plugins"
739
+ )
740
+ parser.add_argument(
741
+ "-k",
742
+ "--filter",
743
+ action="append",
744
+ dest="filters",
745
+ metavar="PATTERN",
746
+ help="Only include matching cases in the preview page",
747
+ )
748
+ parser.add_argument(
749
+ "--result-dir",
750
+ type=Path,
751
+ help=(
752
+ "Override the artifact directory; reports are served from the"
753
+ " reports/ directory beside it"
754
+ ),
755
+ )
756
+ parser.add_argument(
757
+ "--host", default="127.0.0.1", help="Bind address (default: 127.0.0.1)"
758
+ )
759
+ parser.add_argument(
760
+ "--port",
761
+ type=int,
762
+ default=8765,
763
+ help="Port to listen on (default: 8765; 0 picks a free port)",
764
+ )
765
+ return parser
766
+
767
+
768
+ def _run_dashboard(args: argparse.Namespace) -> int:
769
+ workspace, targets = _resolve_targets(args)
770
+ result_root = (
771
+ args.result_dir.resolve()
772
+ if args.result_dir
773
+ else targets[0][1] / workspace.result_dir
774
+ )
775
+ reports_dir = result_root.parent / "reports"
776
+ server = create_dashboard_server(
777
+ host=args.host,
778
+ port=args.port,
779
+ reports_dir=reports_dir,
780
+ collect_cases=lambda: _collect_cases(args)[1],
781
+ )
782
+ host, port = server.server_address[0], server.server_address[1]
783
+ url = f"http://{host}:{port}/"
784
+ console = Console()
785
+ console.print(
786
+ Text.assemble(("Yama dashboard: ", "bold"), (url, f"cyan link {url}"))
787
+ )
788
+ console.print(Text(f"Reports directory: {reports_dir}", style="dim"))
789
+ console.print(Text("Press Ctrl+C to stop.", style="dim"))
790
+ try:
791
+ server.serve_forever()
792
+ finally:
793
+ server.server_close()
794
+ return 0
795
+
796
+
608
797
  def main(argv: list[str] | None = None) -> int:
609
- args = _parser().parse_args(argv)
798
+ # .env is resolved from the working directory upward (like yama.toml);
799
+ # variables already present in the real environment take precedence.
800
+ load_dotenv(find_dotenv(usecwd=True))
801
+ if argv is None:
802
+ argv = sys.argv[1:]
610
803
  try:
804
+ if argv[:1] == ["dashboard"]:
805
+ return _run_dashboard(_dashboard_parser().parse_args(argv[1:]))
806
+ args = _parser().parse_args(argv)
611
807
  return asyncio.run(_run(args))
612
808
  except (ConfigurationError, CollectionError, ValueError) as exc:
613
809
  Console(stderr=True).print(