tokensave 7.0.0

Code intelligence tool that builds a semantic knowledge graph from Rust, Go, Java, Scala, TypeScript, Python, C, C++, Kotlin, C#, Swift, and many more codebases
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
//! HTTP client for the worldwide token counter Cloudflare Worker and
//! GitHub release version checking.
//!
//! All operations are best-effort with timeouts. Failures are silently
//! ignored and never block the CLI.

use std::time::Duration;

/// The Cloudflare Worker endpoint URL.
const WORKER_URL: &str = "https://tokensave-counter.enzinol.workers.dev";

/// GitHub API endpoint for the latest stable release.
const GITHUB_RELEASES_URL: &str =
    "https://api.github.com/repos/aovestdipaperino/tokensave/releases/latest";

/// GitHub API endpoint for listing releases (used to find latest beta).
const GITHUB_RELEASES_LIST_URL: &str =
    "https://api.github.com/repos/aovestdipaperino/tokensave/releases?per_page=10";

/// Timeout for flush (upload) requests.
const FLUSH_TIMEOUT: Duration = Duration::from_secs(2);

/// Timeout for fetching the worldwide total (used in status).
const FETCH_TIMEOUT: Duration = Duration::from_secs(1);

/// Response from the worker's POST /increment and GET /total endpoints.
#[derive(serde::Deserialize)]
struct WorkerResponse {
    total: u64,
}

/// Creates a ureq agent with the given timeout.
pub fn agent_with_timeout(timeout: Duration) -> ureq::Agent {
    ureq::Agent::config_builder()
        .timeout_global(Some(timeout))
        .build()
        .into()
}

/// Uploads pending tokens to the worldwide counter.
/// Returns the new worldwide total on success, or None on any failure.
pub fn flush_pending(amount: u64) -> Option<u64> {
    if amount == 0 {
        return None;
    }
    let body = serde_json::json!({ "amount": amount });
    let agent = agent_with_timeout(FLUSH_TIMEOUT);
    let parsed: WorkerResponse = agent
        .post(&format!("{WORKER_URL}/increment"))
        .send_json(&body)
        .ok()?
        .body_mut()
        .read_json()
        .ok()?;
    Some(parsed.total)
}

/// Fetches the current worldwide total from the worker.
/// Returns None on timeout, network error, or parse failure.
pub fn fetch_worldwide_total() -> Option<u64> {
    let agent = agent_with_timeout(FETCH_TIMEOUT);
    let parsed: WorkerResponse = agent
        .get(&format!("{WORKER_URL}/total"))
        .call()
        .ok()?
        .body_mut()
        .read_json()
        .ok()?;
    Some(parsed.total)
}

/// Response from the worker's GET /countries endpoint.
#[derive(serde::Deserialize)]
struct CountriesResponse {
    flags: Vec<String>,
}

/// Fetches country flags from the worldwide counter.
/// Returns a list of emoji flags, or an empty vec on failure.
pub fn fetch_country_flags() -> Vec<String> {
    let agent = agent_with_timeout(Duration::from_millis(500));
    let Ok(mut resp) = agent.get(&format!("{WORKER_URL}/countries")).call() else {
        return Vec::new();
    };
    let Ok(parsed): Result<CountriesResponse, _> = resp.body_mut().read_json() else {
        return Vec::new();
    };
    parsed.flags
}

/// Response from GitHub releases API (only the fields we need).
#[derive(serde::Deserialize)]
struct GitHubRelease {
    tag_name: String,
    #[serde(default)]
    prerelease: bool,
    #[serde(default)]
    assets: Vec<GitHubAsset>,
}

#[derive(serde::Deserialize)]
struct GitHubAsset {
    name: String,
}

