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,525 @@
1
+ """Case sets, paired trials, the A/A noise floor and the trial caps (PRP-B17, PRP-B4, PRP-B12, PRP-B18, PRP-B21, PRP-B8, PRP-B22, B5 to B7, B9;
2
+ plan T12.6).
3
+
4
+ Release 1 (ADR `first-release-is-simple-trusted-workflows-on-one-machine` S4): before `batch` exists, each case runs as one engine child run at a time, arm A (the
5
+ base package) then arm B (the patched copy), each in its own engine worktree at the case's base commit
6
+ (`run.worktree.base = ref:<base>`), with `--dry-run` so the loop files nothing for them. A case that stops at
7
+ a pause is a tie (PRP open question default). A trial writes no code: only the proposer writes, on its own
8
+ branch (OVR-B16). Trial child runs are ordinary threads with `origin: trial`, so their spend is logged per session
9
+ like any run and joins no workflow run's cost line (PRP-AC6).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import math
16
+ import re
17
+ import tempfile
18
+ import uuid
19
+ from collections.abc import Callable, Mapping, Sequence
20
+ from dataclasses import dataclass, field
21
+ from datetime import UTC, datetime, timedelta
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from tempergraph.contracts import WorkflowSpec
26
+ from tempergraph.docs import read_json, write_json
27
+ from tempergraph.improve import params
28
+ from tempergraph.store.layout import now_iso, run_dir
29
+
30
+ TARGET = re.compile(r"^(first_pass_yield|gate_pass|criterion_met|run_cost|outcome_met|label_agreement)"
31
+ r"(?:\(([A-Za-z0-9_.-]+)(?:,\s*([A-Za-z0-9_.-]+))?\))?$")
32
+ JUDGE_GRADED = frozenset({"gate_pass", "criterion_met", "outcome_met"})
33
+ DECISIONS = ("shown_better", "not_shown", "regressed", "aborted")
34
+
35
+
36
+ class TrialRefused(ValueError):
37
+ """Refused before spend (exit 2)."""
38
+
39
+
40
+ # -- case sets (PRP-B17) ------------------------------------------------------------------------------------
41
+
42
+ @dataclass(frozen=True, kw_only=True)
43
+ class TrialCase:
44
+ case_id: str
45
+ base: str
46
+ request: str
47
+ expected_scope: str = ""
48
+ origin: str = "authored"
49
+ reviewed_by: str | None = None
50
+
51
+
52
+ def case_set(spec: WorkflowSpec) -> tuple[list[TrialCase], str]:
53
+ """The package's `evals/cases.json`, reviewed cases only (harvested ones need `reviewed_by`)."""
54
+ root = spec.package_root
55
+ path = root / "evals" / "cases.json" if root is not None else None
56
+ if path is None or not path.is_file():
57
+ return [], ""
58
+ try:
59
+ doc = json.loads(path.read_text(encoding="utf-8"))
60
+ except ValueError:
61
+ return [], ""
62
+ rows = doc.get("cases") if isinstance(doc, dict) else doc
63
+ out = []
64
+ for r in rows or []:
65
+ cid = r.get("case_id") or r.get("id") if isinstance(r, dict) else None # PKG-B25's minimal set uses `id`
66
+ if not isinstance(r, dict) or not cid:
67
+ continue
68
+ c = TrialCase(case_id=str(cid), base=str(r.get("base") or "HEAD"), request=str(r.get("request") or ""),
69
+ expected_scope=str(r.get("expected_scope") or ""), origin=str(r.get("origin") or "authored"),
70
+ reviewed_by=r.get("reviewed_by"))
71
+ if c.origin.startswith("harvested:") and not c.reviewed_by:
72
+ continue
73
+ out.append(c)
74
+ import hashlib
75
+
76
+ digest = hashlib.sha256(json.dumps([c.__dict__ for c in out], sort_keys=True).encode()).hexdigest()[:16]
77
+ return out, digest
78
+
79
+
80
+ def in_sample(c: TrialCase, cluster_threads: Sequence[str]) -> bool:
81
+ """A case harvested from a run of the proposal's cluster (PRP-B17)."""
82
+ if not c.origin.startswith("harvested:"):
83
+ return False
84
+ run = c.origin.split(":", 1)[1]
85
+ return any(run == t or run.startswith(t + "#") for t in cluster_threads)
86
+
87
+
88
+ # -- the decision rule (PRP-B18, PRP-B19, PRP-B20, ADR `paired-trial-on-a-fixed-case-set`) ------------------------------------------------------------------
89
+
90
+ def sign_count(n: int, alpha: float | None = None) -> int | None:
91
+ """The fewest wins of `n` non-tied pairs with a one-sided sign-test p ≤ alpha (research `self-improvement-gap-analysis` F3); None if none."""
92
+ alpha = params.value("trial.alpha") if alpha is None else alpha
93
+ for k in range(n + 1):
94
+ p = sum(math.comb(n, i) for i in range(k, n + 1)) / 2 ** n
95
+ if p <= alpha:
96
+ return k
97
+ return None
98
+
99
+
100
+ def decide(pairs: Sequence[Mapping[str, Any]], guards: Sequence[Mapping[str, Any]],
101
+ noise_floor: float | str = "unknown", *, aborted: bool = False) -> dict[str, Any]:
102
+ out_pairs = [p for p in pairs if not p.get("in_sample")]
103
+ wins = sum(1 for p in out_pairs if p["result"] == "win")
104
+ losses = sum(1 for p in out_pairs if p["result"] == "loss")
105
+ ties = sum(1 for p in out_pairs if p["result"] == "tie")
106
+ n = wins + losses
107
+ counts = {"wins": wins, "losses": losses, "ties": ties, "in_sample": len(pairs) - len(out_pairs)}
108
+ warnings = []
109
+ if isinstance(noise_floor, int | float) and noise_floor > params.value("trial.noisy_floor"):
110
+ warnings.append("noisy_case_set")
111
+ base = {"counts": counts, "warnings": warnings, "need": sign_count(n) if n else None}
112
+ if aborted:
113
+ return {**base, "decision": "aborted", "reason": "cap_reached"}
114
+ need = sign_count(n)
115
+ if any(g["state"] == "failed" for g in guards):
116
+ return {**base, "decision": "regressed", "reason": "guard:" + ",".join(g["name"] for g in guards
117
+ if g["state"] == "failed")}
118
+ if need is not None and n >= params.value("trial.min_pairs") and losses >= need:
119
+ return {**base, "decision": "regressed", "reason": "losses"}
120
+ if n < params.value("trial.min_pairs"):
121
+ return {**base, "decision": "not_shown", "reason": "too_few_pairs"}
122
+ if need is not None and wins >= need:
123
+ return {**base, "decision": "shown_better", "reason": None}
124
+ return {**base, "decision": "not_shown", "reason": None}
125
+
126
+
127
+ def guard_states(a: Mapping[str, float], b: Mapping[str, float]) -> list[dict[str, Any]]:
128
+ """The default guards: run cost +15%, outcome met −1 case, check pass −1 case, gate escapes +1."""
129
+ out = []
130
+ cost_a, cost_b = float(a.get("cost") or 0), float(b.get("cost") or 0)
131
+ limit = cost_a * (1 + params.value("trial.guard_cost"))
132
+ out.append({"name": "run_cost", "a": round(cost_a, 4), "b": round(cost_b, 4),
133
+ "state": "failed" if cost_a > 0 and cost_b > limit else "held"})
134
+ for name, key, margin, worse in (("outcome_met", "outcome_met", "trial.guard_outcome_cases", -1),
135
+ ("check_pass", "check_pass", "trial.guard_check_cases", -1),
136
+ ("gate_escapes", "escapes", "trial.guard_escapes", 1)):
137
+ va, vb = float(a.get(key) or 0), float(b.get(key) or 0)
138
+ bad = (vb - va) * worse >= params.value(margin)
139
+ out.append({"name": name, "a": va, "b": vb, "state": "failed" if bad else "held"})
140
+ return out
141
+
142
+
143
+ # -- metrics of one child run --------------------------------------------------------------------------------
144
+
145
+ def parse_target(target: str) -> tuple[str, str | None, str | None]:
146
+ m = TARGET.match(target.replace(" ", ""))
147
+ if not m:
148
+ raise TrialRefused(f"target {target!r} is not one of first_pass_yield(unit), gate_pass(unit), "
149
+ "criterion_met(unit, id), run_cost, outcome_met, label_agreement(gate)")
150
+ return m.group(1), m.group(2), m.group(3)
151
+
152
+
153
+ def _records(root: Path, workflow: str, task: str) -> list[dict[str, Any]]:
154
+ from tempergraph.run.events import records
155
+
156
+ return records(run_dir(root, workflow, task) / "run.jsonl")
157
+
158
+
159
+ def run_cost(recs: Sequence[Mapping[str, Any]]) -> float:
160
+ ex: Mapping[str, Any] = next((r for r in reversed(recs) if r.get("kind") == "run_exit"), {})
161
+ c = ex.get("cost") or {}
162
+ reported = float(c.get("reported") or 0)
163
+ return reported + float(c.get("estimated_only") or 0) if reported else float(c.get("estimated") or 0)
164
+
165
+
166
+ def measures(recs: Sequence[Mapping[str, Any]], metric: str, unit: str | None, crit: str | None) -> dict[str, Any]:
167
+ """The target value of one child run and the guard inputs; higher is better except `run_cost`."""
168
+ ex: Mapping[str, Any] = next((r for r in reversed(recs) if r.get("kind") == "run_exit"), {})
169
+ paused = ex.get("exit_code") == 3
170
+ gates = [r for r in recs if r.get("kind") == "gate" and (unit is None or r.get("unit") == unit)]
171
+ value: float | None
172
+ if metric == "first_pass_yield":
173
+ value = 1.0 if gates and gates[0].get("verdict") == "PROCEED" else 0.0
174
+ elif metric == "gate_pass":
175
+ value = sum(g.get("verdict") == "PROCEED" for g in gates) / len(gates) if gates else 0.0
176
+ elif metric == "criterion_met":
177
+ j: Mapping[str, Any] = next((r for r in reversed(recs) if r.get("kind") == "judgement" and r.get("unit") == unit), {})
178
+ value = 1.0 if any(s.get("id") == crit and s.get("status") == "MET" for s in j.get("statuses") or []) else 0.0
179
+ elif metric == "run_cost":
180
+ value = run_cost(recs)
181
+ elif metric == "outcome_met":
182
+ oc: Mapping[str, Any] = next((r for r in reversed(recs) if r.get("kind") == "outcome"), {})
183
+ value = 1.0 if oc.get("verdict") in ("met", "met_with_open") else 0.0
184
+ else:
185
+ value = None
186
+ o: Mapping[str, Any] = next((r for r in reversed(recs) if r.get("kind") == "outcome"), {})
187
+ checks = [r for r in recs if r.get("kind") == "check"]
188
+ proceeded: set[str] = set()
189
+ escapes = 0
190
+ for g in (r for r in recs if r.get("kind") == "gate"):
191
+ if g.get("verdict") == "PROCEED":
192
+ proceeded.add(str(g.get("unit")))
193
+ elif g.get("verdict") == "BACK":
194
+ escapes += 1 if any(str(r.get("unit")) in proceeded for r in recs
195
+ if r.get("kind") == "unit_entered" and r.get("entered_from") == f"back:{g.get('unit')}"
196
+ and int(r.get("seq") or 0) > int(g.get("seq") or 0)) else 0
197
+ return {"value": value, "paused": paused, "cost": run_cost(recs),
198
+ "outcome_met": 1.0 if o.get("verdict") in ("met", "met_with_open") else 0.0,
199
+ "check_pass": 1.0 if checks and all(c.get("result") == "PASS" for c in checks) else 0.0,
200
+ "escapes": float(escapes), "exit_code": ex.get("exit_code")}
201
+
202
+
203
+ def pair_result(metric: str, a: Mapping[str, Any], b: Mapping[str, Any]) -> str:
204
+ if a.get("paused") or b.get("paused") or a.get("value") is None or b.get("value") is None:
205
+ return "tie" # a case that stops at a pause is a tie
206
+ va, vb = float(a["value"]), float(b["value"])
207
+ if abs(va - vb) < 1e-9:
208
+ return "tie"
209
+ better = vb < va if metric == "run_cost" else vb > va
210
+ return "win" if better else "loss"
211
+
212
+
213
+ # -- records and caps ----------------------------------------------------------------------------------------
214
+
215
+ def trials_dir(root: Path) -> Path:
216
+ return root / "improve" / "trials"
217
+
218
+
219
+ def save(root: Path, rec: Mapping[str, Any]) -> None:
220
+ write_json(trials_dir(root) / f"{rec['trial_id']}.json", dict(rec))
221
+
222
+
223
+ def load_trial(root: Path, trial_id: str) -> dict[str, Any]:
224
+ if not re.match(r"^[A-Za-z0-9_-]{1,64}$", trial_id):
225
+ raise TrialRefused(f"{trial_id!r} is not a trial id")
226
+ path = trials_dir(root) / f"{trial_id}.json"
227
+ if not path.is_file():
228
+ raise TrialRefused(f"no trial {trial_id}")
229
+ return dict(read_json(path, "trial"))
230
+
231
+
232
+ def all_trials(root: Path) -> list[dict[str, Any]]:
233
+ d = trials_dir(root)
234
+ out = []
235
+ for p in sorted(d.glob("*.json")) if d.is_dir() else []:
236
+ try:
237
+ out.append(json.loads(p.read_text(encoding="utf-8")))
238
+ except (OSError, ValueError):
239
+ continue
240
+ return out
241
+
242
+
243
+ def _improvement(spec: WorkflowSpec) -> dict[str, Any]:
244
+ root = spec.package_root
245
+ try:
246
+ doc = json.loads((root / "tempergraph.json").read_text(encoding="utf-8")) if root else {}
247
+ except (OSError, ValueError):
248
+ return {}
249
+ return dict(doc.get("improvement") or {}) if isinstance(doc, dict) else {}
250
+
251
+
252
+ def caps(spec: WorkflowSpec, requested: float | None) -> tuple[float, float]:
253
+ imp = _improvement(spec)
254
+ per = float(imp.get("trial_cap_usd") or params.value("trial.cap_usd"))
255
+ monthly = float(imp.get("monthly_trial_cap_usd") or params.value("trial.monthly_cap_usd"))
256
+ return (min(per, requested) if requested is not None else per), monthly
257
+
258
+
259
+ def month_spend(root: Path, workflow: str, now: datetime | None = None) -> float:
260
+ since = ((now or datetime.now(UTC)) - timedelta(days=30)).isoformat()
261
+ return sum(float((t.get("spend") or {}).get("total") or 0) for t in all_trials(root)
262
+ if t.get("workflow") == workflow and str(t.get("at") or "") >= since)
263
+
264
+
265
+ def noise_floor(root: Path, workflow: str, digest: str) -> float | str:
266
+ aa = [t for t in all_trials(root) if t.get("kind") == "aa" and t.get("workflow") == workflow
267
+ and t.get("case_set_digest") == digest]
268
+ return aa[-1].get("noise_floor", "unknown") if aa else "unknown"
269
+
270
+
271
+ # -- running arms --------------------------------------------------------------------------------------------
272
+
273
+ ArmRunner = Callable[[WorkflowSpec, TrialCase, str, str], list[dict[str, Any]]]
274
+
275
+
276
+ @dataclass(kw_only=True)
277
+ class ChildRuns:
278
+ """Runs one case of one arm as an engine child run in `repo`, at the case's base, dry-run."""
279
+
280
+ repo: Path
281
+ registry: Any
282
+ settings: Callable[..., Any] | None = None
283
+ tasks: list[str] = field(default_factory=list)
284
+
285
+ def __call__(self, spec: WorkflowSpec, case: TrialCase, arm: str, trial_id: str) -> list[dict[str, Any]]:
286
+ from tempergraph.run.runner import RunSettings, start
287
+ from tempergraph.store.layout import state_root_path
288
+
289
+ task = re.sub(r"[^A-Za-z0-9._-]", "-", f"tr-{trial_id[:10]}-{case.case_id}-{arm}")[:64]
290
+ base = case.base if case.base.startswith("ref:") else f"ref:{case.base}"
291
+ rs = RunSettings(origin="trial", dry_run=True, workspace="worktree",
292
+ flags={"run.worktree.base": base}, caller={"kind": "engine", "decided_by": "engine"})
293
+ if self.settings is not None:
294
+ rs = self.settings(rs)
295
+ start(spec, task, {"request": case.request}, self.repo, self.registry, rs)
296
+ self.tasks.append(task)
297
+ return _records(state_root_path(self.repo), spec.name, task)
298
+
299
+
300
+ def _load(path: Path) -> WorkflowSpec:
301
+ from tempergraph.package.loader import load
302
+
303
+ return load(path)
304
+
305
+
306
+ def _judge_ready(root: Path, spec: WorkflowSpec, gate: str) -> tuple[bool, str]:
307
+ """PRP-B18, PRP-B19, PRP-B20: a judge-graded target needs FBK `reliable` and JCL `accepted` for that gate's judge."""
308
+ from tempergraph.improve import calibration as cal
309
+ from tempergraph.improve import reliability as rel
310
+
311
+ try:
312
+ accepted = cal.has_score(spec, gate, root)
313
+ grade = rel.report(root, spec.name, [gate], lambda g, b: cal.passing(spec, g))[0]["grade"]
314
+ except (cal.CalibrationError, OSError, ValueError):
315
+ return False, "unscored"
316
+ if grade != "reliable":
317
+ return False, f"judge {gate} is {grade} (FBK)"
318
+ if not accepted:
319
+ return False, f"judge {gate} is not accepted (JCL)"
320
+ return True, ""
321
+
322
+
323
+ def trial(root: Path, spec: WorkflowSpec, proposal_id: str, run_arm: ArmRunner, *, target: str | None = None,
324
+ cap_usd: float | None = None, now: datetime | None = None, judge_executor: Any = None) -> dict[str, Any]:
325
+ """`improve trial`: both arms on the case set, then the decision. Refusals spend nothing."""
326
+ from tempergraph.improve import proposals as prp
327
+
328
+ rec = prp.load_proposal(root, proposal_id)
329
+ if rec.get("state") not in ("drafted", "not_shown", "aborted"):
330
+ raise TrialRefused(f"proposal {proposal_id} is {rec.get('state')}; only a drafted proposal is trialled")
331
+ if rec.get("review_only"):
332
+ raise TrialRefused("a widening tools proposal is opened for review, never trialled alone (ADR `a-person-may-grant-a-step-tools-for-a-run`)")
333
+ unit = (rec.get("cluster") or {}).get("unit")
334
+ if rec.get("side") == "grader":
335
+ target = target or f"label_agreement({unit})"
336
+ target = target or (f"first_pass_yield({unit})" if unit else "run_cost")
337
+ metric, tunit, crit = parse_target(target)
338
+ if "weakening" in (rec.get("classes") or []) and metric not in ("label_agreement",):
339
+ raise TrialRefused("a weakening proposal is trialled on grader metrics only (PRP-B2)")
340
+ if metric in JUDGE_GRADED:
341
+ ok, why = _judge_ready(root, spec, "outcome" if metric == "outcome_met" else str(tunit))
342
+ if not ok:
343
+ raise TrialRefused(f"judge-graded target refused before spend: {why}")
344
+ per_cap, monthly = caps(spec, cap_usd)
345
+ if month_spend(root, spec.name, now) >= monthly:
346
+ raise TrialRefused(f"monthly trial cap ${monthly:.0f} reached for {spec.name}")
347
+ if prp.package_digest(spec.package_root) != rec.get("base_digest"): # type: ignore[arg-type]
348
+ raise TrialRefused("stale_base: the package changed since the proposal; rerun the proposer")
349
+ tid = uuid.uuid4().hex[:12]
350
+ out: dict[str, Any] = {"schema_version": 1, "kind": "trial", "trial_id": tid, "proposal_id": proposal_id,
351
+ "workflow": spec.name, "target_metric": target, "at": (now or datetime.now(UTC)).isoformat()}
352
+ if metric == "label_agreement":
353
+ if judge_executor is None:
354
+ raise TrialRefused("a label_agreement trial needs the gate's judge executor")
355
+ return trial_grader(root, spec, proposal_id, judge_executor, gate=str(tunit), now=now)
356
+ cases, digest = case_set(spec)
357
+ if not cases:
358
+ raise TrialRefused("no reviewed case set (evals/cases.json)")
359
+ out["case_set_digest"] = digest
360
+ out["noise_floor"] = noise_floor(root, spec.name, digest)
361
+ rec["state"], rec["trial_id"] = "trialling", tid
362
+ prp.save(root, rec)
363
+ pairs: list[dict[str, Any]] = []
364
+ spend = {"A": 0.0, "B": 0.0}
365
+ sums = {"A": {"cost": 0.0, "outcome_met": 0.0, "check_pass": 0.0, "escapes": 0.0},
366
+ "B": {"cost": 0.0, "outcome_met": 0.0, "check_pass": 0.0, "escapes": 0.0}}
367
+ aborted = False
368
+ threads = list((rec.get("cluster") or {}).get("threads") or [])
369
+ with tempfile.TemporaryDirectory(prefix="tg-trial-") as tmp:
370
+ assert spec.package_root is not None
371
+ b_root = prp.apply_patch(spec.package_root, str(rec.get("patch") or ""), Path(tmp) / spec.package_root.name)
372
+ for case in cases:
373
+ if spend["A"] + spend["B"] >= per_cap:
374
+ aborted = True # PRP-B7: no further case starts; the pairs so far are kept
375
+ break
376
+ got = {}
377
+ for arm, path in (("A", spec.package_root), ("B", b_root)):
378
+ arm_spec = _load(path) # loaded afresh per arm: callables resolve against this arm's code
379
+ recs = run_arm(arm_spec, case, arm, tid)
380
+ got[arm] = measures(recs, metric, tunit, crit)
381
+ spend[arm] += got[arm]["cost"]
382
+ for k in sums[arm]:
383
+ sums[arm][k] += float(got[arm][k])
384
+ pairs.append({"case": case.case_id, "a": got["A"]["value"], "b": got["B"]["value"],
385
+ "result": pair_result(metric, got["A"], got["B"]), "in_sample": in_sample(case, threads),
386
+ "stopped": bool(got["A"]["paused"] or got["B"]["paused"])})
387
+ _load(spec.package_root) # the import map points at the live package again
388
+ guards = guard_states(sums["A"], sums["B"])
389
+ out.update(pairs=pairs, guards=guards, spend={**{k: round(v, 6) for k, v in spend.items()},
390
+ "total": round(spend["A"] + spend["B"], 6), "cap": per_cap})
391
+ out.update(decide(pairs, guards, out["noise_floor"], aborted=aborted))
392
+ save(root, out)
393
+ rec["state"] = out["decision"]
394
+ prp.save(root, rec)
395
+ return out
396
+
397
+
398
+ def trial_grader(root: Path, spec: WorkflowSpec, proposal_id: str, executor: Any, *, gate: str | None = None,
399
+ now: datetime | None = None) -> dict[str, Any]:
400
+ """PRP-B5 for a grader proposal: per calibration case, the share of labelled criteria whose judged status
401
+ class matches the label, A against B."""
402
+ from tempergraph.improve import calibration as cal
403
+ from tempergraph.improve import proposals as prp
404
+
405
+ rec = prp.load_proposal(root, proposal_id)
406
+ if rec.get("state") not in ("drafted", "not_shown", "aborted"):
407
+ raise TrialRefused(f"proposal {proposal_id} is {rec.get('state')}")
408
+ gate = gate or str((rec.get("cluster") or {}).get("unit"))
409
+ assert spec.package_root is not None
410
+ tid = uuid.uuid4().hex[:12]
411
+ out: dict[str, Any] = {"schema_version": 1, "kind": "trial", "trial_id": tid, "proposal_id": proposal_id,
412
+ "workflow": spec.name, "target_metric": f"label_agreement({gate})",
413
+ "at": (now or datetime.now(UTC)).isoformat(), "noise_floor": "unknown"}
414
+ with tempfile.TemporaryDirectory(prefix="tg-trial-") as tmp:
415
+ b_root = prp.apply_patch(spec.package_root, str(rec.get("patch") or ""), Path(tmp) / spec.package_root.name)
416
+ scored = {}
417
+ for arm, path in (("A", spec.package_root), ("B", b_root)):
418
+ arm_spec = _load(path)
419
+ try:
420
+ scored[arm] = (cal.score(arm_spec, gate, executor, repeats=1, variants=(), write=False),
421
+ {u.case.case_id: u.labels for u in cal.usable(arm_spec, gate)[0]})
422
+ except cal.CalibrationError as exc:
423
+ raise TrialRefused(str(exc)) from exc
424
+ _load(spec.package_root)
425
+
426
+ def agreement(arm: str) -> dict[str, float]:
427
+ res, labels = scored[arm]
428
+ out_: dict[str, float] = {}
429
+ for r in res["results"]:
430
+ lab = labels.get(r["case"]) or {}
431
+ if not lab:
432
+ continue
433
+ same = [cal._klass(str(r["statuses"].get(c, cal.DISCARDED))) == cal._klass(e) for c, e in lab.items()]
434
+ out_[r["case"]] = sum(same) / len(same)
435
+ return out_
436
+
437
+ a, b = agreement("A"), agreement("B")
438
+ pairs = [{"case": c, "a": a[c], "b": b[c], "result": pair_result("label_agreement", {"value": a[c]},
439
+ {"value": b[c]}), "in_sample": False}
440
+ for c in sorted(set(a) & set(b))]
441
+ spend = {"A": scored["A"][0]["usage"]["cost_usd"], "B": scored["B"][0]["usage"]["cost_usd"]}
442
+ out.update(pairs=pairs, guards=[], spend={**spend, "total": round(spend["A"] + spend["B"], 6)})
443
+ out.update(decide(pairs, []))
444
+ save(root, out)
445
+ rec["state"], rec["trial_id"] = out["decision"], tid
446
+ prp.save(root, rec)
447
+ return out
448
+
449
+
450
+ RESULT_MARKER = "<!-- tg-agent: kind=result agent=loop -->" # CONTRIBUTING.md 5.1
451
+ RESULT_FOOTER = "---\n_Generated by [Claude Code](https://claude.ai/code)_"
452
+
453
+
454
+ def result_text(t: Mapping[str, Any]) -> str:
455
+ """PRP-B25: the trial's decision and figures in the agent comment format; ids, enums and numbers, no run text."""
456
+ c = t.get("counts") or {}
457
+ spend = t.get("spend") or {}
458
+ guards = ", ".join(f"{g.get('name')} {g.get('state')}" for g in t.get("guards") or []) or "none"
459
+ reason = f" ({t.get('reason')})" if t.get("reason") else ""
460
+ rows = [RESULT_MARKER, f"**Result:** trial `{t.get('trial_id')}` of proposal `{t.get('proposal_id')}`: "
461
+ f"{t.get('decision')}{reason} on `{t.get('target_metric')}`.", "",
462
+ f"Pairs: {c.get('wins', 0)} wins, {c.get('losses', 0)} losses, {c.get('ties', 0)} ties out of sample; "
463
+ f"{c.get('in_sample', 0)} in-sample pairs reported apart.",
464
+ f"Guards: {guards}.",
465
+ f"Noise floor: {t.get('noise_floor')}. Spend: ${float(spend.get('total') or 0):.2f}.", "",
466
+ "The loop never merges; a person decides.", "", RESULT_FOOTER]
467
+ return "\n".join(rows)
468
+
469
+
470
+ def comment_result(root: Path, trial: Mapping[str, Any], host: Any, *, autonomy: str) -> list[dict[str, Any]]:
471
+ """PRP-B25: one `result` comment on each issue of the trialled proposal's cluster, in any decision, at autonomy
472
+ `file` or above; none at `record`. A host that cannot be reached leaves the comment in the outbox (SIL-B19) and the
473
+ trial record untouched."""
474
+ from tempergraph.improve import filing
475
+ from tempergraph.improve import proposals as prp
476
+ from tempergraph.improve.codehost import CodeHostError
477
+
478
+ if autonomy not in ("file", "propose", "trial"):
479
+ return []
480
+ try:
481
+ rec = prp.load_proposal(root, str(trial.get("proposal_id")))
482
+ except prp.ProposalError:
483
+ return []
484
+ text = result_text(trial)
485
+ out: list[dict[str, Any]] = []
486
+ for ref in dict.fromkeys(r for r in map(prp.issue_ref, (rec.get("cluster") or {}).get("issues") or []) if r):
487
+ p = {"op": "comment", "repo": ref[0], "number": ref[1], "body": text, "fingerprint": None}
488
+ try:
489
+ out.append({"op": "commented", "url": filing._deliver(host, p), "repo": ref[0], "number": ref[1]})
490
+ except CodeHostError:
491
+ filing.Outbox.at(root).add(p)
492
+ out.append({"op": "queued", "repo": ref[0], "number": ref[1]})
493
+ return out
494
+
495
+
496
+ def aa(root: Path, spec: WorkflowSpec, run_arm: ArmRunner, *, cap_usd: float | None = None) -> dict[str, Any]:
497
+ """`improve aa`: the case set twice on the current version; the share of differing pairs is the floor."""
498
+ cases, digest = case_set(spec)
499
+ if not cases:
500
+ raise TrialRefused("no reviewed case set (evals/cases.json)")
501
+ per_cap, monthly = caps(spec, cap_usd)
502
+ if month_spend(root, spec.name) >= monthly:
503
+ raise TrialRefused(f"monthly trial cap ${monthly:.0f} reached for {spec.name}")
504
+ tid = uuid.uuid4().hex[:12]
505
+ pairs: list[dict[str, Any]] = []
506
+ spent = 0.0
507
+ aborted = False
508
+ for case in cases:
509
+ if spent >= per_cap:
510
+ aborted = True
511
+ break
512
+ vals = []
513
+ for arm in ("A1", "A2"):
514
+ m = measures(run_arm(_load(spec.package_root), case, arm, tid), "run_cost", None, None) # type: ignore[arg-type]
515
+ spent += m["cost"]
516
+ vals.append(m)
517
+ differ = (vals[0]["exit_code"], vals[0]["outcome_met"], vals[0]["check_pass"]) != (
518
+ vals[1]["exit_code"], vals[1]["outcome_met"], vals[1]["check_pass"])
519
+ pairs.append({"case": case.case_id, "differ": differ})
520
+ floor: float | str = (sum(1 for p in pairs if p["differ"]) / len(pairs)) if pairs else "unknown"
521
+ out = {"schema_version": 1, "kind": "aa", "trial_id": tid, "workflow": spec.name, "case_set_digest": digest,
522
+ "pairs": pairs, "noise_floor": floor, "aborted": aborted, "spend": {"total": round(spent, 6)},
523
+ "at": now_iso()}
524
+ save(root, out)
525
+ return out
@@ -0,0 +1,11 @@
1
+ """First install of the engine (UPD-B18, UPD-B19): the bootstrap the plugin's launcher runs, the engine environment,
2
+ the shim and the `PATH` block, and the self-check.
3
+
4
+ Like the updater, this package loads none of the engine's compiled libraries: its modules import the
5
+ standard library and the stdlib-only engine modules in :data:`BOOTSTRAP_IMPORTS` (a source-scan test pins it).
6
+ """
7
+
8
+ BOOTSTRAP_IMPORTS = (
9
+ "tempergraph.constants", "tempergraph.docs", "tempergraph.git", "tempergraph.store.layout",
10
+ "tempergraph.security.launch", "tempergraph.release", "tempergraph.install", "tempergraph.store.migrate",
11
+ )