aptu-core 0.10.12

Core library for Aptu - OSS issue triage with AI assistance
Documentation
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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2025 Agentic AI Foundation

//! AST context injection for PR reviews.
//!
//! Extracts function signatures and cross-file call graph information from
//! changed source files and appends structured context to the AI review prompt.
//! Supported languages: Rust, Python, Go, Java, TypeScript, TSX, JavaScript,
//! C, C++, C#, and Fortran (determined by `aptu_coder_core::language_for_extension`).
//!
//! # Feature Flag
//!
//! Most functionality is gated behind the `ast-context` Cargo feature, which
//! enables the optional `aptu-coder-core` dependency. When the feature is
//! disabled, [`build_ast_context`] and [`build_call_graph_context`] return
//! empty strings immediately without performing any I/O.
//!
//! # Output Format
//!
//! Context is emitted as XML-tagged blocks appended after `</pull_request>`:
//! - `<ast_context>`: function signatures and imports per changed file
//! - `<call_graph_context>`: cross-file call chains for changed functions
//!
//! Each block is capped at approximately 2000 characters (soft ceiling; the
//! actual maximum is slightly higher due to the closing XML tag appended
//! after truncation).

use crate::ai::types::PrFile;
use std::path::Path;
use tracing::debug;

#[cfg(feature = "ast-context")]
use std::fmt::Write as _;

#[cfg(feature = "ast-context")]
use aptu_coder_core::{analyze_file, analyze_focused, language_for_extension};

/// Result of building AST context, including both the text string and the
/// structural graph built from the same analysis data.
#[derive(Debug)]
pub(crate) struct AstContextOutput {
    /// Text representation of AST context (for prompt injection).
    pub text: String,
    /// Structural graph built from the same analysis data.
    /// Only present when both `ast-context` and `graph` features are enabled.
    #[cfg(all(feature = "ast-context", feature = "graph"))]
    pub graph: crate::graph::GraphDb,
}

impl AstContextOutput {
    #[cfg(all(feature = "ast-context", feature = "graph"))]
    pub(crate) fn new(text: String) -> Self {
        Self {
            text,
            graph: crate::graph::GraphDb::default(),
        }
    }

    #[cfg(not(all(feature = "ast-context", feature = "graph")))]
    pub(crate) fn new(text: String) -> Self {
        Self { text }
    }

    #[cfg(all(feature = "ast-context", feature = "graph"))]
    fn with_graph(text: String, graph: crate::graph::GraphDb) -> Self {
        Self { text, graph }
    }
}

impl Default for AstContextOutput {
    fn default() -> Self {
        Self::new(String::new())
    }
}

// `str::floor_char_boundary` is available in std but remains behind the
// `str_internals` nightly feature gate on stable Rust. This local
// implementation provides the equivalent behavior on stable.

/// Return the largest byte index `<= max` that falls on a UTF-8 character boundary.
///
/// `String::truncate` panics when the index splits a multi-byte codepoint;
/// this function prevents that by scanning backwards to the nearest boundary.
#[cfg(feature = "ast-context")]
fn floor_char_boundary(s: &str, max: usize) -> usize {
    if max >= s.len() {
        return s.len();
    }
    let mut idx = max;
    while idx > 0 && !s.is_char_boundary(idx) {
        idx -= 1;
    }
    idx
}

/// Build a compact AST context string for the changed files in a PR.
///
/// Returns empty string if `repo_path` is invalid or no files have analysis results.
/// Output is capped at 2000 characters.
#[allow(private_interfaces)]
pub async fn build_ast_context(repo_path: &str, files: &[PrFile]) -> AstContextOutput {
    let repo_path = repo_path.to_string();
    let files: Vec<PrFile> = files.to_vec();

    match tokio::task::spawn_blocking(move || build_ast_context_sync(&repo_path, &files)).await {
        Ok(result) => result,
        Err(e) => {
            tracing::warn!("build_ast_context: blocking task panicked: {e}");
            AstContextOutput::new(String::new())
        }
    }
}

#[cfg(not(feature = "ast-context"))]
fn build_ast_context_sync(_repo_path: &str, _files: &[PrFile]) -> AstContextOutput {
    AstContextOutput::new(String::new())
}

