11"""Data-access layer for the proactive care push records table.
22
33The care_push_records table records the episode_id consumed by each proactive_care
4- push, used to avoid re-pushing the same event within 30 days.
4+ push (used for 30-day dedup) along with delivery coordinates (thread_id, message_id)
5+ and user reply status for backoff and downstream memory feedback.
56"""
67
78from __future__ import annotations
89
910import time
1011import uuid
1112from collections .abc import Sequence
13+ from dataclasses import dataclass
1214
1315from octop .infra .db .pool import DatabasePool
16+ from octop .infra .db .repos ._base import DbRow
17+
18+
19+ @dataclass (frozen = True )
20+ class CarePushRecord :
21+ """One row from ``care_push_records``."""
22+
23+ id : str
24+ agent_id : str
25+ session_key : str
26+ episode_id : str
27+ pushed_at : int
28+ thread_id : str | None = None
29+ message_id : str | None = None
30+ care_text : str | None = None
31+ status : str = "sent"
32+ replied_at : int | None = None
33+ reply_message_id : str | None = None
34+
35+ @classmethod
36+ def from_row (cls , row : DbRow ) -> CarePushRecord :
37+ return cls (
38+ id = str (row ["id" ]),
39+ agent_id = str (row ["agent_id" ]),
40+ session_key = str (row ["session_key" ]),
41+ episode_id = str (row ["episode_id" ]),
42+ pushed_at = int (row ["pushed_at" ]),
43+ thread_id = str (row ["thread_id" ]) if row ["thread_id" ] else None ,
44+ message_id = str (row ["message_id" ]) if row ["message_id" ] else None ,
45+ care_text = str (row ["care_text" ]) if row ["care_text" ] is not None else None ,
46+ status = str (row ["status" ] or "sent" ),
47+ replied_at = int (row ["replied_at" ]) if row ["replied_at" ] is not None else None ,
48+ reply_message_id = str (row ["reply_message_id" ]) if row ["reply_message_id" ] else None ,
49+ )
1450
1551
1652class CarePushRepo :
@@ -26,26 +62,158 @@ def insert(
2662 session_key : str ,
2763 episode_ids : Sequence [str ],
2864 pushed_at : int | None = None ,
65+ thread_id : str | None = None ,
66+ message_id : str | None = None ,
67+ care_text : str | None = None ,
2968 ) -> None :
30- """Batch-insert push records.
69+ """Batch-insert push records for one proactive care delivery .
3170
3271 Args:
3372 agent_id: The agent ID the push belongs to.
3473 session_key: The session key the push belongs to.
3574 episode_ids: The list of episode IDs consumed by this push.
3675 pushed_at: Push timestamp (unix); defaults to the current time.
76+ thread_id: Target thread ID where the care message was stored.
77+ message_id: Canonical ``AIMessage.id`` stored in the thread.
78+ care_text: Delivered care text (for reply correlation and feedback).
3779 """
3880 if not episode_ids :
3981 return
4082 ts = pushed_at if pushed_at is not None else int (time .time ())
41- rows = [(str (uuid .uuid4 ()), agent_id , session_key , ep_id , ts ) for ep_id in episode_ids ]
83+ rows = [
84+ (
85+ str (uuid .uuid4 ()),
86+ agent_id ,
87+ session_key ,
88+ ep_id ,
89+ ts ,
90+ thread_id ,
91+ message_id ,
92+ care_text ,
93+ "sent" ,
94+ )
95+ for ep_id in episode_ids
96+ ]
4297 with self ._db .transaction () as conn :
4398 conn .executemany (
44- "INSERT INTO care_push_records(id, agent_id, session_key, episode_id, pushed_at) "
45- "VALUES (?, ?, ?, ?, ?)" ,
99+ "INSERT INTO care_push_records("
100+ "id, agent_id, session_key, episode_id, pushed_at, "
101+ "thread_id, message_id, care_text, status"
102+ ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" ,
46103 rows ,
47104 )
48105
106+ def mark_replied_for_thread (
107+ self ,
108+ * ,
109+ agent_id : str ,
110+ thread_id : str ,
111+ reply_message_id : str | None = None ,
112+ replied_at : int | None = None ,
113+ ) -> int :
114+ """Record that the user replied in *thread_id* after a proactive care push.
115+
116+ The latest open (``status='sent'``) care push in *thread_id* is marked
117+ ``'replied'``; any older still-open pushes in the same thread are marked
118+ ``'ignored'`` so reply attribution stays tied to the message the user saw.
119+
120+ Returns:
121+ Number of rows marked ``'replied'``.
122+ """
123+ tid = thread_id .strip ()
124+ if not tid :
125+ return 0
126+ ts = replied_at if replied_at is not None else int (time .time ())
127+ with self ._db .transaction () as conn :
128+ latest = conn .execute (
129+ "SELECT message_id, pushed_at FROM care_push_records "
130+ "WHERE agent_id = ? AND thread_id = ? AND status = 'sent' AND pushed_at <= ? "
131+ "ORDER BY pushed_at DESC LIMIT 1" ,
132+ (agent_id , tid , ts ),
133+ ).fetchone ()
134+ if latest is None :
135+ return 0
136+ latest_mid = latest ["message_id" ]
137+ latest_pushed_at = int (latest ["pushed_at" ])
138+ if latest_mid :
139+ cur = conn .execute (
140+ "UPDATE care_push_records "
141+ "SET status = 'replied', replied_at = ?, reply_message_id = ? "
142+ "WHERE agent_id = ? AND thread_id = ? AND status = 'sent' "
143+ "AND message_id = ?" ,
144+ (ts , reply_message_id , agent_id , tid , latest_mid ),
145+ )
146+ replied_count = int (cur .rowcount or 0 )
147+ conn .execute (
148+ "UPDATE care_push_records "
149+ "SET status = 'ignored' "
150+ "WHERE agent_id = ? AND thread_id = ? AND status = 'sent' "
151+ "AND pushed_at <= ? AND (message_id IS NULL OR message_id <> ?)" ,
152+ (agent_id , tid , ts , latest_mid ),
153+ )
154+ else :
155+ cur = conn .execute (
156+ "UPDATE care_push_records "
157+ "SET status = 'replied', replied_at = ?, reply_message_id = ? "
158+ "WHERE agent_id = ? AND thread_id = ? AND status = 'sent' "
159+ "AND pushed_at = ?" ,
160+ (ts , reply_message_id , agent_id , tid , latest_pushed_at ),
161+ )
162+ replied_count = int (cur .rowcount or 0 )
163+ conn .execute (
164+ "UPDATE care_push_records "
165+ "SET status = 'ignored' "
166+ "WHERE agent_id = ? AND thread_id = ? AND status = 'sent' "
167+ "AND pushed_at < ?" ,
168+ (agent_id , tid , latest_pushed_at ),
169+ )
170+ return replied_count
171+
172+ def count_consecutive_unanswered (self , agent_id : str , * , limit : int = 20 ) -> int :
173+ """Count consecutive recent care pushes for *agent_id* without a reply.
174+
175+ Multiple episode rows emitted by the same delivery (sharing ``message_id``,
176+ or ``(pushed_at, session_key)`` for legacy rows) are collapsed into one push.
177+ """
178+ with self ._db .connect () as conn :
179+ rows = conn .execute (
180+ "SELECT message_id, pushed_at, session_key, status "
181+ "FROM care_push_records "
182+ "WHERE agent_id = ? "
183+ "ORDER BY pushed_at DESC LIMIT ?" ,
184+ (agent_id , max (limit * 3 , 30 )),
185+ ).fetchall ()
186+ seen_keys : list [tuple [str , int , str ]] = []
187+ push_replied : dict [tuple [str , int , str ], bool ] = {}
188+ for row in rows :
189+ mid = str (row ["message_id" ] or "" )
190+ key = (mid , int (row ["pushed_at" ]), str (row ["session_key" ])) if not mid else (mid , 0 , "" )
191+ if key not in push_replied :
192+ if len (seen_keys ) >= limit :
193+ break
194+ seen_keys .append (key )
195+ push_replied [key ] = False
196+ if str (row ["status" ] or "sent" ) == "replied" :
197+ push_replied [key ] = True
198+ streak = 0
199+ for key in seen_keys :
200+ if push_replied [key ]:
201+ break
202+ streak += 1
203+ return streak
204+
205+ def list_recent (self , agent_id : str , * , limit : int = 20 ) -> list [CarePushRecord ]:
206+ """Return the most recent care push rows for *agent_id*."""
207+ with self ._db .connect () as conn :
208+ rows = conn .execute (
209+ "SELECT id, agent_id, session_key, episode_id, pushed_at, "
210+ "thread_id, message_id, care_text, status, replied_at, reply_message_id "
211+ "FROM care_push_records WHERE agent_id = ? "
212+ "ORDER BY pushed_at DESC LIMIT ?" ,
213+ (agent_id , limit ),
214+ ).fetchall ()
215+ return [CarePushRecord .from_row (r ) for r in rows ]
216+
49217 def latest_pushed_at (self , agent_id : str ) -> int | None :
50218 """Unix time of the most recent care push for ``agent_id``, if any."""
51219 with self ._db .connect () as conn :
0 commit comments