semantex-core 1.0.0

Core library for semantex semantic code search (indexing, embeddings, search)
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
//! Global project registry — tracks all repos that have been indexed.
//!
//! Stored at `<semantex_home>/projects.json` (i.e. `~/.semantex/projects.json`
//! by default; [`crate::config::SemantexConfig::semantex_home`] honors the
//! `SEMANTEX_HOME` env var, so the whole registry relocates with it — which is
//! also how tests and sandboxed environments keep it away from real user
//! state). **v2** (contract §A) is a versioned object: `{ version: 2,
//! projects: [{ path, project_id, display_name, branches: [...],
//! embedder_fingerprint }] }`. **v1** (pre-v13) was a bare JSON array of
//! canonical absolute path strings; [`load`] transparently upgrades a v1 file
//! to v2 in place (the next [`register`]/[`upsert_branch`] call persists the
//! upgraded shape).
//!
//! Writes are atomic (tmp file + rename in the same directory), so a crash
//! mid-save can never leave a torn/corrupt `projects.json` behind. Concurrent
//! writers (two `semantex index` runs racing) are **last-write-wins** at
//! whole-file granularity: each writer read-modify-writes the full file, and
//! the final rename decides. That can drop the other writer's single upsert,
//! but never corrupts the file — acceptable for a best-effort discovery aid.
//!
//! Both the CLI session hook and the MCP server read this to discover repos
//! that may have drifted (index age > threshold) without waiting for a user
//! to open them — via [`read_all`], which keeps its pre-v13 signature
//! (`Vec<PathBuf>`) so neither caller needed to change.

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Resolve the registry file location. Routed through
/// [`SemantexConfig::semantex_home`](crate::config::SemantexConfig::semantex_home)
/// so it honors `SEMANTEX_HOME` (and never resolves to a developer's real
/// home when that override is set).
fn registry_path() -> PathBuf {
    crate::config::SemantexConfig::semantex_home().join("projects.json")
}

/// One tracked branch of a registered project (contract §A).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct BranchEntry {
    pub branch: String,
    pub branch_key: String,
    #[serde(default)]
    pub last_indexed_ts: i64,
    #[serde(default)]
    pub head_commit: Option<String>,
}

/// One registered project (contract §A).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct ProjectEntry {
    pub path: PathBuf,
    #[serde(default)]
    pub project_id: String,
    #[serde(default)]
    pub display_name: String,
    #[serde(default)]
    pub branches: Vec<BranchEntry>,
    #[serde(default)]
    pub embedder_fingerprint: String,
}

/// The versioned registry file shape (contract §A: `"version": 2`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RegistryV2 {
    pub version: u32,
    pub projects: Vec<ProjectEntry>,
}

impl Default for RegistryV2 {
    fn default() -> Self {
        Self {
            version: 2,
            projects: Vec::new(),
        }
    }
}

/// Derive a stable, filesystem/JSON-safe project id from a canonical path.
/// Purely a function of the path (not random) so re-registering the same
/// project always yields the same id, and so `IndexBuilder` can compute the
/// same id independently when stamping `ProjectMeta::project_id`
/// (`index/layout.rs`) without a registry round-trip.
pub fn project_id_for_path(canonical: &Path) -> String {
    use sha2::{Digest, Sha256};
    use std::fmt::Write as _;
    let mut hasher = Sha256::new();
    hasher.update(canonical.to_string_lossy().as_bytes());
    let digest = hasher.finalize();
    digest[..8].iter().fold(String::new(), |mut out, b| {
        let _ = write!(out, "{b:02x}");
        out
    })
}

fn display_name_for_path(path: &Path) -> String {
    path.file_name().map_or_else(
        || path.to_string_lossy().to_string(),
        |n| n.to_string_lossy().to_string(),
    )
}

