bobbin-ai 0.25.2

Local-first context injection engine for AI coding agents
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
//! Webhook handler and source URL resolution.
#![allow(private_interfaces)]

use std::path::PathBuf;
use std::sync::Arc;

use axum::body::Bytes;
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use axum::response::IntoResponse;
use axum::Json;
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use sha2::Sha256;

use crate::config::Config;
use crate::storage::VectorStore;

use super::AppState;

// ---------------------------------------------------------------------------
// Source URL resolution (called at startup from http/mod.rs)
// ---------------------------------------------------------------------------

/// Known forge types with their URL patterns for file browsing.
#[derive(Debug, Clone, Copy, PartialEq)]
enum ForgeType {
    GitHub,
    GitLab,
    Forgejo, // also covers Gitea
    Bitbucket,
}

impl ForgeType {
    /// Returns the URL template suffix for browsing a file at a line.
    /// Template uses `{path}` and `{line}` placeholders.
    fn file_template(&self) -> &'static str {
        match self {
            ForgeType::GitHub => "/blob/main/{path}#L{line}",
            ForgeType::GitLab => "/-/blob/main/{path}#L{line}",
            ForgeType::Forgejo => "/src/branch/main/{path}#L{line}",
            ForgeType::Bitbucket => "/src/main/{path}#{path}-{line}",
        }
    }
}

/// Detect the forge type from a hostname.
///
/// Uses well-known SaaS hosts plus heuristics for self-hosted instances.
fn detect_forge(host: &str) -> ForgeType {
    let h = host.to_lowercase();
    if h == "github.com" || h.ends_with(".github.com") {
        return ForgeType::GitHub;
    }
    if h == "gitlab.com" || h.ends_with(".gitlab.com") {
        return ForgeType::GitLab;
    }
    if h == "bitbucket.org" || h.ends_with(".bitbucket.org") {
        return ForgeType::Bitbucket;
    }
    // Self-hosted: check if host contains forge name hints
    if h.contains("gitlab") {
        return ForgeType::GitLab;
    }
    if h.contains("bitbucket") {
        return ForgeType::Bitbucket;
    }
    // Default to Forgejo/Gitea for self-hosted (most common for homelab)
    ForgeType::Forgejo
}

/// Extract the hostname from a web base URL.
fn host_from_url(url: &str) -> Option<&str> {
    let rest = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))?;
    // host might include port
    Some(rest.split('/').next()?.split(':').next()?)
}

/// Extract a web base URL from a git remote URL.
///
/// Converts SSH (`git@host:owner/repo.git`) and HTTPS (`https://host/owner/repo.git`)
/// remotes into a plain web base URL (`https://host/owner/repo`).
/// Returns None if the remote URL can't be parsed.
fn web_base_from_remote(remote: &str) -> Option<String> {
    let trimmed = remote.trim().trim_end_matches(".git");

    // SSH: git@host:owner/repo.git
    if let Some(rest) = trimmed.strip_prefix("git@") {
        let (host, path) = rest.split_once(':')?;
        let path = path.trim_start_matches('/');
        if path.split('/').count() < 2 {
            return None;
        }
        return Some(format!("https://{host}/{path}"));
    }

    // HTTPS: http(s)://host[:port]/owner/repo.git
    if trimmed.starts_with("https://") || trimmed.starts_with("http://") {
        return Some(trimmed.to_string());
    }

    None
}

/// Build a full file-browse URL template from a base URL.
///
/// If `remote_template` is configured, uses it. Otherwise auto-detects the
/// forge type from the host and applies the correct URL pattern.
/// `forge_overrides` lets users override detection for specific hosts.
fn build_source_url(
    base: &str,
    remote_template: &str,
    repo_name: &str,
    forge_overrides: &std::collections::HashMap<String, String>,
) -> String {
    if !remote_template.is_empty() {
        return remote_template
            .replace("{remote_base}", base)
            .replace("{repo}", repo_name);
    }

    // Auto-detect forge type from the base URL host
    let forge = host_from_url(base)
        .map(|host| {
            // Check user overrides first
            if let Some(override_type) = forge_overrides.get(host) {
                match override_type.to_lowercase().as_str() {
                    "github" => ForgeType::GitHub,
                    "gitlab" => ForgeType::GitLab,
                    "forgejo" | "gitea" => ForgeType::Forgejo,
                    "bitbucket" => ForgeType::Bitbucket,
                    _ => detect_forge(host),
                }
            } else {
                detect_forge(host)
            }
        })
        .unwrap_or(ForgeType::Forgejo);

    format!("{}{}", base.trim_end_matches('/'), forge.file_template())
}

