bkmr 7.6.7

Knowledge management for humans and agents — bookmarks, snippets, etc, searchable, executable.
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
use crate::domain::error::{DomainError, DomainResult};
use std::sync::Arc;
use tower_lsp_server::ls_types::{
    CompletionItem, CompletionItemKind, CompletionTextEdit, Documentation, InsertTextFormat,
    TextEdit,
};
use tracing::{debug, instrument};

use crate::lsp::backend::BkmrConfig;
use crate::lsp::domain::{CompletionContext, Snippet, SnippetFilter};
use crate::lsp::services::{AsyncSnippetService, LanguageTranslator};

/// Service for handling completion logic
pub struct CompletionService {
    snippet_service: Arc<dyn AsyncSnippetService>,
    config: BkmrConfig,
}

impl std::fmt::Debug for CompletionService {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CompletionService")
            .field("snippet_service", &"<AsyncSnippetService>")
            .field("config", &self.config)
            .finish()
    }
}

impl CompletionService {
    pub fn new(snippet_service: Arc<dyn AsyncSnippetService>) -> Self {
        Self::with_config(snippet_service, BkmrConfig::default())
    }

    pub fn with_config(snippet_service: Arc<dyn AsyncSnippetService>, config: BkmrConfig) -> Self {
        Self {
            snippet_service,
            config,
        }
    }

    /// Generate completion items from context
    #[instrument(skip(self))]
    pub async fn get_completions(
        &self,
        context: &CompletionContext,
    ) -> DomainResult<Vec<CompletionItem>> {
        let filter = self.build_snippet_filter(context);

        let snippets = self.snippet_service.fetch_snippets(&filter).await?;

        let completion_items: Result<Vec<CompletionItem>, _> = snippets
            .iter()
            .map(|snippet| {
                self.snippet_to_completion_item(
                    snippet,
                    context.get_query_text().unwrap_or(""),
                    context.get_replacement_range(),
                    context.language_id.as_deref().unwrap_or("unknown"),
                    &context.uri,
                )
            })
            .collect();

        let completion_items = completion_items.map_err(|e| {
            DomainError::Other(format!(
                "Failed to convert snippets to completion items: {}",
                e
            ))
        })?;

        debug!("Generated {} completion items", completion_items.len());
        Ok(completion_items)
    }

    /// Build snippet filter from completion context
    fn build_snippet_filter(&self, context: &CompletionContext) -> SnippetFilter {
        let query_prefix = context.get_query_text().map(|s| s.to_string());
        SnippetFilter::new(
            context.language_id.clone(),
            query_prefix,
            self.config.max_completions,
            self.config.enable_interpolation,
        )
    }

    /// Convert snippet to LSP completion item with proper text replacement
    pub fn snippet_to_completion_item(
        &self,
        snippet: &Snippet,
        query: &str,
        replacement_range: Option<tower_lsp_server::ls_types::Range>,
        language_id: &str,
        uri: &tower_lsp_server::ls_types::Uri,
    ) -> DomainResult<CompletionItem> {
        // Snippet content is already processed (interpolated) by LspSnippetService
        // We only need to apply language translation
        let snippet_content = LanguageTranslator::translate_snippet(snippet, language_id, uri)?;

        let label = snippet.title.clone();

        debug!(
            "Creating completion item: query='{}', label='{}', content_preview='{}'",
            query,
            label,
            snippet_content.chars().take(20).collect::<String>()
        );

        // Determine if this should be treated as plain text
        let (item_kind, text_format, detail_text) = if snippet.is_plain() {
            (
                CompletionItemKind::TEXT,
                InsertTextFormat::PLAIN_TEXT,
                "bkmr plain text",
            )
        } else {
            (
                CompletionItemKind::SNIPPET,
                InsertTextFormat::SNIPPET,
                "bkmr snippet",
            )
        };

        let mut completion_item = CompletionItem {
            label: label.clone(),
            kind: Some(item_kind),
            detail: Some(detail_text.to_string()),
            documentation: Some(Documentation::String(truncate_preview(
                &snippet_content,
                500,
            ))),
            insert_text_format: Some(text_format),
            filter_text: Some(label.clone()),
            sort_text: Some(label.clone()),
            ..Default::default()
        };

        // Use TextEdit for proper replacement if we have a range
        if let Some(range) = replacement_range {
            completion_item.text_edit = Some(CompletionTextEdit::Edit(TextEdit {
                range,
                new_text: snippet_content,
            }));
            debug!("Set text_edit for range replacement: {:?}", range);
        } else {
            // Fallback to insert_text for backward compatibility
            completion_item.insert_text = Some(snippet_content);
            debug!("Using fallback insert_text (no range available)");
        }

        Ok(completion_item)
    }

