-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdebate_protocol_v1.py
More file actions
1319 lines (1238 loc) · 46.4 KB
/
Copy pathdebate_protocol_v1.py
File metadata and controls
1319 lines (1238 loc) · 46.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Deterministic server semantics for Debate Protocol ``debate/v1``.
This module is deliberately framework-neutral. It owns the typed envelope,
protocol micro-state, blind-commit visibility barrier, stale-read guard,
bounded rounds, judge order-swap projections, same-role binding repair and
adaptive wait policy. Transport remains in :mod:`debate` and
``hooks/debate_pump.py``.
No protocol decision is inferred from prose. ``body`` can remain useful for
humans, but every machine-relevant value is a validated column or JSON field.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import json
import re
import sqlite3
from typing import Any, Iterable, Sequence
PROTOCOL_VERSION = "debate/v1"
SEMANTIC_KINDS = (
"CLAIM",
"CHALLENGE",
"EVIDENCE",
"REBUT",
"CONCEDE",
"VERIFY",
"DISSENT",
"ESCALATE",
)
DEBATE_TURN_KINDS = (
"CLAIM",
"CHALLENGE",
"EVIDENCE",
"REBUT",
"CONCEDE",
"VERIFY",
)
TARGET_REQUIRED_KINDS = (
"CHALLENGE",
"EVIDENCE",
"REBUT",
"CONCEDE",
"VERIFY",
"DISSENT",
)
BODY_MODES = ("structured", "live_text")
PHASES = (
"BLIND_CLAIM",
"DEBATE",
"ADJUDICATE",
"STALEMATE",
"ESCALATED",
"STOPPED",
)
BLIND_BARRIER_STATES = ("not_required", "waiting", "released")
DEFAULT_MAX_ROUNDS = 3
MAX_ROUNDS_LIMIT = 10
_HUMAN_RECIPIENT_RE = re.compile(
r"^(?:HUMAN|OPERATOR|human(?:[-_].+)?|operator)$", re.IGNORECASE
)
_SESSION_SAFE_RE = re.compile(r"[^A-Za-z0-9_]+")
_RETRY_BACKOFF_SECONDS = (1.0, 2.0, 5.0, 10.0, 30.0)
class ProtocolV1Error(ValueError):
"""Typed, detail-carrying server rejection."""
def __init__(
self,
message: str,
*,
error_type: str,
details: dict[str, Any] | None = None,
) -> None:
super().__init__(message)
self.error_type = error_type
self.details = details or {}
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
def _parse_iso(value: str | None) -> datetime | None:
if not value:
return None
try:
parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except (TypeError, ValueError):
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(timezone.utc)
def _json_dict(value: Any, *, field: str) -> dict[str, Any]:
if isinstance(value, dict):
return dict(value)
if isinstance(value, str) and value.strip():
try:
parsed = json.loads(value)
except json.JSONDecodeError as exc:
raise ProtocolV1Error(
f"invalid_{field}: {exc.msg}",
error_type="INVALID_PAYLOAD",
details={"field": field},
) from exc
if isinstance(parsed, dict):
return parsed
raise ProtocolV1Error(
f"invalid_{field}: expected JSON object",
error_type="INVALID_PAYLOAD",
details={"field": field},
)
def _require_nonempty_string(payload: dict[str, Any], key: str) -> None:
if not isinstance(payload.get(key), str) or not payload[key].strip():
raise ProtocolV1Error(
f"invalid_payload: {key} must be a non-empty string",
error_type="INVALID_PAYLOAD",
details={"field": key},
)
def _require_list(payload: dict[str, Any], key: str) -> None:
if not isinstance(payload.get(key), list):
raise ProtocolV1Error(
f"invalid_payload: {key} must be an array",
error_type="INVALID_PAYLOAD",
details={"field": key},
)
_REQUIRED_STRING_FIELDS: dict[str, tuple[str, ...]] = {
"CLAIM": ("summary",),
"CHALLENGE": ("target", "challenge_type", "requested_disposition"),
"EVIDENCE": (
"target",
"source_id",
"locator",
"retrieved_at",
"content_hash",
),
"REBUT": ("target", "disposition"),
"CONCEDE": ("target", "scope", "consequence"),
"VERIFY": ("target",),
"DISSENT": ("decision_target", "unresolved_point", "strongest_evidence"),
"ESCALATE": ("decision_question", "unresolved_point", "exact_human_action"),
}
_REQUIRED_LIST_FIELDS: dict[str, tuple[str, ...]] = {
"CLAIM": ("assumptions", "evidence_refs"),
"REBUT": ("evidence_refs",),
"VERIFY": ("checks",),
"ESCALATE": ("options", "decisive_evidence", "consequence_by_option"),
}
_ENUM_FIELDS: dict[str, tuple[str, frozenset[str], str]] = {
"EVIDENCE": (
"verification_status",
frozenset({"verified", "contested", "unsupported", "unknown"}),
"verification_status",
),
"VERIFY": (
"result",
frozenset({"verified", "contested", "unsupported", "unknown"}),
"VERIFY.result",
),
}
def normalize_payload(kind: str, payload: Any) -> dict[str, Any]:
"""Validate a kind-specific machine payload and return a clean copy."""
if kind not in SEMANTIC_KINDS:
return {}
value = _json_dict(payload, field="payload_json")
for key in _REQUIRED_STRING_FIELDS.get(kind, ()):
_require_nonempty_string(value, key)
for key in _REQUIRED_LIST_FIELDS.get(kind, ()):
_require_list(value, key)
enum_contract = _ENUM_FIELDS.get(kind)
if enum_contract is not None:
key, allowed, label = enum_contract
if value.get(key) not in allowed:
raise ProtocolV1Error(
f"invalid_payload: {label} is not canonical",
error_type="INVALID_PAYLOAD",
details={"field": key},
)
return value
def get_protocol_state(
conn: sqlite3.Connection, topic_id: str
) -> dict[str, Any] | None:
row = conn.execute(
"SELECT * FROM debate_protocol_state WHERE topic_id = ?", (topic_id,)
).fetchone()
if row is None:
return None
out = dict(row)
try:
out["blind_roles"] = json.loads(out.pop("blind_roles_json"))
except (TypeError, json.JSONDecodeError):
out["blind_roles"] = []
return out
def configure_topic(
conn: sqlite3.Connection,
*,
topic_id: str,
declared_roles: Sequence[str],
blind_roles: Sequence[str],
max_rounds: int = DEFAULT_MAX_ROUNDS,
phase_timeout_seconds: int = 300,
) -> dict[str, Any]:
"""Idempotently enable ``debate/v1`` for a topic."""
roles = [str(role) for role in declared_roles if str(role)]
blind = list(dict.fromkeys(str(role) for role in blind_roles if str(role)))
if len(blind) != 2:
raise ProtocolV1Error(
"blind_roles must contain exactly two distinct declared roles",
error_type="INVALID_PROTOCOL_CONFIG",
details={"blind_roles": blind},
)
unknown = [role for role in blind if role not in roles]
if unknown:
raise ProtocolV1Error(
"blind_roles contain undeclared roles",
error_type="INVALID_PROTOCOL_CONFIG",
details={"unknown_roles": unknown},
)
if isinstance(max_rounds, bool) or not isinstance(max_rounds, int):
raise ProtocolV1Error(
"max_rounds must be an integer",
error_type="INVALID_PROTOCOL_CONFIG",
)
if not 1 <= max_rounds <= MAX_ROUNDS_LIMIT:
raise ProtocolV1Error(
f"max_rounds must be between 1 and {MAX_ROUNDS_LIMIT}",
error_type="INVALID_PROTOCOL_CONFIG",
)
if not isinstance(phase_timeout_seconds, int) or phase_timeout_seconds < 30:
raise ProtocolV1Error(
"phase_timeout_seconds must be an integer >= 30",
error_type="INVALID_PROTOCOL_CONFIG",
)
existing = get_protocol_state(conn, topic_id)
if existing is not None:
if (
existing["protocol_version"] == PROTOCOL_VERSION
and existing["blind_roles"] == blind
and int(existing["max_rounds"]) == max_rounds
and int(existing["phase_timeout_seconds"]) == phase_timeout_seconds
):
return existing
raise ProtocolV1Error(
"protocol already configured with a different contract",
error_type="PROTOCOL_CONFIG_CONFLICT",
details={"existing": existing},
)
now = _now_iso()
deadline = (
(datetime.now(timezone.utc) + timedelta(seconds=phase_timeout_seconds))
.isoformat()
.replace("+00:00", "Z")
)
conn.execute(
"INSERT INTO debate_protocol_state "
"(topic_id, protocol_version, phase, round_no, max_rounds, "
" blind_barrier_state, blind_roles_json, stalemate_reason, "
" transition_version, phase_deadline_at, phase_timeout_seconds, updated_at) "
"VALUES (?, ?, 'BLIND_CLAIM', 1, ?, 'waiting', ?, NULL, 1, ?, ?, ?)",
(
topic_id,
PROTOCOL_VERSION,
max_rounds,
json.dumps(blind, ensure_ascii=False, separators=(",", ":")),
deadline,
phase_timeout_seconds,
now,
),
)
return get_protocol_state(conn, topic_id) or {}
def _resolve_author_session(
conn: sqlite3.Connection,
*,
topic_id: str,
role: str,
author_session_id: str | None,
) -> str:
if author_session_id:
binding = conn.execute(
"SELECT 1 FROM debate_role_bindings "
"WHERE topic_id=? AND role=? AND session_id=? AND state='active'",
(topic_id, role, author_session_id),
).fetchone()
worker = conn.execute(
"SELECT 1 FROM debate_worker_claims "
"WHERE topic_id=? AND role=? AND worker_session_id=? AND state='active'",
(topic_id, role, author_session_id),
).fetchone()
if binding is None and worker is None:
raise ProtocolV1Error(
"author_session_id does not own the role",
error_type="ROLE_UNAVAILABLE",
details={"role": role, "session_id": author_session_id},
)
return author_session_id
rows = conn.execute(
"SELECT session_id FROM debate_role_bindings "
"WHERE topic_id=? AND role=? AND state='active' "
"ORDER BY generation DESC LIMIT 2",
(topic_id, role),
).fetchall()
if len(rows) != 1:
raise ProtocolV1Error(
"semantic post requires one active author binding",
error_type="ROLE_UNAVAILABLE",
details={"role": role, "active_binding_count": len(rows)},
)
return str(rows[0]["session_id"])
def assert_fresh_read(
conn: sqlite3.Connection,
*,
topic_id: str,
role: str,
author_session_id: str | None,
) -> str:
"""Reject a post when an earlier addressed H message is unread."""
session_id = _resolve_author_session(
conn,
topic_id=topic_id,
role=role,
author_session_id=author_session_id,
)
cursor = conn.execute(
"SELECT last_processed_ts,last_processed_msg_id "
"FROM debate_signal_state WHERE session_id=? AND role=? AND topic_id=?",
(session_id, role, topic_id),
).fetchone()
cursor_ts = cursor["last_processed_ts"] if cursor else None
cursor_id = (cursor["last_processed_msg_id"] or "") if cursor else ""
worker = conn.execute(
"SELECT trigger_msg_id FROM debate_worker_claims "
"WHERE topic_id=? AND role=? AND worker_session_id=? AND state='active'",
(topic_id, role, session_id),
).fetchone()
if worker is not None:
trigger = conn.execute(
"SELECT msg_id,ts,role,kind FROM debate_messages WHERE msg_id=? "
"AND topic_id=?",
(worker["trigger_msg_id"], topic_id),
).fetchone()
if (
trigger is None
or cursor_ts is None
or (cursor_ts, cursor_id)
< (
trigger["ts"],
trigger["msg_id"],
)
):
details = (
dict(trigger)
if trigger is not None
else {"msg_id": worker["trigger_msg_id"]}
)
details["author_session_id"] = session_id
raise ProtocolV1Error(
f"STALE_READ: unread claimed trigger {worker['trigger_msg_id']}",
error_type="STALE_READ",
details=details,
)
return session_id
params: list[Any] = [topic_id, role, session_id, role]
after = ""
if cursor_ts:
after = "AND (m.ts > ? OR (m.ts = ? AND m.msg_id > ?)) "
params.extend([cursor_ts, cursor_ts, cursor_id])
blocker = conn.execute(
"SELECT m.msg_id,m.ts,m.role,m.kind FROM debate_messages m "
"WHERE m.topic_id=? AND m.priority='H' "
"AND EXISTS (SELECT 1 FROM debate_message_recipients r "
" WHERE r.msg_id=m.msg_id AND r.recipient_mode='normal' "
" AND r.recipient IN (?,?)) "
"AND NOT EXISTS (SELECT 1 FROM debate_blind_commits bc "
" WHERE bc.msg_id=m.msg_id AND bc.released_at IS NULL "
" AND bc.role<>?) "
f"{after}ORDER BY m.ts ASC,m.msg_id ASC LIMIT 1",
params,
).fetchone()
if blocker is not None:
details = dict(blocker)
details["author_session_id"] = session_id
raise ProtocolV1Error(
f"STALE_READ: unread addressed H message {blocker['msg_id']}",
error_type="STALE_READ",
details=details,
)
return session_id
_TARGET_PARENT_KINDS: dict[str, set[str]] = {
"CHALLENGE": {"CLAIM", "EVIDENCE", "REBUT"},
"EVIDENCE": {"CLAIM", "CHALLENGE", "REBUT"},
"REBUT": {"CHALLENGE"},
"CONCEDE": {"CHALLENGE", "CLAIM"},
"VERIFY": {"CLAIM", "EVIDENCE", "REBUT", "CONCEDE"},
"DISSENT": {"VERIFY", "DECISION", "ESCALATE"},
}
def _has_human_recipient(recipients: Iterable[str]) -> bool:
return any(_HUMAN_RECIPIENT_RE.fullmatch(str(value or "")) for value in recipients)
def _validate_semantic_role(*, kind: str, role: str, blind_roles: set[str]) -> None:
if kind == "VERIFY" and role in blind_roles:
raise ProtocolV1Error(
"VERIFY requires a role independent from the opposing positions",
error_type="ROLE_NOT_ALLOWED",
details={"role": role, "kind": kind},
)
def _reject_duplicate_dissent(
conn: sqlite3.Connection, *, topic_id: str, role: str
) -> None:
duplicate = conn.execute(
"SELECT 1 FROM debate_messages WHERE topic_id=? AND role=? "
"AND protocol_version=? AND kind='DISSENT' LIMIT 1",
(topic_id, role, PROTOCOL_VERSION),
).fetchone()
if duplicate is not None:
raise ProtocolV1Error(
"only one DISSENT per semantic role is allowed",
error_type="DISSENT_DUPLICATE",
)
def _validate_round_cap(*, state: dict[str, Any], kind: str) -> None:
round_no = int(state["round_no"])
max_rounds = int(state["max_rounds"])
if round_no > max_rounds and kind not in {"DISSENT", "ESCALATE"}:
raise ProtocolV1Error(
"server round cap exceeded",
error_type="ROUND_CAP",
details={"round_no": round_no, "max_rounds": max_rounds},
)
def _validate_phase_kind(
conn: sqlite3.Connection,
*,
topic_id: str,
role: str,
kind: str,
state: dict[str, Any],
) -> None:
phase = str(state["phase"])
if phase == "BLIND_CLAIM":
if kind != "CLAIM" or role not in set(state["blind_roles"]):
raise ProtocolV1Error(
"blind commit barrier accepts only initial CLAIMs",
error_type="BLIND_NOT_RELEASED",
details={"phase": phase, "blind_roles": state["blind_roles"]},
)
duplicate = conn.execute(
"SELECT 1 FROM debate_blind_commits WHERE topic_id=? AND role=?",
(topic_id, role),
).fetchone()
if duplicate is not None:
raise ProtocolV1Error(
"role already committed its initial CLAIM",
error_type="BLIND_CLAIM_DUPLICATE",
details={"role": role},
)
elif phase == "DEBATE" and kind not in {*DEBATE_TURN_KINDS, "ESCALATE"}:
raise ProtocolV1Error(
f"kind {kind} is not allowed during DEBATE",
error_type="WRONG_PHASE",
details={"phase": phase},
)
elif phase == "ADJUDICATE" and kind != "ESCALATE":
raise ProtocolV1Error(
"ADJUDICATE accepts judge operations or ESCALATE only",
error_type="WRONG_PHASE",
details={"phase": phase},
)
elif phase == "STALEMATE":
if kind not in {"DISSENT", "ESCALATE"}:
raise ProtocolV1Error(
"protocol is in STALEMATE",
error_type="PROTOCOL_STALEMATE",
details={"stalemate_reason": state.get("stalemate_reason")},
)
if kind == "DISSENT":
_reject_duplicate_dissent(conn, topic_id=topic_id, role=role)
elif phase in {"ESCALATED", "STOPPED"}:
raise ProtocolV1Error(
f"protocol phase {phase} is terminal for posts",
error_type="PROTOCOL_TERMINAL",
details={"phase": phase},
)
_validate_round_cap(state=state, kind=kind)
def _reject_duplicate_act(
conn: sqlite3.Connection,
*,
topic_id: str,
role: str,
kind: str,
reply_to: str | None,
normalized_json: str,
) -> None:
existing = conn.execute(
"SELECT msg_id FROM debate_messages WHERE topic_id=? AND role=? "
"AND kind=? AND protocol_version=? AND reply_to IS ? AND payload_json=? "
"LIMIT 1",
(topic_id, role, kind, PROTOCOL_VERSION, reply_to, normalized_json),
).fetchone()
if existing is not None:
raise ProtocolV1Error(
"exact semantic act already exists",
error_type="DUPLICATE_ACT",
details={"msg_id": existing["msg_id"]},
)
def _validate_target(
conn: sqlite3.Connection,
*,
topic_id: str,
kind: str,
reply_to: str | None,
payload: dict[str, Any],
) -> None:
if kind not in TARGET_REQUIRED_KINDS:
return
if not reply_to:
raise ProtocolV1Error(
f"{kind} requires reply_to",
error_type="INVALID_TARGET",
)
parent = conn.execute(
"SELECT topic_id,kind FROM debate_messages WHERE msg_id=?", (reply_to,)
).fetchone()
if parent is None or parent["topic_id"] != topic_id:
raise ProtocolV1Error(
"target must exist in the same topic",
error_type="INVALID_TARGET",
details={"reply_to": reply_to},
)
if parent["kind"] not in _TARGET_PARENT_KINDS[kind]:
raise ProtocolV1Error(
f"{kind} cannot target {parent['kind']}",
error_type="INVALID_TARGET",
details={"reply_to": reply_to, "parent_kind": parent["kind"]},
)
target_key = "decision_target" if kind == "DISSENT" else "target"
if str(payload.get(target_key)) != reply_to:
raise ProtocolV1Error(
f"payload.{target_key} must equal reply_to",
error_type="INVALID_TARGET",
details={"reply_to": reply_to, "payload_target": payload.get(target_key)},
)
def _validate_escalation(
conn: sqlite3.Connection,
*,
topic_id: str,
kind: str,
recipients: Sequence[str],
protocol_generation: int,
) -> None:
if kind != "ESCALATE":
return
if not _has_human_recipient(recipients):
raise ProtocolV1Error(
"ESCALATE requires a human recipient",
error_type="HUMAN_RECIPIENT_REQUIRED",
)
existing = conn.execute(
"SELECT msg_id FROM debate_human_packets WHERE topic_id=? "
"AND protocol_generation=?",
(topic_id, protocol_generation),
).fetchone()
if existing is not None:
raise ProtocolV1Error(
"ESCALATE packet already exists for this protocol generation",
error_type="ESCALATE_DUPLICATE",
details={"msg_id": existing["msg_id"]},
)
def preflight_post(
conn: sqlite3.Connection,
*,
topic_id: str,
role: str,
kind: str,
reply_to: str | None,
payload: Any,
body_mode: str | None,
protocol_version: str | None,
author_session_id: str | None,
recipients: Sequence[str] = (),
) -> dict[str, Any] | None:
"""Read-only semantic validation performed before the message INSERT."""
if kind not in SEMANTIC_KINDS:
if protocol_version not in (None, "", PROTOCOL_VERSION):
raise ProtocolV1Error(
"unknown protocol_version",
error_type="INVALID_PROTOCOL_VERSION",
)
configured = get_protocol_state(conn, topic_id)
if configured is not None and kind in {"Q", "A", "STATUS", "DECISION"}:
raise ProtocolV1Error(
f"legacy conversational kind {kind} is disabled on debate/v1 topics",
error_type="SEMANTIC_KIND_REQUIRED",
details={"kind": kind, "protocol_version": PROTOCOL_VERSION},
)
return None
state = get_protocol_state(conn, topic_id)
if state is None or state.get("protocol_version") != PROTOCOL_VERSION:
raise ProtocolV1Error(
"semantic kind requires a debate/v1 configured topic",
error_type="PROTOCOL_NOT_CONFIGURED",
)
if protocol_version not in (None, "", PROTOCOL_VERSION):
raise ProtocolV1Error(
"semantic post protocol_version mismatch",
error_type="INVALID_PROTOCOL_VERSION",
)
mode = body_mode or "structured"
if mode not in BODY_MODES:
raise ProtocolV1Error(
f"invalid body_mode {mode!r}",
error_type="INVALID_BODY_MODE",
)
normalized = normalize_payload(kind, payload)
normalized_json = json.dumps(
normalized, ensure_ascii=False, sort_keys=True, separators=(",", ":")
)
phase = str(state["phase"])
round_no = int(state["round_no"])
_validate_semantic_role(kind=kind, role=role, blind_roles=set(state["blind_roles"]))
if kind in DEBATE_TURN_KINDS:
assert_fresh_read(
conn,
topic_id=topic_id,
role=role,
author_session_id=author_session_id,
)
_validate_phase_kind(conn, topic_id=topic_id, role=role, kind=kind, state=state)
_reject_duplicate_act(
conn,
topic_id=topic_id,
role=role,
kind=kind,
reply_to=reply_to,
normalized_json=normalized_json,
)
_validate_target(
conn,
topic_id=topic_id,
kind=kind,
reply_to=reply_to,
payload=normalized,
)
_validate_escalation(
conn,
topic_id=topic_id,
kind=kind,
recipients=recipients,
protocol_generation=int(state["transition_version"]),
)
return {
"protocol_version": PROTOCOL_VERSION,
"round_no": round_no,
"body_mode": mode,
"payload": normalized,
"payload_json": normalized_json,
"phase_before": phase,
}
def _phase_deadline(state: dict[str, Any], now: datetime | None = None) -> str:
base = now or datetime.now(timezone.utc)
timeout = int(state.get("phase_timeout_seconds") or 300)
return (base + timedelta(seconds=timeout)).isoformat().replace("+00:00", "Z")
def record_post(
conn: sqlite3.Connection,
*,
topic_id: str,
role: str,
kind: str,
msg_id: str,
semantic: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""Apply deterministic micro-state changes after a valid INSERT."""
if semantic is None:
return get_protocol_state(conn, topic_id)
state = get_protocol_state(conn, topic_id)
if state is None:
raise ProtocolV1Error(
"protocol state disappeared during post",
error_type="PROTOCOL_STATE_MISSING",
)
now = _now_iso()
if kind == "CLAIM" and state["phase"] == "BLIND_CLAIM":
conn.execute(
"INSERT INTO debate_blind_commits "
"(topic_id,role,msg_id,round_no,committed_at,released_at) "
"VALUES (?,?,?,?,?,NULL)",
(topic_id, role, msg_id, int(state["round_no"]), now),
)
count = conn.execute(
"SELECT COUNT(*) FROM debate_blind_commits WHERE topic_id=?",
(topic_id,),
).fetchone()[0]
if count == len(state["blind_roles"]):
conn.execute(
"UPDATE debate_blind_commits SET released_at=? "
"WHERE topic_id=? AND released_at IS NULL",
(now, topic_id),
)
conn.execute(
"UPDATE debate_protocol_state SET phase='DEBATE', "
"blind_barrier_state='released', transition_version=transition_version+1, "
"phase_deadline_at=?, updated_at=? WHERE topic_id=?",
(_phase_deadline(state), now, topic_id),
)
elif kind == "VERIFY":
current_round = int(state["round_no"])
unresolved = conn.execute(
"SELECT COUNT(*) FROM debate_messages c "
"WHERE c.topic_id=? AND c.protocol_version=? "
"AND c.kind='CHALLENGE' "
"AND NOT EXISTS (SELECT 1 FROM debate_messages d "
" WHERE d.topic_id=c.topic_id AND d.reply_to=c.msg_id "
" AND d.kind IN ('REBUT','CONCEDE'))",
(topic_id, PROTOCOL_VERSION),
).fetchone()[0]
result = semantic["payload"].get("result")
if result == "verified" and unresolved == 0:
conn.execute(
"UPDATE debate_protocol_state SET phase='ADJUDICATE', "
"transition_version=transition_version+1,phase_deadline_at=?,updated_at=? "
"WHERE topic_id=?",
(_phase_deadline(state), now, topic_id),
)
elif current_round >= int(state["max_rounds"]):
conn.execute(
"UPDATE debate_protocol_state SET phase='STALEMATE', "
"stalemate_reason='round_cap_unresolved', "
"transition_version=transition_version+1,phase_deadline_at=NULL,updated_at=? "
"WHERE topic_id=?",
(now, topic_id),
)
else:
conn.execute(
"UPDATE debate_protocol_state SET round_no=round_no+1, "
"transition_version=transition_version+1,phase_deadline_at=?,updated_at=? "
"WHERE topic_id=?",
(_phase_deadline(state), now, topic_id),
)
elif kind == "ESCALATE":
generation = int(state["transition_version"])
conn.execute(
"INSERT INTO debate_human_packets "
"(topic_id,protocol_generation,msg_id,state,exact_human_action,payload_json,created_at,resolved_at) "
"VALUES (?,?,?,'open',?,?,?,NULL)",
(
topic_id,
generation,
msg_id,
semantic["payload"]["exact_human_action"],
semantic["payload_json"],
now,
),
)
conn.execute(
"UPDATE debate_protocol_state SET phase='ESCALATED', "
"transition_version=transition_version+1,phase_deadline_at=NULL,updated_at=? "
"WHERE topic_id=?",
(now, topic_id),
)
return get_protocol_state(conn, topic_id)
def visibility_sql(
*, alias: str, viewer_role: str | None, control_plane: bool = False
) -> tuple[str, list[Any]]:
"""Return the canonical blind-commit SQL predicate."""
if control_plane:
return "1=1", []
role = str(viewer_role or "")
return (
"NOT EXISTS (SELECT 1 FROM debate_blind_commits bc "
f"WHERE bc.msg_id={alias}.msg_id AND bc.released_at IS NULL "
"AND bc.role <> ?)",
[role],
)
def visible_message_ids(
conn: sqlite3.Connection,
*,
topic_ids: Sequence[str],
viewer_role: str | None,
control_plane: bool = False,
) -> list[str]:
if not topic_ids:
return []
ph = ",".join("?" for _ in topic_ids)
predicate, predicate_params = visibility_sql(
alias="m", viewer_role=viewer_role, control_plane=control_plane
)
rows = conn.execute(
f"SELECT m.msg_id FROM debate_messages m WHERE m.topic_id IN ({ph}) "
f"AND {predicate} ORDER BY m.ts,m.msg_id",
[*topic_ids, *predicate_params],
).fetchall()
return [str(row["msg_id"]) for row in rows]
def _normalized_position(row: sqlite3.Row) -> dict[str, Any]:
payload: dict[str, Any] = {}
if row["payload_json"]:
try:
parsed = json.loads(row["payload_json"])
if isinstance(parsed, dict):
payload = parsed
except json.JSONDecodeError:
payload = {}
summary = payload.get("summary")
if not isinstance(summary, str) or not summary.strip():
summary = " ".join(str(row["body"] or "").split())[:4000]
return {
"msg_id": row["msg_id"],
"kind": row["kind"],
"summary": summary,
"evidence_refs": payload.get("evidence_refs", []),
}
def prepare_order_swap(
conn: sqlite3.Connection,
*,
topic_id: str,
left_msg_id: str,
right_msg_id: str,
) -> dict[str, Any]:
state = get_protocol_state(conn, topic_id)
if state is None or state["phase"] != "ADJUDICATE":
raise ProtocolV1Error(
"order-swap requires ADJUDICATE phase",
error_type="WRONG_PHASE",
)
rows = conn.execute(
"SELECT msg_id,topic_id,role,kind,body,payload_json FROM debate_messages "
"WHERE topic_id=? AND msg_id IN (?,?)",
(topic_id, left_msg_id, right_msg_id),
).fetchall()
by_id = {row["msg_id"]: row for row in rows}
if set(by_id) != {left_msg_id, right_msg_id} or left_msg_id == right_msg_id:
raise ProtocolV1Error(
"order-swap positions must be two distinct messages in the topic",
error_type="INVALID_TARGET",
)
invalid_kinds = {
str(row["kind"]) for row in rows if str(row["kind"]) not in {"CLAIM", "REBUT"}
}
if invalid_kinds:
raise ProtocolV1Error(
"order-swap accepts only CLAIM or REBUT positions",
error_type="INVALID_TARGET",
details={"invalid_kinds": sorted(invalid_kinds)},
)
position_roles = {str(row["role"]) for row in rows}
if position_roles != set(state["blind_roles"]):
raise ProtocolV1Error(
"order-swap positions must come from the two opposing roles",
error_type="INVALID_TARGET",
details={"position_roles": sorted(position_roles)},
)
positions = {
left_msg_id: _normalized_position(by_id[left_msg_id]),
right_msg_id: _normalized_position(by_id[right_msg_id]),
}
now = _now_iso()
projections: list[dict[str, Any]] = []
for order_key, ordered in (
("AB", [left_msg_id, right_msg_id]),
("BA", [right_msg_id, left_msg_id]),
):
projection_id = f"{topic_id}:{int(state['round_no'])}:{order_key}"
normalized = {
"protocol_version": PROTOCOL_VERSION,
"topic_id": topic_id,
"round_no": int(state["round_no"]),
"positions": [positions[msg_id] for msg_id in ordered],
}
normalized_json = json.dumps(
normalized, ensure_ascii=False, sort_keys=True, separators=(",", ":")
)
existing = conn.execute(
"SELECT left_msg_id,right_msg_id,normalized_json "
"FROM debate_judge_projections "
"WHERE topic_id=? AND round_no=? AND order_key=?",
(topic_id, int(state["round_no"]), order_key),
).fetchone()
if existing is not None and (
existing["left_msg_id"] != ordered[0]
or existing["right_msg_id"] != ordered[1]
or existing["normalized_json"] != normalized_json
):
raise ProtocolV1Error(
"judge projection is immutable for topic/round/order",
error_type="JUDGE_PROJECTION_CONFLICT",
details={"order_key": order_key},
)
if existing is None:
conn.execute(
"INSERT INTO debate_judge_projections "
"(projection_id,topic_id,round_no,order_key,left_msg_id,right_msg_id,"
"normalized_json,verdict_json,judge_role,created_at,decided_at) "
"VALUES (?,?,?,?,?,?,?,NULL,NULL,?,NULL)",
(
projection_id,
topic_id,
int(state["round_no"]),
order_key,
ordered[0],
ordered[1],
normalized_json,
now,
),
)
projections.append(
{"projection_id": projection_id, "order_key": order_key, **normalized}
)
return {"topic_id": topic_id, "projections": projections}
def _validate_judge_role(
conn: sqlite3.Connection, *, topic_id: str, judge_role: str
) -> None:
topic = conn.execute(
"SELECT d.roles_json,p.blind_roles_json FROM debates d "
"JOIN debate_protocol_state p ON p.topic_id=d.topic_id "
"WHERE d.topic_id=?",
(topic_id,),
).fetchone()
try:
roster = json.loads(topic["roles_json"]) if topic is not None else []
blind_roles = (
set(json.loads(topic["blind_roles_json"])) if topic is not None else set()
)
except (TypeError, json.JSONDecodeError):
roster = []
blind_roles = set()
declared = {
str(entry.get("role") if isinstance(entry, dict) else entry) for entry in roster
}
active = conn.execute(
"SELECT 1 FROM debate_role_bindings WHERE topic_id=? AND role=? "
"AND state='active'",
(topic_id, judge_role),
).fetchone()
if (
judge_role not in declared
or judge_role in blind_roles
or _HUMAN_RECIPIENT_RE.fullmatch(str(judge_role or ""))
or active is None
):
raise ProtocolV1Error(
"judge role must be an active, declared, non-opposing machine role",
error_type="JUDGE_ROLE_UNAVAILABLE",
details={"judge_role": judge_role},
)
def record_order_swap_verdict(