rx4 0.6.5

The agent harness engine — loop, tools, providers, sessions, permissions, computer-use
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
use super::extract::ExtractionResult;
use super::graph::{next_node_id, *};
use chrono::Utc;
use std::collections::HashMap;
use std::io::Read;
use std::path::{Path, PathBuf};

/// Scans a workspace and builds a structural graph of files, functions, and classes.
#[derive(Debug)]
pub struct CodebaseScanner {
    workspace: PathBuf,
}

impl CodebaseScanner {
    /// Create a scanner rooted at the given workspace.
    pub fn new(workspace: PathBuf) -> Self {
        CodebaseScanner { workspace }
    }

    /// Scan all `.rs`, `.ts`, `.py`, and `.go` files in the workspace.
    pub fn scan(&self) -> Result<ExtractionResult, GraphMemoryError> {
        let mut files = Vec::new();
        self.collect_files(&self.workspace, &mut files)?;
        self.scan_incremental(&files)
    }

    /// Scan only the provided changed files.
    /// Rejects paths outside the configured workspace.
    pub fn scan_incremental(
        &self,
        changed_files: &[PathBuf],
    ) -> Result<ExtractionResult, GraphMemoryError> {
        let mut result = ExtractionResult::default();
        let now = Utc::now();
        let mut file_ids: HashMap<String, String> = HashMap::new();
        for path in changed_files {
            self.process_file(path, &mut result, &mut file_ids, now);
        }
        Ok(result)
    }

    fn process_file(
        &self,
        path: &Path,
        result: &mut ExtractionResult,
        file_ids: &mut HashMap<String, String>,
        now: chrono::DateTime<Utc>,
    ) {
        if !path.exists() {
            return;
        }

        let meta = match std::fs::metadata(path) {
            Ok(m) => m,
            Err(_) => return,
        };
        if !meta.is_file() {
            return;
        }

        // Reject paths outside workspace rather than falling back to absolute path.
        let rel = match path.strip_prefix(&self.workspace) {
            Ok(r) => r.to_string_lossy().to_string(),
            Err(_) => {
                tracing::warn!(
                    "scan_incremental: rejecting path outside workspace: {}",
                    path.display()
                );
                return;
            }
        };

        let file = match std::fs::File::open(path) {
            Ok(f) => f,
            Err(_) => return,
        };
        let mut buf = Vec::new();
        if file.take(10 * 1024 * 1024).read_to_end(&mut buf).is_err() {
            return;
        }
        let content = match String::from_utf8(buf) {
            Ok(s) => s,
            Err(e) => {
                let utf8_err = e.utf8_error();
                if utf8_err.error_len().is_none() {
                    let mut buf = e.into_bytes();
                    buf.truncate(utf8_err.valid_up_to());
                    match String::from_utf8(buf) {
                        Ok(s) => s,
                        Err(_) => return,
                    }
                } else {
                    return;
                }
            }
        };

        let file_id = next_node_id();
        file_ids.insert(rel.clone(), file_id.clone());
        result.push_node(MemoryNode {
            id: file_id.clone(),
            label: rel.clone(),
            node_type: NodeType::File,
            description: format!("Source file: {}", rel),
            source_file: Some(rel.clone()),
            source_location: None,
            tags: vec![language_tag(path)],
            created_at: now,
        });

        self.process_definitions(&content, path, &rel, &file_id, result, now);
        self.process_imports(&content, path, &rel, &file_id, file_ids, result);
    }

    fn process_definitions(
        &self,
        content: &str,
        path: &Path,
        rel: &str,
        file_id: &str,
        result: &mut ExtractionResult,
        now: chrono::DateTime<Utc>,
    ) {
        let defs = extract_definitions(content, path);
        for def in defs {
            let def_id = next_node_id();
            result.edges.push(MemoryEdge {
                source: file_id.to_string(),
                target: def_id.clone(),
                relation: EdgeRelation::Contains,
                confidence: 1.0,
                source_file: Some(rel.to_string()),
            });
            result.push_node(MemoryNode {
                id: def_id,
                label: def.name.clone(),
                node_type: def.kind,
                description: format!("{} defined in {}", def.name, rel),
                source_file: Some(rel.to_string()),
                source_location: Some(def.location.clone()),
                tags: Vec::new(),
                created_at: now,
            });
        }
    }

