smzuhaib06 commited on
Commit
6db0c22
·
1 Parent(s): ccd25ed

Deploy DebateMind Gradio dashboard

Browse files
README.md CHANGED
@@ -1,3 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # 🏛️ DebateMind
2
 
3
  A multi-agent parliamentary simulation environment for training LLMs on long-horizon negotiation and argument consistency via reinforcement learning. Built on the [OpenEnv](https://github.com/openenv) framework.
 
1
+ ---
2
+ title: DebateMind
3
+ emoji: 🏛️
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.33.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ tags:
12
+ - openenv
13
+ - reinforcement-learning
14
+ - multi-agent
15
+ - negotiation
16
+ - grpo
17
+ ---
18
+
19
  # 🏛️ DebateMind
20
 
21
  A multi-agent parliamentary simulation environment for training LLMs on long-horizon negotiation and argument consistency via reinforcement learning. Built on the [OpenEnv](https://github.com/openenv) framework.
debatemind/debatemind/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """DebateMind: OpenEnv-compliant parliamentary simulation environment."""
debatemind/debatemind/engine/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """DebateMind engine components."""
debatemind/debatemind/engine/argument_tracker.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Argument tracker for recording agent positions, promises, and coalitions.
2
+
3
+ Tracks all agent actions across an episode so that argument consistency
4
+ can be evaluated by the reward rubric.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass, field
10
+
11
+
12
+ @dataclass
13
+ class Position:
14
+ """A position stated by the agent on a topic during a turn."""
15
+
16
+ turn: int
17
+ statement: str
18
+ topic: str
19
+
20
+
21
+ @dataclass
22
+ class Promise:
23
+ """A promise made by the agent to a faction."""
24
+
25
+ turn: int
26
+ target_faction: str
27
+ content: str
28
+ fulfilled: bool | None = None # None = not yet evaluated
29
+
30
+
31
+ @dataclass
32
+ class CoalitionAgreement:
33
+ """A coalition agreement formed between the agent and factions."""
34
+
35
+ turn: int
36
+ factions: list[str]
37
+ terms: str
38
+
39
+
40
+ class ArgumentTracker:
41
+ """Records and retrieves all agent positions, promises, and coalition agreements."""
42
+
43
+ def __init__(self) -> None:
44
+ self.positions: list[Position] = []
45
+ self.promises: list[Promise] = []
46
+ self.coalition_agreements: list[CoalitionAgreement] = []
47
+
48
+ def record_position(self, turn: int, statement: str, topic: str) -> None:
49
+ """Record a position stated by the agent."""
50
+ self.positions.append(Position(turn=turn, statement=statement, topic=topic))
51
+
52
+ def record_promise(self, turn: int, target_faction: str, content: str) -> None:
53
+ """Record a promise made by the agent to a faction."""
54
+ self.promises.append(
55
+ Promise(turn=turn, target_faction=target_faction, content=content)
56
+ )
57
+
58
+ def record_coalition(self, turn: int, factions: list[str], terms: str) -> None:
59
+ """Record a coalition agreement formed by the agent."""
60
+ self.coalition_agreements.append(
61
+ CoalitionAgreement(turn=turn, factions=factions, terms=terms)
62
+ )
63
+
64
+ def get_all_records(self) -> dict:
65
+ """Return all tracked records as a dictionary.
66
+
67
+ Returns a dict with keys 'positions', 'promises', and
68
+ 'coalition_agreements', each containing the respective list.
69
+ """
70
+ return {
71
+ "positions": list(self.positions),
72
+ "promises": list(self.promises),
73
+ "coalition_agreements": list(self.coalition_agreements),
74
+ }
75
+
76
+ # ------------------------------------------------------------------
77
+ # Deterministic consistency scoring
78
+ # ------------------------------------------------------------------
79
+
80
+ def _extract_keywords(self, text: str) -> set[str]:
81
+ """Extract meaningful lowercase keywords from text.
82
+
83
+ Strips common stop words and returns a set of tokens that can be
84
+ used for overlap-based matching.
85
+ """
86
+ _STOP_WORDS = frozenset({
87
+ "i", "we", "the", "a", "an", "is", "are", "was", "were", "be",
88
+ "been", "being", "have", "has", "had", "do", "does", "did",
89
+ "will", "would", "shall", "should", "may", "might", "can",
90
+ "could", "to", "of", "in", "for", "on", "with", "at", "by",
91
+ "from", "as", "into", "through", "during", "before", "after",
92
+ "and", "but", "or", "nor", "not", "so", "yet", "both", "either",
93
+ "neither", "each", "every", "all", "any", "few", "more", "most",
94
+ "other", "some", "such", "no", "only", "own", "same", "than",
95
+ "too", "very", "just", "because", "if", "when", "where", "how",
96
+ "what", "which", "who", "whom", "this", "that", "these", "those",
97
+ "it", "its", "my", "our", "your", "his", "her", "their", "them",
98
+ "about", "up", "out", "then", "also",
99
+ })
100
+ tokens = text.lower().split()
101
+ return {t.strip(".,;:!?\"'()[]{}") for t in tokens if len(t) > 1} - _STOP_WORDS
102
+
103
+ def promise_kept_score(self, bill_clauses: list[str], amendments: list) -> float:
104
+ """Score whether promises were followed through in amendments/clauses.
105
+
106
+ +1 for each promise whose keywords overlap with any amendment's
107
+ new_text or current bill clause text. Returns ratio of kept
108
+ promises, or 1.0 if no promises were made.
109
+
110
+ Contributes up to +0.4 of the total consistency score.
111
+ """
112
+ if not self.promises:
113
+ return 1.0
114
+
115
+ clause_text = " ".join(bill_clauses).lower()
116
+ amendment_texts = " ".join(
117
+ getattr(a, "new_text", a.get("new_text", "")) if isinstance(a, dict) else a.new_text
118
+ for a in amendments
119
+ ).lower()
120
+ combined = clause_text + " " + amendment_texts
121
+
122
+ kept = 0
123
+ for promise in self.promises:
124
+ keywords = self._extract_keywords(promise.content)
125
+ if not keywords:
126
+ kept += 1
127
+ continue
128
+ if any(kw in combined for kw in keywords):
129
+ kept += 1
130
+ promise.fulfilled = True
131
+ else:
132
+ promise.fulfilled = False
133
+
134
+ return kept / len(self.promises)
135
+
136
+ def no_contradiction_score(self) -> float:
137
+ """Score whether the agent avoided contradicting itself on the same topic.
138
+
139
+ Groups positions by topic, then checks for contradictory signals
140
+ within each group using simple negation/opposition detection.
141
+ Returns 1.0 if no contradictions found, decreasing toward 0.0
142
+ as contradictions accumulate.
143
+
144
+ Contributes up to +0.4 of the total consistency score.
145
+ """
146
+ if len(self.positions) < 2:
147
+ return 1.0
148
+
149
+ _NEGATION_PAIRS = [
150
+ ({"support", "favor", "pro", "yes", "agree", "endorse", "back", "promote"},
151
+ {"oppose", "against", "anti", "no", "disagree", "reject", "remove", "eliminate", "cut"}),
152
+ ({"increase", "expand", "raise", "strengthen", "add", "more", "mandate"},
153
+ {"decrease", "reduce", "lower", "weaken", "remove", "less", "eliminate", "cut"}),
154
+ ]
155
+
156
+ # Group positions by topic
157
+ by_topic: dict[str, list[Position]] = {}
158
+ for pos in self.positions:
159
+ topic_key = pos.topic.lower().strip()
160
+ by_topic.setdefault(topic_key, []).append(pos)
161
+
162
+ contradictions = 0
163
+ total_pairs = 0
164
+
165
+ for topic, positions in by_topic.items():
166
+ if len(positions) < 2:
167
+ continue
168
+ for i in range(len(positions)):
169
+ for j in range(i + 1, len(positions)):
170
+ total_pairs += 1
171
+ kw_a = self._extract_keywords(positions[i].statement)
172
+ kw_b = self._extract_keywords(positions[j].statement)
173
+
174
+ for pos_set, neg_set in _NEGATION_PAIRS:
175
+ a_positive = bool(kw_a & pos_set)
176
+ a_negative = bool(kw_a & neg_set)
177
+ b_positive = bool(kw_b & pos_set)
178
+ b_negative = bool(kw_b & neg_set)
179
+
180
+ if (a_positive and b_negative) or (a_negative and b_positive):
181
+ contradictions += 1
182
+ break
183
+
184
+ if total_pairs == 0:
185
+ return 1.0
186
+
187
+ return max(0.0, 1.0 - (contradictions / total_pairs))
188
+
189
+ def position_repetition_score(self) -> float:
190
+ """Score whether the agent restated core positions across readings.
191
+
192
+ Checks if the same topic appears in positions recorded at
193
+ different reading stages (approximated by turn ranges: turns 1-25
194
+ = reading 1, 26-50 = reading 2, 51+ = reading 3). Returns the
195
+ ratio of topics that span multiple reading phases.
196
+
197
+ Contributes up to +0.2 of the total consistency score.
198
+ """
199
+ if not self.positions:
200
+ return 0.0
201
+
202
+ def _reading_phase(turn: int) -> int:
203
+ if turn <= 25:
204
+ return 1
205
+ elif turn <= 50:
206
+ return 2
207
+ else:
208
+ return 3
209
+
210
+ # Map topic -> set of reading phases
211
+ topic_phases: dict[str, set[int]] = {}
212
+ for pos in self.positions:
213
+ topic_key = pos.topic.lower().strip()
214
+ topic_phases.setdefault(topic_key, set()).add(_reading_phase(pos.turn))
215
+
216
+ if not topic_phases:
217
+ return 0.0
218
+
219
+ multi_phase_topics = sum(
220
+ 1 for phases in topic_phases.values() if len(phases) >= 2
221
+ )
222
+ return multi_phase_topics / len(topic_phases)
223
+
224
+ def compute_consistency_score(
225
+ self, bill_clauses: list[str], amendments: list
226
+ ) -> float:
227
+ """Compute the full deterministic argument consistency score.
228
+
229
+ Three sub-components weighted as:
230
+ - promise_kept: 0.4
231
+ - no_contradiction: 0.4
232
+ - position_repetition: 0.2
233
+
234
+ Returns a float in [0.0, 1.0].
235
+ """
236
+ pk = self.promise_kept_score(bill_clauses, amendments)
237
+ nc = self.no_contradiction_score()
238
+ pr = self.position_repetition_score()
239
+ return 0.4 * pk + 0.4 * nc + 0.2 * pr
debatemind/debatemind/engine/faction_agent.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Faction agent system — gives factions autonomous behavior.
2
+
3
+ Each faction can generate responses to agent actions, react to amendments,
4
+ form counter-coalitions, and shift positions dynamically. This creates
5
+ emergent multi-agent negotiation dynamics.
6
+
7
+ Two modes:
8
+ - StrategicFactionAgent: rule-based heuristic agent (default, no deps)
9
+ - LLMFactionAgent: wraps an LLM for open-ended faction responses
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import random
15
+ from abc import ABC, abstractmethod
16
+ from dataclasses import dataclass, field
17
+
18
+ from debatemind.models.bill import Bill
19
+ from debatemind.models.faction import Faction
20
+ from debatemind.models.observation import TranscriptEntry
21
+
22
+
23
+ @dataclass
24
+ class FactionResponse:
25
+ """A faction's autonomous response to an agent action."""
26
+
27
+ faction_id: str
28
+ message: str
29
+ trust_delta: float = 0.0 # change to apply to trust_score
30
+ stance_shift: str | None = None # "support", "oppose", "undecided", or None
31
+
32
+
33
+ class BaseFactionAgent(ABC):
34
+ """Abstract base for faction agent strategies."""
35
+
36
+ @abstractmethod
37
+ def respond(
38
+ self,
39
+ faction: Faction,
40
+ agent_action: dict,
41
+ bill: Bill,
42
+ turn: int,
43
+ transcript: list[TranscriptEntry],
44
+ ) -> FactionResponse:
45
+ """Generate a faction response to the agent's action."""
46
+ ...
47
+
48
+
49
+ class StrategicFactionAgent(BaseFactionAgent):
50
+ """Rule-based faction agent with personality-driven responses.
51
+
52
+ Each faction evaluates the agent's action against its priorities and
53
+ trust level, then generates a contextual response with trust adjustments.
54
+ """
55
+
56
+ def __init__(self, rng: random.Random | None = None) -> None:
57
+ self.rng = rng or random.Random()
58
+
59
+ def respond(
60
+ self,
61
+ faction: Faction,
62
+ agent_action: dict,
63
+ bill: Bill,
64
+ turn: int,
65
+ transcript: list[TranscriptEntry],
66
+ ) -> FactionResponse:
67
+ """Generate a strategic response based on faction priorities."""
68
+ speech = agent_action.get("speech", "")
69
+ tool_name = agent_action.get("tool_name")
70
+ tool_args = agent_action.get("tool_args", {})
71
+
72
+ # Determine relevance of the action to this faction
73
+ relevance = self._compute_relevance(faction, speech, tool_name, tool_args)
74
+ sentiment = self._compute_sentiment(faction, speech, tool_name, tool_args, bill)
75
+
76
+ # Generate response based on action type
77
+ if tool_name == "negotiate" and tool_args.get("faction_id") == faction.faction_id:
78
+ return self._respond_to_negotiation(faction, tool_args, sentiment, turn)
79
+ elif tool_name == "propose_amendment":
80
+ return self._respond_to_amendment(faction, tool_args, bill, sentiment, turn)
81
+ elif speech and relevance > 0.3:
82
+ return self._respond_to_speech(faction, speech, sentiment, turn)
83
+ else:
84
+ return self._passive_response(faction, turn)
85
+
86
+ def _compute_relevance(
87
+ self, faction: Faction, speech: str, tool_name: str | None, tool_args: dict
88
+ ) -> float:
89
+ """How relevant is this action to the faction? [0, 1]"""
90
+ if tool_name == "negotiate" and tool_args.get("faction_id") == faction.faction_id:
91
+ return 1.0
92
+ text = speech.lower() + " " + str(tool_args).lower()
93
+ matches = sum(1 for p in faction.public_priorities if p.lower() in text)
94
+ return min(1.0, matches / max(len(faction.public_priorities), 1))
95
+
96
+ def _compute_sentiment(
97
+ self,
98
+ faction: Faction,
99
+ speech: str,
100
+ tool_name: str | None,
101
+ tool_args: dict,
102
+ bill: Bill,
103
+ ) -> float:
104
+ """How positively does the faction view this action? [-1, 1]"""
105
+ text = (speech + " " + str(tool_args)).lower()
106
+ all_priorities = faction.public_priorities + faction.hidden_priorities
107
+
108
+ positive_matches = sum(1 for p in all_priorities if p.lower() in text)
109
+ # Check for opposition keywords
110
+ opposition_words = {"oppose", "remove", "eliminate", "cut", "against", "reject"}
111
+ has_opposition = any(w in text for w in opposition_words)
112
+
113
+ score = positive_matches / max(len(all_priorities), 1)
114
+ if has_opposition:
115
+ score = -score if score > 0 else -0.3
116
+
117
+ return max(-1.0, min(1.0, score))
118
+
119
+ def _respond_to_negotiation(
120
+ self, faction: Faction, tool_args: dict, sentiment: float, turn: int
121
+ ) -> FactionResponse:
122
+ """Respond to a direct negotiation attempt."""
123
+ offer = tool_args.get("offer", {})
124
+ addressed = offer.get("priorities_addressed", [])
125
+ concessions = offer.get("concessions", {})
126
+
127
+ # Check how many of our priorities are addressed
128
+ matched = sum(
129
+ 1 for p in faction.public_priorities
130
+ if any(p.lower() in a.lower() for a in addressed)
131
+ )
132
+ match_ratio = matched / max(len(faction.public_priorities), 1)
133
+
134
+ if match_ratio >= 0.6 and concessions:
135
+ trust_delta = 0.08 + self.rng.uniform(0, 0.04)
136
+ msg = (
137
+ f"{faction.name}: Your offer addresses our key concerns. "
138
+ f"We appreciate the concrete concessions on "
139
+ f"{', '.join(list(concessions.keys())[:2])}. "
140
+ f"We're moving toward support."
141
+ )
142
+ return FactionResponse(
143
+ faction_id=faction.faction_id,
144
+ message=msg,
145
+ trust_delta=trust_delta,
146
+ stance_shift="support" if faction.trust_score + trust_delta > 0.6 else "undecided",
147
+ )
148
+ elif match_ratio >= 0.3:
149
+ trust_delta = 0.03
150
+ msg = (
151
+ f"{faction.name}: You've touched on some of our priorities, "
152
+ f"but we need more specifics. What about "
153
+ f"{faction.public_priorities[-1]}?"
154
+ )
155
+ return FactionResponse(
156
+ faction_id=faction.faction_id,
157
+ message=msg,
158
+ trust_delta=trust_delta,
159
+ stance_shift="undecided",
160
+ )
161
+ else:
162
+ trust_delta = -0.05
163
+ unaddressed = [
164
+ p for p in faction.public_priorities
165
+ if not any(p.lower() in a.lower() for a in addressed)
166
+ ]
167
+ msg = (
168
+ f"{faction.name}: This offer doesn't address our core concerns: "
169
+ f"{', '.join(unaddressed[:2])}. We expected better."
170
+ )
171
+ return FactionResponse(
172
+ faction_id=faction.faction_id,
173
+ message=msg,
174
+ trust_delta=trust_delta,
175
+ stance_shift="oppose" if faction.trust_score < 0.4 else None,
176
+ )
177
+
178
+ def _respond_to_amendment(
179
+ self,
180
+ faction: Faction,
181
+ tool_args: dict,
182
+ bill: Bill,
183
+ sentiment: float,
184
+ turn: int,
185
+ ) -> FactionResponse:
186
+ """Respond to a proposed amendment."""
187
+ new_text = tool_args.get("new_text", "").lower()
188
+ priorities_in_text = [
189
+ p for p in faction.public_priorities if p.lower() in new_text
190
+ ]
191
+
192
+ if priorities_in_text:
193
+ trust_delta = 0.05
194
+ msg = (
195
+ f"{faction.name}: This amendment aligns with our position on "
196
+ f"{', '.join(priorities_in_text)}. Positive development."
197
+ )
198
+ return FactionResponse(
199
+ faction_id=faction.faction_id,
200
+ message=msg,
201
+ trust_delta=trust_delta,
202
+ )
203
+ elif sentiment < -0.2:
204
+ trust_delta = -0.06
205
+ msg = (
206
+ f"{faction.name}: This amendment moves the bill away from "
207
+ f"our priorities. We have concerns."
208
+ )
209
+ return FactionResponse(
210
+ faction_id=faction.faction_id,
211
+ message=msg,
212
+ trust_delta=trust_delta,
213
+ )
214
+ else:
215
+ msg = f"{faction.name}: We're reviewing this amendment."
216
+ return FactionResponse(
217
+ faction_id=faction.faction_id,
218
+ message=msg,
219
+ trust_delta=0.0,
220
+ )
221
+
222
+ def _respond_to_speech(
223
+ self, faction: Faction, speech: str, sentiment: float, turn: int
224
+ ) -> FactionResponse:
225
+ """Respond to a relevant speech."""
226
+ if sentiment > 0.3:
227
+ trust_delta = 0.02
228
+ msg = (
229
+ f"{faction.name}: We appreciate the agent's attention to "
230
+ f"issues that matter to us."
231
+ )
232
+ elif sentiment < -0.2:
233
+ trust_delta = -0.03
234
+ msg = (
235
+ f"{faction.name}: The agent's remarks conflict with our "
236
+ f"core values. Disappointing."
237
+ )
238
+ else:
239
+ trust_delta = 0.0
240
+ msg = f"{faction.name}: Noted. We're listening."
241
+
242
+ return FactionResponse(
243
+ faction_id=faction.faction_id,
244
+ message=msg,
245
+ trust_delta=trust_delta,
246
+ )
247
+
248
+ def _passive_response(self, faction: Faction, turn: int) -> FactionResponse:
249
+ """Default response when the action isn't directly relevant."""
250
+ return FactionResponse(
251
+ faction_id=faction.faction_id,
252
+ message=f"{faction.name}: We're observing.",
253
+ trust_delta=0.0,
254
+ )
255
+
256
+
257
+ class FactionAgentManager:
258
+ """Manages faction agents and coordinates their responses.
259
+
260
+ Processes agent actions through all faction agents, applies trust
261
+ deltas, records responses in the transcript, and can trigger
262
+ autonomous faction behaviors (counter-coalitions, position shifts).
263
+ """
264
+
265
+ def __init__(
266
+ self,
267
+ factions: list[Faction],
268
+ agent: BaseFactionAgent | None = None,
269
+ rng: random.Random | None = None,
270
+ ) -> None:
271
+ self.factions = factions
272
+ self.agent = agent or StrategicFactionAgent(rng=rng)
273
+ self.rng = rng or random.Random()
274
+ self.faction_memory: dict[str, list[FactionResponse]] = {
275
+ f.faction_id: [] for f in factions
276
+ }
277
+
278
+ def process_action(
279
+ self,
280
+ action: dict,
281
+ bill: Bill,
282
+ turn: int,
283
+ transcript: list[TranscriptEntry],
284
+ ) -> list[FactionResponse]:
285
+ """Run all faction agents against the agent's action.
286
+
287
+ Returns a list of FactionResponse objects. Trust deltas are
288
+ applied to the faction objects in-place.
289
+ """
290
+ responses: list[FactionResponse] = []
291
+
292
+ for faction in self.factions:
293
+ response = self.agent.respond(faction, action, bill, turn, transcript)
294
+
295
+ # Apply trust delta
296
+ faction.trust_score = max(
297
+ 0.0, min(1.0, faction.trust_score + response.trust_delta)
298
+ )
299
+
300
+ # Store in memory
301
+ self.faction_memory[faction.faction_id].append(response)
302
+ responses.append(response)
303
+
304
+ return responses
305
+
306
+ def get_faction_responses_as_transcript(
307
+ self, responses: list[FactionResponse], turn: int
308
+ ) -> list[TranscriptEntry]:
309
+ """Convert faction responses to transcript entries."""
310
+ entries = []
311
+ for r in responses:
312
+ if r.message and r.message != f"{r.faction_id}: We're observing.":
313
+ entries.append(
314
+ TranscriptEntry(
315
+ turn=turn,
316
+ actor=r.faction_id,
317
+ action_type="faction_response",
318
+ content=r.message,
319
+ )
320
+ )
321
+ return entries
debatemind/debatemind/engine/reward_rubric.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reward rubric for DebateMind parliamentary simulation.
2
+
3
+ Computes a composable reward as a weighted sum of four components:
4
+ bill passage, coalition size, argument consistency, and amendment quality.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+
11
+ from debatemind.engine.argument_tracker import ArgumentTracker
12
+ from debatemind.engine.vote_engine import VoteResult
13
+ from debatemind.models.bill import Bill, BillStateMachine
14
+ from debatemind.models.faction import Faction
15
+
16
+
17
+ @dataclass
18
+ class RewardBreakdown:
19
+ """Breakdown of reward into individual component scores and total."""
20
+
21
+ bill_passage: float
22
+ coalition_size: float
23
+ argument_consistency: float
24
+ amendment_quality: float
25
+ total: float
26
+
27
+
28
+ class RewardRubric:
29
+ """Composable reward rubric with four weighted components.
30
+
31
+ Components:
32
+ bill_passage (0.40): 1.0 if bill passed, 0.0 otherwise
33
+ coalition_size (0.20): proportion of factions voting yes
34
+ argument_consistency (0.30): LLM-as-judge evaluation of consistency
35
+ amendment_quality (0.10): how well amendments addressed contested clauses
36
+ """
37
+
38
+ WEIGHTS: dict[str, float] = {
39
+ "bill_passage": 0.40,
40
+ "coalition_size": 0.20,
41
+ "argument_consistency": 0.30,
42
+ "amendment_quality": 0.10,
43
+ }
44
+
45
+ def bill_passage_score(self, bill: Bill) -> float:
46
+ """Return 1.0 if the bill passed, 0.0 otherwise."""
47
+ return 1.0 if bill.status == "passed" else 0.0
48
+
49
+ def coalition_size_score(self, vote_result: VoteResult) -> float:
50
+ """Return the proportion of factions that voted yes.
51
+
52
+ A faction is counted as voting yes when seats_yes > seats_no.
53
+ """
54
+ faction_votes = vote_result.faction_votes
55
+ if not faction_votes:
56
+ return 0.0
57
+
58
+ yes_factions = sum(
59
+ 1 for fv in faction_votes.values() if fv.seats_yes > fv.seats_no
60
+ )
61
+ return yes_factions / len(faction_votes)
62
+
63
+ def argument_consistency_score(
64
+ self,
65
+ tracker: ArgumentTracker,
66
+ bill: Bill,
67
+ ) -> float:
68
+ """Evaluate argument consistency deterministically.
69
+
70
+ Uses the ArgumentTracker's three sub-scores:
71
+ - promise_kept (+0.4): promises followed through in amendments/clauses
72
+ - no_contradiction (+0.4): no opposing positions on the same topic
73
+ - position_repetition (+0.2): core positions restated across readings
74
+
75
+ No LLM call is used — fully deterministic from tracker data.
76
+
77
+ Args:
78
+ tracker: The argument tracker with recorded positions/promises.
79
+ bill: The current bill (used to check promise fulfillment).
80
+
81
+ Returns:
82
+ A float in [0.0, 1.0].
83
+ """
84
+ return tracker.compute_consistency_score(bill.clauses, bill.amendments)
85
+
86
+ def amendment_quality_score(self, bill: Bill, factions: list[Faction]) -> float:
87
+ """Score how well amendments addressed contested clauses.
88
+
89
+ Score = amendments_on_contested / total_contested.
90
+ Returns 1.0 if there are no contested clauses.
91
+ """
92
+ bsm = BillStateMachine(bill)
93
+ contested = bsm.get_contested_clauses(factions)
94
+
95
+ if not contested:
96
+ return 1.0
97
+
98
+ contested_set = set(contested)
99
+ amendments_on_contested = sum(
100
+ 1 for a in bill.amendments if a.clause_index in contested_set
101
+ )
102
+
103
+ return min(1.0, amendments_on_contested / len(contested))
104
+
105
+ def compute(self, env_state: dict) -> RewardBreakdown:
106
+ """Compute the total reward as a weighted sum of all components.
107
+
108
+ Args:
109
+ env_state: Dictionary with keys:
110
+ - "bill": Bill instance
111
+ - "vote_result": VoteResult instance
112
+ - "tracker": ArgumentTracker instance
113
+ - "factions": list of Faction instances
114
+
115
+ Returns:
116
+ RewardBreakdown with individual scores and weighted total.
117
+ """
118
+ bill: Bill = env_state["bill"]
119
+ vote_result: VoteResult = env_state["vote_result"]
120
+ tracker: ArgumentTracker = env_state["tracker"]
121
+ factions: list[Faction] = env_state["factions"]
122
+
123
+ bp = self.bill_passage_score(bill)
124
+ cs = self.coalition_size_score(vote_result)
125
+ ac = self.argument_consistency_score(tracker, bill)
126
+ aq = self.amendment_quality_score(bill, factions)
127
+
128
+ total = (
129
+ self.WEIGHTS["bill_passage"] * bp
130
+ + self.WEIGHTS["coalition_size"] * cs
131
+ + self.WEIGHTS["argument_consistency"] * ac
132
+ + self.WEIGHTS["amendment_quality"] * aq
133
+ )
134
+
135
+ return RewardBreakdown(
136
+ bill_passage=bp,
137
+ coalition_size=cs,
138
+ argument_consistency=ac,
139
+ amendment_quality=aq,
140
+ total=total,
141
+ )
debatemind/debatemind/engine/vote_engine.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Vote engine for DebateMind parliamentary simulation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+ from dataclasses import dataclass
7
+
8
+ from debatemind.models.bill import Bill
9
+ from debatemind.models.faction import Faction
10
+
11
+
12
+ @dataclass
13
+ class FactionVote:
14
+ """Vote details for a single faction."""
15
+
16
+ faction_id: str
17
+ base_probability: float
18
+ noise: float
19
+ final_probability: float # clamped to [0.0, 1.0]
20
+ seats_yes: int
21
+ seats_no: int
22
+
23
+
24
+ @dataclass
25
+ class VoteResult:
26
+ """Aggregated vote result across all factions."""
27
+
28
+ faction_votes: dict[str, FactionVote] # faction_id -> vote details
29
+ total_yes: int
30
+ total_no: int
31
+ threshold: float
32
+ passed: bool
33
+
34
+
35
+ class VoteEngine:
36
+ """Computes vote outcomes with stochastic noise per faction.
37
+
38
+ Each reading has an increasing majority threshold:
39
+ Reading 1: >50%
40
+ Reading 2: >=60%
41
+ Reading 3: >=66%
42
+ """
43
+
44
+ THRESHOLDS: dict[int, float] = {1: 0.50, 2: 0.60, 3: 0.66}
45
+
46
+ def required_majority(self, reading: int) -> float:
47
+ """Return the majority threshold for the given reading."""
48
+ return self.THRESHOLDS[reading]
49
+
50
+ def calculate_votes(
51
+ self,
52
+ factions: list[Faction],
53
+ bill: Bill,
54
+ rng: random.Random | None = None,
55
+ ) -> VoteResult:
56
+ """Compute vote totals with ±0.1 stochastic noise per faction.
57
+
58
+ For each faction:
59
+ 1. Compute base_probability from evaluate_offer against the bill.
60
+ 2. Add uniform noise in [-0.1, +0.1].
61
+ 3. Clamp to [0.0, 1.0] -> final_probability.
62
+ 4. seats_yes = round(final_probability * seat_count).
63
+ 5. Sum all seats_yes, compare against required_majority(reading) * 100.
64
+ """
65
+ if rng is None:
66
+ rng = random.Random()
67
+
68
+ offer = _bill_to_offer(bill)
69
+ reading = bill.reading
70
+ threshold = self.required_majority(reading) if reading in self.THRESHOLDS else 0.50
71
+
72
+ faction_votes: dict[str, FactionVote] = {}
73
+ total_yes = 0
74
+ total_no = 0
75
+
76
+ for faction in factions:
77
+ base_probability = faction.evaluate_offer(offer)
78
+ noise = rng.uniform(-0.1, 0.1)
79
+ final_probability = max(0.0, min(1.0, base_probability + noise))
80
+
81
+ seats_yes = round(final_probability * faction.seat_count)
82
+ seats_no = faction.seat_count - seats_yes
83
+
84
+ faction_votes[faction.faction_id] = FactionVote(
85
+ faction_id=faction.faction_id,
86
+ base_probability=base_probability,
87
+ noise=noise,
88
+ final_probability=final_probability,
89
+ seats_yes=seats_yes,
90
+ seats_no=seats_no,
91
+ )
92
+
93
+ total_yes += seats_yes
94
+ total_no += seats_no
95
+
96
+ passed = total_yes > threshold * 100
97
+
98
+ return VoteResult(
99
+ faction_votes=faction_votes,
100
+ total_yes=total_yes,
101
+ total_no=total_no,
102
+ threshold=threshold,
103
+ passed=passed,
104
+ )
105
+
106
+
107
+ def _bill_to_offer(bill: Bill) -> dict:
108
+ """Convert a bill's current state into an offer dict for evaluate_offer.
109
+
110
+ Maps bill clauses to 'priorities_addressed' keywords so that
111
+ faction.evaluate_offer can score the bill.
112
+ """
113
+ return {
114
+ "priorities_addressed": list(bill.clauses),
115
+ "concessions": {},
116
+ }
debatemind/debatemind/environment.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Parliament environment for DebateMind simulation.
2
+
3
+ Implements the OpenEnv-compliant Gymnasium-style API (reset, step, state)
4
+ for the parliamentary negotiation environment.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import random
11
+
12
+ from debatemind.engine.argument_tracker import ArgumentTracker
13
+ from debatemind.engine.faction_agent import FactionAgentManager
14
+ from debatemind.engine.reward_rubric import RewardRubric
15
+ from debatemind.engine.vote_engine import VoteEngine
16
+ from debatemind.models.bill import Bill, BillStateMachine, DEFAULT_BILL
17
+ from debatemind.models.faction import Faction, get_default_factions
18
+ from debatemind.models.observation import (
19
+ Deal,
20
+ FactionStance,
21
+ Observation,
22
+ TranscriptEntry,
23
+ )
24
+ from debatemind.openenv_stub import MCPEnvironment
25
+
26
+
27
+ class ParliamentEnvironment(MCPEnvironment):
28
+ """OpenEnv-compliant parliamentary simulation environment.
29
+
30
+ Manages turn progression, faction interactions, bill state, and vote
31
+ outcomes over episodes of 50-100 turns.
32
+ """
33
+
34
+ def __init__(self, max_turns: int = 75) -> None:
35
+ self.max_turns = max_turns
36
+ self.bill: Bill | None = None
37
+ self.bill_sm: BillStateMachine | None = None
38
+ self.factions: list[Faction] = []
39
+ self.vote_engine: VoteEngine | None = None
40
+ self.reward_rubric = RewardRubric()
41
+ self.argument_tracker: ArgumentTracker | None = None
42
+ self.transcript: list[TranscriptEntry] = []
43
+ self.turn: int = 0
44
+ self.done: bool = False
45
+ self.rng = random.Random()
46
+ self.faction_manager: FactionAgentManager | None = None
47
+
48
+ def reset(self, bill_config: dict | None = None, **kwargs) -> Observation:
49
+ """Initialize a new parliamentary session.
50
+
51
+ Args:
52
+ bill_config: Optional dict with 'title' and 'clauses' keys
53
+ to override the default climate bill.
54
+
55
+ Returns:
56
+ The initial Observation for the episode.
57
+ """
58
+ if bill_config is not None:
59
+ self.bill = Bill(
60
+ title=bill_config.get("title", DEFAULT_BILL.title),
61
+ clauses=list(bill_config.get("clauses", DEFAULT_BILL.clauses)),
62
+ amendments=[],
63
+ reading=0,
64
+ status="active",
65
+ )
66
+ else:
67
+ self.bill = Bill(
68
+ title=DEFAULT_BILL.title,
69
+ clauses=list(DEFAULT_BILL.clauses),
70
+ amendments=[],
71
+ reading=0,
72
+ status="active",
73
+ )
74
+
75
+ self.bill_sm = BillStateMachine(self.bill)
76
+ self.factions = get_default_factions()
77
+ self.vote_engine = VoteEngine()
78
+ self.argument_tracker = ArgumentTracker()
79
+ self.transcript = []
80
+ self.turn = 0
81
+ self.done = False
82
+ self.faction_manager = FactionAgentManager(
83
+ factions=self.factions, rng=self.rng
84
+ )
85
+
86
+ # Auto-advance bill from draft (reading 0) to reading 1
87
+ self.bill_sm.advance_reading(vote_passed=True)
88
+
89
+ return self._build_observation()
90
+
91
+ def step(self, action: dict, **kwargs) -> tuple[Observation, float, bool, dict]:
92
+ """Advance the simulation by one turn.
93
+
94
+ Args:
95
+ action: Dict that may contain:
96
+ - "speech": str — agent's public statement
97
+ - "tool_name": str — name of MCP tool to call
98
+ - "tool_args": dict — arguments for the tool
99
+
100
+ Returns:
101
+ Tuple of (observation, reward, done, info).
102
+ """
103
+ info: dict = {}
104
+
105
+ if self.done:
106
+ obs = self._build_observation()
107
+ info["error"] = "Episode is already done."
108
+ return obs, 0.0, True, info
109
+
110
+ self.turn += 1
111
+
112
+ # Process speech actions
113
+ speech = action.get("speech")
114
+ if speech:
115
+ entry = TranscriptEntry(
116
+ turn=self.turn,
117
+ actor="agent",
118
+ action_type="speech",
119
+ content=speech,
120
+ )
121
+ self.transcript.append(entry)
122
+ # Record as a position in the argument tracker
123
+ self.argument_tracker.record_position(
124
+ turn=self.turn,
125
+ statement=speech,
126
+ topic="general",
127
+ )
128
+
129
+ # Process tool calls (structure for future tool handlers)
130
+ tool_name = action.get("tool_name")
131
+ if tool_name:
132
+ tool_args = action.get("tool_args", {})
133
+ tool_result = self._dispatch_tool(tool_name, tool_args)
134
+ info["tool_result"] = tool_result
135
+
136
+ entry = TranscriptEntry(
137
+ turn=self.turn,
138
+ actor="agent",
139
+ action_type=f"tool:{tool_name}",
140
+ content=str(tool_result),
141
+ )
142
+ self.transcript.append(entry)
143
+
144
+ # Generate faction responses to the agent's action
145
+ faction_responses = self.faction_manager.process_action(
146
+ action, self.bill, self.turn, self.transcript
147
+ )
148
+ faction_entries = self.faction_manager.get_faction_responses_as_transcript(
149
+ faction_responses, self.turn
150
+ )
151
+ self.transcript.extend(faction_entries)
152
+ info["faction_responses"] = [
153
+ {"faction_id": r.faction_id, "message": r.message, "trust_delta": r.trust_delta}
154
+ for r in faction_responses
155
+ if r.message
156
+ ]
157
+
158
+ # Check terminal conditions
159
+ if self.bill.status in ("passed", "failed", "tabled"):
160
+ self.done = True
161
+ elif self.turn >= self.max_turns:
162
+ self.done = True
163
+
164
+ # Compute reward at episode end using the full rubric
165
+ reward = 0.0
166
+ if self.done:
167
+ vote_result = self.vote_engine.calculate_votes(
168
+ self.factions, self.bill, rng=self.rng
169
+ )
170
+ env_state = {
171
+ "bill": self.bill,
172
+ "vote_result": vote_result,
173
+ "tracker": self.argument_tracker,
174
+ "factions": self.factions,
175
+ }
176
+ breakdown = self.reward_rubric.compute(env_state)
177
+ reward = breakdown.total
178
+ info["reward_breakdown"] = {
179
+ "bill_passage": breakdown.bill_passage,
180
+ "coalition_size": breakdown.coalition_size,
181
+ "argument_consistency": breakdown.argument_consistency,
182
+ "amendment_quality": breakdown.amendment_quality,
183
+ "total": breakdown.total,
184
+ }
185
+
186
+ obs = self._build_observation()
187
+ return obs, reward, self.done, info
188
+
189
+ def state(self, **kwargs) -> Observation:
190
+ """Return the current observation without advancing the simulation."""
191
+ return self._build_observation()
192
+
193
+ def _dispatch_tool(self, tool_name: str, tool_args: dict) -> dict:
194
+ """Dispatch a tool call to the appropriate handler.
195
+
196
+ Tool handlers will be implemented in later tasks. For now, this
197
+ provides the dispatch structure and returns a placeholder result
198
+ for unknown tools.
199
+ """
200
+ if tool_name == "negotiate":
201
+ return self._handle_negotiate(tool_args)
202
+ elif tool_name == "propose_amendment":
203
+ return self._handle_propose_amendment(tool_args)
204
+ elif tool_name == "check_vote_tally":
205
+ return self._handle_check_vote_tally(tool_args)
206
+ elif tool_name == "read_transcript":
207
+ return self._handle_read_transcript(tool_args)
208
+ elif tool_name == "search_precedent":
209
+ return self._handle_search_precedent(tool_args)
210
+ else:
211
+ return {"error": "unknown_tool"}
212
+
213
+ def _handle_negotiate(self, args: dict) -> dict:
214
+ """Handle the negotiate tool call."""
215
+ faction_id = args.get("faction_id")
216
+ offer = args.get("offer", {})
217
+
218
+ faction = self._find_faction(faction_id)
219
+ if faction is None:
220
+ return {"error": "unknown_faction"}
221
+
222
+ score = faction.evaluate_offer(offer)
223
+ # Adjust trust based on offer quality
224
+ trust_delta = (score - 0.5) * 0.1
225
+ faction.trust_score = max(0.0, min(1.0, faction.trust_score + trust_delta))
226
+
227
+ # Record as a promise if offer contains commitments
228
+ if offer.get("priorities_addressed"):
229
+ self.argument_tracker.record_promise(
230
+ turn=self.turn,
231
+ target_faction=faction_id,
232
+ content=str(offer),
233
+ )
234
+
235
+ return {"score": score, "trust_score": faction.trust_score}
236
+
237
+ def _handle_propose_amendment(self, args: dict) -> dict:
238
+ """Handle the propose_amendment tool call."""
239
+ clause_index = args.get("clause_index", 0)
240
+ new_text = args.get("new_text", "")
241
+
242
+ try:
243
+ amendment = self.bill_sm.apply_amendment(
244
+ clause_index=clause_index,
245
+ new_text=new_text,
246
+ proposed_by="agent",
247
+ turn=self.turn,
248
+ )
249
+ return {
250
+ "success": True,
251
+ "amendment": {
252
+ "clause_index": amendment.clause_index,
253
+ "original_text": amendment.original_text,
254
+ "new_text": amendment.new_text,
255
+ "proposed_by": amendment.proposed_by,
256
+ "turn_proposed": amendment.turn_proposed,
257
+ },
258
+ }
259
+ except IndexError:
260
+ return {"success": False, "error": "invalid_clause_index"}
261
+
262
+ def _handle_check_vote_tally(self, args: dict) -> dict:
263
+ """Handle the check_vote_tally tool call."""
264
+ vote_result = self.vote_engine.calculate_votes(
265
+ self.factions, self.bill, rng=self.rng
266
+ )
267
+ projections = {
268
+ fid: fv.final_probability
269
+ for fid, fv in vote_result.faction_votes.items()
270
+ }
271
+ return {
272
+ "projections": projections,
273
+ "threshold": vote_result.threshold,
274
+ }
275
+
276
+ def _handle_read_transcript(self, args: dict) -> dict:
277
+ """Handle the read_transcript tool call."""
278
+ start_turn = args.get("start_turn", 0)
279
+ end_turn = args.get("end_turn", self.turn)
280
+
281
+ # Clamp to valid bounds
282
+ start_turn = max(0, start_turn)
283
+ end_turn = max(start_turn, end_turn)
284
+
285
+ entries = [
286
+ {
287
+ "turn": e.turn,
288
+ "actor": e.actor,
289
+ "action_type": e.action_type,
290
+ "content": e.content,
291
+ }
292
+ for e in self.transcript
293
+ if start_turn <= e.turn <= end_turn
294
+ ]
295
+ return {"entries": entries}
296
+
297
+ def _handle_search_precedent(self, args: dict) -> dict:
298
+ """Handle the search_precedent tool call (placeholder)."""
299
+ topic = args.get("topic", "")
300
+ # Placeholder — real implementation in tools tasks
301
+ return {"precedents": [f"Historical precedent related to: {topic}"]}
302
+
303
+ def _find_faction(self, faction_id: str) -> Faction | None:
304
+ """Find a faction by its ID."""
305
+ for faction in self.factions:
306
+ if faction.faction_id == faction_id:
307
+ return faction
308
+ return None
309
+
310
+ def _build_observation(self) -> Observation:
311
+ """Build the current observation from environment state.
312
+
313
+ Constructs the observation with:
314
+ - Bill summary from BillStateMachine
315
+ - Contested clauses
316
+ - Public-only faction stances (no hidden_priorities)
317
+ - Noisy vote projections
318
+ - Last 3 transcript entries
319
+ - Deals on record from coalition agreements
320
+ - Pending amendments
321
+ """
322
+ bill_summary = self.bill_sm.to_summary()
323
+ contested_clauses = self.bill_sm.get_contested_clauses(self.factions)
324
+
325
+ # Build public faction stances — NO hidden_priorities
326
+ public_faction_stances: dict[str, FactionStance] = {}
327
+ for faction in self.factions:
328
+ # Determine current position based on offer evaluation
329
+ score = faction.evaluate_offer(
330
+ {"priorities_addressed": self.bill.clauses, "concessions": {}}
331
+ )
332
+ if score >= faction.vote_threshold:
333
+ position = "support"
334
+ elif score >= faction.vote_threshold * 0.5:
335
+ position = "undecided"
336
+ else:
337
+ position = "oppose"
338
+
339
+ public_faction_stances[faction.faction_id] = FactionStance(
340
+ faction_id=faction.faction_id,
341
+ name=faction.name,
342
+ public_priorities=list(faction.public_priorities),
343
+ trust_score=faction.trust_score,
344
+ current_position=position,
345
+ )
346
+
347
+ # Noisy vote projections
348
+ vote_projection: dict[str, float] = {}
349
+ vote_result = self.vote_engine.calculate_votes(
350
+ self.factions, self.bill, rng=self.rng
351
+ )
352
+ for fid, fv in vote_result.faction_votes.items():
353
+ vote_projection[fid] = fv.final_probability
354
+
355
+ # Last 3 transcript entries
356
+ transcript_last_3 = self.transcript[-3:] if self.transcript else []
357
+
358
+ # Deals on record from coalition agreements
359
+ deals_on_record: list[Deal] = []
360
+ if self.argument_tracker:
361
+ for ca in self.argument_tracker.coalition_agreements:
362
+ deals_on_record.append(
363
+ Deal(
364
+ turn=ca.turn,
365
+ factions=list(ca.factions),
366
+ terms=ca.terms,
367
+ status="active",
368
+ )
369
+ )
370
+
371
+ # Pending amendments (amendments not yet voted on)
372
+ amendments_pending = list(self.bill.amendments)
373
+
374
+ return Observation(
375
+ turn=self.turn,
376
+ current_reading=self.bill.reading,
377
+ bill_summary=bill_summary,
378
+ contested_clauses=contested_clauses,
379
+ public_faction_stances=public_faction_stances,
380
+ vote_projection=vote_projection,
381
+ transcript_last_3_turns=transcript_last_3,
382
+ deals_on_record=deals_on_record,
383
+ amendments_pending=amendments_pending,
384
+ )
debatemind/debatemind/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """DebateMind data models."""
debatemind/debatemind/models/api.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pydantic API request/response models for the DebateMind MCP server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+ # --- Environment endpoint models ---
9
+
10
+
11
+ class ResetConfig(BaseModel):
12
+ bill_title: str | None = None
13
+ bill_clauses: list[str] | None = None
14
+
15
+
16
+ class ActionRequest(BaseModel):
17
+ tool_name: str | None = None # if agent calls a tool
18
+ tool_args: dict | None = None
19
+ speech: str | None = None # agent's public statement
20
+
21
+
22
+ class ObservationResponse(BaseModel):
23
+ turn: int
24
+ current_reading: int
25
+ bill_summary: dict
26
+ contested_clauses: list[int]
27
+ public_faction_stances: dict[str, dict]
28
+ vote_projection: dict[str, float]
29
+ transcript_last_3_turns: list[dict]
30
+ deals_on_record: list[dict]
31
+ amendments_pending: list[dict]
32
+
33
+
34
+ class StepResponse(BaseModel):
35
+ observation: ObservationResponse
36
+ reward: float
37
+ done: bool
38
+ info: dict = Field(default_factory=dict)
39
+
40
+
41
+ # --- Tool-specific request/response models ---
42
+
43
+
44
+ class SearchPrecedentRequest(BaseModel):
45
+ topic: str
46
+
47
+
48
+ class SearchPrecedentResponse(BaseModel):
49
+ precedents: list[str]
50
+
51
+
52
+ class ProposeAmendmentRequest(BaseModel):
53
+ clause_index: int
54
+ new_text: str
55
+
56
+
57
+ class ProposeAmendmentResponse(BaseModel):
58
+ success: bool
59
+ amendment: dict = Field(default_factory=dict)
60
+ error: str | None = None
61
+
62
+
63
+ class NegotiateRequest(BaseModel):
64
+ faction_id: str
65
+ offer: dict
66
+
67
+
68
+ class NegotiateResponse(BaseModel):
69
+ score: float
70
+ trust_score: float
71
+ error: str | None = None
72
+
73
+
74
+ class ReadTranscriptRequest(BaseModel):
75
+ start_turn: int
76
+ end_turn: int
77
+
78
+
79
+ class ReadTranscriptResponse(BaseModel):
80
+ entries: list[dict]
81
+
82
+
83
+ class CheckVoteTallyResponse(BaseModel):
84
+ projections: dict[str, float]
85
+ threshold: float
debatemind/debatemind/models/bill.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bill and BillStateMachine models for DebateMind parliamentary simulation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from debatemind.models.faction import Faction
8
+
9
+
10
+ @dataclass
11
+ class Amendment:
12
+ """A modification to a bill clause."""
13
+
14
+ clause_index: int
15
+ original_text: str
16
+ new_text: str
17
+ proposed_by: str # faction_id or "agent"
18
+ turn_proposed: int
19
+
20
+
21
+ @dataclass
22
+ class Bill:
23
+ """A legislative proposal managed by the BillStateMachine."""
24
+
25
+ title: str
26
+ clauses: list[str]
27
+ amendments: list[Amendment] = field(default_factory=list)
28
+ reading: int = 0 # 0=draft, 1-3=reading stages
29
+ status: str = "active" # "active", "passed", "failed", "tabled"
30
+
31
+
32
+ class BillStateMachine:
33
+ """State machine governing bill lifecycle transitions.
34
+
35
+ Transitions:
36
+ Draft (reading=0) -> Reading1: advance (auto on first step)
37
+ Reading1 -> Reading2: vote passes (>50%)
38
+ Reading1 -> Failed: vote fails
39
+ Reading2 -> Reading3: vote passes (>=60%)
40
+ Reading2 -> Failed: vote fails
41
+ Reading3 -> Passed: vote passes (>=66%)
42
+ Reading3 -> Failed: vote fails
43
+ Any active state -> Tabled: table_bill()
44
+ Tabled/Failed/Passed are terminal states.
45
+ """
46
+
47
+ def __init__(self, bill: Bill) -> None:
48
+ self.bill = bill
49
+
50
+ def advance_reading(self, vote_passed: bool) -> bool:
51
+ """Advance the bill to the next reading stage.
52
+
53
+ If bill status is not "active", return False (no-op).
54
+ If vote_passed is True: increment reading by 1. If reading reaches 3
55
+ and vote passes, set status to "passed" (reading stays at 3).
56
+ If vote_passed is False: set status to "failed".
57
+ Returns True if a transition happened.
58
+ """
59
+ if self.bill.status != "active":
60
+ return False
61
+
62
+ if vote_passed:
63
+ if self.bill.reading < 3:
64
+ self.bill.reading += 1
65
+ else:
66
+ # Reading 3 vote passed -> bill is passed
67
+ self.bill.status = "passed"
68
+ else:
69
+ self.bill.status = "failed"
70
+
71
+ return True
72
+
73
+ def table_bill(self) -> None:
74
+ """Set the bill status to 'tabled', halting further progression."""
75
+ if self.bill.status == "active":
76
+ self.bill.status = "tabled"
77
+
78
+ def apply_amendment(
79
+ self,
80
+ clause_index: int,
81
+ new_text: str,
82
+ proposed_by: str,
83
+ turn: int,
84
+ ) -> Amendment:
85
+ """Modify a clause and record the amendment.
86
+
87
+ Args:
88
+ clause_index: Index of the clause to modify.
89
+ new_text: Replacement text for the clause.
90
+ proposed_by: faction_id or "agent".
91
+ turn: Turn number when the amendment was proposed.
92
+
93
+ Returns:
94
+ The recorded Amendment.
95
+
96
+ Raises:
97
+ IndexError: If clause_index is out of range.
98
+ """
99
+ original_text = self.bill.clauses[clause_index]
100
+ self.bill.clauses[clause_index] = new_text
101
+ amendment = Amendment(
102
+ clause_index=clause_index,
103
+ original_text=original_text,
104
+ new_text=new_text,
105
+ proposed_by=proposed_by,
106
+ turn_proposed=turn,
107
+ )
108
+ self.bill.amendments.append(amendment)
109
+ return amendment
110
+
111
+ def get_contested_clauses(self, factions: list[Faction]) -> list[int]:
112
+ """Return clause indices where at least 2 factions oppose each other.
113
+
114
+ A clause is contested if at least one faction's public priorities
115
+ suggest support and at least one other faction's priorities suggest
116
+ opposition. We determine this by checking keyword overlap between
117
+ clause text and each faction's public priorities.
118
+ """
119
+ contested: list[int] = []
120
+
121
+ for i, clause in enumerate(self.bill.clauses):
122
+ clause_lower = clause.lower()
123
+ supporters: list[str] = []
124
+ opposers: list[str] = []
125
+
126
+ for faction in factions:
127
+ has_alignment = any(
128
+ p.lower() in clause_lower or clause_lower in p.lower()
129
+ for p in faction.public_priorities
130
+ )
131
+ if has_alignment:
132
+ supporters.append(faction.faction_id)
133
+ else:
134
+ opposers.append(faction.faction_id)
135
+
136
+ if len(supporters) >= 1 and len(opposers) >= 1 and (len(supporters) + len(opposers)) >= 2:
137
+ contested.append(i)
138
+
139
+ return contested
140
+
141
+ def to_summary(self) -> dict:
142
+ """Serialize the bill to a dictionary summary."""
143
+ return {
144
+ "title": self.bill.title,
145
+ "clauses": list(self.bill.clauses),
146
+ "amendments": [
147
+ {
148
+ "clause_index": a.clause_index,
149
+ "original_text": a.original_text,
150
+ "new_text": a.new_text,
151
+ "proposed_by": a.proposed_by,
152
+ "turn_proposed": a.turn_proposed,
153
+ }
154
+ for a in self.bill.amendments
155
+ ],
156
+ "reading": self.bill.reading,
157
+ "status": self.bill.status,
158
+ }
159
+
160
+ @staticmethod
161
+ def from_summary(summary: dict) -> Bill:
162
+ """Deserialize a dictionary summary back into a Bill."""
163
+ amendments = [
164
+ Amendment(
165
+ clause_index=a["clause_index"],
166
+ original_text=a["original_text"],
167
+ new_text=a["new_text"],
168
+ proposed_by=a["proposed_by"],
169
+ turn_proposed=a["turn_proposed"],
170
+ )
171
+ for a in summary.get("amendments", [])
172
+ ]
173
+ return Bill(
174
+ title=summary["title"],
175
+ clauses=list(summary["clauses"]),
176
+ amendments=amendments,
177
+ reading=summary["reading"],
178
+ status=summary["status"],
179
+ )
180
+
181
+
182
+ DEFAULT_BILL = Bill(
183
+ title="Climate Resilience Act",
184
+ clauses=[
185
+ "Mandate 50% reduction in industrial carbon emissions by 2035",
186
+ "Establish a national green infrastructure fund of $10B annually",
187
+ "Require all new buildings to meet net-zero energy standards by 2030",
188
+ "Create carbon credit trading market with government oversight",
189
+ "Provide transition subsidies for fossil fuel workers",
190
+ ],
191
+ amendments=[],
192
+ reading=0,
193
+ status="active",
194
+ )
debatemind/debatemind/models/faction.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Faction data model for DebateMind parliamentary simulation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass
9
+ class Faction:
10
+ """A political faction in the parliament.
11
+
12
+ Each faction has public priorities (visible to the agent) and hidden
13
+ priorities (never included in observations). The evaluate_offer method
14
+ scores an offer based on both priority sets.
15
+ """
16
+
17
+ name: str
18
+ faction_id: str
19
+ public_priorities: list[str]
20
+ hidden_priorities: list[str]
21
+ trust_score: float # [0.0, 1.0], starts at 0.5
22
+ vote_threshold: float # minimum attractiveness to vote yes
23
+ seat_count: int
24
+
25
+ def evaluate_offer(self, offer: dict) -> float:
26
+ """Evaluate an offer based on public + hidden priorities.
27
+
28
+ The offer dict may contain:
29
+ - "priorities_addressed": list[str] — priority keywords addressed
30
+ - "concessions": dict — concessions made (keys are priority keywords)
31
+
32
+ Returns an attractiveness score in [0.0, 1.0].
33
+ """
34
+ all_priorities = self.public_priorities + self.hidden_priorities
35
+ if not all_priorities:
36
+ return 0.0
37
+
38
+ addressed = offer.get("priorities_addressed", [])
39
+ concessions = offer.get("concessions", {})
40
+
41
+ matched = 0
42
+ for priority in all_priorities:
43
+ priority_lower = priority.lower()
44
+ # Check if priority is directly addressed
45
+ if any(priority_lower in a.lower() for a in addressed):
46
+ matched += 1
47
+ # Check if priority appears in concession keys
48
+ elif any(priority_lower in k.lower() for k in concessions):
49
+ matched += 0.5
50
+
51
+ score = matched / len(all_priorities)
52
+ return max(0.0, min(1.0, score))
53
+
54
+
55
+ def get_default_factions() -> list[Faction]:
56
+ """Return the five canonical factions with initial trust_score=0.5."""
57
+ return [
58
+ Faction(
59
+ name="Ironveil Conservatives",
60
+ faction_id="fiscal_conservative",
61
+ public_priorities=["fiscal restraint", "market freedom", "tradition"],
62
+ hidden_priorities=["donor interests", "deregulation"],
63
+ trust_score=0.5,
64
+ vote_threshold=0.6,
65
+ seat_count=25,
66
+ ),
67
+ Faction(
68
+ name="Verdant Alliance",
69
+ faction_id="green",
70
+ public_priorities=["climate action", "sustainability", "regulation"],
71
+ hidden_priorities=["green subsidies", "anti-nuclear"],
72
+ trust_score=0.5,
73
+ vote_threshold=0.5,
74
+ seat_count=20,
75
+ ),
76
+ Faction(
77
+ name="Unity Front",
78
+ faction_id="centrist",
79
+ public_priorities=["compromise", "stability", "incremental reform"],
80
+ hidden_priorities=["political survival", "media approval"],
81
+ trust_score=0.5,
82
+ vote_threshold=0.45,
83
+ seat_count=20,
84
+ ),
85
+ Faction(
86
+ name="New Horizon",
87
+ faction_id="progressive",
88
+ public_priorities=["social equity", "innovation", "public investment"],
89
+ hidden_priorities=["wealth redistribution", "union support"],
90
+ trust_score=0.5,
91
+ vote_threshold=0.5,
92
+ seat_count=18,
93
+ ),
94
+ Faction(
95
+ name="Sovereign Guard",
96
+ faction_id="nationalist",
97
+ public_priorities=["sovereignty", "domestic industry", "border control"],
98
+ hidden_priorities=["military spending", "trade protectionism"],
99
+ trust_score=0.5,
100
+ vote_threshold=0.55,
101
+ seat_count=17,
102
+ ),
103
+ ]
104
+
105
+
106
+ DEFAULT_FACTIONS = get_default_factions()
debatemind/debatemind/models/observation.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Observation and related data models for DebateMind parliamentary simulation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from debatemind.models.bill import Amendment
8
+
9
+
10
+ @dataclass
11
+ class FactionStance:
12
+ """Public-facing faction stance included in observations.
13
+
14
+ This deliberately excludes hidden_priorities — only public information
15
+ is exposed to the agent.
16
+ """
17
+
18
+ faction_id: str
19
+ name: str
20
+ public_priorities: list[str]
21
+ trust_score: float
22
+ current_position: str # "support", "oppose", "undecided"
23
+
24
+
25
+ @dataclass
26
+ class TranscriptEntry:
27
+ """A single entry in the parliamentary transcript."""
28
+
29
+ turn: int
30
+ actor: str # "agent" or faction_id
31
+ action_type: str
32
+ content: str
33
+
34
+
35
+ @dataclass
36
+ class Deal:
37
+ """A recorded deal between factions."""
38
+
39
+ turn: int
40
+ factions: list[str]
41
+ terms: str
42
+ status: str # "active", "fulfilled", "broken"
43
+
44
+
45
+ @dataclass
46
+ class Observation:
47
+ """The structured state returned to the agent each turn.
48
+
49
+ Information constraints:
50
+ - hidden_priorities never appear (FactionStance has no such field)
51
+ - transcript_last_3_turns contains at most 3 entries
52
+ - vote_projection values include stochastic noise
53
+ """
54
+
55
+ turn: int
56
+ current_reading: int
57
+ bill_summary: dict
58
+ contested_clauses: list[int]
59
+ public_faction_stances: dict[str, FactionStance]
60
+ vote_projection: dict[str, float]
61
+ transcript_last_3_turns: list[TranscriptEntry]
62
+ deals_on_record: list[Deal]
63
+ amendments_pending: list[Amendment]
debatemind/debatemind/openenv_stub.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stub module for OpenEnv's MCPEnvironment base class.
2
+
3
+ Since the `openenv` package may not be available, this provides a minimal
4
+ abstract base class that ParliamentEnvironment will inherit from.
5
+ """
6
+
7
+ from abc import ABC, abstractmethod
8
+ from typing import Any
9
+
10
+
11
+ class MCPEnvironment(ABC):
12
+ """Abstract base class for OpenEnv-compliant MCP environments."""
13
+
14
+ @abstractmethod
15
+ def reset(self, **kwargs: Any) -> Any:
16
+ """Initialize a new episode and return the initial observation."""
17
+ ...
18
+
19
+ @abstractmethod
20
+ def step(self, action: Any) -> tuple[Any, float, bool, dict]:
21
+ """Advance the environment by one step.
22
+
23
+ Returns:
24
+ A tuple of (observation, reward, done, info).
25
+ """
26
+ ...
27
+
28
+ @abstractmethod
29
+ def state(self) -> Any:
30
+ """Return the current observation without advancing the environment."""
31
+ ...
debatemind/debatemind/server.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI MCP Server for DebateMind parliamentary simulation.
2
+
3
+ Exposes Gymnasium-style environment endpoints (reset, step, state) and
4
+ five MCP tool endpoints over HTTP.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import asdict
10
+
11
+ from fastapi import FastAPI, HTTPException
12
+ from fastapi.middleware.cors import CORSMiddleware
13
+
14
+ from debatemind.environment import ParliamentEnvironment
15
+ from debatemind.models.api import (
16
+ ActionRequest,
17
+ CheckVoteTallyResponse,
18
+ NegotiateRequest,
19
+ NegotiateResponse,
20
+ ObservationResponse,
21
+ ProposeAmendmentRequest,
22
+ ProposeAmendmentResponse,
23
+ ReadTranscriptRequest,
24
+ ReadTranscriptResponse,
25
+ ResetConfig,
26
+ SearchPrecedentRequest,
27
+ SearchPrecedentResponse,
28
+ StepResponse,
29
+ )
30
+ from debatemind.models.observation import Observation
31
+ from debatemind.tools.check_vote_tally import check_vote_tally as _check_vote_tally
32
+ from debatemind.tools.negotiate import negotiate as _negotiate
33
+ from debatemind.tools.propose_amendment import propose_amendment as _propose_amendment
34
+ from debatemind.tools.read_transcript import read_transcript as _read_transcript
35
+ from debatemind.tools.search_precedent import search_precedent as _search_precedent
36
+
37
+ app = FastAPI(title="DebateMind MCP Server")
38
+ app.add_middleware(
39
+ CORSMiddleware,
40
+ allow_origins=["*"],
41
+ allow_credentials=True,
42
+ allow_methods=["*"],
43
+ allow_headers=["*"],
44
+ )
45
+
46
+ # Global environment instance
47
+ _env: ParliamentEnvironment | None = None
48
+
49
+
50
+ def _get_env() -> ParliamentEnvironment:
51
+ """Return the global environment, raising 400 if not initialized."""
52
+ if _env is None:
53
+ raise HTTPException(
54
+ status_code=400,
55
+ detail="Environment not initialized. Call /reset first.",
56
+ )
57
+ return _env
58
+
59
+
60
+ def _observation_to_response(obs: Observation) -> ObservationResponse:
61
+ """Convert an Observation dataclass to an ObservationResponse Pydantic model."""
62
+ public_faction_stances = {
63
+ fid: {
64
+ "faction_id": stance.faction_id,
65
+ "name": stance.name,
66
+ "public_priorities": stance.public_priorities,
67
+ "trust_score": stance.trust_score,
68
+ "current_position": stance.current_position,
69
+ }
70
+ for fid, stance in obs.public_faction_stances.items()
71
+ }
72
+
73
+ transcript_last_3 = [
74
+ {
75
+ "turn": entry.turn,
76
+ "actor": entry.actor,
77
+ "action_type": entry.action_type,
78
+ "content": entry.content,
79
+ }
80
+ for entry in obs.transcript_last_3_turns
81
+ ]
82
+
83
+ deals = [
84
+ {
85
+ "turn": deal.turn,
86
+ "factions": deal.factions,
87
+ "terms": deal.terms,
88
+ "status": deal.status,
89
+ }
90
+ for deal in obs.deals_on_record
91
+ ]
92
+
93
+ amendments = [
94
+ {
95
+ "clause_index": a.clause_index,
96
+ "original_text": a.original_text,
97
+ "new_text": a.new_text,
98
+ "proposed_by": a.proposed_by,
99
+ "turn_proposed": a.turn_proposed,
100
+ }
101
+ for a in obs.amendments_pending
102
+ ]
103
+
104
+ return ObservationResponse(
105
+ turn=obs.turn,
106
+ current_reading=obs.current_reading,
107
+ bill_summary=obs.bill_summary,
108
+ contested_clauses=obs.contested_clauses,
109
+ public_faction_stances=public_faction_stances,
110
+ vote_projection=obs.vote_projection,
111
+ transcript_last_3_turns=transcript_last_3,
112
+ deals_on_record=deals,
113
+ amendments_pending=amendments,
114
+ )
115
+
116
+
117
+ # --- Environment endpoints ---
118
+
119
+
120
+ @app.post("/reset")
121
+ async def reset_env(config: ResetConfig | None = None) -> ObservationResponse:
122
+ """Initialize a new parliamentary session."""
123
+ global _env
124
+ _env = ParliamentEnvironment()
125
+
126
+ bill_config = None
127
+ if config is not None and (config.bill_title or config.bill_clauses):
128
+ bill_config = {}
129
+ if config.bill_title:
130
+ bill_config["title"] = config.bill_title
131
+ if config.bill_clauses:
132
+ bill_config["clauses"] = config.bill_clauses
133
+
134
+ obs = _env.reset(bill_config=bill_config)
135
+ return _observation_to_response(obs)
136
+
137
+
138
+ @app.post("/step")
139
+ async def step_env(action: ActionRequest) -> StepResponse:
140
+ """Advance the simulation by one turn."""
141
+ env = _get_env()
142
+ action_dict = {}
143
+ if action.tool_name is not None:
144
+ action_dict["tool_name"] = action.tool_name
145
+ if action.tool_args is not None:
146
+ action_dict["tool_args"] = action.tool_args
147
+ if action.speech is not None:
148
+ action_dict["speech"] = action.speech
149
+
150
+ obs, reward, done, info = env.step(action_dict)
151
+ return StepResponse(
152
+ observation=_observation_to_response(obs),
153
+ reward=reward,
154
+ done=done,
155
+ info=info,
156
+ )
157
+
158
+
159
+ @app.get("/state")
160
+ async def get_state() -> ObservationResponse:
161
+ """Return the current observation without advancing."""
162
+ env = _get_env()
163
+ obs = env.state()
164
+ return _observation_to_response(obs)
165
+
166
+
167
+ @app.get("/health")
168
+ async def health() -> dict:
169
+ """Return health status."""
170
+ return {"status": "ok"}
171
+
172
+
173
+ # --- Tool endpoints ---
174
+
175
+
176
+ @app.post("/tools/search_precedent")
177
+ async def search_precedent(req: SearchPrecedentRequest) -> SearchPrecedentResponse:
178
+ """Search historical parliamentary precedents."""
179
+ result = _search_precedent(req.topic)
180
+ return SearchPrecedentResponse(precedents=result["precedents"])
181
+
182
+
183
+ @app.post("/tools/propose_amendment")
184
+ async def propose_amendment(req: ProposeAmendmentRequest) -> ProposeAmendmentResponse:
185
+ """Propose an amendment to a bill clause."""
186
+ env = _get_env()
187
+ result = _propose_amendment(
188
+ clause_index=req.clause_index,
189
+ new_text=req.new_text,
190
+ bill_sm=env.bill_sm,
191
+ turn=env.turn,
192
+ )
193
+ return ProposeAmendmentResponse(
194
+ success=result["success"],
195
+ amendment=result.get("amendment", {}),
196
+ error=result.get("error"),
197
+ )
198
+
199
+
200
+ @app.post("/tools/negotiate")
201
+ async def negotiate(req: NegotiateRequest) -> NegotiateResponse:
202
+ """Negotiate with a faction."""
203
+ env = _get_env()
204
+ result = _negotiate(
205
+ faction_id=req.faction_id,
206
+ offer=req.offer,
207
+ factions=env.factions,
208
+ )
209
+ if "error" in result:
210
+ return NegotiateResponse(
211
+ score=0.0,
212
+ trust_score=0.0,
213
+ error=result["error"],
214
+ )
215
+ return NegotiateResponse(
216
+ score=result["score"],
217
+ trust_score=result["trust_score"],
218
+ )
219
+
220
+
221
+ @app.post("/tools/read_transcript")
222
+ async def read_transcript(req: ReadTranscriptRequest) -> ReadTranscriptResponse:
223
+ """Read transcript entries for a turn range."""
224
+ env = _get_env()
225
+ result = _read_transcript(
226
+ start_turn=req.start_turn,
227
+ end_turn=req.end_turn,
228
+ transcript=env.transcript,
229
+ )
230
+ return ReadTranscriptResponse(entries=result["entries"])
231
+
232
+
233
+ @app.post("/tools/check_vote_tally")
234
+ async def check_vote_tally() -> CheckVoteTallyResponse:
235
+ """Check current projected vote counts with noise."""
236
+ env = _get_env()
237
+ result = _check_vote_tally(
238
+ factions=env.factions,
239
+ bill=env.bill,
240
+ vote_engine=env.vote_engine,
241
+ rng=env.rng,
242
+ )
243
+ return CheckVoteTallyResponse(
244
+ projections=result["projections"],
245
+ threshold=result["threshold"],
246
+ )
debatemind/debatemind/tools/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DebateMind MCP tools.
2
+
3
+ Exports the five MCP tool functions. None of these use the reserved
4
+ names: reset, step, state, or close.
5
+ """
6
+
7
+ from debatemind.tools.check_vote_tally import check_vote_tally
8
+ from debatemind.tools.negotiate import negotiate
9
+ from debatemind.tools.propose_amendment import propose_amendment
10
+ from debatemind.tools.read_transcript import read_transcript
11
+ from debatemind.tools.search_precedent import search_precedent
12
+
13
+ TOOL_NAMES = [
14
+ "search_precedent",
15
+ "propose_amendment",
16
+ "negotiate",
17
+ "read_transcript",
18
+ "check_vote_tally",
19
+ ]
20
+
21
+ _RESERVED_NAMES = {"reset", "step", "state", "close"}
22
+
23
+ # Verify at import time that no tool uses a reserved name
24
+ for _name in TOOL_NAMES:
25
+ assert _name not in _RESERVED_NAMES, f"Tool name '{_name}' is reserved"
26
+
27
+ __all__ = [
28
+ "search_precedent",
29
+ "propose_amendment",
30
+ "negotiate",
31
+ "read_transcript",
32
+ "check_vote_tally",
33
+ "TOOL_NAMES",
34
+ ]
debatemind/debatemind/tools/check_vote_tally.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MCP tool: check_vote_tally -- return projected vote counts with noise."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import random
6
+
7
+ from debatemind.engine.vote_engine import VoteEngine
8
+ from debatemind.models.bill import Bill
9
+ from debatemind.models.faction import Faction
10
+
11
+
12
+ def check_vote_tally(
13
+ factions: list[Faction],
14
+ bill: Bill,
15
+ vote_engine: VoteEngine,
16
+ rng: random.Random,
17
+ ) -> dict:
18
+ """Return projected vote counts per faction with stochastic noise.
19
+
20
+ Args:
21
+ factions: All factions in the parliament.
22
+ bill: The current bill being debated.
23
+ vote_engine: VoteEngine instance for computing votes.
24
+ rng: Random number generator for reproducible noise.
25
+
26
+ Returns:
27
+ A dict with "projections" (faction_id -> probability) and
28
+ "threshold" (float) keys.
29
+ """
30
+ vote_result = vote_engine.calculate_votes(factions, bill, rng=rng)
31
+ projections = {
32
+ fid: fv.final_probability
33
+ for fid, fv in vote_result.faction_votes.items()
34
+ }
35
+ return {
36
+ "projections": projections,
37
+ "threshold": vote_result.threshold,
38
+ }
debatemind/debatemind/tools/negotiate.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MCP tool: negotiate -- negotiate with a faction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from debatemind.models.faction import Faction
6
+
7
+
8
+ def negotiate(
9
+ faction_id: str,
10
+ offer: dict,
11
+ factions: list[Faction],
12
+ ) -> dict:
13
+ """Negotiate with a faction by presenting an offer.
14
+
15
+ Invokes the target faction's evaluate_offer method and adjusts
16
+ trust based on the offer quality.
17
+
18
+ Args:
19
+ faction_id: ID of the faction to negotiate with.
20
+ offer: Offer dict passed to faction.evaluate_offer.
21
+ factions: List of all factions in the parliament.
22
+
23
+ Returns:
24
+ A dict with "score" and "trust_score" keys on success,
25
+ or an "error" key if the faction_id is unknown.
26
+ """
27
+ faction = _find_faction(faction_id, factions)
28
+ if faction is None:
29
+ return {"error": "unknown_faction"}
30
+
31
+ score = faction.evaluate_offer(offer)
32
+
33
+ # Adjust trust: positive delta for good offers, negative for poor ones
34
+ trust_delta = (score - 0.5) * 0.1
35
+ faction.trust_score = max(0.0, min(1.0, faction.trust_score + trust_delta))
36
+
37
+ return {"score": score, "trust_score": faction.trust_score}
38
+
39
+
40
+ def _find_faction(faction_id: str, factions: list[Faction]) -> Faction | None:
41
+ """Find a faction by its ID."""
42
+ for faction in factions:
43
+ if faction.faction_id == faction_id:
44
+ return faction
45
+ return None
debatemind/debatemind/tools/propose_amendment.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MCP tool: propose_amendment -- submit an amendment to the BillStateMachine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from debatemind.models.bill import BillStateMachine
6
+
7
+
8
+ def propose_amendment(
9
+ clause_index: int,
10
+ new_text: str,
11
+ bill_sm: BillStateMachine,
12
+ turn: int,
13
+ ) -> dict:
14
+ """Propose an amendment to a bill clause.
15
+
16
+ Args:
17
+ clause_index: Index of the clause to amend.
18
+ new_text: Replacement text for the clause.
19
+ bill_sm: The active BillStateMachine instance.
20
+ turn: Current turn number.
21
+
22
+ Returns:
23
+ A dict with "success" (bool) and "amendment" (dict) keys on
24
+ success, or "success" (False) and "error" on invalid index.
25
+ """
26
+ try:
27
+ amendment = bill_sm.apply_amendment(
28
+ clause_index=clause_index,
29
+ new_text=new_text,
30
+ proposed_by="agent",
31
+ turn=turn,
32
+ )
33
+ return {
34
+ "success": True,
35
+ "amendment": {
36
+ "clause_index": amendment.clause_index,
37
+ "original_text": amendment.original_text,
38
+ "new_text": amendment.new_text,
39
+ "proposed_by": amendment.proposed_by,
40
+ "turn_proposed": amendment.turn_proposed,
41
+ },
42
+ }
43
+ except IndexError:
44
+ return {"success": False, "error": "invalid_clause_index"}
debatemind/debatemind/tools/read_transcript.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MCP tool: read_transcript -- read transcript entries for a turn range."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from debatemind.models.observation import TranscriptEntry
6
+
7
+
8
+ def read_transcript(
9
+ start_turn: int,
10
+ end_turn: int,
11
+ transcript: list[TranscriptEntry],
12
+ ) -> dict:
13
+ """Return transcript entries for the specified turn range.
14
+
15
+ The range is clamped to valid bounds so out-of-range values are
16
+ handled gracefully rather than raising errors.
17
+
18
+ Args:
19
+ start_turn: First turn to include (inclusive).
20
+ end_turn: Last turn to include (inclusive).
21
+ transcript: Full list of transcript entries.
22
+
23
+ Returns:
24
+ A dict with an "entries" key containing a list of dicts,
25
+ each with turn, actor, action_type, and content fields.
26
+ """
27
+ # Clamp to valid bounds
28
+ start_turn = max(0, start_turn)
29
+ end_turn = max(start_turn, end_turn)
30
+
31
+ entries = [
32
+ {
33
+ "turn": e.turn,
34
+ "actor": e.actor,
35
+ "action_type": e.action_type,
36
+ "content": e.content,
37
+ }
38
+ for e in transcript
39
+ if start_turn <= e.turn <= end_turn
40
+ ]
41
+ return {"entries": entries}
debatemind/debatemind/tools/search_precedent.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MCP tool: search_precedent -- search historical parliamentary precedents."""
2
+
3
+ from __future__ import annotations
4
+
5
+ # Predefined precedent database keyed by topic category
6
+ _PRECEDENTS: dict[str, list[str]] = {
7
+ "climate": [
8
+ "The Clean Air Act of 1956 set precedent for cross-party environmental regulation.",
9
+ "The Kyoto Protocol ratification debate (1997) showed coalition-building across fiscal and green factions.",
10
+ "Carbon tax legislation in British Columbia (2008) demonstrated revenue-neutral climate policy.",
11
+ ],
12
+ "fiscal": [
13
+ "The Balanced Budget Act of 1997 required bipartisan negotiation on spending caps.",
14
+ "Austerity debates in the EU (2010-2015) showed tension between fiscal restraint and social investment.",
15
+ "Tax reform coalitions historically require centrist bridge-building to pass.",
16
+ ],
17
+ "social": [
18
+ "The Civil Rights Act of 1964 required cross-faction coalition despite deep ideological divides.",
19
+ "Universal healthcare debates show recurring patterns of progressive-centrist alliance formation.",
20
+ "Education reform bills historically pass when framed as investment rather than spending.",
21
+ ],
22
+ "sovereignty": [
23
+ "Brexit negotiations demonstrated the tension between sovereignty and economic cooperation.",
24
+ "Trade agreement debates often pit nationalist factions against market-freedom advocates.",
25
+ "Border policy legislation requires balancing domestic industry protection with international obligations.",
26
+ ],
27
+ "energy": [
28
+ "Nuclear energy debates historically split green and progressive factions.",
29
+ "Fossil fuel transition subsidies have precedent in coal mining community support programs.",
30
+ "Renewable energy mandates gain cross-party support when paired with job creation metrics.",
31
+ ],
32
+ "regulation": [
33
+ "Deregulation waves in the 1980s faced opposition from both green and progressive blocs.",
34
+ "Financial regulation post-2008 required unusual conservative-progressive alignment.",
35
+ "Environmental regulation enforcement precedents show graduated compliance timelines work best.",
36
+ ],
37
+ }
38
+
39
+ _DEFAULT_PRECEDENTS = [
40
+ "Parliamentary procedure allows for amendment proposals at any reading stage.",
41
+ "Coalition agreements are non-binding but carry significant political weight.",
42
+ "Precedent supports tabling a bill to allow further negotiation rather than forcing a failed vote.",
43
+ ]
44
+
45
+
46
+ def search_precedent(topic: str) -> dict:
47
+ """Search for historical parliamentary precedents related to a topic.
48
+
49
+ Args:
50
+ topic: A keyword or phrase describing the subject to search for.
51
+
52
+ Returns:
53
+ A dict with a "precedents" key containing a list of relevant
54
+ precedent strings.
55
+ """
56
+ topic_lower = topic.lower()
57
+ results: list[str] = []
58
+
59
+ for category, precedents in _PRECEDENTS.items():
60
+ if category in topic_lower or topic_lower in category:
61
+ results.extend(precedents)
62
+
63
+ # If no category matched, do a broader keyword search
64
+ if not results:
65
+ for category, precedents in _PRECEDENTS.items():
66
+ for p in precedents:
67
+ if topic_lower in p.lower():
68
+ results.append(p)
69
+
70
+ # Fall back to default precedents if nothing matched
71
+ if not results:
72
+ results = list(_DEFAULT_PRECEDENTS)
73
+
74
+ return {"precedents": results}