codebase-recall 0.7.4

CLI based application for codebase dumper for LLMs and fast review/recall project
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! A throwaway local HTTP server for `code-rcl serve`.
//!
//! It serves the graph page plus its static assets on `127.0.0.1`, then shuts
//! itself down as soon as the browser tab goes away — so it never lingers in the
//! background. "Tab is open" is tracked by a held `EventSource` (`/live`); the
//! server also stops on `Ctrl-C` or a `/quit` request.

use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread;
use std::time::{Duration, Instant};

use anyhow::{Result, anyhow};
use tiny_http::{Header, Method, Request, Response, Server};

use crate::assets::{self, Delivery};
use crate::graph::CodeGraph;

pub struct ServeOptions {
    /// 0 = let the OS pick a free port.
    pub port: u16,
    /// Open the URL in the default browser once the server is up.
    pub open: bool,
    /// Project root — needed by the `/dump` endpoint (viewer "dump -r" button).
    pub project: PathBuf,
}

/// Worker threads pulling from the shared accept queue. A held `/live` stream
/// occupies one for the life of the tab, so keep a little headroom for reloads.
const WORKERS: usize = 4;
/// After the last `/live` client disconnects, wait this long before exiting so a
/// page reload (which briefly drops to zero connections) doesn't kill us.
const ZERO_GRACE: Duration = Duration::from_millis(2000);
/// If no browser ever connects (e.g. `--no-open` and nobody opens the URL), give
/// up after this long instead of running forever.
const STARTUP_BACKSTOP: Duration = Duration::from_secs(90);
/// Keep-alive comment cadence on the `/live` stream. Also bounds how fast we
/// notice a dropped connection (the write to a closed socket is what fails).
const KEEPALIVE: Duration = Duration::from_millis(2000);

pub fn serve(graph: &CodeGraph, opts: ServeOptions) -> Result<()> {
    let data = serde_json::to_string(graph)?;
    let stat = format!(
        "{} nodes \u{00b7} {} edges",
        graph.nodes.len(),
        graph.edges.len()
    );
    let page = Arc::new(assets::graph_page(&data, &stat, Delivery::Server));

    let server = Server::http(("127.0.0.1", opts.port))
        .map_err(|e| anyhow!("cannot bind 127.0.0.1:{}: {e}", opts.port))?;
    let port = server
        .server_addr()
        .to_ip()
        .map(|a| a.port())
        .unwrap_or(opts.port);
    let url = format!("http://127.0.0.1:{port}/");
    let server = Arc::new(server);

    let shutdown = Arc::new(AtomicBool::new(false));
    let live = Arc::new(AtomicUsize::new(0));
    let project = Arc::new(opts.project);

    // Ctrl-C -> ask everything to wind down. Workers poll `shutdown` between
    // short accept timeouts, so flipping the flag is all it takes.
    {
        let shutdown = shutdown.clone();
        let _ = ctrlc::set_handler(move || shutdown.store(true, Ordering::SeqCst));
    }

    spawn_reaper(shutdown.clone(), live.clone());

    println!("code-rcl graph  ->  {url}");
    println!(
        "  serving {} nodes / {} edges; the server exits when you close the tab (or press Ctrl-C)",
        graph.nodes.len(),
        graph.edges.len()
    );
    if opts.open && webbrowser::open(&url).is_err() {
        eprintln!("  (couldn't open a browser automatically — open the URL above)");
    }

    let mut workers = Vec::with_capacity(WORKERS);
    for _ in 0..WORKERS {
        let server = server.clone();
        let shutdown = shutdown.clone();
        let live = live.clone();
        let page = page.clone();
        let project = project.clone();
        workers.push(thread::spawn(move || {
            worker_loop(&server, &shutdown, &live, &page, &project);
        }));
    }
    for w in workers {
        let _ = w.join();
    }

    println!("code-rcl serve: stopped.");
    Ok(())
}

fn spawn_reaper(shutdown: Arc<AtomicBool>, live: Arc<AtomicUsize>) {
    thread::spawn(move || {
        let started = Instant::now();
        let mut ever_connected = false;
        let mut zero_since: Option<Instant> = None;
        loop {
            thread::sleep(Duration::from_millis(300));
            if shutdown.load(Ordering::SeqCst) {
                return;
            }
            let n = live.load(Ordering::SeqCst);
            if n > 0 {
                ever_connected = true;
                zero_since = None;
                continue;
            }
            let expired = if ever_connected {
                zero_since.get_or_insert_with(Instant::now).elapsed() > ZERO_GRACE
            } else {
                started.elapsed() > STARTUP_BACKSTOP
            };
            if expired {
                shutdown.store(true, Ordering::SeqCst);
                return;
            }
        }
    });
}

