Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat: MUCIZEWORK MASTER ENGINE v4.0 — BLACK mode
- FastAPI API (port 5002): /status, /graph, /events, /db, /health
- Engine core: graph state, event logging, wallet/flow/position DB
- Storage: JSON-based persistent state (graph, events, db)
- Scripts: health_check.py, start.sh, start.ps1
- Config: BLACK mode, MZC_GRAPH=ACTIVE
  • Loading branch information
devin-ai-integration[bot] committed Jun 22, 2026
commit 13972189041e116a6170d3a7a8342f558db8a853
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.env
__pycache__/
*.pyc
.venv/
venv/
*.egg-info/
dist/
build/
.pytest_cache/
storage/logs/events.json
storage/state/
167 changes: 167 additions & 0 deletions api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
"""
MUCIZEWORK MASTER API — v4.0 BLACK
Port: 5002 | Endpoints: /status, /graph, /events, /db
"""

import os
from typing import Any, Optional

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn

from engine import MucizeEngine

load_dotenv()

MZC_MODE = os.getenv("MZC_MODE", "BLACK")
MZC_PORT = int(os.getenv("MZC_PORT", "5002"))

app = FastAPI(
title="MUCIZEWORK MASTER ENGINE",
version="4.0",
description="Merkezi motor API — graph, event ve veri yönetimi",
)

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)

engine = MucizeEngine()


# =========================
# Pydantic request models
# =========================

class NodeInput(BaseModel):
node_id: str
data: dict[str, Any]


class EdgeInput(BaseModel):
source: str
target: str
weight: float = 1.0


class EventInput(BaseModel):
event_type: str
payload: dict[str, Any]


class WalletInput(BaseModel):
wallet_id: str
data: dict[str, Any]


class FlowInput(BaseModel):
source: str
target: str
amount: float
token: str = "MZC"


class PositionInput(BaseModel):
protocol: str
asset: str
amount: float
chain: str = "ethereum"


# =========================
# Status
# =========================

@app.get("/status")
async def get_status():
return engine.status()


# =========================
# Graph endpoints
# =========================

@app.get("/graph")
async def get_graph():
return engine.get_graph()


@app.post("/graph/node")
async def add_node(body: NodeInput):
node = engine.add_node(body.node_id, body.data)
return {"ok": True, "node": node}


@app.delete("/graph/node/{node_id}")
async def remove_node(node_id: str):
removed = engine.remove_node(node_id)
if not removed:
raise HTTPException(status_code=404, detail=f"Node '{node_id}' bulunamadi")
return {"ok": True, "removed": node_id}


@app.post("/graph/edge")
async def add_edge(body: EdgeInput):
edge = engine.add_edge(body.source, body.target, body.weight)
return {"ok": True, "edge": edge}


# =========================
# Events
# =========================

@app.get("/events")
async def get_events(limit: int = Query(default=50, ge=1, le=500)):
return engine.get_events(limit=limit)


@app.post("/events")
async def post_event(body: EventInput):
event = engine.log_custom_event(body.event_type, body.payload)
return {"ok": True, "event": event}


# =========================
# DB endpoints
# =========================

@app.get("/db")
async def get_db():
return engine.get_db()


@app.post("/db/wallet")
async def add_wallet(body: WalletInput):
wallet = engine.add_wallet(body.wallet_id, body.data)
return {"ok": True, "wallet": wallet}


@app.post("/db/flow")
async def add_flow(body: FlowInput):
flow = engine.add_flow(body.model_dump())
return {"ok": True, "flow": flow}


@app.post("/db/position")
async def add_position(body: PositionInput):
position = engine.add_position(body.model_dump())
return {"ok": True, "position": position}


# =========================
# Health
# =========================

@app.get("/health")
async def health():
return {"status": "alive", "mode": MZC_MODE, "port": MZC_PORT}


if __name__ == "__main__":
uvicorn.run("api:app", host="0.0.0.0", port=MZC_PORT, reload=True)
Empty file added core/__init__.py
Empty file.
6 changes: 6 additions & 0 deletions core/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"engine": "MUCIZEWORK",
"version": "4.0",
"mode": "BLACK",
"status": "ACTIVE"
}
3 changes: 3 additions & 0 deletions engine/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from engine.core import MucizeEngine

__all__ = ["MucizeEngine"]
157 changes: 157 additions & 0 deletions engine/core.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
"""
MUCIZEWORK Engine Core — Graph state, event logging, DB yönetimi.
"""

import json
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional


STORAGE_DIR = Path(__file__).resolve().parent.parent / "storage"


class MucizeEngine:
"""Merkezi motor: graph state, events ve db yönetimi."""

def __init__(self, config_path: Optional[Path] = None):
self.config_path = config_path or (
Path(__file__).resolve().parent.parent / "core" / "config.json"
)
self.config = self._load_json(self.config_path)
self.graph_path = STORAGE_DIR / "graph" / "graph_state.json"
self.events_path = STORAGE_DIR / "logs" / "events.json"
self.db_path = STORAGE_DIR / "db" / "db.json"
self.state_path = STORAGE_DIR / "state"

