tokensave 7.9.0

Code intelligence tool that builds a semantic knowledge graph from Rust, Go, Java, Scala, TypeScript, Python, C, C++, Kotlin, C#, Swift, and many more codebases
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
use std::collections::HashMap;
use std::fmt::Write as _;

use crate::types::TaskContext;

/// Longest signature rendered inline for an entry point, in bytes.
pub const MAX_SIGNATURE_LEN: usize = 200;

/// Renders a signature as one bounded line.
///
/// A signature is normally a one-liner, but for a value binding the extractor
/// stores the whole initializer — a localization catalog or a generated lookup
/// table can run to tens of kilobytes. Emitting that verbatim costs more tokens
/// than the file it came from, which is a poor trade in a tool whose purpose is
/// spending fewer of them. The first line identifies the symbol; the code block
/// below it carries content under its own limits.
pub fn compact_signature(sig: &str) -> String {
    let first = sig.lines().next().unwrap_or("").trim_end();
    let truncated_lines = sig.lines().nth(1).is_some();
    match first.char_indices().nth(MAX_SIGNATURE_LEN) {
        Some((idx, _)) => format!("{}", &first[..idx].trim_end()),
        None if truncated_lines => format!("{first}"),
        None => first.to_string(),
    }
}

/// Markdown fence language for a source file path, derived from its extension.
/// Unknown extensions produce an unlabeled fence.
fn fence_language(file_path: &str) -> &'static str {
    let ext = file_path
        .rsplit('.')
        .next()
        .unwrap_or("")
        .to_ascii_lowercase();
    match ext.as_str() {
        "rs" => "rust",
        "ts" | "mts" | "cts" => "typescript",
        "tsx" => "tsx",
        "js" | "mjs" | "cjs" => "javascript",
        "jsx" => "jsx",
        "py" => "python",
        "go" => "go",
        "java" => "java",
        "kt" | "kts" => "kotlin",
        "rb" => "ruby",
        "php" => "php",
        "cs" => "csharp",
        "c" | "h" => "c",
        "cpp" | "cc" | "cxx" | "hpp" => "cpp",
        "swift" => "swift",
        "dart" => "dart",
        "scala" => "scala",
        "sh" | "bash" | "zsh" => "bash",
        "sql" => "sql",
        "toml" => "toml",
        "yaml" | "yml" => "yaml",
        "json" => "json",
        "html" => "html",
        "css" => "css",
        "lua" => "lua",
        "ex" | "exs" => "elixir",
        "hs" => "haskell",
        "zig" => "zig",
        "vue" => "vue",
        "svelte" => "svelte",
        _ => "",
    }
}

/// Formats a `TaskContext` as a Markdown document suitable for LLM consumption.
///
/// The output includes sections for the query, entry points, related symbols
/// grouped by file, and extracted code blocks.
pub fn format_context_as_markdown(context: &TaskContext) -> String {
    debug_assert!(
        !context.query.is_empty(),
        "format_context_as_markdown called with empty query"
    );
    debug_assert!(
        !context.summary.is_empty(),
        "format_context_as_markdown called with empty summary"
    );
    let mut out = String::new();

    out.push_str("## Code Context\n");
    let _ = write!(out, "**Query:** {}\n\n", context.query);

    // Entry Points
    out.push_str("### Entry Points\n");
    if context.entry_points.is_empty() {
        out.push_str("_No entry points found._\n\n");
    } else {
        for node in &context.entry_points {
            let _ = writeln!(
                out,
                "- **{}** ({}) - {}:{}",
                node.name,
                node.kind.as_str(),
                node.file_path,
                node.start_line + 1,
            );
            if let Some(ref sig) = node.signature {
                let _ = writeln!(out, "  `{}`", compact_signature(sig));
            }
            // A docstring's first line often answers the question without a
            // code fetch — cheap to include, expensive to omit.
            if let Some(first) = node
                .docstring
                .as_deref()
                .and_then(|doc| doc.lines().find(|line| !line.trim().is_empty()))
            {
                let _ = writeln!(out, "  {}", first.trim());
            }
        }
        out.push('\n');
    }

    // Related Symbols grouped by file
    out.push_str("### Related Symbols\n");
    if context.subgraph.nodes.is_empty() {
        out.push_str("_No related symbols._\n\n");
    } else {
        // Group nodes by file_path
        let mut by_file: HashMap<&str, Vec<(&str, u32)>> = HashMap::new();
        for node in &context.subgraph.nodes {
            by_file
                .entry(&node.file_path)
                .or_default()
                .push((&node.name, node.start_line + 1));
        }

        let mut files: Vec<&&str> = by_file.keys().collect();
        files.sort();

        for file in files {
            let symbols = by_file.get(*file).unwrap_or(&Vec::new()).clone();
            let formatted: Vec<String> = symbols
                .iter()
                .map(|(name, line)| format!("{name}:{line}"))
                .collect();
            let _ = writeln!(out, "- {}: {}", file, formatted.join(", "));
        }
        out.push('\n');
    }

    // Code blocks
    out.push_str("### Code\n");
    if context.code_blocks.is_empty() {
        out.push_str("_No code blocks extracted._\n");
    } else {
        for block in &context.code_blocks {
            // Determine a label from the node if available
            let label = if let Some(ref node_id) = block.node_id {
                // Try to find a matching entry point name
                context
                    .entry_points
                    .iter()
                    .find(|n| &n.id == node_id)
                    .map_or_else(|| node_id.clone(), |n| n.name.clone())
            } else {
                "unknown".to_string()
            };

            let _ = writeln!(
                out,
                "#### {} ({}:{})",
                label,
                block.file_path,
                block.start_line + 1,
            );
            // Fence language from the block's file extension, not a hardcoded
            // `rust` (#208).
            let _ = writeln!(out, "```{}", fence_language(&block.file_path));
            out.push_str(&block.content);
            if !block.content.ends_with('\n') {
                out.push('\n');
            }
            out.push_str("```\n\n");
        }
    }

    debug_assert!(
        !out.is_empty(),
        "format_context_as_markdown produced empty output"
    );
    debug_assert!(
        out.contains("## Code Context"),
        "output missing required header"
    );
    out
}

