coralogix-cli 0.1.30

Coralogix CLI - the observability backbone for AI agents and engineering teams.
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
//! Search and fetch official Coralogix product documentation (public llms.txt index).

use std::sync::LazyLock;
use std::time::{Duration, Instant};

use anyhow::{bail, Context, Result};
use serde::Serialize;
use strsim::jaro;
use tokio::sync::Mutex;
use url::Url;

use crate::config::OutputFormat;
use crate::render;

pub const DOCS_LLMS_INDEX_URL: &str = "https://coralogix.com/docs/llms.txt";
const DOCS_HOST: &str = "coralogix.com";
const DOCS_BASE_URL: &str = "https://coralogix.com/docs";
/// Docs resources that are not pages and are fetched as-is (no `.md` suffix).
const NON_PAGE_EXTENSIONS: &[&str] = &[".txt", ".json"];
const INDEX_TTL: Duration = Duration::from_secs(3600);
// The docs CDN rejects reqwest's default user agent. Keep the cx identity as
// a product token while using a curl-compatible leading token.
const DOCS_USER_AGENT: &str = concat!("curl/8.0 cx-cli/", env!("CARGO_PKG_VERSION"));
/// Minimum best-hit score (same threshold as ws-ai-mcp `search_docs`).
const MIN_FUZZY_SCORE: f64 = 0.2;

static INDEX_CACHE: LazyLock<Mutex<Option<CachedIndex>>> = LazyLock::new(|| Mutex::new(None));

struct CachedIndex {
    loaded_at: Instant,
    entries: Vec<(String, String, String)>,
}

#[derive(Debug, Serialize)]
struct SearchHit {
    rank: usize,
    title: String,
    suffix: String,
}

#[derive(Debug, Serialize)]
struct FetchDocResult {
    suffix: String,
    body: String,
}

/// Normalize a docs page URL (strip `.md`, trailing `/index`, trailing slash).
pub fn page_url(url: &str) -> String {
    let mut url = url.trim().trim_end_matches('/').to_string();
    if url.ends_with(".md") {
        url.truncate(url.len() - 3);
    }
    if url.ends_with("/index") {
        url.truncate(url.len() - 6);
    }
    if url.is_empty() {
        DOCS_BASE_URL.to_string()
    } else {
        url
    }
}

/// Path under `/docs/`, preserving the suffix supplied by the docs index.
pub fn docs_suffix(url: &str) -> String {
    let path = Url::parse(url.trim())
        .ok()
        .map(|u| u.path().trim_end_matches('/').to_string())
        .unwrap_or_default();
    let prefix = "/docs";
    let path = path.strip_prefix(prefix).unwrap_or(&path);
    path.trim_start_matches('/').to_string()
}

/// Validate and normalize a docs path suffix from `cx docs search`.
///
/// Strips a leading `/` or `docs/`, a trailing `/`, and any `#fragment` or
/// `?query` (agents often paste heading links).
pub fn normalize_suffix(value: &str) -> Result<String> {
    if value.starts_with("http://") || value.starts_with("https://") {
        bail!("expected a path suffix from `cx docs search` (e.g. user-guides/foo)");
    }
    let mut suffix = value.trim();
    if let Some(idx) = suffix.find(['#', '?']) {
        suffix = &suffix[..idx];
    }
    let suffix = suffix.trim_start_matches('/');
    let suffix = suffix.strip_prefix("docs/").unwrap_or(suffix);
    Ok(suffix.trim_end_matches('/').to_string())
}

/// Page URL for a normalized docs suffix; the empty suffix is the docs root.
pub fn page_url_from_suffix(suffix: &str) -> Result<String> {
    let suffix = normalize_suffix(suffix)?;
    if suffix.is_empty() {
        Ok(DOCS_BASE_URL.to_string())
    } else {
        Ok(format!("{DOCS_BASE_URL}/{suffix}"))
    }
}

