Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gateway/app/core/blob.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ async def url(self, key: str) -> str:
)


@lru_cache()
@lru_cache
def get_blob_backend() -> BlobBackend:
"""Resolve the configured blob backend. Cached per-process."""
backend_name = os.environ.get("BLOB_BACKEND", "local").strip().lower()
Expand Down
2 changes: 1 addition & 1 deletion gateway/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ def _validate_exchange_rate(cls, value: Decimal) -> Decimal:
)


@lru_cache()
@lru_cache
def get_settings() -> Settings:
return Settings()

Expand Down
26 changes: 13 additions & 13 deletions gateway/app/core/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from ..services.oracle_broadcast import OracleBroadcastEngine


@lru_cache()
@lru_cache
def get_iot_bridge() -> ProtocolBridge:
"""Singleton IoT Protocol Bridge with ACL engine and MQTT translator."""
# Settings are read per call, not from a module-level singleton: tests and
Expand All @@ -37,7 +37,7 @@ def get_iot_bridge() -> ProtocolBridge:
return bridge


@lru_cache()
@lru_cache
def get_autonomous_pm() -> AutonomousPM:
"""Singleton Autonomous Product Manager with event store and anomaly detector."""
settings = get_settings()
Expand All @@ -48,67 +48,67 @@ def get_autonomous_pm() -> AutonomousPM:
)


@lru_cache()
@lru_cache
def get_media_engine() -> MediaEngine:
"""Singleton Programmatic Media Engine with full pipeline."""
return MediaEngine()


@lru_cache()
@lru_cache
def get_agent_comms() -> AgentComms:
"""Singleton Agent Communications with registry and message router."""
return AgentComms()


@lru_cache()
@lru_cache
def get_content_factory() -> ContentFactory:
"""Singleton Content Factory with format adapters and algorithmic scheduler."""
return ContentFactory()


@lru_cache()
@lru_cache
def get_red_team_swarm() -> RedTeamSwarm:
"""Singleton Red Team Security Swarm with attack engine and scan store."""
return RedTeamSwarm()


@lru_cache()
@lru_cache
def get_agent_oracle() -> AgentOracle:
"""Singleton Agent Oracle with crawler, indexer, and registration engine."""
return AgentOracle()


@lru_cache()
@lru_cache
def get_agent_money() -> AgentMoney:
"""Singleton Agent Money engine with wallets, metering, and arbitrage."""
return AgentMoney()


@lru_cache()
@lru_cache
def get_protocol_engine() -> ProtocolEngine:
"""Singleton Protocol Generation Engine — code-to-discovery pipeline."""
return ProtocolEngine()


@lru_cache()
@lru_cache
def get_rtaas_engine() -> RTaaSEngine:
"""Singleton Red-Team-as-a-Service engine."""
return RTaaSEngine()


@lru_cache()
@lru_cache
def get_sandbox_engine() -> SandboxEngine:
"""Singleton Interactive Testing Sandbox engine."""
return SandboxEngine()


@lru_cache()
@lru_cache
def get_telemetry_scope() -> TelemetryScope:
"""Singleton Telemetry Scoping engine — multi-tenant autonomous PM."""
return TelemetryScope()


@lru_cache()
@lru_cache
def get_broadcast_engine() -> OracleBroadcastEngine:
"""Singleton Oracle Broadcast — pushes APIs into agent directories."""
return OracleBroadcastEngine(oracle_service=get_agent_oracle())
2 changes: 1 addition & 1 deletion gateway/app/core/durable_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@ async def close(self) -> None:
self._backend = "memory"


@lru_cache()
@lru_cache
def get_durable_state() -> DurableStateStore:
return DurableStateStore()

