"""Build deterministic training context plans from repository information.""" from __future__ import annotations from collections import defaultdict from .repo_model import ConcatenationNode, DependencyEdge, FileInfo, RepoInfo def build_concatenation_tree(repo_id: str, files: tuple[FileInfo, ...], edges: tuple[DependencyEdge, ...], topological_order: tuple[str, ...], components: tuple[tuple[str, ...], ...]) -> ConcatenationNode: """Build a complete ordered tree whose DFS is ``topological_order``.""" file_by_path = {file.path: file for file in files} dependencies: dict[str, set[str]] = defaultdict(set) for edge in edges: if edge.status == "resolved" and edge.source != edge.target: dependencies[edge.source].add(edge.target) position = {path: index for index, path in enumerate(topological_order)} component_by_path = { path: component for component in components for path in component } ordered_components: list[tuple[str, ...]] = [] seen: set[tuple[str, ...]] = set() for path in topological_order: component = component_by_path.get(path, (path,)) if component not in seen: seen.add(component) ordered_components.append(component) children: list[ConcatenationNode] = [] file_order = 0 for component in ordered_components: component_paths = tuple(sorted(component, key=position.__getitem__)) leaves = [] for path in component_paths: file = file_by_path[path] leaves.append(ConcatenationNode( kind="file", name=path.rsplit("/", 1)[-1], order=file_order, path=path, language=file.language, bytes=file.bytes, depends_on=tuple(sorted(dependencies.get(path, ()), key=position.__getitem__)), )) file_order += 1 if len(leaves) == 1: children.append(leaves[0]) continue member_set = set(component_paths) external_dependencies = { dependency for path in component_paths for dependency in dependencies.get(path, ()) if dependency not in member_set } children.append(ConcatenationNode( kind="cycle", name=f"cycle-{len(children)}", order=leaves[0].order, bytes=sum(leaf.bytes for leaf in leaves), depends_on=tuple(sorted(external_dependencies, key=position.__getitem__)), children=tuple(leaves), )) return ConcatenationNode( kind="repo", name=repo_id, order=0, bytes=sum(file.bytes for file in files), children=tuple(children), ) def concatenation_dfs(tree_or_info: ConcatenationNode | RepoInfo) -> tuple[str, ...]: """Return file paths from the suggested tree in depth-first order.""" tree = (tree_or_info.concatenation_tree if isinstance(tree_or_info, RepoInfo) else tree_or_info) if tree is None: return () paths: list[str] = [] stack = [tree] while stack: node = stack.pop() if node.kind == "file" and node.path is not None: paths.append(node.path) stack.extend(reversed(node.children)) return tuple(paths) def dependency_context(info: RepoInfo, target_path: str, *, max_bytes: int | None = None, max_files: int | None = None) -> tuple[str, ...]: """Return transitive dependencies before ``target_path`` within a budget.""" if target_path not in {file.path for file in info.files}: raise KeyError(target_path) dependencies: dict[str, set[str]] = defaultdict(set) for edge in info.edges: if edge.status == "resolved": dependencies[edge.source].add(edge.target) reachable: set[str] = set() stack = [target_path] while stack: source = stack.pop() for target in dependencies.get(source, ()): if target not in reachable and target != target_path: reachable.add(target) stack.append(target) sizes = {file.path: file.bytes for file in info.files} candidates = [path for path in info.topological_order if path in reachable] # Preserve the closest dependencies under tight budgets by selecting in # reverse topological order, then restore dependency-first presentation. selected: set[str] = set() used = sizes.get(target_path, 0) limit = None if max_files is None else max(0, max_files - 1) for path in reversed(candidates): if limit is not None and len(selected) >= limit: break size = sizes.get(path, 0) if max_bytes is not None and used + size > max_bytes: continue selected.add(path) used += size return tuple(path for path in info.topological_order if path in selected) + (target_path,) def repository_windows(info: RepoInfo, *, max_bytes: int) -> tuple[tuple[str, ...], ...]: """Pack dependency-ordered files into deterministic byte-budget windows.""" if max_bytes < 1: raise ValueError("max_bytes must be positive") sizes = {file.path: file.bytes for file in info.files} windows: list[tuple[str, ...]] = [] current: list[str] = [] used = 0 for path in info.topological_order: size = sizes.get(path, 0) if current and used + size > max_bytes: windows.append(tuple(current)) current, used = [], 0 current.append(path) used += size if used >= max_bytes: windows.append(tuple(current)) current, used = [], 0 if current: windows.append(tuple(current)) return tuple(windows)