/// Markdown URL for a docs resource. The portal serves pages as `<page>.md`
/// (`index.md` for the docs root); a plain page path returns HTML, and
/// `<page>/index.md` is not served. Non-page files such as `llms-full.txt`
/// and `docs-index.json` are fetched as-is.
pub fn md_url(url: &str) -> String {
    let url = url.trim().trim_end_matches('/');
    if NON_PAGE_EXTENSIONS.iter().any(|ext| url.ends_with(ext)) {
        return url.to_string();
    }
    let page = page_url(url);
    if page == DOCS_BASE_URL {
        format!("{page}/index.md")
    } else {
        format!("{page}.md")
    }
}

fn is_coralogix_docs_url(url: &str) -> bool {
    Url::parse(url)
        .ok()
        .and_then(|u| u.host_str().map(|h| h.contains(DOCS_HOST)))
        .unwrap_or(false)
}

/// Parse docs index links, keeping the legacy text used for fuzzy ranking.
pub fn parse_index(text: &str) -> Result<Vec<(String, String, String)>> {
    let mut entries = Vec::new();
    for line in text.lines() {
        let Some((title, raw_url, ranking_url)) = parse_link_line(line) else {
            continue;
        };
        if is_coralogix_docs_url(&raw_url) {
            entries.push((title, docs_suffix(&raw_url), docs_suffix(&ranking_url)));
        }
    }
    if entries.is_empty() {
        bail!("docs index is empty");
    }
    Ok(entries)
}

fn parse_link_line(line: &str) -> Option<(String, String, String)> {
    let line = line.trim();
    let rest = line.strip_prefix("- [")?;
    let (title, rest) = rest.split_once("](")?;
    let (url, _) = rest.split_once(')')?;
    if !url.starts_with("http://") && !url.starts_with("https://") {
        return None;
    }
    Some((
        title.to_string(),
        url.to_string(),
        rest.strip_suffix(')').unwrap_or(rest).to_string(),
    ))
}

/// Fuzzy score for a query against title and path suffix (same approach as ws-ai-mcp).
pub fn fuzzy_score(query: &str, title: &str, suffix: &str) -> f64 {
    let q = query.to_lowercase();
    if q.trim().is_empty() {
        return 0.0;
    }
    let t = title.to_lowercase();
    let s = suffix.to_lowercase();
    (jaro(&q, &t) + jaro(&q, &s)) / 2.0
}

async fn fetch_text(url: &str) -> Result<String> {
    let client = reqwest::Client::builder()
        .user_agent(DOCS_USER_AGENT)
        .build()
        .context("failed to build documentation HTTP client")?;
    let response = client
        .get(url)
        .send()
        .await
        .with_context(|| format!("failed to request {url}"))?;
    let status = response.status();
    if !status.is_success() {
        bail!("HTTP {status} for {url}");
    }
    response
        .text()
        .await
        .with_context(|| format!("failed to read body from {url}"))
}

async fn load_index() -> Result<Vec<(String, String, String)>> {
    {
        let guard = INDEX_CACHE.lock().await;
        if let Some(cache) = guard.as_ref() {
            if cache.loaded_at.elapsed() < INDEX_TTL {
                return Ok(cache.entries.clone());
            }
        }
    }

    let text = fetch_text(DOCS_LLMS_INDEX_URL).await?;
    let entries = parse_index(&text)?;

    let mut guard = INDEX_CACHE.lock().await;
    *guard = Some(CachedIndex {
        loaded_at: Instant::now(),
        entries: entries.clone(),
    });
    Ok(entries)
}

