File size: 5,778 Bytes
f764cdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""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)