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,233 @@
1
+ """The ask unit's questions and answers (ASK-B5 to ASK-B13): pure validation and the answers file.
2
+
3
+ A person's answers are kept in a JSON file under the thread's folder, not in graph state, so a resume that
4
+ does not complete the set never moves the graph and a crash loses nothing (ASK-AC2). The file becomes the
5
+ unit's `answers` artifact when the set is complete and the author's check passes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from collections.abc import Mapping, Sequence
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from tempergraph.contracts import AskQuestion, AskSpec
17
+ from tempergraph.docs import write_json
18
+
19
+ MAX_QUESTIONS = 20
20
+ KINDS = ("text", "choice", "choices", "number", "bool", "file", "url")
21
+ SLUG = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
22
+ _ITEM = re.compile(r"^\s*(?:[-*]|\d+[.)])\s+`?([a-z0-9][a-z0-9_-]{0,63})`?\s*:\s*(.+?)\s*$")
23
+ _TRUE, _FALSE = frozenset({"true", "yes", "y", "1"}), frozenset({"false", "no", "n", "0"})
24
+
25
+
26
+ class AskFault(Exception):
27
+ """The question list cannot be used: the unit stops before its pause (ASK-B2, ASK-B2, ASK-B9)."""
28
+
29
+
30
+ class AnswerRefused(ValueError):
31
+ """An answer does not fit its question; nothing is written (ASK-B1)."""
32
+
33
+
34
+ def question_problems(qs: Sequence[AskQuestion]) -> list[str]:
35
+ out: list[str] = []
36
+ if not 1 <= len(qs) <= MAX_QUESTIONS:
37
+ out.append(f"an ask takes 1 to {MAX_QUESTIONS} questions, not {len(qs)}")
38
+ seen: set[str] = set()
39
+ for q in qs:
40
+ if not SLUG.match(q.name):
41
+ out.append(f"question name {q.name!r} is not a slug")
42
+ if q.name in seen:
43
+ out.append(f"question {q.name!r} is declared twice")
44
+ seen.add(q.name)
45
+ if q.kind not in KINDS:
46
+ out.append(f"question {q.name!r}: kind {q.kind!r} is not one of {', '.join(KINDS)}")
47
+ if not q.text.strip() or len(q.text) > 500:
48
+ out.append(f"question {q.name!r}: the text is empty or over 500 characters")
49
+ if q.kind in ("choice", "choices") and len(q.choices) < 2:
50
+ out.append(f"question {q.name!r}: a {q.kind} needs two or more choices")
51
+ if q.kind not in ("choice", "choices") and q.choices:
52
+ out.append(f"question {q.name!r}: `choices` goes with kind choice or choices")
53
+ return out
54
+
55
+
56
+ def from_list(text: str) -> list[AskQuestion]:
57
+ """A list artifact of questions: JSON in the `Question` shape, or Markdown with one `name: question` an item."""
58
+ stripped = text.strip()
59
+ if stripped.startswith("["):
60
+ try:
61
+ doc = json.loads(stripped)
62
+ except ValueError as exc:
63
+ raise AskFault(f"the question list is not JSON: {exc}") from None
64
+ out = []
65
+ for i, item in enumerate(doc if isinstance(doc, list) else []):
66
+ if not isinstance(item, Mapping) or not item.get("name") or not (item.get("text") or item.get("question")):
67
+ raise AskFault(f"question {i + 1} of the list needs a name and a text")
68
+ out.append(AskQuestion(
69
+ name=str(item["name"]), text=str(item.get("text") or item.get("question")),
70
+ kind=str(item.get("kind") or "text"), # type: ignore[arg-type]
71
+ choices=tuple(str(c) for c in item.get("choices") or ()),
72
+ required=bool(item.get("required", True)), default=item.get("default")))
73
+ else:
74
+ out = []
75
+ for n, line in enumerate(stripped.splitlines(), 1):
76
+ if not line.strip() or line.lstrip().startswith("#"):
77
+ continue
78
+ m = _ITEM.match(line)
79
+ if not m:
80
+ raise AskFault(f"line {n} of the question list is not `- name: question`")
81
+ out.append(AskQuestion(name=m.group(1), text=m.group(2)))
82
+ problems = question_problems(out)
83
+ if problems:
84
+ raise AskFault(problems[0])
85
+ return out
86
+
87
+
88
+ def questions(ask: AskSpec, state: Mapping[str, Any], workdir: Path) -> list[AskQuestion]:
89
+ """The unit's questions at entry: declared, or read from the artifact `questions_from` names."""
90
+ if ask.questions_from is None:
91
+ return list(ask.questions)
92
+ pointer = next((arts[ask.questions_from] for arts in (state.get("artifacts") or {}).values()
93
+ if isinstance(arts, Mapping) and ask.questions_from in arts), None)
94
+ if pointer is None:
95
+ raise AskFault(f"artifact {ask.questions_from!r} is missing")
96
+ try:
97
+ text = (workdir / str(pointer)).read_text(encoding="utf-8")
98
+ except OSError:
99
+ raise AskFault(f"artifact {ask.questions_from!r} cannot be read at {pointer}") from None
100
+ return from_list(text)
101
+
102
+
103
+ def to_json(q: AskQuestion) -> dict[str, Any]:
104
+ return {"name": q.name, "text": q.text, "kind": q.kind, "choices": list(q.choices), "required": q.required,
105
+ "default": q.default}
106
+
107
+
108
+ def of_json(d: Mapping[str, Any]) -> AskQuestion:
109
+ return AskQuestion(name=str(d["name"]), text=str(d.get("text") or ""), kind=d.get("kind") or "text",
110
+ choices=tuple(d.get("choices") or ()), required=bool(d.get("required", True)),
111
+ default=d.get("default"))
112
+
113
+
114
+ def parse(q: AskQuestion, raw: Any, workdir: Path | None = None) -> Any:
115
+ """One answer as its question's kind, or `AnswerRefused` naming what is allowed."""
116
+ text = raw if isinstance(raw, str) else json.dumps(raw) if isinstance(raw, (list, dict)) else str(raw)
117
+ text = text.strip()
118
+ if q.kind == "text":
119
+ if not text:
120
+ raise AnswerRefused(f"{q.name}: an empty answer")
121
+ return text
122
+ if q.kind == "choice":
123
+ if text not in q.choices:
124
+ raise AnswerRefused(f"{q.name}: {text!r} is not one of {', '.join(q.choices)}")
125
+ return text
126
+ if q.kind == "choices":
127
+ picked = [str(x).strip() for x in raw] if isinstance(raw, list) else [p.strip() for p in text.split(",")]
128
+ picked = [p for p in picked if p]
129
+ bad = [p for p in picked if p not in q.choices]
130
+ if bad or not picked:
131
+ raise AnswerRefused(f"{q.name}: {', '.join(bad) or 'nothing'} is not among {', '.join(q.choices)}")
132
+ return list(dict.fromkeys(picked))
133
+ if q.kind == "number":
134
+ try:
135
+ return int(text) if re.fullmatch(r"[+-]?\d+", text) else float(text)
136
+ except ValueError:
137
+ raise AnswerRefused(f"{q.name}: {text!r} is not a number") from None
138
+ if q.kind == "bool":
139
+ if isinstance(raw, bool):
140
+ return raw
141
+ if text.lower() in _TRUE | _FALSE:
142
+ return text.lower() in _TRUE
143
+ raise AnswerRefused(f"{q.name}: {text!r} is not true or false")
144
+ if q.kind == "url":
145
+ if not re.fullmatch(r"https?://[^\s]+", text):
146
+ raise AnswerRefused(f"{q.name}: {text!r} is not an http or https address")
147
+ return text
148
+ # file: a path inside the workspace (OVR-B12)
149
+ p = Path(text)
150
+ if not text or p.is_absolute() or ".." in p.parts:
151
+ raise AnswerRefused(f"{q.name}: a file answer is a path inside the workspace")
152
+ if workdir is not None and not (workdir / p).resolve().is_relative_to(workdir.resolve()):
153
+ raise AnswerRefused(f"{q.name}: a file answer is a path inside the workspace")
154
+ return text
155
+
156
+
157
+ def accept(qs: Sequence[AskQuestion], given: Mapping[str, Any], workdir: Path | None = None) -> dict[str, Any]:
158
+ """Every given answer validated by kind; one bad answer refuses the whole resume."""
159
+ by_name = {q.name: q for q in qs}
160
+ out: dict[str, Any] = {}
161
+ for name, raw in given.items():
162
+ if name not in by_name:
163
+ raise AnswerRefused(f"{name}: not a question of this ask ({', '.join(by_name)})")
164
+ out[name] = parse(by_name[name], raw, workdir)
165
+ return out
166
+
167
+
168
+ def unanswered(qs: Sequence[AskQuestion], answers: Mapping[str, Any], *, defaults: bool) -> list[str]:
169
+ """Required questions with no answer; with `defaults`, a declared default counts as one."""
170
+ return [q.name for q in qs if q.required and q.name not in answers and not (defaults and q.default is not None)]
171
+
172
+
173
+ def defaults_problems(qs: Sequence[AskQuestion]) -> list[str]:
174
+ """ASK-B13, FLX-B11: one problem for each required question with no default, which `on_deadline: defaults`
175
+ could not fill; validation and the entry check both read this."""
176
+ return [f"question {q.name!r} is required and has no default, so `on_deadline: defaults` cannot fill it"
177
+ for q in qs if q.required and q.default is None]
178
+
179
+
180
+ def complete(qs: Sequence[AskQuestion], answers: Mapping[str, Any]) -> dict[str, Any]:
181
+ """The answers with each unanswered question's default filled in."""
182
+ out = dict(answers)
183
+ for q in qs:
184
+ if q.name not in out and q.default is not None:
185
+ out[q.name] = q.default
186
+ return out
187
+
188
+
189
+ def check_problems(ask: AskSpec, answers: Mapping[str, Any]) -> list[str]:
190
+ """The author's pure check over the answers: a list of problems, empty when they pass."""
191
+ if ask.check is None:
192
+ return []
193
+ try:
194
+ got = ask.check.resolve()(dict(answers))
195
+ except Exception as exc: # noqa: BLE001 - a check that raises does not pass
196
+ return [f"the answers check raised {type(exc).__name__}"]
197
+ if got is None or got is True:
198
+ return []
199
+ if got is False:
200
+ return ["the answers check did not pass"]
201
+ return [str(x) for x in ([got] if isinstance(got, str) else got)]
202
+
203
+
204
+ def answers_path(run_folder: Path, unit: str) -> Path:
205
+ return run_folder / "answers" / f"{unit}.json"
206
+
207
+
208
+ def load(path: Path) -> dict[str, Any]:
209
+ try:
210
+ doc = json.loads(path.read_text(encoding="utf-8"))
211
+ except (OSError, ValueError):
212
+ return {}
213
+ got = doc.get("answers") if isinstance(doc, dict) else None
214
+ return dict(got) if isinstance(got, dict) else {}
215
+
216
+
217
+ def defaulted(qs: Sequence[AskQuestion], answers: Mapping[str, Any]) -> list[str]:
218
+ """ASK-B12: the questions an applied deadline fills from their default, in question order."""
219
+ return [q.name for q in qs if q.name not in answers and q.default is not None]
220
+
221
+
222
+ def store(path: Path, unit: str, answers: Mapping[str, Any], *, done: bool,
223
+ defaulted: Sequence[str] | None = None) -> None:
224
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
225
+ doc: dict[str, Any] = {"schema_version": 1, "unit": unit, "complete": done, "answers": dict(answers)}
226
+ if defaulted is not None: # only an applied deadline marks what took its default (ASK-B12)
227
+ doc["defaulted"] = list(defaulted)
228
+ write_json(path, doc)
229
+
230
+
231
+ def shown(qs: Sequence[AskQuestion], answers: Mapping[str, Any]) -> list[dict[str, Any]]:
232
+ """The pause payload's question list: kind, choices, default and whether it is answered (ASK-B8)."""
233
+ return [{**to_json(q), "answered": q.name in answers} for q in qs]
@@ -0,0 +1,63 @@
1
+ """The sampled audit judge (JDG-B7, JDG-AC7).
2
+
3
+ After a gate's judgement, with probability `audit_rate` a second judge grades the same subject on the audit
4
+ executor when one is set. Its per-criterion agreement is recorded as an `audit_judge` record and its sessions are
5
+ logged like any judge's; it never changes the verdict, the route, a counter or a budget. A session that failed,
6
+ timed out, could not be read or was discarded by the guard writes nothing.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ from collections.abc import Callable
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+
16
+ from tempergraph.contracts import CheckResult, GateSpec, SessionRequest, SessionResult, Usage
17
+ from tempergraph.run.judging import Unparsed, derive, parse_judgement
18
+
19
+
20
+ def sampled(rate: float, *, seed: int | None, thread: str, unit: str, item: str | None, attempt: int) -> bool:
21
+ """The draw: a hash of the seed, the thread, the unit, the item and the attempt against the rate, so a second
22
+ call, a resume and a rerun of the same attempt draw the same. At 1.0 every judged gate is audited, at 0 none."""
23
+ if rate >= 1.0:
24
+ return True
25
+ if rate <= 0.0:
26
+ return False
27
+ key = "\0".join([str(seed if seed is not None else ""), thread, unit, item or "", str(attempt)])
28
+ point = int.from_bytes(hashlib.sha256(key.encode("utf-8")).digest()[:8], "big") / 2**64
29
+ return point < rate
30
+
31
+
32
+ @dataclass(frozen=True, kw_only=True)
33
+ class Audit:
34
+ """What an `audit_judge` record carries."""
35
+
36
+ executor: str
37
+ alias: str
38
+ session_key: str
39
+ statuses: list[dict[str, str]] = field(default_factory=list)
40
+ usage: Usage = field(default_factory=Usage)
41
+
42
+ def fields(self) -> dict[str, Any]:
43
+ return {"executor": self.executor, "alias": self.alias, "session_key": self.session_key,
44
+ "statuses": self.statuses, "usage": self.usage}
45
+
46
+
47
+ def run(session: Callable[[SessionRequest], tuple[SessionResult, list[SessionResult]]], req: SessionRequest, *,
48
+ gate: GateSpec, check: CheckResult | None, executor: str, discarded: Callable[[SessionResult], bool]
49
+ ) -> Audit | None:
50
+ """One audit session on the gate's own prompt and views; its status per criterion, or nothing when the session
51
+ failed, timed out, could not be parsed or was discarded by the guard."""
52
+ res, _ = session(req)
53
+ if res.infra_cause is not None or res.timed_out:
54
+ return None
55
+ try:
56
+ judgement = parse_judgement(res.text, gate)
57
+ except Unparsed:
58
+ return None
59
+ if discarded(res):
60
+ return None
61
+ outcome = derive(judgement, gate, check, {})
62
+ return Audit(executor=executor, alias=req.alias, session_key=req.session_key, usage=res.usage,
63
+ statuses=[{"id": str(s["id"]), "status": str(s["status"])} for s in outcome.statuses])
@@ -0,0 +1,167 @@
1
+ """The check worker: a gate's check runs in a child engine process (CHK-B16, ADR `in-process-executors-run-in-a-worker-process`).
2
+
3
+ The engine sends the check context as one JSON document on standard input. The worker imports the check
4
+ by its reference, calls it, normalises the result and writes it as one JSON document on standard output;
5
+ anything the check prints goes to standard error. The child is started through the session launcher, so
6
+ the limit (`check_timeout_s` plus WORKER_GRACE_S) ends the worker and its whole process tree.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import shutil
13
+ import sys
14
+ import tempfile
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from tempergraph.contracts import CheckFinding, CheckResult, EventSink, GateSpec
19
+ from tempergraph.package import importer
20
+ from tempergraph.run import checks as checkmod
21
+
22
+ WORKER_GRACE_S = 30
23
+ _PRINT_LIMIT = 4_000
24
+
25
+
26
+ def context_doc(gate: GateSpec, ctx: checkmod.CheckContext) -> dict[str, Any]:
27
+ assert gate.check is not None
28
+ g = ctx.git
29
+ return {
30
+ "check": {"module": gate.check.module, "qualname": gate.check.qualname},
31
+ "check_timeout_s": gate.check_timeout_s,
32
+ "sys_path": [p for p in sys.path if p],
33
+ "packages": importer.mapping(), # private package names (PKG-B15, PKG-B16, PKG-B17 step 3)
34
+ "context": {
35
+ "unit": ctx.unit, "workdir": str(ctx.workdir), "request": ctx.request, "item": ctx.item,
36
+ "visit": ctx.visit, "attempt": ctx.attempt, "preview": ctx.preview,
37
+ "main_checkout": str(ctx.main_checkout) if ctx.main_checkout else None,
38
+ "artifacts": ctx.artifacts, "values": ctx.values, "facts": ctx.facts, "settings": ctx.settings,
39
+ "criteria": list(ctx.criteria), "allow": list(ctx.allow),
40
+ "session": None if ctx.session is None else [dict(c) for c in ctx.session], # CHK-B24, CHK-B25
41
+ "visit_session": None if ctx.visit_session is None else [dict(c) for c in ctx.visit_session], # VSR-B1
42
+ "out_dir": str(ctx.out_dir) if ctx.out_dir else None,
43
+ "reuse_store": str(ctx.reuse_store) if ctx.reuse_store else None,
44
+ "base_dir": str(ctx.base_dir) if ctx.base_dir else None,
45
+ "no_reuse_exit_codes": {k: list(v) for k, v in ctx.no_reuse_exit_codes.items()},
46
+ "changed_paths": list(ctx.changed_paths),
47
+ "alone": [r.to_json() for r in ctx.alone], # KIL-B10: the runs alone the check answers from
48
+ "git": None if g is None else {
49
+ "branch": g.branch, "base": g.base, "head": g.head, "base_head": g.base_head, "own_base": g.own_base,
50
+ "clean": g.clean, "pushed": g.pushed, "changed_paths": list(g.changed_paths),
51
+ "commits_since_base": list(g.commits_since_base)},
52
+ },
53
+ }
54
+
55
+
56
+ def _context_from(doc: dict[str, Any]) -> checkmod.CheckContext:
57
+ c = doc["context"]
58
+ g = c.get("git")
59
+ held = c.get("session")
60
+ visit = c.get("visit_session")
61
+ return checkmod.CheckContext(
62
+ visit_session=tuple(dict(x) for x in visit if isinstance(x, dict)) if isinstance(visit, list) else None,
63
+ session=tuple(dict(x) for x in held if isinstance(x, dict)) if isinstance(held, list) else None,
64
+ changed_paths=tuple(c.get("changed_paths") or ()),
65
+ unit=c["unit"], workdir=Path(c["workdir"]), request=c.get("request") or {}, item=c.get("item"),
66
+ visit=int(c.get("visit", 1)), attempt=int(c.get("attempt", 1)), preview=bool(c.get("preview")),
67
+ main_checkout=Path(c["main_checkout"]) if c.get("main_checkout") else None,
68
+ artifacts=c.get("artifacts") or {}, values=c.get("values") or {}, facts=c.get("facts") or {},
69
+ settings=c.get("settings") or {}, criteria=tuple(c.get("criteria") or ()), allow=tuple(c.get("allow") or ()),
70
+ out_dir=Path(c["out_dir"]) if c.get("out_dir") else None,
71
+ reuse_store=Path(c["reuse_store"]) if c.get("reuse_store") else None,
72
+ base_dir=Path(c["base_dir"]) if c.get("base_dir") else None,
73
+ no_reuse_exit_codes={k: tuple(v) for k, v in (c.get("no_reuse_exit_codes") or {}).items()},
74
+ alone=[checkmod.command_run_from(r) for r in c.get("alone") or [] if isinstance(r, dict)],
75
+ git=None if g is None else checkmod.GitFacts(
76
+ branch=g.get("branch", ""), base=g.get("base", ""), head=g.get("head", ""),
77
+ base_head=g.get("base_head", ""), own_base=g.get("own_base", ""), clean=bool(g.get("clean", True)), pushed=bool(g.get("pushed")),
78
+ changed_paths=tuple(g.get("changed_paths") or ()),
79
+ commits_since_base=tuple(g.get("commits_since_base") or ())))
80
+
81
+
82
+ def result_from(doc: dict[str, Any]) -> CheckResult:
83
+ return CheckResult(
84
+ result=doc.get("result", "FAIL"), evidence=str(doc.get("evidence") or ""),
85
+ environmental=bool(doc.get("environmental")), untracked_only=bool(doc.get("untracked_only")),
86
+ findings=[CheckFinding(status=f.get("status", "maybe"), criterion=f.get("criterion"),
87
+ place=f.get("place", ""), fix=f.get("fix", ""), message=f.get("message", ""),
88
+ kind=f.get("kind") if f.get("kind") in ("substance", "output_contract") else None)
89
+ for f in doc.get("findings") or []],
90
+ facts=dict(doc.get("facts") or {}), runs=list(doc.get("runs") or []))
91
+
92
+
93
+ def main() -> int:
94
+ """The worker's entry: one document in, one document out."""
95
+ out = sys.stdout
96
+ sys.stdout = sys.stderr # a check's own prints never mix with the result
97
+ try:
98
+ doc = json.loads(sys.stdin.read())
99
+ for p in reversed(doc.get("sys_path") or []):
100
+ if p not in sys.path:
101
+ sys.path.insert(0, p)
102
+ importer.install(doc.get("packages"))
103
+ from tempergraph.contracts import CallableRef, Criterion
104
+
105
+ ref = CallableRef(module=doc["check"]["module"], qualname=doc["check"]["qualname"])
106
+ gate = GateSpec(criteria=(Criterion(text="-"),), check=ref, check_timeout_s=int(doc["check_timeout_s"]))
107
+ res, notes = checkmod.run_check(gate, _context_from(doc))
108
+ payload = {"result": checkmod.to_json(res), "notes": notes}
109
+ except Exception as exc: # noqa: BLE001 - the worker itself failed; the engine reads it as environmental
110
+ payload = {"worker_error": type(exc).__name__}
111
+ out.write(json.dumps(payload, default=str))
112
+ out.flush()
113
+ return 0
114
+
115
+
116
+ def run_in_worker(gate: GateSpec, ctx: checkmod.CheckContext, *, python: str | None = None
117
+ ) -> tuple[CheckResult, list[str]]:
118
+ """Run the gate's check in a check worker; a worker past its limit is an environmental FAIL."""
119
+ if gate.check is None:
120
+ return CheckResult(result="PASS", evidence=""), []
121
+ return run_doc(context_doc(gate, ctx), ctx.workdir, gate.check_timeout_s, f"check-{ctx.unit}-{ctx.attempt}",
122
+ python=python)
123
+
124
+
125
+ def run_doc(doc: dict[str, Any], workdir: Path, timeout_s: int, key: str, *, python: str | None = None
126
+ ) -> tuple[CheckResult, list[str]]:
127
+ """One worker run of a context document; the check preview sends a stored one (CHK-B17)."""
128
+ base_dir = tempfile.mkdtemp(prefix="tempergraph-base-") # CHK-B21: outside the workspace, removed below
129
+ try:
130
+ return _run_doc(doc, base_dir, workdir, timeout_s, key, python)
131
+ finally:
132
+ shutil.rmtree(base_dir, ignore_errors=True) # a worker ended at its limit leaves no checkout
133
+
134
+
135
+ def _run_doc(doc: dict[str, Any], base_dir: str, workdir: Path, timeout_s: int, key: str, python: str | None
136
+ ) -> tuple[CheckResult, list[str]]:
137
+ from tempergraph.executors.launcher import LaunchSpec, launch
138
+
139
+ doc = {**doc, "context": {**doc["context"], "base_dir": base_dir}}
140
+ payload = json.dumps(doc, default=str).encode()
141
+ spec = LaunchSpec(argv=[python or sys.executable, "-m", "tempergraph.run.check_worker"], stdin_payload=payload,
142
+ workdir=workdir, timeout_s=timeout_s + WORKER_GRACE_S,
143
+ session_key=key, prompt_window_s=float(timeout_s))
144
+ got: list[bytes] = []
145
+
146
+ def keep(line: bytes) -> list[Any]:
147
+ got.append(line)
148
+ return []
149
+
150
+ raw = launch(spec, keep, EventSink())
151
+ if raw.stop_reason is not None or raw.killed:
152
+ return CheckResult(result="FAIL", evidence=f"check worker ended at its limit of {timeout_s} s",
153
+ environmental=True), ["check_worker_limit"]
154
+ text = b"".join(got).decode("utf-8", errors="replace").strip()
155
+ try:
156
+ out = json.loads(text) if text else {}
157
+ except ValueError:
158
+ out = {}
159
+ if raw.spawn_error is not None or "result" not in out:
160
+ why = out.get("worker_error") or (type(raw.spawn_error).__name__ if raw.spawn_error else "no result")
161
+ return CheckResult(result="FAIL", evidence=f"check worker failed: {str(why)[:_PRINT_LIMIT]}",
162
+ environmental=True), [f"check_worker_failed: {why}"]
163
+ return result_from(out["result"]), list(out.get("notes") or [])
164
+
165
+
166
+ if __name__ == "__main__":
167
+ raise SystemExit(main())