/// Returns the platform slug matching the CI release matrix. Must stay in
/// sync with the `matrix.name` field in `.github/workflows/release.yml`
/// and `release-beta.yml`.
pub(crate) fn current_platform() -> &'static str {
    if cfg!(target_os = "macos") && cfg!(target_arch = "aarch64") {
        "aarch64-macos"
    } else if cfg!(target_os = "macos") && cfg!(target_arch = "x86_64") {
        "x86_64-macos"
    } else if cfg!(target_os = "linux") && cfg!(target_arch = "x86_64") {
        "x86_64-linux"
    } else if cfg!(target_os = "linux") && cfg!(target_arch = "aarch64") {
        "aarch64-linux"
    } else if cfg!(target_os = "windows") {
        "x86_64-windows"
    } else {
        "unknown"
    }
}

/// Archive naming convention per platform. Must stay in sync with the
/// `tar czf` / `Compress-Archive` invocations in `.github/workflows/release.yml`
/// and `release-beta.yml`:
///
/// - Stable: `tokensave-v{version}-{platform}.{ext}`
/// - Beta:   `tokensave-beta-v{version}-{platform}.{ext}`
pub(crate) fn asset_name(version: &str, is_beta: bool) -> String {
    let prefix = if is_beta {
        "tokensave-beta"
    } else {
        "tokensave"
    };
    let platform = current_platform();
    let ext = if cfg!(windows) { "zip" } else { "tar.gz" };
    format!("{prefix}-v{version}-{platform}.{ext}")
}

/// True when the release lists an asset matching the current platform.
/// Filters out releases whose CI build hasn't finished uploading binaries
/// for the current target — otherwise we'd announce a version the user
/// cannot actually install.
fn release_has_current_platform_asset(release: &GitHubRelease) -> bool {
    let version = release.tag_name.trim_start_matches('v');
    let expected = asset_name(version, release.prerelease);
    release.assets.iter().any(|a| a.name == expected)
}

/// Fetches the latest release version from GitHub.
/// For beta builds, fetches the latest prerelease; for stable builds,
/// fetches the latest stable release. This ensures each channel only
/// sees updates from its own channel. Releases whose CI hasn't yet
/// uploaded the current-platform binary are skipped — see
/// `release_has_current_platform_asset`.
pub fn fetch_latest_version() -> Option<String> {
    if is_beta() {
        fetch_latest_beta_version()
    } else {
        fetch_latest_stable_version()
    }
}

/// Fetches the latest stable release version from GitHub.
pub fn fetch_latest_stable_version() -> Option<String> {
    let agent = agent_with_timeout(FETCH_TIMEOUT);
    let release: GitHubRelease = agent
        .get(GITHUB_RELEASES_URL)
        .header("User-Agent", "tokensave")
        .call()
        .ok()?
        .body_mut()
        .read_json()
        .ok()?;
    if !release_has_current_platform_asset(&release) {
        return None;
    }
    Some(release.tag_name.trim_start_matches('v').to_string())
}

/// Fetches the latest prerelease version from GitHub.
pub fn fetch_latest_beta_version() -> Option<String> {
    let agent = agent_with_timeout(FETCH_TIMEOUT);
    let releases: Vec<GitHubRelease> = agent
        .get(GITHUB_RELEASES_LIST_URL)
        .header("User-Agent", "tokensave")
        .call()
        .ok()?
        .body_mut()
        .read_json()
        .ok()?;
    // First prerelease that has the current platform's asset already
    // uploaded. GitHub returns the list newest-first, so the first match
    // is the latest installable beta. Releases whose CI is still in
    // progress are skipped — they will be picked up on the next check.
    releases
        .into_iter()
        .find(|r| r.prerelease && release_has_current_platform_asset(r))
        .map(|r| r.tag_name.trim_start_matches('v').to_string())
}

/// Returns true if the current build is a beta/prerelease version.
pub fn is_beta() -> bool {
    env!("CARGO_PKG_VERSION").contains('-')
}

