python-yama 0.5.0__py3-none-any.whl → 0.6.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.5.0
3
+ Version: 0.6.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
@@ -1,14 +1,15 @@
1
1
  yama/__init__.py,sha256=UYhoZTSu1HiMT54LOZCdvLKMQ_L0qec8RT8jDfde_cY,1156
2
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
3
+ yama/assertions.py,sha256=9tp_fuoFxqHPrClq_D1WF4i58TxgZUMnTdc-Kc9uKiw,23000
4
+ yama/cli.py,sha256=ipNWX1_2o7jy5NmYU3LyKmoPo68VF-LO6A2F8QQw9Tk,34699
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=0BMCWku5zWDOESrFUibiJShlfEhOAGlVKaNxfPB-9OM,4020
9
9
  yama/preview.py,sha256=gVTMqArXQqOLktGnactK9c0kfX6oHd6fWGjhkB7-QLQ,14220
10
- yama/report.py,sha256=qZr94njFDSRA5MTLhb2wvw8PgmK1kWuO-cCb-Nv3G4I,56829
11
- yama/runner.py,sha256=BEKXuHAnvizgMStWuPaudHr1omgGtbYqK2sgg9pUrcs,29319
10
+ yama/report.py,sha256=GyJ7oMKYwrLlt3hFXw6915er-6SWU4nr_Qhx37UJA2c,59590
11
+ yama/runner.py,sha256=zACo6shEqV-9Y_bu4bZs2vjdgaPPr5qj0KylTlqevEs,33549
12
+ yama/thread_case.py,sha256=ZaQvuu1uj9o9adTIbYghYp9iXEVqhEmoG4_b6duHYy0,13147
12
13
  yama/workspace.py,sha256=4GAe36Uj1-gjROMPwrQfTIg1TkzEIk9-gHEuezjbY_I,4614
13
14
  yama/loaders/__init__.py,sha256=DIwfa8QlIlKt6NpFMZJ_OcqbJPPrmKLBzd9_e-BCuBs,174
14
15
  yama/loaders/case.py,sha256=5uUpXm1t9EOmee2BZe7vDGXCrc4CSgcFGApSkuFe5tc,13954
@@ -22,8 +23,8 @@ yama/tools/bash/bash.py,sha256=4GlFvmqTUS4k6DgJ5Io91YF5fB6wF6e3e7p2P-pmbEQ,10358
22
23
  yama/tools/bash/fs.py,sha256=GChDwGe_Sgn73btZJDNp5nOwlVDhLfZyaMVqWSQwfOw,21859
23
24
  yama/tools/skill/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
25
  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,,
26
+ python_yama-0.6.0.dist-info/METADATA,sha256=z4vYMlK6PlFbY6ydnGbCKwJFHDFSfDxc2UyAMeJZnvA,7515
27
+ python_yama-0.6.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
28
+ python_yama-0.6.0.dist-info/entry_points.txt,sha256=N5se3y1FflUcDU3TmUrH2Tu9dzsrBBo7sUP-Gu_2cVs,39
29
+ python_yama-0.6.0.dist-info/licenses/LICENSE,sha256=cMAJJAs7R1lemJPPc7qMNv4w_sqn5QncFf4aXKYyEc4,1067
30
+ python_yama-0.6.0.dist-info/RECORD,,
yama/assertions.py CHANGED
@@ -16,6 +16,28 @@ class AssertionConfigurationError(ValueError):
16
16
  pass
17
17
 
18
18
 
19
+ DEFAULT_HARD_ASSERTION_TAG = "must_pass"
20
+ HARD_ASSERTION_TAG_THRESHOLDS: dict[str, float] = {
21
+ "must_pass": 1.0,
22
+ "high_confidence": 0.9,
23
+ "tolerant": 0.8,
24
+ "informational": 0.0,
25
+ }
26
+
27
+
28
+ def normalize_hard_assertion_tag(tag: Any) -> str:
29
+ if tag is None:
30
+ return DEFAULT_HARD_ASSERTION_TAG
31
+ if not isinstance(tag, str):
32
+ raise AssertionConfigurationError("hard assertion 'tag' must be a string")
33
+ if tag not in HARD_ASSERTION_TAG_THRESHOLDS:
34
+ allowed = ", ".join(HARD_ASSERTION_TAG_THRESHOLDS)
35
+ raise AssertionConfigurationError(
36
+ f"unknown hard assertion tag {tag!r}; expected one of: {allowed}"
37
+ )
38
+ return tag
39
+
40
+
19
41
  _MISSING = object()
20
42
 
21
43
 
@@ -165,11 +187,18 @@ async def run_hard_assertions(
165
187
  ) -> list[dict[str, Any]]:
166
188
  checks: list[dict[str, Any]] = []
167
189
  for assertion in assertions:
168
- if not isinstance(assertion, dict) or len(assertion) != 1:
190
+ if not isinstance(assertion, dict):
169
191
  raise AssertionConfigurationError(
170
192
  "each hard assertion must contain exactly one type"
171
193
  )
