leankg 0.16.7

Lightweight Knowledge Graph for AI-Assisted Development
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
use std::path::PathBuf;
use std::process::Command;

#[derive(Debug, Clone)]
pub struct StagedChange {
    pub path: PathBuf,
    pub status: ChangeStatus,
}

#[derive(Debug, Clone)]
pub enum ChangeStatus {
    Added,
    Modified,
    Deleted,
    Renamed,
}

#[derive(Debug, Clone)]
pub enum HookRecommendation {
    Allow(String),
    Warn(String, Vec<String>),
    Block(String, Vec<String>),
}

#[derive(Debug, Clone)]
pub struct IndexStatus {
    pub is_stale: bool,
    pub last_indexed_commit: Option<String>,
    pub current_commit: String,
    pub affected_files: Vec<PathBuf>,
}

pub struct GitHooks {
    project_path: PathBuf,
}

impl GitHooks {
    pub fn new(project_path: PathBuf) -> Self {
        Self { project_path }
    }

    pub fn install_pre_commit(&self) -> Result<(), HookError> {
        let hooks_dir = self.project_path.join(".git").join("hooks");
        std::fs::create_dir_all(&hooks_dir).map_err(|e| HookError::Io(e.to_string()))?;

        let pre_commit_path = hooks_dir.join("pre-commit");
        let script = self.generate_pre_commit_script()?;

        if pre_commit_path.exists() {
            let existing = std::fs::read_to_string(&pre_commit_path)
                .map_err(|e| HookError::Io(e.to_string()))?;

            if existing.contains("LeanKG") {
                return Err(HookError::AlreadyInstalled(
                    "pre-commit hook already installed by LeanKG".to_string(),
                ));
            }

            let backup_path = hooks_dir.join("pre-commit.leankg.backup");
            std::fs::write(&backup_path, &existing).map_err(|e| HookError::Io(e.to_string()))?;
        }

        std::fs::write(&pre_commit_path, script).map_err(|e| HookError::Io(e.to_string()))?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&pre_commit_path)
                .map_err(|e| HookError::Io(e.to_string()))?
                .permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&pre_commit_path, perms)
                .map_err(|e| HookError::Io(e.to_string()))?;
        }

        println!(
            "Installed LeanKG pre-commit hook at {}",
            pre_commit_path.display()
        );
        Ok(())
    }

    pub fn install_post_commit(&self) -> Result<(), HookError> {
        let hooks_dir = self.project_path.join(".git").join("hooks");
        std::fs::create_dir_all(&hooks_dir).map_err(|e| HookError::Io(e.to_string()))?;

        let post_commit_path = hooks_dir.join("post-commit");
        let script = self.generate_post_commit_script()?;

        if post_commit_path.exists() {
            let existing = std::fs::read_to_string(&post_commit_path)
                .map_err(|e| HookError::Io(e.to_string()))?;

            if existing.contains("LeanKG") {
                return Err(HookError::AlreadyInstalled(
                    "post-commit hook already installed by LeanKG".to_string(),
                ));
            }

            let backup_path = hooks_dir.join("post-commit.leankg.backup");
            std::fs::write(&backup_path, &existing).map_err(|e| HookError::Io(e.to_string()))?;
        }

        std::fs::write(&post_commit_path, script).map_err(|e| HookError::Io(e.to_string()))?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&post_commit_path)
                .map_err(|e| HookError::Io(e.to_string()))?
                .permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&post_commit_path, perms)
                .map_err(|e| HookError::Io(e.to_string()))?;
        }

        println!(
            "Installed LeanKG post-commit hook at {}",
            post_commit_path.display()
        );
        Ok(())
    }

    pub fn install_post_checkout(&self) -> Result<(), HookError> {
        let hooks_dir = self.project_path.join(".git").join("hooks");
        std::fs::create_dir_all(&hooks_dir).map_err(|e| HookError::Io(e.to_string()))?;

        let post_checkout_path = hooks_dir.join("post-checkout");
        let script = self.generate_post_checkout_script()?;

        if post_checkout_path.exists() {
            let existing = std::fs::read_to_string(&post_checkout_path)
                .map_err(|e| HookError::Io(e.to_string()))?;

            if existing.contains("LeanKG") {
                return Err(HookError::AlreadyInstalled(
                    "post-checkout hook already installed by LeanKG".to_string(),
                ));
            }

            let backup_path = hooks_dir.join("post-checkout.leankg.backup");
            std::fs::write(&backup_path, &existing).map_err(|e| HookError::Io(e.to_string()))?;
        }

        std::fs::write(&post_checkout_path, script).map_err(|e| HookError::Io(e.to_string()))?;

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&post_checkout_path)
                .map_err(|e| HookError::Io(e.to_string()))?
                .permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&post_checkout_path, perms)
                .map_err(|e| HookError::Io(e.to_string()))?;
        }

        println!(
            "Installed LeanKG post-checkout hook at {}",
            post_checkout_path.display()
        );
        Ok(())
    }

    pub fn uninstall_hooks(&self) -> Result<(), HookError> {
        let hooks_dir = self.project_path.join(".git").join("hooks");

        for hook_name in ["pre-commit", "post-commit", "post-checkout"] {
            let hook_path = hooks_dir.join(hook_name);
            if hook_path.exists() {
                let content = std::fs::read_to_string(&hook_path)
                    .map_err(|e| HookError::Io(e.to_string()))?;

                if content.contains("LeanKG") {
                    std::fs::remove_file(&hook_path).map_err(|e| HookError::Io(e.to_string()))?;
                    println!("Removed LeanKG {} hook", hook_name);
                }

                let backup_path = hooks_dir.join(format!("{}.leankg.backup", hook_name));
                if backup_path.exists() {
                    std::fs::rename(&backup_path, &hook_path)
                        .map_err(|e| HookError::Io(e.to_string()))?;
                    println!("Restored original {} hook from backup", hook_name);
                }
            }
        }

        Ok(())
    }

    pub fn check_hooks_status(&self) -> Result<HooksStatus, HookError> {
        let hooks_dir = self.project_path.join(".git").join("hooks");

        let mut status = HooksStatus {
            pre_commit_installed: false,
            post_commit_installed: false,
            post_checkout_installed: false,
            pre_commit_backup_exists: false,
            post_commit_backup_exists: false,
            post_checkout_backup_exists: false,
        };

        for hook_name in ["pre-commit", "post-commit", "post-checkout"] {
            let hook_path = hooks_dir.join(hook_name);
            let backup_path = hooks_dir.join(format!("{}.leankg.backup", hook_name));

            if hook_path.exists() {
                let content = std::fs::read_to_string(&hook_path)
                    .map_err(|e| HookError::Io(e.to_string()))?;

                match hook_name {
                    "pre-commit" => status.pre_commit_installed = content.contains("LeanKG"),
                    "post-commit" => status.post_commit_installed = content.contains("LeanKG"),
                    "post-checkout" => status.post_checkout_installed = content.contains("LeanKG"),
                    _ => {}
                }
            }

            match hook_name {
                "pre-commit" => status.pre_commit_backup_exists = backup_path.exists(),
                "post-commit" => status.post_commit_backup_exists = backup_path.exists(),
                "post-checkout" => status.post_checkout_backup_exists = backup_path.exists(),
                _ => {}
            }
        }

        Ok(status)
    }

    pub fn detect_staged_changes(&self) -> Result<Vec<StagedChange>, HookError> {
        let output = Command::new("git")
            .args(["diff", "--cached", "--name-status"])
            .current_dir(&self.project_path)
            .output()
            .map_err(|e| HookError::Git(e.to_string()))?;

        if !output.status.success() {
            return Err(HookError::Git(
                String::from_utf8_lossy(&output.stderr).to_string(),
            ));
        }

        let mut changes = Vec::new();
        for line in String::from_utf8_lossy(&output.stdout).lines() {
            let parts: Vec<&str> = line.split('\t').collect();
            if parts.len() >= 2 {
                let status = match parts[0] {
                    "A" => ChangeStatus::Added,
                    "M" => ChangeStatus::Modified,
                    "D" => ChangeStatus::Deleted,
                    "R" => ChangeStatus::Renamed,
                    _ => continue,
                };
                changes.push(StagedChange {
                    path: PathBuf::from(parts[1]),
                    status,
                });
            }
        }

        Ok(changes)
    }

    pub fn check_critical_files(
        &self,
        changes: &[StagedChange],
    ) -> Result<HookRecommendation, HookError> {
        let critical_patterns = ["src/lib.rs", "src/main.rs", "Cargo.toml", "leankg.yaml"];

        let mut critical_changes = Vec::new();
        let mut warnings = Vec::new();

        for change in changes {
            let path_str = change.path.to_string_lossy();
            for pattern in &critical_patterns {
                if path_str.contains(pattern) {
                    critical_changes.push(path_str.to_string());
                    break;
                }
            }

            if path_str.contains("src/hooks/") || path_str.contains("src/watcher/") {
                warnings.push(format!(
                    "{}: hook/watcher changes may affect auto-indexing",
                    path_str
                ));
            }
        }

        if !critical_changes.is_empty() {
            Ok(HookRecommendation::Block(
                format!("Critical files modified: {}", critical_changes.join(", ")),
                critical_changes,
            ))
        } else if !warnings.is_empty() {
            Ok(HookRecommendation::Warn(
                "Potential issues detected".to_string(),
                warnings,
            ))
        } else {
            Ok(HookRecommendation::Allow(
                "No critical files affected".to_string(),
            ))
        }
    }

    fn generate_pre_commit_script(&self) -> Result<String, HookError> {
        Ok(r#"#!/bin/sh
# LeanKG pre-commit hook
# Generated by LeanKG

# Run leankg detect-changes on staged files
STAGED_FILES=$(git diff --cached --name-only)
if [ -n "$STAGED_FILES" ]; then
    echo "LeanKG: Checking staged changes..."
    # Run detect-changes if available
    if command -v leankg >/dev/null 2>&1; then
        # Check for critical files
        CRITICAL_FILES="src/lib.rs src/main.rs Cargo.toml"
        for file in $STAGED_FILES; do
            for critical in $CRITICAL_FILES; do
                if echo "$file" | grep -q "$critical"; then
                    echo "LeanKG: WARNING - modifying critical file: $file"
                fi
            done
        done
    fi
fi

# Allow commit to proceed
exit 0
"#
        .to_string())
    }

    fn generate_post_commit_script(&self) -> Result<String, HookError> {
        Ok(r#"#!/bin/sh
# LeanKG post-commit hook
# Generated by LeanKG

# Run incremental index after commit
if command -v leankg >/dev/null 2>&1; then
    leankg index --incremental --quiet 2>/dev/null
    if [ $? -ne 0 ]; then
        echo "LeanKG: WARNING - incremental reindex failed" >&2
    fi
fi

exit 0
"#
        .to_string())
    }

    fn generate_post_checkout_script(&self) -> Result<String, HookError> {
        Ok(r#"#!/bin/sh
# LeanKG post-checkout hook
# Generated by LeanKG

# Run incremental index after branch switch
if command -v leankg >/dev/null 2>&1; then
    leankg index --incremental --quiet 2>/dev/null
    if [ $? -ne 0 ]; then
        echo "LeanKG: WARNING - incremental reindex failed after checkout" >&2
    fi
fi

exit 0
"#
        .to_string())
    }
}

