nap-core 0.8.2

Core library for the Narrative Addressing Protocol
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
// SPDX-FileCopyrightText: 2026 Digital Creations
// SPDX-License-Identifier: MIT
//! Lore version detection and compatibility checking
//!
//! Provides utilities to detect installed Lore CLI/server versions and
//! verify compatibility with the SDK's pinned version.
//!
//! NAP requires an **exact match** of the full version string against
//! [`PINNED_LORE_VERSION`].

use anyhow::{Context, Result};
use semver::Version;
use std::process::Command;

/// Pinned Lore version that NAP SDK requires.
///
/// During initialization NAP verifies that the installed `lore` and
/// `loreserver` binaries report **exactly** this version string.
pub const PINNED_LORE_VERSION: &str = "0.8.4-portals.9";

/// Release repository containing the Portals authentication-capable Lore
/// client. Never fall back to the unaffiliated upstream release at runtime.
pub const PINNED_LORE_REPOSITORY: &str = "portalshq/lore";

/// SHA-256 of `scripts/install.sh` at the pinned Lore release tag. This makes
/// `nap install lore` reject a moved tag or compromised download before
/// executing it.
pub const PINNED_LORE_INSTALLER_SHA256: &str =
    "8e7cc96d1b9100610af6c1bd15ec2febbcb48d26cc7f19de3862496897810b74";

/// Digest and Sigstore bundle for the Lore release's binary checksum
/// manifest. Empty means this Nap source is not eligible for a secure cloud
/// release even though local development can still use the pinned installer.
pub const PINNED_LORE_ARTIFACT_MANIFEST_SHA256: &str =
    "sha256:dc853999309ec32e2c91acb94f7ef2aad4f080ac4a0f7591d9371d5cd57eb089";
pub const PINNED_LORE_ARTIFACT_MANIFEST_URL: &str =
    "https://github.com/portalshq/lore/releases/download/v0.8.4-portals.9/SHA256SUMS";
pub const PINNED_LORE_SIGNATURE_BUNDLE_URL: &str =
    "https://github.com/portalshq/lore/releases/download/v0.8.4-portals.9/SHA256SUMS.sigstore.json";

// ── Detected version info ───────────────────────────────────────────────

/// A detected Lore version with both parsed semver and raw string forms.
///
/// The `raw` field preserves the full version string reported by the CLI
/// so that compatibility checks can enforce an exact match — not just
/// major.minor.patch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoreVersionInfo {
    /// Parsed semver (e.g. `0.8.4`).  The nightly suffix is stripped here
    /// because `semver::Version` has no concept of release channels.
    pub parsed: Version,
    /// Raw version string exactly as reported by the binary
    /// (e.g. `"0.8.4"`).
    pub raw: String,
}

impl std::fmt::Display for LoreVersionInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.raw)
    }
}

// ── Version detection ───────────────────────────────────────────────────

/// Extract the raw version token from CLI output.
///
/// Given `"lore 0.8.4\n"`, returns `"0.8.4"`.
fn extract_version_string(version_str: &str) -> Result<String> {
    let version_part = version_str.split_whitespace().nth(1).context(format!(
        "Failed to parse Lore version string '{}'. \
             Expected format: 'lore <version>' (e.g., 'lore 0.8.4')",
        version_str.trim()
    ))?;
    Ok(version_part.trim().to_string())
}

/// Detect the installed Lore CLI version
pub fn detect_lore_version() -> Result<LoreVersionInfo> {
    let output = Command::new("lore").arg("--version").output().context(
        "Failed to execute 'lore --version'. \
             Lore CLI is not installed or not on PATH. \
             Install it with: nap install lore",
    )?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!(
            "lore --version exited with status: {}. stderr: {}",
            output.status,
            stderr.trim()
        );
    }

    let version_str = String::from_utf8_lossy(&output.stdout);
    let raw = extract_version_string(&version_str)?;
    let parsed = parse_lore_version(&version_str)?;
    Ok(LoreVersionInfo { parsed, raw })
}

/// Detect the installed Lore server version
pub fn detect_loreserver_version() -> Result<LoreVersionInfo> {
    let output = Command::new("loreserver")
        .arg("--version")
        .output()
        .context(
            "Failed to execute 'loreserver --version'. \
             Lore server is not installed or not on PATH. \
             Install it with: nap install lore",
        )?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!(
            "loreserver --version exited with status: {}. stderr: {}",
            output.status,
            stderr.trim()
        );
    }

    let version_str = String::from_utf8_lossy(&output.stdout);
    let raw = extract_version_string(&version_str)?;
    let parsed = parse_lore_version(&version_str)?;
    Ok(LoreVersionInfo { parsed, raw })
}

