reflex-search 2.3.0

A local-first, structure-aware code search engine for AI agents
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! The Node runtime that builds Pulse sites, managed outside the rfx binary.
//!
//! ```text
//! ~/.reflex/pulse/                      ($REFLEX_PULSE_HOME)
//!   runtime/<deps-hash>/
//!     package.json, package-lock.json   the template's pinned dependencies
//!     node_modules/                     installed once per deps hash, shared by all projects
//!     sites/<workspace-key>/            staged Astro project per workspace (template + bundle)
//! ```
//! The staged project sits under the runtime so Node's upward module resolution finds
//! `node_modules` without links. The rfx binary embeds only the template sources
//! (tens of KB); Node and `node_modules` never ship inside it.

use crate::pulse::render::project::ProjectWriter;
use anyhow::{Context, Result, bail};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

/// The embedded site template.
pub mod template {
    include!(concat!(env!("OUT_DIR"), "/pulse_template.rs"));
}

/// Minimum Node version (Astro 7).
pub const MIN_NODE: (u32, u32, u32) = (22, 12, 0);

pub fn pulse_home() -> PathBuf {
    if let Ok(h) = std::env::var("REFLEX_PULSE_HOME") {
        return PathBuf::from(h);
    }
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".reflex")
        .join("pulse")
}

#[derive(Debug, Clone)]
pub struct Node {
    pub path: PathBuf,
    pub version: (u32, u32, u32),
}

pub fn parse_node_version(s: &str) -> Option<(u32, u32, u32)> {
    let v = s.trim().trim_start_matches('v');
    let mut it = v.split('.').map(|p| p.parse::<u32>().ok());
    Some((it.next()??, it.next()??, it.next().flatten().unwrap_or(0)))
}

/// `$REFLEX_PULSE_NODE`, else `node` on `PATH`, at [`MIN_NODE`] or newer.
pub fn find_node() -> Result<Node> {
    let path = std::env::var("REFLEX_PULSE_NODE")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("node"));
    let out = Command::new(&path)
        .arg("--version")
        .output()
        .with_context(|| {
            format!(
                "Node.js {}.{}+ is needed to build the site and `{}` was not found.\n  \
             Install Node (https://nodejs.org), or set REFLEX_PULSE_NODE, or run with --no-build \
             to write the site project without building it.",
                MIN_NODE.0,
                MIN_NODE.1,
                path.display()
            )
        })?;
    let version = parse_node_version(&String::from_utf8_lossy(&out.stdout))
        .context("could not read `node --version`")?;
    if version < MIN_NODE {
        bail!(
            "Node {}.{}.{} is too old to build the site; {}.{}+ is needed (set REFLEX_PULSE_NODE to another node).",
            version.0,
            version.1,
            version.2,
            MIN_NODE.0,
            MIN_NODE.1
        );
    }
    Ok(Node { path, version })
}

/// An installed runtime: `node_modules` for the embedded template.
#[derive(Debug, Clone)]
pub struct Runtime {
    pub root: PathBuf,
    pub node: Node,
}

impl Runtime {
    pub fn astro_entry(&self) -> PathBuf {
        self.root.join("node_modules/astro/bin/astro.mjs")
    }

    /// Staging directory for one workspace.
    pub fn site_dir(&self, workspace: &Path) -> PathBuf {
        let canon = std::fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf());
        let key = blake3::hash(canon.to_string_lossy().as_bytes()).to_hex()[..12].to_string();
        let name = canon
            .file_name()
            .map(|n| crate::pulse::model::ids::slugify(&n.to_string_lossy()))
            .unwrap_or_else(|| "site".into());
        self.root.join("sites").join(format!("{name}-{key}"))
    }
}

const COMPLETE: &str = ".pulse-runtime-complete";

/// Find or install the runtime for the embedded template.
///
/// `$REFLEX_PULSE_RUNTIME` points at a directory with `node_modules` (CI caches,
/// air-gapped mirrors). Otherwise the runtime lives under [`pulse_home`], keyed by the
/// template's dependency hash, and is installed once with `npm ci --ignore-scripts`.
pub fn ensure(offline: bool) -> Result<Runtime> {
    let node = find_node()?;
    if let Ok(dir) = std::env::var("REFLEX_PULSE_RUNTIME") {
        let root = PathBuf::from(dir);
        if !root.join("node_modules/astro").exists() {
            bail!(
                "REFLEX_PULSE_RUNTIME={} has no node_modules/astro",
                root.display()
            );
        }
        return Ok(Runtime { root, node });
    }
    let root = pulse_home().join("runtime").join(template::DEPS_HASH);
    if root.join(COMPLETE).exists() {
        return Ok(Runtime { root, node });
    }
    if offline {
        bail!(
            "The site runtime is not installed ({}) and --offline forbids installing it.\n  \
             Run once without --offline, or use --no-build.",
            root.display()
        );
    }
    match install_prebuilt(&root) {
        Ok(true) => {}
        Ok(false) => install(&root, &node)?,
        Err(e) => {
            eprintln!("  prebuilt runtime unavailable ({e:#}); installing with npm instead");
            install(&root, &node)?;
        }
    }
    Ok(Runtime { root, node })
}

