ccd-cli 1.0.0-alpha.2

Bootstrap and validate Continuous Context Development repositories
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
use std::fs;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::process::ExitCode;
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{bail, Context, Result};
use rusqlite::Connection;
use serde::{Deserialize, Serialize};

use crate::output::CommandReport;
use crate::paths::state::StateLayout;
use crate::profile;
use crate::repo::marker as repo_marker;

// ---------------------------------------------------------------------------
// Import schema
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct CodemapInputEntry {
    path: String,
    when_to_use: String,
    #[serde(default)]
    public_types: Vec<String>,
    #[serde(default)]
    public_functions: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CodemapEntry {
    pub path: String,
    pub when_to_use: String,
    pub public_types: Vec<String>,
    pub public_functions: Vec<String>,
    pub imported_at: i64,
}

// ---------------------------------------------------------------------------
// Reports
// ---------------------------------------------------------------------------

#[derive(Serialize)]
pub struct CodemapImportReport {
    command: &'static str,
    ok: bool,
    imported: usize,
    path: String,
}

impl CommandReport for CodemapImportReport {
    fn exit_code(&self) -> ExitCode {
        if self.ok {
            ExitCode::SUCCESS
        } else {
            ExitCode::FAILURE
        }
    }

    fn render_text(&self) {
        if self.ok {
            eprintln!("codemap: imported {} entries", self.imported);
            eprintln!("codemap: database at {}", self.path);
        } else {
            eprintln!("codemap: import failed");
        }
    }
}

#[derive(Serialize)]
pub struct CodemapStatusReport {
    command: &'static str,
    ok: bool,
    total_files: usize,
    oldest_imported_at: Option<i64>,
    newest_imported_at: Option<i64>,
    db_path: String,
}

impl CommandReport for CodemapStatusReport {
    fn exit_code(&self) -> ExitCode {
        if self.ok {
            ExitCode::SUCCESS
        } else {
            ExitCode::FAILURE
        }
    }

    fn render_text(&self) {
        eprintln!("codemap: {} files indexed", self.total_files);
        if let Some(oldest) = self.oldest_imported_at {
            eprintln!("codemap: oldest import: {oldest}");
        }
        if let Some(newest) = self.newest_imported_at {
            eprintln!("codemap: newest import: {newest}");
        }
        eprintln!("codemap: database at {}", self.db_path);
    }
}

#[derive(Serialize)]
pub struct CodemapQueryReport {
    command: &'static str,
    ok: bool,
    entries: Vec<CodemapEntry>,
}

impl CommandReport for CodemapQueryReport {
    fn exit_code(&self) -> ExitCode {
        if self.ok {
            ExitCode::SUCCESS
        } else {
            ExitCode::FAILURE
        }
    }

    fn render_text(&self) {
        for entry in &self.entries {
            eprintln!("{}: {}", entry.path, entry.when_to_use);
        }
        eprintln!("codemap: {} entries", self.entries.len());
    }
}

// ---------------------------------------------------------------------------
// Database helpers
// ---------------------------------------------------------------------------

const CODEMAP_DB_SCHEMA_VERSION: u32 = 1;

fn open_codemap_db(path: &Path) -> Result<Connection> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).with_context(|| {
            format!(
                "failed to create codemap db directory: {}",
                parent.display()
            )
        })?;
    }
    let conn = Connection::open(path)
        .with_context(|| format!("failed to open codemap database at {}", path.display()))?;
    conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;")
        .context("failed to set codemap database PRAGMAs")?;
    migrate_codemap_db(&conn)?;
    Ok(conn)
}

fn migrate_codemap_db(conn: &Connection) -> Result<()> {
    let version: u32 = conn
        .pragma_query_value(None, "user_version", |row| row.get(0))
        .context("failed to read codemap user_version")?;
    if version == CODEMAP_DB_SCHEMA_VERSION {
        return Ok(());
    }
    if version > CODEMAP_DB_SCHEMA_VERSION {
        bail!(
            "codemap database has user_version {version}, but this build only supports up to {CODEMAP_DB_SCHEMA_VERSION}"
        );
    }
    // version == 0: fresh database, create from scratch
    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS files (
            path TEXT PRIMARY KEY,
            when_to_use TEXT NOT NULL,
            public_types TEXT NOT NULL DEFAULT '[]',
            public_functions TEXT NOT NULL DEFAULT '[]',
            imported_at INTEGER NOT NULL
        );",
    )
    .context("failed to create codemap schema")?;
    conn.pragma_update(None, "user_version", CODEMAP_DB_SCHEMA_VERSION)
        .context("failed to set codemap user_version")?;
    Ok(())
}

