Spaces:
Sleeping

File size: 9,131 Bytes
a44d33b
 
2b05ca3
 
a44d33b
 
0ef167d
03d34ae
2b05ca3
a44d33b
03d34ae
 
 
 
 
 
 
 
 
 
 
 
 
a44d33b
636db5f
 
0ef167d
636db5f
 
 
0ef167d
 
636db5f
 
0ef167d
 
636db5f
 
a44d33b
 
636db5f
2b05ca3
 
 
 
636db5f
2b05ca3
636db5f
2b05ca3
636db5f
2b05ca3
 
 
636db5f
 
 
 
 
 
 
3c26e1e
636db5f
 
 
 
 
 
3c26e1e
636db5f
 
 
 
 
 
 
0ef167d
 
 
636db5f
0ef167d
636db5f
 
 
 
2b05ca3
 
 
 
636db5f
2b05ca3
 
 
 
 
 
 
 
 
 
 
 
 
636db5f
2b05ca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a44d33b
 
 
 
 
 
2b05ca3
a44d33b
 
 
2b05ca3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a44d33b
 
 
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
# api/state.py
"""
Request-aware isolated API state to prevent data leakage between different users.
Uses the current_uid ContextVar to partition state data per user dynamically.
"""
import time
import threading
from collections import defaultdict
from typing import Dict, Optional, Set, Any

# Committee session tracking — in-memory, resets on server restart (fine for hackathon)
_week_sessions: dict = defaultdict(list)  # key → [epoch_float, ...]

def count_sessions_this_week(key: str) -> int:
    cutoff = time.time() - 7 * 86400
    _week_sessions[key] = [t for t in _week_sessions[key] if t > cutoff]
    return len(_week_sessions[key])

def record_session(key: str) -> None:
    cutoff = time.time() - 7 * 86400
    _week_sessions[key] = [t for t in _week_sessions[key] if t > cutoff]
    _week_sessions[key].append(time.time())


# Global incident to uid registry
_incident_to_uid: Dict[str, str] = {}
_incident_registry_lock = threading.Lock()

def register_incident_uid(incident_id: str, uid: str):
    if incident_id and uid:
        with _incident_registry_lock:
            _incident_to_uid[incident_id] = uid

def get_uid_for_incident(incident_id: str) -> Optional[str]:
    with _incident_registry_lock:
        return _incident_to_uid.get(incident_id)