/// The runtime id: the template's dependency hash. It names the runtime directory,
/// the prebuilt tarballs and their release tag.
pub fn key() -> &'static str {
    template::DEPS_HASH
}

/// A human-readable report for `rfx pulse runtime status`.
pub fn status() -> String {
    let mut out = String::new();
    match find_node() {
        Ok(n) => out.push_str(&format!(
            "node:      {} ({}.{}.{})\n",
            n.path.display(),
            n.version.0,
            n.version.1,
            n.version.2
        )),
        Err(e) => out.push_str(&format!("node:      not usable: {e:#}\n")),
    }
    let root = pulse_home().join("runtime").join(key());
    let state = if root.join(COMPLETE).exists() {
        "installed"
    } else {
        "not installed"
    };
    out.push_str(&format!("runtime:   {} ({state})\n", root.display()));
    let lock = RuntimeLock::embedded();
    let platform = platform_id().unwrap_or("unsupported");
    let prebuilt = match lock.asset_for(platform) {
        Some(a) => format!("{} ({:.1} MB)", lock.url(a), a.size as f64 / 1_048_576.0),
        None => "none published; falls back to npm ci".to_string(),
    };
    out.push_str(&format!("platform:  {platform}\nprebuilt:  {prebuilt}\n"));
    out
}

/// The platform id Node reports (`process.platform-process.arch`), which names the
/// prebuilt runtime tarballs.
pub fn platform_id() -> Option<&'static str> {
    Some(match (std::env::consts::OS, std::env::consts::ARCH) {
        ("linux", "x86_64") => "linux-x64",
        ("linux", "aarch64") => "linux-arm64",
        ("macos", "x86_64") => "darwin-x64",
        ("macos", "aarch64") => "darwin-arm64",
        ("windows", "x86_64") => "win32-x64",
        ("windows", "aarch64") => "win32-arm64",
        _ => return None,
    })
}

/// One published runtime tarball.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct Asset {
    pub name: String,
    pub sha256: String,
    #[serde(default)]
    pub size: u64,
}

/// `pulse-template/runtime.lock.json`, compiled into the binary.
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct RuntimeLock {
    #[serde(default)]
    pub deps_hash: String,
    #[serde(default)]
    pub release_base: String,
    #[serde(default)]
    pub assets: std::collections::BTreeMap<String, Asset>,
}

impl RuntimeLock {
    pub fn embedded() -> Self {
        serde_json::from_str(template::RUNTIME_LOCK).unwrap_or_default()
    }

    /// The asset for this platform, if the manifest matches the embedded template.
    /// A stale manifest (template dependencies changed since the tarballs were built)
    /// is ignored, so a new template never runs with old packages.
    pub fn asset_for(&self, platform: &str) -> Option<&Asset> {
        (self.deps_hash == template::DEPS_HASH)
            .then(|| self.assets.get(platform))
            .flatten()
    }

    /// Download URL; `REFLEX_PULSE_MIRROR` replaces the release base (air-gapped CI).
    pub fn url(&self, asset: &Asset) -> String {
        let base =
            std::env::var("REFLEX_PULSE_MIRROR").unwrap_or_else(|_| self.release_base.clone());
        format!(
            "{}/pulse-runtime-{}/{}",
            base.trim_end_matches('/'),
            self.deps_hash,
            asset.name
        )
    }
}

pub fn sha256_hex(bytes: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let mut h = Sha256::new();
    h.update(bytes);
    h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}

