File size: 3,985 Bytes
a80c9f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Deep Dive: HOLD System with Async Override



Testing the full HOLD flow:

1. Brain yields a hold point (blocking)

2. Human/chat overrides before timeout

3. See how the override propagates through



This is how Twitch chat can control AI decisions in real-time!

"""

import numpy as np
import threading
import time
from cascade import Hold, HoldResolution

print("=" * 60)
print("⏸️ CASCADE HOLD - Async Override Demo")
print("=" * 60)

# Get the singleton
hold = Hold()

# Track what happened
events = []

def listener(hp):
    """Called when a hold point is created"""
    events.append(f"[LISTENER] Hold point created: brain={hp.brain_id}")
    print(f"\n🔴 HOLD POINT: {hp.brain_id}")
    print(f"   Action probs: {hp.action_probs}")
    print(f"   Labels: {hp.action_labels}")
    print(f"   Value estimate: {hp.value:.3f}")
    
    # Show what AI wants to do
    ai_choice = np.argmax(hp.action_probs)
    print(f"   AI wants: {ai_choice} ({hp.action_labels[ai_choice] if hp.action_labels else '?'})")

hold.register_listener(listener)

def brain_thread():
    """Simulates the AI brain yielding a hold point and waiting"""
    events.append("[BRAIN] Starting inference...")
    print("\n🧠 Brain: Starting inference...")
    
    # Fake observations
    observation = {
        "health": 0.3,  # Low health!
        "enemies": 2,
        "ammo": 5
    }
    
    # AI thinks: "Low health, should retreat!"
    # But maybe human knows better...
    action_probs = np.array([0.05, 0.85, 0.05, 0.05])  # RETREAT strongly preferred
    value = -0.3  # AI thinks situation is bad
    
    events.append("[BRAIN] Yielding hold point (blocking)...")
    print("🧠 Brain: Yielding hold point, waiting for resolution...")
    
    # This blocks until resolved!
    resolution = hold.yield_point(
        action_probs=action_probs,
        value=value,
        observation=observation,
        brain_id="arcade_brain_007",
        action_labels=["ATTACK", "RETREAT", "HEAL", "DODGE"],
        blocking=True  # BLOCKING - will wait
    )
    
    events.append(f"[BRAIN] Resolution received: action={resolution.action}")
    print(f"\n🧠 Brain: Got resolution!")
    print(f"   Final action: {resolution.action} ({['ATTACK', 'RETREAT', 'HEAL', 'DODGE'][resolution.action]})")
    print(f"   Was override: {resolution.was_override}")
    if resolution.was_override:
        print(f"   Override from: {resolution.override_source}")
    print(f"   Hold duration: {resolution.hold_duration:.3f}s")
    print(f"   Merkle: {resolution.merkle_root}")
    
    return resolution

def human_thread():
    """Simulates human (Twitch chat) overriding the decision"""
    time.sleep(0.5)  # Wait for hold point to be created
    events.append("[HUMAN] Deciding to override...")
    print("\n👤 Human: AI wants to RETREAT but I see an opportunity!")
    print("👤 Human: Overriding to ATTACK!")
    
    # Human overrides: "No, attack! I see a power-up!"
    hold.override(0, source="twitch_chat:xX_ProGamer_Xx")
    events.append("[HUMAN] Override injected: ATTACK")
    print("👤 Human: Override injected!")

print("\n=== Starting Async Hold Test ===")
print("Brain will want to RETREAT (low health)")
print("Human will override to ATTACK")
print("-" * 40)

# Start brain in a thread
brain = threading.Thread(target=brain_thread)
brain.start()

# Start human in another thread (with delay)
human = threading.Thread(target=human_thread)
human.start()

# Wait for both
brain.join()
human.join()

print("\n=== Event Log ===")
for i, event in enumerate(events, 1):
    print(f"  {i}. {event}")

print("\n=== Final Stats ===")
stats = hold.stats  # Property not method!
print(f"  Total holds: {stats['total_holds']}")
print(f"  Overrides: {stats['overrides']}")
print(f"  Override rate: {stats['override_rate']:.1%}")
print(f"  Last merkle: {stats['last_merkle']}")