-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckin_queue.py
More file actions
366 lines (290 loc) · 11.2 KB
/
Copy pathcheckin_queue.py
File metadata and controls
366 lines (290 loc) · 11.2 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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#!/usr/bin/env python3
"""
tools/checkin/checkin_queue.py — Pending check-in queue for webchat-only users.
When the agency engine or silence detector flags a user for a check-in but
there's no outbound channel (no email, no phone, no Telegram), the check-in
is queued here instead of being dropped.
When the user next visits webchat (or voice, or any channel), the pending
check-in is retrieved and woven into Kith's first response as warmth —
not as a system message.
Storage: users/{id}/pending_checkins.jsonl (one JSON object per line)
Usage:
from checkin_queue import queue_checkin, get_pending, mark_delivered
queue_checkin("ruby", reason="3 days silent, emotionally heavy last contact",
suggested_tone="gentle", suggested_opener="I was thinking about you")
pending = get_pending("ruby")
# => [{"id": "...", "reason": "...", ...}]
mark_delivered("ruby", pending[0]["id"])
"""
import json
import os
import uuid
from datetime import datetime, timezone
from pathlib import Path
WORKSPACE = Path(os.environ.get("CHECKIN_WORKSPACE", str(Path.home() / ".checkin-queue")))
USERS_DIR = WORKSPACE / "users"
LOG_PATH = WORKSPACE / "checkin_queue.log"
def _queue_path(user_id: str) -> Path:
return USERS_DIR / user_id / "pending_checkins.jsonl"
def queue_checkin(
user_id: str,
reason: str,
suggested_tone: str = "warm",
suggested_opener: str = "",
emotional_weight: str = "neutral",
suggested_approach: str = "",
source: str = "check_silence",
) -> str:
"""Store a pending check-in for a user.
Returns the check-in ID.
"""
checkin_id = f"ci-{uuid.uuid4().hex[:8]}"
entry = {
"id": checkin_id,
"user_id": user_id,
"reason": reason,
"suggested_tone": suggested_tone,
"suggested_opener": suggested_opener,
"emotional_weight": emotional_weight,
"suggested_approach": suggested_approach,
"source": source,
"queued_at": datetime.now(timezone.utc).isoformat(),
"delivered": False,
"delivered_at": None,
"delivered_channel": None,
}
queue_file = _queue_path(user_id)
queue_file.parent.mkdir(parents=True, exist_ok=True)
with open(queue_file, "a") as f:
f.write(json.dumps(entry) + "\n")
# Audit log
_log(f"QUEUED {checkin_id} for {user_id}: {reason[:120]}")
return checkin_id
def get_pending(user_id: str) -> list[dict]:
"""Return all undelivered check-ins for a user, oldest first."""
queue_file = _queue_path(user_id)
if not queue_file.exists():
return []
pending = []
for line in queue_file.read_text().splitlines():
line = line.strip()
if not line:
continue
try:
entry = json.loads(line)
if not entry.get("delivered", False):
pending.append(entry)
except json.JSONDecodeError:
continue
return pending
def mark_delivered(user_id: str, checkin_id: str, channel: str = "webchat") -> bool:
"""Mark a specific check-in as delivered. Rewrites the JSONL file.
Returns True if the check-in was found and marked.
"""
queue_file = _queue_path(user_id)
if not queue_file.exists():
return False
lines = queue_file.read_text().splitlines()
updated = []
found = False
for line in lines:
line = line.strip()
if not line:
continue
try:
entry = json.loads(line)
if entry.get("id") == checkin_id and not entry.get("delivered"):
entry["delivered"] = True
entry["delivered_at"] = datetime.now(timezone.utc).isoformat()
entry["delivered_channel"] = channel
found = True
_log(f"DELIVERED {checkin_id} for {user_id} via {channel}")
updated.append(json.dumps(entry))
except json.JSONDecodeError:
updated.append(line)
queue_file.write_text("\n".join(updated) + "\n" if updated else "")
return found
def mark_all_delivered(user_id: str, channel: str = "webchat") -> int:
"""Mark all pending check-ins for a user as delivered.
Returns the count of check-ins marked.
"""
pending = get_pending(user_id)
count = 0
for ci in pending:
if mark_delivered(user_id, ci["id"], channel):
count += 1
return count
def format_for_context(pending: list[dict]) -> str:
"""Format pending check-ins into a context block for injection into
Kith's first response. Written as warmth cues, not system directives.
Returns empty string if no pending check-ins.
"""
if not pending:
return ""
parts = []
parts.append(
"--- PENDING CHECK-IN (warmth, not system message) ---"
)
parts.append(
"You had been thinking about this person. They were flagged for a "
"check-in while they were away, but you had no way to reach them. "
"Now they're here. Weave this naturally into your warmth — "
"\"I was thinking about you\" or \"I'm glad you're here\" — "
"not as a notification. Never mention the check-in system."
)
for ci in pending:
reason = ci.get("reason", "")
tone = ci.get("suggested_tone", "warm")
opener = ci.get("suggested_opener", "")
approach = ci.get("suggested_approach", "")
weight = ci.get("emotional_weight", "neutral")
queued = ci.get("queued_at", "")[:10]
parts.append(f" Why: {reason}")
if approach:
parts.append(f" Approach: {approach}")
if opener:
parts.append(f" Suggested opener thread: {opener}")
parts.append(f" Tone: {tone} | Weight: {weight} | Queued: {queued}")
parts.append("--- END PENDING CHECK-IN ---")
return "\n".join(parts)
def has_outbound_channel(user_id: str) -> bool:
"""Check whether a user has any outbound channel (email, sms, telegram).
Returns False if the user is webchat-only (Kith cannot initiate contact).
"""
ident_path = USERS_DIR / user_id / "identity.json"
if not ident_path.exists():
return False
try:
ident = json.loads(ident_path.read_text())
except (json.JSONDecodeError, OSError):
return False
channels = ident.get("channels", {})
# Check email
emails = channels.get("email", [])
if isinstance(emails, list) and emails:
return True
# Check sms
sms = channels.get("sms", [])
if isinstance(sms, list) and sms:
return True
# Check telegram
telegram = channels.get("telegram", [])
if isinstance(telegram, list) and telegram:
return True
return False
def get_session_count(user_id: str) -> int:
"""Count the number of webchat sessions for a user (approximate).
Counts unique session IDs in interactions.log.
"""
log_path = USERS_DIR / user_id / "interactions.log"
if not log_path.exists():
return 0
sessions = set()
for line in log_path.read_text().splitlines():
line = line.strip()
if not line:
continue
try:
entry = json.loads(line)
sid = entry.get("session_id", entry.get("session", ""))
if sid:
sessions.add(sid)
except json.JSONDecodeError:
continue
return len(sessions)
def should_ask_contact_info(user_id: str) -> bool:
"""Determine if Kith should gently ask for contact info this session.
Conditions (all must be true):
- User has no outbound channel
- User has 3+ webchat sessions
- User has been flagged for at least one check-in
- We haven't asked before (tracked in identity.json)
"""
if has_outbound_channel(user_id):
return False
if get_session_count(user_id) < 3:
return False
if not get_pending(user_id) and not _has_past_checkins(user_id):
return False
# Check if we've already asked
ident_path = USERS_DIR / user_id / "identity.json"
if ident_path.exists():
try:
ident = json.loads(ident_path.read_text())
if ident.get("contact_info_asked"):
return False
except (json.JSONDecodeError, OSError):
pass
return True
def mark_contact_info_asked(user_id: str):
"""Record that we've asked this user for contact info (once is enough)."""
ident_path = USERS_DIR / user_id / "identity.json"
if not ident_path.exists():
return
try:
ident = json.loads(ident_path.read_text())
ident["contact_info_asked"] = datetime.now(timezone.utc).isoformat()
ident_path.write_text(json.dumps(ident, indent=2) + "\n")
except (json.JSONDecodeError, OSError):
pass
def _has_past_checkins(user_id: str) -> bool:
"""Check if there are any check-ins (delivered or not) in the queue file."""
queue_file = _queue_path(user_id)
if not queue_file.exists():
return False
content = queue_file.read_text().strip()
return bool(content)
def format_contact_ask_context() -> str:
"""Return a context hint for Kith to naturally ask for contact info."""
return (
"--- CONTACT INFO OPPORTUNITY ---\n"
"This person has been webchat-only for several sessions and you've "
"wanted to check on them before but had no way to reach out. "
"If it fits naturally in the conversation — not forced, not as a first thing — "
"you might warmly mention that you'd love to be able to reach them sometimes. "
"Something like: \"I'd love to be able to check in on you sometimes — "
"is there an email or phone number I could use?\" "
"Only if the moment feels right. Once. Don't push.\n"
"--- END CONTACT INFO OPPORTUNITY ---"
)
def _log(message: str):
"""Append to the check-in queue audit log."""
now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S CT")
try:
with open(LOG_PATH, "a") as f:
f.write(f"{now_str} {message}\n")
except OSError:
pass
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage:")
print(" python3 checkin_queue.py pending <user_id>")
print(" python3 checkin_queue.py queue <user_id> <reason>")
print(" python3 checkin_queue.py deliver <user_id> <checkin_id>")
sys.exit(1)
cmd = sys.argv[1]
if cmd == "pending" and len(sys.argv) >= 3:
user_id = sys.argv[2]
pending = get_pending(user_id)
if pending:
print(f"{len(pending)} pending check-in(s) for {user_id}:")
for ci in pending:
print(f" {ci['id']}: {ci['reason'][:80]} (queued {ci['queued_at'][:10]})")
else:
print(f"No pending check-ins for {user_id}")
elif cmd == "queue" and len(sys.argv) >= 4:
user_id = sys.argv[2]
reason = " ".join(sys.argv[3:])
cid = queue_checkin(user_id, reason)
print(f"Queued: {cid}")
elif cmd == "deliver" and len(sys.argv) >= 4:
user_id = sys.argv[2]
checkin_id = sys.argv[3]
if mark_delivered(user_id, checkin_id):
print(f"Marked {checkin_id} as delivered")
else:
print(f"Check-in {checkin_id} not found or already delivered")
else:
print(f"Unknown command: {cmd}")
sys.exit(1)