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,2304 @@
1
+ """The node bodies the compiler wires into the graph (CMP `UnitNodes`): step, judge, gate, human, finalizer.
2
+
3
+ The step and judge nodes are the only places a model session starts (OVR-B3); the gate is pure;
4
+ the human node's interrupt is the compiler's. Budgets follow BUD-B1, BUD-B11: the cause picks the counter.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import dataclasses
11
+ import fnmatch
12
+ import hashlib
13
+ import os
14
+ import posixpath
15
+ import threading
16
+ import time
17
+ from collections.abc import Callable, Mapping, Sequence
18
+ from concurrent.futures import ThreadPoolExecutor
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from tempergraph import git as gitmod
24
+ from tempergraph.compiler.state import Move, RunState, fold, item_view, own_keys, slot_writes
25
+ from tempergraph.contracts import (
26
+ CheckResult,
27
+ Executor,
28
+ MapItem,
29
+ MeasureContext,
30
+ ScriptSpec,
31
+ SessionOptions,
32
+ SessionRequest,
33
+ SessionResult,
34
+ SlotSpec,
35
+ StepSpec,
36
+ UnitSpec,
37
+ Verdict,
38
+ ViewSet,
39
+ WorkflowSpec,
40
+ )
41
+ from tempergraph.executors.launcher import StopRequest
42
+ from tempergraph.executors.registry import Registry
43
+ from tempergraph.improve import lessons as lessonsmod
44
+ from tempergraph.model import flow
45
+ from tempergraph.model.text import load_text, split_judge_file
46
+ from tempergraph.render.output import parse_output
47
+ from tempergraph.render.prompt import AttemptContext, Blocker, render_step
48
+ from tempergraph.run import audit as auditmod
49
+ from tempergraph.run import checks as checkmod
50
+ from tempergraph.run import complexity, mapping, reserve, scriptcache, tool_access
51
+ from tempergraph.run import contest as contestmod
52
+ from tempergraph.run import gate as gatemod
53
+ from tempergraph.run import ladder as laddermod
54
+ from tempergraph.run.check_worker import run_in_worker
55
+ from tempergraph.run.commands import CommandRun, ResolvedCommand, run_command
56
+ from tempergraph.run.commands import expand as expand_commands
57
+ from tempergraph.run.guard import guard, view_set
58
+ from tempergraph.run.judging import (
59
+ CLAIM_CRITERION_ID,
60
+ JudgeInputs,
61
+ Unparsed,
62
+ brief_digest,
63
+ claim_criterion,
64
+ council_dissent_blocker,
65
+ council_inputs,
66
+ criteria_digest,
67
+ derive,
68
+ judged,
69
+ marked_reading,
70
+ parse_judgement,
71
+ reask_prompt,
72
+ render_judge,
73
+ reread_needed,
74
+ reread_prompt,
75
+ )
76
+ from tempergraph.run.log import CostTotals, RunLog, cost_so_far, estimate, session_sink
77
+ from tempergraph.run.session_record import read_session
78
+ from tempergraph.security.scrub import clip, scrub
79
+ from tempergraph.settings import Capture
80
+ from tempergraph.store.layout import session_dir, session_key
81
+ from tempergraph.workspace import WorkspaceRecord, WorkspaceRefused, cut_writers, scan_foreign_worktrees
82
+
83
+ ATTEMPT_CAP = 15
84
+ INFRA_TRIES = 3
85
+ BACKOFF_S = (10, 20, 40)
86
+ DEFAULT_TIMEOUT_S = 600
87
+
88
+
89
+ def check_evidence(evidence: str | None) -> str:
90
+ """EVT-B28: the scrubbed first line whole up to 1000 characters, a newline, then the evidence clipped to 200."""
91
+ whole = clip(evidence, 200)
92
+ if not whole:
93
+ return ""
94
+ first = next((ln for ln in (evidence or "").splitlines() if ln.strip()), "")
95
+ return f"{clip(first, 1000)}\n{whole}"
96
+
97
+
98
+ def _skip_match(path: str, pattern: str) -> bool:
99
+ """SRV-B42: a whole-path, case-sensitive match; `*` and `**` cross directories."""
100
+ return fnmatch.fnmatchcase(path, posixpath.normpath(pattern))
101
+
102
+
103
+ class Drain(Exception):
104
+ """End this process's segment at a boundary; the thread stays resumable (CMP-B5, RCT-B1, BUD cost cap)."""
105
+
106
+ def __init__(self, reason: str) -> None:
107
+ super().__init__(reason)
108
+ self.reason = reason
109
+
110
+
111
+ @dataclass(kw_only=True)
112
+ class RunContext:
113
+ spec: WorkflowSpec
114
+ task_id: str
115
+ state_root: Path
116
+ registry: Registry
117
+ log: RunLog
118
+ judges: Mapping[str, str] = field(default_factory=dict)
119
+ enforce_tools: bool = False
120
+ judge_override: str | None = None
121
+ stop: StopRequest = field(default_factory=StopRequest)
122
+ drain_requested: Callable[[], str | None] = lambda: None
123
+ sleep: Callable[[float], None] = time.sleep
124
+ attempt_cap: int = ATTEMPT_CAP
125
+ infra_tries: int = INFRA_TRIES
126
+ command_killed_retries: int = 2
127
+ backoff_max_s: int = 300
128
+ settings: Mapping[str, Any] = field(default_factory=dict) # workflow-declared settings (RST-B25)
129
+ capture: Capture = field(default_factory=Capture) # the operator's capture level (LOS-B17)
130
+ main_checkout: Path | None = None
131
+ attempts_started: int = 0
132
+ counted: dict[tuple[str, str | None], int] = field(default_factory=dict) # counted attempts by unit and item (CMP-B19)
133
+ started: dict[tuple[str, str | None], int] = field(default_factory=dict) # every attempt started, counted or not
134
+ trips: dict[str, int] = field(default_factory=dict) # trips back, by the unit they entered (CMP-B20)
135
+ origin: str = "cli"
136
+ stage: str = "local-dev" # PRO-B7, PRO-B4
137
+ judge_state: Callable[[str], str] | None = None # a gate's judge binding state (JCL-B17); None reads it
138
+ escalation_record: Callable[[str], bool] | None = None # LAD-B13; None reads the ledger
139
+ self_check_limit: int = 3 # CHK-B17
140
+ audit_rate: float = 0.0 # JDG-B7: the chance that a judged gate is audited by a second judge
141
+ audit_executor: str | None = None # JDG-B7: the executor of the audit judge; None is the gate's judge executor
142
+ audit_seed: int | None = None # a test hook that fixes the audit draw
143
+ child: str | None = None # SWF-B8: the sub-workflow unit whose child this context runs; None for the run's own spec
144
+ parent_thread: str = "" # a child's context keeps the parent's thread
145
+ read_worktreeinclude: bool = True # `run.worktree.read_worktreeinclude`, for the writer worktrees (WSP-B2)
146
+
147
+ def count_attempt(self, unit: str, item: str | None, attempt: int, visit: int) -> None:
148
+ """CMP-B19: an attempt counts against the cap only when its unit, item or slot has attempted before in the
149
+ thread, as a retry or in a visit after a trip back."""
150
+ self.started[(unit, item)] = self.started.get((unit, item), 0) + 1
151
+ if attempt > 1 or visit > 1:
152
+ self.attempts_started += 1
153
+ self.counted[(unit, item)] = self.counted.get((unit, item), 0) + 1
154
+
155
+ def report(self) -> dict[str, Any]:
156
+ """CMP-B20: what repeated in this invocation, for the exit at the attempt cap."""
157
+ repeated = [{"unit": u, "item": i, "attempts": self.started.get((u, i), n),
158
+ "trips_back": self.trips.get(u, 0)} for (u, i), n in self.counted.items()]
159
+ return {"attempts_counted": self.attempts_started, "trips_back": sum(self.trips.values()),
160
+ "repeated": repeated}
161
+
162
+ @property
163
+ def thread(self) -> str:
164
+ return self.parent_thread or f"{self.spec.name}/{self.task_id}"
165
+
166
+ @property
167
+ def key_prefix(self) -> str:
168
+ """SWF-B8: session keys of a child read `<unit>/<child unit>.<attempt>.<kind>`."""
169
+ return f"{self.child}/" if self.child else ""
170
+
171
+
172
+ def _aliases(v: object) -> list[str]:
173
+ if v is None:
174
+ return []
175
+ return [v] if isinstance(v, str) else [str(x) for x in v] # type: ignore[attr-defined]
176
+
177
+
178
+ def _remove_launcher_owned(workdir: Path, owned: tuple[str, ...], before: Any) -> None:
179
+ """EXI-B30: remove launcher-owned paths that did not exist before the session started."""
180
+ if not owned:
181
+ return
182
+ import shutil
183
+
184
+ before_paths: set[str] = set()
185
+ if hasattr(before, "status") and before.status:
186
+ before_paths = {ln[3:] for ln in before.status.splitlines() if ln}
187
+ for rel in owned:
188
+ p = workdir / rel
189
+ if not p.exists():
190
+ continue
191
+ before_present = any(bp.startswith(rel) for bp in before_paths)
192
+ if not before_present:
193
+ if p.is_dir():
194
+ shutil.rmtree(p, ignore_errors=True)
195
+ else:
196
+ p.unlink(missing_ok=True)
197
+
198
+
199
+ class EngineNodes:
200
+ def __init__(self, ctx: RunContext) -> None:
201
+ self._deferred: list[dict[str, Any]] = []
202
+ self._deferred_lock = threading.Lock()
203
+ self._audits: dict[tuple[str, str | None], dict[str, Any]] = {} # audit results waiting for their gate record
204
+ self.ledger = reserve.Ledger() # what each running session of a parallel block holds (BUD-B12)
205
+ self.ctx = ctx
206
+
207
+ # -- helpers ---------------------------------------------------------------------------------
208
+
209
+ def defer(self, update: Mapping[str, Any]) -> None:
210
+ """A state write the runner could not make before the graph ran, because several nodes are pending
211
+ (branches of a parallel block): the first node to finish carries it."""
212
+ with self._deferred_lock:
213
+ self._deferred.append(dict(update))
214
+
215
+ def settle(self, w: dict[str, Any]) -> dict[str, Any]:
216
+ with self._deferred_lock:
217
+ held, self._deferred = self._deferred, []
218
+ for update in held:
219
+ for ch, val in update.items():
220
+ w[ch] = {**val, **w[ch]} if isinstance(val, dict) and isinstance(w.get(ch), dict) else \
221
+ w.get(ch, val) if ch in w else val
222
+ return w
223
+
224
+ def _workdir(self, state: Mapping[str, Any], unit: str | None = None) -> Path:
225
+ """The run's worktree; a writer branch's own worktree for the step, judge, check and script of `unit`
226
+ (WSP-B11, WTR-B25)."""
227
+ child = self._writer_child(state, unit) if unit is not None else None
228
+ if child is not None:
229
+ return Path(str(child["path"]))
230
+ return Path((state.get("workspace") or {}).get("path") or self.ctx.state_root.parent)
231
+
232
+ def _writer_child(self, state: Mapping[str, Any], unit: str) -> Mapping[str, Any] | None:
233
+ """The workspace record's child for `unit` when `unit` is a writer branch of a parallel block, or for the item in
234
+ hand when `unit` is a concurrent map whose step writes (its child is addressed by the item's slot and the map's
235
+ visit, WSP-B20; a contest's slot is addressed by the slot and the contest's attempt, WSP-B20; a block's writer
236
+ branch is that of visit 1)."""
237
+ held = mapping.item_in_hand(state)
238
+ if held is not None: # an item of a writing map or a slot of a writing contest: its child is its slot's
239
+ if flow.writer_map(self.ctx.spec, unit):
240
+ return self._child_of(state, held["slot"], int(mapping.record(state, unit).get("visit", 1)))
241
+ if flow.writer_contest(self.ctx.spec, unit):
242
+ return self._child_of(state, held["slot"], int(mapping.record(state, unit).get("attempt", 1)))
243
+ return None
244
+ block = flow.block_of(self.ctx.spec, unit)
245
+ if block is None or unit not in flow.writer_branches(self.ctx.spec, block):
246
+ return None
247
+ return self._child_of(state, unit)
248
+
249
+ @staticmethod
250
+ def _child_of(state: Mapping[str, Any], name: str, visit: int = 1) -> Mapping[str, Any] | None:
251
+ """The child of the workspace record whose unit is `name` and whose visit (none recorded: the first) is `visit`."""
252
+ for child in (state.get("workspace") or {}).get("children") or []:
253
+ if child.get("unit") == name and int(child.get("visit", 1)) == visit:
254
+ return child
255
+ return None
256
+
257
+ def _in_worktree(self, state: Mapping[str, Any]) -> bool:
258
+ return (state.get("workspace") or {}).get("mode") == "worktree"
259
+
260
+ @staticmethod
261
+ def _workspace_paths(state: Mapping[str, Any]) -> list[str]:
262
+ ws = state.get("workspace") or {}
263
+ return [str(p) for p in (ws.get("path"), *(c.get("path") for c in ws.get("children") or [])) if p]
264
+
265
+ def _foreign_worktrees(self, unit: str, iid: str | None, key: str, known: Sequence[str],
266
+ before: Mapping[str, str]) -> list[str]:
267
+ """WTR-B26, WTR-B13: a worktree that appeared during a step session and is not in the run's record (a
268
+ subagent's, P-WTR-2) is recorded as a `workspace` record `foreign` with its path relative to the
269
+ repository's parent, its branch and the session key. Nothing is removed, merged or read. Returns the
270
+ relative paths."""
271
+ main = self.ctx.main_checkout
272
+ if main is None:
273
+ return []
274
+ out: list[str] = []
275
+ for path, br in scan_foreign_worktrees(main, known).items():
276
+ if path in before:
277
+ continue
278
+ rel = os.path.relpath(path, main.parent)
279
+ out.append(rel)
280
+ self.ctx.log.write("workspace", action="foreign", unit=unit, item=iid, mode="worktree", path=rel,
281
+ branch=br or None, session_key=key)
282
+ return out
283
+
284
+ def fork(self, join: str, state: RunState) -> dict[str, Any]:
285
+ """WSP-B19, WSP-B11: entering a block that has a writer branch commits the run worktree's uncommitted changes on
286
+ the run's branch, then cuts one worktree per writer branch from that commit. A cut that fails ends the segment
287
+ at this boundary (engine_error `workspace_refused`) with nothing left behind."""
288
+ writers = flow.writer_branches(self.ctx.spec, join)
289
+ ws = dict(state.get("workspace") or {})
290
+ try:
291
+ if ws.get("mode") != "worktree":
292
+ raise WorkspaceRefused("needs_worktree", f"writer branch {writers[0]}: the run has no worktree")
293
+ rec = WorkspaceRecord.from_json(ws)
294
+ run_path = Path(rec.path)
295
+ gitmod.commit_all(run_path, f"tempergraph: checkpoint before {join}")
296
+ rec = cut_writers(rec, self.ctx.thread, writers, self.ctx.spec.worktree, self.ctx.state_root,
297
+ read_include=self.ctx.read_worktreeinclude)
298
+ rec.last_head = gitmod.head(run_path)
299
+ except (WorkspaceRefused, gitmod.GitError) as exc:
300
+ word = exc.word if isinstance(exc, WorkspaceRefused) else "git_failed"
301
+ self.ctx.log.write("engine_error", unit=join, error="workspace_refused", detail=f"{word}: {exc}")
302
+ raise Drain("workspace_refused") from None
303
+ return {"workspace": rec.to_json()}
304
+
305
+ def _merge_writers(self, join: str, state: Mapping[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any]]:
306
+ """WSP-B11, WSP-B12: merge each writer branch into the run branch without fast-forward, in the order the
307
+ parallel unit names them. A conflict (or a merge git refuses) puts the run branch back at the commit it held
308
+ before the first merge. Returns the new workspace record, or None with what the attempt records."""
309
+ return self._merge_children(state, [(u, u, f"Merge writer branch {u} of {join}")
310
+ for u in flow.writer_branches(self.ctx.spec, join)])
311
+
312
+ def _merge_items(self, unit: str, state: Mapping[str, Any], ids: Sequence[str], visit: int = 1
313
+ ) -> tuple[dict[str, Any] | None, dict[str, Any]]:
314
+ """WSP-B11, WSP-B12: the same merge for the items of a writing concurrent map, in the order of the list; only the
315
+ children cut for `visit` are merged (WSP-B22)."""
316
+ return self._merge_children(state, [(mapping.slot(unit, i), i, f"Merge map item {i} of {unit}") for i in ids],
317
+ visit)
318
+
319
+ def _merge_children(self, state: Mapping[str, Any], order: Sequence[tuple[str, str, str]], visit: int = 1
320
+ ) -> tuple[dict[str, Any] | None, dict[str, Any]]:
321
+ """Merge the children of the workspace record named by `order` (the child's unit, the name it is told by, the
322
+ merge message), one after the other, without fast-forward. A child is matched by its unit and its `visit`."""
323
+ rec = WorkspaceRecord.from_json(dict(state.get("workspace") or {}))
324
+ run_path = Path(rec.path)
325
+ children = {str(c.get("unit")): c for c in rec.children if int(c.get("visit", 1)) == visit}
326
+ before = gitmod.head(run_path)
327
+ for key, label, message in order:
328
+ child = children.get(key)
329
+ if child is None:
330
+ continue
331
+ try:
332
+ gitmod.commit_all(Path(str(child["path"])), f"tempergraph: work of {label}") # what the session left
333
+ paths = gitmod.merge_no_ff(run_path, str(child["branch"]), message)
334
+ failure = ""
335
+ except gitmod.GitError as exc:
336
+ paths, failure = [], str(exc)
337
+ if paths or failure:
338
+ gitmod.merge_abort(run_path)
339
+ gitmod.reset_hard(run_path, before)
340
+ return None, {"escalate": "merge_conflict", "conflicts": paths, "conflict_branch": label,
341
+ "merge_error": failure}
342
+ rec.last_head = gitmod.head(run_path)
343
+ return rec.to_json(), {}
344
+
345
+ def _boundary(self, state: Mapping[str, Any]) -> None:
346
+ reason = self.ctx.drain_requested()
347
+ if reason:
348
+ raise Drain(reason)
349
+ if self.ctx.attempts_started >= self.ctx.attempt_cap:
350
+ raise Drain("attempt_cap")
351
+ cap = self.ctx.spec.run_cost_cap_usd
352
+ if cap is not None and CostTotals.from_json((state.get("run") or {}).get("cost")).figure() >= cap:
353
+ raise Drain("cost_cap")
354
+
355
+ def _council_boundary(self, state: Mapping[str, Any], accrued: float) -> None:
356
+ """The check made before an attempt (BUD-B9), for a council session that runs alone: the chair, once the members have
357
+ spent what this attempt's state does not hold yet."""
358
+ reason = self.ctx.drain_requested()
359
+ if reason:
360
+ raise Drain(reason)
361
+ cap = self.ctx.spec.run_cost_cap_usd
362
+ if cap is not None and CostTotals.from_json((state.get("run") or {}).get("cost")).figure() + accrued >= cap:
363
+ raise Drain("cost_cap")
364
+
365
+ def _hold(self, unit: str, state: Mapping[str, Any], width: int | None = None) -> dict[str, Any] | None:
366
+ """What a session of `unit` needs to take a reservation (BUD-B12): a branch of a parallel block, an item of a
367
+ concurrent map, or a member or chair session of a council (its `width` is the members of the round, 1 for a session
368
+ that runs alone), in a run with a cost cap. Other units run one session at a time and keep the BUD-B9 check."""
369
+ spec = self.ctx.spec
370
+ cap = spec.run_cost_cap_usd
371
+ block = flow.block_of(spec, unit)
372
+ held = mapping.item_in_hand(state)
373
+ if cap is None or (block is None and held is None and width is None):
374
+ return None
375
+ if width is None and held is not None and spec.units[unit].contest is not None: # a slot of a contest: the
376
+ c = spec.units[unit].contest # slots that may run at once share the cap, the lower of `concurrency` and the
377
+ assert c is not None # slot count (BUD-B12)
378
+ width = min(c.concurrency, max(len(flow.slot_names(spec, unit)), 1))
379
+ elif width is None and held is not None: # an item of a concurrent map: the items that may run at once share the cap
380
+ m = spec.units[unit].map
381
+ assert m is not None
382
+ width = min(m.concurrency, max(len(mapping.record(state, unit).get("items") or []), 1))
383
+ elif width is None:
384
+ assert block is not None
385
+ width = len(spec.units[block].branches)
386
+ totals = CostTotals.from_json((state.get("run") or {}).get("cost"))
387
+ return {"cap": float(cap), "width": width, "snapshot": totals.sessions, "spent": totals.figure()}
388
+
389
+ def _session(self, ex: Executor, req: SessionRequest, judge_views: Any = None,
390
+ lessons_digest: str | None = None, extra: Mapping[str, Any] | None = None,
391
+ hold: Mapping[str, Any] | None = None) -> tuple[SessionResult, list]:
392
+ """One session with infra tries and backoff outside the retry budget (BUD-B1, JDG-B5). With `hold`, each
393
+ try takes a reservation first and gives it back, replaced by its real cost, when it ends (BUD-B12)."""
394
+ results: list[SessionResult] = []
395
+ if req.kind in ("step", "retry"): # the rendered prompt, kept local for the session review (SRV-B17)
396
+ from tempergraph.improve.record import write_prompt
397
+
398
+ write_prompt(self.ctx.state_root, self.ctx.spec.name, self.ctx.task_id, req.session_key, req.prompt)
399
+ key = req.session_key
400
+ started = ""
401
+ if req.kind in ("step", "retry"): # SIL-B33: the commit the session started from
402
+ with contextlib.suppress(Exception):
403
+ started = gitmod.head(req.workdir)
404
+ for n in range(self.ctx.infra_tries):
405
+ if hold is not None:
406
+ reason = self.ledger.acquire(
407
+ key, snapshot=hold["snapshot"], spent_usd=hold["spent"], cap_usd=hold["cap"],
408
+ amount=lambda spent: reserve.session_amount(req.options.cost_cap_usd, hold["cap"], spent,
409
+ hold["width"]),
410
+ write=lambda action, **fig: self.ctx.log.write("reservation", action=action, session_key=key,
411
+ **fig),
412
+ drain=self.ctx.drain_requested)
413
+ if reason:
414
+ raise Drain(reason)
415
+ try:
416
+ sink = session_sink(self.ctx.log, req, ex.name, tool_inputs=self.ctx.capture.tool_inputs)
417
+ self.ctx.log.write("attempt_start", session_key=req.session_key, kind=req.kind, executor=ex.name,
418
+ alias=req.alias, timeout_s=req.timeout_s,
419
+ prompt_digest=hashlib.sha256((req.prompt or "").encode()).hexdigest()[:16],
420
+ **{k: extra[k] for k in ("sources", "ladder") if extra and k in extra})
421
+ try:
422
+ if judge_views is None:
423
+ res = ex.run_step(req, sink)
424
+ else:
425
+ res = ex.run_judge(req, judge_views, sink)
426
+ finally:
427
+ sink.close()
428
+ if not self.ctx.capture.raw and req.session_dir is not None: # `observe.raw = off` (LOS-B17)
429
+ with contextlib.suppress(OSError):
430
+ (req.session_dir / "raw.jsonl").unlink(missing_ok=True)
431
+ if res.usage.estimated_cost_usd is None:
432
+ res.usage.estimated_cost_usd = estimate(res.usage, res.model)
433
+ results.append(res)
434
+ self.ctx.log.write("agent_run", session_key=req.session_key, kind=req.kind, executor=ex.name,
435
+ alias=req.alias, usage=res.usage, ok=res.ok,
436
+ tools=[c.name for c in res.tool_calls],
437
+ cli_version=res.cli_version, session_id=res.session_id,
438
+ unknown_tools=sorted({c.name for c in res.tool_calls
439
+ if not ex.capabilities().knows_tool(c.name)}),
440
+ infra_cause=str(res.infra_cause) if res.infra_cause else None,
441
+ error_kind=res.error_kind, timed_out=res.timed_out, stalled=res.stalled,
442
+ usage_limit=res.usage_limit, usage_limit_resets_at=res.usage_limit_resets_at,
443
+ duration_s=res.duration_s, tool_wall_share=res.tool_wall_share,
444
+ slow_host=bool(res.timed_out and res.tool_wall_share >= 0.6),
445
+ **({"lessons_digest": lessons_digest} if lessons_digest else {}),
446
+ **({"wrote_paths": self._wrote_paths(req, started)}
447
+ if req.kind in ("step", "retry") else {}),
448
+ **dict(extra or {}))
449
+ if hold is not None:
450
+ spent = CostTotals()
451
+ spent.add(res.usage)
452
+ self.ledger.release(key, snapshot=hold["snapshot"], real_usd=spent.figure())
453
+ finally:
454
+ if hold is not None:
455
+ self.ledger.release(key, snapshot=hold["snapshot"], real_usd=0.0) # a no-op once released
456
+ if res.infra_cause is None or n + 1 >= self.ctx.infra_tries or (res.usage_limit and not res.ok):
457
+ break # a usage-limit refusal is never rerun after a backoff (BUD-B17)
458
+ self.ctx.sleep(min(BACKOFF_S[min(n, len(BACKOFF_S) - 1)], self.ctx.backoff_max_s))
459
+ return results[-1], results
460
+
461
+ @staticmethod
462
+ def _wrote_paths(req: SessionRequest, started: str) -> list[str]:
463
+ """SIL-B33: the files that differ from the commit the session started from, committed or not, by any tool or
464
+ command; empty when git cannot say."""
465
+ try:
466
+ return gitmod.changed_paths(req.workdir, started or None)
467
+ except Exception: # noqa: BLE001 - observability never changes the run (OVR-B4)
468
+ return []
469
+
470
+ def _cost(self, state: Mapping[str, Any], results: list[SessionResult]) -> dict[str, Any]:
471
+ totals = CostTotals.from_json((state.get("run") or {}).get("cost"))
472
+ base = dict(totals.to_json()["counters"]) # what this writer read: the reducer adds only its delta
473
+ for r in results:
474
+ totals.add(r.usage)
475
+ return {**totals.to_json(), "_base": base}
476
+
477
+ # -- council (CNL-B13 to CNL-B15): the nodes of the subgraph that is a council's step node --------------------
478
+
479
+ def council_open(self, unit: str, state: Mapping[str, Any]) -> Any:
480
+ from tempergraph.run import council_run
481
+
482
+ return council_run.open_run(self, unit, state)
483
+
484
+ def council_member(self, run: Any, name: str, stage: int) -> None:
485
+ run.member(name, stage)
486
+
487
+ def council_close(self, run: Any, stage: int) -> int:
488
+ return int(run.close(stage))
489
+
490
+ def council_tally(self, run: Any) -> None:
491
+ run.tally_now()
492
+
493
+ def council_chair(self, run: Any) -> None:
494
+ run.chair_now()
495
+
496
+ def council_finish(self, run: Any) -> dict[str, Any]:
497
+ return dict(run.finish())
498
+
499
+ # -- step ------------------------------------------------------------------------------------
500
+
501
+ def _skey(self, unit: str, attempt: int, kind: str, item: str | None = None) -> str:
502
+ return self.ctx.key_prefix + session_key(unit, attempt, kind, item=item)
503
+
504
+ def step(self, unit: str, state: RunState, config: Any = None) -> dict[str, Any]:
505
+ spec = self.ctx.spec
506
+ u = spec.units[unit]
507
+ self._boundary(state)
508
+ if u.kind == "subworkflow": # SWF-B1: the child runs as one unit, on a graph and state of its own
509
+ from tempergraph.run import subrun
510
+
511
+ return subrun.run_child(self, unit, state, config)
512
+ if u.kind == "script":
513
+ return self._script_unit(unit, state)
514
+ if u.kind in ("route", "switch"):
515
+ return self._flow_unit(unit, state)
516
+ if u.kind in ("ask", "wait"):
517
+ return self._person_unit(unit, state)
518
+ if u.kind == "parallel":
519
+ return self._join_unit(unit, state)
520
+ if u.kind == "contest" and mapping.item_in_hand(state) is None: # CTS-B6: the slots run from the unit's own node
521
+ return self._contest_step(unit, state)
522
+ if u.extra.get("outcome"):
523
+ return self._outcome_step(unit, state)
524
+ st = u.step
525
+ assert st is not None
526
+ prev = (state.get("attempts") or {}).get(unit) or {}
527
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
528
+ counters = (state.get("counters") or {}).get(unit) or {}
529
+ entered = prev.get("visit") != visit
530
+ workdir = self._workdir(state, unit)
531
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
532
+ sent = mapping.item_in_hand(state) # an item of a concurrent map: the unit's own entry was logged by its step node
533
+ if entered and sent is None:
534
+ fp = gitmod.fingerprint(workdir)
535
+ self.ctx.log.write("unit_entered", unit=unit, visit=visit, head_commit=fp.head, dirty=fp.dirty,
536
+ entered_from=_entered_from(state, unit))
537
+ item: dict[str, Any] | None = None
538
+ maps: dict[str, Any] = {}
539
+ if (u.map is not None or u.contest is not None) and sent is not None: # the item or slot the node was sent
540
+ m, item = self._concurrent_item(unit, state, sent["id"]) # its own attempt count
541
+ maps = {unit: m}
542
+ elif u.map is not None: # the list is read once per visit; the item in hand is the first not passed
543
+ done, m, item = self._map_item(unit, state, visit, workdir, prev, path_units)
544
+ if done is not None:
545
+ return done
546
+ assert item is not None
547
+ maps = {unit: m}
548
+ iid = item["id"] if item else None
549
+ first = entered or prev.get("item") != iid
550
+ entry_head = "" # SRV-B35: the commit an item's first attempt of the visit started from, carried by its retries
551
+ if u.map is not None:
552
+ if first:
553
+ with contextlib.suppress(Exception):
554
+ entry_head = gitmod.head(workdir)
555
+ else:
556
+ entry_head = str(prev.get("entry_head") or "")
557
+ attempt = int(item["attempt"]) if item else int(prev.get("attempt", 0)) + 1
558
+ again = prev.get("reuse") if (item is None and prev.get("escalate") == "usage_limit"
559
+ and prev.get("usage_limit_stage") == "step" and prev.get("visit") == visit
560
+ and isinstance(prev.get("reuse"), Mapping)) else None
561
+ if again is not None: # DUR-B12: the session the limit ended runs again, as that attempt and with its inputs
562
+ attempt, first = int(prev["attempt"]), bool(again["first"])
563
+ else:
564
+ self.ctx.count_attempt(unit, iid, attempt, visit)
565
+ ov, layer = gatemod.arm_overrides(spec, unit, state) # below the operator layers (SWM-B6, RST-B22, RST-B23)
566
+ ov = {k: v for k, v in ov.items() if k in ("model", "timeout_s", "idle_s", "effort")
567
+ and k not in (u.extra.get("operator_set") or ())}
568
+ sources = {k: layer for k in ov}
569
+ # one alias per attempt: release 1's retry-count list is retired (LAD-B18) and validation refuses it
570
+ alias = (_aliases(ov.get("model")) or _aliases(st.model) or _aliases(spec.model_profile.get(unit)) or ["inherit"])[0]
571
+ full_ov, _ = gatemod.arm_overrides(spec, unit, state)
572
+ rungs, pinned = laddermod.rungs_of(u, full_ov)
573
+ rung = laddermod.held_rung(counters, visit, iid) if rungs and not pinned else 0
574
+ climb: dict[str, Any] | None = None
575
+ if rungs and not pinned: # the effort of this attempt is its rung's (LAD-B9); a pin switches it off
576
+ ov["effort"] = rungs[rung]
577
+ sources["effort"] = f"ladder:effort[{rung}]"
578
+ held = counters.get("ladder") or {}
579
+ up = held.get("escalate") if held.get("visit") == visit and held.get("item") == iid and not first else None
580
+ if up: # LAD-B12: one attempt on the tier above, at the escalation's effort
581
+ alias = str(up["to"])
582
+ sources["model"] = "escalation:+1"
583
+ if up.get("effort"):
584
+ ov["effort"] = up["effort"]
585
+ sources["effort"] = "escalation:+1"
586
+ if item and u.map is not None and u.map.item_model is not None:
587
+ try:
588
+ chosen = str(u.map.item_model.resolve()(MapItem(id=item["id"], text=item["text"])))
589
+ except Exception as exc: # noqa: BLE001 - a workflow fault, recorded
590
+ chosen = f"<{type(exc).__name__}>"
591
+ if chosen not in u.map.models: # MAP-B8, MAP-B10, MAP-B9: the attempt fails before launch
592
+ self.ctx.log.write("engine_error", unit=unit, item=iid, error="item_model",
593
+ detail=f"{chosen!r} is not one of {list(u.map.models)}")
594
+ record: dict[str, Any] = {
595
+ "attempt": attempt, "visit": visit, "item": iid, "ok": False, "text": "", "issues": [],
596
+ "tools": [], "session_id": None, "error_kind": "item_model", "infra_spent": False,
597
+ "check": None, "escalate": "workflow_fault", "timed_out": False,
598
+ "entry_head": entry_head}
599
+ return {"attempts": {unit: record}, "maps": maps}
600
+ alias = chosen
601
+ slot_spec = self._slot_spec(unit, iid) if u.contest is not None else None # CTS-B6: this slot's own overrides
602
+ if slot_spec is not None and slot_spec.model and not up and "model" not in (u.extra.get("operator_set") or ()):
603
+ alias = slot_spec.model
604
+ ex = self.ctx.registry.get((slot_spec.executor if slot_spec is not None else None) or st.executor
605
+ or spec.default_executor)
606
+ caps = ex.capabilities()
607
+ fields = self._fields(unit, state, attempt, visit, workdir)
608
+ if item: # VAL-B8 item keys
609
+ fields.update(item_id=item["id"], item_index=str(item["index"]), item_count=str(item["count"]),
610
+ item=item["text"])
611
+ failed, env, hybrid = self._scripts(st.before, unit, attempt, "before", state, workdir)
612
+ fields.update(hybrid) # a `before` script's keys are the session's to read (SCR-B5)
613
+ if failed is not None:
614
+ return self._script_failed(unit, state, attempt, visit, failed, env, path_units, first, hybrid, entry_head)
615
+ judged = (state.get("judgements") or {}).get(unit) or {}
616
+ fb = (state.get("feedback") or {}).get(unit) or {}
617
+ retry = not first and bool(prev)
618
+ prev_unit = self._previous_unit(unit, path_units)
619
+ prev_judged = ((state.get("judgements") or {}).get(prev_unit) or {}) if prev_unit else {}
620
+ notes = tuple(prev_judged.get("notes") or ()) if first else ()
621
+ lessons_text = lessonsmod.block(lessonsmod.load(spec, unit))
622
+ prior_check = prev.get("check") if retry else None # BUD-B16: the previous attempt's failing check, same visit and item
623
+ # what the attempt's prompt is made from; a refused attempt keeps it, because the judge node overwrites the
624
+ # judgement and the gate clears one-time feedback before the rerun (DUR-B12)
625
+ inputs: dict[str, Any] = dict(again) if again is not None else {
626
+ "first": first, "retry": retry,
627
+ "blockers": [dict(b) for b in (judged.get("blockers") or [])] if retry else [],
628
+ "check_evidence": str(((prev.get("check") or {}).get("evidence")) or "") if retry else "",
629
+ "previous_report": str(prev.get("text") or "") if retry else "",
630
+ "paths_only": retry and bool(prev.get("cut_off")),
631
+ "notes": [*notes, *([str(fb.get("text"))] if fb.get("as") == "notes" else [])],
632
+ "visit_reason": str(((state.get("visits") or {}).get(unit) or {}).get("reason") or "") if first else "",
633
+ "visit_from": str(((state.get("visits") or {}).get(unit) or {}).get("from") or "") if first else "",
634
+ "feedback": str(fb.get("text") or "") if fb.get("as") == "feedback" else "",
635
+ "prior_failing": {"findings": [{k: f.get(k) for k in ("criterion", "place", "message")}
636
+ for f in prior_check.get("findings") or [] if f.get("status") == "fail"],
637
+ "evidence": str(prior_check.get("evidence") or "")}
638
+ if isinstance(prior_check, Mapping) and prior_check.get("result") == "FAIL"
639
+ and not prior_check.get("environmental") else None}
640
+ retry = bool(inputs["retry"])
641
+ ctx = AttemptContext(
642
+ template=load_text(spec, st.prompt), fields=fields, attempt=attempt, retry=retry, lessons=lessons_text,
643
+ blockers=tuple(Blocker(criterion=str(b.get("criterion", "")), place=str(b.get("place", "")),
644
+ problem=str(b.get("problem", "")), fix=str(b.get("fix", "")))
645
+ for b in inputs["blockers"]),
646
+ check_evidence=str(inputs["check_evidence"]), previous_report=str(inputs["previous_report"]),
647
+ paths_only=bool(inputs["paths_only"]), notes=tuple(str(n) for n in inputs["notes"]),
648
+ visit_reason=str(inputs["visit_reason"]), visit_from=str(inputs["visit_from"]),
649
+ feedback=str(inputs["feedback"]),
650
+ rulings=tuple(gatemod.active_rulings(spec, state, unit)),
651
+ upstream_targets=tuple(u.gate.back_targets))
652
+ commands = expand_commands(st.commands, workdir) # `@repository`: what the repository declares (CHK-B11)
653
+ shown = u if commands == tuple(st.commands) else dataclasses.replace(
654
+ u, step=dataclasses.replace(st, commands=commands))
655
+ ticket: str | None = None
656
+ if st.self_check and u.gate.check is not None: # CHK-B17: a ticket for this attempt only
657
+ from tempergraph.run import selfcheck
658
+
659
+ ticket = selfcheck.issue(
660
+ self.ctx.state_root, u.gate,
661
+ self._check_context(unit, state, {"item": iid, "attempt": attempt, "visit": visit}, workdir,
662
+ sub="-preview"), thread=self.ctx.thread, limit=self.ctx.self_check_limit,
663
+ base_branch=str((state.get("workspace") or {}).get("base_branch") or ""))
664
+ ctx = dataclasses.replace(ctx, self_check=selfcheck.command(ticket))
665
+ rendered = render_step(unit, shown, ctx, caps)
666
+ prompt = rendered.text
667
+ if slot_spec is not None and slot_spec.prompt_variant: # CTS-B6: appended under its fixed heading
668
+ prompt += "\n\n## Approach for this attempt\n" + slot_spec.prompt_variant.strip() + "\n"
669
+ key = self._skey(unit, attempt, "retry" if retry else "step", item=iid)
670
+ req = SessionRequest(
671
+ kind="retry" if retry else "step", prompt=prompt, workdir=workdir, alias=alias, session_key=key,
672
+ tools=tuple(st.tools), commands=(*commands, *([ctx.self_check] if ctx.self_check else [])),
673
+ timeout_s=ov.get("timeout_s") or st.timeout_s or DEFAULT_TIMEOUT_S,
674
+ idle_s=ov.get("idle_s") or st.idle_s,
675
+ options=dataclasses.replace(st.session_options or SessionOptions(),
676
+ **({"effort": ov["effort"]} if "effort" in ov else {})),
677
+ session_dir=session_dir(self.ctx.state_root, spec.name, self.ctx.task_id, key),
678
+ enforce_tools=self.ctx.enforce_tools, in_engine_worktree=self._in_worktree(state),
679
+ plugin_dir=spec.package_root)
680
+ if rungs or up or laddermod.escalation_of(u, full_ov) is not None:
681
+ last = (counters.get("ladder") or {}) if not first else {}
682
+ climb = {"rung": rung, "effort": req.options.effort, "alias": alias,
683
+ "source": "escalation:+1" if up else "operator" if pinned else f"ladder:effort[{rung}]"
684
+ if rungs else "declared",
685
+ "evidence": last.get("evidence"), "held_by": last.get("held_by")}
686
+ if up:
687
+ climb["taken_by"] = up.get("taken_by")
688
+ extra: dict[str, Any] = {"sources": sources} if sources else {}
689
+ if climb:
690
+ extra["ladder"] = climb
691
+ before = gitmod.fingerprint(workdir)
692
+ known = self._workspace_paths(state)
693
+ worktrees_before = scan_foreign_worktrees(self.ctx.main_checkout, known) if self.ctx.main_checkout else {}
694
+ try:
695
+ res, results = self._session(ex, req, lessons_digest=lessonsmod.digest(lessons_text),
696
+ extra=extra or None, hold=self._hold(unit, state))
697
+ finally:
698
+ if ticket is not None: # the ticket ends with its attempt; one record a preview (CHK-B17 Record)
699
+ from tempergraph.run import selfcheck
700
+
701
+ for call in selfcheck.close(self.ctx.state_root, ticket):
702
+ self.ctx.log.write("self_check", unit=unit, item=iid, attempt=attempt, result=call.get("result"),
703
+ findings=call.get("findings"), duration_s=call.get("duration_s"))
704
+ if res.partial and not res.ok: # RCT-B11: a session the stop request ended is no failed attempt; none is recorded,
705
+ reason = self.ctx.drain_requested() # so no retry is charged and a resume runs the attempt again
706
+ if reason:
707
+ raise Drain(reason)
708
+ after = gitmod.fingerprint(workdir)
709
+ _remove_launcher_owned(workdir, caps.launcher_owned_paths, before) # EXI-B30: clean up paths the launcher created
710
+ foreign = self._foreign_worktrees(unit, iid, key, known, worktrees_before) # WTR-B26: recorded, never touched
711
+ parsed = parse_output(res.text, st.produces, tuple(u.gate.back_targets))
712
+ after_failed, after_env = None, False
713
+ if res.ok and st.after:
714
+ after_failed, after_env, after_arts = self._scripts(st.after, unit, attempt, "after", state, workdir)
715
+ hybrid.update(after_arts)
716
+ escalate: str | None = None
717
+ try:
718
+ session_calls = read_session(session_dir(self.ctx.state_root, spec.name, self.ctx.task_id, key)) \
719
+ if res.denied else None
720
+ except Exception: # noqa: BLE001 - a journal that cannot be read gives `unclassified` (HUM-B24)
721
+ session_calls = None
722
+ reach = tool_access.refused(unit, st, caps, res.denied, res.tools_at_start, session_calls,
723
+ (*st.commands, *self.ctx.spec.allow_commands))
724
+ limited = bool(res.usage_limit and not res.ok)
725
+ if limited:
726
+ escalate = "usage_limit" # BUD-B17: spends no retry and no infra try, whatever else the result says
727
+ elif res.error_kind in ("auth", "refused"):
728
+ escalate = res.error_kind
729
+ elif reach and (not res.ok or parsed.blocked):
730
+ escalate = "tool_access" # no retry spent; the pause offers the grants (BUD-B1, BUD-B11, RST-B28, RST-B29, RST-B30)
731
+ elif parsed.blocked:
732
+ escalate = "blocked"
733
+ elif parsed.upstream:
734
+ escalate = "upstream"
735
+ prior_failing = inputs["prior_failing"]
736
+ record = {
737
+ "item": iid, "prior_failing": prior_failing, "session_key": key, # the check reads this session's journal (CHK-B24)
738
+ "visit_keys": [*([] if first else [str(k) for k in prev.get("visit_keys") or ()]), key], # VSR-B1
739
+ "attempt": attempt, "visit": visit, "ok": res.ok, "text": clip(scrub(res.text), 8000), "blocked": parsed.blocked, "upstream": parsed.upstream,
740
+ "issues": parsed.issues, "infra_cause": str(res.infra_cause) if res.infra_cause else None,
741
+ "infra_spent": res.infra_cause is not None and not limited, "timed_out": res.timed_out, "stalled": res.stalled,
742
+ "error_kind": res.error_kind, "denied": list(res.denied), "tools": [c.name for c in res.tool_calls],
743
+ "tool_access": reach,
744
+ "session_id": res.session_id, "executor": ex.name, "alias": alias, "model": res.model,
745
+ "changed": before != after, "escalate": escalate, "cut_off": res.partial, "check": None,
746
+ "duration_s": res.duration_s, "tool_wall_share": res.tool_wall_share,
747
+ "slow_host": res.timed_out and res.tool_wall_share >= 0.6, "missing_fields": rendered.missing_fields,
748
+ **({"entry_head": entry_head} if u.map is not None else {}),
749
+ }
750
+ if limited:
751
+ record.update(usage_limit_resets_at=res.usage_limit_resets_at, usage_limit_stage="step", reuse=inputs)
752
+ else: # the merge deletes a key written as None: nothing of an earlier refusal stays
753
+ record.update(usage_limit_resets_at=None, usage_limit_stage=None, reuse=None)
754
+ esc_spec = laddermod.escalation_of(u, full_ov)
755
+ if up:
756
+ record.update(escalated=True, escalated_to=alias)
757
+ elif esc_spec is not None: # E6: what this attempt's tokens would cost one tier up (OBS-B10 to OBS-B13 prices)
758
+ priced = estimate(res.usage, laddermod.TIER_FAMILY.get(laddermod.tier(esc_spec.to)))
759
+ usages = [*(prev.get("up_estimates") or [])] if not first else []
760
+ record["up_estimates"] = [*usages, priced][-5:]
761
+ if foreign:
762
+ record.update(foreign_worktrees=foreign, warnings=[f"foreign_worktree: {rel}" for rel in foreign])
763
+ if u.contest is not None: # the slot's own step cost: the attempt's cost cap and the pick read it (CTS-B6, CTS-B7)
764
+ spent = CostTotals()
765
+ for r in results:
766
+ spent.add(r.usage)
767
+ record["cost_usd"] = spent.figure()
768
+ if record["slow_host"]:
769
+ record.update(infra_cause="slow_host", infra_spent=False)
770
+ if res.ok and before != after and (flow.block_of(spec, unit) or sent is not None) \
771
+ and self._writer_child(state, unit) is None:
772
+ # WSP-B11: a read-only branch or item changes nothing in the run worktree; a writer's fingerprint is its own
773
+ record.update(ok=False, error_kind="branch_changed_the_workspace")
774
+ if after_failed is not None:
775
+ record.update(ok=False, error_kind=f"script_failed:{after_failed}",
776
+ escalate="environmental" if after_env else record["escalate"])
777
+ run: dict[str, Any] = {"cost": self._cost(state, results),
778
+ "executors": {**((state.get("run") or {}).get("executors") or {}),
779
+ ex.name: res.cli_version}}
780
+ if entered and unit not in path_units:
781
+ run["path"] = {"units": path_units + [unit]}
782
+ arts: dict[str, Any] = {**hybrid, **parsed.artifacts}
783
+ vals: dict[str, Any] = dict(parsed.values)
784
+ seen = {"facts": {unit: {"foreign_worktrees": foreign}}} if foreign else {} # the check and the judge read it
785
+ if iid: # an item's keys are kept as `<key>[<item id>]`; the plain key is the item in hand (MAP-B8, MAP-B9, MAP-B10)
786
+ arts.update({mapping.item_key(k, iid): v for k, v in list(arts.items())})
787
+ vals.update({mapping.item_key(k, iid): v for k, v in list(vals.items())})
788
+ return {"attempts": {unit: record}, "artifacts": {unit: arts} if arts else {},
789
+ "values": {unit: vals} if vals else {}, "run": run, "maps": maps, **seen}
790
+ return {"attempts": {unit: record}, "artifacts": {unit: arts or None},
791
+ "values": {unit: vals or None}, "run": run, **seen} # feedback is cleared at the gate
792
+
793
+ @staticmethod
794
+ def _concurrent_item(unit: str, state: Mapping[str, Any], iid: str) -> tuple[dict[str, Any], dict[str, Any]]:
795
+ """The item a concurrent map's node was sent: its `maps` write (its attempt count, which continues across
796
+ visits so session keys never repeat) and the item with its index and attempt (MAP-B9)."""
797
+ m = mapping.record(state, unit)
798
+ items = m.get("items") or []
799
+ at = next(i for i, it in enumerate(items, start=1) if it["id"] == iid)
800
+ n = int(m.get(f"n:{iid}", 0)) + 1
801
+ return {f"n:{iid}": n}, {**items[at - 1], "index": at, "count": len(items), "attempt": n}
802
+
803
+ # -- the contest (CTS-B6 to CTS-B10) ----------------------------------------------------------
804
+
805
+ def _slot_spec(self, unit: str, name: str | None) -> SlotSpec | None:
806
+ c = self.ctx.spec.units[unit].contest
807
+ if c is None or isinstance(c.slots, int):
808
+ return None
809
+ return next((s for s in c.slots if s.name == name), None)
810
+
811
+ @staticmethod
812
+ def _slot_view(state: Mapping[str, Any], unit: str, name: str) -> Any:
813
+ """The state a slot's step or judge reads: the slot's own record in the place the unit's would be, and a person's
814
+ feedback for the unit, which no slot of its own holds."""
815
+ view = item_view(state, unit, name)
816
+ own = (state.get("feedback") or {}).get(unit)
817
+ if own and unit not in (view.get("feedback") or {}):
818
+ view["feedback"] = {**(view.get("feedback") or {}), unit: own}
819
+ return view
820
+
821
+ def _each(self, names: Sequence[str], width: int, work: Callable[[str], None]) -> None:
822
+ """Run `work` for each name, up to `width` at once and the next as one ends; the first failure is raised once every
823
+ started name has ended."""
824
+ with ThreadPoolExecutor(max_workers=max(1, min(width, len(names) or 1)), thread_name_prefix="slot") as pool:
825
+ futures = [pool.submit(work, n) for n in names]
826
+ for f in futures:
827
+ f.result()
828
+
829
+ def _contest_step(self, unit: str, state: RunState) -> dict[str, Any]:
830
+ """CTS-B6, CTS-B8: the step node of a contest. Its slots run the unit's step each in the state of its own, up to
831
+ `concurrency` at once, and an unstarted slot is skipped once the attempt's cost has reached `cost_cap_usd`. A
832
+ visit's first entry runs every slot; a retry runs the slots the retry scope names (CTS-B8). The grading and the
833
+ pick are the judge node's."""
834
+ spec = self.ctx.spec
835
+ u = spec.units[unit]
836
+ c = u.contest
837
+ assert c is not None
838
+ names = list(flow.slot_names(spec, unit))
839
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
840
+ prev = (state.get("attempts") or {}).get(unit) or {}
841
+ workdir = self._workdir(state)
842
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
843
+ run = {"path": {"units": path_units + [unit]}} if unit not in path_units else {}
844
+ m = mapping.record(state, unit)
845
+ writes: dict[str, Any] = {}
846
+ attempt = int(prev.get("attempt", 0)) + 1 # the unit's attempt in hand: a slot's worktree is cut for it (WSP-B20)
847
+ if m.get("visit") != visit: # a new visit: every slot runs, nothing of an earlier visit stands
848
+ if prev.get("visit") != visit:
849
+ fp = gitmod.fingerprint(workdir)
850
+ self.ctx.log.write("unit_entered", unit=unit, visit=visit, head_commit=fp.head, dirty=fp.dirty,
851
+ entered_from=_entered_from(state, unit))
852
+ stale = {k: None for k in m if k.startswith("st:") or k in ("pick", "single", "round", "skipped")}
853
+ writes["maps"] = {unit: {"visit": visit, "items": [{"id": n, "text": ""} for n in names], "passed": [],
854
+ "attempt": attempt, **stale}}
855
+ running = names
856
+ else: # a retry of this visit (CTS-B8)
857
+ running = contestmod.retry_slots(names, m.get("single")) # `best` after a retry: one step (CTS-B8, CTS-B4)
858
+ writes["maps"] = {unit: {"attempt": attempt}}
859
+ if flow.writer_contest(spec, unit): # WSP-B19, WSP-B11, WSP-B20: the checkpoint, then a worktree per slot run
860
+ writes["workspace"] = self._enter_writer_contest(unit, state, running, attempt)
861
+ self._boundary(state)
862
+ start = fold(dict(state), writes)
863
+ cap = c.cost_cap_usd
864
+ lock = threading.Lock()
865
+ done: dict[str, dict[str, Any]] = {}
866
+ skipped: list[str] = []
867
+ spent = 0.0
868
+
869
+ def work(name: str) -> None:
870
+ nonlocal spent
871
+ with lock:
872
+ if cap is not None and spent >= cap: # CTS-B6: the attempt's cost has reached the cap
873
+ skipped.append(name)
874
+ return
875
+ body = self.step(unit, self._slot_view(start, unit, name))
876
+ got = (body.get("attempts") or {}).get(unit) or {}
877
+ with lock:
878
+ spent += float(got.get("cost_usd") or 0.0)
879
+ done[name] = slot_writes(body, unit, name)
880
+
881
+ self._each(running, c.concurrency, work)
882
+ out: dict[str, Any] = fold({}, writes)
883
+ for name in running:
884
+ if name in done:
885
+ out = fold(out, done[name])
886
+ base = {"attempt": attempt, "visit": visit, "ok": True, "text": "", "issues": [], "tools": [],
887
+ "session_id": None, "escalate": None, "infra_spent": False, "check": None, "item": None,
888
+ "timed_out": False, "contest": True}
889
+ round_ = {"round": running, "skipped": [n for n in running if n in skipped], "attempt": attempt}
890
+ return fold(out, {"attempts": {unit: base}, "run": run, "maps": {unit: round_}})
891
+
892
+ def _enter_writer_contest(self, unit: str, state: Mapping[str, Any], names: Sequence[str], attempt: int = 1
893
+ ) -> dict[str, Any]:
894
+ """WSP-B19, WSP-B11, WSP-B20: an attempt of a writing contest commits the run worktree's uncommitted changes on the
895
+ run's branch, then cuts one worktree and branch per slot it runs (`names`) from that commit, named by the attempt
896
+ (`--s-<slot>` for the first, `--s<attempt>-<slot>` after); the worktrees of earlier attempts are left as they are.
897
+ A cut that fails ends the segment at this boundary (engine_error `workspace_refused`) with nothing left behind."""
898
+ ws = dict(state.get("workspace") or {})
899
+ try:
900
+ if ws.get("mode") != "worktree":
901
+ raise WorkspaceRefused("needs_worktree", f"writing contest {unit}: the run has no worktree")
902
+ rec = WorkspaceRecord.from_json(ws)
903
+ run_path = Path(rec.path)
904
+ gitmod.commit_all(run_path, f"tempergraph: checkpoint before {unit}")
905
+ rec = cut_writers(rec, self.ctx.thread, [mapping.slot(unit, n) for n in names], self.ctx.spec.worktree,
906
+ self.ctx.state_root, read_include=self.ctx.read_worktreeinclude, kind="s", visit=attempt)
907
+ rec.last_head = gitmod.head(run_path)
908
+ except (WorkspaceRefused, gitmod.GitError) as exc:
909
+ word = exc.word if isinstance(exc, WorkspaceRefused) else "git_failed"
910
+ self.ctx.log.write("engine_error", unit=unit, error="workspace_refused", detail=f"{word}: {exc}")
911
+ raise Drain("workspace_refused") from None
912
+ return rec.to_json()
913
+
914
+ def _contest_judge(self, unit: str, state: RunState) -> dict[str, Any]:
915
+ """CTS-B7, CTS-B2, CTS-B3, CTS-B9: the judge node of a contest. Each slot that ran is graded alone, on a view of its
916
+ own: its check first, and a judge session only for a slot whose check passed, holding that slot's artifacts
917
+ only. The slots that were not put out are ordered by the fixed rule (`run/contest.py`); the winner's artifacts
918
+ and verdict become the unit's, and a `contest` record says so."""
919
+ spec = self.ctx.spec
920
+ u = spec.units[unit]
921
+ c = u.contest
922
+ assert c is not None
923
+ names = list(flow.slot_names(spec, unit))
924
+ m = mapping.record(state, unit)
925
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
926
+ unit_att = dict((state.get("attempts") or {}).get(unit) or {})
927
+ attempt = int(unit_att.get("attempt", 1))
928
+ skipped = [n for n in names if n in (m.get("skipped") or [])]
929
+ ran = [n for n in names if n in (m.get("round") or []) and n not in skipped]
930
+ before = CostTotals.from_json((state.get("run") or {}).get("cost")).figure()
931
+ lock = threading.Lock()
932
+ bodies: dict[str, dict[str, Any]] = {}
933
+
934
+ def grade(name: str) -> None:
935
+ body = self._judge(unit, self._slot_view(state, unit, name))
936
+ with lock:
937
+ bodies[name] = body
938
+
939
+ self._each(ran, c.concurrency, grade)
940
+ out: dict[str, Any] = {}
941
+ judged: dict[str, dict[str, Any]] = {}
942
+ atts: dict[str, dict[str, Any]] = {}
943
+ costs: dict[str, float] = {}
944
+ for name in ran:
945
+ body = bodies[name]
946
+ out = fold(out, slot_writes(body, unit, name))
947
+ judged[name] = dict((body.get("judgements") or {}).get(unit) or {})
948
+ held = (state.get("attempts") or {}).get(mapping.slot(unit, name)) or {}
949
+ atts[name] = {**held, **((body.get("attempts") or {}).get(unit) or {})}
950
+ cost = (body.get("run") or {}).get("cost")
951
+ mine = CostTotals.from_json(cost).figure() - before if cost else 0.0
952
+ costs[name] = round(float(atts[name].get("cost_usd") or 0.0) + max(mine, 0.0), 6)
953
+ infra = {n for n in ran if atts[n].get("infra_spent") or judged[n].get("infra_spent")}
954
+ out_for = {n: (n in infra or (atts[n].get("check") or {}).get("result") == "FAIL"
955
+ or judged[n].get("reason") in ("step_failed", "output_contract")) for n in ran}
956
+ cands = [contestmod.Candidate(slot=n, order=names.index(n), verdict=str(judged[n].get("verdict")),
957
+ cost=costs[n], **{k: v for k, v in contestmod.keys_of(judged[n]).items()})
958
+ for n in ran if not out_for[n]]
959
+ winner = contestmod.pick(cands)
960
+ rows = []
961
+ for n in names:
962
+ if n in skipped:
963
+ rows.append(contestmod.slot_row(names.index(n) + 1, n, skipped=True))
964
+ elif n in ran:
965
+ gone = out_for[n]
966
+ rows.append(contestmod.slot_row(
967
+ names.index(n) + 1, n, attempt=atts[n].get("attempt"),
968
+ check=(atts[n].get("check") or {}).get("result"), verdict=None if gone else judged[n].get("verdict"),
969
+ keys=None if gone else contestmod.keys_of(judged[n]), cost=costs[n]))
970
+ place = names.index(winner.slot) + 1 if winner is not None else None
971
+ self.ctx.log.write("contest", unit=unit, visit=visit, attempt=attempt, winner=place, slots=rows)
972
+ live = [n for n in ran if n not in infra]
973
+ chosen = winner.slot if winner is not None else None
974
+ if chosen is None: # CTS-B9: every slot was put out; the first slot's FAIL is the unit's check result
975
+ chosen = next((n for n in live if (atts[n].get("check") or {}).get("result") == "FAIL"), None) or (
976
+ live[0] if live else (ran[0] if ran else None))
977
+ verdict_att: dict[str, Any] = {**unit_att, "contest": True, "winner": winner.slot if winner else None,
978
+ "item": None, "attempt": attempt, "visit": visit}
979
+ if chosen is None: # nothing ran: no slot started (cannot happen: the first slot always starts)
980
+ unit_j: dict[str, Any] = {"verdict": str(Verdict.ESCALATE), "reason": "contest_no_slot"}
981
+ elif winner is None and not live: # CTS-B9: every slot failed on infrastructure
982
+ verdict_att.update({k: v for k, v in atts[chosen].items() if k not in ("item", "attempt", "visit")})
983
+ verdict_att.update(infra_spent=True, ok=False, item=None)
984
+ unit_j = {"verdict": str(Verdict.ESCALATE), "reason": "infra", "confidence": 1.0,
985
+ "confidence_source": "engine_placeholder"}
986
+ else:
987
+ verdict_att.update({k: v for k, v in atts[chosen].items() if k not in ("item", "attempt", "visit")})
988
+ verdict_att["item"] = None
989
+ unit_j = {**judged[chosen], "winner": winner.slot if winner else None}
990
+ extra: dict[str, Any] = {}
991
+ if flow.writer_contest(spec, unit) and winner is not None: # CTS-B5, CTS-B7: only the winner's worktree is merged
992
+ merged, found = self._merge_children(state, [(mapping.slot(unit, winner.slot), winner.slot,
993
+ f"Merge contest slot {winner.slot} of {unit}")], attempt)
994
+ verdict_att.update(found)
995
+ if merged is None: # CTS-B9: a failed winner merge is a writer join conflict, the run branch put back
996
+ unit_j = {"verdict": str(Verdict.ESCALATE), "reason": "merge_conflict", "confidence": 1.0,
997
+ "confidence_source": "engine_placeholder", "blockers": [
998
+ {"criterion": "writer-branches", "place": p, "problem": f"conflicting change in {p}",
999
+ "fix": f"decide which change of contest slot {winner.slot} or the run's branch stays"}
1000
+ for p in found.get("conflicts") or []] or [
1001
+ {"criterion": "writer-branches",
1002
+ "problem": str(found.get("merge_error") or "the merge failed")}]}
1003
+ else: # the attempt's other slots' worktrees are discarded and their records kept; earlier attempts stand (WSP-B21)
1004
+ won = mapping.slot(unit, winner.slot)
1005
+ merged["children"] = [{**ch, "state": "discarded"} if str(ch.get("unit")).startswith(f"{unit}.")
1006
+ and ch.get("unit") != won and int(ch.get("visit", 1)) == attempt else ch
1007
+ for ch in merged.get("children") or []]
1008
+ extra["workspace"] = merged
1009
+ writes: dict[str, Any] = {**out, **extra}
1010
+ writes = fold(writes, {"attempts": {unit: verdict_att}, "judgements": {unit: unit_j},
1011
+ "maps": {unit: {"pick": {"winner": winner.slot if winner else None,
1012
+ "verdict": unit_j.get("verdict"),
1013
+ "order": [x.slot for x in contestmod.ordered(cands)],
1014
+ "attempt": attempt},
1015
+ "round": None, "skipped": None}}})
1016
+ if chosen is not None and winner is not None: # the plain keys are the winner's (CTS-B7)
1017
+ for chan in ("artifacts", "values", "facts"):
1018
+ loose: Mapping[str, Any] = state
1019
+ was: Mapping[str, Any] = (loose.get(chan) or {}).get(unit) or {}
1020
+ now: Mapping[str, Any] = (out.get(chan) or {}).get(unit) or {}
1021
+ plain = own_keys({**was, **now}, winner.slot)
1022
+ if plain:
1023
+ writes = fold(writes, {chan: {unit: plain}})
1024
+ return writes
1025
+
1026
+ def _map_item(self, unit: str, state: Mapping[str, Any], visit: int, workdir: Path, prev: Mapping[str, Any],
1027
+ path_units: list[str]) -> tuple[dict[str, Any] | None, dict[str, Any], dict[str, Any] | None]:
1028
+ """Fan-out at the start of a visit, then the item in hand (MAP-B8, MAP-B9, MAP-B10). Returns a finished state write
1029
+ when the list stops or skips the map, else the `maps` record and the item with its attempt number."""
1030
+ m = mapping.record(state, unit)
1031
+ run = {"path": {"units": path_units + [unit]}} if unit not in path_units else {}
1032
+ base = {"attempt": int(prev.get("attempt", 0)) + 1, "visit": visit, "ok": True, "text": "", "issues": [],
1033
+ "tools": [], "session_id": None, "escalate": None, "infra_spent": False, "check": None,
1034
+ "item": None, "timed_out": False}
1035
+ if m.get("visit") != visit:
1036
+ try:
1037
+ items = mapping.read_items(self.ctx.spec, unit, state, workdir)
1038
+ except mapping.MapFault as exc:
1039
+ self.ctx.log.write("map_items", unit=unit, visit=visit, count=exc.count, ids=[], error=exc.code,
1040
+ detail=str(exc))
1041
+ return ({"attempts": {unit: {**base, "ok": False, "map_fault": f"{unit}: {exc}"}}, "run": run},
1042
+ m, None)
1043
+ m = {"visit": visit, "items": [{"id": i.id, "text": i.text} for i in items], "passed": [],
1044
+ "attempts": dict(m.get("attempts") or {})}
1045
+ self.ctx.log.write("map_items", unit=unit, visit=visit, count=len(items), ids=[i.id for i in items])
1046
+ if not items: # `on_empty: skip` passes the map with no item
1047
+ return {"attempts": {unit: {**base, "map_skip": True}}, "maps": {unit: m}, "run": run}, m, None
1048
+ item = mapping.pending(m)
1049
+ if item is None: # every item passed already (a resume at the gate): nothing to run
1050
+ return {"attempts": {unit: {**dict(prev), "visit": visit}}, "maps": {unit: m}, "run": run}, m, None
1051
+ n = int((m.get("attempts") or {}).get(item["id"], 0)) + 1
1052
+ m["attempts"] = {**(m.get("attempts") or {}), item["id"]: n}
1053
+ return None, m, {**item, "attempt": n}
1054
+
1055
+ def map_move(self, unit: str, state: RunState) -> Move:
1056
+ """MAP-B8 to MAP-B10, MAP-B12, MAP-B13: the step node of a concurrent map. It reads the list once per visit, sends
1057
+ the next `concurrency` items that have not started to the item nodes, waits while items run, sends the items
1058
+ that wait for a person to their pause once nothing else can run, and when every item has passed merges the
1059
+ items of a writing map and runs the map's check once on the result, then goes on to the unit's judge."""
1060
+ spec = self.ctx.spec
1061
+ u = spec.units[unit]
1062
+ assert u.map is not None
1063
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
1064
+ prev = (state.get("attempts") or {}).get(unit) or {}
1065
+ judge_node = flow.node_names(unit)[1]
1066
+ workdir = self._workdir(state)
1067
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
1068
+ run = {"path": {"units": path_units + [unit]}} if unit not in path_units else {}
1069
+ writes: dict[str, Any] = {}
1070
+ m = mapping.record(state, unit)
1071
+ if m.get("visit") != visit: # a new visit: the list is read once, the items are all still to start
1072
+ self._boundary(state)
1073
+ if prev.get("visit") != visit:
1074
+ fp = gitmod.fingerprint(workdir)
1075
+ self.ctx.log.write("unit_entered", unit=unit, visit=visit, head_commit=fp.head, dirty=fp.dirty,
1076
+ entered_from=_entered_from(state, unit))
1077
+ base = {"attempt": int(prev.get("attempt", 0)) + 1, "visit": visit, "ok": True, "text": "", "issues": [],
1078
+ "tools": [], "session_id": None, "escalate": None, "infra_spent": False, "check": None,
1079
+ "item": None, "timed_out": False, "map_done": None, "map_skip": None, "map_fault": None}
1080
+ try:
1081
+ items = mapping.read_items(spec, unit, state, workdir)
1082
+ except mapping.MapFault as exc:
1083
+ self.ctx.log.write("map_items", unit=unit, visit=visit, count=exc.count, ids=[], error=exc.code,
1084
+ detail=str(exc))
1085
+ return Move({"attempts": {unit: {**base, "ok": False, "map_fault": f"{unit}: {exc}"}},
1086
+ "run": run}, goto=judge_node)
1087
+ self.ctx.log.write("map_items", unit=unit, visit=visit, count=len(items), ids=[i.id for i in items])
1088
+ stale = {k: None for k in m if k.startswith("st:") or k == "exit"} # nothing of an earlier visit stands
1089
+ fresh = {"visit": visit, "items": [{"id": i.id, "text": i.text} for i in items], "passed": [],
1090
+ **{k: v for k, v in m.items() if k.startswith("n:")}} # attempt numbers continue across visits
1091
+ writes = {"attempts": {unit: base}, "maps": {unit: {**stale, **fresh}}, "run": run}
1092
+ m = {**{k: v for k, v in m.items() if k not in stale}, **fresh}
1093
+ if not items: # `on_empty: skip` passes the map with no item
1094
+ writes["attempts"][unit]["map_skip"] = True
1095
+ return Move(writes, goto=judge_node)
1096
+ if flow.writer_map(spec, unit): # WSP-B19, WSP-B11: the checkpoint, then one worktree per item
1097
+ writes["workspace"] = self._enter_writer_map(unit, state, [i.id for i in items], visit)
1098
+ standing = {it["id"]: mapping.item_state(m, it["id"]) for it in m["items"]}
1099
+ if "started" in standing.values(): # items that run finish first, whatever the others wait for
1100
+ return Move(writes)
1101
+ if m.get("exit"): # an item stopped the map, or a person's rewind or a fallback left it (MAP-B10)
1102
+ return Move(writes, goto=str(m["exit"]["node"]))
1103
+ fresh_ids = [i for i, s in standing.items() if s is None]
1104
+ if fresh_ids:
1105
+ self._boundary(state)
1106
+ wave = fresh_ids[: u.map.concurrency]
1107
+ for iid in wave:
1108
+ at = mapping.slot(unit, iid)
1109
+ for channel in ("attempts", "judgements", "feedback", "pause"):
1110
+ writes.setdefault(channel, {})[at] = None
1111
+ writes.setdefault("counters", {})[at] = {"retries": 0, "infra": 0, "human": 0, "ladder": None,
1112
+ "loops": None}
1113
+ writes.setdefault("maps", {}).setdefault(unit, {})[f"st:{iid}"] = "started"
1114
+ return Move(writes, items=wave)
1115
+ parked = [i for i, s in standing.items() if s == "parked"]
1116
+ if parked:
1117
+ self._boundary(state)
1118
+ return Move(writes, items=parked, kind="human")
1119
+ return self._map_finish(unit, state, m, writes, prev, visit, judge_node)
1120
+
1121
+ def _enter_writer_map(self, unit: str, state: Mapping[str, Any], ids: Sequence[str], visit: int = 1
1122
+ ) -> dict[str, Any]:
1123
+ """WSP-B19, WSP-B11: entering a writing concurrent map commits the run worktree's uncommitted changes on the run's
1124
+ branch, then cuts one worktree per item from that commit, named for the map's `visit` (WSP-B20); the worktrees
1125
+ of earlier visits stay. A cut that fails ends the segment at this boundary (engine_error `workspace_refused`)
1126
+ with nothing left behind."""
1127
+ ws = dict(state.get("workspace") or {})
1128
+ try:
1129
+ if ws.get("mode") != "worktree":
1130
+ raise WorkspaceRefused("needs_worktree", f"writing map {unit}: the run has no worktree")
1131
+ rec = WorkspaceRecord.from_json(ws)
1132
+ run_path = Path(rec.path)
1133
+ gitmod.commit_all(run_path, f"tempergraph: checkpoint before {unit}")
1134
+ rec = cut_writers(rec, self.ctx.thread, [mapping.slot(unit, i) for i in ids], self.ctx.spec.worktree,
1135
+ self.ctx.state_root, read_include=self.ctx.read_worktreeinclude, kind="i", visit=visit)
1136
+ rec.last_head = gitmod.head(run_path)
1137
+ except (WorkspaceRefused, gitmod.GitError) as exc:
1138
+ word = exc.word if isinstance(exc, WorkspaceRefused) else "git_failed"
1139
+ self.ctx.log.write("engine_error", unit=unit, error="workspace_refused", detail=f"{word}: {exc}")
1140
+ raise Drain("workspace_refused") from None
1141
+ return rec.to_json()
1142
+
1143
+ def _map_finish(self, unit: str, state: Mapping[str, Any], m: Mapping[str, Any], writes: dict[str, Any],
1144
+ prev: Mapping[str, Any], visit: int, judge_node: str) -> Move:
1145
+ """Every item has passed (MAP-B10): the plain keys hold the last item of the list, the items of a writing map are
1146
+ merged in the order of the list, and the gate's check runs once on the merged worktree (MAP-B12, MAP-B13). No
1147
+ model session starts here: a merge conflict or a failing check ends the map blocked, for a person."""
1148
+ spec = self.ctx.spec
1149
+ u = spec.units[unit]
1150
+ ids = [it["id"] for it in m["items"]]
1151
+ att: dict[str, Any] = {"attempt": int(prev.get("attempt", 0)) + 1, "visit": visit, "ok": True, "text": "",
1152
+ "issues": [], "tools": [], "session_id": None, "escalate": None, "infra_spent": False,
1153
+ "check": None, "item": None, "timed_out": False, "map_done": True, "conflicts": None,
1154
+ "conflict_branch": None, "merge_error": None, "map_findings": None}
1155
+ writes.setdefault("attempts", {})[unit] = {**(writes.get("attempts") or {}).get(unit, {}), **att}
1156
+ writes.setdefault("maps", {}).setdefault(unit, {})["passed"] = ids
1157
+ last = f"[{ids[-1]}]"
1158
+ for channel in ("artifacts", "values", "facts"): # the plain key holds the last item of the list (MAP-B9)
1159
+ held = (state.get(channel) or {}).get(unit) or {}
1160
+ plain = {k[: -len(last)]: v for k, v in held.items() if k.endswith(last)}
1161
+ if plain:
1162
+ writes.setdefault(channel, {})[unit] = plain
1163
+ if not flow.writer_map(spec, unit):
1164
+ return Move(writes, goto=judge_node)
1165
+ merged, found = self._merge_items(unit, state, ids, visit)
1166
+ record = writes["attempts"][unit]
1167
+ record.update(found)
1168
+ if merged is None: # WSP-B12: the run branch is back where it was; no model session runs
1169
+ return Move(writes, goto=judge_node)
1170
+ writes["workspace"] = merged
1171
+ if u.gate.check is not None: # MAP-B12: once, on the run's worktree, over the joined result, with no item
1172
+ self._joined_check(unit, state, record, Path(str(merged["path"])), writes)
1173
+ return Move(writes, goto=judge_node)
1174
+
1175
+ def _joined_check(self, unit: str, state: Mapping[str, Any], record: dict[str, Any], workdir: Path,
1176
+ writes: dict[str, Any]) -> None:
1177
+ """MAP-B12, MAP-B13, KIL-B4: the map's check over the joined result, with no item. A failing check or a killed
1178
+ command sets `escalate` on `record`; the gate then asks a person. A `retry` at a command_killed pause runs this
1179
+ again after the killed commands ran alone (KIL-B9 to KIL-B11)."""
1180
+ cres, notes = self._check(unit, state, {**record, "item": None}, workdir)
1181
+ notes = [*(record.get("alone_notes") or []), *notes]
1182
+ record["alone_notes"] = []
1183
+ record["check"] = checkmod.to_json(cres)
1184
+ killed, killed_runs = checkmod.killed_commands(cres.runs, self._command_store()) # KIL-B4
1185
+ self.ctx.log.write("check", unit=unit, item=None, attempt=None,
1186
+ result="FAIL" if killed else cres.result,
1187
+ environmental=True if killed else cres.environmental, failed=checkmod.failed_ids(cres),
1188
+ evidence=check_evidence(cres.evidence), notes=notes,
1189
+ **({"reason": "command_killed"} if killed else {}))
1190
+ if cres.facts:
1191
+ writes.setdefault("facts", {}).setdefault(unit, {}).update(cres.facts)
1192
+ if killed:
1193
+ record["escalate"] = "command_killed"
1194
+ record["command_killed"] = killed
1195
+ record["killed_runs"] = killed_runs
1196
+ elif cres.result == "FAIL": # MAP-B13: blocked, not retried, the merge kept
1197
+ record["escalate"] = "map_check"
1198
+ else:
1199
+ return
1200
+ record["map_findings"] = [{"criterion": f.criterion or "check", "place": f.place, "problem": f.message,
1201
+ "fix": f.fix} for f in cres.findings if f.status == "fail"] or [
1202
+ {"criterion": "check", "problem": "check FAIL"}]
1203
+
1204
+ def _script_failed(self, unit: str, state: Mapping[str, Any], attempt: int, visit: int, name: str, env: bool,
1205
+ path_units: list[str], first: bool, arts: dict[str, str], entry_head: str = ""
1206
+ ) -> dict[str, Any]:
1207
+ """A failed `before` script fails the attempt with no session (SCR-B7, SCR-B2). An item of a map keeps the
1208
+ commit its first attempt started from, for the retry that follows (SRV-B35)."""
1209
+ record: dict[str, Any] = {
1210
+ "attempt": attempt, "visit": visit, "ok": False, "text": "", "issues": [], "tools": [],
1211
+ "session_id": None, "error_kind": f"script_failed:{name}", "infra_spent": False, "check": None,
1212
+ "escalate": "environmental" if env else None, "timed_out": False,
1213
+ **({"entry_head": entry_head} if entry_head else {})}
1214
+ run = {"path": {"units": path_units + [unit]}} if first and unit not in path_units else {}
1215
+ return {"attempts": {unit: record}, "artifacts": {unit: arts or None}, "run": run}
1216
+
1217
+ def _previous_unit(self, unit: str, path_units: list[str]) -> str | None:
1218
+ before = [p for p in path_units if p != unit]
1219
+ return before[-1] if before else None
1220
+
1221
+ def _fields(self, unit: str, state: Mapping[str, Any], attempt: int, visit: int, workdir: Path
1222
+ ) -> dict[str, str | None]:
1223
+ req = state.get("request") or {}
1224
+ out: dict[str, str | None] = {k: str(v) for k, v in (req.get("inputs") or {}).items()}
1225
+ ws = state.get("workspace") or {}
1226
+ out.update(task_id=self.ctx.task_id, thread_id=self.ctx.thread, workflow=self.ctx.spec.name, unit=unit,
1227
+ attempt=str(attempt), visit=str(visit), branch=ws.get("branch") or gitmod.branch(workdir),
1228
+ base=ws.get("base_branch") or "", workdir=str(workdir), run_label=None)
1229
+ for chan in ("artifacts", "values"):
1230
+ for owner, vals in (state.get(chan) or {}).items():
1231
+ if isinstance(vals, dict):
1232
+ out.update({k: str(v) for k, v in vals.items()})
1233
+ held = self.ctx.spec.units.get(owner)
1234
+ if held is not None and held.kind == "subworkflow": # SWF-B12: `{<unit>.<key>}`
1235
+ out.update({f"{owner}.{k}": str(v) for k, v in vals.items()})
1236
+ out.update(self._map_lines(unit, state))
1237
+ return out
1238
+
1239
+ def _map_lines(self, unit: str, state: Mapping[str, Any]) -> dict[str, str]:
1240
+ """VAL-B9: a key the step of a map before this unit produces renders one line `<item id>: <value>` for each
1241
+ item of the map's list that holds it, in list order, and `none` when no item does. An item's own template
1242
+ keeps the plain key."""
1243
+ order = list(self.ctx.spec.order)
1244
+ if unit not in order:
1245
+ return {}
1246
+ lines: dict[str, str] = {}
1247
+ for owner in order[: order.index(unit)]:
1248
+ held = self.ctx.spec.units.get(owner)
1249
+ if held is None or held.map is None or held.step is None:
1250
+ continue
1251
+ items = [str(it["id"]) for it in ((state.get("maps") or {}).get(owner) or {}).get("items") or []]
1252
+ for key in held.step.produces:
1253
+ found: list[str] = []
1254
+ for item in items:
1255
+ for chan in ("artifacts", "values"):
1256
+ got = ((state.get(chan) or {}).get(owner) or {}).get(f"{key}[{item}]")
1257
+ if got is not None:
1258
+ found.append(f"{item}: {got}")
1259
+ break
1260
+ lines[key] = "\n".join(found) or "none"
1261
+ return lines
1262
+
1263
+ # -- script units (SCR) ------------------------------------------------------------------------
1264
+
1265
+ def _run_script(self, sc: ScriptSpec, unit: str, attempt: int, phase: str, state: Mapping[str, Any],
1266
+ workdir: Path) -> tuple[bool, bool, dict[str, str], str]:
1267
+ """One script through the command runner or its callable (SCR-B5); returns ok, environmental, artifacts and
1268
+ the type name of the exception its callable raised ("" when none, SCR-B12)."""
1269
+ t0 = time.monotonic()
1270
+ artifacts: dict[str, str] = {}
1271
+ raised = ""
1272
+ ok, env, exit_code = True, False, None
1273
+ name = sc.name or (sc.run[0] if sc.run else unit)
1274
+ cache_key, cache_error = None, None
1275
+ folder = self.ctx.state_root / "runs" / self.ctx.spec.name / self.ctx.task_id / "cache"
1276
+ if sc.cache == "thread": # SCR-B9: a hit restores the recorded files and result and runs nothing
1277
+ try:
1278
+ cache_key = self._script_key(sc, unit, state, workdir)
1279
+ hit = scriptcache.lookup(folder, cache_key, workdir)
1280
+ except (scriptcache.CacheError, OSError) as exc: # an unreadable cache is a logged miss
1281
+ cache_key, hit, cache_error = None, None, type(exc).__name__
1282
+ if hit is not None:
1283
+ self.ctx.log.write("script", unit=unit, name=name, phase=phase, exit_code=hit.exit_code,
1284
+ command_prefix=sc.run[0] if sc.run else None,
1285
+ duration_s=round(time.monotonic() - t0, 3), environmental=False, cached=True,
1286
+ cache="hit")
1287
+ return True, False, {k: str(v) for k, v in hit.artifacts.items()}, ""
1288
+ if sc.run:
1289
+ tag = unit if phase == "unit" else f"{unit}.{phase}.{name}"
1290
+ out = self.ctx.state_root / "runs" / self.ctx.spec.name / self.ctx.task_id / "scripts" / tag / f"{attempt}.out"
1291
+ cmd = ResolvedCommand(argv=sc.run, prefix=sc.run[0])
1292
+ r = run_command(cmd, workdir, out, sc.timeout_s, main=self.ctx.main_checkout)
1293
+ if r.timed_out: # KIL-B1: a script's command killed at its limit leaves its row
1294
+ checkmod.store_killed(folder.parent / "command_runs.jsonl", checkmod.reuse_key(cmd, workdir), r)
1295
+ exit_code = r.exit_code
1296
+ ok = r.finished and r.exit_code == 0
1297
+ env = r.exit_code in sc.environmental_exit_codes or "error" in r.extra
1298
+ artifacts = parse_output(Path(out).read_text(encoding="utf-8", errors="replace") if Path(out).exists()
1299
+ else "", sc.produces).artifacts
1300
+ elif sc.call is not None:
1301
+ try:
1302
+ ws_state = state.get("workspace") or {}
1303
+ call_base = ws_state.get("base_commit") or ""
1304
+ got = sc.call.resolve()(checkmod.CheckContext(
1305
+ unit=unit, workdir=workdir, request=state.get("request") or {},
1306
+ artifacts=state.get("artifacts") or {}, values=state.get("values") or {},
1307
+ settings=dict(self.ctx.settings), # SCR-B5, RST-B25: what a check is given
1308
+ git=checkmod.GitFacts( # SCR-B10, SCR-B11: the own base is read at the call
1309
+ base=call_base,
1310
+ own_base=gitmod.own_base(Path(workdir), call_base, ws_state.get("base_branch") or "")
1311
+ if call_base else "")))
1312
+ artifacts = {str(k): str(v) for k, v in (got or {}).items()} if isinstance(got, dict) else {}
1313
+ except Exception as exc: # noqa: BLE001
1314
+ ok, env, raised = False, True, type(exc).__name__
1315
+ self.ctx.log.write("engine_error", unit=unit, error=raised)
1316
+ if cache_key is not None and ok and not env and all(k in artifacts for k in sc.produces):
1317
+ try: # only a run that finished and succeeded is recorded
1318
+ scriptcache.store(folder, cache_key, scriptcache.Result(
1319
+ exit_code=exit_code, artifacts=artifacts,
1320
+ kinds={k: v if isinstance(v, str) else "value" for k, v in sc.produces.items()}), workdir)
1321
+ except scriptcache.CacheError as exc:
1322
+ cache_error = str(exc)
1323
+ extra: dict[str, Any] = {"cache": "miss"} if sc.cache == "thread" else {}
1324
+ if cache_error:
1325
+ extra["cache_error"] = cache_error
1326
+ self.ctx.log.write("script", unit=unit, name=name, phase=phase, exit_code=exit_code,
1327
+ command_prefix=sc.run[0] if sc.run else None, duration_s=round(time.monotonic() - t0, 3),
1328
+ environmental=env, cached=False, **extra)
1329
+ return ok, env, artifacts, raised
1330
+
1331
+ def _script_key(self, sc: ScriptSpec, unit: str, state: Mapping[str, Any], workdir: Path) -> str:
1332
+ """SCR-B9: the digest of the argv or callable reference, the workflow's content digest, the arguments and
1333
+ each declared input's content digest. The files this unit's earlier visits produced are not part of the
1334
+ workspace input: a restore puts them back."""
1335
+ from tempergraph.package.loader import full_version
1336
+
1337
+ known: dict[str, str] = {k: str(v) for k, v in ((state.get("request") or {}).get("inputs") or {}).items()}
1338
+ for chan in ("artifacts", "values"):
1339
+ for vals in (state.get(chan) or {}).values():
1340
+ if isinstance(vals, dict):
1341
+ known.update({k: str(v) for k, v in vals.items() if v is not None})
1342
+ own = {str(v) for v in ((state.get("artifacts") or {}).get(unit) or {}).values() if v is not None}
1343
+ inputs = {n: scriptcache.input_digest(n, workdir, self.ctx.state_root, known, own) for n in sc.inputs}
1344
+ return scriptcache.key(argv=(sc.run[0],) if sc.run else (), reference=sc.call.ref if sc.call else None,
1345
+ workflow=full_version(self.ctx.spec), arguments=tuple(sc.run[1:]) if sc.run else (),
1346
+ inputs=inputs)
1347
+
1348
+ def _scripts(self, scripts: tuple[ScriptSpec, ...], unit: str, attempt: int, phase: str,
1349
+ state: Mapping[str, Any], workdir: Path) -> tuple[str | None, bool, dict[str, str]]:
1350
+ """Hybrid `before` or `after` scripts in declaration order; the first failure ends the phase."""
1351
+ arts: dict[str, str] = {}
1352
+ for sc in scripts:
1353
+ ok, env, got, _ = self._run_script(sc, unit, attempt, phase, state, workdir)
1354
+ arts.update(got)
1355
+ if not ok:
1356
+ return sc.name or (sc.run[0] if sc.run else phase), env, arts
1357
+ return None, False, arts
1358
+
1359
+ def _script_unit(self, unit: str, state: RunState) -> dict[str, Any]:
1360
+ sc = self.ctx.spec.units[unit].script
1361
+ assert sc is not None
1362
+ prev = (state.get("attempts") or {}).get(unit) or {}
1363
+ attempt = int(prev.get("attempt", 0)) + 1
1364
+ ok, env, artifacts, raised = self._run_script(sc, unit, attempt, "unit", state, self._workdir(state, unit))
1365
+ record = {"attempt": attempt, "visit": 1, "ok": ok, "text": "", "escalate": "environmental" if env else None,
1366
+ "infra_spent": False, "check": None, "script": True, "script_raised": raised or None}
1367
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
1368
+ run = {"path": {"units": path_units + [unit]}} if unit not in path_units else {}
1369
+ return {"attempts": {unit: record}, "artifacts": {unit: artifacts or None}, "run": run}
1370
+
1371
+ def _flow_unit(self, unit: str, state: RunState) -> dict[str, Any]:
1372
+ """A route or switch unit runs no session: its pick is made in the gate node (CMP-B10 to CMP-B16)."""
1373
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
1374
+ record: dict[str, Any] = {"attempt": 1, "visit": visit, "ok": True, "text": "", "escalate": None,
1375
+ "infra_spent": False, "check": None, "flow": True}
1376
+ sw = self.ctx.spec.units[unit].switch
1377
+ if sw is not None and sw.complexity is not None:
1378
+ prev = ((state.get("attempts") or {}).get(unit) or {}).get("complexity")
1379
+ record["complexity"] = prev or self._complexity(unit, state) # once per run (CXR-B7)
1380
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
1381
+ run = {"path": {"units": path_units + [unit]}} if unit not in path_units else {}
1382
+ return {"attempts": {unit: record}, "run": run}
1383
+
1384
+ def _join_unit(self, unit: str, state: RunState) -> dict[str, Any]:
1385
+ """A parallel block's join runs nothing: every branch has passed when this node starts (CMP-B4)."""
1386
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
1387
+ prev = (state.get("attempts") or {}).get(unit) or {}
1388
+ if prev.get("visit") != visit:
1389
+ fp = gitmod.fingerprint(self._workdir(state))
1390
+ self.ctx.log.write("unit_entered", unit=unit, visit=visit, head_commit=fp.head, dirty=fp.dirty,
1391
+ entered_from="join", branches=list(self.ctx.spec.units[unit].branches))
1392
+ record: dict[str, Any] = {"attempt": int(prev.get("attempt", 0)) + 1, "visit": visit, "ok": True, "text": "",
1393
+ "escalate": None, "infra_spent": False, "check": None, "join": True}
1394
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
1395
+ run = {"path": {"units": path_units + [unit]}} if unit not in path_units else {}
1396
+ out: dict[str, Any] = {"attempts": {unit: record}, "run": run}
1397
+ if flow.writer_branches(self.ctx.spec, unit): # no model session starts for a join, merged or not
1398
+ merged, found = self._merge_writers(unit, state)
1399
+ record.update(found)
1400
+ if merged is not None:
1401
+ out["workspace"] = merged
1402
+ return out
1403
+
1404
+ def _person_unit(self, unit: str, state: RunState) -> dict[str, Any]:
1405
+ """An ask or a wait runs nothing: its step node records the entry and the human node pauses (CMP-B10 to CMP-B16).
1406
+ An ask reads its questions here, once per visit, and starts the visit with no answers (ASK-B2)."""
1407
+ from tempergraph.run import asking
1408
+
1409
+ u = self.ctx.spec.units[unit]
1410
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
1411
+ prev = (state.get("attempts") or {}).get(unit) or {}
1412
+ workdir = self._workdir(state)
1413
+ if prev.get("visit") != visit:
1414
+ fp = gitmod.fingerprint(workdir)
1415
+ self.ctx.log.write("unit_entered", unit=unit, visit=visit, head_commit=fp.head, dirty=fp.dirty,
1416
+ entered_from=_entered_from(state, unit))
1417
+ record: dict[str, Any] = {"attempt": int(prev.get("attempt", 0)) + 1, "visit": visit, "ok": True, "text": "",
1418
+ "escalate": None, "infra_spent": False, "check": None, u.kind: True}
1419
+ if u.ask is not None:
1420
+ folder = self.ctx.state_root / "runs" / self.ctx.spec.name / self.ctx.task_id
1421
+ with contextlib.suppress(OSError):
1422
+ asking.answers_path(folder, unit).unlink()
1423
+ try:
1424
+ listed = asking.questions(u.ask, state, workdir)
1425
+ if u.ask.on_deadline == "defaults" and (gaps := asking.defaults_problems(listed)): # ASK-B13
1426
+ raise asking.AskFault(gaps[0])
1427
+ record["questions"] = [asking.to_json(q) for q in listed]
1428
+ except asking.AskFault as exc:
1429
+ record.update(ok=False, ask_fault=str(exc))
1430
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
1431
+ run = {"path": {"units": path_units + [unit]}} if unit not in path_units else {}
1432
+ return {"attempts": {unit: record}, "artifacts": {unit: None}, "values": {unit: None}, "run": run}
1433
+
1434
+ def _escalation_facts(self, unit: str, state: Mapping[str, Any], att: Mapping[str, Any],
1435
+ write: Mapping[str, Any]) -> dict[str, Any]:
1436
+ """What the gate cannot read from state for E1, E6 and E7 (LAD-B12): the stage, whether the escalation
1437
+ record is met, the median estimate of one attempt on the tier above and what the run cost cap leaves."""
1438
+ ctx = self.ctx
1439
+ met = ctx.escalation_record or (lambda u: laddermod.record_met(ctx.state_root, ctx.spec.name,
1440
+ ctx.spec.version, u))
1441
+ try:
1442
+ record_met = bool(met(unit))
1443
+ except Exception: # noqa: BLE001 - LAD-B14: a record that cannot be read is not met
1444
+ record_met = False
1445
+ known = sorted(float(x) for x in att.get("up_estimates") or [] if isinstance(x, int | float))
1446
+ estimate_usd = known[len(known) // 2] if known and len(known) == len(att.get("up_estimates") or []) else None
1447
+ cap = ctx.spec.run_cost_cap_usd
1448
+ cost = (write.get("run") or {}).get("cost") or write["judgements"][unit].get("_cost") or (
1449
+ state.get("run") or {}).get("cost")
1450
+ left = round(float(cap) - CostTotals.from_json(cost).figure(), 6) if cap is not None else None
1451
+ return {"stage": ctx.stage, "record_met": record_met, "estimate_usd": estimate_usd, "cap_left_usd": left}
1452
+
1453
+ def _judge_state(self) -> Callable[[str], str]:
1454
+ if self.ctx.judge_state is None:
1455
+ from tempergraph.improve import calibration
1456
+
1457
+ self.ctx.judge_state = calibration.state_name_for(self.ctx.spec, self.ctx.state_root,
1458
+ child=self.ctx.child) # SWF-B9: a child's own gates
1459
+ return self.ctx.judge_state
1460
+
1461
+ def _complexity(self, unit: str, state: Mapping[str, Any]) -> dict[str, Any]:
1462
+ """CXR-B9, CXR-B10, CXR-B1: the measures, the rules in force and the zone, evaluated in the switch's step node."""
1463
+ ctx = self.ctx
1464
+ workdir = self._workdir(state)
1465
+ maps = (dict, Mapping)
1466
+ mctx = MeasureContext(
1467
+ request=dict(state.get("request") or {}),
1468
+ facts={u: dict(f) for u, f in (state.get("facts") or {}).items() if isinstance(f, maps)},
1469
+ artifacts={u: dict(a) for u, a in (state.get("artifacts") or {}).items() if isinstance(a, maps)},
1470
+ settings=dict(ctx.settings), stage=ctx.stage, workdir=workdir,
1471
+ git=checkmod.git_facts(workdir, (state.get("workspace") or {}).get("base_commit") or "",
1472
+ (state.get("workspace") or {}).get("base_branch") or ""))
1473
+ return complexity.evaluate(ctx.spec, unit, state, mctx, state_root=ctx.state_root, thread=ctx.thread,
1474
+ origin=ctx.origin,
1475
+ recent=complexity.explored_recent(ctx.state_root, ctx.spec.name, unit))
1476
+
1477
+ # -- judge -----------------------------------------------------------------------------------
1478
+
1479
+ def _outcome_step(self, unit: str, state: RunState) -> dict[str, Any]:
1480
+ """OUT-B15, OUT-B16, OUT-B17: no session; the subject is final state, recorded for the judge and the record."""
1481
+ prev = (state.get("attempts") or {}).get(unit) or {}
1482
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
1483
+ attempt = int(prev.get("attempt", 0)) + 1
1484
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
1485
+ if prev.get("visit") != visit:
1486
+ fp = gitmod.fingerprint(self._workdir(state))
1487
+ self.ctx.log.write("unit_entered", unit=unit, visit=visit, head_commit=fp.head, dirty=fp.dirty,
1488
+ entered_from=_entered_from(state, unit))
1489
+ o = self.ctx.spec.outcome
1490
+ record = {"attempt": attempt, "visit": visit, "ok": True, "text": "", "issues": [], "tools": [],
1491
+ "session_id": None, "escalate": None, "infra_spent": False, "check": None,
1492
+ "deliverables": [dict(d) for d in (o.deliverables if o else ())]}
1493
+ run = {"path": {"units": path_units + [unit]}} if unit not in path_units else {}
1494
+ return {"attempts": {unit: record}, "run": run}
1495
+
1496
+ def judge(self, unit: str, state: RunState) -> dict[str, Any]:
1497
+ if self.ctx.spec.units[unit].kind == "contest" and mapping.item_in_hand(state) is None:
1498
+ return self._contest_judge(unit, state) # CTS-B7: every slot graded alone, then the pick
1499
+ w = self._judge(unit, state)
1500
+ if self.ctx.spec.units[unit].extra.get("outcome"):
1501
+ w = self._route_outcome(unit, state, w)
1502
+ return w
1503
+
1504
+ def _route_outcome(self, unit: str, state: RunState, w: dict[str, Any]) -> dict[str, Any]:
1505
+ """A failing outcome gate goes back to the earliest serving unit on the path, else escalates (OUT-B15, OUT-B16, OUT-B17)."""
1506
+ from tempergraph.run.outcome import derived_back
1507
+
1508
+ j = dict((w.get("judgements") or {}).get(unit) or {})
1509
+ if j.get("verdict") not in (str(Verdict.RETRY), str(Verdict.BACK)):
1510
+ return w
1511
+ o = self.ctx.spec.outcome
1512
+ finals = [str(c.id) for c in (o.final if o else ())]
1513
+ failing = [b.get("criterion") for b in j.get("blockers") or [] if b.get("criterion") in finals] or finals
1514
+ path = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
1515
+ target = derived_back(self.ctx.spec, failing, path)
1516
+ if target:
1517
+ j.update(verdict=str(Verdict.BACK), back_to=target, reason="outcome_serves")
1518
+ else:
1519
+ j.update(verdict=str(Verdict.ESCALATE), reason="outcome_no_serving_unit")
1520
+ return {**w, "judgements": {**(w.get("judgements") or {}), unit: j}}
1521
+
1522
+ def _judge(self, unit: str, state: RunState) -> dict[str, Any]:
1523
+ spec = self.ctx.spec
1524
+ u = spec.units[unit]
1525
+ g = u.gate
1526
+ att = dict((state.get("attempts") or {}).get(unit) or {})
1527
+ # KIL-B9: a `retry` at a command_killed pause; no step ran, the commands run alone first
1528
+ held: dict[str, Any] = {} # what a joined map check run again writes (KIL-B10, KIL-B11)
1529
+ if att.get("alone"):
1530
+ if (again := self._runs_alone(unit, state, att)) is not None:
1531
+ return again
1532
+ if att.get("map_done") and g.check is not None: # the check that was killed runs again and decides
1533
+ held = {"attempts": {unit: att}}
1534
+ att.update(map_findings=None)
1535
+ self._joined_check(unit, state, att, self._workdir(state), held)
1536
+ att["alone_runs"] = [] # the runs alone answered this check only
1537
+ if att.get("map_fault"):
1538
+ return {"judgements": {unit: {"verdict": str(Verdict.ESCALATE), "reason": "map_fault"}}}
1539
+ if u.kind in ("ask", "wait"): # no model and no judge: the person's input is the bar (ASK, WFM-B4)
1540
+ return {"judgements": {unit: {"verdict": str(Verdict.ESCALATE), "reason": u.kind}}}
1541
+ if att.get("map_skip"):
1542
+ return {"judgements": {unit: {"verdict": str(Verdict.PROCEED), "reason": "map_empty"}}}
1543
+ if att.get("map_done") and not att.get("escalate"): # MAP-B10: a concurrent map whose items all passed (and merged)
1544
+ return {**held, "judgements": {unit: {"verdict": str(Verdict.PROCEED), "reason": "map_items_passed"}}}
1545
+ if u.kind == "subworkflow" and (done := self._child_verdict(unit, att)) is not None:
1546
+ return done
1547
+ if att.get("council_stop"): # CNL-B13: no decision with `on_no_decision: stop`; the gate stops the run
1548
+ return {"judgements": {unit: {"verdict": str(Verdict.ESCALATE), "reason": "no_decision", "confidence": 1.0,
1549
+ "confidence_source": "engine_placeholder"}}}
1550
+ if (att.get("escalate") == "upstream" and att.get("upstream") and att.get("ok") and g.judge is not None
1551
+ and not att.get("infra_spent")):
1552
+ return self._judge_claim(unit, state, att)
1553
+ if att.get("infra_spent") or att.get("escalate"):
1554
+ placeholder: dict[str, Any] = {"verdict": str(Verdict.ESCALATE), "reason": att.get("escalate") or "infra",
1555
+ "confidence": 1.0, "confidence_source": "engine_placeholder"}
1556
+ if att.get("escalate") == "merge_conflict": # WSP-B12: the pause lists the conflicting paths
1557
+ placeholder["blockers"] = [
1558
+ {"criterion": "writer-branches", "place": p, "problem": f"conflicting change in {p}",
1559
+ "fix": f"decide which change of writer branch {att.get('conflict_branch')} or the run's branch stays"}
1560
+ for p in att.get("conflicts") or []] or [
1561
+ {"criterion": "writer-branches", "problem": str(att.get("merge_error") or "the join failed")}]
1562
+ if att.get("script_raised"): # SCR-B12: the pause names the exception type, and nothing else of it
1563
+ placeholder["blockers"] = [{"criterion": "script", "place": unit,
1564
+ "problem": f"the unit's callable raised {att['script_raised']}"}]
1565
+ if att.get("escalate") == "map_check" or (att.get("escalate") == "command_killed"
1566
+ and att.get("map_findings")): # MAP-B13: the joined check's findings
1567
+ placeholder["blockers"] = list(att.get("map_findings") or [])
1568
+ return {**held, "judgements": {unit: placeholder}}
1569
+ if not att.get("ok"):
1570
+ problem = att.get("error_kind") or ("timed out" if att.get("timed_out") else "the step failed")
1571
+ if att.get("written"): # WSP-B11, CNL-B14: a read-only member wrote to the workspace; its paths are reported
1572
+ problem += ": " + ", ".join(str(p) for p in att["written"])
1573
+ return {"judgements": {unit: {"verdict": str(Verdict.RETRY), "reason": "step_failed", "blockers": [
1574
+ {"criterion": "step", "problem": problem}]}}}
1575
+ bad = [i for i in att.get("issues") or [] if i.startswith(("value_missing", "value_invalid"))]
1576
+ if bad:
1577
+ return {"judgements": {unit: {"verdict": str(Verdict.RETRY), "reason": "output_contract", "blockers": [
1578
+ {"criterion": "output", "problem": i} for i in bad]}}}
1579
+ if att.get("dissent_missing"): # CNL-B12: the built-in check; its failure is retryable
1580
+ return {"judgements": {unit: {"verdict": str(Verdict.RETRY), "reason": "council_dissent",
1581
+ "blockers": [council_dissent_blocker(unit)]}}}
1582
+ workdir = self._workdir(state, unit)
1583
+ cres, notes = self._check(unit, state, att, workdir)
1584
+ notes = [*(att.get("alone_notes") or []), *notes]
1585
+ att["alone_runs"], att["alone_notes"] = [], [] # KIL-B10: the runs alone answered this check only
1586
+ att["check"] = checkmod.to_json(cres)
1587
+ iid = att.get("item")
1588
+ facts: dict[str, Any] = dict(cres.facts or {})
1589
+ if att.get("foreign_worktrees"): # WTR-B26: the step's fact outlives the check's own facts
1590
+ facts["foreign_worktrees"] = att["foreign_worktrees"]
1591
+ if iid:
1592
+ facts.update({mapping.item_key(k, str(iid)): v for k, v in list(facts.items())})
1593
+ write: dict[str, Any] = {"attempts": {unit: att},
1594
+ "facts": {unit: facts} if iid and facts else {} if iid else {unit: facts or None}}
1595
+ killed, killed_runs = checkmod.killed_commands(cres.runs, self._command_store()) # KIL-B4
1596
+ self.ctx.log.write("check", unit=unit, item=iid, attempt=att.get("attempt") if iid else None, # per item
1597
+ result="FAIL" if killed else cres.result,
1598
+ environmental=True if killed else cres.environmental, failed=checkmod.failed_ids(cres),
1599
+ evidence=check_evidence(cres.evidence), notes=notes,
1600
+ **({"reason": "command_killed"} if killed else {})) # KIL-B5
1601
+ if killed: # KIL-B4: before every other class; no retry, no infra try, no judge session
1602
+ att["escalate"] = "command_killed"
1603
+ att["command_killed"] = killed
1604
+ att["killed_runs"] = killed_runs
1605
+ env_blockers = [{"criterion": f.criterion or "check", "place": f.place, "problem": f.message,
1606
+ "fix": f.fix} for f in cres.findings if f.status == "fail"] # HUM-B21
1607
+ write["judgements"] = {unit: {"verdict": str(Verdict.ESCALATE), "reason": "command_killed",
1608
+ "blockers": env_blockers or [{"criterion": "check",
1609
+ "problem": "check FAIL"}]}}
1610
+ return write
1611
+ if cres.result == "FAIL":
1612
+ if cres.environmental:
1613
+ att["escalate"] = "environmental"
1614
+ env_blockers = [{"criterion": f.criterion or "check", "place": f.place, "problem": f.message,
1615
+ "fix": f.fix} for f in cres.findings if f.status == "fail"] # HUM-B21
1616
+ write["judgements"] = {unit: {"verdict": str(Verdict.ESCALATE), "reason": "environmental",
1617
+ "blockers": env_blockers or [{"criterion": "check",
1618
+ "problem": "check FAIL"}]}}
1619
+ elif self._repeats(att, cres): # BUD-B16: the same failure again although files changed: no retry helps
1620
+ att["escalate"] = "check_repeat"
1621
+ att["repeated"] = checkmod.failing(cres)
1622
+ att["repeated_evidence"] = cres.evidence
1623
+ write["judgements"] = {unit: {"verdict": str(Verdict.ESCALATE), "reason": "check_repeat"}}
1624
+ else:
1625
+ blockers = [{"criterion": f.criterion or "check", "place": f.place, "problem": f.message, "fix": f.fix}
1626
+ for f in cres.findings if f.status == "fail"]
1627
+ if g.judge is None and g.on_fail == "back" and blockers and len(g.back_targets) == 1: # HUM-B15
1628
+ write["judgements"] = {unit: {"verdict": str(Verdict.BACK), "back_to": g.back_targets[0],
1629
+ "reason": "check_fail", "blockers": blockers}}
1630
+ else:
1631
+ write["judgements"] = {unit: {"verdict": str(Verdict.RETRY), "reason": "check_fail",
1632
+ "blockers": blockers or [{"criterion": "check",
1633
+ "problem": "check FAIL"}]}}
1634
+ return write
1635
+ if g.judge is None: # a script unit gated by its check alone
1636
+ write["judgements"] = {unit: {"verdict": str(Verdict.PROCEED), "reason": "check_only"}}
1637
+ return write
1638
+ write["judgements"] = {unit: self._judge_session(unit, state, att, cres, workdir)}
1639
+ if u.step is not None and (u.step.effort_ladder or u.step.escalation is not None or any(
1640
+ sw.switch is not None and unit in sw.switch.rearm_units() for sw in spec.units.values())):
1641
+ level = (write["judgements"][unit].get("risk") or {}).get("level") # a level is its own binding
1642
+ g_names = [lv.name for lv in g.judge.risk.levels] if g.judge.risk is not None else []
1643
+ raised = level in g_names[1:]
1644
+ # the gate reads trust from the judgement (LAD-B10)
1645
+ state_of = self._judge_state()(f"{unit}@{level}" if raised else unit)
1646
+ write["judgements"][unit].update(judge_state=state_of, trusted=laddermod.trusted(state_of, self.ctx.stage))
1647
+ if u.step.escalation is not None or gatemod.arm_overrides(spec, unit, state)[0].get("escalation"):
1648
+ write["judgements"][unit]["escalation"] = self._escalation_facts(unit, state, att, write)
1649
+ if write["judgements"][unit].get("reason") == "usage_limit": # JDG-B14: the attempt keeps the cause and the instant
1650
+ att.update(escalate="usage_limit", usage_limit_stage="judge",
1651
+ usage_limit_resets_at=write["judgements"][unit].get("usage_limit_resets_at"))
1652
+ if write["judgements"][unit].get("infra_spent"):
1653
+ att["infra_spent"] = True
1654
+ att["infra_cause"] = "judge_infra"
1655
+ return {**write, "run": {"cost": write["judgements"][unit].pop("_cost")}} if "_cost" in write["judgements"][
1656
+ unit] else write
1657
+
1658
+ def _runs_alone(self, unit: str, state: RunState, att: dict[str, Any]) -> dict[str, Any] | None:
1659
+ """KIL-B9, KIL-B12: each killed command of the pause run by itself, in order, one at a time, under the gate's
1660
+ `check_timeout_s`, in this process. None: none was killed again and the check goes on, answering from the runs
1661
+ alone (`att` now holds them). A kill again: no check runs and the gate pauses again with the facts of that kill;
1662
+ the runs that finished stay on the attempt for the next `retry`."""
1663
+ g = self.ctx.spec.units[unit].gate
1664
+ ctx = self._check_context(unit, state, att, self._workdir(state, unit), sub="-alone")
1665
+ assert ctx.out_dir is not None
1666
+ kept = [dict(r) for r in att.get("alone_runs") or []]
1667
+ ran: list[CommandRun] = []
1668
+ skipped: list[str] = []
1669
+ try:
1670
+ for k in att.get("killed_runs") or []:
1671
+ r = checkmod.run_alone(ctx, k, ctx.out_dir / f"{len(kept) + len(ran) + 1}.out", float(g.check_timeout_s))
1672
+ if r is not None:
1673
+ ran.append(r)
1674
+ else: # it no longer resolves, did not start, or its recorded arguments were redacted: the check meets it
1675
+ skipped.append(f"a killed command ({k.get('prefix') or 'no prefix'}) could not be run alone; "
1676
+ "the check runs it as any command")
1677
+ finally:
1678
+ ctx.cleanup()
1679
+ killed, killed_runs = checkmod.killed_commands([r.to_json() for r in ran], self._command_store())
1680
+ att["alone"] = False
1681
+ att["alone_notes"] = [*(att.get("alone_notes") or []), *skipped] # KIL-B9: reported in the next check record
1682
+ att["alone_runs"] = kept + [r.to_json() for r in ran if not r.timed_out]
1683
+ if not killed:
1684
+ att.update(escalate=None, command_killed=None, killed_runs=None)
1685
+ return None
1686
+ att.update(escalate="command_killed", command_killed=killed, killed_runs=killed_runs)
1687
+ return {"attempts": {unit: att},
1688
+ "judgements": {unit: {"verdict": str(Verdict.ESCALATE), "reason": "command_killed",
1689
+ "blockers": [{"criterion": "check", "problem": "check FAIL"}]}}}
1690
+
1691
+ def _child_verdict(self, unit: str, att: Mapping[str, Any]) -> dict[str, Any] | None:
1692
+ """SWF-B5: what the child's end says about the unit's gate, before anything else is checked. An upstream defect
1693
+ in a key the unit mapped into `inputs` goes back to the parent unit that made it when it is a back target of
1694
+ the gate (the gate's own rule), else asks a person; a child that stopped or ended `unmet` or `needs_person`
1695
+ fails the gate with the child's failing final criteria as blockers. None: the child ended well."""
1696
+ up = att.get("upstream_child")
1697
+ if up:
1698
+ blockers = [{"criterion": "upstream", "problem": str(up.get("reason") or "an upstream defect"),
1699
+ "defect_in": up.get("key")}]
1700
+ if up.get("unit") in self.ctx.spec.units[unit].gate.back_targets:
1701
+ return {"judgements": {unit: {"verdict": str(Verdict.BACK), "back_to": up["unit"], "blockers": blockers,
1702
+ "reason": "upstream_confirmed", "confidence": 1.0,
1703
+ "confidence_source": "child_judge"}}}
1704
+ return {"judgements": {unit: {"verdict": str(Verdict.ESCALATE), "reason": "upstream", "blockers": blockers,
1705
+ "confidence": 1.0, "confidence_source": "child_judge"}}}
1706
+ failing = att.get("child_failed")
1707
+ if failing:
1708
+ return {"judgements": {unit: {"verdict": str(Verdict.RETRY), "reason": "child_unmet", "blockers": [
1709
+ {"criterion": str(f.get("criterion")), "problem": str(f.get("problem"))} for f in failing]}}}
1710
+ return None
1711
+
1712
+ @staticmethod
1713
+ def _repeats(att: Mapping[str, Any], cres: CheckResult) -> bool:
1714
+ """BUD-B16: this failing check equals the previous attempt's, and this attempt's step changed files."""
1715
+ prior = att.get("prior_failing")
1716
+ if not prior or not att.get("changed"):
1717
+ return False
1718
+ return checkmod.repeat_key(prior.get("findings") or [], str(prior.get("evidence") or "")) \
1719
+ == checkmod.repeat_key(checkmod.failing(cres), cres.evidence)
1720
+
1721
+ def _judge_claim(self, unit: str, state: RunState, att: dict[str, Any]) -> dict[str, Any]:
1722
+ """A step's upstream claim is judged on its own against one criterion: confirmed goes BACK, refuted
1723
+ retries, undecided asks a person (BUD-B10, HUM-B7 to HUM-B11). No check runs: the step produced nothing to check."""
1724
+ target, defect = (str(x) for x in att["upstream"])
1725
+ j = self._judge_session(unit, state, att, None, self._workdir(state, unit), claim=(target, defect))
1726
+ cost = j.pop("_cost", None)
1727
+ verdict = j.get("verdict")
1728
+ if j.get("infra_spent"):
1729
+ att["infra_spent"], att["infra_cause"] = True, "judge_infra"
1730
+ elif verdict == str(Verdict.PROCEED): # the one criterion is MET: the defect is there
1731
+ j.update(verdict=str(Verdict.BACK), back_to=target, reason="upstream_confirmed",
1732
+ blockers=[{"criterion": CLAIM_CRITERION_ID, "problem": defect}])
1733
+ att["escalate"] = None
1734
+ elif verdict == str(Verdict.RETRY):
1735
+ j.update(reason="upstream_refuted")
1736
+ att["escalate"] = None
1737
+ else:
1738
+ j.update(verdict=str(Verdict.ESCALATE), reason="upstream")
1739
+ write: dict[str, Any] = {"attempts": {unit: att}, "judgements": {unit: j}}
1740
+ return {**write, "run": {"cost": cost}} if cost is not None else write
1741
+
1742
+ def _check(self, unit: str, state: Mapping[str, Any], att: Mapping[str, Any], workdir: Path
1743
+ ) -> tuple[CheckResult, list[str]]:
1744
+ u = self.ctx.spec.units[unit]
1745
+ ctx = self._check_context(unit, state, att, workdir)
1746
+ skey = att.get("session_key")
1747
+ if isinstance(skey, str) and skey.rsplit(".", 1)[-1] in ("step", "retry"): # CHK-B24: no other check has a record
1748
+ calls = read_session(session_dir(self.ctx.state_root, self.ctx.spec.name, self.ctx.task_id, skey))
1749
+ ctx.session = None if calls is None else tuple(calls)
1750
+ if calls is not None: # VSR-B1, VSR-B2: the attempts of this visit and item, in order; no record adds no call
1751
+ held = att.get("visit_keys")
1752
+ keys = [k for k in held if isinstance(k, str)] if isinstance(held, list) and held else [skey]
1753
+ visit_calls: list[Any] = []
1754
+ for k in keys:
1755
+ if k.rsplit(".", 1)[-1] not in ("step", "retry"):
1756
+ continue
1757
+ got_calls = calls if k == skey else read_session(
1758
+ session_dir(self.ctx.state_root, self.ctx.spec.name, self.ctx.task_id, k))
1759
+ visit_calls.extend(got_calls or ())
1760
+ ctx.visit_session = tuple(visit_calls)
1761
+ got = run_in_worker(u.gate, ctx)
1762
+ if not self.ctx.capture.check_output and ctx.out_dir is not None: # `observe.check_output = off`
1763
+ for f in ctx.out_dir.glob("*.out"):
1764
+ with contextlib.suppress(OSError):
1765
+ f.unlink()
1766
+ return got
1767
+
1768
+ def _check_context(self, unit: str, state: Mapping[str, Any], att: Mapping[str, Any], workdir: Path,
1769
+ sub: str = "") -> checkmod.CheckContext:
1770
+ from tempergraph.run.guard import filter_owned_changed_paths
1771
+
1772
+ u = self.ctx.spec.units[unit]
1773
+ st = u.step
1774
+ ex_name = (st.executor if st else None) or self.ctx.spec.default_executor
1775
+ try:
1776
+ owned = self.ctx.registry.get(ex_name).capabilities().launcher_owned_paths
1777
+ except Exception: # noqa: BLE001 - registry miss or unknown executor: treat as no owned paths
1778
+ owned = ()
1779
+ facts = {k: v for k, v in (state.get("facts") or {}).items() if k != unit}
1780
+ gfacts = checkmod.git_facts(workdir, (state.get("workspace") or {}).get("base_commit") or "",
1781
+ (state.get("workspace") or {}).get("base_branch") or "")
1782
+ return checkmod.CheckContext(
1783
+ changed_paths=filter_owned_changed_paths(checkmod.changed_paths(
1784
+ workdir, gfacts, self.ctx.state_root / "runs" / self.ctx.spec.name / self.ctx.task_id / "manifest.json"),
1785
+ owned),
1786
+ unit=unit, item=att.get("item"), workdir=workdir, request=state.get("request") or {},
1787
+ attempt=int(att.get("attempt", 1)),
1788
+ visit=int(att.get("visit", 1)), main_checkout=self.ctx.main_checkout,
1789
+ artifacts=state.get("artifacts") or {}, values=state.get("values") or {}, facts=facts,
1790
+ git=gfacts,
1791
+ criteria=tuple({"id": c.id, "mechanical": c.mechanical} for c in u.gate.criteria),
1792
+ allow=tuple(self.ctx.spec.allow_commands),
1793
+ alone=[checkmod.command_run_from(r) for r in att.get("alone_runs") or [] if isinstance(r, dict)],
1794
+ out_dir=self.ctx.state_root / "runs" / self.ctx.spec.name / self.ctx.task_id / "checks"
1795
+ / (f"{unit}.{att['item']}" if att.get("item") else unit) / (str(att.get("attempt", 1)) + sub),
1796
+ settings={**self._check_settings(u), **({"path_units": list(
1797
+ ((state.get("run") or {}).get("path") or {}).get("units") or [])} if u.extra.get("outcome") else {})},
1798
+ reuse_store=self.ctx.state_root / "runs" / self.ctx.spec.name / self.ctx.task_id / "command_runs.jsonl")
1799
+
1800
+ def _command_store(self) -> Path:
1801
+ return self.ctx.state_root / "runs" / self.ctx.spec.name / self.ctx.task_id / "command_runs.jsonl"
1802
+
1803
+ def _check_settings(self, u: UnitSpec) -> dict[str, Any]:
1804
+ o = self.ctx.spec.outcome
1805
+ if not u.extra.get("outcome") or o is None:
1806
+ return dict(self.ctx.settings) # the workflow-declared settings a check reads (RST-B25)
1807
+ from tempergraph.run.outcome import deliverable_producers
1808
+
1809
+ return {**self.ctx.settings, "deliverables": [dict(d) for d in o.deliverables],
1810
+ "deliverable_producers": deliverable_producers(self.ctx.spec),
1811
+ "outcome_check": o.check.ref if o.check else None}
1812
+
1813
+ @staticmethod
1814
+ def _reachable_views(ex: Any, views: ViewSet, workdir: Path) -> ViewSet:
1815
+ """ECC-B15: an MCP view whose server has no working proxy on this executor (not in the operator's
1816
+ configuration, defined by a URL, or exits at start) is deferred for the attempt and its tools are dropped from
1817
+ the judge's views, so the prompt names the artifact out of reach and no tool of that server is offered."""
1818
+ check = getattr(ex, "unreachable_views", None) # an executor that fronts MCP servers itself has it
1819
+ if check is None or not any(t.startswith("mcp__") for t in views.tools):
1820
+ return views
1821
+ down: Mapping[str, str] = check(views, workdir)
1822
+ if not down:
1823
+ return views
1824
+ from tempergraph.contracts import Deferred
1825
+ from tempergraph.executors import mcpconfig
1826
+
1827
+ lost = [Deferred(capability=f"mcp:{server}/{tool}", reason=f"mcp_{down[server]}")
1828
+ for server, tools in mcpconfig.viewed_servers(views.tools).items() if server in down for tool in tools]
1829
+ keep = tuple(t for t in views.tools if not (t.startswith("mcp__") and t.split("__", 2)[1] in down))
1830
+ return dataclasses.replace(views, tools=keep, deferred=(*views.deferred, *lost))
1831
+
1832
+ def _entry_commit(self, unit: str, visit: int) -> str:
1833
+ """SRV-B34, SRV-B36: the commit recorded when the unit's visit was entered (EVT-B12), the first record of the
1834
+ unit and visit in this run's log; empty when none holds one."""
1835
+ from tempergraph.run.events import records
1836
+ from tempergraph.run.subrun import root_log
1837
+
1838
+ try:
1839
+ for r in records(root_log(self.ctx.log).path):
1840
+ if r.get("kind") == "unit_entered" and r.get("unit") == unit and r.get("visit") == visit \
1841
+ and r.get("child") == self.ctx.child:
1842
+ return str(r.get("head_commit") or "")
1843
+ except Exception: # noqa: BLE001 - observability never changes the run (OVR-B4)
1844
+ return ""
1845
+ return ""
1846
+
1847
+ def _declared_files(self, unit: str, state: Mapping[str, Any], workdir: Path) -> set[str]:
1848
+ """SRV-B41: the workspace-relative paths of the file artifacts the units of the run's path (and `unit`) declare
1849
+ in `produces`, every item's of a map included; `./x`, `x` and an absolute path inside the workspace name one
1850
+ path."""
1851
+ spec = self.ctx.spec
1852
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
1853
+ out: set[str] = set()
1854
+ root = os.path.normpath(str(workdir))
1855
+ for name in dict.fromkeys([*path_units, unit]):
1856
+ u = spec.units.get(name)
1857
+ produces = getattr(u.step, "produces", None) if u is not None and u.step is not None else None
1858
+ values = (state.get("artifacts") or {}).get(name) or {}
1859
+ for key, kind in (produces or {}).items():
1860
+ if kind != "file":
1861
+ continue
1862
+ # a map keeps each item's value as `<key>[<item id>]`; the plain key is only the item in hand (MAP-B9)
1863
+ for held, value in values.items():
1864
+ if held != key and not (held.startswith(f"{key}[") and held.endswith("]")):
1865
+ continue
1866
+ p = os.path.normpath(str(value))
1867
+ if os.path.isabs(p):
1868
+ if not (p == root or p.startswith(root + os.sep)):
1869
+ continue
1870
+ p = os.path.relpath(p, root)
1871
+ out.add(p)
1872
+ return out
1873
+
1874
+ def _judge_count(self, unit: str, state: Mapping[str, Any], workdir: Path, base: str, g: Any) -> dict[str, Any]:
1875
+ """SRV-B34, SRV-B37 to SRV-B43: the judge's own record fields. The lists of checks, git facts, the session's
1876
+ own record and the suites stay unfiltered (`gitmod.changed_paths`)."""
1877
+ problem = None
1878
+ try:
1879
+ problem = gitmod.base_problem(workdir, base)
1880
+ except Exception: # noqa: BLE001 - observability never changes the run (OVR-B4)
1881
+ problem = "outside_repository"
1882
+ if problem is not None:
1883
+ return {"changed_base": None, "changed_base_reason": problem, "changed_left_out": 0}
1884
+ try:
1885
+ listed = gitmod.judge_changed_paths(workdir, base, 100000)
1886
+ except Exception: # noqa: BLE001
1887
+ listed = []
1888
+ declared = self._declared_files(unit, state, workdir)
1889
+ listed = [p for p in listed if p not in declared]
1890
+ patterns = tuple(getattr(g, "judge_may_skip", ()) or ())
1891
+ kept = [p for p in listed if not any(_skip_match(p, pat) for pat in patterns)]
1892
+ return {"changed_paths": kept[:200], "changed_base": base, "changed_left_out": len(listed) - len(kept)}
1893
+
1894
+ def _judge_session(self, unit: str, state: Mapping[str, Any], att: Mapping[str, Any], cres: CheckResult | None,
1895
+ workdir: Path, claim: tuple[str, str] | None = None) -> dict[str, Any]:
1896
+ spec = self.ctx.spec
1897
+ u = spec.units[unit]
1898
+ g = u.gate
1899
+ st = u.step if u.step is not None else StepSpec() # a sub-workflow unit has no step: its judge reads what `produces` exposes
1900
+ assert g.judge is not None
1901
+ j = g.judge
1902
+ if claim: # one engine criterion replaces the gate's own; the subject is the claimed unit's output
1903
+ g = dataclasses.replace(g, criteria=(claim_criterion(*claim),))
1904
+ else: # OUT-B10, OUT-B12: a judge grades no criterion a person signs or nobody verifies
1905
+ g = judged(g)
1906
+ step_ex = st.executor or spec.default_executor
1907
+ judge_name = self.ctx.judges.get(unit) or self.ctx.registry.judge_executor(step_ex, j.executor,
1908
+ self.ctx.judge_override)
1909
+ ex = self.ctx.registry.get(judge_name)
1910
+ caps = ex.capabilities()
1911
+ from tempergraph.contracts import ToolCall # local: keeps the module's import list short
1912
+
1913
+ views = view_set(st, [ToolCall(name=t) for t in att.get("tools") or []], caps, j.tools,
1914
+ granted=tuple(u.extra.get("views_add") or ()))
1915
+ views = self._reachable_views(ex, views, workdir) # ECC-B15: before the prompt names what is out of reach
1916
+ stance, brief = j.stance, j.brief
1917
+ if j.file:
1918
+ from tempergraph.contracts import TextRef
1919
+
1920
+ stance, brief = split_judge_file(load_text(spec, TextRef(path=j.file)))
1921
+ subject_unit = claim[0] if claim else unit
1922
+ arts = (state.get("artifacts") or {}).get(subject_unit) or {}
1923
+ vals = (state.get("values") or {}).get(subject_unit) or {}
1924
+ if u.contest is not None and att.get("item"): # CTS-B3: one candidate's artifacts, no other slot's
1925
+ arts, vals = own_keys(arts, str(att["item"])), own_keys(vals, str(att["item"]))
1926
+ refs: dict[str, str] = {}
1927
+ for ref in j.references:
1928
+ for chan in ("artifacts", "values"):
1929
+ for vs in (state.get(chan) or {}).values():
1930
+ if isinstance(vs, dict) and ref in vs:
1931
+ refs[ref] = str(vs[ref])
1932
+ inputs = (state.get("request") or {}).get("inputs") or {}
1933
+ for ref in j.references: # a reference may name a request input (validation allows it)
1934
+ if ref not in refs and ref != "request" and ref in inputs:
1935
+ refs[ref] = str(inputs[ref])
1936
+ req_text = str(inputs.get("request", ""))
1937
+ subject = {**{k: str(v) for k, v in arts.items()}, **{k: str(v) for k, v in vals.items()}}
1938
+ if u.kind == "council": # CNL-B4: the judge grades `decision`, with `positions` among its references
1939
+ subject, more = council_inputs(vals)
1940
+ for k, v in more.items():
1941
+ refs.setdefault(k, v)
1942
+ prompt = render_judge(JudgeInputs(
1943
+ gate=g, stance=stance, brief=brief, request=req_text, references=refs,
1944
+ subject=subject,
1945
+ out_of_reach=[d.capability for d in views.deferred], check=cres, step_account=str(att.get("text") or ""),
1946
+ workspace_facts={"branch": gitmod.branch(workdir), "changed": len(gitmod.changed_paths(workdir))},
1947
+ feedback=str(((state.get("feedback") or {}).get(unit) or {}).get("text") or ""),
1948
+ rulings=tuple(gatemod.active_rulings(spec, state, unit)),
1949
+ visit_reason=str(((state.get("visits") or {}).get(unit) or {}).get("reason") or "")))
1950
+ alias = j.model or "inherit" # resolved on the judge chain alone (RST-B22, RST-B23, CON-B3)
1951
+ attempt = int(att.get("attempt", 1))
1952
+ iid = att.get("item")
1953
+ jopts = j.session_options or SessionOptions()
1954
+ risk = self._risk(unit, state, att, cres, workdir, j) if j.risk is not None else None
1955
+ if risk is not None: # JRK-B8: the level's alias and effort for this attempt; a pin keeps its own
1956
+ alias = risk.pop("model") or alias
1957
+ effort = risk.pop("effort")
1958
+ if effort:
1959
+ jopts = dataclasses.replace(jopts, effort=effort)
1960
+ self.ctx.log.write("judge_risk", unit=unit, item=iid, attempt=attempt, alias=alias,
1961
+ effort=jopts.effort, **risk)
1962
+ key = self._skey(unit, attempt, "judge", item=iid)
1963
+ req = SessionRequest(kind="judge", prompt=prompt, workdir=workdir, alias=alias, session_key=key,
1964
+ timeout_s=j.timeout_s or DEFAULT_TIMEOUT_S, idle_s=j.idle_s,
1965
+ options=jopts,
1966
+ session_dir=session_dir(self.ctx.state_root, spec.name, self.ctx.task_id, key))
1967
+ before = gitmod.fingerprint(workdir)
1968
+ base = str(att.get("entry_head") or "") if u.map is not None else self._entry_commit(
1969
+ unit, int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1)))
1970
+ counted = self._judge_count(unit, state, workdir, base, g) # the digest's `changed_read` (SRV-B11, SRV-B34)
1971
+ hold = self._hold(unit, state)
1972
+ res, results = self._session(ex, req, views, extra=counted, hold=hold)
1973
+ all_results = list(results)
1974
+ out: dict[str, Any] = {"judge_executor": judge_name, "alias": alias, "views": list(views.tools)}
1975
+ if risk is not None:
1976
+ out["risk"] = risk
1977
+ if not res.ok and res.usage_limit: # JDG-B14: a refusal derives no verdict and spends nothing
1978
+ return self._judge_limited(out, res, state, all_results)
1979
+ if res.infra_cause is not None:
1980
+ out.update(verdict=str(Verdict.ESCALATE), infra_spent=True, reason="judge_infra")
1981
+ out["_cost"] = self._cost(state, all_results)
1982
+ return out
1983
+ judgement = None
1984
+ if not res.timed_out:
1985
+ try:
1986
+ judgement = parse_judgement(res.text, g)
1987
+ except Unparsed:
1988
+ rkey = self._skey(unit, attempt, "judge_reask", item=iid)
1989
+ rreq = SessionRequest(kind="judge_reask", prompt=reask_prompt(res.text, g), workdir=workdir,
1990
+ alias=alias, session_key=rkey, timeout_s=req.timeout_s, idle_s=req.idle_s,
1991
+ options=req.options,
1992
+ session_dir=session_dir(self.ctx.state_root, spec.name, self.ctx.task_id, rkey))
1993
+ res2, r2 = self._session(ex, rreq, views, hold=hold)
1994
+ all_results += r2
1995
+ if not res2.ok and res2.usage_limit:
1996
+ return self._judge_limited(out, res2, state, all_results)
1997
+ try:
1998
+ judgement = parse_judgement(res2.text, g)
1999
+ except Unparsed:
2000
+ judgement = None
2001
+ after = gitmod.fingerprint(workdir)
2002
+ gkey = key # the judge session whose calls the last guard read
2003
+ gr = guard(views, res.tool_calls, before, after, workspace_mode=(state.get("workspace") or {}).get(
2004
+ "mode", "in_place"), step_session_id=att.get("session_id"), judge_session_id=res.session_id,
2005
+ reports_actions=caps.reports_actions, launcher_owned_paths=caps.launcher_owned_paths)
2006
+ if gr.status == "discarded":
2007
+ judgement = None
2008
+ reread: dict[str, Any] | None = None
2009
+ if judgement is not None and reread_needed(judgement, g, cres): # JDG-B17: one re-read, never a third session
2010
+ mk = marked_reading(judgement, g, cres)
2011
+ ckey = self._skey(unit, attempt, "judge_reread", item=iid)
2012
+ creq = SessionRequest(kind="judge_reread", prompt=reread_prompt(prompt, judgement, mk.marked, g),
2013
+ workdir=workdir, alias=alias, session_key=ckey, timeout_s=req.timeout_s,
2014
+ idle_s=req.idle_s, options=req.options,
2015
+ session_dir=session_dir(self.ctx.state_root, spec.name, self.ctx.task_id, ckey))
2016
+ before3 = gitmod.fingerprint(workdir) # JDG-B21: the re-read has a guard window of its own
2017
+ res3, r3 = self._session(ex, creq, views, hold=hold)
2018
+ all_results += r3
2019
+ if not res3.ok and res3.usage_limit:
2020
+ return self._judge_limited(out, res3, state, all_results)
2021
+ if res3.infra_cause is not None: # JDG-B5: the attempt ends as for any judge session
2022
+ out.update(verdict=str(Verdict.ESCALATE), infra_spent=True, reason="judge_infra")
2023
+ out["_cost"] = self._cost(state, all_results)
2024
+ return out
2025
+ gkey = ckey
2026
+ reread = {"criteria": [g.criteria[i - 1].id or i for i in mk.marked], "gap": mk.gap_marked} # JDG-B22
2027
+ judgement = None # JDG-B19: the verdict comes from the re-read's judgement alone
2028
+ if not res3.timed_out:
2029
+ try:
2030
+ judgement = parse_judgement(res3.text, g)
2031
+ except Unparsed:
2032
+ r3key = self.ctx.key_prefix + session_key(unit, attempt, "judge_reask", item=iid, n=2)
2033
+ r3req = SessionRequest(kind="judge_reask", prompt=reask_prompt(res3.text, g), workdir=workdir,
2034
+ alias=alias, session_key=r3key, timeout_s=req.timeout_s,
2035
+ idle_s=req.idle_s, options=req.options,
2036
+ session_dir=session_dir(self.ctx.state_root, spec.name,
2037
+ self.ctx.task_id, r3key))
2038
+ res4, r4 = self._session(ex, r3req, views, hold=hold)
2039
+ all_results += r4
2040
+ if not res4.ok and res4.usage_limit:
2041
+ return self._judge_limited(out, res4, state, all_results)
2042
+ try:
2043
+ judgement = parse_judgement(res4.text, g)
2044
+ except Unparsed:
2045
+ judgement = None
2046
+ gr = guard(views, res3.tool_calls, before3, gitmod.fingerprint(workdir), workspace_mode=(
2047
+ state.get("workspace") or {}).get("mode", "in_place"), step_session_id=att.get("session_id"),
2048
+ judge_session_id=res3.session_id, reports_actions=caps.reports_actions)
2049
+ if gr.status == "discarded":
2050
+ judgement = None
2051
+ back_units: dict[str, str] = {}
2052
+ for target in flow.effective_order(spec):
2053
+ if target in g.back_targets:
2054
+ tu = spec.units[target]
2055
+ for k in (tu.step.produces if tu.step else {}):
2056
+ back_units[k] = target
2057
+ for b in tu.branches: # a defect in a branch's output sends the run back to its block
2058
+ bu = spec.units.get(b)
2059
+ for k in (bu.step.produces if bu is not None and bu.step else {}):
2060
+ back_units[k] = target
2061
+ outcome = derive(judgement, g, cres, {} if claim else back_units)
2062
+ guard_facts: dict[str, Any] | None = None
2063
+ if judgement is None and gr.status == "discarded":
2064
+ outcome.reason = f"guard:{gr.reason}"
2065
+ guard_facts = self._guard_facts(gr, gkey, caps, u.step, att)
2066
+ self.ctx.log.write("judgement", unit=unit, item=iid, attempt=attempt, statuses=outcome.statuses, blockers=[
2067
+ b["criterion"] for b in outcome.blockers], confidence=outcome.confidence,
2068
+ confidence_source=outcome.confidence_source, gap=outcome.gap, guard=gr.status, views=list(views.tools),
2069
+ judge_executor=judge_name, brief_digest=brief_digest(stance, brief),
2070
+ criteria_digest=criteria_digest(g.criteria), **({"claim": claim[0]} if claim else {}),
2071
+ **({"reread": reread} if reread is not None else {}),
2072
+ **({"deferred": [{"capability": d.capability, "reason": d.reason} for d in views.deferred]}
2073
+ if views.deferred else {}),
2074
+ **({"level": risk["level"]} if risk is not None else {}))
2075
+ self._keep_evidence(unit, att, outcome.blockers)
2076
+ out.update(outcome.to_json())
2077
+ out["guard"] = gr.status
2078
+ if guard_facts:
2079
+ out["guard_facts"] = guard_facts
2080
+ out["_cost"] = self._cost(state, all_results) # the audit judge's cost is in no counter (JDG-B7)
2081
+ if claim is None and judgement is not None and self._audit_drawn(unit, iid, attempt):
2082
+ self._audit_judgement(unit, iid, attempt, ex, req, views, g, cres, state, att, workdir)
2083
+ return out
2084
+
2085
+ def _guard_facts(self, gr: Any, key: str, caps: Any, step: Any, att: Mapping[str, Any]) -> dict[str, Any]:
2086
+ """HUM-B23: what broke the guard, as ids only: the reason word and, for an outside call, the tool, whether a
2087
+ subagent made it and, for a shell tool, the longest declared command prefix or `undeclared` (never the line)."""
2088
+ reason = str(gr.reason or "").split(":", 1)[0]
2089
+ if reason != "outside_call":
2090
+ return {"reason": reason}
2091
+ facts: dict[str, Any] = {"reason": reason, "tool": gr.tool, "subagent": bool(gr.subagent), "prefix": None}
2092
+ if gr.tool:
2093
+ try:
2094
+ calls = read_session(session_dir(self.ctx.state_root, self.ctx.spec.name, self.ctx.task_id, key))
2095
+ except Exception: # noqa: BLE001 - a journal that cannot be read gives `undeclared`
2096
+ calls = None
2097
+ seen = next((c for c in calls or () if c.get("name") == gr.tool), None)
2098
+ if (seen or {}).get("capability") == "shell" or tool_access.capability_of(caps, gr.tool) == "shell":
2099
+ line = (seen or {}).get("target")
2100
+ prefixes = (*(step.commands if step is not None else ()), *self.ctx.spec.allow_commands)
2101
+ facts["prefix"] = tool_access._prefix_of(line, prefixes) if isinstance(line, str) and line.strip() \
2102
+ else "undeclared"
2103
+ return facts
2104
+
2105
+ def _judge_limited(self, out: dict[str, Any], res: SessionResult, state: Mapping[str, Any],
2106
+ results: list[SessionResult]) -> dict[str, Any]:
2107
+ """JDG-B14: the usage limit ended a judge session; the gate gets the ESCALATE placeholder, no `judgement` record."""
2108
+ out.update(verdict=str(Verdict.ESCALATE), reason="usage_limit", confidence=1.0,
2109
+ confidence_source="engine_placeholder", usage_limit_resets_at=res.usage_limit_resets_at)
2110
+ out["_cost"] = self._cost(state, results)
2111
+ return out
2112
+
2113
+ # -- the sampled audit judge (JDG-B7) ---------------------------------------------------------------
2114
+
2115
+ def _audit_drawn(self, unit: str, iid: str | None, attempt: int) -> bool:
2116
+ return auditmod.sampled(self.ctx.audit_rate, seed=self.ctx.audit_seed, thread=self.ctx.thread, unit=unit,
2117
+ item=iid, attempt=attempt)
2118
+
2119
+ def _audit_judgement(self, unit: str, iid: str | None, attempt: int, judge_ex: Executor, req: SessionRequest,
2120
+ views: Any, g: Any, cres: CheckResult | None, state: Mapping[str, Any],
2121
+ att: Mapping[str, Any], workdir: Path) -> None:
2122
+ """A second judge on the same prompt and views, on the audit executor when one is set, under its own
2123
+ session key. The result waits for the gate record of this attempt, which it must follow; no verdict,
2124
+ route, counter or budget reads it, and any failure of the audit leaves no trace but its session log."""
2125
+ try:
2126
+ name = self.ctx.audit_executor or judge_ex.name
2127
+ ex = judge_ex if name == judge_ex.name else self.ctx.registry.get(name)
2128
+ key = session_key(unit, attempt, "audit", item=iid)
2129
+ areq = dataclasses.replace(req, session_key=key, session_dir=session_dir(
2130
+ self.ctx.state_root, self.ctx.spec.name, self.ctx.task_id, key))
2131
+ caps = ex.capabilities()
2132
+ mode = (state.get("workspace") or {}).get("mode", "in_place")
2133
+
2134
+ def session(r: SessionRequest) -> tuple[SessionResult, list[SessionResult]]:
2135
+ return self._session(ex, r, views) # no reservation: an audit holds none of a cap
2136
+
2137
+ before = gitmod.fingerprint(workdir)
2138
+
2139
+ def discarded(res: SessionResult) -> bool:
2140
+ return guard(views, res.tool_calls, before, gitmod.fingerprint(workdir), workspace_mode=mode,
2141
+ step_session_id=att.get("session_id"), judge_session_id=res.session_id,
2142
+ reports_actions=caps.reports_actions,
2143
+ launcher_owned_paths=caps.launcher_owned_paths).status == "discarded"
2144
+
2145
+ found = auditmod.run(session, areq, gate=g, check=cres, executor=name, discarded=discarded)
2146
+ except Exception: # noqa: BLE001 - an audit that cannot run changes nothing
2147
+ return
2148
+ if found is not None:
2149
+ self._audits[(unit, iid)] = {"item": iid, "attempt": attempt, **found.fields()}
2150
+
2151
+ def _risk(self, unit: str, state: Mapping[str, Any], att: Mapping[str, Any], cres: CheckResult | None,
2152
+ workdir: Path, j: Any) -> dict[str, Any]:
2153
+ """JRK-B7, JRK-B8: the rule on model-free facts of the attempt, then the level that grades it."""
2154
+ from tempergraph.contracts import RiskContext
2155
+ from tempergraph.run import risk as riskmod
2156
+
2157
+ ctx = self.ctx
2158
+ maps = (dict, Mapping)
2159
+ facts = {u: dict(f) for u, f in (state.get("facts") or {}).items() if isinstance(f, maps)}
2160
+ if cres is not None and cres.facts:
2161
+ facts[unit] = {**facts.get(unit, {}), **dict(cres.facts)}
2162
+ escalated = bool(att.get("escalated"))
2163
+ rctx = RiskContext(
2164
+ unit=unit, item=att.get("item"), visit=int(att.get("visit", 1)), attempt=int(att.get("attempt", 1)),
2165
+ git=riskmod.git_of(checkmod.git_facts(workdir, (state.get("workspace") or {}).get("base_commit") or "",
2166
+ (state.get("workspace") or {}).get("base_branch") or ""),
2167
+ workdir),
2168
+ facts=facts, request=dict((state.get("request") or {}).get("inputs") or {}), settings=dict(ctx.settings),
2169
+ stage=ctx.stage, producer={"alias": att.get("alias"), "escalated": escalated,
2170
+ "source": "escalation:+1" if escalated else "declared"})
2171
+ opts = j.session_options
2172
+ pinned = any(k in (ctx.spec.units[unit].extra.get("judge_operator_set") or ()) for k in riskmod.PIN_KEYS)
2173
+ return riskmod.resolve(j.risk, riskmod.run_rule(j.risk, rctx), base_model=j.model,
2174
+ base_effort=opts.effort if opts else None, pinned=pinned,
2175
+ producer_rank=riskmod.rank(att.get("alias")) if escalated else None)
2176
+
2177
+ def _keep_evidence(self, unit: str, att: Mapping[str, Any], blockers: list[dict[str, Any]]) -> None:
2178
+ """One judgement's evidence and fix lines per attempt, scrubbed and local only (LOS-B7, LOS-B8, LOS-B9, RDD-B7 to RDD-B11, RDD-B13, RDD-B15)."""
2179
+ if not blockers:
2180
+ return
2181
+ from tempergraph.docs import write_json
2182
+ from tempergraph.store.layout import run_dir
2183
+
2184
+ visit, attempt = int(att.get("visit", 1)), int(att.get("attempt", 1))
2185
+ path = (run_dir(self.ctx.state_root, self.ctx.spec.name, self.ctx.task_id) / "evidence" / "judgements"
2186
+ / (f"{unit}.{att['item']}" if att.get("item") else unit) / f"{visit}.{attempt}.json")
2187
+ rows = [{"criterion": b.get("criterion"),
2188
+ "evidence": clip(scrub(str(b.get("evidence") or b.get("problem") or "")), 400),
2189
+ "fix": clip(scrub(str(b.get("fix") or "")), 400)} for b in blockers]
2190
+ with contextlib.suppress(OSError):
2191
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
2192
+ write_json(path, {"schema_version": 1, "unit": unit, "visit": visit, "attempt": attempt,
2193
+ "blockers": rows}, mode=0o600)
2194
+
2195
+ # -- gate, human, finalizer --------------------------------------------------------------------
2196
+
2197
+ def gate(self, unit: str, state: RunState) -> dict[str, Any]:
2198
+ w = gatemod.decide(self.ctx.spec, unit, state, self.ctx.task_id)
2199
+ if (state.get("feedback") or {}).get(unit):
2200
+ w.setdefault("feedback", {})[unit] = None # one-time: seen by the attempt and its judge (RRN-B14, RRN-B15)
2201
+ r = w["route"][unit]
2202
+ so_far = cost_so_far((state.get("run") or {}).get("cost"))
2203
+ self.ctx.log.write("gate", unit=unit, item=((state.get("attempts") or {}).get(unit) or {}).get("item"),
2204
+ verdict=((state.get("judgements") or {}).get(unit) or {}).get("verdict"),
2205
+ token=r["token"], route_target=r["node"], cost_so_far=so_far)
2206
+ if r["token"] == "BACK":
2207
+ to = ((state.get("judgements") or {}).get(unit) or {}).get("back_to") or r["node"]
2208
+ self.ctx.trips[to] = self.ctx.trips.get(to, 0) + 1
2209
+ done = self._audits.pop((unit, ((state.get("attempts") or {}).get(unit) or {}).get("item")), None)
2210
+ if done is not None: # JDG-B7: the audit record follows the gate of the judgement it audits
2211
+ self.ctx.log.write("audit_judge", unit=unit, **done)
2212
+ self._budget_records(unit, state, w)
2213
+ if r.get("ladder"): # LAD-B16, LAD-B17: every gate that chose the next attempt's rung
2214
+ self.ctx.log.write("ladder_decision", unit=unit, **r["ladder"])
2215
+ att = (state.get("attempts") or {}).get(unit) or {}
2216
+ if att.get("escalated"): # LAD-B16, LAD-B17: the escalation record
2217
+ laddermod.record_escalation(
2218
+ self.ctx.state_root, workflow=self.ctx.spec.name, version=self.ctx.spec.version, unit=unit,
2219
+ thread=self.ctx.thread, passed=r["token"] in ("PROCEED", "NEXT"), to=str(att.get("escalated_to")),
2220
+ judge_state=((state.get("judgements") or {}).get(unit) or {}).get("judge_state"))
2221
+ for name, rr in w["route"].items(): # every pick: predicate, default, operator or re-arm (OBS `route`)
2222
+ p = (rr or {}).get("pick")
2223
+ if p and (name == unit or p.get("chosen_by") == "rearm"):
2224
+ self.ctx.log.write("route", unit=name, arm=p["arm"], target=p["target"], chosen_by=p["chosen_by"],
2225
+ **{k: p[k] for k in ("shadow", "would_choose", "signals", "signals_clipped",
2226
+ "fault", "rearmed_from", "rearm_unit", "rearm_cause",
2227
+ *gatemod.COMPLEXITY_FIELDS)
2228
+ if k in p})
2229
+ if unit in (w.get("pause") or {}) and w["pause"][unit]:
2230
+ p = w["pause"][unit]
2231
+ self.ctx.log.write("pause", unit=unit, item=p.get("item"), pause_kind=p["kind"], decisions=p["decisions"], resume=p["resume"],
2232
+ cost_so_far=so_far, reason=p.get("reason"), escalation=p.get("escalation"),
2233
+ tool_access=[{k: t.get(k) for k in ("name", "capability", "class", "path_class", "prefix")
2234
+ if k in ("name", "capability", "class") or t.get(k) is not None}
2235
+ for t in p.get("tool_access") or []] or None,
2236
+ **({"guard": p["guard"]} if p.get("guard") else {}),
2237
+ **({"deadline_at": p["deadline_at"], "on_deadline": p.get("on_deadline")}
2238
+ if p.get("deadline_at") else {}),
2239
+ **({"usage_limit_resets_at": p["usage_limit_resets_at"]}
2240
+ if "usage_limit_resets_at" in p else {}),
2241
+ **({"command_killed": p["command_killed"]} if p.get("command_killed") else {}),
2242
+ **({"questions": len(p["questions"])} if p.get("questions") is not None else {}))
2243
+ return w
2244
+
2245
+ def _budget_records(self, unit: str, state: RunState, w: Mapping[str, Any]) -> None:
2246
+ """EVT-B10 to EVT-B16 `budget`: one record per counter this gate charged, with its limit and cause."""
2247
+ g = self.ctx.spec.units[unit].gate
2248
+ before = (state.get("counters") or {}).get(unit) or {}
2249
+ after = (w.get("counters") or {}).get(unit) or {}
2250
+ cause = ((state.get("judgements") or {}).get(unit) or {}).get("reason") or "verdict"
2251
+ if int(after.get("retries", 0)) > int(before.get("retries", 0)):
2252
+ self.ctx.log.write("budget", unit=unit, counter="retries", used=int(after["retries"]),
2253
+ limit=g.retry_budget, cause=cause)
2254
+ old_loops = before.get("loops") or {}
2255
+ for target, n in (after.get("loops") or {}).items():
2256
+ if int(n) > int(old_loops.get(target, 0)):
2257
+ self.ctx.log.write("budget", unit=unit, counter=f"loops:{target}", used=int(n), limit=g.loop_budget,
2258
+ cause=cause)
2259
+
2260
+ def human(self, unit: str, state: RunState, decision: Any) -> dict[str, Any]:
2261
+ payload = decision if isinstance(decision, dict) else {"decision": str(decision)}
2262
+ w = gatemod.apply_decision(self.ctx.spec, unit, state, payload)
2263
+ self.ctx.log.write("human", unit=unit, decision=payload.get("decision"), caller=payload.get("caller"),
2264
+ feedback=bool(payload.get("feedback")) and not payload.get("ruling"))
2265
+ if payload.get("council_decision") is not None: # CNL-B13, EVT-B15: the person's answer is the council's outcome
2266
+ held = (state.get("attempts") or {}).get(unit) or {}
2267
+ tally = held.get("council", {}).get("tally") or {}
2268
+ self.ctx.log.write("council_tally", unit=unit, attempt=held.get("attempt"), mode=tally.get("mode"),
2269
+ rule=tally.get("rule"), counts=tally.get("counts"),
2270
+ outcome=str(payload["council_decision"]), chosen_by="person")
2271
+ p = (w.get("pause") or {}).get(unit)
2272
+ if p: # an applied deadline turned the pause into an escalation (FLX-B8)
2273
+ self.ctx.log.write("pause", unit=unit, item=p.get("item"), pause_kind=p["kind"], decisions=p["decisions"],
2274
+ resume=p["resume"], reason=p.get("reason"),
2275
+ cost_so_far=cost_so_far((state.get("run") or {}).get("cost")))
2276
+ used = int((((w.get("counters") or {}).get(unit)) or {}).get("command_killed", 0))
2277
+ if used > int((((state.get("counters") or {}).get(unit)) or {}).get("command_killed", 0)):
2278
+ self.ctx.log.write("budget", unit=unit, counter="command_killed", used=used,
2279
+ limit=self.ctx.command_killed_retries, cause="command_killed")
2280
+ return w
2281
+
2282
+ def finalizer(self, state: RunState) -> dict[str, Any]:
2283
+ from tempergraph.run.finalize import run_finalizer
2284
+
2285
+ result = run_finalizer(self.ctx, state)
2286
+ self.ctx.log.write("finalize", **result)
2287
+ if result.get("manual_steps") or result.get("outcome") == "error": # FIN-B8: seen, not only logged
2288
+ import sys
2289
+
2290
+ reason = str(result.get("reason") or "").replace("\n", " ")
2291
+ sys.stderr.write(f"{self.ctx.thread}: finalizer {result.get('outcome')}: {reason}\n")
2292
+ return {"finalized": {"done": True, **result}}
2293
+
2294
+
2295
+ def _entered_from(state: Mapping[str, Any], unit: str) -> str:
2296
+ """EVT-B10 to EVT-B16 `entered_from`: `start`, `proceed`, `back:<unit>`, `rewind:<unit>` or `resume`."""
2297
+ v = (state.get("visits") or {}).get(unit) or {}
2298
+ if v.get("entered_from"):
2299
+ return str(v["entered_from"])
2300
+ if int(v.get("visit", 1)) > 1 and v.get("from"):
2301
+ return f"back:{v['from']}"
2302
+ path = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
2303
+ return "proceed" if path else "start"
2304
+