fn worker_loop(
    server: &Arc<Server>,
    shutdown: &Arc<AtomicBool>,
    live: &Arc<AtomicUsize>,
    page: &str,
    project: &Path,
) {
    while !shutdown.load(Ordering::SeqCst) {
        let req = match server.recv_timeout(Duration::from_millis(200)) {
            Ok(Some(r)) => r,
            Ok(None) => continue, // accept timed out — re-check `shutdown`
            Err(_) => break,      // fatal accept error
        };

        let is_get = *req.method() == Method::Get;
        let url = req.url().to_owned();
        let path = url.split('?').next().unwrap_or("/").to_owned();

        match (is_get, path.as_str()) {
            (_, "/dump") => {
                let body = run_dump(project, &url);
                let _ = req.respond(with_type(
                    text(
                        if body.contains("\"ok\":true") {
                            200
                        } else {
                            500
                        },
                        &body,
                    ),
                    "application/json; charset=utf-8",
                ));
            }
            (_, "/impact") => {
                let body = run_impact(project, &url);
                let _ = req.respond(with_type(
                    text(
                        if body.contains("\"ok\":true") {
                            200
                        } else {
                            500
                        },
                        &body,
                    ),
                    "application/json; charset=utf-8",
                ));
            }
            (true, "/source") => {
                let (status, body) = run_source(project, &url);
                let _ = req.respond(with_type(
                    text(status, &body),
                    "application/json; charset=utf-8",
                ));
            }
            (_, "/quit") => {
                let _ = req.respond(text(204, ""));
                shutdown.store(true, Ordering::SeqCst);
                break;
            }
            (true, "/live") => {
                // A held stream keeps a worker busy for the life of the tab, so
                // hand it to its own thread and get straight back to accepting.
                let live = live.clone();
                let shutdown = shutdown.clone();
                thread::spawn(move || live_stream(req, live, shutdown));
            }
            (true, "/") | (true, "/index.html") => {
                let _ = req.respond(with_type(text(200, page), "text/html; charset=utf-8"));
            }
            (true, "/assets/d3.min.js") => {
                let _ = req.respond(js(assets::D3_JS));
            }
            (true, "/assets/graph-view.js") => {
                let _ = req.respond(js(assets::GRAPH_VIEW_JS.as_str()));
            }
            (true, "/assets/live.js") => {
                let _ = req.respond(js(assets::LIVE_JS));
            }
            (true, "/assets/graph.css") => {
                let _ = req.respond(with_type(
                    text(200, assets::GRAPH_CSS),
                    "text/css; charset=utf-8",
                ));
            }
            (true, "/favicon.ico") | (true, "/favicon.svg") => {
                let _ = req.respond(with_type(
                    text(200, assets::APP_LOGO),
                    "image/svg+xml; charset=utf-8",
                ));
            }
            _ => {
                let _ = req.respond(text(404, "not found"));
            }
        }
    }
}

/// Answer `/live` with an endless `text/event-stream`, written straight to the
/// socket so every keep-alive is flushed immediately (tiny_http's buffered
/// `Response` streaming would hold the bytes back). Runs until the client
/// disconnects — tab closed or navigated away — or the server shuts down.
///
/// The count of open `/live` streams is how the reaper knows a tab is still
/// there; an open stream is also immune to background-tab timer throttling.
fn live_stream(req: Request, live: Arc<AtomicUsize>, shutdown: Arc<AtomicBool>) {
    live.fetch_add(1, Ordering::SeqCst);
    let _guard = Decrement(&live);

    let mut sock = req.into_writer();
    let head: &[u8] = b"HTTP/1.1 200 OK\r\n\
Content-Type: text/event-stream\r\n\
Cache-Control: no-store\r\n\
Connection: close\r\n\
\r\n\
: connected\n\n";
    if sock.write_all(head).and_then(|_| sock.flush()).is_err() {
        return;
    }
    while !shutdown.load(Ordering::SeqCst) {
        let mut waited = Duration::ZERO;
        while waited < KEEPALIVE {
            if shutdown.load(Ordering::SeqCst) {
                return;
            }
            thread::sleep(Duration::from_millis(100));
            waited += Duration::from_millis(100);
        }
        if sock
            .write_all(b": keep-alive\n\n")
            .and_then(|_| sock.flush())
            .is_err()
        {
            return; // the browser is gone
        }
    }
}

