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,368 @@
1
+ """What a council decides without a session (CNL-B1 to CNL-B3, CNL-B10 to CNL-B13; ADR `council-is-a-gated-step-with-engine-tallied-outcomes`).
2
+
3
+ Everything here is plain code on plain values: the labels `Member A`, `Member B` in an order fixed per attempt, the prompts
4
+ a member is given, the reading of its fenced JSON answer block, the tally of the four vote rules, the Borda count with its
5
+ two tie-breaks, the outcome of each mode and the three artifacts. It imports no executor and makes no model call, so the
6
+ outcome of a council never rests on a model reading the ballots (CNL-B3, CNL-AC2).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import re
14
+ from collections.abc import Collection, Mapping, Sequence
15
+ from dataclasses import dataclass
16
+ from typing import Any
17
+
18
+ _FENCE = re.compile(r"```(?:json)?\s*\n(.*?)\n```", re.S)
19
+ ABSTAIN = "abstain"
20
+ NO_DECISION = "no_decision"
21
+ SYNTHESIZED = "synthesized"
22
+ REASK_TAIL = 1500
23
+
24
+
25
+ class Unparsed(ValueError):
26
+ """A member's answer ends with no readable block (CNL-B11)."""
27
+
28
+
29
+ # ---------------------------------------------------------------------------------------------
30
+ # Labels
31
+
32
+
33
+ def order_of(names: Sequence[str], seed: str) -> list[str]:
34
+ """The members in the order of this attempt: fixed by `seed` (the thread, the unit and the attempt), so a resume
35
+ and a rerun of the attempt agree, and another attempt may order them differently (CNL-B9)."""
36
+ return sorted(names, key=lambda n: hashlib.sha256(f"{seed}/{n}".encode()).hexdigest())
37
+
38
+
39
+ def label_map(names: Sequence[str], seed: str) -> dict[str, str]:
40
+ """Member name -> `Member A`, `Member B`, ... in the attempt's order."""
41
+ return {name: f"Member {chr(65 + i)}" for i, name in enumerate(order_of(names, seed))}
42
+
43
+
44
+ # ---------------------------------------------------------------------------------------------
45
+ # What a member is told
46
+
47
+
48
+ def _block_help(mode: str, options: Sequence[str], round: int, ranking: bool = False) -> str:
49
+ fields: dict[str, Any] = {"position": "<your answer in one line>"}
50
+ notes = ["`position`: your answer in one line"]
51
+ if mode == "vote":
52
+ fields["choice"] = "<one of: " + ", ".join([*options, ABSTAIN]) + ">"
53
+ notes.append("`choice`: exactly one of " + ", ".join(f"`{o}`" for o in [*options, ABSTAIN]))
54
+ if ranking:
55
+ fields["ranking"] = ["<label>", "<label>"]
56
+ notes.append("`ranking`: every other member's label, best first; never your own")
57
+ fields["confidence"] = 0.7
58
+ notes.append("`confidence`: a number from 0 to 1")
59
+ if round >= 1:
60
+ fields.update(changed=True, why_changed="<why your position moved, or why it held>", dissent="<where you still disagree>")
61
+ notes.append("`changed`: true when your position moved; `why_changed`: the reason; `dissent`: where you still "
62
+ "disagree with the others, empty only if you do not")
63
+ return ("End your answer with one fenced JSON block, and nothing after it:\n```json\n" + json.dumps(fields, indent=2)
64
+ + "\n```\n" + "\n".join(f"- {n}" for n in notes))
65
+
66
+
67
+ def member_prompt(*, question: str, stance: str, round: int, mode: str, options: Sequence[str] = (),
68
+ peers: Sequence[tuple[str, str]] = (), anonymize: bool = True, own_previous: str = "") -> str:
69
+ """CNL-B1, CNL-B2. Round 0 holds the question and the member's own stance and nothing of another member. A later round
70
+ adds the others' previous answers, each under its label (or its name when `anonymize` is false), the member's own
71
+ omitted, and requires `changed`, `why_changed` and `dissent`."""
72
+ parts = [question.strip()]
73
+ if stance.strip():
74
+ parts.append(f"Your stance: {stance.strip()}")
75
+ if round >= 1:
76
+ if own_previous.strip():
77
+ parts.append("Your previous answer:\n" + own_previous.strip())
78
+ shown = "\n\n".join(f"{who} answered:\n{text.strip()}" for who, text in peers)
79
+ parts.append("The other members answered in the last round" + (" (anonymized)" if anonymize else "") + ":\n\n"
80
+ + (shown or "(no other answer arrived)")
81
+ + "\n\nWeigh their answers. Keep your position or change it, and say which and why.")
82
+ parts.append(_block_help(mode, options, round))
83
+ return "\n\n".join(parts)
84
+
85
+
86
+ def ranking_prompt(*, question: str, peers: Sequence[tuple[str, str]], own_previous: str = "") -> str:
87
+ """The ranking pass of a `rank` council: each member ranks the others' final answers."""
88
+ shown = "\n\n".join(f"{who} answered:\n{text.strip()}" for who, text in peers)
89
+ parts = [question.strip()]
90
+ if own_previous.strip():
91
+ parts.append("Your own final answer:\n" + own_previous.strip())
92
+ parts.append("Rank the other members' final answers, best first:\n\n" + shown)
93
+ parts.append(_block_help("rank", (), 0, ranking=True))
94
+ return "\n\n".join(parts)
95
+
96
+
97
+ def reask_prompt(previous: str, problem: str, *, mode: str, options: Sequence[str], round: int,
98
+ ranking: bool = False) -> str:
99
+ return (f"Your previous answer could not be read: {problem}. Here is its end:\n\n" + previous[-REASK_TAIL:]
100
+ + "\n\nReply with only the fenced JSON block.\n" + _block_help(mode, options, round, ranking=ranking) + "\n")
101
+
102
+
103
+ def chair_prompt(*, question: str, positions: Sequence[tuple[str, str, str]], mode: str, outcome: str | None,
104
+ notes: Sequence[str] = (), custom: str = "") -> str:
105
+ """The chair's brief: the question, each member's final answer under its label (position and text), the engine's
106
+ outcome for a `vote` or `rank`, and the judge's notes on a retry. A `synthesize` chair names the dissent."""
107
+ shown = "\n\n".join(f"{label} (position: {pos}):\n{text.strip()}" for label, pos, text in positions)
108
+ parts = [custom.strip() or "You chair this council. Write the answer the members' work supports.", question.strip(),
109
+ "The members' final answers:\n\n" + shown]
110
+ if outcome is not None:
111
+ parts.append(f"The engine tallied the outcome: {outcome}. Write the rationale; do not change the outcome.")
112
+ if notes:
113
+ parts.append("The reviewer did not accept your last answer:\n" + "\n".join(f"- {n}" for n in notes))
114
+ parts.append("State where members still disagree. End with one fenced JSON block holding `dissent`, a text that is "
115
+ "empty only if the members' positions agree:\n```json\n{\"dissent\": \"<where members differ>\"}\n```")
116
+ return "\n\n".join(parts)
117
+
118
+
119
+ def chair_dissent(text: str) -> str:
120
+ """The `dissent` of a chair's answer block; empty when there is no readable block."""
121
+ blocks = _FENCE.findall(text or "")
122
+ if not blocks:
123
+ return ""
124
+ try:
125
+ data = json.loads(blocks[-1])
126
+ except ValueError:
127
+ return ""
128
+ return str(data.get("dissent") or "").strip() if isinstance(data, dict) else ""
129
+
130
+
131
+ # ---------------------------------------------------------------------------------------------
132
+ # What a member answered
133
+
134
+
135
+ @dataclass(frozen=True, kw_only=True)
136
+ class Answer:
137
+ status: str # `ok`, `spoiled` (read twice, never parsed) or `missing` (no session ended)
138
+ text: str = ""
139
+ position: str = ""
140
+ choice: str | None = None
141
+ ranking: tuple[str, ...] = ()
142
+ confidence: float | None = None
143
+ changed: bool | None = None
144
+ why_changed: str = ""
145
+ dissent: str = ""
146
+
147
+ def to_json(self) -> dict[str, Any]:
148
+ return {"status": self.status, "text": self.text, "position": self.position, "choice": self.choice,
149
+ "ranking": list(self.ranking), "confidence": self.confidence, "changed": self.changed,
150
+ "why_changed": self.why_changed, "dissent": self.dissent}
151
+
152
+ @classmethod
153
+ def from_json(cls, data: Mapping[str, Any]) -> Answer:
154
+ return cls(status=str(data.get("status", "missing")), text=str(data.get("text") or ""),
155
+ position=str(data.get("position") or ""), choice=data.get("choice"),
156
+ ranking=tuple(str(x) for x in data.get("ranking") or ()), confidence=data.get("confidence"),
157
+ changed=data.get("changed"), why_changed=str(data.get("why_changed") or ""),
158
+ dissent=str(data.get("dissent") or ""))
159
+
160
+
161
+ def spoiled(text: str) -> Answer:
162
+ """A second failure to parse: the answer counts against the quorum (CNL-B11)."""
163
+ return Answer(status="spoiled", text=text)
164
+
165
+
166
+ def missing() -> Answer:
167
+ """A member whose session ended on infrastructure: missing for its round (CNL-B15)."""
168
+ return Answer(status="missing")
169
+
170
+
171
+ def parse_answer(text: str, *, mode: str, options: Sequence[str], round: int, peers: Collection[str] = ()) -> Answer:
172
+ """The last fenced JSON block of `text`, read like a judgement block (CNL-B11). In `rank` mode with `peers` the block
173
+ is a ranking pass and must rank every peer label once, never the author's own."""
174
+ blocks = _FENCE.findall(text or "")
175
+ if not blocks:
176
+ raise Unparsed("no fenced JSON block")
177
+ try:
178
+ data = json.loads(blocks[-1])
179
+ except ValueError as exc:
180
+ raise Unparsed("the fenced block is not JSON") from exc
181
+ if not isinstance(data, dict):
182
+ raise Unparsed("the block is not a JSON object")
183
+ position = data.get("position")
184
+ if not isinstance(position, str) or not position.strip():
185
+ raise Unparsed("`position` is missing")
186
+ conf = data.get("confidence")
187
+ if conf is not None and (isinstance(conf, bool) or not isinstance(conf, (int, float)) or not 0 <= conf <= 1):
188
+ raise Unparsed("`confidence` is not a number from 0 to 1")
189
+ choice = None
190
+ if mode == "vote":
191
+ choice = data.get("choice")
192
+ if not isinstance(choice, str) or choice not in (*options, ABSTAIN):
193
+ raise Unparsed(f"`choice` is not one of {', '.join([*options, ABSTAIN])}")
194
+ ranking: tuple[str, ...] = ()
195
+ if mode == "rank" and peers:
196
+ raw = data.get("ranking")
197
+ if not isinstance(raw, list) or sorted(map(str, raw)) != sorted(peers) or not all(isinstance(x, str) for x in raw):
198
+ raise Unparsed("`ranking` must list every other member's label once")
199
+ ranking = tuple(raw)
200
+ changed: bool | None = None
201
+ why, dissent = "", ""
202
+ if round >= 1:
203
+ if not isinstance(data.get("changed"), bool) or not isinstance(data.get("why_changed"), str) \
204
+ or not isinstance(data.get("dissent"), str):
205
+ raise Unparsed("`changed`, `why_changed` and `dissent` are required after round 0")
206
+ changed, why, dissent = data["changed"], data["why_changed"], data["dissent"]
207
+ return Answer(status="ok", text=text, position=position.strip(), choice=choice, ranking=ranking,
208
+ confidence=float(conf) if conf is not None else None, changed=changed, why_changed=why, dissent=dissent)
209
+
210
+
211
+ # ---------------------------------------------------------------------------------------------
212
+ # The tally
213
+
214
+
215
+ @dataclass(frozen=True, kw_only=True)
216
+ class Tally:
217
+ mode: str
218
+ outcome: str # an option, a label (`rank`), `synthesized`, or `no_decision`
219
+ rule: str | None
220
+ counts: Mapping[str, int]
221
+ votes: int = 0
222
+ abstained: int = 0
223
+ spoiled: int = 0
224
+ missing: int = 0
225
+ valid: int = 0
226
+ quorum: int = 0
227
+ reason: str | None = None # why there is no decision: `quorum`, `tie` or `rule`
228
+ ranking: tuple[Mapping[str, Any], ...] = ()
229
+
230
+
231
+ def _census(answers: Mapping[str, Answer], members: int) -> tuple[int, int, int]:
232
+ valid = sum(1 for a in answers.values() if a.status == "ok")
233
+ bad = sum(1 for a in answers.values() if a.status == "spoiled")
234
+ return valid, bad, max(members - valid - bad, 0)
235
+
236
+
237
+ def tally_vote(answers: Mapping[str, Answer], *, options: Sequence[str], rule: str | None, quorum: int | None,
238
+ members: int) -> Tally:
239
+ """CNL-B3: count the final-round `choice`s by `rule`. An abstention is a valid answer for the quorum and no vote;
240
+ a spoiled ballot and a missing member are neither."""
241
+ rule = rule or "majority"
242
+ need = quorum or members
243
+ valid, bad, absent = _census(answers, members)
244
+ counts = {o: 0 for o in options}
245
+ abstained = 0
246
+ for a in answers.values():
247
+ if a.status != "ok":
248
+ continue
249
+ if a.choice == ABSTAIN:
250
+ abstained += 1
251
+ elif a.choice in counts:
252
+ counts[str(a.choice)] += 1
253
+ votes = sum(counts.values())
254
+ base: dict[str, Any] = {"mode": "vote", "rule": rule, "counts": counts, "votes": votes, "abstained": abstained,
255
+ "spoiled": bad, "missing": absent, "valid": valid, "quorum": need}
256
+ if valid < need:
257
+ return Tally(outcome=NO_DECISION, reason="quorum", **base)
258
+ top = max(counts.values(), default=0)
259
+ leaders = [o for o, n in counts.items() if n == top]
260
+ if votes == 0:
261
+ return Tally(outcome=NO_DECISION, reason="rule", **base)
262
+ if rule == "plurality":
263
+ passed = len(leaders) == 1
264
+ elif rule == "unanimous":
265
+ passed = len(leaders) == 1 and top == votes
266
+ elif rule == "supermajority":
267
+ passed = len(leaders) == 1 and top * 3 >= votes * 2
268
+ else:
269
+ passed = len(leaders) == 1 and top * 2 > votes
270
+ if passed:
271
+ return Tally(outcome=leaders[0], reason=None, **base)
272
+ return Tally(outcome=NO_DECISION, reason="tie" if len(leaders) > 1 else "rule", **base)
273
+
274
+
275
+ def _mean(values: Sequence[float | None]) -> float:
276
+ got = [v for v in values if v is not None]
277
+ return sum(got) / len(got) if got else 0.0
278
+
279
+
280
+ def borda(answers: Mapping[str, Answer], *, labels: Mapping[str, str], confidences: Mapping[str, float | None],
281
+ quorum: int | None) -> Tally:
282
+ """CNL-B12: a Borda count over the peer rankings, k-1 points for the first of k. Ties in points break by the mean
283
+ confidence of the member, then the order of the labels; a tie that both breaks leave at the top is no decision."""
284
+ need = quorum or len(labels)
285
+ valid, bad, absent = _census(answers, len(labels))
286
+ points = {lab: 0 for lab in labels.values()}
287
+ for a in answers.values():
288
+ if a.status != "ok":
289
+ continue
290
+ k = len(a.ranking)
291
+ for place, lab in enumerate(a.ranking):
292
+ if lab in points:
293
+ points[lab] += k - 1 - place
294
+ conf = {labels[n]: _mean([confidences.get(n)]) for n in labels}
295
+ ordered = sorted(points, key=lambda lab: (-points[lab], -conf[lab], lab))
296
+ rows = tuple({"label": lab, "points": points[lab], "mean_confidence": round(conf[lab], 4)} for lab in ordered)
297
+ base: dict[str, Any] = {"mode": "rank", "rule": "borda", "counts": dict(points), "spoiled": bad, "missing": absent,
298
+ "valid": valid, "quorum": need, "votes": valid}
299
+ if valid < need:
300
+ return Tally(outcome=NO_DECISION, reason="quorum", ranking=tuple(
301
+ {"label": lab, "points": points[lab], "mean_confidence": round(conf[lab], 4)} for lab in sorted(points)), **base)
302
+ if len(ordered) > 1 and (points[ordered[0]], conf[ordered[0]]) == (points[ordered[1]], conf[ordered[1]]):
303
+ return Tally(outcome=NO_DECISION, reason="tie", ranking=tuple(
304
+ {"label": lab, "points": points[lab], "mean_confidence": round(conf[lab], 4)} for lab in sorted(points)), **base)
305
+ return Tally(outcome=ordered[0] if ordered else NO_DECISION, ranking=rows, **base)
306
+
307
+
308
+ def synthesis_tally(answers: Mapping[str, Answer], *, quorum: int | None, members: int) -> Tally:
309
+ """CNL-B12: a `synthesize` council's outcome is the chair's answer, once the round met its quorum."""
310
+ need = quorum or members
311
+ valid, bad, absent = _census(answers, members)
312
+ base: dict[str, Any] = {"mode": "synthesize", "rule": None, "counts": {}, "spoiled": bad, "missing": absent,
313
+ "valid": valid, "quorum": need}
314
+ if valid < need:
315
+ return Tally(outcome=NO_DECISION, reason="quorum", **base)
316
+ return Tally(outcome=SYNTHESIZED, **base)
317
+
318
+
319
+ def changed_count(answers: Mapping[str, Answer]) -> int:
320
+ """How many members changed position in a round (CNL-B12)."""
321
+ return sum(1 for a in answers.values() if a.status == "ok" and a.changed)
322
+
323
+
324
+ def round_counts(answers: Mapping[str, Answer], members: Sequence[str]) -> dict[str, int]:
325
+ """The counts one `council_round` record and the run detail show (EVT-B13, RDD-B9)."""
326
+ got = [answers.get(m, missing()) for m in members]
327
+ return {"answered": sum(1 for a in got if a.status == "ok"), "spoiled": sum(1 for a in got if a.status == "spoiled"),
328
+ "missing": sum(1 for a in got if a.status == "missing"), "changed": changed_count(answers)}
329
+
330
+
331
+ def positions_differ(answers: Mapping[str, Answer]) -> bool:
332
+ """Whether any member's final position differs from another's (CNL-B12)."""
333
+ return len({a.position.strip().lower() for a in answers.values() if a.status == "ok"}) > 1
334
+
335
+
336
+ # ---------------------------------------------------------------------------------------------
337
+ # The three artifacts (CNL-B10)
338
+
339
+
340
+ def decision_text(mode: str, tally: Tally, chair_text: str | None) -> str:
341
+ """The chair's answer, or for a chairless `vote` or `rank` the outcome the engine wrote."""
342
+ if chair_text:
343
+ return chair_text
344
+ if mode == "vote":
345
+ counts = ", ".join(f"{o} {n}" for o, n in tally.counts.items())
346
+ return f"Outcome: {tally.outcome}\nRule: {tally.rule}\nVotes: {counts}; abstained {tally.abstained}"
347
+ if mode == "rank":
348
+ rows = "\n".join(f"{i}. {r['label']} ({r['points']} points)" for i, r in enumerate(tally.ranking, 1))
349
+ return f"Outcome: {tally.outcome}\nRule: borda\n{rows}"
350
+ return f"Outcome: {tally.outcome}"
351
+
352
+
353
+ def positions_json(history: Sequence[Mapping[str, Answer]], labels: Mapping[str, str],
354
+ ranks: Mapping[str, Answer] | None = None) -> dict[str, Any]:
355
+ """Each member's final answer and its round history, under its label; a `rank` council adds each member's ranking."""
356
+ out: dict[str, Any] = {}
357
+ for name, label in sorted(labels.items(), key=lambda kv: kv[1]):
358
+ rounds = [{"round": r, **history[r].get(name, missing()).to_json()} for r in range(len(history))]
359
+ out[label] = {"rounds": rounds, "final": rounds[-1] if rounds else missing().to_json()}
360
+ if ranks and name in ranks and ranks[name].status == "ok":
361
+ out[label]["ranking"] = list(ranks[name].ranking)
362
+ return out
363
+
364
+
365
+ def tally_json(t: Tally) -> dict[str, Any]:
366
+ return {"mode": t.mode, "outcome": t.outcome, "rule": t.rule, "counts": dict(t.counts), "votes": t.votes,
367
+ "abstained": t.abstained, "spoiled": t.spoiled, "missing": t.missing, "valid": t.valid, "quorum": t.quorum,
368
+ "reason": t.reason, "ranking": [dict(r) for r in t.ranking]}