#[derive(Debug, Clone)]
pub struct HooksStatus {
    pub pre_commit_installed: bool,
    pub post_commit_installed: bool,
    pub post_checkout_installed: bool,
    pub pre_commit_backup_exists: bool,
    pub post_commit_backup_exists: bool,
    pub post_checkout_backup_exists: bool,
}

pub struct GitWatcher {
    project_path: PathBuf,
    db_path: PathBuf,
}

impl GitWatcher {
    pub fn new(project_path: PathBuf, db_path: PathBuf) -> Self {
        Self {
            project_path,
            db_path,
        }
    }

    pub fn check_index_status(&self) -> Result<IndexStatus, HookError> {
        let current_commit = self.get_current_commit()?;
        let last_indexed_commit = self.get_last_indexed_commit()?;

        let is_stale = last_indexed_commit
            .as_ref()
            .map(|last| last != &current_commit)
            .unwrap_or(true);

        let affected_files = if is_stale {
            self.get_changed_files_since_index()?
        } else {
            Vec::new()
        };

        Ok(IndexStatus {
            is_stale,
            last_indexed_commit,
            current_commit,
            affected_files,
        })
    }

    pub fn sync_on_branch_change(&self, new_branch: &str) -> Result<(), HookError> {
        println!("Branch changed to: {}", new_branch);

        let status = self.check_index_status()?;
        if status.is_stale {
            println!("Index is stale, syncing...");
            self.run_incremental_index()?;
        } else {
            println!("Index is up to date");
        }

        Ok(())
    }

