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,8 @@
1
+ """tempergraph: tempered rails for AI workflows.
2
+
3
+ Workflow packages import only :mod:`tempergraph.api` (PKG-B15, PKG-B16, PKG-B17).
4
+ """
5
+
6
+ from tempergraph.constants import ENGINE_VERSION as __version__
7
+
8
+ __all__ = ["__version__"]
@@ -0,0 +1,5 @@
1
+ """`python -m tempergraph`: the CLI entry the shim execs (UPD-B11, UPD-B12, UPD-B13)."""
2
+
3
+ from tempergraph.cli.main import entry
4
+
5
+ entry()
tempergraph/api.py ADDED
@@ -0,0 +1,428 @@
1
+ """The public declaration interface (PKG-B19, PKG-B20, ADR `declare-workflows-with-typed-python-builders-and-text-in-files`): the only engine module a workflow imports.
2
+
3
+ Each builder produces one CON-B4, CON-B5, CON-B6, CON-B7 type and takes the same field names as keyword arguments; an unknown
4
+ argument is a ``TypeError`` at build time. ``name`` and ``version`` come from the package manifests and
5
+ are refused as arguments (PKG-B2). Kinds outside the running release build, and are refused at validation
6
+ with ``not_in_release`` (ADR `first-release-is-simple-trusted-workflows-on-one-machine`).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import dataclasses
12
+ import inspect
13
+ import re
14
+ from collections.abc import Callable, Iterable, Mapping, Sequence
15
+ from typing import Any
16
+
17
+ from tempergraph import check_helpers as checks # `tempergraph.api.checks` (SCF-B14 to SCF-B17)
18
+ from tempergraph.contracts import (
19
+ AskQuestion,
20
+ AskSpec,
21
+ CallableRef,
22
+ ChairSpec,
23
+ CheckFinding,
24
+ CheckResult,
25
+ ComplexitySpec,
26
+ ContestSpec,
27
+ CouncilSpec,
28
+ Criterion,
29
+ EscalationSpec,
30
+ GateSpec,
31
+ InputDeclaration,
32
+ JudgeSpec,
33
+ MapSpec,
34
+ MeasureSpec,
35
+ MemberSpec,
36
+ ProducesKind,
37
+ RearmSpec,
38
+ ResolveResult,
39
+ RiskLevel,
40
+ RiskSpec,
41
+ RiskWhen,
42
+ RouteView,
43
+ RoutingMetadata,
44
+ ScriptSpec,
45
+ SessionOptions,
46
+ SettingDecl,
47
+ SlotSpec,
48
+ StepSpec,
49
+ SubworkflowSpec,
50
+ SwitchSpec,
51
+ TextRef,
52
+ UnitSpec,
53
+ ValueKind,
54
+ WaitSpec,
55
+ WorkflowSpec,
56
+ WorktreeDecl,
57
+ )
58
+ from tempergraph.contracts import Param as _ParamType
59
+ from tempergraph.run.finalize import FinalizerContext, FinalizerResult
60
+
61
+ __all__ = [
62
+ "CheckFinding", "CheckResult", "Criterion", "FinalizerContext", "FinalizerResult", "Gate", "Input", "Judge", "Param", "ResolveResult", "Route",
63
+ "ComplexitySwitch", "Escalation", "Level", "Measure", "Risk", "When", "stock", "Rearm", "RouteView", "Routing", "Script", "SessionOptions", "Setting", "Step", "Switch", "Value", "Workflow",
64
+ "WorktreeDecl", "checks", "text", "Parallel", "Question", "Map", "Ask", "Wait", "Council", "Member", "Chair", "Contest", "Slot", "Subworkflow",
65
+ ]
66
+
67
+
68
+ def callable_ref(func: Callable[..., Any]) -> CallableRef:
69
+ """Record a module-level function as `<module>:<qualname>`; refuse lambdas, nested and bound callables."""
70
+ if isinstance(func, CallableRef):
71
+ return func
72
+ if not inspect.isfunction(func):
73
+ raise TypeError(f"callable-not-importable: {func!r} is not a module-level function")
74
+ qual = func.__qualname__
75
+ if "<lambda>" in qual or "<locals>" in qual:
76
+ raise TypeError(f"callable-not-importable: {func.__module__}:{qual}")
77
+ return CallableRef(module=func.__module__, qualname=qual, func=func)
78
+
79
+
80
+ def _opt_ref(func: Callable[..., Any] | None) -> CallableRef | None:
81
+ return None if func is None else callable_ref(func)
82
+
83
+
84
+ def text(path: str) -> TextRef:
85
+ """A template or brief file inside the package (PKG-B19, PKG-B20)."""
86
+ return TextRef(path=path)
87
+
88
+
89
+ def Value(*, choices: Iterable[str] | None = None, pattern: str | None = None, max_chars: int = 500,
90
+ optional: bool = False) -> ValueKind:
91
+ return ValueKind(choices=tuple(choices) if choices is not None else None, pattern=pattern,
92
+ max_chars=max_chars, optional=optional)
93
+
94
+
95
+ def Param(*, name: str, meaning: str = "", example: str = "", when_asked: str = "") -> _ParamType: # noqa: N802
96
+ return _ParamType(name=name, meaning=meaning, example=example, when_asked=when_asked)
97
+
98
+
99
+ def Input(*, kind: str = "text", parameters: Iterable[Any] = (), examples: Iterable[str] = (), # noqa: N802
100
+ prerequisites: Iterable[str] = (), resolver: Callable[..., Any] | None = None) -> InputDeclaration:
101
+ return InputDeclaration(kind=kind, parameters=tuple(parameters), examples=tuple(examples), # type: ignore[arg-type]
102
+ prerequisites=tuple(prerequisites), resolver=_opt_ref(resolver))
103
+
104
+
105
+ def Routing(*, description: str, when_to_use: str = "", task_kind: str = "prompt") -> RoutingMetadata: # noqa: N802
106
+ return RoutingMetadata(description=description, when_to_use=when_to_use, task_kind=task_kind) # type: ignore[arg-type]
107
+
108
+
109
+ def Setting(*, kind: str, default: Any, meaning: str = "", choices: Iterable[str] | None = None, # noqa: N802
110
+ min: float | None = None, max: float | None = None) -> SettingDecl:
111
+ return SettingDecl(kind=kind, default=default, meaning=meaning, # type: ignore[arg-type]
112
+ choices=tuple(choices) if choices is not None else None, min=min, max=max)
113
+
114
+
115
+ def Judge(*, file: str | None = None, stance: str = "", brief: str = "", # noqa: N802
116
+ references: Mapping[str, str] | Iterable[str] = (), subject: Iterable[str] = (),
117
+ executor: str | None = None, model: str | None = None, timeout_s: int | None = None,
118
+ tools: Iterable[str] | None = None, effort: str | None = None,
119
+ session_options: SessionOptions | None = None, sizing: str = "",
120
+ risk: RiskSpec | None = None) -> JudgeSpec:
121
+ """`sizing` is one sentence on why `model` and `effort` fit what this judge must read (SCF-B10)."""
122
+ refs = dict(references) if isinstance(references, Mapping) else {k: "required" for k in references}
123
+ if effort is not None:
124
+ if session_options is not None and session_options.effort is not None:
125
+ raise TypeError("Judge() takes `effort` once: as a field or in `session_options`")
126
+ session_options = dataclasses.replace(session_options or SessionOptions(), effort=effort) # type: ignore[arg-type]
127
+ return JudgeSpec(file=file, stance=stance, brief=brief, references=refs, subject=tuple(subject), # type: ignore[arg-type]
128
+ executor=executor, model=model, timeout_s=timeout_s,
129
+ tools=tuple(tools) if tools is not None else None, session_options=session_options,
130
+ sizing=sizing, risk=risk)
131
+
132
+
133
+ def Level(name: str, *, model: str | None = None, effort: str | None = None) -> RiskLevel: # noqa: N802
134
+ """One level of a judge (JRK-B6). The first level takes no model: it is the gate's own judge."""
135
+ return RiskLevel(name=name, model=model, effort=effort)
136
+
137
+
138
+ def When(level: str, *, paths: Iterable[str] = (), min_paths: int = 1, min_lines: int | None = None, # noqa: N802
139
+ fact: tuple[str, str] | None = None, min_fact: float | None = None) -> RiskWhen:
140
+ """A stock risk rule: `level` holds when the attempt changed `min_paths` paths under `paths`, `min_lines`
141
+ lines, or a check fact reached `min_fact`. Of the rules that hold, the highest level wins."""
142
+ return RiskWhen(level=level, paths=tuple(paths), min_paths=min_paths, min_lines=min_lines,
143
+ fact=tuple(fact) if fact else None, min_fact=min_fact) # type: ignore[arg-type]
144
+
145
+
146
+ def Risk(*, levels: Iterable[RiskLevel], rule: Callable[..., Any] | None = None, # noqa: N802
147
+ when: Iterable[RiskWhen] = (), mode: str = "route") -> RiskSpec:
148
+ """Raise a gate's judge by model-free facts of the attempt (JRK): a `rule(ctx: RiskContext)` that returns a
149
+ level name (and optional signals), or stock `when` rules. It only ever raises, and a fault takes the last
150
+ level."""
151
+ return RiskSpec(levels=tuple(levels), rule=_opt_ref(rule), when=tuple(when), mode=mode) # type: ignore[arg-type]
152
+
153
+
154
+ def Gate(*, check: Callable[..., Any] | None = None, check_timeout_s: int = 1800, # noqa: N802
155
+ judge: JudgeSpec | None = None, criteria: Iterable[Criterion] = (), on_fail: str = "retry",
156
+ on_budget_spent: str = "ask", fallback: str | None = None, approval: bool = False,
157
+ back_targets: Iterable[str] = (), loop_budget: int = 1, retry_budget: int = 2,
158
+ judge_may_skip: Iterable[str] = ()) -> GateSpec:
159
+ return GateSpec(check=_opt_ref(check), check_timeout_s=check_timeout_s, judge=judge, criteria=tuple(criteria),
160
+ on_fail=on_fail, on_budget_spent=on_budget_spent, fallback=fallback, # type: ignore[arg-type]
161
+ approval=approval, back_targets=tuple(back_targets), loop_budget=loop_budget,
162
+ retry_budget=retry_budget, judge_may_skip=tuple(judge_may_skip))
163
+
164
+
165
+ def Script(*, run: Iterable[str] | None = None, call: Callable[..., Any] | None = None, # noqa: N802
166
+ produces: Mapping[str, ProducesKind] | None = None, inputs: Iterable[str] = (),
167
+ side_effects: str = "workspace", timeout_s: int = 600, cache: str = "off",
168
+ environmental_exit_codes: Iterable[int] = (), summary: str = "", gate: GateSpec | None = None,
169
+ name: str = "") -> Any:
170
+ """A script declaration. With ``gate`` it is a script unit; without, a hybrid `before`/`after` script."""
171
+ spec = ScriptSpec(run=tuple(run) if run is not None else None, call=_opt_ref(call), produces=dict(produces or {}),
172
+ inputs=tuple(inputs), side_effects=side_effects, timeout_s=timeout_s, cache=cache, # type: ignore[arg-type]
173
+ environmental_exit_codes=tuple(environmental_exit_codes), summary=summary, name=name)
174
+ if gate is None:
175
+ return spec
176
+ return UnitSpec(kind="script", gate=gate, script=spec)
177
+
178
+
179
+ def Step(*, gate: GateSpec, prompt: str | TextRef = "default", executor: str | None = None, # noqa: N802
180
+ tools: Iterable[str] = (), commands: Iterable[str] = (), produces: Mapping[str, ProducesKind] | None = None,
181
+ model: str | Iterable[str] | None = None, timeout_s: int | None = None, idle_s: int | None = None,
182
+ session_options: SessionOptions | None = None, before: Iterable[ScriptSpec] = (),
183
+ after: Iterable[ScriptSpec] = (), self_check: bool = False, summary: str = "",
184
+ subagent_model: str | None = None, route: Callable[..., Any] | None = None,
185
+ route_targets: Iterable[str] = (), effort: str | None = None, effort_ladder: Iterable[str] = (),
186
+ escalation: EscalationSpec | None = None, sizing: str = "") -> UnitSpec:
187
+ """`effort` is the fixed effort; `effort_ladder` and `escalation` are the evidence-gated ladder (LAD-B9).
188
+ `sizing` is one sentence on why `model` and the effort fit the step's work (SCF-B10)."""
189
+ m: str | tuple[str, ...] | None = model if model is None or isinstance(model, str) else tuple(model)
190
+ if effort is not None:
191
+ if session_options is not None and session_options.effort is not None:
192
+ raise TypeError("Step() takes `effort` once: as a field or in `session_options`")
193
+ session_options = dataclasses.replace(session_options or SessionOptions(), effort=effort) # type: ignore[arg-type]
194
+ step = StepSpec(executor=executor, prompt=prompt, tools=tuple(tools), commands=tuple(commands),
195
+ produces=dict(produces or {}), model=m, timeout_s=timeout_s, idle_s=idle_s,
196
+ session_options=session_options, before=tuple(before), after=tuple(after),
197
+ self_check=self_check, summary=summary, subagent_model=subagent_model,
198
+ effort_ladder=tuple(effort_ladder), escalation=escalation, sizing=sizing)
199
+ return UnitSpec(kind="step", gate=gate, step=step, route=_opt_ref(route), route_targets=tuple(route_targets))
200
+
201
+
202
+ def Route(*, select: Callable[..., Any], targets: Iterable[str], gate: GateSpec | None = None) -> UnitSpec: # noqa: N802
203
+ """A route unit: a pure function of state picks one static forward target or the finalizer (CMP-B10 to CMP-B16)."""
204
+ return UnitSpec(kind="route", gate=gate or GateSpec(), route=callable_ref(select), route_targets=tuple(targets))
205
+
206
+
207
+ def Rearm(*, from_arm: str, to: str, units: Iterable[str], on: Iterable[str] = ("budget_spent",)) -> RearmSpec: # noqa: N802
208
+ """SWM-B7: move a run from arm `from_arm` to the entry of arm `to` when a listed unit ends on `on`."""
209
+ return RearmSpec(from_arm=from_arm, to=to, units=tuple(units), on=tuple(on))
210
+
211
+
212
+ def Switch(*, predicate: Callable[..., Any], arms: Mapping[str, str], default: str, sticky: str = "visit", # noqa: N802
213
+ gate: GateSpec | None = None, mode: str = "route",
214
+ arm_overrides: Mapping[str, Mapping[str, Mapping[str, Any]]] | None = None,
215
+ rearm: Iterable[RearmSpec] = ()) -> UnitSpec:
216
+ """A switch: a pure predicate picks one arm, the default on a fault (CMP-B10 to CMP-B16). `mode="shadow"` records
217
+ the pick and takes the default; `arm_overrides` and `rearm` are SWM-B6, SWM-B7."""
218
+ sw = SwitchSpec(predicate=callable_ref(predicate), arms=dict(arms), default=default, sticky=sticky, # type: ignore[arg-type]
219
+ mode=mode, # type: ignore[arg-type]
220
+ arm_overrides={a: {u: dict(v) for u, v in units.items()}
221
+ for a, units in (arm_overrides or {}).items()},
222
+ rearm=tuple(rearm))
223
+ return UnitSpec(kind="switch", gate=gate or GateSpec(), switch=sw)
224
+
225
+
226
+ class stock: # noqa: N801 - a namespace of the stock measures (CXR-B9)
227
+ """Stock measures for `Measure(name, stock.<measure>(...))`."""
228
+
229
+ @staticmethod
230
+ def fact(unit: str, key: str) -> tuple[str, ...]:
231
+ return ("fact", unit, key)
232
+
233
+ @staticmethod
234
+ def input(name: str) -> tuple[str, ...]:
235
+ return ("input", name)
236
+
237
+ @staticmethod
238
+ def setting(name: str) -> tuple[str, ...]:
239
+ return ("setting", name)
240
+
241
+ @staticmethod
242
+ def count_items(unit: str, key: str) -> tuple[str, ...]:
243
+ return ("count_items", unit, key)
244
+
245
+ @staticmethod
246
+ def count_lines(unit: str, key: str, pattern: str) -> tuple[str, ...]:
247
+ return ("count_lines", unit, key, pattern)
248
+
249
+ @staticmethod
250
+ def changed_paths() -> tuple[str, ...]:
251
+ return ("changed_paths",)
252
+
253
+
254
+ def Measure(name: str, source: tuple[str, ...] | Callable[..., Any]) -> MeasureSpec: # noqa: N802
255
+ """One measure of a complexity switch: a stock measure or a pure, model-free callable (CXR-B7)."""
256
+ if callable(source):
257
+ return MeasureSpec(name=name, call=callable_ref(source))
258
+ return MeasureSpec(name=name, stock=tuple(str(x) for x in source))
259
+
260
+
261
+ def Escalation(*, to: str, stages: Mapping[str, str] | None = None, effort: str | None = None) -> EscalationSpec: # noqa: N802
262
+ """One attempt on the tier above the step's alias, on a repeated trusted blocker only (LAD-B12)."""
263
+ return EscalationSpec(to=to, stages=dict(stages or {}), effort=effort)
264
+
265
+
266
+ def ComplexitySwitch(*, arms: Mapping[str, str], measures: Iterable[MeasureSpec], joins_at: str, # noqa: N802
267
+ rules: str | None = None, size: str | None = None, explore: Mapping[str, Any] | None = None,
268
+ mode: str = "route", arm_overrides: Mapping[str, Mapping[str, Mapping[str, Any]]] | None = None,
269
+ rearm: Iterable[RearmSpec] = (), gate: GateSpec | None = None) -> UnitSpec:
270
+ """A complexity switch (CXR): `arms` run from the simplest to the most detailed, which is the safe arm and
271
+ the default. The engine picks the arm from the measures and the rules file; there is no predicate."""
272
+ names = list(arms)
273
+ sw = SwitchSpec(predicate=None, arms=dict(arms), default=names[-1] if names else "", sticky="run",
274
+ mode=mode, # type: ignore[arg-type]
275
+ arm_overrides={a: {u: dict(v) for u, v in units.items()}
276
+ for a, units in (arm_overrides or {}).items()},
277
+ rearm=tuple(rearm),
278
+ complexity=ComplexitySpec(measures=tuple(measures), joins_at=joins_at, rules=rules, size=size,
279
+ explore=dict(explore) if explore else None))
280
+ return UnitSpec(kind="switch", gate=gate or GateSpec(), switch=sw)
281
+
282
+
283
+ def _later(kind: str) -> Callable[..., UnitSpec]:
284
+ def build(*, gate: GateSpec | None = None, **fields: Any) -> UnitSpec:
285
+ return UnitSpec(kind=kind, gate=gate or GateSpec(), extra=dict(fields)) # type: ignore[arg-type]
286
+
287
+ build.__name__ = kind.title()
288
+ build.__doc__ = f"A `{kind}` unit; refused with `not_in_release` by this engine release (ADR `first-release-is-simple-trusted-workflows-on-one-machine`)."
289
+ return build
290
+
291
+
292
+ def Map(*, items_from: tuple[str, str] | Sequence[str], step: UnitSpec, extract: Callable[..., Any] | None = None, # noqa: N802
293
+ max_items: int = 20, on_empty: str = "stop", mode: str = "sequential", concurrency: int = 3,
294
+ item_model: Callable[..., Any] | None = None, models: Iterable[str] = ()) -> UnitSpec:
295
+ """A map: `step` (built with `Step`) runs once per item of the list at `items_from` (`(unit, key)`), each
296
+ item gated on its own by the step's gate (MAP-B7). Release 2 builds the sequential mode."""
297
+ if step.kind not in ("step", "contest") or step.step is None: # a contest as the item is built, then refused (CTS-B10)
298
+ raise TypeError("Map(step=...) takes a unit built with Step()")
299
+ if step.route is not None:
300
+ raise TypeError("a map's step takes no route")
301
+ unit, key = tuple(items_from)
302
+ m = MapSpec(items_from=(str(unit), str(key)), extract=_opt_ref(extract), max_items=max_items,
303
+ on_empty=on_empty, mode=mode, concurrency=concurrency, # type: ignore[arg-type]
304
+ item_model=_opt_ref(item_model), models=tuple(models))
305
+ return UnitSpec(kind="map", gate=step.gate, step=step.step, map=m, contest=step.contest)
306
+
307
+
308
+ def Question(name: str, text: str, *, kind: str = "text", choices: Iterable[str] = (), required: bool = True, # noqa: N802
309
+ default: Any = None) -> AskQuestion:
310
+ return AskQuestion(name=name, text=text, kind=kind, choices=tuple(choices), required=required, # type: ignore[arg-type]
311
+ default=default)
312
+
313
+
314
+ def Ask(*, questions: Iterable[AskQuestion] = (), questions_from: str | None = None, # noqa: N802
315
+ context: Iterable[str] = (), check: Callable[..., Any] | None = None, deadline_s: int | None = None,
316
+ on_deadline: str = "escalate", gate: GateSpec | None = None) -> UnitSpec:
317
+ """An ask unit: pauses for a person's typed answers and stores them as the `answers` artifact (ASK-B5 to
318
+ ASK-B13). `on_deadline` is `escalate`, `stop`, `defaults` (each unanswered question takes its default) or a
319
+ forward unit."""
320
+ return UnitSpec(kind="ask", gate=gate or GateSpec(), ask=AskSpec(
321
+ questions=tuple(questions), questions_from=questions_from, context=tuple(context), check=_opt_ref(check),
322
+ deadline_s=deadline_s, on_deadline=on_deadline))
323
+
324
+
325
+ def Wait(*, event: str, check: Callable[..., Any], deadline_s: int | None = None, # noqa: N802
326
+ on_deadline: str = "escalate", gate: GateSpec | None = None) -> UnitSpec:
327
+ """An event wait: passes only on `event:<name>=<value>` that `check(value)` accepts (HUM-B4)."""
328
+ return UnitSpec(kind="wait", gate=gate or GateSpec(), wait=WaitSpec(
329
+ event=event, check=callable_ref(check), deadline_s=deadline_s, on_deadline=on_deadline))
330
+
331
+
332
+ def Parallel(*, branches: Iterable[str], gate: GateSpec | None = None) -> UnitSpec: # noqa: N802
333
+ """A parallel block's join: `branches` names two or more read-only units that run at once; the unit runs
334
+ nothing itself and passes when every branch has passed (CMP-B10 to CMP-B16)."""
335
+ return UnitSpec(kind="parallel", gate=gate or GateSpec(), branches=tuple(branches))
336
+
337
+
338
+ def Slot(name: str, *, executor: str | None = None, model: str | None = None, # noqa: N802
339
+ prompt_variant: str | None = None) -> SlotSpec:
340
+ """One candidate slot of a contest (CTS-B6): a slug `name`, and optional `executor`, `model` and `prompt_variant`
341
+ overrides that apply to that slot's step only."""
342
+ return SlotSpec(name=name, executor=executor, model=model, prompt_variant=prompt_variant)
343
+
344
+
345
+ def Contest(*, step: UnitSpec, slots: int | Iterable[SlotSpec] = 3, writes: bool = False, # noqa: N802
346
+ retry_scope: str = "best", concurrency: int = 3, cost_cap_usd: float | None = None) -> UnitSpec:
347
+ """A contest: `step` (built with `Step`) runs in 2 to 5 slots, each graded by the step's own gate, and the best
348
+ candidate by the engine's fixed rule is kept (CTS-B6, CTS-B7). `slots` is a count or a list of `Slot`s."""
349
+ if step.kind != "step" or step.step is None:
350
+ raise TypeError("Contest(step=...) takes a unit built with Step()")
351
+ if step.route is not None:
352
+ raise TypeError("a contest's step takes no route")
353
+ held: int | tuple[SlotSpec, ...] = slots if isinstance(slots, int) else tuple(slots)
354
+ c = ContestSpec(slots=held, writes=writes, retry_scope=retry_scope, # type: ignore[arg-type]
355
+ concurrency=concurrency, cost_cap_usd=cost_cap_usd)
356
+ return UnitSpec(kind="contest", gate=step.gate, step=step.step, contest=c)
357
+
358
+
359
+ def Member(*, name: str, executor: str | None = None, model: str | None = None, stance: str = "", # noqa: N802
360
+ tools: Iterable[str] = (), timeout_s: int | None = None, idle_s: int | None = None) -> MemberSpec:
361
+ """One member of a council (CNL-B9): a unique slug `name`, its own `stance` (up to 400 characters) and read-only
362
+ `tools`; its `executor` and `model` resolve on the step layer when unset."""
363
+ return MemberSpec(name=name, executor=executor, model=model, stance=stance, tools=tuple(tools),
364
+ timeout_s=timeout_s, idle_s=idle_s)
365
+
366
+
367
+ def Chair(*, executor: str | None = None, model: str | None = None, prompt: str = "") -> ChairSpec: # noqa: N802
368
+ """The chair of a council (CNL-B9): it writes the synthesis (or a vote's rationale) from the members' final positions."""
369
+ return ChairSpec(executor=executor, model=model, prompt=prompt)
370
+
371
+
372
+ def Council(*, question: str | TextRef, members: Iterable[MemberSpec], mode: str = "synthesize", # noqa: N802
373
+ options: Iterable[str] | str | None = None, rule: str | None = None, rounds: int = 0,
374
+ anonymize: bool = True, chair: ChairSpec | None = None, quorum: int | None = None,
375
+ on_no_decision: str = "escalate", retry_scope: str = "all", cost_cap_usd: float | None = None,
376
+ gate: GateSpec | None = None) -> UnitSpec:
377
+ """A council unit (CNL-B9): `members` answer `question` blind, `rounds` deliberation rounds follow, and the outcome
378
+ is a chair's synthesis (`synthesize`), a tally of votes by `rule` (`vote`) or a Borda count of peer rankings
379
+ (`rank`). `options` (a `vote`'s slugs, or an artifact key of a list) and `rule` belong to `vote` only."""
380
+ spec = CouncilSpec(question=question, members=tuple(members), mode=mode, # type: ignore[arg-type]
381
+ options=options if options is None or isinstance(options, str) else tuple(options),
382
+ rule=rule, rounds=rounds, anonymize=anonymize, chair=chair, quorum=quorum, # type: ignore[arg-type]
383
+ on_no_decision=on_no_decision, retry_scope=retry_scope, # type: ignore[arg-type]
384
+ cost_cap_usd=cost_cap_usd)
385
+ return UnitSpec(kind="council", gate=gate or GateSpec(), council=spec)
386
+
387
+ _INPUT_REF_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*$")
388
+
389
+
390
+ def _input_form(name: str, value: object) -> str:
391
+ """SWF-B7: a child parameter is read from `request`, `<unit>.<key>` or a quoted literal, and nothing else."""
392
+ if isinstance(value, str) and (value == "request" or _INPUT_REF_RE.match(value)
393
+ or (len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'")):
394
+ return value
395
+ raise ValueError(f"Subworkflow(inputs=...): {name!r} reads {value!r}; write `request`, `<unit>.<key>` "
396
+ "or a quoted literal")
397
+
398
+
399
+ def Subworkflow(*, workflow: str, requires: str | None = None, inputs: Mapping[str, str] | None = None, # noqa: N802
400
+ produces: Iterable[str] = (), gate: GateSpec | None = None, summary: str = "") -> UnitSpec:
401
+ """A sub-workflow unit: the registered workflow `workflow` runs as one unit of the parent (SWF-B7).
402
+ `inputs` maps each child parameter to `request`, `<unit>.<key>` or a quoted literal; `produces` names the child
403
+ keys the parent's later units see as `{<unit>.<key>}`."""
404
+ rec = SubworkflowSpec(workflow=workflow, requires=requires,
405
+ inputs={str(k): _input_form(str(k), v) for k, v in (inputs or {}).items()},
406
+ produces=tuple(produces), summary=summary)
407
+ return UnitSpec(kind="subworkflow", gate=gate or GateSpec(), subworkflow=rec)
408
+
409
+
410
+ _WORKFLOW_FIELDS = {f for f in WorkflowSpec.__dataclass_fields__} - {"name", "version", "package_root", "outcome"}
411
+
412
+
413
+ def Workflow(*, order: Iterable[str], units: Mapping[str, UnitSpec], **fields: Any) -> WorkflowSpec: # noqa: N802
414
+ """Build a `WorkflowSpec`. `name` and `version` come from the manifests (PKG-B13, PKG-B2)."""
415
+ for banned in ("name", "version"):
416
+ if banned in fields:
417
+ raise TypeError(f"Workflow() got an unexpected keyword argument '{banned}' "
418
+ f"(it comes from the package manifests)")
419
+ unknown = set(fields) - _WORKFLOW_FIELDS
420
+ if unknown:
421
+ raise TypeError(f"Workflow() got an unexpected keyword argument '{sorted(unknown)[0]}'")
422
+ for key in ("finalizer", "command_resolver"):
423
+ if key in fields and fields[key] is not None:
424
+ fields[key] = callable_ref(fields[key])
425
+ for key in ("finalizer_outcomes", "allow_commands"):
426
+ if key in fields:
427
+ fields[key] = tuple(fields[key])
428
+ return WorkflowSpec(name="", order=tuple(order), units=dict(units), **fields)