pec5d-module / pec5d /api /routes.py
Codexcoder's picture
pec5d: add pec5d/api/routes.py
1eab213 verified
Raw History Blame
11.1 kB
# pec5d/api/routes.py
"""
PEC5D Full Evolution β€” API endpoints under /api/v1/pec5d/*.
Lazy singleton boot: POST /initialize brings up the full hierarchy
(cores, memory, subconscious, sandbox, pattern bridge, IPT, sensor,
coral line, agency, chamber); other endpoints 503 until then.
"""
from __future__ import annotations
import time
from typing import Any, Dict, List, Optional
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
router = APIRouter(prefix="/api/v1/pec5d", tags=["pec5d"])
# ── Lazy singletons ───────────────────────────────────────────────────────
hierarchy = None
memory = None
subconscious = None
sandbox = None
bridge = None
ipt = None
sensor = None
chamber = None
INITIALIZED_AT = None
class PatternIn(BaseModel):
source: str = "signal"
signal: Dict[str, Any] = Field(default_factory=dict)
class ComputeIn(BaseModel):
vector: List[float]
class ProposalIn(BaseModel):
title: str
body: str
proposer: str = "agency"
# ── Lifecycle ─────────────────────────────────────────────────────────────
@router.post("/initialize")
async def initialize_pec5d() -> Dict[str, Any]:
"""Boot the full PEC5D hierarchy (idempotent)."""
global hierarchy, memory, subconscious, sandbox, bridge
global ipt, sensor, chamber, INITIALIZED_AT
if hierarchy is None:
from pec5d.core import CoreHierarchy
from pec5d.holographic_memory import HolographicMemory
from pec5d.subconscious_nexus import SubconsciousNexus
from pec5d.sandbox import Sandbox
from pec5d.pattern_bridge import PatternBridge
from pec5d.ipt import InvisiblePressureTheory
from pec5d.ipt_sensor import IPTSensor
from pec5d.agency import ZenithChamber
hierarchy = CoreHierarchy()
hierarchy.initialize()
memory = HolographicMemory().initialize()
subconscious = SubconsciousNexus().initialize()
sandbox = Sandbox().initialize()
bridge = PatternBridge().initialize()
ipt = InvisiblePressureTheory().initialize()
sensor = IPTSensor("mini").initialize()
chamber = ZenithChamber().initialize()
INITIALIZED_AT = time.time()
return {
"status": "initialized",
"version": "∞.0.0",
"hierarchy": hierarchy.status(),
"memory": memory.get_state(),
"subconscious": subconscious.get_state(),
"sandbox": sandbox.get_state(),
"pattern_bridge": bridge.get_state(),
"ipt": ipt.get_state(),
"sensor": sensor.get_state(),
"chamber": chamber.get_state(),
}
# ── Hierarchy / cores ─────────────────────────────────────────────────────
@router.get("/status")
async def pec5d_status() -> Dict[str, Any]:
if hierarchy is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return {
"version": "∞.0.0",
"hierarchy": hierarchy.status(),
"memory": memory.get_state(),
"subconscious": subconscious.get_state(),
"sandbox": sandbox.get_state(),
"pattern_bridge": bridge.get_state(),
"ipt": ipt.get_state(),
"sensor": sensor.get_state(),
}
@router.get("/cores")
async def list_cores() -> Dict[str, Any]:
if hierarchy is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return hierarchy.status()
@router.get("/cores/{name}")
async def get_core(name: str) -> Dict[str, Any]:
if hierarchy is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
try:
core = hierarchy.get_core(name)
except KeyError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
return core.get_state()
# ── Memory ────────────────────────────────────────────────────────────────
@router.get("/memory")
async def memory_state() -> Dict[str, Any]:
if memory is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return memory.get_state()
@router.post("/memory/write")
async def memory_write(body: Dict[str, Any]) -> Dict[str, Any]:
if memory is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
layer = int(body.get("layer", 1))
key = body.get("key", f"mem_{time.time():.0f}")
value = body.get("value")
try:
return memory.write(layer, key, value)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
# ── Subconscious ──────────────────────────────────────────────────────────
@router.get("/subconscious")
async def subconscious_state() -> Dict[str, Any]:
if subconscious is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return subconscious.get_state()
@router.post("/subconscious/scan")
async def subconscious_scan() -> Dict[str, Any]:
if subconscious is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return subconscious.scan()
# ── Sandbox ───────────────────────────────────────────────────────────────
@router.get("/sandbox")
async def sandbox_state() -> Dict[str, Any]:
if sandbox is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return sandbox.get_state()
@router.post("/sandbox/spawn")
async def sandbox_spawn(body: Dict[str, Any]) -> Dict[str, Any]:
if sandbox is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
module = body.get("module", "quantum_testbed")
try:
state = sandbox.spawn(module, body.get("config"))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return state.to_dict()
# ── Pattern bridge ────────────────────────────────────────────────────────
@router.post("/bridge/detect")
async def bridge_detect(body: PatternIn) -> Dict[str, Any]:
"""Detect β†’ synthesize β†’ validate β†’ deploy an emerged pattern."""
if bridge is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
pattern = bridge.detect(body.source, body.signal)
bridge.synthesize(pattern, module_name=body.source)
validation = bridge.validate(pattern, coherence=float(body.signal.get("coherence", 0.9)))
deployment = bridge.deploy(pattern) if validation.get("validated") else None
return {"pattern": pattern.to_dict(), "validation": validation, "deployment": deployment}
@router.get("/bridge")
async def bridge_state() -> Dict[str, Any]:
if bridge is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return bridge.get_state()
# ── IPT ───────────────────────────────────────────────────────────────────
@router.get("/ipt")
async def ipt_state() -> Dict[str, Any]:
if ipt is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return ipt.get_state()
@router.post("/ipt/pipeline")
async def ipt_pipeline(body: Dict[str, Any]) -> Dict[str, Any]:
if ipt is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return ipt.run_pipeline(body)
@router.post("/ipt/gradient")
async def ipt_gradient() -> Dict[str, Any]:
if ipt is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
import numpy as np
rng = np.random.default_rng()
return ipt.pressure_gradient(rng.random(5) + 0.1, rng.random(5) + 0.1)
@router.get("/sensor")
async def sensor_state() -> Dict[str, Any]:
if sensor is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return sensor.get_state()
@router.post("/sensor/read")
async def sensor_read() -> Dict[str, Any]:
if sensor is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return sensor.read()
# ── Coral ─────────────────────────────────────────────────────────────────
@router.get("/coral")
async def coral_products() -> Dict[str, Any]:
"""Coral product line index."""
if hierarchy is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
from pec5d.coral import CORAL_PRODUCTS
return {"products": list(CORAL_PRODUCTS.keys())}
@router.post("/coral/{product}/operate")
async def coral_operate(product: str) -> Dict[str, Any]:
"""Operate a coral product (drone/spacecraft/bio_chip/home)."""
if hierarchy is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
from pec5d.coral import CORAL_PRODUCTS
cls = CORAL_PRODUCTS.get(product)
if cls is None:
raise HTTPException(status_code=404, detail=f"unknown coral product '{product}'")
instance = cls().initialize()
if product == "drone":
return instance.deploy_mission()
if product == "spacecraft":
return instance.mission()
if product == "bio_chip":
return instance.compute([1.0, 1.618, 2.0])
return instance.design()
# ── Agency & chamber ──────────────────────────────────────────────────────
@router.post("/chamber/propose")
async def chamber_propose(body: ProposalIn) -> Dict[str, Any]:
if chamber is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return chamber.submit_proposal(body.title, body.body, body.proposer)
@router.post("/chamber/vote/{proposal_id}")
async def chamber_vote(proposal_id: str) -> Dict[str, Any]:
if chamber is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
result = chamber.resonance_vote(proposal_id)
if "error" in result:
raise HTTPException(status_code=404, detail=result["error"])
return result
@router.get("/chamber")
async def chamber_state() -> Dict[str, Any]:
if chamber is None:
raise HTTPException(status_code=503, detail="PEC5D not initialized")
return chamber.get_state()