| 255 | * @param nodes batch-resolved endpoint nodes (never a lookup per edge) |
| 256 | */ |
| 257 | export function groupRelations( |
| 258 | edges: readonly Edge[], |
| 259 | endpoint: (edge: Edge) => string, |
| 260 | nodes: Map<string, Node> |
| 261 | ): WireRelation[] { |
| 262 | const byNode = new Map<string, Edge[]>(); |
| 263 | for (const edge of edges) { |
| 264 | const id = endpoint(edge); |
| 265 | const bucket = byNode.get(id); |
| 266 | if (bucket) bucket.push(edge); |
| 267 | else byNode.set(id, [edge]); |
| 268 | } |
| 269 | |
| 270 | const relations: WireRelation[] = []; |
| 271 | for (const [id, group] of byNode) { |
| 272 | const node = nodes.get(id); |
| 273 | // An edge whose endpoint is missing from `nodes` means the graph and the |
| 274 | // node table disagree — skip it rather than invent a row. Callers still see |
| 275 | // it in the totals they computed from the raw edge list. |
| 276 | if (!node) continue; |
| 277 | const ordered = [...group].sort((a, b) => (a.line ?? 0) - (b.line ?? 0)); |
| 278 | const wireEdges = ordered.slice(0, MAX_EDGES_PER_GROUP).map(toWireEdge); |
| 279 | |
| 280 | const edgeKinds: EdgeKind[] = []; |
| 281 | for (const edge of ordered) if (!edgeKinds.includes(edge.kind)) edgeKinds.push(edge.kind); |
| 282 | |
| 283 | const lines = [ |
| 284 | ...new Set(ordered.map((e) => e.line).filter((l): l is number => typeof l === 'number' && l > 0)), |
| 285 | ].sort((a, b) => a - b); |
| 286 | |
| 287 | let confidence: number | null = null; |
| 288 | let synthesized = false; |
| 289 | for (const edge of ordered) { |
| 290 | const value = (edge.metadata as Record<string, unknown> | undefined)?.confidence; |
| 291 | if (typeof value === 'number' && (confidence === null || value > confidence)) confidence = value; |
| 292 | if (edge.provenance === 'heuristic') synthesized = true; |
| 293 | } |
| 294 | |
| 295 | relations.push({ |
| 296 | node: toNodeRef(node), |
| 297 | edgeKinds, |
| 298 | edges: wireEdges, |
| 299 | edgeCount: ordered.length, |
| 300 | lines, |
| 301 | confidence, |
| 302 | // No confidence recorded is NOT uncertain: tree-sitter edges extracted |
| 303 | // straight from the AST carry none precisely because they are certain. |
| 304 | uncertain: confidence !== null && confidence < UNCERTAIN_BELOW, |
| 305 | synthesized, |
| 306 | }); |
| 307 | } |
| 308 | return relations; |
| 309 | } |
| 310 | |
| 311 | /** First call-site line of a relation, for line-anchored ordering. Unlined rows sort last. */ |
| 312 | export function firstLine(relation: WireRelation): number { |