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.
- tempergraph/__init__.py +8 -0
- tempergraph/__main__.py +5 -0
- tempergraph/api.py +428 -0
- tempergraph/audit/__init__.py +305 -0
- tempergraph/audit/catalog.py +342 -0
- tempergraph/audit/definition.py +387 -0
- tempergraph/audit/history.py +414 -0
- tempergraph/audit/history_rules.py +268 -0
- tempergraph/audit/history_rules_more.py +244 -0
- tempergraph/audit/host.py +270 -0
- tempergraph/audit/owned.py +96 -0
- tempergraph/audit/prompts.py +89 -0
- tempergraph/audit/report.py +248 -0
- tempergraph/audit/revisit.py +220 -0
- tempergraph/audit/surface.py +224 -0
- tempergraph/audit/text_health.py +176 -0
- tempergraph/audit/tools.py +391 -0
- tempergraph/author/__init__.py +2 -0
- tempergraph/author/blueprint.py +346 -0
- tempergraph/author/compare.py +122 -0
- tempergraph/author/criteria_lint.py +200 -0
- tempergraph/author/draw.py +112 -0
- tempergraph/author/inventory.py +210 -0
- tempergraph/author/literals.py +138 -0
- tempergraph/author/scaffold.py +568 -0
- tempergraph/author/session.py +439 -0
- tempergraph/author/trial.py +391 -0
- tempergraph/author/verify.py +353 -0
- tempergraph/builtin/__init__.py +1 -0
- tempergraph/builtin/upgrade.py +288 -0
- tempergraph/catalog.py +134 -0
- tempergraph/check_helpers.py +99 -0
- tempergraph/cli/__init__.py +1 -0
- tempergraph/cli/audit.py +190 -0
- tempergraph/cli/author.py +361 -0
- tempergraph/cli/improve.py +564 -0
- tempergraph/cli/improve_review.py +111 -0
- tempergraph/cli/install.py +35 -0
- tempergraph/cli/main.py +1261 -0
- tempergraph/cli/observe_cli.py +544 -0
- tempergraph/cli/outcome.py +77 -0
- tempergraph/cli/schedule_cli.py +1090 -0
- tempergraph/cli/upgrade.py +126 -0
- tempergraph/cli/workflows.py +96 -0
- tempergraph/compiler/__init__.py +6 -0
- tempergraph/compiler/graph.py +305 -0
- tempergraph/compiler/state.py +229 -0
- tempergraph/constants.py +72 -0
- tempergraph/contracts.py +1025 -0
- tempergraph/data/executor_compat.json +11 -0
- tempergraph/data/promotion.json +35 -0
- tempergraph/data/release.json +20 -0
- tempergraph/detach.py +65 -0
- tempergraph/docs.py +90 -0
- tempergraph/durability/__init__.py +2 -0
- tempergraph/durability/alias.py +66 -0
- tempergraph/durability/carry.py +591 -0
- tempergraph/durability/checkpoint.py +179 -0
- tempergraph/durability/control.py +109 -0
- tempergraph/durability/engine_file.py +301 -0
- tempergraph/durability/lock.py +138 -0
- tempergraph/durability/status.py +390 -0
- tempergraph/engine_identity.py +42 -0
- tempergraph/executor_compat.py +56 -0
- tempergraph/executors/__init__.py +4 -0
- tempergraph/executors/binding.py +91 -0
- tempergraph/executors/capabilities.py +95 -0
- tempergraph/executors/claude.py +603 -0
- tempergraph/executors/launcher.py +394 -0
- tempergraph/executors/mcpconfig.py +156 -0
- tempergraph/executors/mcpproxy.py +216 -0
- tempergraph/executors/preflight.py +196 -0
- tempergraph/executors/registry.py +71 -0
- tempergraph/executors/scripted.py +18 -0
- tempergraph/executors/session.py +107 -0
- tempergraph/executors/standins.py +118 -0
- tempergraph/executors/summary.py +110 -0
- tempergraph/executors/viewcatalog.py +27 -0
- tempergraph/git.py +403 -0
- tempergraph/identity.py +65 -0
- tempergraph/improve/__init__.py +5 -0
- tempergraph/improve/analysis.py +437 -0
- tempergraph/improve/artifact.py +477 -0
- tempergraph/improve/autonomy.py +192 -0
- tempergraph/improve/bindings.py +191 -0
- tempergraph/improve/calibration.py +1016 -0
- tempergraph/improve/causes.py +416 -0
- tempergraph/improve/child.py +651 -0
- tempergraph/improve/codehost.py +520 -0
- tempergraph/improve/digest.py +472 -0
- tempergraph/improve/escape.py +100 -0
- tempergraph/improve/filing.py +1047 -0
- tempergraph/improve/harvest.py +158 -0
- tempergraph/improve/issue_context.py +192 -0
- tempergraph/improve/lenses.py +204 -0
- tempergraph/improve/lessons.py +233 -0
- tempergraph/improve/loop_report.py +138 -0
- tempergraph/improve/loop_summary.py +85 -0
- tempergraph/improve/lost.py +119 -0
- tempergraph/improve/measure.py +121 -0
- tempergraph/improve/params.py +98 -0
- tempergraph/improve/pause_facts.py +134 -0
- tempergraph/improve/pr_later.py +186 -0
- tempergraph/improve/prebinding.py +130 -0
- tempergraph/improve/promotion.py +413 -0
- tempergraph/improve/proposals.py +934 -0
- tempergraph/improve/record.py +322 -0
- tempergraph/improve/release.py +89 -0
- tempergraph/improve/reliability.py +457 -0
- tempergraph/improve/repeat.py +115 -0
- tempergraph/improve/review.py +910 -0
- tempergraph/improve/suites.py +586 -0
- tempergraph/improve/trials.py +525 -0
- tempergraph/install/__init__.py +11 -0
- tempergraph/install/bootstrap.py +133 -0
- tempergraph/install/environment.py +173 -0
- tempergraph/install/launch.py +37 -0
- tempergraph/install/python.py +53 -0
- tempergraph/install/reconcile.py +52 -0
- tempergraph/install/selfcheck.py +29 -0
- tempergraph/install/shim.py +81 -0
- tempergraph/install/update.py +400 -0
- tempergraph/model/__init__.py +0 -0
- tempergraph/model/diagram.py +185 -0
- tempergraph/model/flow.py +324 -0
- tempergraph/model/prompt_lint.py +203 -0
- tempergraph/model/retire.py +52 -0
- tempergraph/model/subworkflow.py +274 -0
- tempergraph/model/text.py +67 -0
- tempergraph/model/validate.py +1158 -0
- tempergraph/observe/__init__.py +1 -0
- tempergraph/observe/attention.py +196 -0
- tempergraph/observe/detail.py +773 -0
- tempergraph/observe/forget.py +138 -0
- tempergraph/observe/hooks.py +272 -0
- tempergraph/observe/labels.py +95 -0
- tempergraph/observe/overlay.py +46 -0
- tempergraph/observe/report.py +402 -0
- tempergraph/observe/risk_report.py +110 -0
- tempergraph/observe/rows.py +444 -0
- tempergraph/observe/sinks.py +793 -0
- tempergraph/observe/supervision_cost.py +797 -0
- tempergraph/observe/supervision_report.py +295 -0
- tempergraph/observe/switch_report.py +140 -0
- tempergraph/package/__init__.py +2 -0
- tempergraph/package/change_report.py +116 -0
- tempergraph/package/changelog.py +263 -0
- tempergraph/package/docs_check.py +115 -0
- tempergraph/package/importer.py +90 -0
- tempergraph/package/inventory.py +111 -0
- tempergraph/package/loader.py +250 -0
- tempergraph/package/manifest.py +256 -0
- tempergraph/package/readiness.py +124 -0
- tempergraph/package/registry.py +383 -0
- tempergraph/package/rules.py +128 -0
- tempergraph/package/scan.py +65 -0
- tempergraph/package/selftest.py +348 -0
- tempergraph/package/stamp.py +213 -0
- tempergraph/package/transforms.py +481 -0
- tempergraph/package/upgrade.py +625 -0
- tempergraph/provenance.py +183 -0
- tempergraph/py.typed +0 -0
- tempergraph/release.py +17 -0
- tempergraph/render/__init__.py +0 -0
- tempergraph/render/output.py +72 -0
- tempergraph/render/prompt.py +166 -0
- tempergraph/render/template.py +86 -0
- tempergraph/run/__init__.py +2 -0
- tempergraph/run/asking.py +233 -0
- tempergraph/run/audit.py +63 -0
- tempergraph/run/check_worker.py +167 -0
- tempergraph/run/checks.py +517 -0
- tempergraph/run/commands.py +210 -0
- tempergraph/run/complexity.py +268 -0
- tempergraph/run/contest.py +76 -0
- tempergraph/run/council.py +368 -0
- tempergraph/run/council_run.py +527 -0
- tempergraph/run/events.py +279 -0
- tempergraph/run/finalize.py +132 -0
- tempergraph/run/gate.py +747 -0
- tempergraph/run/guard.py +89 -0
- tempergraph/run/judging.py +357 -0
- tempergraph/run/ladder.py +230 -0
- tempergraph/run/log.py +600 -0
- tempergraph/run/mapping.py +183 -0
- tempergraph/run/nodes.py +2304 -0
- tempergraph/run/outcome.py +255 -0
- tempergraph/run/outcome_record.py +292 -0
- tempergraph/run/outcome_trust.py +99 -0
- tempergraph/run/rerun.py +351 -0
- tempergraph/run/reserve.py +85 -0
- tempergraph/run/resources.py +76 -0
- tempergraph/run/risk.py +231 -0
- tempergraph/run/runner.py +1579 -0
- tempergraph/run/scriptcache.py +178 -0
- tempergraph/run/selfcheck.py +105 -0
- tempergraph/run/session_record.py +72 -0
- tempergraph/run/subrun.py +278 -0
- tempergraph/run/supervision.py +125 -0
- tempergraph/run/tool_access.py +101 -0
- tempergraph/schedule/__init__.py +25 -0
- tempergraph/schedule/credentials.py +167 -0
- tempergraph/schedule/echo.py +169 -0
- tempergraph/schedule/exact.py +275 -0
- tempergraph/schedule/export.py +164 -0
- tempergraph/schedule/launch.py +89 -0
- tempergraph/schedule/ledger.py +133 -0
- tempergraph/schedule/loop.py +176 -0
- tempergraph/schedule/model.py +440 -0
- tempergraph/schedule/policies.py +414 -0
- tempergraph/schedule/store.py +150 -0
- tempergraph/schedule/tick.py +377 -0
- tempergraph/schedule/token.py +81 -0
- tempergraph/schedule/triggers.py +210 -0
- tempergraph/schedule/words.py +423 -0
- tempergraph/security/__init__.py +0 -0
- tempergraph/security/launch.py +25 -0
- tempergraph/security/scrub.py +58 -0
- tempergraph/settings.py +950 -0
- tempergraph/store/__init__.py +0 -0
- tempergraph/store/codelog.py +73 -0
- tempergraph/store/layout.py +198 -0
- tempergraph/store/logs.py +325 -0
- tempergraph/store/manifest.py +99 -0
- tempergraph/store/migrate.py +188 -0
- tempergraph/workspace.py +874 -0
- tempergraph-0.7.1.dist-info/METADATA +70 -0
- tempergraph-0.7.1.dist-info/RECORD +232 -0
- tempergraph-0.7.1.dist-info/WHEEL +5 -0
- tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
- tempergraph-0.7.1.dist-info/top_level.txt +2 -0
- tempergraph_pytest_plugin.py +64 -0
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
"""The engine-shipped transforms of a changelog entry (VER-B13). Model-free.
|
|
2
|
+
|
|
3
|
+
A transform is a pure function over a package's files: it reads the declaration modules by syntax tree and
|
|
4
|
+
the model-facing text files, and rewrites only the bytes of the nodes it names, so comments, layout and line
|
|
5
|
+
endings stay. Each is idempotent. What a transform cannot express it leaves alone (the entry's detect rules
|
|
6
|
+
then still hit, and the upgrade turns the rest into an assisted item, WUP-B17) or raises `TransformError`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import ast
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
API = "tempergraph.api"
|
|
19
|
+
UNIT_BUILDERS = frozenset({"Step", "Script", "Route", "Map", "Council", "Contest", "Ask", "Wait", "Subworkflow"})
|
|
20
|
+
PARENT_BUILDERS = {"gate": {"Gate"}, "judge": {"Judge"}, "risk": {"Risk"}, "escalation": {"Escalation"},
|
|
21
|
+
"session_options": {"SessionOptions"}, "routing": {"Routing"}, "input": {"Input"},
|
|
22
|
+
"step": set(UNIT_BUILDERS)}
|
|
23
|
+
SKIPPED_DIRS = frozenset({"docs", "diagram", ".git", "__pycache__", "tests", "evals"})
|
|
24
|
+
TEXT_SUFFIXES = frozenset({".md", ".txt"})
|
|
25
|
+
CAPABILITY_KEYWORDS = frozenset({"tools", "model", "views", "to", "judge_model", "alias"})
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TransformError(ValueError):
|
|
29
|
+
"""The change cannot be made by rule at this place; the item fails and goes to the assisted path."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(kw_only=True)
|
|
33
|
+
class Result:
|
|
34
|
+
changed: list[str] = field(default_factory=list) # package-relative files rewritten
|
|
35
|
+
owner: list[dict[str, Any]] = field(default_factory=list) # questions only the owner can answer
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
Edit = tuple[int, int, bytes]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _files(root: Path, suffixes: Iterable[str]) -> list[Path]:
|
|
42
|
+
want = set(suffixes)
|
|
43
|
+
out = []
|
|
44
|
+
for p in sorted(root.rglob("*")):
|
|
45
|
+
rel = p.relative_to(root)
|
|
46
|
+
if p.is_file() and not p.is_symlink() and p.suffix in want and not SKIPPED_DIRS & set(rel.parts[:-1]):
|
|
47
|
+
out.append(p)
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class _Module:
|
|
52
|
+
"""One Python file with byte offsets for its nodes and the local names of the engine's public interface."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, path: Path) -> None:
|
|
55
|
+
self.path = path
|
|
56
|
+
self.src = path.read_bytes()
|
|
57
|
+
self.tree = ast.parse(self.src)
|
|
58
|
+
self.starts = [0]
|
|
59
|
+
for line in self.src.splitlines(keepends=True):
|
|
60
|
+
self.starts.append(self.starts[-1] + len(line))
|
|
61
|
+
self.names: dict[str, str] = {} # local name -> public name
|
|
62
|
+
self.modules: set[str] = set() # local names bound to the interface module
|
|
63
|
+
self.edits: list[Edit] = []
|
|
64
|
+
for node in ast.walk(self.tree):
|
|
65
|
+
if isinstance(node, ast.ImportFrom) and node.module == API:
|
|
66
|
+
for a in node.names:
|
|
67
|
+
self.names[a.asname or a.name] = a.name
|
|
68
|
+
elif isinstance(node, ast.ImportFrom) and node.module == "tempergraph":
|
|
69
|
+
self.modules |= {a.asname or a.name for a in node.names if a.name == "api"}
|
|
70
|
+
elif isinstance(node, ast.Import):
|
|
71
|
+
self.modules |= {a.asname for a in node.names if a.name == API and a.asname}
|
|
72
|
+
|
|
73
|
+
def at(self, line: int, col: int) -> int:
|
|
74
|
+
return self.starts[line - 1] + col
|
|
75
|
+
|
|
76
|
+
def span(self, node: Any) -> tuple[int, int]:
|
|
77
|
+
return self.at(node.lineno, node.col_offset), self.at(node.end_lineno, node.end_col_offset)
|
|
78
|
+
|
|
79
|
+
def builder(self, call: ast.Call) -> str | None:
|
|
80
|
+
f = call.func
|
|
81
|
+
if isinstance(f, ast.Name):
|
|
82
|
+
return self.names.get(f.id)
|
|
83
|
+
if isinstance(f, ast.Attribute) and isinstance(f.value, ast.Name) and f.value.id in self.modules:
|
|
84
|
+
return f.attr
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
def calls(self, builders: Iterable[str]) -> list[ast.Call]:
|
|
88
|
+
want = set(builders)
|
|
89
|
+
return [n for n in ast.walk(self.tree) if isinstance(n, ast.Call) and self.builder(n) in want]
|
|
90
|
+
|
|
91
|
+
def replace(self, start: int, end: int, new: str | bytes) -> None:
|
|
92
|
+
self.edits.append((start, end, new.encode() if isinstance(new, str) else new))
|
|
93
|
+
|
|
94
|
+
def save(self) -> bool:
|
|
95
|
+
if not self.edits:
|
|
96
|
+
return False
|
|
97
|
+
out = self.src
|
|
98
|
+
for start, end, new in sorted(set(self.edits), reverse=True):
|
|
99
|
+
out = out[:start] + new + out[end:]
|
|
100
|
+
if out == self.src:
|
|
101
|
+
return False
|
|
102
|
+
ast.parse(out) # a rewrite that does not parse is never written
|
|
103
|
+
self.path.write_bytes(out)
|
|
104
|
+
return True
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _modules(root: Path) -> list[_Module]:
|
|
108
|
+
out = []
|
|
109
|
+
for p in _files(root, {".py"}):
|
|
110
|
+
try:
|
|
111
|
+
out.append(_Module(p))
|
|
112
|
+
except (SyntaxError, ValueError):
|
|
113
|
+
continue
|
|
114
|
+
return out
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _finish(root: Path, mods: Iterable[_Module], res: Result) -> Result:
|
|
118
|
+
for m in mods:
|
|
119
|
+
if m.save():
|
|
120
|
+
res.changed.append(m.path.relative_to(root).as_posix())
|
|
121
|
+
res.changed = sorted(set(res.changed))
|
|
122
|
+
return res
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _target(path: str) -> tuple[set[str], str]:
|
|
126
|
+
"""The builders whose keyword a field path names, and that keyword: `units.*.gate.x` is `x` of `Gate`."""
|
|
127
|
+
parts = [p for p in path.split(".") if p]
|
|
128
|
+
if not parts:
|
|
129
|
+
raise TransformError("an empty field path")
|
|
130
|
+
leaf, parents = parts[-1], parts[:-1]
|
|
131
|
+
if not parents:
|
|
132
|
+
return {"Workflow"}, leaf
|
|
133
|
+
if parents[-1] in PARENT_BUILDERS:
|
|
134
|
+
return set(PARENT_BUILDERS[parents[-1]]), leaf
|
|
135
|
+
if parents[0] == "units" and len(parents) <= 2:
|
|
136
|
+
return set(UNIT_BUILDERS), leaf
|
|
137
|
+
raise TransformError(f"no builder is known for the field path {path!r}")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _keyword(call: ast.Call, name: str) -> ast.keyword | None:
|
|
141
|
+
return next((k for k in call.keywords if k.arg == name), None)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _literal(value: Any) -> str:
|
|
145
|
+
if isinstance(value, Mapping) and set(value) == {"call", "args"}: # a builder call given as data
|
|
146
|
+
args = ", ".join(f"{k}={_literal(v)}" for k, v in dict(value["args"]).items())
|
|
147
|
+
return f"{value['call']}({args})"
|
|
148
|
+
if isinstance(value, str):
|
|
149
|
+
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
150
|
+
return repr(value)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def rename_field(root: Path, *, old: str, new: str) -> Result:
|
|
154
|
+
"""Moves a declared value to a new field of the same builder."""
|
|
155
|
+
builders, leaf = _target(old)
|
|
156
|
+
builders2, leaf2 = _target(new)
|
|
157
|
+
if builders != builders2:
|
|
158
|
+
raise TransformError(f"{old!r} and {new!r} belong to different builders")
|
|
159
|
+
mods = _modules(root)
|
|
160
|
+
for m in mods:
|
|
161
|
+
for call in m.calls(builders):
|
|
162
|
+
kw = _keyword(call, leaf)
|
|
163
|
+
if kw is None:
|
|
164
|
+
continue
|
|
165
|
+
if _keyword(call, leaf2) is not None:
|
|
166
|
+
raise TransformError(f"{m.path.name}:{call.lineno} declares both {leaf!r} and {leaf2!r}")
|
|
167
|
+
start = m.at(kw.lineno, kw.col_offset)
|
|
168
|
+
m.replace(start, start + len(leaf.encode()), leaf2)
|
|
169
|
+
return _finish(root, mods, Result())
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _add_keyword(m: _Module, call: ast.Call, text: str) -> None:
|
|
173
|
+
if any(k.arg is None for k in call.keywords):
|
|
174
|
+
raise TransformError(f"{m.path.name}:{call.lineno} passes its fields as `**`")
|
|
175
|
+
close = m.span(call)[1] - 1
|
|
176
|
+
i = close
|
|
177
|
+
while i > 0 and m.src[i - 1:i] in (b" ", b"\t", b"\n", b"\r"):
|
|
178
|
+
i -= 1
|
|
179
|
+
before = m.src[i - 1:i]
|
|
180
|
+
if before == b"(":
|
|
181
|
+
m.replace(i, i, text)
|
|
182
|
+
elif before == b",":
|
|
183
|
+
m.replace(i, i, f" {text}" + ("," if i != close else ""))
|
|
184
|
+
else:
|
|
185
|
+
m.replace(i, i, f", {text}")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def set_field(root: Path, *, path: str, value: Any) -> Result:
|
|
189
|
+
"""Writes an explicit value where the field is not declared, so a changed default keeps the old behaviour."""
|
|
190
|
+
builders, leaf = _target(path)
|
|
191
|
+
mods = _modules(root)
|
|
192
|
+
for m in mods:
|
|
193
|
+
for call in m.calls(builders):
|
|
194
|
+
if _keyword(call, leaf) is None:
|
|
195
|
+
_add_keyword(m, call, f"{leaf}={_literal(value)}")
|
|
196
|
+
return _finish(root, mods, Result())
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _remove_keyword(m: _Module, call: ast.Call, kw: ast.keyword) -> None:
|
|
200
|
+
start, end = m.at(kw.lineno, kw.col_offset), m.span(kw.value)[1]
|
|
201
|
+
j = end
|
|
202
|
+
while m.src[j:j + 1] in (b" ", b"\t"):
|
|
203
|
+
j += 1
|
|
204
|
+
if m.src[j:j + 1] == b",":
|
|
205
|
+
j += 1
|
|
206
|
+
line_start = m.src.rfind(b"\n", 0, start) + 1
|
|
207
|
+
k = j
|
|
208
|
+
while m.src[k:k + 1] in (b" ", b"\t"):
|
|
209
|
+
k += 1
|
|
210
|
+
alone = not m.src[line_start:start].strip() and m.src[k:k + 1] in (b"\n", b"\r")
|
|
211
|
+
if alone: # the keyword had its own line: the line goes with it
|
|
212
|
+
k += 2 if m.src[k:k + 2] == b"\r\n" else 1
|
|
213
|
+
m.replace(line_start, k, b"")
|
|
214
|
+
else:
|
|
215
|
+
if m.src[k:k + 1] in (b"\n", b"\r"): # nothing follows on the line: no trailing space is left
|
|
216
|
+
while m.src[start - 1:start] in (b" ", b"\t"):
|
|
217
|
+
start -= 1
|
|
218
|
+
m.replace(start, k, b"")
|
|
219
|
+
return
|
|
220
|
+
i = start # the last argument: the comma before it goes
|
|
221
|
+
while i > 0 and m.src[i - 1:i] in (b" ", b"\t", b"\n", b"\r"):
|
|
222
|
+
i -= 1
|
|
223
|
+
if m.src[i - 1:i] == b",":
|
|
224
|
+
i -= 1
|
|
225
|
+
else:
|
|
226
|
+
i = start
|
|
227
|
+
m.replace(i, end, b"")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
_MISSING = object()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def drop_field(root: Path, *, path: str, default: Any = _MISSING) -> Result:
|
|
234
|
+
"""Removes a retired field whose value equals its default; any other value stays for a person."""
|
|
235
|
+
builders, leaf = _target(path)
|
|
236
|
+
mods = _modules(root)
|
|
237
|
+
for m in mods:
|
|
238
|
+
for call in m.calls(builders):
|
|
239
|
+
kw = _keyword(call, leaf)
|
|
240
|
+
if kw is None:
|
|
241
|
+
continue
|
|
242
|
+
if default is not _MISSING:
|
|
243
|
+
try:
|
|
244
|
+
same = ast.literal_eval(kw.value) == default
|
|
245
|
+
except (ValueError, SyntaxError):
|
|
246
|
+
same = False
|
|
247
|
+
if not same:
|
|
248
|
+
continue
|
|
249
|
+
_remove_keyword(m, call, kw)
|
|
250
|
+
return _finish(root, mods, Result())
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def rename_symbol(root: Path, *, old: str, new: str) -> Result:
|
|
254
|
+
"""Rewrites an import and every use of a name of the public interface."""
|
|
255
|
+
mods = _modules(root)
|
|
256
|
+
for m in mods:
|
|
257
|
+
plain = False
|
|
258
|
+
for node in ast.walk(m.tree):
|
|
259
|
+
if isinstance(node, ast.ImportFrom) and node.module == API:
|
|
260
|
+
for a in node.names:
|
|
261
|
+
if a.name == old:
|
|
262
|
+
start = m.at(a.lineno, a.col_offset)
|
|
263
|
+
m.replace(start, start + len(old.encode()), new)
|
|
264
|
+
plain = plain or a.asname is None
|
|
265
|
+
elif isinstance(node, ast.Attribute) and node.attr == old and isinstance(node.value, ast.Name) \
|
|
266
|
+
and node.value.id in m.modules:
|
|
267
|
+
end = m.span(node)[1]
|
|
268
|
+
m.replace(end - len(old.encode()), end, new)
|
|
269
|
+
if plain:
|
|
270
|
+
for node in ast.walk(m.tree):
|
|
271
|
+
if isinstance(node, ast.Name) and node.id == old:
|
|
272
|
+
m.replace(*m.span(node), new)
|
|
273
|
+
return _finish(root, mods, Result())
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _strings(m: _Module, inside: Iterable[ast.AST] | None = None) -> list[ast.Constant]:
|
|
277
|
+
"""The plain string constants of a module (not the parts of an f-string), optionally under given nodes."""
|
|
278
|
+
joined = {id(v) for n in ast.walk(m.tree) if isinstance(n, ast.JoinedStr) for v in ast.walk(n)}
|
|
279
|
+
roots = list(inside) if inside is not None else [m.tree]
|
|
280
|
+
return [n for r in roots for n in ast.walk(r)
|
|
281
|
+
if isinstance(n, ast.Constant) and isinstance(n.value, str) and id(n) not in joined]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _rewrite_text(root: Path, sub: Callable[[str], str], res: Result) -> None:
|
|
285
|
+
for p in _files(root, TEXT_SUFFIXES):
|
|
286
|
+
try:
|
|
287
|
+
raw = p.read_bytes()
|
|
288
|
+
text = raw.decode("utf-8")
|
|
289
|
+
except (OSError, UnicodeDecodeError):
|
|
290
|
+
continue
|
|
291
|
+
new = sub(text)
|
|
292
|
+
if new != text:
|
|
293
|
+
p.write_bytes(new.encode("utf-8"))
|
|
294
|
+
res.changed.append(p.relative_to(root).as_posix())
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def rename_template_key(root: Path, *, old: str, new: str) -> Result:
|
|
298
|
+
"""Rewrites a template field in templates, briefs and inline prompt text."""
|
|
299
|
+
pat = re.compile(r"\{" + re.escape(old) + r"(?=[}:.\[!])")
|
|
300
|
+
res = Result()
|
|
301
|
+
_rewrite_text(root, lambda t: pat.sub("{" + new, t), res)
|
|
302
|
+
mods = _modules(root)
|
|
303
|
+
for m in mods:
|
|
304
|
+
for node in _strings(m):
|
|
305
|
+
if isinstance(node.value, str) and pat.search(node.value):
|
|
306
|
+
start, end = m.span(node)
|
|
307
|
+
m.replace(start, end, pat.sub("{" + new, m.src[start:end].decode("utf-8")))
|
|
308
|
+
return _finish(root, mods, res)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _unit_calls(m: _Module, unit: str, builder: str) -> list[ast.Call]:
|
|
312
|
+
"""The calls of `builder` that declare the unit named `unit`: a dict entry `"<unit>": Builder(...)`, or an
|
|
313
|
+
assignment to `units["<unit>"]` or to a name `<unit>`."""
|
|
314
|
+
out: list[ast.Call] = []
|
|
315
|
+
for node in ast.walk(m.tree):
|
|
316
|
+
if isinstance(node, ast.Dict):
|
|
317
|
+
out += [v for k, v in zip(node.keys, node.values, strict=True) if isinstance(k, ast.Constant)
|
|
318
|
+
and k.value == unit and isinstance(v, ast.Call) and m.builder(v) == builder]
|
|
319
|
+
elif isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) and m.builder(node.value) == builder:
|
|
320
|
+
for t in node.targets:
|
|
321
|
+
if (isinstance(t, ast.Subscript) and isinstance(t.slice, ast.Constant) and t.slice.value == unit) \
|
|
322
|
+
or (isinstance(t, ast.Name) and t.id == unit):
|
|
323
|
+
out.append(node.value)
|
|
324
|
+
return out
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def rename_produced_key(root: Path, *, unit: str, old: str, new: str) -> Result:
|
|
328
|
+
"""A sub-workflow child renamed a key it produces (SWF-B9, WUP-B6): the parent's reference `<unit>.<old>` becomes
|
|
329
|
+
`<unit>.<new>` in templates, briefs and inline prompt text (`{<unit>.<old>}`), as a whole string in a declaration
|
|
330
|
+
(an `inputs` source), and in the `produces` of the parent's `Subworkflow` unit of that name. Another unit's key of
|
|
331
|
+
the same name, and another key that only begins with `old`, stay."""
|
|
332
|
+
ref = f"{unit}.{old}"
|
|
333
|
+
pat = re.compile(r"\{" + re.escape(ref) + r"(?=[}:.\[!])")
|
|
334
|
+
res = Result()
|
|
335
|
+
_rewrite_text(root, lambda t: pat.sub("{" + f"{unit}.{new}", t), res)
|
|
336
|
+
mods = _modules(root)
|
|
337
|
+
for m in mods:
|
|
338
|
+
for node in _strings(m):
|
|
339
|
+
start, end = m.span(node)
|
|
340
|
+
if isinstance(node.value, str) and pat.search(node.value):
|
|
341
|
+
m.replace(start, end, pat.sub("{" + f"{unit}.{new}", m.src[start:end].decode("utf-8")))
|
|
342
|
+
elif node.value == ref:
|
|
343
|
+
m.replace(start, end, m.src[start:end].decode("utf-8").replace(ref, f"{unit}.{new}"))
|
|
344
|
+
for call in _unit_calls(m, unit, "Subworkflow"):
|
|
345
|
+
kw = _keyword(call, "produces")
|
|
346
|
+
for node in _strings(m, [kw.value] if kw is not None else []):
|
|
347
|
+
if node.value == old:
|
|
348
|
+
start, end = m.span(node)
|
|
349
|
+
m.replace(start, end, m.src[start:end].decode("utf-8").replace(old, new))
|
|
350
|
+
return _finish(root, mods, res)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def rename_tool(root: Path, *, executor: str, old: str, new: str) -> Result:
|
|
354
|
+
"""Rewrites an executor's tool name where it stands alone: a whole string in a declaration, a whole word
|
|
355
|
+
in model-facing text. `executor` names whose tool it is and is recorded with the entry; the hits decide
|
|
356
|
+
where the name is used."""
|
|
357
|
+
del executor
|
|
358
|
+
pat = re.compile(r"(?<![\w.-])" + re.escape(old) + r"(?![\w-])")
|
|
359
|
+
res = Result()
|
|
360
|
+
_rewrite_text(root, lambda t: pat.sub(new, t), res)
|
|
361
|
+
mods = _modules(root)
|
|
362
|
+
for m in mods:
|
|
363
|
+
for node in _strings(m):
|
|
364
|
+
if node.value == old:
|
|
365
|
+
start, end = m.span(node)
|
|
366
|
+
m.replace(start, end, m.src[start:end].decode("utf-8").replace(old, new))
|
|
367
|
+
return _finish(root, mods, res)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def map_capability(root: Path, *, old: str, new: str) -> Result:
|
|
371
|
+
"""Rewrites a capability name or an alias tier in the declarations: a whole string under `tools`, `model`
|
|
372
|
+
and the like of a builder call."""
|
|
373
|
+
mods = _modules(root)
|
|
374
|
+
for m in mods:
|
|
375
|
+
values = [k.value for n in ast.walk(m.tree) if isinstance(n, ast.Call) and m.builder(n)
|
|
376
|
+
for k in n.keywords if k.arg in CAPABILITY_KEYWORDS]
|
|
377
|
+
for node in _strings(m, values):
|
|
378
|
+
if node.value == old:
|
|
379
|
+
start, end = m.span(node)
|
|
380
|
+
m.replace(start, end, m.src[start:end].decode("utf-8").replace(old, new))
|
|
381
|
+
return _finish(root, mods, Result())
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _import_name(m: _Module, name: str) -> None:
|
|
385
|
+
if name in m.names.values():
|
|
386
|
+
return
|
|
387
|
+
for node in ast.walk(m.tree):
|
|
388
|
+
if isinstance(node, ast.ImportFrom) and node.module == API and node.names:
|
|
389
|
+
after = next((a for a in node.names if a.name > name), None)
|
|
390
|
+
if after is not None:
|
|
391
|
+
at = m.at(after.lineno, after.col_offset)
|
|
392
|
+
m.replace(at, at, f"{name}, ")
|
|
393
|
+
else:
|
|
394
|
+
last = node.names[-1]
|
|
395
|
+
at = m.at(last.end_lineno or last.lineno, last.end_col_offset or 0)
|
|
396
|
+
m.replace(at, at, f", {name}")
|
|
397
|
+
return
|
|
398
|
+
raise TransformError(f"{m.path.name} does not import from {API}")
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def model_list_to_escalation(root: Path) -> Result:
|
|
402
|
+
"""LAD-B18: a step's `model` list becomes its first alias, with an `escalation` to the second when that
|
|
403
|
+
is one tier up; any other list leaves an owner item."""
|
|
404
|
+
from tempergraph.model.retire import model_list_to_escalation as rewrite
|
|
405
|
+
|
|
406
|
+
res = Result()
|
|
407
|
+
mods = _modules(root)
|
|
408
|
+
for m in mods:
|
|
409
|
+
for call in m.calls({"Step"}):
|
|
410
|
+
kw = _keyword(call, "model")
|
|
411
|
+
if kw is None or not isinstance(kw.value, (ast.List, ast.Tuple)):
|
|
412
|
+
continue
|
|
413
|
+
try:
|
|
414
|
+
rungs = [str(v) for v in ast.literal_eval(kw.value)]
|
|
415
|
+
except (ValueError, SyntaxError):
|
|
416
|
+
raise TransformError(f"{m.path.name}:{kw.value.lineno} builds its model list at run time") from None
|
|
417
|
+
got = rewrite(rungs)
|
|
418
|
+
where = f"{m.path.relative_to(root).as_posix()}:{kw.value.lineno}"
|
|
419
|
+
if got["model"] is None:
|
|
420
|
+
_remove_keyword(m, call, kw)
|
|
421
|
+
continue
|
|
422
|
+
m.replace(*m.span(kw.value), _literal(got["model"]))
|
|
423
|
+
if got["escalation"]:
|
|
424
|
+
if _keyword(call, "escalation") is not None:
|
|
425
|
+
res.owner.append({"where": where, "question": "this step already declares an `escalation`; "
|
|
426
|
+
f"keep it, or use `{got['escalation']['to']}`", "was": rungs})
|
|
427
|
+
continue
|
|
428
|
+
_add_keyword(m, call, f"escalation=Escalation(to={_literal(got['escalation']['to'])})")
|
|
429
|
+
_import_name(m, "Escalation")
|
|
430
|
+
elif got["owner_item"]:
|
|
431
|
+
res.owner.append({"where": where, "question": got["owner_item"], "was": rungs})
|
|
432
|
+
for call in m.calls({"Workflow"}):
|
|
433
|
+
kw = _keyword(call, "model_profile")
|
|
434
|
+
if kw is None or not isinstance(kw.value, ast.Dict):
|
|
435
|
+
continue
|
|
436
|
+
for key, val in zip(kw.value.keys, kw.value.values, strict=False):
|
|
437
|
+
if isinstance(val, (ast.List, ast.Tuple)):
|
|
438
|
+
try:
|
|
439
|
+
rungs = [str(v) for v in ast.literal_eval(val)]
|
|
440
|
+
except (ValueError, SyntaxError):
|
|
441
|
+
continue
|
|
442
|
+
if not rungs:
|
|
443
|
+
continue
|
|
444
|
+
m.replace(*m.span(val), _literal(rungs[0]))
|
|
445
|
+
if len(rungs) > 1:
|
|
446
|
+
name = ast.literal_eval(key) if key is not None else "?"
|
|
447
|
+
res.owner.append({"where": f"{m.path.relative_to(root).as_posix()}:{val.lineno}",
|
|
448
|
+
"question": f"`model_profile.{name}` was a list; a profile holds one "
|
|
449
|
+
"alias, so choose an `escalation.to` on the step, or none",
|
|
450
|
+
"was": rungs})
|
|
451
|
+
return _finish(root, mods, res)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
TRANSFORMS: dict[str, Callable[..., Result]] = {
|
|
455
|
+
"rename_field": rename_field, "set_field": set_field, "drop_field": drop_field,
|
|
456
|
+
"rename_symbol": rename_symbol, "rename_template_key": rename_template_key, "rename_tool": rename_tool,
|
|
457
|
+
"map_capability": map_capability, "model_list_to_escalation": model_list_to_escalation,
|
|
458
|
+
"rename_produced_key": rename_produced_key,
|
|
459
|
+
}
|
|
460
|
+
PARAMETERS = {"rename_field": {"from": "old", "to": "new"}, "rename_symbol": {"from": "old", "to": "new"},
|
|
461
|
+
"rename_template_key": {"from": "old", "to": "new"}, "map_capability": {"from": "old", "to": "new"},
|
|
462
|
+
"rename_produced_key": {"unit": "unit", "from": "old", "to": "new"},
|
|
463
|
+
"rename_tool": {"from": "old", "to": "new", "executor": "executor"},
|
|
464
|
+
"set_field": {"path": "path", "value": "value"}, "drop_field": {"path": "path", "default": "default"},
|
|
465
|
+
"model_list_to_escalation": {}}
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def apply(root: Path, migrate: Mapping[str, Any]) -> Result:
|
|
469
|
+
"""Run the transform a changelog entry's `migrate` names, with the parameters it carries (VER-B12)."""
|
|
470
|
+
name = str(migrate.get("transform") or "")
|
|
471
|
+
if name not in TRANSFORMS:
|
|
472
|
+
raise TransformError(f"{name!r} is not a transform of this engine")
|
|
473
|
+
given = dict(migrate.get("params") or {})
|
|
474
|
+
known = PARAMETERS[name]
|
|
475
|
+
unknown = sorted(set(given) - set(known))
|
|
476
|
+
if unknown:
|
|
477
|
+
raise TransformError(f"{name} takes no parameter {unknown[0]!r}")
|
|
478
|
+
try:
|
|
479
|
+
return TRANSFORMS[name](root, **{known[k]: v for k, v in given.items()})
|
|
480
|
+
except TypeError as exc:
|
|
481
|
+
raise TransformError(f"{name}: {exc}") from exc
|