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.
- tempergraph/__init__.py +8 -0
- tempergraph/__main__.py +5 -0
- tempergraph/api.py +428 -0
- tempergraph/audit/__init__.py +305 -0
- tempergraph/audit/catalog.py +342 -0
- tempergraph/audit/definition.py +387 -0
- tempergraph/audit/history.py +414 -0
- tempergraph/audit/history_rules.py +268 -0
- tempergraph/audit/history_rules_more.py +244 -0
- tempergraph/audit/host.py +270 -0
- tempergraph/audit/owned.py +96 -0
- tempergraph/audit/prompts.py +89 -0
- tempergraph/audit/report.py +248 -0
- tempergraph/audit/revisit.py +220 -0
- tempergraph/audit/surface.py +224 -0
- tempergraph/audit/text_health.py +176 -0
- tempergraph/audit/tools.py +391 -0
- tempergraph/author/__init__.py +2 -0
- tempergraph/author/blueprint.py +346 -0
- tempergraph/author/compare.py +122 -0
- tempergraph/author/criteria_lint.py +200 -0
- tempergraph/author/draw.py +112 -0
- tempergraph/author/inventory.py +210 -0
- tempergraph/author/literals.py +138 -0
- tempergraph/author/scaffold.py +568 -0
- tempergraph/author/session.py +439 -0
- tempergraph/author/trial.py +391 -0
- tempergraph/author/verify.py +353 -0
- tempergraph/builtin/__init__.py +1 -0
- tempergraph/builtin/upgrade.py +288 -0
- tempergraph/catalog.py +134 -0
- tempergraph/check_helpers.py +99 -0
- tempergraph/cli/__init__.py +1 -0
- tempergraph/cli/audit.py +190 -0
- tempergraph/cli/author.py +361 -0
- tempergraph/cli/improve.py +564 -0
- tempergraph/cli/improve_review.py +111 -0
- tempergraph/cli/install.py +35 -0
- tempergraph/cli/main.py +1261 -0
- tempergraph/cli/observe_cli.py +544 -0
- tempergraph/cli/outcome.py +77 -0
- tempergraph/cli/schedule_cli.py +1090 -0
- tempergraph/cli/upgrade.py +126 -0
- tempergraph/cli/workflows.py +96 -0
- tempergraph/compiler/__init__.py +6 -0
- tempergraph/compiler/graph.py +305 -0
- tempergraph/compiler/state.py +229 -0
- tempergraph/constants.py +72 -0
- tempergraph/contracts.py +1025 -0
- tempergraph/data/executor_compat.json +11 -0
- tempergraph/data/promotion.json +35 -0
- tempergraph/data/release.json +20 -0
- tempergraph/detach.py +65 -0
- tempergraph/docs.py +90 -0
- tempergraph/durability/__init__.py +2 -0
- tempergraph/durability/alias.py +66 -0
- tempergraph/durability/carry.py +591 -0
- tempergraph/durability/checkpoint.py +179 -0
- tempergraph/durability/control.py +109 -0
- tempergraph/durability/engine_file.py +301 -0
- tempergraph/durability/lock.py +138 -0
- tempergraph/durability/status.py +390 -0
- tempergraph/engine_identity.py +42 -0
- tempergraph/executor_compat.py +56 -0
- tempergraph/executors/__init__.py +4 -0
- tempergraph/executors/binding.py +91 -0
- tempergraph/executors/capabilities.py +95 -0
- tempergraph/executors/claude.py +603 -0
- tempergraph/executors/launcher.py +394 -0
- tempergraph/executors/mcpconfig.py +156 -0
- tempergraph/executors/mcpproxy.py +216 -0
- tempergraph/executors/preflight.py +196 -0
- tempergraph/executors/registry.py +71 -0
- tempergraph/executors/scripted.py +18 -0
- tempergraph/executors/session.py +107 -0
- tempergraph/executors/standins.py +118 -0
- tempergraph/executors/summary.py +110 -0
- tempergraph/executors/viewcatalog.py +27 -0
- tempergraph/git.py +403 -0
- tempergraph/identity.py +65 -0
- tempergraph/improve/__init__.py +5 -0
- tempergraph/improve/analysis.py +437 -0
- tempergraph/improve/artifact.py +477 -0
- tempergraph/improve/autonomy.py +192 -0
- tempergraph/improve/bindings.py +191 -0
- tempergraph/improve/calibration.py +1016 -0
- tempergraph/improve/causes.py +416 -0
- tempergraph/improve/child.py +651 -0
- tempergraph/improve/codehost.py +520 -0
- tempergraph/improve/digest.py +472 -0
- tempergraph/improve/escape.py +100 -0
- tempergraph/improve/filing.py +1047 -0
- tempergraph/improve/harvest.py +158 -0
- tempergraph/improve/issue_context.py +192 -0
- tempergraph/improve/lenses.py +204 -0
- tempergraph/improve/lessons.py +233 -0
- tempergraph/improve/loop_report.py +138 -0
- tempergraph/improve/loop_summary.py +85 -0
- tempergraph/improve/lost.py +119 -0
- tempergraph/improve/measure.py +121 -0
- tempergraph/improve/params.py +98 -0
- tempergraph/improve/pause_facts.py +134 -0
- tempergraph/improve/pr_later.py +186 -0
- tempergraph/improve/prebinding.py +130 -0
- tempergraph/improve/promotion.py +413 -0
- tempergraph/improve/proposals.py +934 -0
- tempergraph/improve/record.py +322 -0
- tempergraph/improve/release.py +89 -0
- tempergraph/improve/reliability.py +457 -0
- tempergraph/improve/repeat.py +115 -0
- tempergraph/improve/review.py +910 -0
- tempergraph/improve/suites.py +586 -0
- tempergraph/improve/trials.py +525 -0
- tempergraph/install/__init__.py +11 -0
- tempergraph/install/bootstrap.py +133 -0
- tempergraph/install/environment.py +173 -0
- tempergraph/install/launch.py +37 -0
- tempergraph/install/python.py +53 -0
- tempergraph/install/reconcile.py +52 -0
- tempergraph/install/selfcheck.py +29 -0
- tempergraph/install/shim.py +81 -0
- tempergraph/install/update.py +400 -0
- tempergraph/model/__init__.py +0 -0
- tempergraph/model/diagram.py +185 -0
- tempergraph/model/flow.py +324 -0
- tempergraph/model/prompt_lint.py +203 -0
- tempergraph/model/retire.py +52 -0
- tempergraph/model/subworkflow.py +274 -0
- tempergraph/model/text.py +67 -0
- tempergraph/model/validate.py +1158 -0
- tempergraph/observe/__init__.py +1 -0
- tempergraph/observe/attention.py +196 -0
- tempergraph/observe/detail.py +773 -0
- tempergraph/observe/forget.py +138 -0
- tempergraph/observe/hooks.py +272 -0
- tempergraph/observe/labels.py +95 -0
- tempergraph/observe/overlay.py +46 -0
- tempergraph/observe/report.py +402 -0
- tempergraph/observe/risk_report.py +110 -0
- tempergraph/observe/rows.py +444 -0
- tempergraph/observe/sinks.py +793 -0
- tempergraph/observe/supervision_cost.py +797 -0
- tempergraph/observe/supervision_report.py +295 -0
- tempergraph/observe/switch_report.py +140 -0
- tempergraph/package/__init__.py +2 -0
- tempergraph/package/change_report.py +116 -0
- tempergraph/package/changelog.py +263 -0
- tempergraph/package/docs_check.py +115 -0
- tempergraph/package/importer.py +90 -0
- tempergraph/package/inventory.py +111 -0
- tempergraph/package/loader.py +250 -0
- tempergraph/package/manifest.py +256 -0
- tempergraph/package/readiness.py +124 -0
- tempergraph/package/registry.py +383 -0
- tempergraph/package/rules.py +128 -0
- tempergraph/package/scan.py +65 -0
- tempergraph/package/selftest.py +348 -0
- tempergraph/package/stamp.py +213 -0
- tempergraph/package/transforms.py +481 -0
- tempergraph/package/upgrade.py +625 -0
- tempergraph/provenance.py +183 -0
- tempergraph/py.typed +0 -0
- tempergraph/release.py +17 -0
- tempergraph/render/__init__.py +0 -0
- tempergraph/render/output.py +72 -0
- tempergraph/render/prompt.py +166 -0
- tempergraph/render/template.py +86 -0
- tempergraph/run/__init__.py +2 -0
- tempergraph/run/asking.py +233 -0
- tempergraph/run/audit.py +63 -0
- tempergraph/run/check_worker.py +167 -0
- tempergraph/run/checks.py +517 -0
- tempergraph/run/commands.py +210 -0
- tempergraph/run/complexity.py +268 -0
- tempergraph/run/contest.py +76 -0
- tempergraph/run/council.py +368 -0
- tempergraph/run/council_run.py +527 -0
- tempergraph/run/events.py +279 -0
- tempergraph/run/finalize.py +132 -0
- tempergraph/run/gate.py +747 -0
- tempergraph/run/guard.py +89 -0
- tempergraph/run/judging.py +357 -0
- tempergraph/run/ladder.py +230 -0
- tempergraph/run/log.py +600 -0
- tempergraph/run/mapping.py +183 -0
- tempergraph/run/nodes.py +2304 -0
- tempergraph/run/outcome.py +255 -0
- tempergraph/run/outcome_record.py +292 -0
- tempergraph/run/outcome_trust.py +99 -0
- tempergraph/run/rerun.py +351 -0
- tempergraph/run/reserve.py +85 -0
- tempergraph/run/resources.py +76 -0
- tempergraph/run/risk.py +231 -0
- tempergraph/run/runner.py +1579 -0
- tempergraph/run/scriptcache.py +178 -0
- tempergraph/run/selfcheck.py +105 -0
- tempergraph/run/session_record.py +72 -0
- tempergraph/run/subrun.py +278 -0
- tempergraph/run/supervision.py +125 -0
- tempergraph/run/tool_access.py +101 -0
- tempergraph/schedule/__init__.py +25 -0
- tempergraph/schedule/credentials.py +167 -0
- tempergraph/schedule/echo.py +169 -0
- tempergraph/schedule/exact.py +275 -0
- tempergraph/schedule/export.py +164 -0
- tempergraph/schedule/launch.py +89 -0
- tempergraph/schedule/ledger.py +133 -0
- tempergraph/schedule/loop.py +176 -0
- tempergraph/schedule/model.py +440 -0
- tempergraph/schedule/policies.py +414 -0
- tempergraph/schedule/store.py +150 -0
- tempergraph/schedule/tick.py +377 -0
- tempergraph/schedule/token.py +81 -0
- tempergraph/schedule/triggers.py +210 -0
- tempergraph/schedule/words.py +423 -0
- tempergraph/security/__init__.py +0 -0
- tempergraph/security/launch.py +25 -0
- tempergraph/security/scrub.py +58 -0
- tempergraph/settings.py +950 -0
- tempergraph/store/__init__.py +0 -0
- tempergraph/store/codelog.py +73 -0
- tempergraph/store/layout.py +198 -0
- tempergraph/store/logs.py +325 -0
- tempergraph/store/manifest.py +99 -0
- tempergraph/store/migrate.py +188 -0
- tempergraph/workspace.py +874 -0
- tempergraph-0.7.1.dist-info/METADATA +70 -0
- tempergraph-0.7.1.dist-info/RECORD +232 -0
- tempergraph-0.7.1.dist-info/WHEEL +5 -0
- tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
- tempergraph-0.7.1.dist-info/top_level.txt +2 -0
- 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]}
|