172
- kind, config = next(iter(assertion.items()))
194
+ tag = normalize_hard_assertion_tag(assertion.get("tag"))
195
+ type_items = {key: value for key, value in assertion.items() if key != "tag"}
196
+ if len(type_items) != 1:
197
+ raise AssertionConfigurationError(
198
+ "each hard assertion must contain exactly one type, plus an "
199
+ "optional string 'tag'"
200
+ )
201
+ kind, config = next(iter(type_items.items()))
173
202
  diagnostic = await _run_one(
174
203
  kind,
175
204
  config,
@@ -179,7 +208,7 @@ async def run_hard_assertions(
179
208
  plugin_root=plugin_root,
180
209
  relative_root=relative_root,
181
210
  )
182
- checks.append({"type": kind, **diagnostic})
211
+ checks.append({"type": kind, "tag": tag, **diagnostic})
183
212
  return checks
184
213
 
185
214
 
yama/cli.py CHANGED
@@ -31,6 +31,18 @@ from .loaders import CollectionError, resolve_case
31
31
  from .preview import preview_payload, write_preview_html
32
32
  from .report import write_html_report, write_timestamped_report
33
33
  from .runner import YamaRunner, combine_usage
34
+ from .thread_case import (
35
+ ThreadCaseError,
36
+ build_case_dict,
37
+ build_response_preview,
38
+ dump_case_yaml,
39
+ fetch_dsl_at_commit,
40
+ fetch_model_records,
41
+ parse_record_id,
42
+ resolve_dsl_remote_base_dir,
43
+ resolve_dsl_ssh_host,
44
+ select_record,
45
+ )
34
46
 
35
47
  DEFAULT_REPORT = Path("__yama_default_report__")
36
48
 
@@ -794,6 +806,105 @@ def _run_dashboard(args: argparse.Namespace) -> int:
794
806
  return 0
795
807
 
796
808
 
809
+ _THREAD_TYPES = (
810
+ "one_shot",
811
+ "interactive",
812
+ "streaming",
813
+ "adventurer",
814
+ "gamer",
815
+ "atelier",
816
+ )
817
+
818
+
819
+ def _thread_case_parser() -> argparse.ArgumentParser:
820
+ parser = argparse.ArgumentParser(
821
+ prog="yama from-thread",
822
+ description=(
823
+ "Fetch one model-call record for a thread message and print a"
824
+ " single Case YAML skeleton to stdout, auto-populating one step when"
825
+ " DSL and request history make that possible."
826
+ ),
827
+ )
828
+ parser.add_argument(
829
+ "--record-id",
830
+ required=True,
831
+ help=(
832
+ "Composite record ID, comma-separated with thread_id first and"
833
+ " message_id second (e.g. '<thread_id>, <message_id>, ,"
834
+ " <completion_id>'); only the first two parts are used"
835
+ ),
836
+ )
837
+ parser.add_argument("--token", required=True, help="Bearer token")
838
+ parser.add_argument(
839
+ "--env",
840
+ default="dev",
841
+ help=(
842
+ "Target environment: dev, staging, or prod (default: dev)."
843
+ " Selects the admin API base URL and, when --commit-id is set,"
844
+ " the DSL SSH host and remote base dir"
845
+ ),
846
+ )
847
+ parser.add_argument(
848
+ "--thread-type",
849
+ choices=_THREAD_TYPES,
850
+ default=None,
851
+ help=(
852
+ "Thread type query param (default: let the server fall back to"
853
+ " the Thread's own stored type)"
854
+ ),
855
+ )
856
+ parser.add_argument(
857
+ "--record-index",
858
+ type=int,
859
+ default=-1,
860
+ metavar="N",
861
+ help="Which record to use from the message's records array (default: -1, the last one)",
862
+ )
863
+ parser.add_argument(
864
+ "--commit-id",
865
+ default=None,
866
+ help=(
867
+ "Git commit to read dsl.json from via SSH (git show <commit>:dsl.json);"
868
+ " omit to skip fetching dsl entirely"
869
+ ),
870
+ )
871
+ return parser
872
+
873
+
874
+ def _run_thread_case(args: argparse.Namespace) -> int:
875
+ thread_id, message_id = parse_record_id(args.record_id)
876
+ payload = fetch_model_records(
877
+ thread_id, message_id, args.token, args.thread_type, env=args.env
878
+ )
879
+ record = select_record(payload.get("records", []), args.record_index)
880
+ stderr = Console(stderr=True)
881
+ stderr.print(
882
+ Text(
883
+ f"record: provider_file={record.get('provider_file')}"
884
+ f" line_no={record.get('line_no')} record_id={record.get('record_id')}"
885
+ f" model={record.get('model')} datetime={record.get('datetime')}",
886
+ style="dim",
887
+ )
888
+ )
889
+ stderr.print(
890
+ Text(f"response: {build_response_preview(record.get('response'))}", style="dim")
891
+ )
892
+ dsl: dict[str, Any] | None = None
893
+ if args.commit_id is not None:
894
+ ssh_host = resolve_dsl_ssh_host(args.env)
895
+ remote_base_dir = resolve_dsl_remote_base_dir(args.env)
896
+ dsl = fetch_dsl_at_commit(thread_id, args.commit_id, ssh_host, remote_base_dir)
897
+ stderr.print(
898
+ Text(
899
+ f"dsl: fetched {len(dsl)} top-level key(s) at commit {args.commit_id}",
900
+ style="dim",
901
+ )
902
+ )
903
+ case = build_case_dict(record, dsl=dsl, record_id=args.record_id)
904
+ print(dump_case_yaml(case), end="")
905
+ return 0
906
+
907
+
797
908
  def main(argv: list[str] | None = None) -> int:
798
909
  # .env is resolved from the working directory upward (like yama.toml);
799
910
  # variables already present in the real environment take precedence.
@@ -803,6 +914,8 @@ def main(argv: list[str] | None = None) -> int:
803
914
  try:
804
915
  if argv[:1] == ["dashboard"]:
805
916
  return _run_dashboard(_dashboard_parser().parse_args(argv[1:]))
917
+ if argv[:1] == ["from-thread"]:
918
+ return _run_thread_case(_thread_case_parser().parse_args(argv[1:]))
806
919
  args = _parser().parse_args(argv)
807
920
  return asyncio.run(_run(args))
808
921
  except (ConfigurationError, CollectionError, ValueError) as exc:
@@ -818,5 +931,13 @@ def main(argv: list[str] | None = None) -> int:
818
931
  Text.assemble(("LLM error: ", "bold red"), (str(exc), "red"))
819
932
  )
