Coverage for app / services / network / memory.py: 96%

72 statements  

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

1"""The memory graph: what agents remember, conversation by conversation. 

2 

3svc-ai writes one memory entry per completed turn — the task and a digest of 

4the answer — keyed by agent, user and conversation (``agents/graph.py``, 

5the memory-write node). The planner reads them back on later turns, so this 

6is the part of an agent's context that grows on its own, and the part nobody 

7granted explicitly. The graph is agent → conversation → entry: which chats an 

8agent carries forward, and what it took from each. 

9 

10A conversation deleted since stays on the graph, marked as such — its memory 

11outlives it, which is exactly the thing worth seeing. 

12""" 

13 

14from __future__ import annotations 

15 

16from collections.abc import Iterable 

17from typing import Any 

18from uuid import UUID 

19 

20from sqlalchemy.orm import Session 

21 

22from app.db.postgres.models import Agent, Conversation, User 

23 

24from .graph import Network, NetworkEdge, NetworkNode, appearance, node_id 

25from .knowledge import MAX_AGENTS, memory_summaries 

26 

27#: Newest conversations drawn per agent; the rest fold into one node. 

28MAX_CONVERSATIONS_PER_AGENT = 12 

29 

30 

31def build_memory_graph( 

32 *, 

33 agents: Iterable[Any], 

34 summaries: dict[str, dict] | None, 

35 existing_conversations: set[str], 

36) -> Network: 

37 """Join svc-ai's per-agent summaries into agent → conversation → entry. 

38 

39 Entries are drawn only as far as each summary's ``recent`` list goes; a 

40 conversation carries its full entry count regardless. ``summaries`` of 

41 None means svc-ai could not answer, and the summary says so. 

42 """ 

43 nodes: list[NetworkNode] = [] 

44 edges: list[NetworkEdge] = [] 

45 truncated = False 

46 totals = {"agents": 0, "conversations": 0, "entries": 0, "orphaned": 0} 

47 

48 for agent in agents: 

49 a = str(agent.id) 

50 summary = (summaries or {}).get(a) or {} 

51 conversations = list(summary.get("conversations") or []) 

52 entries = int(summary.get("entries") or 0) 

53 totals["agents"] += 1 

54 totals["entries"] += entries 

55 agent_node = node_id("agent", a) 

56 nodes.append( 

57 NetworkNode( 

58 id=agent_node, 

59 kind="agent", 

60 label=agent.name, 

61 ref_id=a, 

62 meta={ 

63 **appearance(agent), 

64 "memory_entries": entries if summaries is not None else None, 

65 "conversations": len(conversations), 

66 "last_written_at": summary.get("last_written_at"), 

67 }, 

68 ) 

69 ) 

70 

71 shown = conversations[:MAX_CONVERSATIONS_PER_AGENT] 

72 folded = conversations[MAX_CONVERSATIONS_PER_AGENT:] 

73 conv_nodes: dict[str | None, str] = {} 

74 for conv in shown: 

75 cid = conv.get("conversation_id") 

76 exists = cid is not None and cid in existing_conversations 

77 totals["conversations"] += 1 

78 if cid is not None and not exists: 

79 totals["orphaned"] += 1 

80 nid = node_id("conversation", f"{a}:{cid or 'none'}") 

81 conv_nodes[cid] = nid 

82 nodes.append( 

83 NetworkNode( 

84 id=nid, 

85 kind="conversation", 

86 label=( 

87 "Conversation" 

88 if exists 

89 else "Deleted conversation" 

90 if cid 

91 else "Outside a conversation" 

92 ), 

93 # Only a live conversation is something to open. 

94 ref_id=cid if exists else None, 

95 meta={ 

96 "agent_id": a, 

97 "entries": int(conv.get("entries") or 0), 

98 "last_written_at": conv.get("last_written_at"), 

99 "deleted": bool(cid) and not exists, 

100 }, 

101 ) 

102 ) 

103 edges.append(NetworkEdge(agent_node, nid, "conversation")) 

104 

105 if folded: 

106 truncated = True 

