litvc 1.2.1

Lit - The agentic-first distributed version control system. A complete Git replacement designed for AI agents first and humans second.
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
//! SSH transport for remote Lit repositories
//!
//! Communicates with a remote `lit serve --stdio` instance over SSH.
//! The SSH client spawns the system `ssh` command and communicates
//! via newline-delimited JSON over stdin/stdout pipes.

use crate::core::{Object, ObjectHash};
use crate::network::transport::RemoteRef;
use crate::storage::ObjectStore;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::process::{Child, Command, Stdio};

/// Check whether a URL uses the SSH transport
pub fn is_ssh_url(url: &str) -> bool {
    url.starts_with("ssh://") || (url.contains('@') && url.contains(':') && !url.contains("://"))
}

/// Parsed SSH URL components
#[derive(Debug, Clone)]
pub struct SshUrl {
    pub user: Option<String>,
    pub host: String,
    pub port: Option<u16>,
    pub path: String,
}

/// Parse an SSH URL into its components.
///
/// Supports two formats:
/// - `ssh://[user@]host[:port]/path`
/// - `user@host:path` (SCP-style)
pub fn parse_ssh_url(url: &str) -> Result<SshUrl, String> {
    if let Some(rest) = url.strip_prefix("ssh://") {
        // ssh://[user@]host[:port]/path
        let (userhost, path) = rest
            .split_once('/')
            .ok_or_else(|| format!("Invalid SSH URL (missing path): {}", url))?;

        let (user, hostport) = if let Some((u, hp)) = userhost.split_once('@') {
            (Some(u.to_string()), hp)
        } else {
            (None, userhost)
        };

        let (host, port) = if let Some((h, p)) = hostport.split_once(':') {
            let port_num = p
                .parse::<u16>()
                .map_err(|_| format!("Invalid port in SSH URL: {}", p))?;
            (h.to_string(), Some(port_num))
        } else {
            (hostport.to_string(), None)
        };

        if host.is_empty() {
            return Err(format!("Empty host in SSH URL: {}", url));
        }

        Ok(SshUrl {
            user,
            host,
            port,
            path: format!("/{}", path),
        })
    } else if url.contains('@') && url.contains(':') && !url.contains("://") {
        // user@host:path (SCP-style)
        let (user_host, path) = url
            .split_once(':')
            .ok_or_else(|| format!("Invalid SCP-style SSH URL: {}", url))?;
        let (user, host) = user_host
            .split_once('@')
            .ok_or_else(|| format!("Invalid SCP-style SSH URL: {}", url))?;

        if host.is_empty() || path.is_empty() {
            return Err(format!("Invalid SCP-style SSH URL: {}", url));
        }

        Ok(SshUrl {
            user: Some(user.to_string()),
            host: host.to_string(),
            port: None,
            path: path.to_string(),
        })
    } else {
        Err(format!(
            "Not an SSH URL: {}. Use ssh://[user@]host[:port]/path or user@host:path",
            url
        ))
    }
}

/// An SSH pipe connection to a remote `lit serve --stdio` instance
pub struct SshPipe {
    child: Child,
    reader: BufReader<std::process::ChildStdout>,
    writer: BufWriter<std::process::ChildStdin>,
}

impl SshPipe {
    /// Open an SSH pipe to a remote repository
    pub fn open(parsed: &SshUrl) -> Result<Self, String> {
        let mut cmd = Command::new("ssh");

        // Disable interactive prompts for batch mode
        cmd.arg("-o").arg("BatchMode=yes");

        if let Some(port) = parsed.port {
            cmd.arg("-p").arg(port.to_string());
        }

        let target = if let Some(ref user) = parsed.user {
            format!("{}@{}", user, parsed.host)
        } else {
            parsed.host.clone()
        };
        cmd.arg(&target);

        // Remote command: cd to repo path and run lit serve --stdio
        let remote_cmd = format!("cd {} && lit serve --stdio", shell_escape(&parsed.path));
        cmd.arg(remote_cmd);

        cmd.stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        let mut child = cmd
            .spawn()
            .map_err(|e| format!("Failed to spawn ssh: {}", e))?;

        let stdout = child.stdout.take().ok_or("Failed to capture ssh stdout")?;
        let stdin = child.stdin.take().ok_or("Failed to capture ssh stdin")?;

        Ok(SshPipe {
            child,
            reader: BufReader::new(stdout),
            writer: BufWriter::new(stdin),
        })
    }