820
933
  return 2
934
+ except ThreadCaseError as exc:
935
+ # Fetching/selecting the thread record failed -- separate label from
936
+ # "Collection error"/"LLM error" since neither Case collection nor an
937
+ # LLM call was involved.
938
+ Console(stderr=True).print(
939
+ Text.assemble(("Thread case error: ", "bold red"), (str(exc), "red"))
940
+ )
941
+ return 2
821
942
  except KeyboardInterrupt:
822
943
  return 130
yama/report.py CHANGED
@@ -8,6 +8,7 @@ from html import escape
8
8
  from pathlib import Path
9
9
  from typing import Any, Sequence
10
10
 
11
+ from .assertions import HARD_ASSERTION_TAG_THRESHOLDS
11
12
  from .models import ResolvedCase, StepResult
12
13
  from .runner import (
13
14
  CaseResult,
@@ -356,6 +357,7 @@ def _render_checks(step: StepResult) -> str:
356
357
  f'<tr class="{"passed" if passed else "failed"}">'
357
358
  f'<td>{_status(passed, kind="tick")}</td>'
358
359
  f'<td><strong>{index:02d} · {_text(check.get("label") or check.get("type", "hard check"))}</strong></td>'
360
+ f'<td>{_text(check.get("tag") or "-")}</td>'
359
361
  f'<td>{_text(check.get("expected", "assertion passes"))}</td>'
360
362
  f'<td>{_text(check.get("actual", check.get("detail", "unknown")))}</td>'
361
363
  f'<td>{_text(check.get("reason", check.get("detail", "")))}</td>'
@@ -363,7 +365,7 @@ def _render_checks(step: StepResult) -> str:
363
365
  )
364
366
  return (
365
367
  '<div class="table-wrap"><table class="checks">'
366
- "<thead><tr><th>Status</th><th>Check</th><th>Expected</th>"
368
+ "<thead><tr><th>Status</th><th>Check</th><th>Tag</th><th>Expected</th>"
367
369
  "<th>Actual</th><th>Reason</th></tr></thead>"
368
370
  f'<tbody>{"".join(rows)}</tbody></table></div>'
369
371
  )
@@ -795,6 +797,70 @@ def _render_run_comparison(result: CaseResult) -> str:
795
797
  return f'<section class="run-compare">{heading}{tables}</section>'
796
798
 
797
799
 
800
+ def _ordered_tag_items(
801
+ tag_summary: dict[Any, dict[str, Any]],
802
+ ) -> list[tuple[str, dict[str, Any]]]:
803
+ return [
804
+ (tag, tag_summary[tag])
805
+ for tag in HARD_ASSERTION_TAG_THRESHOLDS
806
+ if tag in tag_summary
807
+ ] + [
808
+ (str(tag), entry)
809
+ for tag, entry in tag_summary.items()
810
+ if tag not in HARD_ASSERTION_TAG_THRESHOLDS
811
+ ]
812
+
813
+
814
+ def _render_tag_summary(tag_summary: dict[Any, dict[str, Any]]) -> str:
815
+ if not tag_summary:
816
+ return ""
817
+ rows: list[str] = []
818
+ for label, entry in _ordered_tag_items(tag_summary):
819
+ ok = bool(entry.get("ok"))
820
+ rows.append(
821
+ f'<tr class="{"passed" if ok else "failed"}">'
822
+ f'<td>{_status(ok, kind="tick")}</td>'
823
+ f'<td><strong>{_text(label)}</strong></td>'
824
+ f'<td>{entry.get("passed", 0)}/{entry.get("total", 0)}</td>'
825
+ f'<td>{entry.get("rate", 0.0):.0%}</td>'
826
+ f'<td>{entry.get("threshold", 1.0):.0%}</td>'
827
+ "</tr>"
828
+ )
829
+ table = (
830
+ '<div class="table-wrap"><table class="checks">'
831
+ "<thead><tr><th>Status</th><th>Tag</th><th>Passed</th>"
832
+ "<th>Rate</th><th>Threshold</th></tr></thead>"
833
+ f'<tbody>{"".join(rows)}</tbody></table></div>'
834
+ )
835
+ return _fold("Pass rate by tag", table)
836
+
837
+
838
+ def _render_case_tag_summary(tag_summary: dict[Any, dict[str, Any]]) -> str:
839
+ if not tag_summary:
840
+ return ""
841
+ rows: list[str] = []
842
+ for label, entry in _ordered_tag_items(tag_summary):
843
+ ok = bool(entry.get("ok"))
844
+ rows.append(
845
+ f'<tr class="{"passed" if ok else "failed"}">'
846
+ f'<td>{_status(ok, kind="tick")}</td>'
847
+ f'<td><strong>{_text(label)}</strong></td>'
848
+ f'<td>{entry.get("passed", 0)}/{entry.get("total", 0)}</td>'
849
+ f'<td>{entry.get("rate", 0.0):.0%}</td>'
850
+ f'<td>{entry.get("threshold", 1.0):.0%}</td>'
851
+ "</tr>"
852
+ )
853
+ return (
854
+ '<section class="case-tag-summary">'
855
+ "<h3>Case tag summary</h3>"
856
+ '<div class="table-wrap"><table class="checks">'
857
+ "<thead><tr><th>Status</th><th>Tag</th><th>Passed</th>"
858
+ "<th>Rate</th><th>Threshold</th></tr></thead>"
859
+ f'<tbody>{"".join(rows)}</tbody></table></div>'
860
+ "</section>"
861
+ )
862
+
863
+
798
864
  def _render_run(run: RunResult) -> str:
