zacor 0.1.0

Package manager and dispatcher for zr — install, manage, and run modular CLI packages
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
544
545
546
547
548
549
550
551
552
553
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::TempDir;

fn zacor_bin() -> PathBuf {
    let mut path = PathBuf::from(env!("CARGO_BIN_EXE_zacor"));
    if !path.exists() {
        path = PathBuf::from("target/debug/zacor").with_extension(std::env::consts::EXE_EXTENSION);
    }
    path
}

fn zr_bin() -> PathBuf {
    let mut path = PathBuf::from(env!("CARGO_BIN_EXE_zr"));
    if !path.exists() {
        path = PathBuf::from("target/debug/zr").with_extension(std::env::consts::EXE_EXTENSION);
    }
    path
}

fn temp_home() -> TempDir {
    let dir = TempDir::new().unwrap();
    fs::create_dir_all(dir.path().join("modules")).unwrap();
    fs::create_dir_all(dir.path().join("store")).unwrap();
    fs::create_dir_all(dir.path().join("cache")).unwrap();
    fs::create_dir_all(dir.path().join("cache").join("repos")).unwrap();
    fs::create_dir_all(dir.path().join("registries")).unwrap();
    dir
}

fn write_receipt(home: &Path, name: &str, version: &str, active: bool) {
    let receipt = serde_json::json!({
        "schema": 1,
        "current": version,
        "active": active,
        "mode": "command",
        "transport": "local",
        "config": {},
        "versions": {
            version: {
                "source": { "type": "local", "path": "/tmp/test" },
                "installed_at": "2026-03-20T10:30:00Z"
            }
        }
    });
    let path = home.join("modules").join(format!("{}.json", name));
    fs::write(&path, serde_json::to_string_pretty(&receipt).unwrap()).unwrap();
}

fn write_definition(home: &Path, name: &str, version: &str, yaml: &str) {
    let dir = home.join("store").join(name).join(version);
    fs::create_dir_all(&dir).unwrap();
    fs::write(dir.join("package.yaml"), yaml).unwrap();
}

// ─── 12.3: Definition-only install ──────────────────────────────────

#[test]
fn test_definition_only_install() {
    let home = temp_home();
    let tmp = TempDir::new().unwrap();
    let yaml = "name: my-wrapper\nversion: \"1.0.0\"\ncommands:\n  default:\n    invoke: \"echo hello\"\n    description: test\n";
    let yaml_path = tmp.path().join("my-wrapper.yaml");
    fs::write(&yaml_path, yaml).unwrap();

    let output = Command::new(zacor_bin())
        .args(["install", &yaml_path.to_string_lossy()])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor install");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "install should succeed: {}",
        stderr
    );
    assert!(stderr.contains("installed my-wrapper"));

    // Verify receipt exists
    let receipt_path = home.path().join("modules").join("my-wrapper.json");
    assert!(receipt_path.exists(), "receipt should exist");

    // Verify definition in store
    let def_path = home.path().join("store").join("my-wrapper").join("1.0.0").join("package.yaml");
    assert!(def_path.exists(), "definition should be in store");

    // Verify no binary
    let store_dir = home.path().join("store").join("my-wrapper").join("1.0.0");
    let files: Vec<_> = fs::read_dir(&store_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name() != "package.yaml")
        .collect();
    assert!(files.is_empty(), "no binary should exist for definition-only package");
}

// ─── 12.5: Version removal ──────────────────────────────────────────