/// Parses a version string into `(major, minor, patch, pre-release)`.
///
/// Handles optional pre-release suffixes (e.g. `"2.5.0-beta.1"`) by splitting
/// on the first `-`. Returns `None` when the base version is malformed.
fn parse_version(v: &str) -> Option<(u64, u64, u64, Option<&str>)> {
    let (base, pre) = match v.split_once('-') {
        Some((b, p)) => (b, Some(p)),
        None => (v, None),
    };
    let mut parts = base.split('.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    let patch = parts.next()?.parse().ok()?;
    Some((major, minor, patch, pre))
}

/// Classification of an upgrade between two tokensave versions.
///
/// The variant drives the automatic maintenance tokensave performs on upgrade:
///
/// - [`BumpKind::Patch`] (`x.y.Z`): bug fixes only — no reinstall, no reindex.
/// - [`BumpKind::Minor`] (`x.Y.0`): new MCPs/tools — global agent reinstall, no reindex.
/// - [`BumpKind::Major`] (`X.0.0`): DB/schema changes — global reinstall **and** a
///   per-project forced reindex (`sync -f` equivalent).
/// - [`BumpKind::None`]: equal versions, downgrades, or cross-channel transitions —
///   no action beyond advancing the recorded version marker.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BumpKind {
    /// No actionable change (equal, downgrade, or cross-channel).
    None,
    /// Patch bump (`x.y.Z`): bug fixes only.
    Patch,
    /// Minor bump (`x.Y.0`): new MCPs/tools, warrants a global reinstall.
    Minor,
    /// Major bump (`X.0.0`): DB changes, warrants reinstall + forced reindex.
    Major,
}

/// Classifies the upgrade from `old` to `new` as patch, minor, major, or none.
///
/// Uses the same semver rules and channel handling as [`is_newer_version`]:
/// beta and stable are separate channels and never cross. A `new` version that
/// is not strictly newer than `old` (equal or a downgrade) yields
/// [`BumpKind::None`]. An empty or unparseable `old` version is treated as a
/// [`BumpKind::Major`] bump so pre-versioned projects backfill on first use.
///
/// # Examples
///
/// ```
/// use tokensave::cloud::{bump_kind, BumpKind};
/// assert_eq!(bump_kind("6.4.4", "7.0.0"), BumpKind::Major);
/// assert_eq!(bump_kind("6.4.4", "6.5.0"), BumpKind::Minor);
/// assert_eq!(bump_kind("6.4.4", "6.4.5"), BumpKind::Patch);
/// assert_eq!(bump_kind("6.4.4", "6.4.4"), BumpKind::None);
/// ```
pub fn bump_kind(old: &str, new: &str) -> BumpKind {
    // Empty/unparseable old version: treat as needing a full refresh, but only
    // when `new` itself parses and is on the same (stable-vs-stable) channel.
    let Some((nm, nn, np, npre)) = parse_version(new) else {
        return BumpKind::None;
    };
    let Some((om, on, op, opre)) = parse_version(old) else {
        // Cross-channel "old" can't be reasoned about; only backfill when the
        // running version is on the same channel kind we'd otherwise expect.
        return if npre.is_none() {
            BumpKind::Major
        } else {
            BumpKind::None
        };
    };

    // Beta and stable are separate channels — never cross them.
    if opre.is_some() != npre.is_some() {
        return BumpKind::None;
    }

    if !is_newer_version(old, new) {
        return BumpKind::None;
    }

    if nm != om {
        BumpKind::Major
    } else if nn != on {
        BumpKind::Minor
    } else if np != op {
        BumpKind::Patch
    } else {
        // Same base version, strictly-newer pre-release tag within the same
        // channel: classify by base (patch level), matching the channel rules.
        BumpKind::Patch
    }
}

/// Returns true if `latest` is strictly newer than `current` using semver comparison.
/// Handles pre-release suffixes (e.g. "2.5.0-beta.1") by stripping them for the
/// base version comparison, then comparing pre-release tags lexicographically.
pub fn is_newer_version(current: &str, latest: &str) -> bool {
    let parse = parse_version;

    match (parse(current), parse(latest)) {
        (Some((cm, cn, cp, cpre)), Some((lm, ln, lp, lpre))) => {
            // Beta and stable are separate channels — never suggest cross-channel updates.
            if cpre.is_some() != lpre.is_some() {
                return false;
            }
            let c_base = (cm, cn, cp);
            let l_base = (lm, ln, lp);
            if l_base != c_base {
                return l_base > c_base;
            }
            // Same base version, same channel
            match (cpre, lpre) {
                (Some(a), Some(b)) => b > a,
                _ => false,
            }
        }
        _ => false,
    }
}

