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,121 @@
1
+ """Measurement of a shipped fix: two workflow versions compared, model-free (SIL-B5, OVR-B16).
2
+
3
+ It writes no file, ledger row or code and launches nothing; its only writes go through the code host given to
4
+ it: one comment, and before it one reopen when quality fell (more than `measure.quality_drop` points).
5
+ It reads the ledger and run logs as plain text and imports no writer (a source test enforces it).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import Mapping, Sequence
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from tempergraph.improve import params
16
+ from tempergraph.improve.codehost import CodeHost
17
+
18
+ QUALITY_DROP = params.value("measure.quality_drop") # provenance default_no_data (5 points, release 1 default)
19
+ GUARD_COST = params.value("trial.guard_cost") # PRP-B9: the cost margin of the post-release comparison (15 %)
20
+
21
+
22
+ def _rows(path: Path) -> list[dict[str, Any]]:
23
+ try:
24
+ lines = path.read_text(encoding="utf-8").splitlines()
25
+ except OSError:
26
+ return []
27
+ out = []
28
+ for ln in lines:
29
+ try:
30
+ r = json.loads(ln)
31
+ except ValueError:
32
+ continue
33
+ if isinstance(r, dict):
34
+ out.append(r)
35
+ return out
36
+
37
+
38
+ def _cost(row: Mapping[str, Any]) -> float:
39
+ c = row.get("cost") or {}
40
+ return float(c.get("reported") or 0.0) + float(c.get("estimated_only") or 0.0)
41
+
42
+
43
+ def figures(root: Path, workflow: str, version: str) -> dict[str, Any]:
44
+ segs = [r for r in _rows(root / "ledger.jsonl") if r.get("kind") == "run_segment"
45
+ and r.get("workflow") == workflow and r.get("workflow_version") == version]
46
+ return window_figures(root, workflow, version, segs)
47
+
48
+
49
+ def window_figures(root: Path, workflow: str, label: str, segs: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
50
+ """The figures of the given `run_segment` rows of one workflow, whatever version they ran (PRP-B9)."""
51
+ version = label
52
+ threads: dict[str, list[Mapping[str, Any]]] = {}
53
+ for r in segs:
54
+ threads.setdefault(str(r.get("thread_id")), []).append(r)
55
+ n = len(threads)
56
+ cost = sum(_cost(r) for r in segs)
57
+ gates = passes = retries = sessions = 0
58
+ for tid in threads:
59
+ task = tid.split("/", 1)[1]
60
+ for r in _rows(root / "runs" / workflow / task / "run.jsonl"):
61
+ if r.get("kind") == "gate":
62
+ gates += 1
63
+ passes += r.get("token") == "PROCEED"
64
+ elif r.get("kind") == "agent_run":
65
+ sessions += 1
66
+ retries += r.get("session_kind") == "retry"
67
+ outcomes: dict[str, int] = {}
68
+ for rows in threads.values():
69
+ o = (rows[-1].get("outcome") or {}).get("verdict")
70
+ if o:
71
+ outcomes[o] = outcomes.get(o, 0) + 1
72
+ graded = sum(v for k, v in outcomes.items() if k != "not_reached")
73
+ met = outcomes.get("met", 0) + outcomes.get("met_with_open", 0)
74
+ return {"version": version, "runs": n, "cost_per_run": round(cost / n, 4) if n else None,
75
+ "repeat_share": round(retries / sessions, 3) if sessions else None,
76
+ "gate_pass_rate": round(passes / gates, 3) if gates else None,
77
+ "outcome_met_share": round(met / graded, 3) if graded else None, "outcomes": outcomes}
78
+
79
+
80
+ def compare(root: Path, workflow: str, before: str, after: str) -> dict[str, Any]:
81
+ a, b = figures(root, workflow, before), figures(root, workflow, after)
82
+ drops = [k for k in ("gate_pass_rate", "outcome_met_share")
83
+ if a[k] is not None and b[k] is not None and a[k] - b[k] > QUALITY_DROP]
84
+ saved = (a["cost_per_run"] - b["cost_per_run"]) if a["cost_per_run"] is not None and b["cost_per_run"] is not None \
85
+ else None
86
+ return {"workflow": workflow, "before": a, "after": b, "saved_per_run": round(saved, 4) if saved is not None
87
+ else None, "regressed": bool(drops), "dropped": drops,
88
+ "param": {"name": "measure.quality_drop", "value": QUALITY_DROP, "provenance": "default_no_data"}}
89
+
90
+
91
+ def compare_windows(root: Path, workflow: str, before_rows: Sequence[Mapping[str, Any]],
92
+ after_rows: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
93
+ """PRP-B9: two windows of `run_segment` rows compared. A measure is worse when cost per run rose by more than
94
+ `trial.guard_cost` of the before figure, or the gate pass rate or the met share of outcomes fell by more than
95
+ `measure.quality_drop`; a figure counts only when both windows have it. Repeat share is carried, never decides."""
96
+ a = window_figures(root, workflow, "before", before_rows)
97
+ b = window_figures(root, workflow, "after", after_rows)
98
+ worse = []
99
+ cost_a, cost_b = a["cost_per_run"], b["cost_per_run"]
100
+ if cost_a is not None and cost_b is not None and cost_a > 0 and cost_b - cost_a > cost_a * GUARD_COST:
101
+ worse.append("cost_per_run")
102
+ worse += [k for k in ("gate_pass_rate", "outcome_met_share")
103
+ if a[k] is not None and b[k] is not None and a[k] - b[k] > QUALITY_DROP]
104
+ return {"workflow": workflow, "before": a, "after": b, "worse": worse, "regressed": bool(worse),
105
+ "param": {"cost": {"name": "trial.guard_cost", "value": GUARD_COST},
106
+ "quality": {"name": "measure.quality_drop", "value": QUALITY_DROP}}}
107
+
108
+
109
+ def report(cmp: Mapping[str, Any], host: CodeHost, repo: str, issue: int) -> dict[str, Any]:
110
+ """The only writes: a reopen first when quality fell, then one comment (SIL-B5)."""
111
+ a, b = cmp["before"], cmp["after"]
112
+ if cmp["regressed"]:
113
+ host.reopen(repo, issue)
114
+ saved = cmp["saved_per_run"]
115
+ lines = [f"Measured `{cmp['workflow']}` {a['version']} ({a['runs']} runs) against {b['version']} ({b['runs']} runs).",
116
+ f"Cost per run {a['cost_per_run']} -> {b['cost_per_run']}" + (f" (saved {saved})." if saved else "."),
117
+ f"Gate pass rate {a['gate_pass_rate']} -> {b['gate_pass_rate']}; outcome met share "
118
+ f"{a['outcome_met_share']} -> {b['outcome_met_share']}.",
119
+ "Quality fell on " + ", ".join(cmp["dropped"]) + "; reopened." if cmp["regressed"] else "Quality held."]
120
+ url = host.comment(repo, issue, "\n".join(lines))
121
+ return {"comment": url, "reopened": bool(cmp["regressed"])}
@@ -0,0 +1,98 @@
1
+ """Loop thresholds as parameter records with provenance (IMD-B23); the loop never changes its own."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Literal
7
+
8
+
9
+ @dataclass(frozen=True, kw_only=True)
10
+ class Param:
11
+ name: str
12
+ value: float
13
+ provenance: Literal["default_no_data", "fitted", "owner_decision"] = "default_no_data"
14
+ source: str = ""
15
+
16
+ def to_json(self) -> dict[str, object]:
17
+ return {"name": self.name, "value": self.value, "provenance": self.provenance, "source": self.source}
18
+
19
+
20
+ PARAMS = {p.name: p for p in (
21
+ Param(name="retry_burst.min_retries", value=3, source="SIL-B12 to SIL-B16"),
22
+ Param(name="pattern_rule.min_runs", value=3, source="SIL-B3"),
23
+ Param(name="pattern_rule.min_distinct_requests", value=3, source="SIL-B3"),
24
+ Param(name="pattern_rule.window_days", value=30, source="SIL-B3"),
25
+ Param(name="base_rate.min_threads", value=6, source="FFD-B10, FFD-B12"),
26
+ Param(name="base_rate.max_share", value=0.5, source="FFD-B10, FFD-B12"),
27
+ Param(name="mute.days", value=30, source="ISS-B3"),
28
+ Param(name="seen_again.max_per_issue_per_day", value=1, source="ISS-B13"),
29
+ Param(name="outbox.max_age_days", value=30, source="ISS-B18"),
30
+ Param(name="friction.file_confidence", value=0.75, source="release 1 default"),
31
+ Param(name="outcome.audit_every", value=20, source="SIL-B10"),
32
+ Param(name="outcome.low_confidence", value=0.5, source="SIL-B10"),
33
+ Param(name="cost.every_n_exits", value=10, source="SIL-B10"),
34
+ Param(name="cost.window_days", value=30, source="release 1 default"),
35
+ Param(name="cost.min_runs", value=5, source="release 1 default"),
36
+ Param(name="cost.repeat_share", value=0.3, source="release 1 default"),
37
+ Param(name="cost.min_monthly_usd", value=10, source="release 1 default"),
38
+ Param(name="cost.max_lever_share", value=0.5, source="release 1 default"),
39
+ Param(name="stable.new_version_runs", value=5, source="SIL-B10"),
40
+ Param(name="stable.cost_percentile", value=0.9, source="SIL-B10"),
41
+ Param(name="stable.daily_cap_usd", value=50, source="SIL-B19, SIL-B20"),
42
+ Param(name="autonomy.min_room_usd", value=5, source="PRP-B11, release 1 default"),
43
+ Param(name="measure.quality_drop", value=0.05, source="release 1 default"),
44
+ Param(name="digest.repeat_min", value=3, source="SRV-B11"),
45
+ Param(name="digest.idle_minutes", value=10, source="SRV-B11"),
46
+ Param(name="digest.retry_overlap", value=0.8, source="SRV-B12"),
47
+ Param(name="digest.unused_runs", value=5, source="SRV-B12"),
48
+ Param(name="digest.judge_read_share", value=0.25, source="SRV-B31"),
49
+ Param(name="review.max_input_tokens", value=60_000, source="SRV-B17"),
50
+ Param(name="review.max_sessions.signals", value=3, source="SRV-B21"),
51
+ Param(name="review.run_share.dev", value=0.25, source="SRV-B21"),
52
+ Param(name="review.run_share.stable", value=0.10, source="SRV-B21"),
53
+ Param(name="review.run_cap_usd.dev", value=5, source="SRV-B21"),
54
+ Param(name="review.run_cap_usd.stable", value=2, source="SRV-B21"),
55
+ Param(name="review.probation_runs", value=5, source="SRV-B13, SRV-B14, SRV-B15"),
56
+ Param(name="review.repeat_sessions", value=3, source="SRV-B26"),
57
+ Param(name="review.repeat_runs", value=3, source="SRV-B32"),
58
+ Param(name="review.retry_wait_hours", value=6, source="SIL-B25"),
59
+ Param(name="lost_runner.window_days", value=7, source="SIL-B29"),
60
+ # FBK-B9, FBK-B14 (T12.3)
61
+ Param(name="labels.rerun_days", value=14, source="FBK-B9"),
62
+ Param(name="reliability.window_days", value=90, source="FBK-B11, FBK-B12"),
63
+ Param(name="reliability.recent_days", value=30, source="FBK-B11, FBK-B12"),
64
+ Param(name="reliability.min_labels", value=20, source="FBK-B11, FBK-B12"),
65
+ Param(name="reliability.min_known_bad", value=5, source="FBK-B11, FBK-B12"),
66
+ Param(name="reliability.max_false_pass", value=0.15, source="FBK-B11, FBK-B12"),
67
+ Param(name="reliability.min_audit_agreement", value=0.8, source="FBK-B11, FBK-B12"),
68
+ Param(name="reliability.min_audited", value=30, source="FBK-B11, FBK-B12"),
69
+ Param(name="reliability.queue_confidence", value=0.5, source="FBK-B13"),
70
+ Param(name="reliability.queue_sample", value=0.05, source="FBK-B13"),
71
+ Param(name="shift.first_n", value=10, source="FBK-B14"),
72
+ Param(name="shift.last_n", value=30, source="FBK-B14"),
73
+ Param(name="shift.pass_points", value=20, source="FBK-B14"),
74
+ Param(name="shift.unverifiable_points", value=15, source="FBK-B14"),
75
+ # PRP-B12, PRP-B18, PRP-B19, PRP-B20 (T12.5, T12.6)
76
+ Param(name="proposals.label_value", value=5, source="PRP-B12"),
77
+ Param(name="trial.alpha", value=0.05, source="PRP-B18, PRP-B19, PRP-B20, research `self-improvement-gap-analysis` F3"),
78
+ Param(name="trial.min_pairs", value=8, source="PRP-B18, PRP-B19, PRP-B20"),
79
+ Param(name="trial.noisy_floor", value=0.5, source="PRP-B18, PRP-B19, PRP-B20"),
80
+ Param(name="trial.guard_cost", value=0.15, source="PRP-B18, PRP-B19, PRP-B20"),
81
+ Param(name="trial.guard_outcome_cases", value=1, source="PRP-B18, PRP-B19, PRP-B20"),
82
+ Param(name="trial.guard_check_cases", value=1, source="PRP-B18, PRP-B19, PRP-B20"),
83
+ Param(name="trial.guard_escapes", value=1, source="PRP-B18, PRP-B19, PRP-B20"),
84
+ Param(name="trial.cap_usd", value=200, source="PRP-B7"),
85
+ # CAN-B26: the size of `review.run_cap_usd.dev`, which bounds a reader's sessions in one run
86
+ Param(name="analysis.cap_usd", value=5, source="CAN-B26"),
87
+ Param(name="trial.monthly_cap_usd", value=500, source="PRP-B11, release 1 default"),
88
+ Param(name="trial.after_release_runs", value=10, source="PRP-B9"),
89
+ )}
90
+
91
+
92
+ def value(name: str) -> float:
93
+ return PARAMS[name].value
94
+
95
+
96
+ def max_sessions(depth: str) -> int:
97
+ """SRV-B21: `review.max_sessions.<depth>`, the sessions a review of that depth may read in one run."""
98
+ return int(PARAMS[f"review.max_sessions.{depth}"].value)
@@ -0,0 +1,134 @@
1
+ """What answered a pause, for the friction judge (SIL-B37): facts read from ids and enums, never from text.
2
+
3
+ Each finding is told the pause that ended its own segment (`segment_of`: from `segment_started`, else the segment of the latest `run_exit` at
4
+ or before the finding's time): the paused unit and item,
5
+ the pause's reason, the decision word that answered it, the kind of caller, whether a ruling and whether feedback was
6
+ given (never their words), the operator reason of the decision (one of six words, else `not given`), the classes of the decision's touches, whether the workspace changed and the verdict of the
7
+ next gate of the paused unit, child and item. They come from the run log (`pause`, `workspace` and `gate` records)
8
+ and the ledger's `intervention` rows; no feedback or ruling text, answer value, path or file content is read or
9
+ returned (SIL-B38). A fact that cannot be read is `not recorded`, never a guess; a finding with no pause gets no row.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from collections.abc import Mapping, Sequence
16
+ from datetime import datetime
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from tempergraph.improve.record import _jsonl, _when
21
+ from tempergraph.store.layout import run_dir
22
+
23
+ UNKNOWN = "not recorded"
24
+ OPERATOR_REASONS = ("engine_defect", "judge_error", "environment", "plan", "request", "other") # CLI-B24
25
+ TOUCH_ORDER = ("designed", "rescue", "steer", "engine")
26
+ WORKSPACE_ACTIONS = {"prepared": "unchanged", "reused": "unchanged", "attached": "unchanged",
27
+ "external_change": "changed"}
28
+
29
+
30
+ def _second(ts: Any) -> datetime | None:
31
+ got = _when(ts)
32
+ return got.replace(microsecond=0) if got else None
33
+
34
+
35
+ def _word(value: Any) -> str:
36
+ """An id or enum word of a record; anything else (empty, not a string) is not recorded."""
37
+ return value if isinstance(value, str) and value and len(value) <= 80 and "\n" not in value else UNKNOWN
38
+
39
+
40
+ def segment_of(finding: Mapping[str, Any], records: Sequence[Mapping[str, Any]]) -> tuple[int, int] | None:
41
+ """SIL-B51: the index range of the finding's own segment: from the `run_started` at `segment_started` to the next
42
+ one; for a line without it, the segment whose `run_exit` is the latest at or before the finding's time, both read
43
+ to the whole second. None when no such segment is found or the finding's time cannot be read."""
44
+ starts = [i for i, r in enumerate(records) if r.get("kind") == "run_started"]
45
+ bounds = list(zip(starts, [*starts[1:], len(records)], strict=False))
46
+ marked = str(finding.get("segment_started") or "")
47
+ if marked:
48
+ return next((b for b in bounds if str(records[b[0]].get("ts") or "") == marked), None)
49
+ made = _second(finding.get("at"))
50
+ if made is None:
51
+ return None
52
+ found: tuple[int, int] | None = None
53
+ latest: datetime | None = None
54
+ for b in bounds:
55
+ for r in records[b[0]:b[1]]:
56
+ if r.get("kind") != "run_exit":
57
+ continue
58
+ ended = _second(r.get("ts"))
59
+ if ended is not None and ended <= made and (latest is None or ended >= latest):
60
+ found, latest = b, ended
61
+ return found
62
+
63
+
64
+ def pause_reason(seg_records: Sequence[Mapping[str, Any]], findings: Sequence[Mapping[str, Any]]) -> str:
65
+ """The reason of the pause that ended a segment (SIL-B45): the pause at a listed finding's unit, else the segment's
66
+ last pause, read from the pause record's own `reason` (its kind when it has none), never the `run_exit` reason.
67
+ `findings` are those already bound to the segment; `-` when the segment has no pause."""
68
+ pauses = [r for r in seg_records if r.get("kind") == "pause"]
69
+ if not pauses:
70
+ return "-"
71
+ pick = next((p for f in findings for p in reversed(pauses)
72
+ if str(p.get("unit") or "") == str(f.get("unit") or "")
73
+ and str(p.get("child") or "") == str(f.get("child") or "")), pauses[-1])
74
+ return re.sub(r"[^A-Za-z0-9_.:-]", "", str(pick.get("reason") or pick.get("pause_kind") or "-")) or "-"
75
+
76
+
77
+ def _touch(row: Mapping[str, Any]) -> str:
78
+ """SIL-B43: every class the decision touched, each once, in `TOUCH_ORDER`, joined by `,`; none is not recorded."""
79
+ classes = {t.get("class") for t in row.get("touches") or () if isinstance(t, Mapping)}
80
+ return ",".join(c for c in TOUCH_ORDER if c in classes) or UNKNOWN
81
+
82
+
83
+ def _facts(finding: Mapping[str, Any], records: Sequence[Mapping[str, Any]],
84
+ ledger: Sequence[Mapping[str, Any]], thread: str) -> dict[str, str] | None:
85
+ """The row of one finding, or None when no pause, no decision and no gate is recorded for it."""
86
+ unit, kid = str(finding.get("unit") or ""), str(finding.get("child") or "")
87
+ own = segment_of(finding, records)
88
+ if own is None:
89
+ return None
90
+ pauses = [(i, r) for i, r in enumerate(records[own[0]:own[1]], own[0]) if r.get("kind") == "pause"]
91
+ if not pauses:
92
+ return None
93
+ at, pause = next(((i, r) for i, r in reversed(pauses)
94
+ if str(r.get("unit") or "") == unit and str(r.get("child") or "") == kid), pauses[-1])
95
+ out = dict.fromkeys(("reason", "decision", "caller", "feedback", "workspace", "next_gate", "ruling", "touch"),
96
+ UNKNOWN)
97
+ out["operator_reason"] = "not given"
98
+ p_unit, p_kid, p_item = str(pause.get("unit") or ""), str(pause.get("child") or ""), str(pause.get("item") or "")
99
+ out["unit"] = _word(p_unit) if p_unit else "-"
100
+ out["item"] = _word(p_item) if p_item else "-"
101
+ out["reason"] = _word(pause.get("reason") or pause.get("pause_kind"))
102
+ when, owner = _when(pause.get("ts")), f"{p_kid}/{p_unit}" if p_kid else p_unit
103
+ answers = [r for r in ledger if r.get("kind") == "intervention" and r.get("thread_id") == thread
104
+ and str(r.get("unit") or "") == owner
105
+ and (when is None or (_when(r.get("ts")) or when) >= when)]
106
+ if answers:
107
+ row = answers[0]
108
+ out["decision"] = _word(row.get("decision"))
109
+ out["caller"] = _word((row.get("caller") or {}).get("kind") if isinstance(row.get("caller"), Mapping) else None)
110
+ out["ruling"] = "given" if row.get("ruling") else "not given" # whether, never the words (SIL-B38)
111
+ out["feedback"] = "given" if row.get("feedback") is True and not row.get("ruling") else "not given"
112
+ out["touch"] = _touch(row)
113
+ given = row.get("operator_reason")
114
+ out["operator_reason"] = given if given in OPERATOR_REASONS else "not given"
115
+ after = records[at + 1:]
116
+ ws = next((r for r in after if r.get("kind") == "workspace" and r.get("action") in WORKSPACE_ACTIONS), None)
117
+ if ws is not None and ws.get("mode") != "in_place": # WTR-B22: a run in place is compared with nothing
118
+ out["workspace"] = WORKSPACE_ACTIONS[str(ws["action"])]
119
+ gate = next((r for r in after if r.get("kind") == "gate" and str(r.get("unit") or "") == p_unit
120
+ and str(r.get("child") or "") == p_kid and str(r.get("item") or "") == p_item), None)
121
+ out["next_gate"] = "none" if gate is None or not gate.get("verdict") else _word(gate.get("verdict"))
122
+ return out
123
+
124
+
125
+ def of(root: Path, workflow: str, task_id: str, findings: Sequence[Mapping[str, Any]]) -> dict[str, dict[str, str]]:
126
+ """The facts of each finding of a segment that ended in a pause (`segment_exit` 3), by fingerprint."""
127
+ paused = [f for f in findings if f.get("segment_exit") == 3 and f.get("fingerprint")]
128
+ if not paused:
129
+ return {}
130
+ records = _jsonl(run_dir(root, workflow, task_id) / "run.jsonl")
131
+ ledger = _jsonl(root / "ledger.jsonl")
132
+ rows = {str(f["fingerprint"]): _facts(f, records, ledger, str(f.get("thread") or f"{workflow}/{task_id}"))
133
+ for f in paused}
134
+ return {fp: row for fp, row in rows.items() if row is not None}
@@ -0,0 +1,186 @@
1
+ """A read of a run's recorded pull request becomes a `later[]` entry (OUT-B23, OUT-B24, OUT-B25; FBK-B15).
2
+
3
+ The run's `run_segment` ledger row holds its pull request (FIN-B11). At a final exit the loop reads, through the code
4
+ host, each pull request of the workflow that no earlier read found merged or closed, and appends to the ledger one
5
+ `outcome_later` row per changed read: the pull request's state and counts of reviews by state, review comments,
6
+ follow-up commits and the files the run wrote that those commits changed. The files the run wrote are those that
7
+ differ between its branch start (the `base_commit` of the `workspace` record of its run log) and the end commit of
8
+ its ledger row (OUT-B28), whatever tool or command changed them. A row holds no text and counts only a
9
+ person's work. The text of reviews and review comments goes only to the run's local evidence folder,
10
+ `evidence/pull_request.jsonl`, scrubbed. A pull request that cannot be read is skipped. This module never imports
11
+ the filing code, and the filing code never imports it.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import contextlib
17
+ import json
18
+ import os
19
+ from collections.abc import Mapping
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from tempergraph import git as gitmod
24
+ from tempergraph.improve.codehost import CodeHostError
25
+ from tempergraph.run.log import Ledger
26
+ from tempergraph.security.scrub import clip, scrub
27
+ from tempergraph.store.layout import run_dir
28
+
29
+ DONE = ("merged", "closed")
30
+ MARKER = "<!-- tg-agent:" # CONTRIBUTING.md: the hidden first line of every agent comment
31
+ TEXT_CHARS = 8000
32
+ SKIPPED = (CodeHostError, ValueError, KeyError, TypeError, AttributeError)
33
+
34
+
35
+ def _rows(root: Path) -> list[dict[str, Any]]:
36
+ try:
37
+ lines = (root / "ledger.jsonl").read_text(encoding="utf-8").splitlines()
38
+ except OSError:
39
+ return []
40
+ out: list[dict[str, Any]] = []
41
+ for ln in lines:
42
+ with contextlib.suppress(ValueError):
43
+ r = json.loads(ln)
44
+ if isinstance(r, dict):
45
+ out.append(r)
46
+ return out
47
+
48
+
49
+ def _task(thread: str) -> str:
50
+ return thread.split("/", 1)[1] if "/" in thread else thread
51
+
52
+
53
+ def _valid(pr: Any) -> bool:
54
+ return isinstance(pr, Mapping) and isinstance(pr.get("repo"), str) and isinstance(pr.get("number"), int)
55
+
56
+
57
+ def _last_entries(rows: list[dict[str, Any]], workflow: str) -> dict[str, dict[str, Any]]:
58
+ out: dict[str, dict[str, Any]] = {}
59
+ for r in rows:
60
+ if r.get("kind") == "outcome_later" and r.get("workflow") == workflow and isinstance(r.get("entry"), dict):
61
+ out[str(r.get("thread_id"))] = r["entry"]
62
+ return out
63
+
64
+
65
+ def pending(root: Path, workflow: str) -> list[dict[str, Any]]:
66
+ """The latest recorded pull request of each thread of the workflow whose last `outcome_later` row is not
67
+ `merged` or `closed`: `{thread_id, task, pull_request}`."""
68
+ rows = _rows(root)
69
+ last = _last_entries(rows, workflow)
70
+ recorded: dict[str, dict[str, Any]] = {}
71
+ for r in rows:
72
+ if r.get("kind") == "run_segment" and r.get("workflow") == workflow and _valid(r.get("pull_request")):
73
+ recorded[str(r.get("thread_id"))] = dict(r["pull_request"])
74
+ return [{"thread_id": t, "task": _task(t), "pull_request": pr} for t, pr in recorded.items()
75
+ if (last.get(t) or {}).get("state") not in DONE]
76
+
77
+
78
+ def start_commit(root: Path, workflow: str, task: str) -> str:
79
+ """The branch start of a run: the `base_commit` of the first `workspace` record of its run log; empty when the log
80
+ or the field is missing."""
81
+ try:
82
+ lines = (run_dir(root, workflow, task) / "run.jsonl").read_text(encoding="utf-8").splitlines()
83
+ except OSError:
84
+ return ""
85
+ for ln in lines:
86
+ with contextlib.suppress(ValueError):
87
+ r = json.loads(ln)
88
+ if isinstance(r, dict) and r.get("kind") == "workspace" and r.get("base_commit"):
89
+ return str(r["base_commit"])
90
+ return ""
91
+
92
+
93
+ def end_commit(root: Path, workflow: str, thread: str) -> str:
94
+ """The end commit of a run: `pull_request.commit` of the thread's latest `run_segment` ledger row; empty when no
95
+ row or no commit is recorded."""
96
+ commit = ""
97
+ for r in _rows(root):
98
+ if r.get("kind") == "run_segment" and r.get("workflow") == workflow and r.get("thread_id") == thread:
99
+ pr = r.get("pull_request")
100
+ commit = str(pr.get("commit") or "") if isinstance(pr, Mapping) else ""
101
+ return commit
102
+
103
+
104
+ def _wrote(root: Path, workflow: str, task: str, end: str) -> set[str]:
105
+ """OUT-B28: the files the run wrote, those that differ between its branch start (the `base_commit` of the run
106
+ log's `workspace` record) and its recorded end commit, read in the repository of the state root, whatever tool or
107
+ command changed them; none when the log, the base or the end is missing."""
108
+ base = start_commit(root, workflow, task)
109
+ if not base or not end:
110
+ return set()
111
+ return set(gitmod.changed_between(root.parent, base, end))
112
+
113
+
114
+ def _person_text(r: Mapping[str, Any]) -> bool:
115
+ return r.get("author_kind") == "person" and not str(r.get("text") or "").lstrip().startswith(MARKER)
116
+
117
+
118
+ def _follow_ups(commits: list[dict[str, Any]], end: str) -> list[dict[str, Any]]:
119
+ """The commits after the run's recorded end commit; none when no end commit is recorded or it is not among them."""
120
+ if not end:
121
+ return []
122
+ for i, c in enumerate(commits):
123
+ sha = str(c.get("sha") or "")
124
+ if sha and (sha.startswith(end) or end.startswith(sha)):
125
+ return commits[i + 1:]
126
+ return []
127
+
128
+
129
+ def _write_private(path: Path, text: str) -> None:
130
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
131
+ with open(path, "w", encoding="utf-8") as fh:
132
+ fh.write(text)
133
+ if os.name == "posix":
134
+ os.chmod(path, 0o600)
135
+
136
+
137
+ def _evidence(root: Path, workflow: str, task: str, reviews: list[dict[str, Any]],
138
+ comments: list[dict[str, Any]]) -> None:
139
+ lines = [{"kind": "review", "state": r.get("state"), "text": clip(scrub(str(r.get("text") or "")), TEXT_CHARS)}
140
+ for r in reviews if _person_text(r)]
141
+ lines += [{"kind": "comment", "path": c.get("path"), "text": clip(scrub(str(c.get("text") or "")), TEXT_CHARS)}
142
+ for c in comments if _person_text(c)]
143
+ with contextlib.suppress(OSError):
144
+ _write_private(run_dir(root, workflow, task) / "evidence" / "pull_request.jsonl",
145
+ "".join(json.dumps(ln, ensure_ascii=False) + "\n" for ln in lines))
146
+
147
+
148
+ def read(root: Path, workflow: str, host: Any) -> list[dict[str, Any]]:
149
+ """Reads each pending pull request and appends an `outcome_later` row for each whose entry differs from its
150
+ thread's last, read from the ledger just before the comparison. Returns `{thread_id, task, pull_request, entry,
151
+ changed, appended}` for each pull request read, `appended` true only when this read wrote the row and `changed`
152
+ being the files the run wrote that a follow-up commit changed. A pull request that cannot be read (an unknown
153
+ state, or a host read that raised) comes back as `{thread_id, task, number, error}`, `error` the type name, and
154
+ the next pull request is read."""
155
+ ledger = Ledger(path=root / "ledger.jsonl")
156
+ out: list[dict[str, Any]] = []
157
+ for item in pending(root, workflow):
158
+ pr, thread, task = item["pull_request"], item["thread_id"], item["task"]
159
+ repo, number = str(pr["repo"]), int(pr["number"])
160
+ try:
161
+ state = str(host.pull_state(repo, number)["state"])
162
+ if state not in ("open", "merged", "closed"):
163
+ raise ValueError("unknown state")
164
+ reviews = list(host.pull_reviews(repo, number))
165
+ comments = list(host.pull_comments(repo, number))
166
+ commits = list(host.pull_commits(repo, number, after=str(pr.get("commit") or "")))
167
+ except SKIPPED as exc:
168
+ out.append({"thread_id": thread, "task": task, "number": number, "error": type(exc).__name__})
169
+ continue
170
+ mine = [r for r in reviews if _person_text(r)]
171
+ follow = [c for c in _follow_ups(commits, str(pr.get("commit") or "")) if c.get("author_kind") == "person"]
172
+ wrote = _wrote(root, workflow, task, str(pr.get("commit") or ""))
173
+ changed = sorted({str(f) for c in follow for f in c.get("files") or () if str(f) in wrote})
174
+ kinds: dict[str, int] = {}
175
+ for r in mine:
176
+ kinds[str(r.get("state"))] = kinds.get(str(r.get("state")), 0) + 1
177
+ entry = {"state": state, "reviews": dict(sorted(kinds.items())),
178
+ "comments": sum(1 for c in comments if _person_text(c)), "commits": len(follow),
179
+ "files": len(changed)}
180
+ _evidence(root, workflow, task, reviews, comments)
181
+ appended = entry != _last_entries(_rows(root), workflow).get(thread) # the ledger as it is now (OUT-B30)
182
+ if appended:
183
+ ledger.append({"kind": "outcome_later", "thread_id": thread, "workflow": workflow, "entry": entry})
184
+ out.append({"thread_id": thread, "task": task, "pull_request": pr, "entry": entry, "changed": changed,
185
+ "appended": appended})
186
+ return out