File size: 10,338 Bytes
18535e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import asyncio
import json
import time
from dataclasses import dataclass, asdict
from pathlib import Path
from typing import Any, Literal

from pydantic import BaseModel, Field

from autonomy_engine import AutonomyMissionRequest, autonomy_status, build_mission


STATE_DIR = Path(__import__("os").environ.get("V2_STATE_DIR", "/app/runtime"))
BRAIN_DIR = STATE_DIR / "execution_brain"
BRAIN_DIR.mkdir(parents=True, exist_ok=True)

BrainMode = Literal["assist", "prepare", "execute"]
BudgetProfile = Literal["tiny", "balanced", "aggressive"]


@dataclass(frozen=True)
class QualityGate:
    name: str
    passed: bool
    detail: str
    severity: str = "info"


class BrainRequest(BaseModel):
    objective: str = Field(min_length=8)
    mode: BrainMode = "prepare"
    budget_profile: BudgetProfile = "tiny"
    platforms: list[str] = Field(default_factory=list)
    max_tasks: int = Field(default=5, ge=1, le=20)
    auto_run_ready_tasks: bool = False
    include_setup_tasks: bool = True
    require_verification_before_user_brief: bool = True


BUDGETS: dict[BudgetProfile, dict[str, Any]] = {
    "tiny": {
        "max_tasks": 5,
        "max_external_side_effects": 0,
        "gas_hard_ceiling_usd": 0.08,
        "default_mode": "prepare",
        "description": "Lowest-cost mode. Prefer read-only checks, report generation, and queues.",
    },
    "balanced": {
        "max_tasks": 10,
        "max_external_side_effects": 3,
        "gas_hard_ceiling_usd": 0.08,
        "default_mode": "execute",
        "description": "Run ready API-backed work while still queueing uncertain or human-blocked actions.",
    },
    "aggressive": {
        "max_tasks": 20,
        "max_external_side_effects": 8,
        "gas_hard_ceiling_usd": 0.08,
        "default_mode": "execute",
        "description": "Maximize ready platform execution without bypassing auth, consent, KYC, CAPTCHA, or gas policy.",
    },
}


def _mode_to_autonomy_mode(mode: BrainMode) -> str:
    if mode == "assist":
        return "observe"
    if mode == "execute":
        return "execute"
    return "prepare"


def _quality_gates(request: BrainRequest, mission: dict[str, Any], status: dict[str, Any]) -> list[QualityGate]:
    budget = BUDGETS[request.budget_profile]
    tasks = mission.get("tasks", [])
    ready_tasks = [task for task in tasks if task.get("readiness") == "ready"]
    blocked_tasks = [task for task in tasks if task.get("readiness") == "blocked"]
    gates = [
        QualityGate(
            "objective_defined",
            bool(request.objective.strip()),
            "Objective is present and can be converted into platform tasks.",
        ),
        QualityGate(
            "budget_task_limit",
            len(tasks) <= min(request.max_tasks, budget["max_tasks"]),
            f"Mission has {len(tasks)} tasks; budget allows {min(request.max_tasks, budget['max_tasks'])}.",
            "error",
        ),
        QualityGate(
            "ready_or_actionable_tasks",
            bool(ready_tasks or (request.include_setup_tasks and tasks)),
            f"Ready tasks={len(ready_tasks)}, blocked tasks={len(blocked_tasks)}.",
            "warn",
        ),
        QualityGate(
            "human_blockers_explicit",
            all("human_blockers" in task for task in tasks),
            "Every task carries blocker metadata for MFA/CAPTCHA/KYC/consent/account challenges.",
        ),
        QualityGate(
            "gas_policy_preserved",
            budget["gas_hard_ceiling_usd"] <= 0.08,
            "Base gas hard ceiling remains <= $0.08.",
            "error",
        ),
        QualityGate(
            "autonomy_status_available",
            "platforms" in status and bool(status["platforms"]),
            f"Autonomy score={status.get('autonomy_score')} ready={status.get('ready_count')} partial={status.get('partial_count')} blocked={status.get('blocked_count')}.",
        ),
    ]
    if request.mode == "execute":
        gates.append(QualityGate(
            "execute_only_ready_tasks",
            all(task.get("readiness") == "ready" for task in tasks if task.get("can_execute_now")),
            "Execute mode only auto-runs tasks marked can_execute_now.",
            "error",
        ))
    return gates


def _can_share(gates: list[QualityGate]) -> bool:
    return all(gate.passed for gate in gates if gate.severity == "error")


