crosslink 0.8.0

A synced issue tracker CLI for multi-agent AI 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
//! Handler for the unified search endpoint.
//!
//! Implements:
//! - `GET /api/v1/search?q=<query>` — full-text search across issues, comments, and knowledge pages

use axum::{
    extract::{Query, State},
    http::StatusCode,
    response::Json,
};
use serde::Serialize;
use serde_json::Value;

use crate::{
    knowledge::KnowledgeManager,
    server::{
        errors::{bad_request, internal_error},
        state::AppState,
        types::{ApiError, KnowledgeSearchQuery},
    },
};

// ---------------------------------------------------------------------------
// Response types
// ---------------------------------------------------------------------------

/// A single result in the unified search response.
#[derive(Debug, Clone, Serialize)]
pub struct SearchResultItem {
    /// The kind of result: "issue", "comment", or "knowledge".
    pub kind: String,
    /// Display title (issue title, comment excerpt, or page title).
    pub title: String,
    /// Brief snippet of matching content.
    pub snippet: String,
    /// Unique identifier — issue ID, comment ID, or knowledge slug.
    pub id: String,
    /// For comments: the parent issue ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub issue_id: Option<i64>,
}

// ---------------------------------------------------------------------------
// GET /api/v1/search
// ---------------------------------------------------------------------------

