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,65 @@
1
+ """Pseudonymous join keys for the ledger (IMD-B5, R12): the machine id, the repository and request digests.
2
+
3
+ The machine id is the random id of `<home>/machine.json`, never a host name. The repository digest is the
4
+ SHA-256 of the normalized `origin` remote URL (no scheme, no credentials, no `.git`, lower case), cut to 16 hex;
5
+ None when the repository has no `origin`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import re
13
+ from pathlib import Path
14
+
15
+ from tempergraph.git import git
16
+ from tempergraph.store.layout import ensure_home, home_path
17
+
18
+
19
+ def machine_id(home: Path | None = None) -> str | None:
20
+ try:
21
+ h = ensure_home(home or home_path())
22
+ doc = json.loads((h / "machine.json").read_text(encoding="utf-8"))
23
+ except Exception: # noqa: BLE001 - a missing id never stops a run (OVR-B4)
24
+ return None
25
+ return str(doc.get("machine_id")) if isinstance(doc, dict) and doc.get("machine_id") else None
26
+
27
+
28
+ def normalize_remote(url: str) -> str:
29
+ u = url.strip()
30
+ scheme = re.match(r"^[a-z+]+://", u)
31
+ u = u[scheme.end():] if scheme else u
32
+ u = re.sub(r"^[^@/]+@", "", u) # user and token
33
+ if not scheme: # scp-like `host:path`
34
+ u = u.replace(":", "/", 1)
35
+ u = re.sub(r"\.git$", "", u.rstrip("/"))
36
+ return u.lower()
37
+
38
+
39
+ def repo_id(main: Path | None) -> str | None:
40
+ if main is None:
41
+ return None
42
+ url = git(["config", "--get", "remote.origin.url"], main, check=False).strip()
43
+ if not url:
44
+ return None
45
+ return hashlib.sha256(normalize_remote(url).encode()).hexdigest()[:16]
46
+
47
+
48
+ def request_digest(text: str, home: Path | None = None) -> str | None:
49
+ """IMD-B16: a keyed hash with a per-installation key, so equal requests match without the text."""
50
+ import hmac
51
+ import os
52
+ import secrets
53
+
54
+ try:
55
+ h = ensure_home(home or home_path())
56
+ key_file = h / "request_key"
57
+ if not key_file.exists():
58
+ key_file.write_text(secrets.token_hex(32), encoding="utf-8")
59
+ if os.name == "posix":
60
+ os.chmod(key_file, 0o600)
61
+ key = key_file.read_text(encoding="utf-8").strip().encode()
62
+ except OSError:
63
+ return None
64
+ norm = " ".join(text.split()).lower().encode()
65
+ return hmac.new(key, norm, hashlib.sha256).hexdigest()[:16]
@@ -0,0 +1,5 @@
1
+ """The self-improvement loop (SIL, IMD): model-free records, cause codes and lenses; filing lives apart.
2
+
3
+ The publish boundary is a file boundary: `filing` and everything it imports never open the evidence file
4
+ (SIL-B8; a source test enforces it).
5
+ """
@@ -0,0 +1,437 @@
1
+ """Cause analysis of one cluster (CAN): the record store.
2
+
3
+ Records live under the state root: `improve/analyses/<analysis_id>.json`, one per analysis, whatever its
4
+ state (`recorded`, `no_cause_found`, `refused`). Session files live in `improve/analyses/sessions/`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import shutil
12
+ import uuid
13
+ from collections.abc import Callable, Mapping, Sequence
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from tempergraph.docs import write_json
19
+ from tempergraph.improve.proposals import SIDE, Added, ProposalError, _request_shingles, literal_hits
20
+ from tempergraph.improve.review import FENCE
21
+ from tempergraph.store.layout import now_iso
22
+
23
+ ANALYSES_DIR = "improve/analyses"
24
+
25
+
26
+ def new_analysis_id() -> str:
27
+ return uuid.uuid4().hex[:12]
28
+
29
+
30
+ def analyses_dir(root: Path) -> Path:
31
+ return root / ANALYSES_DIR
32
+
33
+
34
+ def write_record(root: Path, rec: Mapping[str, Any]) -> dict[str, Any]:
35
+ out = {"schema_version": 1, **dict(rec)}
36
+ write_json(analyses_dir(root) / f"{out['analysis_id']}.json", out)
37
+ return out
38
+
39
+
40
+ def load_analysis(root: Path, analysis_id: str) -> dict[str, Any]:
41
+ if not re.match(r"^[A-Za-z0-9_-]{1,64}$", analysis_id):
42
+ raise ProposalError(f"{analysis_id!r} is not an analysis id")
43
+ path = analyses_dir(root) / f"{analysis_id}.json"
44
+ if not path.is_file():
45
+ raise ProposalError(f"no analysis {analysis_id}")
46
+ return _read(path)
47
+
48
+
49
+ def _read(path: Path) -> dict[str, Any]:
50
+ data = json.loads(path.read_text(encoding="utf-8"))
51
+ if not isinstance(data, dict):
52
+ raise ValueError(f"{path}: not a JSON object")
53
+ return data
54
+
55
+
56
+ def list_records(root: Path, workflow: str) -> list[dict[str, Any]]:
57
+ """Every readable record of the workflow; a file that cannot be read is skipped."""
58
+ out: list[dict[str, Any]] = []
59
+ d = analyses_dir(root)
60
+ if not d.is_dir():
61
+ return out
62
+ for p in sorted(d.glob("*.json")):
63
+ try:
64
+ rec = _read(p)
65
+ except Exception:
66
+ continue
67
+ if rec.get("workflow") == workflow and "analysis_id" in rec:
68
+ out.append(rec)
69
+ return out
70
+
71
+
72
+ def newest(root: Path, workflow: str, cluster_id: str) -> dict[str, Any] | None:
73
+ """The record of the cluster with the latest `at`, then the greater `analysis_id`."""
74
+ mine = [r for r in list_records(root, workflow) if r.get("cluster_id") == cluster_id]
75
+ if not mine:
76
+ return None
77
+ return max(mine, key=lambda r: (str(r.get("at", "")), str(r["analysis_id"])))
78
+
79
+
80
+ def summary(rec: Mapping[str, Any] | None) -> dict[str, Any] | None:
81
+ if rec is None:
82
+ return None
83
+ return {"analysis_id": rec["analysis_id"], "state": rec["state"]}
84
+
85
+
86
+ PLACE_WORDS = ("engine", "environment", "request")
87
+ CLASSES = frozenset(SIDE) | frozenset(PLACE_WORDS) # PRP-B14's change classes and the three place words (CAN-B18)
88
+ _KEYS = frozenset({"cause", "place", "remedy_class", "evidence", "candidates", "confidence"})
89
+ _ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class Reply:
94
+ """A readable analysis reply (CAN-B29): sentences whitespace-joined."""
95
+
96
+ cause: str
97
+ place: str
98
+ remedy_class: str
99
+ evidence: list[str]
100
+ candidates: list[dict[str, Any]]
101
+ confidence: float
102
+
103
+
104
+ @dataclass(frozen=True)
105
+ class NoCause:
106
+ """A reply that says no cause was found (CAN-B15)."""
107
+
108
+
109
+ def _sentence(v: Any) -> str | None:
110
+ if not isinstance(v, str):
111
+ return None
112
+ s = " ".join(v.split())
113
+ return s or None
114
+
115
+
116
+ def read_reply(text: str) -> Reply | NoCause | None:
117
+ """CAN-B16, CAN-B29, CAN-B18: the last fenced JSON block of a reply, or None when it cannot be read."""
118
+ blocks = FENCE.findall(text)
119
+ if not blocks:
120
+ return None
121
+ try:
122
+ d = json.loads(blocks[-1])
123
+ except ValueError:
124
+ return None
125
+ if not isinstance(d, dict):
126
+ return None
127
+ if d == {"no_cause_found": True}:
128
+ return NoCause()
129
+ if set(d) != _KEYS:
130
+ return None
131
+ cause, place, cls = _sentence(d["cause"]), _sentence(d["place"]), d["remedy_class"]
132
+ conf, ev, cands = d["confidence"], d["evidence"], d["candidates"]
133
+ if cause is None or place is None or not isinstance(cls, str):
134
+ return None
135
+ if place in PLACE_WORDS:
136
+ if cls != place:
137
+ return None
138
+ elif cls not in CLASSES or cls in PLACE_WORDS:
139
+ return None
140
+ if isinstance(conf, bool) or not isinstance(conf, (int, float)) or not 0 <= conf <= 1:
141
+ return None
142
+ if not isinstance(ev, list) or not all(isinstance(e, str) for e in ev):
143
+ return None
144
+ if not isinstance(cands, list):
145
+ return None
146
+ out: list[dict[str, Any]] = []
147
+ for c in cands:
148
+ if not isinstance(c, dict) or set(c) != {"files", "change", "test"}:
149
+ return None
150
+ files, change, test = c["files"], _sentence(c["change"]), _sentence(c["test"])
151
+ if not isinstance(files, list) or not all(isinstance(f, str) for f in files) or change is None or test is None:
152
+ return None
153
+ out.append({"files": list(files), "change": change, "test": test})
154
+ return Reply(cause=cause, place=place, remedy_class=cls, evidence=list(ev), candidates=out,
155
+ confidence=float(conf))
156
+
157
+
158
+ def _engine_side(cluster: Mapping[str, Any]) -> bool:
159
+ side = str(cluster.get("side") or "")
160
+ return side == "engine" or side.startswith("executor:")
161
+
162
+
163
+ def _line_ok(root: Path, rel: str, line: int) -> bool:
164
+ try:
165
+ base = root.resolve()
166
+ path = (base / rel).resolve()
167
+ path.relative_to(base)
168
+ if not path.is_file():
169
+ return False
170
+ return line >= 1 and len(path.read_text(encoding="utf-8").splitlines()) >= line
171
+ except (OSError, ValueError, UnicodeDecodeError):
172
+ return False
173
+
174
+
175
+ def check_citations(ids: Sequence[str], cluster: Mapping[str, Any], member_runs: Sequence[str], package_dir: Path,
176
+ engine_source: Path | None) -> list[str]:
177
+ """CAN-B8, CAN-B9, CAN-B20: the ids that fail, as written and in order; no model is called."""
178
+ findings = {str(x) for x in cluster.get("findings") or ()}
179
+ roots = [package_dir] + ([engine_source] if engine_source is not None and _engine_side(cluster) else [])
180
+ bad: list[str] = []
181
+ for i in ids:
182
+ kind, _, rest = i.partition(":")
183
+ ok = False
184
+ if kind == "finding":
185
+ ok = rest in findings
186
+ elif kind == "run":
187
+ ok = rest in member_runs
188
+ elif kind == "file":
189
+ rel, _, n = rest.rpartition(":")
190
+ ok = bool(rel) and n.isdigit() and any(_line_ok(r, rel, int(n)) for r in roots)
191
+ if not ok:
192
+ bad.append(i)
193
+ return bad
194
+
195
+
196
+ def _outside(path: str) -> bool:
197
+ return path.startswith("/") or ".." in Path(path).parts
198
+
199
+
200
+ def judge_reply(reply: Reply | NoCause, *, root: Path, workflow: str, cluster: Mapping[str, Any],
201
+ member_runs: Sequence[str], package_dir: Path, engine_source: Path | None) -> dict[str, Any]:
202
+ """CAN-B14: the record body of a reply, with at most one refusal, the first of the fixed order."""
203
+ if isinstance(reply, NoCause):
204
+ return {"state": "no_cause_found", "refusal": None, "cause": None, "place": None, "remedy_class": None,
205
+ "evidence": [], "candidates": [], "confidence": None}
206
+ body: dict[str, Any] = {"cause": reply.cause, "place": reply.place, "remedy_class": reply.remedy_class,
207
+ "evidence": list(reply.evidence), "candidates": [dict(c) for c in reply.candidates],
208
+ "confidence": reply.confidence}
209
+ file_place = reply.place not in PLACE_WORDS
210
+ refusal: str | None = None
211
+ missing: list[str] = []
212
+ if not 1 <= len(reply.candidates) <= 3:
213
+ refusal = "candidates"
214
+ elif not reply.evidence or (file_place and any(not c["files"] for c in reply.candidates)):
215
+ refusal = "uncited"
216
+ else:
217
+ missing = check_citations(reply.evidence, cluster, member_runs, package_dir, engine_source)
218
+ if missing:
219
+ refusal = "citation_missing"
220
+ elif (file_place and _outside(reply.place)) or any(_outside(f) for c in reply.candidates for f in c["files"]):
221
+ refusal = "outside_package"
222
+ else:
223
+ sentences = [reply.cause, *(s for c in reply.candidates for s in (c["change"], c["test"]))]
224
+ shingles = _request_shingles(root, workflow, [f"{workflow}/{r}" for r in member_runs])
225
+ added = [Added(file="reply", text=s, ranges=((0, len(s)),)) for s in sentences]
226
+ if literal_hits(added, shingles):
227
+ refusal = "literal"
228
+ if refusal is None:
229
+ return {"state": "recorded", "refusal": None, **body}
230
+ out = {"state": "refused", "refusal": refusal, **body}
231
+ if refusal == "citation_missing":
232
+ out["missing"] = missing
233
+ return out
234
+
235
+
236
+ class AnalysisRefused(ValueError):
237
+ """The verb refuses before any session or write: an unknown cluster, no package folder, a zero cap."""
238
+
239
+
240
+ REASK_SUFFIX = "End with the JSON block only."
241
+ reask_suffix = REASK_SUFFIX # CAN-B16: appended to the prompt of the one re-ask
242
+ READ_TOOLS = ("read", "search", "list") # CAN-B5: no tool that writes or runs a command
243
+ _REPLY_SHAPE = (
244
+ '{"cause": "<one sentence>", "place": "<a package path, or engine, environment or request>", '
245
+ '"remedy_class": "<a change class of the package files, or the place word>", '
246
+ '"evidence": ["finding:<fingerprint>", "run:<run>", "file:<path>:<line>"], '
247
+ '"candidates": [{"files": ["<package path>"], "change": "<one sentence>", "test": "<one sentence>"}], '
248
+ '"confidence": <0 to 1>}'
249
+ )
250
+
251
+
252
+ def build_prompt(cluster: Mapping[str, Any], findings: Sequence[Mapping[str, Any]], member_runs: Sequence[str],
253
+ observations: str, citable: Sequence[str]) -> str:
254
+ """CAN-B7: the cluster's facts, each member finding and run, the kept observations (datamarked), the citable ids."""
255
+ facts = (f"- cause: {cluster.get('cause')}\n- unit: {cluster.get('unit')}\n- side: {cluster.get('side')}\n"
256
+ f"- runs: {cluster.get('runs')}, distinct requests: {cluster.get('distinct_requests')}\n"
257
+ f"- findings: {len(findings)}\n")
258
+ lines = "\n".join(json.dumps(dict(f), sort_keys=True, default=str) for f in findings)
259
+ return (
260
+ "You find the cause of one cluster of findings the engine recorded across runs of a workflow. Your folder is "
261
+ "the workflow package; you may read, search and list files, and nothing else. Do not change any file.\n\n"
262
+ f"## Cluster\n{facts}\n## Member findings\n{lines}\n\n## Member runs\n" + "\n".join(member_runs) + "\n"
263
+ + observations
264
+ + "\n## Evidence you may cite\n" + "\n".join(citable)
265
+ + "\nand `file:<path>:<line>` for a line of a file you read (a path inside the package; for a cluster of the "
266
+ "engine or an executor, a line of the engine's source folder). Every id is checked by the engine.\n\n"
267
+ "## Reply\nName one cause, where it lies, and one to three candidate changes (never a ticket id, URL, number or "
268
+ "quotation from a run). Cite at least one id. End with one fenced JSON block (three backticks, `json`) of this "
269
+ f"shape:\n{_REPLY_SHAPE}\nor, when no cause can be shown, {{\"no_cause_found\": true}}. Only the last "
270
+ "fenced block is read.\n")
271
+
272
+
273
+ def _covered(package: Path) -> list[Path]:
274
+ """The files `package_digest` covers, as paths relative to the package."""
275
+ out: list[Path] = []
276
+ for p in sorted(package.rglob("*")):
277
+ rel = p.relative_to(package)
278
+ if p.is_file() and rel.parts[0] not in ("evals", ".git") and "__pycache__" not in rel.parts:
279
+ out.append(rel)
280
+ return out
281
+
282
+
283
+ def _guarded(package_dir: Path, session_dir: Path, run: Callable[[], Any]) -> tuple[Any, Exception | None, bool]:
284
+ """CAN-B6, CAN-B30: run a session with a copy of the covered files kept; whatever happens, restore them (a changed
285
+ file rewritten, a created one removed), and report whether the digest differed."""
286
+ from tempergraph.improve.proposals import package_digest
287
+
288
+ before = session_dir / "before"
289
+ digest = package_digest(package_dir)
290
+ kept = _covered(package_dir)
291
+ for rel in kept:
292
+ (before / rel).parent.mkdir(parents=True, exist_ok=True)
293
+ (before / rel).write_bytes((package_dir / rel).read_bytes())
294
+ res: Any = None
295
+ err: Exception | None = None
296
+ changed = False
297
+ try:
298
+ try:
299
+ res = run()
300
+ except Exception as exc: # noqa: BLE001 - a failed session is a record, and the package is restored below
301
+ err = exc
302
+ changed = package_digest(package_dir) != digest
303
+ finally:
304
+ keep = set(kept)
305
+ for rel in _covered(package_dir):
306
+ if rel not in keep:
307
+ (package_dir / rel).unlink()
308
+ for parent in (package_dir / rel).parents:
309
+ if parent == package_dir or any(parent.iterdir()):
310
+ break
311
+ parent.rmdir()
312
+ for rel in kept:
313
+ want = (before / rel).read_bytes()
314
+ target = package_dir / rel
315
+ if not target.is_file() or target.read_bytes() != want:
316
+ target.parent.mkdir(parents=True, exist_ok=True)
317
+ target.write_bytes(want)
318
+ shutil.rmtree(before, ignore_errors=True)
319
+ return res, err, changed
320
+
321
+
322
+ @dataclass
323
+ class Asked:
324
+ """What `ask` saw: the readable reply (or none), the failure, the spend, and whether the package changed."""
325
+
326
+ reply: Reply | NoCause | None
327
+ failure: dict[str, Any] | None
328
+ spend: dict[str, Any]
329
+ changed: bool
330
+
331
+
332
+ def ask(*, executor: Any, prompt: str, package_dir: Path, session_root: Path, analysis_id: str, cap: float,
333
+ read_roots: tuple[Path, ...]) -> Asked:
334
+ """CAN-B16, CAN-B25, CAN-B27, CAN-B31: at most two sessions; each gets what the cap leaves."""
335
+ from tempergraph.contracts import EventSink, SessionOptions, SessionRequest
336
+ from tempergraph.improve.review import ALIAS, EFFORT, TIMEOUT_S, _failure_class
337
+ from tempergraph.run.log import estimate
338
+
339
+ spend: dict[str, Any] = {"sessions": 0, "reported_cost_usd": 0.0, "estimated_cost_usd": 0.0}
340
+ takes_cap = "cost_cap_usd" in executor.capabilities().session_options
341
+ failure: dict[str, Any] | None = None
342
+ for n in (1, 2):
343
+ left = cap - spend["reported_cost_usd"] - spend["estimated_cost_usd"]
344
+ if left <= 1e-9:
345
+ return Asked(None, {"error_class": "cap_reached"}, spend, False)
346
+ sdir = session_root / f"{analysis_id}.{n}"
347
+ sdir.mkdir(parents=True, exist_ok=True)
348
+ req = SessionRequest(
349
+ kind="step", prompt=prompt if n == 1 else f"{prompt}\n\n{REASK_SUFFIX}", workdir=package_dir,
350
+ alias=ALIAS, session_key=f"analyse.{analysis_id}.{n}.step", tools=READ_TOOLS, timeout_s=TIMEOUT_S,
351
+ session_dir=sdir, enforce_tools=True, read_roots=read_roots,
352
+ options=SessionOptions(effort=EFFORT, cost_cap_usd=left if takes_cap else None)) # type: ignore[arg-type]
353
+ def session(r: SessionRequest = req) -> Any:
354
+ return executor.run_step(r, EventSink())
355
+
356
+ res, err, changed = _guarded(package_dir, sdir, session)
357
+ spend["sessions"] += 1
358
+ if res is not None:
359
+ if res.usage.reported_cost_usd is not None:
360
+ spend["reported_cost_usd"] += float(res.usage.reported_cost_usd)
361
+ else:
362
+ spend["estimated_cost_usd"] += float(res.usage.estimated_cost_usd or estimate(res.usage, res.model) or 0.0)
363
+ if changed:
364
+ return Asked(None, None, spend, True)
365
+ if err is not None or res is None:
366
+ return Asked(None, {"error_class": "error"}, spend, False)
367
+ if not res.ok:
368
+ return Asked(None, {"error_class": _failure_class(res)}, spend, False)
369
+ reply = read_reply(res.text or "")
370
+ if reply is not None:
371
+ return Asked(reply, None, spend, False)
372
+ failure = {"error_class": "unparsed"}
373
+ return Asked(None, failure, spend, False)
374
+
375
+
376
+ def _empty_body() -> dict[str, Any]:
377
+ return {"cause": None, "place": None, "remedy_class": None, "evidence": [], "candidates": [], "confidence": None}
378
+
379
+
380
+ def analyse(root: Path, spec: Any, cluster_id: str, executor: Any, engine_source: Path | None = None) -> dict[str, Any]:
381
+ """CAN-B1 to CAN-B31: one read-only session on one cluster and the checked record, written under `improve/analyses/`.
382
+ No code host is called; nothing outside the record and its session folder is written."""
383
+ from tempergraph.constants import EXECUTOR_NAMES
384
+ from tempergraph.improve import params
385
+ from tempergraph.improve import proposals as prp
386
+
387
+ wf = spec.name
388
+ ex_name = getattr(executor, "name", None)
389
+ if ex_name not in EXECUTOR_NAMES:
390
+ raise AnalysisRefused(f"improve analyse: unknown executor {ex_name!r}")
391
+ try:
392
+ cl = prp.cluster(root, wf, cluster_id)
393
+ except ProposalError as exc:
394
+ raise AnalysisRefused(str(exc)) from exc
395
+ pkg = spec.package_root
396
+ if pkg is None or not Path(pkg).is_dir():
397
+ raise AnalysisRefused(f"improve analyse: {wf} has no package folder")
398
+ pkg = Path(pkg)
399
+ cap = float(params.value("analysis.cap_usd"))
400
+ if cap <= 0:
401
+ raise AnalysisRefused("improve analyse: analysis.cap_usd is 0, so no session starts")
402
+ listed = next((c for c in prp.clusters(root, wf) if cluster_id in (c["cluster_id"], c.get("twin_of"))), cl)
403
+ fps = {str(x) for x in cl.get("findings") or ()}
404
+ findings = [f for f in prp._findings(root, wf) if str(f.get("fingerprint")) in fps]
405
+ runs = prp._member_runs(root, wf, cl)
406
+ citable = [f"finding:{fp}" for fp in sorted(fps)] + [f"run:{r}" for r in runs]
407
+ engine_side = _engine_side(cl)
408
+ src: Path | None = None
409
+ if engine_side:
410
+ src = Path(engine_source) if engine_source is not None else Path(__file__).resolve().parents[1]
411
+ prompt = build_prompt(cl, findings, runs, prp._observations_block(root, wf, cl), citable)
412
+ aid = new_analysis_id()
413
+ got = ask(executor=executor, prompt=prompt, package_dir=pkg, session_root=analyses_dir(root) / "sessions",
414
+ analysis_id=aid, cap=cap, read_roots=(src,) if src is not None else ())
415
+ head = {"analysis_id": aid, "workflow": wf, "cluster_id": listed["cluster_id"], "base_version": spec.version,
416
+ "author": "person", "spend": got.spend}
417
+ if got.changed:
418
+ rec = base_record(state="refused", refusal="changed_package", **head, **_empty_body())
419
+ elif got.reply is not None:
420
+ body = judge_reply(got.reply, root=root, workflow=wf, cluster=cl, member_runs=runs, package_dir=pkg,
421
+ engine_source=src)
422
+ rec = base_record(**head, **body)
423
+ elif got.failure is not None and got.failure["error_class"] == "unparsed":
424
+ rec = base_record(state="refused", refusal="unparsed", **head, **_empty_body())
425
+ else:
426
+ rec = base_record(state="refused", refusal="session_failed", error_class=(got.failure or {}).get("error_class"),
427
+ **head, **_empty_body())
428
+ return write_record(root, rec)
429
+
430
+
431
+ def base_record(*, analysis_id: str, workflow: str, cluster_id: str | None, base_version: str, author: str,
432
+ state: str, refusal: str | None, spend: Mapping[str, Any],
433
+ **extra: Any) -> dict[str, Any]:
434
+ """The body every record holds, whatever its state (CAN-B17); `extra` adds the state's own fields."""
435
+ return {"analysis_id": analysis_id, "workflow": workflow, "cluster_id": cluster_id,
436
+ "base_version": base_version, "author": author, "at": now_iso(), "state": state,
437
+ "refusal": refusal, "spend": dict(spend), **extra}