Coverage for app / services / knowledge / source_map / builder.py: 97%
150 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 source map, built from evidence: pure, so it is tested without a
2database (``loader.py`` reads what it needs).
4Nodes are the repository's sources (``source``), the workspace's sources
5outside it the evidence ties to it (``suggestion``), and the agents it is
6granted to (``agent``). Edges between sources are ``evidence``: one per
7connected pair, weighted by its kinds together (:func:`combine`) and
8carrying each kind's count, score and examples. Edges from an agent are
9``cited_by``: the share of its answers' citations of this repository that
10went to that source.
11"""
13from __future__ import annotations
15from collections import defaultdict
16from collections.abc import Iterable, Mapping
17from dataclasses import dataclass, field
18from typing import Any
19from uuid import UUID
21from ..recommendations.base import fingerprint
22from .evidence import Example, PairEvidence, get_kind, pair
24#: Members drawn; past it the map says it was truncated.
25MAX_MEMBERS = 60
26#: Each source's strongest connections to the others drawn, and all edges
27#: together.
28MAX_EDGES_PER_NODE = 6
29MAX_EDGES = 300
30#: Suggestions offered, how strong their tie to the repository must be, and
31#: how many of each one's ties are drawn (its strongest).
32MAX_SUGGESTIONS = 8
33MIN_SUGGESTION_WEIGHT = 0.25
34MAX_SUGGESTION_EDGES = 2
37@dataclass
38class SourceInfo:
39 id: UUID
40 name: str
41 source_type: str
42 items: int = 0
43 #: The trust signals asking for a look (``trust.needs_attention``).
44 attention: list[str] = field(default_factory=list)
45 is_system: bool = False
46 is_ai_generated: bool = False
49@dataclass
50class AgentInfo:
51 id: UUID
52 name: str
55@dataclass
56class EdgeEvidence:
57 kind: str
58 count: float
59 score: float
60 contribution: float
61 examples: list[Example]
64@dataclass
65class MapNode:
66 id: str
67 kind: str
68 ref_id: UUID
69 label: str
70 meta: dict[str, Any]
73@dataclass
74class MapEdge:
75 source: str
76 target: str
77 kind: str
78 weight: float
79 evidence: list[EdgeEvidence] = field(default_factory=list)
82@dataclass
83class SourceMap:
84 nodes: list[MapNode]
85 edges: list[MapEdge]
86 summary: dict[str, Any]
87 truncated: bool = False
90def node_id(kind: str, ref: UUID) -> str:
91 return f"{'agent' if kind == 'agent' else 'source'}:{ref}"
94def combine(evidence: Iterable[PairEvidence]) -> tuple[float, list[EdgeEvidence]]:
95 """A pair's weight from its kinds: ``1 − Π(1 − strength × score)`` — each
96 kind adds to what the others leave, so two kinds of evidence read
97 stronger than either, and no number of them passes 1. Disclosed, never a
98 judgement of the sources: it orders and draws the map."""
99 remaining = 1.0
100 parts: list[EdgeEvidence] = []
101 for item in evidence:
102 kind = get_kind(item.kind)
103 if kind is None or item.count <= 0:
104 continue
105 score = kind.score(item.count)
106 contribution = kind.strength * score
107 remaining *= 1 - contribution
108 parts.append(
109 EdgeEvidence(
110 item.kind,
111 item.count,
112 round(score, 4),
113 round(contribution, 4),
114 item.examples[:3],
115 )
116 )
117 parts.sort(key=lambda p: p.contribution, reverse=True)
118 return round(1 - remaining, 4), parts
121def _source_node(info: SourceInfo, kind: str) -> MapNode:
122 return MapNode(
123 id=node_id("source", info.id),
124 kind=kind,
125 ref_id=info.id,
126 label=info.name,
127 meta={
128 "source_type": info.source_type,
129 "items": info.items,
130 "attention": info.attention,
131 "is_system": info.is_system,
132 "is_ai_generated": info.is_ai_generated,
133 },
134 )
137def suggestion_fingerprint(weight: float, kinds: Iterable[str]) -> str:
138 """What a suggestion's evidence reads, for setting it aside while it
139 holds: its tie to the repository, to a tenth, and the kinds behind it."""
140 return fingerprint(f"{weight:.1f}", *sorted(set(kinds)))
143def build_map(
144 *,
145 members: list[SourceInfo],
146 candidates: list[SourceInfo],
147 evidence: list[PairEvidence],
148 agents: list[AgentInfo] | None = None,
149 agent_citations: dict[tuple[UUID, UUID], int] | None = None,
150 unavailable: dict[str, str] | None = None,
151 dismissed: Mapping[UUID, str] | None = None,
152) -> SourceMap:
153 """The map of ``members``, with the ``candidates`` the evidence ties to
154 them as suggestions and ``agents`` (``None``: not asked for) beside.
155 ``dismissed`` is each suggestion the workspace set aside, by the
156 fingerprint its evidence read then: it stays aside while that holds."""
157 truncated = len(members) > MAX_MEMBERS
158 members = members[:MAX_MEMBERS]
159 member_ids = {m.id for m in members}
160 by_id = {c.id: c for c in candidates if c.id not in member_ids}
161 by_id.update({m.id: m for m in members})
163 grouped: dict[tuple[UUID, UUID], list[PairEvidence]] = defaultdict(list)
164 for item in evidence:
165 a, b = pair(item.a, item.b)
166 if a == b or a not in by_id or b not in by_id:
167 continue
168 if a not in member_ids and b not in member_ids:
169 continue
170 grouped[(a, b)].append(item)
172 weighted: list[tuple[float, UUID, UUID, list[EdgeEvidence]]] = []
173 for (a, b), items in grouped.items():
174 weight, parts = combine(items)
175 if weight > 0:
176 weighted.append((weight, a, b, parts))
177 weighted.sort(key=lambda w: (-w[0], str(w[1]), str(w[2])))
179 # Suggestions: the candidates most strongly tied to the repository.
180 strongest: dict[UUID, float] = defaultdict(float)
181 tied_by: dict[UUID, set[str]] = defaultdict(set)
182 for weight, a, b, parts in weighted:
183 for end, other in ((a, b), (b, a)):
184 if end not in member_ids and other in member_ids:
185 strongest[end] = max(strongest[end], weight)
186 tied_by[end].update(p.kind for p in parts)
187 prints = {
188 cid: suggestion_fingerprint(w, tied_by[cid]) for cid, w in strongest.items()
189 }
190 aside = dismissed or {}
191 eligible = [
192 cid
193 for cid, w in sorted(strongest.items(), key=lambda kv: (-kv[1], str(kv[0])))
194 if w >= MIN_SUGGESTION_WEIGHT
195 ]
196 set_aside = [cid for cid in eligible if aside.get(cid) == prints[cid]]
197 suggested = [cid for cid in eligible if cid not in set_aside][:MAX_SUGGESTIONS]
198 shown = member_ids | set(suggested)
200 # The members' own connections first, so a suggestion never crowds one
201 # out; each member keeps its strongest. Then each suggestion's strongest
202 # ties, outside the members' allowance: they are drawn apart, dashed.
203 member_pairs = [w for w in weighted if w[1] in member_ids and w[2] in member_ids]
204 edges: list[MapEdge] = []
205 per_node: dict[UUID, int] = defaultdict(int)
206 for weight, a, b, parts in member_pairs:
207 if per_node[a] >= MAX_EDGES_PER_NODE or per_node[b] >= MAX_EDGES_PER_NODE:
208 truncated = True
209 continue
210 if len(edges) >= MAX_EDGES:
211 truncated = True
212 break
213 per_node[a] += 1
214 per_node[b] += 1
215 edges.append(_evidence_edge(weight, a, b, parts))
217 ties: dict[UUID, int] = defaultdict(int)
218 for weight, a, b, parts in weighted:
219 candidate = b if a in member_ids else a
220 if candidate in member_ids or candidate not in shown:
221 continue
222 if ties[candidate] >= MAX_SUGGESTION_EDGES:
223 continue
224 if len(edges) >= MAX_EDGES:
225 truncated = True
226 break
227 ties[candidate] += 1
228 edges.append(_evidence_edge(weight, a, b, parts))
230 nodes = [_source_node(m, "source") for m in members]
231 for cid in suggested:
232 node = _source_node(by_id[cid], "suggestion")
233 node.meta["fingerprint"] = prints[cid]
234 nodes.append(node)
236 if agents is not None:
237 citations = agent_citations or {}
238 for agent in agents:
239 total = sum(n for (aid, _), n in citations.items() if aid == agent.id)
240 nodes.append(
241 MapNode(
242 id=node_id("agent", agent.id),
243 kind="agent",
244 ref_id=agent.id,
245 label=agent.name,
246 meta={"cited": total},
247 )
248 )
249 for (aid, kid), n in sorted(
250 citations.items(), key=lambda kv: str(kv[0][1])
251 ):
252 if aid != agent.id or kid not in member_ids or not total:
253 continue
254 edges.append(
255 MapEdge(
256 node_id("agent", agent.id),
257 node_id("source", kid),
258 "cited_by",
259 round(n / total, 4),
260 )
261 )
263 # Counted over every pair, drawn or not: the figures say what is there.
264 connected = {end for _, a, b, _ in member_pairs for end in (a, b)}
265 summary = {
266 "sources": len(members),
267 "connections": len(member_pairs),
268 "suggestions": len(suggested),
269 "suggestions_set_aside": len(set_aside),
270 "isolated": sum(1 for m in members if m.id not in connected),
271 "duplicates": sum(
272 1
273 for _, _, _, parts in member_pairs
274 if any(p.kind == "same_document" for p in parts)
275 ),
276 "unavailable": dict(unavailable or {}),
277 }
278 return SourceMap(nodes=nodes, edges=edges, summary=summary, truncated=truncated)
281def _evidence_edge(
282 weight: float, a: UUID, b: UUID, parts: list[EdgeEvidence]
283) -> MapEdge:
284 return MapEdge(
285 node_id("source", a), node_id("source", b), "evidence", weight, parts
286 )