/// Path-parameterized core of [`load`]. Tests point this at a tempdir file so
/// they never read (let alone delete) a developer's real registry.
fn load_from(path: &Path) -> RegistryV2 {
    let Ok(content) = std::fs::read_to_string(path) else {
        return RegistryV2::default();
    };
    if let Ok(v2) = serde_json::from_str::<RegistryV2>(&content) {
        return v2;
    }
    // v1: a bare array of canonical path strings.
    if let Ok(v1_paths) = serde_json::from_str::<Vec<String>>(&content) {
        let projects = v1_paths
            .into_iter()
            .map(|p| {
                let path = PathBuf::from(&p);
                ProjectEntry {
                    project_id: project_id_for_path(&path),
                    display_name: display_name_for_path(&path),
                    path,
                    branches: Vec::new(),
                    embedder_fingerprint: String::new(),
                }
            })
            .collect();
        return RegistryV2 {
            version: 2,
            projects,
        };
    }
    RegistryV2::default()
}

/// Load the registry, transparently upgrading a v1 (bare path array) file to
/// the v2 shape in memory. Returns an empty v2 registry if the file is
/// absent, unreadable, or unparseable as either shape — the registry is a
/// best-effort discovery aid, never a hard dependency.
pub fn load() -> RegistryV2 {
    load_from(&registry_path())
}

/// Atomically persist the registry to `path`: serialize to a tmp file in the
/// SAME directory, then `rename` over the destination. A crash at any point
/// leaves either the old complete file or the new complete file — never a
/// truncated/torn one (which `load_from` would silently read as an empty
/// registry, losing every registered project). Concurrent writers are
/// last-write-wins at whole-file granularity (see module doc).
fn save_to(path: &Path, registry: &RegistryV2) -> bool {
    let Some(parent) = path.parent() else {
        return false;
    };
    if std::fs::create_dir_all(parent).is_err() {
        return false;
    }
    let Ok(json) = serde_json::to_string_pretty(registry) else {
        return false;
    };
    // Pid-suffixed so two racing processes never stomp each other's tmp file;
    // same dir as the destination so the rename is atomic (no cross-device).
    let tmp = parent.join(format!(
        ".{}.tmp.{}",
        path.file_name()
            .map(|n| n.to_string_lossy())
            .unwrap_or_default(),
        std::process::id()
    ));
    if std::fs::write(&tmp, json).is_err() {
        let _ = std::fs::remove_file(&tmp);
        return false;
    }
    let ok = std::fs::rename(&tmp, path).is_ok();
    if !ok {
        let _ = std::fs::remove_file(&tmp);
    }
    ok
}

/// Read all registered project paths from the registry.
///
/// Signature preserved from v1 (`Vec<PathBuf>`) so existing callers
/// (`semantex-mcp`, `semantex-cli`) keep compiling and behaving unchanged
/// across the v1 → v2 upgrade.
pub fn read_all() -> Vec<PathBuf> {
    load().projects.into_iter().map(|p| p.path).collect()
}

/// Read the full v2 registry (path, project_id, branches, embedder
/// fingerprint, etc.) — used by [`crate::search::federation`] to resolve
/// cross-project search targets. `read_all` stays the lightweight
/// path-only accessor for existing callers.
pub fn read_all_v2() -> RegistryV2 {
    load()
}

/// Path-parameterized core of [`register`].
fn register_at(path: &Path, canonical: &Path) {
    let mut registry = load_from(path);
    if registry.projects.iter().any(|p| p.path == canonical) {
        return; // already registered
    }
    registry.projects.push(ProjectEntry {
        path: canonical.to_path_buf(),
        project_id: project_id_for_path(canonical),
        display_name: display_name_for_path(canonical),
        branches: Vec::new(),
        embedder_fingerprint: String::new(),
    });
    save_to(path, &registry);
}

/// Register a project in the global registry (upsert — no duplicates).
///
/// Signature preserved from v1. Internally upgrades/creates a v2
/// [`ProjectEntry`] for `canonical` if one doesn't already exist.
pub fn register(canonical: &Path) {
    register_at(&registry_path(), canonical);
}

