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,233 @@
1
+ """Per-step lessons: the file, its validation, the rendered block and its digest (LSN; ADR `lessons-are-versioned-workflow-content`).
2
+
3
+ A lessons file is workflow content (`lessons/<unit>.json` in the package). Runs read it and never write it;
4
+ it changes only through a `lessons` proposal, whose delta rules are `classify_change` (LSN-B9).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import re
12
+ from collections.abc import Mapping, Sequence
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from tempergraph.contracts import WorkflowSpec
18
+
19
+ MAX_ACTIVE = 12
20
+ MAX_CHARS = 2500
21
+ MAX_TEXT = 300
22
+ CRITERION_OVERLAP = 0.8
23
+ ID_RE = re.compile(r"^L-[1-9][0-9]*$")
24
+ SOURCE_RE = re.compile(r"^(person|proposal:[A-Za-z0-9_.:-]+)$")
25
+
26
+ # The literal floor of SCF-B13 applied to one sentence: a ticket id, a URL, an e-mail, a path, a number from a
27
+ # run (three or more digits), a quote (four or more words in quotation marks).
28
+ KINDS = ("ticket_id", "url", "email", "path", "number", "quote")
29
+
30
+ # Patterns with spans of their own (LSN-B7, PLC-B4): a URL and a path run to the next white space and a path has
31
+ # no leading space.
32
+ _SPAN_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
33
+ ("ticket_id", re.compile(r"\b[A-Z][A-Z0-9]+-[0-9]+\b")),
34
+ ("url", re.compile(r"(?:\b(?:https?|ftp)://|\bwww\.)\S*", re.I)),
35
+ ("email", re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b")),
36
+ ("path", re.compile(r"(?<!\S)(?:/|~/|[A-Za-z]:\\)\S+")),
37
+ ("number", re.compile(r"\d{3,}")),
38
+ )
39
+ _WORD = re.compile(r"[^\W_]+")
40
+ _DOUBLE = "\"“”"
41
+ _SINGLE = "'‘’"
42
+ _APOSTROPHES = "'’"
43
+
44
+
45
+ @dataclass(frozen=True, kw_only=True)
46
+ class Span:
47
+ """One literal as a hit within one line: `line` from 1, `start` in the line, `offset` in the text."""
48
+
49
+ kind: str
50
+ line: int
51
+ start: int
52
+ length: int
53
+ offset: int
54
+
55
+
56
+ def _alnum(c: str) -> bool:
57
+ return c.isalnum()
58
+
59
+
60
+ def _quotes(line: str) -> list[tuple[int, int]]:
61
+ """Quotes of one line as `(start, end)`: four or more words between an opening and the next closing mark of
62
+ one family (LSN-B10 to LSN-B12)."""
63
+ out: list[tuple[int, int]] = []
64
+ n = len(line)
65
+ i = 0
66
+ while i < n:
67
+ c = line[i]
68
+ family = _DOUBLE if c in _DOUBLE else _SINGLE if c in _SINGLE else ""
69
+ opens = (family and i + 1 < n and not line[i + 1].isspace()
70
+ and not (c in _APOSTROPHES and i > 0 and _alnum(line[i - 1])))
71
+ if not opens:
72
+ i += 1
73
+ continue
74
+ j = i + 1
75
+ while j < n:
76
+ d = line[j]
77
+ if (d in family and not line[j - 1].isspace() and j > i + 1
78
+ and not (d in _APOSTROPHES and j + 1 < n and _alnum(line[j + 1]))):
79
+ break
80
+ j += 1
81
+ else:
82
+ i += 1
83
+ continue
84
+ if len(_WORD.findall(line[i + 1:j])) >= 4:
85
+ out.append((i, j + 1))
86
+ i = j + 1
87
+ return out
88
+
89
+
90
+ def spans(text: str) -> list[Span]:
91
+ """Every literal of `text` as a hit, ordered by line and place on the line (PLC-B4)."""
92
+ out: list[Span] = []
93
+ base = 0
94
+ for no, line in enumerate(text.split("\n"), 1):
95
+ for kind, rx in _SPAN_PATTERNS:
96
+ out += [Span(kind=kind, line=no, start=m.start(), length=m.end() - m.start(), offset=base + m.start())
97
+ for m in rx.finditer(line)]
98
+ out += [Span(kind="quote", line=no, start=a, length=b - a, offset=base + a) for a, b in _quotes(line)]
99
+ base += len(line) + 1
100
+ return sorted(out, key=lambda s: (s.line, s.start, KINDS.index(s.kind)))
101
+
102
+
103
+ class LessonsError(ValueError):
104
+ pass
105
+
106
+
107
+ @dataclass(frozen=True, kw_only=True)
108
+ class Lesson:
109
+ id: str
110
+ text: str
111
+ status: str = "active"
112
+
113
+
114
+ def path(root: Path, unit: str) -> Path:
115
+ return root / "lessons" / f"{unit}.json"
116
+
117
+
118
+ def literals(text: str) -> list[str]:
119
+ found = {s.kind for s in spans(text)}
120
+ return [k for k in KINDS if k in found]
121
+
122
+
123
+ def check(doc: Any, unit: str, units: Sequence[str]) -> list[tuple[str, str]]:
124
+ """Validation findings `(code, message)` for one lessons document (LSN-B6, LSN-B7, LSN-B2)."""
125
+ where = f"lessons/{unit}.json"
126
+ if unit not in units:
127
+ return [("lessons-unknown-unit", f"{where}: the workflow declares no unit {unit!r}")]
128
+ if not isinstance(doc, dict) or doc.get("schema_version") != 1 or not isinstance(doc.get("lessons"), list):
129
+ return [("lessons-malformed", f"{where}: needs schema_version 1 and a list `lessons`")]
130
+ out: list[tuple[str, str]] = []
131
+ seen: set[str] = set()
132
+ active = 0
133
+ chars = 0
134
+ for i, e in enumerate(doc["lessons"]):
135
+ if not isinstance(e, dict):
136
+ out.append(("lessons-malformed", f"{where}: entry {i} is not an object"))
137
+ continue
138
+ lid, text, status = str(e.get("id") or ""), e.get("text"), e.get("status")
139
+ if not ID_RE.match(lid) or lid in seen:
140
+ out.append(("lessons-id", f"{where}: entry {i} id {lid!r} is not a new L-<n>"))
141
+ seen.add(lid)
142
+ if not isinstance(text, str) or not text.strip() or len(text) > MAX_TEXT or "\n" in text:
143
+ out.append(("lessons-text", f"{where}: {lid} text must be one line of at most {MAX_TEXT} characters"))
144
+ continue
145
+ if status not in ("active", "retired"):
146
+ out.append(("lessons-status", f"{where}: {lid} status must be active or retired"))
147
+ if not SOURCE_RE.match(str(e.get("source") or "")):
148
+ out.append(("lessons-source", f"{where}: {lid} source must be `person` or `proposal:<id>`"))
149
+ hits = literals(text)
150
+ if hits:
151
+ out.append(("lessons-literal", f"{where}: {lid} holds a literal ({', '.join(hits)})"))
152
+ if status == "active":
153
+ active += 1
154
+ chars += len(text)
155
+ if active > MAX_ACTIVE or chars > MAX_CHARS:
156
+ out.append(("lessons-budget", f"{where}: {active} active entries, {chars} characters "
157
+ f"(at most {MAX_ACTIVE} and {MAX_CHARS})"))
158
+ return out
159
+
160
+
161
+ def validate(spec: WorkflowSpec) -> list[tuple[str, str | None, str]]:
162
+ """Every lessons file of the package: `(code, unit, message)`; nothing when the package has none."""
163
+ root = spec.package_root
164
+ folder = root / "lessons" if root is not None else None
165
+ if folder is None or not folder.is_dir():
166
+ return []
167
+ out: list[tuple[str, str | None, str]] = []
168
+ for f in sorted(folder.iterdir()):
169
+ if f.suffix != ".json":
170
+ continue
171
+ try:
172
+ doc = json.loads(f.read_text(encoding="utf-8"))
173
+ except (OSError, ValueError):
174
+ doc = None
175
+ out += [(code, f.stem, msg) for code, msg in check(doc, f.stem, list(spec.units))]
176
+ return out
177
+
178
+
179
+ def load(spec: WorkflowSpec, unit: str) -> tuple[Lesson, ...]:
180
+ """Active entries in id order; a malformed file raises, so a run never starts on half-read lessons."""
181
+ root = spec.package_root
182
+ if root is None:
183
+ return ()
184
+ p = path(root, unit)
185
+ if not p.exists():
186
+ return ()
187
+ try:
188
+ doc = json.loads(p.read_text(encoding="utf-8"))
189
+ except (OSError, ValueError) as exc:
190
+ raise LessonsError(f"lessons/{unit}.json: {type(exc).__name__}") from None
191
+ problems = check(doc, unit, list(spec.units))
192
+ if problems:
193
+ raise LessonsError(problems[0][1])
194
+ entries = [Lesson(id=e["id"], text=e["text"]) for e in doc["lessons"] if e.get("status") == "active"]
195
+ return tuple(sorted(entries, key=lambda e: int(e.id[2:])))
196
+
197
+
198
+ def block(entries: Sequence[Lesson]) -> str:
199
+ if not entries:
200
+ return ""
201
+ return "## Lessons from earlier runs\n" + "\n".join(f"- {e.id}: {e.text}" for e in entries)
202
+
203
+
204
+ def digest(text: str) -> str | None:
205
+ return hashlib.sha256(text.encode()).hexdigest()[:16] if text else None
206
+
207
+
208
+ def _words(text: str) -> set[str]:
209
+ return set(re.findall(r"[a-z0-9]+", text.lower()))
210
+
211
+
212
+ def overlap(a: str, b: str) -> float:
213
+ wa, wb = _words(a), _words(b)
214
+ return len(wa & wb) / max(1, min(len(wa), len(wb))) if wa and wb else 0.0
215
+
216
+
217
+ def classify_change(old: Sequence[Mapping[str, Any]], new: Sequence[Mapping[str, Any]],
218
+ criteria: Sequence[str]) -> str | None:
219
+ """LSN-B9 for a `lessons` proposal: None when allowed, else the refusal code."""
220
+ before = {str(e.get("id")): e for e in old}
221
+ after = {str(e.get("id")): e for e in new}
222
+ if [i for i in after if i in before] != [i for i in before if i in after]:
223
+ return "lessons_rewrite" # a reorder
224
+ if set(before) - set(after):
225
+ return "lessons_rewrite" # an entry removed instead of retired
226
+ changed = [i for i in after if i not in before or before[i] != after[i]]
227
+ if len(changed) > 2:
228
+ return "lessons_rewrite"
229
+ for i in changed:
230
+ text = str(after[i].get("text") or "")
231
+ if after[i].get("status") == "active" and any(overlap(text, c) >= CRITERION_OVERLAP for c in criteria):
232
+ return "lesson_is_criterion"
233
+ return None
@@ -0,0 +1,138 @@
1
+ """`report --loop`: the loop's own figures over a window, per workflow (IMD-B22; plan T12.8).
2
+
3
+ Read-only and model-free, from this state root: findings, the `loop.jsonl` records of each thread, the ledger's
4
+ `loop` rows, and the proposal and trial records. Release 1 reads no issue or pull request state from the code
5
+ host, so issue precision, time to fix, held after release and estimated saving print as not derived, with the
6
+ reason, never as zero (IMD-B22). Every parameter that decides a figure is printed with its provenance (IMD-B23).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from collections.abc import Callable, Mapping, Sequence
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from tempergraph.improve import params
18
+
19
+ NOT_DERIVED = "issue and pull request states are not read from the code host in release 1"
20
+ FIGURE_PARAMS = ("cost.window_days", "proposals.label_value", "stable.daily_cap_usd", "trial.cap_usd",
21
+ "trial.monthly_cap_usd", "reliability.min_labels")
22
+
23
+
24
+ def _jsonl(path: Path) -> list[dict[str, Any]]:
25
+ try:
26
+ lines = path.read_text(encoding="utf-8").splitlines()
27
+ except OSError:
28
+ return []
29
+ out = []
30
+ for ln in lines:
31
+ try:
32
+ r = json.loads(ln)
33
+ except ValueError:
34
+ continue
35
+ if isinstance(r, dict):
36
+ out.append(r)
37
+ return out
38
+
39
+
40
+ def _docs(folder: Path) -> list[dict[str, Any]]:
41
+ out = []
42
+ for p in sorted(folder.glob("*.json")) if folder.is_dir() else ():
43
+ try:
44
+ d = json.loads(p.read_text(encoding="utf-8"))
45
+ except (OSError, ValueError):
46
+ continue
47
+ if isinstance(d, dict):
48
+ out.append(d)
49
+ return out
50
+
51
+
52
+ def _in(ts: Any, since: datetime | None) -> bool:
53
+ return since is None or str(ts or "") >= since.isoformat()
54
+
55
+
56
+ def _spend(doc: Mapping[str, Any]) -> tuple[float, float]:
57
+ s = doc.get("spend") or {}
58
+ if "total" in s:
59
+ return 0.0, float(s.get("total") or 0) # a trial's total mixes both; shown as estimated
60
+ return float(s.get("reported") or 0), float(s.get("estimated") or 0)
61
+
62
+
63
+ def workflow_figures(root: Path, workflow: str, since: datetime | None) -> dict[str, Any]:
64
+ from tempergraph.improve import proposals as prp
65
+ from tempergraph.improve.record import read_findings
66
+
67
+ base = root / "runs" / workflow
68
+ findings: list[dict[str, Any]] = []
69
+ loop: list[dict[str, Any]] = []
70
+ for d in sorted(base.iterdir()) if base.is_dir() else ():
71
+ findings += [f for f in read_findings(root, workflow, d.name) if _in(f.get("at"), since)]
72
+ loop += [r for r in _jsonl(d / "loop.jsonl") if _in(r.get("ts"), since)]
73
+ props = [p for p in _docs(root / "improve" / "proposals") if p.get("workflow") == workflow and _in(p.get("at"), since)]
74
+ trials = [t for t in _docs(root / "improve" / "trials") if t.get("workflow") == workflow and _in(t.get("at"), since)]
75
+ rows = [r for r in _jsonl(root / "ledger.jsonl") if r.get("kind") == "loop" and r.get("workflow") == workflow
76
+ and _in(r.get("ts"), since)]
77
+ spend = {"children": {"reported": 0.0, "estimated": 0.0}, "proposer": {"reported": 0.0, "estimated": 0.0},
78
+ "trials": {"reported": 0.0, "estimated": 0.0}}
79
+ for r in rows:
80
+ c = r.get("cost") or {}
81
+ spend["children"]["reported"] += float(c.get("reported") or 0)
82
+ spend["children"]["estimated"] += float(c.get("estimated_only") or 0)
83
+ for key, docs in (("proposer", props), ("trials", trials)):
84
+ for doc in docs:
85
+ rep, est = _spend(doc)
86
+ spend[key]["reported"] += rep
87
+ spend[key]["estimated"] += est
88
+ for v in spend.values():
89
+ v["reported"], v["estimated"] = round(v["reported"], 4), round(v["estimated"], 4)
90
+ funnel = {"findings": len(findings), "clusters": len(prp.clusters(root, workflow)),
91
+ "issues_filed": sum(1 for r in loop if r.get("kind") == "issue_filed"),
92
+ "issues_commented": sum(1 for r in loop if r.get("kind") == "issue_commented"),
93
+ "proposals": len(props), "by_loop": sum(1 for p in props if p.get("author") == "loop"),
94
+ "trials": len(trials), "shown_better": sum(1 for t in trials if t.get("decision") == "shown_better"),
95
+ "opened": sum(1 for p in props if p.get("state") in ("opened", "merged", "closed")), "merged": None,
96
+ "held_after_release": None}
97
+ return {"workflow": workflow, "funnel": funnel,
98
+ "issue_precision": {"value": None, "not_derived": NOT_DERIVED},
99
+ "time_to_fix_days": {"value": None, "not_derived": NOT_DERIVED},
100
+ "held_after_release": {"value": None, "not_derived": NOT_DERIVED},
101
+ "estimated_saving": {"value": None, "not_derived": NOT_DERIVED},
102
+ "loop_spend": spend,
103
+ "reviews": sum(1 for r in loop if r.get("kind") == "review_done"),
104
+ "skipped_daily_cap": sum(1 for r in loop if r.get("kind") == "loop_skipped"
105
+ and r.get("reason") == "daily_cap")}
106
+
107
+
108
+ def report(root: Path, workflows: Sequence[str], since: datetime | None,
109
+ coverage: Callable[[str], Sequence[str]] | None = None) -> dict[str, Any]:
110
+ """Every figure of IMD-B22 per workflow; `coverage(workflow)` gives each judged gate's reliability grade."""
111
+ out = []
112
+ for w in workflows:
113
+ fig = workflow_figures(root, w, since)
114
+ grades = list(coverage(w)) if coverage is not None else []
115
+ fig["label_coverage"] = {g: round(grades.count(g) / len(grades), 3) for g in
116
+ ("reliable", "unmeasured", "unreliable")} if grades else None
117
+ out.append(fig)
118
+ return {"schema_version": 1, "since": since.isoformat() if since else None, "workflows": out,
119
+ "params": [params.PARAMS[k].to_json() for k in FIGURE_PARAMS if k in params.PARAMS]}
120
+
121
+
122
+ def text(doc: Mapping[str, Any]) -> str:
123
+ lines = [f"loop report since {doc.get('since') or 'the start'}"]
124
+ for w in doc["workflows"]:
125
+ f = w["funnel"]
126
+ lines.append(f"{w['workflow']}: findings {f['findings']} → clusters {f['clusters']} → issues {f['issues_filed']} "
127
+ f"(+{f['issues_commented']} comments) → proposals {f['proposals']} ({f['by_loop']} by the loop) → "
128
+ f"trials {f['trials']} → shown better {f['shown_better']} → opened {f['opened']} → merged n/a")
129
+ s = w["loop_spend"]
130
+ lines.append(" spend: " + ", ".join(f"{k} ${v['reported']:.2f} reported, ${v['estimated']:.2f} estimated"
131
+ for k, v in s.items()))
132
+ cov = w.get("label_coverage")
133
+ lines.append(" label coverage: " + (", ".join(f"{k} {v:.0%}" for k, v in cov.items()) if cov else "no gates"))
134
+ lines.append(f" reviews {w['reviews']}, days capped {w['skipped_daily_cap']}; precision, time to fix, held "
135
+ f"after release, saving: not derived ({NOT_DERIVED})")
136
+ for p in doc["params"]:
137
+ lines.append(f" param {p['name']} = {p['value']} ({p['provenance']}, {p['source']})")
138
+ return "\n".join(lines) + "\n"
@@ -0,0 +1,85 @@
1
+ """The loop's summary (SIL-B22): what one loop child left, short enough to show beside what waits on a person.
2
+
3
+ One `loop_summary` record per ticket in the thread's `loop.jsonl`: the findings the thread holds, the issues this
4
+ child opened or commented on, and the three kept review observations with the highest confidence, as category, unit
5
+ and confidence and never a note, and `review_failed`, the reviews that ended failed counted by error class (SIL-B24):
6
+ a review ended failed when the latest `review_done` or `review_failed` record of its session is `review_failed`, and
7
+ a `review_failed` record naming no session counts as one review of class `error`. `capped` is the creates the exit kept
8
+ for the daily issue cap (0 in a dry run) and `issue_cap` the ticket's cap (SIL-B53). `attention` and the detail
9
+ document read it (CLI-B20, RDD-B7).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Mapping, Sequence
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from tempergraph.improve import digest as digestmod
19
+ from tempergraph.improve import review
20
+ from tempergraph.improve.record import _jsonl, read_findings
21
+ from tempergraph.store.layout import now_iso, run_dir
22
+
23
+ TOP = 3
24
+ FILED_OPS = frozenset({"filed", "commented"})
25
+
26
+
27
+ def _top(records: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
28
+ kept: list[dict[str, Any]] = []
29
+ for r in records: # plan order: the order the reviews ran in
30
+ if r.get("kind") != "review_done":
31
+ continue
32
+ unit = digestmod.parse_key(str(r.get("session_key")))[0]
33
+ for o in r.get("observations") or []:
34
+ if o.get("check") == "kept":
35
+ conf = o.get("confidence")
36
+ kept.append({"category": o.get("category"), "unit": unit,
37
+ "confidence": float(conf) if isinstance(conf, int | float) else None})
38
+ kept.sort(key=lambda o: -(o["confidence"] if o["confidence"] is not None else -1.0)) # stable: ties keep plan order
39
+ return kept[:TOP]
40
+
41
+
42
+ def _review_failed(records: Sequence[Mapping[str, Any]]) -> dict[str, int]:
43
+ """SIL-B24: the failed reviews by `error_class`; a record with no class counts as `error`."""
44
+ counts: dict[str, int] = {}
45
+ for r in review.failed_records(records):
46
+ cls = str(r.get("error_class") or "error") if r.get("session_key") else "error"
47
+ counts[cls] = counts.get(cls, 0) + 1
48
+ return counts
49
+
50
+
51
+ def build(root: Path, workflow: str, task_id: str, results: Sequence[Mapping[str, Any]], *,
52
+ filing: str | None = None, filing_source: str | None = None,
53
+ issue_cap: int | None = None) -> dict[str, Any]:
54
+ """The `loop_summary` record of the child that has just handled the thread's ticket (LFS-B5, LFS-B6, SIL-B52).
55
+
56
+ `capped` is the creates the exit kept for the daily cap (0 in a dry run); `issue_cap` is the ticket's value (SIL-B53)."""
57
+ records = _jsonl(run_dir(root, workflow, task_id) / "loop.jsonl")
58
+ out: dict[str, Any] = {"ts": now_iso(), "kind": "loop_summary", "thread": f"{workflow}/{task_id}",
59
+ "recorded": len(read_findings(root, workflow, task_id)),
60
+ "filed": sum(1 for r in results if r.get("op") in FILED_OPS), "top": _top(records),
61
+ "review_failed": _review_failed(records),
62
+ "capped": sum(1 for r in results if r.get("op") == "capped")}
63
+ if issue_cap is not None:
64
+ out["issue_cap"] = issue_cap
65
+ if filing is not None:
66
+ out["filing"] = filing
67
+ if filing_source is not None:
68
+ out["filing_source"] = filing_source
69
+ return out
70
+
71
+
72
+ def thread_newest(root: Path, workflow: str, task_id: str) -> dict[str, Any] | None:
73
+ """The newest `loop_summary` record of one thread, or None until a loop child has ended."""
74
+ found = [r for r in _jsonl(run_dir(root, workflow, task_id) / "loop.jsonl") if r.get("kind") == "loop_summary"]
75
+ return max(found, key=lambda r: str(r.get("ts") or "")) if found else None
76
+
77
+
78
+ def newest(root: Path, workflow: str, task_id: str | None = None) -> dict[str, Any] | None:
79
+ """The newest summary of a thread, or of the workflow when no thread is named (the latest of its threads)."""
80
+ if task_id is not None:
81
+ return thread_newest(root, workflow, task_id)
82
+ base = root / "runs" / workflow
83
+ found = [s for d in (sorted(base.iterdir()) if base.is_dir() else ()) if d.is_dir()
84
+ for s in [thread_newest(root, workflow, d.name)] if s is not None]
85
+ return max(found, key=lambda r: str(r.get("ts") or "")) if found else None
@@ -0,0 +1,119 @@
1
+ """A lost runner is a final exit (SIL-B29 to SIL-B32).
2
+
3
+ A thread whose lock is free and whose newest segment started and wrote no `run_exit` lost its runner (killed,
4
+ crashed or cut off by its caller's timeout: the engine cannot tell them apart, RDD-B14). `status`, `stop` and
5
+ `attention` call `settle` to write that segment as an exit with code 5 and reason `runner_lost`, with the records of
6
+ SIL-B8, and to hand it to the loop once per thread. The readers themselves (`durability.status`, `observe.attention`,
7
+ `observe.detail`) stay pure. The thread's run lock, taken without waiting, is the claim (DUR-B10): a verb that finds
8
+ it held skips the thread. Nothing here prints, starts a session or writes a `run_exit`.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ from collections.abc import Mapping
15
+ from datetime import UTC, datetime, timedelta
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from tempergraph.contracts import RunOptions, WorkflowSpec
20
+ from tempergraph.durability.lock import LockHeld, RunLock, is_held
21
+ from tempergraph.durability.status import Selector, _read, select, split_thread
22
+ from tempergraph.executors.registry import Registry, default_registry
23
+ from tempergraph.improve import child, params
24
+ from tempergraph.run.log import CostTotals, Ledger, RunLog
25
+ from tempergraph.store.layout import lock_path, run_dir
26
+
27
+ REASON = "runner_lost"
28
+ EXIT_CODE = 5
29
+
30
+
31
+ def _when(ts: Any) -> datetime | None:
32
+ try:
33
+ got = datetime.fromisoformat(str(ts).replace("Z", "+00:00"))
34
+ except ValueError:
35
+ return None
36
+ return got if got.tzinfo else got.replace(tzinfo=UTC)
37
+
38
+
39
+ def _lost(records: list[dict[str, Any]], now: datetime) -> dict[str, Any] | None:
40
+ """The `run_started` record of the newest segment when it has no `run_exit` and the log is inside the window."""
41
+ start = max((i for i, r in enumerate(records) if r.get("kind") == "run_started"), default=None)
42
+ if start is None or any(r.get("kind") == "run_exit" for r in records[start:]):
43
+ return None
44
+ newest = _when(records[-1].get("ts"))
45
+ days = float(params.value("lost_runner.window_days"))
46
+ if newest is None or now - newest > timedelta(days=days):
47
+ return None
48
+ return records[start]
49
+
50
+
51
+ def _recorded(rows: list[dict[str, Any]], tid: str, started: Mapping[str, Any]) -> bool:
52
+ """SIL-B30: the segment already has its `runner_lost` row: one at or after the segment's `run_started`."""
53
+ at = _when(started.get("ts"))
54
+ return any(r.get("kind") == "run_segment" and r.get("thread_id") == tid and r.get("reason") == REASON
55
+ and (at is None or (_when(r.get("ts")) or at) >= at) for r in rows)
56
+
57
+
58
+ def _settle_thread(root: Path, spec: WorkflowSpec, tid: str, registry: Registry) -> None:
59
+ from tempergraph.improve.record import record_exit
60
+ from tempergraph.run import runner
61
+
62
+ task = split_thread(tid)[1]
63
+ path = lock_path(root, spec.name, task)
64
+ log_path = run_dir(root, spec.name, task) / "run.jsonl"
65
+ now = datetime.now(UTC)
66
+ if is_held(path) or _lost(runner._log_records(log_path), now) is None:
67
+ return # a probe creates nothing: a thread with a live runner or no lost segment is left as it is
68
+ lock = RunLock(path)
69
+ try:
70
+ lock.acquire() # DUR-B10: without waiting; a verb that finds it held skips the thread
71
+ except LockHeld:
72
+ return
73
+ try:
74
+ records = runner._log_records(log_path) # read again under the lock
75
+ started = _lost(records, now)
76
+ rows = runner.ledger_rows(root)
77
+ if started is None or _recorded(rows, tid, started):
78
+ return
79
+ snap, _ = _read(root, spec, tid) # the thread's last checkpoint: its request, outputs and spend
80
+ values = snap.values or {}
81
+ cost = CostTotals.from_json((values.get("run") or {}).get("cost"))
82
+ settings = runner.RunSettings()
83
+ ledger = Ledger(path=root / "ledger.jsonl")
84
+ row = {"kind": "run_segment", "thread_id": tid, "workflow": spec.name, "workflow_version": spec.version,
85
+ **runner.join_keys(root, settings), "exit_code": EXIT_CODE, "reason": REASON, "cost": cost.to_json(),
86
+ "origin": started.get("origin") or settings.origin, "stage": runner._stage(spec, settings)[0],
87
+ "settings_digest": started.get("settings_digest"), "overridden_keys": started.get("overridden_keys"),
88
+ "grants": []}
89
+ ledger.append(row)
90
+ if ledger.failures:
91
+ return # nothing is recorded without its ledger row, so a later look tries again
92
+ written = next((r for r in reversed(runner.ledger_rows(root)) if r.get("kind") == "run_segment"
93
+ and r.get("thread_id") == tid), row)
94
+ log = RunLog(log_path)
95
+ summary = record_exit(root, spec, task, log_path, values, written)
96
+ from tempergraph.improve.reliability import after_exit
97
+
98
+ summary["labels"] = after_exit(root, spec.name, task, written)
99
+ log.write("finding_recorded", **summary)
100
+ if child.started_for(root, spec.name, task, tid, REASON): # SIL-B31: once per thread
101
+ return
102
+ judges = (started.get("executors") or {}).get("judges") or {}
103
+ snap_options = (values.get("run") or {}).get("options") or {} # as `settle_resume` reads them (PRP-B31)
104
+ options = RunOptions(settings={k: dict(v) for k, v in (snap_options.get("settings") or {}).items()},
105
+ profiles=tuple(snap_options.get("profiles") or ()))
106
+ runner.hand_to_loop(root, spec, task, tid, summary, None, registry, judges,
107
+ run_cost_usd=cost.reported + cost.estimated_only, trigger=REASON, options=options)
108
+ finally:
109
+ lock.release()
110
+
111
+
112
+ def settle(root: Path, specs: Mapping[str, WorkflowSpec], selector: str | None = None,
113
+ registry: Registry | None = None) -> None:
114
+ """Hands every lost runner of the selected threads to the loop; every failure is caught, per thread (SIL-B32)."""
115
+ with contextlib.suppress(Exception):
116
+ found = select(root, specs, Selector(value=selector))
117
+ for spec, tid in found:
118
+ with contextlib.suppress(Exception):
119
+ _settle_thread(root, spec, tid, registry or default_registry())