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,747 @@
1
+ """The gate node's decision and the human node's decisions (HUM-B2, BUD-B8, BUD-B9, BUD-B3, B4; CMP routing).
2
+
3
+ `decide` is pure: it reads the unit's attempt record, its judge outcome and its counters, and returns the
4
+ state write that routes the run. It never pauses; a pause is the human node's.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from collections.abc import Mapping, Sequence
11
+ from datetime import UTC, datetime, timedelta
12
+ from typing import Any
13
+
14
+ from tempergraph.contracts import Decision, RouteView, UnitSpec, Verdict, WorkflowSpec
15
+ from tempergraph.model import flow
16
+ from tempergraph.run import contest as contestmod
17
+ from tempergraph.run import ladder as laddermod
18
+ from tempergraph.run import mapping
19
+ from tempergraph.security.scrub import scrub
20
+
21
+ ESCALATE_CAUSES = frozenset({"auth", "refused", "tool_access", "environmental", "blocked", "upstream",
22
+ "workflow_fault", "check_repeat", "merge_conflict", "map_check", "no_decision",
23
+ "usage_limit", "command_killed"})
24
+ HUMAN_CAP = 100
25
+ BLOCKERS_SHOWN = 20
26
+ BLOCKER_CHARS = 1000
27
+ BLOCKER_TEXT = ("criterion", "place", "problem", "fix")
28
+ REASON_OPTION = "--reason <engine_defect|judge_error|environment|plan|request|other>" # CLI-B24, CLI-B30, HUM-B20
29
+
30
+
31
+ def clear_from(spec: WorkflowSpec, unit: str, state: Mapping[str, Any] | None = None) -> dict[str, Any]:
32
+ """BUD-B4: delete verdicts, judgements, artifacts, values and facts of ``unit`` and every later unit.
33
+
34
+ Every later unit that already ran gets a new visit, so its next entry is recorded as one (EVT-B10 to EVT-B16)."""
35
+ order = flow.effective_order(spec)
36
+ block = unit if unit in spec.units and spec.units[unit].kind == "parallel" else flow.block_of(spec, unit)
37
+ first = min((order.index(b) for b in spec.units[block].branches if b in order), default=None) if block else None
38
+ start = first if first is not None else order.index(unit) if unit in order else None
39
+ later = list(order[start:]) if start is not None else [unit] # a block is cleared from its first branch
40
+ out: dict[str, Any] = {k: {u: None for u in later} for k in ("artifacts", "values", "facts", "judgements")}
41
+ out["counters"] = {u: {"retries": 0, "infra": 0, "command_killed": 0} for u in later}
42
+ attempts = (state or {}).get("attempts") or {}
43
+ visits = (state or {}).get("visits") or {}
44
+ out["visits"] = {u: {"visit": int((visits.get(u) or {}).get("visit", 1)) + 1, "entered_from": "proceed"}
45
+ for u in later if u != unit and attempts.get(u)}
46
+ return out
47
+
48
+
49
+ class RouteFault(Exception):
50
+ """A route function raised or returned a name that is not one of its targets (CMP-B3)."""
51
+
52
+
53
+ def route_view(unit: str, state: Mapping[str, Any]) -> RouteView:
54
+ """What a route or switch function sees: step values, check facts and artifact keys, never prose."""
55
+ values: dict[str, str] = {}
56
+ for vals in (state.get("values") or {}).values():
57
+ if isinstance(vals, dict):
58
+ values.update({str(k): str(v) for k, v in vals.items()})
59
+ facts = {u: {str(k): str(v) for k, v in f.items()} for u, f in (state.get("facts") or {}).items()
60
+ if isinstance(f, dict)}
61
+ keys = sorted({str(k) for arts in (state.get("artifacts") or {}).values() if isinstance(arts, dict) for k in arts})
62
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
63
+ return RouteView(unit=unit, visit=visit, values=values, facts=facts, artifact_keys=tuple(keys), settings={})
64
+
65
+
66
+ def pick(spec: WorkflowSpec, unit: str, state: Mapping[str, Any]) -> dict[str, Any] | None:
67
+ """CMP-B10 to CMP-B16: the forward target a step's route, a route unit or a switch picks, as the `route` record's
68
+ fields; None when the unit routes by `order`. A route fault raises `RouteFault`; a switch fault takes the
69
+ default arm. A switch's pick is reused within a visit (`sticky: visit`) or for the run (`sticky: run`)."""
70
+ u = spec.units[unit]
71
+ view = route_view(unit, state)
72
+ if u.switch is not None:
73
+ return _switch_pick(spec, unit, state, view)
74
+ if u.route is None:
75
+ return None
76
+ try:
77
+ got = u.route.resolve()(view)
78
+ except Exception as exc: # noqa: BLE001 - a raise stops the run, never falls back to `order`
79
+ raise RouteFault(f"route {u.route.ref} raised {type(exc).__name__}") from None
80
+ if not isinstance(got, str) or got not in u.route_targets:
81
+ raise RouteFault(f"route {u.route.ref} returned {got!r}, not one of {list(u.route_targets)}")
82
+ out = {"arm": got, "target": flow.through_outcome(spec, got), "chosen_by": "predicate", "visit": view.visit}
83
+ signals, clipped = _signals(view.values) # the step values the route read, so a report can say why (L-25)
84
+ if signals:
85
+ out["signals"] = signals
86
+ if clipped:
87
+ out["signals_clipped"] = clipped
88
+ return out
89
+
90
+
91
+ SIGNALS_MAX, SIGNAL_CHARS = 10, 60
92
+ COMPLEXITY_FIELDS = ("zone", "measures", "rules_digest", "rules_source", "rules_error")
93
+
94
+
95
+ def _signals(raw: Any) -> tuple[dict[str, Any], int]:
96
+ """SWM-B4: at most 10 names to numbers or strings of at most 60 characters; the rest is clipped and counted."""
97
+ if not isinstance(raw, Mapping):
98
+ return {}, 0
99
+ out: dict[str, Any] = {}
100
+ clipped = 0
101
+ for k, v in raw.items():
102
+ if len(out) >= SIGNALS_MAX:
103
+ clipped += 1
104
+ continue
105
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
106
+ v = str(v)
107
+ if len(v) > SIGNAL_CHARS:
108
+ v, clipped = v[:SIGNAL_CHARS], clipped + 1
109
+ out[str(k)[:SIGNAL_CHARS]] = v
110
+ return out, clipped
111
+
112
+
113
+ def _switch_pick(spec: WorkflowSpec, unit: str, state: Mapping[str, Any], view: RouteView) -> dict[str, Any]:
114
+ """A switch's pick with what the predicate would choose (SWM-B5). The operator's arm wins in either mode
115
+ (CMP-B7); shadow mode and any predicate fault take the default; a re-armed pick is never made again."""
116
+ u = spec.units[unit]
117
+ sw = u.switch
118
+ assert sw is not None
119
+ prior = ((state.get("route") or {}).get(unit) or {}).get("pick")
120
+ if prior and (prior.get("chosen_by") == "rearm" or sw.sticky == "run" or prior.get("visit") == view.visit):
121
+ return dict(prior)
122
+ would: str | None = None
123
+ fault: str | None = None
124
+ signals: dict[str, Any] = {}
125
+ clipped = 0
126
+ measured: dict[str, Any] = {}
127
+ if sw.complexity is not None: # CXR-B10, CXR-B1: the step node evaluated the rules once; the gate reads the result
128
+ measured = dict(((state.get("attempts") or {}).get(unit) or {}).get("complexity") or {})
129
+ would = measured.get("arm") if measured.get("arm") in sw.arms else None
130
+ if would is None:
131
+ fault = "not_evaluated"
132
+ else:
133
+ try:
134
+ assert sw.predicate is not None
135
+ got = sw.predicate.resolve()(view)
136
+ if isinstance(got, tuple) and len(got) == 2:
137
+ got, raw = got
138
+ signals, clipped = _signals(raw)
139
+ would = str(got) if str(got) in sw.arms else None
140
+ if would is None:
141
+ fault = "unknown_arm"
142
+ except Exception as exc: # noqa: BLE001 - a predicate fault takes the default arm
143
+ fault = type(exc).__name__
144
+ shadow = sw.mode == "shadow"
145
+ operator = u.extra.get("arm")
146
+ if operator in sw.arms:
147
+ arm, by = str(operator), "operator"
148
+ elif shadow or would is None:
149
+ arm, by = sw.default, "default"
150
+ else:
151
+ arm, by = would, "predicate"
152
+ p: dict[str, Any] = {"arm": arm, "target": flow.through_outcome(spec, sw.arms[arm]), "chosen_by": by,
153
+ "visit": view.visit, "shadow": shadow, "would_choose": would}
154
+ if signals:
155
+ p["signals"] = signals
156
+ if clipped:
157
+ p["signals_clipped"] = clipped
158
+ if fault:
159
+ p["fault"] = fault
160
+ p.update({k: measured[k] for k in COMPLEXITY_FIELDS if k in measured})
161
+ return p
162
+
163
+
164
+ def arm_overrides(spec: WorkflowSpec, unit: str, state: Mapping[str, Any]) -> tuple[dict[str, Any], str]:
165
+ """SWM-B6: the override values of the arm in force that names `unit`, and their layer `arm:<switch>.<arm>`."""
166
+ for name, other in spec.units.items():
167
+ sw = other.switch
168
+ if sw is None or not sw.arm_overrides:
169
+ continue
170
+ p = ((state.get("route") or {}).get(name) or {}).get("pick") or {}
171
+ values = (sw.arm_overrides.get(str(p.get("arm"))) or {}).get(unit)
172
+ if values:
173
+ return dict(values), f"arm:{name}.{p.get('arm')}"
174
+ return {}, ""
175
+
176
+
177
+ def _rearm(spec: WorkflowSpec, unit: str, state: Mapping[str, Any], cause: str) -> tuple[str, Any] | None:
178
+ """The switch and re-arm entry that apply to `unit` ending on `cause`, once per switch and run (SWM-B7)."""
179
+ for name, other in spec.units.items():
180
+ sw = other.switch
181
+ stored = (state.get("route") or {}).get(name) or {}
182
+ p = stored.get("pick") or {}
183
+ if sw is None or not p or stored.get("rearmed"):
184
+ continue
185
+ for r in sw.rearm:
186
+ if r.from_arm == p.get("arm") and unit in r.units and cause in r.on:
187
+ return name, r
188
+ return None
189
+
190
+
191
+ def _merge(*writes: Mapping[str, Any]) -> dict[str, Any]:
192
+ out: dict[str, Any] = {}
193
+ for w in writes:
194
+ for ch, val in w.items():
195
+ if isinstance(val, dict) and isinstance(out.get(ch), dict):
196
+ out[ch] = {**out[ch], **val}
197
+ else:
198
+ out[ch] = val
199
+ return out
200
+
201
+
202
+ def contest_retry(spec: WorkflowSpec, unit: str, state: Mapping[str, Any]) -> dict[str, Any]:
203
+ """CTS-B8, CTS-B4: the state write that goes with a RETRY of a contest. Under `retry_scope: best` the winner's slot alone
204
+ runs again and the contest is a single step for the rest of the visit, however many slots were RETRY (the retry
205
+ budget is charged once, by the gate, as for any unit); under `all` every slot runs again. Nothing for other units."""
206
+ if not flow.is_contest(spec, unit):
207
+ return {}
208
+ return contestmod.retry_write(unit, spec.units[unit].contest.retry_scope, # type: ignore[union-attr]
209
+ (mapping.record(state, unit).get("pick") or {}).get("winner"))
210
+
211
+
212
+ def _json_or(raw: Any) -> Any:
213
+ try:
214
+ return json.loads(str(raw))
215
+ except ValueError:
216
+ return raw
217
+
218
+
219
+ def council_options(state: Mapping[str, Any], unit: str) -> list[str]:
220
+ """What a person may answer at a council's no-decision pause: a `vote`'s options, a `rank`'s labels; a `synthesize`
221
+ council takes any text (CNL-B13)."""
222
+ held = ((state.get("attempts") or {}).get(unit) or {}).get("council") or {}
223
+ if held.get("mode") == "rank":
224
+ return sorted(str(v) for v in (held.get("labels") or {}).values())
225
+ return [str(o) for o in held.get("options") or ()]
226
+
227
+
228
+ def check_council_answer(spec: WorkflowSpec, unit: str, state: Mapping[str, Any], answers: Mapping[str, Any]) -> str:
229
+ """CNL-B13, ASK-B8: `answer:decision=<option>` at a council's no-decision pause. Returns the chosen decision, or
230
+ refuses before anything is written."""
231
+ u = spec.units[unit]
232
+ pause = (state.get("pause") or {}).get(unit) or {}
233
+ if u.kind != "council" or pause.get("reason") != "no_decision":
234
+ raise DecisionRefused("answer: is only accepted at an ask, or at a council's no-decision pause")
235
+ extra = sorted(k for k in answers if k != "decision")
236
+ if extra:
237
+ raise DecisionRefused(f"a council's pause takes answer:decision=<option>, not {', '.join(extra)}")
238
+ value = str(answers.get("decision") or "").strip()
239
+ options = council_options(state, unit)
240
+ if not value or (options and value not in options):
241
+ raise DecisionRefused(f"answer:decision={value or ''}: pick one of {', '.join(options) or 'a non-empty decision'}")
242
+ return value
243
+
244
+
245
+ def retry_scope(u: UnitSpec, att: Mapping[str, Any]) -> str | None:
246
+ """CNL-B7: `chair` when this gate's RETRY of a council with `retry_scope: chair` reruns only the chair, which needs
247
+ the members' final positions of an attempt that reached an outcome; None for every other retry (so the step node
248
+ reads the scope from the route and a stale one is deleted)."""
249
+ c = u.council
250
+ held = att.get("council") or {}
251
+ if c is None or c.retry_scope != "chair" or c.mode == "vote" or c.chair is None:
252
+ return None
253
+ return "chair" if held.get("outcome") not in (None, "no_decision") else None
254
+
255
+
256
+ def resume_command(spec: WorkflowSpec, task_id: str, decisions: list[str], unit: str | None = None) -> str:
257
+ named = f" --unit {unit}" if unit else "" # a pause of one item of a concurrent map is answered by `<unit>.<item>`
258
+ return f"tempergraph resume {spec.name} {task_id}{named} --decision <{'|'.join(decisions)}> {REASON_OPTION}"
259
+
260
+
261
+ def pause_payload(spec: WorkflowSpec, unit: str, kind: str, reason: str, state: Mapping[str, Any],
262
+ task_id: str, blockers: list[dict[str, Any]] | None = None) -> dict[str, Any]:
263
+ u = spec.units[unit]
264
+ s = flow.successors(spec, unit)
265
+ words = ["proceed", "retry"] + [f"back:{t}" for t in u.gate.back_targets] + ["stop"]
266
+ if kind == "approval":
267
+ words = ["proceed", "retry", "stop"]
268
+ arts = sorted(((state.get("artifacts") or {}).get(unit) or {}).keys())
269
+ rubric = [{"n": i, "id": c.id, "text": c.text, "severity": c.severity} for i, c in enumerate(u.gate.criteria, 1)]
270
+ ws = state.get("workspace") or {}
271
+ del s
272
+ item = ((state.get("attempts") or {}).get(unit) or {}).get("item") # a map's item in hand (MAP-B8, MAP-B9, MAP-B10)
273
+ at = (mapping.item_in_hand(state) or {}).get("slot") # an item of a concurrent map: its pause is addressed by slot
274
+ listed = list(blockers or []) # HUM-B22: at most BLOCKERS_SHOWN, each text field scrubbed and cut
275
+ shown = [{k: (_bounded(v) if k in BLOCKER_TEXT and isinstance(v, str) else v) for k, v in dict(b).items()}
276
+ for b in listed[:BLOCKERS_SHOWN]]
277
+ out = {"kind": kind, "unit": unit, "item": item, "reason": reason, "artifacts": arts, "rubric": rubric,
278
+ "blockers": shown, "blockers_left_out": max(0, len(listed) - BLOCKERS_SHOWN), "decisions": words, "workspace": ws.get("path"),
279
+ "resume": resume_command(spec, task_id, words, at)}
280
+ if at:
281
+ out["slot"] = at
282
+ if u.kind == "contest": # CTS-B7: the pause is about the winner's candidate, whose verdict is the unit's
283
+ out["winner"] = (mapping.record(state, unit).get("pick") or {}).get("winner")
284
+ if kind == "input": # ASK-B8: each question with its kind, choices, default and whether it is answered
285
+ qs = list(((state.get("attempts") or {}).get(unit) or {}).get("questions") or [])
286
+ out["questions"] = [{**q, "answered": False} for q in qs]
287
+ out["context"] = list(u.ask.context) if u.ask else []
288
+ out["decisions"] = ["answer:<name>=<value>", "proceed", "stop"]
289
+ out["resume"] = (f"tempergraph resume {spec.name} {task_id} --decision answer:<name>=<value> "
290
+ f"[--decision answer:...] [--decision proceed] {REASON_OPTION}")
291
+ elif kind == "event_wait" and u.wait is not None:
292
+ out["event"] = u.wait.event
293
+ out["decisions"] = [f"event:{u.wait.event}=<value>", "stop"]
294
+ out["resume"] = f"tempergraph resume {spec.name} {task_id} --decision event:{u.wait.event}=<value> {REASON_OPTION}"
295
+ dl = flow.deadline_of(spec, unit)
296
+ if dl is not None and kind in ("input", "event_wait"): # FLX-B8: overdue once this time has passed
297
+ out["deadline_at"] = (datetime.now(UTC) + timedelta(seconds=dl[0])).isoformat(timespec="seconds")
298
+ out["on_deadline"] = dl[1]
299
+ if reason == "no_decision" and u.kind == "council": # CNL-B13: the pause shows what the members said and how it was counted
300
+ held = (state.get("values") or {}).get(unit) or {}
301
+ out["positions"] = _json_or(held.get("positions"))
302
+ out["tally"] = _json_or(held.get("tally"))
303
+ out["decisions"] = ["answer:decision=<option>", "retry", "stop"]
304
+ out["options"] = council_options(state, unit)
305
+ out["resume"] = f"tempergraph resume {spec.name} {task_id} --decision answer:decision=<option> --reason <engine_defect|judge_error|environment|plan|request|other>"
306
+ if reason.startswith("guard:"): # HUM-B23: what broke the guard, never a command text
307
+ facts = ((state.get("judgements") or {}).get(unit) or {}).get("guard_facts")
308
+ if facts:
309
+ out["guard"] = dict(facts)
310
+ if reason == "tool_access": # each refused or missing name and what fixes it (RST-B28, RST-B29, RST-B30)
311
+ out["tool_access"] = list((((state.get("attempts") or {}).get(unit) or {}).get("tool_access")) or [])
312
+ if reason == "check_repeat": # BUD-B16: the failing findings the check returned twice in a row
313
+ held = (state.get("attempts") or {}).get(unit) or {}
314
+ out["repeated"] = list(held.get("repeated") or [])
315
+ if not out["repeated"]: # a check with no findings repeats on its evidence text
316
+ out["repeated_evidence"] = str(held.get("repeated_evidence") or "")[:400]
317
+ if reason == "command_killed": # KIL-B6: each killed command's facts, no argument text
318
+ out["command_killed"] = list((((state.get("attempts") or {}).get(unit) or {}).get("command_killed")) or [])
319
+ if reason == "usage_limit": # BUD-B17, HUM-B14: the instant the session returned, and a resume with no decision
320
+ held = (state.get("attempts") or {}).get(unit) or {}
321
+ out["usage_limit_resets_at"] = held.get("usage_limit_resets_at")
322
+ out["resume"] = f"tempergraph resume {spec.name} {task_id}" + (f" --unit {at}" if at else "")
323
+ if kind == "approval" and u.extra.get("sign_off"):
324
+ out["sign_off"] = list(u.extra["sign_off"]) # person criteria to sign (OUT-B15, OUT-B16, OUT-B17, OUT-B4)
325
+ return out
326
+
327
+
328
+ def _bounded(text: str) -> str:
329
+ """HUM-B22: scrubbed and cut to BLOCKER_CHARS with a final `…`; the lines of a fix or a problem are kept."""
330
+ one = scrub(text)
331
+ return one if len(one) <= BLOCKER_CHARS else one[:BLOCKER_CHARS - 1] + "…"
332
+
333
+
334
+ def _finding_line(b: Mapping[str, Any]) -> str:
335
+ """HUM-B16: the criterion, the place, the message and the fix of one finding, and nothing else."""
336
+ head = f"[{b['criterion']}]" if b.get("criterion") else ""
337
+ if b.get("place"):
338
+ head = f"{head} {b['place']}".strip()
339
+ line = f"{head}: {b['problem']}" if head and b.get("problem") else head or str(b.get("problem") or "")
340
+ if b.get("fix"):
341
+ line += f" (fix: {b['fix']})"
342
+ return line
343
+
344
+
345
+ def decide(spec: WorkflowSpec, unit: str, state: Mapping[str, Any], task_id: str) -> dict[str, Any]:
346
+ u: UnitSpec = spec.units[unit]
347
+ g = u.gate
348
+ s = flow.successors(spec, unit)
349
+ att = (state.get("attempts") or {}).get(unit) or {}
350
+ judged = (state.get("judgements") or {}).get(unit) or {}
351
+ counters = dict((state.get("counters") or {}).get(unit) or {})
352
+ retries = int(counters.get("retries", 0))
353
+ loops = dict(counters.get("loops") or {})
354
+
355
+ def route(token: str, node: str, **extra: Any) -> dict[str, Any]:
356
+ return {"route": {unit: {"token": token, "node": node, **extra}}}
357
+
358
+ def to_human(kind: str, reason: str, **extra: Any) -> dict[str, Any]:
359
+ payload = pause_payload(spec, unit, kind, reason, state, task_id, judged.get("blockers"))
360
+ return _merge(route("ESCALATE", s.escalate[0], kind=kind, **extra), {"pause": {unit: payload}})
361
+
362
+ def rearm(cause: str) -> dict[str, Any] | None:
363
+ """A trip back to the entry of the safer arm in place of the gate's own policy (SWM-B7)."""
364
+ found = _rearm(spec, unit, state, cause)
365
+ if found is None:
366
+ return None
367
+ name, r = found
368
+ sw = spec.units[name].switch
369
+ assert sw is not None
370
+ if sw.complexity is not None and cause == "budget_spent" and laddermod.classify(att, judged).evidence is None:
371
+ return None # CXR-B4, CXR-B11, CXR-B7: a budget spent on held causes keeps the gate's own policy
372
+ entry = sw.arms[r.to]
373
+ prior = ((state.get("route") or {}).get(name) or {}).get("pick") or {}
374
+ visits = (state.get("visits") or {}).get(entry) or {}
375
+ loops[entry] = int(loops.get(entry, 0)) + 1
376
+ p = {"arm": r.to, "target": entry, "chosen_by": "rearm", "visit": prior.get("visit", 1),
377
+ "shadow": False, "would_choose": prior.get("would_choose"), "rearmed_from": r.from_arm,
378
+ "rearm_unit": unit, "rearm_cause": cause, **{k: prior[k] for k in COMPLEXITY_FIELDS if k in prior}}
379
+ return _merge(clear_from(spec, entry, state), route("BACK", flow.entry_node(spec, entry), rearm=name),
380
+ {"route": {name: {"pick": p, "rearmed": True}},
381
+ "counters": {unit: {**counters, "retries": 0, "infra": 0, "loops": loops}},
382
+ "visits": {entry: {"visit": int(visits.get("visit", 1)) + 1,
383
+ "reason": f"re-armed from {r.from_arm} to {r.to} ({cause})", "from": unit,
384
+ "entered_from": f"rearm:{unit}"}}})
385
+
386
+ def fallback(reason: str) -> dict[str, Any]:
387
+ """FLX-B9: forward to the fallback target with the reason; the failed unit's artifacts are kept."""
388
+ node = flow.fallback_node(spec, unit)
389
+ assert node is not None and g.fallback is not None
390
+ why = "; ".join(b.get("problem", "") for b in judged.get("blockers") or [] if b.get("problem"))
391
+ w = _merge(route("FALLBACK", node, fallback=g.fallback, reason=reason),
392
+ {"attempts": {unit: {"failed": True}},
393
+ "run": {"degraded": {"unit": unit, "reason": reason, "to": g.fallback}}})
394
+ if g.fallback != flow.FINALIZER:
395
+ w["feedback"] = {g.fallback: {"text": f"`{unit}` did not pass ({reason})." + (f" {why}" if why else ""),
396
+ "as": "notes"}}
397
+ return w
398
+
399
+ def spent(reason: str) -> dict[str, Any]:
400
+ if reason == "retry_budget":
401
+ w = rearm("budget_spent")
402
+ if w is not None:
403
+ return w
404
+ if g.on_budget_spent == "fallback" and g.fallback:
405
+ return fallback(reason)
406
+ if g.on_budget_spent == "stop":
407
+ return _merge(route("STOP", s.stop[0]), {"run": {"stopped": {"reason": "budget", "unit": unit,
408
+ "detail": reason}}})
409
+ return to_human("budget", reason)
410
+
411
+ if u.kind == "ask":
412
+ if att.get("ask_fault"): # ASK-B2: a list that cannot be used stops the unit before its pause
413
+ return _merge(route("STOP", s.stop[0]), {"run": {"stopped": {"reason": "ask", "unit": unit,
414
+ "detail": att.get("ask_fault")}}})
415
+ return to_human("input", "input")
416
+ if u.kind == "wait":
417
+ return to_human("event_wait", "event_wait")
418
+ if att.get("map_fault"): # the list could not be used: stop before any item (MAP-B8, MAP-B9, MAP-B10 row 1, MAP-B5)
419
+ return _merge(route("STOP", s.stop[0]), {"run": {"stopped": {"reason": "map", "unit": unit,
420
+ "detail": att.get("map_fault")}}})
421
+ if att.get("infra_spent"):
422
+ return _merge(route("STOP", s.stop[0]), {"run": {"stopped": {"reason": "infra", "unit": unit,
423
+ "detail": att.get("infra_cause")}}})
424
+ if att.get("council_stop"): # CNL-B13: no decision with `on_no_decision: stop`
425
+ return _merge(route("STOP", s.stop[0]), {"run": {"stopped": {"reason": "no_decision", "unit": unit,
426
+ "detail": "on_no_decision: stop"}}})
427
+ cause = att.get("escalate")
428
+ if cause in ESCALATE_CAUSES:
429
+ return to_human("escalation", str(cause))
430
+ if att.get("timed_out") and not att.get("slow_host"): # a step timeout re-arms at once (SWM-B7)
431
+ w = rearm("timeout")
432
+ if w is not None:
433
+ return w
434
+ verdict = judged.get("verdict", str(Verdict.ESCALATE))
435
+ if verdict == Verdict.RETRY and att.get("escalated"): # LAD-B12: a failed escalated attempt ends it
436
+ return spent("escalation")
437
+ if verdict == Verdict.RETRY and g.on_fail == "fallback" and g.fallback: # a hard failure, no retry
438
+ return fallback("failed")
439
+ if verdict == Verdict.RETRY and g.on_fail == "stop":
440
+ return _merge(route("STOP", s.stop[0]), {"run": {"stopped": {"reason": "failed", "unit": unit,
441
+ "detail": "on_fail: stop"}}})
442
+ if verdict == Verdict.RETRY:
443
+ if retries < g.retry_budget:
444
+ counters["retries"] = retries + 1
445
+ ov = arm_overrides(spec, unit, state)[0]
446
+ step = laddermod.decide(u, att, judged, counters, ov)
447
+ scope = retry_scope(u, att) # CNL-B7: every unmet blocker of a council's gate concerns `decision`
448
+ if step is None:
449
+ return _merge(route("RETRY", s.retry[0], scope=scope), {"counters": {unit: counters}},
450
+ contest_retry(spec, unit, state))
451
+ counters["ladder"] = {k: step[k] for k in ("visit", "item", "rung", "evidence", "held_by", "trail",
452
+ "escalated")}
453
+ esc = laddermod.escalation(u, step, judged, retry_left=True, overrides=ov,
454
+ rearm_available=_rearm(spec, unit, state, "budget_spent") is not None)
455
+ shown = {k: v for k, v in step.items() if k not in ("trail", "escalated")}
456
+ if esc is not None:
457
+ shown["escalation"] = esc
458
+ if esc and esc["take"] == "offer": # LAD-B12: a person chooses; no retry is spent yet
459
+ counters["retries"] = retries
460
+ counters["ladder"]["offer"] = {k: esc[k] for k in ("to", "effort", "criteria")}
461
+ w = to_human("budget", "escalation_offer", ladder=shown)
462
+ w["pause"][unit]["escalation"] = {**counters["ladder"]["offer"], "judge_state": esc["judge_state"],
463
+ "command": f"tempergraph resume {spec.name} {task_id} --escalate"}
464
+ return _merge(w, {"counters": {unit: counters}})
465
+ if esc and esc["take"] == "auto":
466
+ counters["ladder"].update(escalate={"to": esc["to"], "effort": esc["effort"], "taken_by": "auto"},
467
+ escalated=True)
468
+ return _merge(route("RETRY", s.retry[0], ladder=shown), {"counters": {unit: counters}},
469
+ contest_retry(spec, unit, state))
470
+ return spent("retry_budget")
471
+ if verdict == Verdict.BACK:
472
+ target = judged.get("back_to")
473
+ if not target or target not in g.back_targets:
474
+ return to_human("escalation", "back_target_not_allowed")
475
+ if int(loops.get(target, 0)) >= g.loop_budget:
476
+ return spent("loop_budget")
477
+ loops[target] = int(loops.get(target, 0)) + 1
478
+ visits = (state.get("visits") or {}).get(target) or {}
479
+ if g.judge is None and g.on_fail == "back": # HUM-B16: one numbered line for each finding
480
+ reason = "\n".join(f"{n}. {_finding_line(b)}" for n, b in enumerate(judged.get("blockers") or [], 1)) \
481
+ or "sent back"
482
+ else:
483
+ reason = "; ".join(b.get("problem", "") for b in judged.get("blockers") or []) or "sent back"
484
+ return _merge(clear_from(spec, target, state),
485
+ route("BACK", flow.entry_node(spec, target)),
486
+ {"counters": {unit: {**counters, "retries": 0, "infra": 0, "loops": loops}},
487
+ "visits": {target: {"visit": int(visits.get("visit", 1)) + 1, "reason": reason, "from": unit,
488
+ "entered_from": f"back:{unit}"}}})
489
+ if verdict == Verdict.PROCEED:
490
+ try: # the route is picked before any approval pause (CMP-B10 to CMP-B16)
491
+ p = pick(spec, unit, state)
492
+ except RouteFault as exc:
493
+ return _merge(route("STOP", s.stop[0]), {"run": {"stopped": {"reason": "route", "unit": unit,
494
+ "detail": str(exc)}}})
495
+ extra = {"pick": p} if p else {}
496
+ if mapping.concurrent(spec, unit) and att.get("item"): # an item of a concurrent map has passed (MAP-B10)
497
+ if g.approval:
498
+ return to_human("approval", "approval", **extra)
499
+ return _merge(route("NEXT", s.retry[0], item=att.get("item")), mapping.passed_item_write(unit, att["item"]))
500
+ if g.approval and not att.get("map_done"): # a concurrent map's approval was given item by item
501
+ return to_human("approval", "approval", **extra)
502
+ nxt = mapping.advance(spec, unit, state)
503
+ if nxt is not None: # a map's next item runs the unit's own step node again (MAP-B8, MAP-B9, MAP-B10)
504
+ return _merge(route("NEXT", s.retry[0], item=att.get("item")), nxt)
505
+ return _merge(route("PROCEED", flow.entry_node(spec, p["target"]) if p else s.proceed[0], **extra),
506
+ mapping.passed_write(spec, unit, state))
507
+ return to_human("escalation", judged.get("reason") or "escalate")
508
+
509
+
510
+ # ---------------------------------------------------------------------------------------------
511
+ # Human decisions (HUM-B12)
512
+
513
+
514
+ class DecisionRefused(ValueError):
515
+ pass
516
+
517
+
518
+ def _killed_pause(state: Mapping[str, Any], unit: str) -> bool:
519
+ pause = (state.get("pause") or {}).get(unit) or {}
520
+ return pause.get("kind") == "escalation" and pause.get("reason") == "command_killed"
521
+
522
+
523
+ def check_decision(spec: WorkflowSpec, unit: str, state: Mapping[str, Any], d: Decision, *,
524
+ human_cap: int = HUMAN_CAP, command_killed_cap: int = 2) -> None:
525
+ """HUM-B13: refuse before anything is written."""
526
+ g = spec.units[unit].gate
527
+ path = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
528
+ u = spec.units[unit]
529
+ pause_kind = str(((state.get("pause") or {}).get(unit) or {}).get("kind") or "")
530
+ if d.word == "event":
531
+ if u.wait is None:
532
+ raise DecisionRefused("event: is only accepted at a wait")
533
+ if d.name != u.wait.event:
534
+ raise DecisionRefused(f"this wait takes event:{u.wait.event}=<value>, not {d.name!r}")
535
+ try:
536
+ ok = bool(u.wait.check.resolve()(d.value or ""))
537
+ except Exception as exc: # noqa: BLE001 - a check that raises does not pass
538
+ raise DecisionRefused(f"the wait's check raised {type(exc).__name__}") from None
539
+ if not ok:
540
+ raise DecisionRefused(f"the wait's check does not accept {d.name}={d.value}")
541
+ return
542
+ if d.word == "answer":
543
+ raise DecisionRefused("answer: is only accepted at an ask")
544
+ if pause_kind == "event_wait" and d.word != "stop": # HUM-B4: a wait is not passable by word
545
+ raise DecisionRefused(f"a wait passes only on event:{u.wait.event if u.wait else '<name>'}=<value>; "
546
+ "`stop` ends the run")
547
+ if pause_kind == "input" and d.word not in ("proceed", "stop"):
548
+ raise DecisionRefused("an ask accepts answer:<name>=<value>, proceed and stop")
549
+ if pause_kind == "breakpoint" and d.word not in ("proceed", "stop"):
550
+ raise DecisionRefused("a breakpoint accepts proceed and stop")
551
+ if d.word == "back" and d.unit not in g.back_targets:
552
+ raise DecisionRefused(f"back:{d.unit} is not a back target of {unit}")
553
+ if d.word in ("back", "rewind") and d.unit and flow.block_of(spec, d.unit) and \
554
+ flow.block_of(spec, d.unit) != flow.block_of(spec, unit):
555
+ raise DecisionRefused(f"{d.unit} is a branch of {flow.block_of(spec, d.unit)}; name the block")
556
+ if d.word == "rewind" and d.unit not in path:
557
+ raise DecisionRefused(f"rewind:{d.unit}: {d.unit} was not completed on this path")
558
+ if d.word == "retry" and _killed_pause(state, unit):
559
+ spent = int(((state.get("counters") or {}).get(unit) or {}).get("command_killed", 0))
560
+ if spent >= command_killed_cap:
561
+ raise DecisionRefused(f"the command_killed_retries cap of {command_killed_cap} is spent on {unit}; "
562
+ "answer proceed, back:<unit> or stop")
563
+ human = int(((state.get("counters") or {}).get(unit) or {}).get("human", 0))
564
+ if d.word in ("retry", "rewind") and human >= human_cap:
565
+ raise DecisionRefused(f"the human cap of {human_cap} is spent on {unit}")
566
+
567
+
568
+ FEEDBACK_LIMIT = 8_000
569
+ RULINGS_ACTIVE = 10
570
+ RULINGS_CHARS = 16_000
571
+
572
+
573
+ def active_rulings(spec: WorkflowSpec, state: Mapping[str, Any], unit: str) -> list[str]:
574
+ """RRN-B14, RRN-B15: rulings in force for `unit`: named by `applies_to`, else given at it or an earlier unit."""
575
+ order = flow.effective_order(spec)
576
+ out = []
577
+ for r in (state.get("rulings") or {}).values():
578
+ if not isinstance(r, dict) or r.get("revoked_at"):
579
+ continue
580
+ applies = list(r.get("applies_to") or [])
581
+ if applies:
582
+ hit = unit in applies
583
+ else:
584
+ at = str(r.get("given_at") or "")
585
+ hit = unit == at or (at in order and unit in order and order.index(unit) >= order.index(at))
586
+ if hit:
587
+ out.append(str(r.get("text") or ""))
588
+ return out
589
+
590
+
591
+ def decision_target(spec: WorkflowSpec, unit: str, d: Decision) -> str:
592
+ """The unit a decision's feedback reaches (RRN-B14, RRN-B15)."""
593
+ if d.word == "proceed":
594
+ nxt = flow.successors(spec, unit).proceed[0]
595
+ return nxt.rsplit(".", 1)[0] if nxt.endswith(".step") else unit
596
+ if d.word in ("back", "rewind") and d.unit:
597
+ return d.unit
598
+ return unit
599
+
600
+
601
+ def check_rulings(state: Mapping[str, Any], new_text: str | None, revoke: Sequence[str]) -> None:
602
+ """RRN-B16, RRN-B17, RRN-B18, RRN-B14, RRN-B15: unknown revoke ids, and the limits of 10 active rulings and 16 000 characters."""
603
+ rulings = {k: v for k, v in (state.get("rulings") or {}).items() if isinstance(v, dict)}
604
+ for rid in revoke:
605
+ if rid not in rulings or rulings[rid].get("revoked_at"):
606
+ raise DecisionRefused(f"--revoke-ruling {rid}: no active ruling with that id")
607
+ active = [(k, v) for k, v in rulings.items() if not v.get("revoked_at") and k not in revoke]
608
+ if new_text is None:
609
+ return
610
+ chars = sum(len(str(v.get("text") or "")) for _, v in active) + len(new_text)
611
+ if len(active) + 1 > RULINGS_ACTIVE or chars > RULINGS_CHARS:
612
+ oldest = min(active, key=lambda kv: str(kv[1].get("at") or ""))[0] if active else "-"
613
+ raise DecisionRefused(f"rulings over their limit ({RULINGS_ACTIVE} active, {RULINGS_CHARS} characters); "
614
+ f"revoke one first, the oldest is {oldest}")
615
+
616
+
617
+ def ruling_writes(state: Mapping[str, Any], payload: Mapping[str, Any], given_at: str) -> dict[str, Any]:
618
+ """The `rulings` channel write of one resume: a new ruling and any revocations (RST (moved) `Ruling`)."""
619
+ now = datetime.now(UTC).isoformat(timespec="seconds")
620
+ w: dict[str, Any] = {rid: {"revoked_at": now, "revoked_by": payload.get("caller")}
621
+ for rid in payload.get("revoke") or []}
622
+ r = payload.get("ruling")
623
+ if r and payload.get("feedback"):
624
+ rid = f"r{len(state.get('rulings') or {}) + 1}"
625
+ w[rid] = {"id": rid, "text": str(payload["feedback"]), "given_at": given_at,
626
+ "applies_to": list(r.get("applies_to") or []), "by": payload.get("caller"), "at": now}
627
+ return w
628
+
629
+
630
+ def apply_deadline(spec: WorkflowSpec, unit: str, state: Mapping[str, Any], task_id: str,
631
+ payload: Mapping[str, Any] | None = None) -> dict[str, Any]:
632
+ """FLX-B8: what `resume --apply-deadline` does to an overdue wait or ask. `defaults` (an ask only) goes on
633
+ as a person's complete answers do; `payload` carries the completed answers the resume built (ASK-B10)."""
634
+ dl = flow.deadline_of(spec, unit)
635
+ assert dl is not None
636
+ s = flow.successors(spec, unit)
637
+ how = dl[1]
638
+ if how == "defaults":
639
+ w = _apply(spec, unit, state, {**(payload or {}), "decision": "proceed"})
640
+ w["route"][unit]["by"] = "deadline"
641
+ return w
642
+ if how == "stop":
643
+ return {"route": {unit: {"token": "STOP", "node": s.stop[0], "by": "deadline"}}, "pause": {unit: None},
644
+ "run": {"stopped": {"reason": "deadline", "unit": unit, "detail": "on_deadline: stop"}}}
645
+ if how == "escalate": # the pause becomes an escalation a person answers with the usual decisions
646
+ payload = pause_payload(spec, unit, "escalation", "deadline", state, task_id)
647
+ return {"route": {unit: {"token": "ESCALATE", "node": s.escalate[0], "by": "deadline", "kind": "escalation"}},
648
+ "pause": {unit: payload}}
649
+ node = flow.deadline_node(spec, unit)
650
+ assert node is not None
651
+ return {"route": {unit: {"token": "DEADLINE", "node": node, "by": "deadline"}}, "pause": {unit: None},
652
+ "feedback": {how: {"text": f"`{unit}` got no answer before its deadline.", "as": "notes"}}}
653
+
654
+
655
+ def apply_decision(spec: WorkflowSpec, unit: str, state: Mapping[str, Any], payload: Mapping[str, Any]
656
+ ) -> dict[str, Any]:
657
+ if payload.get("decision") == "deadline":
658
+ return apply_deadline(spec, unit, state, str((state.get("request") or {}).get("task_id") or ""), payload)
659
+ if payload.get("decision") == "usage_limit": # DUR-B12: the session the limit ended runs again, nothing counted
660
+ held = (state.get("attempts") or {}).get(unit) or {}
661
+ at_judge = held.get("usage_limit_stage") == "judge"
662
+ node = flow.node_names(unit)[1 if at_judge else 0]
663
+ w = {"route": {unit: {"token": "RETRY", "node": node, "by": "person", "scope": None}}, "pause": {unit: None}}
664
+ if at_judge: # the rerun judge must not read the cause again
665
+ w["attempts"] = {unit: {"escalate": None, "usage_limit_resets_at": None, "usage_limit_stage": None}}
666
+ return w
667
+ w = _apply(spec, unit, state, payload)
668
+ d = Decision.parse(str(payload.get("decision", "")))
669
+ rulings = ruling_writes(state, payload, decision_target(spec, unit, d))
670
+ if rulings:
671
+ w["rulings"] = rulings
672
+ return w
673
+
674
+
675
+ def _apply(spec: WorkflowSpec, unit: str, state: Mapping[str, Any], payload: Mapping[str, Any]) -> dict[str, Any]:
676
+ d = Decision.parse(str(payload.get("decision", "")))
677
+ s = flow.successors(spec, unit)
678
+ # `--ruling` makes the text a ruling instead of one-time feedback; a rewind's text is still its visit reason
679
+ feedback = payload.get("feedback") or None
680
+ one_time = None if payload.get("ruling") else feedback
681
+ counters = dict((state.get("counters") or {}).get(unit) or {})
682
+
683
+ def route(token: str, node: str) -> dict[str, Any]:
684
+ return {"route": {unit: {"token": token, "node": node, "by": "person", "scope": None}}, "pause": {unit: None}}
685
+
686
+ if d.word == "proceed":
687
+ held = ((state.get("attempts") or {}).get(unit) or {}).get("item")
688
+ if mapping.concurrent(spec, unit) and held: # a person passed one item of a concurrent map: that item alone
689
+ return _merge(route("NEXT", s.retry[0]), mapping.passed_item_write(unit, held))
690
+ more = mapping.advance(spec, unit, state)
691
+ if more is not None: # a person passed one item of a map; the next item runs
692
+ return _merge(route("NEXT", s.retry[0]), more)
693
+ picked = ((state.get("route") or {}).get(unit) or {}).get("pick") # made before the approval pause
694
+ nxt = flow.entry_node(spec, picked["target"]) if picked else s.proceed[0]
695
+ w = _merge(route("PROCEED", nxt), mapping.passed_write(spec, unit, state))
696
+ if picked:
697
+ w["route"][unit]["pick"] = picked
698
+ nxt_unit = nxt.rsplit(".", 1)[0] if nxt.endswith(".step") else None
699
+ if one_time and nxt_unit:
700
+ w["feedback"] = {nxt_unit: {"text": one_time, "as": "notes"}}
701
+ if payload.get("council_decision") is not None: # CNL-B13: a person's answer is the council's decision
702
+ chosen = str(payload["council_decision"])
703
+ held = _json_or(((state.get("values") or {}).get(unit) or {}).get("tally"))
704
+ tally = {**(held if isinstance(held, dict) else {}), "outcome": chosen, "chosen_by": "person"}
705
+ w["values"] = {unit: {"decision": chosen, "tally": json.dumps(tally, sort_keys=True), "tally.outcome": chosen}}
706
+ if payload.get("answers") is not None: # ASK-B5, ASK-B6: the answers file is the unit's one artifact
707
+ w["artifacts"] = {unit: {"answers": str(payload.get("answers_path") or "")}}
708
+ w["values"] = {unit: {str(k): ", ".join(map(str, v)) if isinstance(v, list) else str(v)
709
+ for k, v in dict(payload["answers"]).items()}}
710
+ return w
711
+ if d.word == "event": # HUM-B4: the delivered value passed the wait's check before this node ran
712
+ return _merge(route("PROCEED", s.proceed[0]), {"values": {unit: {str(d.name): str(d.value or "")}}})
713
+ if d.word == "retry" and _killed_pause(state, unit): # KIL-B9, KIL-B14: the killed commands run alone, no step
714
+ counters.update(command_killed=int(counters.get("command_killed", 0)) + 1,
715
+ human=int(counters.get("human", 0)) + 1)
716
+ w = _merge({"route": {unit: {"token": "RETRY", "node": flow.node_names(unit)[1], "by": "person",
717
+ "scope": None}}, "pause": {unit: None}},
718
+ {"counters": {unit: counters}, "attempts": {unit: {"alone": True}}})
719
+ return w
720
+ if d.word == "retry":
721
+ held = counters.get("ladder") or {}
722
+ if payload.get("escalate") and held.get("offer"): # the person took the offer: it spends a retry (E5)
723
+ counters.update(retries=int(counters.get("retries", 0)) + 1, human=int(counters.get("human", 0)) + 1)
724
+ counters["ladder"] = {**{k: v for k, v in held.items() if k != "offer"}, "escalated": True,
725
+ "escalate": {**held["offer"], "taken_by": "person"}}
726
+ return _merge(route("RETRY", s.retry[0]), {"counters": {unit: counters}},
727
+ {"feedback": {unit: {"text": one_time, "as": "feedback"}}} if one_time else {})
728
+ counters.update(retries=0, human=int(counters.get("human", 0)) + 1, infra=0)
729
+ # a person's retry starts the visit at rung 0 (LAD-B11); an escalation of this visit stays spent (E9)
730
+ counters["ladder"] = {"visit": held.get("visit"), "item": held.get("item"), "rung": 0,
731
+ "escalated": True} if held.get("escalated") else None
732
+ w = _merge(route("RETRY", s.retry[0]), {"counters": {unit: counters}})
733
+ if one_time:
734
+ w["feedback"] = {unit: {"text": one_time, "as": "feedback"}}
735
+ return w
736
+ if d.word in ("back", "rewind") and d.unit:
737
+ visits = (state.get("visits") or {}).get(d.unit) or {}
738
+ human = int(counters.get("human", 0)) + (1 if d.word == "rewind" else 0)
739
+ w = _merge(clear_from(spec, d.unit, state), route(d.word.upper(), flow.entry_node(spec, d.unit)),
740
+ {"visits": {d.unit: {"visit": int(visits.get("visit", 1)) + 1,
741
+ "reason": feedback or f"{d.word} by a person", "from": unit,
742
+ "entered_from": f"{d.word}:{unit}"}}})
743
+ w["counters"] = {**w.get("counters", {}),
744
+ unit: {**counters, "human": human, "loops": {}, "command_killed": 0}}
745
+ return w
746
+ return _merge(route("STOP", s.stop[0]), {"run": {"stopped": {"reason": "person", "unit": unit,
747
+ "detail": "stop"}}})