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,444 @@
1
+ """The machine index (CST-B8), the per-user stats rows (OBS-B15, CST-B9 `run`) and their readers.
2
+
3
+ Rows are written from the run log at each `run_exit`, by :func:`on_run_exit`, which the run log's writer calls
4
+ after the record is on disk; the index is touched at `run_started` by :func:`on_run_started`. Both are best
5
+ effort and never change a run (OVR-B4). `stats` and `attention` only read (OVR-B15).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import json
12
+ import os
13
+ import statistics
14
+ import time
15
+ import uuid
16
+ from collections import defaultdict
17
+ from collections.abc import Iterable, Iterator
18
+ from datetime import UTC, datetime
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from tempergraph.docs import append_jsonl, write_json
23
+ from tempergraph.store.layout import ensure_home, home_path, now_iso
24
+
25
+ INDEX_LOCK_S = 2.0
26
+ TOKENS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "thinking_tokens")
27
+ BY = ("machine", "user", "repo", "workflow", "version", "executor", "model", "ticket", "exit", "month", "parent",
28
+ "schedule", "level", "decider", "host")
29
+
30
+
31
+ def _parts(log: Path) -> tuple[Path, str, str]:
32
+ """`<state root>/runs/<workflow>/<task>/run.jsonl` → (state root, workflow, task)."""
33
+ return log.parents[3], log.parent.parent.name, log.parent.name
34
+
35
+
36
+ # -- machine index ---------------------------------------------------------------------------------------------
37
+
38
+
39
+ @contextlib.contextmanager
40
+ def _locked(path: Path, wait_s: float = INDEX_LOCK_S) -> Iterator[bool]:
41
+ lock = path.with_suffix(".lock")
42
+ deadline = time.monotonic() + wait_s
43
+ fd = None
44
+ while fd is None:
45
+ try:
46
+ fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
47
+ except FileExistsError:
48
+ with contextlib.suppress(OSError):
49
+ if time.time() - lock.stat().st_mtime > 30: # a holder that died long ago
50
+ lock.unlink()
51
+ continue
52
+ if time.monotonic() >= deadline:
53
+ yield False
54
+ return
55
+ time.sleep(0.05)
56
+ try:
57
+ yield True
58
+ finally:
59
+ os.close(fd)
60
+ with contextlib.suppress(OSError):
61
+ lock.unlink()
62
+
63
+
64
+ def read_index(home: Path | None = None) -> list[dict[str, Any]]:
65
+ path = (home or home_path()) / "index.json"
66
+ try:
67
+ doc = json.loads(path.read_text(encoding="utf-8"))
68
+ except (OSError, ValueError):
69
+ return []
70
+ roots = doc.get("roots") if isinstance(doc, dict) else None
71
+ return [r for r in roots if isinstance(r, dict) and r.get("path")] if isinstance(roots, list) else []
72
+
73
+
74
+ def touch_index(state_root: Path, home: Path | None = None, now: str | None = None) -> bool:
75
+ """Adds or refreshes this state root in `~/.tempergraph/index.json` under a lock (CST-B8, LOS-B6)."""
76
+ home = ensure_home(home)
77
+ path = home / "index.json"
78
+ stamp = now or now_iso()
79
+ with _locked(path) as got:
80
+ if not got:
81
+ return False
82
+ roots = read_index(home)
83
+ key = str(state_root.resolve())
84
+ for r in roots:
85
+ if r["path"] == key:
86
+ r["last_run_at"] = stamp
87
+ break
88
+ else:
89
+ roots.append({"path": key, "repository": state_root.resolve().parent.name, "first_seen": stamp,
90
+ "last_run_at": stamp})
91
+ write_json(path, {"schema_version": 1, "roots": roots})
92
+ return True
93
+
94
+
95
+ def index_roots(home: Path | None = None) -> list[dict[str, Any]]:
96
+ """Every indexed state root with `missing` when its folder is gone; the index is never changed by a reader."""
97
+ return [{**r, "missing": not Path(r["path"]).is_dir()} for r in read_index(home)]
98
+
99
+
100
+ # -- stats rows ------------------------------------------------------------------------------------------------
101
+
102
+
103
+ def _machine(home: Path) -> dict[str, Any]:
104
+ try:
105
+ return dict(json.loads((home / "machine.json").read_text(encoding="utf-8")))
106
+ except (OSError, ValueError):
107
+ return {}
108
+
109
+
110
+ def _git_user(state_root: Path) -> str | None:
111
+ from tempergraph import git
112
+
113
+ try:
114
+ name = git.git(["config", "user.name"], state_root.parent, check=False).strip()
115
+ except Exception: # noqa: BLE001
116
+ return None
117
+ return name or None
118
+
119
+
120
+ def _ts(text: Any) -> float | None:
121
+ try:
122
+ return datetime.fromisoformat(str(text).replace("Z", "+00:00")).timestamp()
123
+ except ValueError:
124
+ return None
125
+
126
+
127
+ def _schedule_id(block: Any) -> str | None:
128
+ """The schedule a run belongs to: from the `schedule` block of `run_started` (TCK-B24), or a bare id."""
129
+ if isinstance(block, dict):
130
+ return str(block["schedule_id"]) if block.get("schedule_id") else None
131
+ return str(block) if block else None
132
+
133
+
134
+ def schedule_report(home: Path | None = None) -> dict[str, Any]:
135
+ """`report --by schedule` (TCK-B24): per schedule its fires, outcomes, cost, skipped and missed counts, read from the
136
+ fire logs (`ended` rows carry each run's cost), and the totals of those figures. Read-only."""
137
+ from tempergraph.schedule import store
138
+
139
+ groups: dict[str, dict[str, Any]] = {}
140
+ for entry in store.list_entries(home):
141
+ sid = str(entry["schedule_id"])
142
+ log = store.read_log(sid, home)
143
+ ended = {str(e["fire_id"]): e for e in log if e.get("kind") == "ended"}
144
+ started = [e for e in log if e.get("kind") == "started"]
145
+ cost = [float((ended[str(e["fire_id"])].get("cost") or {}).get("estimated") or 0.0)
146
+ for e in started if str(e.get("fire_id")) in ended]
147
+ groups[sid] = {"fires": len(started), "ended": len(ended),
148
+ "outcomes": dict(sorted(_count(str(e.get("outcome")) for e in ended.values()).items())),
149
+ "exits": dict(sorted(_count(str(e.get("exit")) for e in ended.values()).items())),
150
+ "estimated_usd": round(sum(cost), 6),
151
+ "incomplete": any((e.get("cost") or {}).get("incomplete") for e in ended.values()),
152
+ "skipped": sum(1 for e in log if e.get("kind") == "skipped"),
153
+ "missed": sum(1 for e in log if e.get("kind") == "missed"),
154
+ "refused": sum(1 for e in log if e.get("kind") == "refused")}
155
+ keys = ("fires", "ended", "estimated_usd", "skipped", "missed", "refused")
156
+ total = {k: round(sum(g[k] for g in groups.values()), 6) for k in keys}
157
+ total["incomplete"] = any(g["incomplete"] for g in groups.values())
158
+ return {"schema_version": 1, "by": "schedule", "groups": groups, "totals": total}
159
+
160
+
161
+ def run_row(log: Path, recs: Iterable[dict[str, Any]], segment: int | None = None) -> dict[str, Any] | None:
162
+ """The `run` row of one segment of a thread, from its run log (CST-B9, OBS-B15); numbers and names only."""
163
+ root, workflow, task = _parts(log)
164
+ started: dict[str, Any] | None = None
165
+ exit_: dict[str, Any] | None = None
166
+ executors: set[str] = set()
167
+ models: set[str] = set()
168
+ units: set[str] = set()
169
+ repeats: dict[str, int] = defaultdict(int)
170
+ verdicts: dict[str, int] = defaultdict(int)
171
+ tokens: dict[str, int | None] = dict.fromkeys(TOKENS)
172
+ rep = est = 0.0
173
+ n = n_rep = n_est = unmeasured = 0
174
+ agent_s = 0.0
175
+ wait_s = 0.0
176
+ attempts: dict[str, int] = defaultdict(int)
177
+ sup: dict[str, Any] | None = None
178
+ for r in recs:
179
+ if segment is not None and r.get("segment") != segment:
180
+ continue
181
+ kind = r.get("kind")
182
+ if kind == "run_started":
183
+ started = r
184
+ elif kind == "run_exit":
185
+ exit_ = r
186
+ elif kind == "unit_entered" and r.get("unit"):
187
+ units.add(str(r["unit"]))
188
+ if int(r.get("visit") or 1) > 1:
189
+ repeats[str(r.get("entered_from") or "revisit").split(":", 1)[0]] += 1
190
+ elif kind == "attempt_start" and r.get("session_kind") in ("step", "retry") and r.get("unit"):
191
+ attempts[str(r["unit"])] += 1
192
+ if r.get("session_kind") == "retry":
193
+ repeats["retry"] += 1
194
+ elif kind == "agent_run":
195
+ n += 1
196
+ if r.get("executor"):
197
+ executors.add(str(r["executor"]))
198
+ u = r.get("usage") or {}
199
+ for m in (u.get("by_model") or {}):
200
+ models.add(str(m))
201
+ for t in TOKENS:
202
+ v = u.get(t)
203
+ if isinstance(v, int):
204
+ tokens[t] = (tokens[t] or 0) + v
205
+ rc, ec = u.get("reported_cost_usd"), u.get("estimated_cost_usd")
206
+ if isinstance(rc, int | float):
207
+ rep, n_rep = rep + rc, n_rep + 1
208
+ if isinstance(ec, int | float):
209
+ est, n_est = est + ec, n_est + 1
210
+ if not isinstance(rc, int | float) and not isinstance(ec, int | float):
211
+ unmeasured += 1
212
+ if isinstance(r.get("duration_s"), int | float):
213
+ agent_s += float(r["duration_s"])
214
+ elif kind == "gate" and r.get("verdict"):
215
+ verdicts[str(r["verdict"])] += 1
216
+ elif kind == "supervision":
217
+ sup = r
218
+ elif kind == "human" and isinstance(r.get("wait_s"), int | float):
219
+ wait_s += float(r["wait_s"])
220
+ if exit_ is None:
221
+ return None
222
+ t0, t1 = _ts((started or {}).get("ts")), _ts(exit_.get("ts"))
223
+ home = home_path()
224
+ completeness = "incomplete" if unmeasured else "complete" if n_rep == n else "estimated"
225
+ return {
226
+ "row_id": str(uuid.uuid4()), "kind": "run", "schema_version": 1,
227
+ "machine_id": _machine(home).get("machine_id"), "user": _git_user(root),
228
+ "repo": root.parent.name, "state_root": str(root), "workflow": workflow,
229
+ "workflow_version": (started or {}).get("workflow_version"), "thread_id": f"{workflow}/{task}",
230
+ "segment": exit_.get("segment"), "alias": (started or {}).get("alias"), "label": (started or {}).get("label"),
231
+ "origin": (started or {}).get("origin"), "parent": (started or {}).get("parent"),
232
+ "schedule_id": _schedule_id((started or {}).get("schedule")), "ticket": task,
233
+ "executors": sorted(executors), "models": sorted(models),
234
+ "exit_code": exit_.get("exit_code"), "reason": exit_.get("reason"), "units_run": len(units),
235
+ "repeats": dict(repeats), "gate_verdicts": dict(verdicts), "escapes": None, "tokens": tokens,
236
+ "sessions": n, "reported_sessions": n_rep, "estimated_sessions": n_est, "unmeasured_sessions": unmeasured,
237
+ "reported_cost_usd": round(rep, 6) if n_rep else None, "estimated_cost_usd": round(est, 6) if n_est else None,
238
+ "completeness": completeness, "wall_s": round(t1 - t0, 3) if t0 is not None and t1 is not None else None,
239
+ "agent_s": round(agent_s, 3) if agent_s else None, "person_wait_s": round(wait_s, 3) if wait_s else None,
240
+ # copied from the segment's supervision record, the builder the ledger row uses too (SUP-AC2)
241
+ **_supervision_fields(sup),
242
+ "ended_at": exit_.get("ts"),
243
+ }
244
+
245
+
246
+ def session_rows(log: Path, recs: Iterable[dict[str, Any]], run: dict[str, Any]) -> list[dict[str, Any]]:
247
+ """The `session` rows of one segment, one per `agent_run` (CST-B9): numbers and engine words only."""
248
+ out = []
249
+ for r in recs:
250
+ if r.get("kind") != "agent_run" or r.get("segment") != run.get("segment"):
251
+ continue
252
+ u = r.get("usage") or {}
253
+ models = sorted((u.get("by_model") or {}).keys())
254
+ outcome = "ok" if r.get("ok") else "timed_out" if r.get("timed_out") else "stalled" if r.get("stalled") \
255
+ else "infra" if r.get("infra_cause") else "failed"
256
+ out.append({"row_id": str(uuid.uuid4()), "kind": "session", "schema_version": 1,
257
+ "machine_id": run.get("machine_id"), "thread_id": run.get("thread_id"),
258
+ "state_root": run.get("state_root"), "workflow": run.get("workflow"),
259
+ "workflow_version": run.get("workflow_version"), "segment": run.get("segment"),
260
+ "unit": r.get("unit"), "session_kind": r.get("session_kind") or "step",
261
+ "executor": r.get("executor"), "model": models[0] if len(models) == 1 else None,
262
+ "tokens": {t: u.get(t) for t in TOKENS}, "reported_cost_usd": u.get("reported_cost_usd"),
263
+ "estimated_cost_usd": u.get("estimated_cost_usd"), "duration_s": r.get("duration_s"),
264
+ "slow_host": bool(r.get("slow_host")), "outcome": outcome, "tool_calls": len(r.get("tools") or []),
265
+ "ended_at": r.get("ts")})
266
+ return out
267
+
268
+
269
+ def _supervision_fields(sup: dict[str, Any] | None) -> dict[str, Any]:
270
+ if sup is None:
271
+ return dict.fromkeys(("touches_undesigned", "touches_by_decider", "agent_own_rescues", "level", "level_by",
272
+ "callers_unknown"))
273
+ by: dict[str, int] = defaultdict(int)
274
+ for cls in ("rescue", "steer"):
275
+ for d, n in ((sup.get("touches") or {}).get(cls) or {}).items():
276
+ if isinstance(n, int) and n:
277
+ by[d] += n
278
+ return {"touches_undesigned": sup.get("undesigned"), "touches_by_decider": dict(sorted(by.items())),
279
+ "agent_own_rescues": sup.get("agent_own_rescues"), "level": sup.get("level"),
280
+ "level_by": sup.get("level_by"), "callers_unknown": sup.get("callers_unknown")}
281
+
282
+
283
+ def stats_path(home: Path, month: str) -> Path:
284
+ return home / "stats" / f"{month}.jsonl"
285
+
286
+
287
+ def append_stats_row(path: Path, row: dict[str, Any]) -> None:
288
+ """Append `row` to the stats file `path` under the lock beside it (`<month>.lock`).
289
+
290
+ The writers of the stats files and `stats forget` take this one lock, so a row appended while the verb replaces
291
+ the file is not lost (CST-B23). A writer that does not get the lock within :data:`INDEX_LOCK_S` appends anyway,
292
+ so a run's row is never dropped; such a writer is not protected from a rewrite."""
293
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
294
+ with _locked(path):
295
+ append_jsonl(path, row)
296
+
297
+
298
+ def on_run_started(log: Path) -> None:
299
+ """Called by the run log's writer after `run_started`: the machine index (CST-B8); best effort."""
300
+ try:
301
+ touch_index(_parts(log)[0])
302
+ except Exception: # noqa: BLE001 - C2, LOS-B6
303
+ import logging
304
+
305
+ logging.getLogger("tempergraph.index").warning("machine index not updated")
306
+
307
+
308
+ def on_run_exit(log: Path, segment: int | None) -> None:
309
+ """Called by the run log's writer after `run_exit`: the stats row and the outbox rows; best effort (OVR-B4)."""
310
+ try:
311
+ from tempergraph.run.events import records
312
+
313
+ row = run_row(log, records(log), segment)
314
+ if row is None:
315
+ return
316
+ home = ensure_home()
317
+ month = str(row["ended_at"] or now_iso())[:7]
318
+ append_stats_row(stats_path(home, month), row)
319
+ sessions = session_rows(log, records(log), row)
320
+ for srow in sessions:
321
+ append_stats_row(home / "stats" / "sessions" / f"{month}.jsonl", srow)
322
+ from tempergraph.observe import sinks, supervision_cost
323
+
324
+ with contextlib.suppress(Exception): # SCO-B15: the next writing process closes what has ended
325
+ supervision_cost.close(home)
326
+ if sinks.enqueue(home, row, log) + sinks.enqueue_sessions(home, sessions, log, month):
327
+ sinks.start_flusher(home)
328
+ except Exception: # noqa: BLE001
329
+ import logging
330
+
331
+ logging.getLogger("tempergraph.stats").warning("stats row not written")
332
+
333
+
334
+ # -- readers ---------------------------------------------------------------------------------------------------
335
+
336
+
337
+ SAME = ("kind", "machine_id", "workflow", "segment", "exit_code", "ended_at") # equal in a row's local and sink form
338
+
339
+
340
+ def read_rows(paths: Iterable[Path], conflicts: list[str] | None = None) -> tuple[list[dict[str, Any]], int]:
341
+ """Rows from JSON-lines files, de-duplicated by `row_id` (CST-AC3); a newer major schema is skipped. A
342
+ repeated `row_id` whose content differs (a copied `machine.json` or stats file) is kept twice and its id
343
+ added to `conflicts` (CST-B10, CST-B14, CST-B8)."""
344
+ seen: dict[str, tuple[Any, ...]] = {}
345
+ out: list[dict[str, Any]] = []
346
+ unknown = 0
347
+ for p in paths:
348
+ try:
349
+ lines = p.read_text(encoding="utf-8").splitlines()
350
+ except OSError:
351
+ continue
352
+ for ln in lines:
353
+ try:
354
+ r = json.loads(ln)
355
+ except ValueError:
356
+ continue
357
+ if not isinstance(r, dict):
358
+ continue
359
+ if int(r.get("schema_version") or 1) > 1:
360
+ unknown += 1
361
+ continue
362
+ rid = str(r.get("row_id") or "")
363
+ same = tuple(r.get(k) for k in SAME)
364
+ if rid and rid in seen:
365
+ if seen[rid] == same:
366
+ continue
367
+ if conflicts is not None and rid not in conflicts:
368
+ conflicts.append(rid)
369
+ seen.setdefault(rid, same)
370
+ out.append(r)
371
+ return out, unknown
372
+
373
+
374
+ def _key(r: dict[str, Any], by: str) -> str:
375
+ if by == "version":
376
+ return f"{r.get('workflow')}@{r.get('workflow_version') or '?'}"
377
+ if by == "exit":
378
+ return str(r.get("exit_code"))
379
+ if by == "month":
380
+ return str(r.get("ended_at") or "")[:7]
381
+ if by == "executor":
382
+ return ",".join(r.get("executors") or []) or "none"
383
+ if by == "model":
384
+ return ",".join(r.get("models") or []) or "not recorded"
385
+ if by == "machine":
386
+ mid = str(r.get("machine_id") or "?") # two machines may share a label (a host name); never one key
387
+ return f"{r['machine_label']} ({mid[:8]})" if r.get("machine_label") else mid
388
+ if by == "schedule":
389
+ return str(r.get("schedule_id") or "none")
390
+ if by == "decider":
391
+ return ",".join(sorted((r.get("touches_by_decider") or {}).keys())) or "none"
392
+ if by == "repo":
393
+ return str(r.get("repo_id") or r.get("repo") or "none")
394
+ field = {"user": "user", "workflow": "workflow", "ticket": "ticket", "parent": "parent",
395
+ "level": "level", "host": "host"}[by]
396
+ return str(r.get(field) or "none")
397
+
398
+
399
+ def totals(rows: list[dict[str, Any]]) -> dict[str, Any]:
400
+ """Run count, thread count, and reported and estimated cost apart with the completeness flag (CST-B14, CST-B15, CST-B16)."""
401
+ rep = [r["reported_cost_usd"] for r in rows if isinstance(r.get("reported_cost_usd"), int | float)]
402
+ est = [r["estimated_cost_usd"] for r in rows if isinstance(r.get("estimated_cost_usd"), int | float)]
403
+ incomplete = any(r.get("completeness") == "incomplete" for r in rows)
404
+ estimated = any(r.get("completeness") == "estimated" for r in rows)
405
+ return {"runs": len(rows), "threads": len({r.get("thread_id") or r.get("thread_hash") for r in rows}),
406
+ "reported_usd": round(sum(rep), 6) if rep else None, "estimated_usd": round(sum(est), 6) if est else None,
407
+ "completeness": "incomplete" if incomplete else "estimated" if estimated else "complete",
408
+ "lower_bound": incomplete,
409
+ "exits": dict(sorted(_count(str(r.get("exit_code")) for r in rows).items()))}
410
+
411
+
412
+ def _count(xs: Iterable[str]) -> dict[str, int]:
413
+ out: dict[str, int] = defaultdict(int)
414
+ for x in xs:
415
+ out[x] += 1
416
+ return out
417
+
418
+
419
+ def projection(rows: list[dict[str, Any]], by_version: bool = False) -> list[dict[str, Any]]:
420
+ """Median and 90th percentile of estimated cost per finished run, per workflow (CST-B14, CST-B15, CST-B16); `thin` under 5."""
421
+ per: dict[str, dict[str, float]] = defaultdict(dict)
422
+ finished: set[str] = set()
423
+ for r in rows:
424
+ tid = str(r.get("thread_id") or r.get("thread_hash"))
425
+ key = f"{r.get('workflow')}@{r.get('workflow_version') or '?'}" if by_version else str(r.get("workflow"))
426
+ cost = r.get("estimated_cost_usd") if isinstance(r.get("estimated_cost_usd"), int | float) \
427
+ else r.get("reported_cost_usd")
428
+ if isinstance(cost, int | float):
429
+ per[key][tid] = per[key].get(tid, 0.0) + float(cost)
430
+ if r.get("exit_code") == 0:
431
+ finished.add(tid)
432
+ out = []
433
+ for key, threads in sorted(per.items()):
434
+ costs = sorted(c for t, c in threads.items() if t in finished)
435
+ if not costs:
436
+ continue
437
+ p90 = costs[min(len(costs) - 1, max(0, round(0.9 * len(costs) + 0.5) - 1))]
438
+ out.append({"workflow": key, "runs": len(costs), "median_usd": round(statistics.median(costs), 6),
439
+ "p90_usd": round(p90, 6), "thin": len(costs) < 5})
440
+ return out
441
+
442
+
443
+ def month_now() -> str:
444
+ return datetime.now(UTC).strftime("%Y-%m")