#[test]
fn test_version_removal_switches_to_highest() {
    let home = temp_home();
    // Create receipt with multiple versions
    let receipt = serde_json::json!({
        "schema": 1,
        "current": "14.1.0",
        "active": true,
        "mode": "command",
        "transport": "local",
        "config": {},
        "versions": {
            "2.0.0": { "source": { "type": "local", "path": "/tmp/test" }, "installed_at": "2026-01-01T00:00:00Z" },
            "13.0.0": { "source": { "type": "local", "path": "/tmp/test" }, "installed_at": "2026-02-01T00:00:00Z" },
            "14.1.0": { "source": { "type": "local", "path": "/tmp/test" }, "installed_at": "2026-03-01T00:00:00Z" }
        }
    });
    fs::write(
        home.path().join("modules/tool.json"),
        serde_json::to_string_pretty(&receipt).unwrap(),
    ).unwrap();

    // Create store dirs
    for v in &["2.0.0", "13.0.0", "14.1.0"] {
        write_definition(home.path(), "tool", v, "name: tool\nversion: \"1.0.0\"\ncommands:\n  default:\n    description: test\n");
    }

    let output = Command::new(zacor_bin())
        .args(["remove", "tool@14.1.0"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor remove");

    assert!(output.status.success(), "remove should succeed: {}", String::from_utf8_lossy(&output.stderr));

    // Verify current switched to 13.0.0 (not 2.0.0 via lexicographic)
    let receipt_content = fs::read_to_string(home.path().join("modules/tool.json")).unwrap();
    let r: serde_json::Value = serde_json::from_str(&receipt_content).unwrap();
    assert_eq!(r["current"].as_str().unwrap(), "13.0.0");
}

// ─── 12.9: Package name validation ──────────────────────────────────

#[test]
fn test_package_name_validation_in_install() {
    let home = temp_home();
    let tmp = TempDir::new().unwrap();
    // Create a valid yaml but with invalid package name
    let yaml = "name: My_Tool\nversion: \"1.0.0\"\ncommands:\n  default:\n    description: test\n";
    let yaml_path = tmp.path().join("wrapper.yaml");
    fs::write(&yaml_path, yaml).unwrap();

    let output = Command::new(zacor_bin())
        .args(["install", &yaml_path.to_string_lossy()])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor install");

    assert!(!output.status.success(), "install should fail for invalid package name");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("invalid") || stderr.contains("must start with a lowercase"), "got: {}", stderr);
}

// ─── 12.13: Receipt forward-compat ──────────────────────────────────

#[test]
fn test_receipt_forward_compat() {
    let home = temp_home();
    let receipt = serde_json::json!({
        "schema": 99,
        "current": "1.0.0",
        "active": true,
        "mode": "command",
        "transport": "local",
        "config": {},
        "versions": {
            "1.0.0": { "source": { "type": "local", "path": "/tmp/test" }, "installed_at": "2026-03-20T10:30:00Z" }
        }
    });
    fs::write(
        home.path().join("modules/future-tool.json"),
        serde_json::to_string_pretty(&receipt).unwrap(),
    ).unwrap();

    // Dispatch should fail with upgrade guidance
    let output = Command::new(zr_bin())
        .args(["future-tool"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zr");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(!output.status.success());
    assert!(stderr.contains("newer version") || stderr.contains("upgrade"), "got: {}", stderr);
}

// ─── 12.15: No default command error ────────────────────────────────

#[test]
fn test_no_default_command() {
    let home = temp_home();
    write_receipt(home.path(), "my-tool", "1.0.0", true);
    write_definition(
        home.path(),
        "my-tool",
        "1.0.0",
        "name: my-tool\nversion: \"1.0.0\"\ncommands:\n  transcribe:\n    description: transcribe audio\n  translate:\n    description: translate audio\n",
    );

    let output = Command::new(zr_bin())
        .args(["my-tool"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zr");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(!output.status.success());
    assert!(
        stderr.contains("requires a subcommand") || stderr.contains("subcommand"),
        "should indicate a subcommand is required, got: {}",
        stderr
    );
}

// ─── 12.16: Corrupt package.yaml ────────────────────────────────────

#[test]
fn test_corrupt_package_yaml() {
    let home = temp_home();
    write_receipt(home.path(), "broken", "1.0.0", true);
    // No package.yaml in store

    let output = Command::new(zr_bin())
        .args(["broken"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zr");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(!output.status.success());
    assert!(
        stderr.contains("not found in store") || stderr.contains("reinstall"),
        "should suggest reinstall, got: {}",
        stderr
    );
}

// ─── Basic CLI tests ────────────────────────────────────────────────

#[test]
fn test_zr_unknown_flag() {
    let home = temp_home();
    let output = Command::new(zr_bin())
        .args(["--unknown-flag"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zr");

    assert!(!output.status.success());
}

#[test]
fn test_zr_works_with_nonexistent_home() {
    let tmp = TempDir::new().unwrap();
    let home = tmp.path().join("nonexistent_zr_home");

    let output = Command::new(zr_bin())
        .args(["nonexistent-package"])
        .env("ZR_HOME", home.to_str().unwrap())
        .output()
        .expect("failed to run zr");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("not found"), "got: {}", stderr);
}

// ─── Shell completions ──────────────────────────────────────────────

#[test]
fn test_completions_valid_shells() {
    let home = temp_home();
    for shell in &["bash", "zsh", "fish", "powershell"] {
        let output = Command::new(zacor_bin())
            .args(["completions", shell])
            .env("ZR_HOME", home.path().to_str().unwrap())
            .output()
            .expect("failed to run zacor completions");

        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(output.status.success(), "shell '{}' failed", shell);
        assert!(!stdout.is_empty(), "shell '{}' produced no output", shell);
    }
}

#[test]
fn test_completions_invalid_shell() {
    let home = temp_home();
    let output = Command::new(zacor_bin())
        .args(["completions", "invalid"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor completions");

    assert!(!output.status.success());
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("unsupported shell"),
        "should mention unsupported shell, got: {}",
        stderr
    );
}

// ─── Daemon integration tests ────────────────────────────────────────

use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;

fn daemon_request(addr: &str, req: &serde_json::Value) -> serde_json::Value {
    let mut stream = TcpStream::connect(addr).expect("failed to connect to daemon");
    stream.set_read_timeout(Some(std::time::Duration::from_secs(5))).ok();
    let json = serde_json::to_string(req).unwrap();
    writeln!(stream, "{}", json).unwrap();
    stream.flush().unwrap();
    let mut reader = BufReader::new(stream);
    let mut line = String::new();
    reader.read_line(&mut line).expect("failed to read daemon response");
    serde_json::from_str(line.trim()).expect("failed to parse daemon response")
}

#[test]
#[ignore] // Uses fixed port 19100, must run in isolation: cargo test -- --ignored test_daemon_start
fn test_daemon_start_ping_status_stop() {
    let home = temp_home();

    // Start daemon in background
    let mut child = Command::new(zacor_bin())
        .args(["daemon", "start"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("failed to spawn daemon");

    // Wait for daemon to start
    let addr = "127.0.0.1:19100";
    let start = std::time::Instant::now();
    let mut connected = false;
    while start.elapsed() < std::time::Duration::from_secs(5) {
        if TcpStream::connect(addr).is_ok() {
            connected = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    assert!(connected, "daemon should start and accept connections");

    // Ping
    let resp = daemon_request(addr, &serde_json::json!({"request": "ping"}));
    assert_eq!(resp["ok"], true);

    // Status (no services)
    let resp = daemon_request(addr, &serde_json::json!({"request": "status"}));
    assert_eq!(resp["ok"], true);
    assert_eq!(resp["services"].as_array().unwrap().len(), 0);

    // Shutdown
    let resp = daemon_request(addr, &serde_json::json!({"request": "shutdown"}));
    assert_eq!(resp["ok"], true);

    // Wait for daemon to exit
    let status = child.wait().expect("failed to wait for daemon");
    assert!(status.success(), "daemon should exit cleanly");
    // Allow port to be released
    std::thread::sleep(std::time::Duration::from_millis(100));
}

#[test]
fn test_daemon_stop_when_not_running() {
    let home = temp_home();
    let output = Command::new(zacor_bin())
        .args(["daemon", "stop"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor daemon stop");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("not running"), "got: {}", stdout);
}

#[test]
fn test_daemon_status_when_not_running() {
    let home = temp_home();
    let output = Command::new(zacor_bin())
        .args(["daemon", "status"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor daemon status");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("not running"), "got: {}", stdout);
}

// ─── Registry CLI integration tests ──────────────────────────────────

fn write_config(home: &Path, toml_content: &str) {
    fs::write(home.join("config.toml"), toml_content).unwrap();
}

fn create_mock_registry(home: &Path, registry_name: &str, packages: &[(&str, &str)]) {
    let reg_dir = home.join("registries").join(registry_name);
    for (pkg_name, index_toml) in packages {
        let pkg_dir = reg_dir.join("packages").join(pkg_name);
        fs::create_dir_all(&pkg_dir).unwrap();
        fs::write(pkg_dir.join("index.toml"), index_toml).unwrap();
    }
    // Touch sync marker so it's not stale
    fs::write(reg_dir.join(".zr-last-sync"), "").unwrap();
}

#[test]
fn test_registry_cli_add_list_remove() {
    let home = temp_home();

    // Add
    let output = Command::new(zacor_bin())
        .args(["registry", "add", "https://github.com/my-org/zr-packages", "--name", "company"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor registry add");
    assert!(output.status.success(), "add should succeed: {}", String::from_utf8_lossy(&output.stderr));

    // List
    let output = Command::new(zacor_bin())
        .args(["registry", "list"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor registry list");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("company"), "list should show company registry, got: {}", stdout);

    // Add duplicate should fail
    let output = Command::new(zacor_bin())
        .args(["registry", "add", "https://example.com/other", "--name", "company"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor registry add");
    assert!(!output.status.success(), "duplicate add should fail");

    // Remove
    let output = Command::new(zacor_bin())
        .args(["registry", "remove", "company"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor registry remove");
    assert!(output.status.success(), "remove should succeed: {}", String::from_utf8_lossy(&output.stderr));

    // List should be empty
    let output = Command::new(zacor_bin())
        .args(["registry", "list"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor registry list");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("no registries"), "list should be empty after remove, got: {}", stdout);

    // Remove non-existent should fail
    let output = Command::new(zacor_bin())
        .args(["registry", "remove", "nonexistent"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor registry remove");
    assert!(!output.status.success(), "remove nonexistent should fail");
}

#[test]
fn test_install_bare_name_from_mock_registry() {
    let home = temp_home();

    write_config(home.path(), "[[registries]]\nname = \"test-reg\"\nurl = \"https://example.com/test\"\n");

    create_mock_registry(home.path(), "test-reg", &[
        ("mock-tool", "schema = 1\ndescription = \"A mock tool\"\n\n[[versions]]\nversion = \"1.0.0\"\nrelease = \"nonexistent/mock-tool\"\n"),
    ]);

    // Install by bare name — should resolve from registry, then fail at GitHub download
    let output = Command::new(zacor_bin())
        .args(["install", "mock-tool"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor install");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("resolved mock-tool v1.0.0"), "should resolve from registry, got: {}", stderr);
}

#[test]
fn test_install_bare_name_with_version_from_mock_registry() {
    let home = temp_home();

    write_config(home.path(), "[[registries]]\nname = \"test-reg\"\nurl = \"https://example.com/test\"\n");

    create_mock_registry(home.path(), "test-reg", &[
        ("mock-tool", "schema = 1\n\n[[versions]]\nversion = \"0.1.0\"\nrelease = \"nonexistent/mock-tool\"\n\n[[versions]]\nversion = \"0.2.0\"\nrelease = \"nonexistent/mock-tool\"\n"),
    ]);

    // Install specific version
    let output = Command::new(zacor_bin())
        .args(["install", "mock-tool@0.1.0"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor install");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("resolved mock-tool v0.1.0"), "should resolve v0.1.0, got: {}", stderr);
}

#[test]
#[ignore] // Requires network and git
fn test_install_git_url() {
    let home = temp_home();

    let output = Command::new(zacor_bin())
        .args(["install", "https://github.com/zacor-packages/p-zr-core.git"])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run zacor install");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(output.status.success(), "git install should succeed: {}", stderr);
}

#[test]
#[ignore] // Requires network and git
fn test_monorepo_git_install_reuses_cache() {
    let home = temp_home();
    let url = "https://github.com/zacor-packages/p-zr-core.git";

    let output = Command::new(zacor_bin())
        .args(["install", url])
        .env("ZR_HOME", home.path().to_str().unwrap())
        .output()
        .expect("failed to run first install");
    assert!(output.status.success(), "first install should succeed: {}", String::from_utf8_lossy(&output.stderr));

    let repos_dir = home.path().join("cache").join("repos");
    let repo_count = fs::read_dir(&repos_dir)
        .map(|d| d.count())
        .unwrap_or(0);
    assert_eq!(repo_count, 1, "should have exactly one cached repo");
}