def _user_brief(request: BrainRequest, mission: dict[str, Any], gates: list[QualityGate]) -> dict[str, Any]:
    ready = [task for task in mission.get("tasks", []) if task.get("readiness") == "ready"]
    partial = [task for task in mission.get("tasks", []) if task.get("readiness") == "partial"]
    blocked = [task for task in mission.get("tasks", []) if task.get("readiness") == "blocked"]
    return {
        "mode": request.mode,
        "budget_profile": request.budget_profile,
        "objective": request.objective,
        "decision": "dispatch_ready_work" if ready and request.mode == "execute" else "prepare_and_queue" if ready or partial else "setup_required",
        "highest_probability_actions": [
            {"platform": task["platform"], "lane": task["lane"], "readiness": task["readiness"], "goal": task["goal"]}
            for task in (ready + partial)[: request.max_tasks]
        ],
        "blocked_actions": [
            {"platform": task["platform"], "missing_required": task.get("missing_required", []), "human_blockers": task.get("human_blockers", [])}
            for task in blocked
        ],
        "quality_gates": [asdict(gate) for gate in gates],
        "instructions": [
            "Use execute mode only when platform credentials/session and program handle are present.",
            "Use prepare mode to create reports and queue handoffs without irreversible external effects.",
            "Use assist mode for advisory planning and readiness review.",
            "MFA/CAPTCHA/KYC/consent/account challenges are blockers to report, not obstacles to bypass.",
            "Keep Base on-chain actions under the $0.08 hard gas ceiling; unknown gas blocks execution.",
        ],
    }


def build_brain_blueprint(request: BrainRequest) -> dict[str, Any]:
    status = autonomy_status()
    budget = BUDGETS[request.budget_profile]
    max_tasks = min(request.max_tasks, budget["max_tasks"])
    mission_request = AutonomyMissionRequest(
        mode=_mode_to_autonomy_mode(request.mode),
        platforms=request.platforms,
        max_tasks=max_tasks,
        objective=request.objective,
        include_signup_preparation=request.include_setup_tasks,
    )
    mission = build_mission(mission_request)
    gates = _quality_gates(request, mission, status)
    blueprint = {
        "brain_id": f"brain-{int(time.time())}",
        "created_at": time.time(),
        "request": request.model_dump(),
        "budget": budget,
        "autonomy_status": status,
        "mission": mission,
        "quality_gates": [asdict(gate) for gate in gates],
        "validated": _can_share(gates),
        "user_brief": _user_brief(request, mission, gates) if (not request.require_verification_before_user_brief or _can_share(gates)) else None,
    }
    (BRAIN_DIR / f"{blueprint['brain_id']}.json").write_text(json.dumps(blueprint, indent=2), encoding="utf-8")
    return blueprint


async def execute_brain_request(request: BrainRequest) -> dict[str, Any]:
    from tasks import create_task, update_task_plan, add_task_log
    from agents.commander import plan_task
    from orchestrator import run_task_async

    blueprint = build_brain_blueprint(request)
    if not blueprint["validated"]:
        return {"blueprint": blueprint, "created_tasks": [], "auto_run_tasks": [], "status": "blocked_by_quality_gate"}

    created_tasks = []
    auto_run_tasks = []
    for item in blueprint["mission"].get("tasks", []):
        if item.get("readiness") == "blocked" and not request.include_setup_tasks:
            continue
        task = create_task(item["goal"])
        plan = plan_task(item["goal"])
        update_task_plan(task.id, plan["plan"], plan["agents"])
        add_task_log(task.id, "execution_brain", "validated_dispatch", f"brain={blueprint['brain_id']} platform={item['platform']} readiness={item['readiness']} mode={request.mode}")
        record = {
            "task_id": task.id,
            "platform": item["platform"],
            "lane": item["lane"],
            "readiness": item["readiness"],
            "bounty_id": task.bounty_id,
            "tags": task.tags,
        }
        created_tasks.append(record)
        if request.mode == "execute" and request.auto_run_ready_tasks and item.get("can_execute_now"):
            asyncio.create_task(run_task_async(task.id, task.goal))
            auto_run_tasks.append(record)
    return {"blueprint": blueprint, "created_tasks": created_tasks, "auto_run_tasks": auto_run_tasks, "status": "dispatched"}


def list_brain_runs(limit: int = 25) -> dict[str, Any]:
    runs = []
    for path in sorted(BRAIN_DIR.glob("brain-*.json"), key=lambda item: item.stat().st_mtime, reverse=True)[:limit]:
        try:
            runs.append(json.loads(path.read_text(encoding="utf-8")))
        except Exception:
            pass
    return {"runs": runs, "total": len(runs), "brain_dir": str(BRAIN_DIR)}


def register_brain_routes(app) -> None:
    @app.get("/api/v2/brain/runs")
    async def get_brain_runs(limit: int = 25) -> dict[str, Any]:
        return list_brain_runs(limit=limit)

    @app.get("/api/v2/brain/status")
    async def get_brain_status() -> dict[str, Any]:
        return {
            "budgets": BUDGETS,
            "contract": {
                "execution_first": "plan internally, validate utility/readiness/budget/risk, then dispatch eligible work",
                "share_after_validation": "user_brief is returned only after hard quality gates pass unless explicitly disabled",
                "assistance_mode": "assist mode creates an iron-clad brief without dispatching tasks",
            },
        }

    @app.post("/api/v2/brain/blueprint")
    async def create_brain_blueprint(request: BrainRequest) -> dict[str, Any]:
        return build_brain_blueprint(request)

    @app.post("/api/v2/brain/execute")
    async def execute_brain(request: BrainRequest) -> dict[str, Any]:
        return await execute_brain_request(request)