/// Auto-detect source URLs from git remotes for all indexed repos,
/// merged with manual overrides from config. Called once at startup.
///
/// For each repo without an explicit `[sources.repos]` entry, reads its git
/// remote origin, extracts a web base URL, and auto-detects the forge type
/// (GitHub/GitLab/Forgejo/Bitbucket) to build correct deep links.
pub(crate) fn resolve_sources(
    repo_root: &std::path::Path,
    config_sources: &crate::config::SourcesConfig,
) -> crate::config::SourcesConfig {
    let mut sources = config_sources.clone();
    let repos_dir = repo_root.join("repos");
    if let Ok(entries) = std::fs::read_dir(&repos_dir) {
        for entry in entries.flatten() {
            let repo_name = entry.file_name().to_string_lossy().to_string();
            if sources.repos.contains_key(&repo_name) {
                continue;
            }
            let repo_path = entry.path();
            if let Ok(output) = std::process::Command::new("git")
                .args([
                    "-C",
                    &repo_path.to_string_lossy(),
                    "remote",
                    "get-url",
                    "origin",
                ])
                .output()
            {
                if output.status.success() {
                    let remote = String::from_utf8_lossy(&output.stdout).trim().to_string();
                    if let Some(base) = web_base_from_remote(&remote) {
                        let url = build_source_url(
                            &base,
                            &sources.remote_template,
                            &repo_name,
                            &sources.forge_overrides,
                        );
                        sources.repos.insert(repo_name, url);
                    }
                } else {
                    sources.repos.insert(repo_name, String::new());
                }
            } else {
                sources.repos.insert(repo_name, String::new());
            }
        }
    }
    sources
}

// ---------------------------------------------------------------------------
// /webhook/push
// ---------------------------------------------------------------------------

/// Forgejo push webhook payload (subset of fields we care about)
#[derive(Deserialize)]
pub(super) struct ForgejoPushPayload {
    #[serde(rename = "ref")]
    git_ref: Option<String>,
    repository: Option<RepoInfo>,
}

#[derive(Deserialize)]
pub(super) struct RepoInfo {
    full_name: Option<String>,
}

#[derive(Serialize)]
pub(super) struct WebhookResponse {
    status: String,
    message: String,
}

const SIGNATURE_HEADER: &str = "x-gitea-signature";

/// Verify Forgejo/Gitea's hex-encoded HMAC-SHA256 over the exact request body.
/// Empty configuration is fail-closed: a declared authentication surface that
/// silently becomes public when its secret is missing is worse than an outage.
fn valid_signature(secret: &str, signature: Option<&str>, body: &[u8]) -> bool {
    if secret.is_empty() {
        return false;
    }
    let Some(signature) = signature.and_then(|value| hex::decode(value).ok()) else {
        return false;
    };
    let Ok(mut mac) = Hmac::<Sha256>::new_from_slice(secret.as_bytes()) else {
        return false;
    };
    mac.update(body);
    mac.verify_slice(&signature).is_ok()
}

#[cfg(test)]
fn hmac_sha256(key: &[u8], body: &[u8]) -> [u8; 32] {
    let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC accepts keys of any size");
    mac.update(body);
    mac.finalize().into_bytes().into()
}

pub(super) async fn webhook_push(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    body: Bytes,
) -> axum::response::Response {
    let signature = headers
        .get(SIGNATURE_HEADER)
        .and_then(|value| value.to_str().ok());
    if !valid_signature(&state.config.archive.webhook_secret, signature, &body) {
        tracing::warn!("Rejected push webhook with missing or invalid signature");
        return (
            StatusCode::UNAUTHORIZED,
            Json(WebhookResponse {
                status: "unauthorized".to_string(),
                message: "Missing or invalid webhook signature".to_string(),
            }),
        )
            .into_response();
    }
    let payload: ForgejoPushPayload = match serde_json::from_slice(&body) {
        Ok(payload) => payload,
        Err(error) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(WebhookResponse {
                    status: "invalid".to_string(),
                    message: format!("Invalid webhook payload: {error}"),
                }),
            )
                .into_response();
        }
    };
    let repo_name = payload
        .repository
        .as_ref()
        .and_then(|r| r.full_name.as_deref())
        .unwrap_or("unknown");

    let git_ref = payload.git_ref.as_deref().unwrap_or("unknown");

    tracing::info!(repo = repo_name, git_ref = git_ref, "Received push webhook");

    // Try to map repo full_name to our indexed repo name
    // e.g., "stiwi/bobbin" -> "bobbin"
    let short_repo = repo_name
        .rsplit('/')
        .next()
        .unwrap_or(repo_name)
        .to_string();

    // Verify this repo is indexed
    let repos_dir = state.repo_root.join("repos");
    let repo_dir = repos_dir.join(&short_repo);
    if !repo_dir.exists() {
        tracing::warn!(repo = short_repo, "Webhook for non-indexed repo, skipping");
        return Json(WebhookResponse {
            status: "skipped".to_string(),
            message: format!("Repo '{}' not indexed", short_repo),
        })
        .into_response();
    }

    // Pull latest changes
    let pull_result = std::process::Command::new("git")
        .args(["-C", &repo_dir.to_string_lossy(), "pull", "--ff-only"])
        .output();

    match pull_result {
        Ok(output) if output.status.success() => {
            tracing::info!(repo = short_repo, "Git pull succeeded");
        }
        Ok(output) => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            tracing::warn!(repo = short_repo, error = %stderr, "Git pull failed");
        }
        Err(e) => {
            tracing::warn!(repo = short_repo, error = %e, "Failed to run git pull");
        }
    }

    // Queue background re-index
    let repo_root = state.repo_root.clone();
    let config = state.config.clone();
    let source_dir = repo_dir.clone();
    let repo_tag = short_repo.clone();
    tokio::spawn(async move {
        if let Err(e) = run_incremental_index(repo_root, config, &source_dir, &repo_tag).await {
            tracing::error!(repo = short_repo, error = %e, "Background re-index failed");
        } else {
            tracing::info!("Background re-index completed for {}", short_repo);
        }
    });

    Json(WebhookResponse {
        status: "accepted".to_string(),
        message: format!("Re-index queued for push to {}", git_ref),
    })
    .into_response()
}

