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,158 @@
1
+ """Harvest of judge misses into calibration case candidates, and replay of judges on kept cases (LIF-B7 to LIF-B16,
2
+ JCL-B9, JCL-B10, EVS-B13, EVS-B14).
3
+
4
+ A harvested candidate is local: it is written under the state root, holds ids, paths and statuses only, and
5
+ enters a package's gold set only after a person reviewed it and wrote its labels.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import uuid
13
+ from collections import defaultdict
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from tempergraph.contracts import WorkflowSpec
18
+ from tempergraph.docs import append_jsonl, write_json
19
+ from tempergraph.improve import calibration
20
+ from tempergraph.store.layout import now_iso, run_dir
21
+
22
+ REPLAY_CAP_USD = 20.0
23
+
24
+
25
+ def harvest_dir(root: Path, gate: str) -> Path:
26
+ return root / "evals" / "harvest" / gate
27
+
28
+
29
+ def _workspace(root: Path, workflow: str, thread: str) -> dict[str, Any]:
30
+ from tempergraph.run.events import records
31
+
32
+ task = thread.split("/", 1)[-1]
33
+ try:
34
+ recs = records(run_dir(root, workflow, task) / "run.jsonl")
35
+ except OSError:
36
+ return {}
37
+ ws: dict[str, Any] = next((r for r in reversed(recs) if r.get("kind") == "workspace"), {})
38
+ return {k: ws.get(k) for k in ("mode", "branch", "base_commit", "path") if ws.get(k)}
39
+
40
+
41
+ def harvest(root: Path, spec: WorkflowSpec, gate: str) -> list[dict[str, Any]]:
42
+ """`evals harvest`: one candidate per judged attempt a recorded label disagreed with (a gate escape, a
43
+ person's override or pushback, an audit disagreement, a rerun). The expected status is the opposite of what
44
+ the gate said: `UNMET` where it proceeded, `MET` where it blocked."""
45
+ from tempergraph.improve import reliability
46
+
47
+ g, step, _ = calibration.gate_spec(spec, gate)
48
+ misses: dict[tuple[str, Any], list[dict[str, Any]]] = defaultdict(list)
49
+ for lab in reliability.read_labels(root, spec.name):
50
+ if lab.get("unit") == gate and lab.get("value") == "disagree":
51
+ misses[(str(lab.get("thread")), lab.get("gate_record"))].append(lab)
52
+ produced = sorted(step.produces) if step is not None else []
53
+ blockers = sorted(calibration.judged_blockers(g))
54
+ out = []
55
+ for (thread, seq), labs in sorted(misses.items(), key=lambda kv: (kv[0][0], str(kv[0][1]))):
56
+ cid = "h-" + hashlib.sha256(f"{thread}\0{seq}".encode()).hexdigest()[:10]
57
+ proceeded = str(labs[0].get("gate_verdict")) in ("PROCEED", "NEXT")
58
+ named = sorted({str(x["criterion_id"]) for x in labs if x.get("criterion_id")})
59
+ case = {"schema_version": 1, "case_id": cid, "gate": gate, "provenance": "harvested", "state": "candidate",
60
+ "origin": {"thread": thread, "run_id": labs[0].get("run_id"), "attempt": labs[0].get("attempt"),
61
+ "gate_verdict": labs[0].get("gate_verdict"),
62
+ "labels": [{"label_id": x.get("label_id"), "kind": x.get("label_kind")} for x in labs]},
63
+ "suggested": [{"criterion": c, "expected": "UNMET" if proceeded else "MET"}
64
+ for c in (named or blockers)],
65
+ "subject": {"produces": produced, "workspace": _workspace(root, spec.name, thread)},
66
+ "labels": [], "harvested_at": now_iso()}
67
+ path = harvest_dir(root, gate) / cid / "case.json"
68
+ new = not path.exists()
69
+ if new:
70
+ path.parent.mkdir(parents=True, exist_ok=True)
71
+ write_json(path, case)
72
+ out.append({"case_id": cid, "path": str(path), "new": new, "thread": thread,
73
+ "suggested": case["suggested"]})
74
+ if gate == "outcome":
75
+ out.extend(_escape_candidates(root, spec, produced, blockers))
76
+ return out
77
+
78
+
79
+ def _escape_candidates(root: Path, spec: WorkflowSpec, produced: list[str], blockers: list[str]
80
+ ) -> list[dict[str, Any]]:
81
+ """LIF-B17: one candidate per escape of the outcome gate; ids, counts and kinds only, never text."""
82
+ from tempergraph.run import outcome_record
83
+
84
+ out = []
85
+ for rec in outcome_record.escape_records(spec, root / "ledger.jsonl"):
86
+ thread = str(rec["thread"])
87
+ cid = "h-" + hashlib.sha256(f"{thread}\0escape".encode()).hexdigest()[:10]
88
+ pull = {k: v for k, v in (rec.get("pull_request") or {}).items() if k in ("host", "repo", "number")}
89
+ case = {"schema_version": 1, "case_id": cid, "gate": "outcome", "provenance": "harvested",
90
+ "state": "candidate",
91
+ "origin": {"thread": thread, "pull_request": pull, "entry": rec.get("entry"),
92
+ "entries": rec.get("entries"), "signals": rec.get("signals")},
93
+ "suggested": [{"criterion": c, "expected": "UNMET"} for c in blockers],
94
+ "subject": {"produces": produced, "workspace": _workspace(root, spec.name, thread)},
95
+ "labels": [], "harvested_at": now_iso()}
96
+ path = harvest_dir(root, "outcome") / cid / "case.json"
97
+ new = not path.exists()
98
+ if new:
99
+ path.parent.mkdir(parents=True, exist_ok=True)
100
+ write_json(path, case)
101
+ out.append({"case_id": cid, "path": str(path), "new": new, "thread": thread,
102
+ "suggested": case["suggested"]})
103
+ return out
104
+
105
+
106
+ def replay(spec: WorkflowSpec, root: Path, executor: Any, *, cap_usd: float | None = None,
107
+ write: bool = True) -> dict[str, Any]:
108
+ """`evals replay`: each judged gate's judge once on every kept case, compared with the statuses its latest
109
+ complete score recorded. Judge sessions only; a cap reached keeps the record `partial`."""
110
+ from tempergraph.improve import suites
111
+
112
+ suites.refuse_live("judge", executor)
113
+ cap = REPLAY_CAP_USD if cap_usd is None else float(cap_usd)
114
+ spent, partial = 0.0, False
115
+ gates = []
116
+ for gate in calibration.judged_gates(spec):
117
+ if spec.package_root is None:
118
+ break
119
+ g, _, _ = calibration.gate_spec(spec, gate)
120
+ us, _ = calibration.usable(spec, gate)
121
+ complete = [s for s in calibration.scores(spec.package_root, gate) if not s.get("partial")
122
+ and not s.get("level")]
123
+ if not us or not complete:
124
+ continue
125
+ recorded = {r["case"]: r for r in complete[-1].get("results") or []
126
+ if r.get("variant") == "base" and r.get("repeat") == 1}
127
+ same = compared = verdict_same = cases = 0
128
+ flips = []
129
+ for u in us:
130
+ was = recorded.get(u.case.case_id)
131
+ if was is None:
132
+ continue
133
+ if spent >= cap:
134
+ partial = True
135
+ break
136
+ jd = calibration.judge_once(spec, gate, calibration.base_subject(u.case, g.criteria), executor,
137
+ f"replay.{u.case.case_id}")
138
+ spent += jd.cost
139
+ cases += 1
140
+ verdict_same += int(jd.verdict == was.get("verdict"))
141
+ for cid, status in sorted(jd.statuses.items()):
142
+ before = (was.get("statuses") or {}).get(cid)
143
+ compared += 1
144
+ same += int(status == before)
145
+ if status != before:
146
+ flips.append({"case": u.case.case_id, "criterion": cid, "was": before, "now": status})
147
+ gates.append({"gate": gate, "score_id": complete[-1].get("score_id"), "cases": cases,
148
+ "statuses_compared": compared, "agreement": round(same / compared, 4) if compared else None,
149
+ "verdict_agreement": round(verdict_same / cases, 4) if cases else None, "flips": flips})
150
+ rec = {"schema_version": 1, "replay_id": uuid.uuid4().hex[:12], "at": now_iso(), "workflow": spec.name,
151
+ "partial": partial, "cost_usd": round(spent, 6), "cap_usd": cap, "gates": gates}
152
+ if write:
153
+ append_jsonl(root / "evals" / "replays.jsonl", rec)
154
+ return rec
155
+
156
+
157
+ def read_candidate(path: Path) -> dict[str, Any]:
158
+ return dict(json.loads(path.read_text(encoding="utf-8")))
@@ -0,0 +1,192 @@
1
+ """What a loop issue tells its reader about the run behind a finding (ISS-B8 to ISS-B10).
2
+
3
+ Built by the loop child from the run's own log (`run.jsonl`) and the machine it runs on, never from the evidence
4
+ file. Every value is taken from a fixed list of record keys whose values the engine writes itself: ids, enums,
5
+ numbers, versions and model names. A value that does not look like one of those (any text with a space in it, a
6
+ path, a long string) is left out, so no request text, model output, judge note or check output can reach an issue.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import platform
12
+ import re
13
+ from collections.abc import Mapping, Sequence
14
+ from typing import Any
15
+
16
+ from tempergraph.constants import ENGINE_VERSION
17
+ from tempergraph.improve import pause_facts
18
+
19
+ LOG_LINES = 40 # the most run-log lines an issue or comment shows (ISS-B10)
20
+ SAFE = re.compile(r"^[A-Za-z0-9_.:@+\-]{1,64}$") # an id, enum, version or model name: no space, no slash
21
+ # The record keys a run-log line may show; anything else (request, notes, evidence, gap, transcript, paths) never.
22
+ LOG_KEYS = ("attempt", "visit", "entered_from", "session_key", "executor", "alias", "model", "effort", "cli_version",
23
+ "ok", "error_kind", "infra_cause", "timed_out", "stalled", "slow_host", "duration_s", "result",
24
+ "environmental", "verdict", "route_target", "blockers", "statuses", "confidence", "confidence_source",
25
+ "cause", "counter", "limit", "used", "exit_code", "reason", "cost", "cost_so_far", "unknown_tools")
26
+ RUN_KINDS = frozenset({"run_started", "run_exit"}) # shown whatever unit they name
27
+
28
+
29
+ def _safe(v: Any) -> Any:
30
+ """The value when it is a number, a bool or an id-like string; lists and maps of those, clipped; else None."""
31
+ if isinstance(v, bool) or v is None:
32
+ return v
33
+ if isinstance(v, int | float):
34
+ return round(v, 4) if isinstance(v, float) else v
35
+ if isinstance(v, str):
36
+ return v if SAFE.match(v) else None
37
+ if isinstance(v, list | tuple):
38
+ got = [x for x in (_safe(x) for x in list(v)[:10]) if x is not None and not isinstance(x, list | dict)]
39
+ return got or None
40
+ if isinstance(v, Mapping):
41
+ kept: dict[str, Any] = {}
42
+ for k, x in list(v.items())[:12]:
43
+ y = _safe(x)
44
+ if SAFE.match(str(k)) and y is not None and not isinstance(y, list | dict):
45
+ kept[str(k)] = y
46
+ return kept or None
47
+ return None
48
+
49
+
50
+ def _unit_of(r: Mapping[str, Any]) -> str:
51
+ return f"{r['child']}/{r.get('unit') or '-'}" if r.get("child") else str(r.get("unit") or "")
52
+
53
+
54
+ def segment(records: Sequence[Mapping[str, Any]], started: str | None = None) -> list[Mapping[str, Any]]:
55
+ """The segment that starts at the `run_started` whose `ts` is `started`; the last one when None or not found."""
56
+ starts = [i for i, r in enumerate(records) if r.get("kind") == "run_started"]
57
+ if started:
58
+ for n, i in enumerate(starts):
59
+ if str(records[i].get("ts") or "") == started:
60
+ return list(records[i:starts[n + 1] if n + 1 < len(starts) else len(records)])
61
+ return list(records[max(starts, default=0):])
62
+
63
+
64
+ def log_lines(records: Sequence[Mapping[str, Any]], units: Sequence[str], *,
65
+ segment_started: str | None = None, facts: Mapping[str, str] | None = None) -> tuple[list[str], int]:
66
+ """ISS-B10: the segment's records of the finding's units and its start and exit, one line each, at most
67
+ `LOG_LINES`; returns the lines and how many earlier matching records were left out. `facts` is accepted for the
68
+ same call shape as `run_facts`; the log lines never show it."""
69
+ want = set(units)
70
+ rows: list[str] = []
71
+ for r in segment(records, segment_started):
72
+ kind = str(r.get("kind") or "")
73
+ if kind not in RUN_KINDS and _unit_of(r) not in want:
74
+ continue
75
+ if not SAFE.match(kind):
76
+ continue
77
+ parts = [str(r.get("ts") or "")[:19], kind]
78
+ if r.get("unit") and kind not in RUN_KINDS:
79
+ parts.append(f"unit={_unit_of(r)}" if SAFE.match(_unit_of(r).replace("/", "-")) else "")
80
+ for k in LOG_KEYS:
81
+ if k not in r:
82
+ continue
83
+ v = _safe(r[k])
84
+ if v is None or v == [] or v == {}:
85
+ continue
86
+ if isinstance(v, list):
87
+ v = ",".join(str(x) for x in v)
88
+ elif isinstance(v, dict):
89
+ v = ",".join(f"{a}:{b}" for a, b in v.items())
90
+ parts.append(f"{k}={v}")
91
+ if kind == "agent_run":
92
+ cost = _safe((r.get("usage") or {}).get("reported_cost_usd")) if isinstance(r.get("usage"), Mapping) else None
93
+ if isinstance(cost, int | float):
94
+ parts.append(f"cost_usd={cost}")
95
+ if isinstance(r.get("changed_paths"), list):
96
+ parts.append(f"changed_paths={len(r['changed_paths'])}")
97
+ rows.append(" ".join(p for p in parts if p))
98
+ left = max(0, len(rows) - LOG_LINES)
99
+ return rows[left:], left
100
+
101
+
102
+ def environment(records: Sequence[Mapping[str, Any]], units: Sequence[str], mode: str | None = None,
103
+ judge_executor: str | None = None, *, segment_started: str | None = None,
104
+ facts: Mapping[str, str] | None = None) -> dict[str, Any]:
105
+ """ISS-B8: the versions and machine behind a finding, as names and numbers. `facts` is accepted for the same
106
+ call shape as `run_facts`; the environment never shows it."""
107
+ seg = segment(records, segment_started)
108
+ started: Mapping[str, Any] = next((r for r in seg if r.get("kind") == "run_started"), {})
109
+ want = set(units)
110
+ mine = [r for r in seg if _unit_of(r) in want]
111
+ executors = sorted({str(x) for r in mine if (x := _safe(r.get("executor")))})
112
+ cli = sorted({str(x) for r in mine if r.get("kind") == "agent_run" and (x := _safe(r.get("cli_version")))})
113
+ models = sorted({str(x) for r in mine if r.get("kind") == "session_opened" and (x := _safe(r.get("model")))})
114
+ aliases = sorted({str(x) for r in mine if r.get("kind") == "attempt_start" and (x := _safe(r.get("alias")))})
115
+ efforts = sorted({str(x) for r in mine if (x := _safe(r.get("effort")))})
116
+ out: dict[str, Any] = {
117
+ "engine_version": _safe(started.get("engine_version")) or ENGINE_VERSION,
118
+ "loop_engine_version": ENGINE_VERSION,
119
+ "workflow_version": _safe(started.get("workflow_version")),
120
+ "executors": executors, "executor_cli": cli, "models": models, "aliases": aliases, "efforts": efforts,
121
+ "judge_executor": _safe(judge_executor), "improvement_mode": _safe(mode),
122
+ "python": platform.python_version(), "os": f"{platform.system()} {platform.release()}".strip(),
123
+ "arch": platform.machine(),
124
+ }
125
+ return {k: v for k, v in out.items() if v not in (None, "", [])}
126
+
127
+
128
+ def run_facts(records: Sequence[Mapping[str, Any]], finding: Mapping[str, Any],
129
+ units: Sequence[str], *, segment_started: str | None = None,
130
+ facts: Mapping[str, str] | None = None) -> dict[str, Any]:
131
+ """ISS-B8: the run's id, how its segment ended, and the units' attempts and cost; with `facts` (SIL-B37) the
132
+ line that says what answered the segment's pause."""
133
+ seg = segment(records, segment_started)
134
+ started: Mapping[str, Any] = next((r for r in seg if r.get("kind") == "run_started"), {})
135
+ ended: Mapping[str, Any] = next((r for r in reversed(seg) if r.get("kind") == "run_exit"), {})
136
+ want = set(units)
137
+ attempts = {u: max([int(r.get("attempt") or 1) for r in seg if r.get("kind") == "attempt_start"
138
+ and _unit_of(r) == u] or [0]) for u in units}
139
+ cost = sum(float((r.get("usage") or {}).get("reported_cost_usd") or 0.0) for r in seg
140
+ if r.get("kind") == "agent_run" and _unit_of(r) in want and isinstance(r.get("usage"), Mapping))
141
+ reason = pause_facts.pause_reason(seg, [finding]) if ended.get("exit_code") == 3 else ended.get("reason")
142
+ out: dict[str, Any] = {
143
+ "thread": _safe(str(finding.get("thread") or "").replace("/", ":")) and str(finding.get("thread")),
144
+ "started": _safe(str(started.get("ts") or "")[:19]),
145
+ "exit_code": _safe(ended.get("exit_code", finding.get("segment_exit"))),
146
+ "exit_reason": _safe(reason),
147
+ "run_cost_usd": _safe(ended.get("cost_so_far") if ended.get("cost_so_far") is not None else ended.get("cost")),
148
+ "unit_cost_usd": round(cost, 4) if cost else None,
149
+ "attempts": {u: n for u, n in attempts.items() if n} or None,
150
+ "request_digest": _safe(finding.get("request_digest")),
151
+ "rerun_of": _safe(str(finding.get("rerun_of") or "").replace("/", ":")) and finding.get("rerun_of"),
152
+ "machine": _safe(finding.get("machine")),
153
+ "facts": _facts_line(facts) if facts else None,
154
+ }
155
+ return {k: v for k, v in out.items() if v not in (None, "", {}, [])}
156
+
157
+
158
+ FACT_KEYS = (("pause", "reason"), ("unit", "unit"), ("item", "item"), ("decision", "decision"),
159
+ ("operator_reason", "operator_reason"), ("caller", "caller"),
160
+ ("ruling", "ruling"), ("feedback", "feedback"), ("touch", "touch"), ("workspace", "workspace"),
161
+ ("next_gate", "next_gate"))
162
+
163
+
164
+ def _fact_value(raw: Any) -> str | None:
165
+ """A fact as one id-like word, or a list of such words joined by `,` (the classes of a decision's touches, SIL-B43);
166
+ None when any word of it is not an id or enum."""
167
+ words = [_safe(w.replace(" ", "_")) for w in str(raw or "").split(",")]
168
+ return ",".join(words) if words and all(isinstance(w, str) and w for w in words) else None
169
+
170
+
171
+ def _facts_line(facts: Mapping[str, str]) -> str | None:
172
+ """The facts of the segment's pause (SIL-B37) as `key=id` words; a value that is not an id or enum is left out."""
173
+ parts = []
174
+ for name, key in FACT_KEYS:
175
+ v = _fact_value(facts.get(key))
176
+ if v:
177
+ parts.append(f"{name}={v}")
178
+ return " ".join(parts) or None
179
+
180
+
181
+ def build(records: Sequence[Mapping[str, Any]], findings: Sequence[Mapping[str, Any]], *, mode: str | None = None,
182
+ judge_executor: str | None = None, segment_started: str | None = None,
183
+ facts: Mapping[str, str] | None = None) -> dict[str, Any]:
184
+ """The context of one issue or comment: the findings' units, their environment, run facts and log lines."""
185
+ first = findings[0]
186
+ units = [u for u in dict.fromkeys(
187
+ (f"{f['child']}/{f.get('unit') or '-'}" if f.get("child") else str(f.get("unit") or "")) for f in findings) if u]
188
+ lines, left = log_lines(records, units, segment_started=segment_started, facts=facts)
189
+ return {"environment": environment(records, units, mode, judge_executor, segment_started=segment_started,
190
+ facts=facts),
191
+ "run": run_facts(records, first, units, segment_started=segment_started, facts=facts),
192
+ "log": lines, "log_left_out": left}
@@ -0,0 +1,204 @@
1
+ """Which lenses fire at a final exit, and the model-free cost rules and gate scorecard (SIL-B10).
2
+
3
+ Friction and outcome need a judge in the loop child (T12.1.5); this module only decides that they fire, from
4
+ records. The cost lens is model-free here: fixed rules over a window of one workflow version.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import statistics
11
+ from collections.abc import Mapping, Sequence
12
+ from datetime import UTC, datetime, timedelta
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from tempergraph.contracts import WorkflowSpec
17
+ from tempergraph.improve import causes as causemod
18
+ from tempergraph.improve import params
19
+ from tempergraph.model import flow
20
+ from tempergraph.store.layout import run_dir
21
+
22
+ STABLE_FRICTION = ("tool_access", "grant_missing", "retries_spent", "loop_budget_spent", "check_fail",
23
+ "gap_escalation", "retry_burst", "pushback", "agent_decided", "blocked_without_check")
24
+ LARGE = frozenset({"large", "opus"})
25
+
26
+
27
+ def _jsonl(path: Path) -> list[dict[str, Any]]:
28
+ try:
29
+ lines = path.read_text(encoding="utf-8").splitlines()
30
+ except OSError:
31
+ return []
32
+ out = []
33
+ for ln in lines:
34
+ try:
35
+ r = json.loads(ln)
36
+ except ValueError:
37
+ continue
38
+ if isinstance(r, dict):
39
+ out.append(r)
40
+ return out
41
+
42
+
43
+ def _cost(row: Mapping[str, Any]) -> float:
44
+ c = row.get("cost") or {}
45
+ return float(c.get("reported") or 0.0) + float(c.get("estimated_only") or 0.0)
46
+
47
+
48
+ def _final_rows(root: Path, workflow: str, version: str | None) -> list[dict[str, Any]]:
49
+ return [r for r in _jsonl(root / "ledger.jsonl") if r.get("kind") == "run_segment"
50
+ and r.get("workflow") == workflow and r.get("workflow_version") == version
51
+ and int(r.get("exit_code") or 0) in (0, 4, 5)]
52
+
53
+
54
+ def decide(spec: WorkflowSpec, root: Path, thread: str, findings: Sequence[Mapping[str, Any]],
55
+ row: Mapping[str, Any], seg: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
56
+ """SIL-B10 triggers for this final exit, in the workflow's improvement mode.
57
+
58
+ `findings` are the segment's own findings and, at every final exit, the unjudged findings of the thread's
59
+ earlier pauses (SIL-B28): a fault among them turns the friction lens on.
60
+ """
61
+ mode = spec.improvement_mode
62
+ faults = [f for f in findings if f.get("class") == "fault"]
63
+ bases = {str(f["cause"]).split(":", 1)[0] for f in faults}
64
+ finals = _final_rows(root, spec.name, row.get("workflow_version"))
65
+ n = len(finals)
66
+ out: dict[str, Any] = {"mode": mode}
67
+ if mode == "dev":
68
+ friction = bool(faults)
69
+ else:
70
+ costs = [_cost(r) for r in finals[:-1]]
71
+ p90 = statistics.quantiles(costs, n=10)[-1] if len(costs) >= 10 else None
72
+ friction = bool(bases & set(STABLE_FRICTION)) or n <= int(params.value("stable.new_version_runs")) or (
73
+ p90 is not None and _cost(row) > p90)
74
+ out["friction"] = friction
75
+ orec = row.get("outcome")
76
+ if orec is not None:
77
+ reached = orec.get("verdict") != "not_reached"
78
+ conf = next((float(r.get("confidence") or 0) for r in reversed(seg) if r.get("kind") == "judgement"
79
+ and r.get("unit") == flow.OUTCOME_UNIT), None)
80
+ if mode == "dev":
81
+ fire = True
82
+ else:
83
+ low = conf is not None and conf <= params.value("outcome.low_confidence") and orec.get("verdict") == "met"
84
+ clean = not faults
85
+ fire = "pushback" in bases or low or (clean and n % int(params.value("outcome.audit_every")) == 0)
86
+ judged = any(c.get("class") == "judge" and c.get("status") not in ("not_judged",)
87
+ for c in orec.get("criteria", []))
88
+ out["outcome"] = {"fire": fire, "needs_judge": fire and (not reached or not judged)}
89
+ else:
90
+ out["outcome"] = {"fire": False, "needs_judge": False}
91
+ out["cost"] = n > 0 and n % int(params.value("cost.every_n_exits")) == 0
92
+ out["quality"] = scorecard(seg)
93
+ return out
94
+
95
+
96
+ def scorecard(seg: Sequence[Mapping[str, Any]]) -> dict[str, dict[str, Any]]:
97
+ """Per gate: visits, attempts, first-try passes and blocker counts; reported only until a binding is reliable."""
98
+ out: dict[str, dict[str, Any]] = {}
99
+ tries: dict[str, int] = {}
100
+ for r in seg:
101
+ unit = str(r.get("unit") or "")
102
+ if r.get("kind") == "unit_entered":
103
+ tries[unit] = 0
104
+ out.setdefault(unit, {"visits": 0, "attempts": 0, "first_try_pass": 0, "blockers": 0})["visits"] += 1
105
+ elif r.get("kind") == "gate" and unit in out:
106
+ tries[unit] = tries.get(unit, 0) + 1
107
+ out[unit]["attempts"] += 1
108
+ if r.get("token") == "PROCEED" and tries[unit] == 1:
109
+ out[unit]["first_try_pass"] += 1
110
+ elif r.get("kind") == "judgement" and unit in out:
111
+ out[unit]["blockers"] += len(r.get("blockers") or [])
112
+ for v in out.values():
113
+ v["filing"] = "report_only" # FBK-B5: a gate files only while its judge binding is `reliable`
114
+ return out
115
+
116
+
117
+ def _sessions(root: Path, workflow: str, thread: str) -> list[dict[str, Any]]:
118
+ task = thread.split("/", 1)[1] if "/" in thread else thread
119
+ return _jsonl(run_dir(root, workflow, task) / "run.jsonl")
120
+
121
+
122
+ def _usage_cost(r: Mapping[str, Any]) -> float | None:
123
+ u = r.get("usage") or {}
124
+ rep, est = u.get("reported_cost_usd"), u.get("estimated_cost_usd")
125
+ return float(rep) if rep is not None else float(est) if est is not None else None
126
+
127
+
128
+ def cost_rules(spec: WorkflowSpec, root: Path, version: str | None, now: datetime | None = None) -> dict[str, Any]:
129
+ """The model-free cost lens over a 30-day window of one version (SIL-B10, release 1 rule set)."""
130
+ now = now or datetime.now(UTC)
131
+ days = int(params.value("cost.window_days"))
132
+ since = (now - timedelta(days=days)).isoformat()
133
+ rows = [r for r in _final_rows(root, spec.name, version) if str(r.get("ts") or "") >= since]
134
+ threads = list(dict.fromkeys(str(r.get("thread_id")) for r in rows))
135
+ base = {"workflow": spec.name, "version": version, "window_days": days, "runs": len(threads),
136
+ "params": [params.PARAMS[k].to_json() for k in ("cost.window_days", "cost.min_runs", "cost.repeat_share",
137
+ "cost.min_monthly_usd", "cost.max_lever_share")]}
138
+ if len(threads) < int(params.value("cost.min_runs")):
139
+ return {**base, "status": "thin", "findings": []}
140
+ per: dict[str, dict[str, float]] = {}
141
+ blockers: dict[str, set[str]] = {}
142
+ unpriced: dict[str, int] = {}
143
+ large: dict[str, bool] = {}
144
+ blocked_units: set[str] = set()
145
+ for t in threads:
146
+ last_check_fail: dict[str, bool] = {}
147
+ for r in _sessions(root, spec.name, t):
148
+ unit = str(r.get("unit") or str(r.get("session_key") or "").split(".", 1)[0])
149
+ if r.get("kind") == "check":
150
+ last_check_fail[unit] = r.get("result") == "FAIL"
151
+ elif r.get("kind") == "judgement":
152
+ for cid in r.get("blockers") or ():
153
+ blockers.setdefault(f"{unit}:{cid}", set()).add(t)
154
+ blocked_units.add(unit)
155
+ elif r.get("kind") == "agent_run":
156
+ c = _usage_cost(r)
157
+ k = str(r.get("session_kind") or "step")
158
+ p = per.setdefault(unit, {"step": 0.0, "retry": 0.0, "judge": 0.0, "retry_after_check": 0.0})
159
+ if c is None:
160
+ unpriced[unit] = unpriced.get(unit, 0) + 1
161
+ continue
162
+ if k.startswith("judge"):
163
+ p["judge"] += c
164
+ elif k == "retry":
165
+ p["retry"] += c
166
+ if last_check_fail.get(unit):
167
+ p["retry_after_check"] += c
168
+ else:
169
+ p["step"] += c
170
+ if str(r.get("alias") or "").lower() in LARGE:
171
+ large[unit] = True
172
+ scale = 30 / days
173
+ lever = params.value("cost.max_lever_share")
174
+ floor = params.value("cost.min_monthly_usd")
175
+ found: list[dict[str, Any]] = []
176
+
177
+ def add(rule: str, unit: str, usd: float, **extra: Any) -> None:
178
+ saving = round(usd * lever * scale, 2)
179
+ found.append({"rule": rule, "unit": unit, "monthly_saving_usd": saving, "filed": saving >= floor,
180
+ "basis": "reported, else estimated", **extra})
181
+
182
+ for unit, p in per.items():
183
+ total = p["step"] + p["retry"] + p["judge"]
184
+ if total and p["retry"] / total >= params.value("cost.repeat_share"):
185
+ add("repeat_share", unit, p["retry"], share=round(p["retry"] / total, 3))
186
+ if p["retry_after_check"]:
187
+ add("retry_after_check", unit, p["retry_after_check"])
188
+ if p["judge"] > p["step"] + p["retry"] > 0:
189
+ add("judge_over_step", unit, p["judge"] - p["step"] - p["retry"])
190
+ if large.get(unit) and unit not in blocked_units:
191
+ add("expensive_unblocked", unit, p["step"])
192
+ for key, ts in blockers.items():
193
+ if len(ts) >= 3:
194
+ unit, cid = key.split(":", 1)
195
+ p = per.get(unit) or {}
196
+ add("recurring_blocker", unit, float(p.get("retry", 0.0)), criterion=cid, runs=len(ts))
197
+ for unit, n_unpriced in unpriced.items():
198
+ found.append({"rule": "unpriced_gate", "unit": unit, "sessions": n_unpriced, "monthly_saving_usd": None,
199
+ "filed": False, "basis": "unpriced"})
200
+ return {**base, "status": "ok", "findings": found}
201
+
202
+
203
+ def cause_class(code: str) -> str:
204
+ return causemod.cause_of(code).klass