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,322 @@
1
+ """Records on every exit, both modes, no model call (SIL-B8, IMD-B20, IMD-B21).
2
+
3
+ Findings are metadata only (`runs/<workflow>/<task>/findings.json`, LOS-B7, LOS-B8, LOS-B9). The evidence file
4
+ (`runs/<workflow>/<task>/evidence/record.json`) holds the request, the outputs and scrubbed feedback, stays on the
5
+ machine, and is never opened by filing code.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from collections.abc import Mapping, Sequence
15
+ from datetime import UTC, datetime
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from tempergraph import identity
20
+ from tempergraph.contracts import WorkflowSpec
21
+ from tempergraph.improve import causes as causemod
22
+ from tempergraph.improve import digest as digestmod
23
+ from tempergraph.improve import lenses
24
+ from tempergraph.model import flow
25
+ from tempergraph.security.scrub import clip, scrub
26
+ from tempergraph.store.layout import run_dir
27
+
28
+ FINAL_EXITS = frozenset({0, 4, 5}) # not a pause (exit 3)
29
+ OUTCOME_FAILED = frozenset({"UNMET", "PARTIAL"}) # a judge's grade; a person's `declined` is pushback
30
+ EVIDENCE_CHARS = 32_000
31
+
32
+
33
+ def findings_path(root: Path, workflow: str, task_id: str) -> Path:
34
+ return run_dir(root, workflow, task_id) / "findings.json"
35
+
36
+
37
+ def evidence_path(root: Path, workflow: str, task_id: str) -> Path:
38
+ return run_dir(root, workflow, task_id) / "evidence" / "record.json"
39
+
40
+
41
+ def prompt_path(root: Path, workflow: str, task_id: str, session_key: str) -> Path:
42
+ return run_dir(root, workflow, task_id) / "evidence" / "prompts" / f"{session_key}.txt"
43
+
44
+
45
+ def write_prompt(root: Path, workflow: str, task_id: str, session_key: str, text: str) -> None:
46
+ """A step session's rendered prompt, scrubbed, whole and with its line breaks, local only: the session
47
+ review's intent (SRV-B17)."""
48
+ with contextlib.suppress(OSError): # OVR-B4
49
+ _write_private(prompt_path(root, workflow, task_id, session_key), scrub(text))
50
+
51
+
52
+ def read_prompt(root: Path, workflow: str, task_id: str, session_key: str) -> str:
53
+ try:
54
+ return prompt_path(root, workflow, task_id, session_key).read_text(encoding="utf-8")
55
+ except OSError:
56
+ return ""
57
+
58
+
59
+ def unit_decls(spec: WorkflowSpec) -> dict[str, dict[str, Any]]:
60
+ """What each unit declares, for the digest and the review header: tools, criteria, the judge's brief."""
61
+ from tempergraph.contracts import TextRef
62
+ from tempergraph.model.text import TextUnreadable, load_text, split_judge_file
63
+
64
+ out: dict[str, dict[str, Any]] = {}
65
+ for name, u in spec.units.items():
66
+ j = u.gate.judge
67
+ brief = (j.brief if j else "") or ""
68
+ if j is not None and j.file:
69
+ with contextlib.suppress(TextUnreadable):
70
+ brief = split_judge_file(load_text(spec, TextRef(path=j.file)))[1] or brief
71
+ out[name] = {"tools": list(u.step.tools) if u.step else [],
72
+ "criteria": [{"id": c.id, "text": c.text} for c in u.gate.criteria],
73
+ "brief": scrub(brief)} # whole: the session view cuts it only at its cap (SRV-B17)
74
+ return out
75
+ def read_evidence(root: Path, workflow: str, task_id: str) -> dict[str, Any]:
76
+ """A run's local evidence record, or {} when absent or unreadable (the proposer's reading set, PRP-B23)."""
77
+ try:
78
+ doc = json.loads(evidence_path(root, workflow, task_id).read_text(encoding="utf-8"))
79
+ except (OSError, ValueError):
80
+ return {}
81
+ return doc if isinstance(doc, dict) else {}
82
+
83
+
84
+ def read_findings(root: Path, workflow: str, task_id: str) -> list[dict[str, Any]]:
85
+ try:
86
+ doc = json.loads(findings_path(root, workflow, task_id).read_text(encoding="utf-8"))
87
+ except (OSError, ValueError):
88
+ return []
89
+ return [f for f in doc.get("findings") or [] if isinstance(f, dict)] if isinstance(doc, dict) else []
90
+
91
+
92
+ def append_findings(root: Path, workflow: str, task_id: str, thread: str, lines: Sequence[Mapping[str, Any]]) -> None:
93
+ """Appends finding lines to the thread's findings document, in one private write (SIL-B8, SRV-B26)."""
94
+ if not lines:
95
+ return
96
+ doc = {"schema_version": 1, "thread": thread, "findings": read_findings(root, workflow, task_id) + list(lines)}
97
+ _write_private(findings_path(root, workflow, task_id), json.dumps(doc, default=str))
98
+
99
+
100
+ def write_findings(root: Path, workflow: str, task_id: str, thread: str, findings: Sequence[Mapping[str, Any]]) -> None:
101
+ """Rewrites the thread's findings document with `findings`, in one private write (SRV-B7)."""
102
+ doc = {"schema_version": 1, "thread": thread, "findings": list(findings)}
103
+ _write_private(findings_path(root, workflow, task_id), json.dumps(doc, default=str))
104
+
105
+
106
+ def _jsonl(path: Path) -> list[dict[str, Any]]:
107
+ try:
108
+ lines = path.read_text(encoding="utf-8").splitlines()
109
+ except OSError:
110
+ return []
111
+ out = []
112
+ for ln in lines:
113
+ try:
114
+ r = json.loads(ln)
115
+ except ValueError:
116
+ continue
117
+ if isinstance(r, dict):
118
+ out.append(r)
119
+ return out
120
+
121
+
122
+ def segment(records: Sequence[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
123
+ """The records of the last segment: from the last `run_started` on."""
124
+ start = max((i for i, r in enumerate(records) if r.get("kind") == "run_started"), default=0)
125
+ return list(records[start:])
126
+
127
+
128
+ def fingerprint(side: str, workflow: str, cause: str, unit: str) -> str:
129
+ return hashlib.sha256(f"{side}|{workflow}|{cause}|{unit}".encode()).hexdigest()[:16]
130
+
131
+
132
+ def _child_owner(spec: WorkflowSpec, path: Any, kids: Mapping[str, Any]) -> dict[str, Any]:
133
+ """SWF-B9: the fields that make a finding about a sub-workflow child's unit the child workflow's: its name and
134
+ version as the run started it (`run_started.children`), the parent, the unit's path, and the child's own
135
+ `issue_repository` (none when the child declares none: a child's finding never files to its parent's repository).
136
+ Empty for a unit of the run's own workflow."""
137
+ if not path:
138
+ return {}
139
+ held = kids.get(str(path)) or {}
140
+ name = str(held.get("workflow") or "")
141
+ if not name:
142
+ return {}
143
+ from tempergraph.model import subworkflow
144
+
145
+ got = subworkflow.read_child(name)
146
+ repo = got.spec.issue_repository if isinstance(got, subworkflow.Child) else None
147
+ labels = None # ISS-B1: the child's own `improvement.issue_labels`; a bad or missing document gives none
148
+ if isinstance(got, subworkflow.Child) and got.spec.package_root is not None:
149
+ try:
150
+ doc = json.loads((got.spec.package_root / "tempergraph.json").read_text(encoding="utf-8"))
151
+ declared = (doc.get("improvement") or {}).get("issue_labels") if isinstance(doc, dict) else None
152
+ labels = declared if isinstance(declared, list) else None
153
+ except (OSError, ValueError, AttributeError):
154
+ labels = None
155
+ return {"workflow": name, "workflow_version": held.get("workflow_version"), "parent": spec.name,
156
+ "child": str(path), "issue_repository": repo, "issue_labels": labels}
157
+
158
+
159
+ ANSWER_FIELDS = ("criteria", "items", "reasons", "decisions", "wait_s_median", "from_unit", "recovered")
160
+
161
+
162
+ def _side(code: str, executor: str | None) -> str:
163
+ side = causemod.cause_of(code).side
164
+ return f"executor:{executor or 'unknown'}" if side == "executor" else side
165
+
166
+
167
+ def _write_private(path: Path, text: str) -> None:
168
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
169
+ with open(path, "w", encoding="utf-8") as fh:
170
+ fh.write(text)
171
+ if os.name == "posix":
172
+ os.chmod(path, 0o600)
173
+
174
+
175
+ def evidence(values: Mapping[str, Any]) -> dict[str, Any]:
176
+ """Request, outputs and feedback, scrubbed; local only. The request is whole and keeps its line breaks (the
177
+ artifact review cuts it only at its cap, ALN-B29); the other parts are clipped."""
178
+ req = values.get("request") or {}
179
+ fb = [str(v.get("text")) for v in (values.get("feedback") or {}).values() if isinstance(v, Mapping) and v.get("text")]
180
+ fb += [str(r.get("text")) for r in (values.get("rulings") or {}).values() if isinstance(r, Mapping) and r.get("text")]
181
+ return {"schema_version": 1,
182
+ "request": {k: scrub(str(v)) for k, v in (req.get("inputs") or {}).items()},
183
+ "artifacts": clip(scrub(json.dumps(values.get("artifacts") or {}, default=str)), EVIDENCE_CHARS),
184
+ "values": clip(scrub(json.dumps(values.get("values") or {}, default=str)), EVIDENCE_CHARS),
185
+ "feedback": [clip(scrub(t), 8000) for t in fb]}
186
+
187
+
188
+ def _when(ts: Any) -> datetime | None:
189
+ try:
190
+ got = datetime.fromisoformat(str(ts))
191
+ except ValueError:
192
+ return None
193
+ return got if got.tzinfo else got.replace(tzinfo=UTC)
194
+
195
+
196
+ def unjudged_pause_findings(root: Path, workflow: str, task_id: str, thread: str,
197
+ home: Path | None = None) -> list[dict[str, Any]]:
198
+ """SIL-B28, SIL-B47, SIL-B48: the findings of the thread's segments that ended in a pause (exit 3) that no loop of
199
+ the thread has dealt with. A waiting or claimed ticket of the thread that holds the fingerprint covers it. A
200
+ `loop_started` record covers it when it names the fingerprint at or after the finding was made, was not held
201
+ (autonomy `record`, a dry run) and, for a friction fault, the loop log holds a judge answer for the fingerprint.
202
+ Read at every final exit of the thread."""
203
+ from tempergraph.improve import child
204
+ from tempergraph.improve.filing import COUNT_CAUSES, THREAD_COUNT_CAUSE
205
+
206
+ held =[f for f in read_findings(root, workflow, task_id) if f.get("segment_exit") == 3
207
+ and str(f.get("thread")) == thread]
208
+ if not held:
209
+ return []
210
+ in_tickets = child.held_by_tickets(root, thread, home)
211
+ log = _jsonl(child.loop_log(root, workflow, task_id))
212
+ started = [(_when(r.get("ts")), set(r.get("fingerprints") or ())) for r in log
213
+ if r.get("kind") == "loop_started" and r.get("held") is not True]
214
+ answered = {str(a.get("fingerprint")) for r in log if r.get("kind") == "loop_judged"
215
+ for a in r.get("answers") or () if isinstance(a, dict)}
216
+ out = []
217
+ for f in held:
218
+ fp = f.get("fingerprint")
219
+ if fp in in_tickets:
220
+ continue
221
+ made = _when(f.get("at"))
222
+ by_count = str(f.get("cause") or "").split(":", 1)[0] in (*COUNT_CAUSES, THREAD_COUNT_CAUSE) # SIL-B35
223
+ friction = f.get("class") == "fault" and f.get("lens") not in ("outcome", "review") and not by_count
224
+ covered = any(fps and fp in fps and (made is None or ts is None or ts >= made)
225
+ for ts, fps in started) and (not friction or str(fp) in answered)
226
+ if not covered:
227
+ out.append(f)
228
+ return out
229
+
230
+
231
+ def judged_units(seg: Sequence[Mapping[str, Any]]) -> dict[str, dict[str, Any]]:
232
+ """SRV-B12, SRV-B31, SRV-B44: per `unit.item` (the bare unit when the record has no `item`) with a `judgement`
233
+ record, `passed` (its last record has no blockers) and `gave` (the attempts with a record whose
234
+ `confidence_source` is not `engine_placeholder`: a real judgement)."""
235
+ passed: dict[str, bool] = {}
236
+ gave: dict[str, set[int]] = {}
237
+ for r in seg:
238
+ if r.get("kind") != "judgement" or not r.get("unit"):
239
+ continue
240
+ unit = f"{r['unit']}.{r['item']}" if r.get("item") else str(r["unit"])
241
+ passed[unit] = not (r.get("blockers") or [])
242
+ held = gave.setdefault(unit, set())
243
+ if r.get("confidence_source") != "engine_placeholder":
244
+ held.add(int(r.get("attempt") or 1))
245
+ return {u: {"passed": passed[u], "gave": sorted(gave[u])} for u in passed}
246
+
247
+
248
+ def record_exit(root: Path, spec: WorkflowSpec, task_id: str, log_path: Path, values: Mapping[str, Any],
249
+ row: Mapping[str, Any], seg: Sequence[Mapping[str, Any]] | None = None) -> dict[str, Any]:
250
+ """Findings and evidence of the segment that just ended; the lenses at a final exit. Returns the summary.
251
+
252
+ `seg` is the records the exit covers when they are not the last segment's (SIL-B27: a stop before a unit has
253
+ no segment of its own)."""
254
+ thread = str(row.get("thread_id"))
255
+ records = _jsonl(log_path)
256
+ seg = segment(records) if seg is None else list(seg)
257
+ seg_start = str((seg[0] if seg else {}).get("ts") or "")
258
+ ledger = _jsonl(root / "ledger.jsonl")
259
+ exits = [str(r.get("ts")) for r in ledger if r.get("kind") == "run_segment" and r.get("thread_id") == thread]
260
+ since = exits[-2] if len(exits) >= 2 else "" # interventions after the previous segment ended
261
+ ivs = [r for r in ledger if r.get("kind") == "intervention" and r.get("thread_id") == thread
262
+ and str(r.get("ts") or "") >= since and (not seg_start or str(r.get("ts") or "") <= seg_start)]
263
+ starter = next((r.get("caller") or {} for r in records if r.get("kind") == "run_started"), {})
264
+ found = causemod.derive(seg, ivs, row.get("grants") or (), starter=starter)
265
+ decls = unit_decls(spec)
266
+ try: # SRV-B11, SRV-B12: digests first, their causes join the findings; never changes the exit (OVR-B4)
267
+ digests = digestmod.write_segment(root, spec.name, task_id, seg, decls)
268
+ found += digestmod.causes(digests, root=root, workflow=spec.name, version=row.get("workflow_version"),
269
+ units=decls, judged=judged_units(seg))
270
+ except Exception: # noqa: BLE001
271
+ digests = []
272
+ if int(row.get("exit_code") or 0) in FINAL_EXITS: # the outcome lens's candidates (SIL-B10, B3, B7)
273
+ for c in (row.get("outcome") or {}).get("criteria") or ():
274
+ if c.get("class") == "judge" and c.get("status") in OUTCOME_FAILED:
275
+ found.append({"unit": flow.OUTCOME_UNIT, "cause": f"outcome_unmet:{c.get('id')}", "count": 1,
276
+ "lens": "outcome"})
277
+ keys = {k: row.get(k) for k in ("workflow", "workflow_version", "machine", "repo", "settings_digest",
278
+ "overridden_keys")}
279
+ req = str(((values.get("request") or {}).get("inputs") or {}).get("request") or "")
280
+ digest = identity.request_digest(req) if req else None
281
+ at = datetime.now(UTC).isoformat(timespec="seconds")
282
+ rerun_of = next((r.get("rerun_of") for r in seg if r.get("kind") == "run_started" and r.get("rerun_of")), None)
283
+ kids = next((r.get("children") or {} for r in seg if r.get("kind") == "run_started"), {})
284
+ lines = []
285
+ for f in found:
286
+ c = causemod.cause_of(f["cause"])
287
+ side = _side(f["cause"], f.get("executor"))
288
+ owner = _child_owner(spec, f.get("child"), kids) # SWF-B9: a child's unit is the child workflow's
289
+ lines.append({"kind": "finding", "thread": thread, **keys, **owner, "segment_exit": row.get("exit_code"),
290
+ "segment_started": seg_start,
291
+ "unit": f["unit"], "cause": f["cause"], "class": f.get("class") or c.klass, "side": side, "count": f["count"],
292
+ "remedy": c.remedy,
293
+ "fingerprint": fingerprint(side, str(owner.get("workflow") or spec.name), f["cause"], f["unit"]),
294
+ "at": at, "request_digest": digest,
295
+ **({"executor_version": f["executor_version"]} if f.get("executor_version") else {}),
296
+ **({"lens": f["lens"]} if f.get("lens") else {}),
297
+ **{k: f[k] for k in ANSWER_FIELDS if k in f}, # FRC-B8, FRC-B9, FRC-B13: ids, enums, numbers
298
+ **({"rerun_of": rerun_of} if rerun_of else {})})
299
+ final = int(row.get("exit_code") or 0) in FINAL_EXITS
300
+ stop = int(row.get("exit_code") or 0) == 4 and row.get("reason") == "person"
301
+ earlier = unjudged_pause_findings(root, spec.name, task_id, thread) if final else [] # SIL-B28
302
+ append_findings(root, spec.name, task_id, thread, lines) # one document per thread; each segment appends (SIL-B8)
303
+ _write_private(evidence_path(root, spec.name, task_id), json.dumps(evidence(values), default=str))
304
+ summary: dict[str, Any] = {"digests": len(digests), "causes": sorted({x["cause"] for x in lines}),
305
+ "sides": sorted({x["side"] for x in lines if x["class"] == "fault"}),
306
+ "count": len(lines),
307
+ "fingerprints": sorted({x["fingerprint"] for x in lines}),
308
+ "fault_fingerprints": sorted({x["fingerprint"] for x in lines
309
+ if x["class"] == "fault" and x.get("lens") != "outcome"}),
310
+ "outcome_fingerprints": sorted({x["fingerprint"] for x in lines
311
+ if x.get("lens") == "outcome"})}
312
+ covered = [x for x in earlier if x.get("lens") not in ("outcome", "review")] # their lines are already written
313
+ if covered:
314
+ # SIL-B28, SIL-AC45: the session review plans from `fingerprints`, so only a person's stop adds the pauses there
315
+ key = "fingerprints" if stop else "pause_fingerprints"
316
+ summary[key] = sorted({*summary.get(key, ()), *(str(x["fingerprint"]) for x in covered)})
317
+ summary["fault_fingerprints"] = sorted({*summary["fault_fingerprints"],
318
+ *(str(x["fingerprint"]) for x in covered if x.get("class") == "fault")})
319
+ if final:
320
+ summary["lenses"] = lenses.decide(spec, root, thread,
321
+ [x for x in lines if x.get("lens") != "outcome"] + covered, row, seg)
322
+ return summary
@@ -0,0 +1,89 @@
1
+ """The post-release comparison of a merged proposal and the regression record (PRP-B9, PRP-B29).
2
+
3
+ When the first `trial.after_release_runs` real final exits after a proposal's merge exist, the exits of the
4
+ proposal's `base_version` before the merge are compared with them (`measure.compare_windows`) and the proposal
5
+ holds `regressed_after_release` or `held_after_release`, once. A regression reopens the cluster's issues that are
6
+ in the pull request's repository; a host that cannot be reached leaves the reopen in the outbox (SIL-B19).
7
+ `measure.py` imports no writer (a source test enforces it), so the writes live here. Model-free.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Mapping
13
+ from datetime import UTC, datetime
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from tempergraph.improve import filing, measure, params, promotion
18
+ from tempergraph.improve import proposals as prp
19
+ from tempergraph.improve.codehost import CodeHost, CodeHostError
20
+ from tempergraph.store.layout import now_iso
21
+
22
+
23
+ def _dry(root: Path, workflow: str, thread: str) -> bool:
24
+ task = thread.split("/", 1)[-1]
25
+ return any(r.get("kind") == "run_started" and r.get("dry_run")
26
+ for r in prp._jsonl(root / "runs" / workflow / task / "run.jsonl"))
27
+
28
+
29
+ def real_exits(root: Path, workflow: str) -> list[dict[str, Any]]:
30
+ """The workflow's final `run_segment` rows (exit 0, 4 or 5), oldest first, leaving out the runs PRO-B8 leaves
31
+ out: trial, scenario and eval origins, a child's records from inside a parent and dry runs."""
32
+ out = []
33
+ for r in prp._jsonl(root / "ledger.jsonl"):
34
+ origin = str(r.get("origin") or "")
35
+ if r.get("kind") != "run_segment" or r.get("workflow") != workflow \
36
+ or r.get("exit_code") not in promotion.FINAL_EXITS or prp._ts(r.get("ts")) is None \
37
+ or origin in promotion.EXCLUDED_ORIGINS or origin.startswith(promotion.CHILD_ORIGIN) \
38
+ or _dry(root, workflow, str(r.get("thread_id") or "")):
39
+ continue
40
+ out.append(r)
41
+ return sorted(out, key=lambda r: prp._ts(r.get("ts")) or datetime.min.replace(tzinfo=UTC))
42
+
43
+
44
+ def _reopen(rec: Mapping[str, Any], host: CodeHost, outbox: filing.Outbox) -> None:
45
+ """PRP-B29: the cluster's issues of the pull request's repository, open again; the ones the host cannot take
46
+ wait in the outbox."""
47
+ ref = prp.pull_ref(rec.get("pull_request"))
48
+ if ref is None:
49
+ return
50
+ done: set[int] = set()
51
+ for url in (rec.get("cluster") or {}).get("issues") or []:
52
+ issue = prp.issue_ref(url)
53
+ if issue is None or issue[0] != ref[1] or issue[1] in done:
54
+ continue
55
+ done.add(issue[1])
56
+ try:
57
+ host.reopen(issue[0], issue[1])
58
+ except CodeHostError:
59
+ outbox.add({"op": "reopen", "repo": issue[0], "number": issue[1]})
60
+
61
+
62
+ def compare_due(root: Path, workflow: str, host: CodeHost, outbox: filing.Outbox) -> list[dict[str, Any]]:
63
+ """PRP-B9: compares each merged proposal of the workflow that holds no release record and has its first
64
+ `trial.after_release_runs` real exits after the merge; returns one outcome per proposal compared."""
65
+ need = int(params.value("trial.after_release_runs"))
66
+ exits: list[dict[str, Any]] | None = None
67
+ out: list[dict[str, Any]] = []
68
+ for rec in prp._saved(root, workflow):
69
+ merged_at = prp._ts(rec.get("merged_at"))
70
+ if rec.get("state") != "merged" or merged_at is None \
71
+ or rec.get("regressed_after_release") or rec.get("held_after_release"):
72
+ continue
73
+ exits = real_exits(root, workflow) if exits is None else exits
74
+ after = [r for r in exits if (prp._ts(r["ts"]) or merged_at) > merged_at][:need]
75
+ if len(after) < need:
76
+ continue
77
+ before = [r for r in exits if r.get("workflow_version") == rec.get("base_version")
78
+ and (prp._ts(r["ts"]) or merged_at) <= merged_at]
79
+ cmp = measure.compare_windows(root, workflow, before, after)
80
+ entry = {"before": cmp["before"], "after": cmp["after"], "at": now_iso()}
81
+ if cmp["regressed"]:
82
+ rec["regressed_after_release"] = {**entry, "worse": cmp["worse"]}
83
+ else:
84
+ rec["held_after_release"] = entry
85
+ prp.save(root, rec)
86
+ if cmp["regressed"]:
87
+ _reopen(rec, host, outbox)
88
+ out.append({"proposal_id": str(rec["proposal_id"]), "result": "regressed" if cmp["regressed"] else "held"})
89
+ return out