-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop_events.py
More file actions
206 lines (187 loc) · 6.23 KB
/
loop_events.py
File metadata and controls
206 lines (187 loc) · 6.23 KB
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
import json
import uuid
from typing import Any
from db.database import get_conn
from training.collector import count_untrained_pairs
def _json(data: dict[str, Any] | None) -> str:
return json.dumps(data or {}, ensure_ascii=True, sort_keys=True)
async def record_event(
user_id: str,
event_type: str,
source: str,
summary: str = "",
payload: dict[str, Any] | None = None,
weight: float = 1.0,
) -> str:
event_id = str(uuid.uuid4())
async with get_conn() as db:
await db.execute(
"""
INSERT INTO echo_events (id, user_id, event_type, source, summary, payload_json, weight)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(event_id, user_id, event_type, source, summary[:500], _json(payload), weight),
)
await db.execute(
"""
INSERT OR IGNORE INTO life_events
(id, user_id, event_domain, event_type, source, title, summary, payload_json, confidence, privacy_level)
VALUES (?, ?, 'echo', ?, ?, ?, ?, ?, ?, 'local')
""",
(
event_id,
user_id,
event_type,
source,
event_type.replace("_", " ").title(),
summary[:700],
_json(payload),
max(0.0, min(float(weight) / 2.0, 1.0)),
),
)
await db.commit()
return event_id
async def record_life_event(
user_id: str,
event_domain: str,
event_type: str,
source: str,
title: str = "",
summary: str = "",
payload: dict[str, Any] | None = None,
confidence: float = 0.5,
privacy_level: str = "local",
subject_type: str | None = None,
subject_id: str | None = None,
) -> str:
event_id = str(uuid.uuid4())
async with get_conn() as db:
await db.execute(
"""
INSERT INTO life_events
(id, user_id, event_domain, event_type, source, subject_type, subject_id,
title, summary, payload_json, confidence, privacy_level)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
event_id,
user_id,
event_domain,
event_type,
source,
subject_type,
subject_id,
title[:160],
summary[:1000],
_json(payload),
max(0.0, min(confidence, 1.0)),
privacy_level,
),
)
await db.commit()
return event_id
async def record_outcome(
user_id: str,
subject_type: str,
outcome: str,
score: float,
subject_id: str | None = None,
event_id: str | None = None,
note: str = "",
) -> str:
outcome_id = str(uuid.uuid4())
async with get_conn() as db:
await db.execute(
"""
INSERT INTO shadow_outcomes
(id, user_id, event_id, subject_type, subject_id, outcome, score, note)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(outcome_id, user_id, event_id, subject_type, subject_id, outcome, score, note[:500]),
)
await db.commit()
return outcome_id
async def loop_snapshot(user_id: str) -> dict[str, Any]:
async with get_conn() as db:
async with db.execute(
"""
SELECT event_type, source, summary, payload_json, weight, created_at
FROM echo_events
WHERE user_id=?
ORDER BY created_at DESC
LIMIT 12
""",
(user_id,),
) as cur:
events = [dict(r) for r in await cur.fetchall()]
async with db.execute(
"""
SELECT outcome, subject_type, subject_id, score, note, created_at
FROM shadow_outcomes
WHERE user_id=?
ORDER BY created_at DESC
LIMIT 8
""",
(user_id,),
) as cur:
outcomes = [dict(r) for r in await cur.fetchall()]
async with db.execute(
"""
SELECT id, prompt, topic, status, winning_style, created_at
FROM tournament_runs
WHERE user_id=?
ORDER BY created_at DESC
LIMIT 1
""",
(user_id,),
) as cur:
latest_tournament = await cur.fetchone()
async with db.execute(
"SELECT COUNT(*) as cnt FROM echo_events WHERE user_id=?",
(user_id,),
) as cur:
event_count = await cur.fetchone()
async with db.execute(
"""
SELECT event_domain, event_type, source, title, summary, confidence, created_at
FROM life_events
WHERE user_id=?
ORDER BY created_at DESC
LIMIT 10
""",
(user_id,),
) as cur:
life_events = [dict(r) for r in await cur.fetchall()]
for event in events:
try:
event["payload"] = json.loads(event.pop("payload_json") or "{}")
except json.JSONDecodeError:
event["payload"] = {}
latest = dict(latest_tournament) if latest_tournament else None
if latest and latest.get("id"):
async with get_conn() as db:
async with db.execute(
"""
SELECT id, style, response, score, signals_json
FROM tournament_candidates
WHERE run_id=?
ORDER BY score DESC, created_at ASC
""",
(latest["id"],),
) as cur:
latest["candidates"] = [dict(r) for r in await cur.fetchall()]
headline = "Echo is still collecting signal."
if latest and latest.get("winning_style"):
headline = f"Your {latest['winning_style']} clone won the latest round."
elif events:
headline = events[0].get("summary") or headline
untrained_pairs = await count_untrained_pairs(user_id)
return {
"headline": headline,
"event_count": event_count["cnt"] if event_count else 0,
"untrained_pairs": untrained_pairs,
"latest_events": events,
"latest_outcomes": outcomes,
"latest_tournament": latest,
"latest_life_events": life_events,
}