/// Run incremental indexing for a specific repo (used by webhook handler).
///
/// `source_dir` is the directory to walk (e.g., `/var/lib/bobbin/repos/gastown`).
/// `repo_name` is the tag stored in the vector DB (e.g., `"gastown"`).
async fn run_incremental_index(
    repo_root: PathBuf,
    config: crate::config::Config,
    source_dir: &std::path::Path,
    repo_name: &str,
) -> anyhow::Result<()> {
    use crate::index::{Embedder, Parser};
    use ignore::WalkBuilder;
    use sha2::{Digest, Sha256};
    use std::path::Path;
    let lance_path = Config::lance_path(&repo_root);
    let mut vector_store = VectorStore::open(&lance_path).await?;

    let model_dir = Config::model_cache_dir()?;
    let embedder = Embedder::load(&model_dir, &config.embedding.model)?;
    let mut parser = Parser::new()?.with_chunking(
        config.index.chunk_size,
        config.index.chunk_overlap,
        embedder.max_seq().unwrap_or(0),
    );

    // Collect files
    let mut walker = WalkBuilder::new(source_dir);
    walker.hidden(true).git_ignore(config.index.use_gitignore);

    let include_globs: Vec<glob::Pattern> = config
        .index
        .include
        .iter()
        .filter_map(|p| glob::Pattern::new(p).ok())
        .collect();
    let exclude_globs: Vec<glob::Pattern> = config
        .index
        .exclude
        .iter()
        .filter_map(|p| glob::Pattern::new(p).ok())
        .collect();

    let mut files_to_index = Vec::new();
    for entry in walker.build().flatten() {
        if !entry.file_type().is_some_and(|ft| ft.is_file()) {
            continue;
        }
        let path = entry.path();
        let rel_path = path
            .strip_prefix(source_dir)
            .unwrap_or(path)
            .to_string_lossy()
            .to_string();

        let matches_include =
            include_globs.is_empty() || include_globs.iter().any(|g| g.matches(&rel_path));
        let matches_exclude = exclude_globs.iter().any(|g| g.matches(&rel_path));

        if matches_include && !matches_exclude {
            let content = match std::fs::read_to_string(path) {
                Ok(c) => c,
                Err(_) => continue,
            };
            let hash = format!("{:x}", Sha256::digest(content.as_bytes()));
            let needs = vector_store
                .needs_reindex(&rel_path, &hash, Some(repo_name))
                .await
                .unwrap_or(true);
            if needs {
                files_to_index.push((rel_path, content, hash));
            }
        }
    }

    tracing::info!(
        "Webhook index: {} files need re-indexing",
        files_to_index.len()
    );

    for (rel_path, content, hash) in &files_to_index {
        let chunks = match parser.parse_file(Path::new(rel_path), content) {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!("Failed to parse {}: {}", rel_path, e);
                continue;
            }
        };
        if chunks.is_empty() {
            continue;
        }

        vector_store
            .delete_by_file(&[rel_path.clone()], Some(repo_name))
            .await?;

        let texts: Vec<&str> = chunks.iter().map(|c| c.content.as_str()).collect();
        let embeddings = embedder.embed_batch(&texts).await?;
        let contexts: Vec<Option<String>> = vec![None; chunks.len()];
        let now = chrono::Utc::now().to_rfc3339();

        vector_store
            .insert(&chunks, &embeddings, &contexts, repo_name, hash, &now)
            .await?;
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[path = "webhook_tests.rs"]
mod tests;