/// Path-parameterized core of [`upsert_branch`].
#[allow(clippy::too_many_arguments)]
fn upsert_branch_at(
    path: &Path,
    canonical: &Path,
    branch: &str,
    branch_key: &str,
    last_indexed_ts: i64,
    head_commit: Option<String>,
    embedder_fingerprint: &str,
) {
    let mut registry = load_from(path);
    let entry = if let Some(existing) = registry.projects.iter_mut().find(|p| p.path == canonical) {
        existing
    } else {
        registry.projects.push(ProjectEntry {
            path: canonical.to_path_buf(),
            project_id: project_id_for_path(canonical),
            display_name: display_name_for_path(canonical),
            branches: Vec::new(),
            embedder_fingerprint: String::new(),
        });
        registry.projects.last_mut().expect("just pushed")
    };
    entry.embedder_fingerprint = embedder_fingerprint.to_string();
    if let Some(existing_branch) = entry
        .branches
        .iter_mut()
        .find(|b| b.branch_key == branch_key)
    {
        existing_branch.branch = branch.to_string();
        existing_branch.last_indexed_ts = last_indexed_ts;
        existing_branch.head_commit = head_commit;
    } else {
        entry.branches.push(BranchEntry {
            branch: branch.to_string(),
            branch_key: branch_key.to_string(),
            last_indexed_ts,
            head_commit,
        });
    }
    save_to(path, &registry);
}