// ── Version parsing ─────────────────────────────────────────────────────

/// Parse Lore version string into `semver::Version`.
///
/// Strips the nightly/release suffix before parsing because
/// `semver::Version` does not model release channels.  Use
/// [`extract_version_string`] when you need the full, unparsed token.
fn parse_lore_version(version_str: &str) -> Result<Version> {
    // Lore version format: "lore 0.8.4" or "loreserver 0.8.4"
    let version_part = version_str.split_whitespace().nth(1).context(format!(
        "Failed to parse Lore version string '{}'. \
             Expected format: 'lore <version>' (e.g., 'lore 0.8.4')",
        version_str.trim()
    ))?;

    // Handle nightly versions by stripping the suffix for semver parsing
    let version_for_semver = version_part.trim_end_matches("-nightly");

    Version::parse(version_for_semver).context(format!(
        "Failed to parse '{}' as semver version. \
             Lore version string may be in an unexpected format.",
        version_for_semver
    ))
}

// ── Compatibility gate ──────────────────────────────────────────────────

/// Check if the installed Lore version **exactly** matches the pinned version.
///
/// Build metadata after `+` (e.g. `0.8.4+283`) is stripped before
/// comparison per the semver spec. Pre-release tags like `-nightly` or
/// `-stable` are **not** stripped and will cause a mismatch.
pub fn check_lore_compatibility(installed: &LoreVersionInfo) -> Result<bool> {
    let installed_version = installed.raw.split('+').next().unwrap_or(&installed.raw);
    Ok(installed_version == PINNED_LORE_VERSION)
}

// ── Full installation verification ──────────────────────────────────────

/// Verify Lore installation and compatibility
pub fn verify_lore_installation() -> Result<LoreInstallationStatus> {
    let cli_version = match detect_lore_version() {
        Ok(v) => Some(v),
        Err(e) => {
            tracing::debug!("Lore CLI not detected: {}", e);
            None
        }
    };

    let server_version = match detect_loreserver_version() {
        Ok(v) => Some(v),
        Err(e) => {
            tracing::debug!("Lore server not detected: {}", e);
            None
        }
    };

    let cli_compatible = cli_version
        .as_ref()
        .map(|v| check_lore_compatibility(v).unwrap_or(false))
        .unwrap_or(false);

    let server_compatible = server_version
        .as_ref()
        .map(|v| check_lore_compatibility(v).unwrap_or(false))
        .unwrap_or(false);

    Ok(LoreInstallationStatus {
        cli_installed: cli_version.is_some(),
        cli_version,
        cli_compatible,
        server_installed: server_version.is_some(),
        server_version,
        server_compatible,
        pinned_version: PINNED_LORE_VERSION.to_string(),
    })
}

// ── Installation status ─────────────────────────────────────────────────

/// Status of Lore installation
#[derive(Debug, Clone)]
pub struct LoreInstallationStatus {
    pub cli_installed: bool,
    pub cli_version: Option<LoreVersionInfo>,
    pub cli_compatible: bool,
    pub server_installed: bool,
    pub server_version: Option<LoreVersionInfo>,
    pub server_compatible: bool,
    pub pinned_version: String,
}

impl LoreInstallationStatus {
    /// Check if installation is fully compatible
    pub fn is_fully_compatible(&self) -> bool {
        self.cli_installed && self.cli_compatible && self.server_installed && self.server_compatible
    }

    /// Get a human-readable status message
    pub fn status_message(&self) -> String {
        let mut messages = vec![];

        if !self.cli_installed {
            messages.push("Lore CLI is not installed".to_string());
        } else if !self.cli_compatible {
            messages.push(format!(
                "Lore CLI version '{}' is incompatible with required version '{}'",
                self.cli_version
                    .as_ref()
                    .map(|v| v.raw.as_str())
                    .unwrap_or("unknown"),
                self.pinned_version
            ));
        }

        if !self.server_installed {
            messages.push("Lore server is not installed".to_string());
        } else if !self.server_compatible {
            messages.push(format!(
                "Lore server version '{}' is incompatible with required version '{}'",
                self.server_version
                    .as_ref()
                    .map(|v| v.raw.as_str())
                    .unwrap_or("unknown"),
                self.pinned_version
            ));
        }

        if messages.is_empty() {
            "Lore installation is compatible".to_string()
        } else {
            messages.join("; ")
        }
    }
}

