unfault 1.0.54

Unfault — a cognitive context engine for thoughtful engineers
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
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
//! Workspace identifier computation.
//!
//! This module provides functions to compute stable workspace identifiers
//! that remain consistent across CLI and LSP analysis sessions.
//!
//! The workspace_id is a fingerprint computed from stable workspace characteristics:
//! 1. Git remote URL (most reliable)
//! 2. Project manifest name (fallback)
//! 3. Workspace label scoped to org (last resort)

use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
use std::process::Command;

/// Source used to compute workspace_id.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WorkspaceIdSource {
    /// Computed from git remote URL - most stable.
    Git,
    /// Computed from project manifest (pyproject.toml, package.json, etc.).
    Manifest,
    /// Computed from workspace label - least stable.
    Label,
}

impl WorkspaceIdSource {
    /// Get the string representation for API requests.
    pub fn as_str(&self) -> &'static str {
        match self {
            WorkspaceIdSource::Git => "git",
            WorkspaceIdSource::Manifest => "manifest",
            WorkspaceIdSource::Label => "label",
        }
    }
}

/// Result of workspace ID computation.
#[derive(Debug, Clone)]
pub struct WorkspaceIdResult {
    /// The computed workspace ID (format: wks_{16_hex_chars}).
    pub id: String,
    /// The source used to compute the ID.
    pub source: WorkspaceIdSource,
}

/// Normalize a git remote URL to a canonical form.
///
/// Handles various git URL formats and normalizes them to a consistent form:
/// - `git@github.com:org/repo.git` -> `github.com/org/repo`
/// - `https://github.com/org/repo.git` -> `github.com/org/repo`
/// - `ssh://git@github.com/org/repo` -> `github.com/org/repo`
pub fn normalize_git_remote(remote: &str) -> String {
    let mut remote = remote.trim().to_string();

    // Handle SSH format: git@github.com:org/repo.git
    if remote.starts_with("git@") {
        remote = remote[4..].to_string();
        remote = remote.replacen(":", "/", 1);
    }
    // Handle explicit SSH protocol: ssh://git@github.com/org/repo
    else if remote.starts_with("ssh://") {
        remote = remote[6..].to_string();
        if remote.starts_with("git@") {
            remote = remote[4..].to_string();
        }
    }
    // Handle HTTP(S) protocol
    else if let Some(pos) = remote.find("://") {
        remote = remote[(pos + 3)..].to_string();
        // Remove credentials if present (user:pass@host)
        if let Some(at_pos) = remote.find('@') {
            if at_pos < remote.find('/').unwrap_or(remote.len()) {
                remote = remote[(at_pos + 1)..].to_string();
            }
        }
    }

    // Remove .git suffix
    if remote.ends_with(".git") {
        remote = remote[..remote.len() - 4].to_string();
    }

    // Remove trailing slashes
    remote = remote.trim_end_matches('/').to_string();

    // Lowercase for consistency
    remote.to_lowercase()
}

/// Compute SHA256 hash and return first 16 hex chars.
fn compute_hash(source: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(source.as_bytes());
    let result = hasher.finalize();
    hex::encode(&result[..8]) // 8 bytes = 16 hex chars
}

/// Get the git remote URL for a workspace.
///
/// Tries to get the "origin" remote first, falls back to any available remote.
pub fn get_git_remote(workspace_root: &Path) -> Option<String> {
    // Try to get origin remote
    let output = Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(workspace_root)
        .output()
        .ok()?;

    if output.status.success() {
        let remote = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if !remote.is_empty() {
            return Some(remote);
        }
    }

    // Fall back to first available remote
    let output = Command::new("git")
        .args(["remote"])
        .current_dir(workspace_root)
        .output()
        .ok()?;

    if output.status.success() {
        let remotes = String::from_utf8_lossy(&output.stdout);
        if let Some(first_remote) = remotes.lines().next() {
            let remote_output = Command::new("git")
                .args(["remote", "get-url", first_remote])
                .current_dir(workspace_root)
                .output()
                .ok()?;

            if remote_output.status.success() {
                let remote = String::from_utf8_lossy(&remote_output.stdout)
                    .trim()
                    .to_string();
                if !remote.is_empty() {
                    return Some(remote);
                }
            }
        }
    }

    None
}

