tempergraph 0.7.1__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.
Files changed (232) hide show
  1. tempergraph/__init__.py +8 -0
  2. tempergraph/__main__.py +5 -0
  3. tempergraph/api.py +428 -0
  4. tempergraph/audit/__init__.py +305 -0
  5. tempergraph/audit/catalog.py +342 -0
  6. tempergraph/audit/definition.py +387 -0
  7. tempergraph/audit/history.py +414 -0
  8. tempergraph/audit/history_rules.py +268 -0
  9. tempergraph/audit/history_rules_more.py +244 -0
  10. tempergraph/audit/host.py +270 -0
  11. tempergraph/audit/owned.py +96 -0
  12. tempergraph/audit/prompts.py +89 -0
  13. tempergraph/audit/report.py +248 -0
  14. tempergraph/audit/revisit.py +220 -0
  15. tempergraph/audit/surface.py +224 -0
  16. tempergraph/audit/text_health.py +176 -0
  17. tempergraph/audit/tools.py +391 -0
  18. tempergraph/author/__init__.py +2 -0
  19. tempergraph/author/blueprint.py +346 -0
  20. tempergraph/author/compare.py +122 -0
  21. tempergraph/author/criteria_lint.py +200 -0
  22. tempergraph/author/draw.py +112 -0
  23. tempergraph/author/inventory.py +210 -0
  24. tempergraph/author/literals.py +138 -0
  25. tempergraph/author/scaffold.py +568 -0
  26. tempergraph/author/session.py +439 -0
  27. tempergraph/author/trial.py +391 -0
  28. tempergraph/author/verify.py +353 -0
  29. tempergraph/builtin/__init__.py +1 -0
  30. tempergraph/builtin/upgrade.py +288 -0
  31. tempergraph/catalog.py +134 -0
  32. tempergraph/check_helpers.py +99 -0
  33. tempergraph/cli/__init__.py +1 -0
  34. tempergraph/cli/audit.py +190 -0
  35. tempergraph/cli/author.py +361 -0
  36. tempergraph/cli/improve.py +564 -0
  37. tempergraph/cli/improve_review.py +111 -0
  38. tempergraph/cli/install.py +35 -0
  39. tempergraph/cli/main.py +1261 -0
  40. tempergraph/cli/observe_cli.py +544 -0
  41. tempergraph/cli/outcome.py +77 -0
  42. tempergraph/cli/schedule_cli.py +1090 -0
  43. tempergraph/cli/upgrade.py +126 -0
  44. tempergraph/cli/workflows.py +96 -0
  45. tempergraph/compiler/__init__.py +6 -0
  46. tempergraph/compiler/graph.py +305 -0
  47. tempergraph/compiler/state.py +229 -0
  48. tempergraph/constants.py +72 -0
  49. tempergraph/contracts.py +1025 -0
  50. tempergraph/data/executor_compat.json +11 -0
  51. tempergraph/data/promotion.json +35 -0
  52. tempergraph/data/release.json +20 -0
  53. tempergraph/detach.py +65 -0
  54. tempergraph/docs.py +90 -0
  55. tempergraph/durability/__init__.py +2 -0
  56. tempergraph/durability/alias.py +66 -0
  57. tempergraph/durability/carry.py +591 -0
  58. tempergraph/durability/checkpoint.py +179 -0
  59. tempergraph/durability/control.py +109 -0
  60. tempergraph/durability/engine_file.py +301 -0
  61. tempergraph/durability/lock.py +138 -0
  62. tempergraph/durability/status.py +390 -0
  63. tempergraph/engine_identity.py +42 -0
  64. tempergraph/executor_compat.py +56 -0
  65. tempergraph/executors/__init__.py +4 -0
  66. tempergraph/executors/binding.py +91 -0
  67. tempergraph/executors/capabilities.py +95 -0
  68. tempergraph/executors/claude.py +603 -0
  69. tempergraph/executors/launcher.py +394 -0
  70. tempergraph/executors/mcpconfig.py +156 -0
  71. tempergraph/executors/mcpproxy.py +216 -0
  72. tempergraph/executors/preflight.py +196 -0
  73. tempergraph/executors/registry.py +71 -0
  74. tempergraph/executors/scripted.py +18 -0
  75. tempergraph/executors/session.py +107 -0
  76. tempergraph/executors/standins.py +118 -0
  77. tempergraph/executors/summary.py +110 -0
  78. tempergraph/executors/viewcatalog.py +27 -0
  79. tempergraph/git.py +403 -0
  80. tempergraph/identity.py +65 -0
  81. tempergraph/improve/__init__.py +5 -0
  82. tempergraph/improve/analysis.py +437 -0
  83. tempergraph/improve/artifact.py +477 -0
  84. tempergraph/improve/autonomy.py +192 -0
  85. tempergraph/improve/bindings.py +191 -0
  86. tempergraph/improve/calibration.py +1016 -0
  87. tempergraph/improve/causes.py +416 -0
  88. tempergraph/improve/child.py +651 -0
  89. tempergraph/improve/codehost.py +520 -0
  90. tempergraph/improve/digest.py +472 -0
  91. tempergraph/improve/escape.py +100 -0
  92. tempergraph/improve/filing.py +1047 -0
  93. tempergraph/improve/harvest.py +158 -0
  94. tempergraph/improve/issue_context.py +192 -0
  95. tempergraph/improve/lenses.py +204 -0
  96. tempergraph/improve/lessons.py +233 -0
  97. tempergraph/improve/loop_report.py +138 -0
  98. tempergraph/improve/loop_summary.py +85 -0
  99. tempergraph/improve/lost.py +119 -0
  100. tempergraph/improve/measure.py +121 -0
  101. tempergraph/improve/params.py +98 -0
  102. tempergraph/improve/pause_facts.py +134 -0
  103. tempergraph/improve/pr_later.py +186 -0
  104. tempergraph/improve/prebinding.py +130 -0
  105. tempergraph/improve/promotion.py +413 -0
  106. tempergraph/improve/proposals.py +934 -0
  107. tempergraph/improve/record.py +322 -0
  108. tempergraph/improve/release.py +89 -0
  109. tempergraph/improve/reliability.py +457 -0
  110. tempergraph/improve/repeat.py +115 -0
  111. tempergraph/improve/review.py +910 -0
  112. tempergraph/improve/suites.py +586 -0
  113. tempergraph/improve/trials.py +525 -0
  114. tempergraph/install/__init__.py +11 -0
  115. tempergraph/install/bootstrap.py +133 -0
  116. tempergraph/install/environment.py +173 -0
  117. tempergraph/install/launch.py +37 -0
  118. tempergraph/install/python.py +53 -0
  119. tempergraph/install/reconcile.py +52 -0
  120. tempergraph/install/selfcheck.py +29 -0
  121. tempergraph/install/shim.py +81 -0
  122. tempergraph/install/update.py +400 -0
  123. tempergraph/model/__init__.py +0 -0
  124. tempergraph/model/diagram.py +185 -0
  125. tempergraph/model/flow.py +324 -0
  126. tempergraph/model/prompt_lint.py +203 -0
  127. tempergraph/model/retire.py +52 -0
  128. tempergraph/model/subworkflow.py +274 -0
  129. tempergraph/model/text.py +67 -0
  130. tempergraph/model/validate.py +1158 -0
  131. tempergraph/observe/__init__.py +1 -0
  132. tempergraph/observe/attention.py +196 -0
  133. tempergraph/observe/detail.py +773 -0
  134. tempergraph/observe/forget.py +138 -0
  135. tempergraph/observe/hooks.py +272 -0
  136. tempergraph/observe/labels.py +95 -0
  137. tempergraph/observe/overlay.py +46 -0
  138. tempergraph/observe/report.py +402 -0
  139. tempergraph/observe/risk_report.py +110 -0
  140. tempergraph/observe/rows.py +444 -0
  141. tempergraph/observe/sinks.py +793 -0
  142. tempergraph/observe/supervision_cost.py +797 -0
  143. tempergraph/observe/supervision_report.py +295 -0
  144. tempergraph/observe/switch_report.py +140 -0
  145. tempergraph/package/__init__.py +2 -0
  146. tempergraph/package/change_report.py +116 -0
  147. tempergraph/package/changelog.py +263 -0
  148. tempergraph/package/docs_check.py +115 -0
  149. tempergraph/package/importer.py +90 -0
  150. tempergraph/package/inventory.py +111 -0
  151. tempergraph/package/loader.py +250 -0
  152. tempergraph/package/manifest.py +256 -0
  153. tempergraph/package/readiness.py +124 -0
  154. tempergraph/package/registry.py +383 -0
  155. tempergraph/package/rules.py +128 -0
  156. tempergraph/package/scan.py +65 -0
  157. tempergraph/package/selftest.py +348 -0
  158. tempergraph/package/stamp.py +213 -0
  159. tempergraph/package/transforms.py +481 -0
  160. tempergraph/package/upgrade.py +625 -0
  161. tempergraph/provenance.py +183 -0
  162. tempergraph/py.typed +0 -0
  163. tempergraph/release.py +17 -0
  164. tempergraph/render/__init__.py +0 -0
  165. tempergraph/render/output.py +72 -0
  166. tempergraph/render/prompt.py +166 -0
  167. tempergraph/render/template.py +86 -0
  168. tempergraph/run/__init__.py +2 -0
  169. tempergraph/run/asking.py +233 -0
  170. tempergraph/run/audit.py +63 -0
  171. tempergraph/run/check_worker.py +167 -0
  172. tempergraph/run/checks.py +517 -0
  173. tempergraph/run/commands.py +210 -0
  174. tempergraph/run/complexity.py +268 -0
  175. tempergraph/run/contest.py +76 -0
  176. tempergraph/run/council.py +368 -0
  177. tempergraph/run/council_run.py +527 -0
  178. tempergraph/run/events.py +279 -0
  179. tempergraph/run/finalize.py +132 -0
  180. tempergraph/run/gate.py +747 -0
  181. tempergraph/run/guard.py +89 -0
  182. tempergraph/run/judging.py +357 -0
  183. tempergraph/run/ladder.py +230 -0
  184. tempergraph/run/log.py +600 -0
  185. tempergraph/run/mapping.py +183 -0
  186. tempergraph/run/nodes.py +2304 -0
  187. tempergraph/run/outcome.py +255 -0
  188. tempergraph/run/outcome_record.py +292 -0
  189. tempergraph/run/outcome_trust.py +99 -0
  190. tempergraph/run/rerun.py +351 -0
  191. tempergraph/run/reserve.py +85 -0
  192. tempergraph/run/resources.py +76 -0
  193. tempergraph/run/risk.py +231 -0
  194. tempergraph/run/runner.py +1579 -0
  195. tempergraph/run/scriptcache.py +178 -0
  196. tempergraph/run/selfcheck.py +105 -0
  197. tempergraph/run/session_record.py +72 -0
  198. tempergraph/run/subrun.py +278 -0
  199. tempergraph/run/supervision.py +125 -0
  200. tempergraph/run/tool_access.py +101 -0
  201. tempergraph/schedule/__init__.py +25 -0
  202. tempergraph/schedule/credentials.py +167 -0
  203. tempergraph/schedule/echo.py +169 -0
  204. tempergraph/schedule/exact.py +275 -0
  205. tempergraph/schedule/export.py +164 -0
  206. tempergraph/schedule/launch.py +89 -0
  207. tempergraph/schedule/ledger.py +133 -0
  208. tempergraph/schedule/loop.py +176 -0
  209. tempergraph/schedule/model.py +440 -0
  210. tempergraph/schedule/policies.py +414 -0
  211. tempergraph/schedule/store.py +150 -0
  212. tempergraph/schedule/tick.py +377 -0
  213. tempergraph/schedule/token.py +81 -0
  214. tempergraph/schedule/triggers.py +210 -0
  215. tempergraph/schedule/words.py +423 -0
  216. tempergraph/security/__init__.py +0 -0
  217. tempergraph/security/launch.py +25 -0
  218. tempergraph/security/scrub.py +58 -0
  219. tempergraph/settings.py +950 -0
  220. tempergraph/store/__init__.py +0 -0
  221. tempergraph/store/codelog.py +73 -0
  222. tempergraph/store/layout.py +198 -0
  223. tempergraph/store/logs.py +325 -0
  224. tempergraph/store/manifest.py +99 -0
  225. tempergraph/store/migrate.py +188 -0
  226. tempergraph/workspace.py +874 -0
  227. tempergraph-0.7.1.dist-info/METADATA +70 -0
  228. tempergraph-0.7.1.dist-info/RECORD +232 -0
  229. tempergraph-0.7.1.dist-info/WHEEL +5 -0
  230. tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
  231. tempergraph-0.7.1.dist-info/top_level.txt +2 -0
  232. tempergraph_pytest_plugin.py +64 -0