pub async fn run_search(query: &str, limit: u32, output: OutputFormat) -> Result<()> {
    let query = query.trim();
    if query.is_empty() {
        bail!("query is required");
    }
    let limit = limit.clamp(1, 20) as usize;

    let index = load_index().await?;
    let mut ranked: Vec<(String, String, f64)> = index
        .into_iter()
        .map(|(title, suffix, ranking_suffix)| {
            let score = fuzzy_score(query, &title, &ranking_suffix);
            (title, suffix, score)
        })
        .collect();
    ranked.sort_by(|a, b| {
        b.2.partial_cmp(&a.2)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase()))
    });

    if ranked.is_empty() || ranked[0].2 < MIN_FUZZY_SCORE {
        bail!("no docs matched {query:?}");
    }

    let hits: Vec<(String, String)> = ranked
        .into_iter()
        .take(limit)
        .map(|(title, suffix, _)| (title, suffix))
        .collect();

    let rows: Vec<SearchHit> = hits
        .iter()
        .enumerate()
        .map(|(i, (title, suffix))| SearchHit {
            rank: i + 1,
            title: title.clone(),
            suffix: suffix.clone(),
        })
        .collect();

    match output {
        OutputFormat::Text => {
            for hit in &rows {
                println!("{}. {} — {}", hit.rank, hit.title, hit.suffix);
            }
        }
        OutputFormat::Json => {
            let json_rows: Vec<serde_json::Value> = rows
                .iter()
                .map(|r| serde_json::to_value(r).unwrap_or_default())
                .collect();
            render::render_json(&json_rows)?;
        }
        OutputFormat::Toon => {
            let values: Vec<serde_json::Value> = rows
                .iter()
                .map(|r| serde_json::to_value(r).unwrap_or_default())
                .collect();
            render::render_toon(&values)?;
        }
    }

    Ok(())
}

pub async fn run_fetch(suffix: &str, output: OutputFormat) -> Result<()> {
    let md = md_url(&page_url_from_suffix(suffix)?);
    let body = fetch_text(&md).await?;
    let result = FetchDocResult {
        suffix: docs_suffix(&md),
        body: body.trim().to_string(),
    };

    match output {
        OutputFormat::Text => {
            println!("Path: {}\n", result.suffix);
            println!("{}", result.body);
        }
        OutputFormat::Json => {
            render::render_json_auto(&[serde_json::to_value(&result)?])?;
        }
        OutputFormat::Toon => {
            render::render_toon(&[serde_json::to_value(&result)?])?;
        }
    }

    Ok(())
}

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

    const SAMPLE_INDEX: &str = r#"