/// Record (upsert) that `branch` of the project at `canonical` was just
/// indexed, stamping `last_indexed_ts` (Unix seconds) and the resolved
/// `head_commit`. Creates the project entry first via [`register`]-equivalent
/// logic if it doesn't exist yet. Available for Wave 2's multi-branch daemon
/// to keep the registry's branch list in sync with what's actually been built.
pub fn upsert_branch(
    canonical: &Path,
    branch: &str,
    branch_key: &str,
    last_indexed_ts: i64,
    head_commit: Option<String>,
    embedder_fingerprint: &str,
) {
    upsert_branch_at(
        &registry_path(),
        canonical,
        branch,
        branch_key,
        last_indexed_ts,
        head_commit,
        embedder_fingerprint,
    );
}

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

    // Every test operates on its own tempdir registry file via the `_at`/
    // `_from`/`_to` internals — the public wrappers only add path resolution
    // (`registry_path()`), so this covers all the logic while guaranteeing no
    // test can ever read, overwrite, or delete a developer's real
    // `~/.semantex/projects.json`. (The old delete-and-restore guard was
    // unsafe: a SIGKILL/panic=abort inside the window destroyed the real
    // file permanently.) No env-var mutation either, so tests stay
    // parallel-safe.
    fn tmp_registry() -> (TempDir, PathBuf) {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("projects.json");
        (tmp, path)
    }

    #[test]
    fn register_and_read_all_round_trip() {
        let (_tmp, reg) = tmp_registry();

        let p1 = PathBuf::from("/tmp/project-one");
        let p2 = PathBuf::from("/tmp/project-two");
        register_at(&reg, &p1);
        register_at(&reg, &p2);
        register_at(&reg, &p1); // duplicate — must not double-register

        let all: Vec<PathBuf> = load_from(&reg)
            .projects
            .into_iter()
            .map(|p| p.path)
            .collect();
        assert_eq!(all.len(), 2);
        assert!(all.contains(&p1));
        assert!(all.contains(&p2));

        let v2 = load_from(&reg);
        assert_eq!(v2.version, 2);
        let entry = v2.projects.iter().find(|p| p.path == p1).unwrap();
        assert_eq!(entry.project_id, project_id_for_path(&p1));
        assert_eq!(entry.display_name, "project-one");
    }

    #[test]
    fn v1_array_is_upgraded_to_v2_on_load() {
        let (_tmp, reg) = tmp_registry();

        let v1_json =
            serde_json::to_string(&vec!["/repo/a".to_string(), "/repo/b".to_string()]).unwrap();
        std::fs::write(&reg, v1_json).unwrap();

        let v2 = load_from(&reg);
        assert_eq!(v2.version, 2);
        assert_eq!(v2.projects.len(), 2);
        assert!(v2.projects.iter().any(|p| p.path == Path::new("/repo/a")));

        // Registering upgrades the persisted file to v2 (versioned object,
        // v1 content preserved).
        register_at(&reg, Path::new("/repo/c"));
        let raw = std::fs::read_to_string(&reg).unwrap();
        let persisted: RegistryV2 = serde_json::from_str(&raw).unwrap();
        assert_eq!(persisted.version, 2);
        assert_eq!(persisted.projects.len(), 3);
    }

    #[test]
    fn upsert_branch_creates_project_and_updates_existing_branch() {
        let (_tmp, reg) = tmp_registry();

        let proj = PathBuf::from("/tmp/branchy-project");
        upsert_branch_at(
            &reg,
            &proj,
            "main",
            "main-abc12345",
            100,
            Some("c1".into()),
            "fp1",
        );
        let v2 = load_from(&reg);
        let entry = v2.projects.iter().find(|p| p.path == proj).unwrap();
        assert_eq!(entry.branches.len(), 1);
        assert_eq!(entry.branches[0].last_indexed_ts, 100);
        assert_eq!(entry.embedder_fingerprint, "fp1");

        // Re-indexing the SAME branch_key updates in place, not append.
        upsert_branch_at(
            &reg,
            &proj,
            "main",
            "main-abc12345",
            200,
            Some("c2".into()),
            "fp2",
        );
        let v2 = load_from(&reg);
        let entry = v2.projects.iter().find(|p| p.path == proj).unwrap();
        assert_eq!(entry.branches.len(), 1);
        assert_eq!(entry.branches[0].last_indexed_ts, 200);
        assert_eq!(entry.branches[0].head_commit, Some("c2".to_string()));
        assert_eq!(entry.embedder_fingerprint, "fp2");

        // A second branch appends rather than replacing.
        upsert_branch_at(&reg, &proj, "develop", "develop-def67890", 50, None, "fp2");
        let v2 = load_from(&reg);
        let entry = v2.projects.iter().find(|p| p.path == proj).unwrap();
        assert_eq!(entry.branches.len(), 2);
    }

    #[test]
    fn save_is_atomic_no_tmp_file_left_behind() {
        let (_tmp, reg) = tmp_registry();
        register_at(&reg, Path::new("/tmp/atomic-project"));

        // The registry file exists and parses; no tmp artifact lingers in
        // the directory (write went through tmp-then-rename).
        assert!(reg.exists());
        let entries: Vec<_> = std::fs::read_dir(reg.parent().unwrap())
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(entries, vec!["projects.json".to_string()], "{entries:?}");
    }

    #[test]
    fn corrupt_registry_loads_as_empty_and_is_replaced_on_next_save() {
        let (_tmp, reg) = tmp_registry();
        std::fs::write(&reg, "{ this is not json").unwrap();
        assert!(load_from(&reg).projects.is_empty());
        register_at(&reg, Path::new("/tmp/recovered"));
        assert_eq!(load_from(&reg).projects.len(), 1);
    }

    #[test]
    fn registry_path_honors_semantex_home_layout() {
        // registry_path() must be `<semantex_home>/projects.json` — the same
        // resolution the rest of the crate uses (gate.rs, models dir), which
        // honors the SEMANTEX_HOME env override. We assert the relationship
        // rather than mutating the env (env mutation is process-global and
        // racy under the parallel test runner).
        assert_eq!(
            registry_path(),
            crate::config::SemantexConfig::semantex_home().join("projects.json")
        );
    }

    #[test]
    fn project_id_is_stable_for_same_path() {
        let p = PathBuf::from("/tmp/stable-id-project");
        assert_eq!(project_id_for_path(&p), project_id_for_path(&p));
        assert_ne!(
            project_id_for_path(&p),
            project_id_for_path(&PathBuf::from("/tmp/other-project"))
        );
    }
}