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,126 @@
1
+ """`tempergraph upgrade <workflow>` and its alias `upgrade-check <workflow> [--stamp]` (WUP-B10, WUP-B11, WUP-B12, WUP-B13, VER-B16).
2
+
3
+ `--check` plans only: read-only and model-free. Without it the verb runs the phases of `package/upgrade.py` on
4
+ a branch of the workflow's source. The paired trial (`--trial`, V8) is not built in this release."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from tempergraph.constants import ENGINE_VERSION, ExitCode
14
+ from tempergraph.package import change_report
15
+ from tempergraph.package.registry import RegistryRefusal, read_entries
16
+ from tempergraph.package.stamp import check, read_stamp
17
+
18
+
19
+ def add_parsers(sub: Any) -> None:
20
+ for verb in ("upgrade", "upgrade-check"):
21
+ p = sub.add_parser(verb, help="bring a workflow up to the running engine, or only check it")
22
+ p.add_argument("workflow")
23
+ if verb == "upgrade":
24
+ p.add_argument("--check", action="store_true", help="plan only: read-only, model-free")
25
+ p.add_argument("--fail-on", choices=("pending", "never"), default="never")
26
+ p.add_argument("--no-assist", action="store_true", help="transforms only; assisted items stay manual")
27
+ p.add_argument("--executor", help="the executor of the upgrade workflow's sessions")
28
+ p.add_argument("--cap", type=float, default=10.0, help="cost cap of the assist run, in USD")
29
+ p.add_argument("--trial", action="store_true", help="also a paired trial of the result (later release)")
30
+ p.add_argument("--cases", help="the case set of --trial")
31
+ p.add_argument("--bump", action="store_true", help="write the proposed version to the branch")
32
+ p.add_argument("--open-pr", action="store_true", help="open a draft pull request with the report")
33
+ p.add_argument("--continue", dest="continue_id", metavar="UPGRADE_ID",
34
+ help="go on after a pause, a fix by hand or a failed check")
35
+ p.add_argument("--stamp", action="store_true")
36
+ p.add_argument("--format", choices=("text", "json"), default="json")
37
+
38
+
39
+ def cmd_upgrade(env: Any, a: argparse.Namespace) -> int:
40
+ path = _source(env, a.workflow)
41
+ if path is None:
42
+ env.err.write(f"tempergraph: unknown workflow {a.workflow!r}; `tempergraph workflows list` shows them\n")
43
+ return int(ExitCode.USAGE)
44
+ caps = {n: env.registry.get(n).capabilities() for n in env.registry.available()}
45
+ if a.verb == "upgrade-check" or a.check:
46
+ rep = check(path, caps, stamp=a.stamp, fail_on_pending=getattr(a, "fail_on", "never") == "pending")
47
+ if rep.refused:
48
+ env.err.write(f"tempergraph: {rep.refused}\n")
49
+ changes = _changes(rep.workflow)
50
+ if getattr(a, "format", "json") == "text":
51
+ prior = read_stamp(path)
52
+ lines = [f"upgrade {rep.workflow}: engine {(prior or {}).get('engine_version') or 'unstamped'} "
53
+ f"to {ENGINE_VERSION}"]
54
+ lines += [f" pending: {p['item_id']}" for p in rep.pending]
55
+ lines += change_report.lines(changes) if changes else []
56
+ env.out.write("\n".join(lines) + "\n")
57
+ else:
58
+ from tempergraph.engine_identity import identity
59
+
60
+ env.out.write(json.dumps({**rep.to_json(), "changes": changes, **identity(env.cwd)}, indent=2,
61
+ default=str) + "\n")
62
+ return rep.exit_code
63
+ if a.trial or a.cases:
64
+ env.err.write("tempergraph: upgrade --trial is not_in_release; verification runs V1 to V7\n")
65
+ return int(ExitCode.USAGE)
66
+ from tempergraph.package.upgrade import upgrade
67
+
68
+ host = None
69
+ if a.open_pr:
70
+ from tempergraph.improve.codehost import GhCodeHost
71
+
72
+ host = (getattr(env, "code_host", None) or GhCodeHost)()
73
+ caller = env.caller(a) # a mutating call: its caller is classified before any write (PRV-B13)
74
+ assist = getattr(env, "upgrade_assist", None)
75
+ if assist is None and not a.no_assist:
76
+ from tempergraph.builtin import upgrade as builtin
77
+
78
+ settings = env.run_settings() if env.run_settings else None
79
+
80
+ def assist(job: Any) -> Any:
81
+ return builtin.assist(job, env.registry, caller=caller, settings=settings)
82
+ out = upgrade(path, caps, no_assist=a.no_assist, stamp=a.stamp, bump=a.bump, open_pr=a.open_pr,
83
+ continue_id=a.continue_id, cap_usd=a.cap, executor=a.executor, host=host,
84
+ assist=assist)
85
+ if out.refused:
86
+ env.err.write(f"tempergraph: {out.refused}\n")
87
+ env.out.write((text(out) if a.format == "text" else json.dumps(out.to_json(), indent=2, default=str)) + "\n")
88
+ return out.exit_code
89
+
90
+
91
+ def text(rep: Any) -> str:
92
+ lines = [f"upgrade {rep.workflow}: engine {rep.from_engine or 'unstamped'} to {rep.to_engine}"
93
+ + (f", branch {rep.branch}" if rep.branch else "")]
94
+ lines += [f" before the upgrade: {b}" for b in rep.baseline_errors]
95
+ lines += [f" {i.item_id}: {i.action}, {i.state}" + (f" by {i.by}" if i.by else "")
96
+ + (f" ({i.reason})" if i.reason else "") for i in rep.items]
97
+ if rep.not_touched:
98
+ lines.append(" not touched: " + ", ".join(rep.not_touched))
99
+ lines += [f" {v.check}: {v.state}. {v.evidence}" for v in rep.checks]
100
+ if rep.proposed:
101
+ lines.append(f" proposed version {rep.proposed['version']} ({rep.proposed['level']}), "
102
+ f"requires_engine {rep.proposed['requires_engine']}")
103
+ lines += [f" warning: {w}" for w in rep.warnings]
104
+ if rep.exit_code == 4:
105
+ lines.append(f" fix what failed on the branch, then `tempergraph upgrade {rep.workflow} --continue "
106
+ f"{rep.upgrade_id}`")
107
+ return "\n".join(lines)
108
+
109
+
110
+ def _changes(workflow: str) -> dict[str, Any] | None:
111
+ """WUP-B22: the report of the registry entry of `workflow`; null without an entry or a `previous`."""
112
+ try:
113
+ entries = read_entries()
114
+ except RegistryRefusal:
115
+ return None
116
+ entry = next((e for e in entries if e.get("name") == workflow), None)
117
+ return change_report.build(entry) if entry and entry.get("previous") else None
118
+
119
+
120
+ def _source(env: Any, name: str) -> Path | None:
121
+ spec = env.catalog.specs.get(name)
122
+ if spec is not None and spec.package_root is not None:
123
+ return Path(spec.package_root)
124
+ p = Path(name)
125
+ p = p if p.is_absolute() else env.cwd / p
126
+ return p if (p / "tempergraph.json").is_file() else None
@@ -0,0 +1,96 @@
1
+ """`tempergraph workflows list|register|unregister|reinstall` (UPD-B20 to UPD-B24, CLI-B7, CLI-B8, CLI-B14).
2
+
3
+ `list` and `register --check` are read-only and call no model (OVR-B15). `list` prints one text line per entry (`0.1.0 -> 0.2.0 (3 changes)` when the version moved) and JSON with
4
+ `schema_version` under `--json`; the other actions print JSON.
5
+ Exit codes: 0 done, 2 a refusal (nothing written), 1 an engine error.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from tempergraph.constants import ExitCode
16
+ from tempergraph.model.validate import Finding
17
+ from tempergraph.package import registry as reg
18
+ from tempergraph.store.layout import NotInRepository, state_root_path
19
+
20
+
21
+ def add_parsers(sub: Any) -> None:
22
+ wf = sub.add_parser("workflows", help="the workflow registry")
23
+ act = wf.add_subparsers(dest="action", parser_class=type(wf))
24
+ ls = act.add_parser("list", help="the registry, with state and pins")
25
+ ls.add_argument("--json", action="store_true", help="print the registry as JSON (the default is text)")
26
+ rg = act.add_parser("register", help="register a local workflow package")
27
+ rg.add_argument("path")
28
+ rg.add_argument("--check", action="store_true", help="load and validate only; nothing is written")
29
+ ur = act.add_parser("unregister", help="remove a registry entry, never files")
30
+ ur.add_argument("name")
31
+ ri = act.add_parser("reinstall", help="dependencies, then load and validate")
32
+ ri.add_argument("name", nargs="?")
33
+ ri.add_argument("--all", action="store_true")
34
+
35
+
36
+ def _findings(fs: list[Finding]) -> list[dict[str, Any]]:
37
+ return [{"severity": f.severity, "code": f.code, "unit": f.unit, "message": f.message} for f in fs]
38
+
39
+
40
+ def _emit(env: Any, doc: Any) -> None:
41
+ env.out.write(json.dumps(doc, indent=2, default=str) + "\n")
42
+
43
+
44
+ def _list_line(r: dict[str, Any]) -> str:
45
+ """One text line of `list` (UPD-B26): name, version (the arrow form when it moved), state, reason, engine pin."""
46
+ version = str(r.get("version") or "-")
47
+ prev, n = r.get("previous_version"), int(r.get("changes_since_previous") or 0)
48
+ if prev and prev != r.get("version"):
49
+ version = f"{prev} -> {version} ({n} change{'' if n == 1 else 's'})"
50
+ parts = [str(r.get("name")), version, str(r.get("state"))]
51
+ if r.get("reason"):
52
+ parts.append(str(r["reason"]))
53
+ if r.get("engine_pin"):
54
+ parts.append(f"pinned {r['engine_pin']}")
55
+ return " ".join(parts)
56
+
57
+
58
+ def cmd_workflows(env: Any, a: argparse.Namespace) -> int:
59
+ caps = {n: env.registry.get(n).capabilities() for n in env.registry.available()}
60
+ try:
61
+ if a.action == "list":
62
+ doc = reg.listing()
63
+ if a.json:
64
+ _emit(env, doc)
65
+ else:
66
+ for r in doc["workflows"]:
67
+ env.out.write(_list_line(r) + "\n")
68
+ elif a.action == "register":
69
+ got = reg.register(Path(a.path) if Path(a.path).is_absolute() else env.cwd / a.path, caps,
70
+ check_only=a.check)
71
+ _emit(env, {"schema_version": 1, "registered": not a.check, "entry": got.entry,
72
+ "findings": _findings(got.findings)})
73
+ elif a.action == "unregister":
74
+ try:
75
+ roots = [state_root_path(env.cwd)]
76
+ except NotInRepository:
77
+ roots = [] # outside a repository only the registry is checked
78
+ entry = reg.unregister(a.name, roots)
79
+ _emit(env, {"schema_version": 1, "unregistered": entry["name"], "path": entry.get("path")})
80
+ elif a.action == "reinstall":
81
+ if bool(a.name) == bool(a.all):
82
+ env.err.write("tempergraph: workflows reinstall needs a name or --all\n")
83
+ return int(ExitCode.USAGE)
84
+ done = reg.reinstall(None if a.all else [a.name], caps)
85
+ _emit(env, {"schema_version": 1, "workflows": [
86
+ {"entry": c.entry, "findings": _findings(c.findings), "remedy": c.remedy} for c in done]})
87
+ return 0 if all(c.ok for c in done) else int(ExitCode.USAGE)
88
+ else:
89
+ env.err.write("tempergraph: workflows needs list, register, unregister or reinstall\n")
90
+ return int(ExitCode.USAGE)
91
+ except reg.RegistryRefusal as exc:
92
+ env.err.write(f"tempergraph: {exc}\n")
93
+ if exc.findings:
94
+ _emit(env, {"schema_version": 1, "refused": exc.code, "findings": _findings(exc.findings)})
95
+ return int(ExitCode.USAGE)
96
+ return 0
@@ -0,0 +1,6 @@
1
+ """The compiler (CMP): a validated workflow becomes a LangGraph StateGraph, four nodes per unit."""
2
+
3
+ from tempergraph.compiler.graph import CompiledWorkflow, UnitNodes, compile_workflow
4
+ from tempergraph.compiler.state import RunState, merge_units
5
+
6
+ __all__ = ["CompiledWorkflow", "RunState", "UnitNodes", "compile_workflow", "merge_units"]
@@ -0,0 +1,305 @@
1
+ """Four nodes per unit, one finalizer node, static edges for every target (CMP-B8, ADR `four-nodes-per-unit`).
2
+
3
+ The node bodies come from the gate funnel through :class:`UnitNodes`; this module owns only the graph
4
+ shape and the human node's ``interrupt``, which is its first statement (HUM-AC1). LangGraph is imported
5
+ only here and in the durability package.
6
+
7
+ A contest is a unit like any other here (CMP-B16, CMP-AC6): its four nodes, and no node per slot. Its slots are the
8
+ items of its own step node, which runs them up to `concurrency` at once and writes each under its slot (`item_view`,
9
+ `slot_writes`); its judge node grades them and picks. Only a concurrent map fans out through `Send` nodes.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass
16
+ from typing import Any, Protocol, TypedDict
17
+
18
+ from langchain_core.runnables import RunnableConfig
19
+ from langgraph.checkpoint.base import BaseCheckpointSaver
20
+ from langgraph.graph import END, START, StateGraph
21
+ from langgraph.types import Command, Send, interrupt
22
+
23
+ from tempergraph.compiler.state import ITEM, RunState, fold, item_end, item_view, slot, slot_writes
24
+ from tempergraph.contracts import WorkflowSpec
25
+ from tempergraph.model import flow
26
+
27
+ RECURSION_LIMIT = 10_000 # a backstop only; the attempt cap stops runs first (CMP-B5)
28
+
29
+
30
+ class UnknownRoutingToken(Exception):
31
+ pass
32
+
33
+
34
+ class UnitNodes(Protocol):
35
+ def step(self, unit: str, state: RunState, config: Any = None) -> dict[str, Any]: ...
36
+ def judge(self, unit: str, state: RunState) -> dict[str, Any]: ...
37
+ def gate(self, unit: str, state: RunState) -> dict[str, Any]: ...
38
+ def human(self, unit: str, state: RunState, decision: Any) -> dict[str, Any]: ...
39
+ def finalizer(self, state: RunState) -> dict[str, Any]: ...
40
+
41
+
42
+ @dataclass
43
+ class CompiledWorkflow:
44
+ graph: Any # CompiledStateGraph
45
+ spec: WorkflowSpec
46
+ nodes: list[str]
47
+ edges: list[tuple[str, str]] # every possible (source, target), conditional ones included
48
+ engine: Any = None # the node bodies' owner, for a state write deferred to the first node (`defer`)
49
+
50
+ def config(self, thread_id: str) -> dict[str, Any]:
51
+ return {"configurable": {"thread_id": thread_id}, "recursion_limit": RECURSION_LIMIT}
52
+
53
+
54
+ def _end(name: str) -> str:
55
+ return END if name == flow.END else name
56
+
57
+
58
+ def compile_workflow(spec: WorkflowSpec, nodes: UnitNodes, checkpointer: BaseCheckpointSaver | None) -> CompiledWorkflow:
59
+ g: Any = StateGraph(RunState)
60
+ order = flow.effective_order(spec)
61
+ names: list[str] = []
62
+ edges: list[tuple[str, str]] = []
63
+ post: Callable[[dict[str, Any]], dict[str, Any]] = getattr(nodes, "settle", lambda w: w)
64
+
65
+ for unit in order:
66
+ step, judge, gate, human = flow.node_names(unit)
67
+ fan_out = flow.concurrent_map(spec, unit) # MAP-B9: the items of a concurrent map run at once
68
+ item_nodes = {kind: flow.item_node(unit, kind) for kind in flow.ITEM_KINDS}
69
+ if unit in spec.units and spec.units[unit].kind == "subworkflow": # SWF-B8: the child is a subgraph of this node
70
+ g.add_node(step, _subgraph_node(nodes, unit, post))
71
+ elif unit in spec.units and spec.units[unit].kind == "council": # CNL-B14, ADR `new-node-kinds-keep-the-gated-unit`: its sessions are a subgraph
72
+ g.add_node(step, _council_node(nodes, unit, post))
73
+ elif fan_out: # this node reads the list and sends the items; it names where it may send them
74
+ g.add_node(step, _map_node(nodes, unit, post), destinations=tuple(dict.fromkeys(
75
+ (judge, item_nodes["step"], item_nodes["human"], *_goes(spec, unit)))))
76
+ else:
77
+ g.add_node(step, _bind1(nodes.step, unit, post))
78
+ g.add_node(judge, _bind1(nodes.judge, unit, post))
79
+ g.add_node(gate, _bind1(nodes.gate, unit, post))
80
+ g.add_node(human, _human_node(nodes, unit, post))
81
+ names += [step, judge, gate, human]
82
+ if fan_out: # the unit's own step node goes to its judge by itself, once every item has passed
83
+ for kind in flow.ITEM_KINDS:
84
+ dest = {"step": (item_nodes["judge"],), "judge": (item_nodes["gate"],),
85
+ "gate": (item_nodes["step"], step), "human": (item_nodes["step"], step)}[kind]
86
+ g.add_node(item_nodes[kind], _item_node(nodes, unit, kind, post), destinations=dest)
87
+ names.append(item_nodes[kind])
88
+ edges += [(step, item_nodes["step"]), (step, item_nodes["human"]), (item_nodes["step"], item_nodes["judge"]),
89
+ (item_nodes["judge"], item_nodes["gate"]), (item_nodes["gate"], item_nodes["step"]),
90
+ (item_nodes["gate"], step), (item_nodes["human"], item_nodes["step"]),
91
+ (item_nodes["human"], step)]
92
+ else:
93
+ g.add_edge(step, judge)
94
+ g.add_edge(judge, gate)
95
+ edges += [(step, judge), (judge, gate)]
96
+ gate_targets = flow.gate_targets(spec, unit)
97
+ g.add_conditional_edges(gate, _router(unit, gate_targets), {t: _end(t) for t in gate_targets})
98
+ edges += [(gate, t) for t in gate_targets]
99
+ human_targets = flow.human_targets(spec, unit)
100
+ g.add_conditional_edges(human, _router(unit, human_targets), {t: _end(t) for t in human_targets})
101
+ edges += [(human, t) for t in human_targets]
102
+
103
+ for join in order: # CMP-B10 to CMP-B16: a parallel block forks to every branch and joins on every pass
104
+ u = spec.units.get(join)
105
+ if u is None or u.kind != "parallel":
106
+ continue
107
+ fork = flow.fork_node(join)
108
+ enter = getattr(nodes, "fork", None) # WSP-B19, WSP-B11: a block with a writer branch is entered by the engine
109
+ if enter is not None and flow.writer_branches(spec, join):
110
+ g.add_node(fork, _bind1(enter, join, post))
111
+ else:
112
+ g.add_node(fork, _passthrough(fork))
113
+ names.append(fork)
114
+ dones = []
115
+ for b in u.branches:
116
+ done = flow.done_node(b)
117
+ g.add_node(done, _passthrough(done))
118
+ g.add_edge(fork, flow.step_node(b))
119
+ names.append(done)
120
+ dones.append(done)
121
+ edges.append((fork, flow.step_node(b)))
122
+ edges.append((done, flow.step_node(join)))
123
+ g.add_edge(dones, flow.step_node(join)) # the engine-owned AND-join
124
+
125
+ g.add_node(flow.FINALIZER, nodes.finalizer)
126
+ names.append(flow.FINALIZER)
127
+ g.add_edge(flow.FINALIZER, END)
128
+ edges.append((flow.FINALIZER, flow.END))
129
+ g.add_edge(START, flow.entry_node(spec, order[0]))
130
+ compiled = g.compile(checkpointer=checkpointer)
131
+ return CompiledWorkflow(graph=compiled, spec=spec, nodes=names, edges=edges, engine=nodes)
132
+
133
+
134
+ def _bind1(fn: Callable[[str, RunState], dict[str, Any]], unit: str,
135
+ post: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[[RunState], dict[str, Any]]:
136
+ def node(state: RunState) -> dict[str, Any]:
137
+ return post(fn(unit, state))
138
+
139
+ node.__name__ = f"{fn.__name__}_{unit}"
140
+ return node
141
+
142
+
143
+ def _subgraph_node(nodes: UnitNodes, unit: str, post: Callable[[dict[str, Any]], dict[str, Any]]
144
+ ) -> Callable[[RunState, RunnableConfig], dict[str, Any]]:
145
+ """The step node of a sub-workflow unit (SWF-B8): it invokes the child's own graph with this node's config, so the
146
+ child is a subgraph under the parent's checkpointer and thread, its checkpoint namespace nested in this node's;
147
+ a pause inside the child is a pause of this node. It hands back only what the unit exposes."""
148
+
149
+ def node(state: RunState, config: RunnableConfig) -> dict[str, Any]:
150
+ return post(nodes.step(unit, state, config))
151
+
152
+ node.__name__ = f"step_{unit}"
153
+ return node
154
+
155
+
156
+ class _CouncilState(TypedDict, total=False):
157
+ """The state of a council's subgraph: the attempt's run (a plain object, never checkpointed), the stage in hand and,
158
+ on a `Send` to a member node, the member's name."""
159
+
160
+ parent: Any
161
+ run: Any
162
+ stage: int
163
+ who: str
164
+ out: dict[str, Any]
165
+
166
+
167
+ def _council_node(nodes: Any, unit: str, post: Callable[[dict[str, Any]], dict[str, Any]]
168
+ ) -> Callable[[RunState], dict[str, Any]]:
169
+ """The step node of a council unit (CNL-B14, ADR `new-node-kinds-keep-the-gated-unit`): a subgraph of one member node per round and member (a `Send`
170
+ each), the engine-owned barrier that waits for every member's answer, failure or spoil before the next round, a pure
171
+ tally node and the chair node. The unit's usual judge, gate and human nodes follow in the parent graph. Each member
172
+ session is kept on its own as it ends (`run.council_run`), so the subgraph itself takes no checkpointer: a rerun of
173
+ the attempt finds the sessions that ended and runs only the others."""
174
+
175
+ def fan(s: _CouncilState) -> Any:
176
+ names = s["run"].dispatch(int(s["stage"]))
177
+ if not names:
178
+ return "tally"
179
+ return [Send("member", {"run": s["run"], "stage": s["stage"], "who": n}) for n in names]
180
+
181
+ def member(s: _CouncilState) -> dict[str, Any]:
182
+ nodes.council_member(s["run"], s["who"], int(s["stage"]))
183
+ return {}
184
+
185
+ def barrier(s: _CouncilState) -> dict[str, Any]:
186
+ return {"stage": nodes.council_close(s["run"], int(s["stage"]))}
187
+
188
+ def tally(s: _CouncilState) -> dict[str, Any]:
189
+ nodes.council_tally(s["run"])
190
+ return {}
191
+
192
+ def chair(s: _CouncilState) -> dict[str, Any]:
193
+ nodes.council_chair(s["run"])
194
+ return {"out": nodes.council_finish(s["run"])}
195
+
196
+ sub: Any = StateGraph(_CouncilState)
197
+ sub.add_node("open", lambda s: {"run": nodes.council_open(unit, s["parent"]), "stage": 0})
198
+ sub.add_node("member", member)
199
+ sub.add_node("barrier", barrier)
200
+ sub.add_node("tally", tally)
201
+ sub.add_node("chair", chair)
202
+ sub.add_edge(START, "open")
203
+ sub.add_conditional_edges("open", fan, ["member", "tally"])
204
+ sub.add_edge("member", "barrier")
205
+ sub.add_conditional_edges("barrier", fan, ["member", "tally"])
206
+ sub.add_edge("tally", "chair")
207
+ sub.add_edge("chair", END)
208
+ graph = sub.compile(checkpointer=False)
209
+
210
+ def node(state: RunState) -> dict[str, Any]:
211
+ got = graph.invoke({"parent": state}, {"recursion_limit": 100})
212
+ return post(got["out"])
213
+
214
+ node.__name__ = f"step_{unit}"
215
+ return node
216
+
217
+
218
+ def _passthrough(name: str) -> Callable[[RunState], dict[str, Any]]:
219
+ def node(state: RunState) -> dict[str, Any]:
220
+ return {}
221
+
222
+ node.__name__ = name.replace(".", "_")
223
+ return node
224
+
225
+
226
+ def _goes(spec: WorkflowSpec, unit: str) -> tuple[str, ...]:
227
+ """Where a concurrent map can go once an item has stopped it: where a gate or a person's decision can send a unit."""
228
+ return tuple(_end(t) for t in flow.gate_targets(spec, unit) + flow.human_targets(spec, unit))
229
+
230
+
231
+ def _map_node(nodes: Any, unit: str, post: Callable[[dict[str, Any]], dict[str, Any]]
232
+ ) -> Callable[[RunState], Command[Any]]:
233
+ """The step node of a concurrent map (MAP-B9, MAP-B10): the node's own body says what the map does next (its `Move`),
234
+ and this node sends the items it names, each with a state of its own, or goes where it says, or waits."""
235
+
236
+ def node(state: RunState) -> Command[Any]:
237
+ move = nodes.map_move(unit, state)
238
+ writes = post(move.writes)
239
+ goto: list[Any] = []
240
+ if move.items:
241
+ after = fold(state, writes)
242
+ target = flow.item_node(unit, move.kind)
243
+ goto = [Send(target, {**after, ITEM: {"unit": unit, "id": i, "slot": slot(unit, i)}}) for i in move.items]
244
+ elif move.goto:
245
+ goto = [_end(move.goto)]
246
+ return Command(update=writes, goto=goto)
247
+
248
+ node.__name__ = f"step_{unit}"
249
+ return node
250
+
251
+
252
+ def _item_node(nodes: Any, unit: str, kind: str, post: Callable[[dict[str, Any]], dict[str, Any]]
253
+ ) -> Callable[[dict[str, Any]], Command[Any]]:
254
+ """One node of an item of a concurrent map (MAP-B9, CMP-B14): the unit's own step, judge, gate or human body runs on
255
+ the item's view of the state, its writes are kept under the item's slot, and the next node of the same item is sent
256
+ the state as it reads after them. An item that has passed, waits for a person or has stopped the map goes back to the
257
+ unit's step node, which decides what the map does next."""
258
+
259
+ def node(sent: dict[str, Any]) -> Command[Any]:
260
+ held = sent[ITEM]
261
+ decision = interrupt((sent.get("pause") or {}).get(held["slot"])) if kind == "human" else None # HUM-AC1
262
+ iid = held["id"]
263
+ view = item_view(sent, unit, iid)
264
+ if kind == "step":
265
+ body = nodes.step(unit, view)
266
+ elif kind == "judge":
267
+ body = nodes.judge(unit, view)
268
+ elif kind == "gate":
269
+ body = nodes.gate(unit, view)
270
+ else:
271
+ body = nodes.human(unit, view, decision)
272
+ writes = slot_writes(post(body), unit, iid)
273
+ if kind in ("step", "judge"):
274
+ after = {**fold(sent, writes), ITEM: held}
275
+ return Command(update=writes, goto=Send(flow.item_node(unit, "judge" if kind == "step" else "gate"), after))
276
+ route = (writes.get("route") or {}).get(slot(unit, iid)) or {}
277
+ token = str(route.get("token"))
278
+ writes = fold(writes, item_end(unit, iid, token, str(route.get("node")))) # the two writes, composed
279
+ if token == "RETRY": # a retry reruns this item alone, from its judge when the route names it (KIL-B9, DUR-B12)
280
+ again = "judge" if route.get("node") == flow.node_names(unit)[1] else "step"
281
+ return Command(update=writes, goto=Send(flow.item_node(unit, again), {**fold(sent, writes), ITEM: held}))
282
+ return Command(update=writes, goto=flow.step_node(unit))
283
+
284
+ node.__name__ = f"item_{kind}_{unit}"
285
+ return node
286
+
287
+
288
+ def _human_node(nodes: UnitNodes, unit: str,
289
+ post: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[[RunState], dict[str, Any]]:
290
+ def human(state: RunState) -> dict[str, Any]:
291
+ decision = interrupt((state.get("pause") or {}).get(unit))
292
+ return post(nodes.human(unit, state, decision))
293
+
294
+ return human
295
+
296
+
297
+ def _router(unit: str, allowed: list[str]) -> Callable[[RunState], str]:
298
+ def route(state: RunState) -> str:
299
+ rec = (state.get("route") or {}).get(unit) or {}
300
+ target = rec.get("node")
301
+ if target not in allowed:
302
+ raise UnknownRoutingToken(f"unit {unit!r} routed to {target!r}; allowed {allowed}")
303
+ return str(target)
304
+
305
+ return route