    /// Open a pipe directly to a `lit serve --stdio` process (for testing without SSH)
    pub fn open_local(repo_path: &std::path::Path) -> Result<Self, String> {
        // Find the lit binary: look in the same directory as the current executable,
        // which covers both `cargo run` and `cargo test` scenarios.
        let current_exe = std::env::current_exe()
            .map_err(|e| format!("Cannot find current executable: {}", e))?;
        let exe_dir = current_exe
            .parent()
            .ok_or("Cannot determine executable directory")?;

        // In test builds, the test binary is in target/debug/deps/ but
        // the lit binary is in target/debug/
        let lit_exe = if exe_dir.ends_with("deps") {
            exe_dir
                .parent()
                .unwrap()
                .join("lit")
                .with_extension(std::env::consts::EXE_EXTENSION)
        } else {
            exe_dir
                .join("lit")
                .with_extension(std::env::consts::EXE_EXTENSION)
        };

        if !lit_exe.exists() {
            return Err(format!(
                "lit binary not found at {}. Run `cargo build` first.",
                lit_exe.display()
            ));
        }

        let mut child = Command::new(lit_exe)
            .arg("serve")
            .arg("--stdio")
            .current_dir(repo_path)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| format!("Failed to spawn lit serve --stdio: {}", e))?;

        let stdout = child.stdout.take().ok_or("Failed to capture stdout")?;
        let stdin = child.stdin.take().ok_or("Failed to capture stdin")?;

        Ok(SshPipe {
            child,
            reader: BufReader::new(stdout),
            writer: BufWriter::new(stdin),
        })
    }

    /// Send a request and read the response
    fn request(
        &mut self,
        method: &str,
        path: &str,
        body: &str,
    ) -> Result<(u16, serde_json::Value), String> {
        let req = serde_json::json!({
            "method": method,
            "path": path,
            "body": body,
        });
        writeln!(self.writer, "{}", req)
            .map_err(|e| format!("Failed to write to SSH pipe: {}", e))?;
        self.writer
            .flush()
            .map_err(|e| format!("Failed to flush SSH pipe: {}", e))?;

        let mut line = String::new();
        self.reader
            .read_line(&mut line)
            .map_err(|e| format!("Failed to read from SSH pipe: {}", e))?;

        if line.is_empty() {
            return Err("SSH pipe closed unexpectedly".to_string());
        }

        let resp: serde_json::Value = serde_json::from_str(line.trim())
            .map_err(|e| format!("Invalid JSON from SSH pipe: {}", e))?;

        let status = resp.get("status").and_then(|v| v.as_u64()).unwrap_or(500) as u16;

        // The body field is a JSON string that needs to be parsed
        let body_str = resp.get("body").and_then(|v| v.as_str()).unwrap_or("{}");

        let body_json: serde_json::Value =
            serde_json::from_str(body_str).unwrap_or_else(|_| serde_json::json!({"raw": body_str}));

        Ok((status, body_json))
    }

    /// Close the SSH pipe gracefully.
    /// The `Drop` implementation will kill the process if not already exited.
    pub fn close(&mut self) {
        // Signal EOF to the remote process by closing our stdin handle,
        // using a zero-byte write attempt followed by checking the child status.
        let _ = self.child.try_wait();
    }
}