    pub fn run_incremental_index(&self) -> Result<(), HookError> {
        let output = Command::new("leankg")
            .args(["index", "--incremental"])
            .current_dir(&self.project_path)
            .output()
            .map_err(|e| HookError::Io(e.to_string()))?;

        if !output.status.success() {
            return Err(HookError::HookExecution(format!(
                "Incremental index failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }

        self.update_last_indexed_commit()?;

        Ok(())
    }

    fn get_current_commit(&self) -> Result<String, HookError> {
        let output = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&self.project_path)
            .output()
            .map_err(|e| HookError::Git(e.to_string()))?;

        if !output.status.success() {
            return Err(HookError::Git(
                String::from_utf8_lossy(&output.stderr).to_string(),
            ));
        }

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    fn get_last_indexed_commit(&self) -> Result<Option<String>, HookError> {
        let marker_path = self.db_path.join(".last_indexed_commit");

        if marker_path.exists() {
            let content =
                std::fs::read_to_string(&marker_path).map_err(|e| HookError::Io(e.to_string()))?;
            Ok(Some(content.trim().to_string()))
        } else {
            Ok(None)
        }
    }

    fn update_last_indexed_commit(&self) -> Result<(), HookError> {
        let commit = self.get_current_commit()?;
        let marker_path = self.db_path.join(".last_indexed_commit");

        std::fs::write(&marker_path, &commit).map_err(|e| HookError::Io(e.to_string()))?;

        Ok(())
    }

    fn get_changed_files_since_index(&self) -> Result<Vec<PathBuf>, HookError> {
        let last_commit = self
            .get_last_indexed_commit()?
            .ok_or(HookError::HookExecution(
                "No previous commit found".to_string(),
            ))?;

        let output = Command::new("git")
            .args(["diff", "--name-only", &last_commit, "HEAD"])
            .current_dir(&self.project_path)
            .output()
            .map_err(|e| HookError::Git(e.to_string()))?;

        if !output.status.success() {
            return Err(HookError::Git(
                String::from_utf8_lossy(&output.stderr).to_string(),
            ));
        }

        let files: Vec<PathBuf> = String::from_utf8_lossy(&output.stdout)
            .lines()
            .filter(|line| !line.is_empty())
            .map(PathBuf::from)
            .collect();

        Ok(files)
    }
}

#[derive(Debug)]
pub enum HookError {
    Io(String),
    Git(String),
    AlreadyInstalled(String),
    HookExecution(String),
}

impl std::fmt::Display for HookError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HookError::Io(msg) => write!(f, "IO error: {}", msg),
            HookError::Git(msg) => write!(f, "Git error: {}", msg),
            HookError::AlreadyInstalled(msg) => write!(f, "Hook already installed: {}", msg),
            HookError::HookExecution(msg) => write!(f, "Hook execution error: {}", msg),
        }
    }
}

impl std::error::Error for HookError {}

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

