python-yama 0.8.0__py3-none-any.whl → 0.9.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.8.0
3
+ Version: 0.9.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
@@ -103,6 +103,7 @@ uv run --project yama yama --plugin dingding-simple --report
103
103
  | `--list` | Only print the collected Cases, without running them |
104
104
  | `--no-artifacts` | Write no artifact files at all |
105
105
  | `--json` | Emit machine-readable JSON instead of Rich tables |
106
+ | `pr-run --upload-report --commit-id SHA` | With `--report`, upload the push report and merge/upload affected Plugin latest reports; requires `ADMIN_HOST` and `YAMA_EVAL_REPORT_API_TOKEN` |
106
107
 
107
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.
108
109
 
@@ -123,6 +124,12 @@ OPENAI_API_KEY=... uv run --project yama yama pr-run --base origin/main --report
123
124
 
124
125
  `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
126
 
127
+ For CI environments that publish reports to the Yama Eval Report service, add
128
+ `--upload-report --commit-id <sha>` together with `--report`. The command reads
129
+ `ADMIN_HOST` and `YAMA_EVAL_REPORT_API_TOKEN` from the environment, uploads the
130
+ current commit report, then updates each affected Plugin latest report by merging
131
+ the just-run cases into the previous remote Plugin report.
132
+
126
133
  ### Output
127
134
 
128
135
  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,14 +1,16 @@
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=GDhKWyPFvZLJ8lyxl0ZAsRE6zWyaXiWfpw6Lxth1emI,45116
4
+ yama/cli.py,sha256=kCpMWY_USb4C6qKwAmfWUmDzVlXxSw526EU6yAJeo3c,47320
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
+ yama/pr.py,sha256=ao27i5T5V0I16FFN3A7tX0dGvctc8Zqj2YhufX7isdI,11762
10
10
  yama/preview.py,sha256=gVTMqArXQqOLktGnactK9c0kfX6oHd6fWGjhkB7-QLQ,14220
11
- yama/report.py,sha256=WVY4EWInVQbE-Pv2LFHcH-QMoPFpdOd5unDs4uGEq-w,64557
11
+ yama/report.py,sha256=gzVGkfkhms5ABMvaHXYBAibyrVQFs-7jf_fUZeeE0ro,74587
12
+ yama/report_bundle.py,sha256=Y6ZaBTieSvnokq6s447uhbv7cxvlNr3kpX4WPp7a7bk,7477
13
+ yama/report_upload.py,sha256=GLmUJPHJNH7g5IhvaznJbnEYJAfccUSuOAMrM-WH7Ec,10840
12
14
  yama/runner.py,sha256=e3vIBgYBAbhRzG7aUTb9YKw5HJlEUWdpASIDwav1RGQ,38942
13
15
  yama/thread_case.py,sha256=WZzF4va44aRUkJ4DxP3m9F1A219AhwKQHG5fi9-tPqQ,13106
14
16
  yama/workspace.py,sha256=4GAe36Uj1-gjROMPwrQfTIg1TkzEIk9-gHEuezjbY_I,4614
@@ -24,8 +26,8 @@ yama/tools/bash/bash.py,sha256=dGKi2EvftnLs3CrJlbo4IYm6aicWrEnFzrXoH0vYqGw,10451
24
26
  yama/tools/bash/fs.py,sha256=gPsdiTomnURzv1mTq6qWDlCg9IZNU_r-sYYk3S3NODQ,23706
25
27
  yama/tools/skill/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
26
28
  yama/tools/skill/skill.py,sha256=H2KdIBLkYhecYX7M2xbn79csDpDvougpRcAmlrwigEM,2235
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,,
29
+ python_yama-0.9.0.dist-info/METADATA,sha256=cZL5fYN1qMwjmHW_WxHCZmfodoDSSmGGj682e6840m8,8919
30
+ python_yama-0.9.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
31
+ python_yama-0.9.0.dist-info/entry_points.txt,sha256=N5se3y1FflUcDU3TmUrH2Tu9dzsrBBo7sUP-Gu_2cVs,39
32
+ python_yama-0.9.0.dist-info/licenses/LICENSE,sha256=cMAJJAs7R1lemJPPc7qMNv4w_sqn5QncFf4aXKYyEc4,1067
33
+ python_yama-0.9.0.dist-info/RECORD,,
yama/cli.py CHANGED
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
  import argparse
4
4
  import asyncio
5
5
  import json
6
+ import os
6
7
  import sys
7
8
  from io import StringIO
8
9
  from pathlib import Path
@@ -40,6 +41,8 @@ from .pr import (
40
41
  read_changed_files_from_git,
41
42
  )
42
43
  from .report import write_html_report, write_timestamped_report
44
+ from .report_bundle import validate_commit_id
45
+ from .report_upload import upload_pr_reports
43
46
  from .runner import YamaRunner, combine_usage
44
47
  from .thread_case import (
45
48
  ThreadCaseError,
@@ -868,6 +871,13 @@ def _changed_files_for_args(args: argparse.Namespace) -> Any:
868
871
  return read_changed_files_from_git(args.base, args.head)
869
872
 
870
873
 
874
+ def _relative_path(path: Path, root: Path) -> str:
875
+ try:
876
+ return path.resolve().relative_to(root.resolve()).as_posix()
877
+ except ValueError:
878
+ return str(path)
879
+
880
+
871
881
  def _run_pr_plan(args: argparse.Namespace) -> int:
872
882
  workspace = load_workspace_config(Path.cwd())
873
883
  changed_files = _changed_files_for_args(args)
@@ -905,14 +915,36 @@ def _pr_run_parser() -> argparse.ArgumentParser:
905
915
  )
906
916
  parser.add_argument("--changed-files", type=Path)
907
917
  parser.add_argument("--report", action="store_true")
918
+ parser.add_argument("--upload-report", action="store_true")
919
+ parser.add_argument("--commit-id")
908
920
  parser.add_argument("--json-summary", type=Path, required=True)
909
921
  parser.add_argument("--concurrency", type=_positive_int, default=10)
910
922
  parser.add_argument("--no-artifacts", action="store_true")
911
923
  return parser
912
924
 
913
925
 
926
+ def _validate_pr_upload_args(args: argparse.Namespace) -> tuple[str, str, str] | None:
927
+ if not args.upload_report:
928
+ return None
929
+ if not args.report:
930
+ raise ConfigurationError("--upload-report requires --report")
931
+ if not args.commit_id:
932
+ raise ConfigurationError("--upload-report requires --commit-id")
933
+ commit_id = validate_commit_id(args.commit_id)
934
+ admin_host = os.environ.get("ADMIN_HOST")
935
+ token = os.environ.get("YAMA_EVAL_REPORT_API_TOKEN")
936
+ if not admin_host:
937
+ raise ConfigurationError("ADMIN_HOST is required when --upload-report is set")
938
+ if not token:
939
+ raise ConfigurationError(
940
+ "YAMA_EVAL_REPORT_API_TOKEN is required when --upload-report is set"
941
+ )
942
+ return commit_id, admin_host, token
943
+
944
+
914
945
  async def _run_pr_run(args: argparse.Namespace) -> int:
915
946
  workspace = load_workspace_config(Path.cwd())
947
+ upload_config = _validate_pr_upload_args(args)
916
948
  changed_files = _changed_files_for_args(args)
917
949
  plan = build_pr_plan(workspace, changed_files, base=args.base, head=args.head)
918
950
  if not any(plugin.cases for plugin in plan.plugins):
@@ -926,6 +958,7 @@ async def _run_pr_run(args: argparse.Namespace) -> int:
926
958
  return 0
927
959
 
928
960
  plugin_results: dict[str, dict[str, Any]] = {}
961
+ plugin_cases: dict[str, list[Any]] = {}
929
962
  for plugin in plan.plugins:
930
963
  if not plugin.cases:
931
964
  continue
@@ -945,6 +978,7 @@ async def _run_pr_run(args: argparse.Namespace) -> int:
945
978
  )
946
979
  for selected in plugin.cases
947
980
  ]
981
+ plugin_cases[plugin_key] = cases
948
982
  except (ConfigurationError, CollectionError, ValueError) as exc:
949
983
  plugin_results[plugin_key] = {
950
984
  "results": [],
@@ -1001,19 +1035,42 @@ async def _run_pr_run(args: argparse.Namespace) -> int:
1001
1035
  if report_path
1002
1036
  else None,
1003
1037
  "runs_root": result_root,
1038
+ "plugin_root": _relative_path(plugin.root, workspace.root),
1004
1039
  }
1005
1040
 
1041
+ remote_push_report_url = None
1042
+ upload_errors: list[str] = []
1043
+ if upload_config is not None and any(
1044
+ entry.get("report_path") for entry in plugin_results.values()
1045
+ ):
1046
+ commit_id, admin_host, token = upload_config
1047
+ upload_payload = upload_pr_reports(
1048
+ workspace_root=workspace.root,
1049
+ commit_id=commit_id,
1050
+ admin_host=admin_host,
1051
+ token=token,
1052
+ plugin_results=plugin_results,
1053
+ plugin_cases=plugin_cases,
1054
+ )
1055
+ remote_push_report_url = upload_payload.get("remote_push_report_url")
1056
+ upload_errors = list(upload_payload.get("upload_errors", []))
1057
+
1006
1058
  payload = pr_summary_to_dict(
1007
1059
  plan,
1008
1060
  workspace_root=workspace.root,
1009
1061
  plugin_results=plugin_results,
1062
+ remote_push_report_url=remote_push_report_url,
1063
+ upload_errors=upload_errors,
1010
1064
  )
1011
1065
  args.json_summary.parent.mkdir(parents=True, exist_ok=True)
1012
1066
  args.json_summary.write_text(
1013
1067
  json.dumps(payload, ensure_ascii=False, indent=2),
1014
1068
  encoding="utf-8",
1015
1069
  )
1016
- return pr_run_exit_status(plugin_results)
1070
+ status = pr_run_exit_status(plugin_results)
1071
+ if status == 0 and upload_errors:
1072
+ return 2
1073
+ return status
1017
1074
 
1018
1075
 
1019
1076
  def _dashboard_parser() -> argparse.ArgumentParser:
yama/pr.py CHANGED
@@ -302,7 +302,12 @@ def pr_run_exit_status(plugin_results: Mapping[str, Mapping[str, Any]]) -> int:
302
302
  for entry in plugin_results.values():
303
303
  counts = _counts(list(entry.get("results", [])))
304
304
  has_fail = has_fail or bool(counts["fail"])
305
- has_error = has_error or bool(counts["error"]) or bool(_entry_errors(entry))
305
+ has_error = (
306
+ has_error
307
+ or bool(counts["error"])
308
+ or bool(_entry_errors(entry))
309
+ or bool(entry.get("upload_error"))
310
+ )
306
311
  if has_fail:
307
312
  return 1
308
313
  if has_error:
@@ -315,8 +320,12 @@ def pr_summary_to_dict(
315
320
  *,
316
321
  workspace_root: Path,
317
322
  plugin_results: Mapping[str, Mapping[str, Any]],
323
+ remote_push_report_url: str | None = None,
324
+ upload_errors: Sequence[str] = (),
318
325
  ) -> dict[str, Any]:
319
326
  payload = pr_plan_to_dict(plan, workspace_root)
327
+ payload["remote_push_report_url"] = remote_push_report_url
328
+ payload["upload_errors"] = list(upload_errors)
320
329
  plugins = []
321
330
  for selection, plugin in zip(plan.plugins, payload["plugins"]):
322
331
  key = plugin_result_key(selection, workspace_root)
@@ -345,6 +354,8 @@ def pr_summary_to_dict(
345
354
  if result_entry.get("runs_root") is not None
346
355
  else None
347
356
  )
357
+ plugin["remote_report_url"] = result_entry.get("remote_report_url")
358
+ plugin["upload_error"] = result_entry.get("upload_error")
348
359
  plugins.append(plugin)
349
360
  payload["plugins"] = plugins
350
361
  return payload
yama/report.py CHANGED
@@ -6,10 +6,12 @@ import shutil
6
6
  from datetime import datetime, timezone
7
7
  from html import escape
8
8
  from pathlib import Path
9
+ from types import SimpleNamespace
9
10
  from typing import Any, Sequence
10
11
 
11
12
  from .assertions import HARD_ASSERTION_TAG_THRESHOLDS
12
13
  from .models import ResolvedCase, StepResult
14
+ from .report_bundle import embed_json_for_html_script
13
15
  from .runner import (
14
16
  CaseResult,
15
17
  ResultStatus,
@@ -1045,7 +1047,145 @@ def _render_planned_runs(case: ResolvedCase) -> str:
1045
1047
  return _fold("<span>Planned runs</span>", plan_html + config_html, meta=meta)
1046
1048
 
1047
1049
 
1048
- def _render_case(case: ResolvedCase, result: CaseResult) -> str:
1050
+ def _object_from_dict(value: dict[str, Any]) -> Any:
1051
+ return SimpleNamespace(**value)
1052
+
1053
+
1054
+ def _tool_call_from_dict(value: dict[str, Any]) -> Any:
1055
+ data = dict(value)
1056
+ call = data.get("call")
1057
+ if isinstance(call, dict):
1058
+ data["call"] = _object_from_dict(call)
1059
+ return _object_from_dict(data)
1060
+
1061
+
1062
+ def _step_from_dict(value: dict[str, Any]) -> Any:
1063
+ data = {
1064
+ "step_id": value.get("step_id", ""),
1065
+ "user_message": value.get("user_message", {}),
1066
+ "assistant_message": value.get("assistant_message", {}),
1067
+ "tool_calls": [
1068
+ _tool_call_from_dict(record)
1069
+ for record in value.get("tool_calls", [])
1070
+ if isinstance(record, dict)
1071
+ ],
1072
+ "messages": value.get("messages", []),
1073
+ "hard_checks": value.get("hard_checks", []),
1074
+ "hard_pass": value.get("hard_pass", True),
1075
+ "tag_summary": value.get("tag_summary", {}),
1076
+ "judge_result": value.get("judge_result"),
1077
+ }
1078
+ return _object_from_dict(data)
1079
+
1080
+
1081
+ def _run_from_dict(value: dict[str, Any]) -> Any:
1082
+ usage_value = value.get("usage")
1083
+ duration_value = value.get("request_duration_ms")
1084
+ data = {
1085
+ "run_index": value.get("run_index", 1),
1086
+ "label": value.get("label"),
1087
+ "model": value.get("model", {}),
1088
+ "passed": bool(value.get("passed", False)),
1089
+ "status": value.get("status", "fail"),
1090
+ "error_kind": value.get("error_kind"),
1091
+ "steps": [
1092
+ _step_from_dict(step)
1093
+ for step in value.get("steps", [])
1094
+ if isinstance(step, dict)
1095
+ ],
1096
+ "error": value.get("error"),
1097
+ "traceback": value.get("traceback"),
1098
+ "mock_events": value.get("mock_events", []),
1099
+ "mock_state": value.get("mock_state", {}),
1100
+ "requests": value.get("requests", []),
1101
+ "artifact_dir": value.get("artifact_dir"),
1102
+ "tag_summary": value.get("tag_summary", {}),
1103
+ }
1104
+ data["usage"] = lambda usage_value=usage_value: usage_value
1105
+ data["request_duration_ms"] = lambda duration_value=duration_value: duration_value
1106
+ return _object_from_dict(data)
1107
+
1108
+
1109
+ def _result_from_bundle_entry(entry: dict[str, Any]) -> Any:
1110
+ source = dict(entry.get("result") or {})
1111
+ source.setdefault("case_key", entry.get("case_key", ""))
1112
+ source.setdefault("description", entry.get("description", ""))
1113
+ source.setdefault("passed", entry.get("status") == "pass")
1114
+ source.setdefault("status", entry.get("status", "fail"))
1115
+ source.setdefault("pass_rate", entry.get("pass_rate", 0.0))
1116
+ data = {
1117
+ "case_key": source["case_key"],
1118
+ "description": source.get("description", ""),
1119
+ "passed": bool(source.get("passed", False)),
1120
+ "status": source.get("status", "fail"),
1121
+ "pass_rate": source.get("pass_rate", 0.0),
1122
+ "runs": [
1123
+ _run_from_dict(run)
1124
+ for run in source.get("runs", [])
1125
+ if isinstance(run, dict)
1126
+ ],
1127
+ }
1128
+ data["usage"] = lambda entry=entry, source=source: (
1129
+ entry.get("usage") if "usage" in entry else source.get("usage")
1130
+ )
1131
+ data["request_duration_ms"] = lambda entry=entry, source=source: (
1132
+ entry.get("llm_request_duration_ms")
1133
+ if "llm_request_duration_ms" in entry
1134
+ else source.get("request_duration_ms")
1135
+ )
1136
+ return _object_from_dict(data)
1137
+
1138
+
1139
+ def _case_from_bundle_entry(entry: dict[str, Any]) -> Any:
1140
+ source = dict(entry.get("case") or {})
1141
+ source.setdefault("case_key", entry.get("case_key", ""))
1142
+ source.setdefault("path", entry.get("path", entry.get("case_key", "")))
1143
+ source.setdefault("description", entry.get("description", ""))
1144
+ source.setdefault("model", {})
1145
+ source.setdefault("execution", {})
1146
+ tools = source.get("tools", [])
1147
+ skills = source.get("skills", [])
1148
+ source["tools"] = [
1149
+ _object_from_dict({"name": name}) for name in tools if isinstance(name, str)
1150
+ ]
1151
+ source["skills"] = [
1152
+ _object_from_dict({"name": name}) for name in skills if isinstance(name, str)
1153
+ ]
1154
+ return _object_from_dict(source)
1155
+
1156
+
1157
+ def _bundle_case_entries(bundle: dict[str, Any] | None) -> list[dict[str, Any]]:
1158
+ entries: list[dict[str, Any]] = []
1159
+ if not isinstance(bundle, dict):
1160
+ return entries
1161
+ plugins = bundle.get("plugins", [])
1162
+ if not isinstance(plugins, list):
1163
+ return entries
1164
+ for plugin in plugins:
1165
+ if not isinstance(plugin, dict):
1166
+ continue
1167
+ cases = plugin.get("cases", [])
1168
+ if isinstance(cases, list):
1169
+ entries.extend(entry for entry in cases if isinstance(entry, dict))
1170
+ return entries
1171
+
1172
+
1173
+ def _bundle_update_map(bundle: dict[str, Any] | None) -> dict[str, str]:
1174
+ updates: dict[str, str] = {}
1175
+ for entry in _bundle_case_entries(bundle):
1176
+ case_key = entry.get("case_key")
1177
+ value = entry.get("updated_at_beijing")
1178
+ if isinstance(case_key, str) and isinstance(value, str) and value:
1179
+ updates[case_key] = value
1180
+ return updates
1181
+
1182
+
1183
+ def _render_case(
1184
+ case: ResolvedCase,
1185
+ result: CaseResult,
1186
+ *,
1187
+ updated_at_beijing: str | None = None,
1188
+ ) -> str:
1049
1189
  evaluated_runs = [run for run in result.runs if run.status != "error"]
1050
1190
  passed_runs = sum(run.passed for run in evaluated_runs)
1051
1191
  run_errors = len(result.runs) - len(evaluated_runs)
@@ -1093,6 +1233,7 @@ def _render_case(case: ResolvedCase, result: CaseResult) -> str:
1093
1233
  f'<div><span>Skills</span><strong>{_text(skills)}</strong></div>'
1094
1234
  f'<div><span>LLM tokens</span><strong>{_text(usage_cell)}</strong></div>'
1095
1235
  f'<div><span>LLM request time</span><strong>{_text(duration_cell)}</strong></div>'
1236
+ f'<div><span>Updated at (Beijing time)</span><strong>{_text(updated_at_beijing or "-")}</strong></div>'
1096
1237
  "</div>"
1097
1238
  f'{_render_run_comparison(result)}'
1098
1239
  f'{_render_planned_runs(case)}'
@@ -1374,22 +1515,25 @@ def render_page(
1374
1515
  overall_html: str,
1375
1516
  body_html: str,
1376
1517
  meta: dict[str, Any] | None = None,
1518
+ bundle: dict[str, Any] | None = None,
1377
1519
  ) -> str:
1378
1520
  """Shared single-file page shell (palette, typography, layout) for every
1379
1521
  HTML surface yama emits: run reports, case previews, and the dashboard
1380
1522
  index. `meta`, when given, is embedded as an inert JSON <script> in the
1381
1523
  head so the dashboard can list a page's verdict/stats without parsing
1382
1524
  its markup."""
1383
- meta_html = ""
1525
+ head_scripts: list[str] = []
1384
1526
  if meta is not None:
1385
- payload = json.dumps(meta, ensure_ascii=False, default=str)
1386
- # `\/` is valid JSON string escaping: a literal `</script>` inside a
1387
- # value can never terminate the script element early.
1388
- payload = payload.replace("</", "<\\/")
1389
- meta_html = (
1390
- '\n<script type="application/json" id="yama-report-meta">'
1391
- f"{payload}</script>"
1527
+ head_scripts.append(
1528
+ '<script type="application/json" id="yama-report-meta">'
1529
+ f"{embed_json_for_html_script(meta)}</script>"
1530
+ )
1531
+ if bundle is not None:
1532
+ head_scripts.append(
1533
+ '<script type="application/json" id="yama-report-bundle">'
1534
+ f"{embed_json_for_html_script(bundle)}</script>"
1392
1535
  )
1536
+ meta_html = ("\n" + "\n".join(head_scripts)) if head_scripts else ""
1393
1537
  return f"""<!doctype html>
1394
1538
  <html lang="en">
1395
1539
  <head>
@@ -1414,7 +1558,10 @@ def render_page(
1414
1558
 
1415
1559
 
1416
1560
  def render_html_report(
1417
- cases: Sequence[ResolvedCase], results: Sequence[CaseResult]
1561
+ cases: Sequence[ResolvedCase],
1562
+ results: Sequence[CaseResult],
1563
+ *,
1564
+ bundle: dict[str, Any] | None = None,
1418
1565
  ) -> str:
1419
1566
  if len(cases) != len(results):
1420
1567
  raise ValueError("HTML report requires one result for every resolved case")
@@ -1471,8 +1618,14 @@ def render_html_report(
1471
1618
  else "<strong>–</strong>"
1472
1619
  )
1473
1620
  generated_at = datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")
1621
+ update_times = _bundle_update_map(bundle)
1474
1622
  rendered_cases = "".join(
1475
- _render_case(case, result) for case, result in zip(cases, results, strict=True)
1623
+ _render_case(
1624
+ case,
1625
+ result,
1626
+ updated_at_beijing=update_times.get(result.case_key),
1627
+ )
1628
+ for case, result in zip(cases, results, strict=True)
1476
1629
  )
1477
1630
  body = f"""<section class="summary-grid" aria-label="Summary">
1478
1631
  <div class="summary-card"><span>CASES PASSED</span><strong>{passed_cases}/{len(results)}</strong></div>
@@ -1482,7 +1635,10 @@ def render_html_report(
1482
1635
  {rendered_cases or '<p>No cases were included in this report.</p>'}"""
1483
1636
  return render_page(
1484
1637
  title="Yama Eval Report",
1485
- header_note_html=f"Generated {_text(generated_at)}",
1638
+ header_note_html=(
1639
+ f"Generated {_text(generated_at)}"
1640
+ + (" · Case update times are Beijing time." if bundle is not None else "")
1641
+ ),
1486
1642
  overall_html=(
1487
1643
  _status(overall_status, kind="stamp", size="lg", seed="overall")
1488
1644
  + "<span>Overall result</span>"
@@ -1509,6 +1665,116 @@ def render_html_report(
1509
1665
  "total_tokens": total_usage["total_tokens"] if total_usage else None,
1510
1666
  "llm_request_duration_ms": total_duration,
1511
1667
  },
1668
+ bundle=bundle,
1669
+ )
1670
+
1671
+
1672
+ def _bundle_counts(bundle: dict[str, Any], key: str) -> int:
1673
+ total = 0
1674
+ for entry in _bundle_case_entries(bundle):
1675
+ counts = entry.get("counts")
1676
+ if isinstance(counts, dict):
1677
+ value = counts.get(key)
1678
+ if isinstance(value, int) and not isinstance(value, bool):
1679
+ total += value
1680
+ return total
1681
+
1682
+
1683
+ def _bundle_usage_total(bundle: dict[str, Any]) -> int | None:
1684
+ total = 0
1685
+ seen = False
1686
+ for entry in _bundle_case_entries(bundle):
1687
+ usage = entry.get("usage")
1688
+ if not isinstance(usage, dict):
1689
+ continue
1690
+ value = usage.get("total_tokens")
1691
+ if isinstance(value, int) and not isinstance(value, bool):
1692
+ seen = True
1693
+ total += value
1694
+ return total if seen else None
1695
+
1696
+
1697
+ def _bundle_duration_total(bundle: dict[str, Any]) -> float | None:
1698
+ return combine_duration_ms(
1699
+ entry.get("llm_request_duration_ms") for entry in _bundle_case_entries(bundle)
1700
+ )
1701
+
1702
+
1703
+ def render_html_report_from_bundle(bundle: dict[str, Any]) -> str:
1704
+ cases: list[Any] = []
1705
+ results: list[Any] = []
1706
+ update_times: dict[str, str] = {}
1707
+ for entry in _bundle_case_entries(bundle):
1708
+ cases.append(_case_from_bundle_entry(entry))
1709
+ result = _result_from_bundle_entry(entry)
1710
+ results.append(result)
1711
+ updated_at = entry.get("updated_at_beijing")
1712
+ if isinstance(updated_at, str):
1713
+ update_times[result.case_key] = updated_at
1714
+
1715
+ if any(result.status == "fail" for result in results):
1716
+ overall_status = "fail"
1717
+ elif any(result.status == "error" for result in results):
1718
+ overall_status = "error"
1719
+ else:
1720
+ overall_status = "pass" if results else "fail"
1721
+
1722
+ rendered_cases = "".join(
1723
+ _render_case(
1724
+ case,
1725
+ result,
1726
+ updated_at_beijing=update_times.get(result.case_key),
1727
+ )
1728
+ for case, result in zip(cases, results, strict=True)
1729
+ )
1730
+ generated_at = str(
1731
+ bundle.get("generated_at")
1732
+ or datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")
1733
+ )
1734
+ cases_passed = sum(result.status == "pass" for result in results)
1735
+ cases_error = sum(result.status == "error" for result in results)
1736
+ runs_total = _bundle_counts(bundle, "runs_total")
1737
+ runs_error = _bundle_counts(bundle, "runs_error")
1738
+ total_tokens = _bundle_usage_total(bundle)
1739
+ usage_card = f"<strong>{total_tokens:,}</strong>" if total_tokens is not None else "<strong>-</strong>"
1740
+ body = f"""<section class="summary-grid" aria-label="Summary">
1741
+ <div class="summary-card"><span>CASES PASSED</span><strong>{cases_passed}/{len(results)}</strong></div>
1742
+ <div class="summary-card"><span>CASES ERRORS</span><strong>{cases_error}/{len(results)}</strong></div>
1743
+ <div class="summary-card"><span>LLM TOKENS</span>{usage_card}</div>
1744
+ </section>
1745
+ {rendered_cases or '<p>No cases were included in this report.</p>'}"""
1746
+ return render_page(
1747
+ title="Yama Eval Report",
1748
+ header_note_html=(
1749
+ f"Generated {_text(generated_at)} · Case update times are Beijing time."
1750
+ ),
1751
+ overall_html=(
1752
+ _status(overall_status, kind="stamp", size="lg", seed="overall")
1753
+ + "<span>Overall result</span>"
1754
+ ),
1755
+ body_html=body,
1756
+ meta={
1757
+ "generator": "yama",
1758
+ "kind": "report",
1759
+ "generated_at": generated_at,
1760
+ "passed": overall_status == "pass",
1761
+ "status": overall_status,
1762
+ "cases_passed": cases_passed,
1763
+ "cases_evaluated": len(results) - cases_error,
1764
+ "cases_error": cases_error,
1765
+ "cases_total": len(results),
1766
+ "runs_passed": _bundle_counts(bundle, "runs_passed"),
1767
+ "runs_evaluated": runs_total - runs_error,
1768
+ "runs_error": runs_error,
1769
+ "llm_errors": None,
1770
+ "framework_errors": None,
1771
+ "runs_total": runs_total,
1772
+ "checks_passed": None,
1773
+ "checks_total": None,
1774
+ "total_tokens": total_tokens,
1775
+ "llm_request_duration_ms": _bundle_duration_total(bundle),
1776
+ },
1777
+ bundle=bundle,
1512
1778
  )
1513
1779
 
1514
1780
 
@@ -1516,10 +1782,14 @@ def write_html_report(
1516
1782
  cases: Sequence[ResolvedCase],
1517
1783
  results: Sequence[CaseResult],
1518
1784
  path: Path,
1785
+ *,
1786
+ bundle: dict[str, Any] | None = None,
1519
1787
  ) -> Path:
1520
1788
  target = path.expanduser().resolve()
1521
1789
  target.parent.mkdir(parents=True, exist_ok=True)
1522
- target.write_text(render_html_report(cases, results), encoding="utf-8")
1790
+ target.write_text(
1791
+ render_html_report(cases, results, bundle=bundle), encoding="utf-8"
1792
+ )
1523
1793
  return target
1524
1794
 
1525
1795
 
@@ -1527,6 +1797,8 @@ def write_timestamped_report(
1527
1797
  cases: Sequence[ResolvedCase],
1528
1798
  results: Sequence[CaseResult],
1529
1799
  reports_dir: Path,
1800
+ *,
1801
+ bundle: dict[str, Any] | None = None,
1530
1802
  ) -> Path:
1531
1803
  """Write `report-<timestamp>.html` into `reports_dir` and repoint the
1532
1804
  `latest.html` symlink at it, so report history accumulates (the
@@ -1541,7 +1813,9 @@ def write_timestamped_report(
1541
1813
  while target.exists():
1542
1814
  serial += 1
1543
1815
  target = directory / f"report-{stamp}-{serial}.html"
1544
- target.write_text(render_html_report(cases, results), encoding="utf-8")
1816
+ target.write_text(
1817
+ render_html_report(cases, results, bundle=bundle), encoding="utf-8"
1818
+ )
1545
1819
  latest = directory / "latest.html"
1546
1820
  latest.unlink(missing_ok=True)
1547
1821
  try:
yama/report_bundle.py ADDED
@@ -0,0 +1,237 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from copy import deepcopy
6
+ from dataclasses import dataclass
7
+ from datetime import datetime
8
+ from html.parser import HTMLParser
9
+ from pathlib import Path
10
+ from typing import Any, Literal, Sequence
11
+ from zoneinfo import ZoneInfo
12
+
13
+ from .models import ResolvedCase
14
+ from .runner import CaseResult
15
+
16
+
17
+ _COMMIT_RE = re.compile(r"^[0-9a-fA-F]{7,64}$")
18
+ _PLUGIN_KEY_RE = re.compile(r"^[A-Za-z0-9._-]+$")
19
+ _BEIJING = ZoneInfo("Asia/Shanghai")
20
+
21
+
22
+ class ReportBundleError(ValueError):
23
+ pass
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class PluginReportData:
28
+ name: str
29
+ root: str
30
+ cases: list[dict[str, Any]]
31
+
32
+
33
+ def validate_commit_id(value: str) -> str:
34
+ if not isinstance(value, str) or not _COMMIT_RE.fullmatch(value):
35
+ raise ReportBundleError("commit id must be 7-64 hex characters")
36
+ return value
37
+
38
+
39
+ def validate_plugin_report_key(value: str) -> str:
40
+ if not isinstance(value, str) or not _PLUGIN_KEY_RE.fullmatch(value):
41
+ raise ReportBundleError(
42
+ "plugin report key may only contain letters, digits, '.', '_' and '-'"
43
+ )
44
+ return value
45
+
46
+
47
+ def beijing_timestamp(moment: datetime | None = None) -> str:
48
+ moment = moment or datetime.now(tz=_BEIJING)
49
+ if moment.tzinfo is None:
50
+ moment = moment.replace(tzinfo=_BEIJING)
51
+ return moment.astimezone(_BEIJING).strftime("%Y-%m-%d %H:%M:%S")
52
+
53
+
54
+ def _relative(path: Path, root: Path) -> str:
55
+ try:
56
+ return path.resolve().relative_to(root.resolve()).as_posix()
57
+ except ValueError:
58
+ return str(path)
59
+
60
+
61
+ def _case_counts(result: CaseResult) -> dict[str, int]:
62
+ runs = list(result.runs)
63
+ return {
64
+ "runs_passed": sum(run.passed for run in runs if run.status != "error"),
65
+ "runs_total": len(runs),
66
+ "runs_error": sum(1 for run in runs if run.status == "error"),
67
+ }
68
+
69
+
70
+ def _tool_names(case: ResolvedCase) -> list[str]:
71
+ return [tool.name for tool in case.tools]
72
+
73
+
74
+ def _skill_names(case: ResolvedCase) -> list[str]:
75
+ return [skill.name for skill in case.skills]
76
+
77
+
78
+ def build_case_entry(
79
+ case: ResolvedCase,
80
+ result: CaseResult,
81
+ *,
82
+ workspace_root: Path,
83
+ updated_at_beijing: str,
84
+ ) -> dict[str, Any]:
85
+ return {
86
+ "case_key": result.case_key,
87
+ "path": _relative(case.path, workspace_root),
88
+ "description": result.description or case.description,
89
+ "status": result.status,
90
+ "pass_rate": result.pass_rate,
91
+ "counts": _case_counts(result),
92
+ "usage": result.usage(),
93
+ "llm_request_duration_ms": result.request_duration_ms(),
94
+ "updated_at_beijing": updated_at_beijing,
95
+ "case": {
96
+ "case_key": case.case_key,
97
+ "path": _relative(case.path, workspace_root),
98
+ "description": case.description,
99
+ "model": deepcopy(case.model),
100
+ "execution": deepcopy(case.execution),
101
+ "tools": _tool_names(case),
102
+ "skills": _skill_names(case),
103
+ },
104
+ "result": result.to_dict(),
105
+ }
106
+
107
+
108
+ def build_report_bundle(
109
+ plugin_entries: Sequence[dict[str, Any] | PluginReportData],
110
+ *,
111
+ kind: Literal["push", "plugin"],
112
+ generated_at: datetime | None = None,
113
+ ) -> dict[str, Any]:
114
+ generated_at = generated_at or datetime.now(tz=_BEIJING)
115
+ if generated_at.tzinfo is None:
116
+ generated_at = generated_at.replace(tzinfo=_BEIJING)
117
+ plugins: list[dict[str, Any]] = []
118
+ for entry in plugin_entries:
119
+ if isinstance(entry, PluginReportData):
120
+ plugin = {"name": entry.name, "root": entry.root, "cases": entry.cases}
121
+ else:
122
+ plugin = dict(entry)
123
+ plugins.append(
124
+ {
125
+ "name": plugin["name"],
126
+ "root": plugin["root"],
127
+ "cases": list(plugin.get("cases", [])),
128
+ }
129
+ )
130
+ return {
131
+ "schema_version": 1,
132
+ "kind": kind,
133
+ "generated_at": generated_at.astimezone(_BEIJING).isoformat(
134
+ timespec="seconds"
135
+ ),
136
+ "plugins": plugins,
137
+ }
138
+
139
+
140
+ def embed_json_for_html_script(value: Any) -> str:
141
+ return json.dumps(value, ensure_ascii=False, default=str).replace("</", "<\\/")
142
+
143
+
144
+ class _BundleParser(HTMLParser):
145
+ def __init__(self) -> None:
146
+ super().__init__(convert_charrefs=False)
147
+ self.in_bundle = False
148
+ self.parts: list[str] = []
149
+
150
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
151
+ attr_map = dict(attrs)
152
+ if tag.lower() == "script" and attr_map.get("id") == "yama-report-bundle":
153
+ self.in_bundle = True
154
+
155
+ def handle_endtag(self, tag: str) -> None:
156
+ if tag.lower() == "script" and self.in_bundle:
157
+ self.in_bundle = False
158
+
159
+ def handle_data(self, data: str) -> None:
160
+ if self.in_bundle:
161
+ self.parts.append(data)
162
+
163
+
164
+ def extract_report_bundle(html: str) -> dict[str, Any] | None:
165
+ parser = _BundleParser()
166
+ parser.feed(html)
167
+ if not parser.parts:
168
+ return None
169
+ raw = "".join(parser.parts)
170
+ try:
171
+ payload = json.loads(raw)
172
+ except json.JSONDecodeError as exc:
173
+ raise ReportBundleError(f"invalid yama-report-bundle JSON: {exc}") from exc
174
+ if not isinstance(payload, dict):
175
+ raise ReportBundleError("yama-report-bundle must be a JSON object")
176
+ if payload.get("schema_version") != 1:
177
+ raise ReportBundleError("unsupported yama-report-bundle schema_version")
178
+ return payload
179
+
180
+
181
+ def _plugin_from_bundle(
182
+ bundle: dict[str, Any], plugin_name: str
183
+ ) -> dict[str, Any] | None:
184
+ plugins = bundle.get("plugins")
185
+ if not isinstance(plugins, list):
186
+ raise ReportBundleError("report bundle plugins must be a list")
187
+ for plugin in plugins:
188
+ if isinstance(plugin, dict) and plugin.get("name") == plugin_name:
189
+ return plugin
190
+ return None
191
+
192
+
193
+ def _case_map(plugin: dict[str, Any]) -> dict[str, dict[str, Any]]:
194
+ cases = plugin.get("cases", [])
195
+ if not isinstance(cases, list):
196
+ raise ReportBundleError("plugin bundle cases must be a list")
197
+ result: dict[str, dict[str, Any]] = {}
198
+ for case in cases:
199
+ if not isinstance(case, dict) or not isinstance(case.get("case_key"), str):
200
+ raise ReportBundleError(
201
+ "each plugin bundle case requires a string case_key"
202
+ )
203
+ result[case["case_key"]] = deepcopy(case)
204
+ return result
205
+
206
+
207
+ def merge_plugin_report_bundle(
208
+ existing: dict[str, Any] | None,
209
+ current: dict[str, Any],
210
+ *,
211
+ plugin_name: str,
212
+ ) -> dict[str, Any]:
213
+ current_plugin = _plugin_from_bundle(current, plugin_name)
214
+ if current_plugin is None:
215
+ raise ReportBundleError(
216
+ f"current bundle does not contain plugin {plugin_name!r}"
217
+ )
218
+ merged_cases: dict[str, dict[str, Any]] = {}
219
+ root = current_plugin.get("root", plugin_name)
220
+ if existing is not None:
221
+ existing_plugin = _plugin_from_bundle(existing, plugin_name)
222
+ if existing_plugin is not None:
223
+ root = existing_plugin.get("root", root)
224
+ merged_cases.update(_case_map(existing_plugin))
225
+ merged_cases.update(_case_map(current_plugin))
226
+ return {
227
+ "schema_version": 1,
228
+ "kind": "plugin",
229
+ "generated_at": current.get("generated_at"),
230
+ "plugins": [
231
+ {
232
+ "name": plugin_name,
233
+ "root": root,
234
+ "cases": [merged_cases[key] for key in sorted(merged_cases)],
235
+ }
236
+ ],
237
+ }
yama/report_upload.py ADDED
@@ -0,0 +1,323 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import mimetypes
5
+ import tempfile
6
+ import uuid
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+ from typing import Any, Callable
10
+ from urllib.error import HTTPError, URLError
11
+ from urllib.parse import quote
12
+ from urllib.request import Request, urlopen as stdlib_urlopen
13
+
14
+ from .report import render_html_report_from_bundle
15
+ from .report_bundle import (
16
+ ReportBundleError,
17
+ beijing_timestamp,
18
+ build_case_entry,
19
+ build_report_bundle,
20
+ extract_report_bundle,
21
+ merge_plugin_report_bundle,
22
+ validate_commit_id,
23
+ validate_plugin_report_key,
24
+ )
25
+
26
+
27
+ class ReportUploadError(RuntimeError):
28
+ pass
29
+
30
+
31
+ UrlOpen = Callable[..., Any]
32
+
33
+
34
+ class ReportUploadClient:
35
+ def __init__(
36
+ self,
37
+ *,
38
+ admin_host: str,
39
+ token: str,
40
+ urlopen: UrlOpen = stdlib_urlopen,
41
+ timeout: int = 30,
42
+ ) -> None:
43
+ self.admin_host = admin_host.rstrip("/")
44
+ self.token = token
45
+ self.urlopen = urlopen
46
+ self.timeout = timeout
47
+ self.base_url = self.admin_host + "/admin/api/v1/test/v2"
48
+
49
+ def _request_json(self, method: str, path: str) -> dict[str, Any] | None:
50
+ request = Request(
51
+ self.base_url + path,
52
+ method=method,
53
+ headers={"Authorization": f"Bearer {self.token}"},
54
+ )
55
+ try:
56
+ with self.urlopen(request, timeout=self.timeout) as response:
57
+ body = response.read()
58
+ except HTTPError as exc:
59
+ if exc.code == 404:
60
+ return None
61
+ raise ReportUploadError(
62
+ f"report API {method} {path} failed with HTTP {exc.code}: {exc.reason}"
63
+ ) from exc
64
+ except URLError as exc:
65
+ raise ReportUploadError(
66
+ f"report API {method} {path} failed: {exc.reason}"
67
+ ) from exc
68
+ try:
69
+ payload = json.loads(body.decode("utf-8"))
70
+ except json.JSONDecodeError as exc:
71
+ raise ReportUploadError(
72
+ f"report API {method} {path} returned invalid JSON"
73
+ ) from exc
74
+ if not isinstance(payload, dict):
75
+ raise ReportUploadError(
76
+ f"report API {method} {path} returned non-object JSON"
77
+ )
78
+ return payload
79
+
80
+ def get_plugin_report(self, plugin_name: str) -> dict[str, Any] | None:
81
+ return self._request_json(
82
+ "GET", f"/yama-eval-report/plugins/{quote(plugin_name, safe='')}"
83
+ )
84
+
85
+ def download_text(self, url: str) -> str:
86
+ try:
87
+ with self.urlopen(url, timeout=self.timeout) as response:
88
+ return response.read().decode("utf-8")
89
+ except HTTPError as exc:
90
+ raise ReportUploadError(
91
+ f"download report HTML failed with HTTP {exc.code}: {url}"
92
+ ) from exc
93
+ except URLError as exc:
94
+ raise ReportUploadError(
95
+ f"download report HTML failed: {exc.reason}"
96
+ ) from exc
97
+
98
+ def upload_report(
99
+ self,
100
+ *,
101
+ report_scope: str,
102
+ report_key: str,
103
+ file_path: Path,
104
+ ) -> dict[str, Any]:
105
+ boundary = "----yama-" + uuid.uuid4().hex
106
+ body = _multipart_body(
107
+ {
108
+ "report_scope": report_scope,
109
+ "report_key": report_key,
110
+ },
111
+ file_field="file",
112
+ file_path=file_path,
113
+ boundary=boundary,
114
+ )
115
+ request = Request(
116
+ self.base_url + "/yama-eval-report/upload",
117
+ data=body,
118
+ method="POST",
119
+ headers={
120
+ "Authorization": f"Bearer {self.token}",
121
+ "Content-Type": f"multipart/form-data; boundary={boundary}",
122
+ },
123
+ )
124
+ try:
125
+ with self.urlopen(request, timeout=self.timeout) as response:
126
+ payload = json.loads(response.read().decode("utf-8"))
127
+ except HTTPError as exc:
128
+ raise ReportUploadError(
129
+ f"upload {report_scope} report {report_key!r} failed with "
130
+ f"HTTP {exc.code}: {exc.reason}"
131
+ ) from exc
132
+ except URLError as exc:
133
+ raise ReportUploadError(
134
+ f"upload {report_scope} report {report_key!r} failed: {exc.reason}"
135
+ ) from exc
136
+ except json.JSONDecodeError as exc:
137
+ raise ReportUploadError(
138
+ f"upload {report_scope} report {report_key!r} returned invalid JSON"
139
+ ) from exc
140
+ if not isinstance(payload, dict):
141
+ raise ReportUploadError(
142
+ f"upload {report_scope} report {report_key!r} returned non-object JSON"
143
+ )
144
+ return payload
145
+
146
+
147
+ def _multipart_body(
148
+ fields: dict[str, str],
149
+ *,
150
+ file_field: str,
151
+ file_path: Path,
152
+ boundary: str,
153
+ ) -> bytes:
154
+ parts: list[bytes] = []
155
+ for name, value in fields.items():
156
+ parts.append(f"--{boundary}\r\n".encode())
157
+ parts.append(
158
+ f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode()
159
+ )
160
+ parts.append(str(value).encode("utf-8"))
161
+ parts.append(b"\r\n")
162
+ filename = file_path.name
163
+ content_type = mimetypes.guess_type(filename)[0] or "text/html"
164
+ parts.append(f"--{boundary}\r\n".encode())
165
+ parts.append(
166
+ (
167
+ f'Content-Disposition: form-data; name="{file_field}"; '
168
+ f'filename="{filename}"\r\n'
169
+ f"Content-Type: {content_type}\r\n\r\n"
170
+ ).encode()
171
+ )
172
+ parts.append(file_path.read_bytes())
173
+ parts.append(b"\r\n")
174
+ parts.append(f"--{boundary}--\r\n".encode())
175
+ return b"".join(parts)
176
+
177
+
178
+ def load_remote_plugin_bundle(
179
+ report_record: dict[str, Any],
180
+ *,
181
+ download_text: Callable[[str], str],
182
+ ) -> dict[str, Any] | None:
183
+ report_url = report_record.get("report_url")
184
+ if not isinstance(report_url, str) or not report_url:
185
+ raise ReportUploadError("plugin report response did not include report_url")
186
+ try:
187
+ return extract_report_bundle(download_text(report_url))
188
+ except ReportBundleError as exc:
189
+ raise ReportUploadError(str(exc)) from exc
190
+
191
+
192
+ def _case_entries_for_results(
193
+ *,
194
+ cases: list[Any],
195
+ results: list[Any],
196
+ workspace_root: Path,
197
+ updated_at_beijing: str,
198
+ ) -> list[dict[str, Any]]:
199
+ cases_by_key = {case.case_key: case for case in cases}
200
+ entries = []
201
+ for result in results:
202
+ case = cases_by_key.get(result.case_key)
203
+ if case is None:
204
+ raise ReportUploadError(
205
+ f"cannot build report entry for result {result.case_key!r}: "
206
+ "resolved case is unavailable"
207
+ )
208
+ entries.append(
209
+ build_case_entry(
210
+ case,
211
+ result,
212
+ workspace_root=workspace_root,
213
+ updated_at_beijing=updated_at_beijing,
214
+ )
215
+ )
216
+ return entries
217
+
218
+
219
+ def upload_pr_reports(
220
+ *,
221
+ workspace_root: Path,
222
+ commit_id: str,
223
+ admin_host: str,
224
+ token: str,
225
+ plugin_results: dict[str, dict[str, Any]],
226
+ plugin_cases: dict[str, list[Any]],
227
+ client: ReportUploadClient | None = None,
228
+ ) -> dict[str, Any]:
229
+ validate_commit_id(commit_id)
230
+ client = client or ReportUploadClient(admin_host=admin_host, token=token)
231
+ now = datetime.now().astimezone()
232
+ updated_at = beijing_timestamp(now)
233
+ plugin_entries: list[dict[str, Any]] = []
234
+ per_plugin_bundles: dict[str, dict[str, Any]] = {}
235
+
236
+ for plugin_key, entry in plugin_results.items():
237
+ if not entry.get("report_path"):
238
+ continue
239
+ entry["remote_report_url"] = None
240
+ entry["upload_error"] = None
241
+ try:
242
+ case_entries = _case_entries_for_results(
243
+ cases=plugin_cases.get(plugin_key, []),
244
+ results=list(entry.get("results", [])),
245
+ workspace_root=workspace_root,
246
+ updated_at_beijing=updated_at,
247
+ )
248
+ plugin_entry = {
249
+ "name": plugin_key,
250
+ "root": str(entry.get("plugin_root") or plugin_key),
251
+ "cases": case_entries,
252
+ }
253
+ plugin_entries.append(plugin_entry)
254
+ except (ReportUploadError, AttributeError) as exc:
255
+ entry["upload_error"] = str(exc)
256
+ continue
257
+
258
+ try:
259
+ validate_plugin_report_key(plugin_key)
260
+ per_plugin_bundles[plugin_key] = build_report_bundle(
261
+ [plugin_entry],
262
+ kind="plugin",
263
+ generated_at=now,
264
+ )
265
+ except ReportBundleError as exc:
266
+ entry["upload_error"] = str(exc)
267
+
268
+ push_bundle = build_report_bundle(plugin_entries, kind="push", generated_at=now)
269
+ upload_errors: list[str] = []
270
+ remote_push_report_url = None
271
+ with tempfile.TemporaryDirectory() as tmp:
272
+ directory = Path(tmp)
273
+ push_path = directory / f"{commit_id}.html"
274
+ push_path.write_text(
275
+ render_html_report_from_bundle(push_bundle),
276
+ encoding="utf-8",
277
+ )
278
+ try:
279
+ push_response = client.upload_report(
280
+ report_scope="push",
281
+ report_key=commit_id,
282
+ file_path=push_path,
283
+ )
284
+ remote_push_report_url = push_response.get("report_url")
285
+ except ReportUploadError as exc:
286
+ upload_errors.append(str(exc))
287
+
288
+ for plugin_key, current_bundle in per_plugin_bundles.items():
289
+ try:
290
+ remote_record = client.get_plugin_report(plugin_key)
291
+ existing_bundle = (
292
+ load_remote_plugin_bundle(
293
+ remote_record,
294
+ download_text=client.download_text,
295
+ )
296
+ if remote_record is not None
297
+ else None
298
+ )
299
+ merged = merge_plugin_report_bundle(
300
+ existing_bundle,
301
+ current_bundle,
302
+ plugin_name=plugin_key,
303
+ )
304
+ plugin_path = directory / f"{plugin_key}.html"
305
+ plugin_path.write_text(
306
+ render_html_report_from_bundle(merged),
307
+ encoding="utf-8",
308
+ )
309
+ response = client.upload_report(
310
+ report_scope="plugin",
311
+ report_key=plugin_key,
312
+ file_path=plugin_path,
313
+ )
314
+ plugin_results[plugin_key]["remote_report_url"] = response.get(
315
+ "report_url"
316
+ )
317
+ except (ReportUploadError, ReportBundleError) as exc:
318
+ plugin_results[plugin_key]["upload_error"] = str(exc)
319
+
320
+ return {
321
+ "remote_push_report_url": remote_push_report_url,
322
+ "upload_errors": upload_errors,
323
+ }