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,950 @@
1
+ """Run settings: one catalog over fixed layers, resolved the same way everywhere (RST-B16 to RST-B32; ADR `one-catalog-of-run-settings-over-fixed-layers`, 0071, 0072).
2
+
3
+ `resolve` and `validate_overrides` are pure and model-free. `run --check`, `run`, `resume` and `config show` call
4
+ them. The operator layers (flag, profile and both files) are snapshotted on the thread at start and reapplied on
5
+ resume (RST-B26); the workflow layers come from the content the thread runs.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import dataclasses
12
+ import difflib
13
+ import hashlib
14
+ import json
15
+ import re
16
+ from collections.abc import Callable, Iterable, Mapping, Sequence
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from tempergraph.contracts import (
21
+ GateSpec,
22
+ JudgeSpec,
23
+ ResolvedSettings,
24
+ RunOptions,
25
+ SessionOptions,
26
+ SettingDecl,
27
+ SettingRow,
28
+ StepSpec,
29
+ UnitSpec,
30
+ WorkflowSpec,
31
+ )
32
+ from tempergraph.model.validate import Finding
33
+ from tempergraph.security.launch import has_shell_metacharacter
34
+
35
+ SETTINGS_FILE = "settings.json"
36
+
37
+ # Rank order of RST-B22, RST-B23. The `arm:` layer sits below the first four: it is applied where a session request is
38
+ # built, for the keys no operator layer set (SWM-B6).
39
+ LAYERS = ("flag", "profile", "project:overrides", "user:overrides", "workflow:unit", "workflow:default",
40
+ "project:defaults", "user:defaults", "engine")
41
+ OPERATOR_LAYERS = ("flag", "profile", "project:overrides", "user:overrides", "project:defaults", "user:defaults")
42
+
43
+ SESSION_KINDS = ("step", "map", "contest") # unit kinds whose `step` runs model sessions (per item, per slot)
44
+ # What the `steps` scope sets for the member and chair sessions of a council (CNL-B9, BUD-B12): never a `<unit>.` key.
45
+ COUNCIL_STEP_KEYS = ("session_cost_cap_usd", "model", "executor")
46
+ SESSION = frozenset({"steps", "judges", "unit", "judge"})
47
+ STEP_SIDE = frozenset({"steps", "unit"})
48
+ JUDGE_SIDE = frozenset({"judges", "judge"})
49
+ SCRIPT = frozenset({"script"})
50
+ ALIAS = re.compile(r"^(inherit|small|medium|large|[a-z][a-z0-9-]*:[A-Za-z0-9._-]+)$")
51
+ SLUG = re.compile(r"^[a-z][a-z0-9_-]{0,63}$")
52
+ REF_PART = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$")
53
+
54
+ # Keys of the catalog whose feature is not in this release (ADR `first-release-is-simple-trusted-workflows-on-one-machine`, ADR `release-two-adds-upgrade-ladders-judge-risk-and-complexity-routing`): refused rather than silently ignored.
55
+ # None now: the keys of a unit kind that is built are in KIND_ONLY.
56
+ NOT_IN_RELEASE: dict[str, str] = {}
57
+ # Keys that only one kind of unit takes (RST-B19): refused on a unit of any other kind (`setting_not_for_kind`). A council
58
+ # adds its own kind to `attempt_cost_cap_usd` when it is built.
59
+ KIND_ONLY: dict[str, tuple[str, ...]] = {"attempt_cost_cap_usd": ("contest",), "concurrency": ("contest",)}
60
+ # Keys whose effect is not built yet on this branch, with the plan row that builds it.
61
+ NOT_BUILT: dict[str, str] = {}
62
+ WIDENING = frozenset({"tools.add", "commands.add", "views.add"}) # RST-B28, RST-B29, RST-B30, T6.3
63
+
64
+
65
+ class SettingError(ValueError):
66
+ def __init__(self, code: str, message: str) -> None:
67
+ super().__init__(message)
68
+ self.code = code
69
+
70
+
71
+ # ---------------------------------------------------------------------------------------------
72
+ # Values
73
+
74
+
75
+ def _int(lo: int, hi: int | None = None) -> Callable[[Any], int]:
76
+ def check(v: Any) -> int:
77
+ if isinstance(v, bool):
78
+ raise SettingError("setting_value", f"{v!r} is not a whole number")
79
+ try:
80
+ n = int(v) if not isinstance(v, float) or v.is_integer() else None
81
+ except (TypeError, ValueError):
82
+ n = None
83
+ if n is None or n < lo or (hi is not None and n > hi):
84
+ raise SettingError("setting_value", f"{v!r} is not a whole number from {lo}" + (f" to {hi}" if hi else ""))
85
+ return n
86
+ return check
87
+
88
+
89
+ def _float(lo: float, hi: float | None = None, *, open_lo: bool = True) -> Callable[[Any], float]:
90
+ def check(v: Any) -> float:
91
+ try:
92
+ x = float(v) if not isinstance(v, bool) else None
93
+ except (TypeError, ValueError):
94
+ x = None
95
+ if x is None or (x <= lo if open_lo else x < lo) or (hi is not None and x > hi):
96
+ raise SettingError("setting_value", f"{v!r} is not a number {'above' if open_lo else 'from'} {lo}"
97
+ + (f" to {hi}" if hi is not None else ""))
98
+ return x
99
+ return check
100
+
101
+
102
+ def _choice(*choices: str) -> Callable[[Any], str]:
103
+ def check(v: Any) -> str:
104
+ if v not in choices:
105
+ raise SettingError("setting_value", f"{v!r} is not one of {', '.join(choices)}")
106
+ return str(v)
107
+ return check
108
+
109
+
110
+ def _true(v: Any) -> bool:
111
+ if v is True or v == "true":
112
+ return True
113
+ raise SettingError("tighten_only", "this key can only be set to true (RST-B22, RST-B23)")
114
+
115
+
116
+ def _bool(v: Any) -> bool:
117
+ if v in (True, "true"):
118
+ return True
119
+ if v in (False, "false"):
120
+ return False
121
+ raise SettingError("setting_value", f"{v!r} is not true or false")
122
+
123
+
124
+ def _dry_run_value(v: Any) -> bool:
125
+ """LFS-B1: `loop_dry_run` takes `true` or `false` only; `1` and `0` are refused."""
126
+ if v is True or v == "true":
127
+ return True
128
+ if v is False or v == "false":
129
+ return False
130
+ raise SettingError("setting_value", f"{v!r} is not true or false")
131
+
132
+
133
+ def _alias(v: Any) -> str:
134
+ if not isinstance(v, str) or not ALIAS.match(v):
135
+ raise SettingError("setting_value", f"{v!r} is not a model alias (inherit, small, medium, large or "
136
+ "<executor>:<name>)")
137
+ return v
138
+
139
+
140
+ def _one_alias(v: Any) -> str:
141
+ """LAD-B14: `model` takes one alias; release 1's list is retired (LAD-B18)."""
142
+ if isinstance(v, (list, tuple)) or (isinstance(v, str) and "," in v):
143
+ raise SettingError("setting_value", "`model` takes one alias; a list of models is retired, declare an "
144
+ "`escalation` on the step instead")
145
+ return _alias(v)
146
+
147
+
148
+ def _slug(v: Any) -> str:
149
+ if not isinstance(v, str) or not SLUG.match(v):
150
+ raise SettingError("setting_value", f"{v!r} is not a name")
151
+ return v
152
+
153
+
154
+ def _prefix(v: Any) -> str:
155
+ parts = str(v).split("/")
156
+ if not 1 <= len(parts) <= 3 or not all(REF_PART.match(p) for p in parts) or ".." in str(v):
157
+ raise SettingError("setting_value", f"{v!r} is not 1 to 3 ref-safe components")
158
+ return str(v)
159
+
160
+
161
+ @dataclasses.dataclass(frozen=True)
162
+ class Entry:
163
+ scopes: frozenset[str]
164
+ check: Callable[[Any], Any]
165
+ default: Any = None
166
+ release1: Callable[[Any], None] | None = None # refuses a value whose feature is a later release
167
+
168
+
169
+ def _root(v: Any) -> None:
170
+ """WTR-B17: `sibling`, `in_repo` or `path:<absolute path>`."""
171
+ if v in ("sibling", "in_repo"):
172
+ return
173
+ if isinstance(v, str) and v.startswith("path:") and Path(v[5:]).is_absolute():
174
+ return
175
+ raise SettingError("setting_value", f"worktree.root {v!r} is not sibling, in_repo or path:<absolute path>")
176
+
177
+
178
+ def _base(v: Any) -> None:
179
+ """WTR-B17, WTR-B21: `head`, `default_branch` or `ref:<name>`."""
180
+ if v in ("head", "default_branch") or (isinstance(v, str) and v.startswith("ref:") and len(v) > 4):
181
+ return
182
+ raise SettingError("setting_value", f"worktree.base {v!r} is not head, default_branch or ref:<name>")
183
+
184
+
185
+ RUN = frozenset({"run"})
186
+ SCHEDULE_DEFAULTS: dict[str, bool] = {"loop_autostart": False}
187
+ """The `schedule` map of the user settings file (TCK-B14): machine-wide, never a run layer, off by default.
188
+ `loop_autostart` lets the plugin's `SessionStart` hook start `schedule loop --detach` when no loop runs."""
189
+ CATALOG: dict[str, Entry] = {
190
+ "executor": Entry(SESSION, _slug),
191
+ "model": Entry(SESSION, _one_alias, "inherit"),
192
+ "subagent_model": Entry(STEP_SIDE, _alias),
193
+ "effort": Entry(SESSION, _choice("low", "medium", "high", "xhigh", "max")),
194
+ "session_cost_cap_usd": Entry(SESSION, _float(0)),
195
+ "turn_cap": Entry(SESSION, _int(1, 500)),
196
+ "fallback_alias": Entry(STEP_SIDE, _alias),
197
+ "timeout_s": Entry(SESSION | SCRIPT, _int(1, 86_400), 600),
198
+ "idle_s": Entry(SESSION, _int(30, 86_400)),
199
+ "retry_budget": Entry(STEP_SIDE, _int(0, 10), 2),
200
+ "loop_budget": Entry(STEP_SIDE, _int(0, 5), 1),
201
+ "on_budget_spent": Entry(STEP_SIDE, _choice("stop", "ask", "fallback"), "ask"),
202
+ "approve": Entry(frozenset({"unit"}), _true),
203
+ "infra_tries": Entry(RUN, _int(0, 10), 3),
204
+ "command_killed_retries": Entry(RUN, _int(0, 10), 2),
205
+ "infra_backoff_max_s": Entry(RUN, _int(10, 300), 300),
206
+ "attempt_cap": Entry(RUN, _int(1, 100), 15),
207
+ "human_cap": Entry(RUN, _int(1, 100), 100),
208
+ "self_check_limit": Entry(RUN, _int(1, 10), 3), # check previews a step may run in one attempt (CHK-B17)
209
+ "run_cost_cap_usd": Entry(RUN, _float(0)),
210
+ "daily_cap_usd": Entry(RUN, _float(0)), # stable mode's self-improvement budget per day (SIL-B19, SIL-B20)
211
+ "loop_model": Entry(RUN, _alias, "medium"), # the alias of the loop's own sessions (SIL-B11)
212
+ # an operator's hold: lowers the loop's autonomy, read again at each final exit, no default (PRP-B31)
213
+ "loop_autonomy": Entry(RUN, _choice("record", "file", "propose", "trial")),
214
+ "loop_issue_cap": Entry(RUN, _int(0, 50), 3), # new loop issues per repository and UTC day (ICAP-B1)
215
+ "loop_effort": Entry(RUN, _choice("low", "medium", "high", "xhigh", "max"), "max"), # their effort (SIL-B17)
216
+ "auto_reopen": Entry(RUN, _int(0, 10), 0),
217
+ "workspace": Entry(RUN, _choice("auto", "in_place", "worktree"), "auto"),
218
+ "session_review": Entry(RUN, _choice("auto", "full", "signals", "off"), "auto"), # lowers only (SRV-B13, SRV-B14, SRV-B15)
219
+ "loop_dry_run": Entry(RUN, _dry_run_value, False), # the loop files nothing and writes `would_file` (LFS-B1)
220
+ "worktree.root": Entry(RUN, str, "sibling", _root),
221
+ "worktree.base": Entry(RUN, str, "head", _base),
222
+ "worktree.branch_prefix": Entry(RUN, _prefix, "tg"),
223
+ "worktree.cleanup": Entry(RUN, _choice("never", "on_finish"), "never"),
224
+ "worktree.read_worktreeinclude": Entry(RUN, _bool, True),
225
+ "enforce_tools": Entry(RUN, _true, False),
226
+ "strict_permissions": Entry(RUN, _true, False),
227
+ "audit_rate": Entry(RUN, _float(0, 1, open_lo=False), 0.0),
228
+ "audit_executor": Entry(RUN, _slug),
229
+ "arm": Entry(frozenset({"unit"}), str),
230
+ "attempt_cost_cap_usd": Entry(frozenset({"unit"}), _float(0)),
231
+ "concurrency": Entry(frozenset({"unit"}), _int(1, 5), 3),
232
+ "deadline_s": Entry(frozenset({"unit"}), _int(1)),
233
+ "tools.add": Entry(STEP_SIDE, lambda v: _caps(v, read_only=False)),
234
+ "commands.add": Entry(STEP_SIDE | SCRIPT, lambda v: _prefixes(v)),
235
+ "views.add": Entry(frozenset({"judge"}), lambda v: _caps(v, read_only=True)),
236
+ }
237
+ CAPABILITIES = frozenset({"read", "search", "list", "edit", "write", "shell", "web_fetch", "web_search", "subagent"})
238
+ READ_ONLY = frozenset({"read", "search", "list", "web_fetch", "web_search"})
239
+ MCP_CAP = re.compile(r"^mcp:[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
240
+ SKILL_CAP = re.compile(r"^skill:[a-z0-9][a-z0-9_-]*:[a-z0-9][a-z0-9_-]*$")
241
+
242
+
243
+ def _list(v: Any) -> list[str]:
244
+ if isinstance(v, str):
245
+ return [p.strip() for p in v.split(",") if p.strip()]
246
+ if isinstance(v, (list, tuple)) and all(isinstance(x, str) for x in v):
247
+ return [str(x) for x in v]
248
+ raise SettingError("setting_value", f"{v!r} is not a list")
249
+
250
+
251
+ def _caps(v: Any, *, read_only: bool) -> tuple[str, ...]:
252
+ """RST-B28, RST-B29, RST-B30 What and Never: a capability name; a judge view is read-only (RST-B13)."""
253
+ out = _list(v)
254
+ for c in out:
255
+ if not (c in CAPABILITIES or MCP_CAP.match(c) or SKILL_CAP.match(c)):
256
+ raise SettingError("unknown-capability", f"{c!r} is not a tool capability (CON-B11)")
257
+ if read_only and c.startswith("mcp:"):
258
+ raise SettingError("judge-view-unclassified", f"{c!r}: a judge sees an MCP tool only through the "
259
+ "engine's view catalog, as the read view of its step's tool; "
260
+ "a grant cannot add one")
261
+ if read_only and c not in READ_ONLY:
262
+ raise SettingError("judge-view-not-read-only", f"{c!r}: a judge takes read-only views only")
263
+ return tuple(out)
264
+
265
+
266
+ def _prefixes(v: Any) -> tuple[str, ...]:
267
+ out = _list(v) if not isinstance(v, str) else [v.strip()]
268
+ for c in out:
269
+ if not c or has_shell_metacharacter(c):
270
+ raise SettingError("command-metacharacter", f"command {c!r} holds a shell metacharacter")
271
+ return tuple(out)
272
+
273
+
274
+ # Fields of a unit that verify the work: never a setting (ADR `overrides-never-change-what-verifies-the-work`).
275
+ VERIFICATION = frozenset({"criteria", "check", "judge", "stance", "brief", "tools", "prompt", "back_targets",
276
+ "flow", "references", "subject", "views", "fallback", "independence", "approval"})
277
+ SESSION_OPTIONS = {"effort": "effort", "session_cost_cap_usd": "cost_cap_usd", "fallback_alias": "fallback_alias",
278
+ "turn_cap": "turn_cap"}
279
+
280
+
281
+ def parse_value(raw: str) -> Any:
282
+ """A `--set` value: JSON when it parses (numbers, booleans, lists), else the text itself."""
283
+ try:
284
+ return json.loads(raw)
285
+ except ValueError:
286
+ return raw
287
+
288
+
289
+ # ---------------------------------------------------------------------------------------------
290
+ # Keys
291
+
292
+
293
+ @dataclasses.dataclass(frozen=True)
294
+ class Key:
295
+ scope: str # run, steps, judges, unit, judge, script, settings
296
+ name: str
297
+ unit: str | None = None
298
+ script: tuple[str, int] | None = None # ("before" | "after", n from 1)
299
+
300
+ def text(self) -> str:
301
+ head = {"run": "run", "steps": "steps", "judges": "judges", "settings": "settings"}.get(self.scope)
302
+ if head:
303
+ return f"{head}.{self.name}"
304
+ if self.scope == "judge":
305
+ return f"judge:{self.unit}.{self.name}"
306
+ if self.scope == "script":
307
+ assert self.script is not None
308
+ return f"{self.unit}.{self.script[0]}:{self.script[1]}.{self.name}"
309
+ return f"{self.unit}.{self.name}"
310
+
311
+
312
+ def _nearest(word: str, names: Iterable[str]) -> str:
313
+ near = difflib.get_close_matches(word, list(names), n=1)
314
+ return f"; did you mean {near[0]!r}?" if near else ""
315
+
316
+
317
+ def parse_key(spec: WorkflowSpec, raw: str) -> Key:
318
+ """RST-B17 keys, checked against the workflow and the catalog (RST-B5, B10, RST-B32)."""
319
+ head, dot, rest = raw.partition(".")
320
+ if not dot or not rest:
321
+ raise SettingError("unknown_setting", f"{raw!r} is not <scope>.<name>")
322
+ if head == "settings":
323
+ if rest not in spec.settings:
324
+ raise SettingError("unknown_setting", f"the workflow declares no setting {rest!r}"
325
+ + _nearest(rest, spec.settings))
326
+ return Key("settings", rest)
327
+ if head in ("run", "steps", "judges"):
328
+ key = Key(head, rest)
329
+ elif head.startswith("judge:"):
330
+ key = Key("judge", rest, unit=head[6:])
331
+ else:
332
+ unit = head
333
+ m = re.match(r"^(before|after):(\d+)\.(.+)$", rest)
334
+ sub = re.match(r"^(member|chair|slot)(:[^.]*)?\.", rest)
335
+ if sub:
336
+ _unit_exists(spec, unit, raw)
337
+ raise SettingError("setting_not_for_kind", f"{raw}: {unit} is a {spec.units[unit].kind}; a member of a "
338
+ "council or a slot of a contest takes no key of its own, set "
339
+ "the unit's")
340
+ if m:
341
+ key = Key("script", m.group(3), unit=unit, script=(m.group(1), int(m.group(2))))
342
+ else:
343
+ key = Key("unit", rest, unit=unit)
344
+ name = key.name
345
+ if name not in WIDENING and (name in VERIFICATION or name.split(".")[0] in VERIFICATION):
346
+ raise SettingError("not_a_setting", f"{raw}: what verifies the work is not a setting (ADR `overrides-never-change-what-verifies-the-work`)")
347
+ if name not in CATALOG:
348
+ raise SettingError("unknown_setting", f"{raw}: no setting {name!r}" + _nearest(name, CATALOG))
349
+ entry = CATALOG[name]
350
+ if key.unit is not None:
351
+ _unit_exists(spec, key.unit, raw)
352
+ if name in NOT_IN_RELEASE:
353
+ raise SettingError("setting_not_in_release", f"{raw}: {NOT_IN_RELEASE[name]}")
354
+ if name in NOT_BUILT:
355
+ raise SettingError("setting_not_built", f"{raw}: built in {NOT_BUILT[name]}")
356
+ if key.scope not in entry.scopes:
357
+ raise SettingError("setting_not_for_kind", f"{raw}: {name} is set on {', '.join(sorted(entry.scopes))}")
358
+ if key.scope in ("unit", "script", "judge"):
359
+ u = spec.units[str(key.unit)]
360
+ if key.scope == "judge" and u.gate.judge is None:
361
+ raise SettingError("setting_not_for_kind", f"{raw}: {key.unit} has no judge")
362
+ if name == "arm":
363
+ if u.switch is None:
364
+ raise SettingError("setting_not_for_kind", f"{raw}: {key.unit} is a {u.kind}, not a switch")
365
+ elif name == "deadline_s":
366
+ if u.kind not in ("ask", "wait"):
367
+ raise SettingError("setting_not_for_kind", f"{raw}: {key.unit} is a {u.kind}, not a wait or ask unit")
368
+ elif name in KIND_ONLY:
369
+ if u.kind not in KIND_ONLY[name]:
370
+ raise SettingError("setting_not_for_kind", f"{raw}: {key.unit} is a {u.kind}, not a "
371
+ f"{' or '.join(KIND_ONLY[name])} unit")
372
+ elif key.scope == "unit" and not (u.kind in SESSION_KINDS or (u.kind == "script" and name == "timeout_s")):
373
+ raise SettingError("setting_not_for_kind", f"{raw}: {key.unit} is a {u.kind}")
374
+ if key.scope == "script":
375
+ phase, n = key.script or ("", 0)
376
+ scripts = (u.step.before if phase == "before" else u.step.after) if u.step is not None else ()
377
+ if not 1 <= n <= len(scripts):
378
+ raise SettingError("setting_not_for_kind", f"{raw}: {key.unit} has no {phase} script {n}")
379
+ return key
380
+
381
+
382
+ def child_scope(spec: WorkflowSpec, raw: str) -> tuple[WorkflowSpec, str]:
383
+ """SWF-B8: a flag reaches a unit of a sub-workflow's child as `<unit>/<child unit>.<key>` (and a setting of the child as
384
+ `<unit>/settings.<name>`). Returns the spec the key belongs to and the key as that spec reads it."""
385
+ unit, slash, rest = raw.partition("/")
386
+ held = spec.units.get(unit)
387
+ if not slash or held is None or held.subworkflow is None:
388
+ return spec, raw
389
+ from tempergraph.model import subworkflow
390
+
391
+ got = subworkflow.read_child(held.subworkflow.workflow)
392
+ if not isinstance(got, subworkflow.Child):
393
+ raise SettingError("unknown_setting", f"{raw}: the child {held.subworkflow.workflow!r} cannot be read")
394
+ return child_scope(got.spec, rest)
395
+
396
+
397
+ def _unit_exists(spec: WorkflowSpec, unit: str, raw: str) -> None:
398
+ if unit not in spec.units:
399
+ raise SettingError("unknown_setting", f"{raw}: no unit {unit!r}" + _nearest(unit, spec.units))
400
+
401
+
402
+ def _value(spec: WorkflowSpec, key: Key, value: Any) -> Any:
403
+ if key.scope == "settings":
404
+ return check_declared(spec.settings[key.name], value)
405
+ entry = CATALOG[key.name]
406
+ v = entry.check(value)
407
+ if key.name == "model" and key.scope in JUDGE_SIDE and not isinstance(v, str):
408
+ raise SettingError("setting_value", "a judge takes one alias, never a ladder")
409
+ if entry.release1 is not None:
410
+ entry.release1(v)
411
+ if key.name == "arm":
412
+ sw = spec.units[str(key.unit)].switch
413
+ if sw is None or v not in sw.arms:
414
+ raise SettingError("setting_value", f"{key.text()}: {v!r} is not one of the arms "
415
+ f"{', '.join(sw.arms) if sw else ''}")
416
+ if key.name == "on_budget_spent" and v == "fallback":
417
+ units = [key.unit] if key.unit else [n for n, u in spec.units.items() if u.kind in SESSION_KINDS]
418
+ if any(spec.units[str(n)].gate.fallback is None for n in units):
419
+ raise SettingError("no_fallback_target", f"{key.text()}: the gate declares no fallback target")
420
+ return v
421
+
422
+
423
+ def check_declared(decl: SettingDecl, value: Any) -> Any:
424
+ """RST-B25 value kinds."""
425
+ kind = decl.kind
426
+ if kind == "bool":
427
+ return _bool(value)
428
+ if kind in ("int", "duration_s"):
429
+ lo = int(decl.min) if decl.min is not None else (0 if kind == "duration_s" else -(10**12))
430
+ v = _int(lo, int(decl.max) if decl.max is not None else None)(value)
431
+ return v
432
+ if kind == "float":
433
+ try:
434
+ x = float(value)
435
+ except (TypeError, ValueError):
436
+ raise SettingError("setting_value", f"{value!r} is not a number") from None
437
+ if (decl.min is not None and x < decl.min) or (decl.max is not None and x > decl.max):
438
+ raise SettingError("setting_value", f"{x} is outside {decl.min} to {decl.max}")
439
+ return x
440
+ if kind == "choice":
441
+ if value not in (decl.choices or ()):
442
+ raise SettingError("setting_value", f"{value!r} is not one of {', '.join(decl.choices or ())}")
443
+ return str(value)
444
+ if not isinstance(value, str):
445
+ raise SettingError("setting_value", f"{value!r} is not text")
446
+ return value
447
+
448
+
449
+ # ---------------------------------------------------------------------------------------------
450
+ # Files
451
+
452
+
453
+ @dataclasses.dataclass(frozen=True, kw_only=True)
454
+ class ConfigFiles:
455
+ """The two `settings.json` files (RST-B24); `None` where the file does not exist."""
456
+
457
+ project: Mapping[str, Any] | None = None
458
+ user: Mapping[str, Any] | None = None
459
+ project_path: Path | None = None
460
+ user_path: Path | None = None
461
+ errors: tuple[Finding, ...] = ()
462
+
463
+
464
+ @dataclasses.dataclass(frozen=True, kw_only=True)
465
+ class Capture:
466
+ """The operator's capture level and observers (LOS-B17, EVT-B21): full capture unless lowered."""
467
+
468
+ raw: bool = True
469
+ tool_inputs: bool = True
470
+ check_output: bool = True
471
+ observers: tuple[str, ...] = ()
472
+
473
+ def lowered(self) -> list[str]:
474
+ return [k for k in ("raw", "tool_inputs", "check_output") if not getattr(self, k)]
475
+
476
+
477
+ def capture(files: ConfigFiles) -> Capture:
478
+ """The `observe` map of the settings files: `raw`, `tool_inputs`, `check_output` (`on` or `off`) and
479
+ `observers` (names to enable). The project file wins per key over the user file; never a run layer."""
480
+ got: dict[str, Any] = {}
481
+ for doc in (files.user, files.project):
482
+ o = (doc or {}).get("observe")
483
+ if isinstance(o, Mapping):
484
+ got.update(o)
485
+
486
+ def on(key: str) -> bool:
487
+ return got.get(key, "on") not in ("off", False)
488
+
489
+ names = got.get("observers")
490
+ obs = tuple(str(n) for n in names if isinstance(n, str)) if isinstance(names, list) else ()
491
+ return Capture(raw=on("raw"), tool_inputs=on("tool_inputs"), check_output=on("check_output"), observers=obs)
492
+
493
+
494
+ def schedule_settings(home: Path) -> dict[str, bool]:
495
+ """`schedule.*` of the user settings file only (a project file cannot start a process at login); a missing file, an
496
+ unknown key or a value that is not a boolean leaves the default."""
497
+ out = dict(SCHEDULE_DEFAULTS)
498
+ try:
499
+ doc = json.loads((home / "config" / SETTINGS_FILE).read_text(encoding="utf-8"))
500
+ except (OSError, ValueError):
501
+ return out
502
+ given = doc.get("schedule") if isinstance(doc, Mapping) else None
503
+ for key in SCHEDULE_DEFAULTS:
504
+ if isinstance(given, Mapping) and isinstance(given.get(key), bool):
505
+ out[key] = bool(given[key])
506
+ return out
507
+
508
+
509
+ def config_paths(state_root: Path | None, home: Path) -> tuple[Path | None, Path]:
510
+ return (state_root / "config" / SETTINGS_FILE if state_root else None), home / "config" / SETTINGS_FILE
511
+
512
+
513
+ def load_files(state_root: Path | None, home: Path) -> ConfigFiles:
514
+ """Read both files once; a file that does not parse or has a newer schema is a finding (RST-B32)."""
515
+ pp, up = config_paths(state_root, home)
516
+ docs: dict[str, Any] = {}
517
+ errors: list[Finding] = []
518
+ for name, p in (("project", pp), ("user", up)):
519
+ if p is None or not p.exists():
520
+ docs[name] = None
521
+ continue
522
+ try:
523
+ doc = json.loads(p.read_text(encoding="utf-8"))
524
+ except (OSError, ValueError) as exc:
525
+ errors.append(Finding(code="config_file", unit=None, message=f"{p}: {exc}"))
526
+ docs[name] = None
527
+ continue
528
+ if not isinstance(doc, Mapping) or doc.get("schema_version") != 1:
529
+ errors.append(Finding(code="config_file", unit=None, message=f"{p}: not a schema_version 1 object"))
530
+ docs[name] = None
531
+ continue
532
+ docs[name] = doc
533
+ return ConfigFiles(project=docs["project"], user=docs["user"], project_path=pp, user_path=up,
534
+ errors=tuple(errors))
535
+
536
+
537
+ def _file_layers(spec: WorkflowSpec, files: ConfigFiles) -> tuple[dict[str, dict[str, dict[str, Any]]],
538
+ list[Finding]]:
539
+ layers: dict[str, dict[str, dict[str, Any]]] = {}
540
+ out: list[Finding] = list(files.errors)
541
+ for where, doc, path in (("project", files.project, files.project_path), ("user", files.user, files.user_path)):
542
+ if doc is None:
543
+ continue
544
+ ov: dict[str, dict[str, Any]] = {}
545
+ named: set[str] = set()
546
+ for i, entry in enumerate(doc.get("overrides") or []):
547
+ if not isinstance(entry, Mapping) or entry.get("workflow") not in (spec.name, "*"):
548
+ continue
549
+ for k, v in (entry.get("set") or {}).items():
550
+ if _widening(str(k)):
551
+ out.append(Finding(code="widening_in_file", unit=None, message=f"{path}: {k} widens tools; only "
552
+ "a person's flag may (RST-B28, RST-B29, RST-B30)"))
553
+ continue
554
+ specific = entry.get("workflow") == spec.name
555
+ if k in ov and not specific and k in named:
556
+ continue # a named entry beats `*` per key
557
+ ov[str(k)] = {"value": v, "ref": f"{path}#overrides[{i}]"}
558
+ if specific:
559
+ named.add(str(k))
560
+ layers[f"{where}:overrides"] = ov
561
+ df: dict[str, dict[str, Any]] = {}
562
+ for k, v in (doc.get("defaults") or {}).items():
563
+ head = str(k).split(".")[0]
564
+ if head not in ("run", "steps", "judges", "settings"):
565
+ out.append(Finding(code="unit_in_defaults", unit=None,
566
+ message=f"{path}: defaults key {k} names a unit; use overrides"))
567
+ continue
568
+ if head == "settings" and str(k)[9:] not in spec.settings:
569
+ continue # another workflow's setting
570
+ df[str(k)] = {"value": v, "ref": f"{path}#defaults"}
571
+ layers[f"{where}:defaults"] = df
572
+ return layers, out
573
+
574
+
575
+ def _widening(k: str) -> bool:
576
+ return any(k.endswith("." + w) for w in WIDENING)
577
+
578
+
579
+ is_widening = _widening
580
+
581
+
582
+ def as_list(v: Any) -> list[str]:
583
+ return [str(x) for x in v] if isinstance(v, (list, tuple)) else _list(v) if isinstance(v, str) else [str(v)]
584
+
585
+
586
+ def find_profile(spec: WorkflowSpec, name: str, files: ConfigFiles) -> tuple[Mapping[str, Any], str] | None:
587
+ """Project file, then user file, then the workflow's own; the first found is used whole (RST-B24)."""
588
+ for doc, path in ((files.project, files.project_path), (files.user, files.user_path)):
589
+ prof = ((doc or {}).get("profiles") or {}).get(name)
590
+ if isinstance(prof, Mapping):
591
+ return prof, f"{path}#profiles.{name}"
592
+ if name in spec.profiles:
593
+ return spec.profiles[name], f"workflow:profiles.{name}"
594
+ return None
595
+
596
+
597
+ # ---------------------------------------------------------------------------------------------
598
+ # Snapshot (RunOptions.settings) and validation
599
+
600
+
601
+ def snapshot(spec: WorkflowSpec, flags: Mapping[str, Any], profiles: Sequence[str], files: ConfigFiles,
602
+ via: str = "cli") -> tuple[dict[str, dict[str, dict[str, Any]]], list[Finding]]:
603
+ """The operator layers for `RunOptions.settings`: layer -> key -> {value, ref, via?} (RST-B26)."""
604
+ out: list[Finding] = []
605
+ layers, file_findings = _file_layers(spec, files)
606
+ out += file_findings
607
+ prof: dict[str, dict[str, Any]] = {}
608
+ for name in profiles:
609
+ found = find_profile(spec, name, files)
610
+ if found is None:
611
+ out.append(Finding(code="unknown_profile", unit=None, message=f"no profile {name!r}"))
612
+ continue
613
+ values, ref = found
614
+ if not ref.startswith("workflow:"):
615
+ for k in values:
616
+ if _widening(str(k)):
617
+ out.append(Finding(code="widening_in_file", unit=None,
618
+ message=f"{ref}: {k} widens tools; only a workflow's own profile may"))
619
+ prof.update({str(k): {"value": v, "ref": ref} for k, v in values.items() if not
620
+ (_widening(str(k)) and not ref.startswith("workflow:"))})
621
+ layers["profile"] = prof
622
+ layers["flag"] = {str(k): {"value": v, "ref": f"--set {k}", "via": via} for k, v in flags.items()}
623
+ return {k: layers.get(k, {}) for k in OPERATOR_LAYERS}, out
624
+
625
+
626
+ def validate_layers(spec: WorkflowSpec, layers: Mapping[str, Mapping[str, Mapping[str, Any]]],
627
+ caller_kind: str = "person") -> list[Finding]:
628
+ out: list[Finding] = []
629
+ if caller_kind != "person":
630
+ for raw in (layers.get("flag") or {}):
631
+ if _widening(raw):
632
+ out.append(Finding(code="widening_by_agent", unit=None,
633
+ message=f"{raw}: only a person may widen a step's tools (RST-B28, RST-B29, RST-B30, PRV-B21, PRV-B22)"))
634
+ for layer in OPERATOR_LAYERS:
635
+ for raw, cell in (layers.get(layer) or {}).items():
636
+ try:
637
+ scope, name = child_scope(spec, raw)
638
+ key = parse_key(scope, name)
639
+ _value(scope, key, cell.get("value"))
640
+ except SettingError as exc:
641
+ out.append(Finding(code=exc.code, unit=None, message=f"{layer} {cell.get('ref', raw)}: {exc}"))
642
+ return out
643
+
644
+
645
+ def options_snapshot(spec: WorkflowSpec, flags: Mapping[str, Any], profiles: Sequence[str], files: ConfigFiles,
646
+ via: str = "cli", caller_kind: str = "person") -> tuple[RunOptions, list[Finding]]:
647
+ layers, out = snapshot(spec, flags, profiles, files, via)
648
+ out += validate_layers(spec, layers, caller_kind)
649
+ return RunOptions(settings={k: dict(v) for k, v in layers.items()}, profiles=tuple(profiles)), out
650
+
651
+
652
+ def validate_overrides(spec: WorkflowSpec, options: RunOptions, files: ConfigFiles) -> list[Finding]:
653
+ """RST-B16 to RST-B32 contract: every operator value of these options and files, checked before spend."""
654
+ flags = {k: c["value"] for k, c in (options.settings.get("flag") or {}).items()}
655
+ _, out = options_snapshot(spec, flags, options.profiles, files)
656
+ return out
657
+
658
+
659
+ # ---------------------------------------------------------------------------------------------
660
+ # Resolution
661
+
662
+
663
+ def _workflow_values(spec: WorkflowSpec) -> dict[str, dict[str, dict[str, Any]]]:
664
+ """The two workflow layers as concrete keys: what the units and the workflow declare."""
665
+ unit_l: dict[str, dict[str, Any]] = {}
666
+ dflt: dict[str, dict[str, Any]] = {}
667
+
668
+ def put(layer: dict[str, dict[str, Any]], key: str, value: Any, ref: str) -> None:
669
+ if value is not None:
670
+ layer[key] = {"value": value, "ref": ref}
671
+
672
+ for name, u in spec.units.items():
673
+ g = u.gate
674
+ if u.kind in SESSION_KINDS and u.step is not None:
675
+ st = u.step
676
+ put(unit_l, f"{name}.executor", st.executor, f"units.{name}.executor")
677
+ put(unit_l, f"{name}.model", st.model, f"units.{name}.model")
678
+ put(unit_l, f"{name}.subagent_model", st.subagent_model, f"units.{name}.subagent_model")
679
+ put(unit_l, f"{name}.timeout_s", st.timeout_s, f"units.{name}.timeout_s")
680
+ put(unit_l, f"{name}.idle_s", st.idle_s, f"units.{name}.idle_s")
681
+ for k, f in SESSION_OPTIONS.items():
682
+ put(unit_l, f"{name}.{k}", getattr(st.session_options, f) if st.session_options else None,
683
+ f"units.{name}.session_options.{f}")
684
+ for k, default in (("retry_budget", 2), ("loop_budget", 1), ("on_budget_spent", "ask")):
685
+ if getattr(g, k) != default:
686
+ put(unit_l, f"{name}.{k}", getattr(g, k), f"units.{name}.gate.{k}")
687
+ if g.approval:
688
+ put(unit_l, f"{name}.approve", True, f"units.{name}.gate.approval")
689
+ for phase in ("before", "after"):
690
+ for i, sc in enumerate(getattr(st, phase), start=1):
691
+ if sc.timeout_s != 600:
692
+ put(unit_l, f"{name}.{phase}:{i}.timeout_s", sc.timeout_s, f"units.{name}.{phase}[{i - 1}]")
693
+ put(dflt, f"{name}.model", spec.model_profile.get(name), f"model_profile.{name}")
694
+ if u.kind == "contest" and u.contest is not None: # CTS-B6, RST-B19: what the contest declares is its own layer
695
+ put(unit_l, f"{name}.concurrency", u.contest.concurrency, f"units.{name}.contest.concurrency")
696
+ put(unit_l, f"{name}.attempt_cost_cap_usd", u.contest.cost_cap_usd, f"units.{name}.contest.cost_cap_usd")
697
+ if u.kind == "script" and u.script is not None and u.script.timeout_s != 600:
698
+ put(unit_l, f"{name}.timeout_s", u.script.timeout_s, f"units.{name}.script.timeout_s")
699
+ j = g.judge
700
+ if j is not None:
701
+ put(unit_l, f"judge:{name}.executor", j.executor, f"units.{name}.gate.judge.executor")
702
+ put(unit_l, f"judge:{name}.timeout_s", j.timeout_s, f"units.{name}.gate.judge.timeout_s")
703
+ put(unit_l, f"judge:{name}.idle_s", j.idle_s, f"units.{name}.gate.judge.idle_s")
704
+ for k, f in SESSION_OPTIONS.items():
705
+ if k != "fallback_alias":
706
+ put(unit_l, f"judge:{name}.{k}", getattr(j.session_options, f) if j.session_options else None,
707
+ f"units.{name}.gate.judge.session_options.{f}")
708
+ if j.model:
709
+ put(unit_l, f"judge:{name}.model", j.model, f"units.{name}.gate.judge.model")
710
+ elif u.step is not None and u.step.model:
711
+ first = u.step.model if isinstance(u.step.model, str) else list(u.step.model)[0]
712
+ put(unit_l, f"judge:{name}.model", first, f"units.{name}.model") # CON-B3
713
+ prof = spec.model_profile.get(f"judge:{name}")
714
+ put(dflt, f"judge:{name}.model", prof if isinstance(prof, str) or prof is None else list(prof)[0],
715
+ f"model_profile.judge:{name}")
716
+ put(dflt, "run.run_cost_cap_usd", spec.run_cost_cap_usd, "run_cost_cap_usd")
717
+ put(dflt, "run.daily_cap_usd", spec.daily_cap_usd, "daily_cap_usd")
718
+ put(dflt, "run.loop_dry_run", spec.loop_dry_run, "loop_dry_run") # LFS-B1: `None` declares nothing
719
+ if spec.workspace != "auto":
720
+ put(dflt, "run.workspace", spec.workspace, "workspace")
721
+ if spec.worktree is not None:
722
+ put(dflt, "run.worktree.base", spec.worktree.base, "worktree.base")
723
+ put(dflt, "run.worktree.cleanup", spec.worktree.cleanup, "worktree.cleanup")
724
+ for name, decl in spec.settings.items():
725
+ put(dflt, f"settings.{name}", decl.default, f"settings.{name}.default")
726
+ return {"workflow:unit": unit_l, "workflow:default": dflt}
727
+
728
+
729
+ def targets(spec: WorkflowSpec) -> list[tuple[str, str, list[str]]]:
730
+ """Every concrete key the run reads, its catalog name, and its matching keys narrowest first (RST-B22, RST-B23)."""
731
+ out: list[tuple[str, str, list[str]]] = []
732
+ for name, e in CATALOG.items():
733
+ if name in NOT_IN_RELEASE or name in NOT_BUILT:
734
+ continue
735
+ if "run" in e.scopes:
736
+ out.append((f"run.{name}", name, [f"run.{name}"]))
737
+ for unit, u in spec.units.items():
738
+ for name, e in CATALOG.items():
739
+ if name in NOT_IN_RELEASE or name in NOT_BUILT:
740
+ continue
741
+ if name in KIND_ONLY: # a key of one kind of unit is read for units of that kind only (RST-B19)
742
+ if u.kind in KIND_ONLY[name]:
743
+ out.append((f"{unit}.{name}", name, [f"{unit}.{name}"]))
744
+ continue
745
+ if name == "arm":
746
+ if u.switch is not None:
747
+ out.append((f"{unit}.arm", "arm", [f"{unit}.arm"]))
748
+ continue
749
+ if name == "deadline_s":
750
+ if u.kind in ("ask", "wait"):
751
+ out.append((f"{unit}.deadline_s", name, [f"{unit}.deadline_s"]))
752
+ continue
753
+ if u.kind in SESSION_KINDS and e.scopes & STEP_SIDE:
754
+ out.append((f"{unit}.{name}", name, [f"{unit}.{name}", f"steps.{name}"] if "steps" in e.scopes
755
+ else [f"{unit}.{name}"]))
756
+ if u.kind == "council" and name in COUNCIL_STEP_KEYS: # CNL-B9: members and chair sit on the step layer
757
+ out.append((f"{unit}.{name}", name, [f"steps.{name}"])) # `council` is no SESSION_KIND: no `<unit>.` key
758
+ if u.kind == "script" and name == "timeout_s":
759
+ out.append((f"{unit}.timeout_s", "timeout_s", [f"{unit}.timeout_s"]))
760
+ if u.gate.judge is not None and e.scopes & JUDGE_SIDE:
761
+ out.append((f"judge:{unit}.{name}", name, [f"judge:{unit}.{name}", f"judges.{name}"]))
762
+ if u.step is not None:
763
+ for phase in ("before", "after"):
764
+ for i, _ in enumerate(getattr(u.step, phase), start=1):
765
+ for name in ("timeout_s", "commands.add"):
766
+ k = f"{unit}.{phase}:{i}.{name}"
767
+ out.append((k, name, [k]))
768
+ for name in spec.settings:
769
+ out.append((f"settings.{name}", "", [f"settings.{name}"]))
770
+ return out
771
+
772
+
773
+ def _canonical(v: Any) -> Any:
774
+ return list(v) if isinstance(v, tuple) else v
775
+
776
+
777
+ def resolve(spec: WorkflowSpec, options: RunOptions, files: ConfigFiles | None = None) -> ResolvedSettings:
778
+ """Pure: the winning value, layer and ref of every key the run reads (RST-B22, RST-B23, RST-B27).
779
+
780
+ `options.settings` is the snapshot of the operator layers. With `files`, the file and profile layers are
781
+ built from them and only the flags are taken from the options (a start, `config show`, `run --check`).
782
+ """
783
+ layers: dict[str, Mapping[str, Mapping[str, Any]]] = dict(options.settings or {})
784
+ if files is not None:
785
+ flags = {k: c["value"] for k, c in (layers.get("flag") or {}).items()}
786
+ layers = dict(snapshot(spec, flags, options.profiles, files)[0])
787
+ layers.update(_workflow_values(spec))
788
+ text_keys = {f"settings.{n}" for n, d in spec.settings.items() if d.kind == "text"}
789
+ values: dict[str, Any] = {}
790
+ rows: list[SettingRow] = []
791
+ for target, name, matching in targets(spec):
792
+ found: list[tuple[str, Any, str]] = []
793
+ for layer in LAYERS[:-1]:
794
+ cells = layers.get(layer) or {}
795
+ for m in matching: # inside a layer the narrowest matching scope wins
796
+ if m in cells:
797
+ found.append((layer, cells[m]["value"], str(cells[m].get("ref") or m)))
798
+ break
799
+ entry = CATALOG.get(name)
800
+ if found:
801
+ layer, value, ref = found[0]
802
+ if layer in OPERATOR_LAYERS:
803
+ with contextlib.suppress(SettingError): # refused by validate_layers before any start
804
+ value = _value(spec, parse_key(spec, target), value)
805
+ values[target] = value
806
+ shown = (hashlib.sha256(str(value).encode()).hexdigest()[:16] if target in text_keys else value)
807
+ rows.append(SettingRow(key=target, value=_canonical(shown), layer=layer, ref=ref,
808
+ shadowed=tuple({"layer": lyr, "ref": r} for lyr, _, r in found[1:])))
809
+ else:
810
+ values[target] = entry.default if entry is not None else None
811
+ table = [{"key": r.key, "value": r.value, "layer": r.layer} for r in rows]
812
+ digest = hashlib.sha256(json.dumps(table, sort_keys=True, default=str).encode()).hexdigest()
813
+ return ResolvedSettings(rows=tuple(rows), values=values, digest=digest, profiles=tuple(options.profiles))
814
+
815
+
816
+ def overridden_keys(res: ResolvedSettings) -> list[str]:
817
+ """Keys whose winning layer ranks 1 to 4 (RST-B27)."""
818
+ return [r.key for r in res.rows if r.layer in LAYERS[:4]]
819
+
820
+
821
+ def changed_keys(old: ResolvedSettings | None, new: ResolvedSettings) -> list[str]:
822
+ if old is None:
823
+ return []
824
+ keys = set(old.values) | set(new.values)
825
+ return sorted(k for k in keys if _canonical(old.values.get(k)) != _canonical(new.values.get(k)))
826
+
827
+
828
+ # ---------------------------------------------------------------------------------------------
829
+ # Applying a resolution to the spec the run executes
830
+
831
+
832
+ def effective_spec(spec: WorkflowSpec, res: ResolvedSettings) -> WorkflowSpec:
833
+ """The workflow with every resolved session, budget and workflow-wide value in its own field.
834
+
835
+ Judges get their resolved model written in, so a step-side override never reaches them through the
836
+ runner's step-to-judge inheritance (RST-B22, RST-B23, Judges apart).
837
+ """
838
+ v = res.values
839
+ layer_of = {r.key: r.layer for r in res.rows}
840
+ units: dict[str, UnitSpec] = {}
841
+ for name, u in spec.units.items():
842
+ g: GateSpec = u.gate
843
+ if u.kind in SESSION_KINDS and u.step is not None:
844
+ st: StepSpec = u.step
845
+ opts = SessionOptions(**{f: v.get(f"{name}.{k}") for k, f in SESSION_OPTIONS.items()})
846
+ added = tuple(v.get(f"{name}.tools.add") or ())
847
+ cmds = tuple(v.get(f"{name}.commands.add") or ())
848
+ st = dataclasses.replace(
849
+ st, tools=tuple(dict.fromkeys(st.tools + added)), commands=tuple(dict.fromkeys(st.commands + cmds)),
850
+ executor=v.get(f"{name}.executor") or st.executor,
851
+ model=_model(v.get(f"{name}.model")), timeout_s=v.get(f"{name}.timeout_s"),
852
+ idle_s=v.get(f"{name}.idle_s"), subagent_model=v.get(f"{name}.subagent_model"),
853
+ session_options=opts if opts.set_names() else None,
854
+ before=tuple(dataclasses.replace(sc, timeout_s=int(v.get(f"{name}.before:{i}.timeout_s") or 600))
855
+ for i, sc in enumerate(st.before, start=1)),
856
+ after=tuple(dataclasses.replace(sc, timeout_s=int(v.get(f"{name}.after:{i}.timeout_s") or 600))
857
+ for i, sc in enumerate(st.after, start=1)))
858
+ g = dataclasses.replace(g, retry_budget=int(v.get(f"{name}.retry_budget", g.retry_budget)),
859
+ loop_budget=int(v.get(f"{name}.loop_budget", g.loop_budget)),
860
+ on_budget_spent=v.get(f"{name}.on_budget_spent") or g.on_budget_spent,
861
+ approval=g.approval or bool(v.get(f"{name}.approve")))
862
+ operator = tuple(k for k in ("model", "timeout_s", "idle_s", "effort")
863
+ if layer_of.get(f"{name}.{k}") in LAYERS[:4])
864
+ u = dataclasses.replace(u, step=st, extra={**u.extra, "operator_set": operator} if operator else u.extra)
865
+ if u.kind == "council" and u.council is not None: # a member or chair that declares none takes the step layer's
866
+ model, executor = _model(v.get(f"{name}.model")), v.get(f"{name}.executor")
867
+ alias = model if isinstance(model, str) or model is None else model[0]
868
+ cc = u.council
869
+ u = dataclasses.replace(u, council=dataclasses.replace(
870
+ cc, members=tuple(dataclasses.replace(m, model=m.model or alias, executor=m.executor or executor)
871
+ for m in cc.members),
872
+ chair=dataclasses.replace(cc.chair, model=cc.chair.model or alias,
873
+ executor=cc.chair.executor or executor) if cc.chair else None))
874
+ cap = v.get(f"{name}.session_cost_cap_usd")
875
+ if cap is not None:
876
+ u = dataclasses.replace(u, extra={**u.extra, "session_cost_cap_usd": float(cap)})
877
+ if u.switch is not None and v.get(f"{name}.arm"):
878
+ u = dataclasses.replace(u, extra={**u.extra, "arm": v.get(f"{name}.arm")}) # CMP-B7
879
+ if u.kind == "contest" and u.contest is not None: # CTS-B6, RST-B19: the resolved values win over the declared
880
+ cap = v.get(f"{name}.attempt_cost_cap_usd")
881
+ u = dataclasses.replace(u, contest=dataclasses.replace(
882
+ u.contest, concurrency=int(v.get(f"{name}.concurrency") or u.contest.concurrency),
883
+ cost_cap_usd=float(cap) if cap is not None else u.contest.cost_cap_usd))
884
+ deadline = v.get(f"{name}.deadline_s")
885
+ if deadline and u.ask is not None: # FLX-B8: an operator may move a declared or default deadline
886
+ u = dataclasses.replace(u, ask=dataclasses.replace(u.ask, deadline_s=int(deadline)))
887
+ if deadline and u.wait is not None:
888
+ u = dataclasses.replace(u, wait=dataclasses.replace(u.wait, deadline_s=int(deadline)))
889
+ if u.kind == "script" and u.script is not None:
890
+ u = dataclasses.replace(u, script=dataclasses.replace(u.script, timeout_s=int(
891
+ v.get(f"{name}.timeout_s") or u.script.timeout_s)))
892
+ if g.judge is not None:
893
+ j: JudgeSpec = g.judge
894
+ jopts = SessionOptions(**{f: v.get(f"judge:{name}.{k}") for k, f in SESSION_OPTIONS.items()
895
+ if k != "fallback_alias"})
896
+ model = v.get(f"judge:{name}.model")
897
+ j = dataclasses.replace(j, executor=v.get(f"judge:{name}.executor") or j.executor,
898
+ model=model if model and model != "inherit" else None,
899
+ timeout_s=v.get(f"judge:{name}.timeout_s"), idle_s=v.get(f"judge:{name}.idle_s"),
900
+ session_options=jopts if jopts.set_names() else None)
901
+ g = dataclasses.replace(g, judge=j)
902
+ jpins = tuple(k for k in ("model", "effort") if layer_of.get(f"judge:{name}.{k}") in LAYERS[:4])
903
+ if jpins: # JRK-B8 rule 1: a pinned judge model or effort wins over a risk level
904
+ u = dataclasses.replace(u, extra={**u.extra, "judge_operator_set": jpins})
905
+ views = tuple(v.get(f"judge:{name}.views.add") or ())
906
+ if views:
907
+ u = dataclasses.replace(u, extra={**u.extra, "views_add": views})
908
+ units[name] = dataclasses.replace(u, gate=g)
909
+ wt = spec.worktree
910
+ if wt is not None:
911
+ wt = dataclasses.replace(wt, base=v.get("run.worktree.base"), cleanup=v.get("run.worktree.cleanup"))
912
+ allowed = tuple(dict.fromkeys(spec.allow_commands + tuple(
913
+ p for k, val in v.items() if k.endswith("commands.add") for p in (val or ()))))
914
+ return dataclasses.replace(spec, units=units, run_cost_cap_usd=v.get("run.run_cost_cap_usd"),
915
+ allow_commands=allowed,
916
+ workspace=v.get("run.workspace") or "auto", worktree=wt)
917
+
918
+
919
+ def _model(v: Any) -> str | tuple[str, ...] | None:
920
+ if v is None or v == "inherit":
921
+ return None
922
+ return tuple(v) if isinstance(v, (list, tuple)) else str(v)
923
+
924
+
925
+ def run_values(res: ResolvedSettings) -> dict[str, Any]:
926
+ """The run-scope values (`run.<name>` without the prefix)."""
927
+ return {k[4:]: val for k, val in res.values.items() if k.startswith("run.")}
928
+
929
+
930
+ def workflow_settings(res: ResolvedSettings) -> dict[str, Any]:
931
+ """`settings.<name>` values for checks, scripts and templates (RST-B25)."""
932
+ return {k[9:]: val for k, val in res.values.items() if k.startswith("settings.")}
933
+
934
+
935
+ def rows_json(res: ResolvedSettings) -> list[dict[str, Any]]:
936
+ return [{"key": r.key, "value": r.value, "layer": r.layer, "ref": r.ref, "shadowed": list(r.shadowed),
937
+ **({"widening": True} if _widening(r.key) else {})} for r in res.rows]
938
+
939
+
940
+ def grants(res: ResolvedSettings) -> list[dict[str, Any]]:
941
+ """Every resolved widening value as one grant: `{unit, key, capability | prefix}` (RST-B28, RST-B29, RST-B30 Shown)."""
942
+ out: list[dict[str, Any]] = []
943
+ for k, v in sorted(res.values.items()):
944
+ if not _widening(k) or not v:
945
+ continue
946
+ unit = k.split(".", 1)[0].removeprefix("judge:")
947
+ field_ = "prefix" if k.endswith("commands.add") else "capability"
948
+ out += [{"unit": unit, "key": k, field_: item} for item in v]
949
+ return out
950
+