/// `GET /api/v1/search?q=<query>` — unified full-text search.
///
/// Searches across issues (title + description), comments (content), and
/// knowledge pages (full-text). Returns a combined, ordered list of results.
///
/// # Errors
///
/// Returns an error if the search query is empty or a database/knowledge
/// search operation fails.
pub async fn global_search(
    State(state): State<AppState>,
    Query(params): Query<KnowledgeSearchQuery>,
) -> Result<Json<Value>, (StatusCode, Json<ApiError>)> {
    let query = params.q.trim().to_string();
    if query.is_empty() {
        return Err(bad_request("Search query 'q' cannot be empty"));
    }

    let mut results: Vec<SearchResultItem> = Vec::new();

    // --- Search issues ---
    {
        let db = state.db().await;

        let issues = db
            .search_issues(&query)
            .map_err(|e| internal_error("Issue search failed", e))?;

        // --- Search comments (single query instead of N+1) ---
        let matching_comments = db
            .search_comments(&query)
            .map_err(|e| internal_error("Failed to search comments", e))?;

        drop(db);

        for issue in issues {
            let snippet = issue
                .description
                .as_deref()
                .unwrap_or("")
                .chars()
                .take(200)
                .collect::<String>();

            results.push(SearchResultItem {
                kind: "issue".to_string(),
                title: issue.title.clone(),
                snippet,
                id: issue.id.to_string(),
                issue_id: None,
            });
        }

        for (comment, issue_id, issue_title) in matching_comments {
            let snippet = comment.content.chars().take(200).collect::<String>();
            results.push(SearchResultItem {
                kind: "comment".to_string(),
                title: format!("Comment on #{issue_id}: {issue_title}"),
                snippet,
                id: comment.id.to_string(),
                issue_id: Some(issue_id),
            });
        }
    }

    // --- Search knowledge pages ---
    {
        let km = KnowledgeManager::new(&state.crosslink_dir)
            .map_err(|e| internal_error("Failed to initialize knowledge manager", e))?;

        if km.is_initialized() {
            let matches = km
                .search_content(&query, 1)
                .map_err(|e| internal_error("Knowledge search failed", e))?;

            // Build a title lookup from page metadata.
            let pages = km.list_pages().unwrap_or_default();
            let title_map: std::collections::HashMap<String, String> = pages
                .into_iter()
                .map(|p| (p.slug.clone(), p.frontmatter.title))
                .collect();

            // Deduplicate by slug — only show one result per knowledge page.
            let mut seen_slugs = std::collections::HashSet::new();
            for m in matches {
                if !seen_slugs.insert(m.slug.clone()) {
                    continue;
                }

                let title = title_map
                    .get(&m.slug)
                    .cloned()
                    .unwrap_or_else(|| m.slug.clone());

                let snippet = m
                    .context_lines
                    .iter()
                    .map(|(_, line): &(usize, String)| line.as_str())
                    .collect::<Vec<_>>()
                    .join(" ")
                    .chars()
                    .take(200)
                    .collect::<String>();

                results.push(SearchResultItem {
                    kind: "knowledge".to_string(),
                    title,
                    snippet,
                    id: m.slug,
                    issue_id: None,
                });
            }
        }
    }

    let total = results.len();
    Ok(Json(
        serde_json::json!({ "items": results, "total": total }),
    ))
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{body::Body, http::Request, routing::get, Router};
    use serde_json::Value;
    use tower::ServiceExt;

    fn test_state(tmp_dir: &std::path::Path) -> AppState {
        let db_path = tmp_dir.join("test.db");
        let db = crate::db::Database::open(&db_path).unwrap();
        let crosslink_dir = tmp_dir.join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();
        AppState::new(db, crosslink_dir)
    }

    fn build_router(state: AppState) -> Router {
        Router::new()
            .route("/search", get(global_search))
            .with_state(state)
    }

    #[tokio::test]
    async fn test_search_empty_query_returns_400() {
        let tmp = tempfile::tempdir().unwrap();
        let state = test_state(tmp.path());
        let app = build_router(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/search?q=")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_search_no_results() {
        let tmp = tempfile::tempdir().unwrap();
        let state = test_state(tmp.path());
        let app = build_router(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/search?q=nonexistent")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let body: Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(body["total"], 0);
    }

    #[tokio::test]
    async fn test_search_finds_issues() {
        let tmp = tempfile::tempdir().unwrap();
        let state = test_state(tmp.path());

        // Create an issue to search for.
        {
            let db = state.db.lock().await;
            db.create_issue("Fix authentication bug", None, "high")
                .unwrap();
        }

        let app = build_router(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/search?q=authentication")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let body: Value = serde_json::from_slice(&bytes).unwrap();
        assert!(body["total"].as_u64().unwrap() >= 1);
        assert_eq!(body["items"][0]["kind"], "issue");
        assert!(body["items"][0]["title"]
            .as_str()
            .unwrap()
            .contains("authentication"));
    }

    #[tokio::test]
    async fn test_search_finds_comments() {
        let tmp = tempfile::tempdir().unwrap();
        let state = test_state(tmp.path());

        // Create an issue and a comment.
        {
            let db = state.db.lock().await;
            db.create_issue("Some issue", None, "medium").unwrap();
            db.add_comment(1, "The frobulator is broken and needs replacement", "note")
                .unwrap();
        }

        let app = build_router(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/search?q=frobulator")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let body: Value = serde_json::from_slice(&bytes).unwrap();
        let items = body["items"].as_array().unwrap();
        let comment_results: Vec<_> = items.iter().filter(|i| i["kind"] == "comment").collect();
        assert!(!comment_results.is_empty());
        assert!(comment_results[0]["snippet"]
            .as_str()
            .unwrap()
            .contains("frobulator"));
        assert_eq!(comment_results[0]["issue_id"], 1);
    }

    #[tokio::test]
    async fn test_search_finds_knowledge_pages() {
        let tmp = tempfile::tempdir().unwrap();
        let cache_dir = tmp.path().join(".crosslink").join(".knowledge-cache");
        std::fs::create_dir_all(&cache_dir).unwrap();

        // Write a knowledge page.
        let page = "---\ntitle: \"Enzyme Kinetics\"\ntags: [biology]\nsources: []\ncontributors: []\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nMichaelis-Menten kinetics describes enzyme catalysis rates.\n";
        std::fs::write(cache_dir.join("enzyme-kinetics.md"), page).unwrap();

        let state = test_state(tmp.path());
        let app = build_router(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/search?q=Michaelis")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let body: Value = serde_json::from_slice(&bytes).unwrap();
        let items = body["items"].as_array().unwrap();
        let knowledge_results: Vec<_> = items.iter().filter(|i| i["kind"] == "knowledge").collect();
        assert!(!knowledge_results.is_empty());
        assert_eq!(knowledge_results[0]["id"], "enzyme-kinetics");
        assert_eq!(knowledge_results[0]["title"], "Enzyme Kinetics");
    }

    #[tokio::test]
    async fn test_search_whitespace_only_query_returns_400() {
        let tmp = tempfile::tempdir().unwrap();
        let state = test_state(tmp.path());
        let app = build_router(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/search?q=+++")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_search_issue_without_description() {
        let tmp = tempfile::tempdir().unwrap();
        let state = test_state(tmp.path());

        // Create an issue with no description so the snippet is empty.
        {
            let db = state.db.lock().await;
            db.create_issue("Undescribed widget", None, "low").unwrap();
        }

        let app = build_router(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/search?q=widget")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let body: Value = serde_json::from_slice(&bytes).unwrap();
        assert!(body["total"].as_u64().unwrap() >= 1);
        let items = body["items"].as_array().unwrap();
        let issue_result = items.iter().find(|i| i["kind"] == "issue").unwrap();
        // snippet should be empty string when no description.
        assert_eq!(issue_result["snippet"], "");
    }

    #[test]
    fn test_helper_functions_directly() {
        let (status, json) = crate::server::errors::internal_error("ctx", "detail");
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(json.error, "ctx");
        assert_eq!(json.detail.as_deref(), Some("detail"));

        let (status, json) = crate::server::errors::bad_request("bad input");
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(json.error, "bad request");
        assert_eq!(json.detail.as_deref(), Some("bad input"));
    }

    #[tokio::test]
    async fn test_search_knowledge_page_title_fallback() {
        // When a page file exists but has no frontmatter, its slug is used as the title.
        let tmp = tempfile::tempdir().unwrap();
        let cache_dir = tmp.path().join(".crosslink").join(".knowledge-cache");
        std::fs::create_dir_all(&cache_dir).unwrap();

        // Write a page without frontmatter.
        let page = "No frontmatter here. Just a raw doc about widgets.\n";
        std::fs::write(cache_dir.join("raw-widget-doc.md"), page).unwrap();

        let state = test_state(tmp.path());
        let app = build_router(state);

        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/search?q=widgets")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let body: Value = serde_json::from_slice(&bytes).unwrap();
        let items = body["items"].as_array().unwrap();
        let knowledge_results: Vec<_> = items.iter().filter(|i| i["kind"] == "knowledge").collect();
        // The slug is used as title when no frontmatter title is present.
        assert!(!knowledge_results.is_empty());
        assert_eq!(knowledge_results[0]["id"], "raw-widget-doc");
        // title falls back to slug when not in title_map
        assert_eq!(knowledge_results[0]["title"], "raw-widget-doc");
    }
}