    fn process_imports(
        &self,
        content: &str,
        path: &Path,
        rel: &str,
        file_id: &str,
        file_ids: &HashMap<String, String>,
        result: &mut ExtractionResult,
    ) {
        for imp in extract_imports(content, path) {
            if let Some(target_id) = file_ids.get(&imp) {
                if target_id != file_id {
                    result.edges.push(MemoryEdge {
                        source: file_id.to_string(),
                        target: target_id.clone(),
                        relation: EdgeRelation::Imports,
                        confidence: 0.9,
                        source_file: Some(rel.to_string()),
                    });
                }
            }
        }
    }

    fn collect_files(&self, dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), GraphMemoryError> {
        let mut visited = std::collections::HashSet::new();
        self.collect_files_inner(dir, out, &mut visited)
    }

    fn collect_files_inner(
        &self,
        dir: &Path,
        out: &mut Vec<PathBuf>,
        visited: &mut std::collections::HashSet<std::path::PathBuf>,
    ) -> Result<(), GraphMemoryError> {
        // Canonicalize to resolve symlinks; reject if outside workspace or already visited.
        let canonical = match std::fs::canonicalize(dir) {
            Ok(c) => c,
            Err(_) => return Ok(()),
        };
        if !visited.insert(canonical.clone()) {
            return Ok(()); // cycle — already visited
        }
        let ws_canonical = self
            .workspace
            .canonicalize()
            .unwrap_or_else(|_| self.workspace.clone());
        if !canonical.starts_with(&ws_canonical) {
            return Ok(()); // symlink escapes workspace
        }
        let entries = match std::fs::read_dir(dir) {
            Ok(e) => e,
            Err(_) => return Ok(()),
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                let name = path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default();
                if name.starts_with('.')
                    || name == "target"
                    || name == "node_modules"
                    || name == "vendor"
                {
                    continue;
                }
                self.collect_files_inner(&path, out, visited)?;
            } else if is_source_file(&path) {
                out.push(path);
            }
        }
        Ok(())
    }
}

fn is_source_file(path: &Path) -> bool {
    matches!(
        path.extension().and_then(|e| e.to_str()),
        Some("rs") | Some("ts") | Some("py") | Some("go")
    )
}

fn language_tag(path: &Path) -> String {
    match path.extension().and_then(|e| e.to_str()) {
        Some("rs") => "rust",
        Some("ts") => "typescript",
        Some("py") => "python",
        Some("go") => "go",
        _ => "unknown",
    }
    .to_string()
}

struct Definition {
    name: String,
    kind: NodeType,
    location: String,
}

fn extract_definitions(content: &str, path: &Path) -> Vec<Definition> {
    let mut defs = Vec::new();
    let lang = language_tag(path);
    for (i, line) in content.lines().enumerate() {
        let trimmed = line.trim_start();
        let name = match lang.as_str() {
            "rust" => extract_rust_def(trimmed),
            "typescript" => extract_ts_def(trimmed),
            "python" => extract_py_def(trimmed),
            "go" => extract_go_def(trimmed),
            _ => None,
        };
        if let Some((name, kind)) = name {
            defs.push(Definition {
                name,
                kind,
                location: format!("line:{}", i + 1),
            });
        }
    }
    defs
}

fn extract_rust_def(line: &str) -> Option<(String, NodeType)> {
    let no_pub = line.strip_prefix("pub ").unwrap_or(line);
    let no_pub = no_pub.strip_prefix("pub(crate) ").unwrap_or(no_pub);
    if let Some(rest) = no_pub.strip_prefix("fn ") {
        return Some((take_ident(rest), NodeType::Function));
    }
    if let Some(rest) = no_pub.strip_prefix("struct ") {
        return Some((take_ident(rest), NodeType::Class));
    }
    if let Some(rest) = no_pub.strip_prefix("enum ") {
        return Some((take_ident(rest), NodeType::Class));
    }
    if let Some(rest) = no_pub.strip_prefix("trait ") {
        return Some((take_ident(rest), NodeType::Class));
    }
    if let Some(rest) = no_pub.strip_prefix("mod ") {
        return Some((take_ident(rest), NodeType::Module));
    }
    None
}

