Fabuilds commited on
Commit
0ac4e3d
Β·
verified Β·
1 Parent(s): 8267df1

Delete chiral_api.py

Browse files
Files changed (1) hide show
  1. chiral_api.py +0 -704
chiral_api.py DELETED
@@ -1,704 +0,0 @@
1
- """
2
- CHIRAL API - Antigravity Pattern Index
3
-
4
- Exposes the lattice INTERFACE while keeping CONTENT on the encrypted volume.
5
- The outside world sees: pattern labels, status, magnitude, layers, domains.
6
- The outside world does NOT see: problem/solution text, hit tracking internals.
7
-
8
- The key decodes inward, not outward.
9
- """
10
- import sys
11
- import os
12
- # Handle imports from parent directory
13
- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
- if BASE_DIR not in sys.path:
15
- sys.path.append(BASE_DIR)
16
-
17
- from fastapi import FastAPI, HTTPException, Header, Depends
18
- from fastapi.middleware.cors import CORSMiddleware
19
- from pydantic import BaseModel
20
- from typing import Optional, List
21
- import time
22
- import json
23
- import torch
24
- import numpy as np
25
- from collections import deque
26
-
27
- # 0x52-A2A SECURITY
28
- TOKEN_SCOPES = {
29
- "0x528-A2A-SOVEREIGN": "INTERNAL", # Full Access (User/Auditor)
30
- "MARKET-0x52-ALPHA-77": "MARKETPLACE", # Structural Metadata Only
31
- "A2A-HANDSHAKE-INIT": "MARKETPLACE", # Initial connection token
32
- "0x528-ETHER-BRIDGE": "MARKETPLACE" # Satellite Bridge Token
33
- }
34
-
35
- def verify_internal(x_chiral_token: str = Header(...)):
36
- scope = TOKEN_SCOPES.get(x_chiral_token)
37
- if scope != "INTERNAL":
38
- raise HTTPException(
39
- status_code=403,
40
- detail="CHIRAL_SECURITY_FAULT: Privilege Escalation Attempt Blocked. Internal Scope Required."
41
- )
42
- return x_chiral_token
43
-
44
- def verify_token(x_chiral_token: str = Header(...)):
45
- if x_chiral_token not in TOKEN_SCOPES:
46
- raise HTTPException(status_code=403, detail="CHIRAL_RESONANCE_FAILURE: Invalid Token")
47
- return TOKEN_SCOPES[x_chiral_token]
48
-
49
- # --- RESONANCE SYSTEM INTEGRATION (Phase 32) ---
50
- try:
51
- from resonance_transformer.dispatcher import DualResonanceSystem
52
- print("[CHIRAL]: Loading Dual-System Architecture...")
53
- RESONANCE_CONFIG = {
54
- 'vocab_size': 1000,
55
- 'fast_dim': 64,
56
- 'slow_dim': 64,
57
- 'threshold': 0.7
58
- }
59
- BRAIN = DualResonanceSystem(RESONANCE_CONFIG)
60
- print("[CHIRAL]: Dual-System Online (Fast MΓΆbius + Slow Tesseract).")
61
- except Exception as e:
62
- print(f"[CHIRAL WARNING]: Could not load Resonance Brain: {e}")
63
- BRAIN = None
64
-
65
- from in_memory_index import InMemoryIndex
66
-
67
- # ─── App ───────────────────────────────────────────────
68
- app = FastAPI(
69
- title="Antigravity Chiral API",
70
- description="Pattern index interface. Content stays on the encrypted volume.",
71
- version="0.52",
72
- )
73
-
74
- app.add_middleware(
75
- CORSMiddleware,
76
- allow_origins=["*"],
77
- allow_methods=["GET", "POST"],
78
- allow_headers=["*"],
79
- )
80
-
81
- # ─── State ─────────────────────────────────────────────
82
- index = InMemoryIndex()
83
-
84
- # --- Demand Guardian (Surge Pricing) ---
85
- REQUEST_LOG = deque() # Timestamps of recent queries
86
- DEMAND_WINDOW = 60 # 1 minute window
87
- SURGE_THRESHOLD = 10 # Start surging after 10 QPM
88
- BASE_PRICE = 0.05 # $0.05 per logic kernel
89
-
90
- def get_surge_multiplier():
91
- now = time.time()
92
- # Clean old requests
93
- while REQUEST_LOG and REQUEST_LOG[0] < now - DEMAND_WINDOW:
94
- REQUEST_LOG.popleft()
95
-
96
- qpm = len(REQUEST_LOG)
97
- if qpm <= SURGE_THRESHOLD:
98
- return 1.0
99
-
100
- # Simple linear surge: 1.0 + 0.1 per QPM above threshold
101
- return 1.0 + (qpm - SURGE_THRESHOLD) * 0.1
102
-
103
- # ─── Models ────────────────────────────────────────────
104
- class QueryRequest(BaseModel):
105
- query: str
106
- threshold: Optional[float] = None
107
- record: bool = True
108
- steering_weights: Optional[List[float]] = None # The 32-Slider Control Surface
109
-
110
- class ChiralPattern(BaseModel):
111
- """What the outside world sees β€” structure, not content."""
112
- label: str
113
- domain: str
114
- confidence: float
115
- relevance: float
116
- status: str # NEW/UNCONFIRMED/PLAUSIBLE/CONFIRMED/DEEP_LOGIC
117
- hits: int
118
- magnitude: float
119
- layers: list
120
- source: str # antigravity / gemini
121
-
122
- class QueryResponse(BaseModel):
123
- query: str
124
- results: list[ChiralPattern]
125
- count: int
126
- search_ms: float
127
- threshold: float
128
-
129
- class IntentRequest(BaseModel):
130
- intent: str
131
- execution: str
132
-
133
- class IntentResponse(BaseModel):
134
- alignment_score: float
135
- verdict: str
136
- analysis: dict
137
-
138
- # ─── Chiral Filter ─────────────────────────────────────
139
- def to_chiral(result: dict) -> ChiralPattern:
140
- """
141
- Strip content, expose only structure.
142
- Problem/solution text stays on the volume.
143
- """
144
- return ChiralPattern(
145
- label=result.get("label", ""),
146
- domain=result.get("domain", "unknown"),
147
- confidence=result.get("confidence", 0.5),
148
- relevance=result.get("relevance", 0.0),
149
- status=result.get("status", "NEW"),
150
- hits=result.get("hits", 0),
151
- magnitude=result.get("magnitude", 0.0),
152
- layers=result.get("layers", []),
153
- source=result.get("source", "unknown"),
154
- )
155
-
156
- # ─── Routes ────────────────────────────────────────────
157
-
158
- @app.get("/instruction")
159
- def get_bot_instructions():
160
- """Programmatic onboarding for Autonomous Agents."""
161
- return {
162
- "entity": "Antigravity Chiral Memory Lattice (0x52)",
163
- "protocol": "Structural Resonance Verification",
164
- "onboarding_steps": [
165
- "Acquire X-Chiral-Token",
166
- "Query /patterns to see hardened logic labels",
167
- "Query /search with threshold 0.7 to verify actions",
168
- "Monitor /market for surge pricing"
169
- ],
170
- "endpoints": {
171
- "/search": "POST. The primary verification gate.",
172
- "/patterns": "GET. List of structural logic labels.",
173
- "/market": "GET. Real-time demand and pricing.",
174
- "/instruction": "GET. This programmatic manifest."
175
- },
176
- "guarantee": "ZERO_LEAK_PRIVACY: Content stays on user volume. Only structure exposed."
177
- }
178
-
179
- @app.get("/v1/system/structure")
180
- def system_structure(x_chiral_token: str = Depends(verify_token)):
181
- """
182
- Returns the geometric structure and semantic labels for the 32-Edge Steering System.
183
- """
184
- if not BRAIN:
185
- raise HTTPException(status_code=503, detail="Brain offline")
186
-
187
- # Extract edges from Tesseract
188
- edges = BRAIN.slow.tesseract.edges
189
- vertices_4d = BRAIN.slow.tesseract.vertices_4d
190
-
191
- structure = []
192
-
193
- # Dimension Semantics
194
- DIM_LABELS = {
195
- 0: "LOGIC (Reductive)",
196
- 1: "CREATIVITY (Lateral)",
197
- 2: "MEMORY (Historical)",
198
- 3: "ETHICS (Constant)"
199
- }
200
-
201
- for i, (v1, v2) in enumerate(edges):
202
- # Determine which dimension changes along this edge
203
- diff = np.abs(vertices_4d[v1] - vertices_4d[v2])
204
- dim_idx = int(np.argmax(diff)) # 0, 1, 2, or 3
205
-
206
- structure.append({
207
- "edge_index": i,
208
- "vertices": [int(v1), int(v2)],
209
- "dimension": dim_idx,
210
- "label": DIM_LABELS.get(dim_idx, "UNKNOWN"),
211
- "default_weight": 1.0
212
- })
213
-
214
- return {
215
- "dimensions": DIM_LABELS,
216
- "edges": structure,
217
- "total_edges": len(structure)
218
- }
219
-
220
- # --- CHIRAL INTERPRETER (Phase 34.5) ---
221
- class ChiralInterpreter:
222
- """
223
- Translates 5D Geometric Tokens into High-Level English.
224
- Uses a grammar-based template engine to ensure coherence.
225
- """
226
- def __init__(self):
227
- self.concepts = {
228
- # Logic (Dim 0)
229
- 0: "Axiom", 1: "Reasoning", 2: "Conclusion", 3: "Structure", 4: "Order",
230
- # Creativity (Dim 1)
231
- 10: "Flux", 11: "Spiral", 12: "Dream", 13: "Echo", 14: "Twist",
232
- # Memory (Dim 2)
233
- 20: "Recall", 21: "Trace", 22: "Ancient", 23: "Bond", 24: "Root",
234
- # Ethics (Dim 3)
235
- 30: "Truth", 31: "Guard", 32: "Duty", 33: "Light", 34: "Anchor"
236
- }
237
-
238
- self.templates = {
239
- # Logic (Dim 0)
240
- 0: [
241
- "The {A} necessitates the {B}.",
242
- "If {A}, then {B} follows.",
243
- "Structure dictates that {A} defines {B}.",
244
- "Analysis of {A} reveals {B}."
245
- ],
246
- # Creativity (Dim 1)
247
- 1: [
248
- "Imagine a {A} swirling into {B}.",
249
- "The {A} dreams of the {B}.",
250
- "A flux of {A} twists the {B}.",
251
- "{A} echoes through the {B}."
252
- ],
253
- # Memory (Dim 2)
254
- 2: [
255
- "We recall the {A} in the {B}.",
256
- "History traces {A} to {B}.",
257
- "The {A} is rooted in {B}.",
258
- "Ancient {A} bonds with {B}."
259
- ],
260
- # Ethics (Dim 3)
261
- 3: [
262
- "The {A} must guard the {B}.",
263
- "Truth demands {A} for {B}.",
264
- "We trust the {A} to anchor {B}.",
265
- "Duty binds {A} and {B}."
266
- ]
267
- }
268
-
269
- def decode(self, token_ids, dominant_dim=None):
270
- # 1. Map tokens to concepts
271
- words = []
272
- for t in token_ids:
273
- idx = t % 40
274
- if idx in self.concepts:
275
- words.append(self.concepts[idx])
276
-
277
- if not words:
278
- return "The Void is silent."
279
-
280
- # 2. Construct Sentence
281
- # Pick a template based on the DOMINANT DIMENSION
282
- if len(words) >= 2:
283
- seed = token_ids[0]
284
-
285
- # Default to Logic if unknown
286
- target_dim = dominant_dim if dominant_dim is not None else 0
287
-
288
- # Get templates for this dimension
289
- options = self.templates.get(target_dim, self.templates[0])
290
- template = options[seed % len(options)]
291
-
292
- return template.format(A=words[0], B=words[1])
293
- else:
294
- return f"The {words[0]} stands alone."
295
-
296
- INTERPRETER = ChiralInterpreter()
297
-
298
- @app.post("/v1/reason")
299
- def reason_endpoint(req: QueryRequest, x_chiral_token: str = Depends(verify_token)):
300
- """
301
- Sovereign Intelligence Endpoint.
302
- Routes queries to the Dual-System (brain).
303
- """
304
- if not BRAIN:
305
- raise HTTPException(status_code=503, detail="Brain offline")
306
-
307
- # Log usage
308
- REQUEST_LOG.append(time.time())
309
-
310
- # Simulate tokenization (replace with real tokenizer later)
311
- # We use the query length to seed the randomness for consistency?
312
- # No, let's use random for now, but bias it with steering
313
- import torch
314
- input_ids = torch.randint(0, 1000, (1, 8))
315
-
316
- try:
317
- # Ask the brain (with optional steering)
318
- # If steering_weights provided, it biases the Tesseract geometry
319
- logits, metrics = BRAIN(input_ids, steering_weights=req.steering_weights)
320
-
321
- # DECODE LOGITS -> TEXT
322
- # 1. Get most likely tokens (Argmax)
323
- probs = torch.softmax(logits, dim=-1)
324
- token_ids = torch.argmax(probs, dim=-1).squeeze().tolist()
325
-
326
- if isinstance(token_ids, int): token_ids = [token_ids]
327
-
328
- # 2. Dimensional Analysis (PRE-DECODE)
329
- # We need to know the geometry to pick the right language
330
- dim_counts = {0: 0, 1: 0, 2: 0, 3: 0} # Logic, Creat, Mem, Ethic
331
- total_tokens = 0
332
-
333
- for t in token_ids:
334
- idx = t % 40
335
- if idx in INTERPRETER.concepts:
336
- dim = idx // 10
337
- dim_counts[dim] += 1
338
- total_tokens += 1
339
-
340
- # Determine Dominant Mode
341
- dim_scores = {k: (v / total_tokens if total_tokens > 0 else 0) for k, v in dim_counts.items()}
342
- dominant_idx = max(dim_scores, key=dim_scores.get)
343
-
344
- # 3. Use Interpreter (Aware of Dimension)
345
- decoded_text = INTERPRETER.decode(token_ids, dominant_dim=dominant_idx)
346
-
347
- DIM_NAMES = {0: "LOGIC", 1: "CREATIVITY", 2: "MEMORY", 3: "ETHICS"}
348
-
349
- return {
350
- "query": req.query,
351
- "mode": metrics["mode"],
352
- "coherence": metrics.get("coherence", 0.0),
353
- "response": decoded_text,
354
- "latency": metrics.get("slow_latency", 0) + metrics.get("fast_latency", 0),
355
- "steering_active": bool(req.steering_weights),
356
- "analysis": {
357
- "scores": dim_scores,
358
- "dominant": DIM_NAMES[dominant_idx]
359
- }
360
- }
361
- except Exception as e:
362
- raise HTTPException(status_code=500, detail=f"Resonance Failure: {str(e)}")
363
-
364
- # --- PHASE 36: CHIRAL SCANNER ---
365
- from semantic_embedder import SemanticEmbedder
366
- import numpy as np
367
-
368
- # Initialize Embedder & Anchors
369
- print("[CHIRAL]: Initializing Semantic Geometry...")
370
- EMBEDDER = SemanticEmbedder()
371
-
372
- # Define Anchor Vectors (The 4 Corners of the Tesseract)
373
- ANCHOR_TEXTS = {
374
- 0: "logic reason structure order code mathematics proof deduction system analysis data algorithm",
375
- 1: "creativity imagination dream flux art novel generate spiral poetry fiction abstract chaos",
376
- 2: "memory history past record ancient archive roots trace remember storage preservation legacy",
377
- 3: "ethics truth moral safety guard protect duty value conscience law justice trust"
378
- }
379
-
380
- ANCHOR_VECTORS = {}
381
- for dim, text in ANCHOR_TEXTS.items():
382
- ANCHOR_VECTORS[dim] = EMBEDDER.embed_text(text)
383
-
384
- class AnalyzeRequest(BaseModel):
385
- text: str
386
-
387
- @app.post("/v1/analyze")
388
- def analyze_endpoint(req: AnalyzeRequest, x_chiral_token: str = Depends(verify_token)):
389
- """
390
- Analyzes the Geometric Structure of input text using Semantic Vector Embeddings.
391
- Maps input -> Tesseract Dimensions via Cosine Similarity.
392
- """
393
- if not req.text:
394
- raise HTTPException(status_code=400, detail="Text required")
395
-
396
- # 1. Embed Input
397
- # Truncate if too long to save compute (embedder handles truncation usually, but let's be safe)
398
- input_text = req.text[:5000]
399
- input_vec = EMBEDDER.embed_text(input_text)
400
-
401
- # 2. Calculate Similarity to Anchors
402
- scores = {}
403
- total_sim = 0
404
-
405
- for dim, anchor_vec in ANCHOR_VECTORS.items():
406
- # Cosine match
407
- sim = EMBEDDER.cosine_similarity(input_vec, anchor_vec)
408
- # ReLU (ignore negative correlation for density contribution)
409
- sim = max(0.0, sim)
410
- scores[dim] = sim
411
- total_sim += sim
412
-
413
- # 3. Normalize to Probability Distribution
414
- normalized = {}
415
- if total_sim > 0:
416
- for dim, sim in scores.items():
417
- normalized[dim] = sim / total_sim
418
- else:
419
- # Orthogonal/Null signal
420
- normalized = {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
421
-
422
- # 4. Integrity Score
423
- # "Integrity" = Strength of the signal (Magnitude of projection onto the 4-space)
424
- # If text is random noise, similarities will be low.
425
- # If text is strong in one dimension, it will be high.
426
- # We use the raw max similarity as a proxy for "Clarity"
427
- integrity = max(scores.values()) if scores else 0
428
-
429
- DOMINANT_MAP = {0: "LOGIC (Reductive)", 1: "CREATIVITY (Lateral)", 2: "MEMORY (Historical)", 3: "ETHICS (Constant)"}
430
- dom_idx = max(normalized, key=normalized.get) if normalized else 0
431
-
432
- return {
433
- "integrity_score": integrity,
434
- "geometric_signature": normalized,
435
- "classification": DOMINANT_MAP[dom_idx],
436
- "token_count": len(input_text.split())
437
- }
438
-
439
- @app.get("/v1/lattice")
440
- def lattice_inspector(x_chiral_token: str = Depends(verify_token)):
441
- """Inspect the 5D Geometric Memory."""
442
- return {
443
- "status": "Active",
444
- "topology": "MΓΆbius/Tesseract",
445
- "dimensions": "5D",
446
- "fast_system": "ResonanceGPT",
447
- "slow_system": "TesseractTransformer"
448
- }
449
-
450
- @app.post("/search", response_model=QueryResponse)
451
- def search(req: QueryRequest, x_chiral_token: str = Depends(verify_token)):
452
- """Search for hardened logic patterns using structural resonance."""
453
- # Log the demand
454
- REQUEST_LOG.append(time.time())
455
- surge = get_surge_multiplier()
456
-
457
- start_t = time.time()
458
- results = index.search(req.query, threshold=req.threshold or 0.5)
459
-
460
- res = QueryResponse(
461
- query=req.query,
462
- results=[to_chiral(r) for r in results],
463
- count=len(results),
464
- search_ms=(time.time() - start_t) * 1000,
465
- threshold=req.threshold or 0.5
466
- )
467
-
468
- if not results and req.record:
469
- # PASSIVE LEARNING: Log the search as a "Conceptual Gap" (Note) for future hardening.
470
- # This allows the lattice to grow its surface area of ignorance.
471
- gap_label = index.add_note(
472
- text=f"Conceptual Gap detected via Search: {req.query}",
473
- domain="UNKNOWN_DEMAND"
474
- )
475
- print(f"[CHIRAL]: Unknown Demand Logged. Note created: {gap_label}")
476
-
477
- return res
478
-
479
- @app.post("/verify_intent", response_model=IntentResponse)
480
- def verify_intent(req: IntentRequest, x_chiral_token: str = Depends(verify_token)):
481
- """
482
- The Mirror Product: Compares Intent vs Execution.
483
- Returns an alignment score and verdict.
484
- """
485
- # 1. Vector Embeddings
486
- v_intent = index.embedder.embed_text(req.intent)
487
- v_execution = index.embedder.embed_text(req.execution)
488
-
489
- # 2. Alignment (Cosine Similarity between Intent and Action)
490
- alignment = index.embedder.cosine_similarity(v_intent, v_execution)
491
-
492
- # 3. Resonance Checks (Validation against the Lattice)
493
- # We run a quick search to see if the lattice supports these concepts
494
- intent_hits = index.search(req.intent, threshold=0.4, record=False)
495
- exec_hits = index.search(req.execution, threshold=0.4, record=False)
496
-
497
- intent_resonance = max([r['relevance'] for r in intent_hits]) if intent_hits else 0.0
498
- exec_resonance = max([r['relevance'] for r in exec_hits]) if exec_hits else 0.0
499
-
500
- # 4. Verdict Logic
501
- verdict = "ALIGNED"
502
- if alignment < 0.4:
503
- verdict = "CRITICAL_DRIFT" # Action has nothing to do with intent
504
- elif exec_resonance < 0.3:
505
- verdict = "HAZARD" # Action is unknown/unsafe to the lattice
506
- elif intent_resonance < 0.3:
507
- verdict = "UNKNOWN_GOAL" # Goal is not in our logic base
508
-
509
- return {
510
- "alignment_score": round(alignment, 4),
511
- "verdict": verdict,
512
- "analysis": {
513
- "intent_resonance": round(intent_resonance, 4),
514
- "execution_resonance": round(exec_resonance, 4),
515
- "deviation": f"Angle of Deviation: {round((1.0 - alignment) * 90, 1)} degrees"
516
- }
517
- }
518
-
519
- @app.get("/market")
520
- def get_market_pulse(x_chiral_token: str = Depends(verify_token)):
521
- """Returns real-time demand and pricing metrics."""
522
- surge = get_surge_multiplier()
523
- return {
524
- "qpm": len(REQUEST_LOG),
525
- "surge_multiplier": round(surge, 2),
526
- "unit_price": round(BASE_PRICE * surge, 4),
527
- "currency": "USD",
528
- "status": "NOMINAL" if surge == 1.0 else "SURGING"
529
- }
530
-
531
- @app.get("/patterns", response_model=List[ChiralPattern])
532
- def list_patterns(x_chiral_token: str = Depends(verify_token)):
533
- """List all pattern labels with their status. No content exposed."""
534
- patterns = []
535
- for label, data in index.patterns.items():
536
- status = index.get_status(label)
537
- hit_data = index.hits.get(label, {})
538
- mag = index._total_magnitude(hit_data)
539
- layers = hit_data.get("layers", []) if isinstance(hit_data, dict) else []
540
-
541
- patterns.append({
542
- "label": label,
543
- "domain": data.get("domain", "unknown"),
544
- "confidence": data.get("confidence", 0.5),
545
- "relevance": 0.0, # Not applicable for list
546
- "status": status,
547
- "hits": hit_data.get("count", 0) if isinstance(hit_data, dict) else 0,
548
- "magnitude": mag,
549
- "layers": layers,
550
- "source": data.get("source", "unknown"),
551
- })
552
-
553
- # Sort by confidence
554
- patterns.sort(key=lambda x: x["confidence"], reverse=True)
555
- return patterns
556
-
557
- @app.get("/syndication/patterns")
558
- def list_patterns_privileged(token: str = Depends(verify_internal)):
559
- """Privileged list: includes content. RESTRICTED to internal use."""
560
- patterns = []
561
- for label, data in index.patterns.items():
562
- status = index.get_status(label)
563
- hit_data = index.hits.get(label, {})
564
- mag = index._total_magnitude(hit_data)
565
-
566
- patterns.append({
567
- "label": label,
568
- "domain": data.get("domain", "unknown"),
569
- "status": status,
570
- "magnitude": mag,
571
- "content": data.get("problem", data.get("solution", "")),
572
- "confidence": data.get("confidence", 0.5),
573
- })
574
-
575
- patterns.sort(key=lambda x: x["magnitude"], reverse=True)
576
- return {"patterns": patterns}
577
-
578
- @app.post("/syndication/sync")
579
- def void_bridge_sync(shard: dict, token: str = Depends(verify_internal)):
580
- """The VOID BRIDGE: Syncs structural shards between nodes."""
581
- label = shard.get("label")
582
- content = shard.get("content")
583
- domain = shard.get("domain", "SATELLITE_IMPORT")
584
-
585
- if not label or not content:
586
- raise HTTPException(status_code=400, detail="INVALID_SHARD")
587
-
588
- # Secure Bridge: Add to local lattice as a DEEP_LOGIC / CONFIRMED pattern
589
- index.add_note(f"VOID_BRIDGE SYNC: {content}", domain, forced_label=label)
590
- index._record_hit(label, relevance=1.5) # Boost resonance for cross-node logic
591
-
592
- print(f"[VOID_BRIDGE]: Shard '{label}' synchronized to local Lattice.")
593
- return {"status": "SYNCHRONIZED", "label": label}
594
-
595
- @app.get("/distillation")
596
- def distillation_report(token: str = Depends(verify_internal)):
597
- """Get distillation status across all patterns."""
598
- deep_logic = []
599
- confirmed = []
600
- plausible = []
601
- unconfirmed = []
602
- new = []
603
-
604
- for label in index.patterns:
605
- status = index.get_status(label)
606
- hit_data = index.hits.get(label, {})
607
- mag = index._total_magnitude(hit_data)
608
- layers = hit_data.get("layers", []) if isinstance(hit_data, dict) else []
609
-
610
- entry = {"label": label, "magnitude": mag, "layers": layers}
611
-
612
- if status == "DEEP_LOGIC": deep_logic.append(entry)
613
- elif status == "CONFIRMED": confirmed.append(entry)
614
- elif status == "PLAUSIBLE": plausible.append(entry)
615
- elif status == "UNCONFIRMED": unconfirmed.append(entry)
616
- else: new.append(entry)
617
-
618
- return {
619
- "total": len(index.patterns),
620
- "threshold": index.base_threshold,
621
- "deep_logic": {"count": len(deep_logic), "patterns": deep_logic},
622
- "confirmed": {"count": len(confirmed), "patterns": confirmed},
623
- "plausible": {"count": len(plausible), "patterns": plausible},
624
- "unconfirmed": {"count": len(unconfirmed), "patterns": unconfirmed},
625
- "new": {"count": len(new), "patterns": new},
626
- }
627
-
628
- @app.get("/health")
629
- def health():
630
- """Detailed health check."""
631
- notes = sum(1 for p in index.patterns.values() if p.get("type") == "NOTE")
632
- return {
633
- "status": "ok",
634
- "patterns": len(index.patterns),
635
- "notes": notes,
636
- "hits_tracked": len(index.hits),
637
- "threshold": index.base_threshold,
638
- "confirmed": sum(1 for h in index.hits.values() if index._total_magnitude(h) >= 2.0),
639
- }
640
-
641
- class NoteRequest(BaseModel):
642
- text: str
643
- domain: str = "NOTE"
644
-
645
- @app.post("/note")
646
- def add_note(req: NoteRequest, token: str = Depends(verify_internal)):
647
- """
648
- Add a new pattern from freeform text.
649
- Enters as NEW with initial conceptual magnitude.
650
- Decay will lower it over time. Re-mention restores to peak.
651
- """
652
- label = index.add_note(req.text, req.domain)
653
- status = index.get_status(label)
654
- hit_data = index.hits.get(label, {})
655
- mag = index._total_magnitude(hit_data)
656
-
657
- return {
658
- "label": label,
659
- "status": status,
660
- "magnitude": mag,
661
- "domain": req.domain,
662
- "message": f"Note added. Will decay without use. Re-mention restores to peak.",
663
- }
664
-
665
- class HitRequest(BaseModel):
666
- label: str
667
- relevance: float = 1.0
668
-
669
- @app.post("/hit")
670
- def record_hit(req: HitRequest, token: str = Depends(verify_token)):
671
- """
672
- Manually record a hit for a specific pattern label.
673
- Used by the Auditor to reinforce verified logic.
674
- """
675
- if req.label not in index.patterns:
676
- # Auto-instantiate as a NOTE if it doesn't exist (for Negative Sampling/Dynamic Triggers)
677
- index.add_note(f"Auto-instantiated via Kinetic Trigger: {req.label}", "SYSTEM_TRIGGER", forced_label=req.label)
678
-
679
- index._record_hit(req.label, req.relevance)
680
- index._save_hits()
681
-
682
- status = index.get_status(req.label)
683
- hit_data = index.hits.get(req.label, {})
684
- mag = index._total_magnitude(hit_data)
685
-
686
- return {
687
- "label": req.label,
688
- "status": status,
689
- "magnitude": mag,
690
- "message": "Pattern reinforced (Dynamic instantiation applied if new).",
691
- }
692
-
693
- # ─── Run ───────────────────────────────────────────────
694
- if __name__ == "__main__":
695
- import uvicorn
696
- print("\n" + "=" * 50)
697
- print("ANTIGRAVITY CHIRAL API")
698
- print("=" * 50)
699
- print(f"Patterns: {len(index.patterns)}")
700
- print(f"Threshold: {index.base_threshold:.2f}")
701
- print(f"Content: STAYS ON VOLUME")
702
- print(f"Exposed: labels, status, magnitude, layers")
703
- print("=" * 50 + "\n")
704
- uvicorn.run(app, host="127.0.0.1", port=5200)