# Docs
- [Explore spans](https://coralogix.com/docs/user-guides/data_exploration/spans/)
- [API keys](https://coralogix.com/docs/user-guides/account-management/api-keys/)
- [Other host](https://example.com/docs/page/)
"#;
    const INDEX_WITH_DESCRIPTION: &str = r#"
- [Search](https://coralogix.com/docs/search.md): Find product docs.
"#;

    #[test]
    fn parse_index_extracts_coralogix_suffixes() {
        let entries = parse_index(SAMPLE_INDEX).unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].1, "user-guides/data_exploration/spans");
        assert_eq!(entries[0].2, "user-guides/data_exploration/spans");
        assert!(entries[0].1.contains("user-guides"));
    }

    #[test]
    fn parse_index_keeps_legacy_ranking_text() {
        let entries = parse_index(INDEX_WITH_DESCRIPTION).unwrap();
        assert_eq!(entries[0].1, "search.md");
        assert!(entries[0].2.contains("Find%20product%20docs"));
    }

    #[test]
    fn docs_suffix_strips_docs_prefix() {
        assert_eq!(
            docs_suffix("https://coralogix.com/docs/foo/bar/"),
            "foo/bar"
        );
    }

    #[test]
    fn normalize_suffix_strips_leading_slash_and_docs_prefix() {
        assert_eq!(
            normalize_suffix("/docs/user-guides/foo").unwrap(),
            "user-guides/foo"
        );
    }

    #[test]
    fn normalize_suffix_rejects_url() {
        assert!(normalize_suffix("https://coralogix.com/docs/foo").is_err());
    }

    #[test]
    fn normalize_suffix_strips_fragment_query_and_trailing_slash() {
        assert_eq!(
            normalize_suffix("user-guides/alerting/introduction-to-alerts#overview").unwrap(),
            "user-guides/alerting/introduction-to-alerts"
        );
        assert_eq!(
            normalize_suffix("user-guides/foo/?x=1").unwrap(),
            "user-guides/foo"
        );
        assert_eq!(
            normalize_suffix("user-guides/foo/").unwrap(),
            "user-guides/foo"
        );
        assert_eq!(normalize_suffix("/").unwrap(), "");
    }

    #[test]
    fn page_url_from_suffix_maps_empty_to_docs_root() {
        assert_eq!(page_url_from_suffix("").unwrap(), DOCS_BASE_URL);
        assert_eq!(page_url_from_suffix("/").unwrap(), DOCS_BASE_URL);
        assert_eq!(
            page_url_from_suffix("docs/user-guides/foo/").unwrap(),
            "https://coralogix.com/docs/user-guides/foo"
        );
    }

    #[test]
    fn page_url_strips_md_and_index() {
        assert_eq!(
            page_url("https://coralogix.com/docs/foo/index.md"),
            "https://coralogix.com/docs/foo"
        );
    }

    #[test]
    fn md_url_appends_md_to_plain_page_path() {
        // Example from `cx docs fetch --help`.
        let page = page_url_from_suffix("user-guides/data_exploration/spans/").unwrap();
        assert_eq!(
            md_url(&page),
            "https://coralogix.com/docs/user-guides/data_exploration/spans.md"
        );
        assert_eq!(
            md_url("https://coralogix.com/docs/user-guides/alerting/introduction-to-alerts"),
            "https://coralogix.com/docs/user-guides/alerting/introduction-to-alerts.md"
        );
    }

    #[test]
    fn md_url_keeps_suffixes_from_search() {
        // `cx docs search` returns suffixes that already end in `.md`.
        let page = page_url_from_suffix("user-guides/aaa/access-control/permissions.md").unwrap();
        assert_eq!(
            md_url(&page),
            "https://coralogix.com/docs/user-guides/aaa/access-control/permissions.md"
        );
    }

    #[test]
    fn md_url_maps_docs_root_to_index() {
        assert_eq!(
            md_url(&page_url_from_suffix("").unwrap()),
            "https://coralogix.com/docs/index.md"
        );
        // `cx docs search` lists the root as `index.md`.
        assert_eq!(
            md_url(&page_url_from_suffix("index.md").unwrap()),
            "https://coralogix.com/docs/index.md"
        );
    }

    #[test]
    fn md_url_strips_page_index() {
        // The portal serves `<page>.md`, not `<page>/index.md`.
        for suffix in ["user-guides/foo/index", "user-guides/foo/index.md"] {
            assert_eq!(
                md_url(&page_url_from_suffix(suffix).unwrap()),
                "https://coralogix.com/docs/user-guides/foo.md"
            );
        }
    }

    #[test]
    fn md_url_strips_fragment_from_pasted_heading_link() {
        assert_eq!(
            md_url(
                &page_url_from_suffix("user-guides/alerting/introduction-to-alerts#overview")
                    .unwrap()
            ),
            "https://coralogix.com/docs/user-guides/alerting/introduction-to-alerts.md"
        );
    }

    #[test]
    fn md_url_keeps_non_page_resources() {
        for file in [
            "llms-full.txt",
            "docs-index.json",
            "search/search_index.json",
        ] {
            assert_eq!(
                md_url(&page_url_from_suffix(file).unwrap()),
                format!("https://coralogix.com/docs/{file}")
            );
        }
    }

    #[test]
    fn md_url_keeps_dotted_page_names() {
        // Page names can contain dots; only known non-page extensions pass through.
        assert_eq!(
            md_url("https://coralogix.com/docs/user-guides/https/support-for-incident.io"),
            "https://coralogix.com/docs/user-guides/https/support-for-incident.io.md"
        );
    }

    #[test]
    fn fuzzy_score_high_for_close_match() {
        let s = fuzzy_score(
            "explore spans",
            "Explore spans",
            "user-guides/data_exploration/spans",
        );
        assert!(s >= MIN_FUZZY_SCORE);
    }

    #[test]
    fn fuzzy_score_low_for_unrelated() {
        let s = fuzzy_score(
            "zzzznotfound",
            "API keys",
            "user-guides/account-management/api-keys",
        );
        assert!(s < MIN_FUZZY_SCORE);
    }
}