struct Decrement<'a>(&'a Arc<AtomicUsize>);
impl Drop for Decrement<'_> {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::SeqCst);
    }
}

// --- /dump: relation-aware context bundle for the viewer's "dump -r" button ---
// --- /impact: caller/importer report for the viewer's right-click menu -----

/// Sanitize a query-string filename to a bare basename — no directory
/// components, no `.`/`..`, no drive letters. Shared by `/dump` and `/impact`.
fn sanitize_name(raw: Option<String>, default: &str) -> String {
    raw.map(|s| s.trim().to_string())
        .and_then(|s| {
            let base = s.rsplit(['/', '\\']).next().unwrap_or("").to_string();
            (!base.is_empty() && base != "." && base != ".." && !base.contains(':')).then_some(base)
        })
        .unwrap_or_else(|| default.to_string())
}

/// Resolve an optional `dir` query param (a project-relative directory, as
/// sent by the viewer's right-click menu for "write next to this file") to
/// an absolute path guaranteed to stay inside `project`. Falls back to
/// `project` itself when `dir` is absent/empty — this keeps the side panel's
/// existing "dump -r" button (which never sends `dir`) writing to the
/// project root exactly as before. Same containment check as `run_source`.
fn resolve_output_dir(project: &Path, dir_param: Option<String>) -> Result<PathBuf, String> {
    let Some(dir) = dir_param.filter(|d| !d.trim().is_empty()) else {
        return Ok(project.to_path_buf());
    };
    let dir_clean = dir.replace('\\', "/");
    let dir_path = Path::new(&dir_clean);
    if dir_path.is_absolute()
        || dir_clean.starts_with('/')
        || dir_clean.split('/').any(|segment| segment == "..")
        || dir_clean.contains(':')
    {
        return Err("access denied".to_string());
    }
    let target = project.join(dir_path);
    if let (Ok(cp), Ok(ct)) = (project.canonicalize(), target.canonicalize()) {
        if !ct.starts_with(&cp) {
            return Err("access denied".to_string());
        }
    }
    Ok(target)
}

/// Runs `dump -r` for `?target=…&depth=…&dir=…` and returns a small JSON
/// reply. NOTE: unlike the rest of `serve`, this writes a file to disk.
fn run_dump(project: &Path, url: &str) -> String {
    let Some(target) = query_param(url, "target").filter(|t| !t.is_empty()) else {
        return serde_json::json!({"ok": false, "error": "missing target"}).to_string();
    };
    let depth = query_param(url, "depth")
        .and_then(|d| d.parse::<u32>().ok())
        .unwrap_or(2)
        .clamp(1, 5);
    let name = sanitize_name(query_param(url, "name"), "codebase-context.md");
    let dir = match resolve_output_dir(project, query_param(url, "dir")) {
        Ok(d) => d,
        Err(e) => return serde_json::json!({"ok": false, "error": e}).to_string(),
    };
    let output = dir.join(&name);

    match crate::commands::dump::relation_bundle(project, &target, depth, 50, false, &output) {
        Ok((path, n)) => serde_json::json!({
            "ok": true,
            "path": path.display().to_string(),
            "files": n,
        })
        .to_string(),
        Err(e) => serde_json::json!({
            "ok": false,
            "error": e.to_string(),
        })
        .to_string(),
    }
}