/// Returns true if `latest` is a newer version than `current` AND the
/// difference is at least a minor version bump (patch-only bumps return false).
///
/// Used by the CLI version warning to avoid nagging on patch releases.
pub fn is_newer_minor_version(current: &str, latest: &str) -> bool {
    fn parse(v: &str) -> Option<(u64, u64)> {
        let base = v.split_once('-').map_or(v, |(b, _)| b);
        let mut parts = base.split('.');
        let major = parts.next()?.parse().ok()?;
        let minor = parts.next()?.parse().ok()?;
        Some((major, minor))
    }

    is_newer_version(current, latest)
        && match (parse(current), parse(latest)) {
            (Some(c), Some(l)) => l > c,
            _ => true,
        }
}

/// How tokensave was installed, detected from the binary path.
pub enum InstallMethod {
    Cargo,
    Brew,
    Scoop,
    Unknown,
}

/// Detects how tokensave was installed by inspecting the binary path.
pub fn detect_install_method() -> InstallMethod {
    let Ok(exe) = std::env::current_exe() else {
        return InstallMethod::Unknown;
    };
    let path = exe.to_string_lossy();
    if path.contains(".cargo/bin") || path.contains(".cargo\\bin") {
        InstallMethod::Cargo
    } else if path.contains("/homebrew/") || path.contains("/Cellar/") {
        InstallMethod::Brew
    } else if path.contains("\\scoop\\") || path.contains("/scoop/") {
        InstallMethod::Scoop
    } else {
        InstallMethod::Unknown
    }
}

/// Returns the upgrade command string.
///
/// Always suggests `tokensave upgrade` which handles all install methods
/// and channels automatically.
pub fn upgrade_command(_method: &InstallMethod) -> &'static str {
    "tokensave upgrade"
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    fn release(tag: &str, prerelease: bool, asset_names: &[&str]) -> GitHubRelease {
        GitHubRelease {
            tag_name: tag.to_string(),
            prerelease,
            assets: asset_names
                .iter()
                .map(|n| GitHubAsset {
                    name: (*n).to_string(),
                })
                .collect(),
        }
    }

    #[test]
    fn skips_release_with_no_assets() {
        // A release that was just created — CI hasn't started uploading yet.
        let r = release("v9.9.9", false, &[]);
        assert!(!release_has_current_platform_asset(&r));
    }

    #[test]
    fn skips_release_missing_current_platform_asset() {
        // Other platforms uploaded but ours hasn't yet (e.g. the macOS leg
        // of the matrix is still running). Detection should treat this as
        // "no upgrade for me" so the user isn't told about a version they
        // cannot install.
        let r = release(
            "v9.9.9",
            false,
            &[
                "tokensave-v9.9.9-some-other-platform.tar.gz",
                "tokensave-v9.9.9-yet-another-platform.tar.gz",
            ],
        );
        assert!(!release_has_current_platform_asset(&r));
    }

    #[test]
    fn accepts_release_with_matching_asset() {
        let expected = asset_name("9.9.9", false);
        let r = release("v9.9.9", false, &[&expected]);
        assert!(release_has_current_platform_asset(&r));
    }

    #[test]
    fn accepts_beta_release_with_matching_beta_asset() {
        let expected = asset_name("9.9.9-beta.1", true);
        let r = release("v9.9.9-beta.1", true, &[&expected]);
        assert!(release_has_current_platform_asset(&r));
    }

    #[test]
    fn rejects_stable_named_asset_on_beta_release() {
        // If someone uploads a `tokensave-v...` asset to a prerelease, the
        // filter should still reject — the naming convention says beta
        // releases carry `tokensave-beta-v...` assets.
        let stable_name = asset_name("9.9.9-beta.1", false);
        let r = release("v9.9.9-beta.1", true, &[&stable_name]);
        assert!(!release_has_current_platform_asset(&r));
    }
}