Coverage for app / routers / memory.py: 100%

100 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1from uuid import UUID 

2 

3from fastapi import APIRouter, Depends, HTTPException, Query 

4from pydantic import BaseModel 

5from sqlalchemy.orm import Session 

6 

7from app.db.postgres.models import AgentMemory 

8from app.dependency.base import get_db 

9from app.memory.kinds import MemoryKind, parse 

10from app.util.time import UTCDateTime, utc_isoformat 

11 

12router = APIRouter(prefix="/memory", tags=["memory"]) 

13 

14 

15class MemoryEntryOut(BaseModel): 

16 id: str 

17 user_id: str 

18 external_agent_id: str | None 

19 conversation_id: str | None 

20 memory_key: str 

21 content: str 

22 created_at: str 

23 #: ``app.memory.kinds.MemoryKind``: an episode (one turn) or a curated 

24 #: memory kept from the person's own words — which ``evidence`` holds. 

25 kind: str = MemoryKind.episode.value 

26 evidence: str | None = None 

27 workspace: str | None = None 

28 #: A temporary memory's end; recall leaves it out afterwards. 

29 expires_at: UTCDateTime | None = None 

30 #: Replaced by a correction (the replacing memory), and when. 

31 superseded_at: UTCDateTime | None = None 

32 superseded_by: str | None = None 

33 #: When the person last restated it. 

34 confirmed_at: UTCDateTime | None = None 

35 #: How often, and when last, recall sent it to a model. 

36 recall_count: int = 0 

37 last_recalled_at: UTCDateTime | None = None 

38 

39 

40def _scoped(query, user_id: str | None): 

41 """Narrow to one user's entries when ``user_id`` is given. 

42 

43 Memory is written per (agent, user). An agent one principal owns is 

44 managed agent-wide; one every user shares (CHAINR Bot) is managed per 

45 user, and svc-core passes ``user_id`` for it — without it, listing would 

46 disclose every user's memories and clearing would wipe them. 

47 """ 

48 if user_id: 

49 query = query.filter(AgentMemory.user_id == user_id) 

50 return query 

51 

52 

53class MemoryConversationSummary(BaseModel): 

54 conversation_id: str | None 

55 entries: int 

56 last_written_at: UTCDateTime 

57 

58 

59class MemoryRecentEntry(BaseModel): 

60 id: str 

61 conversation_id: str | None 

62 #: The task an episode remembers (its first line, without the prefix), 

63 #: or a curated memory's statement. 

64 task: str 

65 created_at: UTCDateTime 

66 kind: str = MemoryKind.episode.value 

67 

68 

69class AgentMemorySummary(BaseModel): 

70 agent_id: str 

71 entries: int 

72 last_written_at: UTCDateTime | None 

73 conversations: list[MemoryConversationSummary] 

74 recent: list[MemoryRecentEntry] 

75 

76 

77#: How many agents one summary may span, and how many recent entries each 

78#: may carry — a dashboard tile's worth, not an export. 

79MAX_SUMMARY_AGENTS = 50 

80MAX_RECENT = 100 

81_TASK_CHARS = 140 

82 

83 

84def _task_of(content: str) -> str: 

85 """The remembered task, as the memory-write node formats an episode. 

86 

87 Episodes are ``"Task: …\\nResponse: …"`` (``app/memory/text.py``); a 

88 curated memory, or an entry written any other way, is its first line. 

89 """ 

90 first = (content or "").strip().split("\n", 1)[0] 

91 if first.startswith("Task:"): 

92 first = first[len("Task:") :].strip() 

93 return first[:_TASK_CHARS] 

94 

95 

96# Declared before ``/{agent_id}`` so "summary" is not read as an agent id. 

97@router.get("/summary", response_model=list[AgentMemorySummary]) 

98def summarise_agent_memory( 

99 agent_id: list[UUID] = Query(default_factory=list), 

100 user_id: str | None = None, 

101 recent: int = Query(default=0, ge=0, le=MAX_RECENT), 

102 db: Session = Depends(get_db), 

103): 

104 """How much each agent remembers, from which conversations. 

105 

106 Read by svc-core's network views: one call for a whole fleet, rather than 

107 listing every agent's entries to count them. ``recent`` adds that many of 

108 each agent's newest entries, as a task line rather than the full text. 

109 Every requested agent is answered, with zeroes if it remembers nothing. 

110 """ 

111 agent_ids = list(dict.fromkeys(agent_id))[:MAX_SUMMARY_AGENTS] 

112 if not agent_ids: 

113 return [] 

114 rows = ( 

115 _scoped( 

116 db.query(AgentMemory).filter(AgentMemory.external_agent_id.in_(agent_ids)), 

117 user_id, 

118 ) 

119 .order_by(AgentMemory.created_at.desc()) 

120 .all() 

121 ) 

122 

123 by_agent: dict[str, list] = {str(a): [] for a in agent_ids} 

124 for row in rows: 

125 key = str(row.external_agent_id) 

126 if key in by_agent: 

127 by_agent[key].append(row) 

128 

129 out: list[AgentMemorySummary] = [] 

130 for key, entries in by_agent.items(): 