class SimulationState:
    def __init__(self):
        # Store state dictionaries keyed by "uid:incident_id"
        self._states: Dict[str, Dict[str, Any]] = {}

    def _get_state(self) -> Dict[str, Any]:
        uid = "__public__"
        incident_id = None
        try:
            from core.auth import current_uid, current_incident_id
            uid = current_uid.get()
            incident_id = current_incident_id.get()
        except Exception:
            pass

        if uid == "__mcp_client__":
            import os
            uid = os.getenv("FUSION_UID") or os.getenv("FUSION_ACTIVE_UID") or "__mcp_client__"

        # If incident_id is not in context, try to look up or find an active one for the uid
        if not incident_id:
            active_state = None
            for key, state in list(self._states.items()):
                if key.startswith(f"{uid}:") and state.get("running"):
                    active_state = state
                    break
            if active_state:
                return active_state

            user_keys = [k for k in list(self._states.keys()) if k.startswith(f"{uid}:")]
            if user_keys:
                user_keys.sort(key=lambda k: self._states[k].get("last_event_at", 0), reverse=True)
                return self._states[user_keys[0]]

            incident_id = "default"

        # Register mapping if we have both
        # ponytail: removed the unauthenticated→authenticated namespace escalation that was here.
        # That block allowed any caller who knew an incident_id to be silently remapped to the
        # owner's namespace. Background tasks (watchdog) explicitly set current_uid themselves.
        if uid and incident_id and incident_id != "default" and uid not in ("__public__", "__mcp_client__"):
            register_incident_uid(incident_id, uid)

        state_key = f"{uid}:{incident_id}"
        if state_key not in self._states:
            self._states[state_key] = {
                "running": False,
                "active_uid": uid if uid not in ("__public__", "__mcp_client__") else None,
                "active_user_name": None,
                "agent_statuses": {},
                "active_incident_id": incident_id if incident_id != "default" else None,
                "active_pitch_file": "novapay_pitch.json",
                "dispatched_deals": set(),
                "completed_agents": set(),
                "deal_concluded": False,
                "verdict_dispatched": False,
                "last_event_at": time.time(),
                "started_at": 0.0,
                "max_file_size_mb": 10,
                "active_company_name": None,
                "final_verdict_card": None,
                "_mp_verdict_pending": False,
                "_mp_verdict_triggered": False,
            }
        return self._states[state_key]

    @property
    def running(self) -> bool:
        return self._get_state()["running"]

    @running.setter
    def running(self, val: bool):
        self._get_state()["running"] = val

    @property
    def active_uid(self) -> Optional[str]:
        return self._get_state()["active_uid"]

    @active_uid.setter
    def active_uid(self, val: Optional[str]):
        self._get_state()["active_uid"] = val

    @property
    def active_user_name(self) -> Optional[str]:
        return self._get_state()["active_user_name"]

    @active_user_name.setter
    def active_user_name(self, val: Optional[str]):
        self._get_state()["active_user_name"] = val

    @property
    def agent_statuses(self) -> Dict[str, str]:
        return self._get_state()["agent_statuses"]

    @agent_statuses.setter
    def agent_statuses(self, val: Dict[str, str]):
        self._get_state()["agent_statuses"] = val

    @property
    def active_incident_id(self) -> Optional[str]:
        return self._get_state()["active_incident_id"]

    @active_incident_id.setter
    def active_incident_id(self, val: Optional[str]):
        self._get_state()["active_incident_id"] = val

    @property
    def active_pitch_file(self) -> str:
        return self._get_state()["active_pitch_file"]

    @active_pitch_file.setter
    def active_pitch_file(self, val: str):
        self._get_state()["active_pitch_file"] = val

    @property
    def dispatched_deals(self) -> Set[str]:
        return self._get_state()["dispatched_deals"]

    @dispatched_deals.setter
    def dispatched_deals(self, val: Set[str]):
        self._get_state()["dispatched_deals"] = val

    @property
    def completed_agents(self) -> Set[str]:
        return self._get_state()["completed_agents"]

    @completed_agents.setter
    def completed_agents(self, val: Set[str]):
        self._get_state()["completed_agents"] = val

    @property
    def deal_concluded(self) -> bool:
        return self._get_state()["deal_concluded"]

    @deal_concluded.setter
    def deal_concluded(self, val: bool):
        self._get_state()["deal_concluded"] = val

    @property
    def verdict_dispatched(self) -> bool:
        return self._get_state()["verdict_dispatched"]

    @verdict_dispatched.setter
    def verdict_dispatched(self, val: bool):
        self._get_state()["verdict_dispatched"] = val

    @property
    def last_event_at(self) -> float:
        return self._get_state()["last_event_at"]

    @last_event_at.setter
    def last_event_at(self, val: float):
        self._get_state()["last_event_at"] = val

    @property
    def started_at(self) -> float:
        return self._get_state()["started_at"]

    @started_at.setter
    def started_at(self, val: float):
        self._get_state()["started_at"] = val

    @property
    def max_file_size_mb(self) -> int:
        return self._get_state()["max_file_size_mb"]

    @max_file_size_mb.setter
    def max_file_size_mb(self, val: int):
        self._get_state()["max_file_size_mb"] = val

    @property
    def active_company_name(self) -> Optional[str]:
        return self._get_state()["active_company_name"]

    @active_company_name.setter
    def active_company_name(self, val: Optional[str]):
        self._get_state()["active_company_name"] = val

    @property
    def final_verdict_card(self) -> Optional[str]:
        return self._get_state()["final_verdict_card"]

    @final_verdict_card.setter
    def final_verdict_card(self, val: Optional[str]):
        self._get_state()["final_verdict_card"] = val

    @property
    def _mp_verdict_pending(self) -> bool:
        return self._get_state()["_mp_verdict_pending"]

    @_mp_verdict_pending.setter
    def _mp_verdict_pending(self, val: bool):
        self._get_state()["_mp_verdict_pending"] = val

    @property
    def _mp_verdict_triggered(self) -> bool:
        return self._get_state()["_mp_verdict_triggered"]

    @_mp_verdict_triggered.setter
    def _mp_verdict_triggered(self, val: bool):
        self._get_state()["_mp_verdict_triggered"] = val

    def touch(self):
        self.last_event_at = time.time()

    def is_stale(self, max_idle_seconds: float = 300.0) -> bool:
        """True if a run claims to be in progress but no agent has emitted
        an event for max_idle_seconds."""
        return self.running and (time.time() - self.last_event_at) > max_idle_seconds

    def reset(self):
        st = self._get_state()
        st["running"] = False
        st["active_user_name"] = None
        st["agent_statuses"] = {}
        st["active_incident_id"] = None
        st["dispatched_deals"].clear()
        st["completed_agents"].clear()
        st["deal_concluded"] = False
        st["active_company_name"] = None
        st["active_pitch_file"] = "novapay_pitch.json"
        st["verdict_dispatched"] = False
        st["final_verdict_card"] = None
        st["started_at"] = 0.0
        st["_mp_verdict_pending"] = False
        st["_mp_verdict_triggered"] = False


sim_state = SimulationState()