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,625 @@
1
+ """`tempergraph upgrade <workflow>` beyond `--check`: baseline, plan, transforms on a branch, verification and
2
+ the finish (WUP-B14, WUP-B7, WUP-B20, WUP-B21). Model-free; the assisted and owner items go to a caller-given assist step
3
+ (the built-in upgrade workflow, UWF), which is the only part that may start a session.
4
+
5
+ Nothing here touches the person's checkout: the changes are commits on `tempergraph/upgrade/<workflow>/<engine>`
6
+ in a worktree of its own, and the record is `upgrades/<upgrade_id>/` under the source repository's state root.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import fnmatch
12
+ import json
13
+ import shutil
14
+ from collections.abc import Callable, Mapping, Sequence
15
+ from dataclasses import asdict, dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from tempergraph import git as gitmod
20
+ from tempergraph.constants import ENGINE_VERSION
21
+ from tempergraph.contracts import Capabilities, WorkflowSpec
22
+ from tempergraph.docs import write_json
23
+ from tempergraph.model.diagram import diagram_model, to_mermaid
24
+ from tempergraph.model.validate import Finding, validate
25
+ from tempergraph.package import transforms
26
+ from tempergraph.package.changelog import children_entries, detect, entries_between, semver
27
+ from tempergraph.package.inventory import canonical
28
+ from tempergraph.package.loader import LoadedPackage, PackageNotLoaded, load_package
29
+ from tempergraph.package.registry import plugin_cache
30
+ from tempergraph.package.stamp import STAMP, Verification, _audit_keys, _entries_applied, read_stamp, tool_set
31
+ from tempergraph.store.layout import ensure_state_root, now_iso, state_root_path
32
+
33
+ BRANCH_PREFIX = "tempergraph/upgrade"
34
+ ASSIST_DIR = ".tempergraph-upgrade" # the assist run's inputs at the worktree root; never committed
35
+ PROTECTED_DEFAULT = ("units.*.gate.criteria*", "units.*.gate.judge.stance*", "outcome.json", "workflow/*/checks*.py",
36
+ "judges/*")
37
+
38
+
39
+ def is_open(item: Any) -> bool:
40
+ """Still owed: pending, or failed with no successor (a failed transform hands its hits to a `/rest` item)."""
41
+ return item.state == "pending" or (item.state == "failed" and item.action != "transform")
42
+ COMMIT = ["-c", "user.name=tempergraph", "-c", "user.email=engine@localhost", "commit", "-q", "-m"]
43
+
44
+
45
+ class UpgradeRefused(Exception):
46
+ """Exit 2: an unknown or installed workflow, a dirty source, a branch that is not this upgrade's."""
47
+
48
+
49
+ @dataclass(kw_only=True)
50
+ class Item:
51
+ item_id: str
52
+ entry: str
53
+ action: str # transform, assisted, owner, manual, none
54
+ hits: list[dict[str, Any]] = field(default_factory=list)
55
+ protected: bool = False
56
+ state: str = "pending" # pending, done, failed, skipped, answered
57
+ by: str | None = None # transform, model, person
58
+ note: str = ""
59
+ ask: str = "" # the assisted instruction or the owner's question
60
+ reason: str = ""
61
+
62
+
63
+ @dataclass(kw_only=True)
64
+ class Report:
65
+ workflow: str
66
+ upgrade_id: str = ""
67
+ exit_code: int = 0
68
+ refused: str = ""
69
+ from_engine: str | None = None
70
+ to_engine: str = ENGINE_VERSION
71
+ from_version: str = ""
72
+ proposed: dict[str, Any] = field(default_factory=dict)
73
+ items: list[Item] = field(default_factory=list)
74
+ not_touched: list[str] = field(default_factory=list)
75
+ checks: list[Verification] = field(default_factory=list)
76
+ baseline_errors: list[str] = field(default_factory=list)
77
+ shares: dict[str, Any] = field(default_factory=dict)
78
+ notes: dict[str, str] = field(default_factory=dict)
79
+ warnings: list[str] = field(default_factory=list)
80
+ stale: list[str] = field(default_factory=list)
81
+ shape_changed: list[str] = field(default_factory=list)
82
+ classes: list[str] = field(default_factory=list)
83
+ branch: str = ""
84
+ worktree: str = ""
85
+ commits: list[dict[str, str]] = field(default_factory=list)
86
+ assist: dict[str, Any] = field(default_factory=dict)
87
+ stamp: dict[str, Any] | None = None
88
+ pull_request: str | None = None
89
+
90
+ def to_json(self) -> dict[str, Any]:
91
+ doc = asdict(self)
92
+ doc["schema_version"] = 1
93
+ doc["verification"] = doc.pop("checks")
94
+ return doc
95
+
96
+
97
+ @dataclass(kw_only=True)
98
+ class Assist:
99
+ """What the assist step is given: the upgrade's record, the package on the branch and the open items."""
100
+
101
+ upgrade_id: str
102
+ record: Path
103
+ worktree: Path
104
+ package: Path
105
+ items: list[Item]
106
+ cap_usd: float
107
+ executor: str | None
108
+ entries: Mapping[str, Mapping[str, Any]] = field(default_factory=dict)
109
+ base: Mapping[str, Any] = field(default_factory=dict)
110
+ protected: tuple[str, ...] = ()
111
+
112
+
113
+ AssistFn = Callable[[Assist], Mapping[str, Any]]
114
+
115
+
116
+ # -- where it works (WUP-B14, WUP-B7) ----------------------------------------------------------------------------------
117
+
118
+
119
+ @dataclass(kw_only=True)
120
+ class Place:
121
+ package: Path
122
+ repo: Path
123
+ rel: str # the package folder inside the repository, posix; "" when it is the repository
124
+ record: Path
125
+ branch: str
126
+ worktree: Path
127
+ upgrade_id: str
128
+
129
+
130
+ def locate(path: Path, workflow: str, engine: str = ENGINE_VERSION) -> Place:
131
+ root = path.resolve()
132
+ if root.is_relative_to(plugin_cache().resolve()):
133
+ raise UpgradeRefused(f"upgrade the workflow's source; this is an installed copy ({root}). Clone the "
134
+ "plugin's repository and register that folder")
135
+ repo = gitmod.toplevel(root)
136
+ if repo is None:
137
+ raise UpgradeRefused(f"upgrade the workflow's source; {root} is not inside a git repository")
138
+ repo = repo.resolve()
139
+ rel = root.relative_to(repo).as_posix()
140
+ upgrade_id = f"{workflow}-{engine}"
141
+ from tempergraph.workspace import sibling_root
142
+
143
+ return Place(package=root, repo=repo, rel="" if rel == "." else rel,
144
+ record=state_root_path(repo) / "upgrades" / upgrade_id, branch=f"{BRANCH_PREFIX}/{workflow}/{engine}",
145
+ worktree=sibling_root(repo) / f"upgrade--{workflow}--{engine}", upgrade_id=upgrade_id)
146
+
147
+
148
+ def _branch_exists(repo: Path, branch: str) -> bool:
149
+ return bool(gitmod.git(["rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], repo, check=False).strip())
150
+
151
+
152
+ def _dirty(place: Place) -> list[str]:
153
+ out = gitmod.git(["status", "--porcelain=v1", "--untracked-files=all", "--", place.rel or "."], place.repo)
154
+ return [ln[3:] for ln in out.splitlines() if ln.strip()]
155
+
156
+
157
+ # -- baseline and plan (WUP-B15, WUP-B16) -------------------------------------------------------------------------------
158
+
159
+
160
+ def _finding_key(f: Finding) -> str:
161
+ return f"{f.severity}|{f.code}|{f.unit or ''}"
162
+
163
+
164
+ def _suites(spec: WorkflowSpec) -> list[str]:
165
+ from tempergraph.improve.suites import green_model_free
166
+
167
+ return green_model_free(spec)
168
+
169
+
170
+ def baseline(lp: LoadedPackage, caps: Mapping[str, Capabilities]) -> dict[str, Any]:
171
+ found = validate(lp.spec, caps)
172
+ model = diagram_model(lp.spec)
173
+ return {"schema_version": 1, "taken_at": now_iso(), "engine_version": ENGINE_VERSION,
174
+ "workflow_version": lp.workflow_version, "version": lp.manifests.version,
175
+ "validation": [{"severity": f.severity, "code": f.code, "unit": f.unit, "message": f.message}
176
+ for f in found],
177
+ "validation_keys": sorted({_finding_key(f) for f in found}),
178
+ "audit": _audit_keys(lp, caps), "suites_failing": _suites(lp.spec),
179
+ "shape_digest": model["digest"], "units": sorted(lp.spec.units), "parse": canonical(lp.spec)}
180
+
181
+
182
+ def _protected(spec: WorkflowSpec, hits: Sequence[Mapping[str, Any]]) -> bool:
183
+ policy = dict(spec.upgrade or {})
184
+ globs = tuple(policy.get("protected") or PROTECTED_DEFAULT)
185
+ return any(fnmatch.fnmatchcase(str(h.get("where") or "").rsplit(":", 1)[0], g)
186
+ or fnmatch.fnmatchcase(str(h.get("where") or ""), g) for h in hits for g in globs)
187
+
188
+
189
+ def plan(lp: LoadedPackage, entries: Sequence[Mapping[str, Any]], codes: set[str], *, no_assist: bool = False
190
+ ) -> tuple[list[Item], list[str], dict[str, str]]:
191
+ items: list[Item] = []
192
+ untouched: list[str] = []
193
+ notes: dict[str, str] = {}
194
+ assist_off = no_assist or (lp.spec.upgrade or {}).get("assist") == "off"
195
+ for e in entries:
196
+ eid = str(e["id"])
197
+ hits = [h.__dict__ for h in detect(e, lp.spec, lp.root, codes)]
198
+ if not hits:
199
+ untouched.append(eid)
200
+ continue
201
+ mig = dict(e.get("migrate") or {})
202
+ action = str(mig.get("action") or "none")
203
+ protected = _protected(lp.spec, hits)
204
+ if action == "assisted" and protected:
205
+ action = "owner"
206
+ if action == "assisted" and assist_off:
207
+ action = "manual"
208
+ notes[eid] = str(e.get("note") or "")
209
+ items.append(Item(item_id=eid, entry=eid, action=action, hits=hits, protected=protected,
210
+ note=str(e.get("note") or ""), state="done" if action == "none" else "pending",
211
+ ask=str(mig.get("instruction") or mig.get("question") or mig.get("reason") or "")))
212
+ return items, untouched, notes
213
+
214
+
215
+ # -- transforms (WUP-B17) --------------------------------------------------------------------------------------
216
+
217
+
218
+ def _outside(place: Place) -> list[str]:
219
+ """Changed paths of the worktree that lie outside the package folder (WUP-B14, WUP-B7 scope)."""
220
+ out = gitmod.git(["status", "--porcelain=v1", "--untracked-files=all"], place.worktree)
221
+ paths = [ln[3:].split(" -> ")[-1].strip('"') for ln in out.splitlines() if ln.strip()]
222
+ prefix = place.rel + "/" if place.rel else ""
223
+ return [p for p in paths if prefix and not p.startswith((prefix, ASSIST_DIR + "/"))]
224
+
225
+
226
+ def _discard(place: Place) -> None:
227
+ gitmod.git(["checkout", "-q", "--", "."], place.worktree, check=False)
228
+ gitmod.git(["clean", "-fdq"], place.worktree, check=False)
229
+
230
+
231
+ def _commit(place: Place, message: str) -> str | None:
232
+ gitmod.git(["add", "-A", "--", place.rel or "."], place.worktree)
233
+ if not gitmod.git(["diff", "--cached", "--name-only"], place.worktree).strip():
234
+ return None
235
+ gitmod.git([*COMMIT, message], place.worktree)
236
+ return gitmod.git(["rev-parse", "HEAD"], place.worktree).strip()
237
+
238
+
239
+ def _pkg(place: Place) -> Path:
240
+ return place.worktree / place.rel if place.rel else place.worktree
241
+
242
+
243
+ def _still_hit(entry: Mapping[str, Any], pkg: Path, caps: Mapping[str, Capabilities]) -> list[dict[str, Any]] | None:
244
+ """The entry's hits in the package as it now is; None when it no longer loads."""
245
+ try:
246
+ lp = load_package(pkg)
247
+ except PackageNotLoaded:
248
+ return None
249
+ codes = {f.code for f in validate(lp.spec, caps)}
250
+ hits = [h.__dict__ for h in detect(entry, lp.spec, lp.root, codes)]
251
+ raised = sorted(codes & {str(c) for c in entry.get("proof") or []})
252
+ return hits + [{"entry": str(entry.get("id")), "rule": c, "where": f"finding:{c}", "confidence": "high"}
253
+ for c in raised if not any(h["where"] == f"finding:{c}" for h in hits)]
254
+
255
+
256
+ def apply_transforms(place: Place, rep: Report, entries: Mapping[str, Mapping[str, Any]],
257
+ caps: Mapping[str, Capabilities], workflow: str) -> None:
258
+ """One commit per changelog entry, oldest release first; each entry's rules run again afterwards."""
259
+ pkg = _pkg(place)
260
+ for it in [i for i in rep.items if i.action == "transform" and i.state == "pending"]:
261
+ entry = entries[it.entry]
262
+ owner: list[dict[str, Any]] = []
263
+ try:
264
+ res = transforms.apply(pkg, dict(entry.get("migrate") or {}))
265
+ owner = res.owner
266
+ if _outside(place):
267
+ raise transforms.TransformError("the transform changed a path outside the package")
268
+ except (transforms.TransformError, SyntaxError, OSError) as exc:
269
+ _discard(place)
270
+ it.state, it.reason = "failed", f"{type(exc).__name__}: {exc}"
271
+ rest: list[dict[str, Any]] | None = it.hits
272
+ else:
273
+ sha = _commit(place, f"upgrade({workflow}): {it.entry} {entry.get('subject') or ''}".strip())
274
+ if sha:
275
+ rep.commits.append({"entry": it.entry, "commit": sha})
276
+ rest = _still_hit(entry, pkg, caps)
277
+ if rest:
278
+ it.state, it.reason = "failed", "the entry's detect rules still hit after the transform"
279
+ elif rest is None:
280
+ it.state, it.reason = "failed", "the package no longer loads after the transform"
281
+ else:
282
+ it.state, it.by = "done", "transform"
283
+ if it.state == "failed":
284
+ rep.items.append(Item(item_id=f"{it.entry}/rest", entry=it.entry, action="assisted", hits=rest or it.hits,
285
+ protected=it.protected, note=it.note,
286
+ ask=f"The transform could not finish this change ({it.reason}). "
287
+ + str(entry.get("note") or "")))
288
+ for n, o in enumerate(owner, 1):
289
+ rep.items.append(Item(item_id=f"{it.entry}/owner-{n}", entry=it.entry, action="owner", note=it.note,
290
+ hits=[{"entry": it.entry, "rule": "transform", "where": str(o.get("where")),
291
+ "confidence": "high"}],
292
+ ask=f"{o.get('question')} (it was {o.get('was')})"))
293
+
294
+
295
+ # -- verification (WUP-B19) ------------------------------------------------------------------------------------
296
+
297
+
298
+ def _reconcile(rep: Report, entries: Mapping[str, Mapping[str, Any]], pkg: Path,
299
+ caps: Mapping[str, Capabilities], continuing: bool) -> None:
300
+ """Before verifying: an open item whose entry no longer hits was fixed by hand. An owner item left without
301
+ an assist step is answered by the person who continues the upgrade (`--continue`), never by a first run."""
302
+ for it in rep.items:
303
+ if not is_open(it) or it.entry not in entries or it.action not in ("assisted", "manual", "owner"):
304
+ continue
305
+ if it.action == "owner" and not continuing:
306
+ continue
307
+ if _still_hit(entries[it.entry], pkg, caps) == []:
308
+ it.state, it.by = ("answered" if it.action == "owner" else "done"), "person"
309
+
310
+
311
+ def verify(place: Place, rep: Report, base: Mapping[str, Any], entries: Mapping[str, Mapping[str, Any]],
312
+ caps: Mapping[str, Capabilities], before: WorkflowSpec | None) -> LoadedPackage | None:
313
+ """V1 to V7 in order; the first failure stops the list. Returns the loaded package when all passed."""
314
+ pkg = _pkg(place)
315
+ rep.checks = []
316
+
317
+ def add(check: str, ok: bool, evidence: str) -> bool:
318
+ rep.checks.append(Verification(check=check, state="passed" if ok else "failed", evidence=evidence[:600]))
319
+ return ok
320
+
321
+ try:
322
+ lp = load_package(pkg)
323
+ except PackageNotLoaded as exc:
324
+ add("V1 load", False, str(exc))
325
+ return None
326
+ add("V1 load", True, lp.workflow_version)
327
+ found = validate(lp.spec, caps)
328
+ known = set(base.get("validation_keys") or [])
329
+ new = sorted({_finding_key(f) for f in found if f.severity in ("error", "warning")} - known)
330
+ if not add("V2 validation", not new, f"new findings: {', '.join(new)}" if new else
331
+ f"no error or warning the baseline lacks ({len(found)} findings)"):
332
+ return None
333
+ codes = {f.code for f in found}
334
+ open_items = [i.item_id for i in rep.items if i.action != "none" and is_open(i)]
335
+ unproven = []
336
+ for it in rep.items:
337
+ if it.state == "done" and it.entry in entries and it.action != "none":
338
+ e = entries[it.entry]
339
+ left = detect(e, lp.spec, lp.root, codes)
340
+ raised = sorted(codes & {str(c) for c in e.get("proof") or []})
341
+ if left or raised:
342
+ unproven.append(f"{it.item_id}: {', '.join(raised) or str(len(left)) + ' hits'}")
343
+ if not add("V3 proof", not open_items and not unproven,
344
+ "; ".join(([f"items not done: {', '.join(open_items)}"] if open_items else []) + unproven)
345
+ or "every done item's rules and proof codes are clear"):
346
+ return None
347
+ audit_now = _audit_keys(lp, caps)
348
+ added = sorted(set(audit_now) - set(base.get("audit") or []))
349
+ if not add("V4 audit", not added, f"new findings: {', '.join(added)}" if added else
350
+ f"no finding at warning or above that the baseline lacks ({len(audit_now)} known)"):
351
+ return None
352
+ classes: list[str] = []
353
+ details: list[str] = []
354
+ if before is not None:
355
+ from tempergraph.improve.proposals import classify
356
+
357
+ got = classify(before, lp.spec)
358
+ classes = list(got.classes)
359
+ rep.classes = classes
360
+ details = [f"{d.get('class')}: {d.get('where')} {d.get('what')}" for d in got.details]
361
+ answered = [i for i in rep.items if i.action == "owner" and i.state == "answered"]
362
+ by_model_protected = [i.item_id for i in rep.items if i.by == "model" and i.protected]
363
+ weak_ok = "weakening" not in classes or bool(answered)
364
+ if not add("V5 change classes", weak_ok and not by_model_protected,
365
+ ("a weakening no owner item answered: " + "; ".join(d for d in details if d.startswith("weakening")))
366
+ if not weak_ok else ("a protected path changed by the model: " + ", ".join(by_model_protected))
367
+ if by_model_protected else (", ".join(classes) or "no change of a class")
368
+ + ("; weakening approved by the owner" if "weakening" in classes else "")):
369
+ return None
370
+ was_red = set(base.get("suites_failing") or [])
371
+ red = _suites(lp.spec)
372
+ worse = sorted(set(red) - was_red)
373
+ if not add("V6 suites", not worse, "; ".join(worse) if worse else
374
+ (f"pre-existing failures: {len(was_red)}" if was_red else "model-free suites pass")):
375
+ return None
376
+ model = diagram_model(lp.spec)
377
+ write_json(pkg / "diagram" / "model.json", model, mode=0o644)
378
+ (pkg / "diagram" / "workflow.md").write_text("```mermaid\n" + to_mermaid(model) + "\n```\n", encoding="utf-8")
379
+ sha = _commit(place, f"upgrade({lp.spec.name}): regenerate the diagram")
380
+ if sha:
381
+ rep.commits.append({"entry": "diagram", "commit": sha})
382
+ if model["digest"] != base.get("shape_digest"):
383
+ was, now = set(base.get("units") or []), set(lp.spec.units)
384
+ rep.shape_changed = [f"+{u}" for u in sorted(now - was)] + [f"-{u}" for u in sorted(was - now)] or ["edges"]
385
+ add("V7 diagram", True, "shape changed: " + ", ".join(rep.shape_changed) if rep.shape_changed else "shape unchanged")
386
+ if lp.workflow_version != base.get("workflow_version"):
387
+ rep.stale = ["rubric scores and judge acceptance recorded for the earlier content are stale"]
388
+ return load_package(pkg)
389
+
390
+
391
+ # -- finish (WUP-B20, WUP-B21) ------------------------------------------------------------------------------------------
392
+
393
+
394
+ def propose(rep: Report, base: Mapping[str, Any], lp: LoadedPackage, classes: Sequence[str] = ()) -> dict[str, Any]:
395
+ was = dict(base.get("parse") or {})
396
+ now = canonical(lp.spec)
397
+ gone_units = set(was.get("units") or {}) - set(now.get("units") or {})
398
+ old_in = {p.get("name") for p in ((was.get("input") or {}).get("parameters") or [])}
399
+ new_in = {p.get("name") for p in ((now.get("input") or {}).get("parameters") or [])}
400
+
401
+ def keys(doc: Mapping[str, Any]) -> set[str]:
402
+ return {f"{u}.{k}" for u, d in (doc.get("units") or {}).items()
403
+ for k in (((d or {}).get("step") or {}).get("produces") or {})}
404
+
405
+ if gone_units or (old_in - new_in) or (keys(was) - keys(now)):
406
+ level = "major"
407
+ elif any(i.by in ("model", "person") for i in rep.items) or (new_in - old_in) or classes:
408
+ level = "minor"
409
+ else:
410
+ level = "patch"
411
+ major, minor, patch = semver(str(base.get("version") or "0.0.0"))
412
+ new = {"major": f"{major + 1}.0.0", "minor": f"{major}.{minor + 1}.0", "patch": f"{major}.{minor}.{patch + 1}"}[level]
413
+ emajor = semver(rep.to_engine)[0]
414
+ return {"level": level, "version": new, "requires_engine": f">={rep.to_engine},<{emajor + 1}"}
415
+
416
+
417
+ def _bump(place: Place, rep: Report, lp: LoadedPackage) -> None:
418
+ pkg = _pkg(place)
419
+ manifest = pkg / ".claude-plugin" / "plugin.json"
420
+ doc = json.loads(manifest.read_text(encoding="utf-8"))
421
+ doc["version"] = rep.proposed["version"]
422
+ write_json(manifest, doc, mode=0o644)
423
+ if rep.proposed["level"] in ("major", "minor"):
424
+ done = [i for i in rep.items if i.state in ("done", "answered") and i.action != "none"]
425
+ write_json(pkg / "changes" / f"{rep.proposed['version']}.json", {
426
+ "schema_version": 1, "version": rep.proposed["version"], "draft": True,
427
+ "entries": [{"entry": i.entry, "by": i.by, "note": i.note} for i in done]}, mode=0o644)
428
+ sha = _commit(place, f"upgrade({lp.spec.name}): version {rep.proposed['version']}")
429
+ if sha:
430
+ rep.commits.append({"entry": "version", "commit": sha})
431
+
432
+
433
+ def _stamp(place: Place, rep: Report, lp: LoadedPackage, base: Mapping[str, Any], caps: Mapping[str, Capabilities],
434
+ entry_ids: Sequence[str]) -> None:
435
+ by = {i.entry: i.by or "none" for i in rep.items}
436
+ model = diagram_model(lp.spec)
437
+ found = validate(lp.spec, caps)
438
+ outcome = getattr(lp.spec, "outcome", None)
439
+ rep.stamp = {
440
+ "schema_version": 1, "engine_version": rep.to_engine, "workflow_api": lp.manifests.engine.workflow_api,
441
+ "workflow_version": lp.workflow_version, "docs_digest": lp.docs_digest, "shape_digest": model["digest"],
442
+ "entries_applied": _entries_applied(read_stamp(_pkg(place)), entry_ids, by),
443
+ "tool_set": tool_set(lp.spec), "audit": _audit_keys(lp, caps),
444
+ "outcome_revision": int(getattr(outcome, "revision", 0) or 0),
445
+ "baseline": {"error": sum(1 for f in found if f.severity == "error"),
446
+ "warning": sum(1 for f in found if f.severity == "warning")},
447
+ "upgrade_id": rep.upgrade_id, "stamped_at": now_iso(),
448
+ }
449
+ write_json(_pkg(place) / STAMP, rep.stamp, mode=0o644)
450
+ sha = _commit(place, f"upgrade({lp.spec.name}): stamp for engine {rep.to_engine}")
451
+ if sha:
452
+ rep.commits.append({"entry": "stamp", "commit": sha})
453
+
454
+
455
+ def shares(items: Sequence[Item]) -> dict[str, Any]:
456
+ done = [i for i in items if i.action != "none" and i.state in ("done", "answered")]
457
+ count = {k: sum(1 for i in done if i.by == k) for k in ("transform", "model", "person")}
458
+ total = len(done)
459
+ return {"done": total, **count,
460
+ "share": {k: (round(v / total, 3) if total else 0.0) for k, v in count.items()},
461
+ "open": sum(1 for i in items if is_open(i)), "skipped": sum(1 for i in items if i.state == "skipped")}
462
+
463
+
464
+ def body(rep: Report) -> str:
465
+ """The report as the pull request's text: counts and the entries' own notes, no run text."""
466
+ lines = [f"Upgrade of `{rep.workflow}` from engine {rep.from_engine or 'unstamped'} to {rep.to_engine}.",
467
+ f"Version {rep.from_version} to {rep.proposed.get('version')} ({rep.proposed.get('level')}); "
468
+ f"`requires_engine` {rep.proposed.get('requires_engine')}.", "",
469
+ f"Items done: {rep.shares.get('done', 0)} (transform {rep.shares.get('transform', 0)}, model "
470
+ f"{rep.shares.get('model', 0)}, person {rep.shares.get('person', 0)}).", ""]
471
+ lines += [f"- {i.item_id}: {i.state}" + (f" by {i.by}" if i.by else "") + (f". {i.note}" if i.note else "")
472
+ for i in rep.items]
473
+ lines += ["", "Verification:"] + [f"- {v.check}: {v.state}. {v.evidence}" for v in rep.checks]
474
+ if rep.not_touched:
475
+ lines += ["", "Considered and not touched: " + ", ".join(rep.not_touched)]
476
+ return "\n".join(lines) + "\n"
477
+
478
+
479
+ # -- the verb ---------------------------------------------------------------------------------------------------
480
+
481
+
482
+ def _save(place: Place, rep: Report, name: str = "report.json", doc: Mapping[str, Any] | None = None) -> None:
483
+ write_json(place.record / name, dict(doc) if doc is not None else rep.to_json())
484
+
485
+
486
+ def _load_json(path: Path) -> dict[str, Any]:
487
+ try:
488
+ doc = json.loads(path.read_text(encoding="utf-8"))
489
+ except (OSError, ValueError):
490
+ return {}
491
+ return doc if isinstance(doc, dict) else {}
492
+
493
+
494
+ def upgrade(path: Path, caps: Mapping[str, Capabilities], *, no_assist: bool = False, stamp: bool = False,
495
+ bump: bool = False, open_pr: bool = False, continue_id: str | None = None, cap_usd: float = 10.0,
496
+ executor: str | None = None, assist: AssistFn | None = None, host: Any = None,
497
+ engine: str = ENGINE_VERSION, folder: Path | None = None) -> Report:
498
+ """Phases 1 to 7. `assist` runs the assisted and owner items and returns `{exit_code, items: {id: {state,
499
+ by, reason}}, cost_usd}`; without it, or with `no_assist`, those items stay for a person."""
500
+ root = path.resolve()
501
+ try:
502
+ src = load_package(root)
503
+ except PackageNotLoaded as exc:
504
+ return Report(workflow=root.name, exit_code=2, refused=f"the package does not load: {exc}")
505
+ name = src.spec.name
506
+ rep = Report(workflow=name, to_engine=engine)
507
+ try:
508
+ place = locate(root, name, engine)
509
+ except UpgradeRefused as exc:
510
+ rep.refused, rep.exit_code = str(exc), 2
511
+ return rep
512
+ rep.upgrade_id, rep.branch, rep.worktree = place.upgrade_id, place.branch, str(place.worktree)
513
+ all_entries = [e for e in entries_between(None, engine, folder) if e.get("audience") == "workflow"]
514
+ # SWF-B9, VER-B17, WUP-B16: the change notes of each sub-workflow the workflow runs, read from the child's registered
515
+ # package (those the stamp has not applied), join the engine's entries in the plan
516
+ kids = children_entries(src.spec, read_stamp(root))
517
+ all_entries += kids
518
+ by_id = {str(e["id"]): e for e in all_entries}
519
+ if continue_id is not None:
520
+ saved = _load_json(place.record / "report.json")
521
+ if continue_id != place.upgrade_id or not saved or not place.worktree.is_dir():
522
+ rep.refused, rep.exit_code = f"no upgrade {continue_id!r} of {name} is in progress here", 2
523
+ return rep
524
+ base = _load_json(place.record / "baseline.json")
525
+ rep.items = [Item(**i) for i in saved.get("items") or []]
526
+ for key in ("from_engine", "from_version", "not_touched", "notes", "commits", "baseline_errors", "assist"):
527
+ setattr(rep, key, saved.get(key) or getattr(rep, key))
528
+ else:
529
+ if _branch_exists(place.repo, place.branch) or place.worktree.exists():
530
+ rep.refused, rep.exit_code = (f"the branch {place.branch} already exists; `tempergraph upgrade {name} "
531
+ f"--continue {place.upgrade_id}` goes on with it"), 2
532
+ return rep
533
+ dirty = _dirty(place)
534
+ if dirty:
535
+ rep.refused, rep.exit_code = (f"the source has uncommitted changes ({dirty[0]}); commit or stash them "
536
+ "first"), 2
537
+ return rep
538
+ prior = read_stamp(root)
539
+ rep.from_engine = str(prior["engine_version"]) if prior else None
540
+ rep.from_version = src.manifests.version
541
+ base = baseline(src, caps) # phase 2, on the unchanged package
542
+ rep.baseline_errors = [f"{f['code']} {f['unit'] or ''}: {f['message']}".strip() for f in base["validation"]
543
+ if f["severity"] == "error"]
544
+ between = [e for e in entries_between(rep.from_engine, engine, folder) if e.get("audience") == "workflow"] + kids
545
+ codes = {str(f["code"]) for f in base["validation"]}
546
+ rep.items, rep.not_touched, rep.notes = plan(src, between, codes, no_assist=no_assist) # phase 3
547
+ ensure_state_root(state_root_path(place.repo))
548
+ place.record.mkdir(parents=True, exist_ok=True, mode=0o700)
549
+ _save(place, rep, "baseline.json", base)
550
+ _save(place, rep, "plan.json", {"schema_version": 1, "upgrade_id": place.upgrade_id, "engine_version": engine,
551
+ "workflow": name, "items": [asdict(i) for i in rep.items],
552
+ "not_touched": rep.not_touched})
553
+ place.worktree.parent.mkdir(parents=True, exist_ok=True)
554
+ gitmod.git(["worktree", "add", "-q", "-b", place.branch, str(place.worktree), "HEAD"], place.repo)
555
+ apply_transforms(place, rep, by_id, caps, name) # phase 4
556
+ pkg = _pkg(place)
557
+ todo = [i for i in rep.items if i.action in ("assisted", "owner") and is_open(i)]
558
+ if todo and (no_assist or assist is None):
559
+ for i in todo:
560
+ if i.action == "assisted":
561
+ i.action = "manual"
562
+ if assist is None and not no_assist:
563
+ rep.warnings.append("no assist step is available; the assisted and owner items stay for a person")
564
+ elif todo and assist is not None: # phase 5
565
+ got = dict(assist(Assist(upgrade_id=place.upgrade_id, record=place.record, worktree=place.worktree, package=pkg,
566
+ items=todo, cap_usd=cap_usd, entries=by_id, base=base,
567
+ executor=executor or (src.spec.upgrade or {}).get("executor"),
568
+ protected=tuple((src.spec.upgrade or {}).get("protected") or PROTECTED_DEFAULT))))
569
+ if int(got.get("exit_code") or 0) == 0: # the run ended: its edits become one commit, its inputs go
570
+ shutil.rmtree(place.worktree / ASSIST_DIR, ignore_errors=True)
571
+ sha = _commit(place, f"upgrade({name}): assisted and owner items")
572
+ if sha:
573
+ rep.commits.append({"entry": "assist", "commit": sha})
574
+ for i in todo:
575
+ new = dict((got.get("items") or {}).get(i.item_id) or {})
576
+ i.state, i.by = str(new.get("state") or i.state), new.get("by") or i.by
577
+ i.reason = str(new.get("reason") or i.reason)
578
+ rep.assist = {k: got.get(k) for k in ("thread_id", "cost_usd", "exit_code", "message") if k in got}
579
+ code = int(got.get("exit_code") or 0)
580
+ if code in (3, 5) or (code and any(is_open(i) for i in todo)):
581
+ rep.exit_code = code if code in (3, 5) else 4
582
+ rep.shares = shares(rep.items)
583
+ _save(place, rep)
584
+ return rep
585
+ _reconcile(rep, by_id, pkg, caps, continue_id is not None)
586
+ try:
587
+ before: WorkflowSpec | None = load_package(root).spec
588
+ except PackageNotLoaded:
589
+ before = None
590
+ lp = verify(place, rep, base, by_id, caps, before) # phase 6
591
+ rep.shares = shares(rep.items)
592
+ if lp is None:
593
+ rep.exit_code = 4
594
+ _save(place, rep)
595
+ return rep
596
+ rep.proposed = propose(rep, base, lp, rep.classes) # phase 7
597
+ if bump:
598
+ _bump(place, rep, lp)
599
+ lp = load_package(pkg)
600
+ if stamp:
601
+ _stamp(place, rep, lp, base, caps, [str(e["id"]) for e in all_entries
602
+ if e["id"] in {i.entry for i in rep.items} | set(rep.not_touched)])
603
+ if open_pr:
604
+ rep.pull_request = _open_pr(place, rep, lp, host)
605
+ _save(place, rep)
606
+ return rep
607
+
608
+
609
+ def _open_pr(place: Place, rep: Report, lp: LoadedPackage, host: Any) -> str | None:
610
+ from tempergraph.improve.codehost import CodeHostError
611
+
612
+ repo = lp.spec.issue_repository
613
+ if host is None or not repo:
614
+ rep.warnings.append("no pull request was opened: " + ("no code host credentials" if host is None else
615
+ "the workflow names no `issue_repository`"))
616
+ return None
617
+ labels = ["engine-upgrade"] + (["weakens-gate"] if any(
618
+ v.check.startswith("V5") and "weakening" in v.evidence for v in rep.checks) else [])
619
+ try:
620
+ gitmod.git(["push", "-q", "origin", f"refs/heads/{place.branch}:refs/heads/{place.branch}"], place.repo)
621
+ return str(host.create_draft_pr(repo, place.branch, host.default_branch(repo),
622
+ f"[upgrade] {rep.workflow}: engine {rep.to_engine}", body(rep), labels))
623
+ except (CodeHostError, gitmod.GitError) as exc:
624
+ rep.warnings.append(f"no pull request was opened: {exc}")
625
+ return None