131 # Newest first throughout: rows arrive that way, and a conversation's 

132 # first sighting is therefore its latest write. 

133 conversations: dict[str | None, MemoryConversationSummary] = {} 

134 for row in entries: 

135 conv = str(row.conversation_id) if row.conversation_id else None 

136 if conv in conversations: 

137 conversations[conv].entries += 1 

138 else: 

139 conversations[conv] = MemoryConversationSummary( 

140 conversation_id=conv, entries=1, last_written_at=row.created_at 

141 ) 

142 out.append( 

143 AgentMemorySummary( 

144 agent_id=key, 

145 entries=len(entries), 

146 last_written_at=entries[0].created_at if entries else None, 

147 conversations=list(conversations.values()), 

148 recent=[ 

149 MemoryRecentEntry( 

150 id=str(row.id), 

151 conversation_id=( 

152 str(row.conversation_id) if row.conversation_id else None 

153 ), 

154 task=_task_of(row.content), 

155 created_at=row.created_at, 

156 kind=parse(getattr(row, "kind", None)).value, 

157 ) 

158 for row in entries[:recent] 

159 ], 

160 ) 

161 ) 

162 return out 

163 

164 

165def _entry_out(r: AgentMemory) -> MemoryEntryOut: 

166 return MemoryEntryOut( 

167 id=str(r.id), 

168 user_id=r.user_id, 

169 external_agent_id=str(r.external_agent_id) if r.external_agent_id else None, 

170 conversation_id=str(r.conversation_id) if r.conversation_id else None, 

171 memory_key=r.memory_key, 

172 content=r.content, 

173 created_at=utc_isoformat(r.created_at), 

174 kind=parse(getattr(r, "kind", None)).value, 

175 evidence=getattr(r, "evidence", None), 

176 workspace=getattr(r, "workspace", None), 

177 expires_at=getattr(r, "expires_at", None), 

178 superseded_at=getattr(r, "superseded_at", None), 

179 superseded_by=( 

180 str(r.superseded_by) if getattr(r, "superseded_by", None) else None 

181 ), 

182 confirmed_at=getattr(r, "confirmed_at", None), 

183 recall_count=int(getattr(r, "recall_count", 0) or 0), 

184 last_recalled_at=getattr(r, "last_recalled_at", None), 

185 ) 

186 

187 

188@router.get("", response_model=list[MemoryEntryOut]) 

189def list_user_memory( 

190 user_id: str = Query(..., min_length=1), db: Session = Depends(get_db) 

191): 

192 """Everything any agent remembers from one user's conversations. 

193 

194 The user's data export reads this. Per agent would miss what a deleted 

195 agent still holds and what a shared agent (CHAINR Bot) remembers, and 

196 both are the user's. ``user_id`` is required: this route has no agent to 

197 narrow by, so without it it would return every user's memories. 

198 """ 

199 rows = ( 

200 db.query(AgentMemory) 

201 .filter(AgentMemory.user_id == user_id) 

202 .order_by(AgentMemory.created_at.asc()) 

203 .all() 

204 ) 

205 return [_entry_out(r) for r in rows] 

206 

207 

208@router.delete("", status_code=204) 

209def delete_user_memory( 

210 user_id: str = Query(..., min_length=1), db: Session = Depends(get_db) 

211): 

212 """Delete everything any agent remembers of one person — what svc-core 

213 calls when the person's account is deleted. ``user_id`` is required: 

214 without it this would delete every person's memories.""" 

215 db.query(AgentMemory).filter(AgentMemory.user_id == user_id).delete( 

216 synchronize_session=False 

217 ) 

218 db.commit() 

219 

220 

221@router.get("/{agent_id}", response_model=list[MemoryEntryOut]) 

222def list_agent_memory( 

223 agent_id: UUID, user_id: str | None = None, db: Session = Depends(get_db) 

224): 

225 rows = ( 

226 _scoped( 

227 db.query(AgentMemory).filter(AgentMemory.external_agent_id == agent_id), 

228 user_id, 

229 ) 

230 .order_by(AgentMemory.created_at.asc()) 

231 .all() 

232 ) 

233 return [_entry_out(r) for r in rows] 

234 

235 

236@router.delete("/{agent_id}/{memory_id}", status_code=204) 

237def delete_memory_entry( 

238 agent_id: UUID, 

239 memory_id: UUID, 

240 user_id: str | None = None, 

241 db: Session = Depends(get_db), 

242): 

243 row = _scoped( 

244 db.query(AgentMemory).filter( 

245 AgentMemory.id == memory_id, 

246 AgentMemory.external_agent_id == agent_id, 

247 ), 

248 user_id, 

249 ).first() 

250 if not row: 

251 raise HTTPException(status_code=404, detail="Memory entry not found") 

252 db.delete(row) 

253 db.commit() 

254 

255 

256@router.delete("/{agent_id}", status_code=204) 

257def clear_agent_memory( 

258 agent_id: UUID, user_id: str | None = None, db: Session = Depends(get_db) 

259): 

260 _scoped( 

261 db.query(AgentMemory).filter(AgentMemory.external_agent_id == agent_id), 

262 user_id, 

263 ).delete() 

264 db.commit()