#[cfg(feature = "ast-context")]
#[allow(clippy::too_many_lines)]
fn build_ast_context_sync(repo_path: &str, files: &[PrFile]) -> AstContextOutput {
    // CAP is a soft ceiling: the closing XML tag is appended after truncation,
    // so actual maximum output length is CAP + len(closing_tag).
    const CAP: usize = 2000;
    let mut output = String::from("\n<ast_context>\n");

    // Accumulate analysis data for graph building
    #[cfg(feature = "graph")]
    let mut analysis_pairs: Vec<(std::path::PathBuf, aptu_coder_core::SemanticAnalysis)> =
        Vec::new();
    #[cfg(feature = "graph")]
    let mut impl_traits: Vec<aptu_coder_core::ImplTraitInfo> = Vec::new();

    for file in files {
        let ext = Path::new(&file.filename)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");
        // skip files with unsupported languages
        if language_for_extension(ext).is_none() {
            continue;
        }
        let full_path = Path::new(repo_path).join(&file.filename);
        let path_str = full_path.to_string_lossy().into_owned();

        match analyze_file(&path_str, None) {
            Ok(analysis) => {
                let mut file_block = format!("## {}\n", file.filename);
                for func in &analysis.semantic.functions {
                    let _ = writeln!(file_block, "  fn {}", func.compact_signature());
                }
                if !analysis.semantic.imports.is_empty() {
                    file_block.push_str("  imports:");
                    for imp in analysis.semantic.imports.iter().take(5) {
                        let _ = write!(file_block, " {}", imp.module);
                    }
                    file_block.push('\n');
                }
                if output.len() + file_block.len() > CAP {
                    break;
                }
                output.push_str(&file_block);

                // Accumulate for graph building
                #[cfg(feature = "graph")]
                {
                    analysis_pairs.push((full_path.clone(), analysis.semantic.clone()));
                    impl_traits.extend(analysis.semantic.impl_traits.clone());
                }
            }
            Err(e) => {
                debug!("ast_context: skipping {}: {}", file.filename, e);
            }
        }
    }
    output.push_str("</ast_context>\n");

    // If nothing was added (only the wrapper tags), return empty
    if output == "\n<ast_context>\n</ast_context>\n" {
        return AstContextOutput::new(String::new());
    }

    // Enforce cap on the full output
    if output.len() > CAP {
        let boundary = floor_char_boundary(&output, CAP);
        output.truncate(boundary);
        output.push_str("\n</ast_context>\n");
    }

    // Build structural graph from accumulated analysis data (no second analyze_file pass).
    #[cfg(feature = "graph")]
    {
        if analysis_pairs.is_empty() {
            return AstContextOutput::with_graph(output, crate::graph::GraphDb::new());
        }

        match aptu_coder_core::graph::CallGraph::build_from_results(
            analysis_pairs.clone(),
            &impl_traits,
            false,
        ) {
            Ok(call_graph) => {
                // Reuse the already-accumulated (path, semantic) pairs -- no second analyze_file.
                let mut merged = crate::graph::GraphDb::new();
                for (full_path, semantic) in &analysis_pairs {
                    let rel_name = full_path.file_name().map_or_else(
                        || full_path.to_string_lossy().into_owned(),
                        |n| n.to_string_lossy().into_owned(),
                    );
                    let file_graph = crate::graph::builder::build_from_analysis(
                        &rel_name,
                        semantic,
                        &call_graph,
                    );
                    // Merge into combined graph.
                    let node_map: Vec<_> = file_graph
                        .node_indices()
                        .map(|idx| merged.add_node(file_graph[idx].clone()))
                        .collect();
                    for edge_idx in file_graph.edge_indices() {
                        let (src, dst) = file_graph.edge_endpoints(edge_idx).unwrap();
                        let weight = *file_graph.edge_weight(edge_idx).unwrap();
                        merged.add_edge(node_map[src.index()], node_map[dst.index()], weight);
                    }
                }
                AstContextOutput::with_graph(output, merged)
            }
            Err(e) => {
                tracing::warn!("ast_context: CallGraph::build_from_results failed: {e}");
                AstContextOutput::with_graph(output, crate::graph::GraphDb::new())
            }
        }
    }

    #[cfg(not(feature = "graph"))]
    AstContextOutput::new(output)
}

/// Build cross-file call graph context for the changed files.
///
/// For each function in each changed file, looks up its callers.
/// Output is capped at 3000 characters.
pub async fn build_call_graph_context(repo_path: &str, files: &[PrFile]) -> String {
    let repo_path = repo_path.to_string();
    let files: Vec<PrFile> = files.to_vec();

    match tokio::task::spawn_blocking(move || build_call_graph_context_sync(&repo_path, &files))
        .await
    {
        Ok(result) => result,
        Err(e) => {
            tracing::warn!("build_call_graph_context: blocking task panicked: {e}");
            String::new()
        }
    }
}

#[cfg(not(feature = "ast-context"))]
fn build_call_graph_context_sync(_repo_path: &str, _files: &[PrFile]) -> String {
    String::new()
}

