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,400 @@
|
|
|
1
|
+
"""`update` (UPD-B14, UPD-B6, UPD-B17): the plan, the install beside the current engine, the switch, rollback and
|
|
2
|
+
`--prune-engines`. Deterministic, no model. Like `install`, this module imports only the standard library and
|
|
3
|
+
the stdlib-only engine modules; registered workflows are reinstalled and checked inside the new environment.
|
|
4
|
+
|
|
5
|
+
Exit codes: 0 done, up to date or a read-only check; 2 refused (downgrade, no engine, rollback across a
|
|
6
|
+
layout the previous engine cannot read); 1 failed, with nothing switched.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import shutil
|
|
15
|
+
import sys
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import IO, Any
|
|
19
|
+
|
|
20
|
+
from tempergraph.docs import write_json
|
|
21
|
+
from tempergraph.install import environment as envmod
|
|
22
|
+
from tempergraph.install import shim
|
|
23
|
+
from tempergraph.install.python import find_python
|
|
24
|
+
from tempergraph.release import release
|
|
25
|
+
from tempergraph.store.layout import home_path, now_iso
|
|
26
|
+
|
|
27
|
+
EXTRAS = ("agent-sdk", "messages-api")
|
|
28
|
+
KEEP_UNPINNED = 2 # old engines kept before the report suggests `--prune-engines` (UPD open question)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def parser() -> argparse.ArgumentParser:
|
|
32
|
+
p = argparse.ArgumentParser(prog="tempergraph update")
|
|
33
|
+
p.add_argument("--check", action="store_true", help="plan only; read-only")
|
|
34
|
+
p.add_argument("--dry-run", action="store_true", help="print the plan with every write it would make")
|
|
35
|
+
p.add_argument("--json", action="store_true")
|
|
36
|
+
p.add_argument("--with", dest="extras", action="append", default=[], choices=EXTRAS)
|
|
37
|
+
p.add_argument("--rollback", action="store_true")
|
|
38
|
+
p.add_argument("--restore-backups", action="store_true")
|
|
39
|
+
p.add_argument("--prune-engines", action="store_true")
|
|
40
|
+
return p
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _version(v: Any) -> tuple[int, ...]:
|
|
44
|
+
return tuple(int(p) if p.isdigit() else 0 for p in str(v or "0").split("+", 1)[0].split("."))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _read(path: Path) -> dict[str, Any]:
|
|
48
|
+
try:
|
|
49
|
+
doc = json.loads(path.read_text(encoding="utf-8"))
|
|
50
|
+
except (OSError, ValueError):
|
|
51
|
+
return {}
|
|
52
|
+
return doc if isinstance(doc, dict) else {}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def source_release(engine: Path) -> dict[str, Any]:
|
|
56
|
+
"""The release record of the staged engine, read from its files (it may be newer than this code)."""
|
|
57
|
+
return _read(engine / "src" / "tempergraph" / "data" / "release.json") or dict(release())
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def find_source() -> Path | None:
|
|
61
|
+
"""UPD-B14, UPD-B6 step 1: the staged engine of the plugin copy that invoked the verb; no option names a path.
|
|
62
|
+
Through the shim, the plugin copy is the one Claude Code names in `CLAUDE_PLUGIN_ROOT`."""
|
|
63
|
+
here = envmod.staged_engine()
|
|
64
|
+
if here is not None:
|
|
65
|
+
return here
|
|
66
|
+
root = os.environ.get("CLAUDE_PLUGIN_ROOT")
|
|
67
|
+
cand = Path(root) / "engine" if root else None
|
|
68
|
+
return cand if cand and (cand / "pyproject.toml").is_file() and (cand / "src" / "tempergraph").is_dir() else None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def index_roots(home: Path) -> list[Path]:
|
|
72
|
+
"""The state roots of the machine index (CST-B8) that still exist."""
|
|
73
|
+
doc = _read(home / "index.json")
|
|
74
|
+
got = doc.get("roots")
|
|
75
|
+
roots = got if isinstance(got, list) else []
|
|
76
|
+
return [Path(str(r.get("path"))) for r in roots if isinstance(r, dict) and Path(str(r.get("path"))).is_dir()]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def live_processes(roots: Sequence[Path]) -> list[dict[str, Any]]:
|
|
80
|
+
"""Each live run with the engine its lock names (MIG-B8); a lock is live while its holder file is."""
|
|
81
|
+
out = []
|
|
82
|
+
for root in roots:
|
|
83
|
+
for holder in sorted((root / "locks").glob("*/*.holder.json")) if (root / "locks").is_dir() else []:
|
|
84
|
+
doc = _read(holder)
|
|
85
|
+
pid = doc.get("pid")
|
|
86
|
+
if not isinstance(pid, int) or not _alive(pid):
|
|
87
|
+
continue
|
|
88
|
+
out.append({"thread_id": f"{holder.parent.name}/{holder.name[:-len('.holder.json')]}",
|
|
89
|
+
"state_root": str(root), "pid": pid, "engine": doc.get("engine"),
|
|
90
|
+
"engine_version": doc.get("engine_version")})
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _alive(pid: int) -> bool:
|
|
95
|
+
try:
|
|
96
|
+
os.kill(pid, 0)
|
|
97
|
+
except ProcessLookupError:
|
|
98
|
+
return False
|
|
99
|
+
except OSError:
|
|
100
|
+
return True
|
|
101
|
+
return True
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def thread_pins(roots: Sequence[Path]) -> list[dict[str, Any]]:
|
|
105
|
+
"""Threads pinned to an engine (MIG-B12, MIG-B13, MIG-B14), from each thread's `engine.json`."""
|
|
106
|
+
out = []
|
|
107
|
+
for root in roots:
|
|
108
|
+
for f in sorted((root / "runs").glob("*/*/engine.json")) if (root / "runs").is_dir() else []:
|
|
109
|
+
pin = _read(f).get("pinned")
|
|
110
|
+
if isinstance(pin, dict) and pin.get("engine"):
|
|
111
|
+
out.append({"thread_id": f"{f.parent.parent.name}/{f.parent.name}", "state_root": str(root),
|
|
112
|
+
"engine": pin.get("engine"), "reason": pin.get("reason")})
|
|
113
|
+
return out
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def workflow_pins(home: Path) -> list[dict[str, Any]]:
|
|
117
|
+
entries = _read(home / "registry.json").get("workflows") or []
|
|
118
|
+
return [{"workflow": e.get("name"), "engine": e["engine_pin"].get("engine"), "reason": e["engine_pin"].get("reason")}
|
|
119
|
+
for e in entries if isinstance(e, dict) and isinstance(e.get("engine_pin"), dict)]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def store_layouts(home: Path, roots: Sequence[Path]) -> list[dict[str, Any]]:
|
|
123
|
+
out = []
|
|
124
|
+
for kind, folder in [("home", home), *(("state_root", r) for r in roots)]:
|
|
125
|
+
man = _read(folder / "manifest.json")
|
|
126
|
+
out.append({"kind": kind, "path": str(folder), "layout": man.get("layout"),
|
|
127
|
+
"backup": man.get("backup"), "moved_by": man.get("moved_by")})
|
|
128
|
+
return out
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def plan(home: Path, engine: Path | None) -> dict[str, Any]:
|
|
132
|
+
"""UPD-B14, UPD-B6 step 2: what an update would do; reads only."""
|
|
133
|
+
cur = envmod.current(home)
|
|
134
|
+
if engine is None:
|
|
135
|
+
return {"decision": "no_source", "current": cur}
|
|
136
|
+
rel = source_release(engine)
|
|
137
|
+
digest = envmod.source_digest(engine)
|
|
138
|
+
target = {"engine_version": rel.get("engine_version"), "digest": digest,
|
|
139
|
+
"folder": f"{rel.get('engine_version')}-{digest[:12]}", "store_layout": rel.get("store_layout")}
|
|
140
|
+
if cur is None:
|
|
141
|
+
decision = "no_engine"
|
|
142
|
+
elif _version(cur.get("engine_version")) > _version(target["engine_version"]):
|
|
143
|
+
decision = "refused_downgrade"
|
|
144
|
+
elif cur.get("engine_version") == target["engine_version"] and cur.get("digest") == digest:
|
|
145
|
+
decision = "up_to_date"
|
|
146
|
+
elif cur.get("engine_version") == target["engine_version"]:
|
|
147
|
+
decision = "reinstall"
|
|
148
|
+
else:
|
|
149
|
+
decision = "install"
|
|
150
|
+
roots = index_roots(home)
|
|
151
|
+
layouts = store_layouts(home, roots)
|
|
152
|
+
new_layout = int(rel.get("store_layout") or 0)
|
|
153
|
+
return {"decision": decision, "current": cur, "target": target, "release": rel,
|
|
154
|
+
"live": live_processes(roots), "thread_pins": thread_pins(roots), "workflow_pins": workflow_pins(home),
|
|
155
|
+
"stores": [{**s, "moves": isinstance(s["layout"], int) and s["layout"] < new_layout} for s in layouts],
|
|
156
|
+
"extras": list((cur or {}).get("extras") or [])}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
ENGINE_SAYS = {
|
|
160
|
+
"up_to_date": "engine {cur} is up to date",
|
|
161
|
+
"install": "will install engine {new} beside {cur}",
|
|
162
|
+
"reinstall": "will reinstall engine {new}: same version, other content",
|
|
163
|
+
"refused_downgrade": "refused: the installed engine {cur} is newer than this copy's {new}; an older "
|
|
164
|
+
"tempergraph is probably first on PATH, so run the newer copy's `tempergraph update`",
|
|
165
|
+
"no_engine": "no engine is installed; run `tempergraph install` first",
|
|
166
|
+
"no_source": "no staged engine found beside this code; run the tempergraph plugin's bin/tempergraph update",
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _plan_lines(p: dict[str, Any], installed: bool = False) -> list[dict[str, Any]]:
|
|
171
|
+
"""UPD-B15: one line per kind, each with a fixed key set."""
|
|
172
|
+
cur, target = p.get("current") or {}, p.get("target") or {}
|
|
173
|
+
says = ENGINE_SAYS[p["decision"]].format(cur=cur.get("engine_version"), new=target.get("engine_version"))
|
|
174
|
+
if installed:
|
|
175
|
+
says = f"installed engine {target.get('engine_version')} ({target.get('folder')})"
|
|
176
|
+
lines: list[dict[str, Any]] = [{"kind": "engine", "says": says, "decision": p["decision"],
|
|
177
|
+
"state": "installed" if installed else p["decision"],
|
|
178
|
+
"current": cur.get("engine_version"), "target": target.get("engine_version"),
|
|
179
|
+
"digest": target.get("digest")}]
|
|
180
|
+
rel_extras = (p.get("release") or {}).get("extras") or {}
|
|
181
|
+
for name in sorted(rel_extras):
|
|
182
|
+
lines.append({"kind": "extras", "says": f"{name} {rel_extras[name]}: "
|
|
183
|
+
f"{'installed' if name in p.get('extras', []) else 'not installed'}", "name": name,
|
|
184
|
+
"range": rel_extras[name], "state": "installed" if name in p.get("extras", []) else "absent"})
|
|
185
|
+
if not rel_extras:
|
|
186
|
+
lines.append({"kind": "extras", "says": "this release has no optional executor package", "name": None,
|
|
187
|
+
"range": None, "state": "none"})
|
|
188
|
+
for lv in p.get("live") or []:
|
|
189
|
+
lines.append({"kind": "live", "says": f"{lv['thread_id']} keeps engine {lv.get('engine_version') or '?'} "
|
|
190
|
+
"until it exits", "thread_id": lv["thread_id"], "pid": lv["pid"],
|
|
191
|
+
"engine": lv.get("engine_version"), "state_root": lv["state_root"]})
|
|
192
|
+
by_root: dict[str, list[dict[str, Any]]] = {}
|
|
193
|
+
for t in p.get("thread_pins") or []:
|
|
194
|
+
by_root.setdefault(t["state_root"], []).append(t)
|
|
195
|
+
for root, pins in sorted(by_root.items()):
|
|
196
|
+
lines.append({"kind": "threads", "says": f"{len(pins)} thread(s) pinned to an older engine in {root}",
|
|
197
|
+
"state_root": root, "pinned": len(pins),
|
|
198
|
+
"reasons": sorted({str(t.get("reason")) for t in pins})})
|
|
199
|
+
for s in p.get("stores") or []:
|
|
200
|
+
if s.get("moves"):
|
|
201
|
+
lines.append({"kind": "store", "says": f"{s['path']} moves from layout {s['layout']} at the first "
|
|
202
|
+
"run on the new engine, with a backup", "path": s["path"], "from_layout": s["layout"],
|
|
203
|
+
"backup": True})
|
|
204
|
+
return lines
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _workflow_lines(rec: dict[str, Any]) -> list[dict[str, Any]]:
|
|
208
|
+
out = []
|
|
209
|
+
for w in rec.get("workflows") or []:
|
|
210
|
+
pin = w.get("engine_pin") or {}
|
|
211
|
+
local = w.get("kind") == "local"
|
|
212
|
+
remedy = (f"tempergraph upgrade {w.get('name')}" if local else "update the workflow's plugin") if pin or \
|
|
213
|
+
w.get("state") == "not_loaded" else ""
|
|
214
|
+
says = f"{w.get('name')} {w.get('version') or ''}: {w.get('state')}" + (
|
|
215
|
+
f", pinned to engine {pin.get('engine')} ({pin.get('reason')}); it keeps working there. {remedy}"
|
|
216
|
+
if pin else f". {remedy}" if remedy else "")
|
|
217
|
+
out.append({"kind": "workflow", "says": says, "name": w.get("name"), "version": w.get("version"),
|
|
218
|
+
"source": w.get("kind"), "state": w.get("state"), "dependencies": w.get("dependencies"),
|
|
219
|
+
"engine_pin": pin or None, "findings": w.get("findings") or [], "remedy": remedy})
|
|
220
|
+
return out
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _change_lines(home: Path) -> list[dict[str, Any]]:
|
|
224
|
+
"""UPD-B27: one `changes` line for each registry entry that holds a `previous`; reads only the registry and
|
|
225
|
+
the packages' files."""
|
|
226
|
+
from tempergraph.package import change_report
|
|
227
|
+
from tempergraph.package.registry import RegistryRefusal, read_entries
|
|
228
|
+
|
|
229
|
+
try:
|
|
230
|
+
entries = read_entries(home)
|
|
231
|
+
except RegistryRefusal:
|
|
232
|
+
return []
|
|
233
|
+
out = []
|
|
234
|
+
for e in entries:
|
|
235
|
+
if not e.get("previous"):
|
|
236
|
+
continue
|
|
237
|
+
rep = change_report.build(e)
|
|
238
|
+
out.append({"kind": "changes", "says": "\n".join(change_report.lines(rep)), "name": e.get("name"), **rep})
|
|
239
|
+
return out
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _report(out: IO[str], lines: list[dict[str, Any]], as_json: bool) -> None:
|
|
243
|
+
for line in lines:
|
|
244
|
+
out.write((json.dumps(line) if as_json else f"{line['kind']}: {line['says']}") + "\n")
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def kept_engines(home: Path, roots: Sequence[Path]) -> dict[str, str]:
|
|
248
|
+
"""UPD-B11, UPD-B12, UPD-B13: the environments `--prune-engines` never removes, each with why."""
|
|
249
|
+
eng = envmod.engines_dir(home)
|
|
250
|
+
kept: dict[str, str] = {}
|
|
251
|
+
for name in ("current", "previous"):
|
|
252
|
+
path = _read(eng / f"{name}.json").get("path")
|
|
253
|
+
if path:
|
|
254
|
+
kept.setdefault(Path(str(path)).name, name)
|
|
255
|
+
for w in workflow_pins(home):
|
|
256
|
+
kept.setdefault(str(w["engine"]), f"workflow {w['workflow']} is pinned to it")
|
|
257
|
+
for t in thread_pins(roots):
|
|
258
|
+
kept.setdefault(str(t["engine"]), f"thread {t['thread_id']} is pinned to it")
|
|
259
|
+
for lv in live_processes(roots):
|
|
260
|
+
if lv.get("engine"):
|
|
261
|
+
kept.setdefault(str(lv["engine"]), f"live run {lv['thread_id']} runs on it")
|
|
262
|
+
return kept
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def prune(home: Path, *, dry_run: bool = False) -> list[dict[str, Any]]:
|
|
266
|
+
eng = envmod.engines_dir(home)
|
|
267
|
+
kept = kept_engines(home, index_roots(home))
|
|
268
|
+
lines: list[dict[str, Any]] = []
|
|
269
|
+
for env in sorted(p for p in eng.iterdir() if p.is_dir()) if eng.is_dir() else []:
|
|
270
|
+
why = kept.get(env.name)
|
|
271
|
+
if why:
|
|
272
|
+
lines.append({"kind": "engine", "says": f"kept {env.name}: {why}", "state": "kept", "engine": env.name,
|
|
273
|
+
"reason": why})
|
|
274
|
+
continue
|
|
275
|
+
if not dry_run:
|
|
276
|
+
shutil.rmtree(env, ignore_errors=True)
|
|
277
|
+
lines.append({"kind": "engine", "says": f"{'would remove' if dry_run else 'removed'} {env.name}",
|
|
278
|
+
"state": "would_remove" if dry_run else "removed", "engine": env.name, "reason": None})
|
|
279
|
+
return lines
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def rollback(home: Path, *, restore_backups: bool = False, dry_run: bool = False) -> tuple[int, list[dict[str, Any]]]:
|
|
283
|
+
"""UPD-B17: swap `current.json` and `previous.json`, unless a store's layout is one the previous engine
|
|
284
|
+
cannot read; `--restore-backups` restores each such store's pre-migration backup when nothing ran since."""
|
|
285
|
+
from tempergraph.store import migrate
|
|
286
|
+
|
|
287
|
+
eng = envmod.engines_dir(home)
|
|
288
|
+
cur, prev = _read(eng / "current.json"), _read(eng / "previous.json")
|
|
289
|
+
if not prev or not (Path(str(prev.get("path") or "")) / ".complete").is_file():
|
|
290
|
+
return 2, [{"kind": "engine", "says": "no previous engine to roll back to", "state": "refused"}]
|
|
291
|
+
reads = [int(n) for n in prev.get("reads_store_layouts") or [1]]
|
|
292
|
+
blocked = [s for s in store_layouts(home, index_roots(home)) if isinstance(s["layout"], int)
|
|
293
|
+
and s["layout"] not in reads]
|
|
294
|
+
lines: list[dict[str, Any]] = []
|
|
295
|
+
for s in blocked:
|
|
296
|
+
ok = restore_backups and migrate.restorable(Path(s["path"]))
|
|
297
|
+
lines.append({"kind": "store", "says": f"{s['path']} has layout {s['layout']}, which engine "
|
|
298
|
+
f"{prev.get('engine_version')} cannot read" + ("; its backup will be restored" if ok else ""),
|
|
299
|
+
"path": s["path"], "from_layout": s["layout"], "backup": bool(ok)})
|
|
300
|
+
if not ok:
|
|
301
|
+
lines.append({"kind": "summary", "says": "rollback refused; pass --restore-backups to restore each "
|
|
302
|
+
"store's pre-migration backup when no run has written to it since"
|
|
303
|
+
if not restore_backups else f"rollback refused: {s['path']} has been written to since "
|
|
304
|
+
"its migration, so its backup cannot be restored"})
|
|
305
|
+
return 2, lines
|
|
306
|
+
if dry_run:
|
|
307
|
+
lines.append({"kind": "summary", "says": f"would switch back to engine {prev.get('engine_version')}"})
|
|
308
|
+
return 0, lines
|
|
309
|
+
for s in blocked:
|
|
310
|
+
migrate.restore(Path(s["path"]))
|
|
311
|
+
write_json(eng / "previous.json", cur)
|
|
312
|
+
write_json(eng / "current.json", {**prev, "switched_at": now_iso()})
|
|
313
|
+
lines.append({"kind": "engine", "says": f"switched back to engine {prev.get('engine_version')}; "
|
|
314
|
+
f"{cur.get('engine_version')} is kept as previous", "state": "rolled_back",
|
|
315
|
+
"current": prev.get("engine_version"), "target": cur.get("engine_version")})
|
|
316
|
+
return 0, lines
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def update(argv: Sequence[str], *, home: Path | None = None, builder: envmod.Builder | None = None,
|
|
320
|
+
out: IO[str] | None = None, engine: Path | None = None, plugin_version: str | None = None) -> int:
|
|
321
|
+
out = out or sys.stdout
|
|
322
|
+
a = parser().parse_args(list(argv))
|
|
323
|
+
home = home or home_path()
|
|
324
|
+
if a.rollback:
|
|
325
|
+
code, lines = rollback(home, restore_backups=a.restore_backups, dry_run=a.dry_run or a.check)
|
|
326
|
+
_report(out, lines, a.json)
|
|
327
|
+
return code
|
|
328
|
+
if a.prune_engines:
|
|
329
|
+
_report(out, prune(home, dry_run=a.dry_run or a.check), a.json)
|
|
330
|
+
return 0
|
|
331
|
+
engine = engine or find_source()
|
|
332
|
+
p = plan(home, engine)
|
|
333
|
+
lines = _plan_lines(p)
|
|
334
|
+
decision = p["decision"]
|
|
335
|
+
if a.check or a.dry_run or decision in ("up_to_date", "refused_downgrade", "no_engine", "no_source"):
|
|
336
|
+
if a.check:
|
|
337
|
+
lines += _change_lines(home)
|
|
338
|
+
if a.dry_run and decision in ("install", "reinstall"):
|
|
339
|
+
lines.append({"kind": "summary", "says": "would write: "
|
|
340
|
+
f"engines/{p['target']['folder']}/, engines/previous.json, engines/current.json, "
|
|
341
|
+
"registry.json; nothing was written"})
|
|
342
|
+
else:
|
|
343
|
+
lines.append({"kind": "summary", "says": {
|
|
344
|
+
"up_to_date": "you are on the latest engine of this plugin copy; nothing to do",
|
|
345
|
+
"install": "an update is available: run `tempergraph update`",
|
|
346
|
+
"reinstall": "this plugin copy's engine differs from the installed one: run `tempergraph update`",
|
|
347
|
+
}.get(decision, ENGINE_SAYS[decision].format(cur=(p.get("current") or {}).get("engine_version"),
|
|
348
|
+
new=(p.get("target") or {}).get("engine_version")))})
|
|
349
|
+
_report(out, lines, a.json)
|
|
350
|
+
return 2 if decision in ("refused_downgrade", "no_engine", "no_source") and not a.check else 0
|
|
351
|
+
python = find_python()
|
|
352
|
+
if python is None:
|
|
353
|
+
_report(out, [{"kind": "engine", "says": "no Python 3.11 or newer found; install one or set "
|
|
354
|
+
"TEMPERGRAPH_PYTHON", "decision": decision, "state": "no_python", "current": None,
|
|
355
|
+
"target": None, "digest": None}], a.json)
|
|
356
|
+
return 2
|
|
357
|
+
assert engine is not None
|
|
358
|
+
b = builder or envmod.VenvBuilder()
|
|
359
|
+
extras = tuple(dict.fromkeys([*p["extras"], *a.extras]))
|
|
360
|
+
rel = p["release"]
|
|
361
|
+
try:
|
|
362
|
+
inst = envmod.install_engine(home, python[0], engine, b, extras, version=str(rel["engine_version"])) # 3, 4
|
|
363
|
+
from tempergraph.store import migrate
|
|
364
|
+
|
|
365
|
+
migrate.migrate(home, target=int(rel.get("store_layout") or 1), engine=str(rel["engine_version"])) # 5
|
|
366
|
+
except (envmod.InstallFailed, OSError, RuntimeError) as exc: # a complete new folder may stay; it is prunable
|
|
367
|
+
_report(out, [{"kind": "engine", "says": f"update failed: {exc}; nothing was switched",
|
|
368
|
+
"decision": decision, "state": "failed", "current": (p["current"] or {}).get("engine_version"),
|
|
369
|
+
"target": rel.get("engine_version"), "digest": p["target"]["digest"]}], a.json)
|
|
370
|
+
return 1
|
|
371
|
+
old = Path(str(p["current"]["path"])).name
|
|
372
|
+
envmod.switch(home, inst, extras=extras, release_doc=rel) # 6
|
|
373
|
+
shim.write_shim(home)
|
|
374
|
+
from tempergraph.schedule import triggers
|
|
375
|
+
|
|
376
|
+
triggers.refresh(home) # TCK-B8: an `os` entry is rewritten only if the shim path changed; nothing when none exists
|
|
377
|
+
rec = b.reconcile(inst.env, previous=old)
|
|
378
|
+
lines = _plan_lines(p, installed=True)
|
|
379
|
+
if rec.get("error"):
|
|
380
|
+
lines.append({"kind": "workflow", "says": f"registry not reconciled: {rec['error']}", "name": None,
|
|
381
|
+
"version": None, "source": None, "state": "error", "dependencies": None, "engine_pin": None,
|
|
382
|
+
"findings": [], "remedy": "tempergraph workflows reinstall --all"})
|
|
383
|
+
lines += _workflow_lines(rec)
|
|
384
|
+
if plugin_version or os.environ.get("CLAUDE_PLUGIN_ROOT"):
|
|
385
|
+
pv = plugin_version or str(_read(Path(os.environ["CLAUDE_PLUGIN_ROOT"]) / ".claude-plugin" / "plugin.json")
|
|
386
|
+
.get("version") or "")
|
|
387
|
+
same = pv == str(rel["engine_version"])
|
|
388
|
+
lines.append({"kind": "plugin", "says": f"plugin {pv} {'matches' if same else 'differs from'} engine "
|
|
389
|
+
f"{rel['engine_version']}" + ("" if same else "; run /reload-plugins"), "plugin": pv,
|
|
390
|
+
"engine": rel["engine_version"], "match": same})
|
|
391
|
+
unpinned = [e for e in (envmod.engines_dir(home).iterdir()) if e.is_dir()
|
|
392
|
+
and e.name not in kept_engines(home, index_roots(home))]
|
|
393
|
+
pinned = [w for w in lines if w["kind"] == "workflow" and w.get("engine_pin")]
|
|
394
|
+
lines.append({"kind": "summary", "says": f"you are on engine {rel['engine_version']}"
|
|
395
|
+
+ (f"; {len(pinned)} workflow(s) stay on the previous engine until upgraded" if pinned
|
|
396
|
+
else "; nothing else to do")
|
|
397
|
+
+ (f"; {len(unpinned)} old engine(s) can go with `tempergraph update --prune-engines`"
|
|
398
|
+
if len(unpinned) > KEEP_UNPINNED else "")})
|
|
399
|
+
_report(out, lines, a.json)
|
|
400
|
+
return 0
|
|
File without changes
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""The diagram model (LIF-B7 to LIF-B16): versioned JSON with a digest, generated from the spec, verified against the
|
|
2
|
+
compiled graph (CMP-B6, CMP-AC4). Renderers are pure; digests, not bytes, are compared (LIF-B3).
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from tempergraph.constants import SCHEMA
|
|
12
|
+
from tempergraph.contracts import WorkflowSpec
|
|
13
|
+
from tempergraph.model import flow
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def diagram_model(spec: WorkflowSpec) -> dict[str, Any]:
|
|
17
|
+
order = flow.effective_order(spec)
|
|
18
|
+
nodes: list[str] = []
|
|
19
|
+
edges: list[list[str]] = []
|
|
20
|
+
units: list[dict[str, Any]] = []
|
|
21
|
+
for unit in order:
|
|
22
|
+
step, judge, gate, human = flow.node_names(unit)
|
|
23
|
+
nodes += [step, judge, gate, human]
|
|
24
|
+
edges += [[step, judge, "next"], [judge, gate, "next"]]
|
|
25
|
+
s = flow.successors(spec, unit)
|
|
26
|
+
for token, targets in s.by_token().items():
|
|
27
|
+
for t in targets:
|
|
28
|
+
edges.append([gate, t, token])
|
|
29
|
+
fb = flow.fallback_node(spec, unit)
|
|
30
|
+
if fb:
|
|
31
|
+
edges.append([gate, fb, "FALLBACK"])
|
|
32
|
+
dl = flow.deadline_node(spec, unit)
|
|
33
|
+
for t in flow.human_targets(spec, unit):
|
|
34
|
+
edges.append([human, t, "DEADLINE" if t == dl and t not in s.proceed else "decision"])
|
|
35
|
+
u = spec.units.get(unit)
|
|
36
|
+
if u is not None and u.kind == "parallel": # the fork to every branch and the engine-owned join
|
|
37
|
+
fork = flow.fork_node(unit)
|
|
38
|
+
nodes.append(fork)
|
|
39
|
+
for b in u.branches:
|
|
40
|
+
nodes.append(flow.done_node(b))
|
|
41
|
+
edges += [[fork, flow.step_node(b), "fork"], [flow.done_node(b), step, "join"]]
|
|
42
|
+
if u is not None and u.council is not None: # CMP-B16: a council is one box of the unit's four nodes, its mode named, no member count
|
|
43
|
+
summary = f"{u.council.mode} council"
|
|
44
|
+
else:
|
|
45
|
+
summary = (u.step.summary if u is not None and u.step is not None else "") if u else "outcome gate"
|
|
46
|
+
entry: dict[str, Any] = {
|
|
47
|
+
"name": unit,
|
|
48
|
+
"kind": u.kind if u is not None else "outcome",
|
|
49
|
+
"summary": summary,
|
|
50
|
+
"approval": bool(u.gate.approval) if u is not None else False,
|
|
51
|
+
}
|
|
52
|
+
if flow.is_contest(spec, unit): # CMP-B16: a contest is one unit, drawn with its slot count
|
|
53
|
+
entry["slots"] = len(flow.slot_names(spec, unit))
|
|
54
|
+
units.append(entry)
|
|
55
|
+
nodes.append(flow.FINALIZER)
|
|
56
|
+
edges.append([flow.FINALIZER, flow.END, "next"])
|
|
57
|
+
edges.append(["__start__", flow.entry_node(spec, order[0]), "next"])
|
|
58
|
+
shape = {"nodes": sorted(nodes), "edges": sorted({(a, b) for a, b, _ in edges})}
|
|
59
|
+
digest = hashlib.sha256(json.dumps(shape, sort_keys=True).encode()).hexdigest()
|
|
60
|
+
return {
|
|
61
|
+
"schema_version": SCHEMA["diagram_model"],
|
|
62
|
+
"workflow": spec.name,
|
|
63
|
+
"units": units,
|
|
64
|
+
"nodes": nodes,
|
|
65
|
+
"edges": edges,
|
|
66
|
+
"digest": digest,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def edge_set(model: dict[str, Any]) -> set[tuple[str, str]]:
|
|
71
|
+
return {(a, b) for a, b, _ in model["edges"]}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def to_mermaid(model: dict[str, Any]) -> str:
|
|
75
|
+
"""Draw one box per unit, with its routing edges between units (counts and words only)."""
|
|
76
|
+
lines = ["flowchart TD", " start((start))"]
|
|
77
|
+
ids = {u["name"]: f"u{i}" for i, u in enumerate(model["units"])}
|
|
78
|
+
ov = model.get("overlay") or {}
|
|
79
|
+
for u in model["units"]:
|
|
80
|
+
label = u["name"] + (f"<br/>{u['summary']}" if u["summary"] else "") + (" ✋" if u["approval"] else "")
|
|
81
|
+
if u.get("slots"): # a contest: its slot count beside the unit's name (CMP-B16)
|
|
82
|
+
label += f"<br/>{u['slots']} slots"
|
|
83
|
+
o = (ov.get("units") or {}).get(u["name"])
|
|
84
|
+
if o: # the run overlay (OBS-B15): counts and engine words only
|
|
85
|
+
verdicts = ", ".join(f"{k} {v}" for k, v in o["verdicts"].items())
|
|
86
|
+
label += f"<br/>visits {o['visits']} · sessions {o['sessions']}" + (f" · {verdicts}" if verdicts else "")
|
|
87
|
+
lines.append(f' {ids[u["name"]]}["{label}"]')
|
|
88
|
+
lines.append(" fin([finalizer])")
|
|
89
|
+
lines.append(" stop((end))")
|
|
90
|
+
for a, b, _ in model["edges"]:
|
|
91
|
+
if a == "__start__":
|
|
92
|
+
entry = [e.split(".")[0] for x, e, t in model["edges"] if x == b and t == "fork"] or [b.split(".")[0]]
|
|
93
|
+
lines += [f" start --> {ids[name]}" for name in entry if name in ids]
|
|
94
|
+
seen: set[tuple[str, str, str]] = set()
|
|
95
|
+
taken: dict[tuple[str, str, str], int] = {}
|
|
96
|
+
for a, b, token, n in ov.get("edges") or []:
|
|
97
|
+
dst_unit = "fin" if b == flow.FINALIZER.split(".")[0] else b
|
|
98
|
+
taken[(a, dst_unit, token)] = taken.get((a, dst_unit, token), 0) + n
|
|
99
|
+
forks: dict[str, list[str]] = {a: [] for a, _, t in model["edges"] if t == "fork"}
|
|
100
|
+
for a, b, token in model["edges"]:
|
|
101
|
+
if token == "fork":
|
|
102
|
+
forks[a].append(b.split(".")[0])
|
|
103
|
+
joins = {a: b.split(".")[0] for a, b, t in model["edges"] if t == "join"}
|
|
104
|
+
drawn = {"PROCEED": "-->", "BACK": "-.->|back|", "FALLBACK": "-.->|fallback|", "DEADLINE": "-.->|deadline|"}
|
|
105
|
+
for a, b, token in model["edges"]:
|
|
106
|
+
src = a.split(".")[0]
|
|
107
|
+
if (a.endswith(".gate") and token in ("PROCEED", "BACK", "FALLBACK")) or token == "DEADLINE":
|
|
108
|
+
# a block is entered at every branch, and a branch's pass goes to its join
|
|
109
|
+
names = forks[b] if b in forks else [joins[b]] if b in joins else [b.split(".")[0]]
|
|
110
|
+
for name in names:
|
|
111
|
+
dst = "fin" if b == flow.FINALIZER else ids.get(name)
|
|
112
|
+
if dst is None:
|
|
113
|
+
continue
|
|
114
|
+
key = (ids[src], dst, token)
|
|
115
|
+
if key in seen:
|
|
116
|
+
continue
|
|
117
|
+
seen.add(key)
|
|
118
|
+
n = taken.pop((src, "fin" if b == flow.FINALIZER else b.split(".")[0], token), 0)
|
|
119
|
+
mark = f" ×{n}" if n else ""
|
|
120
|
+
arrow = (f"-->|{mark.strip()}|" if n else "-->") if token == "PROCEED" else \
|
|
121
|
+
drawn[token].replace("|", f"|{mark.strip()} " if n else "|", 1) if n else drawn[token]
|
|
122
|
+
lines.append(f" {ids[src]} {arrow} {dst}")
|
|
123
|
+
for (src, dst_unit, token), n in sorted(taken.items()): # taken routes the unit boxes do not draw
|
|
124
|
+
dst = "fin" if dst_unit in ("fin", "end") else ids.get(dst_unit)
|
|
125
|
+
if src in ids and dst is not None:
|
|
126
|
+
lines.append(f" {ids[src]} -.->|{token.lower()} ×{n}| {dst}")
|
|
127
|
+
lines.append(" fin --> stop")
|
|
128
|
+
return "\n".join(lines) + "\n"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def to_svg(model: dict[str, Any]) -> str:
|
|
132
|
+
"""The same boxes and routing edges as :func:`to_mermaid`, as one standalone SVG: units top to bottom, forward
|
|
133
|
+
edges on the left, back, fallback and deadline edges dashed on the right; with an overlay, each box carries the
|
|
134
|
+
counts the overlay holds for its unit and nothing else (OBS-B15)."""
|
|
135
|
+
from html import escape
|
|
136
|
+
|
|
137
|
+
names = [u["name"] for u in model["units"]] + ["finalizer"]
|
|
138
|
+
w, h, gap, x = 300, 58, 30, 70
|
|
139
|
+
ys = {n: 20 + i * (h + gap) for i, n in enumerate(names)}
|
|
140
|
+
height = 20 + len(names) * (h + gap)
|
|
141
|
+
ov = (model.get("overlay") or {}).get("units") or {}
|
|
142
|
+
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{x + w + 140}" height="{height}" '
|
|
143
|
+
'font-family="sans-serif" font-size="13">',
|
|
144
|
+
'<defs><marker id="a" markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">'
|
|
145
|
+
'<path d="M0,0 L8,4 L0,8 z" fill="#555"/></marker></defs>']
|
|
146
|
+
for u in model["units"]:
|
|
147
|
+
y = ys[u["name"]]
|
|
148
|
+
parts.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="4" fill="#fff" stroke="#333"/>')
|
|
149
|
+
label = u["name"] + (" (approval)" if u["approval"] else "") + (f" · {u['slots']} slots" if u.get("slots")
|
|
150
|
+
else "")
|
|
151
|
+
parts.append(f'<text x="{x + 10}" y="{y + 18}" font-weight="bold">{escape(label)}</text>')
|
|
152
|
+
if u["summary"]:
|
|
153
|
+
parts.append(f'<text x="{x + 10}" y="{y + 34}" fill="#555">{escape(u["summary"])}</text>')
|
|
154
|
+
o = ov.get(u["name"])
|
|
155
|
+
if o:
|
|
156
|
+
verdicts = ", ".join(f"{k} {v}" for k, v in o["verdicts"].items())
|
|
157
|
+
line = f"visits {o['visits']} · sessions {o['sessions']}" + (f" · {verdicts}" if verdicts else "")
|
|
158
|
+
parts.append(f'<text x="{x + 10}" y="{y + 50}" fill="#264">{escape(line)}</text>')
|
|
159
|
+
fy = ys["finalizer"]
|
|
160
|
+
parts.append(f'<rect x="{x}" y="{fy}" width="{w}" height="{h}" rx="22" fill="#fff" stroke="#333"/>')
|
|
161
|
+
parts.append(f'<text x="{x + 10}" y="{fy + 18}" font-weight="bold">finalizer</text>')
|
|
162
|
+
seen: set[tuple[str, str, str]] = set()
|
|
163
|
+
for a, b, token in model["edges"]:
|
|
164
|
+
if not ((a.endswith(".gate") and token in ("PROCEED", "BACK", "FALLBACK")) or token == "DEADLINE"):
|
|
165
|
+
continue
|
|
166
|
+
src, dst = a.split(".")[0], "finalizer" if b == flow.FINALIZER else b.split(".")[0]
|
|
167
|
+
if src not in ys or dst not in ys or (src, dst, token) in seen:
|
|
168
|
+
continue
|
|
169
|
+
seen.add((src, dst, token))
|
|
170
|
+
y1, y2 = ys[src], ys[dst]
|
|
171
|
+
if token == "PROCEED" and y2 > y1:
|
|
172
|
+
if y2 == y1 + h + gap:
|
|
173
|
+
parts.append(f'<line x1="{x + w / 2}" y1="{y1 + h}" x2="{x + w / 2}" y2="{y2 - 2}" stroke="#555" '
|
|
174
|
+
'marker-end="url(#a)"/>')
|
|
175
|
+
else:
|
|
176
|
+
parts.append(f'<path d="M{x},{y1 + h / 2} C{x - 60},{y1 + h / 2} {x - 60},{y2 + h / 2} '
|
|
177
|
+
f'{x - 2},{y2 + h / 2}" fill="none" stroke="#555" marker-end="url(#a)"/>')
|
|
178
|
+
else:
|
|
179
|
+
word = {"BACK": "back", "FALLBACK": "fallback", "DEADLINE": "deadline"}.get(token, token.lower())
|
|
180
|
+
c = x + w + 90
|
|
181
|
+
parts.append(f'<path d="M{x + w},{y1 + h / 2} C{c},{y1 + h / 2} {c},{y2 + h / 2} {x + w + 2},{y2 + h / 2}" '
|
|
182
|
+
'fill="none" stroke="#555" stroke-dasharray="5,4" marker-end="url(#a)"/>')
|
|
183
|
+
parts.append(f'<text x="{c - 20}" y="{(y1 + y2 + h) / 2}" fill="#555" font-size="11">{word}</text>')
|
|
184
|
+
parts.append("</svg>")
|
|
185
|
+
return "\n".join(parts) + "\n"
|