799
865
  error = ""
800
866
  if run.error:
@@ -835,7 +901,7 @@ def _render_run(run: RunResult) -> str:
835
901
  f'<strong>Run {run.run_index}</strong>{label_html}{meta}'
836
902
  "</summary>"
837
903
  '<div class="run-body">'
838
- f"{error}{steps}"
904
+ f"{error}{steps}{_render_tag_summary(run.tag_summary)}"
839
905
  # The count stays inside the summary text (not a meta span): the
840
906
  # `LLM requests (N)` form is part of the report's stable markup.
841
907
  + _fold(
@@ -941,6 +1007,7 @@ def _render_case(case: ResolvedCase, result: CaseResult) -> str:
941
1007
  f'<span>{passed_runs}/{len(result.runs)} runs passed</span>'
942
1008
  "</div>"
943
1009
  "</header>"
1010
+ f"{_render_case_tag_summary(result.tag_summary)}"
944
1011
  '<div class="metadata">'
945
1012
  f'<div><span>Model</span><strong>{_text(model_cell)}</strong></div>'
946
1013
  f'<div><span>Tools</span><strong>{_text(tools)}</strong></div>'
@@ -1087,6 +1154,8 @@ summary:focus-visible, a:focus-visible, .verdict:focus-visible { outline: 2px so
1087
1154
  .eyebrow { color: var(--muted); font-family: var(--font-display); text-transform: uppercase; letter-spacing: .12em; font-size: 11px; }
1088
1155
  .case-outcome { min-width: 130px; display: grid; justify-items: end; align-content: start; gap: 5px; }
1089
1156
  .case-outcome strong { font-family: var(--font-mono); font-size: 22px; }
1157
+ .case-tag-summary { padding: 16px 20px; border-bottom: 1px solid var(--border); }
1158
+ .case-tag-summary h3 { margin: 0 0 10px; font-family: var(--font-display); font-size: 13px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); }
1090
1159
  .metadata { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); border-bottom: 1px solid var(--border); }
1091
1160
  .metadata > div { min-width: 0; padding: 14px 20px; border-right: 1px solid var(--border); }
1092
1161
  .metadata > div:last-child { border-right: 0; }
yama/runner.py CHANGED
@@ -13,7 +13,14 @@ from typing import Any, Callable, Iterable, Mapping
13
13
 
14
14
  import yaml
15
15
 
16
- from .assertions import run_hard_assertions, run_judge
16
+ from .assertions import (
17
+ DEFAULT_HARD_ASSERTION_TAG,
18
+ HARD_ASSERTION_TAG_THRESHOLDS,
19
+ AssertionConfigurationError,
20
+ normalize_hard_assertion_tag,
21
+ run_hard_assertions,
22
+ run_judge,
23
+ )
17
24
  from .tools.bash.fs import case_workspace_root, cleanup_session
18
25
  from .llm import LLMClient