107 totals["conversations"] += len(folded) 

108 nid = node_id("conversation", f"{a}:older") 

109 nodes.append( 

110 NetworkNode( 

111 id=nid, 

112 kind="conversation", 

113 label=f"{len(folded)} older conversation{'s' if len(folded) != 1 else ''}", 

114 meta={ 

115 "agent_id": a, 

116 "entries": sum(int(c.get("entries") or 0) for c in folded), 

117 "last_written_at": folded[0].get("last_written_at"), 

118 "folded": len(folded), 

119 }, 

120 ) 

121 ) 

122 edges.append(NetworkEdge(agent_node, nid, "conversation")) 

123 

124 for entry in summary.get("recent") or []: 

125 parent = conv_nodes.get(entry.get("conversation_id")) 

126 if parent is None: # in a folded conversation 

127 continue 

128 eid = node_id("memory_entry", entry.get("id")) 

129 nodes.append( 

130 NetworkNode( 

131 id=eid, 

132 kind="memory_entry", 

133 label=entry.get("task") or "(no task recorded)", 

134 ref_id=entry.get("id"), 

135 meta={"created_at": entry.get("created_at")}, 

136 ) 

137 ) 

138 edges.append(NetworkEdge(parent, eid, "entry")) 

139 

140 return Network( 

141 nodes=nodes, 

142 edges=edges, 

143 truncated=truncated, 

144 summary={ 

145 "agents": totals["agents"], 

146 "conversations": totals["conversations"], 

147 "entries": totals["entries"] if summaries is not None else None, 

148 "deleted_conversations": totals["orphaned"], 

149 "memory_available": summaries is not None, 

150 }, 

151 ) 

152 

153 

154def load_memory_graph( 

155 db: Session, 

156 user: User, 

157 *, 

158 ws=None, 

159 agent_ids: list[UUID] | None = None, 

160 recent: int = 20, 

161) -> Network: 

162 """A workspace's agents' memory (the caller's Personal when ``ws`` is 

163 None), or the named agents' among them. 

164 

165 Memory is written per (agent, user). A person's own agents' memory is 

166 theirs alone; a shared workspace's agents remember every member, so 

167 there only the caller's entries are read — an agent-wide read would 

168 disclose the others'. CHAINR Bot is left out, as it is from the 

169 knowledge network. 

170 """ 

171 from app.services import workspace as workspace_service 

172 from app.services.network.knowledge import _memory_user 

173 

174 ws = ws or workspace_service.Workspace( 

175 workspace_service.WorkspaceKind.personal, user.id 

176 ) 

177 query = db.query(Agent).filter(workspace_service.in_scope(Agent, ws, system=False)) 

178 if agent_ids: 

179 query = query.filter(Agent.id.in_(agent_ids)) 

180 agents = sorted(query.all(), key=lambda a: a.name)[:MAX_AGENTS] 

181 

182 summaries = memory_summaries( 

183 [str(a.id) for a in agents], recent=recent, user_id=_memory_user(ws, user) 

184 ) 

185 # Agents that remember nothing add a lone node each; leave them off a 

186 # fleet view, keep them when named (an empty answer is still an answer). 

187 if summaries is not None and not agent_ids: 

188 agents = [a for a in agents if (summaries.get(str(a.id)) or {}).get("entries")] 

189 

190 conv_ids = { 

191 c.get("conversation_id") 

192 for s in (summaries or {}).values() 

193 for c in s.get("conversations") or [] 

194 if c.get("conversation_id") 

195 } 

196 existing: set[str] = set() 

197 if conv_ids: 

198 parsed = [] 

199 for cid in conv_ids: 

200 try: 

201 parsed.append(UUID(str(cid))) 

202 except ValueError: 

203 continue 

204 existing = { 

205 str(cid) 

206 for (cid,) in db.query(Conversation.id) 

207 .filter(Conversation.id.in_(parsed), Conversation.owner_user_id == user.id) 

208 .all() 

209 } 

210 

211 return build_memory_graph( 

212 agents=agents, summaries=summaries, existing_conversations=existing 

213 )