impl Drop for SshPipe {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

/// Check response status and extract error messages
fn check_status(status: u16, body: &serde_json::Value) -> Result<(), String> {
    if status >= 400 {
        let msg = body
            .get("error")
            .and_then(|e| e.get("message"))
            .and_then(|m| m.as_str())
            .or_else(|| body.get("raw").and_then(|v| v.as_str()))
            .unwrap_or("Unknown error");
        Err(format!("SSH transport error ({}): {}", status, msg))
    } else {
        Ok(())
    }
}

/// List refs from a remote server via SSH pipe
pub fn list_refs_ssh(pipe: &mut SshPipe, kind: &str) -> Result<Vec<RemoteRef>, String> {
    let path = format!("/api/v1/transport/refs?kind={}", kind);
    let (status, body) = pipe.request("GET", &path, "")?;
    check_status(status, &body)?;

    let refs = body
        .get("refs")
        .and_then(|v| v.as_array())
        .ok_or("Invalid refs response from SSH")?;

    let mut result = Vec::new();
    for r in refs {
        let kind = r.get("kind").and_then(|v| v.as_str()).unwrap_or("heads");
        let name = r
            .get("name")
            .and_then(|v| v.as_str())
            .ok_or("Missing ref name")?;
        let hash = r
            .get("hash")
            .and_then(|v| v.as_str())
            .ok_or("Missing ref hash")?;
        result.push(RemoteRef {
            kind: kind.to_string(),
            name: name.to_string(),
            hash: hash.to_string(),
        });
    }
    Ok(result)
}

/// Read a branch ref from a remote server via SSH pipe
pub fn read_ref_ssh(pipe: &mut SshPipe, branch: &str) -> Result<String, String> {
    let path = format!("/api/v1/transport/refs/heads/{}", branch);
    let (status, body) = pipe.request("GET", &path, "")?;
    check_status(status, &body)?;
    body.get("hash")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
        .ok_or("Missing hash in SSH response".to_string())
}

/// Read HEAD from a remote server via SSH pipe
pub fn read_head_ssh(pipe: &mut SshPipe) -> Result<String, String> {
    let (status, body) = pipe.request("GET", "/api/v1/transport/head", "")?;
    check_status(status, &body)?;
    body.get("head")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
        .ok_or("Missing head in SSH response".to_string())
}

/// Update a branch ref on a remote server via SSH pipe
pub fn update_ref_ssh(
    pipe: &mut SshPipe,
    branch: &str,
    hash: &str,
    force: bool,
) -> Result<(), String> {
    let path = format!("/api/v1/transport/refs/heads/{}", branch);
    let body = serde_json::json!({"hash": hash, "force": force}).to_string();
    let (status, resp) = pipe.request("PUT", &path, &body)?;
    check_status(status, &resp)
}

/// Negotiate which objects are needed via SSH pipe
pub fn negotiate_ssh(
    pipe: &mut SshPipe,
    wants: &[String],
    haves: &[String],
) -> Result<Vec<ObjectHash>, String> {
    let body = serde_json::json!({"wants": wants, "haves": haves}).to_string();
    let (status, resp) = pipe.request("POST", "/api/v1/transport/negotiate", &body)?;
    check_status(status, &resp)?;

    let needed = resp
        .get("needed")
        .and_then(|v| v.as_array())
        .ok_or("Invalid negotiate response from SSH")?;

    Ok(needed
        .iter()
        .filter_map(|v| v.as_str())
        .map(|s| ObjectHash::from_hex(s.to_string()))
        .collect())
}

/// Download objects from a remote server via SSH pipe
pub fn download_objects_ssh(
    pipe: &mut SshPipe,
    local_store: &ObjectStore,
    hashes: &[ObjectHash],
) -> Result<usize, String> {
    let mut count = 0;
    for hash in hashes {
        if local_store.exists(hash) {
            continue;
        }
        let path = format!("/api/v1/transport/objects/{}", hash.as_str());
        let (status, body) = pipe.request("GET", &path, "")?;
        check_status(status, &body)?;

        let b64_data = body
            .get("data")
            .and_then(|v| v.as_str())
            .ok_or("Missing object data in SSH response")?;

        let compressed = base64_decode(b64_data)?;

        use std::io::Read as _;
        let mut decoder = flate2::read::ZlibDecoder::new(&compressed[..]);
        let mut raw = Vec::new();
        decoder
            .read_to_end(&mut raw)
            .map_err(|e| format!("Decompress error: {}", e))?;

        let obj = Object::from_bytes(&raw)?;
        local_store.write(&obj)?;
        count += 1;
    }
    Ok(count)
}

/// Upload objects from a local store to a remote server via SSH pipe
pub fn upload_objects_ssh(
    pipe: &mut SshPipe,
    local_store: &ObjectStore,
    hashes: &[ObjectHash],
) -> Result<usize, String> {
    // Upload in batches of 50
    let mut total = 0;
    for chunk in hashes.chunks(50) {
        let mut objects_json = Vec::new();
        for hash in chunk {
            let obj = local_store.read(hash)?;
            let data = obj.to_bytes();
            use std::io::Write as _;
            let mut encoder =
                flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
            encoder
                .write_all(&data)
                .map_err(|e| format!("Compress error: {}", e))?;
            let compressed = encoder
                .finish()
                .map_err(|e| format!("Compress error: {}", e))?;
            let b64 = base64_encode(&compressed);
            objects_json.push(serde_json::json!({"hash": hash.as_str(), "data": b64}));
        }

        let body = serde_json::json!({"objects": objects_json}).to_string();
        let (status, resp) = pipe.request("POST", "/api/v1/transport/objects", &body)?;
        check_status(status, &resp)?;
        total += resp.get("written").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
    }
    Ok(total)
}

// ── Base64 helpers ──

fn base64_encode(data: &[u8]) -> String {
    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
        let triple = (b0 << 16) | (b1 << 8) | b2;
        out.push(CHARS[((triple >> 18) & 0x3F) as usize] as char);
        out.push(CHARS[((triple >> 12) & 0x3F) as usize] as char);
        if chunk.len() > 1 {
            out.push(CHARS[((triple >> 6) & 0x3F) as usize] as char);
        } else {
            out.push('=');
        }
        if chunk.len() > 2 {
            out.push(CHARS[(triple & 0x3F) as usize] as char);
        } else {
            out.push('=');
        }
    }
    out
}