fn extract_ts_def(line: &str) -> Option<(String, NodeType)> {
    if let Some(rest) = line.strip_prefix("export ") {
        if let Some(r) = rest.strip_prefix("function ") {
            return Some((take_ident(r), NodeType::Function));
        }
        if let Some(r) = rest.strip_prefix("class ") {
            return Some((take_ident(r), NodeType::Class));
        }
    }
    if let Some(rest) = line.strip_prefix("function ") {
        return Some((take_ident(rest), NodeType::Function));
    }
    if let Some(rest) = line.strip_prefix("class ") {
        return Some((take_ident(rest), NodeType::Class));
    }
    None
}

fn extract_py_def(line: &str) -> Option<(String, NodeType)> {
    if let Some(rest) = line.strip_prefix("def ") {
        return Some((take_ident(rest), NodeType::Function));
    }
    if let Some(rest) = line.strip_prefix("class ") {
        return Some((take_ident(rest), NodeType::Class));
    }
    None
}

fn extract_go_def(line: &str) -> Option<(String, NodeType)> {
    if let Some(rest) = line.strip_prefix("func ") {
        if let Some(rest) = rest.strip_prefix("(") {
            if let Some(idx) = rest.find(')') {
                let after = &rest[idx + 1..].trim_start();
                if let Some(r) = after.strip_prefix(" ") {
                    return Some((take_ident(r), NodeType::Function));
                }
                return Some((take_ident(after), NodeType::Function));
            }
        }
        return Some((take_ident(rest), NodeType::Function));
    }
    if let Some(rest) = line.strip_prefix("type ") {
        return Some((take_ident(rest), NodeType::Class));
    }
    None
}

fn take_ident(s: &str) -> String {
    let mut out = String::new();
    for c in s.chars() {
        if c.is_alphanumeric() || c == '_' {
            out.push(c);
        } else {
            break;
        }
    }
    out
}

fn extract_imports(content: &str, path: &Path) -> Vec<String> {
    let mut imports = Vec::new();
    let lang = language_tag(path);
    for line in content.lines() {
        let trimmed = line.trim_start();
        match lang.as_str() {
            "rust" => {
                if let Some(rest) = trimmed.strip_prefix("mod ") {
                    let name = take_ident(rest);
                    if !name.is_empty() {
                        imports.push(format!("{}.rs", name));
                    }
                }
                if let Some(rest) = trimmed.strip_prefix("use ") {
                    if let Some(last) = rest
                        .split(|c: char| !c.is_alphanumeric() && c != '_')
                        .next_back()
                    {
                        if !last.is_empty() {
                            imports.push(format!("{}.rs", last));
                        }
                    }
                }
            }
            "python" => {
                if let Some(rest) = trimmed.strip_prefix("from ") {
                    if let Some(idx) = rest.find(" import ") {
                        imports.push(rest[..idx].trim().to_string());
                    }
                } else if let Some(rest) = trimmed.strip_prefix("import ") {
                    imports.push(rest.split_whitespace().next().unwrap_or("").to_string());
                }
            }
            "typescript" => {
                if let Some(rest) = trimmed.strip_prefix("import ") {
                    if let Some(idx) = rest.find("from ") {
                        let target = rest[idx + 5..]
                            .trim()
                            .trim_matches(|c: char| c == '"' || c == '\'');
                        imports.push(target.to_string());
                    }
                }
            }
            "go" if trimmed.starts_with("import") => {
                let quoted: Vec<&str> = trimmed.split('"').collect();
                if quoted.len() >= 3 {
                    imports.push(quoted[1].to_string());
                }
            }
            _ => {}
        }
    }
    imports
}