fn import_entries(conn: &Connection, entries: &[CodemapInputEntry]) -> Result<usize> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .context("system clock before UNIX epoch")?
        .as_secs() as i64;

    let tx = conn.unchecked_transaction()?;
    let mut count = 0usize;
    {
        let mut stmt = tx.prepare(
            "INSERT OR REPLACE INTO files (path, when_to_use, public_types, public_functions, imported_at)
             VALUES (?1, ?2, ?3, ?4, ?5)",
        )?;

        for entry in entries {
            let types_json = serde_json::to_string(&entry.public_types)?;
            let funcs_json = serde_json::to_string(&entry.public_functions)?;
            stmt.execute(rusqlite::params![
                entry.path,
                entry.when_to_use,
                types_json,
                funcs_json,
                now,
            ])?;
            count += 1;
        }
    }
    tx.commit()?;
    Ok(count)
}

/// Compute the exclusive upper bound for a prefix range query.
///
/// Increments the last byte of the prefix so that `path >= prefix AND path < upper`
/// matches exactly the rows whose path starts with `prefix`. If the prefix
/// consists entirely of `\xFF` bytes (pathological case), falls back to an
/// unreachable sentinel that is lexicographically above any valid UTF-8 path.
fn prefix_upper_bound(prefix: &str) -> String {
    let mut bytes = prefix.as_bytes().to_vec();
    // Walk backwards, incrementing the last byte that won't overflow.
    while let Some(last) = bytes.last_mut() {
        if *last < 0xFF {
            *last += 1;
            return String::from_utf8_lossy(&bytes).into_owned();
        }
        bytes.pop();
    }
    // Every byte was 0xFF — use a high sentinel.
    "\u{FFFF}".to_owned()
}

fn query_entries_from_db(
    conn: &Connection,
    prefix: Option<&str>,
    limit: usize,
) -> Result<Vec<CodemapEntry>> {
    let mut entries = Vec::new();

    match prefix {
        Some(pfx) => {
            // Use a range query instead of LIKE to avoid metacharacter
            // injection (%, _) and get correct prefix semantics.
            let upper = prefix_upper_bound(pfx);
            let mut stmt = conn.prepare(
                "SELECT path, when_to_use, public_types, public_functions, imported_at
                 FROM files WHERE path >= ?1 AND path < ?2 ORDER BY path LIMIT ?3",
            )?;
            let rows = stmt.query_map(rusqlite::params![pfx, upper, limit as i64], map_row)?;
            for row in rows {
                entries.push(row?);
            }
        }
        None => {
            let mut stmt = conn.prepare(
                "SELECT path, when_to_use, public_types, public_functions, imported_at
                 FROM files ORDER BY path LIMIT ?1",
            )?;
            let rows = stmt.query_map(rusqlite::params![limit as i64], map_row)?;
            for row in rows {
                entries.push(row?);
            }
        }
    }

    Ok(entries)
}

fn map_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<CodemapEntry> {
    let path: String = row.get(0)?;
    let types_json: String = row.get(2)?;
    let funcs_json: String = row.get(3)?;
    let public_types: Vec<String> = serde_json::from_str(&types_json).map_err(|e| {
        rusqlite::Error::FromSqlConversionFailure(2, rusqlite::types::Type::Text, Box::new(e))
    })?;
    let public_functions: Vec<String> = serde_json::from_str(&funcs_json).map_err(|e| {
        rusqlite::Error::FromSqlConversionFailure(3, rusqlite::types::Type::Text, Box::new(e))
    })?;
    Ok(CodemapEntry {
        path,
        when_to_use: row.get(1)?,
        public_types,
        public_functions,
        imported_at: row.get(4)?,
    })
}

fn count_entries_from_db(conn: &Connection) -> Result<usize> {
    let count: i64 = conn.query_row("SELECT COUNT(*) FROM files", [], |row| row.get(0))?;
    Ok(count as usize)
}

