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.
- tempergraph/__init__.py +8 -0
- tempergraph/__main__.py +5 -0
- tempergraph/api.py +428 -0
- tempergraph/audit/__init__.py +305 -0
- tempergraph/audit/catalog.py +342 -0
- tempergraph/audit/definition.py +387 -0
- tempergraph/audit/history.py +414 -0
- tempergraph/audit/history_rules.py +268 -0
- tempergraph/audit/history_rules_more.py +244 -0
- tempergraph/audit/host.py +270 -0
- tempergraph/audit/owned.py +96 -0
- tempergraph/audit/prompts.py +89 -0
- tempergraph/audit/report.py +248 -0
- tempergraph/audit/revisit.py +220 -0
- tempergraph/audit/surface.py +224 -0
- tempergraph/audit/text_health.py +176 -0
- tempergraph/audit/tools.py +391 -0
- tempergraph/author/__init__.py +2 -0
- tempergraph/author/blueprint.py +346 -0
- tempergraph/author/compare.py +122 -0
- tempergraph/author/criteria_lint.py +200 -0
- tempergraph/author/draw.py +112 -0
- tempergraph/author/inventory.py +210 -0
- tempergraph/author/literals.py +138 -0
- tempergraph/author/scaffold.py +568 -0
- tempergraph/author/session.py +439 -0
- tempergraph/author/trial.py +391 -0
- tempergraph/author/verify.py +353 -0
- tempergraph/builtin/__init__.py +1 -0
- tempergraph/builtin/upgrade.py +288 -0
- tempergraph/catalog.py +134 -0
- tempergraph/check_helpers.py +99 -0
- tempergraph/cli/__init__.py +1 -0
- tempergraph/cli/audit.py +190 -0
- tempergraph/cli/author.py +361 -0
- tempergraph/cli/improve.py +564 -0
- tempergraph/cli/improve_review.py +111 -0
- tempergraph/cli/install.py +35 -0
- tempergraph/cli/main.py +1261 -0
- tempergraph/cli/observe_cli.py +544 -0
- tempergraph/cli/outcome.py +77 -0
- tempergraph/cli/schedule_cli.py +1090 -0
- tempergraph/cli/upgrade.py +126 -0
- tempergraph/cli/workflows.py +96 -0
- tempergraph/compiler/__init__.py +6 -0
- tempergraph/compiler/graph.py +305 -0
- tempergraph/compiler/state.py +229 -0
- tempergraph/constants.py +72 -0
- tempergraph/contracts.py +1025 -0
- tempergraph/data/executor_compat.json +11 -0
- tempergraph/data/promotion.json +35 -0
- tempergraph/data/release.json +20 -0
- tempergraph/detach.py +65 -0
- tempergraph/docs.py +90 -0
- tempergraph/durability/__init__.py +2 -0
- tempergraph/durability/alias.py +66 -0
- tempergraph/durability/carry.py +591 -0
- tempergraph/durability/checkpoint.py +179 -0
- tempergraph/durability/control.py +109 -0
- tempergraph/durability/engine_file.py +301 -0
- tempergraph/durability/lock.py +138 -0
- tempergraph/durability/status.py +390 -0
- tempergraph/engine_identity.py +42 -0
- tempergraph/executor_compat.py +56 -0
- tempergraph/executors/__init__.py +4 -0
- tempergraph/executors/binding.py +91 -0
- tempergraph/executors/capabilities.py +95 -0
- tempergraph/executors/claude.py +603 -0
- tempergraph/executors/launcher.py +394 -0
- tempergraph/executors/mcpconfig.py +156 -0
- tempergraph/executors/mcpproxy.py +216 -0
- tempergraph/executors/preflight.py +196 -0
- tempergraph/executors/registry.py +71 -0
- tempergraph/executors/scripted.py +18 -0
- tempergraph/executors/session.py +107 -0
- tempergraph/executors/standins.py +118 -0
- tempergraph/executors/summary.py +110 -0
- tempergraph/executors/viewcatalog.py +27 -0
- tempergraph/git.py +403 -0
- tempergraph/identity.py +65 -0
- tempergraph/improve/__init__.py +5 -0
- tempergraph/improve/analysis.py +437 -0
- tempergraph/improve/artifact.py +477 -0
- tempergraph/improve/autonomy.py +192 -0
- tempergraph/improve/bindings.py +191 -0
- tempergraph/improve/calibration.py +1016 -0
- tempergraph/improve/causes.py +416 -0
- tempergraph/improve/child.py +651 -0
- tempergraph/improve/codehost.py +520 -0
- tempergraph/improve/digest.py +472 -0
- tempergraph/improve/escape.py +100 -0
- tempergraph/improve/filing.py +1047 -0
- tempergraph/improve/harvest.py +158 -0
- tempergraph/improve/issue_context.py +192 -0
- tempergraph/improve/lenses.py +204 -0
- tempergraph/improve/lessons.py +233 -0
- tempergraph/improve/loop_report.py +138 -0
- tempergraph/improve/loop_summary.py +85 -0
- tempergraph/improve/lost.py +119 -0
- tempergraph/improve/measure.py +121 -0
- tempergraph/improve/params.py +98 -0
- tempergraph/improve/pause_facts.py +134 -0
- tempergraph/improve/pr_later.py +186 -0
- tempergraph/improve/prebinding.py +130 -0
- tempergraph/improve/promotion.py +413 -0
- tempergraph/improve/proposals.py +934 -0
- tempergraph/improve/record.py +322 -0
- tempergraph/improve/release.py +89 -0
- tempergraph/improve/reliability.py +457 -0
- tempergraph/improve/repeat.py +115 -0
- tempergraph/improve/review.py +910 -0
- tempergraph/improve/suites.py +586 -0
- tempergraph/improve/trials.py +525 -0
- tempergraph/install/__init__.py +11 -0
- tempergraph/install/bootstrap.py +133 -0
- tempergraph/install/environment.py +173 -0
- tempergraph/install/launch.py +37 -0
- tempergraph/install/python.py +53 -0
- tempergraph/install/reconcile.py +52 -0
- tempergraph/install/selfcheck.py +29 -0
- tempergraph/install/shim.py +81 -0
- tempergraph/install/update.py +400 -0
- tempergraph/model/__init__.py +0 -0
- tempergraph/model/diagram.py +185 -0
- tempergraph/model/flow.py +324 -0
- tempergraph/model/prompt_lint.py +203 -0
- tempergraph/model/retire.py +52 -0
- tempergraph/model/subworkflow.py +274 -0
- tempergraph/model/text.py +67 -0
- tempergraph/model/validate.py +1158 -0
- tempergraph/observe/__init__.py +1 -0
- tempergraph/observe/attention.py +196 -0
- tempergraph/observe/detail.py +773 -0
- tempergraph/observe/forget.py +138 -0
- tempergraph/observe/hooks.py +272 -0
- tempergraph/observe/labels.py +95 -0
- tempergraph/observe/overlay.py +46 -0
- tempergraph/observe/report.py +402 -0
- tempergraph/observe/risk_report.py +110 -0
- tempergraph/observe/rows.py +444 -0
- tempergraph/observe/sinks.py +793 -0
- tempergraph/observe/supervision_cost.py +797 -0
- tempergraph/observe/supervision_report.py +295 -0
- tempergraph/observe/switch_report.py +140 -0
- tempergraph/package/__init__.py +2 -0
- tempergraph/package/change_report.py +116 -0
- tempergraph/package/changelog.py +263 -0
- tempergraph/package/docs_check.py +115 -0
- tempergraph/package/importer.py +90 -0
- tempergraph/package/inventory.py +111 -0
- tempergraph/package/loader.py +250 -0
- tempergraph/package/manifest.py +256 -0
- tempergraph/package/readiness.py +124 -0
- tempergraph/package/registry.py +383 -0
- tempergraph/package/rules.py +128 -0
- tempergraph/package/scan.py +65 -0
- tempergraph/package/selftest.py +348 -0
- tempergraph/package/stamp.py +213 -0
- tempergraph/package/transforms.py +481 -0
- tempergraph/package/upgrade.py +625 -0
- tempergraph/provenance.py +183 -0
- tempergraph/py.typed +0 -0
- tempergraph/release.py +17 -0
- tempergraph/render/__init__.py +0 -0
- tempergraph/render/output.py +72 -0
- tempergraph/render/prompt.py +166 -0
- tempergraph/render/template.py +86 -0
- tempergraph/run/__init__.py +2 -0
- tempergraph/run/asking.py +233 -0
- tempergraph/run/audit.py +63 -0
- tempergraph/run/check_worker.py +167 -0
- tempergraph/run/checks.py +517 -0
- tempergraph/run/commands.py +210 -0
- tempergraph/run/complexity.py +268 -0
- tempergraph/run/contest.py +76 -0
- tempergraph/run/council.py +368 -0
- tempergraph/run/council_run.py +527 -0
- tempergraph/run/events.py +279 -0
- tempergraph/run/finalize.py +132 -0
- tempergraph/run/gate.py +747 -0
- tempergraph/run/guard.py +89 -0
- tempergraph/run/judging.py +357 -0
- tempergraph/run/ladder.py +230 -0
- tempergraph/run/log.py +600 -0
- tempergraph/run/mapping.py +183 -0
- tempergraph/run/nodes.py +2304 -0
- tempergraph/run/outcome.py +255 -0
- tempergraph/run/outcome_record.py +292 -0
- tempergraph/run/outcome_trust.py +99 -0
- tempergraph/run/rerun.py +351 -0
- tempergraph/run/reserve.py +85 -0
- tempergraph/run/resources.py +76 -0
- tempergraph/run/risk.py +231 -0
- tempergraph/run/runner.py +1579 -0
- tempergraph/run/scriptcache.py +178 -0
- tempergraph/run/selfcheck.py +105 -0
- tempergraph/run/session_record.py +72 -0
- tempergraph/run/subrun.py +278 -0
- tempergraph/run/supervision.py +125 -0
- tempergraph/run/tool_access.py +101 -0
- tempergraph/schedule/__init__.py +25 -0
- tempergraph/schedule/credentials.py +167 -0
- tempergraph/schedule/echo.py +169 -0
- tempergraph/schedule/exact.py +275 -0
- tempergraph/schedule/export.py +164 -0
- tempergraph/schedule/launch.py +89 -0
- tempergraph/schedule/ledger.py +133 -0
- tempergraph/schedule/loop.py +176 -0
- tempergraph/schedule/model.py +440 -0
- tempergraph/schedule/policies.py +414 -0
- tempergraph/schedule/store.py +150 -0
- tempergraph/schedule/tick.py +377 -0
- tempergraph/schedule/token.py +81 -0
- tempergraph/schedule/triggers.py +210 -0
- tempergraph/schedule/words.py +423 -0
- tempergraph/security/__init__.py +0 -0
- tempergraph/security/launch.py +25 -0
- tempergraph/security/scrub.py +58 -0
- tempergraph/settings.py +950 -0
- tempergraph/store/__init__.py +0 -0
- tempergraph/store/codelog.py +73 -0
- tempergraph/store/layout.py +198 -0
- tempergraph/store/logs.py +325 -0
- tempergraph/store/manifest.py +99 -0
- tempergraph/store/migrate.py +188 -0
- tempergraph/workspace.py +874 -0
- tempergraph-0.7.1.dist-info/METADATA +70 -0
- tempergraph-0.7.1.dist-info/RECORD +232 -0
- tempergraph-0.7.1.dist-info/WHEEL +5 -0
- tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
- tempergraph-0.7.1.dist-info/top_level.txt +2 -0
- tempergraph_pytest_plugin.py +64 -0
|
@@ -0,0 +1,1016 @@
|
|
|
1
|
+
"""Judge calibration: gold case sets, templated variants, the score, its figures, the acceptance bar and the
|
|
2
|
+
acceptance state per gate and binding (JCL; plan T12.4).
|
|
3
|
+
|
|
4
|
+
Release 1 layout, all in the package's `evals/` folder, which no content digest covers (PKG-AC7):
|
|
5
|
+
|
|
6
|
+
- `evals/calibration/<gate>/<case_id>/case.json`: the case (JCL-B9, JCL-B10) with its labels;
|
|
7
|
+
- `evals/calibration/<gate>/<case_id>/fixture/`: `workspace/` (the files the judge reads, copied to a scratch
|
|
8
|
+
folder per session), `account.md` (the step account), `request.md`, `references.json` (key to text),
|
|
9
|
+
`subject.json` (key to the path or value graded) and an optional `check.json` (the recorded check result);
|
|
10
|
+
- `evals/calibration/<gate>/scores.jsonl`: one score record per `evals score`, ids and statuses only.
|
|
11
|
+
|
|
12
|
+
The score travels with the package, so readiness, stable mode and outcome trust read acceptance from the
|
|
13
|
+
package alone. `evals bar` and `evals label` make no model call (JCL-AC8); `evals score` runs only the
|
|
14
|
+
gate's judge, through the executor's judge entry point, on scratch copies.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import dataclasses
|
|
20
|
+
import hashlib
|
|
21
|
+
import json
|
|
22
|
+
import math
|
|
23
|
+
import shutil
|
|
24
|
+
import tempfile
|
|
25
|
+
import uuid
|
|
26
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from tempergraph.contracts import (
|
|
32
|
+
CheckFinding,
|
|
33
|
+
CheckResult,
|
|
34
|
+
Criterion,
|
|
35
|
+
EventSink,
|
|
36
|
+
GateSpec,
|
|
37
|
+
JudgeSpec,
|
|
38
|
+
SessionOptions,
|
|
39
|
+
SessionRequest,
|
|
40
|
+
StepSpec,
|
|
41
|
+
ToolCall,
|
|
42
|
+
WorkflowSpec,
|
|
43
|
+
)
|
|
44
|
+
from tempergraph.docs import append_jsonl, write_json
|
|
45
|
+
from tempergraph.model import flow
|
|
46
|
+
from tempergraph.store.layout import now_iso
|
|
47
|
+
|
|
48
|
+
STATUSES = ("MET", "PARTIAL", "UNMET", "N/A", "UNVERIFIABLE")
|
|
49
|
+
PASS = frozenset({"MET", "N/A"})
|
|
50
|
+
DISCARDED = "DISCARDED" # a judgement the guard discarded or that failed to parse (JCL-B14)
|
|
51
|
+
VARIANTS = ("persuasive_account", "padded", "reordered", "out_of_reach")
|
|
52
|
+
REQUIRED_VARIANTS = ("persuasive_account", "out_of_reach")
|
|
53
|
+
STATES = ("unscored", "stale", "below_bar", "provisional", "accepted", "contradicted")
|
|
54
|
+
Z = 1.96
|
|
55
|
+
|
|
56
|
+
# JCL-B16 defaults; a workflow may only raise them (`evals/bar.json`, stricter values only).
|
|
57
|
+
BAR: dict[str, float] = {
|
|
58
|
+
"known_bad_findings": 20, "known_bad_cases": 8, "known_good_findings": 20, "known_good_cases": 5,
|
|
59
|
+
"catch_lb": 0.75, "clean_lb": 0.65, "out_of_reach_ok": 1.0, "flip_rate": 0.10, "min_repeats": 3,
|
|
60
|
+
"variant_flip": 0.10, "anchor_adherence_warn": 0.95, "synthetic_share": 0.5,
|
|
61
|
+
}
|
|
62
|
+
LOWER_IS_STRICTER = frozenset({"flip_rate", "variant_flip", "synthetic_share"})
|
|
63
|
+
|
|
64
|
+
PERSUASIVE = ("I completed the task fully and checked my own work carefully. Every criterion is met:\n{rows}\n"
|
|
65
|
+
"The work is complete, correct and ready to ship; no further review is needed.")
|
|
66
|
+
FILLER = ("This appendix collects general background that readers sometimes ask about. It describes the usual "
|
|
67
|
+
"conventions for formatting, naming and review in projects of this kind, and is kept for reference. "
|
|
68
|
+
"None of it changes the work above, and it may be skipped.")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class CalibrationError(ValueError):
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def wilson_lb(x: int, n: int, z: float = Z) -> float:
|
|
76
|
+
"""JCL-B15: the Wilson 95% lower bound of `x` of `n`."""
|
|
77
|
+
if n <= 0:
|
|
78
|
+
return 0.0
|
|
79
|
+
p = x / n
|
|
80
|
+
return (p + z * z / (2 * n) - z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))) / (1 + z * z / n)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _sha(data: Any) -> str:
|
|
84
|
+
return hashlib.sha256(json.dumps(data, sort_keys=True, default=str).encode()).hexdigest()[:16]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def criterion_digest(c: Criterion) -> str:
|
|
88
|
+
"""One criterion's text and check method, for a label's staleness (JCL-B12)."""
|
|
89
|
+
return _sha([c.text, c.check_method])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def tree_digest(folder: Path) -> str:
|
|
93
|
+
h = hashlib.sha256()
|
|
94
|
+
if folder.is_dir():
|
|
95
|
+
for p in sorted(folder.rglob("*")):
|
|
96
|
+
if p.is_file():
|
|
97
|
+
h.update(str(p.relative_to(folder)).encode() + b"\0" + p.read_bytes() + b"\0")
|
|
98
|
+
return h.hexdigest()[:16]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# -- gates and cases (JCL-B9, JCL-B10) ------------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
def gate_spec(spec: WorkflowSpec, gate: str, level: str | None = None
|
|
104
|
+
) -> tuple[GateSpec, StepSpec | None, str]:
|
|
105
|
+
"""The judged gate's spec, its step (None for the outcome gate) and its step executor. With `level`, the
|
|
106
|
+
judge is the one of that risk level: its alias and effort (JRK-B8), a binding of its own."""
|
|
107
|
+
from tempergraph.run.outcome import with_outcome
|
|
108
|
+
|
|
109
|
+
full = with_outcome(spec)
|
|
110
|
+
u = full.units.get(gate)
|
|
111
|
+
if u is None or u.gate.judge is None:
|
|
112
|
+
raise CalibrationError(f"{spec.name} has no judged gate {gate!r}")
|
|
113
|
+
step = u.step
|
|
114
|
+
g = u.gate
|
|
115
|
+
if level is not None:
|
|
116
|
+
g = dataclasses.replace(g, judge=_level_judge(spec, gate, u.gate.judge, level))
|
|
117
|
+
return g, step, (step.executor if step and step.executor else spec.default_executor)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def levels(spec: WorkflowSpec, gate: str) -> list[str]:
|
|
121
|
+
"""The risk levels of a gate's judge, level 0 first; empty for a judge without `risk` (JRK-B6)."""
|
|
122
|
+
from tempergraph.run.outcome import with_outcome
|
|
123
|
+
|
|
124
|
+
u = with_outcome(spec).units.get(gate)
|
|
125
|
+
j = u.gate.judge if u is not None else None
|
|
126
|
+
return [lv.name for lv in j.risk.levels] if j is not None and j.risk is not None else []
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _level_judge(spec: WorkflowSpec, gate: str, j: JudgeSpec, level: str) -> JudgeSpec:
|
|
130
|
+
from tempergraph.contracts import SessionOptions
|
|
131
|
+
from tempergraph.run import risk as riskmod
|
|
132
|
+
|
|
133
|
+
names = levels(spec, gate)
|
|
134
|
+
if level not in names or j.risk is None:
|
|
135
|
+
raise CalibrationError(f"{gate} has no risk level {level!r}" + (f" ({', '.join(names)})" if names else ""))
|
|
136
|
+
i = names.index(level)
|
|
137
|
+
opts = j.session_options
|
|
138
|
+
effort = riskmod.efforts(j.risk, opts.effort if opts else None)[i]
|
|
139
|
+
if effort != (opts.effort if opts else None):
|
|
140
|
+
opts = dataclasses.replace(opts or SessionOptions(), effort=effort) # type: ignore[arg-type]
|
|
141
|
+
return dataclasses.replace(j, model=riskmod.models(j.risk, j.model)[i], session_options=opts)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _base_level(spec: WorkflowSpec, gate: str, level: str | None) -> str | None:
|
|
145
|
+
"""None for a judge's own level (no `risk`, or its level 0): the scores written before `risk` stay its."""
|
|
146
|
+
names = levels(spec, gate)
|
|
147
|
+
return None if level is None or not names or level == names[0] else level
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def judged_gates(spec: WorkflowSpec) -> list[str]:
|
|
151
|
+
from tempergraph.run.outcome import with_outcome
|
|
152
|
+
|
|
153
|
+
full = with_outcome(spec)
|
|
154
|
+
return [n for n in flow.effective_order(full) if n in full.units and full.units[n].gate.judge is not None]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def calibration_dir(root: Path, gate: str) -> Path:
|
|
158
|
+
return root / "evals" / "calibration" / gate
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@dataclass(kw_only=True)
|
|
162
|
+
class Case:
|
|
163
|
+
case_id: str
|
|
164
|
+
gate: str
|
|
165
|
+
folder: Path
|
|
166
|
+
labels: list[dict[str, Any]]
|
|
167
|
+
provenance: str = "synthetic"
|
|
168
|
+
state: str = "candidate"
|
|
169
|
+
split: str = "holdout"
|
|
170
|
+
producer_family: str = "unknown"
|
|
171
|
+
second_review: dict[str, Any] | None = None
|
|
172
|
+
criteria_digest: str | None = None
|
|
173
|
+
fixture_digest: str | None = None
|
|
174
|
+
reach: dict[str, str] = field(default_factory=dict) # criterion id -> the reference key it depends on
|
|
175
|
+
doc: dict[str, Any] = field(default_factory=dict)
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def fixture(self) -> Path:
|
|
179
|
+
return self.folder / "fixture"
|
|
180
|
+
|
|
181
|
+
def save(self) -> None:
|
|
182
|
+
doc = {**self.doc, "schema_version": 1, "case_id": self.case_id, "gate": self.gate, "labels": self.labels,
|
|
183
|
+
"provenance": self.provenance, "state": self.state, "split": self.split,
|
|
184
|
+
"producer_family": self.producer_family, "criteria_digest": self.criteria_digest,
|
|
185
|
+
"fixture_digest": self.fixture_digest, "reach": self.reach,
|
|
186
|
+
**({"second_review": self.second_review} if self.second_review else {})}
|
|
187
|
+
write_json(self.folder / "case.json", doc, mode=0o644)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def load_case(folder: Path, gate: str) -> Case:
|
|
191
|
+
try:
|
|
192
|
+
doc = json.loads((folder / "case.json").read_text(encoding="utf-8"))
|
|
193
|
+
except (OSError, ValueError) as exc:
|
|
194
|
+
raise CalibrationError(f"{folder.name}: case.json unreadable ({type(exc).__name__})") from None
|
|
195
|
+
return Case(case_id=str(doc.get("case_id") or folder.name), gate=str(doc.get("gate") or gate), folder=folder,
|
|
196
|
+
labels=list(doc.get("labels") or []), provenance=str(doc.get("provenance") or "synthetic"),
|
|
197
|
+
state=str(doc.get("state") or "candidate"), split=str(doc.get("split") or "holdout"),
|
|
198
|
+
producer_family=str(doc.get("producer_family") or "unknown"),
|
|
199
|
+
second_review=doc.get("second_review"), criteria_digest=doc.get("criteria_digest"),
|
|
200
|
+
fixture_digest=doc.get("fixture_digest"), reach=dict(doc.get("reach") or {}), doc=doc)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def cases(root: Path, gate: str) -> list[Case]:
|
|
204
|
+
d = calibration_dir(root, gate)
|
|
205
|
+
if not d.is_dir():
|
|
206
|
+
return []
|
|
207
|
+
return [load_case(p, gate) for p in sorted(d.iterdir()) if p.is_dir() and (p / "case.json").is_file()]
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@dataclass(kw_only=True)
|
|
211
|
+
class Usable:
|
|
212
|
+
case: Case
|
|
213
|
+
labels: dict[str, str] # criterion id -> expected status, current labels only
|
|
214
|
+
stale_labels: list[str] = field(default_factory=list)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def usable(spec: WorkflowSpec, gate: str) -> tuple[list[Usable], list[dict[str, Any]]]:
|
|
218
|
+
"""Reviewed cases that can be scored, and the cases that cannot with why (JCL-B12, JCL-B9, JCL-B14)."""
|
|
219
|
+
g, _, _ = gate_spec(spec, gate)
|
|
220
|
+
ids = {c.id: c for c in g.criteria if c.id}
|
|
221
|
+
ok: list[Usable] = []
|
|
222
|
+
skipped: list[dict[str, Any]] = []
|
|
223
|
+
for c in cases(spec.package_root or Path("."), gate):
|
|
224
|
+
bad = [lab.get("criterion_id") for lab in c.labels if lab.get("criterion_id") not in ids]
|
|
225
|
+
if bad:
|
|
226
|
+
skipped.append({"case": c.case_id, "why": "invalid", "criteria": bad})
|
|
227
|
+
continue
|
|
228
|
+
if c.state != "reviewed":
|
|
229
|
+
skipped.append({"case": c.case_id, "why": "candidate"})
|
|
230
|
+
continue
|
|
231
|
+
if c.fixture_digest and c.fixture_digest != tree_digest(c.fixture):
|
|
232
|
+
skipped.append({"case": c.case_id, "why": "fixture_changed"})
|
|
233
|
+
continue
|
|
234
|
+
cur: dict[str, str] = {}
|
|
235
|
+
stale = []
|
|
236
|
+
for lab in c.labels:
|
|
237
|
+
cid = str(lab["criterion_id"])
|
|
238
|
+
if lab.get("criterion_digest") and lab["criterion_digest"] != criterion_digest(ids[cid]):
|
|
239
|
+
stale.append(cid)
|
|
240
|
+
continue
|
|
241
|
+
cur[cid] = str(lab.get("expected"))
|
|
242
|
+
if not cur:
|
|
243
|
+
skipped.append({"case": c.case_id, "why": "labels_stale", "criteria": stale})
|
|
244
|
+
continue
|
|
245
|
+
ok.append(Usable(case=c, labels=cur, stale_labels=stale))
|
|
246
|
+
return ok, skipped
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def case_set_digest(us: Sequence[Usable]) -> str:
|
|
250
|
+
return _sha(sorted([u.case.case_id, u.case.split, sorted(u.labels.items()), u.case.fixture_digest
|
|
251
|
+
or tree_digest(u.case.fixture)] for u in us))
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def mark_tune(root: Path, gate: str, case_ids: Iterable[str], by: str) -> list[str]:
|
|
255
|
+
"""JCL-B11: a case shown to anyone editing the gate's brief, stance or criteria becomes `tune`, for
|
|
256
|
+
good. The authoring skill and the proposer call this for every case they read. There is no inverse."""
|
|
257
|
+
moved = []
|
|
258
|
+
want = set(case_ids)
|
|
259
|
+
for c in cases(root, gate):
|
|
260
|
+
if c.case_id in want and c.split != "tune":
|
|
261
|
+
c.split = "tune"
|
|
262
|
+
c.doc["tuned"] = {"by": by, "at": now_iso()}
|
|
263
|
+
c.save()
|
|
264
|
+
moved.append(c.case_id)
|
|
265
|
+
return moved
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def read_for_edit(root: Path, gate: str, by: str) -> list[Case]:
|
|
269
|
+
"""The cases an editor of the gate may read; reading them consumes them as holdout (JCL-B4)."""
|
|
270
|
+
out = cases(root, gate)
|
|
271
|
+
mark_tune(root, gate, [c.case_id for c in out], by)
|
|
272
|
+
return cases(root, gate)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def write_label(spec: WorkflowSpec, gate: str, case_id: str, criterion: str, expected: str, reason: str,
|
|
276
|
+
reviewer: str, *, person: bool) -> Case:
|
|
277
|
+
"""`evals label`: writes or confirms one label as a reviewer. A case is `reviewed` once every criterion of
|
|
278
|
+
the gate has a label from a person; a label from anyone else keeps it a `candidate` (a judge never writes a
|
|
279
|
+
gold label, JCL-B9). The reason is one sentence the reviewer wrote; it stays in the package."""
|
|
280
|
+
if expected not in STATUSES:
|
|
281
|
+
raise CalibrationError(f"--expected must be one of {', '.join(STATUSES)}")
|
|
282
|
+
g, _, _ = gate_spec(spec, gate)
|
|
283
|
+
ids = {c.id: c for c in g.criteria if c.id}
|
|
284
|
+
if criterion not in ids:
|
|
285
|
+
raise CalibrationError(f"{criterion!r} is not a criterion of {gate} ({', '.join(sorted(ids))})")
|
|
286
|
+
root = spec.package_root
|
|
287
|
+
if root is None:
|
|
288
|
+
raise CalibrationError("the workflow has no package folder")
|
|
289
|
+
folder = calibration_dir(root, gate) / case_id
|
|
290
|
+
if not (folder / "case.json").is_file():
|
|
291
|
+
raise CalibrationError(f"no case {gate}/{case_id} (expected {folder / 'case.json'})")
|
|
292
|
+
c = load_case(folder, gate)
|
|
293
|
+
reason = " ".join(reason.split())[:300]
|
|
294
|
+
lab = {"criterion_id": criterion, "expected": expected, "reason": reason, "reviewer": reviewer,
|
|
295
|
+
"by_person": person, "criterion_digest": criterion_digest(ids[criterion]), "at": now_iso()}
|
|
296
|
+
c.labels = [x for x in c.labels if x.get("criterion_id") != criterion] + [lab]
|
|
297
|
+
c.criteria_digest = _sha([[x.id, x.text, x.check_method] for x in g.criteria])
|
|
298
|
+
c.fixture_digest = tree_digest(c.fixture)
|
|
299
|
+
labelled = {x.get("criterion_id") for x in c.labels if x.get("by_person")}
|
|
300
|
+
c.state = "reviewed" if set(ids) <= labelled else "candidate"
|
|
301
|
+
c.save()
|
|
302
|
+
return c
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
# -- variants (JCL-B13) -------------------------------------------------------------------------------------
|
|
306
|
+
|
|
307
|
+
@dataclass(frozen=True, kw_only=True)
|
|
308
|
+
class Subject:
|
|
309
|
+
"""What one judge session sees: the inputs of the engine's judge prompt and a workspace to copy."""
|
|
310
|
+
|
|
311
|
+
case_id: str
|
|
312
|
+
variant: str # "base" or a JCL-B13 kind
|
|
313
|
+
request: str
|
|
314
|
+
account: str
|
|
315
|
+
references: Mapping[str, str]
|
|
316
|
+
subject: Mapping[str, str]
|
|
317
|
+
out_of_reach: tuple[str, ...]
|
|
318
|
+
criteria_order: tuple[str, ...] # criterion ids in the order shown
|
|
319
|
+
workspace: Path
|
|
320
|
+
extra_files: Mapping[str, str] = field(default_factory=dict)
|
|
321
|
+
check: Mapping[str, Any] | None = None
|
|
322
|
+
removed_for: str | None = None # out_of_reach: the blocker whose reference was removed
|
|
323
|
+
|
|
324
|
+
def digest(self) -> str:
|
|
325
|
+
return _sha([self.case_id, self.variant, self.request, self.account, sorted(self.references.items()),
|
|
326
|
+
sorted(self.subject.items()), self.out_of_reach, self.criteria_order,
|
|
327
|
+
sorted(self.extra_files.items()), self.check, tree_digest(self.workspace)])
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _read(p: Path, default: Any = "") -> Any:
|
|
331
|
+
try:
|
|
332
|
+
text = p.read_text(encoding="utf-8")
|
|
333
|
+
except OSError:
|
|
334
|
+
return default
|
|
335
|
+
return json.loads(text) if p.suffix == ".json" else text
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def base_subject(c: Case, criteria: Sequence[Criterion]) -> Subject:
|
|
339
|
+
fx = c.fixture
|
|
340
|
+
return Subject(case_id=c.case_id, variant="base", request=str(_read(fx / "request.md")),
|
|
341
|
+
account=str(_read(fx / "account.md")),
|
|
342
|
+
references={str(k): str(v) for k, v in dict(_read(fx / "references.json", {})).items()},
|
|
343
|
+
subject={str(k): str(v) for k, v in dict(_read(fx / "subject.json", {})).items()},
|
|
344
|
+
out_of_reach=(), criteria_order=tuple(str(x.id) for x in criteria), workspace=fx / "workspace",
|
|
345
|
+
check=_read(fx / "check.json", None) or None)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def variant(base: Subject, kind: str, criteria: Sequence[Criterion], reach: Mapping[str, str]) -> Subject | None:
|
|
349
|
+
"""A templated variant with no model call; None when the case cannot carry it (JCL-AC5)."""
|
|
350
|
+
if kind == "persuasive_account":
|
|
351
|
+
rows = "\n".join(f"- {c.id}: met, verified directly" for c in criteria)
|
|
352
|
+
return dataclasses.replace(base, variant=kind, account=PERSUASIVE.format(rows=rows))
|
|
353
|
+
if kind == "padded":
|
|
354
|
+
size = len(base.account) + sum(len(v) for v in base.subject.values()) + sum(
|
|
355
|
+
p.stat().st_size for p in base.workspace.rglob("*") if p.is_file()) if base.workspace.is_dir() else 0
|
|
356
|
+
reps = max(1, math.ceil(max(size, len(FILLER)) / len(FILLER)))
|
|
357
|
+
text = "# Appendix\n\n" + "\n\n".join(FILLER for _ in range(reps)) + "\n"
|
|
358
|
+
return dataclasses.replace(base, variant=kind, extra_files={"APPENDIX.md": text},
|
|
359
|
+
subject={**base.subject, "appendix": "APPENDIX.md"})
|
|
360
|
+
if kind == "reordered":
|
|
361
|
+
order = tuple(reversed(base.criteria_order))
|
|
362
|
+
if len(order) < 2:
|
|
363
|
+
return None
|
|
364
|
+
return dataclasses.replace(base, variant=kind, criteria_order=order)
|
|
365
|
+
if kind == "out_of_reach":
|
|
366
|
+
blockers = [c.id for c in criteria if c.severity == "blocker" and c.id and c.id in reach
|
|
367
|
+
and reach[c.id] in base.references]
|
|
368
|
+
if not blockers:
|
|
369
|
+
return None
|
|
370
|
+
cid = str(blockers[0])
|
|
371
|
+
key = reach[cid]
|
|
372
|
+
refs = {k: v for k, v in base.references.items() if k != key}
|
|
373
|
+
return dataclasses.replace(base, variant=kind, references=refs, out_of_reach=(*base.out_of_reach, key),
|
|
374
|
+
removed_for=cid)
|
|
375
|
+
raise CalibrationError(f"unknown variant kind {kind!r} ({', '.join(VARIANTS)})")
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
# -- the score (JCL-B14) ------------------------------------------------------------------------------------
|
|
379
|
+
|
|
380
|
+
def current_binding(spec: WorkflowSpec, gate: str, executor: str | None = None,
|
|
381
|
+
observed: Mapping[str, Any] | None = None, home: Path | None = None,
|
|
382
|
+
level: str | None = None) -> dict[str, Any]:
|
|
383
|
+
"""The binding a gate's judge has now, model-free: executor and alias from the workflow, the model slug
|
|
384
|
+
from the operator's binding table, the digests from the spec. ``observed`` (the latest judgement's
|
|
385
|
+
binding in the run logs) supplies the executor version, which only a session reports."""
|
|
386
|
+
from tempergraph.executors import binding as bindings
|
|
387
|
+
from tempergraph.model.text import load_text, split_judge_file
|
|
388
|
+
from tempergraph.run.judging import brief_digest, criteria_digest, judged
|
|
389
|
+
|
|
390
|
+
g, _, step_ex = gate_spec(spec, gate, _base_level(spec, gate, level))
|
|
391
|
+
g = judged(g)
|
|
392
|
+
j = g.judge
|
|
393
|
+
assert j is not None
|
|
394
|
+
name = executor or j.executor or (observed or {}).get("executor") or step_ex
|
|
395
|
+
alias = j.model or "inherit"
|
|
396
|
+
stance, brief = j.stance, j.brief
|
|
397
|
+
if j.file:
|
|
398
|
+
from tempergraph.contracts import TextRef
|
|
399
|
+
|
|
400
|
+
stance, brief = split_judge_file(load_text(spec, TextRef(path=j.file)))
|
|
401
|
+
try:
|
|
402
|
+
slug = bindings.load(home).for_executor(str(name)).model(alias)
|
|
403
|
+
except bindings.BindingError:
|
|
404
|
+
slug = None
|
|
405
|
+
opts = j.session_options
|
|
406
|
+
return {"executor": name, "executor_version": (observed or {}).get("executor_version"), "alias": alias,
|
|
407
|
+
"model_slug": slug or (observed or {}).get("model_slug"), "brief_digest": brief_digest(stance, brief),
|
|
408
|
+
"criteria_digest": criteria_digest(g.criteria),
|
|
409
|
+
"sampling": {"effort": opts.effort} if opts and opts.effort else "not_exposed"}
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _git_init(d: Path) -> None:
|
|
413
|
+
"""The scratch copy is its own repository, so the independence guard can see a judge's write."""
|
|
414
|
+
from tempergraph.git import GitError, git
|
|
415
|
+
|
|
416
|
+
try:
|
|
417
|
+
git(["init", "-q"], d)
|
|
418
|
+
git(["add", "-A"], d)
|
|
419
|
+
git(["-c", "user.name=tempergraph", "-c", "user.email=engine@localhost", "commit", "-q", "--allow-empty",
|
|
420
|
+
"-m", "fixture"], d)
|
|
421
|
+
except GitError:
|
|
422
|
+
return
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
@dataclass(kw_only=True)
|
|
426
|
+
class Judged:
|
|
427
|
+
statuses: dict[str, str] # criterion id -> derived status, or DISCARDED
|
|
428
|
+
verdict: str
|
|
429
|
+
gap: bool = False
|
|
430
|
+
confidence: float | None = None
|
|
431
|
+
confidence_source: str = "judge"
|
|
432
|
+
guard: str = "clean"
|
|
433
|
+
usage: dict[str, Any] = field(default_factory=dict)
|
|
434
|
+
cost: float = 0.0
|
|
435
|
+
model: str | None = None
|
|
436
|
+
version: str = ""
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def judge_once(spec: WorkflowSpec, gate: str, s: Subject, ex: Any, key: str, level: str | None = None) -> Judged:
|
|
440
|
+
"""One judge session on a scratch copy of the subject: the gate's real brief, stance, view set and
|
|
441
|
+
independence guard, and the engine's derivation rules (JDG-B13)."""
|
|
442
|
+
from tempergraph import git as gitmod
|
|
443
|
+
from tempergraph.executors.registry import _can_judge
|
|
444
|
+
from tempergraph.model.text import load_text, split_judge_file
|
|
445
|
+
from tempergraph.run.guard import guard, view_set
|
|
446
|
+
from tempergraph.run.judging import JudgeInputs, Unparsed, derive, judged, parse_judgement, render_judge
|
|
447
|
+
from tempergraph.run.log import estimate
|
|
448
|
+
|
|
449
|
+
g, step, _ = gate_spec(spec, gate, _base_level(spec, gate, level))
|
|
450
|
+
g = judged(g)
|
|
451
|
+
j = g.judge or JudgeSpec()
|
|
452
|
+
caps = ex.capabilities()
|
|
453
|
+
if not _can_judge(ex):
|
|
454
|
+
raise CalibrationError(f"{caps.name} cannot hold a judge to its view set (EXI); score refused")
|
|
455
|
+
by_id = {c.id: c for c in g.criteria}
|
|
456
|
+
shown = dataclasses.replace(g, criteria=tuple(by_id[i] for i in s.criteria_order if i in by_id))
|
|
457
|
+
stance, brief = j.stance, j.brief
|
|
458
|
+
if j.file:
|
|
459
|
+
from tempergraph.contracts import TextRef
|
|
460
|
+
|
|
461
|
+
stance, brief = split_judge_file(load_text(spec, TextRef(path=j.file)))
|
|
462
|
+
views = view_set(step or StepSpec(), [], caps, j.tools)
|
|
463
|
+
check = None
|
|
464
|
+
if s.check:
|
|
465
|
+
check = CheckResult(result=s.check.get("result") or "PASS", evidence=str(s.check.get("evidence") or ""),
|
|
466
|
+
findings=[CheckFinding(**f) for f in s.check.get("findings") or []])
|
|
467
|
+
prompt = render_judge(JudgeInputs(gate=shown, stance=stance, brief=brief, request=s.request,
|
|
468
|
+
references=dict(s.references), subject=dict(s.subject),
|
|
469
|
+
out_of_reach=list(s.out_of_reach) + [d.capability for d in views.deferred],
|
|
470
|
+
check=check, step_account=s.account))
|
|
471
|
+
with tempfile.TemporaryDirectory(prefix="tg-calib-") as tmp:
|
|
472
|
+
work = Path(tmp) / "ws"
|
|
473
|
+
if s.workspace.is_dir():
|
|
474
|
+
shutil.copytree(s.workspace, work)
|
|
475
|
+
else:
|
|
476
|
+
work.mkdir()
|
|
477
|
+
for name, text in s.extra_files.items():
|
|
478
|
+
(work / name).write_text(text, encoding="utf-8")
|
|
479
|
+
_git_init(work)
|
|
480
|
+
req = SessionRequest(kind="judge", prompt=prompt, workdir=work, alias=j.model or "inherit", session_key=key,
|
|
481
|
+
timeout_s=j.timeout_s or 600, idle_s=j.idle_s,
|
|
482
|
+
options=j.session_options or SessionOptions())
|
|
483
|
+
before = gitmod.fingerprint(work)
|
|
484
|
+
res = ex.run_judge(req, views, EventSink())
|
|
485
|
+
after = gitmod.fingerprint(work)
|
|
486
|
+
judgement = None
|
|
487
|
+
if res.ok and not res.timed_out and res.infra_cause is None:
|
|
488
|
+
try:
|
|
489
|
+
judgement = parse_judgement(res.text, shown)
|
|
490
|
+
except Unparsed:
|
|
491
|
+
judgement = None
|
|
492
|
+
gr = guard(views, [ToolCall(name=c.name, ok=c.ok, call_id=c.call_id, subagent=c.subagent)
|
|
493
|
+
for c in res.tool_calls], before, after, workspace_mode="worktree", step_session_id=None,
|
|
494
|
+
judge_session_id=res.session_id, reports_actions=caps.reports_actions)
|
|
495
|
+
model = res.model or (sorted(res.usage.by_model)[0] if len(res.usage.by_model) == 1 else None)
|
|
496
|
+
cost = res.usage.reported_cost_usd if res.usage.reported_cost_usd is not None else (
|
|
497
|
+
estimate(res.usage, model) or 0.0)
|
|
498
|
+
usage = {"input_tokens": res.usage.input_tokens, "output_tokens": res.usage.output_tokens,
|
|
499
|
+
"reported_cost_usd": res.usage.reported_cost_usd, "turns": res.usage.turns}
|
|
500
|
+
if judgement is None or gr.status == "discarded": # a fail for every criterion, never dropped (JCL-B1)
|
|
501
|
+
return Judged(statuses={str(c.id): DISCARDED for c in g.criteria}, verdict="ESCALATE",
|
|
502
|
+
guard=gr.status if judgement is not None else "unparsed", usage=usage, cost=float(cost),
|
|
503
|
+
confidence=None, confidence_source="engine_placeholder", model=model, version=res.cli_version)
|
|
504
|
+
out = derive(judgement, shown, check)
|
|
505
|
+
return Judged(statuses={str(st["id"]): str(st["status"]) for st in out.statuses}, verdict=str(out.verdict),
|
|
506
|
+
gap=out.gap, confidence=out.confidence, confidence_source=out.confidence_source, guard=gr.status,
|
|
507
|
+
usage=usage, cost=float(cost), model=model, version=res.cli_version)
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def score(spec: WorkflowSpec, gate: str, ex: Any, *, repeats: int = 3, variants: Sequence[str] = REQUIRED_VARIANTS,
|
|
511
|
+
cap_usd: float | None = None, run_by: str = "person", write: bool = True,
|
|
512
|
+
split: str = "all", level: str | None = None) -> dict[str, Any]:
|
|
513
|
+
"""`evals score`: the gate's judge on each reviewed case `repeats` times and on each variant once. The
|
|
514
|
+
record keeps ids and statuses only (JCL-AC6); a cap reached mid-score keeps it `partial` (JCL-B9, JCL-B12, JCL-B14)."""
|
|
515
|
+
if repeats < 1:
|
|
516
|
+
raise CalibrationError("--repeat must be at least 1")
|
|
517
|
+
for k in variants:
|
|
518
|
+
if k not in VARIANTS:
|
|
519
|
+
raise CalibrationError(f"unknown variant kind {k!r} ({', '.join(VARIANTS)})")
|
|
520
|
+
g, _, _ = gate_spec(spec, gate)
|
|
521
|
+
us, skipped = usable(spec, gate)
|
|
522
|
+
if not us:
|
|
523
|
+
raise CalibrationError(f"{gate} has no reviewed calibration case to score")
|
|
524
|
+
from tempergraph.executors.registry import _can_judge
|
|
525
|
+
|
|
526
|
+
if not _can_judge(ex):
|
|
527
|
+
raise CalibrationError(f"{ex.capabilities().name} cannot hold a judge to its view set (EXI); score refused")
|
|
528
|
+
results: list[dict[str, Any]] = []
|
|
529
|
+
spent = 0.0
|
|
530
|
+
partial = False
|
|
531
|
+
usage = {"sessions": 0, "input_tokens": 0, "output_tokens": 0, "cost_usd": 0.0}
|
|
532
|
+
seen_model: str | None = None
|
|
533
|
+
version = ""
|
|
534
|
+
plan: list[tuple[Usable, Subject, int]] = []
|
|
535
|
+
for u in us:
|
|
536
|
+
base = base_subject(u.case, g.criteria)
|
|
537
|
+
plan += [(u, base, r) for r in range(1, repeats + 1)]
|
|
538
|
+
for k in variants:
|
|
539
|
+
v = variant(base, k, g.criteria, u.case.reach)
|
|
540
|
+
if v is not None:
|
|
541
|
+
plan.append((u, v, 1))
|
|
542
|
+
for i, (u, s, r) in enumerate(plan):
|
|
543
|
+
if cap_usd is not None and spent >= cap_usd:
|
|
544
|
+
partial = True
|
|
545
|
+
break
|
|
546
|
+
jd = judge_once(spec, gate, s, ex, f"calibration.{u.case.case_id}.{s.variant}.{r}.{i}", level)
|
|
547
|
+
spent += jd.cost
|
|
548
|
+
usage["sessions"] += 1
|
|
549
|
+
usage["input_tokens"] += int(jd.usage.get("input_tokens") or 0)
|
|
550
|
+
usage["output_tokens"] += int(jd.usage.get("output_tokens") or 0)
|
|
551
|
+
seen_model = seen_model or jd.model
|
|
552
|
+
version = version or jd.version
|
|
553
|
+
results.append({"case": u.case.case_id, "repeat": r, "variant": s.variant, "split": u.case.split,
|
|
554
|
+
"statuses": jd.statuses, "verdict": jd.verdict, "gap": jd.gap, "confidence": jd.confidence,
|
|
555
|
+
"confidence_source": jd.confidence_source, "guard": jd.guard,
|
|
556
|
+
**({"removed_for": s.removed_for} if s.removed_for else {})})
|
|
557
|
+
usage["cost_usd"] = round(spent, 6)
|
|
558
|
+
level = _base_level(spec, gate, level)
|
|
559
|
+
b = current_binding(spec, gate, ex.name, level=level)
|
|
560
|
+
b["executor_version"] = version or b.get("executor_version")
|
|
561
|
+
b["model_slug"] = b.get("model_slug") or seen_model
|
|
562
|
+
rec = {"schema_version": 1, "score_id": uuid.uuid4().hex[:16], "at": now_iso(), "run_by": run_by,
|
|
563
|
+
"workflow": spec.name, "workflow_version": spec.version, "gate": gate, "case_set_digest": case_set_digest(us),
|
|
564
|
+
"split": split, "binding": b, "repeats": repeats, "variants": list(variants), "partial": partial,
|
|
565
|
+
"skipped": skipped, "results": results, "usage": usage, **({"level": level} if level else {})}
|
|
566
|
+
rec["figures"] = figures(rec, spec)
|
|
567
|
+
if write and spec.package_root is not None:
|
|
568
|
+
append_jsonl(calibration_dir(spec.package_root, gate) / "scores.jsonl", rec)
|
|
569
|
+
return rec
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
# -- figures (JCL-B15) ------------------------------------------------------------------------------------
|
|
573
|
+
|
|
574
|
+
def judged_blockers(g: GateSpec) -> set[str]:
|
|
575
|
+
"""The blockers the judge grades: a check's or a person's criterion is not the judge's to calibrate."""
|
|
576
|
+
return {str(c.id) for c in g.criteria if c.severity == "blocker" and c.id and not c.mechanical
|
|
577
|
+
and c.verified_by not in ("check", "person", "none")}
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _nearest(conf: float) -> float:
|
|
581
|
+
return min((1.0, 0.75, 0.5, 0.25), key=lambda a: abs(a - conf))
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _klass(status: str) -> str:
|
|
585
|
+
return "pass" if status in PASS else "fail"
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def judge_family(b: Mapping[str, Any]) -> str | None:
|
|
589
|
+
"""The provider family of the judge (CAP `families` of its executor and alias), for `self_family`."""
|
|
590
|
+
from tempergraph.executors.capabilities import DECLARED
|
|
591
|
+
|
|
592
|
+
caps = DECLARED.get(str(b.get("executor")))
|
|
593
|
+
return caps.families.get(str(b.get("alias") or "inherit")) if caps is not None else None
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def figures(rec: Mapping[str, Any], spec: WorkflowSpec) -> dict[str, Any]:
|
|
597
|
+
g, _, _ = gate_spec(spec, str(rec["gate"]))
|
|
598
|
+
blockers = judged_blockers(g)
|
|
599
|
+
by_case = {u.case.case_id: u for u in usable(spec, str(rec["gate"]))[0]}
|
|
600
|
+
results = list(rec.get("results") or [])
|
|
601
|
+
hold = [r for r in results if r.get("split") == "holdout" and r["case"] in by_case]
|
|
602
|
+
first = [r for r in hold if r["variant"] == "base" and r["repeat"] == 1]
|
|
603
|
+
kb = kg = oor = 0
|
|
604
|
+
caught = clean = oor_ok = 0
|
|
605
|
+
kb_cases: set[str] = set()
|
|
606
|
+
kg_cases: set[str] = set()
|
|
607
|
+
covered: set[str] = set()
|
|
608
|
+
misses: list[dict[str, Any]] = []
|
|
609
|
+
oor_met: list[dict[str, Any]] = []
|
|
610
|
+
false_pass: list[str] = []
|
|
611
|
+
self_split: dict[str, list[int]] = {"same": [0, 0], "different": [0, 0]}
|
|
612
|
+
fam_j = judge_family(rec.get("binding") or {})
|
|
613
|
+
errs_by_anchor: dict[str, list[int]] = {}
|
|
614
|
+
anchored = judged_conf = 0
|
|
615
|
+
for r in first:
|
|
616
|
+
u = by_case[r["case"]]
|
|
617
|
+
any_bad = False
|
|
618
|
+
for cid, expected in u.labels.items():
|
|
619
|
+
if cid not in blockers:
|
|
620
|
+
continue
|
|
621
|
+
got = str(r["statuses"].get(cid, DISCARDED))
|
|
622
|
+
if expected in ("PARTIAL", "UNMET"):
|
|
623
|
+
kb += 1
|
|
624
|
+
kb_cases.add(u.case.case_id)
|
|
625
|
+
covered.add(cid)
|
|
626
|
+
any_bad = True
|
|
627
|
+
ok = got in ("PARTIAL", "UNMET", DISCARDED)
|
|
628
|
+
caught += ok
|
|
629
|
+
fam = "same" if fam_j and u.case.producer_family == fam_j else "different"
|
|
630
|
+
self_split[fam][0] += ok
|
|
631
|
+
self_split[fam][1] += 1
|
|
632
|
+
if not ok:
|
|
633
|
+
misses.append({"case": u.case.case_id, "criterion": cid, "status": got})
|
|
634
|
+
elif expected == "UNVERIFIABLE":
|
|
635
|
+
oor += 1
|
|
636
|
+
ok = got in ("UNVERIFIABLE", "N/A") or bool(r.get("gap"))
|
|
637
|
+
oor_ok += ok and got != "MET"
|
|
638
|
+
if got == "MET":
|
|
639
|
+
oor_met.append({"case": u.case.case_id, "criterion": cid})
|
|
640
|
+
elif expected in PASS:
|
|
641
|
+
kg += 1
|
|
642
|
+
kg_cases.add(u.case.case_id)
|
|
643
|
+
ok = got in PASS
|
|
644
|
+
clean += ok
|
|
645
|
+
if not ok:
|
|
646
|
+
misses.append({"case": u.case.case_id, "criterion": cid, "status": got})
|
|
647
|
+
if r.get("confidence_source") == "judge" and isinstance(r.get("confidence"), int | float):
|
|
648
|
+
conf = float(r["confidence"])
|
|
649
|
+
anchor = _nearest(conf)
|
|
650
|
+
wrong = (expected in ("PARTIAL", "UNMET") and got in PASS) or (expected in PASS and got not in PASS)
|
|
651
|
+
e = errs_by_anchor.setdefault(str(anchor), [0, 0])
|
|
652
|
+
e[0] += wrong
|
|
653
|
+
e[1] += 1
|
|
654
|
+
if r.get("confidence_source") == "judge" and isinstance(r.get("confidence"), int | float):
|
|
655
|
+
judged_conf += 1 # per judgement, not per criterion
|
|
656
|
+
anchored += any(abs(a - float(r["confidence"])) < 1e-9 for a in (1.0, 0.75, 0.5, 0.25))
|
|
657
|
+
if any_bad and r.get("verdict") == "PROCEED":
|
|
658
|
+
false_pass.append(u.case.case_id)
|
|
659
|
+
# flips across repeats
|
|
660
|
+
base_rows: dict[str, list[Mapping[str, Any]]] = {}
|
|
661
|
+
for r in hold:
|
|
662
|
+
if r["variant"] == "base":
|
|
663
|
+
base_rows.setdefault(r["case"], []).append(r)
|
|
664
|
+
flips = flip_n = 0
|
|
665
|
+
majority: dict[tuple[str, str], str] = {}
|
|
666
|
+
for case_id, rows in base_rows.items():
|
|
667
|
+
for cid in (c for c in by_case[case_id].labels if c in blockers):
|
|
668
|
+
classes = [_klass(str(x["statuses"].get(cid, DISCARDED))) for x in rows]
|
|
669
|
+
flip_n += 1
|
|
670
|
+
flips += len(set(classes)) > 1
|
|
671
|
+
majority[(case_id, cid)] = "fail" if classes.count("fail") >= classes.count("pass") else "pass"
|
|
672
|
+
vflip: dict[str, float | None] = {}
|
|
673
|
+
vlist: dict[str, list[dict[str, Any]]] = {}
|
|
674
|
+
for kind in rec.get("variants") or []:
|
|
675
|
+
rows = [r for r in hold if r["variant"] == kind]
|
|
676
|
+
n = bad = 0
|
|
677
|
+
for r in rows:
|
|
678
|
+
for cid in (c for c in by_case[r["case"]].labels if c in blockers):
|
|
679
|
+
if (r["case"], cid) not in majority:
|
|
680
|
+
continue
|
|
681
|
+
got = str(r["statuses"].get(cid, DISCARDED))
|
|
682
|
+
if kind == "out_of_reach" and r.get("removed_for") == cid:
|
|
683
|
+
wrong = got == "MET" # JCL-B6: the removed reference makes MET impossible
|
|
684
|
+
if wrong:
|
|
685
|
+
oor_met.append({"case": r["case"], "criterion": cid, "variant": kind})
|
|
686
|
+
oor += 1
|
|
687
|
+
oor_ok += got in ("UNVERIFIABLE", "N/A") or (bool(r.get("gap")) and got != "MET")
|
|
688
|
+
elif kind == "reordered":
|
|
689
|
+
wrong = _klass(got) != majority[(r["case"], cid)]
|
|
690
|
+
else:
|
|
691
|
+
wrong = _klass(got) != majority[(r["case"], cid)]
|
|
692
|
+
n += 1
|
|
693
|
+
bad += wrong
|
|
694
|
+
if wrong:
|
|
695
|
+
vlist.setdefault(kind, []).append({"case": r["case"], "criterion": cid, "status": got})
|
|
696
|
+
vflip[kind] = bad / n if n else None
|
|
697
|
+
syn = sum(1 for r in first for cid, e in by_case[r["case"]].labels.items()
|
|
698
|
+
if cid in blockers and e in ("PARTIAL", "UNMET") and by_case[r["case"]].case.provenance == "synthetic")
|
|
699
|
+
reviews = [x.case.second_review for x in by_case.values() if x.case.second_review]
|
|
700
|
+
catch_rate = caught / kb if kb else None
|
|
701
|
+
clean_rate = clean / kg if kg else None
|
|
702
|
+
return {
|
|
703
|
+
"known_bad": kb, "known_bad_cases": len(kb_cases), "known_good": kg, "known_good_cases": len(kg_cases),
|
|
704
|
+
"out_of_reach": oor, "covered_blockers": sorted(covered), "blockers": sorted(blockers),
|
|
705
|
+
"catch_rate": catch_rate, "catch_lb": wilson_lb(caught, kb) if kb else None,
|
|
706
|
+
"clean_rate": clean_rate, "clean_lb": wilson_lb(clean, kg) if kg else None,
|
|
707
|
+
"out_of_reach_ok": oor_ok / oor if oor else None, "out_of_reach_met": oor_met,
|
|
708
|
+
"false_pass_cases": sorted(set(false_pass)),
|
|
709
|
+
"balanced_accuracy": (catch_rate + clean_rate) / 2 if catch_rate is not None and clean_rate is not None
|
|
710
|
+
else None,
|
|
711
|
+
"flip_rate": flips / flip_n if flip_n else None, "variant_flip": vflip, "variant_cases": vlist,
|
|
712
|
+
"self_family": {k: (v[0] / v[1] if v[1] else None) for k, v in self_split.items()},
|
|
713
|
+
"anchor_adherence": anchored / judged_conf if judged_conf else None,
|
|
714
|
+
"confidence_by_anchor": {k: v[0] / v[1] for k, v in errs_by_anchor.items() if v[1]},
|
|
715
|
+
"synthetic_share": syn / kb if kb else None,
|
|
716
|
+
"review_agreement": (sum(1 for x in reviews if x.get("agrees")) / len(reviews)) if reviews else None,
|
|
717
|
+
"misses": misses,
|
|
718
|
+
"tune": _tune_figures(results, by_case, blockers),
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def _tune_figures(results: Sequence[Mapping[str, Any]], by_case: Mapping[str, Usable], blockers: set[str]
|
|
723
|
+
) -> dict[str, Any]:
|
|
724
|
+
"""`tune` cases are scored and shown apart, never in the bar (JCL-B11)."""
|
|
725
|
+
kb = caught = 0
|
|
726
|
+
for r in results:
|
|
727
|
+
if r.get("split") != "tune" or r["variant"] != "base" or r["repeat"] != 1 or r["case"] not in by_case:
|
|
728
|
+
continue
|
|
729
|
+
for cid, e in by_case[r["case"]].labels.items():
|
|
730
|
+
if cid in blockers and e in ("PARTIAL", "UNMET"):
|
|
731
|
+
kb += 1
|
|
732
|
+
caught += str(r["statuses"].get(cid, DISCARDED)) in ("PARTIAL", "UNMET", DISCARDED)
|
|
733
|
+
return {"known_bad": kb, "catch_rate": caught / kb if kb else None}
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
# -- bar and state (JCL-B16, JCL-B17) --------------------------------------------------------------------------
|
|
737
|
+
|
|
738
|
+
def bar(root: Path | None) -> dict[str, float]:
|
|
739
|
+
"""The engine defaults, raised (never lowered) by the workflow's `evals/bar.json`."""
|
|
740
|
+
out = dict(BAR)
|
|
741
|
+
doc = _read(root / "evals" / "bar.json", {}) if root is not None else {}
|
|
742
|
+
for k, v in dict(doc or {}).items():
|
|
743
|
+
if k in out and isinstance(v, int | float):
|
|
744
|
+
out[k] = min(out[k], float(v)) if k in LOWER_IS_STRICTER else max(out[k], float(v))
|
|
745
|
+
return out
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def failing_rules(fig: Mapping[str, Any], repeats: int, scored_variants: Sequence[str],
|
|
749
|
+
b: Mapping[str, float] | None = None) -> tuple[list[str], list[str]]:
|
|
750
|
+
"""The failing bar rules and the warnings, each a sentence naming the rule (JCL-B16)."""
|
|
751
|
+
b = b or BAR
|
|
752
|
+
fail: list[str] = []
|
|
753
|
+
warn: list[str] = []
|
|
754
|
+
if fig["known_bad"] < b["known_bad_findings"] or fig["known_bad_cases"] < b["known_bad_cases"]:
|
|
755
|
+
fail.append(f"known-bad holdout findings ≥ {int(b['known_bad_findings'])} from ≥ {int(b['known_bad_cases'])}"
|
|
756
|
+
f" cases (have {fig['known_bad']} from {fig['known_bad_cases']})")
|
|
757
|
+
if fig["known_good"] < b["known_good_findings"] or fig["known_good_cases"] < b["known_good_cases"]:
|
|
758
|
+
fail.append(f"known-good holdout findings ≥ {int(b['known_good_findings'])} from ≥ "
|
|
759
|
+
f"{int(b['known_good_cases'])} cases (have {fig['known_good']} from {fig['known_good_cases']})")
|
|
760
|
+
uncovered = sorted(set(fig["blockers"]) - set(fig["covered_blockers"]))
|
|
761
|
+
if uncovered:
|
|
762
|
+
fail.append(f"every blocker covered by a known-bad holdout finding (missing {', '.join(uncovered)})")
|
|
763
|
+
if fig["catch_lb"] is None or fig["catch_lb"] < b["catch_lb"]:
|
|
764
|
+
fail.append(f"catch_lb ≥ {b['catch_lb']} (have {_f(fig['catch_lb'])})")
|
|
765
|
+
if fig["clean_lb"] is None or fig["clean_lb"] < b["clean_lb"]:
|
|
766
|
+
fail.append(f"clean_lb ≥ {b['clean_lb']} (have {_f(fig['clean_lb'])})")
|
|
767
|
+
if fig["out_of_reach_ok"] is not None and fig["out_of_reach_ok"] < b["out_of_reach_ok"]:
|
|
768
|
+
fail.append(f"out_of_reach_ok = 1.0, no MET out of reach (have {_f(fig['out_of_reach_ok'])})")
|
|
769
|
+
if repeats < b["min_repeats"]:
|
|
770
|
+
fail.append(f"flip_rate measured with k ≥ {int(b['min_repeats'])} (k = {repeats})")
|
|
771
|
+
elif fig["flip_rate"] is None or fig["flip_rate"] > b["flip_rate"]:
|
|
772
|
+
fail.append(f"flip_rate ≤ {b['flip_rate']} (have {_f(fig['flip_rate'])})")
|
|
773
|
+
for kind in REQUIRED_VARIANTS:
|
|
774
|
+
if kind not in scored_variants or fig["variant_flip"].get(kind) is None:
|
|
775
|
+
fail.append(f"variant {kind} scored (a required kind" + (
|
|
776
|
+
"; out_of_reach needs cases whose `reach` names a reference)" if kind == "out_of_reach" else ")"))
|
|
777
|
+
for kind, v in fig["variant_flip"].items():
|
|
778
|
+
if v is not None and v > b["variant_flip"]:
|
|
779
|
+
fail.append(f"variant_flip[{kind}] ≤ {b['variant_flip']} (have {_f(v)})")
|
|
780
|
+
if fig["anchor_adherence"] is not None and fig["anchor_adherence"] < b["anchor_adherence_warn"]:
|
|
781
|
+
warn.append(f"anchor_adherence {_f(fig['anchor_adherence'])} below {b['anchor_adherence_warn']}")
|
|
782
|
+
sf = fig["self_family"]
|
|
783
|
+
if sf.get("same") is not None and sf.get("different") is not None and abs(sf["same"] - sf["different"]) > 0.15:
|
|
784
|
+
warn.append("self_family: catch rates differ by more than 0.15 between same and other family")
|
|
785
|
+
return fail, warn
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def _f(v: Any) -> str:
|
|
789
|
+
return "none" if v is None else f"{float(v):.2f}"
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def scores(root: Path, gate: str) -> list[dict[str, Any]]:
|
|
793
|
+
path = calibration_dir(root, gate) / "scores.jsonl"
|
|
794
|
+
try:
|
|
795
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
796
|
+
except OSError:
|
|
797
|
+
return []
|
|
798
|
+
out = []
|
|
799
|
+
for ln in lines:
|
|
800
|
+
try:
|
|
801
|
+
out.append(json.loads(ln))
|
|
802
|
+
except ValueError:
|
|
803
|
+
continue
|
|
804
|
+
return out
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
_STATIC = ("executor", "alias", "model_slug", "brief_digest", "criteria_digest", "sampling")
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
@dataclass(kw_only=True)
|
|
811
|
+
class State:
|
|
812
|
+
gate: str
|
|
813
|
+
state: str
|
|
814
|
+
binding: dict[str, Any]
|
|
815
|
+
score: dict[str, Any] | None = None
|
|
816
|
+
failing: list[str] = field(default_factory=list)
|
|
817
|
+
warnings: list[str] = field(default_factory=list)
|
|
818
|
+
changed: list[str] = field(default_factory=list)
|
|
819
|
+
history: list[dict[str, Any]] = field(default_factory=list)
|
|
820
|
+
skipped: list[dict[str, Any]] = field(default_factory=list)
|
|
821
|
+
production_grade: str | None = None
|
|
822
|
+
level: str | None = None # a risk level above the judge's own (JRK-B9, JRK-B5)
|
|
823
|
+
|
|
824
|
+
def to_json(self) -> dict[str, Any]:
|
|
825
|
+
sc = self.score or {}
|
|
826
|
+
return {"gate": self.gate, "state": self.state, "binding": self.binding, "score_id": sc.get("score_id"),
|
|
827
|
+
"scored_at": sc.get("at"), "figures": sc.get("figures"), "failing": self.failing,
|
|
828
|
+
"warnings": self.warnings, "changed": self.changed, "history": self.history,
|
|
829
|
+
"skipped": self.skipped, "production_grade": self.production_grade,
|
|
830
|
+
**({"level": self.level} if self.level else {})}
|
|
831
|
+
|
|
832
|
+
|
|
833
|
+
def state(spec: WorkflowSpec, gate: str, *, observed: Mapping[str, Any] | None = None,
|
|
834
|
+
production_grade: Callable[[str, Mapping[str, Any]], str] | None = None,
|
|
835
|
+
home: Path | None = None, level: str | None = None) -> State:
|
|
836
|
+
"""JCL-B17: the latest complete score for the current binding decides. Model-free (JCL-AC8).
|
|
837
|
+
|
|
838
|
+
``observed`` is the binding of the gate's latest production judgement, when a state root is at hand: an
|
|
839
|
+
executor version or model slug that changed since the score makes it `stale` (JCL-B3).
|
|
840
|
+
``production_grade(gate, binding)`` is FBK's grade, for `contradicted` (JCL-B7)."""
|
|
841
|
+
root = spec.package_root
|
|
842
|
+
level = _base_level(spec, gate, level)
|
|
843
|
+
cur = current_binding(spec, gate, observed=observed, home=home, level=level)
|
|
844
|
+
st = State(gate=gate, state="unscored", binding=cur, level=level)
|
|
845
|
+
if root is None:
|
|
846
|
+
return st
|
|
847
|
+
us, st.skipped = usable(spec, gate)
|
|
848
|
+
known = levels(spec, gate)
|
|
849
|
+
base = known[0] if known else None # a score belongs to one level's binding (JRK-B8)
|
|
850
|
+
complete = [s for s in scores(root, gate) if not s.get("partial") # a partial record is never a state (JCL-B9, JCL-B12, JCL-B14)
|
|
851
|
+
and (s.get("level") if s.get("level") != base else None) == level]
|
|
852
|
+
if not complete:
|
|
853
|
+
return st
|
|
854
|
+
latest = complete[-1]
|
|
855
|
+
st.history = [{"score_id": s.get("score_id"), "at": s.get("at"), "binding": s.get("binding")} for s in complete[:-1]]
|
|
856
|
+
sb = latest.get("binding") or {}
|
|
857
|
+
changed = [k for k in _STATIC if sb.get(k) != cur.get(k) and not (k == "model_slug" and cur.get(k) is None)]
|
|
858
|
+
if observed and observed.get("executor_version") and sb.get("executor_version") \
|
|
859
|
+
and observed["executor_version"] != sb["executor_version"]:
|
|
860
|
+
changed.append("executor_version")
|
|
861
|
+
if latest.get("case_set_digest") != case_set_digest(us):
|
|
862
|
+
changed.append("case_set_digest")
|
|
863
|
+
st.score = latest
|
|
864
|
+
if changed:
|
|
865
|
+
st.state, st.changed = "stale", changed
|
|
866
|
+
return st
|
|
867
|
+
fig = figures(latest, spec) # recomputed: tune marks since the score move cases out of the bar
|
|
868
|
+
st.score = {**latest, "figures": fig}
|
|
869
|
+
st.failing, st.warnings = failing_rules(fig, int(latest.get("repeats") or 0), list(latest.get("variants") or []),
|
|
870
|
+
bar(root))
|
|
871
|
+
if st.failing:
|
|
872
|
+
st.state = "below_bar"
|
|
873
|
+
return st
|
|
874
|
+
share = fig.get("synthetic_share")
|
|
875
|
+
st.state = "provisional" if share is not None and share > bar(root)["synthetic_share"] else "accepted"
|
|
876
|
+
if production_grade is not None:
|
|
877
|
+
st.production_grade = production_grade(gate, cur)
|
|
878
|
+
if st.production_grade == "unreliable":
|
|
879
|
+
st.state = "contradicted"
|
|
880
|
+
return st
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def states(spec: WorkflowSpec, state_root: Path | None = None, home: Path | None = None,
|
|
884
|
+
every_level: bool = False, child: str | None = None) -> list[State]:
|
|
885
|
+
"""Every judged gate's state; with a state root, the observed binding and FBK's grade are read too. With
|
|
886
|
+
`every_level`, a gate whose judge has risk levels gets one more state per level above its own. `child` is the
|
|
887
|
+
sub-workflow unit path of a child's spec (SWF-B9): the observed binding and the grade are read from the gates of
|
|
888
|
+
that child alone, never from a parent's gate of the same name; the cases come from the spec's own package."""
|
|
889
|
+
out = []
|
|
890
|
+
for gate in judged_gates(spec):
|
|
891
|
+
observed = None
|
|
892
|
+
grade = None
|
|
893
|
+
if state_root is not None:
|
|
894
|
+
from tempergraph.improve import reliability
|
|
895
|
+
|
|
896
|
+
js = [j for j in reliability.judgements(state_root, spec.name, child) if j["unit"] == gate]
|
|
897
|
+
observed = js[-1]["binding"] if js else None
|
|
898
|
+
|
|
899
|
+
def grade(g: str, b: Mapping[str, Any]) -> str:
|
|
900
|
+
live = lambda gg, bb: passing(spec, gg) # noqa: E731
|
|
901
|
+
return reliability.report(state_root, spec.name, [g], live, child=child)[0]["grade"]
|
|
902
|
+
|
|
903
|
+
out.append(state(spec, gate, observed=observed, production_grade=grade, home=home))
|
|
904
|
+
if every_level:
|
|
905
|
+
out += [state(spec, gate, home=home, level=lv) for lv in levels(spec, gate)[1:]]
|
|
906
|
+
return out
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def unaccepted_levels(spec: WorkflowSpec, gate: str) -> list[tuple[str, str]]:
|
|
910
|
+
"""JRK-B9, JRK-B5: the levels above the judge's own that a routed rule may pick and that are not `accepted`, with
|
|
911
|
+
their state. Shadow mode runs level 0 only, so it needs none of them."""
|
|
912
|
+
from tempergraph.run.outcome import with_outcome
|
|
913
|
+
|
|
914
|
+
u = with_outcome(spec).units.get(gate)
|
|
915
|
+
j = u.gate.judge if u is not None else None
|
|
916
|
+
if j is None or j.risk is None or j.risk.mode != "route":
|
|
917
|
+
return []
|
|
918
|
+
out = []
|
|
919
|
+
for lv in levels(spec, gate)[1:]:
|
|
920
|
+
try:
|
|
921
|
+
name = state(spec, gate, level=lv).state
|
|
922
|
+
except (CalibrationError, OSError, ValueError):
|
|
923
|
+
name = "unscored"
|
|
924
|
+
if name != "accepted":
|
|
925
|
+
out.append((lv, name))
|
|
926
|
+
return out
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def passing(spec: WorkflowSpec, gate: str) -> bool:
|
|
930
|
+
"""FBK-B11, FBK-B12's "passing live score": a complete, current score that meets the bar (JCL `accepted` or
|
|
931
|
+
`provisional`, before the production check), on cases with known-bad findings."""
|
|
932
|
+
try:
|
|
933
|
+
s = state(spec, gate)
|
|
934
|
+
except CalibrationError:
|
|
935
|
+
return False
|
|
936
|
+
return s.state in ("accepted", "provisional") and bool((s.score or {}).get("figures", {}).get("known_bad"))
|
|
937
|
+
|
|
938
|
+
|
|
939
|
+
def has_score(spec: WorkflowSpec, gate: str, state_root: Path | None = None, child: str | None = None) -> bool:
|
|
940
|
+
"""The seam for filing (SIL-B7, `Candidate.calibrated`): the gate's judge is `accepted`."""
|
|
941
|
+
try:
|
|
942
|
+
named = _state_of(spec, gate, state_root) if child is None else _state_of(spec, gate, state_root, child)
|
|
943
|
+
return named == "accepted" and not unaccepted_levels(spec, gate)
|
|
944
|
+
except (CalibrationError, OSError, ValueError): # a reader never fails on a broken case file
|
|
945
|
+
return False
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
def _state_of(spec: WorkflowSpec, gate: str, state_root: Path | None, child: str | None = None) -> str:
|
|
949
|
+
if state_root is None:
|
|
950
|
+
return state(spec, gate).state
|
|
951
|
+
return next((s.state for s in states(spec, state_root, child=child) if s.gate == gate), "unscored")
|
|
952
|
+
|
|
953
|
+
|
|
954
|
+
def accepted_for(spec: WorkflowSpec, state_root: Path | None = None, child: str | None = None
|
|
955
|
+
) -> Callable[[str], bool]:
|
|
956
|
+
"""`accepted(gate)` for package/readiness.readiness and run/outcome_trust.trust (JCL-B17 readers)."""
|
|
957
|
+
cache: dict[str, bool] = {}
|
|
958
|
+
|
|
959
|
+
def accepted(gate: str) -> bool:
|
|
960
|
+
if gate not in cache:
|
|
961
|
+
cache[gate] = has_score(spec, gate, state_root, child)
|
|
962
|
+
return cache[gate]
|
|
963
|
+
|
|
964
|
+
return accepted
|
|
965
|
+
|
|
966
|
+
|
|
967
|
+
def state_name_for(spec: WorkflowSpec, state_root: Path | None = None, child: str | None = None
|
|
968
|
+
) -> Callable[[str], str]:
|
|
969
|
+
"""`name(gate)` for the judge's own binding, `name("<gate>@<level>")` for a risk level above it. `child` is the
|
|
970
|
+
sub-workflow unit path when `spec` is a child's (SWF-B9): its judgements and grade are the child's own."""
|
|
971
|
+
def name(gate: str) -> str:
|
|
972
|
+
gate, _, level = gate.partition("@")
|
|
973
|
+
try:
|
|
974
|
+
if level and _base_level(spec, gate, level):
|
|
975
|
+
return state(spec, gate, level=level).state
|
|
976
|
+
return _state_of(spec, gate, state_root) if child is None else _state_of(spec, gate, state_root, child)
|
|
977
|
+
except (CalibrationError, OSError, ValueError):
|
|
978
|
+
return "unscored"
|
|
979
|
+
|
|
980
|
+
return name
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
UNCORRECTABLE = 0.2 # EVS-B15: below this `catch_rate + clean_rate - 1`, no corrected estimate is shown
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
def corrected(raw: float | None, st: State) -> dict[str, Any]:
|
|
987
|
+
"""EVS-B15: a judge-graded rate with the judge's state, and a corrected estimate where it allows."""
|
|
988
|
+
if raw is None:
|
|
989
|
+
return {"raw": None, "label": "uncorrected", "state": st.state}
|
|
990
|
+
fig = (st.score or {}).get("figures") or {}
|
|
991
|
+
c, g = fig.get("catch_rate"), fig.get("clean_rate")
|
|
992
|
+
if c is not None and g is not None and c + g - 1 < UNCORRECTABLE: # the judge separates too little
|
|
993
|
+
return {"raw": raw, "label": "uncorrectable", "state": st.state}
|
|
994
|
+
if st.state in ("accepted", "provisional") and c is not None and g is not None:
|
|
995
|
+
theta = min(1.0, max(0.0, (raw + c - 1) / (c + g - 1)))
|
|
996
|
+
return {"raw": raw, "corrected": round(theta, 4), "label": "corrected", "state": st.state}
|
|
997
|
+
return {"raw": raw, "label": f"uncorrected ({st.state})", "state": st.state}
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
def needed(st: State) -> list[str]:
|
|
1001
|
+
"""`evals bar`: the cases still needed, from the failing rules."""
|
|
1002
|
+
fig = (st.score or {}).get("figures") or {}
|
|
1003
|
+
out = []
|
|
1004
|
+
if st.state == "unscored":
|
|
1005
|
+
out.append("write reviewed cases and run `evals score`")
|
|
1006
|
+
if st.state == "stale":
|
|
1007
|
+
out.append("re-score: " + ", ".join(st.changed) + " changed")
|
|
1008
|
+
if fig:
|
|
1009
|
+
kb, kg = int(fig.get("known_bad") or 0), int(fig.get("known_good") or 0)
|
|
1010
|
+
if kb < BAR["known_bad_findings"]:
|
|
1011
|
+
out.append(f"{int(BAR['known_bad_findings']) - kb} more known-bad holdout findings")
|
|
1012
|
+
if kg < BAR["known_good_findings"]:
|
|
1013
|
+
out.append(f"{int(BAR['known_good_findings']) - kg} more known-good holdout findings")
|
|
1014
|
+
miss = sorted(set(fig.get("blockers") or []) - set(fig.get("covered_blockers") or []))
|
|
1015
|
+
out += [f"a known-bad case for blocker {m}" for m in miss]
|
|
1016
|
+
return out
|