Coverage for app / services / network / knowledge.py: 98%
133 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""The knowledge network: which agents can reach which knowledge.
3Agents never integrate a source directly — they are granted whole
4repositories, and a repository expands to its member sources at inference
5time (``agents/transformers._load_agent_knowledge_bases``). So the network is
6three layers joined by two kinds of edge, ``grant`` and ``member``, plus each
7agent's memory store beside it.
9What it answers is *reach*: a grant is what an agent may retrieve from. Use —
10which sources answers actually cited — is the citations record
11(``knowledge_citations``, ``services/knowledge/citations.py``), read by the
12knowledge pages; this network still draws reach. The summary counts sources
13several agents share and sources no agent reaches — the second is a
14governance finding in its own right (knowledge somebody indexed that nothing
15will ever read), and neither needs a model to compute.
16"""
18from __future__ import annotations
20import logging
21from collections import defaultdict
22from collections.abc import Iterable
23from typing import Any
24from uuid import UUID
26from sqlalchemy import func
27from sqlalchemy.orm import Session
29from app.db.postgres.models import (
30 Agent,
31 AgentRepository,
32 Knowledge,
33 KnowledgeDocument,
34 KnowledgeRepository,
35 RepositoryKnowledge,
36 User,
37)
38from app.services import ai_client
40from .graph import Network, NetworkEdge, NetworkNode, appearance, node_id
42logger = logging.getLogger(__name__)
44#: Caps per layer. A board tile, not an export: past these the network says
45#: it was truncated rather than drawing a hairball.
46MAX_AGENTS = 50
47MAX_REPOSITORIES = 100
48MAX_SOURCES = 200
51def _item_count(kb: Any, documents: dict[str, int]) -> int:
52 """What a source holds: documents or pages, or a graph's entities.
54 A graph source keeps its counts in ``source_config`` (updated on save);
55 only that integer is read, never the rest of a config that may hold
56 credentials for other source types.
57 """
58 if kb.source_type == "graph":
59 config = kb.source_config if isinstance(kb.source_config, dict) else {}
60 count = config.get("node_count")
61 return count if isinstance(count, int) else 0
62 return documents.get(str(kb.id), 0)
65def build_network(
66 *,
67 agents: Iterable[Any],
68 repositories: Iterable[Any],
69 knowledge: Iterable[Any],
70 grants: Iterable[tuple[Any, Any]],
71 members: Iterable[tuple[Any, Any]],
72 documents: dict[str, int] | None = None,
73 memory: dict[str, dict] | None = None,
74 include_unconnected: bool = True,
75) -> Network:
76 """Join agents, repositories and sources into a layered graph.
78 ``grants`` are ``(agent_id, repository_id)`` and ``members``
79 ``(repository_id, knowledge_id)``. ``memory`` maps an agent id to svc-ai's
80 memory summary; ``None`` means memory was not asked for, or could not be
81 read — the summary says which rather than reporting zero entries.
83 With ``include_unconnected`` false, only what some agent reaches is drawn.
84 """
85 documents = documents or {}
86 agent_rows = {str(a.id): a for a in agents}
87 repo_rows = {str(r.id): r for r in repositories}
88 kb_rows = {str(k.id): k for k in knowledge}
90 grant_pairs = {
91 (str(a), str(r))
92 for a, r in grants
93 if str(a) in agent_rows and str(r) in repo_rows
94 }
95 member_pairs = {
96 (str(r), str(k))
97 for r, k in members
98 if str(r) in repo_rows and str(k) in kb_rows
99 }
101 repos_of_agent: dict[str, set[str]] = defaultdict(set)
102 agents_of_repo: dict[str, set[str]] = defaultdict(set)
103 for a, r in grant_pairs:
104 repos_of_agent[a].add(r)
105 agents_of_repo[r].add(a)
106 kbs_of_repo: dict[str, set[str]] = defaultdict(set)
107 repos_of_kb: dict[str, set[str]] = defaultdict(set)
108 for r, k in member_pairs:
109 kbs_of_repo[r].add(k)
110 repos_of_kb[k].add(r)
112 # Reach: the agents a source is retrievable by, through any repository.
113 reach: dict[str, set[str]] = defaultdict(set)
114 for k, repos in repos_of_kb.items():
115 for r in repos:
116 reach[k] |= agents_of_repo[r]
117 agent_sources: dict[str, set[str]] = defaultdict(set)
118 for k, holders in reach.items():
119 for a in holders:
120 agent_sources[a].add(k)
122 if not include_unconnected:
123 repo_rows = {r: row for r, row in repo_rows.items() if agents_of_repo[r]}
124 kb_rows = {k: row for k, row in kb_rows.items() if reach[k]}
126 truncated = False
128 def _capped(rows: dict[str, Any], order, cap: int) -> list[str]:
129 nonlocal truncated
130 ordered = sorted(rows, key=order)
131 if len(ordered) > cap:
132 truncated = True
133 return ordered[:cap]
135 agent_ids = _capped(
136 agent_rows, lambda a: (-len(agent_sources[a]), agent_rows[a].name), MAX_AGENTS
137 )
138 repo_ids = _capped(
139 repo_rows,
140 lambda r: (-len(agents_of_repo[r]), repo_rows[r].name),
141 MAX_REPOSITORIES,
142 )
143 kb_ids = _capped(kb_rows, lambda k: (-len(reach[k]), kb_rows[k].name), MAX_SOURCES)
144 kept = {*agent_ids, *repo_ids, *kb_ids}
146 nodes: list[NetworkNode] = []
147 edges: list[NetworkEdge] = []
148 memory_entries = 0
150 for a in agent_ids:
151 row = agent_rows[a]
152 summary = (memory or {}).get(a)
153 entries = int(summary.get("entries") or 0) if summary else None
154 nodes.append(
155 NetworkNode(
156 id=node_id("agent", a),
157 kind="agent",
158 label=row.name,
159 ref_id=a,
160 meta={
161 **appearance(row),
162 "repositories": len(repos_of_agent[a]),
163 "sources": len(agent_sources[a]),
164 "memory_entries": entries,
165 },
166 )
167 )
168 if summary and entries:
169 memory_entries += entries
170 nodes.append(
171 NetworkNode(
172 id=node_id("memory", a),
173 kind="memory",
174 label=f"{entries} memor{'y' if entries == 1 else 'ies'}",
175 ref_id=a,
176 meta={
177 "entries": entries,
178 "conversations": len(summary.get("conversations") or []),
179 "last_written_at": summary.get("last_written_at"),
180 },
181 )
182 )
183 edges.append(
184 NetworkEdge(node_id("agent", a), node_id("memory", a), "memory")
185 )
187 for r in repo_ids:
188 row = repo_rows[r]
189 nodes.append(
190 NetworkNode(
191 id=node_id("repository", r),
192 kind="repository",
193 label=row.name,
194 ref_id=r,
195 meta={
196 **appearance(row),
197 "sources": len(kbs_of_repo[r]),
198 "agents": len(agents_of_repo[r]),
199 },
200 )
201 )
203 for k in kb_ids:
204 row = kb_rows[k]
205 nodes.append(
206 NetworkNode(
207 id=node_id("knowledge", k),
208 kind="knowledge",
209 label=row.name,
210 ref_id=k,
211 meta={
212 **appearance(row),
213 "source_type": row.source_type,
214 "items": _item_count(row, documents),
215 "repositories": len(repos_of_kb[k]),
216 "agents": len(reach[k]),
217 },
218 )
219 )
221 for a, r in sorted(grant_pairs):
222 if a in kept and r in kept:
223 edges.append(
224 NetworkEdge(node_id("agent", a), node_id("repository", r), "grant")
225 )
226 for r, k in sorted(member_pairs):
227 if r in kept and k in kept:
228 edges.append(
229 NetworkEdge(node_id("repository", r), node_id("knowledge", k), "member")
230 )
232 return Network(
233 nodes=nodes,
234 edges=edges,
235 truncated=truncated,
236 summary={
237 "agents": len(agent_rows),
238 "repositories": len(repo_rows),
239 "sources": len(kb_rows),
240 "reachable_sources": sum(1 for k in kb_rows if reach[k]),
241 "shared_sources": sum(1 for k in kb_rows if len(reach[k]) > 1),
242 "unreachable_sources": sum(1 for k in kb_rows if not reach[k]),
243 "agents_without_knowledge": sum(
244 1 for a in agent_rows if not agent_sources[a]
245 ),
246 "memory_entries": memory_entries if memory is not None else None,
247 },
248 )
251# --------------------------------------------------------------------------- #
252# Loader
253# --------------------------------------------------------------------------- #
256def memory_summaries(
257 agent_ids: list[str], *, recent: int = 0, user_id: str | None = None
258) -> dict[str, dict] | None:
259 """svc-ai's memory summary keyed by agent, or None when it cannot answer.
261 None rather than an empty dict, so a caller can say "memory unavailable"
262 instead of drawing a fleet that apparently remembers nothing.
263 """
264 if not agent_ids:
265 return {}
266 try:
267 rows = ai_client.summarise_agent_memory(
268 agent_ids, recent=recent, user_id=user_id
269 )
270 except ai_client.AIServiceError as exc:
271 logger.warning("Memory summary unavailable: %s", exc)
272 return None
273 return {str(row.get("agent_id")): row for row in rows if isinstance(row, dict)}
276def _memory_user(ws, user: User) -> str:
277 """Whose memory to count: the viewer's own, in every workspace. An agent
278 remembers each person who chats with it separately — a personal agent
279 too, which its owner's personal projects inherit — and counting it
280 agent-wide showed one person what it remembered of another's
281 conversations."""
282 return str(user.id)
285def load_network(
286 db: Session,
287 user: User,
288 *,
289 ws=None,
290 agent_ids: list[UUID] | None = None,
291 include_memory: bool = True,
292 include_unconnected: bool = True,
293) -> Network:
294 """A workspace's agents, repositories and sources, joined.
296 Scoped to the workspace ``ws`` (``app/services/workspace.py``; the
297 caller's Personal when None), as the resource listings are — its own and,
298 in a project, what it inherits — plus any system repository (the CHAIN-R
299 User Guide) one of its agents has been granted, since the grant is what
300 makes it part of the network. CHAINR Bot itself is not drawn: it is
301 every user's, not one of the workspace's. Outside Personal, memory is
302 the caller's own with each agent: an organisation's agent remembers each
303 member separately, and the others' entries are theirs.
305 Naming ``agent_ids`` narrows the view to those agents and what they
306 reach; an id the caller does not own is ignored, never an error, so a
307 tile outliving an agent still renders the rest.
308 """
309 from app.services import workspace as workspace_service
311 ws = ws or workspace_service.Workspace(
312 workspace_service.WorkspaceKind.personal, user.id
313 )
314 agent_query = db.query(Agent).filter(
315 workspace_service.in_scope(Agent, ws, system=False)
316 )
317 if agent_ids:
318 agent_query = agent_query.filter(Agent.id.in_(agent_ids))
319 agents = agent_query.all()
320 owned_agent_ids = [a.id for a in agents]
322 grants = (
323 db.query(AgentRepository.agent_id, AgentRepository.repository_id)
324 .filter(AgentRepository.agent_id.in_(owned_agent_ids))
325 .all()
326 if owned_agent_ids
327 else []
328 )
329 granted_repo_ids = {r for _, r in grants}
331 repo_query = db.query(KnowledgeRepository)
332 if agent_ids:
333 # A focused view is the agents' own reach, not the whole library.
334 repositories = (
335 repo_query.filter(KnowledgeRepository.id.in_(granted_repo_ids)).all()
336 if granted_repo_ids
337 else []
338 )
339 else:
340 repositories = [
341 *repo_query.filter(
342 workspace_service.in_scope(KnowledgeRepository, ws, system=False)
343 ).all(),
344 *(
345 repo_query.filter(
346 KnowledgeRepository.id.in_(granted_repo_ids),
347 KnowledgeRepository.is_system.is_(True),
348 ).all()
349 if granted_repo_ids
350 else []
351 ),
352 ]
353 repo_ids = [r.id for r in repositories]
355 members = (
356 db.query(RepositoryKnowledge.repository_id, RepositoryKnowledge.knowledge_id)
357 .filter(RepositoryKnowledge.repository_id.in_(repo_ids))
358 .all()
359 if repo_ids
360 else []
361 )
362 member_kb_ids = {k for _, k in members}
364 knowledge: list[Knowledge] = (
365 db.query(Knowledge).filter(Knowledge.id.in_(member_kb_ids)).all()
366 if member_kb_ids
367 else []
368 )
369 if not agent_ids and include_unconnected:
370 # Sources in no repository at all: indexed, and reachable by nothing.
371 seen = {k.id for k in knowledge}
372 knowledge += [
373 k
374 for k in db.query(Knowledge)
375 .filter(workspace_service.in_scope(Knowledge, ws, system=False))
376 .all()
377 if k.id not in seen
378 ]
380 kb_ids = [k.id for k in knowledge if k.source_type != "graph"]
381 documents = (
382 {
383 str(kid): int(count)
384 for kid, count in db.query(
385 KnowledgeDocument.knowledge_id, func.count(KnowledgeDocument.id)
386 )
387 .filter(KnowledgeDocument.knowledge_id.in_(kb_ids))
388 .group_by(KnowledgeDocument.knowledge_id)
389 .all()
390 }
391 if kb_ids
392 else {}
393 )
395 memory = (
396 memory_summaries(
397 [str(a) for a in owned_agent_ids[:MAX_AGENTS]],
398 user_id=_memory_user(ws, user),
399 )
400 if include_memory
401 else None
402 )
404 return build_network(
405 agents=agents,
406 repositories=repositories,
407 knowledge=knowledge,
408 grants=grants,
409 members=members,
410 documents=documents,
411 memory=memory,
412 include_unconnected=include_unconnected,
413 )
416def load_source_network(
417 db: Session,
418 user: User,
419 *,
420 ws,
421 knowledge_ids: list[UUID],
422 include_memory: bool = False,
423) -> Network:
424 """Where sources are used, in the workspace ``ws``: the repositories
425 holding them (its own, what it inherits, and the built-ins), the
426 workspace's agents those are granted to, and the sources themselves —
427 what a source's page draws. Never another workspace's agents: a
428 built-in source is held by many, and whose is theirs."""
429 from app.services import workspace as workspace_service
431 knowledge = (
432 db.query(Knowledge).filter(Knowledge.id.in_(knowledge_ids)).all()
433 if knowledge_ids
434 else []
435 )
436 kb_ids = [k.id for k in knowledge]
437 members = (
438 db.query(RepositoryKnowledge.repository_id, RepositoryKnowledge.knowledge_id)
439 .join(
440 KnowledgeRepository,
441 KnowledgeRepository.id == RepositoryKnowledge.repository_id,
442 )
443 .filter(
444 RepositoryKnowledge.knowledge_id.in_(kb_ids),
445 workspace_service.in_scope(KnowledgeRepository, ws, system=True),
446 )
447 .all()
448 if kb_ids
449 else []
450 )
451 repo_ids = list({r for r, _ in members})
452 repositories = (
453 db.query(KnowledgeRepository).filter(KnowledgeRepository.id.in_(repo_ids)).all()
454 if repo_ids
455 else []
456 )
457 grants = (
458 db.query(AgentRepository.agent_id, AgentRepository.repository_id)
459 .join(Agent, Agent.id == AgentRepository.agent_id)
460 .filter(
461 AgentRepository.repository_id.in_(repo_ids),
462 workspace_service.in_scope(Agent, ws, system=False),
463 )
464 .all()
465 if repo_ids
466 else []
467 )
468 agent_ids = list({a for a, _ in grants})
469 agents = db.query(Agent).filter(Agent.id.in_(agent_ids)).all() if agent_ids else []
470 documents = (
471 {
472 str(kid): int(count)
473 for kid, count in db.query(
474 KnowledgeDocument.knowledge_id, func.count(KnowledgeDocument.id)
475 )
476 .filter(
477 KnowledgeDocument.knowledge_id.in_(
478 [k.id for k in knowledge if k.source_type != "graph"]
479 )
480 )
481 .group_by(KnowledgeDocument.knowledge_id)
482 .all()
483 }
484 if kb_ids
485 else {}
486 )
487 memory = (
488 memory_summaries(
489 [str(a) for a in agent_ids[:MAX_AGENTS]], user_id=_memory_user(ws, user)
490 )
491 if include_memory and agent_ids
492 else None
493 )
494 return build_network(
495 agents=agents,
496 repositories=repositories,
497 knowledge=knowledge,
498 grants=grants,
499 members=members,
500 documents=documents,
501 memory=memory,
502 )