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,1261 @@
1
+ """The engine CLI's release 1 core verbs (CLI-B7, CLI-B8, CLI-B14, CLI-B17, CLI-B18, CLI-B19; milestone M1).
2
+
3
+ Exit codes are the caller contract (CON-B12, CON-B13, ADR `exit-codes-as-caller-contract`). Read-only verbs create nothing and call no model
4
+ (OVR-B15). Machine output is JSON with `schema_version`; a run's one-line outcome goes to stderr.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import dataclasses
11
+ import json
12
+ import logging
13
+ import os
14
+ import sys
15
+ import traceback
16
+ from collections.abc import Callable, Mapping, Sequence
17
+ from pathlib import Path
18
+ from typing import IO, Any
19
+
20
+ from tempergraph import executor_compat
21
+ from tempergraph.catalog import Catalog, PackageNotLoaded, from_registry, resolve_request
22
+ from tempergraph.cli import audit as audit_cli
23
+ from tempergraph.cli import author as author_cli
24
+ from tempergraph.cli import install as install_cli
25
+ from tempergraph.cli import observe_cli, schedule_cli
26
+ from tempergraph.cli import upgrade as upgrade_cli
27
+ from tempergraph.cli import workflows as workflows_cli
28
+ from tempergraph.constants import SCHEMA, ExitCode
29
+ from tempergraph.contracts import WorkflowSpec, thread_id
30
+ from tempergraph.executors.registry import Registry, default_registry
31
+ from tempergraph.store.layout import ROOT_VAR
32
+
33
+ # Every verb word of CLI-B7, CLI-B8, CLI-B14, reserved so it is never read as a workflow or a request (CLI-B2, AC-3).
34
+ VERBS = ("attention", "audit", "author", "batch", "blueprint", "carry", "config", "evals", "events", "executors", "facts",
35
+ "graph", "hooks", "improve", "install", "label", "labels", "list", "literals", "logs", "orchestrate",
36
+ "outcome", "promote-check", "report", "rerun", "resume", "run", "scaffold", "schedule", "self-check",
37
+ "stats", "status", "stop", "store", "supervision", "update", "upgrade", "upgrade-check", "validate", "wait",
38
+ "workflows", "worktree", "help")
39
+ OPERATOR_REASONS = ("engine_defect", "judge_error", "environment", "plan", "request", "other") # CLI-B24
40
+ WORKSPACES = ("auto", "worktree", "in_place")
41
+ CHECK_EXIT = {"ok": ExitCode.FINISHED, "needs": ExitCode.USAGE, "error": ExitCode.USAGE,
42
+ "broken": ExitCode.INTERNAL}
43
+
44
+
45
+ class UsageError(Exception):
46
+ pass
47
+
48
+
49
+ class _Parser(argparse.ArgumentParser):
50
+ def error(self, message: str) -> Any: # exit 2 through our own path, never argparse's SystemExit text
51
+ raise UsageError(message)
52
+
53
+
54
+ # CLI-B28: the top-level help lists the verbs in these groups, operating runs first; a verb in no group is listed last.
55
+ HELP_GROUPS = (
56
+ ("Operate runs", ("run", "resume", "attention", "status", "wait", "events", "logs", "facts", "stop", "rerun",
57
+ "report", "config")),
58
+ ("Inspect and improve workflows", ("list", "graph", "validate", "audit", "outcome", "executors", "self-check",
59
+ "improve", "label", "labels", "evals", "promote-check", "supervision", "stats",
60
+ "store")),
61
+ ("Author and upgrade workflows", ("author", "blueprint", "scaffold", "literals", "upgrade", "upgrade-check",
62
+ "hooks")),
63
+ ("Install, register and place runs", ("install", "update", "workflows", "worktree", "carry", "schedule", "help")),
64
+ )
65
+
66
+
67
+ class _TopParser(_Parser):
68
+ def format_help(self) -> str:
69
+ """CLI-B28: the verbs grouped, each with its one-line help, then the global options."""
70
+ sub = next(a for a in self._actions if isinstance(a, argparse._SubParsersAction))
71
+ helps = {c.dest: c.help or "" for c in sub._choices_actions}
72
+ rest = [v for v in helps if not any(v in g for _, g in HELP_GROUPS)]
73
+ lines = ["usage: tempergraph [--state-root DIR] <verb> ...", "", str(self.description), ""]
74
+ for title, verbs in (*HELP_GROUPS, ("Other", tuple(rest))):
75
+ shown = [v for v in verbs if v in helps]
76
+ if not shown:
77
+ continue
78
+ lines.append(f"{title}:")
79
+ lines += [f" {v:<15} {helps[v]}" for v in shown]
80
+ lines.append("")
81
+ lines += ["options:", " -h, --help show this help and exit",
82
+ " --state-root DIR outside a git repository: the state root to use (WSP-B15 to WSP-B18)", "",
83
+ "`tempergraph <verb> --help` shows one verb's options. A thread is named <workflow>/<task id> or by "
84
+ "its alias.", ""]
85
+ return "\n".join(lines)
86
+
87
+
88
+ # The positionals that take any number of words (`nargs="*"`), by their destination.
89
+ STAR_POSITIONALS = ("request", "paths", "selectors")
90
+
91
+
92
+ def _parse(given: list[str]) -> argparse.Namespace:
93
+ """Parse the command line the same way on every supported Python. Python 3.11's argparse fills a `*` positional
94
+ when it meets the first option and then refuses the positional words after that option
95
+ (`author start x --from sources templates`); 3.12 takes them. Those words join the positional here."""
96
+ a, extra = _parser().parse_known_args(given)
97
+ if extra:
98
+ target = next((n for n in STAR_POSITIONALS if isinstance(getattr(a, n, None), list)), None)
99
+ if target is None or any(w.startswith("-") for w in extra):
100
+ raise UsageError(f"unrecognized arguments: {' '.join(extra)}")
101
+ getattr(a, target).extend(extra)
102
+ return a
103
+
104
+
105
+ def _parser() -> _Parser:
106
+ p = _TopParser(prog="tempergraph", description="Tempered rails for AI workflows")
107
+ p.add_argument("--state-root", metavar="DIR", help="outside a git repository: the state root to use (WSP-B15 to WSP-B18)")
108
+ sub = p.add_subparsers(dest="verb", parser_class=_Parser)
109
+
110
+ run = sub.add_parser("run", help="resolve, preflight and start a workflow")
111
+ run.add_argument("workflow")
112
+ run.add_argument("request", nargs="*")
113
+ run.add_argument("--check", action="store_true", help="resolve and preflight only; nothing is created")
114
+ run.add_argument("--task-id")
115
+ run.add_argument("--input", action="append", default=[], metavar="K=V")
116
+ _run_options(run)
117
+
118
+ res = sub.add_parser("resume", help="resume a paused, stopped or unfinished thread")
119
+ res.add_argument("workflow")
120
+ res.add_argument("thread")
121
+ res.add_argument("--decision", action="append", default=[],
122
+ help="one decision; repeat only for an ask's answer:<name>=<value>")
123
+ res.add_argument("--answers", metavar="FILE", help="a JSON map of an ask's answers (ASK-B8)")
124
+ res.add_argument("--apply-deadline", action="store_true",
125
+ help="apply the overdue deadline of a wait or an ask (FLX-B8)")
126
+ res.add_argument("--unit", help="which pending gate the decision answers, when there are several (HUM-B3)")
127
+ res.add_argument("--reason", dest="operator_reason", choices=OPERATOR_REASONS, metavar="REASON",
128
+ help="why the decision is made, one of: " + ", ".join(OPERATOR_REASONS)
129
+ + "; required when an agent decides at a pause, a person may omit it (CLI-B24, CLI-B30)")
130
+ res.add_argument("--unpin", action="store_true",
131
+ help="clear the thread's engine pin when this engine can resume it (MIG-B12, MIG-B13, MIG-B14)")
132
+ res.add_argument("--escalate", action="store_true",
133
+ help="take the offered one-step model escalation for the next attempt (LAD-B12)")
134
+ fb = res.add_mutually_exclusive_group()
135
+ fb.add_argument("--feedback")
136
+ fb.add_argument("--feedback-file")
137
+ res.add_argument("--ruling", action="store_true", help="the feedback is a lasting ruling (RRN-B14, RRN-B15)")
138
+ res.add_argument("--ruling-for", metavar="UNITS", help="comma-separated units the ruling applies to")
139
+ res.add_argument("--revoke-ruling", action="append", default=[], metavar="ID")
140
+ res.add_argument("--accept-external", action="store_true")
141
+ _run_options(res, start=False)
142
+
143
+ rr = sub.add_parser("rerun", help="a new thread forked from an earlier one, linked to it (RRN-B17, RRN-B18)")
144
+ rr.add_argument("workflow")
145
+ rr.add_argument("thread")
146
+ rr.add_argument("--from", dest="start_at", required=True, metavar="UNIT|start")
147
+ rr.add_argument("--check", action="store_true")
148
+ rfb = rr.add_mutually_exclusive_group()
149
+ rfb.add_argument("--feedback")
150
+ rfb.add_argument("--feedback-file")
151
+ rr.add_argument("--task-id")
152
+ rr.add_argument("--workspace", dest="rerun_workspace", choices=("current", "at-unit"), default="current")
153
+ rr.add_argument("--same-branch", action="store_true")
154
+ rr.add_argument("--drop-rulings", action="store_true")
155
+ rr.add_argument("--ruling", action="store_true")
156
+ rr.add_argument("--accept-external", action="store_true")
157
+ _spellings(rr)
158
+ _caller_options(rr)
159
+ rr.add_argument("--json", action="store_true")
160
+ _settings_options(rr, resume=True)
161
+ st = sub.add_parser("status", help="the status document, or one thread's detail document")
162
+ st.add_argument("selector", nargs="?")
163
+ st.add_argument("--detail", action="store_true", help="the run detail document of one thread (RDD)")
164
+ st.add_argument("--unit", help="with --detail: one unit in full")
165
+ st.add_argument("--no-live", action="store_true", help="with --detail: leave out the live session blocks")
166
+ st.add_argument("--json", action="store_true", help="machine output (the default for status)")
167
+ st.add_argument("--all-roots", action="store_true", help="every state root of the machine index (CST-B8)")
168
+ ev = sub.add_parser("events", help="a thread's run-log records in seq order (EVT)")
169
+ ev.add_argument("selector")
170
+ ev.add_argument("--since", type=int, metavar="SEQ")
171
+ ev.add_argument("--follow", action="store_true")
172
+ ev.add_argument("--activity", metavar="SESSION_KEY", help="one session's activity journal instead")
173
+ ev.add_argument("--json", action="store_true", help="one JSON object per line")
174
+ ev.add_argument("--timeout", type=float, help=argparse.SUPPRESS)
175
+ sub.add_parser("list", help="the workflow catalog")
176
+ va = sub.add_parser("validate", help="validate a workflow")
177
+ va.add_argument("workflow")
178
+ ex = sub.add_parser("executors", help="registered executors and their capabilities")
179
+ ex.add_argument("--probe", action="store_true")
180
+ sc = sub.add_parser("self-check", help="a step's preview of its gate's check (CHK-B17)")
181
+ sc.add_argument("ticket")
182
+ hk = sub.add_parser("hooks", help="run lifecycle hooks (HOK-B1 to HOK-B6)")
183
+ hks = hk.add_subparsers(dest="action", required=True)
184
+ hka = hks.add_parser("add", help="register a command for an event: hooks add <event> -- <argv…>")
185
+ hka.add_argument("event")
186
+ hka.add_argument("argv", nargs=argparse.REMAINDER)
187
+ _caller_options(hka)
188
+ hkr = hks.add_parser("remove", help="remove one hook by its id")
189
+ hkr.add_argument("id")
190
+ _caller_options(hkr)
191
+ hks.add_parser("list", help="the registered hooks")
192
+ hks.add_parser("test", help="run an event's hooks once against a fixture facts file").add_argument("event")
193
+ fa = sub.add_parser("facts", help="read-only facts about a run")
194
+ fa.add_argument("selector")
195
+ gr = sub.add_parser("graph", help="the workflow diagram")
196
+ gr.add_argument("workflow")
197
+ gr.add_argument("--format", choices=("mermaid", "md", "json", "svg"), default="mermaid")
198
+ gr.add_argument("--overlay", metavar="THREAD", help="a thread's counts on the diagram (OBS-B15); read-only")
199
+ wa = sub.add_parser("wait", help="block until a thread's outcome")
200
+ wa.add_argument("selectors", nargs="+", metavar="selector")
201
+ wa.add_argument("--any", action="store_true",
202
+ help="watch every named thread and return when the first one stops running (DUR-B16)")
203
+ wa.add_argument("--timeout", type=float, default=3600.0)
204
+ sub.add_parser("help", help="this list of verbs, grouped (CLI-B28)")
205
+ so = sub.add_parser("stop", help="ask a live run to stop")
206
+ so.add_argument("selector")
207
+ so.add_argument("--now", action="store_true", help="stop the open session now instead of draining")
208
+ _caller_options(so)
209
+ wt = sub.add_parser("worktree", help="run worktrees")
210
+ wsub = wt.add_subparsers(dest="action", parser_class=_Parser)
211
+ wl = wsub.add_parser("list")
212
+ wl.add_argument("--all", action="store_true", help="also foreign worktrees and git worktrees no record owns")
213
+ wl.add_argument("--json", action="store_true")
214
+ wp = wsub.add_parser("path")
215
+ wp.add_argument("thread")
216
+ wr = wsub.add_parser("prune", help="list removable run worktrees; --apply removes them, clean ones only")
217
+ wr.add_argument("--thread", metavar="THREAD")
218
+ wr.add_argument("--finished", action="store_true")
219
+ wr.add_argument("--older-than", type=float, metavar="DAYS")
220
+ wr.add_argument("--apply", action="store_true")
221
+ wr.add_argument("--json", action="store_true")
222
+ _caller_options(wr)
223
+ observe_cli.add_parsers(sub)
224
+ ca = sub.add_parser("carry", help="a run's state on its own branch: push, pull, status, drop (CAR)")
225
+ ca.add_argument("action", choices=("push", "pull", "status", "drop"))
226
+ ca.add_argument("workflow")
227
+ ca.add_argument("thread")
228
+ ca.add_argument("--remote")
229
+ ca.add_argument("--force", action="store_true")
230
+ ca.add_argument("--json", action="store_true")
231
+ _caller_options(ca)
232
+ co = sub.add_parser("config", help="resolved run settings and the settings files (RST-B31)")
233
+ csub = co.add_subparsers(dest="action", parser_class=_Parser)
234
+ cs = csub.add_parser("show")
235
+ cs.add_argument("workflow")
236
+ cs.add_argument("--thread")
237
+ cs.add_argument("--key", help="a glob over the keys shown")
238
+ _spellings(cs)
239
+ _settings_options(cs)
240
+ cs.add_argument("--json", action="store_true")
241
+ cv = csub.add_parser("validate")
242
+ cv.add_argument("--file")
243
+ csub.add_parser("paths")
244
+ workflows_cli.add_parsers(sub)
245
+ audit_cli.add_parsers(sub)
246
+ schedule_cli.add_parsers(sub)
247
+ author_cli.add_parsers(sub)
248
+ install_cli.add_parsers(sub)
249
+ upgrade_cli.add_parsers(sub)
250
+ from tempergraph.cli import outcome as outcome_cli
251
+
252
+ outcome_cli.add_parser(sub, _Parser)
253
+ from tempergraph.cli import improve as improve_cli
254
+
255
+ improve_cli.add_parsers(sub, _Parser)
256
+ return p
257
+
258
+
259
+ def _settings_options(p: argparse.ArgumentParser, resume: bool = False) -> None:
260
+ p.add_argument("--set", action="append", default=[], metavar="KEY=VALUE", dest="set_")
261
+ p.add_argument("--settings", metavar="FILE", help="a JSON map of keys to values, recorded as flags")
262
+ p.add_argument("--profile", action="append", default=None)
263
+ if resume:
264
+ p.add_argument("--unset", action="append", default=[], metavar="KEY")
265
+ p.add_argument("--reload-settings", action="store_true")
266
+
267
+
268
+ # Named run options that are spellings of `--set` (ROP-B1 to ROP-B13): option dest -> key, or a `<unit>=<value>` pair.
269
+ SPELLINGS = {"executor": "steps.executor", "judge_executor": "judges.executor", "model": "steps.model",
270
+ "judge_model": "judges.model", "timeout": "steps.timeout_s", "judge_timeout": "judges.timeout_s",
271
+ "idle": "steps.idle_s", "run_cost_cap": "run.run_cost_cap_usd", "worktree_root": "run.worktree.root",
272
+ "worktree_base": "run.worktree.base", "worktree_cleanup": "run.worktree.cleanup",
273
+ "auto_reopen": "run.auto_reopen", "daily_cap": "run.daily_cap_usd", "audit_rate": "run.audit_rate",
274
+ "audit_executor": "run.audit_executor"}
275
+ PER_UNIT = {"step_executor": "executor", "step_model": "model"}
276
+
277
+
278
+ def _caller_options(p: argparse.ArgumentParser) -> None:
279
+ """PRV-B18: run options, never settings; each call is classified on its own."""
280
+ p.add_argument("--caller", choices=("person", "agent", "pipeline", "orchestrator", "scheduler", "engine"))
281
+ p.add_argument("--as-agent", action="store_true")
282
+ p.add_argument("--caller-app")
283
+ p.add_argument("--relayed", action="store_true")
284
+
285
+
286
+ def _spellings(p: argparse.ArgumentParser) -> None:
287
+ for opt in ("executor", "judge-executor", "model", "judge-model", "timeout", "judge-timeout", "idle",
288
+ "run-cost-cap", "daily-cap", "auto-reopen", "audit-rate", "audit-executor"):
289
+ p.add_argument(f"--{opt}")
290
+ p.add_argument("--step-executor", action="append", default=[], metavar="STEP=NAME")
291
+ p.add_argument("--step-model", action="append", default=[], metavar="STEP=ALIAS")
292
+ p.add_argument("--approve", action="append", default=[], metavar="STEP")
293
+ p.add_argument("--grant", action="append", default=[], metavar="UNIT=CAPABILITY[,…]")
294
+ p.add_argument("--allow-command", action="append", default=[], metavar="UNIT=PREFIX")
295
+ p.add_argument("--enforce-tools", action="store_true")
296
+ p.add_argument("--strict-permissions", action="store_true")
297
+
298
+
299
+ def _run_options(p: argparse.ArgumentParser, start: bool = True) -> None:
300
+ _spellings(p)
301
+ _caller_options(p)
302
+ p.add_argument("--schedule", metavar="FIRE_ID", help="reserved to the schedule tick: needs its fire token (TCK-B17)")
303
+ p.add_argument("--json", action="store_true")
304
+ p.add_argument("--carry", action="store_true", help="carry this thread's state on its own branch (CAR)")
305
+ _settings_options(p, resume=not start)
306
+ p.add_argument("--pause-before", action="append", default=[], metavar="UNIT")
307
+ p.add_argument("--dry-run", action="store_const", const=True, default=None,
308
+ help="self-improvement files nothing; every step runs (the flag run.loop_dry_run true)")
309
+ p.add_argument("--no-dry-run", action="store_true",
310
+ help="self-improvement files; ends a dry run (the flag run.loop_dry_run false)")
311
+ if start:
312
+ p.add_argument("--alias")
313
+ p.add_argument("--label")
314
+ for opt in ("worktree-root", "worktree-base", "worktree-cleanup"):
315
+ p.add_argument(f"--{opt}")
316
+ ws = p.add_mutually_exclusive_group()
317
+ ws.add_argument("--workspace", choices=WORKSPACES)
318
+ ws.add_argument("--worktree", dest="workspace", action="store_const", const="worktree")
319
+ ws.add_argument("--in-place", dest="workspace", action="store_const", const="in_place")
320
+
321
+
322
+ @dataclasses.dataclass(kw_only=True)
323
+ class Env:
324
+ catalog: Catalog
325
+ registry: Registry
326
+ cwd: Path
327
+ out: IO[str]
328
+ err: IO[str]
329
+ run_settings: Callable[..., Any] | None = None # tests pass a factory to replace the backoff sleep
330
+ signals: tuple[Mapping[str, str], bool] | None = None # (environment, terminal); tests stub them (PRV-AC1)
331
+ hand_over: Callable[[Path, list[str]], int] | None = None # tests replace the pinned engine's launch
332
+ argv: tuple[str, ...] = () # this process's own arguments, handed unchanged to a pinned engine (MIG-B12, MIG-B13, MIG-B14)
333
+
334
+ def caller(self, a: argparse.Namespace) -> dict[str, Any]:
335
+ """PRV-B13, once per mutating call, before any write; read-only verbs never call this."""
336
+ from tempergraph.provenance import CallerRefused, classify
337
+ from tempergraph.schedule.token import entry_for_fire
338
+
339
+ known = getattr(a, "caller_block", None)
340
+ if known: # a scheduled run classifies its caller once, before it reads its hand-off ticket (TCK-B17)
341
+ return dict(known)
342
+ env, tty = self.signals or (os.environ, sys.stdin.isatty() and sys.stdout.isatty())
343
+ declared = getattr(a, "caller", None) or ("agent" if getattr(a, "as_agent", False) else None)
344
+ try:
345
+ return classify(env, tty, declared=declared, caller_app=getattr(a, "caller_app", None),
346
+ schedule=getattr(a, "schedule", None), entry_for_fire=entry_for_fire)
347
+ except CallerRefused as exc:
348
+ raise UsageError(f"{exc.code}: {exc}") from exc
349
+
350
+
351
+ def _emit(env: Env, doc: Any) -> None:
352
+ env.out.write(json.dumps(doc, indent=2, sort_keys=False, default=str) + "\n")
353
+
354
+
355
+ def _spec(env: Env, name: str) -> WorkflowSpec:
356
+ if name in VERBS:
357
+ own = env.catalog.specs.get(name)
358
+ if own is not None and own.builtin: # a built-in workflow's threads are resumed and read like any other
359
+ return own
360
+ raise UsageError(f"{name!r} is a reserved verb, not a workflow (CLI-B2)")
361
+ if name not in env.catalog.specs and name not in env.catalog.broken:
362
+ from tempergraph.package.manifest import workflow_name
363
+
364
+ name = workflow_name(name) # the plugin name `<workflow>-tgraph` names the same workflow (ADR `a-workflow-plugin-name-is-the-workflow-name-plus-tgraph`)
365
+ if name in env.catalog.broken:
366
+ raise PackageNotLoaded(env.catalog.broken[name])
367
+ if name not in env.catalog.specs:
368
+ raise UsageError(f"unknown workflow {name!r}; `tempergraph list` shows the catalog")
369
+ return env.catalog.specs[name]
370
+
371
+
372
+ def _inputs(pairs: Sequence[str]) -> dict[str, str]:
373
+ out = {}
374
+ for p in pairs:
375
+ k, sep, v = p.partition("=")
376
+ if not sep or not k:
377
+ raise UsageError(f"--input {p!r}: expected key=value")
378
+ out[k] = v
379
+ return out
380
+
381
+
382
+ def _flags(env: Env, a: argparse.Namespace) -> dict[str, Any]:
383
+ """`--settings`, then `--set`, then the named spellings: every one lands on the flag layer (RST-B22, RST-B23)."""
384
+ from tempergraph.settings import parse_value
385
+
386
+ flags: dict[str, Any] = {}
387
+ if getattr(a, "settings", None):
388
+ try:
389
+ doc = json.loads((env.cwd / a.settings).read_text(encoding="utf-8"))
390
+ except (OSError, ValueError) as exc:
391
+ raise UsageError(f"--settings {a.settings}: {type(exc).__name__}") from exc
392
+ if not isinstance(doc, dict):
393
+ raise UsageError(f"--settings {a.settings}: not a JSON object of keys to values")
394
+ flags.update(doc)
395
+ for pair in getattr(a, "set_", None) or []:
396
+ k, sep, v = pair.partition("=")
397
+ if not sep or not k:
398
+ raise UsageError(f"--set {pair!r}: expected key=value")
399
+ flags[k] = parse_value(v)
400
+ for dest, key in SPELLINGS.items():
401
+ v = getattr(a, dest, None)
402
+ if v is not None:
403
+ flags[key] = parse_value(v)
404
+ if getattr(a, "dry_run", None) and getattr(a, "no_dry_run", False):
405
+ raise UsageError("argument --no-dry-run: not allowed with argument --dry-run")
406
+ if getattr(a, "dry_run", None):
407
+ flags["run.loop_dry_run"] = True
408
+ elif getattr(a, "no_dry_run", False):
409
+ flags["run.loop_dry_run"] = False
410
+ for dest, name in PER_UNIT.items():
411
+ for pair in getattr(a, dest, None) or []:
412
+ unit, sep, v = pair.partition("=")
413
+ if not sep or not unit:
414
+ raise UsageError(f"--{dest.replace('_', '-')} {pair!r}: expected <step>=<value>")
415
+ flags[f"{unit}.{name}"] = parse_value(v)
416
+ for unit in getattr(a, "approve", None) or []:
417
+ flags[f"{unit}.approve"] = True
418
+ for opt, pairs in (("grant", getattr(a, "grant", None)), ("allow-command", getattr(a, "allow_command", None))):
419
+ for pair in pairs or []: # a person's tool grant for this run (RST-B28, RST-B29, RST-B30)
420
+ unit, sep, v = pair.partition("=")
421
+ if not sep or not unit or not v:
422
+ raise UsageError(f"--{opt} {pair!r}: expected <unit>=<value>")
423
+ if opt == "allow-command":
424
+ key, items = f"{unit}.commands.add", [v]
425
+ else:
426
+ key = f"{unit}.views.add" if unit.startswith("judge:") else f"{unit}.tools.add"
427
+ items = [c.strip() for c in v.split(",") if c.strip()]
428
+ flags[key] = list(dict.fromkeys(list(flags.get(key) or []) + items))
429
+ if getattr(a, "workspace", None):
430
+ flags["run.workspace"] = a.workspace
431
+ if getattr(a, "enforce_tools", False):
432
+ flags["run.enforce_tools"] = True
433
+ if getattr(a, "strict_permissions", False):
434
+ flags["run.strict_permissions"] = True
435
+ return flags
436
+
437
+
438
+ def _settings(env: Env, a: argparse.Namespace, mutating: bool = True) -> Any:
439
+ from tempergraph.run.runner import RunSettings
440
+
441
+ caller = env.caller(a) if mutating else {}
442
+ fields: dict[str, Any] = {"flags": {**(getattr(a, "ticket_flags", None) or {}), **_flags(env, a)},
443
+ "caller": caller,
444
+ "relayed": bool(getattr(a, "relayed", False)),
445
+ "profiles": tuple(a.profile) if getattr(a, "profile", None) is not None else None}
446
+ if getattr(a, "schedule", None) and caller.get("kind") == "scheduler": # TCK-B24: every start path writes the fire
447
+ block = caller["schedule"]
448
+ fields.update(origin="schedule", schedule={k: block[k] for k in ("schedule_id", "fire_id", "slot")})
449
+ if hasattr(a, "alias"):
450
+ fields.update(alias=a.alias, label=a.label)
451
+ if getattr(a, "escalate", False):
452
+ fields["escalate"] = True
453
+ if getattr(a, "carry", False):
454
+ fields["carry"] = True
455
+ if getattr(a, "pause_before", None): # FLX-B10
456
+ fields["pause_before"] = tuple(a.pause_before)
457
+ if hasattr(a, "unset"):
458
+ fields.update(unset=tuple(a.unset), reload_settings=a.reload_settings)
459
+ if hasattr(a, "ruling"):
460
+ if getattr(a, "ruling_for", None) and not a.ruling:
461
+ raise UsageError("--ruling-for needs --ruling")
462
+ fields.update(ruling=a.ruling, revoke_rulings=tuple(getattr(a, "revoke_ruling", None) or ()),
463
+ accept_external=bool(getattr(a, "accept_external", False)),
464
+ ruling_for=tuple(u.strip() for u in (getattr(a, "ruling_for", None) or "").split(",")
465
+ if u.strip()))
466
+ if env.run_settings is not None:
467
+ return env.run_settings(**fields)
468
+ return RunSettings(**fields)
469
+
470
+
471
+ def next_commands(out: Any) -> list[str]:
472
+ """CLI-B27: the reads that explain a pause (exit 3) or a stop for budget or infrastructure (exit 5)."""
473
+ tid = out.thread_id
474
+ if not tid or out.exit_code not in (ExitCode.PAUSED, ExitCode.BUDGET_OR_INFRA):
475
+ return []
476
+ if out.exit_code == ExitCode.PAUSED:
477
+ unit = (out.payload or {}).get("unit")
478
+ return [f"tempergraph status {tid} --detail" + (f" --unit {unit}" if unit else ""), "tempergraph attention"]
479
+ return [f"tempergraph status {tid} --detail", f"tempergraph logs {tid}"]
480
+
481
+
482
+ def _report(env: Env, out: Any, as_json: bool) -> int:
483
+ after = next_commands(out)
484
+ doc = {"schema_version": 1, "exit_code": int(out.exit_code), "reason": out.reason, "thread_id": out.thread_id,
485
+ "message": out.message, "payload": out.payload, "refusals": out.refusals, "warnings": out.warnings,
486
+ "next": after}
487
+ if as_json:
488
+ _emit(env, doc)
489
+ line = out.message or out.reason or ExitCode(out.exit_code).name.lower()
490
+ env.err.write(f"{out.thread_id or 'tempergraph'}: {line}\n")
491
+ if out.payload and out.payload.get("resume"):
492
+ env.err.write(f" {out.payload['resume']}\n")
493
+ for i, cmd in enumerate(after): # CLI-B27
494
+ env.err.write(f" {'next: ' if i == 0 else ' '}{cmd}\n")
495
+ return int(out.exit_code)
496
+
497
+
498
+ def _scheduled(env: Env, a: argparse.Namespace) -> None:
499
+ """TCK-B17: a scheduled run checks its fire token before anything is written, then takes its request, inputs,
500
+ options and label from the hand-off ticket the tick left (SEC-B6) and removes the ticket. The token leaves this
501
+ process's environment so no step session inherits it."""
502
+ from tempergraph.schedule import launch, token
503
+
504
+ a.caller_block = env.caller(a) # exit 2 `schedule_token_invalid` or `schedule_reserved` here
505
+ os.environ.pop(token.ENV_VAR, None)
506
+ ticket = launch.read_ticket(str(a.schedule))
507
+ if ticket is None:
508
+ raise UsageError("schedule_ticket_invalid: the fire's hand-off ticket is missing or malformed")
509
+ a.request = str(ticket["request"]).split()
510
+ a.input = [f"{k}={v}" for k, v in ticket["inputs"].items()]
511
+ a.label = ticket["label"]
512
+ a.ticket_flags = dict(ticket["flags"])
513
+ a.profile = list(ticket["profiles"]) or None
514
+
515
+
516
+ def cmd_run(env: Env, a: argparse.Namespace) -> int:
517
+ from tempergraph.executors.preflight import preflight
518
+ from tempergraph.run.runner import SettingsRefused, settle_start, start
519
+
520
+ if getattr(a, "schedule", None) and not a.check:
521
+ _scheduled(env, a)
522
+ try:
523
+ spec = _spec(env, a.workflow)
524
+ except PackageNotLoaded as exc:
525
+ if a.check:
526
+ _emit(env, {"schema_version": 1, "status": "broken", "workflow": a.workflow, "reason": exc.reason})
527
+ else:
528
+ env.err.write(f"{a.workflow}: {exc}\n")
529
+ return int(CHECK_EXIT["broken"])
530
+ if a.request and a.request[0] in VERBS:
531
+ raise UsageError(f"{a.request[0]!r} is a reserved verb and cannot start a request (CLI-B2)")
532
+ if spec.builtin: # UWF-B5: a built-in workflow is started by its own verb
533
+ raise UsageError(f"{spec.name} is started by `tempergraph {spec.name} <workflow>`, not by `run`")
534
+ for name in a.pause_before: # FLX-B11: refused before spend, by `--check` too
535
+ if name not in spec.units:
536
+ raise UsageError(f"breakpoint_unknown: --pause-before {name}: the workflow has no such unit")
537
+ try:
538
+ res = resolve_request(spec, list(a.request), _inputs(a.input), env.cwd, a.task_id)
539
+ except PackageNotLoaded as exc:
540
+ _emit(env, {"schema_version": 1, "status": "broken", "workflow": spec.name, "reason": exc.reason})
541
+ return int(CHECK_EXIT["broken"])
542
+ if a.check or res.status != "ok":
543
+ doc: dict[str, Any] = {"schema_version": 1, "status": res.status, "workflow": spec.name}
544
+ if res.status == "ok":
545
+ doc.update(task_id=res.task_id, thread_id=thread_id(spec.name, res.task_id))
546
+ try:
547
+ settled = settle_start(spec, _settings(env, a, mutating=False),
548
+ _root_or_none(env))
549
+ except SettingsRefused as exc: # the same refusals `run` gives (CLI-AC2, RST-B9)
550
+ doc.update(status="error", refusals=[{"code": f.code, "unit": f.unit, "message": f.message}
551
+ for f in exc.findings], warnings=[])
552
+ _emit(env, doc)
553
+ return int(CHECK_EXIT["error"])
554
+ rv = settled.run
555
+ rep = preflight(settled.spec, env.registry, enforce_tools=bool(rv["enforce_tools"]),
556
+ strict_permissions=bool(rv["strict_permissions"]))
557
+ counts: dict[str, int] = {}
558
+ for f in rep.authoring_warnings:
559
+ counts[f.code] = counts.get(f.code, 0) + 1
560
+ doc.update(refusals=[{"code": f.code, "unit": f.unit, "message": f.message} for f in rep.refusals],
561
+ warnings=[{"code": f.code, "unit": f.unit, "message": f.message} for f in rep.warnings],
562
+ authoring_warnings={"counts": counts, "total": sum(counts.values()),
563
+ "command": f"tempergraph validate {spec.name}"},
564
+ judges=rep.judges, settings_digest=settled.resolved.digest)
565
+ if rep.refusals:
566
+ doc["status"] = "error"
567
+ else: # the refusal `run` gives after validation: a child that needs git
568
+ from tempergraph.model import subworkflow
569
+ from tempergraph.store.layout import outside_git
570
+ from tempergraph.workspace import WorkspaceRefused, file_missing_at_base, resolve_workspace
571
+
572
+ needs = (subworkflow.unit_reasons(settled.spec) + subworkflow.needs_git(settled.spec) # WSP-B18
573
+ if outside_git(env.cwd) else [])
574
+ if needs:
575
+ doc["refusals"] = [{"code": "needs_git", "unit": None, "message": f"outside a git repository this "
576
+ f"run cannot use {n}"} for n in needs]
577
+ doc["status"] = "error"
578
+ elif settled.spec.input.kind == "file": # CLI-B21: refuse a file request missing at the base ref
579
+ base_str = str(rv.get("worktree.base") or "head")
580
+ if base_str != "head":
581
+ try:
582
+ plan = resolve_workspace(settled.spec, env.cwd, rv["workspace"],
583
+ prefix=str(rv["worktree.branch_prefix"]),
584
+ base=base_str, root=str(rv.get("worktree.root") or "sibling"))
585
+ if plan.main is not None and plan.base_commit:
586
+ err = file_missing_at_base(plan.main, plan.base_commit, plan.base_ref,
587
+ res.inputs.get("file", ""))
588
+ if err:
589
+ doc["refusals"] = [{"code": "request_missing_at_base", "unit": None,
590
+ "message": err}]
591
+ doc["status"] = "error"
592
+ except WorkspaceRefused:
593
+ pass
594
+ elif res.status == "needs":
595
+ doc["questions"] = [{"name": q.name, "question": q.question, "choices": list(q.choices or [])}
596
+ for q in res.questions]
597
+ else:
598
+ doc["message"] = res.message
599
+ _emit(env, doc)
600
+ return int(CHECK_EXIT[doc["status"]])
601
+ out = start(spec, res.task_id, res.inputs, env.cwd, env.registry, _settings(env, a))
602
+ return _report(env, out, a.json)
603
+
604
+
605
+ def cmd_resume(env: Env, a: argparse.Namespace) -> int:
606
+ from tempergraph.run.runner import resume
607
+
608
+ spec = _spec(env, a.workflow)
609
+ task = a.thread.split("/", 1)[1] if a.thread.startswith(spec.name + "/") else a.thread
610
+ feedback = a.feedback
611
+ if a.feedback_file:
612
+ path = (env.cwd / a.feedback_file)
613
+ try:
614
+ feedback = path.read_text(encoding="utf-8")
615
+ except OSError as exc:
616
+ raise UsageError(f"--feedback-file {a.feedback_file}: {type(exc).__name__}") from exc
617
+ code = _pinned_engine(env, spec, task, a)
618
+ if code is not None:
619
+ return code
620
+ answers: dict[str, Any] = {}
621
+ if a.answers: # ASK-B8: a JSON map of answers
622
+ try:
623
+ doc = json.loads((env.cwd / a.answers).read_text(encoding="utf-8"))
624
+ except (OSError, ValueError) as exc:
625
+ raise UsageError(f"--answers {a.answers}: {type(exc).__name__}") from exc
626
+ if not isinstance(doc, dict):
627
+ raise UsageError(f"--answers {a.answers}: not a JSON map of answers")
628
+ answers.update(doc)
629
+ words = []
630
+ for text in a.decision:
631
+ if text.startswith("answer:") and "=" in text:
632
+ name, _, value = text[len("answer:"):].partition("=")
633
+ answers[name] = value
634
+ else:
635
+ words.append(text)
636
+ if len(words) > 1:
637
+ raise UsageError("one --decision a resume; only answer:<name>=<value> repeats")
638
+ settings = dataclasses.replace(_settings(env, a), answers=answers, apply_deadline=bool(a.apply_deadline),
639
+ unit=a.unit, operator_reason=a.operator_reason)
640
+ out = resume(spec, task, env.cwd, env.registry, decision=words[0] if words else None, feedback=feedback,
641
+ settings=settings)
642
+ if out.exit_code == ExitCode.FINISHED: # MIG-B12, MIG-B13, MIG-B14: a pin ends with its thread
643
+ from tempergraph.durability import engine_file
644
+
645
+ root = _root_or_none(env)
646
+ if root is not None:
647
+ engine_file.unpin(root, spec.name, task)
648
+ return _report(env, out, a.json)
649
+
650
+
651
+ def _pinned_engine(env: Env, spec: WorkflowSpec, task: str, a: argparse.Namespace) -> int | None:
652
+ """MIG-B12, MIG-B13, MIG-B14, before anything else: None when this engine resumes the thread, else the exit code of the
653
+ pinned engine that did, or 2 with the reason."""
654
+ from tempergraph.durability import engine_file
655
+ from tempergraph.install import environment, launch
656
+ from tempergraph.store.layout import home_path
657
+
658
+ root = _root_or_none(env)
659
+ if root is None or not engine_file.path(root, spec.name, task).is_file():
660
+ return None
661
+ if getattr(a, "unpin", False):
662
+ why = engine_file.try_unpin(root, spec.name, task)
663
+ if why:
664
+ raise UsageError(f"--unpin: {why}")
665
+ action, detail = engine_file.at_resume(root, spec.name, task)
666
+ if action == "move":
667
+ return None
668
+ if action == "refuse":
669
+ raise UsageError(str(detail))
670
+ argv = [x for x in env.argv if x != "--unpin"]
671
+ return (env.hand_over or launch.hand_over)(environment.interpreter(home_path() / "engines" / str(detail)), argv)
672
+
673
+
674
+ def _feedback_text(env: Env, a: argparse.Namespace) -> str | None:
675
+ if getattr(a, "feedback_file", None):
676
+ try:
677
+ return (env.cwd / a.feedback_file).read_text(encoding="utf-8")
678
+ except OSError as exc:
679
+ raise UsageError(f"--feedback-file {a.feedback_file}: {type(exc).__name__}") from exc
680
+ return getattr(a, "feedback", None)
681
+
682
+
683
+ def cmd_rerun(env: Env, a: argparse.Namespace) -> int:
684
+ from tempergraph.run.rerun import rerun
685
+
686
+ spec = _spec(env, a.workflow)
687
+ task = a.thread.split("/", 1)[1] if a.thread.startswith(spec.name + "/") else a.thread
688
+ out = rerun(spec, task, env.cwd, env.registry, start_at=a.start_at, feedback=_feedback_text(env, a),
689
+ settings=_settings(env, a, mutating=not a.check), task_id=a.task_id, workspace_from=a.rerun_workspace,
690
+ same_branch=a.same_branch, drop_rulings=a.drop_rulings, accept_external=a.accept_external,
691
+ check=a.check)
692
+ if isinstance(out, dict):
693
+ _emit(env, out)
694
+ return 0
695
+ if a.check: # `rerun --check` refuses as `rerun` does, and prints one document (RRN-AC4)
696
+ _emit(env, {"schema_version": 1, "status": "error", "reason": out.reason, "message": out.message,
697
+ "refusals": out.refusals or [out.message]})
698
+ return int(out.exit_code)
699
+ return _report(env, out, a.json)
700
+
701
+
702
+ def _root(env: Env) -> Path:
703
+ from tempergraph.store.layout import NotInRepository, state_root_path
704
+
705
+ try:
706
+ return state_root_path(env.cwd)
707
+ except NotInRepository as exc:
708
+ raise UsageError("not inside a git repository") from exc
709
+
710
+
711
+ def _needs_git(env: Env, what: str) -> None:
712
+ """WSP-B15 to WSP-B18: a verb that works on branches or worktrees is refused outside a git repository."""
713
+ from tempergraph.store.layout import outside_git
714
+
715
+ if outside_git(env.cwd):
716
+ raise UsageError(f"needs_git: {what} needs a git repository")
717
+
718
+
719
+ def _root_or_none(env: Env) -> Path | None:
720
+ from tempergraph.store.layout import NotInRepository, state_root_path
721
+
722
+ try:
723
+ return state_root_path(env.cwd)
724
+ except NotInRepository:
725
+ return None
726
+
727
+
728
+ def _one(env: Env, selector: str) -> tuple[WorkflowSpec, str]:
729
+ from tempergraph.durability.status import Selector, select
730
+
731
+ found = select(_root(env), env.catalog.specs, Selector(value=selector))
732
+ if not found:
733
+ raise UsageError(_no_thread(env, selector))
734
+ if len(found) != 1:
735
+ raise UsageError(f"{selector!r} names more than one thread")
736
+ return found[0]
737
+
738
+
739
+ def _no_thread(env: Env, selector: str) -> str:
740
+ """CLI-B29: the refusal of a selector that names no thread, with the threads whose task id it is."""
741
+ from tempergraph.durability.status import Selector, select
742
+
743
+ same = [t for _, t in select(_root(env), env.catalog.specs, Selector()) if t.split("/", 1)[-1] == selector]
744
+ hint = f"; did you mean {', '.join(sorted(same))}" if same else ""
745
+ return (f"{selector!r} names no thread: name a thread as <workflow>/<task id> or by its alias, or give a "
746
+ f"workflow name{hint}")
747
+
748
+
749
+ def _hand_over_lost(env: Env, roots: list[Path], selector: str | None = None) -> None:
750
+ """SIL-B29, SIL-B32: `status`, `stop` and `attention` hand a lost runner to the loop before they answer; whatever
751
+ fails there never changes their output or exit code."""
752
+ try:
753
+ from tempergraph.improve import lost
754
+
755
+ for r in roots:
756
+ lost.settle(r, env.catalog.specs, selector, env.registry)
757
+ except Exception: # noqa: BLE001
758
+ pass
759
+
760
+
761
+ def cmd_status(env: Env, a: argparse.Namespace) -> int:
762
+ from tempergraph.durability.status import Selector, status
763
+
764
+ if a.detail:
765
+ from tempergraph.observe.detail import detail
766
+
767
+ if not a.selector:
768
+ raise UsageError("status --detail needs one thread")
769
+ spec, tid = _one(env, a.selector)
770
+ doc = detail(_root(env), spec, tid, unit=a.unit, with_live=not a.no_live)
771
+ if doc is None:
772
+ raise UsageError(f"{a.unit!r} is not a unit of {spec.name}")
773
+ if doc["run"].get("state") == "none":
774
+ raise UsageError(f"{tid}: no such thread")
775
+ _emit(env, doc)
776
+ return 0
777
+ if a.unit:
778
+ raise UsageError("--unit needs --detail")
779
+ _hand_over_lost(env, [_root(env)], a.selector) # SIL-B29: a lost runner is handed to the loop once
780
+ if a.all_roots:
781
+ from tempergraph.observe.rows import index_roots
782
+
783
+ doc = status(_root(env), env.catalog.specs, Selector(value=a.selector))
784
+ here = str(_root(env).resolve())
785
+ for r in doc["threads"]:
786
+ r["state_root"] = here
787
+ doc["roots"] = [{"path": here, "missing": False}]
788
+ for entry in index_roots():
789
+ if entry["path"] == here:
790
+ continue
791
+ doc["roots"].append({"path": entry["path"], "missing": entry["missing"]})
792
+ if entry["missing"]:
793
+ continue
794
+ for r in status(Path(entry["path"]), env.catalog.specs, Selector(value=a.selector))["threads"]:
795
+ doc["threads"].append({**r, "state_root": entry["path"]})
796
+ _refuse_empty(env, a.selector, doc)
797
+ _emit(env, doc)
798
+ return 0
799
+ doc = status(_root(env), env.catalog.specs, Selector(value=a.selector))
800
+ from tempergraph.observe.sinks import warnings
801
+ from tempergraph.store.layout import home_path
802
+
803
+ lines = warnings(home_path())
804
+ if lines:
805
+ doc["warnings"] = lines # CST-B10, CST-B12, CST-B13: a sink failing for 7 days
806
+ from tempergraph.cli.schedule_cli import CLOCK
807
+ from tempergraph.observe.attention import trigger_stale
808
+
809
+ stale = trigger_stale(home_path(), CLOCK().timestamp()) # TCK-B7: read-only, shown only when a heartbeat is old
810
+ if stale:
811
+ doc["trigger_stale"] = stale
812
+ _refuse_empty(env, a.selector, doc)
813
+ _emit(env, doc)
814
+ return 0
815
+
816
+
817
+ def _refuse_empty(env: Env, selector: str | None, doc: Mapping[str, Any]) -> None:
818
+ """CLI-B29: a selector that is not a workflow name and selects no thread is refused, as the other readers do."""
819
+ if selector and selector not in env.catalog.specs and not doc.get("threads"):
820
+ raise UsageError(_no_thread(env, selector))
821
+
822
+
823
+ def cmd_events(env: Env, a: argparse.Namespace) -> int:
824
+ from tempergraph.durability.lock import is_held
825
+ from tempergraph.run import events as evmod
826
+ from tempergraph.store.layout import lock_path, run_dir, session_dir
827
+
828
+ spec, tid = _one(env, a.selector)
829
+ root, task = _root(env), tid.split("/", 1)[1]
830
+ log = run_dir(root, spec.name, task) / "run.jsonl"
831
+ if not log.exists():
832
+ raise UsageError(f"{tid} has no run log")
833
+ lock = lock_path(root, spec.name, task)
834
+
835
+ def held() -> bool:
836
+ return is_held(lock)
837
+
838
+ def show(rec: dict[str, Any]) -> None:
839
+ env.out.write((json.dumps(rec, ensure_ascii=False) if a.json else evmod.narrate(rec)) + "\n")
840
+ env.out.flush()
841
+
842
+ if a.activity:
843
+ sdir = session_dir(root, spec.name, task, a.activity)
844
+ journal = sdir / "activity.jsonl"
845
+ if not sdir.is_dir():
846
+ raise UsageError(f"{tid} has no session {a.activity!r}")
847
+ lines = (evmod.follow_activity(journal, sdir / "live.json", held, a.since, timeout_s=a.timeout)
848
+ if a.follow else evmod.activity(journal, a.since))
849
+ for ln in lines:
850
+ env.out.write(json.dumps(ln, ensure_ascii=False) + "\n")
851
+ return 0
852
+ recs = evmod.follow(log, held, a.since, timeout_s=a.timeout) if a.follow else evmod.records(log, a.since)
853
+ for rec in recs:
854
+ show(rec)
855
+ return 0
856
+
857
+
858
+ def cmd_list(env: Env, a: argparse.Namespace) -> int:
859
+ _emit(env, env.catalog.to_json())
860
+ return 0
861
+
862
+
863
+ def cmd_validate(env: Env, a: argparse.Namespace) -> int:
864
+ from tempergraph.executors.preflight import preflight
865
+
866
+ spec = _spec(env, a.workflow)
867
+ rep = preflight(spec, env.registry)
868
+ doc = {"schema_version": 1, "workflow": spec.name, "ok": rep.ok,
869
+ "findings": [{"severity": "error", "code": f.code, "unit": f.unit, "message": f.message}
870
+ for f in rep.refusals]
871
+ + [{"severity": "warning", "code": f.code, "unit": f.unit, "message": f.message}
872
+ for f in rep.authoring_warnings + rep.warnings],
873
+ "deferred_views": {u: [dataclasses.asdict(d) for d in ds] for u, ds in rep.deferred.items()}}
874
+ _emit(env, doc)
875
+ return 0 if rep.ok else int(ExitCode.USAGE)
876
+
877
+
878
+ def cmd_executors(env: Env, a: argparse.Namespace) -> int:
879
+ rows = []
880
+ for name in env.registry.available():
881
+ ex = env.registry.get(name)
882
+ caps = ex.capabilities()
883
+ row: dict[str, Any] = {"name": name, "capabilities": dataclasses.asdict(caps)}
884
+ facts = getattr(ex, "live_facts", None) # live probe facts and their recorded state (CLI-B3)
885
+ if isinstance(facts, dict):
886
+ row["live_facts"] = dict(facts)
887
+ if a.probe:
888
+ pr = ex.probe()
889
+ row["probe"] = {"ok": pr.ok, "reason": pr.reason, "version": pr.version, "path": pr.path,
890
+ "facts": dict(pr.facts)}
891
+ row["compat"] = executor_compat.row(name, row["probe"]["version"] if a.probe else caps.version) # LIF-AC4
892
+ rows.append(row)
893
+ _emit(env, {"schema_version": 1, "executors": rows})
894
+ return 0
895
+
896
+
897
+ def cmd_self_check(env: Env, a: argparse.Namespace) -> int:
898
+ """CHK-B17: the one verb a step session may call; it changes no state."""
899
+ from tempergraph.run import selfcheck
900
+
901
+ root = _root_or_none(env)
902
+ if root is None:
903
+ env.out.write("self-check: unknown or expired ticket; nothing was run\n")
904
+ return int(ExitCode.USAGE)
905
+ return selfcheck.run(root, a.ticket, env.out)
906
+
907
+
908
+ def cmd_hooks(env: Env, a: argparse.Namespace) -> int:
909
+ """HOK-B1 to HOK-B6: the operator's registry of lifecycle hooks; add and remove write, list and test do not."""
910
+ from tempergraph.observe import hooks
911
+
912
+ root = _root(env)
913
+ try:
914
+ if a.action == "add":
915
+ caller = env.caller(a)
916
+ words = a.argv[1:] if a.argv[:1] == ["--"] else a.argv
917
+ _emit(env, {"schema_version": 1, "added": hooks.add(root, a.event, words), "caller": caller})
918
+ elif a.action == "remove":
919
+ caller = env.caller(a)
920
+ _emit(env, {"schema_version": 1, "removed": hooks.remove(root, a.id), "caller": caller})
921
+ elif a.action == "list":
922
+ _emit(env, {"schema_version": 1, "events": list(hooks.RUN_EVENTS), "hooks": hooks.load(root)})
923
+ else:
924
+ results = hooks.test(root, a.event)
925
+ _emit(env, {"schema_version": 1, "event": a.event, "results": results})
926
+ return int(ExitCode.FINISHED if all(r["ok"] for r in results) else ExitCode.ADVISORY)
927
+ except hooks.HookRefused as exc:
928
+ raise UsageError(str(exc)) from exc
929
+ return int(ExitCode.FINISHED)
930
+
931
+
932
+ def cmd_facts(env: Env, a: argparse.Namespace) -> int:
933
+ from tempergraph.durability.status import row
934
+
935
+ spec, tid = _one(env, a.selector)
936
+ r = row(_root(env), spec, tid)
937
+ keep = ("thread_id", "workflow", "state", "alive", "pending_gates", "workspace", "alias", "label", "origin",
938
+ "exit_code", "exit_reason", "cost", "artifacts", "next")
939
+ _emit(env, {"schema_version": SCHEMA["status"], **{k: r[k] for k in keep if k in r}})
940
+ return 0
941
+
942
+
943
+ def cmd_graph(env: Env, a: argparse.Namespace) -> int:
944
+ from tempergraph.model.diagram import diagram_model, to_mermaid
945
+
946
+ model = diagram_model(_spec(env, a.workflow))
947
+ if a.overlay:
948
+ from tempergraph.durability.status import split_thread
949
+ from tempergraph.observe.overlay import overlay
950
+ from tempergraph.store.layout import run_dir
951
+
952
+ spec, tid = _one(env, a.overlay)
953
+ if spec.name != a.workflow:
954
+ raise UsageError(f"{tid} is a run of {spec.name!r}, not of {a.workflow!r}")
955
+ if not (run_dir(_root(env), spec.name, split_thread(tid)[1]) / "run.jsonl").exists():
956
+ raise UsageError(f"{tid} has no run log to overlay")
957
+ model["overlay"] = overlay(_root(env), spec.name, split_thread(tid)[1])
958
+ if a.format == "json":
959
+ _emit(env, model)
960
+ elif a.format == "svg":
961
+ from tempergraph.model.diagram import to_svg
962
+
963
+ env.out.write(to_svg(model))
964
+ else:
965
+ text = to_mermaid(model)
966
+ env.out.write(f"```mermaid\n{text}\n```\n" if a.format == "md" else text + "\n")
967
+ return 0
968
+
969
+
970
+ def cmd_wait(env: Env, a: argparse.Namespace) -> int:
971
+ from tempergraph.durability.status import wait
972
+
973
+ if a.timeout <= 0:
974
+ raise UsageError("--timeout must be positive")
975
+ if a.any: # DUR-B16: the first named thread that stops running, verdicts not counted
976
+ from tempergraph.durability.status import wait_any
977
+
978
+ pairs: list[tuple[WorkflowSpec, str]] = []
979
+ for sel in a.selectors:
980
+ spec, tid = _one(env, sel)
981
+ if tid not in [t for _, t in pairs]:
982
+ pairs.append((spec, tid))
983
+ first = wait_any(_root(env), pairs, a.timeout)
984
+ _emit(env, {"schema_version": 1, "state": first.state, "exit_code": int(first.exit_code),
985
+ "reason": first.reason, "thread_id": first.row.get("thread_id"), "row": first.row,
986
+ "threads": first.threads})
987
+ return int(first.exit_code)
988
+ if len(a.selectors) > 1:
989
+ raise UsageError("wait names one thread; several threads need --any (DUR-B16)")
990
+ spec, tid = _one(env, a.selectors[0])
991
+ w = wait(_root(env), spec, tid, a.timeout)
992
+ _emit(env, {"schema_version": 1, "state": w.state, "exit_code": int(w.exit_code), "reason": w.reason,
993
+ "row": w.row})
994
+ return int(w.exit_code)
995
+
996
+
997
+ def cmd_help(env: Env, a: argparse.Namespace) -> int:
998
+ """CLI-B28: `tempergraph help` prints what `tempergraph --help` prints."""
999
+ env.out.write(_parser().format_help())
1000
+ return 0
1001
+
1002
+
1003
+ def cmd_stop(env: Env, a: argparse.Namespace) -> int:
1004
+ from tempergraph.durability.control import NotLive, request_stop
1005
+
1006
+ spec, tid = _one(env, a.selector)
1007
+ _hand_over_lost(env, [_root(env)], tid) # SIL-B29: a lost runner is found here and answered as "not running"
1008
+ try:
1009
+ mode = request_stop(_root(env), spec.name, tid.split("/", 1)[1], "now" if a.now else "drain",
1010
+ caller=_stop_caller(env, a))
1011
+ except NotLive as exc:
1012
+ raise UsageError(str(exc)) from exc
1013
+ _emit(env, {"schema_version": 1, "thread_id": tid, "mode": mode})
1014
+ return 0
1015
+
1016
+
1017
+ def cmd_carry(env: Env, a: argparse.Namespace) -> int:
1018
+ """CAR-B5: `carry push|pull|status|drop <workflow> <thread>`."""
1019
+ from tempergraph import identity
1020
+ from tempergraph.durability import carry
1021
+ from tempergraph.durability.lock import is_held
1022
+ from tempergraph.package.loader import full_version
1023
+ from tempergraph.store.layout import lock_path
1024
+
1025
+ spec = _spec(env, a.workflow)
1026
+ root = _root(env)
1027
+ _needs_git(env, "carry")
1028
+ repo = root.parent
1029
+ task = a.thread.split("/", 1)[1] if a.thread.startswith(f"{spec.name}/") else a.thread
1030
+ machine = identity.machine_id()
1031
+ try:
1032
+ if a.action == "status":
1033
+ doc: dict[str, Any] = carry.status(root, repo, spec.name, task, remote=a.remote)
1034
+ elif is_held(lock_path(root, spec.name, task)):
1035
+ raise UsageError(f"{spec.name}/{task} is running in another process")
1036
+ elif a.action == "push":
1037
+ if not (run_dir_of(root, spec.name, task) / "run.jsonl").exists():
1038
+ raise UsageError(f"{spec.name}/{task}: no such thread")
1039
+ got = carry.push(root, repo, spec.name, task, remote=a.remote, workflow_version=full_version(spec),
1040
+ machine=machine, force=a.force)
1041
+ doc = {"branch": got.branch, "remote": got.remote, "seq": got.seq, "commit": got.commit}
1042
+ elif a.action == "pull":
1043
+ caller = _stop_caller(env, a) if a.force else {}
1044
+ doc = carry.pull(root, repo, spec.name, task, remote=a.remote, current_version=full_version(spec),
1045
+ machine=machine, force=a.force, caller=caller)
1046
+ else:
1047
+ doc = carry.drop(root, repo, spec.name, task, remote=a.remote)
1048
+ except carry.CarryRefused as exc:
1049
+ raise UsageError(f"{exc.code}: {exc}") from exc
1050
+ except carry.CarryFailed as exc:
1051
+ env.err.write(f"tempergraph: the remote could not be reached or refused: {exc}\n")
1052
+ return int(ExitCode.BUDGET_OR_INFRA)
1053
+ doc = {"schema_version": 1, "action": a.action, "thread_id": f"{spec.name}/{task}", **doc}
1054
+ if a.json:
1055
+ _emit(env, doc)
1056
+ else:
1057
+ env.out.write("".join(f"{k}: {v}\n" for k, v in doc.items() if k != "schema_version" and v is not None))
1058
+ return 0
1059
+
1060
+
1061
+ def run_dir_of(root: Path, workflow: str, task_id: str) -> Path:
1062
+ from tempergraph.store.layout import run_dir
1063
+
1064
+ return run_dir(root, workflow, task_id)
1065
+
1066
+
1067
+ def _stop_caller(env: Env, a: argparse.Namespace) -> dict[str, Any]:
1068
+ from tempergraph.provenance import decide
1069
+ from tempergraph.store.layout import home_path
1070
+
1071
+ return decide(env.caller(a), relayed=bool(getattr(a, "relayed", False)), words=("stop",), home=home_path())
1072
+
1073
+
1074
+ def cmd_worktree(env: Env, a: argparse.Namespace) -> int:
1075
+ from tempergraph.workspace import list_worktrees, prune_apply, prune_plan, worktree_path
1076
+
1077
+ if a.action == "list":
1078
+ _emit(env, {"schema_version": 1, "worktrees": list_worktrees(env.cwd, all=bool(a.all))})
1079
+ return 0
1080
+ if a.action == "prune": # WTR-B27, WTR-B16: without --apply it only lists; with it, clean ones go, no branch
1081
+ rows = prune_plan(env.cwd, thread=a.thread, finished=bool(a.finished), older_than=a.older_than)
1082
+ if not a.apply:
1083
+ _emit(env, {"schema_version": 1, "removable": rows})
1084
+ return 0
1085
+ caller = env.caller(a) # PRV: the call that changed the repository's worktrees records who made it
1086
+ _emit(env, {"schema_version": 1, "removed": prune_apply(env.cwd, rows), "caller": caller})
1087
+ return 0
1088
+ if a.action == "path":
1089
+ p = worktree_path(env.cwd, a.thread)
1090
+ if p is None:
1091
+ raise UsageError(f"no run worktree for {a.thread}")
1092
+ env.out.write(f"{p}\n")
1093
+ return 0
1094
+ raise UsageError("worktree needs list, path or prune")
1095
+
1096
+
1097
+ def cmd_config(env: Env, a: argparse.Namespace) -> int:
1098
+ """RST-B31: read-only, model-free; `show` calls the same resolver a start or resume does (RST-B9)."""
1099
+ import fnmatch
1100
+
1101
+ from tempergraph import settings as rst
1102
+ from tempergraph.store.layout import home_path
1103
+
1104
+ root = _root_or_none(env)
1105
+ if a.action == "paths":
1106
+ pp, up = rst.config_paths(root, home_path())
1107
+ _emit(env, {"schema_version": 1, "files": [{"layer": "project", "path": str(pp) if pp else None,
1108
+ "exists": bool(pp and pp.exists())},
1109
+ {"layer": "user", "path": str(up), "exists": up.exists()}]})
1110
+ return 0
1111
+ if a.action == "validate":
1112
+ return _config_validate(env, a, root)
1113
+ if a.action != "show":
1114
+ raise UsageError("config needs show, validate or paths")
1115
+ from tempergraph.run.runner import SettingsRefused, settle_resume, settle_start
1116
+
1117
+ spec = _spec(env, a.workflow)
1118
+ settings = _settings(env, a, mutating=False)
1119
+ findings: list[Any] = []
1120
+ try:
1121
+ if a.thread:
1122
+ from tempergraph.durability.checkpoint import thread_values
1123
+
1124
+ if root is None:
1125
+ raise UsageError("--thread needs a git repository")
1126
+ task = a.thread.split("/", 1)[1] if "/" in a.thread else a.thread
1127
+ from tempergraph.durability import engine_file
1128
+
1129
+ values = thread_values(engine_file.checkpoint_of(root, spec.name, task), spec,
1130
+ thread_id(spec.name, task))
1131
+ if not values:
1132
+ raise UsageError(f"no thread {thread_id(spec.name, task)}")
1133
+ settled = settle_resume(spec, settings, root, values)
1134
+ else:
1135
+ settled = settle_start(spec, settings, root)
1136
+ rows = rst.rows_json(settled.resolved)
1137
+ digest = settled.resolved.digest
1138
+ except SettingsRefused as exc:
1139
+ findings, rows, digest = exc.findings, [], None
1140
+ if a.key:
1141
+ rows = [r for r in rows if fnmatch.fnmatch(r["key"], a.key)]
1142
+ _emit(env, {"schema_version": 1, "workflow": spec.name, "settings_digest": digest, "rows": rows,
1143
+ "findings": [{"code": f.code, "message": f.message} for f in findings]})
1144
+ return int(ExitCode.USAGE) if findings else 0
1145
+
1146
+
1147
+ def _config_validate(env: Env, a: argparse.Namespace, root: Path | None) -> int:
1148
+ from tempergraph import settings as rst
1149
+ from tempergraph.store.layout import home_path
1150
+
1151
+ if a.file:
1152
+ p = (env.cwd / a.file).resolve()
1153
+ files = rst.ConfigFiles()
1154
+ try:
1155
+ doc = json.loads(p.read_text(encoding="utf-8"))
1156
+ files = dataclasses.replace(files, user=doc if isinstance(doc, dict) and doc.get("schema_version") == 1
1157
+ else None, user_path=p)
1158
+ errs = [] if files.user is not None else [{"code": "config_file", "message": f"{p}: not schema 1"}]
1159
+ except (OSError, ValueError) as exc:
1160
+ errs = [{"code": "config_file", "message": f"{p}: {exc}"}]
1161
+ else:
1162
+ files = rst.load_files(root, home_path())
1163
+ errs = [{"code": f.code, "message": f.message} for f in files.errors]
1164
+ named = {str(e.get("workflow")) for doc in (files.project, files.user) if doc
1165
+ for e in (doc.get("overrides") or []) if isinstance(e, dict)}
1166
+ for name, spec in env.catalog.specs.items(): # defaults reach every workflow, so every one is checked
1167
+ _, found = rst.options_snapshot(spec, {}, (), dataclasses.replace(files, errors=()))
1168
+ errs += [{"code": f.code, "workflow": name, "message": f.message} for f in found]
1169
+ for wf in sorted(named - set(env.catalog.specs) - {"*"}):
1170
+ errs.append({"code": "unknown_workflow", "workflow": wf, "message": f"no registered workflow {wf!r}"})
1171
+ _emit(env, {"schema_version": 1, "ok": not errs, "findings": errs})
1172
+ return int(ExitCode.USAGE) if errs else 0
1173
+
1174
+
1175
+ def cmd_outcome(env: Env, a: argparse.Namespace) -> int:
1176
+ from tempergraph.cli.outcome import cmd_outcome as run_outcome
1177
+
1178
+ return run_outcome(env, a)
1179
+
1180
+
1181
+ COMMANDS: dict[str, Callable[[Env, argparse.Namespace], int]] = {
1182
+ "run": cmd_run, "resume": cmd_resume, "status": cmd_status, "list": cmd_list, "validate": cmd_validate,
1183
+ "executors": cmd_executors, "events": cmd_events, "facts": cmd_facts, "self-check": cmd_self_check, "hooks": cmd_hooks, "graph": cmd_graph, "wait": cmd_wait,
1184
+ "stop": cmd_stop, "carry": cmd_carry, "worktree": cmd_worktree, "config": cmd_config, "rerun": cmd_rerun, "outcome": cmd_outcome,
1185
+ "help": cmd_help,
1186
+ **observe_cli.COMMANDS,
1187
+ **schedule_cli.COMMANDS,
1188
+ "workflows": workflows_cli.cmd_workflows,
1189
+ "audit": audit_cli.cmd_audit,
1190
+ "blueprint": author_cli.cmd_blueprint,
1191
+ "literals": author_cli.cmd_literals,
1192
+ "scaffold": author_cli.cmd_scaffold,
1193
+ "author": author_cli.cmd_author,
1194
+ "install": install_cli.cmd_install,
1195
+ "update": install_cli.cmd_update,
1196
+ "upgrade": upgrade_cli.cmd_upgrade,
1197
+ "upgrade-check": upgrade_cli.cmd_upgrade,
1198
+ "evals": lambda env, a: _improve().cmd_evals(env, a),
1199
+ "labels": lambda env, a: _improve().cmd_labels(env, a),
1200
+ "improve": lambda env, a: _improve().cmd_improve(env, a),
1201
+ "promote-check": lambda env, a: _improve().cmd_promote_check(env, a),
1202
+ }
1203
+
1204
+
1205
+ def _improve() -> Any:
1206
+ from tempergraph.cli import improve
1207
+
1208
+ return improve
1209
+
1210
+
1211
+ def main(argv: Sequence[str] | None = None, *, catalog: Catalog | None = None, registry: Registry | None = None,
1212
+ cwd: Path | None = None, out: IO[str] | None = None, err: IO[str] | None = None,
1213
+ run_settings: Callable[..., Any] | None = None, signals: tuple[Mapping[str, str], bool] | None = None,
1214
+ hand_over: Callable[[Path, list[str]], int] | None = None) -> int:
1215
+ out, err = out or sys.stdout, err or sys.stderr
1216
+ root_before = os.environ.get(ROOT_VAR)
1217
+ try:
1218
+ given = tuple(argv if argv is not None else sys.argv[1:])
1219
+ a = _parse(list(given))
1220
+ if a.state_root: # read by `state_root_path` outside git; inside a repository it changes nothing
1221
+ declared = Path(a.state_root).expanduser()
1222
+ os.environ[ROOT_VAR] = str((declared if declared.is_absolute() else (cwd or Path.cwd()) / declared).resolve())
1223
+ if not a.verb:
1224
+ raise UsageError("a verb is needed; `tempergraph --help` lists them")
1225
+ if a.verb not in COMMANDS:
1226
+ raise UsageError(f"{a.verb}: not in this release")
1227
+ light = a.verb == "help" or (a.verb == "supervision" and getattr(a, "action", None) in ("hook", "log", "close"))
1228
+ env = Env(catalog=catalog if catalog is not None else Catalog() if light else from_registry(),
1229
+ registry=registry if registry is not None else default_registry(),
1230
+ cwd=(cwd or Path.cwd()).resolve(), out=out, err=err, run_settings=run_settings,
1231
+ signals=signals, argv=given, hand_over=hand_over)
1232
+ return COMMANDS[a.verb](env, a)
1233
+ except UsageError as exc:
1234
+ err.write(f"tempergraph: {exc}\n")
1235
+ return int(ExitCode.USAGE)
1236
+ except PackageNotLoaded as exc:
1237
+ err.write(f"tempergraph: {exc}\n")
1238
+ return int(ExitCode.INTERNAL)
1239
+ except SystemExit as exc: # --help
1240
+ return int(exc.code or 0) if isinstance(exc.code, int) else 0
1241
+ except Exception as exc: # noqa: BLE001 - CLI-B17, CLI-B18, CLI-B19: exit 1 after an engine-error record
1242
+ _engine_error(exc)
1243
+ err.write(f"tempergraph: internal error ({type(exc).__name__})\n")
1244
+ return int(ExitCode.INTERNAL)
1245
+ finally: # `--state-root` holds for this call only
1246
+ if root_before is None:
1247
+ os.environ.pop(ROOT_VAR, None)
1248
+ else:
1249
+ os.environ[ROOT_VAR] = root_before
1250
+
1251
+
1252
+ def _engine_error(exc: BaseException) -> None:
1253
+ """The engine-error record in the engine code log (LOS-B13); best effort (OVR-B4)."""
1254
+ try:
1255
+ logging.getLogger("tempergraph").error("engine_error", exc_info=exc)
1256
+ except Exception: # noqa: BLE001
1257
+ traceback.print_exception(exc, file=sys.stderr)
1258
+
1259
+
1260
+ def entry() -> None:
1261
+ raise SystemExit(main())