// ── Unit tests ──────────────────────────────────────────────────────────

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

    #[test]
    fn test_extract_version_string() {
        assert_eq!(extract_version_string("lore 0.8.4").unwrap(), "0.8.4");
        assert_eq!(extract_version_string("loreserver 0.8.4").unwrap(), "0.8.4");
        assert_eq!(extract_version_string("lore 0.8.4\n").unwrap(), "0.8.4");
    }

    #[test]
    fn test_extract_version_string_failure() {
        // Single-word input has no second token → should fail
        assert!(extract_version_string("lore").is_err());
        // Empty string → should fail
        assert!(extract_version_string("").is_err());
    }

    #[test]
    fn test_parse_lore_version() {
        let version_str = "lore 0.8.4";
        let version = parse_lore_version(version_str).unwrap();
        assert_eq!(version.major, 0);
        assert_eq!(version.minor, 8);
        assert_eq!(version.patch, 4);
    }

    #[test]
    fn test_parse_lore_version_with_nightly_suffix() {
        // Nightly suffix is stripped for semver parsing
        let version_str = "lore 0.8.4-nightly";
        let version = parse_lore_version(version_str).unwrap();
        assert_eq!(version.major, 0);
        assert_eq!(version.minor, 8);
        assert_eq!(version.patch, 4);
    }

    #[test]
    fn test_parse_loreserver_version() {
        let version_str = "loreserver 0.8.4";
        let version = parse_lore_version(version_str).unwrap();
        assert_eq!(version.major, 0);
        assert_eq!(version.minor, 8);
        assert_eq!(version.patch, 4);
    }

    #[test]
    fn test_compatibility_exact_match() {
        let installed = LoreVersionInfo {
            parsed: Version::new(0, 8, 4),
            raw: PINNED_LORE_VERSION.to_string(),
        };
        assert!(check_lore_compatibility(&installed).unwrap());
    }

    #[test]
    fn test_compatibility_ignores_build_metadata() {
        // "0.8.4-portals.9+283" must match pinned "0.8.4-portals.9" — build
        // metadata is ignored per the semver specification.
        let installed = LoreVersionInfo {
            parsed: Version::new(0, 8, 4),
            raw: format!("{}+283", PINNED_LORE_VERSION),
        };
        assert!(check_lore_compatibility(&installed).unwrap());
    }

    #[test]
    fn test_compatibility_rejects_nightly_suffix() {
        // "0.8.4-nightly" must NOT match pinned "0.8.4"
        let installed = LoreVersionInfo {
            parsed: Version::new(0, 8, 4),
            raw: "0.8.4-nightly".to_string(),
        };
        assert!(!check_lore_compatibility(&installed).unwrap());
    }

    #[test]
    fn test_compatibility_rejects_wrong_channel() {
        let installed = LoreVersionInfo {
            parsed: Version::new(0, 8, 4),
            raw: "0.8.4-stable".to_string(),
        };
        assert!(!check_lore_compatibility(&installed).unwrap());
    }

    #[test]
    fn test_compatibility_rejects_wrong_version() {
        let installed = LoreVersionInfo {
            parsed: Version::new(0, 7, 0),
            raw: "0.7.0".to_string(),
        };
        assert!(!check_lore_compatibility(&installed).unwrap());
    }

    #[test]
    fn test_installation_status_message() {
        let status = LoreInstallationStatus {
            cli_installed: false,
            cli_version: None,
            cli_compatible: false,
            server_installed: false,
            server_version: None,
            server_compatible: false,
            pinned_version: PINNED_LORE_VERSION.to_string(),
        };

        let message = status.status_message();
        assert!(message.contains("Lore CLI is not installed"));
        assert!(message.contains("Lore server is not installed"));
    }

    #[test]
    fn test_installation_status_message_incompatible() {
        let status = LoreInstallationStatus {
            cli_installed: true,
            cli_version: Some(LoreVersionInfo {
                parsed: Version::new(0, 8, 4),
                raw: "0.8.4-nightly".to_string(),
            }),
            cli_compatible: false,
            server_installed: true,
            server_version: Some(LoreVersionInfo {
                parsed: Version::new(0, 8, 4),
                raw: "0.8.4-nightly".to_string(),
            }),
            server_compatible: false,
            pinned_version: PINNED_LORE_VERSION.to_string(),
        };

        let message = status.status_message();
        assert!(message.contains("'0.8.4-nightly'"));
        assert!(message.contains(&format!("'{}'", PINNED_LORE_VERSION)));
        assert!(!status.is_fully_compatible());
    }

    #[test]
    fn test_pinned_version_constant() {
        // This test documents the contract: the pinned version must be
        // "0.8.4-portals.9".  If you intentionally change it, update this
        // test and the integration test as well.
        assert_eq!(PINNED_LORE_VERSION, "0.8.4-portals.9");
    }
}