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,279 @@
1
+ """Reading run events: the run log in `seq` order, the activity journal, `--follow`, narrator lines and the
2
+ in-process observers (EVT-B8, EVT-B9, EVT-B10 to EVT-B16, EVT-B17, EVT-B18, EVT-B7, EVT-B19, EVT-B22, EVT-B23, EVT-B24; ADR `observers-read-files-not-sockets`, ADR `in-process-observers-and-wider-hook-events`).
3
+
4
+ Readers here create nothing and call no model (OVR-B15); they skip unknown kinds and fields (OVR-B14).
5
+ Observers never change a run or its exit code (OVR-B4, EVT-B5).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import json
12
+ import queue
13
+ import threading
14
+ import time
15
+ from collections.abc import Callable, Iterator, Mapping
16
+ from dataclasses import dataclass, field
17
+ from importlib.metadata import entry_points
18
+ from pathlib import Path
19
+ from typing import Any, Protocol, runtime_checkable
20
+
21
+ QUEUE_SIZE = 1_000
22
+ NARRATED = frozenset({"unit_entered", "check", "gate", "route", "pause", "human", "budget", "stop_requested"})
23
+
24
+
25
+ # -- reading ----------------------------------------------------------------------------------------
26
+
27
+
28
+ def _lines(path: Path, offset: int = 0) -> tuple[list[dict[str, Any]], int]:
29
+ """Complete JSON lines from byte `offset`; a partial last line is left for the next read."""
30
+ try:
31
+ with open(path, "rb") as fh:
32
+ fh.seek(offset)
33
+ data = fh.read()
34
+ except OSError:
35
+ return [], offset
36
+ out: list[dict[str, Any]] = []
37
+ end = data.rfind(b"\n")
38
+ if end < 0:
39
+ return out, offset
40
+ for line in data[: end + 1].splitlines():
41
+ if not line.strip():
42
+ continue
43
+ try:
44
+ rec = json.loads(line)
45
+ except ValueError:
46
+ continue
47
+ if isinstance(rec, dict):
48
+ out.append(rec)
49
+ return out, offset + end + 1
50
+
51
+
52
+ def records(path: Path, since: int | None = None) -> list[dict[str, Any]]:
53
+ """Every run-log record after `since`, in `seq` order; the schema line is not a record."""
54
+ recs, _ = _lines(path)
55
+ return [r for r in recs if isinstance(r.get("seq"), int) and (since is None or r["seq"] > since)]
56
+
57
+
58
+ def follow(path: Path, held: Callable[[], bool], since: int | None = None, *, poll_s: float = 0.25,
59
+ timeout_s: float | None = None, sleep: Callable[[float], None] = time.sleep) -> Iterator[dict[str, Any]]:
60
+ """Records after `since` as they are written; ends once the newest segment's `run_exit` is read and no
61
+ lock is held (EVT-B22, EVT-B23, EVT-B24, EVT-B3). Each record is yielded once."""
62
+ offset, last, ended = 0, since, False
63
+ start = time.monotonic()
64
+ while True:
65
+ recs, offset = _lines(path, offset)
66
+ for r in recs:
67
+ seq = r.get("seq")
68
+ if not isinstance(seq, int):
69
+ continue
70
+ if r.get("kind") == "run_started":
71
+ ended = False
72
+ elif r.get("kind") == "run_exit":
73
+ ended = True
74
+ if last is not None and seq <= last:
75
+ continue
76
+ last = seq
77
+ yield r
78
+ if not held() and (ended or not recs):
79
+ return # the segment exited, or the process is gone without a `run_exit` (orphaned)
80
+ if timeout_s is not None and time.monotonic() - start >= timeout_s:
81
+ return
82
+ sleep(poll_s)
83
+
84
+
85
+ def activity(path: Path, since: int | None = None) -> list[dict[str, Any]]:
86
+ """One session's activity journal lines after line number `since`."""
87
+ lines, _ = _lines(path)
88
+ return [ln for ln in lines if since is None or (isinstance(ln.get("n"), int) and ln["n"] > since)]
89
+
90
+
91
+ def follow_activity(path: Path, live: Path, held: Callable[[], bool], since: int | None = None, *,
92
+ poll_s: float = 0.25, timeout_s: float | None = None,
93
+ sleep: Callable[[float], None] = time.sleep) -> Iterator[dict[str, Any]]:
94
+ """Journal lines as they are flushed; ends at the session's `result` or `truncated` line, when its live
95
+ file is removed at session end, or when no lock is held."""
96
+ offset, last, seen_live, done = 0, since, False, False
97
+ start = time.monotonic()
98
+ while True:
99
+ lines, offset = _lines(path, offset)
100
+ seen_live = seen_live or live.exists()
101
+ for ln in lines:
102
+ if ln.get("ev") in ("result", "truncated"):
103
+ done = True
104
+ n = ln.get("n")
105
+ if last is not None and isinstance(n, int) and n <= last:
106
+ continue
107
+ if isinstance(n, int):
108
+ last = n
109
+ yield ln
110
+ if not lines and (done or (seen_live and not live.exists()) or not held()):
111
+ return
112
+ if timeout_s is not None and time.monotonic() - start >= timeout_s:
113
+ return
114
+ sleep(poll_s)
115
+
116
+
117
+ # -- narrator lines ---------------------------------------------------------------------------------
118
+
119
+
120
+ def route_unit(node: Any) -> str | None:
121
+ """A graph node by its unit: `draft.step` is `draft`, a human node is `human`, the end is `end`."""
122
+ if not isinstance(node, str) or not node:
123
+ return None
124
+ if node.endswith(".human"):
125
+ return "human"
126
+ if node == "__end__":
127
+ return "end"
128
+ return node.split(".", 1)[0]
129
+
130
+
131
+ def narrate(r: Mapping[str, Any]) -> str:
132
+ """One line for a run-log record, as a monitor's narrator shows it (RDD-B7 to RDD-B11, RDD-B13, RDD-B15 `events_tail`)."""
133
+ kind = str(r.get("kind"))
134
+ where = r.get("unit") or ""
135
+ if r.get("item"):
136
+ where = f"{where}[{r['item']}]"
137
+ if r.get("attempt") is not None and kind not in ("unit_entered",):
138
+ where = f"{where}#{r['attempt']}" if where else ""
139
+ text: str
140
+ if kind == "unit_entered":
141
+ text = f"entered {where} (visit {r.get('visit')}, from {r.get('entered_from')})"
142
+ elif kind == "check":
143
+ env = " environmental" if r.get("environmental") else ""
144
+ text = f"check {where}: {r.get('result')}{env}"
145
+ elif kind == "judgement":
146
+ text = f"judge {where}: {r.get('met', '?')}/{r.get('total', '?')} met"
147
+ elif kind == "gate":
148
+ target = route_unit(r.get("route_target"))
149
+ text = f"gate {where}: {r.get('verdict')}" + (f" -> {target}" if target else "")
150
+ elif kind == "pause":
151
+ text = f"paused at {where} ({r.get('pause_kind') or r.get('session_kind')}): {r.get('resume') or ''}".rstrip()
152
+ elif kind == "human":
153
+ text = f"decision at {where}: {r.get('decision')}"
154
+ elif kind == "budget":
155
+ text = f"budget {r.get('counter')}: {r.get('used')}/{r.get('limit')} ({r.get('cause')})"
156
+ elif kind == "stop_requested":
157
+ text = f"stop requested ({r.get('mode')})"
158
+ elif kind == "route":
159
+ text = f"route {where} -> {route_unit(r.get('target') or r.get('route_target'))}"
160
+ elif kind == "session_opened":
161
+ text = f"session {r.get('session_key')} on {r.get('executor')} ({r.get('model') or r.get('alias')})"
162
+ elif kind == "run_started":
163
+ text = f"segment {r.get('segment')} started ({r.get('origin')})"
164
+ elif kind == "run_exit":
165
+ text = f"segment {r.get('segment')} exited {r.get('exit_code')} ({r.get('reason')})"
166
+ else:
167
+ text = f"{kind} {where}".rstrip()
168
+ return f"{r.get('seq')} {r.get('ts')} {text}"
169
+
170
+
171
+ def tail(recs: list[dict[str, Any]], n: int = 20) -> list[str]:
172
+ return [narrate(r) for r in recs if r.get("kind") in NARRATED][-n:]
173
+
174
+
175
+ # -- in-process observers (EVT-B22, EVT-B23, EVT-B24) ----------------------------------------------------------------
176
+
177
+
178
+ @runtime_checkable
179
+ class RunObserver(Protocol):
180
+ name: str
181
+
182
+ def on_record(self, record: dict[str, Any]) -> None: ...
183
+
184
+ def on_activity(self, session_key: str, line: dict[str, Any]) -> None: ...
185
+
186
+
187
+ def register_observers(entry_point_group: str = "tempergraph.observers",
188
+ names: tuple[str, ...] | None = None) -> tuple[list[RunObserver], list[str]]:
189
+ """Observers installed under the entry-point group; only those named (operator config) are loaded.
190
+ Returns the observers and the names that are not installed (a preflight warning, EVT-B25)."""
191
+ wanted = set(names or ())
192
+ found: dict[str, RunObserver] = {}
193
+ for ep in entry_points(group=entry_point_group):
194
+ if ep.name not in wanted:
195
+ continue
196
+ try:
197
+ obj = ep.load()
198
+ inst = obj() if isinstance(obj, type) else obj
199
+ except Exception: # noqa: BLE001 - a broken observer never stops a run
200
+ continue
201
+ if isinstance(inst, RunObserver):
202
+ found[ep.name] = inst
203
+ missing = sorted(wanted - set(found))
204
+ return list(found.values()), missing
205
+
206
+
207
+ @dataclass
208
+ class _Lane:
209
+ observer: RunObserver
210
+ q: queue.Queue[tuple[str, Any] | None] = field(default_factory=lambda: queue.Queue(QUEUE_SIZE))
211
+ dropped: int = 0
212
+ disabled: bool = False
213
+ error: str | None = None
214
+ thread: threading.Thread | None = None
215
+
216
+
217
+ class ObserverHub:
218
+ """Each observer on its own thread behind a bounded queue: a full queue drops and counts, an exception
219
+ disables that observer for the segment and is recorded once as an `engine_error` of scope `observer`."""
220
+
221
+ def __init__(self, observers: list[RunObserver]) -> None:
222
+ self.lanes = [_Lane(o) for o in observers]
223
+ self._errors: queue.Queue[tuple[str, str]] = queue.Queue()
224
+ for lane in self.lanes:
225
+ lane.thread = threading.Thread(target=self._pump, args=(lane,), daemon=True,
226
+ name=f"observer-{lane.observer.name}")
227
+ lane.thread.start()
228
+
229
+ def _pump(self, lane: _Lane) -> None:
230
+ while True:
231
+ item = lane.q.get()
232
+ if item is None:
233
+ return
234
+ if lane.disabled:
235
+ continue
236
+ what, payload = item
237
+ try:
238
+ if what == "record":
239
+ lane.observer.on_record(payload)
240
+ else:
241
+ lane.observer.on_activity(payload[0], payload[1])
242
+ except Exception as exc: # noqa: BLE001 - EVT-B5
243
+ lane.disabled = True
244
+ lane.error = type(exc).__name__
245
+ self._errors.put((lane.observer.name, lane.error))
246
+
247
+ def _put(self, item: tuple[str, Any]) -> None:
248
+ for lane in self.lanes:
249
+ if lane.disabled:
250
+ continue
251
+ try:
252
+ lane.q.put_nowait(item)
253
+ except queue.Full:
254
+ lane.dropped += 1
255
+
256
+ def on_record(self, record: dict[str, Any]) -> None:
257
+ self._put(("record", dict(record)))
258
+
259
+ def on_activity(self, session_key: str, line: dict[str, Any]) -> None:
260
+ self._put(("activity", (session_key, dict(line))))
261
+
262
+ def take_errors(self) -> list[tuple[str, str]]:
263
+ out = []
264
+ while True:
265
+ try:
266
+ out.append(self._errors.get_nowait())
267
+ except queue.Empty:
268
+ return out
269
+
270
+ def close(self, timeout_s: float = 5.0) -> dict[str, dict[str, Any]]:
271
+ """Drain and stop every lane; returns per observer its dropped count and whether it was disabled."""
272
+ for lane in self.lanes:
273
+ with contextlib.suppress(queue.Full):
274
+ lane.q.put(None, timeout=timeout_s)
275
+ for lane in self.lanes:
276
+ if lane.thread is not None:
277
+ lane.thread.join(timeout_s)
278
+ return {lane.observer.name: {"dropped": lane.dropped, "disabled": lane.disabled, "error": lane.error}
279
+ for lane in self.lanes}
@@ -0,0 +1,132 @@
1
+ """The finalizer contract (FIN-B6 to FIN-B10): one call after the last pass, no model, never the request text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import time
7
+ from collections.abc import Mapping
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from tempergraph.run import checks as checkmod
13
+ from tempergraph.run.commands import CommandRefusal, CommandRun, ResolvedCommand, resolve_command, run_command
14
+ from tempergraph.security.scrub import clip, scrub
15
+
16
+ if TYPE_CHECKING:
17
+ from tempergraph.run.nodes import RunContext
18
+
19
+ FINALIZER_LIMIT_S = 600
20
+ COMMAND_LIMIT_S = 120
21
+
22
+
23
+ @dataclass(kw_only=True)
24
+ class FinalizerContext:
25
+ task_id: str
26
+ thread_id: str
27
+ workflow: str
28
+ branch: str
29
+ base: str
30
+ workdir: Path
31
+ artifacts: Mapping[str, Any]
32
+ values: Mapping[str, Any]
33
+ facts: Mapping[str, Any]
34
+ open_warnings: int
35
+ degraded: bool
36
+ run_options: Mapping[str, Any]
37
+ git: checkmod.GitFacts | None # None outside a git repository (WSP-B15 to WSP-B18)
38
+ allow: tuple[str, ...] = ()
39
+ main: Path | None = None
40
+ out_dir: Path | None = None
41
+ runs: list[CommandRun] = field(default_factory=list)
42
+ settings: Mapping[str, Any] = field(default_factory=dict) # FIN-B12: the workflow's resolved settings
43
+
44
+ def resolve(self, text: str) -> ResolvedCommand | CommandRefusal:
45
+ return resolve_command(self.allow, text, self.workdir)
46
+
47
+ def run(self, cmd: ResolvedCommand | str, timeout_s: float = COMMAND_LIMIT_S) -> CommandRun:
48
+ if isinstance(cmd, str):
49
+ got = self.resolve(cmd)
50
+ if isinstance(got, CommandRefusal):
51
+ return CommandRun(argv=(clip(scrub(cmd), 200),), not_started=True, extra={"refused": got.reason})
52
+ cmd = got
53
+ out = (self.out_dir or self.workdir) / f"{len(self.runs) + 1}.out"
54
+ r = run_command(cmd, self.workdir, out, timeout_s, main=self.main)
55
+ self.runs.append(r)
56
+ return r
57
+
58
+ @staticmethod
59
+ def scrub(text: str) -> str:
60
+ return scrub(text)
61
+
62
+ @staticmethod
63
+ def clip(text: str, n: int) -> str:
64
+ return clip(text, n)
65
+
66
+
67
+ @dataclass(kw_only=True)
68
+ class FinalizerResult:
69
+ outcome: str
70
+ reason: str = ""
71
+ url: str | None = None
72
+ manual_steps: list[str] = field(default_factory=list)
73
+
74
+
75
+ def recorded_pull_request(result: Mapping[str, Any] | None, workdir: Path | None) -> dict[str, Any] | None:
76
+ """FIN-B11: the code host, repository, number and end commit of the pull request the `finalized` result's url
77
+ names; none for no url or a url that names no pull request. It holds no text."""
78
+ from tempergraph import git
79
+ from tempergraph.improve.proposals import pull_ref
80
+
81
+ ref = pull_ref((result or {}).get("url"))
82
+ if ref is None:
83
+ return None
84
+ commit = ""
85
+ if workdir is not None:
86
+ try:
87
+ commit = git.head(workdir)
88
+ except Exception: # noqa: BLE001 - a workspace that is gone has no end commit to record
89
+ commit = ""
90
+ return {"host": ref[0], "repo": ref[1], "number": ref[2], "commit": commit}
91
+
92
+
93
+ def run_finalizer(ctx: RunContext, state: Mapping[str, Any]) -> dict[str, Any]:
94
+ spec = ctx.spec
95
+ if spec.finalizer is None:
96
+ return {"outcome": "none"}
97
+ ws = state.get("workspace") or {}
98
+ workdir = Path(ws.get("path") or ctx.state_root.parent)
99
+ open_warnings = sum(len((j or {}).get("notes") or []) for j in (state.get("judgements") or {}).values())
100
+ fctx = FinalizerContext(
101
+ task_id=ctx.task_id, thread_id=ctx.thread, workflow=spec.name, branch=str(ws.get("branch") or ""),
102
+ base=str(ws.get("base_branch") or ""), workdir=workdir, artifacts=state.get("artifacts") or {},
103
+ values=state.get("values") or {}, facts=state.get("facts") or {}, open_warnings=open_warnings,
104
+ degraded=False, run_options={"mode": ws.get("mode")}, git=checkmod.git_facts(workdir),
105
+ allow=tuple(spec.allow_commands), main=ctx.main_checkout, settings=dict(ctx.settings),
106
+ out_dir=ctx.state_root / "runs" / spec.name / ctx.task_id / "finalizer")
107
+ box: dict[str, Any] = {}
108
+ fn = spec.finalizer.resolve()
109
+
110
+ def call() -> None:
111
+ try:
112
+ box["result"] = fn(fctx)
113
+ except Exception as exc: # noqa: BLE001 - recorded as `error`
114
+ box["error"] = type(exc).__name__
115
+
116
+ t0 = time.monotonic()
117
+ th = threading.Thread(target=call, name="finalizer", daemon=True)
118
+ th.start()
119
+ th.join(FINALIZER_LIMIT_S)
120
+ dur = round(time.monotonic() - t0, 3)
121
+ if th.is_alive():
122
+ return {"outcome": "error", "reason": "timed_out", "duration_s": dur}
123
+ if "error" in box:
124
+ return {"outcome": "error", "reason": box["error"], "duration_s": dur}
125
+ res = box.get("result")
126
+ if not isinstance(res, FinalizerResult):
127
+ return {"outcome": "invalid", "reason": clip(scrub(repr(res)), 200), "duration_s": dur}
128
+ outcome = res.outcome if res.outcome in spec.finalizer_outcomes else "invalid"
129
+ reason = clip(scrub(res.reason if outcome != "invalid" else res.outcome), 200)
130
+ return {"outcome": outcome, "reason": reason, "url": res.url, "manual_steps": [clip(scrub(m), 300) for m in
131
+ res.manual_steps[:5]],
132
+ "duration_s": dur}