fn status_from_db(conn: &Connection) -> Result<(usize, Option<i64>, Option<i64>)> {
    let count = count_entries_from_db(conn)?;
    if count == 0 {
        return Ok((0, None, None));
    }
    let oldest: i64 = conn.query_row("SELECT MIN(imported_at) FROM files", [], |row| row.get(0))?;
    let newest: i64 = conn.query_row("SELECT MAX(imported_at) FROM files", [], |row| row.get(0))?;
    Ok((count, Some(oldest), Some(newest)))
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

fn validate_entry(entry: &CodemapInputEntry) -> Result<()> {
    if entry.path.is_empty() {
        bail!("codemap entry has empty path");
    }
    let p = Path::new(&entry.path);
    for component in p.components() {
        match component {
            Component::ParentDir => {
                bail!("codemap entry path must not contain `..`: {}", entry.path);
            }
            Component::RootDir | Component::Prefix(_) => {
                bail!(
                    "codemap entry path must be relative, got absolute: {}",
                    entry.path
                );
            }
            _ => {}
        }
    }
    if entry.when_to_use.is_empty() {
        bail!("codemap entry for `{}` has empty when_to_use", entry.path);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Resolve helpers
// ---------------------------------------------------------------------------

fn resolve_db_path(repo_root: &Path, explicit_profile: Option<&str>) -> Result<PathBuf> {
    let profile = profile::resolve(explicit_profile)?;
    let layout = StateLayout::resolve(repo_root, profile)?;
    let marker = repo_marker::load(repo_root)?.ok_or_else(|| {
        anyhow::anyhow!(
            "no CCD marker found at {}; run `ccd attach` first",
            repo_root.join(repo_marker::MARKER_FILE).display()
        )
    })?;
    layout.codemap_db_path(&marker.locality_id)
}

// ---------------------------------------------------------------------------
// Public command implementations
// ---------------------------------------------------------------------------

pub fn import(repo_root: &Path, explicit_profile: Option<&str>) -> Result<CodemapImportReport> {
    let db_path = resolve_db_path(repo_root, explicit_profile)?;

    let mut input = String::new();
    std::io::stdin()
        .read_to_string(&mut input)
        .context("failed to read codemap JSON from stdin")?;

    let entries: Vec<CodemapInputEntry> =
        serde_json::from_str(&input).context("failed to parse codemap JSON from stdin")?;

    for entry in &entries {
        validate_entry(entry)?;
    }

    let conn = open_codemap_db(&db_path)?;
    let count = import_entries(&conn, &entries)?;

    Ok(CodemapImportReport {
        command: "codemap import",
        ok: true,
        imported: count,
        path: db_path.display().to_string(),
    })
}

pub fn status(repo_root: &Path, explicit_profile: Option<&str>) -> Result<CodemapStatusReport> {
    let db_path = resolve_db_path(repo_root, explicit_profile)?;
    let db_path_str = db_path.display().to_string();

    if !db_path.exists() {
        return Ok(CodemapStatusReport {
            command: "codemap status",
            ok: true,
            total_files: 0,
            oldest_imported_at: None,
            newest_imported_at: None,
            db_path: db_path_str,
        });
    }

    let conn = open_codemap_db(&db_path)?;
    let (total, oldest, newest) = status_from_db(&conn)?;

    Ok(CodemapStatusReport {
        command: "codemap status",
        ok: true,
        total_files: total,
        oldest_imported_at: oldest,
        newest_imported_at: newest,
        db_path: db_path_str,
    })
}

pub fn query(
    repo_root: &Path,
    explicit_profile: Option<&str>,
    prefix: Option<&str>,
    limit: usize,
) -> Result<Vec<CodemapEntry>> {
    let db_path = resolve_db_path(repo_root, explicit_profile)?;

    if !db_path.exists() {
        return Ok(Vec::new());
    }

    let conn = open_codemap_db(&db_path)?;
    query_entries_from_db(&conn, prefix, limit)
}

pub fn query_report(
    repo_root: &Path,
    explicit_profile: Option<&str>,
    prefix: Option<&str>,
    limit: usize,
) -> Result<CodemapQueryReport> {
    let entries = query(repo_root, explicit_profile, prefix, limit)?;
    Ok(CodemapQueryReport {
        command: "codemap query",
        ok: true,
        entries,
    })
}

/// Count entries in an existing codemap DB (used by health diagnostics).
pub fn count_entries_at(db_path: &Path) -> Result<usize> {
    let conn = Connection::open(db_path)
        .with_context(|| format!("failed to open codemap database at {}", db_path.display()))?;
    conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;")
        .context("failed to set codemap database PRAGMAs")?;
    migrate_codemap_db(&conn)?;
    count_entries_from_db(&conn)
}