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,773 @@
1
+ """The run detail document (RDD-B7 to RDD-B15): one thread in full, built on demand, never stored.
2
+
3
+ Sources, all opened read-only: the diagram model, the run log, the checkpoint (through the status row and
4
+ an observer graph) and each running session's live file. It calls no model and creates nothing (contract
5
+ C13). Text is scrubbed and clipped; paths are local. Facts the run has not recorded are left out or null,
6
+ never zero (CON-B14, CON-B1, CON-B15).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections.abc import Mapping
13
+ from datetime import UTC, datetime
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from tempergraph.constants import SCHEMA
18
+ from tempergraph.contracts import WorkflowSpec
19
+ from tempergraph.durability import engine_file
20
+ from tempergraph.durability.checkpoint import Snapshot, observer_graph, open_readonly, snapshot
21
+ from tempergraph.durability.status import row as status_row
22
+ from tempergraph.durability.status import split_thread
23
+ from tempergraph.improve import loop_summary
24
+ from tempergraph.model import flow
25
+ from tempergraph.model.diagram import diagram_model
26
+ from tempergraph.run.events import records, route_unit, tail
27
+ from tempergraph.security.scrub import clip, scrub
28
+ from tempergraph.store.layout import now_iso, run_dir, session_dir
29
+
30
+ TEXT_CLIP = 200
31
+ EVIDENCE_CLIP = 400
32
+ MAX_BYTES = 1_000_000
33
+ STEP_KINDS = frozenset({"step", "retry"})
34
+ JUDGE_KINDS = frozenset({"judge", "judge_reask", "judge_reread"})
35
+ ENTERED_WORDS = ("start", "proceed", "retry", "resume", "rerun")
36
+
37
+
38
+ def _ts(value: Any) -> datetime | None:
39
+ if not isinstance(value, str):
40
+ return None
41
+ try:
42
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
43
+ except ValueError:
44
+ return None
45
+
46
+
47
+ def _secs(a: Any, b: Any) -> float | None:
48
+ ta, tb = (_ts(a) if not isinstance(a, datetime) else a), (_ts(b) if not isinstance(b, datetime) else b)
49
+ if ta is None or tb is None:
50
+ return None
51
+ return round((tb - ta).total_seconds(), 3)
52
+
53
+
54
+ def _text(v: Any, limit: int = TEXT_CLIP) -> str | None:
55
+ return clip(scrub(str(v)), limit) if v not in (None, "") else None
56
+
57
+
58
+ def _entered_from(value: Any, units: Mapping[str, Any]) -> str:
59
+ """The run log's `entered_from`, in the words of EVT-B10 to EVT-B16 (a bare unit name is a trip back from it)."""
60
+ v = str(value or "start")
61
+ if v in ENTERED_WORDS or ":" in v:
62
+ return v
63
+ return f"back:{v}" if v in units else v
64
+
65
+
66
+ def _unit_of(node: Any) -> str | None:
67
+ if not isinstance(node, str) or not node:
68
+ return None
69
+ if node in (flow.FINALIZER, flow.END):
70
+ return node
71
+ return node.split(".", 1)[0]
72
+
73
+
74
+ # -- plan ----------------------------------------------------------------------------------------------
75
+
76
+
77
+ def _plan(spec: WorkflowSpec, model: Mapping[str, Any]) -> list[dict[str, Any]]:
78
+ by_unit: dict[str, list[dict[str, Any]]] = {}
79
+ for a, b, token in model.get("edges") or []:
80
+ if not a.endswith(".gate"):
81
+ continue # a human node's edges are its decision words, shown on the pause
82
+ src, dst = a.split(".", 1)[0], route_unit(b)
83
+ if dst is None or (dst == src and token == "RETRY"):
84
+ continue
85
+ by_unit.setdefault(src, [])
86
+ edge = {"target": dst, "on": token}
87
+ if edge not in by_unit[src]:
88
+ by_unit[src].append(edge)
89
+ out = []
90
+ for u in model.get("units") or []:
91
+ name = u["name"]
92
+ us = spec.units.get(name)
93
+ gated = bool(us is not None and (us.gate.judge is not None or us.gate.check is not None or us.gate.approval))
94
+ step = us.step if us is not None else None
95
+ judge = us.gate.judge if us is not None else None
96
+ out.append({"name": name, "kind": u.get("kind"), "gated": gated,
97
+ "executor": (step.executor if step else None) or (spec.default_executor if step else None),
98
+ "judge_executor": (judge.executor if judge else None) or (spec.default_executor if judge else None),
99
+ "alias": _alias(step.model if step else None), "edges": by_unit.get(name, []), "items": None})
100
+ out.append({"name": flow.FINALIZER, "kind": "finalizer", "gated": False, "executor": None,
101
+ "judge_executor": None, "alias": None, "edges": [], "items": None})
102
+ return out
103
+
104
+
105
+ def _alias(model: Any) -> str | None:
106
+ if isinstance(model, str):
107
+ return model
108
+ if isinstance(model, tuple | list) and model:
109
+ return str(model[0])
110
+ return None
111
+
112
+
113
+ # -- folding the run log -------------------------------------------------------------------------------
114
+
115
+
116
+ class _Fold:
117
+ """Walks the records once and builds units, sessions, budgets, touches and the open pause."""
118
+
119
+ def __init__(self, units: Mapping[str, Any]) -> None:
120
+ self.units_spec = units
121
+ self.units: dict[str, dict[str, Any]] = {}
122
+ self.sessions: dict[str, dict[str, Any]] = {}
123
+ self.current: dict[str, dict[str, Any]] = {} # unit -> its open attempt
124
+ self._round: dict[str, int] = {} # contest unit -> the picks recorded so far
125
+ self.budgets: dict[str, dict[str, Any]] = {}
126
+ self.touches: list[dict[str, Any]] = []
127
+ self.pause: dict[str, Any] | None = None
128
+ self.supervision: dict[str, Any] | None = None
129
+ self.segment_start: dict[str, Any] | None = None
130
+ self.segment_exit: dict[str, Any] | None = None
131
+ self.last_unit: str | None = None
132
+ self.plan_digest: str | None = None
133
+
134
+ def _unit(self, name: str) -> dict[str, Any]:
135
+ return self.units.setdefault(name, {"visits": []})
136
+
137
+ def _visit(self, unit: str, entered_from: str = "resume") -> dict[str, Any]:
138
+ u = self._unit(unit)
139
+ if not u["visits"]:
140
+ u["visits"].append({"visit": 1, "entered_from": entered_from, "attempts": []})
141
+ return u["visits"][-1]
142
+
143
+ def _contest(self, unit: str) -> bool:
144
+ u = self.units_spec.get(unit)
145
+ return u is not None and getattr(u, "kind", None) == "contest"
146
+
147
+ def _entry(self, unit: str, number: Any, item: Any, ts: Any) -> dict[str, Any]:
148
+ att: dict[str, Any] = {"attempt": number, "item": item, "started_at": ts, "ended_at": None, "step": None,
149
+ "check": None, "judge": None, "gate": None, "repeat_cause": None}
150
+ if self._contest(unit): # RDD-B19, RDD-B20: a slot's verdict, keys, `skipped` and `winner` come with the pick
151
+ att.update(verdict=None, keys=None, skipped=False, winner=None)
152
+ return att
153
+
154
+ def _attempt(self, unit: str, number: Any, item: Any, ts: Any) -> dict[str, Any]:
155
+ visit = self._visit(unit)
156
+ for a in visit["attempts"]:
157
+ if a["attempt"] == number and a["item"] == item:
158
+ return a
159
+ att = self._entry(unit, number, item, ts)
160
+ visit["attempts"].append(att)
161
+ self.current[unit] = att
162
+ return att
163
+
164
+ def _open(self, unit: str, item: Any = None, attempt: Any = None) -> dict[str, Any] | None:
165
+ """RDD-B10: the attempt a record belongs to: the one of the `item` it names (and its `attempt` when it names one),
166
+ else the unit's open attempt; interleaved slots or items of a unit keep their own records."""
167
+ held = self.units.get(unit)
168
+ if item is not None and held and held["visits"]:
169
+ mine = [a for a in held["visits"][-1]["attempts"] if a["item"] == item]
170
+ if attempt is not None:
171
+ exact = [a for a in mine if a["attempt"] == attempt]
172
+ mine = exact or mine
173
+ if mine:
174
+ return mine[-1]
175
+ return self.current.get(unit)
176
+
177
+ def feed(self, r: Mapping[str, Any]) -> None:
178
+ kind = r.get("kind")
179
+ unit = r.get("unit") if isinstance(r.get("unit"), str) else None
180
+ handler = getattr(self, f"_on_{kind}", None)
181
+ if handler is not None:
182
+ handler(r, unit)
183
+ if unit:
184
+ self.last_unit = unit
185
+
186
+ def _on_run_started(self, r: Mapping[str, Any], unit: str | None) -> None:
187
+ self.segment_start, self.segment_exit = dict(r), None
188
+ if isinstance(r.get("plan_digest"), str):
189
+ self.plan_digest = r["plan_digest"]
190
+
191
+ def _on_run_exit(self, r: Mapping[str, Any], unit: str | None) -> None:
192
+ self.segment_exit = dict(r)
193
+
194
+ def _on_unit_entered(self, r: Mapping[str, Any], unit: str | None) -> None:
195
+ if not unit:
196
+ return
197
+ u = self._unit(unit)
198
+ u["visits"].append({"visit": r.get("visit") or len(u["visits"]) + 1,
199
+ "entered_from": _entered_from(r.get("entered_from"), self.units_spec), "attempts": []})
200
+ self.current.pop(unit, None)
201
+
202
+ def _on_attempt_start(self, r: Mapping[str, Any], unit: str | None) -> None:
203
+ key = r.get("session_key")
204
+ if not unit or not isinstance(key, str):
205
+ return
206
+ kind = r.get("session_kind")
207
+ att = self._attempt(unit, r.get("attempt"), r.get("item"), r.get("ts"))
208
+ s = self.sessions.get(key)
209
+ if s is None:
210
+ s = {"session_key": key, "kind": kind, "executor": r.get("executor"), "alias": r.get("alias"),
211
+ "model": None, "session_id": None, "transcript": None, "activity_path": None, "live_path": None,
212
+ "usage": None, "tool_calls": None, "outcome": None, "started_at": r.get("ts"), "ended_at": None,
213
+ "timeout_s": r.get("timeout_s"), "idle_s": r.get("idle_s"), "infra_tries": 0}
214
+ self.sessions[key] = s
215
+ if kind in JUDGE_KINDS:
216
+ att["judge"] = att["judge"] or {"sessions": []}
217
+ att["judge"]["sessions"].append(s)
218
+ else:
219
+ att["step"] = att["step"] or {"sessions": []}
220
+ att["step"]["sessions"].append(s)
221
+ else: # an infra retry of the same session (BUD-B1): the same folder, a new process
222
+ s["infra_tries"] += 1
223
+ s["ended_at"] = None
224
+
225
+ def _on_session_opened(self, r: Mapping[str, Any], unit: str | None) -> None:
226
+ s = self.sessions.get(str(r.get("session_key")))
227
+ if s is not None:
228
+ s.update(model=r.get("model"), session_id=r.get("session_id"), transcript=r.get("transcript"),
229
+ pgid=r.get("pgid"))
230
+
231
+ def _on_agent_run(self, r: Mapping[str, Any], unit: str | None) -> None:
232
+ s = self.sessions.get(str(r.get("session_key")))
233
+ if s is None:
234
+ return
235
+ tools = r.get("tools")
236
+ s.update(usage=r.get("usage"), tool_calls=len(tools) if isinstance(tools, list) else None,
237
+ session_id=s.get("session_id") or r.get("session_id"), ended_at=r.get("ts"),
238
+ outcome={"ok": r.get("ok"), "timed_out": r.get("timed_out"), "stalled": r.get("stalled"),
239
+ "partial": r.get("partial"), "infra_cause": r.get("infra_cause"),
240
+ "error_kind": r.get("error_kind")})
241
+
242
+ def _council(self, r: Mapping[str, Any], unit: str | None) -> dict[str, Any] | None:
243
+ """The `council` field of the attempt a council record names: it exists on a council attempt only (RDD-B9)."""
244
+ if not unit or r.get("attempt") is None:
245
+ return None
246
+ att = self._attempt(unit, r.get("attempt"), None, r.get("ts"))
247
+ return att.setdefault("council", {"members": [], "rounds": [], "tally": None, "outcome": None})
248
+
249
+ def _on_council_round(self, r: Mapping[str, Any], unit: str | None) -> None:
250
+ c = self._council(r, unit)
251
+ if c is None:
252
+ return
253
+ c["members"] = [str(m) for m in r.get("labels") or c["members"]]
254
+ c["rounds"] = [x for x in c["rounds"] if x["round"] != r.get("round")] + [
255
+ {k: r.get(k) for k in ("round", "answered", "spoiled", "missing", "changed")}]
256
+
257
+ def _on_council_tally(self, r: Mapping[str, Any], unit: str | None) -> None:
258
+ c = self._council(r, unit)
259
+ if c is None:
260
+ return
261
+ c["tally"] = {k: r.get(k) for k in ("mode", "rule", "counts", "chosen_by")}
262
+ c["outcome"] = r.get("outcome")
263
+
264
+ def _on_script(self, r: Mapping[str, Any], unit: str | None) -> None:
265
+ if not unit:
266
+ return
267
+ if r.get("phase") in (None, "unit"):
268
+ visit = self._visit(unit)
269
+ att = self._attempt(unit, len(visit["attempts"]) + 1, r.get("item"), r.get("ts"))
270
+ att["ended_at"] = r.get("ts")
271
+ else:
272
+ att = self._open(unit) or self._attempt(unit, 1, r.get("item"), r.get("ts"))
273
+ att.setdefault("scripts", []).append({k: r.get(k) for k in (
274
+ "name", "phase", "exit_code", "duration_s", "cached", "environmental")})
275
+
276
+ def _on_contest(self, r: Mapping[str, Any], unit: str | None) -> None:
277
+ """EVT-B15, RDD-B19, RDD-B20: a pick. Each slot it names gets its verdict and keys, and `winner` true on the slot the
278
+ pick kept and false on the others, null when it kept none; a slot the cost cap kept from starting is an entry of its
279
+ own with `skipped` true. The pick's entries are one round, the order the slots are declared in."""
280
+ if not unit or not self._contest(unit):
281
+ return
282
+ self._round[unit] = self._round.get(unit, 0) + 1
283
+ place = r.get("winner") if isinstance(r.get("winner"), int) else None
284
+ visit = self._visit(unit)
285
+ entries: list[dict[str, Any]] = []
286
+ for row in r.get("slots") or []:
287
+ if not isinstance(row, Mapping):
288
+ continue
289
+ name = row.get("name")
290
+ if row.get("skipped"):
291
+ entry = self._entry(unit, None, name, r.get("ts"))
292
+ entry["skipped"] = True
293
+ visit["attempts"].append(entry)
294
+ else:
295
+ entry = self._attempt(unit, row.get("attempt"), name, r.get("ts"))
296
+ entry["verdict"] = row.get("verdict")
297
+ entry["keys"] = dict(row["keys"]) if isinstance(row.get("keys"), Mapping) else None
298
+ entry["winner"] = None if place is None else row.get("slot") == place
299
+ entry["_round"] = self._round[unit]
300
+ entries.append(entry)
301
+ kept = next((e for e in entries if e["winner"]), None) or (entries[0] if entries else None)
302
+ if kept is not None:
303
+ self.current[unit] = kept # the unit's own gate record, which names no item, lands on the winner's entry
304
+
305
+ def _on_check(self, r: Mapping[str, Any], unit: str | None) -> None:
306
+ att = self._open(unit, r.get("item"), r.get("attempt")) if unit else None
307
+ if att is not None:
308
+ att["check"] = {"result": r.get("result"), "environmental": r.get("environmental"),
309
+ "duration_s": r.get("duration_s"), "output_path": r.get("output_path"),
310
+ "evidence": _text(r.get("evidence"), EVIDENCE_CLIP)}
311
+
312
+ def _on_judgement(self, r: Mapping[str, Any], unit: str | None) -> None:
313
+ att = self._open(unit, r.get("item"), r.get("attempt")) if unit else None
314
+ if att is None:
315
+ return
316
+ statuses = [{"n": s.get("n"), "id": s.get("id"), "status": s.get("status")}
317
+ for s in r.get("statuses") or [] if isinstance(s, Mapping)]
318
+ met = r.get("met") if isinstance(r.get("met"), int) else sum(1 for s in statuses if s["status"] == "MET")
319
+ total = r.get("total") if isinstance(r.get("total"), int) else len(statuses)
320
+ att["judge"] = att["judge"] or {"sessions": []}
321
+ att["judge"].update(criteria=statuses, met=met, total=total, gap=r.get("gap"),
322
+ blockers=[{"id": b, "evidence": None, "fix": None} for b in r.get("blockers") or []],
323
+ confidence=r.get("confidence"), confidence_source=r.get("confidence_source"),
324
+ guard=r.get("guard"))
325
+
326
+ def _on_gate(self, r: Mapping[str, Any], unit: str | None) -> None:
327
+ att = self._open(unit, r.get("item")) if unit else None
328
+ if att is None:
329
+ return
330
+ verdict = r.get("verdict") or r.get("token")
331
+ target = route_unit(r.get("route_target"))
332
+ att["gate"] = {"verdict": verdict, "route_target": target, "token": r.get("token"),
333
+ "guard": (att.get("judge") or {}).get("guard")}
334
+ att["ended_at"] = r.get("ts")
335
+ if verdict == "RETRY":
336
+ blockers = (att.get("judge") or {}).get("blockers") or []
337
+ chk = att.get("check") or {}
338
+ if blockers:
339
+ att["repeat_cause"] = f"blocker:{blockers[0]['id']}"
340
+ elif chk.get("result") == "FAIL":
341
+ att["repeat_cause"] = "check:FAIL"
342
+ else:
343
+ att["repeat_cause"] = "retry"
344
+
345
+ def _on_pause(self, r: Mapping[str, Any], unit: str | None) -> None:
346
+ self.pause = dict(r)
347
+
348
+ def _on_human(self, r: Mapping[str, Any], unit: str | None) -> None:
349
+ raw = r.get("caller")
350
+ caller: Mapping[str, Any] = raw if isinstance(raw, Mapping) else {}
351
+ waited = _secs((self.pause or {}).get("ts"), r.get("ts")) if self.pause else None
352
+ self.touches.append({"ts": r.get("ts"), "unit": unit, "class": r.get("touch_class") or (
353
+ (self.pause or {}).get("pause_kind")), "action": r.get("decision"), "caller_kind": caller.get("kind"),
354
+ "decider": r.get("decider") or caller.get("decider"), "relay": caller.get("relay"),
355
+ "wait_s": waited, "feedback": bool(r.get("feedback"))})
356
+ self.pause = None
357
+
358
+ def _on_budget(self, r: Mapping[str, Any], unit: str | None) -> None:
359
+ name = f"{unit}.{r.get('counter')}" if unit else str(r.get("counter"))
360
+ self.budgets[name] = {"used": r.get("used"), "limit": r.get("limit"), "cause": r.get("cause")}
361
+
362
+ def _on_supervision(self, r: Mapping[str, Any], unit: str | None) -> None:
363
+ self.supervision = dict(r)
364
+
365
+
366
+ # -- live sessions ---------------------------------------------------------------------------------------
367
+
368
+
369
+ def _read_live(path: Path, now: datetime) -> dict[str, Any] | None:
370
+ """The live block of RDD-B12; a file mid-replace is never read partially (writes are atomic)."""
371
+ try:
372
+ data = json.loads(path.read_text(encoding="utf-8"))
373
+ except (OSError, ValueError):
374
+ return None
375
+ if not isinstance(data, dict) or data.get("ended"):
376
+ return None
377
+ tool = data.get("open_tool") if isinstance(data.get("open_tool"), dict) else None
378
+ open_tool = None
379
+ if tool is not None:
380
+ open_tool = {"name": tool.get("name"), "capability": tool.get("capability"),
381
+ "input_summary": _text(tool.get("input_summary")),
382
+ "elapsed": _elapsed(tool.get("started_at"), now)}
383
+ recent = [{"name": c.get("name"), "input_summary": _text(c.get("input_summary")), "ok": c.get("ok"),
384
+ "duration_s": c.get("duration_s")} for c in (data.get("recent") or [])[-10:] if isinstance(c, dict)]
385
+ return {"open_tool": open_tool, "recent": recent, "last_text": _text(data.get("last_text")),
386
+ "tokens_so_far": data.get("tokens_so_far"), "turns_so_far": data.get("turns_so_far"),
387
+ "pgid": data.get("pgid"), "last_event_age_s": _elapsed(data.get("last_event_at"), now)}
388
+
389
+
390
+ def _elapsed(ts: Any, now: datetime) -> float | None:
391
+ t = _ts(ts)
392
+ return None if t is None else round(max(0.0, (now - t).total_seconds()), 1)
393
+
394
+
395
+ # -- the document ------------------------------------------------------------------------------------------
396
+
397
+
398
+ def _usage_cost(usage: Any) -> tuple[float | None, float | None]:
399
+ if not isinstance(usage, Mapping):
400
+ return None, None
401
+ rep, est = usage.get("reported_cost_usd"), usage.get("estimated_cost_usd")
402
+ return (float(rep) if isinstance(rep, int | float) else None, float(est) if isinstance(est, int | float) else None)
403
+
404
+
405
+ def _unit_cost(sessions: list[dict[str, Any]]) -> dict[str, Any]:
406
+ rep = est = 0.0
407
+ n_rep = n_est = unmeasured = 0
408
+ for s in sessions:
409
+ r, e = _usage_cost(s.get("usage"))
410
+ if r is not None:
411
+ rep, n_rep = rep + r, n_rep + 1
412
+ if e is not None:
413
+ est, n_est = est + e, n_est + 1
414
+ if r is None and e is None and s.get("usage") is not None:
415
+ unmeasured += 1
416
+ figure = rep + sum(e for s in sessions for r, e in [_usage_cost(s.get("usage"))] if r is None and e is not None)
417
+ flag = "incomplete" if unmeasured else ("complete" if sessions and n_rep == len(sessions) else "estimated")
418
+ return {"reported": round(rep, 6) if n_rep else None, "estimated": round(est, 6) if n_est else None,
419
+ "figure": round(figure, 6), "completeness": flag if sessions else None}
420
+
421
+
422
+ def _sessions_of(unit: dict[str, Any]) -> list[dict[str, Any]]:
423
+ out: list[dict[str, Any]] = []
424
+ for v in unit["visits"]:
425
+ for a in v["attempts"]:
426
+ for part in ("step", "judge"):
427
+ out.extend((a.get(part) or {}).get("sessions") or [])
428
+ return out
429
+
430
+
431
+ def _state(name: str, unit: dict[str, Any] | None, row: Mapping[str, Any], current: str | None,
432
+ contest: bool = False) -> str:
433
+ if name in {g.get("unit") for g in row.get("pending_gates") or []}:
434
+ return "paused"
435
+ attempts = [a for v in reversed((unit or {}).get("visits") or []) for a in reversed(v["attempts"])]
436
+ last = next((a for a in attempts if a.get("gate")), None) if contest else None # the unit's gate record, on one entry
437
+ last = last or next(iter(attempts), None)
438
+ if last is None:
439
+ return "skipped" if row.get("state") == "finished" else "not_reached"
440
+ verdict = (last.get("gate") or {}).get("verdict")
441
+ live_here = bool(row.get("alive")) and name == current
442
+ if live_here and verdict in (None, "RETRY"):
443
+ return "running"
444
+ if verdict == "PROCEED":
445
+ return "passed"
446
+ if verdict is None and last.get("scripts") and all(sc.get("exit_code") == 0 for sc in last["scripts"]):
447
+ return "passed"
448
+ return "running" if live_here else "failed"
449
+
450
+
451
+ def _public_session(s: dict[str, Any], root: Path, workflow: str, task: str, live: dict[str, Any] | None
452
+ ) -> dict[str, Any]:
453
+ sdir = session_dir(root, workflow, task, s["session_key"])
454
+ out = {k: s.get(k) for k in ("session_key", "kind", "executor", "alias", "model", "session_id", "transcript",
455
+ "usage", "tool_calls", "outcome", "started_at", "ended_at")}
456
+ out["activity_path"] = str(sdir / "activity.jsonl")
457
+ out["live_path"] = str(sdir / "live.json")
458
+ if s.get("infra_tries"):
459
+ out["infra_tries"] = s["infra_tries"]
460
+ if live is not None:
461
+ out["live"] = live
462
+ return out
463
+
464
+
465
+ def _snapshot(root: Path, spec: WorkflowSpec, tid: str) -> Snapshot:
466
+ with open_readonly(engine_file.checkpoint_of(root, spec.name, tid.partition("/")[2])) as saver:
467
+ if saver is None:
468
+ return Snapshot(exists=False)
469
+ return snapshot(observer_graph(spec, saver), tid)
470
+
471
+
472
+ def detail(root: Path, spec: WorkflowSpec, tid: str, *, unit: str | None = None, with_live: bool = True,
473
+ now: datetime | None = None) -> dict[str, Any] | None:
474
+ """`status --detail <selector> --json` (RDD-B7 to RDD-B15). None when `unit` names no unit of the workflow."""
475
+ now = now or datetime.now(UTC)
476
+ _, task = split_thread(tid)
477
+ model = diagram_model(spec)
478
+ if unit is not None and unit not in {u["name"] for u in model["units"]}:
479
+ return None
480
+ row = status_row(root, spec, tid)
481
+ snap = _snapshot(root, spec, tid)
482
+ values = snap.values or {}
483
+ log = run_dir(root, spec.name, task) / "run.jsonl"
484
+ truncated: list[str] = []
485
+ try:
486
+ recs = records(log) if log.exists() else None
487
+ except Exception: # noqa: BLE001 - RDD-B16, RDD-B8, RDD-B12
488
+ recs = None
489
+ if recs is None:
490
+ truncated.append("run_log_unreadable")
491
+ recs = []
492
+ fold = _Fold(spec.units)
493
+ for r in recs:
494
+ fold.feed(r)
495
+
496
+ current = fold.last_unit
497
+ alive = bool(row.get("alive"))
498
+ open_keys = {k for k, s in fold.sessions.items() if s.get("ended_at") is None}
499
+ units_out = []
500
+ total_figure = 0.0
501
+ per_unit: list[tuple[dict[str, Any], dict[str, Any]]] = []
502
+ judgements = values.get("judgements") or {}
503
+ for p in model["units"]:
504
+ name = p["name"]
505
+ u = fold.units.get(name, {"visits": []})
506
+ _add_evidence(u, judgements.get(name) or {}, run_dir(root, spec.name, task) / "evidence" / "judgements" / name)
507
+ sessions = _sessions_of(u)
508
+ cost = _unit_cost(sessions)
509
+ total_figure += cost["figure"]
510
+ durations = [d for v in u["visits"] for a in v["attempts"]
511
+ for d in [_secs(a.get("started_at"), a.get("ended_at"))] if d is not None]
512
+ visits = []
513
+ contest = fold._contest(name)
514
+ slots = flow.slot_names(spec, name) if contest else ()
515
+ for v in u["visits"]:
516
+ attempts = []
517
+ held = v["attempts"]
518
+ if contest: # RDD-B19: each pick's slots in the order they are declared; slots whose pick has not run, last
519
+ held = sorted(held, key=lambda a: (a.get("_round") or 10**9,
520
+ slots.index(a["item"]) if a.get("item") in slots else len(slots)))
521
+ for a in held:
522
+ out = {k: x for k, x in a.items() if k != "_round"}
523
+ if contest:
524
+ out["cost"] = _unit_cost([s for part in ("step", "judge") for s in (a.get(part) or {}).get("sessions") or []])
525
+ for part in ("step", "judge"):
526
+ if out.get(part):
527
+ out[part] = {**out[part], "sessions": [
528
+ _public_session(s, root, spec.name, task,
529
+ _read_live(session_dir(root, spec.name, task, s["session_key"]) /
530
+ "live.json", now)
531
+ if with_live and alive and s["session_key"] in open_keys else None)
532
+ for s in out[part].get("sessions") or []]}
533
+ attempts.append(out)
534
+ visits.append({**v, "attempts": attempts})
535
+ entry = {"name": name, "state": _state(name, u, row, current, contest), "visits": visits, "cost": cost,
536
+ "duration_s": round(sum(durations), 3) if durations else None, "share": None}
537
+ per_unit.append((entry, cost))
538
+ units_out.append(entry)
539
+ for entry, cost in per_unit:
540
+ entry["share"] = round(cost["figure"] / total_figure, 4) if total_figure > 0 else None
541
+
542
+ doc: dict[str, Any] = {
543
+ "schema_version": SCHEMA["detail"], "generated_at": now_iso(),
544
+ "run": {**row, "segment": (fold.segment_start or {}).get("segment"),
545
+ "last_seq": recs[-1]["seq"] if recs else None, "run_dir": str(run_dir(root, spec.name, task)),
546
+ "plan_digest": model["digest"]},
547
+ "plan": _plan(spec, model),
548
+ "plan_stale": bool(fold.plan_digest and fold.plan_digest != model["digest"]),
549
+ "units": units_out,
550
+ "pause": _pause(spec, row, snap, fold.pause, now),
551
+ "budgets": _budgets(spec, values, fold.budgets, total_figure),
552
+ "health": _health(row, recs, fold, units_out, spec, now, root, task),
553
+ "supervision": {"touches": fold.touches, "record": fold.supervision,
554
+ "hosts": (fold.supervision or {}).get("hosts")
555
+ or ((fold.supervision or {}).get("supervisors") or {}).get("hosts"),
556
+ "level": (fold.supervision or {}).get("level"),
557
+ "level_by": (fold.supervision or {}).get("level_by"),
558
+ "designed_by": (fold.supervision or {}).get("designed_by"),
559
+ "cost": _closed_cost(root, f"{spec.name}/{task}")
560
+ or (fold.supervision or {}).get("supervision_cost", (fold.supervision or {}).get("cost"))},
561
+ "loop": loop_summary.thread_newest(root, spec.name, task), # RDD-B7: null until a loop child has ended
562
+ "events_tail": tail(recs),
563
+ "truncated": truncated,
564
+ }
565
+ if unit is not None:
566
+ doc["units"] = [u for u in units_out if u["name"] == unit]
567
+ doc["plan"] = [p for p in doc["plan"] if p["name"] == unit]
568
+ return doc
569
+ return cut(doc)
570
+
571
+
572
+ def _add_evidence(unit: dict[str, Any], judged: Mapping[str, Any], folder: Path | None = None) -> None:
573
+ """Evidence and fix lines per judged attempt from `evidence/judgements/<unit>/<visit>.<attempt>.json`;
574
+ the unit's last judged attempt falls back to the checkpoint's local judgement (RDD-B7 to RDD-B11, RDD-B13, RDD-B15)."""
575
+ last = next((a for v in reversed(unit["visits"]) for a in reversed(v["attempts"]) if a.get("judge")), None)
576
+ for v in unit["visits"]:
577
+ for a in v["attempts"]:
578
+ if not (a.get("judge") or {}).get("blockers"):
579
+ continue
580
+ kept: dict[str, Any] = {}
581
+ if folder is not None:
582
+ try:
583
+ doc = json.loads((folder / f"{v['visit']}.{a['attempt']}.json").read_text(encoding="utf-8"))
584
+ kept = {str(b.get("criterion")): b for b in doc.get("blockers") or [] if isinstance(b, Mapping)}
585
+ except (OSError, ValueError, AttributeError, KeyError):
586
+ kept = {}
587
+ if not kept and a is last:
588
+ kept = {str(b.get("criterion")): b for b in judged.get("blockers") or [] if isinstance(b, Mapping)}
589
+ for b in a["judge"]["blockers"]:
590
+ src = kept.get(str(b["id"]))
591
+ if src is not None:
592
+ b["evidence"] = _text(src.get("evidence") or src.get("problem"), EVIDENCE_CLIP)
593
+ b["fix"] = _text(src.get("fix"), EVIDENCE_CLIP)
594
+
595
+
596
+ def _artifact_path(spec: WorkflowSpec, values: Mapping[str, Any], unit: Any, key: str) -> str | None:
597
+ """The local path of a file artifact, resolved against the run's workspace; None for a value."""
598
+ us = spec.units.get(str(unit))
599
+ if us is None or us.step is None or us.step.produces.get(key) != "file":
600
+ return None
601
+ v = ((values.get("artifacts") or {}).get(unit) or {}).get(key)
602
+ path = v.get("path") if isinstance(v, Mapping) else v
603
+ if not isinstance(path, str) or not path:
604
+ return None
605
+ ws = (values.get("workspace") or {}).get("path")
606
+ p = Path(path)
607
+ return str(p if p.is_absolute() or not ws else Path(ws) / p)
608
+
609
+
610
+ def _pause(spec: WorkflowSpec, row: Mapping[str, Any], snap: Snapshot, rec: Mapping[str, Any] | None, now: datetime
611
+ ) -> dict[str, Any] | None:
612
+ """RDD-B22 to RDD-B24: the whole block comes from the first source that holds the pause (the pending payload,
613
+ the checkpoint's pause entry, the last `pause` record, the status row's pending gate), never merged."""
614
+ from tempergraph.run.gate import _finding_line
615
+
616
+ if row.get("state") != "paused":
617
+ return None
618
+ gate = (row.get("pending_gates") or [{}])[0]
619
+ values = snap.values or {}
620
+ p: Mapping[str, Any] | None = None
621
+ unit: Any = None
622
+ payload_source = True
623
+ if snap.interrupts:
624
+ node, payload = snap.interrupts[0]
625
+ p = payload if isinstance(payload, Mapping) else {}
626
+ unit = p.get("unit") or _unit_of(node)
627
+ else:
628
+ held = values.get("pause") or {}
629
+ entry = held.get(gate.get("unit")) if gate.get("unit") else next((v for v in held.values() if v), None)
630
+ if isinstance(entry, Mapping) and entry:
631
+ p = entry
632
+ unit = p.get("unit") or gate.get("unit")
633
+ if p is None and rec:
634
+ payload_source = False
635
+ p = {"kind": rec.get("pause_kind"), "unit": rec.get("unit"), "item": rec.get("item"),
636
+ "reason": rec.get("reason"), "decisions": rec.get("decisions"), "resume": rec.get("resume"),
637
+ **{k: rec[k] for k in ("tool_access", "guard", "escalation", "command_killed") if rec.get(k)},
638
+ **({"usage_limit_resets_at": rec["usage_limit_resets_at"]} if "usage_limit_resets_at" in rec else {})}
639
+ unit = p["unit"] or gate.get("unit")
640
+ if p is None:
641
+ payload_source = False
642
+ p = {"kind": gate.get("kind"), "item": gate.get("item"), "resume": gate.get("resume")}
643
+ unit = gate.get("unit")
644
+ since = (rec or {}).get("ts")
645
+ resume = p.get("resume") or gate.get("resume")
646
+ blockers = [{k: scrub(v) if isinstance(v, str) else v for k, v in dict(b).items()}
647
+ for b in p.get("blockers") or [] if isinstance(b, Mapping)] # scrubbed, not clipped (RDD-B15)
648
+ block: dict[str, Any] = {
649
+ "unit": unit, "kind": p.get("kind") or (rec or {}).get("pause_kind"), "item": p.get("item"),
650
+ "reason": _text(p.get("reason")),
651
+ "question": _text(p.get("question") or p.get("reason")) if payload_source else None,
652
+ "artifacts": [{"key": k, "path": _artifact_path(spec, values, unit, k)} for k in p.get("artifacts") or []],
653
+ "blockers": blockers, "blockers_left_out": int(p.get("blockers_left_out") or 0),
654
+ "decisions": list(p.get("decisions") or []), "resume": [resume] if resume else [],
655
+ "waiting_since": since, "waiting_s": _elapsed(since, now)}
656
+ for key in ("tool_access", "guard", "repeated", "escalation", "winner", "questions", "command_killed"):
657
+ if key in p:
658
+ block[key] = p[key]
659
+ if "usage_limit_resets_at" in p: # RDD-B21
660
+ block["usage_limit_resets_at"] = p["usage_limit_resets_at"]
661
+ lines = [f"{n}. {' '.join(scrub(_finding_line(b)).split())}" for n, b in enumerate(blockers[:20], 1)] # one line each
662
+ g = p.get("guard")
663
+ if isinstance(g, Mapping) and g:
664
+ lines.append("guard: " + " ".join(f"{k}={g[k]}" for k in ("reason", "tool", "subagent", "prefix")
665
+ if g.get(k) is not None))
666
+ for t in p.get("tool_access") or []:
667
+ if isinstance(t, Mapping):
668
+ more = "".join(f", {k} {t[k]}" for k in ("path_class", "prefix") if t.get(k))
669
+ lines.append(f"refused: {t.get('name')} ({t.get('class')}{more})")
670
+ for c in p.get("command_killed") or []: # KIL-B8: one line for each killed command
671
+ if isinstance(c, Mapping):
672
+ last = c.get("last_finished_s")
673
+ lines.append(" ".join(scrub(str(x)) for x in (
674
+ f"killed: {c.get('prefix')}", f"in {c['cwd']}," if c.get("cwd") else "",
675
+ "at base," if c.get("at_base") else "", f"limit {c.get('limit_s')} s,", f"ran {c.get('elapsed_s')} s,",
676
+ f"last finished {last} s" if last is not None else "last finished none recorded") if x))
677
+ block["lines"] = lines
678
+ return block
679
+
680
+
681
+ def _budgets(spec: WorkflowSpec, values: Mapping[str, Any], recorded: Mapping[str, Any], spent: float
682
+ ) -> dict[str, Any]:
683
+ counters = values.get("counters") or {}
684
+ out: dict[str, Any] = {}
685
+ for name, u in spec.units.items():
686
+ c = counters.get(name) or {}
687
+ if "retries" in c:
688
+ out[f"{name}.retries"] = {"used": c.get("retries"), "limit": u.gate.retry_budget}
689
+ for target, used in (c.get("loops") or {}).items():
690
+ out[f"{name}.loops.{target}"] = {"used": used, "limit": u.gate.loop_budget}
691
+ out.update({k: dict(v) for k, v in recorded.items()})
692
+ cap = spec.run_cost_cap_usd
693
+ return {"counters": out, "run_cost_cap": {"limit": cap, "left": round(cap - spent, 6) if cap is not None else None}}
694
+
695
+
696
+ def _health(row: Mapping[str, Any], recs: list[dict[str, Any]], fold: _Fold, units: list[dict[str, Any]],
697
+ spec: WorkflowSpec, now: datetime, root: Path, task: str) -> dict[str, Any]:
698
+ alive = bool(row.get("alive"))
699
+ newest = recs[-1].get("ts") if recs else None
700
+ silent = _elapsed(newest, now)
701
+ stall = False
702
+ for u in units:
703
+ for v in u["visits"]:
704
+ for a in v["attempts"]:
705
+ for part in ("step", "judge"):
706
+ for s in (a.get(part) or {}).get("sessions") or []:
707
+ live = s.get("live")
708
+ if live is None:
709
+ continue
710
+ age = live.get("last_event_age_s")
711
+ silent = min(silent, age) if silent is not None and age is not None else silent
712
+ limit = _idle_limit(spec, u["name"], fold.sessions.get(s["session_key"]) or {})
713
+ if age is not None and limit and age >= 0.8 * limit:
714
+ stall = True
715
+ started = fold.segment_start
716
+ orphaned = bool(started and fold.segment_exit is None and not alive)
717
+ cost_seg = sum(c for c in (_segment_cost(recs, (started or {}).get("seq")),) if c is not None)
718
+ wall = _secs((started or {}).get("ts"), (fold.segment_exit or {}).get("ts") or now)
719
+ burn = round(cost_seg / wall * 3600, 4) if wall and wall > 0 and started else None
720
+ cap = spec.run_cost_cap_usd
721
+ spent = sum((u["cost"] or {}).get("figure") or 0.0 for u in units)
722
+ eta = round((cap - spent) / burn * 60, 1) if cap is not None and burn and alive else None
723
+ waiting = _elapsed((fold.pause or {}).get("ts"), now) if row.get("state") == "paused" and fold.pause else None
724
+ return {"alive": alive, "silent_s": silent, "suspect_stall": alive and stall, "orphaned": orphaned,
725
+ "waiting_for_person_s": waiting, "burn_usd_per_h": burn, "cap_eta_min": eta}
726
+
727
+
728
+ def _idle_limit(spec: WorkflowSpec, unit: str, s: Mapping[str, Any]) -> float | None:
729
+ if isinstance(s.get("idle_s"), int | float):
730
+ return float(s["idle_s"])
731
+ us = spec.units.get(unit)
732
+ if us is not None and us.step is not None and us.step.idle_s:
733
+ return float(us.step.idle_s)
734
+ return None
735
+
736
+
737
+ def _segment_cost(recs: list[dict[str, Any]], since: Any) -> float | None:
738
+ if not isinstance(since, int):
739
+ return None
740
+ total = 0.0
741
+ for r in recs:
742
+ if r.get("kind") == "agent_run" and isinstance(r.get("seq"), int) and r["seq"] > since:
743
+ rep, est = _usage_cost(r.get("usage"))
744
+ total += rep if rep is not None else (est or 0.0)
745
+ return total
746
+
747
+
748
+ def cut(doc: dict[str, Any], limit: int = MAX_BYTES) -> dict[str, Any]:
749
+ """RDD-B7 to RDD-B11, RDD-B13, RDD-B15: above `limit` bytes drop `events_tail`, then the attempt detail of passed units."""
750
+ def size() -> int:
751
+ return len(json.dumps(doc, ensure_ascii=False, default=str).encode("utf-8"))
752
+
753
+ if size() <= limit:
754
+ return doc
755
+ doc["events_tail"] = []
756
+ doc["truncated"] = [*doc.get("truncated", []), "events_tail"]
757
+ if size() <= limit:
758
+ return doc
759
+ for u in doc["units"]:
760
+ if u["state"] == "passed":
761
+ for v in u["visits"]:
762
+ v["attempts_count"] = len(v["attempts"])
763
+ v["attempts"] = []
764
+ doc["truncated"].append("passed_attempts")
765
+ return doc
766
+
767
+
768
+ def _closed_cost(root: Path, tid: str) -> dict[str, Any] | None:
769
+ """SCO-B15's closed figures for the thread, when its supervision has closed; else the record's null."""
770
+ from tempergraph.observe.supervision_cost import closed_for
771
+
772
+ line = closed_for(root).get(tid)
773
+ return {k: line.get(k) for k in ("marginal", "turn", "completeness", "observations")} if line else None