letitloop 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- letitloop-0.2.0.dist-info/METADATA +232 -0
- letitloop-0.2.0.dist-info/RECORD +175 -0
- letitloop-0.2.0.dist-info/WHEEL +5 -0
- letitloop-0.2.0.dist-info/entry_points.txt +4 -0
- letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
- letitloop-0.2.0.dist-info/top_level.txt +1 -0
- orchestrator/SKILL.md +292 -0
- orchestrator/__init__.py +151 -0
- orchestrator/anti_ouroboros.py +78 -0
- orchestrator/approval.py +139 -0
- orchestrator/ast_node_splicer.py +130 -0
- orchestrator/ast_splicer.py +94 -0
- orchestrator/audit.py +88 -0
- orchestrator/budget.py +195 -0
- orchestrator/checkpoint.py +248 -0
- orchestrator/cli.py +1971 -0
- orchestrator/codebase_introspector.py +66 -0
- orchestrator/component_slicer.py +185 -0
- orchestrator/config.py +152 -0
- orchestrator/contract.py +404 -0
- orchestrator/dag_validator.py +172 -0
- orchestrator/elasticity_governor.py +80 -0
- orchestrator/env_doctor.py +166 -0
- orchestrator/errors.py +211 -0
- orchestrator/events.py +120 -0
- orchestrator/evidence.py +203 -0
- orchestrator/exceptions.py +37 -0
- orchestrator/experimental/arena_arbiter.py +260 -0
- orchestrator/experimental/fuzz_engine.py +206 -0
- orchestrator/experimental/mutation_tester.py +382 -0
- orchestrator/failure.py +226 -0
- orchestrator/fast_sandbox.py +126 -0
- orchestrator/feasibility_gate.py +115 -0
- orchestrator/feedback.py +302 -0
- orchestrator/fixtures/__init__.py +0 -0
- orchestrator/fixtures/example_contract.json +50 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
- orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
- orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
- orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
- orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
- orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
- orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
- orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
- orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
- orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
- orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
- orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
- orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
- orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
- orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
- orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
- orchestrator/fixtures/generated/perf-step-1.json +61 -0
- orchestrator/fixtures/generated/perf-step-2.json +62 -0
- orchestrator/fixtures/generated/perf-step-3.json +62 -0
- orchestrator/fixtures/generated/perf-step-4.json +62 -0
- orchestrator/fixtures/generated/perf-step-5.json +63 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
- orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
- orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
- orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
- orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
- orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
- orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
- orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
- orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
- orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
- orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
- orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
- orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
- orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
- orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
- orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
- orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
- orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
- orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
- orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
- orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
- orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
- orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
- orchestrator/fixtures/run_proofs.py +299 -0
- orchestrator/fixtures/test_normalizer.py +16 -0
- orchestrator/generator.py +239 -0
- orchestrator/goal.py +245 -0
- orchestrator/handoff.py +86 -0
- orchestrator/hybrid_worker.py +840 -0
- orchestrator/impossibility.py +162 -0
- orchestrator/limits.py +60 -0
- orchestrator/live_evolution_engine.py +247 -0
- orchestrator/llm.py +291 -0
- orchestrator/local_tool_calling.py +285 -0
- orchestrator/lock.py +404 -0
- orchestrator/mcp_client.py +571 -0
- orchestrator/mcp_server.py +344 -0
- orchestrator/memory_bridge.py +182 -0
- orchestrator/metrics.py +159 -0
- orchestrator/micro_epoch.py +42 -0
- orchestrator/models.py +350 -0
- orchestrator/parsing.py +237 -0
- orchestrator/patch_applier.py +154 -0
- orchestrator/plan_preview.py +138 -0
- orchestrator/plan_quality.py +357 -0
- orchestrator/planner.py +532 -0
- orchestrator/preferences.py +115 -0
- orchestrator/preflight.py +141 -0
- orchestrator/process_guard.py +357 -0
- orchestrator/prometheus_exporter.py +207 -0
- orchestrator/prompts.py +275 -0
- orchestrator/proposal_ledger.py +194 -0
- orchestrator/provenance.py +263 -0
- orchestrator/provider_scheduler.py +394 -0
- orchestrator/qc/__init__.py +153 -0
- orchestrator/qc/aggregator.py +330 -0
- orchestrator/qc/parsing.py +287 -0
- orchestrator/qc/personas.py +242 -0
- orchestrator/qc/runner.py +569 -0
- orchestrator/qc_overrule.py +87 -0
- orchestrator/qc_review.py +282 -0
- orchestrator/quality_lenses.py +314 -0
- orchestrator/quality_plan.py +449 -0
- orchestrator/quality_plane.py +103 -0
- orchestrator/reconcile.py +191 -0
- orchestrator/replanner.py +433 -0
- orchestrator/research.py +176 -0
- orchestrator/review_artifact.py +672 -0
- orchestrator/safety.py +271 -0
- orchestrator/schemas.py +230 -0
- orchestrator/scope.py +466 -0
- orchestrator/sensory_radar.py +79 -0
- orchestrator/skill_installer.py +140 -0
- orchestrator/sse_server.py +160 -0
- orchestrator/state.py +871 -0
- orchestrator/subprocess_helper.py +131 -0
- orchestrator/supervisor/__init__.py +184 -0
- orchestrator/supervisor/_shared.py +164 -0
- orchestrator/supervisor/cleanup.py +185 -0
- orchestrator/supervisor/core.py +1680 -0
- orchestrator/supervisor/recovery.py +367 -0
- orchestrator/supervisor/reporting.py +251 -0
- orchestrator/surgical_extractor.py +119 -0
- orchestrator/telemetry.py +61 -0
- orchestrator/templates.py +268 -0
- orchestrator/token_gate.py +245 -0
- orchestrator/tui.py +649 -0
- orchestrator/verifier.py +1103 -0
- orchestrator/webhooks.py +168 -0
- orchestrator/worker.py +469 -0
- orchestrator/worker_adapters.py +815 -0
- orchestrator/worker_pool.py +121 -0
- orchestrator/worktree.py +364 -0
orchestrator/evidence.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Persistent evidence ledger — tracks contract outputs with metadata."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import threading
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from typing import Any, Dict, List
|
|
9
|
+
|
|
10
|
+
from .lock import FileLock
|
|
11
|
+
|
|
12
|
+
LEDGER_FILENAME = "evidence_ledger.json"
|
|
13
|
+
|
|
14
|
+
# AUT-009: serializes load->mutate->save so parallel worker threads cannot
|
|
15
|
+
# lose ledger entries.
|
|
16
|
+
_LEDGER_LOCK = threading.Lock()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _sha256(path: str) -> str:
|
|
20
|
+
h = hashlib.sha256()
|
|
21
|
+
try:
|
|
22
|
+
with open(path, "rb") as f:
|
|
23
|
+
for chunk in iter(lambda: f.read(65536), b""):
|
|
24
|
+
h.update(chunk)
|
|
25
|
+
return h.hexdigest()
|
|
26
|
+
except OSError:
|
|
27
|
+
return ""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _file_size(path: str) -> int:
|
|
31
|
+
try:
|
|
32
|
+
return os.path.getsize(path)
|
|
33
|
+
except OSError:
|
|
34
|
+
return 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def load_ledger(run_dir: str) -> Dict[str, List[Dict[str, Any]]]:
|
|
38
|
+
"""Load evidence ledger from disk. Returns dict keyed by task_id."""
|
|
39
|
+
ledger_path = os.path.join(run_dir, LEDGER_FILENAME)
|
|
40
|
+
if not os.path.isfile(ledger_path):
|
|
41
|
+
return {}
|
|
42
|
+
try:
|
|
43
|
+
with open(ledger_path, "r", encoding="utf-8") as f:
|
|
44
|
+
return json.load(f)
|
|
45
|
+
except (json.JSONDecodeError, OSError):
|
|
46
|
+
return {}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def save_ledger(run_dir: str, ledger: Dict[str, List[Dict[str, Any]]]) -> None:
|
|
50
|
+
"""Save evidence ledger to disk."""
|
|
51
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
52
|
+
ledger_path = os.path.join(run_dir, LEDGER_FILENAME)
|
|
53
|
+
lock_path = ledger_path + ".lock"
|
|
54
|
+
with FileLock(lock_path):
|
|
55
|
+
tmp = ledger_path + ".tmp"
|
|
56
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
57
|
+
json.dump(ledger, f, indent=2, ensure_ascii=False)
|
|
58
|
+
os.replace(tmp, ledger_path)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def append_output(run_dir: str, task_id: str, output_path: str, workspace_root: str) -> Dict[str, Any]:
|
|
62
|
+
"""Record an output file in the ledger with metadata."""
|
|
63
|
+
abs_path = os.path.join(workspace_root, output_path) if not os.path.isabs(output_path) else output_path
|
|
64
|
+
entry = {
|
|
65
|
+
"task_id": task_id,
|
|
66
|
+
"relative_path": output_path,
|
|
67
|
+
"absolute_path": abs_path,
|
|
68
|
+
"sha256": _sha256(abs_path),
|
|
69
|
+
"size_bytes": _file_size(abs_path),
|
|
70
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
71
|
+
}
|
|
72
|
+
# AUT-009: parallel supervisor runs call append_output from worker threads —
|
|
73
|
+
# the load-mutate-save sequence must be atomic to avoid lost ledger entries.
|
|
74
|
+
with _LEDGER_LOCK:
|
|
75
|
+
ledger = load_ledger(run_dir)
|
|
76
|
+
if task_id not in ledger:
|
|
77
|
+
ledger[task_id] = []
|
|
78
|
+
# Replace existing entries for this output path
|
|
79
|
+
ledger[task_id] = [e for e in ledger[task_id] if e.get("relative_path") != output_path]
|
|
80
|
+
ledger[task_id].append(entry)
|
|
81
|
+
save_ledger(run_dir, ledger)
|
|
82
|
+
return entry
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def rebuild_evidence_store(ledger: Dict[str, List[Dict[str, Any]]]) -> Dict[str, List[str]]:
|
|
86
|
+
"""Rebuild evidence_store dict from ledger — maps task_id to list of absolute paths."""
|
|
87
|
+
store = {}
|
|
88
|
+
for task_id, entries in ledger.items():
|
|
89
|
+
paths = []
|
|
90
|
+
for e in entries:
|
|
91
|
+
ap = e.get("absolute_path", "")
|
|
92
|
+
if ap and os.path.isfile(ap):
|
|
93
|
+
paths.append(ap)
|
|
94
|
+
if paths:
|
|
95
|
+
store[task_id] = paths
|
|
96
|
+
return store
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def check_evidence_freshness(run_dir: str) -> List[Dict[str, Any]]:
|
|
100
|
+
"""Check all ledger entries for staleness (missing or changed files). Returns issues list."""
|
|
101
|
+
ledger = load_ledger(run_dir)
|
|
102
|
+
issues = []
|
|
103
|
+
for task_id, entries in ledger.items():
|
|
104
|
+
for e in entries:
|
|
105
|
+
ap = e.get("absolute_path", "")
|
|
106
|
+
if not ap:
|
|
107
|
+
issues.append({"task_id": task_id, "path": e.get("relative_path", "?"), "issue": "no absolute_path"})
|
|
108
|
+
continue
|
|
109
|
+
if not os.path.isfile(ap):
|
|
110
|
+
issues.append({"task_id": task_id, "path": e.get("relative_path", "?"), "issue": "file_missing"})
|
|
111
|
+
continue
|
|
112
|
+
stored_hash = e.get("sha256", "")
|
|
113
|
+
if stored_hash:
|
|
114
|
+
current_hash = _sha256(ap)
|
|
115
|
+
if stored_hash != current_hash:
|
|
116
|
+
issues.append({"task_id": task_id, "path": e.get("relative_path", "?"), "issue": "hash_changed"})
|
|
117
|
+
return issues
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def write_run_manifest(
|
|
121
|
+
run_dir: str, goal_id: str, plan, results: Dict[str, Dict[str, Any]], workspace_root: str
|
|
122
|
+
) -> None:
|
|
123
|
+
"""Write run_manifest.json with goal metadata, input/output hashes, and exit codes."""
|
|
124
|
+
manifest_path = os.path.join(run_dir, "run_manifest.json")
|
|
125
|
+
inputs = []
|
|
126
|
+
outputs = []
|
|
127
|
+
exit_codes = {}
|
|
128
|
+
|
|
129
|
+
for c_info in plan.contracts:
|
|
130
|
+
task_id = c_info["task_id"]
|
|
131
|
+
task_dir = os.path.join(run_dir, task_id)
|
|
132
|
+
|
|
133
|
+
contract_dict = c_info.get("contract", {})
|
|
134
|
+
contract_path = os.path.join(task_dir, "contract.json")
|
|
135
|
+
if not contract_dict and os.path.isfile(contract_path):
|
|
136
|
+
try:
|
|
137
|
+
with open(contract_path, "r", encoding="utf-8") as f:
|
|
138
|
+
contract_dict = json.load(f)
|
|
139
|
+
except (json.JSONDecodeError, OSError):
|
|
140
|
+
pass
|
|
141
|
+
|
|
142
|
+
for inp in contract_dict.get("inputs", []):
|
|
143
|
+
if isinstance(inp, dict):
|
|
144
|
+
path = inp.get("path", "")
|
|
145
|
+
else:
|
|
146
|
+
path = str(inp)
|
|
147
|
+
if path:
|
|
148
|
+
abs_path = os.path.join(workspace_root, path) if not os.path.isabs(path) else path
|
|
149
|
+
inputs.append({"path": path, "sha256": _sha256(abs_path)})
|
|
150
|
+
|
|
151
|
+
for out in contract_dict.get("outputs", []):
|
|
152
|
+
if isinstance(out, dict):
|
|
153
|
+
path = out.get("path", "")
|
|
154
|
+
else:
|
|
155
|
+
path = str(out)
|
|
156
|
+
if path:
|
|
157
|
+
abs_path = os.path.join(workspace_root, path) if not os.path.isabs(path) else path
|
|
158
|
+
qc_path = os.path.join(task_dir, "qc_verdict.json")
|
|
159
|
+
qc_status = "MISSING"
|
|
160
|
+
if os.path.isfile(qc_path):
|
|
161
|
+
try:
|
|
162
|
+
with open(qc_path, "r", encoding="utf-8") as f:
|
|
163
|
+
qc_data = json.load(f)
|
|
164
|
+
qc_status = qc_data.get("status", "MISSING")
|
|
165
|
+
except (json.JSONDecodeError, OSError):
|
|
166
|
+
pass
|
|
167
|
+
status = results.get(task_id, {}).get("status", "UNKNOWN") if results else "UNKNOWN"
|
|
168
|
+
outputs.append(
|
|
169
|
+
{
|
|
170
|
+
"task_id": task_id,
|
|
171
|
+
"path": path,
|
|
172
|
+
"sha256": _sha256(abs_path),
|
|
173
|
+
"status": status,
|
|
174
|
+
"qc_verdict": qc_status,
|
|
175
|
+
}
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
state_file = os.path.join(task_dir, "state.json")
|
|
179
|
+
exit_code = None
|
|
180
|
+
if os.path.isfile(state_file):
|
|
181
|
+
try:
|
|
182
|
+
with open(state_file, "r", encoding="utf-8") as f:
|
|
183
|
+
state_data = json.load(f)
|
|
184
|
+
worker_results = state_data.get("worker_results", [])
|
|
185
|
+
if worker_results:
|
|
186
|
+
last_wr = worker_results[-1]
|
|
187
|
+
exit_code = last_wr.get("exit_code") if isinstance(last_wr, dict) else None
|
|
188
|
+
except (json.JSONDecodeError, OSError):
|
|
189
|
+
pass
|
|
190
|
+
exit_codes[task_id] = exit_code
|
|
191
|
+
|
|
192
|
+
manifest = {
|
|
193
|
+
"goal_id": goal_id,
|
|
194
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
195
|
+
"inputs": inputs,
|
|
196
|
+
"outputs": outputs,
|
|
197
|
+
"exit_codes": exit_codes,
|
|
198
|
+
}
|
|
199
|
+
os.makedirs(run_dir, exist_ok=True)
|
|
200
|
+
tmp = manifest_path + ".tmp"
|
|
201
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
202
|
+
json.dump(manifest, f, indent=2, ensure_ascii=False)
|
|
203
|
+
os.replace(tmp, manifest_path)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Exception hierarchy for the orchestrator subsystem."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class OrchestratorError(Exception):
|
|
5
|
+
"""Base for all orchestrator errors."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ValidationError(OrchestratorError):
|
|
9
|
+
"""Contract or state validation failure."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class StateError(OrchestratorError):
|
|
13
|
+
"""State machine violation."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class IllegalTransitionError(StateError):
|
|
17
|
+
"""Transition not allowed from current state."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PreflightError(OrchestratorError):
|
|
21
|
+
"""Preflight check failure."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class VerifierError(OrchestratorError):
|
|
25
|
+
"""Verifier execution failure."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class WorkerError(OrchestratorError):
|
|
29
|
+
"""Worker adapter failure."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class HandoffError(OrchestratorError):
|
|
33
|
+
"""Handoff generation failure."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class PlannerError(OrchestratorError):
|
|
37
|
+
"""LLM planner decomposition failure."""
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""ArenaArbiter multi-agent consensus and decision arbitration module (Pruned & Hardened)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ConsensusStrategy(str, Enum):
|
|
11
|
+
"""Supported consensus strategies for arbitrating multi-agent proposals."""
|
|
12
|
+
|
|
13
|
+
MAJORITY_VOTE = "majority_vote"
|
|
14
|
+
WEIGHTED_MAJORITY = "weighted_majority"
|
|
15
|
+
SUPERMAJORITY = "supermajority"
|
|
16
|
+
UNANIMOUS = "unanimous"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Proposal:
|
|
21
|
+
"""Represents a proposal submitted by an agent."""
|
|
22
|
+
|
|
23
|
+
proposal_id: str
|
|
24
|
+
agent_id: str
|
|
25
|
+
content: Any
|
|
26
|
+
confidence: float = 1.0
|
|
27
|
+
score: float = 0.0
|
|
28
|
+
rank: Optional[int] = None
|
|
29
|
+
rationale: Optional[str] = None
|
|
30
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
31
|
+
|
|
32
|
+
def __post_init__(self) -> None:
|
|
33
|
+
if not self.proposal_id or not isinstance(self.proposal_id, str):
|
|
34
|
+
raise ValueError("proposal_id must be a non-empty string")
|
|
35
|
+
if not self.agent_id or not isinstance(self.agent_id, str):
|
|
36
|
+
raise ValueError("agent_id must be a non-empty string")
|
|
37
|
+
if not (0.0 <= self.confidence <= 1.0):
|
|
38
|
+
raise ValueError(f"Confidence must be in range [0.0, 1.0], got {self.confidence}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass
|
|
42
|
+
class AgentVote:
|
|
43
|
+
"""Represents a vote or evaluation from an agent for proposals."""
|
|
44
|
+
|
|
45
|
+
agent_id: str
|
|
46
|
+
proposal_id: str
|
|
47
|
+
weight: float = 1.0
|
|
48
|
+
rank: Optional[int] = None
|
|
49
|
+
score: Optional[float] = None
|
|
50
|
+
confidence: float = 1.0
|
|
51
|
+
comment: Optional[str] = None
|
|
52
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
53
|
+
|
|
54
|
+
def __post_init__(self) -> None:
|
|
55
|
+
if not self.agent_id or not isinstance(self.agent_id, str):
|
|
56
|
+
raise ValueError("agent_id must be a non-empty string")
|
|
57
|
+
if not self.proposal_id or not isinstance(self.proposal_id, str):
|
|
58
|
+
raise ValueError("proposal_id must be a non-empty string")
|
|
59
|
+
if self.weight < 0:
|
|
60
|
+
raise ValueError(f"Weight must be non-negative, got {self.weight}")
|
|
61
|
+
if not (0.0 <= self.confidence <= 1.0):
|
|
62
|
+
raise ValueError(f"Confidence must be in range [0.0, 1.0], got {self.confidence}")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class ArbitrationResult:
|
|
67
|
+
"""Result of multi-agent proposal arbitration and consensus resolution."""
|
|
68
|
+
|
|
69
|
+
selected_proposal: Optional[Proposal]
|
|
70
|
+
consensus_reached: bool
|
|
71
|
+
strategy_used: ConsensusStrategy
|
|
72
|
+
confidence_score: float
|
|
73
|
+
vote_distribution: Dict[str, float] = field(default_factory=dict)
|
|
74
|
+
ranked_proposals: List[Tuple[Proposal, float]] = field(default_factory=list)
|
|
75
|
+
reasoning: str = ""
|
|
76
|
+
dissenting_agents: List[str] = field(default_factory=list)
|
|
77
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class ArenaArbiter:
|
|
81
|
+
"""Arbitrates consensus across multi-agent proposals using clean majority rules."""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self,
|
|
85
|
+
default_strategy: ConsensusStrategy = ConsensusStrategy.MAJORITY_VOTE,
|
|
86
|
+
min_quorum: int = 1,
|
|
87
|
+
min_consensus_threshold: float = 0.5,
|
|
88
|
+
supermajority_threshold: float = 0.66,
|
|
89
|
+
):
|
|
90
|
+
self.default_strategy = default_strategy
|
|
91
|
+
self.min_quorum = min_quorum
|
|
92
|
+
self.min_consensus_threshold = min_consensus_threshold
|
|
93
|
+
self.supermajority_threshold = supermajority_threshold
|
|
94
|
+
self.agent_weights: Dict[str, float] = {}
|
|
95
|
+
|
|
96
|
+
def register_agent_weight(self, agent_id: str, weight: float) -> None:
|
|
97
|
+
if weight < 0:
|
|
98
|
+
raise ValueError("Agent weight cannot be negative")
|
|
99
|
+
self.agent_weights[agent_id] = float(weight)
|
|
100
|
+
|
|
101
|
+
def resolve_consensus(
|
|
102
|
+
self,
|
|
103
|
+
proposals: Sequence[Proposal],
|
|
104
|
+
votes: Optional[Sequence[AgentVote]] = None,
|
|
105
|
+
strategy: Optional[ConsensusStrategy] = None,
|
|
106
|
+
quorum: Optional[int] = None,
|
|
107
|
+
tie_breaker: Optional[Callable[[Sequence[Proposal]], Proposal]] = None,
|
|
108
|
+
) -> ArbitrationResult:
|
|
109
|
+
if not proposals:
|
|
110
|
+
return ArbitrationResult(
|
|
111
|
+
selected_proposal=None,
|
|
112
|
+
consensus_reached=False,
|
|
113
|
+
strategy_used=strategy or self.default_strategy,
|
|
114
|
+
confidence_score=0.0,
|
|
115
|
+
reasoning="No proposals provided for arbitration.",
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
active_strategy = strategy or self.default_strategy
|
|
119
|
+
active_quorum = quorum if quorum is not None else self.min_quorum
|
|
120
|
+
prop_map = {p.proposal_id: p for p in proposals}
|
|
121
|
+
|
|
122
|
+
# Quorum validation
|
|
123
|
+
participant_count = len(votes) if votes is not None else len(proposals)
|
|
124
|
+
if participant_count < active_quorum:
|
|
125
|
+
return ArbitrationResult(
|
|
126
|
+
selected_proposal=None,
|
|
127
|
+
consensus_reached=False,
|
|
128
|
+
strategy_used=active_strategy,
|
|
129
|
+
confidence_score=0.0,
|
|
130
|
+
reasoning=f"Quorum failure: required {active_quorum}, got {participant_count}",
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
# 1. Unanimous
|
|
134
|
+
if active_strategy == ConsensusStrategy.UNANIMOUS:
|
|
135
|
+
if votes is not None:
|
|
136
|
+
vote_targets = {v.proposal_id for v in votes}
|
|
137
|
+
if len(vote_targets) == 1:
|
|
138
|
+
target_id = list(vote_targets)[0]
|
|
139
|
+
if target_id in prop_map:
|
|
140
|
+
return ArbitrationResult(
|
|
141
|
+
selected_proposal=prop_map[target_id],
|
|
142
|
+
consensus_reached=True,
|
|
143
|
+
strategy_used=ConsensusStrategy.UNANIMOUS,
|
|
144
|
+
confidence_score=1.0,
|
|
145
|
+
reasoning="Unanimous consensus reached via agent votes.",
|
|
146
|
+
)
|
|
147
|
+
dissenters = [v.agent_id for v in votes if v.proposal_id != votes[0].proposal_id]
|
|
148
|
+
return ArbitrationResult(
|
|
149
|
+
selected_proposal=None,
|
|
150
|
+
consensus_reached=False,
|
|
151
|
+
strategy_used=ConsensusStrategy.UNANIMOUS,
|
|
152
|
+
confidence_score=0.0,
|
|
153
|
+
dissenting_agents=dissenters,
|
|
154
|
+
reasoning="Unanimous consensus failed: votes differ.",
|
|
155
|
+
)
|
|
156
|
+
else:
|
|
157
|
+
first_content = proposals[0].content
|
|
158
|
+
all_match = all(p.content == first_content for p in proposals)
|
|
159
|
+
if all_match:
|
|
160
|
+
return ArbitrationResult(
|
|
161
|
+
selected_proposal=proposals[0],
|
|
162
|
+
consensus_reached=True,
|
|
163
|
+
strategy_used=ConsensusStrategy.UNANIMOUS,
|
|
164
|
+
confidence_score=1.0,
|
|
165
|
+
reasoning="Unanimous consensus reached across proposals.",
|
|
166
|
+
)
|
|
167
|
+
dissenters = [p.agent_id for p in proposals if p.content != first_content]
|
|
168
|
+
return ArbitrationResult(
|
|
169
|
+
selected_proposal=None,
|
|
170
|
+
consensus_reached=False,
|
|
171
|
+
strategy_used=ConsensusStrategy.UNANIMOUS,
|
|
172
|
+
confidence_score=0.0,
|
|
173
|
+
dissenting_agents=dissenters,
|
|
174
|
+
reasoning="Unanimous consensus failed across proposals.",
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
# 2. Majority & Supermajority
|
|
178
|
+
tally: Dict[str, float] = {p.proposal_id: 0.0 for p in proposals}
|
|
179
|
+
total_weight = 0.0
|
|
180
|
+
|
|
181
|
+
if votes is not None:
|
|
182
|
+
for v in votes:
|
|
183
|
+
if v.proposal_id in tally:
|
|
184
|
+
w = (
|
|
185
|
+
v.weight
|
|
186
|
+
if active_strategy != ConsensusStrategy.WEIGHTED_MAJORITY
|
|
187
|
+
else self.agent_weights.get(v.agent_id, v.weight)
|
|
188
|
+
)
|
|
189
|
+
tally[v.proposal_id] += w
|
|
190
|
+
total_weight += w
|
|
191
|
+
else:
|
|
192
|
+
for p in proposals:
|
|
193
|
+
w = (
|
|
194
|
+
self.agent_weights.get(p.agent_id, 1.0)
|
|
195
|
+
if active_strategy == ConsensusStrategy.WEIGHTED_MAJORITY
|
|
196
|
+
else 1.0
|
|
197
|
+
)
|
|
198
|
+
tally[p.proposal_id] += w
|
|
199
|
+
total_weight += w
|
|
200
|
+
|
|
201
|
+
if total_weight <= 0:
|
|
202
|
+
total_weight = 1.0
|
|
203
|
+
|
|
204
|
+
sorted_tally = sorted(tally.items(), key=lambda item: item[1], reverse=True)
|
|
205
|
+
top_id, top_score = sorted_tally[0]
|
|
206
|
+
top_ratio = top_score / total_weight
|
|
207
|
+
|
|
208
|
+
# Check threshold
|
|
209
|
+
req_threshold = (
|
|
210
|
+
self.supermajority_threshold
|
|
211
|
+
if active_strategy == ConsensusStrategy.SUPERMAJORITY
|
|
212
|
+
else self.min_consensus_threshold
|
|
213
|
+
)
|
|
214
|
+
if len(sorted_tally) > 1 and sorted_tally[0][1] == sorted_tally[1][1]:
|
|
215
|
+
# Tie breaking
|
|
216
|
+
if tie_breaker is not None:
|
|
217
|
+
tied_props = [prop_map[pid] for pid, sc in sorted_tally if sc == top_score]
|
|
218
|
+
chosen = tie_breaker(tied_props)
|
|
219
|
+
return ArbitrationResult(
|
|
220
|
+
selected_proposal=chosen,
|
|
221
|
+
consensus_reached=True,
|
|
222
|
+
strategy_used=active_strategy,
|
|
223
|
+
confidence_score=top_ratio,
|
|
224
|
+
vote_distribution=tally,
|
|
225
|
+
reasoning="Tie resolved via tie-breaker.",
|
|
226
|
+
)
|
|
227
|
+
return ArbitrationResult(
|
|
228
|
+
selected_proposal=None,
|
|
229
|
+
consensus_reached=False,
|
|
230
|
+
strategy_used=active_strategy,
|
|
231
|
+
confidence_score=top_ratio,
|
|
232
|
+
vote_distribution=tally,
|
|
233
|
+
reasoning="Tied vote without tie-breaker.",
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
if top_ratio >= req_threshold:
|
|
237
|
+
dissenters = []
|
|
238
|
+
if votes is not None:
|
|
239
|
+
dissenters = [v.agent_id for v in votes if v.proposal_id != top_id]
|
|
240
|
+
else:
|
|
241
|
+
dissenters = [p.agent_id for p in proposals if p.proposal_id != top_id]
|
|
242
|
+
|
|
243
|
+
return ArbitrationResult(
|
|
244
|
+
selected_proposal=prop_map[top_id],
|
|
245
|
+
consensus_reached=True,
|
|
246
|
+
strategy_used=active_strategy,
|
|
247
|
+
confidence_score=top_ratio,
|
|
248
|
+
vote_distribution=tally,
|
|
249
|
+
dissenting_agents=dissenters,
|
|
250
|
+
reasoning=f"Consensus reached under {active_strategy.value} (ratio: {top_ratio:.2f})",
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
return ArbitrationResult(
|
|
254
|
+
selected_proposal=None,
|
|
255
|
+
consensus_reached=False,
|
|
256
|
+
strategy_used=active_strategy,
|
|
257
|
+
confidence_score=top_ratio,
|
|
258
|
+
vote_distribution=tally,
|
|
259
|
+
reasoning=f"Threshold not met: {top_ratio:.2f} < {req_threshold:.2f}",
|
|
260
|
+
)
|