self.graph = self._load_json(self.graph_path)
self.events: list[dict[str, Any]] = self._load_json(self.events_path)
self.db = self._load_json(self.db_path)

# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------

@staticmethod
def _load_json(path: Path) -> Any:
with open(path, "r", encoding="utf-8") as fh:
return json.load(fh)

@staticmethod
def _save_json(path: Path, data: Any) -> None:
with open(path, "w", encoding="utf-8") as fh:
json.dump(data, fh, indent=2, ensure_ascii=False, default=str)

def _now(self) -> str:
return datetime.now(timezone.utc).isoformat()

# ------------------------------------------------------------------
# Status
# ------------------------------------------------------------------

def status(self) -> dict[str, Any]:
return {
"engine": self.config.get("engine"),
"version": self.config.get("version"),
"mode": self.config.get("mode"),
"status": self.config.get("status"),
"graph_nodes": len(self.graph.get("nodes", {})),
"graph_edges": len(self.graph.get("edges", [])),
"event_count": len(self.events),
"timestamp": self._now(),
}

# ------------------------------------------------------------------
# Graph operations
# ------------------------------------------------------------------

def get_graph(self) -> dict[str, Any]:
return self.graph

def add_node(self, node_id: str, data: dict[str, Any]) -> dict[str, Any]:
self.graph["nodes"][node_id] = {
"data": data,
"created": self._now(),
}
self.graph["updated"] = self._now()
self._save_json(self.graph_path, self.graph)
self._log_event("NODE_ADDED", {"node_id": node_id})
return self.graph["nodes"][node_id]

def remove_node(self, node_id: str) -> bool:
if node_id not in self.graph["nodes"]:
return False
del self.graph["nodes"][node_id]
self.graph["edges"] = [
e
for e in self.graph["edges"]
if e.get("source") != node_id and e.get("target") != node_id
]
self.graph["updated"] = self._now()
self._save_json(self.graph_path, self.graph)
self._log_event("NODE_REMOVED", {"node_id": node_id})
return True

def add_edge(self, source: str, target: str, weight: float = 1.0) -> dict[str, Any]:
edge = {
"source": source,
"target": target,
"weight": weight,
"created": self._now(),
}
self.graph["edges"].append(edge)
self.graph["updated"] = self._now()
self._save_json(self.graph_path, self.graph)
self._log_event("EDGE_ADDED", {"source": source, "target": target})
return edge

# ------------------------------------------------------------------
# Event log
# ------------------------------------------------------------------

def _log_event(self, event_type: str, payload: dict[str, Any]) -> dict[str, Any]:
event = {
"type": event_type,
"payload": payload,
"timestamp": self._now(),
}
self.events.append(event)
self._save_json(self.events_path, self.events)
return event

def get_events(self, limit: int = 50) -> list[dict[str, Any]]:
return self.events[-limit:]

def log_custom_event(self, event_type: str, payload: dict[str, Any]) -> dict[str, Any]:
return self._log_event(event_type, payload)

# ------------------------------------------------------------------
# DB operations (wallets, flows, positions)
# ------------------------------------------------------------------

def get_db(self) -> dict[str, Any]:
return self.db

def add_wallet(self, wallet_id: str, data: dict[str, Any]) -> dict[str, Any]:
self.db["wallets"][wallet_id] = {
"data": data,
"added": self._now(),
}
self._save_json(self.db_path, self.db)
self._log_event("WALLET_ADDED", {"wallet_id": wallet_id})
return self.db["wallets"][wallet_id]

def add_flow(self, flow: dict[str, Any]) -> dict[str, Any]:
record = {**flow, "recorded": self._now()}
self.db["flows"].append(record)
self._save_json(self.db_path, self.db)
self._log_event("FLOW_RECORDED", {"flow": flow})
return record

def add_position(self, position: dict[str, Any]) -> dict[str, Any]:
record = {**position, "recorded": self._now()}
self.db["positions"].append(record)
self._save_json(self.db_path, self.db)
self._log_event("POSITION_ADDED", {"position": position})
return record
Empty file added modules/__init__.py
Empty file.
6 changes: 6 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
fastapi>=0.110.0
uvicorn>=0.29.0
python-dotenv>=1.0.0
pydantic>=2.6.0
requests>=2.31.0
httpx>=0.27.0
12 changes: 12 additions & 0 deletions scripts/health_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import requests

BASE = "http://127.0.0.1:5002"

endpoints = ["/status", "/graph", "/events"]

for e in endpoints:
try:
r = requests.get(BASE + e)
print(e, r.status_code, r.text[:80])
except Exception as ex:
print(e, "ERROR", ex)
2 changes: 2 additions & 0 deletions start.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
cd C:\Users\enver\mzc-engine-v3
python api.py
3 changes: 3 additions & 0 deletions start.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
cd "$(dirname "$0")"
python api.py
5 changes: 5 additions & 0 deletions storage/db/db.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"wallets": {},
"flows": [],
"positions": []
}
5 changes: 5 additions & 0 deletions storage/graph/graph_state.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"nodes": {},
"edges": [],
"updated": null
}