    /// Health check for the completion service
    pub async fn health_check(&self) -> DomainResult<()> {
        self.snippet_service
            .health_check()
            .await
            .map_err(|e| DomainError::Other(e.to_string()))
    }
}

/// Truncate content to at most `max_chars` characters for the documentation
/// preview, respecting char boundaries (byte-slicing panics on multibyte UTF-8).
fn truncate_preview(content: &str, max_chars: usize) -> String {
    match content.char_indices().nth(max_chars) {
        Some((byte_idx, _)) => format!("{}...", &content[..byte_idx]),
        None => content.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::testing::{init_test_env, EnvGuard};
    use tower_lsp_server::ls_types::{Position, Range, Uri};

    // Tests run single-threaded (--test-threads=1) against a shared SQLite file.
    // Always construct services via TestServiceContainer, never production factories.

    #[tokio::test]
    async fn given_context_with_query_when_getting_completions_then_returns_filtered_items() {
        // Arrange
        let _env = init_test_env();
        let _guard = EnvGuard::new();
        let ctx = crate::util::test_context::TestContext::new();
        let lsp_bundle = ctx.create_lsp_services();
        let service = lsp_bundle.completion_service;

        let uri = "file:///test.rs".parse::<Uri>().expect("parse URI");
        let context = CompletionContext::new(
            uri,
            Position {
                line: 0,
                character: 5,
            },
            Some("rust".to_string()),
        );

        // Act
        let result = service.get_completions(&context).await;

        // Assert
        assert!(result.is_ok());
        let items = result.expect("valid completion items");
        // Note: Actual number depends on database content
        debug!("Got {} completion items", items.len());
    }

    #[tokio::test]
    async fn given_query_prefix_with_hyphen_when_getting_completions_then_does_not_error() {
        // Regression: a word ending in a hyphen produced the FTS term `metadata:foo-*`,
        // which SQLite FTS5 rejects with `syntax error near "*"`, failing the whole
        // combined query and returning zero completions.
        let _env = init_test_env();
        let _guard = EnvGuard::new();
        let ctx = crate::util::test_context::TestContext::new();
        let service = ctx.create_lsp_services().completion_service;

        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 4,
            },
        };
        let context = CompletionContext::new(
            "file:///test.mk".parse::<Uri>().expect("parse URI"),
            Position {
                line: 0,
                character: 4,
            },
            Some("make".to_string()),
        )
        .with_query(crate::lsp::domain::CompletionQuery::new(
            "foo-".to_string(),
            range,
        ));

        let result = service.get_completions(&context).await;

        assert!(
            result.is_ok(),
            "hyphenated prefix must not crash FTS: {:?}",
            result.err()
        );
    }

    #[tokio::test]
    async fn given_plain_snippet_when_creating_completion_item_then_uses_plain_text_format() {
        // Arrange
        let _env = init_test_env();
        let _guard = EnvGuard::new();
        let plain_snippet = Snippet::new(
            1,
            "Plain Text".to_string(),
            "simple text content with no ${1:placeholders}".to_string(),
            "Plain text snippet".to_string(),
            vec!["plain".to_string(), "_snip_".to_string()],
        );

        let ctx = crate::util::test_context::TestContext::new();
        let lsp_bundle = ctx.create_lsp_services();
        let service = lsp_bundle.completion_service;

        let uri = "file:///test.rs".parse::<Uri>().expect("parse URI");

        // Act
        let result = service.snippet_to_completion_item(&plain_snippet, "", None, "rust", &uri);

        // Assert
        assert!(result.is_ok());
        let item = result.expect("valid completion item");

        assert_eq!(item.kind, Some(CompletionItemKind::TEXT));
        assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
        assert_eq!(item.detail, Some("bkmr plain text".to_string()));
        assert_eq!(item.label, "Plain Text");
    }

    #[tokio::test]
    async fn given_regular_snippet_when_creating_completion_item_then_uses_snippet_format() {
        // Arrange
        let _env = init_test_env();
        let _guard = EnvGuard::new();
        let regular_snippet = Snippet::new(
            1,
            "Regular Snippet".to_string(),
            "snippet with ${1:placeholder}".to_string(),
            "Regular snippet".to_string(),
            vec!["rust".to_string(), "_snip_".to_string()],
        );

        let ctx = crate::util::test_context::TestContext::new();
        let lsp_bundle = ctx.create_lsp_services();
        let service = lsp_bundle.completion_service;

        let uri = "file:///test.rs".parse::<Uri>().expect("parse URI");

        // Act
        let result = service.snippet_to_completion_item(&regular_snippet, "", None, "rust", &uri);

        // Assert
        assert!(result.is_ok());
        let item = result.expect("valid completion item");

        assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET));
        assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
        assert_eq!(item.detail, Some("bkmr snippet".to_string()));
        assert_eq!(item.label, "Regular Snippet");
    }

    #[tokio::test]
    async fn given_universal_snippet_when_creating_completion_item_then_translates_content() {
        // Arrange
        let _env = init_test_env();
        let _guard = EnvGuard::new();
        let universal_snippet = Snippet::new(
            1,
            "Universal Comment".to_string(),
            "// This is a universal comment".to_string(),
            "Universal snippet".to_string(),
            vec!["universal".to_string(), "_snip_".to_string()],
        );

        let ctx = crate::util::test_context::TestContext::new();
        let lsp_bundle = ctx.create_lsp_services();
        let service = lsp_bundle.completion_service;

        let uri = "file:///test.py".parse::<Uri>().expect("parse URI");

        // Act
        let result =
            service.snippet_to_completion_item(&universal_snippet, "", None, "python", &uri);

        // Assert
        assert!(result.is_ok());
        let item = result.expect("valid completion item");

        // Should have translated Rust comment to Python comment
        let insert_text = item.insert_text.expect("insert text");
        assert!(insert_text.contains("# This is a universal comment"));
    }

    #[tokio::test]
    async fn given_completion_item_with_range_when_creating_then_uses_text_edit() {
        // Arrange
        let _env = init_test_env();
        let _guard = EnvGuard::new();
        let snippet = Snippet::new(
            1,
            "Test Snippet".to_string(),
            "test content".to_string(),
            "Test description".to_string(),
            vec!["rust".to_string(), "_snip_".to_string()],
        );

        let ctx = crate::util::test_context::TestContext::new();
        let lsp_bundle = ctx.create_lsp_services();
        let service = lsp_bundle.completion_service;

        let uri = "file:///test.rs".parse::<Uri>().expect("parse URI");
        let range = Range {
            start: Position {
                line: 0,
                character: 0,
            },
            end: Position {
                line: 0,
                character: 4,
            },
        };

        // Act
        let result =
            service.snippet_to_completion_item(&snippet, "test", Some(range), "rust", &uri);

        // Assert
        assert!(result.is_ok());
        let item = result.expect("valid completion item");

        match item.text_edit {
            Some(CompletionTextEdit::Edit(edit)) => {
                assert_eq!(edit.range, range);
                assert_eq!(edit.new_text, "test content");
            }
            _ => panic!("Expected text edit"),
        }
    }

    #[tokio::test]
    async fn given_multibyte_content_longer_than_preview_when_creating_item_then_does_not_panic() {
        // Documentation preview truncation must respect char boundaries:
        // 200 x '€' (3 bytes each) = 600 bytes, and byte 500 falls mid-char.
        let _env = init_test_env();
        let _guard = EnvGuard::new();
        let snippet = Snippet::new(
            1,
            "Multibyte".to_string(),
            "".repeat(200),
            "desc".to_string(),
            vec!["rust".to_string(), "_snip_".to_string()],
        );

        let ctx = crate::util::test_context::TestContext::new();
        let service = ctx.create_lsp_services().completion_service;
        let uri = "file:///test.rs".parse::<Uri>().expect("parse URI");

        let result = service.snippet_to_completion_item(&snippet, "", None, "rust", &uri);

        assert!(result.is_ok(), "must not panic or fail: {:?}", result.err());
    }

    #[tokio::test]
    async fn given_healthy_service_when_health_check_then_returns_ok() {
        // Arrange
        let _env = init_test_env();
        let _guard = EnvGuard::new();
        let ctx = crate::util::test_context::TestContext::new();
        let lsp_bundle = ctx.create_lsp_services();
        let service = lsp_bundle.completion_service;

        // Act
        let result = service.health_check().await;

        // Assert
        assert!(result.is_ok());
    }
}