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,527 @@
1
+ """A council attempt, session by session (CNL-B1, CNL-B2, CNL-B11 to CNL-B15, ADR `new-node-kinds-keep-the-gated-unit`, ADR `council-is-a-gated-step-with-engine-tallied-outcomes`).
2
+
3
+ `compiler.graph` builds the unit's step node as a small subgraph (one member dispatch per round and member, a barrier,
4
+ a tally node and the chair node) and calls the methods of `CouncilRun` from its nodes. This module owns what the nodes
5
+ do: the member, re-ask and chair sessions with their keys, the fingerprints around each member, the caps, and the
6
+ state write the step node hands back. What a council decides without a session lives in `run.council`.
7
+
8
+ Each member session is kept on its own, under its session key, as soon as it ends (`council_result.json` in its
9
+ folder). The step node's own state write is made once, at the end, so a crash or a drain in the middle of a round
10
+ leaves the state as it was and the rerun of the attempt finds the sessions that ended and runs only the others.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import hashlib
17
+ import json
18
+ import threading
19
+ from collections.abc import Mapping, Sequence
20
+ from dataclasses import dataclass, field
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from tempergraph import git as gitmod
25
+ from tempergraph.compiler.state import council_answers
26
+ from tempergraph.contracts import (
27
+ CouncilSpec,
28
+ SessionOptions,
29
+ SessionRequest,
30
+ SessionResult,
31
+ ToolCall,
32
+ Usage,
33
+ )
34
+ from tempergraph.docs import write_json
35
+ from tempergraph.model.text import load_text
36
+ from tempergraph.render.template import render
37
+ from tempergraph.run import council as cn
38
+ from tempergraph.run.log import CostTotals
39
+ from tempergraph.security.scrub import clip, scrub
40
+ from tempergraph.store.layout import session_dir
41
+
42
+ RESULT_FILE = "council_result.json"
43
+ DEFAULT_TIMEOUT_S = 600
44
+
45
+
46
+ # -- sessions kept on their own ---------------------------------------------------------------------------------
47
+
48
+
49
+ def dump_result(res: SessionResult) -> dict[str, Any]:
50
+ return {"ok": res.ok, "text": res.text, "session_id": res.session_id, "usage": res.usage.to_json(),
51
+ "tools": [c.name for c in res.tool_calls], "timed_out": res.timed_out, "stalled": res.stalled,
52
+ "partial": res.partial, "error_kind": res.error_kind, "cli_version": res.cli_version, "model": res.model,
53
+ "duration_s": res.duration_s, "tool_wall_share": res.tool_wall_share, "denied": list(res.denied),
54
+ "tools_at_start": list(res.tools_at_start)}
55
+
56
+
57
+ def load_result(d: Mapping[str, Any]) -> SessionResult:
58
+ return SessionResult(
59
+ ok=bool(d["ok"]), text=str(d.get("text") or ""), session_id=d.get("session_id"),
60
+ usage=Usage(**dict(d.get("usage") or {})), tool_calls=[ToolCall(name=str(n)) for n in d.get("tools") or []],
61
+ timed_out=bool(d.get("timed_out")), stalled=bool(d.get("stalled")), partial=bool(d.get("partial")),
62
+ error_kind=d.get("error_kind"), cli_version=str(d.get("cli_version") or ""), model=d.get("model"),
63
+ duration_s=d.get("duration_s"), tool_wall_share=float(d.get("tool_wall_share") or 0.0),
64
+ denied=tuple(d.get("denied") or ()), tools_at_start=tuple(d.get("tools_at_start") or ()))
65
+
66
+
67
+ def _digest(text: str) -> str:
68
+ return hashlib.sha256(text.encode()).hexdigest()[:16]
69
+
70
+
71
+ @dataclass(kw_only=True)
72
+ class CouncilRun:
73
+ """One attempt of one council unit, shared by the nodes of its subgraph (never checkpointed itself)."""
74
+
75
+ engine: Any # EngineNodes
76
+ unit: str
77
+ council: CouncilSpec
78
+ state: Mapping[str, Any]
79
+ attempt: int
80
+ visit: int
81
+ entered: bool
82
+ workdir: Path
83
+ question: str
84
+ options: tuple[str, ...]
85
+ labels: dict[str, str]
86
+ names: list[str]
87
+ chair_only: bool = False
88
+ notes: tuple[str, ...] = ()
89
+ prior: Mapping[str, Any] = field(default_factory=dict)
90
+ stages: list[dict[str, cn.Answer]] = field(default_factory=list)
91
+ ranks: dict[str, cn.Answer] = field(default_factory=dict)
92
+ results: list[SessionResult] = field(default_factory=list)
93
+ executors: dict[str, str] = field(default_factory=dict)
94
+ infra_stage: dict[int, set[str]] = field(default_factory=dict)
95
+ infra_all: bool = False
96
+ capped: bool = False
97
+ stopped_early: bool = False # a round missed its quorum: no later round is asked
98
+ written: list[str] = field(default_factory=list)
99
+ tally: cn.Tally | None = None
100
+ decision: str = ""
101
+ chair_text: str | None = None
102
+ chair_failed: str | None = None
103
+ chair_infra: bool = False
104
+ limited: tuple[float | None] | None = None # the usage limit ended a session: its reset instant (BUD-B17)
105
+ rounds_log: list[dict[str, Any]] = field(default_factory=list)
106
+ lock: threading.Lock = field(default_factory=threading.Lock)
107
+
108
+ # -- the shape of the attempt -----------------------------------------------------------------------------
109
+
110
+ @property
111
+ def spec(self) -> Any:
112
+ return self.engine.ctx.spec
113
+
114
+ @property
115
+ def rounds(self) -> int:
116
+ return self.council.rounds
117
+
118
+ @property
119
+ def last_stage(self) -> int:
120
+ """The last stage a member is asked in: the final round, or the ranking pass of a `rank` council."""
121
+ return self.rounds + (1 if self.council.mode == "rank" else 0)
122
+
123
+ def dispatch(self, stage: int) -> list[str] | None:
124
+ """The members asked in `stage`, or None when no member is (the attempt is past its last stage, a chair-only
125
+ retry, a stop at a boundary, or an attempt that has already failed)."""
126
+ if (self.chair_only or self.infra_all or self.capped or self.stopped_early or self.written
127
+ or self.limited is not None):
128
+ return None
129
+ return list(self.names) if stage <= self.last_stage else None
130
+
131
+ def key(self, kind: str, name: str | None = None, stage: int | None = None) -> str:
132
+ """`<unit>.<attempt>.member.<name>.<round>`, the same with `member_reask`, and `<unit>.<attempt>.chair` (CNL-B14)."""
133
+ what = kind if name is None else f"{kind}.{name}.{stage}"
134
+ return self.engine._skey(self.unit, self.attempt, what)
135
+
136
+ def accrued(self) -> float:
137
+ """What this attempt's sessions cost so far, as the run line counts it."""
138
+ t = CostTotals()
139
+ with self.lock:
140
+ for r in self.results:
141
+ t.add(r.usage)
142
+ return t.figure()
143
+
144
+ # -- one session ------------------------------------------------------------------------------------------
145
+
146
+ def _request(self, kind: str, key: str, prompt: str, *, executor: str | None, alias: str | None, tools: Sequence[str],
147
+ timeout_s: int | None, idle_s: int | None) -> tuple[Any, SessionRequest]:
148
+ eng = self.engine
149
+ ex = eng.ctx.registry.get(executor or self.spec.default_executor)
150
+ cap = (eng.ctx.spec.units[self.unit].extra or {}).get("session_cost_cap_usd")
151
+ req = SessionRequest(
152
+ kind=kind, prompt=prompt, workdir=self.workdir, alias=alias or "inherit", session_key=key, # type: ignore[arg-type]
153
+ tools=tuple(tools), timeout_s=timeout_s or DEFAULT_TIMEOUT_S, idle_s=idle_s,
154
+ options=SessionOptions(cost_cap_usd=float(cap)) if cap is not None else SessionOptions(),
155
+ session_dir=session_dir(eng.ctx.state_root, self.spec.name, eng.ctx.task_id, key),
156
+ enforce_tools=eng.ctx.enforce_tools, in_engine_worktree=eng._in_worktree(self.state),
157
+ plugin_dir=self.spec.package_root)
158
+ return ex, req
159
+
160
+ def _kept(self, req: SessionRequest) -> SessionResult | None:
161
+ path = (req.session_dir or Path()) / RESULT_FILE
162
+ try:
163
+ doc = json.loads(path.read_text(encoding="utf-8"))
164
+ if doc.get("key") == req.session_key and doc.get("digest") == _digest(req.prompt):
165
+ return load_result(doc["result"])
166
+ except (OSError, ValueError, KeyError, TypeError):
167
+ return None
168
+ return None
169
+
170
+ def _keep(self, req: SessionRequest, res: SessionResult) -> None:
171
+ if req.session_dir is None or res.infra_cause is not None or not res.ok:
172
+ return
173
+ with contextlib.suppress(OSError):
174
+ req.session_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
175
+ write_json(req.session_dir / RESULT_FILE, {"key": req.session_key, "digest": _digest(req.prompt),
176
+ "result": dump_result(res)}, mode=0o600)
177
+
178
+ def session(self, ex: Any, req: SessionRequest, *, width: int, gated: bool = True) -> SessionResult | None:
179
+ """Run one session, or take the one that already ended under this key. None: the council's own cost cap stopped
180
+ it before it started (CNL-B8). The reservation of a run with a cost cap is taken per try (BUD-B12)."""
181
+ eng = self.engine
182
+ kept = self._kept(req)
183
+ if kept is not None:
184
+ with self.lock:
185
+ self.results.append(kept)
186
+ self.executors[ex.name] = kept.cli_version or self.executors.get(ex.name, "")
187
+ hold = self._hold(width)
188
+ if hold is not None: # it was paid before this process: it counts as spent for the sessions that follow
189
+ paid = CostTotals()
190
+ paid.add(kept.usage)
191
+ eng.ledger.add_ended(int(hold["snapshot"]), paid.figure())
192
+ return kept
193
+ cap = self.council.cost_cap_usd
194
+ if cap is not None and self.accrued() >= cap: # no new session; the running ones finish (CNL-B8)
195
+ with self.lock:
196
+ self.capped = True
197
+ return None
198
+ res, tries = eng._session(ex, req, hold=self._hold(width) if gated else None)
199
+ with self.lock:
200
+ self.results.extend(tries)
201
+ self.executors[ex.name] = res.cli_version or self.executors.get(ex.name, "")
202
+ self._keep(req, res)
203
+ return res
204
+
205
+ def _hold(self, width: int) -> dict[str, Any] | None:
206
+ return self.engine._hold(self.unit, self.state, width=width)
207
+
208
+ def _workspace_guard(self, before: gitmod.Fingerprint, after: gitmod.Fingerprint) -> list[str]:
209
+ """WSP-B11: the paths a read-only session left written in the run's worktree."""
210
+ if before == after:
211
+ return []
212
+ old = set(before.status.splitlines())
213
+ return sorted({ln[3:] for ln in after.status.splitlines() if ln not in old and len(ln) > 3}) or ["(the workspace)"]
214
+
215
+ # -- a member's stage -------------------------------------------------------------------------------------
216
+
217
+ def _peers(self, name: str, stage: int) -> list[tuple[str, str]]:
218
+ """The others' answers of the stage before, under their labels in the attempt's order (or their names)."""
219
+ prev = self.stages[stage - 1] if 0 < stage <= len(self.stages) else {}
220
+ order = sorted((n for n in self.names if n != name), key=lambda n: self.labels[n])
221
+ if not self.council.anonymize:
222
+ order = [n for n in self.names if n != name]
223
+ return [((self.labels[n] if self.council.anonymize else n), prev[n].text)
224
+ for n in order if n in prev and prev[n].status == "ok"]
225
+
226
+ def member(self, name: str, stage: int) -> None:
227
+ """One member answers once in `stage` (CNL-B1, CNL-B2, CNL-B11); a read-only session in the run's worktree."""
228
+ c = self.council
229
+ m = next(x for x in c.members if x.name == name)
230
+ ranking = stage > self.rounds
231
+ prev = self.stages[stage - 1] if 0 < stage <= len(self.stages) else {}
232
+ own = prev[name].text if name in prev and prev[name].status == "ok" else ""
233
+ if ranking:
234
+ final = self.stages[self.rounds] if self.rounds < len(self.stages) else {}
235
+ peers = [(self.labels[n], final[n].text) for n in sorted(self.names, key=lambda x: self.labels[x])
236
+ if n != name and n in final and final[n].status == "ok"]
237
+ prompt = cn.ranking_prompt(question=self.question, peers=peers,
238
+ own_previous=final[name].text if name in final else "")
239
+ asked = tuple(lab for lab, _ in peers)
240
+ read_round = 0
241
+ else:
242
+ prompt = cn.member_prompt(question=self.question, stance=m.stance, round=stage, mode=c.mode,
243
+ options=self.options, peers=self._peers(name, stage), anonymize=c.anonymize,
244
+ own_previous=own)
245
+ asked, read_round = (), stage
246
+ ex, req = self._request("member", self.key("member", name, stage), prompt, executor=m.executor, alias=m.model,
247
+ tools=m.tools, timeout_s=m.timeout_s, idle_s=m.idle_s)
248
+ width = len(self.names)
249
+ before = gitmod.fingerprint(self.workdir)
250
+ res = self.session(ex, req, width=width)
251
+ answer = self._read(name, stage, ex, req, res, ranking, asked, read_round, width)
252
+ written = self._workspace_guard(before, gitmod.fingerprint(self.workdir)) if res is not None and res.ok else []
253
+ with self.lock:
254
+ if written:
255
+ self.written.extend(p for p in written if p not in self.written)
256
+ answer = cn.missing()
257
+ self._put(stage, name, answer, res)
258
+
259
+ def _read(self, name: str, stage: int, ex: Any, req: SessionRequest, res: SessionResult | None, ranking: bool,
260
+ asked: tuple[str, ...], read_round: int, width: int) -> cn.Answer:
261
+ c = self.council
262
+ if res is not None and res.usage_limit and not res.ok:
263
+ self._limit(res) # not a missing answer: the attempt pauses and nothing is spent (BUD-B17)
264
+ return cn.missing()
265
+ if res is None or res.infra_cause is not None or not res.ok:
266
+ return cn.missing() # no session ended with an answer (CNL-B15)
267
+ try:
268
+ return cn.parse_answer(res.text, mode=c.mode, options=self.options, round=read_round, peers=asked)
269
+ except cn.Unparsed as exc:
270
+ problem = str(exc)
271
+ again = cn.reask_prompt(res.text, problem, mode=c.mode, options=self.options, round=read_round,
272
+ ranking=ranking)
273
+ ex2, req2 = self._request("member_reask", self.key("member_reask", name, stage), again,
274
+ executor=next(x for x in c.members if x.name == name).executor,
275
+ alias=req.alias, tools=req.tools, timeout_s=req.timeout_s, idle_s=req.idle_s)
276
+ res2 = self.session(ex2, req2, width=width)
277
+ if res2 is not None and res2.usage_limit and not res2.ok:
278
+ self._limit(res2)
279
+ return cn.missing()
280
+ if res2 is None or res2.infra_cause is not None or not res2.ok:
281
+ return cn.spoiled(res.text)
282
+ try:
283
+ return cn.parse_answer(res2.text, mode=c.mode, options=self.options, round=read_round, peers=asked)
284
+ except cn.Unparsed:
285
+ return cn.spoiled(res2.text) # a second failure counts against the quorum (CNL-B11)
286
+
287
+ def _limit(self, res: SessionResult) -> None:
288
+ with self.lock:
289
+ if self.limited is None or (res.usage_limit_resets_at or 0) > (self.limited[0] or 0):
290
+ self.limited = (res.usage_limit_resets_at,)
291
+
292
+ def _put(self, stage: int, name: str, answer: cn.Answer, res: SessionResult | None) -> None:
293
+ while len(self.stages) <= min(stage, self.rounds):
294
+ self.stages.append({})
295
+ if stage > self.rounds:
296
+ self.ranks[name] = answer
297
+ else:
298
+ self.stages[stage][name] = answer
299
+ if res is not None and res.infra_cause is not None:
300
+ self.infra_stage.setdefault(stage, set()).add(name)
301
+
302
+ # -- the barrier --------------------------------------------------------------------------------------------
303
+
304
+ def close(self, stage: int) -> int:
305
+ """The round barrier: every member has answered, failed or spoiled. Writes the `council_round` record, applies
306
+ the stops, and names the next stage (CNL-B14, CNL-B15, EVT-B13)."""
307
+ c = self.council
308
+ if stage <= self.rounds:
309
+ got = self.stages[stage] if stage < len(self.stages) else {}
310
+ counts = cn.round_counts(got, self.names)
311
+ self.rounds_log.append({"round": stage, **counts})
312
+ self.engine.ctx.log.write("council_round", unit=self.unit, attempt=self.attempt, round=stage,
313
+ labels=sorted(self.names, key=lambda n: self.labels[n]), **counts)
314
+ need = c.quorum or len(self.names)
315
+ if counts["answered"] < need:
316
+ self.stopped_early = True # a round below quorum ends the deliberation (CNL-B13)
317
+ failed = self.infra_stage.get(stage, set())
318
+ if failed and len(failed) >= len(self.names):
319
+ self.infra_all = True # every member failed on infrastructure: an infra failure, never a pause (CNL-B15)
320
+ return stage + 1
321
+
322
+ # -- the tally and the chair --------------------------------------------------------------------------------
323
+
324
+ def _restore(self) -> None:
325
+ """A chair-only retry reuses the members' recorded positions (CNL-B7)."""
326
+ held = council_answers(self.state, self.unit)
327
+ self.stages = [{n: cn.Answer.from_json(a) for n, a in dict(stage).items()} for stage in held.get("stages") or []]
328
+ self.ranks = {n: cn.Answer.from_json(a) for n, a in dict(held.get("ranks") or {}).items()}
329
+
330
+ def tally_now(self) -> None:
331
+ """The pure tally node: the outcome by rule, no model reading the ballots (CNL-B3, CNL-B12)."""
332
+ c = self.council
333
+ if self.chair_only:
334
+ self._restore()
335
+ if self.infra_all or self.capped or self.written or self.limited is not None:
336
+ return
337
+ final =self.stages[min(len(self.stages), self.rounds + 1) - 1] if self.stages else {}
338
+ n = len(self.names)
339
+ if c.mode == "vote":
340
+ self.tally = cn.tally_vote(final, options=self.options, rule=c.rule, quorum=c.quorum, members=n)
341
+ elif c.mode == "rank":
342
+ conf = {nm: _mean_confidence(self.stages, nm) for nm in self.names}
343
+ have_all = len(self.stages) == self.rounds + 1 and not self.stopped_early
344
+ self.tally = cn.borda(self.ranks if have_all else {}, labels=self.labels, confidences=conf,
345
+ quorum=c.quorum)
346
+ else:
347
+ self.tally = cn.synthesis_tally(final, quorum=c.quorum, members=n)
348
+ if not self.chair_only:
349
+ self.engine.ctx.log.write("council_tally", unit=self.unit, attempt=self.attempt, mode=c.mode,
350
+ rule=self.tally.rule, counts=dict(self.tally.counts), outcome=self.tally.outcome,
351
+ chosen_by="engine")
352
+
353
+ def final_answers(self) -> dict[str, cn.Answer]:
354
+ return self.stages[min(len(self.stages), self.rounds + 1) - 1] if self.stages else {}
355
+
356
+ def chair_now(self) -> None:
357
+ """The chair node: the synthesis of a `synthesize` council, the rationale of a `vote` or `rank` that has a chair.
358
+ It does not run when there is no decision, or the attempt has already failed (CNL-B12, CNL-B13)."""
359
+ c = self.council
360
+ t = self.tally
361
+ if t is None or t.outcome == cn.NO_DECISION or c.chair is None:
362
+ self.decision = cn.decision_text(c.mode, t, None) if t is not None else ""
363
+ return
364
+ final = self.final_answers()
365
+ positions = [(self.labels[n], final[n].position, final[n].text) for n in
366
+ sorted(self.names, key=lambda x: self.labels[x]) if n in final and final[n].status == "ok"]
367
+ prompt = cn.chair_prompt(question=self.question, positions=positions, mode=c.mode,
368
+ outcome=None if c.mode == "synthesize" else t.outcome, notes=self.notes,
369
+ custom=c.chair.prompt)
370
+ eng = self.engine
371
+ eng._council_boundary(self.state, self.accrued()) # the chair runs alone: it meets the check of an attempt
372
+ ex, req = self._request("chair", self.key("chair"), prompt, executor=c.chair.executor, alias=c.chair.model,
373
+ tools=(), timeout_s=None, idle_s=None)
374
+ before = gitmod.fingerprint(self.workdir)
375
+ res = self.session(ex, req, width=1)
376
+ if res is None:
377
+ return
378
+ written = self._workspace_guard(before, gitmod.fingerprint(self.workdir)) if res.ok else []
379
+ if res.usage_limit and not res.ok:
380
+ self._limit(res)
381
+ return
382
+ if written:
383
+ self.written.extend(written)
384
+ elif res.infra_cause is not None:
385
+ self.chair_infra = True
386
+ elif not res.ok:
387
+ self.chair_failed = res.error_kind or ("timed out" if res.timed_out else "the chair's session failed")
388
+ else:
389
+ self.chair_text = res.text
390
+ self.decision = cn.decision_text(c.mode, t, self.chair_text)
391
+
392
+ # -- what the step node writes -------------------------------------------------------------------------------
393
+
394
+ def finish(self) -> dict[str, Any]:
395
+ """The state write of the step node: the attempt record, the three artifacts and the cost (CNL-B10)."""
396
+ eng = self.engine
397
+ c = self.council
398
+ state = self.state
399
+ t = self.tally
400
+ final = self.final_answers()
401
+ outcome = t.outcome if t is not None else None
402
+ positions = cn.positions_json(self.stages, self.labels, self.ranks or None) if self.stages else {}
403
+ dissent = cn.chair_dissent(self.chair_text or "") if self.chair_text is not None else ""
404
+ differs = cn.positions_differ(final) if final else False
405
+ council: dict[str, Any] = {
406
+ "mode": c.mode, "labels": dict(self.labels),
407
+ "order": sorted(self.names, key=lambda n: self.labels[n]), "rounds": list(self.rounds_log),
408
+ "outcome": outcome, "tally": cn.tally_json(t) if t is not None else None,
409
+ "chair_only": self.chair_only, "dissent": dissent, "positions_differ": differs,
410
+ "options": list(self.options)}
411
+ rec: dict[str, Any] = {
412
+ "attempt": self.attempt, "visit": self.visit, "ok": True, "text": clip(scrub(self.decision), 8000),
413
+ "issues": [], "tools": [], "session_id": None, "escalate": None, "infra_spent": False, "check": None,
414
+ "item": None, "timed_out": False, "changed": False, "council": council, "error_kind": None,
415
+ "council_stop": None, "dissent_missing": None, "written": None, "infra_cause": None}
416
+ if self.limited is not None: # BUD-B17: nothing is spent and the attempt keeps no artifacts
417
+ rec.update(ok=False, escalate="usage_limit", usage_limit_resets_at=self.limited[0],
418
+ usage_limit_stage="step", reuse={"notes": list(self.notes)})
419
+ elif self.infra_all or self.chair_infra:
420
+ rec.update(ok=False, infra_spent=True, infra_cause="member_infra" if self.infra_all else "chair_infra")
421
+ elif self.written:
422
+ rec.update(ok=False, error_kind="member_changed_the_workspace", written=list(self.written))
423
+ elif self.capped:
424
+ rec.update(ok=False, error_kind="cap_reached")
425
+ elif self.chair_failed:
426
+ rec.update(ok=False, error_kind=self.chair_failed)
427
+ elif outcome == cn.NO_DECISION:
428
+ how = c.on_no_decision
429
+ if how == "escalate":
430
+ rec["escalate"] = "no_decision"
431
+ elif how == "retry":
432
+ rec.update(ok=False, error_kind="no_decision")
433
+ else:
434
+ rec["council_stop"] = True
435
+ elif c.mode == "synthesize" and differs and not dissent: # a retryable built-in check (CNL-B12)
436
+ rec["dissent_missing"] = True
437
+ failed = not rec["ok"] and rec["error_kind"] != "no_decision" or bool(rec["infra_spent"])
438
+ arts: dict[str, Any] | None = None
439
+ if t is not None and not failed:
440
+ arts = {"decision": self.decision, "positions": json.dumps(positions, sort_keys=True),
441
+ "tally": json.dumps(cn.tally_json(t), sort_keys=True), "tally.outcome": str(outcome)}
442
+ run: dict[str, Any] = {"cost": eng._cost(state, self.results),
443
+ "executors": {**((state.get("run") or {}).get("executors") or {}), **self.executors}}
444
+ path_units = list(((state.get("run") or {}).get("path") or {}).get("units") or [])
445
+ if self.entered and self.unit not in path_units:
446
+ run["path"] = {"units": path_units + [self.unit]}
447
+ kept = {"attempt": self.attempt, "labels": dict(self.labels),
448
+ "stages": [{n: a.to_json() for n, a in s.items()} for s in self.stages],
449
+ "ranks": {n: a.to_json() for n, a in self.ranks.items()}} if self.stages and not failed else None
450
+ return {"attempts": {self.unit: rec}, "values": {self.unit: arts}, "council": {self.unit: kept}, "run": run}
451
+
452
+
453
+ def _mean_confidence(stages: Sequence[Mapping[str, cn.Answer]], name: str) -> float | None:
454
+ got = [s[name].confidence for s in stages if name in s and s[name].confidence is not None]
455
+ return sum(got) / len(got) if got else None # type: ignore[arg-type]
456
+
457
+
458
+ # -- the entry the subgraph's first node calls ---------------------------------------------------------------------
459
+
460
+
461
+ def open_run(engine: Any, unit: str, state: Mapping[str, Any]) -> CouncilRun:
462
+ """The first node: what this attempt is (its number, its labels, the question) and whether it is a chair-only
463
+ retry (CNL-B7). The unit's entry is logged once per visit, as a step's is."""
464
+ spec = engine.ctx.spec
465
+ c = spec.units[unit].council
466
+ assert c is not None
467
+ engine._boundary(state)
468
+ prev = (state.get("attempts") or {}).get(unit) or {}
469
+ visit = int(((state.get("visits") or {}).get(unit) or {}).get("visit", 1))
470
+ entered = prev.get("visit") != visit
471
+ workdir = engine._workdir(state, unit)
472
+ if entered:
473
+ from tempergraph.run.nodes import _entered_from
474
+
475
+ fp = gitmod.fingerprint(workdir)
476
+ engine.ctx.log.write("unit_entered", unit=unit, visit=visit, head_commit=fp.head, dirty=fp.dirty,
477
+ entered_from=_entered_from(state, unit))
478
+ again = prev.get("escalate") == "usage_limit" and not entered # DUR-B12: the refused attempt runs again
479
+ attempt = int(prev["attempt"]) if again else int(prev.get("attempt", 0)) + 1
480
+ if not again:
481
+ engine.ctx.count_attempt(unit, None, attempt, visit)
482
+ names = [m.name for m in c.members]
483
+ seed = f"{engine.ctx.thread}/{unit}/{attempt}"
484
+ fields = engine._fields(unit, state, attempt, visit, workdir)
485
+ question = render(load_text(spec, c.question), fields)[0]
486
+ held = prev.get("council") or {}
487
+ judged = (state.get("judgements") or {}).get(unit) or {}
488
+ retry = not entered and bool(prev)
489
+ scoped = ((state.get("route") or {}).get(unit) or {}).get("scope") == "chair" # the gate said so (CNL-B7)
490
+ chair_only = (scoped and retry and bool(council_answers(state, unit).get("stages")) and bool(held.get("labels"))
491
+ and c.chair is not None)
492
+ notes: tuple[str, ...] = ()
493
+ if again: # the judgement is the placeholder now: the refused attempt kept what its chair prompt reads
494
+ notes = tuple(str(n) for n in (prev.get("reuse") or {}).get("notes") or ())
495
+ elif retry:
496
+ notes =tuple(str(b.get("problem") or b.get("evidence") or "") for b in judged.get("blockers") or []
497
+ if b.get("problem") or b.get("evidence"))
498
+ labels = dict(held["labels"]) if chair_only else cn.label_map(names, seed)
499
+ return CouncilRun(engine=engine, unit=unit, council=c, state=state, attempt=attempt, visit=visit, entered=entered,
500
+ workdir=workdir, question=question, options=options_of(c, state, workdir), labels=labels,
501
+ names=names, chair_only=chair_only, notes=notes, prior=held,
502
+ rounds_log=[dict(r) for r in held.get("rounds") or []] if chair_only else [])
503
+
504
+
505
+ def options_of(c: CouncilSpec, state: Mapping[str, Any], workdir: Path) -> tuple[str, ...]:
506
+ """A `vote`'s options: its slugs, or the list an earlier unit produced under the key `options` names (CNL-B9)."""
507
+ if c.options is None:
508
+ return ()
509
+ if not isinstance(c.options, str):
510
+ return tuple(c.options)
511
+ raw = ""
512
+ for chan in ("values", "artifacts"):
513
+ for vals in (state.get(chan) or {}).values():
514
+ if isinstance(vals, dict) and c.options in vals:
515
+ raw = str(vals[c.options])
516
+ if raw and "\n" not in raw and not raw.lstrip().startswith(("[", "-")):
517
+ with contextlib.suppress(OSError):
518
+ p = (workdir / raw).resolve()
519
+ if p.is_relative_to(workdir.resolve()) and p.is_file():
520
+ raw = p.read_text(encoding="utf-8", errors="replace")
521
+ try:
522
+ data = json.loads(raw)
523
+ if isinstance(data, list):
524
+ return tuple(str(x) for x in data)
525
+ except ValueError:
526
+ pass
527
+ return tuple(ln.strip().lstrip("-* ").strip() for ln in raw.splitlines() if ln.strip().lstrip("-* ").strip())