74 lines
2.2 KiB
Python
74 lines
2.2 KiB
Python
"""Contracts module for CosmosMesh MVP tests.
|
|
|
|
This module provides minimal, test-friendly data structures for LocalProblem
|
|
and a small registry facade GraphOfContracts. The goal is to satisfy unit tests
|
|
without pulling in heavy dependencies.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from dataclasses import dataclass, field
|
|
from typing import Any, Dict, Optional
|
|
|
|
|
|
@dataclass
|
|
class LocalProblem:
|
|
"""Minimal LocalProblem contract used by tests.
|
|
|
|
Attributes:
|
|
agent_id: Unique identifier for the agent describing the problem.
|
|
variables: Mapping of decision variables and their current values.
|
|
objective: Dict describing the objective (could be coefficients, type, etc).
|
|
constraints: Dict describing constraints (types and limits).
|
|
version: Protocol version of this contract payload.
|
|
"""
|
|
|
|
agent_id: str
|
|
variables: Dict[str, float] = field(default_factory=dict)
|
|
objective: Dict[str, Any] = field(default_factory=dict)
|
|
constraints: Dict[str, Any] = field(default_factory=dict)
|
|
version: str = "0.0.1"
|
|
|
|
def to_dict(self) -> Dict[str, Any]:
|
|
return {
|
|
"agent_id": self.agent_id,
|
|
"variables": self.variables,
|
|
"objective": self.objective,
|
|
"constraints": self.constraints,
|
|
"version": self.version,
|
|
}
|
|
|
|
def to_json(self) -> str:
|
|
return json.dumps(self.to_dict())
|
|
|
|
@classmethod
|
|
def from_json(cls, payload: str) -> "LocalProblem":
|
|
data = json.loads(payload)
|
|
return cls(
|
|
agent_id=data["agent_id"],
|
|
variables=data.get("variables", {}),
|
|
objective=data.get("objective", {}),
|
|
constraints=data.get("constraints", {}),
|
|
version=data.get("version", "0.0.1"),
|
|
)
|
|
|
|
|
|
class GraphOfContracts:
|
|
"""Tiny in-memory registry of contract names -> versions."""
|
|
|
|
def __init__(self) -> None:
|
|
self._registry: Dict[str, str] = {}
|
|
|
|
def register(self, name: str, version: str) -> None:
|
|
self._registry[name] = version
|
|
|
|
def get_version(self, name: str) -> Optional[str]:
|
|
return self._registry.get(name)
|
|
|
|
def to_json(self) -> str:
|
|
return json.dumps(self._registry)
|
|
|
|
|
|
__all__ = ["LocalProblem", "GraphOfContracts"]
|