/// Download, verify and unpack the prebuilt `node_modules` tarball. `Ok(false)` when
/// no tarball is published for this platform and template.
fn install_prebuilt(root: &Path) -> Result<bool> {
    let lock = RuntimeLock::embedded();
    let Some(asset) = platform_id().and_then(|p| lock.asset_for(p)) else {
        return Ok(false);
    };
    std::fs::create_dir_all(root)?;
    let guard =
        crate::atomic_write::IndexLock::acquire_with_timeout(root, Duration::from_secs(900))
            .context("waiting for another rfx process that is installing the site runtime")?;
    if root.join(COMPLETE).exists() {
        drop(guard);
        return Ok(true);
    }
    let url = lock.url(asset);
    eprintln!("Downloading the Pulse site runtime ({})…", asset.name);
    let start = Instant::now();
    let bytes = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(async {
            let resp = reqwest::get(&url).await?.error_for_status()?;
            resp.bytes().await
        })
        .with_context(|| format!("downloading {url}"))?;
    let got = sha256_hex(&bytes);
    if !got.eq_ignore_ascii_case(&asset.sha256) {
        bail!(
            "checksum mismatch for {}: expected {}, got {got}",
            asset.name,
            asset.sha256
        );
    }
    // Unpack beside the final location, then rename: a crash never leaves half a runtime.
    let tmp = root.join(format!("node_modules.tmp-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::create_dir_all(&tmp)?;
    let decoder = zstd::stream::read::Decoder::new(&bytes[..])?;
    let mut archive = tar::Archive::new(decoder);
    for entry in archive.entries()? {
        let mut entry = entry?;
        // `unpack_in` refuses paths that escape `tmp` (`..`, absolute).
        entry.unpack_in(&tmp)?;
    }
    let nm = tmp.join("node_modules");
    if !nm.join("astro").exists() {
        bail!("{} does not contain node_modules/astro", asset.name);
    }
    let _ = std::fs::remove_dir_all(root.join("node_modules"));
    std::fs::rename(&nm, root.join("node_modules"))?;
    let _ = std::fs::remove_dir_all(&tmp);
    std::fs::write(root.join(COMPLETE), template::DEPS_HASH)?;
    eprintln!(
        "  runtime ready in {:.0}s ({:.1} MB)",
        start.elapsed().as_secs_f64(),
        bytes.len() as f64 / 1_048_576.0
    );
    drop(guard);
    Ok(true)
}

fn npm_for(node: &Node) -> PathBuf {
    // Prefer the npm that ships next to this node.
    if let Some(dir) = node.path.parent().filter(|d| !d.as_os_str().is_empty()) {
        for name in ["npm", "npm.cmd"] {
            let p = dir.join(name);
            if p.exists() {
                return p;
            }
        }
    }
    PathBuf::from(if cfg!(windows) { "npm.cmd" } else { "npm" })
}

fn install(root: &Path, node: &Node) -> Result<()> {
    std::fs::create_dir_all(root)?;
    // Another rfx may be installing the same runtime; wait for it.
    let lock = crate::atomic_write::IndexLock::acquire_with_timeout(root, Duration::from_secs(900))
        .context("waiting for another rfx process that is installing the site runtime")?;
    if root.join(COMPLETE).exists() {
        drop(lock);
        return Ok(());
    }
    for (rel, bytes) in template::FILES {
        if *rel == "package.json" || *rel == "package-lock.json" {
            std::fs::write(root.join(rel), bytes)?;
        }
    }
    eprintln!(
        "Installing the Pulse site runtime (Astro + Starlight) into {} — once per template version…",
        root.display()
    );
    let start = Instant::now();
    let status = Command::new(npm_for(node))
        .args([
            "ci",
            "--ignore-scripts",
            "--omit=dev",
            "--no-audit",
            "--no-fund",
            "--loglevel=error",
        ])
        .current_dir(root)
        .status()
        .context("running `npm ci` (npm must be installed alongside node)")?;
    if !status.success() {
        bail!("`npm ci` failed in {} ({status})", root.display());
    }
    std::fs::write(root.join(COMPLETE), template::DEPS_HASH)?;
    eprintln!("  runtime ready in {:.0}s", start.elapsed().as_secs_f64());
    drop(lock);
    Ok(())
}

/// Write the embedded template into `site_dir`; unchanged files keep their mtime.
pub fn stage_template(site_dir: &Path) -> Result<()> {
    let mut w = ProjectWriter::open(site_dir)?;
    for (rel, bytes) in template::FILES {
        if *rel == "package-lock.json" {
            continue; // the runtime owns dependencies; a site has no node_modules
        }
        w.put(rel, bytes)?;
    }
    // Template files are never swept: only bundle files come and go.
    w.finish("\0")?;
    Ok(())
}

#[derive(Debug, Clone)]
pub struct BuildOutcome {
    pub dist: PathBuf,
    pub elapsed: Duration,
}

/// Run `astro build` in `site_dir`. Output goes to `build.log`; a failure returns the
/// last lines of it.
pub fn astro_build(rt: &Runtime, site_dir: &Path, verbose: bool) -> Result<BuildOutcome> {
    let start = Instant::now();
    let log_path = site_dir.join("build.log");
    let mut child = Command::new(&rt.node.path)
        .arg(rt.astro_entry())
        .args(["build", "--root"])
        .arg(site_dir)
        .current_dir(site_dir)
        .env("ASTRO_TELEMETRY_DISABLED", "1")
        .env("NODE_ENV", "production")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .context("starting astro build")?;
    let stderr = child.stderr.take().expect("piped stderr");
    let err_thread = std::thread::spawn(move || {
        BufReader::new(stderr)
            .lines()
            .map_while(Result::ok)
            .collect::<Vec<_>>()
    });
    let mut log: Vec<String> = Vec::new();
    let stdout = child.stdout.take().expect("piped stdout");
    for line in BufReader::new(stdout).lines().map_while(Result::ok) {
        if verbose {
            eprintln!("  {line}");
        } else if line.contains("Complete!")
            || line.contains("pages built in")
            || line.contains("[build] ") && line.contains("page(s) built")
        {
            eprintln!("  {}", strip_ansi(&line));
        }
        log.push(line);
    }
    let status = child.wait()?;
    log.extend(err_thread.join().unwrap_or_default());
    let _ = std::fs::write(&log_path, log.join("\n"));
    if !status.success() {
        let tail: Vec<String> = log
            .iter()
            .rev()
            .take(40)
            .rev()
            .map(|l| strip_ansi(l))
            .collect();
        bail!(
            "astro build failed ({status}). Last lines of {}:\n{}",
            log_path.display(),
            tail.join("\n")
        );
    }
    Ok(BuildOutcome {
        dist: site_dir.join("dist"),
        elapsed: start.elapsed(),
    })
}

fn strip_ansi(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\u{1b}' {
            for n in chars.by_ref() {
                if n.is_ascii_alphabetic() {
                    break;
                }
            }
        } else {
            out.push(c);
        }
    }
    out
}

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

    #[test]
    fn node_versions() {
        assert_eq!(parse_node_version("v24.15.0\n"), Some((24, 15, 0)));
        assert_eq!(parse_node_version("22.12"), Some((22, 12, 0)));
        assert!(parse_node_version("v22.11.0").unwrap() < MIN_NODE);
        assert!(parse_node_version("v22.12.0").unwrap() >= MIN_NODE);
        assert_eq!(parse_node_version("nope"), None);
    }

    #[test]
    fn template_is_embedded() {
        let names: Vec<&str> = template::FILES.iter().map(|(n, _)| *n).collect();
        for want in [
            "astro.config.mjs",
            "package.json",
            "package-lock.json",
            "src/layouts/PulsePage.astro",
        ] {
            assert!(names.contains(&want), "{want} missing from {names:?}");
        }
        assert!(
            !names
                .iter()
                .any(|n| n.starts_with("node_modules/") || n.starts_with("scripts/"))
        );
        assert_eq!(template::DEPS_HASH.len(), 12);
    }

    #[test]
    fn staging_writes_template_without_dependencies() {
        let dir = tempfile::TempDir::new().unwrap();
        stage_template(dir.path()).unwrap();
        assert!(dir.path().join("astro.config.mjs").exists());
        assert!(!dir.path().join("package-lock.json").exists());
        assert!(
            dir.path().join("package.json").exists(),
            "declares \"type\": \"module\""
        );
    }

    #[test]
    fn runtime_lock_matching() {
        let json = format!(
            r#"{{"deps_hash": "{}", "release_base": "https://example.test/dl",
                "assets": {{"linux-x64": {{"name": "a.tar.zst", "sha256": "ab", "size": 1}}}}}}"#,
            template::DEPS_HASH
        );
        let lock: RuntimeLock = serde_json::from_str(&json).unwrap();
        assert!(lock.asset_for("linux-x64").is_some());
        assert!(lock.asset_for("darwin-arm64").is_none());
        assert_eq!(
            lock.url(lock.asset_for("linux-x64").unwrap()),
            format!(
                "https://example.test/dl/pulse-runtime-{}/a.tar.zst",
                template::DEPS_HASH
            )
        );
        let stale: RuntimeLock =
            serde_json::from_str(r#"{"deps_hash": "000000000000", "assets": {"linux-x64": {"name": "a", "sha256": "b"}}}"#).unwrap();
        assert!(
            stale.asset_for("linux-x64").is_none(),
            "a stale manifest is ignored"
        );
        // The committed manifest parses.
        let _ = RuntimeLock::embedded();
        assert_eq!(
            sha256_hex(b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    #[test]
    fn ansi_is_stripped() {
        assert_eq!(strip_ansi("\u{1b}[32m✓ Complete!\u{1b}[39m"), "✓ Complete!");
    }
}