/// Extract project name from pyproject.toml content.
fn extract_pyproject_name(contents: &str) -> Option<String> {
    // Try [project].name first (PEP 621)
    let project_section_re =
        regex::Regex::new(r#"\[project\]\s*\n[^\[]*?name\s*=\s*["\']([^"\']+)["\']"#).ok()?;
    if let Some(captures) = project_section_re.captures(contents) {
        return Some(captures.get(1)?.as_str().to_string());
    }

    // Try [tool.poetry].name
    let poetry_section_re =
        regex::Regex::new(r#"\[tool\.poetry\]\s*\n[^\[]*?name\s*=\s*["\']([^"\']+)["\']"#).ok()?;
    if let Some(captures) = poetry_section_re.captures(contents) {
        return Some(captures.get(1)?.as_str().to_string());
    }

    None
}

/// Extract project name from package.json content.
fn extract_package_json_name(contents: &str) -> Option<String> {
    let json: serde_json::Value = serde_json::from_str(contents).ok()?;
    json.get("name")?.as_str().map(|s| s.to_string())
}

/// Extract package name from Cargo.toml content.
fn extract_cargo_toml_name(contents: &str) -> Option<String> {
    let cargo_section_re =
        regex::Regex::new(r#"\[package\]\s*\n[^\[]*?name\s*=\s*["\']([^"\']+)["\']"#).ok()?;
    if let Some(captures) = cargo_section_re.captures(contents) {
        return Some(captures.get(1)?.as_str().to_string());
    }
    None
}

/// Extract module path from go.mod content.
fn extract_go_mod_module(contents: &str) -> Option<String> {
    let module_re = regex::Regex::new(r#"^module\s+(\S+)"#).ok()?;
    for line in contents.lines() {
        if let Some(captures) = module_re.captures(line) {
            return Some(captures.get(1)?.as_str().to_string());
        }
    }
    None
}

/// Meta file information for project name extraction.
pub struct MetaFileInfo {
    pub kind: &'static str,
    pub contents: String,
}

/// Extract project name from meta files.
pub fn extract_project_name_from_meta_files(meta_files: &[MetaFileInfo]) -> Option<String> {
    for mf in meta_files {
        let name = match mf.kind {
            "pyproject" => extract_pyproject_name(&mf.contents),
            "package_json" => extract_package_json_name(&mf.contents),
            "cargo_toml" => extract_cargo_toml_name(&mf.contents),
            "go_mod" => extract_go_mod_module(&mf.contents),
            _ => None,
        };

        if name.is_some() {
            return name;
        }
    }

    None
}

/// Compute a stable workspace identifier.
///
/// Tries sources in order of stability:
/// 1. Git remote URL (if available)
/// 2. Project manifest name (if available)
/// 3. Workspace label (fallback)
pub fn compute_workspace_id(
    git_remote: Option<&str>,
    meta_files: Option<&[MetaFileInfo]>,
    workspace_label: Option<&str>,
) -> Option<WorkspaceIdResult> {
    // Priority 1: Git remote URL
    if let Some(remote) = git_remote {
        let normalized = normalize_git_remote(remote);
        if !normalized.is_empty() {
            let hash = compute_hash(&format!("git:{}", normalized));
            return Some(WorkspaceIdResult {
                id: format!("wks_{}", hash),
                source: WorkspaceIdSource::Git,
            });
        }
    }

    // Priority 2: Project manifest name
    if let Some(files) = meta_files {
        if let Some(project_name) = extract_project_name_from_meta_files(files) {
            let hash = compute_hash(&format!("manifest:{}", project_name));
            return Some(WorkspaceIdResult {
                id: format!("wks_{}", hash),
                source: WorkspaceIdSource::Manifest,
            });
        }
    }

    // Priority 3: Workspace label
    if let Some(label) = workspace_label {
        // Note: In CLI, we don't have org_id, so we use "cli" as scope
        // This means label-based IDs from CLI won't match API-computed ones
        // until git remote is added
        let hash = compute_hash(&format!("label:cli:{}", label));
        return Some(WorkspaceIdResult {
            id: format!("wks_{}", hash),
            source: WorkspaceIdSource::Label,
        });
    }

    None
}

/// Return relative paths of files changed since HEAD (staged + unstaged).
///
/// Runs:
///   `git diff --name-only HEAD`  — staged and unstaged changes vs HEAD
///   `git ls-files --others --exclude-standard` — untracked new files
///
/// Returns an empty `Vec` (not an error) if not inside a git repository or
/// if git is not installed. The caller treats an empty list as "no diff info."
pub fn get_git_changed_files(workspace_root: &Path) -> Vec<String> {
    let mut changed: Vec<String> = Vec::new();

    // 1) Staged + unstaged changes against HEAD.
    if let Ok(output) = Command::new("git")
        .args(["diff", "--name-only", "HEAD"])
        .current_dir(workspace_root)
        .output()
    {
        if output.status.success() {
            for line in String::from_utf8_lossy(&output.stdout).lines() {
                let line = line.trim();
                if !line.is_empty() {
                    changed.push(line.to_string());
                }
            }
        }
    }

    // 2) New untracked files (not yet committed or staged).
    if let Ok(output) = Command::new("git")
        .args(["ls-files", "--others", "--exclude-standard"])
        .current_dir(workspace_root)
        .output()
    {
        if output.status.success() {
            for line in String::from_utf8_lossy(&output.stdout).lines() {
                let line = line.trim();
                if !line.is_empty() && !changed.contains(&line.to_string()) {
                    changed.push(line.to_string());
                }
            }
        }
    }

    changed
}

/// Return the absolute paths of source files touched by a specific git commit.
///
/// Runs `git diff-tree --no-commit-id -r --name-only <commit_ref>` which lists
/// every file added, modified, or deleted in the given commit.  Deleted files
/// are resolved but will simply not exist on disk; callers that pass the result
/// to the IR builder will skip them silently (the file-read step returns an
/// error that is treated as a cache miss / skip).
///
/// `commit_ref` can be any git revision accepted by `diff-tree`: a full SHA,
/// short SHA, branch name, tag, or symbolic ref like `HEAD` or `HEAD~1`.
///
/// Returns an error string if git is not available or the ref is invalid.
/// Returns an empty `Vec` when the commit touched no files (e.g. an empty
/// merge commit).
pub fn get_git_commit_files(
    workspace_root: &Path,
    commit_ref: &str,
) -> Result<Vec<PathBuf>, String> {
    let output = Command::new("git")
        .args([
            "diff-tree",
            "--no-commit-id",
            "-r",
            "--name-only",
            "--diff-filter=ACM", // Added, Copied, Modified — skip Deleted
            commit_ref,
        ])
        .current_dir(workspace_root)
        .output()
        .map_err(|e| format!("Failed to run git: {e}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!(
            "git diff-tree failed for ref '{commit_ref}': {stderr}"
        ));
    }

    let mut files = Vec::new();
    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let line = line.trim();
        if !line.is_empty() {
            files.push(workspace_root.join(line));
        }
    }
    Ok(files)
}

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

    #[test]
    fn test_normalize_git_remote_ssh() {
        assert_eq!(
            normalize_git_remote("git@github.com:acme/repo.git"),
            "github.com/acme/repo"
        );
    }

    #[test]
    fn test_normalize_git_remote_https() {
        assert_eq!(
            normalize_git_remote("https://github.com/acme/repo.git"),
            "github.com/acme/repo"
        );
    }

    #[test]
    fn test_normalize_git_remote_ssh_protocol() {
        assert_eq!(
            normalize_git_remote("ssh://git@github.com/acme/repo.git"),
            "github.com/acme/repo"
        );
    }

    #[test]
    fn test_normalize_git_remote_no_suffix() {
        assert_eq!(
            normalize_git_remote("https://github.com/acme/repo"),
            "github.com/acme/repo"
        );
    }

    #[test]
    fn test_normalize_git_remote_trailing_slash() {
        assert_eq!(
            normalize_git_remote("https://github.com/acme/repo/"),
            "github.com/acme/repo"
        );
    }

    #[test]
    fn test_compute_workspace_id_git() {
        let result = compute_workspace_id(
            Some("git@github.com:acme/payments.git"),
            None,
            Some("payments"),
        );

        assert!(result.is_some());
        let result = result.unwrap();
        assert!(result.id.starts_with("wks_"));
        assert_eq!(result.id.len(), 20); // "wks_" + 16 hex chars
        assert_eq!(result.source, WorkspaceIdSource::Git);
    }

    #[test]
    fn test_compute_workspace_id_manifest() {
        let meta_files = vec![MetaFileInfo {
            kind: "pyproject",
            contents: r#"[project]
name = "payments-service"
version = "1.0.0"
"#
            .to_string(),
        }];

        let result = compute_workspace_id(None, Some(&meta_files), Some("payments"));

        assert!(result.is_some());
        let result = result.unwrap();
        assert!(result.id.starts_with("wks_"));
        assert_eq!(result.source, WorkspaceIdSource::Manifest);
    }

    #[test]
    fn test_compute_workspace_id_label_fallback() {
        let result = compute_workspace_id(None, None, Some("my-project"));

        assert!(result.is_some());
        let result = result.unwrap();
        assert!(result.id.starts_with("wks_"));
        assert_eq!(result.source, WorkspaceIdSource::Label);
    }

    #[test]
    fn test_compute_workspace_id_none() {
        let result = compute_workspace_id(None, None, None);
        assert!(result.is_none());
    }

    #[test]
    fn test_extract_pyproject_name_pep621() {
        let content = r#"[project]
name = "my-package"
version = "1.0.0"
"#;
        assert_eq!(
            extract_pyproject_name(content),
            Some("my-package".to_string())
        );
    }

    #[test]
    fn test_extract_pyproject_name_poetry() {
        let content = r#"[tool.poetry]
name = "my-package"
version = "1.0.0"
"#;
        assert_eq!(
            extract_pyproject_name(content),
            Some("my-package".to_string())
        );
    }

    #[test]
    fn test_extract_package_json_name() {
        let content = r#"{"name": "my-package", "version": "1.0.0"}"#;
        assert_eq!(
            extract_package_json_name(content),
            Some("my-package".to_string())
        );
    }

    #[test]
    fn test_extract_cargo_toml_name() {
        let content = r#"[package]
name = "my-crate"
version = "0.1.0"
"#;
        assert_eq!(
            extract_cargo_toml_name(content),
            Some("my-crate".to_string())
        );
    }

    #[test]
    fn test_extract_go_mod_module() {
        let content = r#"module github.com/acme/myservice

go 1.21
"#;
        assert_eq!(
            extract_go_mod_module(content),
            Some("github.com/acme/myservice".to_string())
        );
    }
}