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,130 @@
1
+ """Pre-binding a cause to an open issue the loop did not open (PBD-B1 to PBD-B8).
2
+
3
+ The matcher reads only ids, enums and numbers of the finding and the text of other people's issues; nothing of an
4
+ issue's text is ever written back (ISS-B10): a comment's opening sentence and the `## Possibly related` list hold
5
+ workflow, cause, unit ids and issue numbers only.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections.abc import Callable, Mapping, Sequence
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ from tempergraph.improve import bindings
16
+ from tempergraph.improve.causes import CAUSES
17
+ from tempergraph.improve.codehost import CodeHostError, NotFound
18
+
19
+ BIND = "tempergraph:bind="
20
+ CRITERION_CAUSES = frozenset({"judge_blocked"}) # SIL-B12: the cause's detail part is a criterion id
21
+ RELATED_MAX = 5
22
+
23
+
24
+ @dataclass
25
+ class Found:
26
+ """`issues` are the candidates by `rule` (`line`, else `token`), none when `failed` (a read failed twice)."""
27
+
28
+ issues: list[dict[str, Any]] = field(default_factory=list)
29
+ rule: str | None = None
30
+ failed: bool = False
31
+
32
+ @property
33
+ def numbers(self) -> list[int]:
34
+ return sorted(int(i["number"]) for i in self.issues)[:RELATED_MAX]
35
+
36
+
37
+ def is_token(text: str, word: str) -> bool:
38
+ """PBD-B2: `word` with no letter, digit, `_` or `-` directly before or after it, in the same letter case."""
39
+ return bool(word) and re.search(rf"(?<![A-Za-z0-9_\-]){re.escape(word)}(?![A-Za-z0-9_\-])", text) is not None
40
+
41
+
42
+ def words_of(cause: str) -> list[str]:
43
+ """The cause code (before the first `:`) and, for a cause that carries one, its criterion id."""
44
+ code, _, detail = cause.partition(":")
45
+ return [code, *([detail] if code in CRITERION_CAUSES and detail else [])]
46
+
47
+
48
+ def _text(issue: Mapping[str, Any]) -> str:
49
+ return f"{issue.get('title') or ''}\n{issue.get('body') or ''}"
50
+
51
+
52
+ def _two_codes(text: str, code: str) -> bool:
53
+ return sum(1 for c in {*CAUSES, code} if is_token(text, c)) >= 2
54
+
55
+
56
+ def _has_bind(text: str, line: str) -> bool:
57
+ return any(ln.strip() == line for ln in text.splitlines())
58
+
59
+
60
+ def _comments(read: Callable[[int], Sequence[Mapping[str, Any]]], number: int) -> list[Mapping[str, Any]] | None:
61
+ """The comments of one issue, one retry; `None` when the read failed twice."""
62
+ for _ in range(2):
63
+ try:
64
+ return list(read(number))
65
+ except NotFound:
66
+ return []
67
+ except CodeHostError:
68
+ continue
69
+ return None
70
+
71
+
72
+ def candidates(issues: Sequence[Mapping[str, Any]], finding: Mapping[str, Any],
73
+ read_comments: Callable[[int], Sequence[Mapping[str, Any]]]) -> Found:
74
+ """PBD-B2, PBD-B3: the candidates by line, else by token. Comments are read only for an issue that is a candidate
75
+ by token or whose body holds `tempergraph:bind=`, and only when it has any (PBD-B3)."""
76
+ cause = str(finding.get("cause") or "")
77
+ code = cause.partition(":")[0]
78
+ line = f"{BIND}{finding.get('workflow')}/{code}"
79
+ by_token: list[dict[str, Any]] = []
80
+ by_line: list[dict[str, Any]] = []
81
+ failed = False
82
+ for issue in sorted(issues, key=lambda i: int(i.get("number") or 0)):
83
+ text = _text(issue)
84
+ token = any(is_token(text, w) for w in words_of(cause)) and not _two_codes(text, code)
85
+ bound = _has_bind(str(issue.get("body") or ""), line)
86
+ if token:
87
+ by_token.append(dict(issue))
88
+ if bound:
89
+ by_line.append(dict(issue))
90
+ continue
91
+ if (token or BIND in str(issue.get("body") or "")) and int(issue.get("comments") or 0) > 0:
92
+ got = _comments(read_comments, int(issue["number"]))
93
+ if got is None:
94
+ failed = True
95
+ continue
96
+ if any(c.get("author_kind") == "person" and not bindings.is_loop_comment(str(c.get("text") or ""))
97
+ and _has_bind(str(c.get("text") or ""), line) for c in got):
98
+ by_line.append(dict(issue))
99
+ if failed:
100
+ return Found(failed=True)
101
+ if by_line:
102
+ return Found(sorted(by_line, key=lambda i: int(i["number"])), "line")
103
+ return Found(by_token, "token") if by_token else Found()
104
+
105
+
106
+ def opening_sentence(workflow: str, cause: str, units: Sequence[str]) -> str:
107
+ """PBD-B4: the one sentence that opens a pre-bind comment, built from ids; it holds no `duplicate of #`."""
108
+ where = ", ".join(f"`{u}`" for u in units) or "no recorded unit"
109
+ return (f"This comment comes from tempergraph's improvement loop: it saw the cause `{cause}` of workflow "
110
+ f"`{workflow}` again at {where}, and sends it here because this open issue names the cause.")
111
+
112
+
113
+ def related_section(numbers: Sequence[int]) -> list[str]:
114
+ """PBD-B7: the `## Possibly related` lines for the five lowest numbers, each `#<n>`; nothing for none."""
115
+ low = sorted(int(n) for n in numbers)[:RELATED_MAX]
116
+ return ["## Possibly related", *(f"- #{n}" for n in low)] if low else []
117
+
118
+
119
+ def read_open(host: Any, repo: str) -> tuple[list[dict[str, Any]] | None, bool]:
120
+ """PBD-B1: the open issues without the loop's label, one retry; the flag says the read failed twice. A host with
121
+ no such read gives no issues and no failure."""
122
+ if not hasattr(host, "open_issues"):
123
+ return None, False
124
+ for attempt in (1, 2):
125
+ try:
126
+ return list(host.open_issues(repo)), False
127
+ except CodeHostError:
128
+ if attempt == 2:
129
+ return None, True
130
+ return None, True
@@ -0,0 +1,413 @@
1
+ """Stages of a run, the promotion check and the promotion stamp (PRO-B7, PRO-B4, PRO-B10). Model-free.
2
+
3
+ The check reads the functions the reports read (`report`, `report --supervision`, `evals bar`, `evals report`),
4
+ so a number never differs between two verbs. Release 2 measures and stamps `local-stable`; `pipeline` is
5
+ refused with `not_in_release`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ from collections import defaultdict
13
+ from collections.abc import Mapping, Sequence
14
+ from dataclasses import dataclass, field
15
+ from importlib import resources
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from tempergraph.contracts import STAGES, WorkflowSpec
20
+
21
+ PROMOTION = "promotion.json"
22
+ BUILT = ("local-stable",) # the targets this release measures and stamps
23
+ EXCLUDED_ORIGINS = frozenset({"trial", "scenario", "evals"})
24
+ CHILD_ORIGIN = "subworkflow:" # SWF-B9: a child's records from inside a parent (`subworkflow:<parent>`) never enter its window
25
+ STAMP_CALLERS = frozenset({"person"}) # who may decide a stamp; a pipeline caller arrives with pipelines
26
+ FINAL_EXITS = frozenset({0, 4, 5})
27
+ FAULT_SIDES = ("engine", "executor")
28
+
29
+
30
+ class PromotionRefused(ValueError):
31
+ def __init__(self, code: str, message: str) -> None:
32
+ super().__init__(message)
33
+ self.code = code
34
+
35
+
36
+ def stage_of(spec: WorkflowSpec, caller: Mapping[str, Any] | None = None) -> tuple[str, bool]:
37
+ """PRO-B7, PRO-B4: the stage of a run, and whether a pipeline caller runs it unpromoted. No run has stage
38
+ `pipeline` in this release, so a pipeline caller always runs at the local stage."""
39
+ stage = "local-stable" if spec.improvement_mode == "stable" else "local-dev"
40
+ return stage, (caller or {}).get("kind") == "pipeline"
41
+
42
+
43
+ def bars(stage: str) -> dict[str, float]:
44
+ """The stage's bars, from the one engine config file (PRO-B9)."""
45
+ doc = json.loads(resources.files("tempergraph.data").joinpath(PROMOTION).read_text(encoding="utf-8"))
46
+ return {str(k): float(v) for k, v in doc["stages"][stage].items()}
47
+
48
+
49
+ def current_version(spec: WorkflowSpec) -> str:
50
+ """The workflow version with its content digest (VER-B14, VER-B15) for a package, else the declared version."""
51
+ if spec.package_root is None:
52
+ return spec.version
53
+ from tempergraph.package.loader import load_package
54
+
55
+ return load_package(spec.package_root).workflow_version # read anew: a changed file voids a stamp
56
+
57
+
58
+ @dataclass(kw_only=True)
59
+ class WindowRun:
60
+ thread: Any # observe.report.Thread
61
+ records: list[dict[str, Any]]
62
+ request: str | None
63
+ escapes: int = 0
64
+
65
+
66
+ def _escapes(t: Any) -> int:
67
+ from tempergraph.observe import report
68
+
69
+ return sum(int(c["escapes"]) for c in report.criteria([t]))
70
+
71
+
72
+ def window(root: Path, spec: WorkflowSpec, version: str, size: int, *, restart_on_escape: bool = False
73
+ ) -> list[WindowRun]:
74
+ """PRO-B8: the last `size` finished runs of this workflow version, oldest first. Only the workflow's own runs
75
+ count: its records from inside a parent are the parent's thread, never a run of its own (SWF-B9). Trial,
76
+ scenario, eval and dry runs and reruns of a trial are left out. With `restart_on_escape` (a stage whose escape bar is 0)
77
+ the window starts after the last run that held a gate escape."""
78
+ from tempergraph.observe import report
79
+ from tempergraph.run.events import records as read_records
80
+
81
+ out: list[WindowRun] = []
82
+ base = root / "runs" / spec.name
83
+ for log in sorted(base.glob("*/run.jsonl")) if base.is_dir() else []:
84
+ recs = list(read_records(log))
85
+ t = report.fold(recs, log.parent)
86
+ starts = [r for r in recs if r.get("kind") == "run_started"]
87
+ if t is None or not starts or t.exit is None or int(t.exit.get("exit_code") or 0) not in FINAL_EXITS:
88
+ continue
89
+ first = starts[0]
90
+ rerun = first.get("rerun_of") or {}
91
+ if any(s.get("origin") in EXCLUDED_ORIGINS or str(s.get("origin") or "").startswith(CHILD_ORIGIN)
92
+ or s.get("dry_run") for s in starts) \
93
+ or (isinstance(rerun, Mapping) and rerun.get("origin") == "trial"):
94
+ continue
95
+ ran = next((s.get("content_version") for s in reversed(starts) if s.get("content_version")), None) \
96
+ or t.version
97
+ if ran != version and not (ran == spec.version and "+" not in str(ran)):
98
+ continue
99
+ task = next((r for r in recs if r.get("kind") == "task"), {})
100
+ req = str(task.get("request") or "")
101
+ out.append(WindowRun(thread=t, records=recs, escapes=_escapes(t),
102
+ request=hashlib.sha256(req.encode()).hexdigest()[:16] if req else None))
103
+ out.sort(key=lambda w: str(w.thread.exit.get("ts") or w.thread.started_at or ""))
104
+ if restart_on_escape:
105
+ last = max((i for i, w in enumerate(out) if w.escapes), default=-1)
106
+ out = out[last + 1:]
107
+ return out[-size:] if size > 0 else []
108
+
109
+
110
+ def _row(pid: str, name: str, value: Any, bar: Any, met: bool | None, *, detail: str = "") -> dict[str, Any]:
111
+ """`met` None is a reported row; a missing value is `unmeasured`, which is not met (PRO-B9)."""
112
+ verdict = "reported" if met is None else "unmeasured" if value is None else "met" if met else "not_met"
113
+ return {"id": pid, "criterion": name, "value": value, "bar": bar, "verdict": verdict,
114
+ **({"detail": detail} if detail else {})}
115
+
116
+
117
+ def _at_most(v: float | None, bar: float) -> bool:
118
+ return v is not None and v <= bar
119
+
120
+
121
+ def _at_least(v: float | None, bar: float) -> bool:
122
+ return v is not None and v >= bar
123
+
124
+
125
+ def _supervision(root: Path, ids: set[str], b: Mapping[str, float]) -> list[dict[str, Any]]:
126
+ """P5: the rows of SUP-B17 over the window, from `report --supervision`'s own aggregate."""
127
+ from tempergraph.observe import supervision_report as sr
128
+
129
+ rs = [r for r in sr.runs(root) if r.thread_id in ids]
130
+ n = len(ids)
131
+ a = sr.aggregate(rs)
132
+ recorded = len(rs) / n if n else 0.0
133
+ und = a["undesigned_per_run"] if rs and recorded == 1.0 else None
134
+ lower = (a["unattended_interval"] or [None])[0] if rs and recorded == 1.0 else None
135
+ share = a["supervision_share"]
136
+ measured = round(share["measured"] / n, 4) if n else None
137
+ median = share["median"] if measured is not None and measured >= b["share_measured"] else None
138
+ known = a["data_quality"]["callers_known"] if rs and recorded == 1.0 else None
139
+ cost = round(a["supervision_cost_per_run"]["measured"] / n, 4) if n else None
140
+ note = "" if recorded == 1.0 else f"{n - len(rs)} of {n} runs have no supervision record"
141
+ rows = [
142
+ _row("P5.undesigned", "undesigned touches per run, every decider", und, f"<= {b['undesigned_per_run']:g}",
143
+ _at_most(und, b["undesigned_per_run"]), detail=note),
144
+ _row("P5.unattended", "unattended rate, lower bound of the interval", lower,
145
+ f">= {b['unattended_lower_bound']:g}", _at_least(lower, b["unattended_lower_bound"]), detail=note),
146
+ _row("P5.agent_rescues", "agent's own rescue share", a["agent_own_rescue_share"],
147
+ f"<= {b['agent_own_rescue_share']:g}" if "agent_own_rescue_share" in b else "reported",
148
+ _at_most(a["agent_own_rescue_share"], b["agent_own_rescue_share"])
149
+ if "agent_own_rescue_share" in b and a["agent_own_rescue_share"] is not None else None),
150
+ _row("P5.share", "supervision share, median", median, f"<= {b['supervision_share_median']:g}",
151
+ _at_most(median, b["supervision_share_median"]),
152
+ detail=f"measured on {share['measured']} of {n} runs; at least {b['share_measured']:g} of them needed"),
153
+ _row("P5.callers", "runs with every caller known", known, f">= {b['callers_known']:g}",
154
+ _at_least(known, b["callers_known"]), detail=note),
155
+ ]
156
+ if "cost_measured" in b:
157
+ rows.append(_row("P5.cost_measured", "runs with supervision cost measured",
158
+ cost if cost is not None and cost >= b["cost_measured"] else None,
159
+ f">= {b['cost_measured']:g}", cost is not None and cost >= b["cost_measured"],
160
+ detail=f"measured on {cost if cost is not None else 0:g} of the runs"))
161
+ else:
162
+ rows.append(_row("P5.cost_measured", "runs with supervision cost measured", cost, "reported", None))
163
+ return rows
164
+
165
+
166
+ def _judges(spec: WorkflowSpec, root: Path) -> dict[str, Any]:
167
+ """P4: every judged gate's binding `accepted`, each routed risk level included (JRK-B9, JRK-B5)."""
168
+ from tempergraph.improve import calibration as cal
169
+
170
+ bad: list[str] = []
171
+ bindings: dict[str, Any] = {}
172
+ gates = cal.judged_gates(spec)
173
+ try:
174
+ for st in cal.states(spec, state_root=root):
175
+ bindings[st.gate] = {k: st.binding.get(k) for k in ("executor", "alias")}
176
+ if st.state != "accepted":
177
+ bad.append(f"{st.gate}: {st.state}")
178
+ for gate in gates:
179
+ bad += [f"{gate}@{lv}: {name}" for lv, name in cal.unaccepted_levels(spec, gate)]
180
+ except (cal.CalibrationError, OSError, ValueError) as exc:
181
+ bad.append(f"unreadable: {type(exc).__name__}")
182
+ row = _row("P4", "every gate's judge binding accepted, routed risk levels included",
183
+ len(gates) - len({b.split(":")[0].split("@")[0] for b in bad} & set(gates)),
184
+ f"{len(gates)} of {len(gates)} gates", not bad, detail="; ".join(bad))
185
+ return {"row": row, "bindings": bindings}
186
+
187
+
188
+ def _p90(xs: Sequence[float]) -> float | None:
189
+ from tempergraph.observe.supervision_report import _pct
190
+
191
+ return _pct(list(xs), 0.9)
192
+
193
+
194
+ def _escalations(root: Path, spec: WorkflowSpec, ids: set[str]) -> dict[str, dict[str, Any]]:
195
+ """P9: escalated attempts per unit in the window, from the escalation record (LAD-B16, LAD-B17)."""
196
+ from tempergraph.improve.calibration import wilson_lb
197
+
198
+ by: dict[str, list[bool]] = defaultdict(list)
199
+ try:
200
+ lines = (root / "ledger.jsonl").read_text(encoding="utf-8").splitlines()
201
+ except OSError:
202
+ lines = []
203
+ for ln in lines:
204
+ try:
205
+ r = json.loads(ln)
206
+ except ValueError:
207
+ continue
208
+ if isinstance(r, dict) and r.get("kind") == "escalation" and r.get("workflow") == spec.name \
209
+ and r.get("thread_id") in ids:
210
+ by[str(r.get("unit"))].append(bool(r.get("passed")))
211
+ return {u: {"attempts": len(v), "passed": sum(v), "pass_lower_bound": round(wilson_lb(sum(v), len(v)), 4)}
212
+ for u, v in sorted(by.items())}
213
+
214
+
215
+ def _ladders(spec: WorkflowSpec, runs: Sequence[WindowRun]) -> dict[str, dict[str, Any]]:
216
+ """P10: per unit with an effort ladder, the share of its attempts that ran above rung 0."""
217
+ out: dict[str, dict[str, Any]] = {}
218
+ for name, u in spec.units.items():
219
+ if u.step is None or not u.step.effort_ladder:
220
+ continue
221
+ ss = [s for w in runs for s in w.thread.sessions if s.unit == name and s.kind in ("step", "retry")]
222
+ climbed = sum(1 for s in ss if s.climbed)
223
+ out[name] = {"attempts": len(ss), "climbed": climbed, "share": round(climbed / len(ss), 4) if ss else None,
224
+ **({"ladder_unseen": True} if not climbed else {})}
225
+ return out
226
+
227
+
228
+ def _arms(runs: Sequence[WindowRun]) -> dict[str, dict[str, int]]:
229
+ """P11: runs per switch arm in the window."""
230
+ by: dict[str, dict[str, set[str]]] = defaultdict(lambda: defaultdict(set))
231
+ for w in runs:
232
+ for r in w.thread.routes:
233
+ by[str(r.get("unit"))][str(r.get("arm"))].add(w.thread.thread_id)
234
+ return {u: {a: len(ts) for a, ts in sorted(arms.items())} for u, arms in sorted(by.items())}
235
+
236
+
237
+ @dataclass(kw_only=True)
238
+ class Report:
239
+ workflow: str
240
+ to: str
241
+ workflow_version: str
242
+ executor: str
243
+ window: dict[str, Any] = field(default_factory=dict)
244
+ criteria: list[dict[str, Any]] = field(default_factory=list)
245
+ alias_bindings: dict[str, Any] = field(default_factory=dict)
246
+ ladder_seen: dict[str, Any] = field(default_factory=dict)
247
+ escalation_covered: dict[str, Any] = field(default_factory=dict)
248
+ arms_covered: dict[str, Any] = field(default_factory=dict)
249
+ stamp: dict[str, Any] | None = None
250
+ stamped: bool = False
251
+ refused: str | None = None
252
+
253
+ @property
254
+ def met(self) -> bool:
255
+ return bool(self.criteria) and all(c["verdict"] in ("met", "reported") for c in self.criteria)
256
+
257
+ @property
258
+ def exit_code(self) -> int:
259
+ return 0 if self.met and not self.refused else 6
260
+
261
+ def to_json(self) -> dict[str, Any]:
262
+ return {"schema_version": 1, "workflow": self.workflow, "to": self.to,
263
+ "workflow_version": self.workflow_version, "executor": self.executor, "met": self.met,
264
+ "window": self.window, "criteria": self.criteria, "alias_bindings": self.alias_bindings,
265
+ "ladder_seen": self.ladder_seen, "escalation_covered": self.escalation_covered,
266
+ "arms_covered": self.arms_covered, "stamp": self.stamp, "stamped": self.stamped,
267
+ **({"refused": self.refused} if self.refused else {})}
268
+
269
+
270
+ def check(spec: WorkflowSpec, root: Path, *, to: str, executor: str | None = None, size: int | None = None
271
+ ) -> Report:
272
+ """PRO-B9: every criterion's number, bar and verdict for the target stage. Reads only."""
273
+ from tempergraph.improve import record, suites
274
+ from tempergraph.improve.trials import run_cost
275
+ from tempergraph.observe import report as rep
276
+
277
+ if to not in STAGES or to == "local-dev":
278
+ raise PromotionRefused("usage", "`--to` is `local-stable` or `pipeline`")
279
+ if to not in BUILT:
280
+ raise PromotionRefused("not_in_release", f"`--to {to}` arrives with pipelines in a later release "
281
+ "(not_in_release); `--to local-stable` is built")
282
+ b = bars(to)
283
+ size = int(size if size is not None else b["window"])
284
+ if size < 1:
285
+ raise PromotionRefused("usage", "`--window` takes a whole number of runs, 1 or more")
286
+ version = current_version(spec)
287
+ runs = window(root, spec, version, size, restart_on_escape=b["gate_escapes"] == 0)
288
+ ts = [w.thread for w in runs]
289
+ ids = {t.thread_id for t in ts}
290
+ out = Report(workflow=spec.name, to=to, workflow_version=version, executor=executor or spec.default_executor)
291
+ out.window = {"size": size, "runs": len(runs), "threads": sorted(ids),
292
+ "stamp": read_stamps(spec.package_root, version) if spec.package_root else {}}
293
+ requests = {w.request for w in runs if w.request}
294
+ need = int(b["runs"]) # a smaller `--window` never lowers the bar
295
+ out.criteria.append(_row(
296
+ "P1", "runs in the window, with distinct requests", len(runs) or None,
297
+ f">= {need} runs, {int(b['distinct_requests'])} distinct requests",
298
+ len(runs) >= need and len(requests) >= b["distinct_requests"], detail=f"{len(requests)} distinct requests"))
299
+ first = next(iter(rep.ladder(ts)), {}).get("first_pass") or {}
300
+ gates = int(first.get("gates") or 0)
301
+ fpy = round(int(first.get("passed") or 0) / gates, 4) if gates else None
302
+ out.criteria.append(_row("P2", "first-pass yield of rung-0 attempts", fpy, f">= {b['first_pass_yield']:g}",
303
+ _at_least(fpy, b["first_pass_yield"]), detail=f"{gates} gates"))
304
+ escapes = sum(w.escapes for w in runs) if runs else None
305
+ out.criteria.append(_row("P3", "gate escapes in the window", escapes, f"<= {int(b['gate_escapes'])}",
306
+ _at_most(escapes, b["gate_escapes"])))
307
+ judges = _judges(spec, root)
308
+ out.criteria.append(judges["row"] if runs else {**judges["row"], "value": None, "verdict": "unmeasured"})
309
+ out.alias_bindings = judges["bindings"]
310
+ out.criteria += _supervision(root, ids, b)
311
+ costs = [run_cost(w.records) for w in runs]
312
+ cap = spec.run_cost_cap_usd
313
+ out.criteria.append(_row("P6", "run cost per run, p90", _p90(costs), "reported", None,
314
+ detail=f"run_cost_cap_usd {cap:g}" if cap is not None else "no run_cost_cap_usd"))
315
+ faults = sorted({str(f.get("fingerprint")) for t in ts
316
+ for f in record.read_findings(root, spec.name, t.thread_id.split("/", 1)[-1])
317
+ if f.get("class") == "fault" and str(f.get("side") or "").split(":")[0] in FAULT_SIDES})
318
+ out.criteria.append(_row("P7", "engine or executor fault findings of the window's runs", len(faults),
319
+ "reported", None, detail=", ".join(faults[:5])))
320
+ states: dict[str, int] = defaultdict(int)
321
+ for s in suites.report(spec, root)["suites"]:
322
+ states[str(s["status"])] += 1
323
+ out.criteria.append(_row("P8", "eval suites of the workflow", dict(sorted(states.items())) or None,
324
+ "reported", None))
325
+ out.escalation_covered = _escalations(root, spec, ids)
326
+ out.criteria.append(_row("P9", "escalated attempts: count and pass rate per unit",
327
+ out.escalation_covered or None, "reported", None))
328
+ out.ladder_seen = _ladders(spec, runs)
329
+ unseen = sorted(u for u, v in out.ladder_seen.items() if v.get("ladder_unseen"))
330
+ out.criteria.append(_row("P10", "effort ladder seen: share of climbed attempts per unit",
331
+ {u: v["share"] for u, v in out.ladder_seen.items()} or None, "reported", None,
332
+ detail=f"ladder_unseen: {', '.join(unseen)}" if unseen else ""))
333
+ out.arms_covered = _arms(runs)
334
+ out.criteria.append(_row("P11", "switch arms: runs per arm", out.arms_covered or None, "reported", None))
335
+ return out
336
+
337
+
338
+ def _doc(root: Path) -> tuple[dict[str, Any], bool]:
339
+ """The package's `promotion.json` and whether it could be read; an unreadable file is no stamp."""
340
+ try:
341
+ doc = json.loads((root / PROMOTION).read_text(encoding="utf-8"))
342
+ except FileNotFoundError:
343
+ return {}, True
344
+ except (OSError, ValueError):
345
+ return {}, False
346
+ ok = isinstance(doc, dict) and isinstance(doc.get("stamps"), dict)
347
+ return (doc if ok else {}), ok
348
+
349
+
350
+ def read_stamps(root: Path | None, version: str) -> dict[str, Any]:
351
+ """Each stage's stamp and whether it stands: a stamp of another workflow version is void (PRO-B10)."""
352
+ if root is None:
353
+ return {}
354
+ doc, ok = _doc(root)
355
+ out: dict[str, Any] = {} if ok else {"warning": f"{PROMOTION} is unreadable: treated as no stamp"}
356
+ for stage, e in (doc.get("stamps") or {}).items():
357
+ if isinstance(e, dict):
358
+ out[str(stage)] = {"workflow_version": e.get("workflow_version"), "stamped_at": e.get("stamped_at"),
359
+ "state": "current" if e.get("workflow_version") == version else "void"}
360
+ return out
361
+
362
+
363
+ def stamped(spec: WorkflowSpec, stage: str) -> bool:
364
+ """Whether the current workflow version holds the stage's stamp."""
365
+ if spec.package_root is None:
366
+ return False
367
+ return (read_stamps(spec.package_root, current_version(spec)).get(stage) or {}).get("state") == "current"
368
+
369
+
370
+ def stamp(spec: WorkflowSpec, rep: Report, caller: Mapping[str, Any]) -> Report:
371
+ """`--stamp`: writes the stage's entry only when every criterion is met, for a person, into a package
372
+ that is not an installed copy (PRO-B10, PRO-B6, PRO-B9). A void entry of another stage is dropped."""
373
+ from tempergraph.docs import write_json
374
+ from tempergraph.package.registry import plugin_cache
375
+ from tempergraph.store.layout import now_iso
376
+
377
+ root = spec.package_root
378
+ kind = str(caller.get("kind") or "unknown")
379
+ if kind == "pipeline":
380
+ raise PromotionRefused("not_in_release", "a pipeline caller's stamp arrives with pipelines in a later "
381
+ "release (not_in_release)")
382
+ if root is None:
383
+ raise PromotionRefused("usage", "only a workflow package can be stamped")
384
+ if root.resolve().is_relative_to(plugin_cache().resolve()):
385
+ raise PromotionRefused("usage", "stamp the workflow's source; this is an installed copy")
386
+ if caller.get("decided_by") not in STAMP_CALLERS:
387
+ raise PromotionRefused("usage", "a promotion stamp needs a person: run it yourself, or pass --relayed "
388
+ "with the person's words")
389
+ if not rep.met:
390
+ return rep
391
+ doc, _ = _doc(root)
392
+ kept = {s: e for s, e in (doc.get("stamps") or {}).items()
393
+ if isinstance(e, dict) and e.get("workflow_version") == rep.workflow_version}
394
+ rep.stamp = {"stage": rep.to, "workflow_version": rep.workflow_version, "executor": rep.executor,
395
+ "alias_bindings": rep.alias_bindings, "criteria": rep.criteria, "ladder_seen": rep.ladder_seen,
396
+ "escalation_covered": rep.escalation_covered, "arms_covered": rep.arms_covered,
397
+ "stamped_at": now_iso(),
398
+ "caller": {k: caller.get(k) for k in ("kind", "confidence", "decided_by", "relay", "host")}}
399
+ write_json(root / PROMOTION, {"schema_version": 1, "stamps": {**kept, rep.to: rep.stamp}}, mode=0o644)
400
+ rep.stamped = True
401
+ return rep
402
+
403
+
404
+ def text(rep: Report) -> str:
405
+ lines = [f"{rep.workflow} {rep.workflow_version} to {rep.to}: "
406
+ f"{'every criterion met' if rep.met else 'not met'} ({rep.window.get('runs')} runs in the window)"]
407
+ for c in rep.criteria:
408
+ val = "-" if c["value"] is None else json.dumps(c["value"]) if isinstance(c["value"], dict) else c["value"]
409
+ lines.append(f" {c['id']:<17} {c['verdict']:<10} {val} (bar: {c['bar']}) {c['criterion']}"
410
+ + (f" [{c['detail']}]" if c.get("detail") else ""))
411
+ if rep.stamped:
412
+ lines.append(f"stamped: {PROMOTION}")
413
+ return "\n".join(lines) + "\n"