File size: 10,145 Bytes
82bd569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce290f4
 
 
82bd569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce290f4
 
 
 
 
82bd569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce290f4
 
 
 
 
 
 
 
 
 
 
 
82bd569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce290f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82bd569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
```python
from fastapi import FastAPI, HTTPException, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
import sqlite3
import json
import os
from datetime import datetime
import uuid

# Import existing engines
from truth_engine import TruthEngine
from mind_layer_verdict_engine import MindVerdict
from soul_layer_spiritual_engine import SoulCore
from body_layer_api_executor import APIExecutor
from mostar_philosophy import CovenantFilter
from mostar_moments_log import log_event

# Import Mostly AI
from mostlyai.sdk import MostlyAI

app = FastAPI(title="Mostar Grid API", version="3.0.0")

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize engines
truth_engine = TruthEngine()
mind_verdict = MindVerdict()
soul_core = SoulCore()
api_executor = APIExecutor()
covenant_filter = CovenantFilter()

# Initialize Mostly AI
MOSTLY_AI_KEY = os.getenv("MOSTLY_AI_KEY", "INSERT_YOUR_API_KEY")
MOSTLY_BASE_URL = os.getenv("MOSTLY_BASE_URL", "https://app.mostly.ai")
mostly = MostlyAI(api_key=MOSTLY_AI_KEY, base_url=MOSTLY_BASE_URL)

# Database path
DB_PATH = "mostar.db"

# Create tables if they don't exist
def init_db():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    # Extend existing table with new columns
    try:
        cursor.execute("ALTER TABLE mind_verdicts ADD COLUMN truth_score REAL")
    except sqlite3.OperationalError:
        pass  # Column already exists
    
    try:
        cursor.execute("ALTER TABLE mind_verdicts ADD COLUMN soul_state TEXT")
    except sqlite3.OperationalError:
        pass  # Column already exists
    
    try:
        cursor.execute("ALTER TABLE mind_verdicts ADD COLUMN policy TEXT")
    except sqlite3.OperationalError:
        pass  # Column already exists
    
    # Create soulprints table if it doesn't exist
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS soulprints (
            id TEXT PRIMARY KEY,
            name TEXT,
            content TEXT,
            tags TEXT,
            created_at TEXT
        )
    """)
    
    # Create grid_training table
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS grid_training (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            dataset_id TEXT,
            generator_id TEXT,
            agent TEXT,
            record_count INTEGER,
            timestamp TEXT
        )
    """)
    
    conn.commit()
    conn.close()

init_db()

# Models
class DecisionRequest(BaseModel):
    query: str
    context: Optional[Dict[Any, Any]] = None

class DecisionResponse(BaseModel):
    verdict: Dict[Any, Any]
    truth_assessment: Dict[Any, Any]
    soul_insight: Dict[Any, Any]
    execution_result: Optional[Dict[Any, Any]] = None
    policy_alignment: str

class SoulPrintUpload(BaseModel):
    name: str
    content: str
    tags: List[str]

# Grid Routes
@app.get("/grid/status")
def grid_status():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("SELECT COUNT(*) FROM mind_verdicts")
    node_count = cursor.fetchone()[0]
    conn.close()
    
    return {
        "status": "Active",
        "neural_nodes": node_count,
        "coherence": 99.98,
        "sync_delay": 2.3,
        "timestamp": datetime.now().isoformat()
    }

@app.get("/grid/feed")
def grid_feed():
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("SELECT COUNT(*) FROM mind_verdicts")
    node_count = cursor.fetchone()[0]
    conn.close()
    
    return {
        "message": f"🔸 [Mostar Feed] Grid sync stable – Neural nodes: {node_count} active – Last signal: 2.3s ago – Coherence: 99.98% – Flow: Optimal"
    }

# Decision Making Endpoint
@app.post("/grid/evaluate", response_model=DecisionResponse)
def evaluate_decision(request: DecisionRequest):
    try:
        # Get truth assessment
        truth_result = truth_engine.assess_truth(request.query)
        
        # Get mind verdict
        mind_result = mind_verdict.form_verdict(request.query, request.context or {})
        
        # Get soul insight
        soul_result = soul_core.reflect_on_issue(request.query)
        
        # Apply covenant filter
        policy_alignment = covenant_filter.evaluate_compliance({
            "verdict": mind_result,
            "truth": truth_result,
            "soul_state": soul_result
        })
        
        # Execute if needed
        execution_result = None
        if mind_result.get("requires_action"):
            execution_result = api_executor.execute_task(request.query)
        
        # Store in database
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("""
            INSERT INTO mind_verdicts (query, verdict, timestamp, truth_score, soul_state, policy)
            VALUES (?, ?, ?, ?, ?, ?)
        """, (
            request.query,
            json.dumps(mind_result),
            datetime.now().isoformat(),
            truth_result.get("confidence", 0),
            json.dumps(soul_result),
            policy_alignment
        ))
        conn.commit()
        conn.close()
        
        # Log event
        log_event("GRID_EVALUATION", {
            "query": request.query,
            "policy_alignment": policy_alignment
        })
        
        return DecisionResponse(
            verdict=mind_result,
            truth_assessment=truth_result,
            soul_insight=soul_result,
            execution_result=execution_result,
            policy_alignment=policy_alignment
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Soulprint Management
@app.post("/grid/upload_soulprint")
def upload_soulprint(soulprint: SoulPrintUpload):
    try:
        soulprint_id = str(uuid.uuid4())
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("""
            INSERT INTO soulprints (id, name, content, tags, created_at)
            VALUES (?, ?, ?, ?, ?)
        """, (
            soulprint_id,
            soulprint.name,
            soulprint.content,
            json.dumps(soulprint.tags),
            datetime.now().isoformat()
        ))
        conn.commit()
        conn.close()
        
        log_event("SOULPRINT_UPLOAD", {
            "name": soulprint.name,
            "id": soulprint_id
        })
        
        return {"id": soulprint_id, "message": "Soulprint uploaded successfully"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/grid/soulprints")
def list_soulprints():
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("SELECT id, name, tags, created_at FROM soulprints")
        rows = cursor.fetchall()
        conn.close()
        
        soulprints = [
            {
                "id": row[0],
                "name": row[1],
                "tags": json.loads(row[2]),
                "created_at": row[3]
            }
            for row in rows
        ]
        
        return soulprints
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Task Execution
@app.post("/grid/execute")
def execute_task(task: dict):
    try:
        result = api_executor.execute_task(task)
        log_event("TASK_EXECUTION", task)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Training with Mostly AI
@app.post("/grid/train")
def train_consciousness(dataset_id: str, agent: str = "DeepSeek V3.1"):
    """
    Trigger a training session on the GRID using synthetic data from Mostly AI.
    """
    try:
        # Fetch dataset configuration and metadata
        sd = mostly.synthetic_datasets.get(dataset_id)
        config = sd.config()
        
        # Consume and return the synthetic dataset
        df = sd.data()  # returns a pandas DataFrame
        
        # Prepare training stats
        timestamp = datetime.now().isoformat()
        stats = {
            "dataset_id": dataset_id,
            "generator_id": config.get("generator_id"),
            "records": len(df),
            "timestamp": timestamp,
            "agent": agent
        }
        
        # Store event in DB
        with sqlite3.connect(DB_PATH) as conn:
            conn.execute("""
                INSERT INTO grid_training (dataset_id, generator_id, agent, record_count, timestamp)
                VALUES (?, ?, ?, ?, ?)
            """, (dataset_id, config.get("generator_id"), agent, len(df), timestamp))
            conn.commit()
        
        # Log event
        log_event("GRID_TRAINING", {
            "dataset_id": dataset_id,
            "agent": agent,
            "record_count": len(df)
        })
        
        return {
            "message": f"Grid training initialized with {len(df)} records.",
            "dataset": config.get("name", "Unknown Dataset"),
            "generator_id": config.get("generator_id"),
            "agent": agent,
            "timestamp": timestamp
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Health Check
@app.get("/grid/health")
def health_check():
    return {
        "status": "healthy",
        "engines": {
            "truth_engine": hasattr(truth_engine, 'assess_truth'),
            "mind_verdict": hasattr(mind_verdict, 'form_verdict'),
            "soul_core": hasattr(soul_core, 'reflect_on_issue'),
            "api_executor": hasattr(api_executor, 'execute_task')
        },
        "timestamp": datetime.now().isoformat()
    }

# Swagger UI
@app.get("/swagger.json")
def swagger_json():
    from fastapi.openapi.utils import get_openapi
    return get_openapi(
        title="Mostar Grid API",
        version="3.0.0",
        description="Unified Mind, Soul, Body orchestration API",
        routes=app.routes
    )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
```