fn base64_decode(input: &str) -> Result<Vec<u8>, String> {
    fn val(c: u8) -> Result<u32, String> {
        match c {
            b'A'..=b'Z' => Ok((c - b'A') as u32),
            b'a'..=b'z' => Ok((c - b'a' + 26) as u32),
            b'0'..=b'9' => Ok((c - b'0' + 52) as u32),
            b'+' => Ok(62),
            b'/' => Ok(63),
            b'=' => Ok(0),
            _ => Err(format!("Invalid base64 character: {}", c as char)),
        }
    }
    let bytes: Vec<u8> = input.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
    let mut out = Vec::with_capacity(bytes.len() * 3 / 4);
    for chunk in bytes.chunks(4) {
        if chunk.len() < 4 {
            return Err("Invalid base64 length".to_string());
        }
        let a = val(chunk[0])?;
        let b = val(chunk[1])?;
        let c = val(chunk[2])?;
        let d = val(chunk[3])?;
        let triple = (a << 18) | (b << 12) | (c << 6) | d;
        out.push(((triple >> 16) & 0xFF) as u8);
        if chunk[2] != b'=' {
            out.push(((triple >> 8) & 0xFF) as u8);
        }
        if chunk[3] != b'=' {
            out.push((triple & 0xFF) as u8);
        }
    }
    Ok(out)
}

/// Escape a path for use in a shell command
fn shell_escape(s: &str) -> String {
    // Use single quotes, escaping any single quotes in the string
    format!("'{}'", s.replace('\'', "'\\''"))
}