@@ -0,0 +1,586 @@
1
+ """Eval suites for checks, steps and whole workflows (EVS-B8, EVS-B17, EVS-B18).
2
+
3
+ A suite's cases live in the package (`evals/checks/<unit>/`, `evals/steps/<unit>/<case>/`, `evals/cases.json`);
4
+ its results are rows of `evals/results.jsonl` under the state root, holding ids, statuses, counts and digests
5
+ only. Graders are trusted in a fixed order: code, then an accepted judge, then a person (ADR `eval-graders-in-a-fixed-order-of-trust`).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import dataclasses
11
+ import fnmatch
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import re
16
+ import shutil
17
+ import tempfile
18
+ import uuid
19
+ from collections import defaultdict
20
+ from collections.abc import Callable, Mapping, Sequence
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from tempergraph.contracts import InputDeclaration, Param, WorkflowSpec
25
+ from tempergraph.docs import append_jsonl
26
+ from tempergraph.store.layout import now_iso
27
+
28
+ KINDS = ("check", "judge", "step", "workflow")
29
+ ROLES = ("regression", "capability")
30
+ LIVE_KINDS = ("judge", "step", "workflow")
31
+ DEFAULT_CAP_USD = 20.0
32
+ STEP_TRIALS = 3
33
+ NEVER_PASSED_MIN = 5
34
+ GRADUATE_RUNS = 3
35
+ TEST_MARKER = "PYTEST_CURRENT_TEST"
36
+
37
+
38
+ class SuiteRefused(Exception):
39
+ pass
40
+
41
+
42
+ def results_path(root: Path) -> Path:
43
+ return root / "evals" / "results.jsonl"
44
+
45
+
46
+ def under_test() -> bool:
47
+ """The engine's test marker (EVS-B13, EVS-B12, EVS-B14): set by the test runner, lifted only for marked live checks."""
48
+ return TEST_MARKER in os.environ and os.environ.get("TEMPERGRAPH_LIVE") != "1"
49
+
50
+
51
+ def is_live(executor: Any) -> bool:
52
+ """A scripted stand-in says so itself; every other executor makes model calls."""
53
+ return not getattr(executor, "scripted", False)
54
+
55
+
56
+ def refuse_live(kind: str, executor: Any) -> None:
57
+ """EVS-AC3: no live suite starts under the test marker."""
58
+ if kind in LIVE_KINDS and is_live(executor) and under_test():
59
+ raise SuiteRefused(f"a live `{kind}` suite cannot start from the test suite or CI")
60
+
61
+
62
+ # -- assertions (EVS-B9, EVS-B2, EVS-B10 `expect`, EVS-B12 `end_state`) --------------------------------------------------------
63
+
64
+ def assertion_failures(asserts: Sequence[Mapping[str, Any]], workdir: Path,
65
+ changed: Sequence[str] = ()) -> list[str]:
66
+ """The assertions that do not hold, by index and kind; the texts they read are never returned."""
67
+ out = []
68
+ for i, a in enumerate(asserts):
69
+ path = workdir / str(a["path"]) if a.get("path") else None
70
+ if path is not None and not path.resolve().is_relative_to(workdir.resolve()):
71
+ out.append(f"{i}:outside_workspace")
72
+ continue
73
+ text = None
74
+ if path is not None and path.is_file():
75
+ text = path.read_text(encoding="utf-8", errors="replace")
76
+ if "changed_within" in a:
77
+ globs = [str(g) for g in a["changed_within"]]
78
+ if any(not any(fnmatch.fnmatchcase(p, g) for g in globs) for p in changed):
79
+ out.append(f"{i}:changed_within")
80
+ elif path is None:
81
+ out.append(f"{i}:unknown_assertion")
82
+ elif a.get("absent"):
83
+ if path.exists():
84
+ out.append(f"{i}:absent")
85
+ elif "pattern" in a:
86
+ if text is None or not re.search(str(a["pattern"]), text, re.M):
87
+ out.append(f"{i}:pattern")
88
+ elif "heading" in a:
89
+ want = str(a["heading"]).strip().lower()
90
+ heads = [ln.lstrip("#").strip().lower() for ln in (text or "").splitlines() if ln.startswith("#")]
91
+ if want not in heads:
92
+ out.append(f"{i}:heading")
93
+ elif not path.exists():
94
+ out.append(f"{i}:path")
95
+ return out
96
+
97
+
98
+ # -- cases ---------------------------------------------------------------------------------------------------
99
+
100
+ @dataclasses.dataclass(frozen=True, kw_only=True)
101
+ class StepCase:
102
+ unit: str
103
+ case_id: str
104
+ role: str = "regression"
105
+ inputs: Mapping[str, str] = dataclasses.field(default_factory=dict)
106
+ expect: tuple[Mapping[str, Any], ...] = ()
107
+ covered: bool = False # the assertions cover the case fully, so code decides a pass (EVS-B16)
108
+ trials: int = STEP_TRIALS
109
+ workspace: Path | None = None
110
+
111
+
112
+ def step_cases(spec: WorkflowSpec) -> tuple[list[StepCase], list[dict[str, str]]]:
113
+ """`evals/steps/<unit>/<case_id>/case.json` with an optional `workspace/`; invalid cases are listed."""
114
+ root = spec.package_root
115
+ out: list[StepCase] = []
116
+ bad: list[dict[str, str]] = []
117
+ if root is None:
118
+ return out, bad
119
+ for folder in sorted((root / "evals" / "steps").glob("*/*")):
120
+ unit, cid = folder.parent.name, folder.name
121
+ try:
122
+ doc = json.loads((folder / "case.json").read_text(encoding="utf-8"))
123
+ except (OSError, ValueError):
124
+ bad.append({"unit": unit, "case": cid, "reason": "case.json is missing or not JSON"})
125
+ continue
126
+ u = spec.units.get(unit)
127
+ if u is None or u.step is None or u.gate.judge is None:
128
+ bad.append({"unit": unit, "case": cid, "reason": "not a judged step of the workflow"})
129
+ continue
130
+ if doc.get("role", "regression") not in ROLES:
131
+ bad.append({"unit": unit, "case": cid, "reason": "role is regression or capability"})
132
+ continue
133
+ ws = folder / "workspace"
134
+ out.append(StepCase(unit=unit, case_id=str(doc.get("case_id") or cid), role=doc.get("role", "regression"),
135
+ inputs={str(k): str(v) for k, v in (doc.get("inputs") or {}).items()},
136
+ expect=tuple(doc.get("expect") or ()), covered=bool(doc.get("covered")),
137
+ trials=int(doc.get("trials") or STEP_TRIALS), workspace=ws if ws.is_dir() else None))
138
+ return out, bad
139
+
140
+
141
+ def workflow_cases(spec: WorkflowSpec) -> list[dict[str, Any]]:
142
+ """The reviewed entries of `evals/cases.json` (PRP-B17) with the fields of EVS-B12."""
143
+ from tempergraph.improve.trials import case_set
144
+
145
+ root = spec.package_root
146
+ reviewed = {c.case_id: c for c in case_set(spec)[0]}
147
+ try:
148
+ doc = json.loads((root / "evals" / "cases.json").read_text(encoding="utf-8")) if root else []
149
+ except (OSError, ValueError):
150
+ return []
151
+ rows = doc.get("cases") if isinstance(doc, dict) else doc
152
+ out = []
153
+ for r in rows or []:
154
+ cid = str(r.get("case_id") or r.get("id") or "") if isinstance(r, dict) else ""
155
+ if cid in reviewed:
156
+ default = 3 if spec.improvement_mode == "stable" and r.get("role", "regression") == "regression" else 1
157
+ out.append({"case": reviewed[cid], "role": r.get("role", "regression"),
158
+ "end_state": list(r.get("end_state") or []), "answers": list(r.get("answers") or []),
159
+ "covered": bool(r.get("covered")), "trials": int(r.get("trials") or default)})
160
+ return out
161
+
162
+
163
+ # -- bindings ------------------------------------------------------------------------------------------------
164
+
165
+ def _sha(data: Any) -> str:
166
+ return hashlib.sha256(json.dumps(data, sort_keys=True, default=str).encode()).hexdigest()[:16]
167
+
168
+
169
+ def step_binding(spec: WorkflowSpec, unit: str) -> str:
170
+ """The digest of what a step trial ran on: the step's executor, alias, effort and prompt, and its judge's
171
+ binding (EVS-B13, EVS-B14)."""
172
+ from tempergraph.improve import calibration
173
+ from tempergraph.model.text import TextUnreadable, load_text
174
+
175
+ st = spec.units[unit].step
176
+ assert st is not None
177
+ try:
178
+ prompt = load_text(spec, st.prompt)
179
+ except TextUnreadable:
180
+ prompt = ""
181
+ opts = st.session_options
182
+ return _sha({"executor": st.executor or spec.default_executor, "alias": st.model, "prompt": _sha(prompt),
183
+ "effort": opts.effort if opts else None, "ladder": list(st.effort_ladder),
184
+ "judge": calibration.current_binding(spec, unit)})
185
+
186
+
187
+ def workflow_binding(spec: WorkflowSpec) -> str:
188
+ return _sha({"version": spec.version, "units": {n: step_binding(spec, n) for n, u in spec.units.items()
189
+ if u.step is not None and u.gate.judge is not None}})
190
+
191
+
192
+ # -- grading (EVS-B16) --------------------------------------------------------------------------------------
193
+
194
+ def grade(*, finished: bool, failures: Sequence[str], covered: bool, failed_by_code: bool,
195
+ judge_state: str) -> tuple[str, str]:
196
+ """`(status, graded_by)` of one trial: code decides a failed assertion or check and a fully covered case,
197
+ an `accepted` judge decides the rest, and otherwise a person must."""
198
+ if failures or (not finished and failed_by_code):
199
+ return "failed", "code"
200
+ if finished and covered:
201
+ return "passed", "code"
202
+ if judge_state == "accepted":
203
+ return ("passed" if finished else "failed"), "judge"
204
+ return "needs_person", "person"
205
+
206
+
207
+ def _unit_end(recs: Sequence[Mapping[str, Any]], unit: str) -> tuple[int, bool]:
208
+ """A unit's attempts in the run and whether its last failure was decided by code (a check, a step that
209
+ did not end with a result) and not by the judge's blockers."""
210
+ attempts = sum(1 for r in recs if r.get("kind") == "attempt_start" and r.get("unit") == unit
211
+ and r.get("session_kind") in ("step", "retry"))
212
+ checks = [r for r in recs if r.get("kind") == "check" and r.get("unit") == unit]
213
+ judged = [r for r in recs if r.get("kind") == "judgement" and r.get("unit") == unit]
214
+ by_code = bool(checks and checks[-1].get("result") == "FAIL") or not judged
215
+ return attempts, by_code
216
+
217
+
218
+ # -- running -------------------------------------------------------------------------------------------------
219
+
220
+ def _row(run_id: str, kind: str, subject: str, case: str, role: str, trial: int, status: str, graded_by: str,
221
+ **more: Any) -> dict[str, Any]:
222
+ return {"schema_version": 1, "result_id": uuid.uuid4().hex[:12], "run_id": run_id, "at": now_iso(),
223
+ "kind": kind, "subject": subject, "case": case, "role": role, "trial": trial, "status": status,
224
+ "graded_by": graded_by, **more}
225
+
226
+
227
+ def run_checks(spec: WorkflowSpec, run_id: str) -> list[dict[str, Any]]:
228
+ """The `check` suite: every fixture with LF and CRLF line endings; a case passes when both give the
229
+ expected result and the findings name a criterion (EVS-B2). Model-free."""
230
+ from tempergraph.package import selftest
231
+
232
+ root = spec.package_root
233
+ if root is None:
234
+ return []
235
+ with tempfile.TemporaryDirectory() as tmp:
236
+ runs = selftest.fixture_runs(root, Path(tmp), spec)
237
+ cases: dict[tuple[str, str, str], list[dict[str, Any]]] = defaultdict(list)
238
+ out = []
239
+ for r in runs:
240
+ if "missing" in r:
241
+ out.append(_row(run_id, "check", r["unit"], "fixtures", "regression", 1, "invalid", "code",
242
+ reason="check_without_" + ("fail" if "must-fail" in r["missing"] else "pass") + "_case"))
243
+ else:
244
+ cases[(r["unit"], r["which"], r["fixture"])].append(r)
245
+ for (unit, which, fixture), both in sorted(cases.items()):
246
+ want = "PASS" if which == "must-pass" else "FAIL"
247
+ ok = all(r["result"] == want and r["named"] for r in both)
248
+ differs = len({r["result"] for r in both}) > 1
249
+ out.append(_row(run_id, "check", unit, f"{which}/{fixture}", "regression", 1,
250
+ "passed" if ok else "failed", "code", expected=want,
251
+ results=[r["result"] for r in both], line_endings_differ=differs))
252
+ return out
253
+
254
+
255
+ def _step_spec(spec: WorkflowSpec, case: StepCase) -> WorkflowSpec:
256
+ """The one step as its own workflow: its prompt, tools, check, judge and budgets unchanged; what earlier
257
+ units would have produced comes from the case's inputs."""
258
+ u = spec.units[case.unit]
259
+ gate = dataclasses.replace(u.gate, back_targets=(), fallback=None,
260
+ on_budget_spent="stop" if u.gate.on_budget_spent == "fallback" else u.gate.on_budget_spent)
261
+ names = list(dict.fromkeys(["request", *case.inputs]))
262
+ return dataclasses.replace(
263
+ spec, order=(case.unit,), units={case.unit: dataclasses.replace(u, gate=gate)}, outcome=None,
264
+ input=InputDeclaration(kind="any", parameters=tuple(Param(name=n) for n in names)), settings={}, profiles={})
265
+
266
+
267
+ def _git_repo(workspace: Path | None, into: Path) -> Path:
268
+ from tempergraph import git as gitmod
269
+
270
+ repo = into / "repo"
271
+ if workspace is not None:
272
+ shutil.copytree(workspace, repo)
273
+ else:
274
+ repo.mkdir(parents=True)
275
+ (repo / ".gitignore").write_text(".tempergraph/\n", encoding="utf-8") if not (repo / ".gitignore").exists() else None
276
+ gitmod.git(["init", "-q"], repo)
277
+ gitmod.git(["add", "-A"], repo)
278
+ gitmod.git(["-c", "user.email=evals@example.invalid", "-c", "user.name=evals", "commit", "-q", "--allow-empty",
279
+ "-m", "case base"], repo)
280
+ return repo
281
+
282
+
283
+ def run_step_trial(spec: WorkflowSpec, case: StepCase, registry: Any, trial: int, run_id: str, *,
284
+ judge_state: Callable[[str], str], settings: Callable[..., Any] | None = None) -> dict[str, Any]:
285
+ """One step trial in a fresh repository at the case's workspace: the step, its check and its judge exactly
286
+ as in a run (EVS-B9, EVS-B2, EVS-B10)."""
287
+ from tempergraph import git as gitmod
288
+ from tempergraph.constants import ExitCode
289
+ from tempergraph.improve.trials import _records, run_cost
290
+ from tempergraph.run.runner import RunSettings, start
291
+ from tempergraph.store.layout import state_root_path
292
+
293
+ sub = _step_spec(spec, case)
294
+ with tempfile.TemporaryDirectory() as tmp:
295
+ repo = _git_repo(case.workspace, Path(tmp))
296
+ rs = RunSettings(origin="trial", dry_run=True, workspace="in_place", sleep=lambda s: None,
297
+ caller={"kind": "pipeline", "decided_by": "engine", "caller_app": "evals"},
298
+ judge_state=judge_state)
299
+ if settings is not None:
300
+ rs = settings(rs)
301
+ task = re.sub(r"[^A-Za-z0-9._-]", "-", f"ev-{run_id[:8]}-{case.case_id}-{trial}")[:64]
302
+ out = start(sub, task, {"request": case.inputs.get("request", ""), **case.inputs}, repo, registry, rs)
303
+ recs = _records(state_root_path(repo), sub.name, task)
304
+ finished = out.exit_code is ExitCode.FINISHED
305
+ failures = assertion_failures(case.expect, repo, gitmod.changed_paths(repo)) if finished else []
306
+ attempts, by_code = _unit_end(recs, case.unit)
307
+ refused = not recs or out.reason in ("not_in_release", "preflight", "validation")
308
+ pauses = [r for r in recs if r.get("kind") == "pause"]
309
+ waits = not finished and bool(pauses) and pauses[-1].get("pause_kind") != "budget" # not a verdict on the work
310
+ status, by = ("invalid", "code") if refused else ("paused", "code") if waits else grade(
311
+ finished=finished, failures=failures, covered=case.covered, failed_by_code=by_code,
312
+ judge_state=judge_state(case.unit))
313
+ return _row(run_id, "step", case.unit, case.case_id, case.role, trial, status, by, attempts=attempts,
314
+ first_attempt=finished and attempts == 1, cost_usd=round(run_cost(recs), 6),
315
+ failures=failures, binding=step_binding(spec, case.unit),
316
+ **({"reason": out.reason} if refused else {}))
317
+
318
+
319
+ def run_workflow_trial(spec: WorkflowSpec, entry: Mapping[str, Any], repo: Path, registry: Any, trial: int,
320
+ run_id: str, *, judge_state: Callable[[str], str],
321
+ settings: Callable[..., Any] | None = None) -> dict[str, Any]:
322
+ """One whole run on a fixed case as a dry run, with the recorded answers applied to its pauses in order
323
+ (EVS-B12)."""
324
+ from tempergraph import git as gitmod
325
+ from tempergraph.constants import ExitCode
326
+ from tempergraph.improve.trials import ChildRuns, _records, run_cost
327
+ from tempergraph.run.runner import RunSettings, read_exit, resume
328
+ from tempergraph.store.layout import state_root_path
329
+
330
+ case = entry["case"]
331
+ binding = workflow_binding(spec)
332
+ try:
333
+ gitmod.git(["rev-parse", "--verify", "-q", f"{case.base}^{{commit}}"], repo)
334
+ except gitmod.GitError:
335
+ return _row(run_id, "workflow", spec.name, case.case_id, entry["role"], trial, "invalid", "code",
336
+ reason="base_missing", binding=binding)
337
+ runner = ChildRuns(repo=repo, registry=registry, settings=settings)
338
+ runner(spec, case, f"ev{trial}", run_id)
339
+ task = runner.tasks[-1]
340
+ root = state_root_path(repo)
341
+ caller = {"kind": "pipeline", "decided_by": "engine", "caller_app": "evals"}
342
+ answers = list(entry.get("answers") or [])
343
+ paused = False
344
+ while True:
345
+ ex = read_exit(root, spec.name, task) or {}
346
+ if ex.get("exit_code") != int(ExitCode.PAUSED):
347
+ break
348
+ if not answers:
349
+ paused = True
350
+ break
351
+ a = answers.pop(0)
352
+ rs = RunSettings(origin="trial", dry_run=True, caller=caller, relayed=True, sleep=lambda s: None)
353
+ if settings is not None:
354
+ rs = settings(rs)
355
+ got = resume(spec, task, repo, registry, decision=str(a.get("decision") or "proceed"),
356
+ feedback=a.get("feedback"), settings=rs)
357
+ if got.exit_code is ExitCode.USAGE:
358
+ paused = True
359
+ break
360
+ recs = _records(root, spec.name, task)
361
+ ex = read_exit(root, spec.name, task) or {}
362
+ finished = ex.get("exit_code") == int(ExitCode.FINISHED)
363
+ work = Path(str(next((r.get("path") for r in reversed(recs) if r.get("kind") == "workspace"
364
+ and r.get("path")), repo)))
365
+ failures = assertion_failures(entry["end_state"], work, gitmod.changed_paths(work, case.base)) \
366
+ if finished and work.is_dir() else []
367
+ more = {"cost_usd": round(run_cost(recs), 6), "failures": failures, "binding": binding, "task": task}
368
+ if paused:
369
+ return _row(run_id, "workflow", spec.name, case.case_id, entry["role"], trial, "paused", "code", **more)
370
+ last = next((str(r.get("unit")) for r in reversed(recs) if r.get("kind") == "judgement"), "")
371
+ grader = "outcome" if spec.outcome is not None else last
372
+ _, by_code = _unit_end(recs, last) if last else (0, True)
373
+ status, by = grade(finished=finished, failures=failures, covered=bool(entry.get("covered")),
374
+ failed_by_code=by_code, judge_state=judge_state(grader) if grader else "unscored")
375
+ return _row(run_id, "workflow", spec.name, case.case_id, entry["role"], trial, status, by, **more)
376
+
377
+
378
+ def run(spec: WorkflowSpec, kind: str, root: Path, *, registry: Any = None, repo: Path | None = None,
379
+ executor: Any = None, role: str | None = None, trials: int | None = None, cap_usd: float | None = None,
380
+ judge_state: Callable[[str], str] | None = None, settings: Callable[..., Any] | None = None,
381
+ write: bool = True) -> dict[str, Any]:
382
+ """`evals run`: the suites of one kind, recorded. A cap reached keeps the record `partial` (EVS-B6)."""
383
+ from tempergraph.improve import calibration
384
+
385
+ if kind not in KINDS:
386
+ raise SuiteRefused(f"unknown suite kind {kind!r} ({', '.join(KINDS)})")
387
+ if role is not None and role not in ROLES:
388
+ raise SuiteRefused(f"unknown role {role!r} ({', '.join(ROLES)})")
389
+ refuse_live(kind, executor)
390
+ run_id = uuid.uuid4().hex[:12]
391
+ cap = DEFAULT_CAP_USD if cap_usd is None else float(cap_usd)
392
+ state_of = judge_state or calibration.state_name_for(spec, root)
393
+ rows: list[dict[str, Any]] = []
394
+ invalid: list[dict[str, str]] = []
395
+ spent, partial = 0.0, False
396
+
397
+ def take(row: dict[str, Any]) -> None:
398
+ nonlocal spent
399
+ rows.append(row)
400
+ spent += float(row.get("cost_usd") or 0.0)
401
+
402
+ if kind == "check":
403
+ rows = [r for r in run_checks(spec, run_id) if role in (None, r["role"])]
404
+ elif kind == "step":
405
+ cases, invalid = step_cases(spec)
406
+ for c in cases:
407
+ if role not in (None, c.role):
408
+ continue
409
+ for t in range(1, (trials or c.trials) + 1):
410
+ if spent >= cap:
411
+ partial = True
412
+ break
413
+ take(run_step_trial(spec, c, registry, t, run_id, judge_state=state_of, settings=settings))
414
+ elif kind == "workflow":
415
+ if repo is None:
416
+ raise SuiteRefused("a workflow suite needs the repository its cases are based on")
417
+ for e in workflow_cases(spec):
418
+ if role not in (None, e["role"]):
419
+ continue
420
+ for t in range(1, (trials or e["trials"]) + 1):
421
+ if spent >= cap:
422
+ partial = True
423
+ break
424
+ take(run_workflow_trial(spec, e, repo, registry, t, run_id, judge_state=state_of,
425
+ settings=settings))
426
+ else: # judge: each judged gate's gold set, scored under the same cap (JCL)
427
+ for gate in calibration.judged_gates(spec):
428
+ for level in [None, *calibration.levels(spec, gate)[1:]]:
429
+ if spent >= cap:
430
+ partial = True
431
+ break
432
+ try:
433
+ rec = calibration.score(spec, gate, executor, cap_usd=cap - spent, level=level)
434
+ except calibration.CalibrationError as exc:
435
+ invalid.append({"unit": gate, "case": level or "", "reason": str(exc)[:120]})
436
+ continue
437
+ partial = partial or bool(rec.get("partial"))
438
+ name = calibration.state(spec, gate, level=level).state
439
+ take(_row(run_id, "judge", gate, level or "judge", "regression", 1,
440
+ "passed" if name in ("accepted", "provisional") else "failed", "gold",
441
+ score_id=rec["score_id"], state=name, cost_usd=rec["usage"]["cost_usd"]))
442
+ for r in rows:
443
+ r.update(partial=partial, workflow=spec.name)
444
+ if write:
445
+ for r in rows:
446
+ append_jsonl(results_path(root), r)
447
+ return {"schema_version": 1, "run_id": run_id, "workflow": spec.name, "kind": kind, "partial": partial,
448
+ "cost_usd": round(spent, 6), "cap_usd": cap, "results": rows, "invalid": invalid}
449
+
450
+
451
+ # -- reading, grading by a person, figures (EVS-B17, EVS-B18) --------------------------------------------------------
452
+
453
+ def read_results(root: Path) -> list[dict[str, Any]]:
454
+ try:
455
+ lines = results_path(root).read_text(encoding="utf-8").splitlines()
456
+ except OSError:
457
+ return []
458
+ rows: list[dict[str, Any]] = []
459
+ grades: dict[str, dict[str, Any]] = {}
460
+ for ln in lines:
461
+ try:
462
+ r = json.loads(ln)
463
+ except ValueError:
464
+ continue
465
+ if isinstance(r, dict) and r.get("record") == "grade":
466
+ grades[str(r.get("result_id"))] = r
467
+ elif isinstance(r, dict):
468
+ rows.append(r)
469
+ for r in rows:
470
+ g = grades.get(str(r.get("result_id")))
471
+ if g and r.get("status") == "needs_person":
472
+ r.update(status="passed" if g.get("passed") else "failed", graded_by="person", graded_at=g.get("at"))
473
+ return rows
474
+
475
+
476
+ def person_grade(root: Path, result_id: str, passed: bool, reason: str, by: str) -> dict[str, Any]:
477
+ """`evals grade`: a person's grade for a `needs_person` trial. No model call."""
478
+ row = next((r for r in read_results(root) if r.get("result_id") == result_id), None)
479
+ if row is None:
480
+ raise SuiteRefused(f"no eval result {result_id!r}")
481
+ if row.get("status") != "needs_person":
482
+ raise SuiteRefused(f"result {result_id} is {row.get('status')}, graded by {row.get('graded_by')}: "
483
+ "only a `needs_person` trial takes a person's grade")
484
+ if not reason.strip():
485
+ raise SuiteRefused("a grade needs a reason")
486
+ rec = {"schema_version": 1, "record": "grade", "result_id": result_id, "passed": bool(passed),
487
+ "reason": reason.strip()[:400], "by": by, "at": now_iso()}
488
+ append_jsonl(results_path(root), rec)
489
+ return rec
490
+
491
+
492
+ def figures(rows: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
493
+ """The figures of one suite run. A `needs_person`, `paused` or `invalid` trial counts in no rate."""
494
+ counted = [r for r in rows if r.get("status") in ("passed", "failed")]
495
+ passing = [r for r in counted if r["status"] == "passed"]
496
+ by_case: dict[str, list[Mapping[str, Any]]] = defaultdict(list)
497
+ for r in rows:
498
+ by_case[str(r.get("case"))].append(r)
499
+ full = [c for c, rs in by_case.items() if all(r.get("status") in ("passed", "failed") for r in rs)]
500
+ all_pass = [c for c in full if all(r["status"] == "passed" for r in by_case[c])]
501
+ cost = sum(float(r.get("cost_usd") or 0.0) for r in rows)
502
+ attempts = [int(r["attempts"]) for r in passing if r.get("attempts")]
503
+ n = len(counted)
504
+ return {"trials": len(rows), "counted": n, "cases": len(by_case),
505
+ "pass_at_1": round(len(passing) / n, 4) if n else None,
506
+ "pass_hat_k": round(len(all_pass) / len(full), 4) if full else None,
507
+ "first_attempt_pass": round(sum(1 for r in counted if r.get("first_attempt")) / n, 4)
508
+ if n and any("first_attempt" in r for r in counted) else None,
509
+ "mean_attempts": round(sum(attempts) / len(attempts), 4) if attempts else None,
510
+ "cost_per_pass": round(cost / len(passing), 6) if passing and cost else None,
511
+ "needs_person": sum(1 for r in rows if r.get("status") == "needs_person")}
512
+
513
+
514
+ def suite_status(role: str, rows: Sequence[Mapping[str, Any]]) -> str:
515
+ """A regression suite fails on one failing case and is `incomplete` while a trial waits on a person or a
516
+ pause (EVS-AC4); a capability suite is tracked as a rate and never fails."""
517
+ if role == "capability":
518
+ return "tracked"
519
+ if any(r.get("status") in ("failed", "invalid") for r in rows):
520
+ return "failed"
521
+ if any(r.get("status") in ("needs_person", "paused") for r in rows) or any(r.get("partial") for r in rows):
522
+ return "incomplete"
523
+ return "passed" if rows else "empty"
524
+
525
+
526
+ def _corrected(spec: WorkflowSpec, gate: str, raw: float | None) -> dict[str, Any]:
527
+ """A judge-graded pass rate with the judge's state and, where it allows, the corrected estimate."""
528
+ from tempergraph.improve import calibration
529
+
530
+ try:
531
+ return calibration.corrected(raw, calibration.state(spec, gate))
532
+ except (calibration.CalibrationError, OSError, ValueError):
533
+ return {"raw": raw, "label": "uncorrected (unscored)", "state": "unscored"}
534
+
535
+
536
+ def report(spec: WorkflowSpec, root: Path) -> dict[str, Any]:
537
+ """`evals report`: the latest run of each suite, the graduation list, stale and `needs_person` results,
538
+ and cases that never passed. No model call."""
539
+ rows = [r for r in read_results(root) if r.get("workflow") == spec.name]
540
+ current: dict[str, Callable[[str], str]] = {"step": lambda s: step_binding(spec, s) if s in spec.units else "",
541
+ "workflow": lambda s: workflow_binding(spec)}
542
+ suites: dict[tuple[str, str, str], list[dict[str, Any]]] = defaultdict(list)
543
+ for r in rows:
544
+ suites[(str(r.get("kind")), str(r.get("subject")), str(r.get("role")))].append(r)
545
+ out = []
546
+ graduation: list[dict[str, str]] = []
547
+ never: list[dict[str, Any]] = []
548
+ for (kind, subject, role), rs in sorted(suites.items()):
549
+ runs = list(dict.fromkeys(str(r.get("run_id")) for r in rs))
550
+ latest = [r for r in rs if r.get("run_id") == runs[-1]]
551
+ now = current[kind](subject) if kind in current else None
552
+ stale = now is not None and any(r.get("binding") != now for r in latest)
553
+ fig = figures(latest)
554
+ if kind == "step" and any(r.get("graded_by") == "judge" for r in latest): # EVS-B15
555
+ fig["judge_graded"] = _corrected(spec, subject, fig["pass_at_1"])
556
+ out.append({"kind": kind, "subject": subject, "role": role, "run_id": runs[-1],
557
+ "status": "stale" if stale else suite_status(role, latest), "figures": fig,
558
+ "cases": [{"case": r.get("case"), "trial": r.get("trial"), "status": r.get("status"),
559
+ "graded_by": r.get("graded_by"), "result_id": r.get("result_id")} for r in latest]})
560
+ by_case: dict[str, list[dict[str, Any]]] = defaultdict(list)
561
+ for r in rs:
562
+ by_case[str(r.get("case"))].append(r)
563
+ for case, crs in sorted(by_case.items()):
564
+ counted = [r for r in crs if r.get("status") in ("passed", "failed")]
565
+ if len(counted) >= NEVER_PASSED_MIN and not any(r["status"] == "passed" for r in counted):
566
+ never.append({"kind": kind, "subject": subject, "case": case, "trials": len(counted),
567
+ "advice": "check the case first"})
568
+ if role == "capability":
569
+ on_now = [r for r in crs if now is None or r.get("binding") == now]
570
+ last = list(dict.fromkeys(str(r.get("run_id")) for r in on_now))[-GRADUATE_RUNS:]
571
+ if len(last) == GRADUATE_RUNS and all(
572
+ all(r.get("status") == "passed" for r in on_now if r.get("run_id") == rid) for rid in last):
573
+ graduation.append({"kind": kind, "subject": subject, "case": case})
574
+ waiting = [{"result_id": r.get("result_id"), "kind": r.get("kind"), "subject": r.get("subject"),
575
+ "case": r.get("case"), "command": f"tempergraph evals grade {r.get('result_id')} --pass|--fail "
576
+ "--reason <text>"}
577
+ for r in rows if r.get("status") == "needs_person"]
578
+ return {"schema_version": 1, "workflow": spec.name, "suites": out, "graduation": graduation,
579
+ "needs_person": waiting, "never_passed": never}
580
+
581
+
582
+ def green_model_free(spec: WorkflowSpec) -> list[str]:
583
+ """EVS-B7: the failing cases of the model-free regression suites, for a stamp. A check with no fixture
584
+ has no case to fail; validation warns about it (EVS-B1)."""
585
+ return [f"{r['subject']} {r['case']}: expected {r.get('expected')}, got {'/'.join(r.get('results') or [])}"
586
+ for r in run_checks(spec, "stamp") if r["status"] == "failed"]