File size: 11,149 Bytes
1eab213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# 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()