File size: 13,064 Bytes
829dbce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// Code graph: scan a repo, find symbols and file-to-file edges, then segment
// along that structure instead of along character offsets.
//
// Deliberately lexical, not a parser. A real parse (tree-sitter, clang) is a
// dependency and a build burden, and the segmentation only needs to know where
// a symbol starts and which files reference which. Heuristics that are right
// most of the time produce better segments than exact offsets would, because
// the consumer is a language model reading the text anyway.
#include "ctxstream.hpp"

#include <algorithm>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <map>
#include <regex>
#include <set>
#include <sstream>

namespace fs = std::filesystem;

namespace ctxstream {

static std::string lang_of(const std::string& ext) {
    static const std::map<std::string, std::string> m = {
        {".c", "c"}, {".h", "c"}, {".cpp", "cpp"}, {".cc", "cpp"},
        {".hpp", "cpp"}, {".hh", "cpp"}, {".cxx", "cpp"},
        {".py", "python"}, {".pyi", "python"},
        {".js", "js"}, {".mjs", "js"}, {".ts", "ts"}, {".tsx", "ts"},
        {".go", "go"}, {".rs", "rust"}, {".java", "java"},
        {".rb", "ruby"}, {".sh", "shell"}, {".bash", "shell"},
        {".cs", "csharp"}, {".kt", "kotlin"}, {".swift", "swift"},
        {".php", "php"}, {".lua", "lua"}, {".m", "objc"},
    };
    const auto it = m.find(ext);
    return it == m.end() ? std::string() : it->second;
}

static bool looks_binary(const std::string& head) {
    for (unsigned char c : head) {
        if (c == 0) return true;
    }
    return false;
}

static std::string read_file(const fs::path& p, std::size_t cap, bool* too_big) {
    std::error_code ec;
    const auto sz = fs::file_size(p, ec);
    if (!ec && sz > cap) { *too_big = true; return {}; }
    std::ifstream in(p, std::ios::binary);
    if (!in) return {};
    std::ostringstream ss;
    ss << in.rdbuf();
    return ss.str();
}

// One pattern per language family. Captures the symbol name in group 1.
static const std::vector<std::pair<std::regex, NodeKind>>& defs_for(
    const std::string& lang) {
    static const std::vector<std::pair<std::regex, NodeKind>> c_like = {
        {std::regex(R"(^\s*(?:class)\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Class},
        {std::regex(R"(^\s*(?:struct)\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Struct},
        // return-type name(...) at line start, not a call or control keyword
        {std::regex(R"(^[A-Za-z_][A-Za-z0-9_:<>,\s\*&]*\s[\*&]?([A-Za-z_][A-Za-z0-9_]*)\s*\([^;]*\)\s*(?:const)?\s*\{)"),
         NodeKind::Function},
    };
    static const std::vector<std::pair<std::regex, NodeKind>> python = {
        {std::regex(R"(^\s*class\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Class},
        {std::regex(R"(^\s*(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Function},
    };
    static const std::vector<std::pair<std::regex, NodeKind>> js_like = {
        {std::regex(R"(^\s*(?:export\s+)?class\s+([A-Za-z_$][A-Za-z0-9_$]*))"), NodeKind::Class},
        {std::regex(R"(^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*))"), NodeKind::Function},
        {std::regex(R"(^\s*(?:export\s+)?const\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\()"), NodeKind::Function},
    };
    static const std::vector<std::pair<std::regex, NodeKind>> go_like = {
        {std::regex(R"(^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Function},
        {std::regex(R"(^\s*type\s+([A-Za-z_][A-Za-z0-9_]*)\s+struct)"), NodeKind::Struct},
    };
    static const std::vector<std::pair<std::regex, NodeKind>> rust_like = {
        {std::regex(R"(^\s*(?:pub\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Function},
        {std::regex(R"(^\s*(?:pub\s+)?struct\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Struct},
    };
    static const std::vector<std::pair<std::regex, NodeKind>> none;
    if (lang == "c" || lang == "cpp" || lang == "java" || lang == "csharp") return c_like;
    if (lang == "python") return python;
    if (lang == "js" || lang == "ts") return js_like;
    if (lang == "go") return go_like;
    if (lang == "rust") return rust_like;
    return none;
}

// #include "x.h" / import x / from x import / require('x')
static std::vector<std::string> imports_of(const std::string& text,
                                           const std::string& lang) {
    static const std::regex inc_c(R"(^\s*#\s*include\s*[\"<]([^\">]+)[\">])");
    static const std::regex imp_py(R"(^\s*(?:from\s+([A-Za-z0-9_.]+)\s+import|import\s+([A-Za-z0-9_.]+)))");
    static const std::regex imp_js(R"((?:from\s*[\"']([^\"']+)[\"']|require\(\s*[\"']([^\"']+)[\"']\s*\)))");
    std::vector<std::string> out;
    std::istringstream in(text);
    std::string line;
    while (std::getline(in, line)) {
        std::smatch m;
        if ((lang == "c" || lang == "cpp") && std::regex_search(line, m, inc_c)) {
            out.push_back(m[1].str());
        } else if (lang == "python" && std::regex_search(line, m, imp_py)) {
            out.push_back(m[1].matched ? m[1].str() : m[2].str());
        } else if ((lang == "js" || lang == "ts") && std::regex_search(line, m, imp_js)) {
            out.push_back(m[1].matched ? m[1].str() : m[2].str());
        }
    }
    return out;
}

CodeGraph scan_repo(const std::string& root, const ScanOptions& opt) {
    CodeGraph g;
    g.root = root;
    const std::set<std::string> excluded(opt.exclude_dirs.begin(),
                                         opt.exclude_dirs.end());
    // path (as written in imports) -> file id, for edge resolution
    std::map<std::string, int> by_stem;
    std::vector<std::string> texts;

    std::error_code ec;
    auto it = fs::recursive_directory_iterator(
        root,
        opt.follow_symlinks ? fs::directory_options::follow_directory_symlink
                            : fs::directory_options::skip_permission_denied,
        ec);
    if (ec) return g;

    for (fs::recursive_directory_iterator end; it != end; it.increment(ec)) {
        if (ec) { ec.clear(); continue; }
        const fs::path p = it->path();
        if (it->is_directory(ec)) {
            if (excluded.count(p.filename().string())) it.disable_recursion_pending();
            continue;
        }
        if (!it->is_regular_file(ec)) continue;
        const std::string lang = lang_of(p.extension().string());
        if (lang.empty()) continue;

        bool too_big = false;
        const std::string text = read_file(p, opt.max_file_bytes, &too_big);
        const std::string rel = fs::relative(p, root, ec).string();
        if (too_big) { g.skipped.emplace_back(rel, "over max_file_bytes"); continue; }
        if (text.empty()) { g.skipped.emplace_back(rel, "empty or unreadable"); continue; }
        if (looks_binary(text.substr(0, 512))) {
            g.skipped.emplace_back(rel, "binary");
            continue;
        }

        FileNode f;
        f.id = static_cast<int>(g.files.size());
        f.path = rel;
        f.language = lang;
        f.bytes = text.size();
        g.files.push_back(f);
        texts.push_back(text);
        by_stem[p.filename().string()] = f.id;
        by_stem[p.stem().string()] = f.id;
    }

    // Symbols
    for (std::size_t fi = 0; fi < g.files.size(); ++fi) {
        const auto& pats = defs_for(g.files[fi].language);
        if (pats.empty()) continue;
        const std::string& text = texts[fi];
        std::size_t off = 0;
        int line_no = 0;
        std::istringstream in(text);
        std::string line;
        while (std::getline(in, line)) {
            ++line_no;
            for (const auto& [re, kind] : pats) {
                std::smatch m;
                if (std::regex_search(line, m, re)) {
                    SymbolNode s;
                    s.id = static_cast<int>(g.symbols.size());
                    s.kind = kind;
                    s.name = m[1].str();
                    s.file = static_cast<int>(fi);
                    s.line = line_no;
                    s.offset = off;
                    g.symbols.push_back(s);
                    g.files[fi].symbols++;
                    break;
                }
            }
            off += line.size() + 1;
        }
    }

    // Edges from imports/includes, resolved by filename or stem.
    std::set<std::pair<int, int>> seen;
    for (std::size_t fi = 0; fi < g.files.size(); ++fi) {
        for (const std::string& imp : imports_of(texts[fi], g.files[fi].language)) {
            fs::path ip(imp);
            for (const std::string& key : {ip.filename().string(), ip.stem().string()}) {
                const auto hit = by_stem.find(key);
                if (hit == by_stem.end() || hit->second == static_cast<int>(fi)) continue;
                if (!seen.insert({static_cast<int>(fi), hit->second}).second) break;
                g.edges.push_back({static_cast<int>(fi), hit->second, EdgeKind::Includes});
                break;
            }
        }
    }
    return g;
}

std::string graph_summary(const CodeGraph& g) {
    std::map<std::string, int> per_lang;
    std::size_t bytes = 0;
    for (const auto& f : g.files) { per_lang[f.language]++; bytes += f.bytes; }
    std::ostringstream o;
    o << "files=" << g.files.size() << " symbols=" << g.symbols.size()
      << " edges=" << g.edges.size() << " bytes=" << bytes
      << " skipped=" << g.skipped.size() << " langs=";
    bool first = true;
    for (const auto& [l, n] : per_lang) {
        o << (first ? "" : ",") << l << ":" << n;
        first = false;
    }
    return o.str();
}

// Dependency-first ordering: a file appears after the files it includes, so a
// segment carrying a caller has a decent chance of following its callee. Cycles
// are broken arbitrarily rather than dropped -- coverage matters more than order.
static std::vector<int> topo_order(const CodeGraph& g) {
    const int n = static_cast<int>(g.files.size());
    std::vector<std::vector<int>> out(n);
    std::vector<int> indeg(n, 0);
    for (const auto& e : g.edges) {
        if (e.from == e.to) continue;
        out[e.to].push_back(e.from);   // dependency -> dependent
        indeg[e.from]++;
    }
    std::vector<int> ready, order;
    for (int i = 0; i < n; ++i) {
        if (indeg[i] == 0) ready.push_back(i);
    }
    std::vector<bool> done(n, false);
    while (!ready.empty()) {
        const int v = ready.back();
        ready.pop_back();
        if (done[v]) continue;
        done[v] = true;
        order.push_back(v);
        for (int w : out[v]) {
            if (--indeg[w] == 0) ready.push_back(w);
        }
    }
    for (int i = 0; i < n; ++i) {
        if (!done[i]) order.push_back(i);  // cycle members
    }
    return order;
}

std::vector<Segment> plan_codebase(const CodeGraph& g, const ManifestOptions& opt,
                                   std::string* packed_text) {
    packed_text->clear();
    std::vector<Segment> segs;
    if (g.files.empty()) return segs;

    // Pack files in dependency order into one buffer with explicit headers, so
    // the model always knows which file a fragment came from, then cut segments
    // on file boundaries.
    struct Placed { std::size_t start, end; };
    std::vector<Placed> placed;
    placed.reserve(g.files.size());

    for (int fi : topo_order(g)) {
        const FileNode& f = g.files[fi];
        std::error_code ec;
        std::ifstream in(fs::path(g.root) / f.path, std::ios::binary);
        std::ostringstream ss;
        ss << in.rdbuf();
        const std::size_t start = packed_text->size();
        *packed_text += "\n===== FILE " + f.path + " (" + f.language + ") =====\n";
        *packed_text += ss.str();
        placed.push_back({start, packed_text->size()});
    }

    // Greedy: accumulate whole files until the next one would overflow.
    int index = 0;
    std::size_t seg_start = 0;
    for (std::size_t i = 0; i < placed.size(); ++i) {
        const std::size_t seg_end = placed[i].end;
        const bool last = (i + 1 == placed.size());
        const std::size_t next_end = last ? seg_end : placed[i + 1].end;

        if (last || next_end - seg_start > opt.segment_chars) {
            Segment s;
            s.index = index++;
            s.offset = seg_start;
            s.length = seg_end - seg_start;
            s.overlap_prefix = 0;
            segs.push_back(s);
            seg_start = seg_end;
        }
    }

    // A single file larger than a segment still has to be split; fall back to
    // line-boundary cutting inside it rather than dropping it.
    std::vector<Segment> final_segs;
    for (const Segment& s : segs) {
        if (s.length <= opt.segment_chars) { final_segs.push_back(s); continue; }
        const std::string sub = packed_text->substr(s.offset, s.length);
        for (Segment inner : plan(sub, opt)) {
            inner.offset += s.offset;
            final_segs.push_back(inner);
        }
    }
    for (std::size_t i = 0; i < final_segs.size(); ++i) {
        final_segs[i].index = static_cast<int>(i);
    }
    return final_segs;
}

}  // namespace ctxstream