    #[test]
    fn test_githooks_new() {
        let path = PathBuf::from("/test/path");
        let hooks = GitHooks::new(path.clone());
        assert_eq!(hooks.project_path, path);
    }

    #[test]
    fn test_gitwatcher_new() {
        let project = PathBuf::from("/test/project");
        let db = PathBuf::from("/test/project/.leankg");
        let watcher = GitWatcher::new(project.clone(), db.clone());
        assert_eq!(watcher.project_path, project);
        assert_eq!(watcher.db_path, db);
    }

    #[test]
    fn test_hook_error_display() {
        let err = HookError::Io("test error".to_string());
        assert_eq!(format!("{}", err), "IO error: test error");

        let err = HookError::Git("git error".to_string());
        assert_eq!(format!("{}", err), "Git error: git error");
    }

    #[test]
    fn test_staged_change_status() {
        let change = StagedChange {
            path: PathBuf::from("test.rs"),
            status: ChangeStatus::Modified,
        };
        assert!(matches!(change.status, ChangeStatus::Modified));
    }

    #[test]
    fn test_hooks_status_defaults() {
        let status = HooksStatus {
            pre_commit_installed: false,
            post_commit_installed: false,
            post_checkout_installed: false,
            pre_commit_backup_exists: false,
            post_commit_backup_exists: false,
            post_checkout_backup_exists: false,
        };
        assert!(!status.pre_commit_installed);
    }
}