/// Runs `impact` for `?target=…&depth=…&kinds=…&format=ascii|json&dir=…` and
/// writes the rendered report to disk, returning a small JSON reply.
fn run_impact(project: &Path, url: &str) -> String {
    let Some(target) = query_param(url, "target").filter(|t| !t.is_empty()) else {
        return serde_json::json!({"ok": false, "error": "missing target"}).to_string();
    };
    let depth = query_param(url, "depth")
        .and_then(|d| d.parse::<u32>().ok())
        .unwrap_or(3)
        .clamp(1, 8);
    let kinds: Vec<String> = query_param(url, "kinds")
        .filter(|k| !k.trim().is_empty())
        .map(|k| k.split(',').map(|s| s.trim().to_string()).collect())
        .unwrap_or_else(|| vec!["calls".to_string(), "imports".to_string()]);
    let as_json = query_param(url, "format").as_deref() == Some("json");
    let default_name = if as_json { "impact.json" } else { "impact.md" };
    let name = sanitize_name(query_param(url, "name"), default_name);
    let dir = match resolve_output_dir(project, query_param(url, "dir")) {
        Ok(d) => d,
        Err(e) => return serde_json::json!({"ok": false, "error": e}).to_string(),
    };
    let output = dir.join(&name);

    let args = crate::cli::ImpactArgs {
        symbol: target,
        project: project.to_path_buf(),
        depth,
        kinds,
        json: as_json,
        no_sync: false,
        precise: Default::default(),
    };

    let result = crate::commands::impact::generate_reports(&args).and_then(|reports| {
        let body = if as_json {
            crate::commands::impact::render_json(&reports)?
        } else {
            crate::commands::impact::render_ascii(&reports)
        };
        std::fs::write(&output, body)?;
        Ok(reports.len())
    });

    match result {
        Ok(n) => serde_json::json!({
            "ok": true,
            "path": output.display().to_string(),
            "targets": n,
        })
        .to_string(),
        Err(e) => serde_json::json!({
            "ok": false,
            "error": e.to_string(),
        })
        .to_string(),
    }
}

fn run_source(project: &Path, url: &str) -> (u16, String) {
    let Some(rel) = query_param(url, "path") else {
        return (
            400,
            serde_json::json!({"ok": false, "error": "missing path param"}).to_string(),
        );
    };
    let rel_clean = rel.replace('\\', "/");
    let rel_path = Path::new(&rel_clean);
    if rel_path.is_absolute()
        || rel_clean.starts_with('/')
        || rel_clean.split('/').any(|segment| segment == "..")
        || rel_clean.contains(':')
    {
        return (
            403,
            serde_json::json!({"ok": false, "error": "access denied"}).to_string(),
        );
    }
    let target = project.join(rel_path);
    if let (Ok(cp), Ok(ct)) = (project.canonicalize(), target.canonicalize()) {
        if !ct.starts_with(&cp) {
            return (
                403,
                serde_json::json!({"ok": false, "error": "access denied"}).to_string(),
            );
        }
    }
    if !target.exists() || !target.is_file() {
        return (
            404,
            serde_json::json!({"ok": false, "error": "file not found"}).to_string(),
        );
    }
    match std::fs::read_to_string(&target) {
        Ok(content) => (
            200,
            serde_json::json!({
                "ok": true,
                "path": rel_clean,
                "content": content,
            })
            .to_string(),
        ),
        Err(e) => (
            500,
            serde_json::json!({
                "ok": false,
                "error": e.to_string(),
            })
            .to_string(),
        ),
    }
}

/// First `key=value` from a URL query string, percent-decoded (`+` -> space).
fn query_param(url: &str, key: &str) -> Option<String> {
    let q = url.split_once('?')?.1;
    for pair in q.split('&') {
        let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
        if k == key {
            return Some(percent_decode(v));
        }
    }
    None
}

fn percent_decode(s: &str) -> String {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b'+' => out.push(b' '),
            b'%' if i + 2 < b.len() => {
                let hex = |c: u8| (c as char).to_digit(16);
                match (hex(b[i + 1]), hex(b[i + 2])) {
                    (Some(h), Some(l)) => {
                        out.push((h * 16 + l) as u8);
                        i += 2;
                    }
                    _ => out.push(b'%'),
                }
            }
            c => out.push(c),
        }
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}


// --- small response helpers ------------------------------------------------

fn header(name: &str, value: &str) -> Header {
    Header::from_bytes(name.as_bytes(), value.as_bytes()).expect("static header")
}

fn text(status: u16, body: &str) -> Response<io::Cursor<Vec<u8>>> {
    Response::from_string(body).with_status_code(status)
}

fn with_type(mut r: Response<io::Cursor<Vec<u8>>>, ct: &str) -> Response<io::Cursor<Vec<u8>>> {
    r.add_header(header("Content-Type", ct));
    r
}

fn js(src: &str) -> Response<io::Cursor<Vec<u8>>> {
    with_type(text(200, src), "application/javascript; charset=utf-8")
}