#[cfg(feature = "ast-context")]
fn build_call_graph_context_sync(repo_path: &str, files: &[PrFile]) -> String {
    const CAP: usize = 3000;
    let mut output = String::from("\n<call_graph>\n");
    let repo = Path::new(repo_path);

    for file in files {
        let ext = Path::new(&file.filename)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");
        // skip files with unsupported languages
        if language_for_extension(ext).is_none() {
            continue;
        }
        let full_path = repo.join(&file.filename);
        let path_str = full_path.to_string_lossy().into_owned();

        // Get function names in this file
        let fn_names: Vec<String> = match analyze_file(&path_str, None) {
            Ok(a) => a
                .semantic
                .functions
                .iter()
                .map(|f| {
                    // Extract function name from the compact signature format produced by
                    // aptu-coder-core ("name(params) -> return_type"). The crate version
                    // is pinned in Cargo.toml; a format change would require updating this.
                    f.compact_signature()
                        .split('(')
                        .next()
                        .unwrap_or("")
                        .trim()
                        .to_string()
                })
                .filter(|s| !s.is_empty())
                .collect(),
            Err(_) => continue,
        };

        'outer: for fn_name in fn_names.iter().take(5) {
            match analyze_focused(repo, fn_name, 1, Some(3), None) {
                Ok(focused) => {
                    if focused.prod_chains.is_empty() {
                        continue;
                    }
                    let mut block = format!("### callers of `{fn_name}`\n");
                    for chain in focused.prod_chains.iter().take(3) {
                        if let Some((caller_sym, caller_file, caller_line)) = chain.chain.first() {
                            let _ = writeln!(
                                block,
                                "  {} ({}:{})",
                                caller_sym,
                                caller_file
                                    .file_name()
                                    .map(|n| n.to_string_lossy().into_owned())
                                    .unwrap_or_default(),
                                caller_line
                            );
                        }
                    }
                    if output.len() + block.len() > CAP {
                        break 'outer;
                    }
                    output.push_str(&block);
                }
                Err(e) => {
                    debug!("call_graph: skipping {}/{}: {}", file.filename, fn_name, e);
                }
            }
        }
    }

    output.push_str("</call_graph>\n");

    if output == "\n<call_graph>\n</call_graph>\n" {
        return String::new();
    }

    if output.len() > CAP {
        let boundary = floor_char_boundary(&output, CAP);
        output.truncate(boundary);
        output.push_str("\n</call_graph>\n");
    }

    output
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_pr_file(filename: &str) -> PrFile {
        PrFile {
            filename: filename.to_string(),
            status: "modified".to_string(),
            additions: 0,
            deletions: 0,
            patch: None,
            patch_truncated: false,
            full_content: None,
        }
    }

    #[tokio::test]
    async fn test_build_ast_context_missing_path_returns_empty() {
        let files = vec![make_pr_file("src/main.rs")];
        let result = build_ast_context("/nonexistent/path/xyz", &files).await;
        assert!(
            result.text.is_empty(),
            "expected empty for missing repo path"
        );
    }

    #[tokio::test]
    async fn test_build_ast_context_valid_rust_file() {
        let repo_path = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
        let files = vec![make_pr_file("src/ast_context.rs")];
        let result = build_ast_context(&repo_path, &files).await;
        // Verify it doesn't panic and respects the cap
        assert!(result.text.len() <= 2200, "output should be near cap");
    }

    #[tokio::test]
    async fn test_build_ast_context_cap_enforced() {
        let files: Vec<PrFile> = (0..50)
            .map(|i| make_pr_file(&format!("src/file_{i}.rs")))
            .collect();
        let result = build_ast_context(".", &files).await;
        assert!(
            result.text.len() <= 2200,
            "output must be capped near 2000 chars"
        );
    }

    #[tokio::test]
    async fn test_ast_context_python_file_included() {
        let files = vec![make_pr_file("test_file.py")];
        let result = build_ast_context(".", &files).await;
        // Python file should be processed by language_for_extension (happy path)
        assert!(
            result.text.is_empty() || result.text.contains("<ast_context>"),
            "Python file should be included in AST context"
        );
    }

    #[tokio::test]
    async fn test_ast_context_typescript_file_included() {
        let files = vec![make_pr_file("test_file.ts")];
        let result = build_ast_context(".", &files).await;
        // TypeScript file should be processed by language_for_extension
        assert!(
            result.text.is_empty() || result.text.contains("<ast_context>"),
            "TypeScript file should be included in AST context"
        );
    }

    #[tokio::test]
    async fn test_ast_context_markdown_file_included() {
        let files = vec![make_pr_file("README.md")];
        let result = build_ast_context(".", &files).await;
        // Markdown is supported in aptu-coder-core >= 0.22.0 (tree-sitter-md)
        #[cfg(feature = "ast-context")]
        assert!(
            result.text.contains("<ast_context>"),
            "Markdown file should produce an <ast_context> block; got: {result:?}"
        );
        #[cfg(not(feature = "ast-context"))]
        assert!(
            result.text.is_empty(),
            "without ast-context feature, build_ast_context returns empty"
        );
    }
}