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,564 @@
1
+ """`evals score|bar|label` (JCL-B14, JCL-B18), `labels queue|grades` (FBK-B11, FBK-B12, FBK-B13) and the `improve` verbs (PRP-B4, PRP-B12, PRP-B18, PRP-B21, PRP-B8, PRP-B22).
2
+
3
+ Only `evals score`, `improve propose` (without `--patch`), `improve analyse` (one read-only session, CAN-B1),
4
+ `improve trial` and `improve aa` start sessions;
5
+ every other verb here is model-free.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import contextlib
12
+ import os
13
+ from typing import Any
14
+
15
+
16
+ def _caller(p: argparse.ArgumentParser) -> None:
17
+ p.add_argument("--caller", choices=("person", "agent", "pipeline", "orchestrator", "scheduler", "engine"))
18
+ p.add_argument("--as-agent", action="store_true")
19
+ p.add_argument("--caller-app")
20
+ p.add_argument("--relayed", action="store_true")
21
+
22
+
23
+ def add_parsers(sub: Any, parser_class: type[argparse.ArgumentParser]) -> None:
24
+ pc = sub.add_parser("promote-check", help="measure a workflow version against a stage's criteria (PRO)")
25
+ pc.add_argument("workflow")
26
+ pc.add_argument("--to", required=True, choices=("local-stable", "pipeline"))
27
+ pc.add_argument("--executor")
28
+ pc.add_argument("--window", type=int, default=None, metavar="N")
29
+ pc.add_argument("--stamp", action="store_true", help="write the promotion stamp when every criterion is met")
30
+ pc.add_argument("--caller", choices=("person", "agent", "pipeline", "orchestrator", "scheduler", "engine"))
31
+ pc.add_argument("--relayed", action="store_true")
32
+ pc.add_argument("--json", action="store_true")
33
+ ev = sub.add_parser("evals", help="judge calibration: score, bar and gold labels (JCL)")
34
+ esub = ev.add_subparsers(dest="action", parser_class=parser_class)
35
+ sc = esub.add_parser("score", help="score the gate's judge on its reviewed cases (spends)")
36
+ sc.add_argument("workflow")
37
+ sc.add_argument("gate")
38
+ sc.add_argument("--executor")
39
+ sc.add_argument("--repeat", type=int, default=3)
40
+ sc.add_argument("--variants", default="persuasive_account,out_of_reach",
41
+ help="comma-separated kinds, or none")
42
+ sc.add_argument("--cap", type=float, default=None, metavar="USD")
43
+ sc.add_argument("--level", help="score the judge of this risk level (JRK-B9, JRK-B5)")
44
+ sc.add_argument("--json", action="store_true")
45
+ ba = esub.add_parser("bar", help="each gate's acceptance state, figures and failing rules")
46
+ ba.add_argument("workflow", nargs="?")
47
+ ba.add_argument("--json", action="store_true")
48
+ ru = esub.add_parser("run", help="run the eval suites of one kind and record the results (EVS-B17, EVS-B18)")
49
+ ru.add_argument("workflow")
50
+ ru.add_argument("--kind", required=True, choices=("check", "judge", "step", "workflow"))
51
+ ru.add_argument("--role", choices=("regression", "capability"))
52
+ ru.add_argument("--trials", type=int)
53
+ ru.add_argument("--executor")
54
+ ru.add_argument("--cap", type=float, default=None, metavar="USD")
55
+ ru.add_argument("--json", action="store_true")
56
+ rep = esub.add_parser("report", help="figures per suite and case, graduation, stale and waiting results")
57
+ rep.add_argument("workflow")
58
+ rep.add_argument("--json", action="store_true")
59
+ gr_ = esub.add_parser("grade", help="a person's grade for a trial no grader could decide")
60
+ gr_.add_argument("result")
61
+ verdict = gr_.add_mutually_exclusive_group(required=True)
62
+ verdict.add_argument("--pass", dest="passed", action="store_true")
63
+ verdict.add_argument("--fail", dest="failed", action="store_true")
64
+ gr_.add_argument("--reason", required=True)
65
+ gr_.add_argument("--json", action="store_true")
66
+ hv = esub.add_parser("harvest", help="turn recorded judge misses into local calibration case candidates")
67
+ hv.add_argument("workflow")
68
+ hv.add_argument("gate")
69
+ hv.add_argument("--json", action="store_true")
70
+ rpl = esub.add_parser("replay", help="rerun the judges on kept cases and compare with the recorded score")
71
+ rpl.add_argument("workflow")
72
+ rpl.add_argument("--executor")
73
+ rpl.add_argument("--cap", type=float, default=None, metavar="USD")
74
+ rpl.add_argument("--json", action="store_true")
75
+ la = esub.add_parser("label", help="write or confirm one gold label as a reviewer")
76
+ la.add_argument("case", metavar="WORKFLOW/GATE/CASE")
77
+ la.add_argument("--criterion", required=True)
78
+ la.add_argument("--expected", required=True, choices=("MET", "PARTIAL", "UNMET", "N/A", "UNVERIFIABLE"))
79
+ la.add_argument("--reason", required=True)
80
+ la.add_argument("--reviewer")
81
+ la.add_argument("--json", action="store_true")
82
+ _caller(la)
83
+ lq = sub.add_parser("labels", help="the labelling queue and judge reliability grades (FBK)")
84
+ lsub = lq.add_subparsers(dest="action", parser_class=parser_class)
85
+ qu = lsub.add_parser("queue")
86
+ qu.add_argument("workflow")
87
+ qu.add_argument("--json", action="store_true")
88
+ gr = lsub.add_parser("grades")
89
+ gr.add_argument("workflow")
90
+ gr.add_argument("--json", action="store_true")
91
+ im = sub.add_parser("improve", help="clusters, proposals, paired trials and cause analyses (PRP-B4, PRP-B12, PRP-B18, "
92
+ "PRP-B21, PRP-B8, PRP-B22, CAN-B1)")
93
+ isub = im.add_subparsers(dest="action", parser_class=parser_class)
94
+ bl = isub.add_parser("backlog")
95
+ bl.add_argument("workflow", nargs="?")
96
+ bl.add_argument("--json", action="store_true")
97
+ pr = isub.add_parser("propose")
98
+ pr.add_argument("workflow")
99
+ pr.add_argument("cluster")
100
+ pr.add_argument("--patch", metavar="FILE", help="a person's unified diff over the package")
101
+ pr.add_argument("--rule", help="the general rule the change states (needed with --patch)")
102
+ pr.add_argument("--executor")
103
+ pr.add_argument("--json", action="store_true")
104
+ tr = isub.add_parser("trial")
105
+ tr.add_argument("proposal")
106
+ tr.add_argument("--target", help="first_pass_yield(unit), run_cost, outcome_met, ...")
107
+ tr.add_argument("--cap", type=float, default=None, metavar="USD")
108
+ tr.add_argument("--executor")
109
+ tr.add_argument("--json", action="store_true")
110
+ aa = isub.add_parser("aa")
111
+ aa.add_argument("workflow")
112
+ aa.add_argument("--cap", type=float, default=None, metavar="USD")
113
+ aa.add_argument("--json", action="store_true")
114
+ op = isub.add_parser("open")
115
+ op.add_argument("proposal")
116
+ op.add_argument("--json", action="store_true")
117
+ sh = isub.add_parser("show")
118
+ sh.add_argument("record", metavar="PROPOSAL|TRIAL|ANALYSIS")
119
+ an = isub.add_parser("analyse", help="one read-only session on one cluster and a checked cause record under "
120
+ "improve/analyses/ (CAN-B1)")
121
+ an.add_argument("workflow")
122
+ an.add_argument("cluster")
123
+ an.add_argument("--executor")
124
+ an.add_argument("--json", action="store_true")
125
+ from tempergraph.cli.improve_review import add_review_parser
126
+
127
+ add_review_parser(isub) # SRV-B23
128
+ ob = isub.add_parser("outbox", help="the filing outbox: `list` its waiting entries, `clear` them, `send` them "
129
+ "under the daily issue cap (CLI-B21, CLI-B22, CLI-B26)")
130
+ osub = ob.add_subparsers(dest="outbox_action", parser_class=parser_class)
131
+ osub.add_parser("list", help="print the waiting entries, oldest first, without their text")
132
+ sd = osub.add_parser("send", help="deliver the waiting entries under the daily issue cap")
133
+ _caller(sd)
134
+ cl = osub.add_parser("clear", help="remove every entry (--all) or those of one fingerprint (--fingerprint)")
135
+ cl.add_argument("--all", action="store_true", help="remove every entry")
136
+ cl.add_argument("--fingerprint", metavar="FINGERPRINT", help="remove the entries of this fingerprint")
137
+ _caller(cl)
138
+
139
+
140
+ def _usage(msg: str) -> Exception:
141
+ from tempergraph.cli.main import UsageError
142
+
143
+ return UsageError(msg)
144
+
145
+
146
+ def _suites(env: Any, a: argparse.Namespace) -> int:
147
+ """`evals run|report|grade` (EVS-B17, EVS-B18). Only `run` on a live kind makes a model call."""
148
+ from tempergraph.cli.main import _emit, _root, _spec
149
+ from tempergraph.improve import calibration as cal
150
+ from tempergraph.improve import suites
151
+
152
+ root = _root(env)
153
+ try:
154
+ if a.action == "grade":
155
+ by = os.environ.get("USER") or "unknown"
156
+ doc: dict[str, Any] = suites.person_grade(root, a.result, bool(a.passed), a.reason, by)
157
+ text = f"result {a.result} graded {'passed' if a.passed else 'failed'}\n"
158
+ elif a.action == "report":
159
+ doc = suites.report(_spec(env, a.workflow), root)
160
+ lines = [f"{s['kind']} {s['subject']} ({s['role']}): {s['status']}"
161
+ + (f", pass@1 {s['figures']['pass_at_1']:.2f}" if s["figures"]["pass_at_1"] is not None else "")
162
+ + (f", pass^k {s['figures']['pass_hat_k']:.2f}" if s["figures"]["pass_hat_k"] is not None else "")
163
+ for s in doc["suites"]]
164
+ lines += [f"graduate: {g['kind']} {g['subject']} {g['case']}" for g in doc["graduation"]]
165
+ lines += [f"needs a person: {w['command']}" for w in doc["needs_person"]]
166
+ lines += [f"never passed, check the case first: {n['kind']} {n['subject']} {n['case']}"
167
+ for n in doc["never_passed"]]
168
+ text = "\n".join(lines or [f"{a.workflow}: no eval result recorded"]) + "\n"
169
+ else:
170
+ spec = _spec(env, a.workflow)
171
+ ex = None
172
+ if a.kind != "check":
173
+ name = a.executor or spec.default_executor
174
+ if a.kind == "judge" and not a.executor:
175
+ name = env.registry.judge_executor(spec.default_executor, None, None)
176
+ ex = env.registry.get(name)
177
+ doc = suites.run(spec, a.kind, root, registry=env.registry, repo=env.cwd, executor=ex, role=a.role,
178
+ trials=a.trials, cap_usd=a.cap)
179
+ done = sum(1 for r in doc["results"] if r["status"] == "passed")
180
+ text = (f"{a.workflow} {a.kind}: {done} of {len(doc['results'])} trials passed"
181
+ + (" (partial: the cap was reached)" if doc["partial"] else "") + "\n")
182
+ except (suites.SuiteRefused, cal.CalibrationError) as exc:
183
+ raise _usage(str(exc)) from exc
184
+ if a.json:
185
+ _emit(env, doc)
186
+ else:
187
+ env.out.write(text)
188
+ failed = a.action == "run" and any(r["status"] in ("failed", "invalid") and r["role"] == "regression"
189
+ for r in doc["results"])
190
+ return 1 if failed else 0
191
+
192
+
193
+ def cmd_evals(env: Any, a: argparse.Namespace) -> int:
194
+ from tempergraph.cli.main import _emit, _root_or_none, _spec
195
+ from tempergraph.improve import calibration as cal
196
+
197
+ if a.action in ("run", "report", "grade"):
198
+ return _suites(env, a)
199
+ if a.action in ("harvest", "replay"):
200
+ from tempergraph.cli.main import _root
201
+ from tempergraph.improve import harvest as hv
202
+ from tempergraph.improve import suites
203
+
204
+ spec = _spec(env, a.workflow)
205
+ try:
206
+ if a.action == "harvest":
207
+ rows = hv.harvest(_root(env), spec, a.gate)
208
+ out: dict[str, Any] = {"schema_version": 1, "workflow": spec.name, "gate": a.gate, "candidates": rows}
209
+ text = "".join(f"{'new' if r['new'] else 'kept'} {r['case_id']}: {r['path']}\n" for r in rows) or \
210
+ f"{a.gate}: no recorded judge miss to harvest\n"
211
+ text += "Review each candidate, copy it into the package's evals/calibration and label it with " \
212
+ "`tempergraph evals label`.\n" if rows else ""
213
+ else:
214
+ name = a.executor or env.registry.judge_executor(spec.default_executor, None, None)
215
+ out = hv.replay(spec, _root(env), env.registry.get(name), cap_usd=a.cap)
216
+ text = "".join(f"{g['gate']}: {g['cases']} cases, agreement "
217
+ f"{g['agreement'] if g['agreement'] is not None else '-'}, {len(g['flips'])} changed\n"
218
+ for g in out["gates"]) or f"{spec.name}: no scored case to replay\n"
219
+ except (cal.CalibrationError, suites.SuiteRefused) as exc:
220
+ raise _usage(str(exc)) from exc
221
+ if a.json:
222
+ _emit(env, out)
223
+ else:
224
+ env.out.write(text)
225
+ return 0
226
+ if a.action == "bar":
227
+ specs = [_spec(env, a.workflow)] if a.workflow else list(env.catalog.specs.values())
228
+ root = _root_or_none(env)
229
+ doc: dict[str, Any] = {"schema_version": 1, "workflows": []}
230
+ for spec in specs:
231
+ rows = []
232
+ for st in cal.states(spec, root, every_level=True):
233
+ rows.append({**st.to_json(), "needed": cal.needed(st)})
234
+ doc["workflows"].append({"workflow": spec.name, "gates": rows})
235
+ if a.json:
236
+ _emit(env, doc)
237
+ else:
238
+ for w in doc["workflows"]:
239
+ for g in w["gates"]:
240
+ env.out.write(f"{w['workflow']} {g['gate']}" + (f" level {g['level']}" if g.get("level") else "")
241
+ + f": {g['state']}"
242
+ + (f" ({'; '.join(g['failing'])})" if g["failing"] else "")
243
+ + (f"; needs {', '.join(g['needed'])}" if g["needed"] else "") + "\n")
244
+ return 0
245
+ if a.action == "label":
246
+ parts = a.case.split("/")
247
+ if len(parts) != 3:
248
+ raise _usage("evals label: the case is WORKFLOW/GATE/CASE")
249
+ spec = _spec(env, parts[0])
250
+ from tempergraph.provenance import decide
251
+ from tempergraph.store.layout import home_path
252
+
253
+ decided = decide(env.caller(a), relayed=bool(a.relayed), words=("evals", "label"), home=home_path())
254
+ reviewer = a.reviewer or os.environ.get("USER") or "unknown"
255
+ try:
256
+ case = cal.write_label(spec, parts[1], parts[2], a.criterion, a.expected, a.reason, reviewer,
257
+ person=decided.get("decided_by") == "person")
258
+ except cal.CalibrationError as exc:
259
+ raise _usage(str(exc)) from exc
260
+ doc = {"case": case.case_id, "gate": case.gate, "state": case.state, "split": case.split,
261
+ "criterion": a.criterion, "expected": a.expected, "by_person": decided.get("decided_by") == "person"}
262
+ if a.json:
263
+ _emit(env, doc)
264
+ else:
265
+ env.out.write(f"label {a.expected} on {a.case} {a.criterion} written; case is {case.state}\n")
266
+ return 0
267
+ if a.action == "score":
268
+ spec = _spec(env, a.workflow)
269
+ kinds = [] if a.variants in ("none", "") else [k.strip() for k in a.variants.split(",") if k.strip()]
270
+ try:
271
+ g, _, step_ex = cal.gate_spec(spec, a.gate)
272
+ name = a.executor or (g.judge.executor if g.judge else None) or env.registry.judge_executor(
273
+ step_ex, None, None)
274
+ ex = env.registry.get(name)
275
+ rec = cal.score(spec, a.gate, ex, repeats=a.repeat, variants=kinds, cap_usd=a.cap,
276
+ run_by="person", level=a.level)
277
+ st = cal.state(spec, a.gate, level=a.level)
278
+ except cal.CalibrationError as exc:
279
+ raise _usage(str(exc)) from exc
280
+ doc = {"score_id": rec["score_id"], "gate": a.gate, **({"level": a.level} if a.level else {}), "partial": rec["partial"], "usage": rec["usage"],
281
+ "figures": rec["figures"], "state": st.state, "failing": st.failing}
282
+ if a.json:
283
+ _emit(env, doc)
284
+ else:
285
+ env.out.write(f"scored {a.workflow} {a.gate}: {st.state}, {rec['usage']['sessions']} sessions, "
286
+ f"${rec['usage']['cost_usd']:.2f}" + (" (partial: cap reached)" if rec["partial"] else "")
287
+ + "\n")
288
+ return 0
289
+ raise _usage("evals needs score, bar or label")
290
+
291
+
292
+ def _live(spec: Any) -> Any:
293
+ from tempergraph.improve import calibration as cal
294
+
295
+ return lambda gate, binding: cal.passing(spec, gate)
296
+
297
+
298
+ def cmd_labels(env: Any, a: argparse.Namespace) -> int:
299
+ from tempergraph.cli.main import _emit, _root, _spec
300
+ from tempergraph.improve import calibration as cal
301
+ from tempergraph.improve import reliability as rel
302
+
303
+ spec = _spec(env, a.workflow)
304
+ root = _root(env)
305
+ grades = rel.report(root, spec.name, cal.judged_gates(spec), _live(spec))
306
+ if a.action == "grades":
307
+ if a.json:
308
+ _emit(env, {"schema_version": 1, "workflow": spec.name, "gates": grades})
309
+ else:
310
+ for g in grades:
311
+ env.out.write(f"{g['gate']}: {g['grade']}" + (f" ({'; '.join(g['why'])})" if g["why"] else "") + "\n")
312
+ return 0
313
+ if a.action == "queue":
314
+ rows = rel.queue(root, spec.name, {g["gate"]: g["grade"] for g in grades})
315
+ if a.json:
316
+ _emit(env, {"schema_version": 1, "workflow": spec.name, "queue": rows})
317
+ else:
318
+ for r in rows:
319
+ env.out.write(f"{r['why']}: {r['command']}\n")
320
+ return 0
321
+ raise _usage("labels needs queue or grades")
322
+
323
+
324
+ def _host() -> Any:
325
+ from tempergraph.improve.codehost import GhCodeHost
326
+
327
+ return GhCodeHost()
328
+
329
+
330
+ def _arm_runner(env: Any) -> Any:
331
+ from tempergraph.improve.trials import ChildRuns
332
+
333
+ return ChildRuns(repo=env.cwd, registry=env.registry, settings=env.run_settings)
334
+
335
+
336
+ def cmd_improve(env: Any, a: argparse.Namespace) -> int:
337
+ if a.action == "review":
338
+ from tempergraph.cli.improve_review import cmd_review
339
+
340
+ return cmd_review(env, a)
341
+ from tempergraph.cli.main import _emit, _root, _spec
342
+ from tempergraph.improve import analysis as ana
343
+ from tempergraph.improve import proposals as prp
344
+ from tempergraph.improve import trials as trl
345
+
346
+ root = _root(env)
347
+ if a.action == "outbox":
348
+ return _outbox(env, a, root)
349
+ try:
350
+ if a.action == "analyse": # CAN-B1 to CAN-B4, CAN-B21: no code host is asked for
351
+ spec = _spec(env, a.workflow)
352
+ name = a.executor or spec.default_executor
353
+ if name not in env.registry.available():
354
+ raise _usage(f"executor {name!r} is not registered in this release (not_in_release)")
355
+ rec = ana.analyse(root, spec, a.cluster, env.registry.get(name))
356
+ _out(env, a, rec, f"analysis {rec['analysis_id']}: {rec['state']}"
357
+ + (f" ({rec['refusal']})" if rec.get("refusal") else ""))
358
+ return 0
359
+ if a.action == "backlog":
360
+ specs = [_spec(env, a.workflow)] if a.workflow else list(env.catalog.specs.values())
361
+ machine = os.environ.get("TEMPERGRAPH_AUTONOMY")
362
+ doc: dict[str, Any] = {"schema_version": 1,
363
+ "autonomy": {s.name: prp.autonomy(s, machine) for s in specs},
364
+ "clusters": [{**c, "analysis": ana.summary(ana.newest(root, c["workflow"], c["cluster_id"]))}
365
+ for s in specs for c in prp.clusters(root, s.name)]}
366
+ if a.json:
367
+ _emit(env, doc)
368
+ else:
369
+ for c in doc["clusters"]:
370
+ env.out.write(f"{c['cluster_id']} {c['workflow']} {c['side']} {c['unit'] or '-'} {c['cause']}: "
371
+ f"score {c['score']:.2f}, {c['runs']} runs" + (" (twin folded)" if c["twin_of"] else "")
372
+ + "\n")
373
+ return 0
374
+ if a.action == "propose":
375
+ spec = _spec(env, a.workflow)
376
+ cl = prp.cluster(root, spec.name, a.cluster)
377
+ if a.patch:
378
+ if not a.rule:
379
+ raise _usage("improve propose --patch needs --rule <the general rule the change states>")
380
+ from pathlib import Path
381
+
382
+ text = Path(a.patch).read_text(encoding="utf-8")
383
+ rec = prp.record(root, spec, cl, text, author="person", rule=a.rule)
384
+ else:
385
+ name = a.executor or spec.default_executor
386
+ rec = prp.propose(root, spec, cl, env.registry.get(name))
387
+ line = (f"proposal {rec['proposal_id']}: {rec['state']}"
388
+ + (f" ({rec['refusal']})" if rec.get("refusal") else "") + f", classes {rec.get('classes')}")
389
+ if rec.get("refusal") == "literal" and rec.get("literal_hits"): # PLC-B9: where each hit is, no text
390
+ line += "\n" + "; ".join(f"{h['kind']} {h['file']} line {h['line']} length {h['length']}"
391
+ for h in rec["literal_hits"])
392
+ _out(env, a, rec, line)
393
+ return 0 if rec["state"] != "refused" else 2
394
+ if a.action == "trial":
395
+ from tempergraph.store.layout import outside_git
396
+
397
+ if outside_git(env.cwd): # a trial runs its arms in worktrees (WSP-B15 to WSP-B18)
398
+ raise _usage("needs_git: a trial needs a git repository")
399
+ rec = prp.load_proposal(root, a.proposal)
400
+ spec = _spec(env, str(rec["workflow"]))
401
+ judge = env.registry.get(a.executor or spec.default_executor) if rec.get("side") == "grader" else None
402
+ out = trl.trial(root, spec, a.proposal, _arm_runner(env), target=a.target, cap_usd=a.cap,
403
+ judge_executor=judge)
404
+ from tempergraph.improve.codehost import CodeHostError
405
+
406
+ with contextlib.suppress(CodeHostError): # PRP-B25: a host that is down leaves the comment in the outbox
407
+ trl.comment_result(root, out, _host(), autonomy=prp.autonomy(spec, os.environ.get("TEMPERGRAPH_AUTONOMY")))
408
+ _out(env, a, out, f"trial {out['trial_id']}: {out['decision']}"
409
+ + (f" ({out['reason']})" if out.get("reason") else "")
410
+ + f", {out['counts']['wins']} wins {out['counts']['losses']} losses {out['counts']['ties']} ties")
411
+ return 0
412
+ if a.action == "aa":
413
+ spec = _spec(env, a.workflow)
414
+ out = trl.aa(root, spec, _arm_runner(env), cap_usd=a.cap)
415
+ _out(env, a, out, f"A/A {out['trial_id']}: noise floor {out['noise_floor']}")
416
+ return 0
417
+ if a.action == "open":
418
+ rec = prp.load_proposal(root, a.proposal)
419
+ spec = _spec(env, str(rec["workflow"]))
420
+ out = prp.open_pr(root, spec, a.proposal, _host())
421
+ _out(env, a, out, f"proposal {a.proposal}: " + (f"draft pull request {out['pull_request']}"
422
+ if out.get("pull_request") else
423
+ f"not opened ({out.get('open_error')})"))
424
+ return 0 if out.get("pull_request") else 1
425
+ if a.action == "show":
426
+ try:
427
+ doc = prp.load_proposal(root, a.record)
428
+ except prp.ProposalError:
429
+ try:
430
+ doc = trl.load_trial(root, a.record)
431
+ except trl.TrialRefused:
432
+ doc = ana.load_analysis(root, a.record) # CAN-B23
433
+ _emit(env, doc)
434
+ return 0
435
+ except (prp.ProposalError, trl.TrialRefused, ana.AnalysisRefused) as exc:
436
+ raise _usage(str(exc)) from exc
437
+ raise _usage("improve needs backlog, propose, analyse, trial, aa, open, show or outbox")
438
+
439
+
440
+ def _age_days(entry: dict[str, Any], now: Any) -> float | None:
441
+ from datetime import UTC, datetime
442
+
443
+ try:
444
+ at = datetime.fromisoformat(str(entry.get("queued_at") or "").replace("Z", "+00:00"))
445
+ except ValueError:
446
+ return None
447
+ at = at if at.tzinfo else at.replace(tzinfo=UTC)
448
+ return round((now - at).total_seconds() / 86400, 1)
449
+
450
+
451
+ def _outbox(env: Any, a: argparse.Namespace, root: Any) -> int:
452
+ """CLI-B21 to CLI-B23: list the filing outbox without a body, or clear it whole or by fingerprint."""
453
+ from datetime import UTC, datetime
454
+
455
+ from tempergraph.cli.main import _emit
456
+ from tempergraph.improve.filing import Outbox
457
+
458
+ box = Outbox.at(root)
459
+ if a.outbox_action == "list":
460
+ now = datetime.now(UTC)
461
+ rows = []
462
+ for e in box.entries():
463
+ row: dict[str, Any] = {"op": e.get("op"), "repo": e.get("repo")}
464
+ if e.get("op") == "create":
465
+ row["title"] = e.get("title")
466
+ else:
467
+ row["number"] = e.get("number")
468
+ row["fingerprint"] = e.get("fingerprint")
469
+ row["age_days"] = _age_days(e, now)
470
+ if e.get("capped") is True: # ICAP-B10: kept for the cap, not put back by a refused send
471
+ row["capped"] = True
472
+ rows.append(row)
473
+ rows.sort(key=lambda r: (r["age_days"] is None, -(r["age_days"] or 0.0))) # oldest first, none last
474
+ _emit(env, {"schema_version": 1, "entries": rows})
475
+ return 0
476
+ if a.outbox_action == "clear":
477
+ if bool(a.all) == bool(a.fingerprint):
478
+ raise _usage("improve outbox clear needs exactly one of --all and --fingerprint <fingerprint>")
479
+ caller = env.caller(a)
480
+ removed = box.remove(None if a.all else a.fingerprint)
481
+ _emit(env, {"schema_version": 1, "removed": removed, "caller": caller})
482
+ return 0
483
+ if a.outbox_action == "send":
484
+ from tempergraph.improve import filing
485
+
486
+ caller = env.caller(a)
487
+ cap = _file_issue_cap(root)
488
+ results = filing.file([], _host(), box, issue_cap=cap, now=datetime.now(UTC)) if box.entries() else []
489
+ sent = sum(1 for r in results if r.get("op") in ("redelivered", "commented"))
490
+ dropped = sum(1 for r in results if r.get("op") == "outbox_dropped")
491
+ _emit(env, {"schema_version": 1, "sent": sent, "stayed": len(box.entries()), "dropped": dropped,
492
+ "caller": caller})
493
+ return 0
494
+ raise _usage("improve outbox needs list, clear or send")
495
+
496
+
497
+ def _file_issue_cap(root: Any) -> int:
498
+ """ICAP-B13: `run.loop_issue_cap` from the settings files with no workflow: the `defaults` and the `overrides`
499
+ entries for workflow `*`, ranked as RST-B22 ranks them; a value the catalog refuses, or none, gives 3."""
500
+ from collections.abc import Mapping
501
+
502
+ from tempergraph import settings as rst
503
+ from tempergraph.store.layout import home_path
504
+
505
+ try:
506
+ files = rst.load_files(root, home_path())
507
+ except Exception:
508
+ return 3
509
+ key = "run.loop_issue_cap"
510
+ for doc_name, section in (("project", "overrides"), ("user", "overrides"), ("project", "defaults"),
511
+ ("user", "defaults")):
512
+ doc = getattr(files, doc_name)
513
+ if not isinstance(doc, Mapping):
514
+ continue
515
+ values: list[Any] = []
516
+ if section == "overrides":
517
+ for entry in doc.get("overrides") or []:
518
+ if isinstance(entry, Mapping) and entry.get("workflow") == "*" and isinstance(entry.get("set"), Mapping) \
519
+ and key in entry["set"]:
520
+ values.append(entry["set"][key])
521
+ elif isinstance(doc.get("defaults"), Mapping) and key in doc["defaults"]:
522
+ values.append(doc["defaults"][key])
523
+ if values:
524
+ try:
525
+ return int(rst.CATALOG["loop_issue_cap"].check(values[-1]))
526
+ except (rst.SettingError, KeyError, TypeError, ValueError, AttributeError):
527
+ return 3
528
+ return 3
529
+
530
+
531
+ def _out(env: Any, a: argparse.Namespace, doc: Any, line: str) -> None:
532
+ from tempergraph.cli.main import _emit
533
+
534
+ if getattr(a, "json", False):
535
+ _emit(env, doc)
536
+ else:
537
+ env.out.write(line + "\n")
538
+
539
+
540
+ COMMANDS = {"evals": cmd_evals, "labels": cmd_labels, "improve": cmd_improve}
541
+
542
+
543
+ def cmd_promote_check(env: Any, a: argparse.Namespace) -> int:
544
+ """PRO-B6: read-only without `--stamp`; exit 0 when every criterion is met, 6 when any is not."""
545
+ from tempergraph.cli.main import _emit, _root, _spec
546
+ from tempergraph.improve import promotion as pro
547
+ from tempergraph.provenance import decide
548
+ from tempergraph.store.layout import home_path
549
+
550
+ spec = _spec(env, a.workflow)
551
+ if a.executor and a.executor not in env.registry.available():
552
+ raise _usage(f"executor {a.executor!r} is not registered in this release (not_in_release)")
553
+ try:
554
+ rep = pro.check(spec, _root(env), to=a.to, executor=a.executor, size=a.window)
555
+ if a.stamp:
556
+ caller = decide(env.caller(a), relayed=bool(a.relayed), words=("stamp", "promote"), home=home_path())
557
+ rep = pro.stamp(spec, rep, caller)
558
+ except pro.PromotionRefused as exc:
559
+ raise _usage(str(exc)) from exc
560
+ if a.json:
561
+ _emit(env, rep.to_json())
562
+ else:
563
+ env.out.write(pro.text(rep))
564
+ return rep.exit_code