MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / findPath

Method findPath

src/graph/traversal.ts:617–674  ·  view source on GitHub ↗

* Find the shortest path between two nodes * * @param fromId - Starting node ID * @param toId - Target node ID * @param edgeKinds - Edge types to consider (all if empty) * @returns Array of nodes and edges forming the path, or null if no path exists

(
    fromId: string,
    toId: string,
    edgeKinds: EdgeKind[] = []
  )

Source from the content-addressed store, hash-verified

615 * @returns Array of nodes and edges forming the path, or null if no path exists
616 */
617 findPath(
618 fromId: string,
619 toId: string,
620 edgeKinds: EdgeKind[] = []
621 ): Array<{ node: Node; edge: Edge | null }> | null {
622 const fromNode = this.queries.getNodeById(fromId);
623 const toNode = this.queries.getNodeById(toId);
624
625 if (!fromNode || !toNode) {
626 return null;
627 }
628
629 // BFS to find shortest path
630 const visited = new Set<string>();
631 const queue: Array<{ nodeId: string; path: Array<{ node: Node; edge: Edge | null }> }> = [
632 { nodeId: fromId, path: [{ node: fromNode, edge: null }] },
633 ];
634
635 while (queue.length > 0) {
636 const { nodeId, path } = queue.shift()!;
637
638 if (nodeId === toId) {
639 return path;
640 }
641
642 if (visited.has(nodeId)) {
643 continue;
644 }
645 visited.add(nodeId);
646
647 // Get outgoing edges
648 const outgoingEdges = this.queries.getOutgoingEdges(
649 nodeId,
650 edgeKinds.length > 0 ? edgeKinds : undefined
651 );
652 if (outgoingEdges.length === 0) continue;
653
654 // Batch-fetch only the unvisited targets (was N+1 per BFS frontier).
655 const wantIds = outgoingEdges
656 .map((e) => e.target)
657 .filter((id) => !visited.has(id));
658 const nextNodes = wantIds.length > 0 ? this.queries.getNodesByIds(wantIds) : new Map();
659
660 for (const edge of outgoingEdges) {
661 if (!visited.has(edge.target)) {
662 const nextNode = nextNodes.get(edge.target);
663 if (nextNode) {
664 queue.push({
665 nodeId: edge.target,
666 path: [...path, { node: nextNode, edge }],
667 });
668 }
669 }
670 }
671 }
672
673 return null; // No path found
674 }

Callers

nothing calls this directly

Calls 5

hasMethod · 0.80
getNodesByIdsMethod · 0.80
getNodeByIdMethod · 0.65
getMethod · 0.65
getOutgoingEdgesMethod · 0.45

Tested by

no test coverage detected