/// Formats a `TaskContext` as pretty-printed JSON.
pub fn format_context_as_json(context: &TaskContext) -> String {
    serde_json::to_string_pretty(context).unwrap_or_default()
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::types::*;

    fn make_test_context() -> TaskContext {
        TaskContext {
            query: "test query".to_string(),
            summary: "Test summary".to_string(),
            subgraph: Subgraph::default(),
            entry_points: vec![],
            code_blocks: vec![],
            related_files: vec![],
            seen_node_ids: vec![],
        }
    }

    #[test]
    fn test_markdown_contains_header() {
        let ctx = make_test_context();
        let md = format_context_as_markdown(&ctx);
        assert!(md.contains("## Code Context"));
        assert!(md.contains("test query"));
    }

    #[test]
    fn test_json_roundtrip() {
        let ctx = make_test_context();
        let json = format_context_as_json(&ctx);
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["query"], "test query");
    }

    #[test]
    fn test_markdown_with_entry_points() {
        let ctx = TaskContext {
            query: "process".to_string(),
            summary: "Found 1 entry point".to_string(),
            subgraph: Subgraph::default(),
            entry_points: vec![Node {
                id: "function:abc123".to_string(),
                kind: NodeKind::Function,
                name: "process_data".to_string(),
                qualified_name: "src/lib.rs::process_data".to_string(),
                file_path: "src/lib.rs".to_string(),
                start_line: 10,
                attrs_start_line: 10,
                end_line: 20,
                start_column: 0,
                end_column: 1,
                signature: Some("pub fn process_data(input: &str) -> Result<()>".to_string()),
                docstring: None,
                visibility: Visibility::Pub,
                is_async: false,
                branches: 0,
                loops: 0,
                returns: 0,
                max_nesting: 0,
                unsafe_blocks: 0,
                unchecked_calls: 0,
                assertions: 0,
                cognitive_complexity: 0,
                distinct_operators: 0,
                distinct_operands: 0,
                total_operators: 0,
                total_operands: 0,
                updated_at: 0,
                parent_id: None,
            }],
            code_blocks: vec![],
            related_files: vec!["src/lib.rs".to_string()],
            seen_node_ids: vec![],
        };

        let md = format_context_as_markdown(&ctx);
        assert!(md.contains("**process_data**"));
        assert!(md.contains("(function)"));
        assert!(md.contains("src/lib.rs:11"));
        assert!(md.contains("`pub fn process_data(input: &str) -> Result<()>`"));
    }

    #[test]
    fn test_markdown_with_code_blocks() {
        let ctx = TaskContext {
            query: "test".to_string(),
            summary: "Summary".to_string(),
            subgraph: Subgraph::default(),
            entry_points: vec![Node {
                id: "function:abc".to_string(),
                kind: NodeKind::Function,
                name: "my_fn".to_string(),
                qualified_name: "my_fn".to_string(),
                file_path: "src/main.rs".to_string(),
                start_line: 1,
                attrs_start_line: 1,
                end_line: 3,
                start_column: 0,
                end_column: 1,
                signature: None,
                docstring: None,
                visibility: Visibility::Pub,
                is_async: false,
                branches: 0,
                loops: 0,
                returns: 0,
                max_nesting: 0,
                unsafe_blocks: 0,
                unchecked_calls: 0,
                assertions: 0,
                cognitive_complexity: 0,
                distinct_operators: 0,
                distinct_operands: 0,
                total_operators: 0,
                total_operands: 0,
                updated_at: 0,
                parent_id: None,
            }],
            code_blocks: vec![CodeBlock {
                content: "fn my_fn() {\n    println!(\"hello\");\n}".to_string(),
                file_path: "src/main.rs".to_string(),
                start_line: 1,
                end_line: 3,
                node_id: Some("function:abc".to_string()),
            }],
            related_files: vec!["src/main.rs".to_string()],
            seen_node_ids: vec![],
        };

        let md = format_context_as_markdown(&ctx);
        assert!(md.contains("#### my_fn (src/main.rs:2)"));
        assert!(md.contains("```rust"));
        assert!(md.contains("fn my_fn()"));
    }

    #[test]
    fn test_entry_point_docstring_first_line_shown() {
        let mut ctx = make_test_context();
        ctx.entry_points = vec![Node {
            id: "function:doc".to_string(),
            kind: NodeKind::Function,
            name: "documented".to_string(),
            qualified_name: "src/lib.rs::documented".to_string(),
            file_path: "src/lib.rs".to_string(),
            start_line: 1,
            attrs_start_line: 1,
            end_line: 5,
            start_column: 0,
            end_column: 1,
            signature: None,
            docstring: Some("Parses the config file.\n\nLong detail here.".to_string()),
            visibility: Visibility::Pub,
            is_async: false,
            branches: 0,
            loops: 0,
            returns: 0,
            max_nesting: 0,
            unsafe_blocks: 0,
            unchecked_calls: 0,
            assertions: 0,
            cognitive_complexity: 0,
            distinct_operators: 0,
            distinct_operands: 0,
            total_operators: 0,
            total_operands: 0,
            updated_at: 0,
            parent_id: None,
        }];
        let md = format_context_as_markdown(&ctx);
        assert!(md.contains("  Parses the config file."), "{md}");
        assert!(!md.contains("Long detail here"), "{md}");
    }

    #[test]
    fn test_fence_language_from_extension() {
        // #208
        assert_eq!(super::fence_language("a/b.tsx"), "tsx");
        assert_eq!(super::fence_language("a/b.ts"), "typescript");
        assert_eq!(super::fence_language("a/b.rs"), "rust");
        assert_eq!(super::fence_language("a/b.unknownext"), "");
    }

    #[test]
    fn compact_signature_leaves_a_normal_signature_alone() {
        let sig = "pub fn process_data(input: &str) -> Result<()>";
        assert_eq!(super::compact_signature(sig), sig);
    }

    #[test]
    fn compact_signature_collapses_a_multiline_initializer() {
        // A localization catalog stored as a const "signature" can run to tens
        // of kilobytes; emitting it verbatim costs more than the source file.
        let sig = "MESSAGES = {\n  \"a\": \"one\",\n  \"b\": \"two\",\n}";
        assert_eq!(super::compact_signature(sig), "MESSAGES = { …");
    }

    #[test]
    fn compact_signature_bounds_a_long_single_line() {
        let sig = format!("const TABLE = [{}]", "0, ".repeat(500));
        let out = super::compact_signature(&sig);
        assert!(
            out.len() <= super::MAX_SIGNATURE_LEN + 8,
            "got {} bytes",
            out.len()
        );
        assert!(out.ends_with(''));
    }

    #[test]
    fn compact_signature_truncates_on_a_char_boundary() {
        // Multi-byte characters must not be split; slicing mid-char panics.
        let sig = format!("const EMOJI = \"{}\"", "🚀".repeat(400));
        let out = super::compact_signature(&sig);
        assert!(out.ends_with(''));
        assert!(out.chars().count() <= super::MAX_SIGNATURE_LEN + 2);
    }
}