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,1158 @@
1
+ """Validation before spend (WFM-B8, WFM-B9, WFM-B10, WFM-B11, WFM-B12).
2
+
3
+ One function guards the catalog, a start, a resume, the pre-start check and the upgrade check
4
+ (WFM-AC2). Each refusal has its own finding code (WFM-AC1). The engine never names a workflow (OVR-B10).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import re
11
+ from collections.abc import Mapping
12
+ from dataclasses import dataclass
13
+ from typing import Any, Literal
14
+
15
+ from tempergraph.constants import RELEASE
16
+ from tempergraph.contracts import (
17
+ ARM_OVERRIDE_KEYS,
18
+ EFFORTS,
19
+ READ_ONLY_CAPABILITIES,
20
+ REARM_CAUSES,
21
+ STAGES,
22
+ CallableRef,
23
+ Capabilities,
24
+ Criterion,
25
+ StepSpec,
26
+ SwitchSpec,
27
+ UnitSpec,
28
+ ValueKind,
29
+ WorkflowSpec,
30
+ is_capability,
31
+ )
32
+ from tempergraph.improve import lessons
33
+ from tempergraph.model import flow
34
+ from tempergraph.model.text import (
35
+ ENGINE_KEYS,
36
+ ITEM_KEYS,
37
+ RESERVED_KEYS,
38
+ TextUnreadable,
39
+ input_names,
40
+ load_text,
41
+ )
42
+ from tempergraph.render.template import TemplateError, fields
43
+ from tempergraph.security.launch import has_shell_metacharacter
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Finding:
48
+ code: str
49
+ unit: str | None
50
+ message: str
51
+ severity: Literal["error", "warning"] = "error"
52
+
53
+
54
+ # Kinds, primitives and fields this release does not build, with the release that adds them (ADR `first-release-is-simple-trusted-workflows-on-one-machine`).
55
+ LATER_KINDS: dict[str, int] = {}
56
+ # The artifacts a council produces, keyed by the unit (CNL-B10); the judge reads `decision` and `positions` (CNL-B4).
57
+ COUNCIL_ARTIFACTS = ("decision", "positions", "tally")
58
+ COUNCIL_MODES = ("synthesize", "vote", "rank")
59
+ COUNCIL_RULES = ("majority", "supermajority", "unanimous", "plurality")
60
+ STANCE_MAX = 400
61
+ MODEL_KINDS = frozenset({"step"})
62
+ # Keys the settings resolution writes into a unit's `extra` (RST `effective_spec`), never a workflow's own field.
63
+ RESOLVED_EXTRA = frozenset({"operator_set", "arm", "judge_operator_set", "session_cost_cap_usd"})
64
+ ISSUE_REPO_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
65
+ SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
66
+ READ_VIEW_KINDS = frozenset({"file", "url", "value"}) # what a claude judge can read without MCP views
67
+
68
+
69
+ def validate(spec: WorkflowSpec, executors: Mapping[str, Capabilities]) -> list[Finding]:
70
+ v = _Validator(spec, executors)
71
+ v.run()
72
+ return v.findings
73
+
74
+
75
+ def errors(findings: list[Finding]) -> list[Finding]:
76
+ return [f for f in findings if f.severity == "error"]
77
+
78
+
79
+ class _Validator:
80
+ def __init__(self, spec: WorkflowSpec, executors: Mapping[str, Capabilities]) -> None:
81
+ self.spec = spec
82
+ self.executors = executors
83
+ self.findings: list[Finding] = []
84
+ self._children: dict[str, Any] = {}
85
+
86
+ def _child(self, name: str) -> Any:
87
+ """A child read once per validation, by the one reader (SWF-B6, SWF-B12); loaded only when a unit names one."""
88
+ if name not in self._children:
89
+ from tempergraph.model import subworkflow
90
+
91
+ self._children[name] = subworkflow.read_child(name)
92
+ return self._children[name]
93
+
94
+ def err(self, code: str, unit: str | None, message: str) -> None:
95
+ self.findings.append(Finding(code, unit, message, "error"))
96
+
97
+ def warn(self, code: str, unit: str | None, message: str) -> None:
98
+ self.findings.append(Finding(code, unit, message, "warning"))
99
+
100
+ def run(self) -> None:
101
+ s = self.spec
102
+ if not s.order:
103
+ self.err("order-empty", None, "the workflow's order is empty")
104
+ return
105
+ for name in s.order:
106
+ if name not in s.units:
107
+ self.err("order-unknown-unit", name, f"order names {name!r}, which is not a unit")
108
+ if any(f.code == "order-unknown-unit" for f in self.findings):
109
+ return
110
+ if flow.OUTCOME_UNIT in s.units:
111
+ self.err("reserved-unit-name", flow.OUTCOME_UNIT, "the unit name 'outcome' is reserved (OUT-B15, OUT-B16, OUT-B17)")
112
+ self._release()
113
+ self._inputs()
114
+ self._settings()
115
+ self._routing()
116
+ for name in s.order:
117
+ self._unit(name, s.units[name])
118
+ self._flow()
119
+ self._finalizer()
120
+ for code, unit, msg in lessons.validate(s): # LSN-B6, LSN-B7
121
+ self.err(code, unit, msg)
122
+ from tempergraph.model.prompt_lint import lint # LIF: prompt lint is part of validate
123
+
124
+ self.findings += [Finding(f.code, f.unit, f"{f.where}: {f.message}", f.severity) for f in lint(s)]
125
+ if s.package_root is not None and (s.package_root / "tempergraph.json").is_file(): # PKG-B15, PKG-B16, PKG-B17 step 6
126
+ from tempergraph.package.loader import package_findings
127
+
128
+ self.findings += package_findings(s)
129
+
130
+ def _inputs(self) -> None:
131
+ """VAL-B8: a declared input named like an engine or item key is refused."""
132
+ for param in self.spec.input.parameters:
133
+ if param.name in RESERVED_KEYS:
134
+ self.err("reserved-key", None, f"input {param.name!r} is a reserved template key")
135
+
136
+ # -- release --------------------------------------------------------------------------------
137
+ def _release(self) -> None:
138
+ s = self.spec
139
+ for name, u in s.units.items():
140
+ if u.kind in LATER_KINDS:
141
+ self.err("not_in_release", name,
142
+ f"unit kind {u.kind!r} is built in release {LATER_KINDS[u.kind]}, not release {RELEASE}")
143
+ if u.step is not None and u.step.self_check and u.gate.check is None:
144
+ self.err("self-check-without-check", name, "`self_check` needs a gate check to preview (CHK-B15, CHK-B14, CHK-B10, CHK-B17)")
145
+ later = sorted(k for k in u.extra if k not in RESOLVED_EXTRA)
146
+ if later:
147
+ self.err("not_in_release", name, f"fields {later} are not built in release {RELEASE}")
148
+ if s.extra:
149
+ self.err("not_in_release", None, f"workflow fields {sorted(s.extra)} are not built in release {RELEASE}")
150
+
151
+ # -- settings and routing ---------------------------------------------------------------------
152
+ def _settings(self) -> None:
153
+ s = self.spec
154
+ if s.builtin and not s.issue_repository:
155
+ pass # a workflow the engine ships files nothing: it has no repository of its own (UWF-B6, UWF-B5, UWF-B7)
156
+ elif not s.issue_repository or not ISSUE_REPO_RE.match(s.issue_repository):
157
+ self.err("issue-repository-invalid", None, "`issue_repository` must be `owner/name`")
158
+ if s.run_cost_cap_usd is not None and not s.run_cost_cap_usd > 0:
159
+ self.err("cost-cap-invalid", None, "`run_cost_cap_usd` must be positive")
160
+ for name, decl in s.settings.items():
161
+ if not _setting_ok(decl.kind, decl.default, decl.choices, decl.min, decl.max):
162
+ self.err("setting-default-invalid", None, f"setting {name!r}: default outside its kind or range")
163
+ for pname, bundle in s.profiles.items():
164
+ for key, value in bundle.items():
165
+ if key.startswith("settings."):
166
+ found = s.settings.get(key[len("settings."):])
167
+ if found is None:
168
+ self.err("profile-key-unknown", None, f"profile {pname!r} names unknown setting {key!r}")
169
+ elif not _setting_ok(found.kind, value, found.choices, found.min, found.max):
170
+ self.err("profile-value-invalid", None, f"profile {pname!r}: {key} outside its range")
171
+
172
+ # -- person units and flow extensions (ASK, HUM-B4, FLX-B11) -------------------------------------
173
+ def _forward(self, name: str, target: str, *, finalizer: bool) -> bool:
174
+ order = list(self.spec.order)
175
+ if target == flow.FINALIZER:
176
+ return finalizer
177
+ return target in order and name in order and order.index(target) > order.index(name)
178
+
179
+ def _deadline(self, name: str, deadline_s: int | None, on_deadline: str) -> None:
180
+ if deadline_s is None:
181
+ return
182
+ if not isinstance(deadline_s, int) or deadline_s <= 0:
183
+ self.err("deadline-invalid", name, "`deadline_s` must be a positive integer")
184
+ if on_deadline not in ("escalate", "stop", "defaults") and not self._forward(name, on_deadline,
185
+ finalizer=True):
186
+ self.err("deadline-target-not-forward", name,
187
+ f"`on_deadline` is `escalate`, `stop`, `defaults` (an ask only) or a unit after {name!r}, "
188
+ f"not {on_deadline!r}")
189
+
190
+ def _person_gate(self, name: str, u: UnitSpec) -> None:
191
+ g = u.gate
192
+ if g.judge is not None or g.criteria:
193
+ self.err("person-unit-judge", name, f"a `{u.kind}` unit has no judge and no criteria: the person's "
194
+ "input, checked by rule, is the bar")
195
+ if g.approval or g.back_targets:
196
+ self.err("person-unit-gate", name, f"a `{u.kind}` unit takes no approval and no back target")
197
+
198
+ def _ask(self, name: str, u: UnitSpec) -> None:
199
+ from tempergraph.run import asking
200
+
201
+ a = u.ask
202
+ if a is None:
203
+ self.err("ask-invalid", name, "an ask unit needs questions or `questions_from`")
204
+ return
205
+ self._person_gate(name, u)
206
+ if bool(a.questions) == bool(a.questions_from):
207
+ self.err("ask-invalid", name, "an ask takes exactly one of `questions` and `questions_from`")
208
+ for problem in asking.question_problems(a.questions) if a.questions else ():
209
+ self.err("ask-question-invalid", name, problem)
210
+ if a.questions_from and a.questions_from not in self._keys_before(name):
211
+ self.err("ask-from-unknown", name, f"`questions_from` names {a.questions_from!r}, which no earlier "
212
+ "unit produces")
213
+ for key in a.context:
214
+ if key not in self._keys_before(name):
215
+ self.err("ask-context-unknown", name, f"context names {key!r}, which no earlier unit produces")
216
+ if a.check is not None:
217
+ self._callable(name, a.check, "check")
218
+ self._deadline(name, a.deadline_s, a.on_deadline)
219
+ if a.on_deadline == "defaults" and a.questions: # FLX-B11: with or without `deadline_s`
220
+ for problem in asking.defaults_problems(a.questions):
221
+ self.err("deadline-defaults-incomplete", name, problem)
222
+
223
+ def _wait(self, name: str, u: UnitSpec) -> None:
224
+ w = u.wait
225
+ if w is None:
226
+ self.err("wait-invalid", name, "a wait unit needs an event name and a check")
227
+ return
228
+ self._person_gate(name, u)
229
+ if not SLUG_RE.match(w.event.replace("_", "-")):
230
+ self.err("wait-invalid", name, f"event name {w.event!r} is not a slug")
231
+ self._callable(name, w.check, "check")
232
+ self._deadline(name, w.deadline_s, w.on_deadline)
233
+ if w.on_deadline == "defaults":
234
+ self.err("deadline-defaults-not-ask", name, "`on_deadline: defaults` fills an ask's questions; a wait "
235
+ "has none")
236
+
237
+ def _keys_before(self, name: str) -> set[str]:
238
+ return self._earlier_keys(name)["any"]
239
+
240
+ def _parallel(self, name: str, u: UnitSpec) -> None:
241
+ """CMP-B10 to CMP-B16, WFM-B7, WFM-B8: two or more branches directly before their join; a branch that declares
242
+ `write` or `edit` works in its own worktree, which `workspace: in_place` has none of."""
243
+ order = list(self.spec.order)
244
+ if len(u.branches) < 2 or len(set(u.branches)) != len(u.branches):
245
+ self.err("parallel-branches", name, "a parallel block needs two or more distinct branches")
246
+ return
247
+ at = order.index(name)
248
+ for b in u.branches:
249
+ bu = self.spec.units.get(b)
250
+ if bu is None or b not in order:
251
+ self.err("parallel-branch-unknown", name, f"branch {b!r} is not a unit in `order`")
252
+ continue
253
+ if order.index(b) > at:
254
+ self.err("parallel-join-before-branch", name, f"the join {name!r} comes before its branch {b!r}")
255
+ if bu.kind not in ("step", "script"):
256
+ self.err("parallel-branch-kind", b, f"a branch is a step or a script unit, not a `{bu.kind}`")
257
+ if bu.kind == "contest": # CTS-B10: its own code beside the general one
258
+ self.err("contest-in-branch", b, f"{b!r} is a contest, which a parallel branch cannot be")
259
+ if bu.gate.back_targets or bu.gate.fallback or bu.route is not None or b in self.spec.flow:
260
+ self.err("parallel-branch-flow", b, "a branch takes no back target, fallback, route or `next`: "
261
+ "its pass goes to the join")
262
+ others = [n for n, o in self.spec.units.items() if n != name and o.kind == "parallel" and b in o.branches]
263
+ if others:
264
+ self.err("parallel-branch-shared", b, f"{b!r} is a branch of {name!r} and of {others[0]!r}")
265
+ placed = [order.index(b) for b in u.branches if b in order]
266
+ if placed and sorted(placed) != list(range(at - len(placed), at)):
267
+ self.err("parallel-branches-not-adjacent", name, "a block's branches are the units directly before "
268
+ "its join in `order`")
269
+ writers = flow.writer_branches(self.spec, name)
270
+ if writers and self.spec.workspace == "in_place": # WFM-B8: a writer branch has its own worktree
271
+ self.err("parallel-writer-in-place", writers[0], f"{writers[0]!r} declares `write` or `edit`, which needs its "
272
+ "own worktree; a workflow that declares `workspace: in_place` has none (WSP-B11)")
273
+ if u.gate.judge is not None or u.gate.criteria or u.gate.check is not None or u.gate.approval:
274
+ self.err("parallel-join-gate", name, "the join is engine-owned in this release: it takes no check, "
275
+ "judge, criteria or approval")
276
+
277
+ def _subworkflow(self, name: str, u: UnitSpec) -> None:
278
+ """SWF-B6: the refusals of one sub-workflow unit, from the one reader of a child, with no spend."""
279
+ if u.subworkflow is None:
280
+ return
281
+ from tempergraph.model import subworkflow
282
+
283
+ for code, unit, message in subworkflow.unit_problems(self.spec, name, read=self._child):
284
+ self.err(code, unit, message)
285
+ child = self._child(u.subworkflow.workflow)
286
+ if isinstance(child, subworkflow.Child) and child.spec.finalizer is not None: # SWF-B8, SWF-B10
287
+ self.warn("subworkflow-finalizer-skipped", name,
288
+ f"unit {name!r}: child {child.name!r} declares a finalizer, which never runs from a parent; the "
289
+ "parent's own finalizer can call the same code")
290
+
291
+ def _council(self, name: str, u: UnitSpec) -> None:
292
+ """CNL-B9, CNL-B16: the refusals of one council unit, each with its own finding code, and its three warnings."""
293
+ s = self.spec
294
+ c = u.council
295
+ if c is None:
296
+ self.err("council-missing", name, "a council unit needs its council fields")
297
+ return
298
+ block = flow.block_of(s, name)
299
+ if block is not None and flow.writer_branches(s, block): # WSP-B11: a branch of a writer block works in a worktree of its own
300
+ self.err("council-in-writer-block", name, f"{name!r} is a branch of {block!r}, a block with a writer branch")
301
+ if not 2 <= len(c.members) <= 7:
302
+ self.err("council-members-count", name, f"a council has 2 to 7 members, not {len(c.members)}")
303
+ names = [m.name for m in c.members]
304
+ for dup in sorted({n for n in names if names.count(n) > 1}):
305
+ self.err("council-member-duplicate", name, f"two members are named {dup!r}")
306
+ for m in c.members:
307
+ if not SLUG_RE.match(m.name):
308
+ self.err("council-member-name-invalid", name, f"member name {m.name!r} is not a slug")
309
+ if len(m.stance) > STANCE_MAX:
310
+ self.err("council-stance-too-long", name, f"member {m.name!r}: a stance holds at most {STANCE_MAX} characters")
311
+ for label, val in (("timeout_s", m.timeout_s), ("idle_s", m.idle_s)):
312
+ if val is not None and (isinstance(val, bool) or not isinstance(val, int) or val <= 0):
313
+ self.err("timeout-invalid", name, f"member {m.name!r}: `{label}` must be a positive integer")
314
+ for tool in m.tools: # GRD: the engine's catalog holds no MCP tool read-only, so any MCP tool is refused
315
+ if tool not in READ_ONLY_CAPABILITIES:
316
+ self.err("council-member-tool-not-read-only", name,
317
+ f"member {m.name!r}: tool {tool!r} is outside the read-only catalog")
318
+ self._council_options(name, c)
319
+ if not isinstance(c.rounds, int) or isinstance(c.rounds, bool) or not 0 <= c.rounds <= 3:
320
+ self.err("council-rounds-invalid", name, "`rounds` is an integer from 0 to 3")
321
+ if c.quorum is not None and (isinstance(c.quorum, bool) or not isinstance(c.quorum, int)
322
+ or not 1 <= c.quorum <= max(len(c.members), 1)):
323
+ self.err("council-quorum-invalid", name, "`quorum` is an integer from 1 to the member count")
324
+ if c.on_no_decision not in ("escalate", "retry", "stop"):
325
+ self.err("council-no-decision-invalid", name, "`on_no_decision` is escalate, retry or stop")
326
+ if c.retry_scope not in ("all", "chair"):
327
+ self.err("council-retry-scope-invalid", name, "`retry_scope` is all or chair")
328
+ elif c.retry_scope == "chair" and c.mode == "vote":
329
+ self.err("council-retry-scope-vote", name, "`retry_scope: chair` keeps final positions for `synthesize` and `rank`, not `vote`")
330
+ if c.cost_cap_usd is not None and not c.cost_cap_usd > 0:
331
+ self.err("cost-cap-invalid", name, "`cost_cap_usd` must be positive")
332
+ if c.mode == "synthesize" and c.chair is None:
333
+ self.err("council-chair-missing", name, "a `synthesize` council needs a chair")
334
+ if u.gate.judge is None: # OVR-B6: a council is a step; its gate has the one independent judge
335
+ self.err("council-judge-missing", name, "a council's gate needs a judge")
336
+ if not u.gate.criteria:
337
+ self.err("criteria-missing", name, "a judged gate needs at least one criterion")
338
+ self._template(name, c.question)
339
+ self._council_sessions(name, u, c)
340
+ if u.gate.judge is not None:
341
+ self._judge(name, u, s.default_executor)
342
+ if c.mode == "vote" and (c.rule or "majority") == "majority" and len(c.members) % 2 == 0:
343
+ self.warn("council-even-majority", name, f"{name!r}: `rule: majority` with {len(c.members)} members can tie")
344
+ if c.rounds > 0 and not c.anonymize:
345
+ self.warn("council-anonymize-off", name, f"{name!r}: deliberation rounds with `anonymize: false` name the authors")
346
+
347
+ def _council_options(self, name: str, c: Any) -> None:
348
+ if c.mode not in COUNCIL_MODES:
349
+ self.err("council-mode-invalid", name, f"`mode` is one of {list(COUNCIL_MODES)}")
350
+ if c.mode != "vote":
351
+ if c.rule is not None:
352
+ self.err("council-rule-outside-vote", name, "`rule` belongs to a `vote` council")
353
+ if c.options is not None:
354
+ self.err("council-options-outside-vote", name, "`options` belongs to a `vote` council")
355
+ return
356
+ if c.rule is not None and c.rule not in COUNCIL_RULES:
357
+ self.err("council-rule-invalid", name, f"`rule` is one of {list(COUNCIL_RULES)}")
358
+ opts = c.options
359
+ if opts is None or (not isinstance(opts, str) and len(opts) < 2):
360
+ self.err("council-options-missing", name, "a `vote` council needs `options`: 2 to 10 slugs or a list artifact")
361
+ elif isinstance(opts, str):
362
+ if opts not in self._keys_before(name):
363
+ self.err("council-options-unknown", name, f"`options` names {opts!r}, which no earlier unit produces")
364
+ elif len(opts) > 10 or len(set(opts)) != len(opts) or not all(SLUG_RE.match(str(o)) for o in opts):
365
+ self.err("council-options-invalid", name, "`options` are 2 to 10 distinct slugs")
366
+
367
+ def _council_sessions(self, name: str, u: UnitSpec, c: Any) -> None:
368
+ """The executor, alias and tools of each member and of the chair, and the one-family warning (CNL-B16, ARC-B15)."""
369
+ s = self.spec
370
+ families: list[str | None] = []
371
+ for who, ex_name, alias, tools in [(f"member {m.name!r}", m.executor, m.model, m.tools) for m in c.members] + (
372
+ [("the chair", c.chair.executor, c.chair.model, ())] if c.chair is not None else []):
373
+ executor = ex_name or s.default_executor
374
+ caps = self.executors.get(executor)
375
+ if caps is None:
376
+ self.err("executor-unknown", name, f"{who}: unknown executor {executor!r}")
377
+ families.append(None)
378
+ continue
379
+ if alias:
380
+ self._alias(name, alias, caps)
381
+ for tool in tools:
382
+ if tool in READ_ONLY_CAPABILITIES and not caps.maps(tool):
383
+ self.err("tool-unmapped", name, f"{who}: executor {executor!r} maps no tool for {tool!r}")
384
+ if who != "the chair":
385
+ families.append(caps.families.get(alias or "inherit"))
386
+ if len(families) >= 2 and None not in families and len(set(families)) == 1:
387
+ self.warn("council-one-family", name, f"{name!r}: every member runs on the {families[0]!r} model family")
388
+
389
+ def _exposed(self, unit: str, owner: str, key: str) -> bool:
390
+ """SWF-B12: `{<owner>.<key>}` read by `unit` names a key a sub-workflow unit earlier in the order exposes."""
391
+ from tempergraph.model import subworkflow
392
+
393
+ s = self.spec
394
+ order = list(s.order)
395
+ o = s.units.get(owner)
396
+ if o is None or o.subworkflow is None or owner not in order or unit not in order \
397
+ or order.index(owner) >= order.index(unit):
398
+ return False
399
+ child = self._child(o.subworkflow.workflow)
400
+ if not isinstance(child, subworkflow.Child): # a child that cannot be read exposes nothing
401
+ return False
402
+ return key in subworkflow.exposed_keys(o, child)
403
+
404
+ def _fallback(self, name: str, u: UnitSpec) -> None:
405
+ g = u.gate
406
+ if (g.on_fail == "fallback" or g.on_budget_spent == "fallback") and not g.fallback:
407
+ self.err("fallback-missing", name, "`on_fail: fallback` or `on_budget_spent: fallback` needs `fallback`")
408
+ if g.fallback and not self._forward(name, g.fallback, finalizer=True):
409
+ self.err("fallback-not-forward", name, f"`fallback` names {g.fallback!r}, which is not a unit after "
410
+ f"{name!r} or the finalizer")
411
+ if g.fallback and g.on_fail != "fallback" and g.on_budget_spent != "fallback":
412
+ self.warn("fallback-unused", name, "`fallback` is set but neither `on_fail` nor `on_budget_spent` "
413
+ "uses it")
414
+
415
+ def _back(self, name: str, g: Any) -> None: # HUM-B18
416
+ if g.on_fail != "back":
417
+ return
418
+ if g.judge is not None:
419
+ self.err("back-with-judge", name, "`on_fail: back` is declared on a gate with a judge; the judge "
420
+ "decides where a run goes back")
421
+ if not g.back_targets:
422
+ self.err("back-target-missing", name, "`on_fail: back` needs one back target")
423
+ elif len(g.back_targets) > 1:
424
+ self.err("back-targets-many", name, "`on_fail: back` takes exactly one back target, "
425
+ f"not {len(g.back_targets)}")
426
+
427
+ def _may_skip(self, name: str, g: Any) -> None: # WFM-B14
428
+ if not g.judge_may_skip:
429
+ return
430
+ if g.judge is None:
431
+ self.err("judge-may-skip-without-judge", name, "`judge_may_skip` is declared on a gate with no judge")
432
+ for pattern in g.judge_may_skip:
433
+ if pattern.startswith(("/", "\\")) or re.match(r"^[A-Za-z]:", pattern):
434
+ self.err("judge-may-skip-absolute", name, f"`judge_may_skip` pattern {pattern!r} is absolute")
435
+ continue
436
+ depth = 0
437
+ for part in pattern.replace("\\", "/").split("/"):
438
+ if part == "..":
439
+ depth -= 1
440
+ if depth < 0:
441
+ self.err("judge-may-skip-outside-repository", name,
442
+ f"`judge_may_skip` pattern {pattern!r} leaves the repository")
443
+ break
444
+ elif part not in ("", "."):
445
+ depth += 1
446
+
447
+ def _routing(self) -> None:
448
+ if not self.spec.routing.description.strip():
449
+ self.err("routing-description-missing", None, "routing metadata needs a one-line description")
450
+
451
+ # -- units ----------------------------------------------------------------------------------
452
+ def _unit(self, name: str, u: UnitSpec) -> None:
453
+ if name in RESERVED_KEYS:
454
+ self.err("reserved-key", name, f"unit name {name!r} is a reserved template key")
455
+ g = u.gate
456
+ for label, n in (("retry_budget", g.retry_budget), ("loop_budget", g.loop_budget)):
457
+ if not isinstance(n, int) or n < 0:
458
+ self.err("budget-invalid", name, f"`{label}` must be an integer ≥ 0")
459
+ if not isinstance(g.check_timeout_s, int) or g.check_timeout_s <= 0:
460
+ self.err("timeout-invalid", name, "`check_timeout_s` must be a positive integer")
461
+ if g.check is not None:
462
+ self._callable(name, g.check, "check")
463
+ self._may_skip(name, g)
464
+ self._back(name, g)
465
+ self._fallback(name, u)
466
+ if u.kind not in ("ask", "wait"):
467
+ for label, d in (("ask", u.ask), ("wait", u.wait)):
468
+ if d is not None:
469
+ self.err("deadline-misplaced", name, f"`{label}` fields, deadlines included, go on a "
470
+ f"`{label}` unit, not a `{u.kind}`")
471
+ if u.council is not None and u.kind == "map": # CNL-B16: a map item runs one session, never a council
472
+ self.err("council-in-map-item", name, f"{name!r} is a map whose item would be a council")
473
+ elif u.council is not None and u.kind != "council":
474
+ self.err("council-misplaced", name, f"`council` fields go on a `council` unit, not a `{u.kind}`")
475
+ mechanical = [c for c in g.criteria if c.mechanical]
476
+ if mechanical and g.check is None:
477
+ self.err("mechanical-without-check", name, "a `mechanical` criterion needs a gate check")
478
+ if u.kind == "step":
479
+ self._step(name, u)
480
+ elif u.kind == "map":
481
+ self._step(name, u)
482
+ self._map(name, u)
483
+ if u.contest is not None:
484
+ self._contest(name, u)
485
+ elif u.kind == "contest":
486
+ self._step(name, u)
487
+ self._contest(name, u)
488
+ elif u.kind == "script":
489
+ self._script_unit(name, u)
490
+ elif u.kind == "parallel":
491
+ self._parallel(name, u)
492
+ elif u.kind == "subworkflow":
493
+ self._subworkflow(name, u)
494
+ elif u.kind == "council":
495
+ self._council(name, u)
496
+ elif u.kind == "ask":
497
+ self._ask(name, u)
498
+ elif u.kind == "wait":
499
+ self._wait(name, u)
500
+ elif u.kind == "route":
501
+ if u.route is None or not u.route_targets:
502
+ self.err("route-invalid", name, "a route unit needs a select function and targets")
503
+ elif u.kind == "switch":
504
+ sw = u.switch
505
+ if sw is None or not sw.arms or sw.default not in sw.arms:
506
+ self.err("switch-invalid", name, "a switch needs arms and a default arm among them")
507
+ else:
508
+ self._measured_switch(name, sw)
509
+ if u.route is not None:
510
+ self._callable(name, u.route, "route")
511
+ if u.switch is not None and u.switch.complexity is not None:
512
+ self._complexity(name, u.switch)
513
+ elif u.switch is not None and u.switch.predicate is None:
514
+ self.err("switch-invalid", name, "a switch needs a predicate")
515
+ elif u.switch is not None:
516
+ self._callable(name, u.switch.predicate, "switch predicate") # type: ignore[arg-type]
517
+ for c in g.criteria:
518
+ if c.severity not in ("blocker", "warning"):
519
+ self.err("criterion-invalid", name, f"criterion severity {c.severity!r}")
520
+ if not c.check_method.strip():
521
+ self.warn("criterion-no-check-method", name, f"criterion {c.id or c.text[:30]!r} has no check method")
522
+
523
+ def _map(self, name: str, u: UnitSpec) -> None:
524
+ """MAP-B11 and the limits of MAP-B7: the mode, `concurrency` of a concurrent map, and a concurrent map whose
525
+ step writes in a workflow that has no worktrees."""
526
+ m = u.map
527
+ s = self.spec
528
+ if m is None:
529
+ self.err("map-invalid", name, "a map unit needs its map fields")
530
+ return
531
+ if m.mode not in ("sequential", "concurrent"):
532
+ self.err("map-invalid", name, f"map mode {m.mode!r} is not sequential or concurrent")
533
+ elif m.mode == "concurrent":
534
+ if isinstance(m.concurrency, bool) or not isinstance(m.concurrency, int) or not 1 <= m.concurrency <= 10:
535
+ self.err("map-invalid", name, "`concurrency` must be an integer from 1 to 10")
536
+ if flow.writer_map(s, name) and s.workspace == "in_place": # MAP-B11, WFM-B8, WSP-B11
537
+ self.err("map-writer-in-place", name, f"{name!r} is a concurrent map whose step declares `write` or "
538
+ "`edit`, which needs a worktree for each item; a workflow that declares `workspace: "
539
+ "in_place` has none (WSP-B11)")
540
+ if m.on_empty not in ("one_item", "stop", "skip"):
541
+ self.err("map-invalid", name, f"on_empty {m.on_empty!r} is not one_item, stop or skip")
542
+ if isinstance(m.max_items, bool) or not isinstance(m.max_items, int) or not 1 <= m.max_items <= 50:
543
+ self.err("map-invalid", name, "`max_items` must be an integer from 1 to 50")
544
+ if u.gate.on_fail == "back":
545
+ self.err("back-on-map", name, "a map's gate takes no `on_fail: back` (MAP-B11)")
546
+ if u.gate.back_targets:
547
+ self.err("map-back-target", name, "a map's gate takes no back targets: a defect across items is found "
548
+ "at the join (MAP-B11)")
549
+ if u.route is not None or u.switch is not None:
550
+ self.err("map-invalid", name, "a map takes no route")
551
+ src, key = m.items_from
552
+ order = list(s.order)
553
+ if src not in s.units or src not in order or name not in order or order.index(src) >= order.index(name):
554
+ self.err("map-items-unknown", name, f"items_from names {src!r}, which does not precede the map")
555
+ elif key not in _produced(s.units[src]):
556
+ self.err("map-items-unknown", name, f"{src!r} produces no {key!r}")
557
+ elif key not in self._earlier_keys(name)["all"]:
558
+ self.err("map-items-unknown", name, f"{key!r} is not produced on every path into the map")
559
+ for ref, what in ((m.extract, "map extract"), (m.item_model, "map item_model")):
560
+ if ref is not None:
561
+ self._callable(name, ref, what)
562
+ if m.item_model is not None and not 1 <= len(m.models) <= 8:
563
+ self.err("map-invalid", name, "`item_model` needs one to eight declared `models`")
564
+ caps = self.executors.get((u.step.executor if u.step else None) or s.default_executor)
565
+ if caps is not None:
566
+ for alias in m.models:
567
+ self._alias(name, alias, caps)
568
+
569
+ def _contest(self, name: str, u: UnitSpec) -> None:
570
+ """CTS-B6, CTS-B10: the refusals of one contest, each with a finding code of its own, and the one warning."""
571
+ c = u.contest
572
+ s = self.spec
573
+ if c is None:
574
+ self.err("contest-invalid", name, "a contest unit needs its contest fields")
575
+ return
576
+ slots = c.slots
577
+ if isinstance(slots, bool) or not isinstance(slots, (int, tuple, list)):
578
+ self.err("contest-slot-count", name, "`slots` is a count from 2 to 5 or a list of slots")
579
+ return
580
+ count = slots if isinstance(slots, int) else len(slots)
581
+ if not 2 <= count <= 5:
582
+ self.err("contest-slot-count", name, f"a contest has 2 to 5 slots, not {count}")
583
+ if not isinstance(slots, int):
584
+ names = [sl.name for sl in slots]
585
+ if len(set(names)) != len(names):
586
+ self.err("contest-slot-duplicate", name, "two slots of a contest share one name")
587
+ for sl in slots:
588
+ if not SLUG_RE.match(sl.name):
589
+ self.err("contest-slot-name", name, f"slot name {sl.name!r} is not a slug")
590
+ if isinstance(c.concurrency, bool) or not isinstance(c.concurrency, int) or not 1 <= c.concurrency <= 5:
591
+ self.err("contest-concurrency", name, "`concurrency` must be an integer from 1 to 5")
592
+ if c.cost_cap_usd is not None and (isinstance(c.cost_cap_usd, bool) or not isinstance(c.cost_cap_usd, (int, float))
593
+ or not c.cost_cap_usd > 0):
594
+ self.err("contest-cost-cap", name, "`cost_cap_usd` must be a number above 0")
595
+ if c.retry_scope not in ("best", "all"):
596
+ self.err("contest-retry-scope", name, f"`retry_scope` is `best` or `all`, not {c.retry_scope!r}")
597
+ if c.writes and s.workspace == "in_place": # WSP-B11, WFM-B8: a writer slot needs a worktree of its own
598
+ self.err("contest-writer-in-place", name, f"{name!r} is a contest of `writes: true`, which needs a worktree "
599
+ "for each slot; a workflow that declares `workspace: in_place` has none (WSP-B11)")
600
+ if flow.in_map_item(s, name):
601
+ self.err("contest-in-map-item", name, f"{name!r} is a contest inside a map item, which a contest cannot be")
602
+ if c.writes and u.map is not None and u.map.mode == "sequential":
603
+ self.err("contest-writer-sequential-map", name,
604
+ f"{name!r} writes inside a sequential map, which has no worktree for a slot")
605
+ if flow.in_branch(s, name):
606
+ self.err("contest-in-branch", name, f"{name!r} is a contest and a branch of a parallel block")
607
+ if u.gate.judge is None:
608
+ self.err("contest-judge-missing", name, "a contest picks by its gate's judge: the gate needs a judge")
609
+ if u.route is not None or u.switch is not None:
610
+ self.err("contest-invalid", name, "a contest takes no route")
611
+ if identical_slots(s, name):
612
+ self.warn("contest-identical-slots", name, f"every slot of {name!r} shares executor, model and prompt: "
613
+ "vary model, executor or `prompt_variant`")
614
+
615
+ def _measured_switch(self, name: str, sw: SwitchSpec) -> None:
616
+ """SWM-B4, SWM-B5: the mode, every arm override and every re-arm entry."""
617
+ s = self.spec
618
+ order = list(s.order)
619
+ if sw.mode not in ("route", "shadow"):
620
+ self.err("switch-invalid", name, f"switch mode {sw.mode!r} is not route or shadow")
621
+ if any(t != flow.FINALIZER and t not in s.units for t in sw.arms.values()):
622
+ return # reported as target-unknown by the flow pass
623
+ for arm, units in sw.arm_overrides.items():
624
+ if arm not in sw.arms:
625
+ self.err("switch-arm-unknown", name, f"arm_overrides names arm {arm!r}, which the switch lacks")
626
+ continue
627
+ reach = flow.arm_units(s, sw.arms[arm])
628
+ for unit, values in units.items():
629
+ target = s.units.get(unit)
630
+ if unit not in reach or target is None or target.step is None:
631
+ self.err("switch-override-unreachable", name,
632
+ f"arm {arm!r} overrides {unit!r}, which is not a step on that arm's path")
633
+ continue
634
+ for key, value in values.items():
635
+ self._override_value(name, arm, unit, target, key, value)
636
+ for r in sw.rearm:
637
+ if r.from_arm not in sw.arms or r.to not in sw.arms:
638
+ self.err("switch-arm-unknown", name, f"rearm names an arm the switch lacks ({r.from_arm} -> {r.to})")
639
+ continue
640
+ entry = sw.arms[r.to]
641
+ if not r.units or not r.on or any(c not in REARM_CAUSES for c in r.on):
642
+ self.err("switch-rearm-invalid", name, f"rearm needs units and causes among {list(REARM_CAUSES)}")
643
+ if r.from_arm == r.to or entry == flow.FINALIZER:
644
+ self.err("switch-rearm-invalid", name, "rearm needs two different arms and a unit as the entry of `to`")
645
+ continue
646
+ for unit in r.units:
647
+ if unit not in order or unit not in flow.arm_units(s, sw.arms[r.from_arm]):
648
+ self.err("switch-rearm-invalid", name, f"rearm unit {unit!r} is not on the path of arm {r.from_arm!r}")
649
+ elif order.index(entry) >= order.index(unit):
650
+ self.err("switch-rearm-invalid", name,
651
+ f"the entry of arm {r.to!r} ({entry}) does not precede {unit!r}")
652
+
653
+ def _ladder(self, name: str, st: StepSpec, caps: Capabilities | None, executor: str) -> None:
654
+ """LAD-B9, LAD-B14: the shape of an effort ladder and whether the executor applies each rung."""
655
+ from tempergraph.run.ladder import ascending
656
+
657
+ rungs = tuple(st.effort_ladder)
658
+ esc = st.escalation
659
+ if esc is not None: # LAD-B9: one tier above a plain tier alias, never from `large`, `inherit` or an item
660
+ from tempergraph.run.ladder import MODES, TIER_UP, stages_ok
661
+
662
+ model = st.model if isinstance(st.model, str) else None
663
+ m = self.spec.units[name].map
664
+ if model not in TIER_UP or TIER_UP[model] != esc.to or (m is not None and m.item_model is not None):
665
+ self.err("escalation-invalid", name,
666
+ f"`escalation.to` must be exactly one tier above a `small` or `medium` step ({model!r} -> {esc.to!r})")
667
+ elif caps is not None:
668
+ self._alias(name, esc.to, caps)
669
+ if not stages_ok(esc) or (esc.effort is not None and esc.effort not in EFFORTS):
670
+ self.err("escalation-invalid", name, f"`escalation` takes stages {list(STAGES)} as {list(MODES)} and an effort")
671
+ if dict(esc.stages).get("pipeline") == "offer":
672
+ self.err("escalation-invalid", name, "a pipeline never waits on an offer: use `off` or `auto`")
673
+ if not rungs:
674
+ return
675
+ if not 2 <= len(rungs) <= 4 or not ascending(rungs):
676
+ self.err("ladder-invalid", name, f"`effort_ladder` holds 2 to 4 efforts of {list(EFFORTS)}, strictly ascending")
677
+ return
678
+ pinned = "effort" in (self.spec.units[name].extra.get("operator_set") or ()) # an operator's pin is no field
679
+ if st.session_options is not None and st.session_options.effort is not None and not pinned:
680
+ self.err("ladder-invalid", name, "`effort_ladder` excludes a fixed `effort`")
681
+ if caps is None:
682
+ return
683
+ for rung in rungs:
684
+ if "effort" not in caps.session_options or rung not in caps.efforts:
685
+ self.err("effort-rung-unsupported", name,
686
+ f"step {name!r}: executor {executor!r} cannot apply effort {rung!r}; a climb would be silent")
687
+ elif rung in caps.efforts_uncertain:
688
+ self.warn("effort-rung-uncertain", name,
689
+ f"step {name!r}: effort {rung!r} on {executor!r} is not yet shown by a live probe")
690
+
691
+ def _complexity(self, name: str, sw: SwitchSpec) -> None:
692
+ """CXR-B7, CXR-B4, CXR-B10: the declaration, the rules file, the direction of re-arms and the arm contract."""
693
+ from tempergraph.run import complexity as cx
694
+
695
+ s = self.spec
696
+ comp = sw.complexity
697
+ assert comp is not None
698
+ arms = list(sw.arms)
699
+ if sw.predicate is not None:
700
+ self.err("complexity-predicate", name, "a complexity switch takes no predicate; the engine reads the rules")
701
+ names = [m.name for m in comp.measures]
702
+ if not 2 <= len(arms) <= 3 or sw.default != (arms[-1] if arms else None) or sw.sticky != "run":
703
+ self.err("complexity-invalid", name,
704
+ "a complexity switch has 2 or 3 arms, the last one as its default, and is sticky for the run")
705
+ if not names or len(set(names)) != len(names) or any(not SLUG_RE.match(n) for n in names):
706
+ self.err("complexity-invalid", name, "measures need unique slug names, at least one")
707
+ for m in comp.measures:
708
+ if m.call is not None:
709
+ self._callable(name, m.call, f"measure {m.name}")
710
+ elif not m.stock or cx.STOCK_ARITY.get(m.stock[0]) != len(m.stock) - 1:
711
+ self.err("complexity-invalid", name, f"measure {m.name!r} is not a stock measure with its arguments")
712
+ elif m.stock[0] in ("fact", "count_items", "count_lines") and m.stock[1] not in s.units:
713
+ self.err("complexity-invalid", name, f"measure {m.name!r} names unknown unit {m.stock[1]!r}")
714
+ if comp.size is not None and comp.size not in names:
715
+ self.err("complexity-invalid", name, f"`size` names {comp.size!r}, which is not a measure")
716
+ ex = comp.explore
717
+ if ex is not None:
718
+ rate, per_week = cx._num(ex.get("rate")), cx._num(ex.get("per_week"))
719
+ if rate is None or per_week is None or not 0 < rate <= cx.EXPLORE_MAX_RATE \
720
+ or not 0 < per_week <= cx.EXPLORE_MAX_PER_WEEK or set(ex) - {"rate", "per_week"}:
721
+ self.err("complexity-explore", name,
722
+ f"explore takes rate up to {cx.EXPLORE_MAX_RATE} and per_week up to {cx.EXPLORE_MAX_PER_WEEK}")
723
+ for r in sw.rearm:
724
+ if r.from_arm in arms and r.to in arms and arms.index(r.to) <= arms.index(r.from_arm):
725
+ self.err("complexity-rearm", name, f"rearm {r.from_arm} -> {r.to} goes toward a simpler arm")
726
+ if s.package_root is not None and len(set(names)) == len(names):
727
+ loaded = cx.load_rules(s, name, None)
728
+ if loaded["error"]:
729
+ self.err("complexity-rules", name, f"rules file: {loaded['error']}")
730
+ if any(t != flow.FINALIZER and t not in s.units for t in sw.arms.values()):
731
+ return # reported as target-unknown by the flow pass
732
+ join = comp.joins_at
733
+ if join not in s.units or join in sw.arms.values():
734
+ self.err("complexity-joins", name, f"`joins_at` {join!r} is not a unit after every arm's entry")
735
+ return
736
+ after = flow.arm_units(s, join)
737
+ paths: dict[str, set[str]] = {}
738
+ for arm, entry in sw.arms.items():
739
+ reach = flow.arm_units(s, entry) if entry != flow.FINALIZER else set()
740
+ if join not in reach:
741
+ self.err("complexity-joins", name, f"arm {arm!r} does not reach `joins_at` {join!r}")
742
+ return
743
+ paths[arm] = reach - after
744
+ if flow.OUTCOME_UNIT in paths[arm]:
745
+ self.err("complexity-joins", name, f"arm {arm!r} holds the final outcome gate")
746
+ if any(s.units[u].switch is not None and s.units[u].switch.complexity is not None # type: ignore[union-attr]
747
+ for u in paths[arm]):
748
+ self.err("complexity-invalid", name, f"arm {arm!r} holds another complexity switch")
749
+ made = {arm: set().union(*[_produced(s.units[u]) for u in units]) for arm, units in paths.items()}
750
+ on_arms = set().union(*made.values())
751
+ for reader in [u for u in s.order if u in after]:
752
+ for key in sorted(self._reads(reader) & on_arms):
753
+ for arm in arms:
754
+ if key not in made[arm]:
755
+ self.err("arm-contract", name,
756
+ f"arm {arm!r} does not produce {key!r}, which {reader!r} reads after `joins_at`")
757
+
758
+ def _reads(self, unit: str) -> set[str]:
759
+ """Artifact keys a unit's prompt, judge references and map list name."""
760
+ u = self.spec.units[unit]
761
+ keys: set[str] = set()
762
+ if u.step is not None:
763
+ with contextlib.suppress(TextUnreadable, TemplateError):
764
+ keys |= set(fields(load_text(self.spec, u.step.prompt)))
765
+ if u.gate.judge is not None:
766
+ keys |= set(u.gate.judge.references)
767
+ if u.map is not None:
768
+ keys.add(u.map.items_from[1])
769
+ return keys
770
+
771
+ def _override_value(self, name: str, arm: str, unit: str, target: UnitSpec, key: str, value: object) -> None:
772
+ where = f"arm_overrides.{arm}.{unit}.{key}"
773
+ if key not in ARM_OVERRIDE_KEYS:
774
+ self.err("switch-override-invalid", name, f"{where}: an arm overrides only {', '.join(ARM_OVERRIDE_KEYS)}")
775
+ elif key == "model":
776
+ st = target.step
777
+ caps = self.executors.get((st.executor if st else None) or self.spec.default_executor)
778
+ aliases = [value] if isinstance(value, str) else list(value) if isinstance(value, (list, tuple)) else []
779
+ if not aliases or not all(isinstance(a, str) for a in aliases):
780
+ self.err("switch-override-invalid", name, f"{where}: not a model alias")
781
+ elif caps is not None:
782
+ for a in aliases:
783
+ self._alias(name, str(a), caps)
784
+ elif key in ("timeout_s", "idle_s"):
785
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
786
+ self.err("switch-override-invalid", name, f"{where} must be a positive integer")
787
+ elif key == "effort" and value not in EFFORTS:
788
+ self.err("switch-override-invalid", name, f"{where}: {value!r} is not one of {', '.join(EFFORTS)}")
789
+
790
+ def _step(self, name: str, u: UnitSpec) -> None:
791
+ s = self.spec
792
+ st = u.step
793
+ if st is None:
794
+ self.err("step-missing", name, "a step unit needs its step fields")
795
+ return
796
+ g = u.gate
797
+ if g.judge is None and u.kind != "contest": # a contest refuses it with its own code (CTS-B10)
798
+ self.err("judge-missing", name, "a model step's gate needs a judge")
799
+ if not g.criteria:
800
+ self.err("criteria-missing", name, "a judged gate needs at least one criterion")
801
+ executor = st.executor or s.default_executor
802
+ caps = self.executors.get(executor)
803
+ if caps is None:
804
+ self.err("executor-unknown", name, f"unknown executor {executor!r}")
805
+ else:
806
+ for alias in _aliases(st.model)[:1] + _aliases(s.model_profile.get(name))[:1]:
807
+ self._alias(name, alias, caps)
808
+ for tool in st.tools:
809
+ if not is_capability(tool):
810
+ self.err("tool-unknown", name, f"{tool!r} is not a tool capability")
811
+ elif not caps.maps(tool):
812
+ self.err("tool-unmapped", name, f"executor {executor!r} maps no tool for {tool!r}")
813
+ if st.session_options is not None:
814
+ for opt in st.session_options.set_names():
815
+ if opt not in caps.session_options:
816
+ if opt == "effort":
817
+ self.warn("effort-unsupported", name, f"{executor!r} cannot apply `effort`")
818
+ else:
819
+ self.err("option-unsupported", name, f"{executor!r} does not support {opt!r}")
820
+ self._ladder(name, st, caps, executor)
821
+ from tempergraph.model import retire
822
+
823
+ for where, got in retire.detect(s).items(): # LAD-B14: a release 1 model list, with its rewrite (LAD-B18)
824
+ if where in (f"units.{name}.model", f"model_profile.{name}"):
825
+ self.err("model-ladder-retired", name,
826
+ f"`{where}` is a list of models, retired in release 2; write {retire.describe(got)}")
827
+ for label, val in (("timeout_s", st.timeout_s), ("idle_s", st.idle_s)):
828
+ if val is not None and (not isinstance(val, int) or val <= 0):
829
+ self.err("timeout-invalid", name, f"`{label}` must be a positive integer")
830
+ self._commands(name, st.commands, "shell" in st.tools)
831
+ for tool in st.tools:
832
+ if tool.startswith("skill:"):
833
+ self._skill(name, tool)
834
+ self._produces(name, st.produces)
835
+ self._judge(name, u, executor)
836
+ self._template(name, st.prompt)
837
+ for sc in st.before + st.after:
838
+ self._script(name, sc, hybrid="before" if sc in st.before else "after")
839
+ if g.approval is False and any(sc.side_effects == "external" for sc in st.after):
840
+ self.warn("external-after-without-approval", name, "an `after` script with external side effects on a gate with no approval")
841
+
842
+ def _alias(self, unit: str, alias: str, caps: Capabilities) -> None:
843
+ if ":" in alias:
844
+ ex, _ = alias.split(":", 1)
845
+ if ex != caps.name:
846
+ self.err("alias-unbound", unit, f"alias {alias!r} is qualified for another executor")
847
+ else:
848
+ self.warn("alias-qualified", unit, f"executor-qualified alias {alias!r} where a tier would do")
849
+ elif alias not in caps.binds_aliases:
850
+ self.err("alias-unbound", unit, f"{caps.name!r} binds no alias {alias!r}")
851
+
852
+ def _commands(self, unit: str, commands: tuple[str, ...], has_shell: bool) -> None:
853
+ allow = self.spec.allow_commands
854
+ for cmd in commands:
855
+ if has_shell_metacharacter(cmd):
856
+ self.err("command-metacharacter", unit, f"command {cmd!r} holds a shell metacharacter")
857
+ elif not any(cmd == a or cmd.startswith(a + " ") for a in allow):
858
+ self.err("command-not-allowed", unit, f"command {cmd!r} is outside the workflow allow-list")
859
+ if not has_shell:
860
+ self.err("command-without-shell", unit, f"command {cmd!r} on a step that does not declare `shell`")
861
+
862
+ def _skill(self, unit: str, tool: str) -> None:
863
+ _, plugin, skill = tool.split(":", 2)
864
+ root = self.spec.package_root
865
+ if root is None or not (root / "skills" / skill / "SKILL.md").exists():
866
+ self.err("skill-not-installed", unit, f"{tool!r}: skills/{skill}/SKILL.md is not in the package")
867
+
868
+ def _produces(self, unit: str, produces: Mapping[str, object]) -> None:
869
+ for key, kind in produces.items():
870
+ if key in RESERVED_KEYS:
871
+ self.err("reserved-key", unit, f"artifact key {key!r} is a reserved template key")
872
+ if isinstance(kind, ValueKind):
873
+ if kind.choices is not None and kind.pattern is not None:
874
+ self.err("value-choices-and-pattern", unit, f"value {key!r} sets both `choices` and `pattern`")
875
+ if kind.pattern is not None:
876
+ try:
877
+ re.compile(kind.pattern)
878
+ except re.error:
879
+ self.err("value-pattern-invalid", unit, f"value {key!r} has an invalid pattern")
880
+ elif kind not in ("file", "url", "wiki_page", "tracker_issue", "pull_request", "value"):
881
+ self.err("artifact-kind-unknown", unit, f"artifact {key!r} has unknown kind {kind!r}")
882
+
883
+ def _judge(self, unit: str, u: UnitSpec, step_executor: str) -> None:
884
+ g = u.gate
885
+ j = g.judge
886
+ if j is None:
887
+ return
888
+ if j.tools is not None:
889
+ for t in j.tools:
890
+ if t not in READ_ONLY_CAPABILITIES:
891
+ self.err("judge-tool-not-read-only", unit, f"judge tool {t!r} is outside the read-only catalog")
892
+ judge_ex = j.executor or step_executor
893
+ caps = self.executors.get(judge_ex)
894
+ # The judge moves to a capable executor at preflight (EXI-B24); refuse only when none exists.
895
+ if caps is not None and not caps.restricts_judge_tools and not any(
896
+ c.restricts_judge_tools for c in self.executors.values()
897
+ ):
898
+ self.err("judge-executor-unrestricted", unit, "no registered executor can restrict judge tools")
899
+ if j.model:
900
+ target = caps or self.executors.get("claude")
901
+ if target is not None:
902
+ self._alias(unit, j.model, target)
903
+ if j.risk is not None: # JRK-B6, JRK-B7, JRK-B2
904
+ from tempergraph.run import risk as riskmod
905
+
906
+ base = j.model or (u.step.model if u.step is not None and isinstance(u.step.model, str) else None)
907
+ opts = j.session_options
908
+ for problem in riskmod.problems(j.risk, base, opts.effort if opts else None):
909
+ self.err("risk-invalid", unit, f"judge `risk`: {problem}")
910
+ target = caps or self.executors.get("claude")
911
+ for lv in j.risk.levels[1:]:
912
+ if lv.model and target is not None:
913
+ self._alias(unit, lv.model, target)
914
+ if j.risk.rule is not None:
915
+ self._callable(unit, j.risk.rule, "risk rule")
916
+ produces: Mapping[str, Any] = u.step.produces if u.step else (
917
+ {k: "value" for k in COUNCIL_ARTIFACTS} if u.kind == "council" else {})
918
+ subject = j.subject or (("decision",) if u.kind == "council" else tuple(produces)) # CNL-B4
919
+ unverified = any(c.unverified_system for c in g.criteria)
920
+ judge_caps = caps if (caps is not None and caps.restricts_judge_tools) else self.executors.get("claude")
921
+ for key in subject:
922
+ kind = produces.get(key)
923
+ if isinstance(kind, ValueKind) or kind is None:
924
+ continue
925
+ if kind not in READ_VIEW_KINDS and not (judge_caps and judge_caps.judge_mcp) and not unverified:
926
+ self.err("judge-view-unavailable", unit,
927
+ f"the judge cannot read artifact {key!r} of kind {kind!r}; mark the system unverified")
928
+ earlier = self._earlier_keys(unit)
929
+ for ref, need in j.references.items():
930
+ if ref in ("request",) or ref in input_names(self.spec):
931
+ continue
932
+ if ref not in earlier["any"] and ref not in produces:
933
+ self.err("reference-unknown", unit, f"judge reference {ref!r} is produced by no earlier unit")
934
+ elif need == "required" and ref not in earlier["all"] and ref not in produces:
935
+ self.err("reference-not-on-every-path", unit,
936
+ f"required judge reference {ref!r} is not produced on every path into {unit!r}")
937
+
938
+ def _template(self, unit: str, source: object) -> None:
939
+ try:
940
+ text = load_text(self.spec, source) # type: ignore[arg-type]
941
+ except TextUnreadable as exc:
942
+ self.err("template-unreadable", unit, str(exc))
943
+ return
944
+ try:
945
+ names = fields(text)
946
+ except TemplateError as exc:
947
+ self.err("template-invalid", unit, str(exc))
948
+ return
949
+ inputs = input_names(self.spec)
950
+ earlier = self._earlier_keys(unit)
951
+ for f in names:
952
+ if f in ENGINE_KEYS or f in inputs:
953
+ continue
954
+ if f in ITEM_KEYS and self.spec.units[unit].kind == "map":
955
+ continue
956
+ if f.startswith("settings."):
957
+ if f[len("settings."):] not in self.spec.settings:
958
+ self.err("template-unknown-field", unit, f"field {{{f}}} names no declared setting")
959
+ continue
960
+ if "." in f: # `<unit>.<key>` (CON-B8, SWF-B12)
961
+ owner, key = f.split(".", 1)
962
+ if not self._exposed(unit, owner, key):
963
+ self.err("template-unknown-field", unit,
964
+ f"field {{{f}}} is not a key an earlier sub-workflow unit {owner!r} exposes")
965
+ continue
966
+ if f in earlier["any"]:
967
+ if f not in earlier["all"]:
968
+ self.warn("template-key-not-on-every-path", unit, f"field {{{f}}} is not produced on every path")
969
+ continue
970
+ self.err("template-unknown-field", unit, f"field {{{f}}} is neither an engine key, an input nor an earlier artifact")
971
+
972
+ def _earlier_keys(self, unit: str) -> dict[str, set[str]]:
973
+ """Artifact keys produced before ``unit``: on any path, and on every path from the start."""
974
+ s = self.spec
975
+ order = list(s.order)
976
+ if unit not in order:
977
+ return {"any": set(), "all": set()}
978
+ idx = order.index(unit)
979
+ any_keys: set[str] = set()
980
+ for name in order[:idx]:
981
+ any_keys |= _produced(s.units[name])
982
+ # every path: keys of units that dominate `unit` (all paths from the first unit pass them)
983
+ all_keys: set[str] = set()
984
+ for name in order[:idx]:
985
+ if _dominates(s, name, unit):
986
+ all_keys |= _produced(s.units[name])
987
+ return {"any": any_keys, "all": all_keys}
988
+
989
+ def _script_unit(self, name: str, u: UnitSpec) -> None:
990
+ if u.script is None:
991
+ self.err("script-missing", name, "a script unit needs its script fields")
992
+ return
993
+ self._script(name, u.script, hybrid=None)
994
+ if u.gate.judge is not None and not any(
995
+ k in READ_VIEW_KINDS or isinstance(k, ValueKind) for k in u.script.produces.values()
996
+ ):
997
+ self.err("script-judge-nothing-to-read", name, "a judged script unit must produce a readable artifact")
998
+
999
+ def _script(self, unit: str, sc: object, hybrid: str | None) -> None:
1000
+ from tempergraph.contracts import ScriptSpec
1001
+
1002
+ assert isinstance(sc, ScriptSpec)
1003
+ if (sc.run is None) == (sc.call is None):
1004
+ self.err("script-run-or-call", unit, "a script needs exactly one of `run` and `call`")
1005
+ if sc.run is not None:
1006
+ if not sc.run:
1007
+ self.err("script-run-or-call", unit, "an empty `run`")
1008
+ else:
1009
+ for part in sc.run:
1010
+ if part.startswith("{") and part.endswith("}") and "{" not in part[1:-1]:
1011
+ continue
1012
+ if has_shell_metacharacter(part):
1013
+ self.err("script-part-invalid", unit, f"script part {part!r} is neither a constant nor one field")
1014
+ prefix = sc.run[0]
1015
+ if not any(prefix == a or prefix == a.split(" ")[0] for a in self.spec.allow_commands):
1016
+ self.err("command-not-allowed", unit, f"script program {prefix!r} is outside the allow-list")
1017
+ if sc.call is not None:
1018
+ self._callable(unit, sc.call, "script")
1019
+ if sc.cache == "thread" and (sc.side_effects != "none" or not sc.inputs):
1020
+ self.err("script-cache-side-effects", unit, "a cached script must have no side effects and declare inputs")
1021
+ if hybrid == "before" and sc.side_effects == "external":
1022
+ self.err("script-before-external", unit, "a `before` script may not have external side effects")
1023
+ if not isinstance(sc.timeout_s, int) or sc.timeout_s <= 0:
1024
+ self.err("timeout-invalid", unit, "a script `timeout_s` must be a positive integer")
1025
+ self._produces(unit, sc.produces)
1026
+
1027
+ def _callable(self, unit: str, ref: CallableRef, what: str) -> None:
1028
+ if "<locals>" in ref.qualname or "<lambda>" in ref.qualname:
1029
+ self.err("callable-not-importable", unit, f"{what} {ref.ref} is not module-level")
1030
+ return
1031
+ try:
1032
+ ref.resolve()
1033
+ except Exception as exc: # noqa: BLE001 - any import failure is a finding
1034
+ self.err("callable-not-importable", unit, f"{what} {ref.ref}: {type(exc).__name__}")
1035
+
1036
+ # -- flow -----------------------------------------------------------------------------------
1037
+ def _flow(self) -> None:
1038
+ s = self.spec
1039
+ order = list(s.order)
1040
+ for name in order:
1041
+ u = s.units[name]
1042
+ idx = order.index(name)
1043
+ targets: list[str] = []
1044
+ if u.route is not None:
1045
+ targets = list(u.route_targets)
1046
+ if u.switch is not None:
1047
+ targets = list(u.switch.arms.values())
1048
+ if name in s.flow and s.flow[name].next:
1049
+ targets.append(s.flow[name].next or "")
1050
+ for t in targets:
1051
+ if t == flow.FINALIZER:
1052
+ continue
1053
+ if t not in order:
1054
+ self.err("target-unknown", name, f"target {t!r} is outside order")
1055
+ elif order.index(t) <= idx:
1056
+ self.err("target-not-forward", name, f"route target {t!r} is not a forward unit")
1057
+ for t in u.gate.back_targets:
1058
+ if t not in order:
1059
+ self.err("target-unknown", name, f"back target {t!r} is outside order")
1060
+ elif order.index(t) >= idx:
1061
+ self.err("back-target-not-earlier", name, f"back target {t!r} is not an earlier unit")
1062
+ if any(f.code.startswith("target-") or f.code == "back-target-not-earlier" for f in self.findings):
1063
+ return
1064
+ reach = flow.reachable_units(s)
1065
+ for name in order:
1066
+ if name not in reach:
1067
+ self.err("unreachable", name, f"unit {name!r} is unreachable")
1068
+ if not flow.finalizer_reachable(s):
1069
+ self.err("finalizer-unreachable", None, "no path reaches the finalizer")
1070
+
1071
+ def _finalizer(self) -> None:
1072
+ s = self.spec
1073
+ if s.finalizer is not None:
1074
+ self._callable(None, s.finalizer, "finalizer") # type: ignore[arg-type]
1075
+ if not s.finalizer_outcomes:
1076
+ self.err("finalizer-outcomes-missing", None, "a finalizer needs `finalizer_outcomes`")
1077
+ for o in s.finalizer_outcomes:
1078
+ if not SLUG_RE.match(o):
1079
+ self.err("finalizer-outcomes-invalid", None, f"finalizer outcome {o!r} is not a slug")
1080
+
1081
+
1082
+ def identical_slots(spec: WorkflowSpec, unit: str) -> bool:
1083
+ """CTS-B10, ARC-B15: every slot of the contest `unit` shares executor, model and prompt. The validation warning and
1084
+ the audit's `contest-identical-slots` both ask this one question; a slot count runs the base step unchanged."""
1085
+ u = spec.units.get(unit)
1086
+ if u is None or u.contest is None:
1087
+ return False
1088
+ slots = u.contest.slots
1089
+ if isinstance(slots, bool) or not isinstance(slots, (int, tuple, list)):
1090
+ return False
1091
+ if isinstance(slots, int):
1092
+ return slots >= 2
1093
+ if len(slots) < 2:
1094
+ return False
1095
+ return len({(sl.executor, sl.model, sl.prompt_variant) for sl in slots}) == 1
1096
+
1097
+
1098
+ def _aliases(model: str | tuple[str, ...] | None) -> list[str]:
1099
+ if model is None:
1100
+ return []
1101
+ if isinstance(model, str):
1102
+ return [model]
1103
+ return [m for m in model if isinstance(m, str)]
1104
+
1105
+
1106
+ def _produced(u: UnitSpec) -> set[str]:
1107
+ keys: set[str] = set()
1108
+ if u.step is not None:
1109
+ keys |= set(u.step.produces)
1110
+ for sc in u.step.before + u.step.after:
1111
+ keys |= set(sc.produces)
1112
+ if u.script is not None:
1113
+ keys |= set(u.script.produces)
1114
+ if u.kind == "ask":
1115
+ keys.add("answers") # ASK-B5, ASK-B6: the unit's one artifact
1116
+ if u.kind == "council":
1117
+ keys |= set(COUNCIL_ARTIFACTS) # CNL-B10
1118
+ return keys
1119
+
1120
+
1121
+ def _dominates(spec: WorkflowSpec, a: str, b: str) -> bool:
1122
+ """True when every forward path from the first unit to ``b`` passes ``a``."""
1123
+ order = list(spec.order)
1124
+ start = order[0]
1125
+ if a == start:
1126
+ return True
1127
+ join = flow.block_of(spec, a)
1128
+ if join is not None and join != b: # CMP-B10 to CMP-B16: a join runs only once every branch has passed
1129
+ return _dominates(spec, join, b)
1130
+ seen: set[str] = set()
1131
+ todo = [start]
1132
+ while todo:
1133
+ u = todo.pop()
1134
+ if u == b:
1135
+ return False
1136
+ if u in seen or u == a or u == flow.FINALIZER or u not in spec.units:
1137
+ continue
1138
+ seen.add(u)
1139
+ todo.extend(flow.proceed_targets(spec, u))
1140
+ return True
1141
+
1142
+
1143
+ def _setting_ok(kind: str, value: object, choices: tuple[str, ...] | None, lo: float | None, hi: float | None) -> bool:
1144
+ if kind == "bool":
1145
+ return isinstance(value, bool)
1146
+ if kind in ("int", "float"):
1147
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
1148
+ return False
1149
+ if kind == "int" and not isinstance(value, int):
1150
+ return False
1151
+ return (lo is None or value >= lo) and (hi is None or value <= hi)
1152
+ if kind == "choice":
1153
+ return choices is not None and value in choices
1154
+ return isinstance(value, str)
1155
+
1156
+
1157
+ def criteria_texts(criteria: tuple[Criterion, ...]) -> list[str]:
1158
+ return [c.text for c in criteria]