Expand Down
2 changes: 1 addition & 1 deletion gateway/app/core/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async def _run_check(
start = time.monotonic()
try:
result = await asyncio.wait_for(check(), timeout=CHECK_TIMEOUT_SECONDS)
except asyncio.TimeoutError:
except TimeoutError:
result = {
"status": "down",
"error": f"timeout after {CHECK_TIMEOUT_SECONDS}s",
Expand Down
4 changes: 2 additions & 2 deletions gateway/app/db/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ def _normalize_bind_parameters(parameters: Any) -> Any:
to_naive_utc(value) if isinstance(value, datetime) else value
for value in parameters
]
if all(a is b for a, b in zip(rewritten_seq, parameters)):
if all(a is b for a, b in zip(rewritten_seq, parameters, strict=True)):
return parameters
return tuple(rewritten_seq) if isinstance(parameters, tuple) else rewritten_seq
return parameters
Expand Down Expand Up @@ -243,7 +243,7 @@ def _coerce_naive_utc( # noqa: ANN001, ANN202
):
if executemany and isinstance(parameters, (list, tuple)):
normalized = [_normalize_bind_parameters(p) for p in parameters]
if all(a is b for a, b in zip(normalized, parameters)):
if all(a is b for a, b in zip(normalized, parameters, strict=True)):
return statement, parameters
return statement, normalized
return statement, _normalize_bind_parameters(parameters)
Expand Down
6 changes: 3 additions & 3 deletions gateway/app/optimizer/planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,17 +97,17 @@ def _greedy_heuristic(
total_risk = 0.0
for action in scored:
c = action.get("credit_cost", 0.0)
l = action.get("latency_ms", 0.0)
latency_ms = action.get("latency_ms", 0.0)
r = action.get("risk_score", 0.0)
if total_cost + c > state.remaining_budget:
continue
if total_latency + l > state.slo_window_seconds * 1000:
if total_latency + latency_ms > state.slo_window_seconds * 1000:
continue
if total_risk + r > risk_budget:
continue
selected.append(action)
total_cost += c
total_latency += l
total_latency += latency_ms
total_risk += r
if len(selected) >= max_actions:
break
Expand Down
5 changes: 3 additions & 2 deletions gateway/app/routers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,8 +446,9 @@ class ToolCallResponse(BaseModel):
"""MCP tool call response."""

content: list[dict[str, Any]]
isError: bool = False
structuredContent: dict[str, Any] | None = None
# MCP tool-result field names are camelCase on the wire.
isError: bool = False # noqa: N815
structuredContent: dict[str, Any] | None = None # noqa: N815
receipt: dict[str, Any] | None = None


Expand Down
4 changes: 2 additions & 2 deletions gateway/app/routers/preflight.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
wallet-scoped tenant key is refused with 403 admin_access_denied.
"""

from fastapi import APIRouter, Depends
from fastapi import APIRouter, Body, Depends
from pydantic import BaseModel, Field
from datetime import datetime

Expand Down Expand Up @@ -91,7 +91,7 @@ class PreflightResponse(BaseModel):
),
)
async def run_preflight(
request: PreflightRequest = PreflightRequest(),
request: PreflightRequest = Body(default_factory=PreflightRequest),
auth: AuthContext = Depends(get_auth_context),
):
# The report is operator configuration, not tenant data: a wallet-scoped
Expand Down
26 changes: 13 additions & 13 deletions gateway/app/schemas/optimizer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import math
from typing import Annotated, Any, Dict, List, Literal, Optional
from typing import Annotated, Any, Literal, Optional

from pydantic import BaseModel, Field, field_validator

Expand Down Expand Up @@ -37,16 +37,16 @@ class OptimizerState(BaseModel):
daily_spend_used: float = Field(..., ge=0, allow_inf_nan=False)
daily_limit: float = Field(..., ge=0, allow_inf_nan=False)
rate_limit_headroom: float = Field(..., ge=0, le=1, allow_inf_nan=False)
service_health: Dict[str, Literal["healthy", "degraded", "down"]]
simulation_flags: Dict[str, bool]
auth_scope: List[str]
task_context: Dict
service_health: dict[str, Literal["healthy", "degraded", "down"]]
simulation_flags: dict[str, bool]
auth_scope: list[str]
task_context: dict
remaining_budget: float = Field(..., ge=0, allow_inf_nan=False)
slo_window_seconds: int = Field(30, ge=1)

@field_validator("task_context")
@classmethod
def _task_context_is_finite(cls, task_context: Dict) -> Dict:
def _task_context_is_finite(cls, task_context: dict) -> dict:
# task_context is untyped, but its candidate_actions carry the
# credit_cost / latency_ms / risk_score / expected_value / reliability
# the planner scores and budgets with. A NaN cost passes every budget
Expand All @@ -60,7 +60,7 @@ def _task_context_is_finite(cls, task_context: Dict) -> Dict:

class OptimizerRequest(BaseModel):
state: OptimizerState
objective_overrides: Optional[Dict[str, FiniteFloat]] = None
objective_overrides: Optional[dict[str, FiniteFloat]] = None
max_actions: Optional[int] = Field(default=5, ge=1)
require_real_effects: bool = False

Expand All @@ -70,10 +70,10 @@ class OptimizerResponse(BaseModel):
# solver was never a declared dependency). Selection is the deterministic
# greedy heuristic, so these are the two statuses the planner can emit.
status: Literal["HeuristicFallback", "Infeasible"]
selected_actions: List[Dict]
rejected_actions: List[Dict]
policy_reasons: Dict[str, str]
selected_actions: list[dict]
rejected_actions: list[dict]
policy_reasons: dict[str, str]
expected_utility: float
totals: Dict[str, float]
constraint_margins: Dict[str, float]
governance: Optional[Dict] = None
totals: dict[str, float]
constraint_margins: dict[str, float]
governance: Optional[dict] = None
2 changes: 1 addition & 1 deletion gateway/app/schemas/red_team.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ class ScanRequest(BaseModel):
description="Which service pillars to attack. Default: all.",
)
attack_categories: list[AttackCategory] = Field(
default=[c for c in AttackCategory],
default=list(AttackCategory),
description="Which attack vectors to deploy. Default: all.",
)
intensity: str = Field(
Expand Down
6 changes: 3 additions & 3 deletions gateway/app/services/awi_rag_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -744,7 +744,7 @@ def _extract_entities(
if isinstance(entity, str)
)

return sorted(list(entities))[:100]
return sorted(entities)[:100]

def _infer_session_type(
self,
Expand Down Expand Up @@ -886,7 +886,7 @@ def _cosine_similarity(self, a: list[float], b: list[float]) -> float:
if len(a) != len(b):
return 0.0

dot_product = sum(x * y for x, y in zip(a, b))
dot_product = sum(x * y for x, y in zip(a, b, strict=True))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(x * x for x in b))

Expand Down Expand Up @@ -937,7 +937,7 @@ def _suggest_actions(

suggested = []

for action, score in sorted_actions[:5]:
for action, _score in sorted_actions[:5]:
if action not in suggested:
suggested.append(action)

Expand Down
6 changes: 3 additions & 3 deletions gateway/app/services/behavioral_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ async def execute_tool(
if request.dry_run:
execution.cost_estimate = result.get("cost_estimate", 0.0)

except asyncio.TimeoutError:
except TimeoutError:
execution.status = ExecutionStatus.TIMEOUT
execution.error = f"Execution timed out after {env.timeout_seconds}s"
except Exception as e:
Expand Down Expand Up @@ -472,7 +472,7 @@ async def _execute_python_docker(
stdout, stderr = await asyncio.wait_for(
proc.communicate(), timeout=timeout_seconds
)
except asyncio.TimeoutError:
except TimeoutError:
proc.kill()
await proc.wait()
return {
Expand Down Expand Up @@ -534,7 +534,7 @@ async def _execute_python_host(
stdout, stderr = await asyncio.wait_for(
proc.communicate(), timeout=timeout_seconds
)
except asyncio.TimeoutError:
except TimeoutError:
proc.kill()
await proc.wait()
return {
Expand Down
2 changes: 1 addition & 1 deletion gateway/app/services/content_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -1170,7 +1170,7 @@ async def launch_campaign(
)
schedule_summary = {
"total_scheduled": len(recommendations),
"platforms": list(set(r.platform for r in recommendations)),
"platforms": list({r.platform for r in recommendations}),
"date_range": (
f"{recommendations[0].recommended_time.strftime('%Y-%m-%d')} to "
f"{recommendations[-1].recommended_time.strftime('%Y-%m-%d')}"
Expand Down
2 changes: 1 addition & 1 deletion gateway/app/services/mcp_dispatch_attempts.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ async def count_duplicate_denial_receipts() -> tuple[int | None, str | None]:
_query_duplicate_denial_receipts(),
timeout=DUPLICATE_DENIAL_COUNT_TIMEOUT_SECONDS,
)
except (RuntimeError, SQLAlchemyError, asyncio.TimeoutError) as exc:
except (TimeoutError, RuntimeError, SQLAlchemyError) as exc:
logger.warning("duplicate_denial_count_unavailable: %s", type(exc).__name__)
return None, type(exc).__name__
return count, None
Expand Down
2 changes: 1 addition & 1 deletion gateway/app/services/media_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ async def _generate_synthetic_hooks(self, video: StoredVideo) -> list[ViralHook]
("retention_signal", "Strong opening hook with pattern interrupt"),
]

for i in range(num_hooks):
for _ in range(num_hooks):
start = random.uniform(0, max(0, duration - self._max_hook_duration))
hook_dur = random.uniform(self._min_hook_duration, self._max_hook_duration)
trigger = random.choice(trigger_types)
Expand Down
4 changes: 3 additions & 1 deletion gateway/app/services/pods.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,9 @@ async def create_pod(
)

provisioned: list[ProvisionedMember] = []
for member, member_budget in zip(members, member_budgets):
for member, member_budget in zip(
members, member_budgets, strict=True
):
agent_id_in_flight = (
member.agent_id or f"pod-member-{len(provisioned)}"
)
Expand Down
4 changes: 1 addition & 3 deletions gateway/app/services/receipts.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import json
import re
import uuid
from decimal import Decimal
Expand Down Expand Up @@ -65,9 +66,6 @@ class ReceiptWriteContendedError(RuntimeError):
reason = "receipt_write_contended"


import json


def _loads_dict(value: str | None) -> dict[str, Any]:
try:
decoded = json.loads(value or "{}")
Expand Down
2 changes: 1 addition & 1 deletion gateway/app/services/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ def _evaluate_action(
if action_type == "submit_transform":
# Check if agent guessed the transformation rule
guess = str(action_value).lower()
for rule in env.hidden_rules:
for _rule in env.hidden_rules:
if any(
keyword in guess
for keyword in [
Expand Down
2 changes: 1 addition & 1 deletion gateway/app/services/telemetry_pm.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ async def _detect_error_spike(self, owner: str | None) -> AnomalyCandidate | Non
)

if baseline_rate > 0 and recent_rate > baseline_rate * 3:
sources = set(se.event.source for se in recent_errors)
sources = {se.event.source for se in recent_errors}
return AnomalyCandidate(
category="error_spike",
severity=Severity.HIGH,
Expand Down
Loading
Loading