19
26
  from .mocks import (
@@ -174,6 +181,7 @@ class RunResult:
174
181
  artifact_dir: Path | None = None
175
182
  label: str | None = None
176
183
  model: dict[str, Any] = field(default_factory=dict)
184
+ tag_summary: dict[str, dict[str, Any]] = field(default_factory=dict)
177
185
 
178
186
  def usage(self) -> dict[str, int] | None:
179
187
  """Token usage of every LLM call this run made: the step tool-loop
@@ -201,7 +209,98 @@ class RunResult:
201
209
  "mock_state": self.mock_state,
202
210
  "requests": self.requests,
203
211
  "artifact_dir": str(self.artifact_dir) if self.artifact_dir else None,
212
+ "tag_summary": {
213
+ normalize_hard_assertion_tag(tag): entry
214
+ for tag, entry in self.tag_summary.items()
215
+ },
216
+ }
217
+
218
+
219
+ def _thresholds_from_outcome(outcome: Mapping[str, Any]) -> dict[str, float]:
220
+ raw_thresholds = outcome.get("require", {}).get("tags", {})
221
+ if raw_thresholds is None:
222
+ raw_thresholds = {}
223
+ if not isinstance(raw_thresholds, Mapping):
224
+ raise AssertionConfigurationError("outcome.require.tags must be an object")
225
+ thresholds = dict(HARD_ASSERTION_TAG_THRESHOLDS)
226
+ for tag, value in raw_thresholds.items():
227
+ if tag not in HARD_ASSERTION_TAG_THRESHOLDS:
228
+ allowed = ", ".join(HARD_ASSERTION_TAG_THRESHOLDS)
229
+ raise AssertionConfigurationError(
230
+ f"unknown outcome tag {tag!r}; expected one of: {allowed}"
231
+ )
232
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
233
+ raise AssertionConfigurationError(
234
+ f"outcome.require.tags[{tag!r}] must be a number in [0, 1], got {value!r}"
235
+ )
236
+ threshold = float(value)
237
+ if not 0.0 <= threshold <= 1.0:
238
+ raise AssertionConfigurationError(
239
+ f"outcome.require.tags[{tag!r}] must be a number in [0, 1], got {value!r}"
240
+ )
241
+ if tag == DEFAULT_HARD_ASSERTION_TAG and threshold != 1.0:
242
+ raise AssertionConfigurationError(
243
+ "outcome.require.tags['must_pass'] is fixed at 1.0"
244
+ )
245
+ thresholds[tag] = threshold
246
+ return thresholds
247
+
248
+
249
+ def tag_pass_summary(
250
+ steps: Iterable[StepResult], outcome: Mapping[str, Any]
251
+ ) -> dict[str, dict[str, Any]]:
252
+ """Group every hard check by its fixed assertion tag and compute pass rate."""
253
+ thresholds = _thresholds_from_outcome(outcome)
254
+ groups: dict[str, list[bool]] = {}
255
+ for step in steps:
256
+ for check in step.hard_checks:
257
+ tag = normalize_hard_assertion_tag(check.get("tag"))
258
+ groups.setdefault(tag, []).append(bool(check.get("passed", False)))
259
+ summary: dict[str, dict[str, Any]] = {}
260
+ for tag, results in groups.items():
261
+ threshold = thresholds[tag]
262
+ total = len(results)
263
+ passed = sum(results)
264
+ rate = passed / total
265
+ summary[tag] = {
266
+ "passed": passed,
267
+ "total": total,
268
+ "rate": rate,
269
+ "threshold": threshold,
270
+ "ok": rate >= threshold,
271
+ }
272
+ return summary
273
+
274
+
275
+ def case_tag_summary(runs: Iterable[RunResult]) -> dict[str, dict[str, Any]]:
276
+ groups: dict[str, dict[str, Any]] = {}
277
+ for run in runs:
278
+ for tag, entry in run.tag_summary.items():
279
+ normalized = normalize_hard_assertion_tag(tag)
280
+ group = groups.setdefault(
281
+ normalized,
282
+ {
283
+ "passed": 0,
284
+ "total": 0,
285
+ "threshold": float(entry.get("threshold", 1.0)),
286
+ },
287
+ )
288
+ group["passed"] += int(entry.get("passed", 0))
289
+ group["total"] += int(entry.get("total", 0))
290
+ group["threshold"] = float(entry.get("threshold", group["threshold"]))
291
+ summary: dict[str, dict[str, Any]] = {}
292
+ for tag, entry in groups.items():
293
+ total = entry["total"]
294
+ rate = entry["passed"] / total if total else 0.0
295
+ threshold = entry["threshold"]
296
+ summary[tag] = {
297
+ "passed": entry["passed"],
298
+ "total": total,
299
+ "rate": rate,
300
+ "threshold": threshold,
301
+ "ok": rate >= threshold,
204
302
  }
303
+ return summary
205
304
 
206
305
 
207
306
  @dataclass
@@ -211,6 +310,7 @@ class CaseResult:
211
310
  runs: list[RunResult]
212
311
  pass_rate: float
213
312
  description: str = ""
313
+ tag_summary: dict[str, dict[str, Any]] = field(default_factory=dict)
214
314
 
215
315
  def usage(self) -> dict[str, int] | None:
216
316
  return combine_usage(run.usage() for run in self.runs)
@@ -222,6 +322,7 @@ class CaseResult:
222
322
  "passed": self.passed,
223
323
  "pass_rate": self.pass_rate,
224
324
  "usage": self.usage(),
325
+ "tag_summary": self.tag_summary,
225
326
  "runs": [run.to_dict() for run in self.runs],
226
327
  }
227
328
 
@@ -272,6 +373,7 @@ class YamaRunner:
272
373
  passed=passed_count == len(plan),
273
374
  runs=runs,
274
375
  pass_rate=passed_count / len(plan),
376
+ tag_summary=case_tag_summary(runs),
275
377
  )
276
378
  self._emit("case_end", result=result)
277
379
  return result
@@ -367,7 +469,8 @@ class YamaRunner:
367
469
  run_index=run_index,
368
470
  step=step_result,
369
471
  )
370
- passed = self._case_passed(case, steps)
472
+ tag_summary = tag_pass_summary(steps, case.outcome)
473
+ passed = self._case_passed(case, steps, tag_summary)
371
474
  run = RunResult(
372
475
  run_index=run_index,
373
476
  passed=passed,
@@ -378,6 +481,7 @@ class YamaRunner:
378
481
  artifact_dir=artifact_dir,
379
482
  label=spec.label,
380
483
  model=deepcopy(spec.model),
484
+ tag_summary=tag_summary,
381
485
  )
382
486
  except Exception as exc:
383
487
  run = RunResult(
@@ -392,6 +496,7 @@ class YamaRunner:
392
496
  artifact_dir=artifact_dir,
393
497
  label=spec.label,
394
498
  model=deepcopy(spec.model),
499
+ tag_summary={},
395
500
  )
396
501
  finally:
397
502
  if registry is not None:
@@ -620,8 +725,13 @@ class YamaRunner:
620
725
  output.extend(produced)
621
726
  return output
622
727
 
623
- def _case_passed(self, case: ResolvedCase, steps: list[StepResult]) -> bool:
624
- if not all(step.hard_pass for step in steps):
728
+ def _case_passed(
729
+ self,
730
+ case: ResolvedCase,
731
+ steps: list[StepResult],
732
+ tag_summary: dict[str, dict[str, Any]],
733
+ ) -> bool:
734
+ if not all(entry["ok"] for entry in tag_summary.values()):
625
735
  return False
626
736
  judge_results = [
627
737
  step.judge_result for step in steps if step.judge_result is not None
yama/thread_case.py ADDED
@@ -0,0 +1,401 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import shlex
6
+ import subprocess
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ import yaml
11
+ from copy import deepcopy
12
+ from typing import Any
13
+
14
+ _DEV_STAGING_BASE_URL = "https://dev-vidmuse-admin.sandaii.cn/admin/public"
15
+ _PROD_BASE_URL = "https://prod-vidmuse-admin.vidmuse.ai/admin/public"
16
+
17
+ _DEV_STAGING_DSL_SSH_HOST = "root@8.219.55.193"
18
+ _PROD_DSL_SSH_HOST = "1.1.1.1" # TODO: replace with the real prod SSH host
19
+
20
+ _DEV_STAGING_DSL_REMOTE_BASE_DIR = "/work/aion-runtime-v2-dev"
21
+ _PROD_DSL_REMOTE_BASE_DIR = "/work/aion-runtime-v2-prod"
22
+
23
+ _FIXED_OUTCOME: dict[str, Any] = {"require": {"hard_checks": "all_pass"}}
24
+
25
+
26
+ class ThreadCaseError(RuntimeError):
27
+ pass
28
+
29
+
30
+ def _is_prod(env: str) -> bool:
31
+ normalized = env.strip().lower()
32
+ if normalized in ("dev", "staging"):
33
+ return False
34
+ if normalized == "prod":
35
+ return True
36
+ raise ThreadCaseError(f"env={env!r} is invalid; expected one of: dev, staging, prod")
37
+
38
+
39
+ def resolve_base_url(env: str) -> str:
40
+ """Admin API base URL for `env` (dev/staging share one host)."""
41
+ return _PROD_BASE_URL if _is_prod(env) else _DEV_STAGING_BASE_URL
42
+
43
+
44
+ def resolve_dsl_ssh_host(env: str) -> str:
45
+ """SSH host to read dsl.json from for `env` (dev/staging share one host)."""
46
+ return _PROD_DSL_SSH_HOST if _is_prod(env) else _DEV_STAGING_DSL_SSH_HOST
47
+
48
+
49
+ def resolve_dsl_remote_base_dir(env: str) -> str:
50
+ """Remote workspace root to read dsl.json from for `env`."""
51
+ return _PROD_DSL_REMOTE_BASE_DIR if _is_prod(env) else _DEV_STAGING_DSL_REMOTE_BASE_DIR
52
+
53
+
54
+ def parse_record_id(record_id: str) -> tuple[str, str]:
55
+ """Split a composite `record_id` (`<thread_id>, <message_id>, ..., <completion_id>`)
56
+ into its first two comma-separated parts: (thread_id, message_id)."""
57
+ parts = [part.strip() for part in record_id.split(",")]
58
+ if len(parts) < 2 or not parts[0] or not parts[1]:
59
+ raise ThreadCaseError(
60
+ f"record_id {record_id!r} must have thread_id and message_id as its"
61
+ " first two comma-separated parts"
62
+ )
63
+ return parts[0], parts[1]
64
+
65
+
66
+ def fetch_model_records(
67
+ thread_id: str,
68
+ message_id: str,
69
+ token: str,
70
+ thread_type: str | None = None,
71
+ env: str = "dev",
72
+ ) -> dict[str, Any]:
73
+ base_url = resolve_base_url(env)
74
+ url = (
75
+ f"{base_url}/api/v1/threads/{thread_id}"
76
+ f"/messages/{message_id}/model-records"
77
+ )
78
+ if thread_type is not None:
79
+ url = f"{url}?thread_type={urllib.parse.quote(thread_type)}"
80
+ request = urllib.request.Request(
81
+ url, headers={"Authorization": f"Bearer {token}"}
82
+ )
83
+ try:
84
+ with urllib.request.urlopen(request, timeout=30) as response:
85
+ body = response.read()
86
+ except urllib.error.HTTPError as exc:
87
+ detail = _error_detail(exc.read())
88
+ raise ThreadCaseError(f"{exc.code} {exc.reason}: {detail}") from exc
89
+ except urllib.error.URLError as exc:
90
+ raise ThreadCaseError(f"request failed: {exc.reason}") from exc
91
+ try:
92
+ return json.loads(body)
93
+ except json.JSONDecodeError as exc:
94
+ raise ThreadCaseError(f"invalid JSON response: {exc}") from exc
95
+
96
+
97
+ def _error_detail(raw_body: bytes) -> str:
98
+ try:
99
+ parsed = json.loads(raw_body)
100
+ except json.JSONDecodeError:
101
+ return raw_body.decode("utf-8", errors="replace")[:500]
102
+ if isinstance(parsed, dict):
103
+ for key in ("detail", "message"):
104
+ if isinstance(parsed.get(key), str):
105
+ return parsed[key]
106
+ return json.dumps(parsed)[:500]
107
+
108
+
109
+ def select_record(records: list[dict[str, Any]], index: int) -> dict[str, Any]:
110
+ if not records:
111
+ raise ThreadCaseError("message has no model records")
112
+ try:
113
+ return records[index]
114
+ except IndexError:
115
+ raise ThreadCaseError(
116
+ f"record index {index} out of range for {len(records)} records"
117
+ ) from None
118
+
119
+
120
+ _DSL_FETCH_TIMEOUT_SECONDS = 30
121
+
122
+
123
+ def fetch_dsl_at_commit(
124
+ thread_id: str,
125
+ commit_id: str,
126
+ ssh_host: str,
127
+ remote_base_dir: str,
128
+ ) -> dict[str, Any]:
129
+ remote_dir = f"{remote_base_dir.rstrip('/')}/thread_{thread_id}/workspace"
130
+ remote_command = (
131
+ f"git -C {shlex.quote(remote_dir)} show {shlex.quote(f'{commit_id}:dsl.json')}"
132
+ )
133
+ try:
134
+ result = subprocess.run(
135
+ ["ssh", ssh_host, remote_command],
136
+ capture_output=True,
137
+ text=True,
138
+ timeout=_DSL_FETCH_TIMEOUT_SECONDS,
139
+ )
140
+ except FileNotFoundError as exc:
141
+ raise ThreadCaseError(f"ssh executable not found: {exc}") from exc
142
+ except subprocess.TimeoutExpired as exc:
143
+ raise ThreadCaseError(
144
+ f"ssh to {ssh_host} timed out after {_DSL_FETCH_TIMEOUT_SECONDS}s"
145
+ ) from exc
146
+
147
+ if result.returncode != 0:
148
+ detail = result.stderr.strip() or f"exit code {result.returncode}"
149
+ raise ThreadCaseError(f"git show failed on {ssh_host}: {detail}")
150
+
151
+ try:
152
+ data = json.loads(result.stdout)
153
+ except json.JSONDecodeError as exc:
154
+ raise ThreadCaseError(f"dsl.json at {commit_id} is not valid JSON: {exc}") from exc
155
+ if not isinstance(data, dict):
156
+ raise ThreadCaseError(
157
+ f"dsl.json at {commit_id} must be a JSON object, got {type(data).__name__}"
158
+ )
159
+ return data
160
+
161
+
162
+ _AVAILABLE_SKILLS_RE = re.compile(
163
+ r"<available_skills>(.*?)</available_skills>", re.DOTALL
164
+ )
165
+ _SKILL_NAME_RE = re.compile(r"<skill>\s*<name>(.*?)</name>", re.DOTALL)
166
+
167
+
168
+ def extract_skill_names(system_prompt_text: str | None) -> list[str]:
169
+ if not isinstance(system_prompt_text, str):
170
+ return []
171
+ block_match = _AVAILABLE_SKILLS_RE.search(system_prompt_text)
172
+ if not block_match:
173
+ return []
174
+ return [name.strip() for name in _SKILL_NAME_RE.findall(block_match.group(1))]
175
+
176
+
177
+ def build_case_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
178
+ result: list[dict[str, Any]] = []
179
+ for message in messages:
180
+ if message.get("role") == "system":
181
+ continue
182
+ resolved = deepcopy(message)
183
+ if resolved.get("content") is None:
184
+ resolved["content"] = ""
185
+ result.append(resolved)
186
+ return result
187
+
188
+
189
+ def build_case_tools(
190
+ tools: list[dict[str, Any]], skill_names: list[str]
191
+ ) -> list[dict[str, Any]]:
192
+ result: list[dict[str, Any]] = []
193
+ for tool in tools:
194
+ function = tool.get("function", {})
195
+ result.append(
196
+ {
197
+ "inline": {
198
+ "name": function.get("name"),
199
+ "description": function.get("description"),
200
+ "parameters": function.get("parameters"),
201
+ }
202
+ }
203
+ )
204
+ if skill_names:
205
+ result.append({"builtin": "skill"})
206
+ return result
207
+
208
+
209
+ _SYSTEM_REMINDER_RE = re.compile(
210
+ r"^<system-reminder>[\s\S]*</system-reminder>$"
211
+ )
212
+
213
+
214
+ def _step_identifier(step: Any) -> str | None:
215
+ if not isinstance(step, dict):
216
+ return None
217
+ for key in ("step", "id"):
218
+ value = step.get(key)
219
+ if isinstance(value, str) and value:
220
+ return value
221
+ return None
222
+
223
+
224
+ def current_workflow_step_id(dsl: dict[str, Any] | None) -> str | None:
225
+ if not isinstance(dsl, dict):
226
+ return None
227
+ workflow = dsl.get("workflow")
228
+ if not isinstance(workflow, dict):
229
+ return None
230
+ steps = workflow.get("steps")
231
+ if not isinstance(steps, list):
232
+ return None
233
+ for step in steps:
234
+ if isinstance(step, dict) and step.get("status") == "in_progress":
235
+ return _step_identifier(step)
236
+ for step in steps:
237
+ if not isinstance(step, dict):
238
+ continue
239
+ if step.get("status") not in {"completed", "skipped"}:
240
+ return _step_identifier(step)
241
+ return None
242
+
243
+
244
+ def is_system_reminder_message(message: dict[str, Any]) -> bool:
245
+ if message.get("role") != "user":
246
+ return False
247
+ content = message.get("content")
248
+ return isinstance(content, str) and bool(_SYSTEM_REMINDER_RE.match(content.strip()))
249
+
250
+
251
+ def find_step_user_turn(
252
+ messages: list[dict[str, Any]],
253
+ ) -> tuple[int, dict[str, Any]] | None:
254
+ for index in range(len(messages) - 1, -1, -1):
255
+ message = messages[index]
256
+ if message.get("role") == "user" and not is_system_reminder_message(message):
257
+ return index, message
258
+ return None
259
+
260
+
261
+ def build_message_inject_after_user(
262
+ messages: list[dict[str, Any]], user_index: int
263
+ ) -> list[dict[str, Any]]:
264
+ next_index = user_index + 1
265
+ if next_index >= len(messages):
266
+ return []
267
+ message = messages[next_index]
268
+ if not is_system_reminder_message(message):
269
+ return []
270
+ return [
271
+ {
272
+ "position": "after_user_message",
273
+ "message": {
274
+ "role": "user",
275
+ "content": message.get("content"),
276
+ },
277
+ }
278
+ ]
279
+
280
+
281
+ def _tool_call_names_from_message(message: Any) -> list[str]:
282
+ if not isinstance(message, dict):
283
+ return []
284
+ result: list[str] = []
285
+ for tool_call in message.get("tool_calls") or []:
286
+ if not isinstance(tool_call, dict):
287
+ continue
288
+ function = tool_call.get("function")
289
+ if not isinstance(function, dict):
290
+ continue
291
+ name = function.get("name")
292
+ if isinstance(name, str) and name:
293
+ result.append(name)
294
+ return result
295
+
296
+
297
+ def _response_message(response: Any) -> dict[str, Any] | None:
298
+ if not isinstance(response, dict):
299
+ return None
300
+ choices = response.get("choices") or []
301
+ if not choices or not isinstance(choices[0], dict):
302
+ return None
303
+ message = choices[0].get("message")
304
+ return message if isinstance(message, dict) else None
305
+
306
+
307
+ def collect_tool_called_assertions(
308
+ messages: list[dict[str, Any]],
309
+ user_index: int,
310
+ response: Any,
311
+ ) -> list[dict[str, Any]]:
312
+ counts: dict[str, int] = {}
313
+ for message in messages[user_index + 1 :]:
314
+ if message.get("role") != "assistant":
315
+ continue
316
+ for name in _tool_call_names_from_message(message):
317
+ counts[name] = counts.get(name, 0) + 1
318
+ response_message = _response_message(response)
319
+ for name in _tool_call_names_from_message(response_message):
320
+ counts[name] = counts.get(name, 0) + 1
321
+ return [
322
+ {"tool_called": {"name": name, "times": count}, "tag": "must_pass"}
323
+ for name, count in counts.items()
324
+ ]
325
+
326
+
327
+ def _build_step(
328
+ messages: list[dict[str, Any]],
329
+ response: Any,
330
+ step_id: str | None,
331
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
332
+ if step_id is None:
333
+ return build_case_messages(messages), []
334
+ user_turn = find_step_user_turn(messages)
335
+ if user_turn is None:
336
+ return build_case_messages(messages), []
337
+ user_index, user_message = user_turn
338
+ step: dict[str, Any] = {
339
+ "id": step_id,
340
+ "user": deepcopy(user_message.get("content", "")),
341
+ }
342
+ message_inject = build_message_inject_after_user(messages, user_index)
343
+ if message_inject:
344
+ step["message_inject"] = message_inject
345
+ hard = collect_tool_called_assertions(messages, user_index, response)
346
+ if hard:
347
+ step["assert"] = {"hard": hard}
348
+ return build_case_messages(messages[:user_index]), [step]
349
+
350
+
351
+ def build_case_dict(
352
+ record: dict[str, Any],
353
+ dsl: dict[str, Any] | None = None,
354
+ record_id: str | None = None,
355
+ ) -> dict[str, Any]:
356
+ request = record.get("request") or {}
357
+ messages = request.get("messages") or []
358
+ tools = (request.get("extra_body") or {}).get("tools") or []
359
+ system_text: str | None = None
360
+ for message in messages:
361
+ if message.get("role") == "system":
362
+ content = message.get("content")
363
+ system_text = content if isinstance(content, str) else None
364
+ break
365
+ skill_names = extract_skill_names(system_text)
366
+ step_id = current_workflow_step_id(dsl)
367
+ context_messages, steps = _build_step(messages, record.get("response"), step_id)
368
+
369
+ context: dict[str, Any] = {}
370
+ if skill_names:
371
+ context["skills"] = skill_names
372
+ case_tools = build_case_tools(tools, skill_names)
373
+ if case_tools:
374
+ context["tools"] = case_tools
375
+ context["messages"] = context_messages
376
+
377
+ case: dict[str, Any] = {}
378
+ if steps and record_id is not None:
379
+ case["description"] = f"{steps[0]['id']} {record_id}"
380
+ case["context"] = context
381
+ if dsl is not None:
382
+ case["mocks"] = {"state": {"dsl": dsl}}
383
+ case["steps"] = steps
384
+ case["outcome"] = deepcopy(_FIXED_OUTCOME)
385
+ return case
386
+
387
+
388
+ def build_response_preview(response: Any) -> str:
389
+ if not isinstance(response, dict):
390
+ return "<no response>"
391
+ choices = response.get("choices") or []
392
+ if not choices or not isinstance(choices[0], dict):
393
+ return "<no choices>"
394
+ message = choices[0].get("message") or {}
395
+ content_preview = (message.get("content") or "")[:200]
396
+ has_tool_calls = bool(message.get("tool_calls"))
397
+ return f"content={content_preview!r} tool_calls={has_tool_calls}"
398
+
399
+
400
+ def dump_case_yaml(case: dict[str, Any]) -> str:
401
+ return yaml.safe_dump(case, sort_keys=False, allow_unicode=True)