carryctx 0.7.0

Local-first memory for coding agents — resume tasks, checkpoints, and context across windows, sessions, and worktrees.
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Regression tests for CTX-0070: reachable panics (#94), --dry-run contract
//! violations (#95), and output-envelope violations (#96).
//!
//! Each test drives the real binary in a disposable Git repository.

mod common;

use serde_json::Value;

fn run(dir: &std::path::Path, bin: &std::path::Path, args: &[&str]) -> std::process::Output {
    common::run_cmd(dir, bin, args)
}

fn stdout_str(output: &std::process::Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr_str(output: &std::process::Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

fn exit_code(output: &std::process::Output) -> i32 {
    output.status.code().unwrap_or(-1)
}

/// Parse the success envelope emitted on stdout and assert its shape.
fn assert_success_envelope(output: &std::process::Output, command: &str) -> Value {
    let stdout = stdout_str(output);
    let parsed: Value = serde_json::from_str(stdout.trim())
        .unwrap_or_else(|e| panic!("stdout must be a valid JSON envelope ({e}): {stdout}"));
    assert_eq!(
        parsed["success"], true,
        "envelope must be successful: {parsed}"
    );
    assert_eq!(parsed["command"], command, "envelope command label");
    parsed
}

/// Parse the error envelope emitted on stderr and return it.
fn assert_error_envelope(output: &std::process::Output, command: &str) -> Value {
    let stderr = stderr_str(output);
    let last_line = stderr
        .lines()
        .rev()
        .find(|l| l.trim_start().starts_with('{'))
        .unwrap_or_else(|| panic!("stderr must contain a JSON envelope: {stderr}"));
    let parsed: Value = serde_json::from_str(last_line.trim())
        .unwrap_or_else(|e| panic!("stderr must be valid JSON ({e}): {stderr}"));
    assert_eq!(
        parsed["success"], false,
        "must be an error envelope: {parsed}"
    );
    assert_eq!(parsed["command"], command, "envelope command label");
    parsed
}

// ── #94: reachable panics ────────────────────────────────────────────────

#[test]
fn dry_run_json_task_list_renders_normally_instead_of_panicking() {
    let (dir, bin) = common::setup_test_project("dryrun_task_list");
    common::init_and_agent(&dir, &bin);
    run(&dir, &bin, &["task", "create", "--title", "中文标题任务"]);

    // Regression: `--json --dry-run task list` hit `unreachable!()` (SIGABRT,
    // exit 134). Non-mutating subcommands must render normally.
    let output = run(&dir, &bin, &["--json", "--dry-run", "task", "list"]);
    assert_eq!(
        exit_code(&output),
        0,
        "exit must be 0, got {} (stderr: {})",
        exit_code(&output),
        stderr_str(&output)
    );
    let envelope = assert_success_envelope(&output, "task.list");
    let tasks = envelope["data"].as_array().expect("task list data array");
    assert!(
        tasks.iter().any(|t| t["title"] == "中文标题任务"),
        "list contents must render under dry-run"
    );

    // task show is equally non-mutating.
    let show = run(
        &dir,
        &bin,
        &[
            "--json",
            "--dry-run",
            "task",
            "show",
            tasks[0]["display_id"].as_str().unwrap(),
        ],
    );
    assert_eq!(exit_code(&show), 0, "task show must render under dry-run");
}

#[test]
fn markdown_renderers_survive_multibyte_content() {
    let (dir, bin) = common::setup_test_project("markdown_multibyte");
    common::init_and_agent(&dir, &bin);

    let created = run(
        &dir,
        &bin,
        &["--json", "task", "create", "--title", "中文任务"],
    );
    let envelope: Value =
        serde_json::from_str(stdout_str(&created).trim()).expect("create envelope");
    let display_id = envelope["data"]["display_id"]
        .as_str()
        .expect("display_id")
        .to_string();

    // Progress content that crosses the 40-byte boundary mid-character.
    run(
        &dir,
        &bin,
        &[
            "progress",
            "note",
            "这是一条非常长的中文进度内容用来触发字节截断边界崩溃测试内容继续加长",
            "--task",
            &display_id,
        ],
    );

    // Decision title crossing the same boundary.
    run(
        &dir,
        &bin,
        &[
            "decision",
            "add",
            "--title",
            "这是一个非常长的中文决策标题用于触发字符边界截断回归测试补充长度",
        ],
    );

    // A session so session-list has rows with agent ids.
    run(&dir, &bin, &["session", "start", "--agent", "tester"]);

    for args in [
        vec![
            "--format",
            "markdown",
            "progress",
            "list",
            "--task",
            &display_id,
        ],
        vec!["--format", "markdown", "decision", "list"],
        vec!["--format", "markdown", "session", "list"],
        vec!["--format", "markdown", "event", "list"],
        vec!["--format", "markdown", "task", "list"],
    ] {
        let output = run(&dir, &bin, &args);
        assert_eq!(
            exit_code(&output),
            0,
            "{args:?} must not abort; stderr={}",
            stderr_str(&output)
        );
        let out = stdout_str(&output);
        assert!(
            out.starts_with('#'),
            "{args:?} must render a markdown table"
        );
        assert!(
            !out.contains("Error:"),
            "{args:?} must not print an error document: {out}"
        );
    }
}

#[test]
fn markdown_truncation_clips_on_char_boundaries() {
    let (dir, bin) = common::setup_test_project("markdown_boundary");
    common::init_and_agent(&dir, &bin);

    let created = run(&dir, &bin, &["--json", "task", "create", "--title", "t"]);
    let envelope: Value =
        serde_json::from_str(stdout_str(&created).trim()).expect("create envelope");
    let display_id = envelope["data"]["display_id"].as_str().unwrap().to_string();

    run(
        &dir,
        &bin,
        &[
            "progress",
            "note",
            "🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀",
            "--task",
            &display_id,
        ],
    );
    let output = run(
        &dir,
        &bin,
        &[
            "--format",
            "markdown",
            "progress",
            "list",
            "--task",
            &display_id,
        ],
    );
    assert_eq!(exit_code(&output), 0, "emoji content must not abort");
}

// ── #95: --dry-run contract ──────────────────────────────────────────────

#[test]
fn dry_run_json_mutating_commands_emit_stdout_envelopes() {
    let (dir, bin) = common::setup_test_project("dryrun_envelopes");
    common::init_and_agent(&dir, &bin);
    // Snapshot the scaffolded project config so we can prove no dry-run
    // mutated it (init writes a full default config.toml).
    let config_path = dir.join(".carryctx").join("config.toml");
    let config_before = std::fs::read_to_string(&config_path).unwrap();
    let created = run(&dir, &bin, &["--json", "task", "create", "--title", "t1"]);
    let envelope: Value =
        serde_json::from_str(stdout_str(&created).trim()).expect("create envelope");
    let display_id = envelope["data"]["display_id"].as_str().unwrap().to_string();

    let cases: Vec<(Vec<&str>, &str)> = vec![
        (
            vec![
                "--json",
                "--dry-run",
                "worktree",
                "create",
                &display_id,
                "--path",
                "wt-dryrun",
            ],
            "worktree.create",
        ),
        (
            vec![
                "--json",
                "--dry-run",
                "session",
                "start",
                "--agent",
                "tester",
            ],
            "session.start",
        ),
        (
            vec![
                "--json",
                "--dry-run",
                "checkpoint",
                "--note",
                "n",
                "--no-git",
            ],
            "checkpoint.create",
        ),
        (
            vec!["--json", "--dry-run", "decision", "add", "--title", "d1"],
            "decision.add",
        ),
        (
            vec![
                "--json",
                "--dry-run",
                "progress",
                "todo",
                "do things",
                "--task",
                &display_id,
            ],
            "progress.todo",
        ),
    ];

    for (args, command) in &cases {
        let output = run(&dir, &bin, args);
        assert_eq!(
            exit_code(&output),
            0,
            "{command} dry-run must succeed; stderr={}",
            stderr_str(&output)
        );
        let envelope = assert_success_envelope(&output, command);
        assert_eq!(
            envelope["data"]["operation"]["applied"], false,
            "{command} dry-run envelope must carry operation.applied=false"
        );
        assert!(
            stderr_str(&output).contains("[dry-run]"),
            "{command} text note must still appear on stderr"
        );
    }

    // The dry-runs above must not have mutated anything.
    assert!(
        !dir.join("wt-dryrun").exists(),
        "worktree create dry-run must not create directories"
    );
    let config_after = std::fs::read_to_string(&config_path).unwrap();
    assert_eq!(
        config_before, config_after,
        "config set dry-run must not write the file"
    );
}

#[test]
fn dry_run_graph_add_node_writes_nothing() {
    let (dir, bin) = common::setup_test_project("dryrun_graph");
    common::init_and_agent(&dir, &bin);

    let probe = format!("probe-node-{}", unique_suffix());
    let output = run(
        &dir,
        &bin,
        &[
            "--json",
            "--dry-run",
            "graph",
            "add-node",
            "--node-type",
            "file",
            "--name",
            &probe,
        ],
    );
    assert_eq!(exit_code(&output), 0, "dry-run add-node must succeed");
    let envelope = assert_success_envelope(&output, "graph.add-node");
    assert_eq!(envelope["data"]["operation"]["applied"], false);

    let export = run(&dir, &bin, &["graph", "export", "--type", "mermaid"]);
    let exported = stdout_str(&export);
    assert!(
        !exported.contains(&probe),
        "node must not be written during dry-run: {exported}"
    );

    // Control: a real add-node IS persisted and visible.
    run(
        &dir,
        &bin,
        &["graph", "add-node", "--node-type", "file", "--name", &probe],
    );
    let export = run(&dir, &bin, &["graph", "export", "--type", "mermaid"]);
    assert!(
        stdout_str(&export).contains(&probe),
        "control: real add-node must persist"
    );
}

#[test]
fn graph_dry_run_gates_link_and_scan_but_not_export() {
    let (dir, bin) = common::setup_test_project("dryrun_graph_more");
    common::init_and_agent(&dir, &bin);

    let link = run(
        &dir,
        &bin,
        &["--dry-run", "graph", "link", "a", "b", "uses"],
    );
    assert_eq!(exit_code(&link), 0);
    assert!(stderr_str(&link).contains("[dry-run]"));
    assert!(
        stdout_str(&link).is_empty(),
        "text mode prints nothing on stdout"
    );

    let scan = run(&dir, &bin, &["--dry-run", "graph", "scan", "--dir", "."]);
    assert_eq!(exit_code(&scan), 0);
    assert!(stderr_str(&scan).contains("[dry-run]"));

    // Read-only subcommands still render normally.
    let export = run(
        &dir,
        &bin,
        &["--dry-run", "graph", "export", "--type", "ascii"],
    );
    assert_eq!(exit_code(&export), 0);
    assert!(
        stderr_str(&export).is_empty(),
        "non-mutating arms are not gated"
    );
}

#[test]
fn dry_run_json_team_error_produces_error_envelope() {
    let (dir, bin) = common::setup_test_project("dryrun_team_err");
    common::init_and_agent(&dir, &bin);

    // Regression: `.map_err(|e| e.exit_code)?` exited 7 with empty stdout AND
    // empty stderr.
    let output = run(
        &dir,
        &bin,
        &[
            "--json",
            "--dry-run",
            "team",
            "member",
            "add",
            "missing-team",
            "--agent",
            "alice",
        ],
    );
    assert_eq!(exit_code(&output), 7);
    let envelope = assert_error_envelope(&output, "team.member_add");
    assert_eq!(envelope["error"]["code"], "RESOURCE_NOT_FOUND");
}

#[test]
fn dry_run_json_task_team_set_error_produces_error_envelope() {
    let (dir, bin) = common::setup_test_project("dryrun_task_team_err");
    common::init_and_agent(&dir, &bin);

    let output = run(
        &dir,
        &bin,
        &[
            "--json",
            "--dry-run",
            "task",
            "team",
            "set",
            "TASK-DOES-NOT-EXIST",
            "--team",
            "some-team",
        ],
    );
    assert_eq!(exit_code(&output), 7);
    let envelope = assert_error_envelope(&output, "task.team_set");
    assert_eq!(envelope["error"]["code"], "RESOURCE_NOT_FOUND");

    let unset = run(
        &dir,
        &bin,
        &[
            "--json",
            "--dry-run",
            "task",
            "team",
            "unset",
            "ALSO-MISSING",
        ],
    );
    assert_eq!(exit_code(&unset), 7);
    assert_error_envelope(&unset, "task.team_unset");
}

// ── #96: output envelopes ────────────────────────────────────────────────

#[test]
fn checkpoint_show_missing_renders_resource_not_found_envelope() {
    let (dir, bin) = common::setup_test_project("checkpoint_show_missing");
    common::init_and_agent(&dir, &bin);

    let text = run(
        &dir,
        &bin,
        &["checkpoint", "show", "01NOSUCHCHECKPOINT000000"],
    );
    assert_eq!(exit_code(&text), 7);
    let err = stderr_str(&text);
    assert!(
        err.contains("not found") || err.contains("RESOURCE_NOT_FOUND"),
        "text mode must explain the failure: {err}"
    );
    assert!(
        !stdout_str(&text).contains("Error"),
        "error text must not land on stdout"
    );

    let json = run(
        &dir,
        &bin,
        &["--json", "checkpoint", "show", "01NOSUCHCHECKPOINT000000"],
    );
    assert_eq!(exit_code(&json), 7);
    let envelope = assert_error_envelope(&json, "checkpoint.show");
    assert_eq!(envelope["error"]["code"], "RESOURCE_NOT_FOUND");
}

#[test]
fn project_register_unregister_fail_honestly() {
    let (dir, bin) = common::setup_test_project("project_register_honest");
    common::init_and_agent(&dir, &bin);

    let cases: Vec<(Vec<&str>, &str)> = vec![
        (
            vec!["project", "register", "/tmp/somewhere"],
            "project.register",
        ),
        (
            vec!["project", "unregister", "SOMEPROJECT"],
            "project.unregister",
        ),
    ];

    for (args, command) in &cases {
        let text = run(&dir, &bin, args);
        assert_ne!(exit_code(&text), 0, "{command} must not fake success");
        let out = stdout_str(&text);
        assert!(
            !out.contains("\"status\""),
            "{command} must not emit a fabricated success payload"
        );
        assert!(
            !stderr_str(&text).is_empty(),
            "{command} must explain itself on stderr"
        );

        let mut json_args = vec!["--json"];
        json_args.extend_from_slice(args);
        let full = run(&dir, &bin, &json_args);
        assert_eq!(
            exit_code(&full),
            10,
            "{command} must exit UNSUPPORTED(10); stdout={}",
            stdout_str(&full)
        );
        let envelope = assert_error_envelope(&full, command);
        assert_eq!(envelope["error"]["code"], "UNSUPPORTED_OPERATION");
    }
}

#[test]
fn preset_list_json_serializes_lockfile_presets() {
    let (dir, bin) = common::setup_test_project("preset_list_json");
    common::init_and_agent(&dir, &bin);

    std::fs::create_dir_all(dir.join(".carryctx")).unwrap();
    std::fs::write(
        dir.join(".carryctx").join("presets.lock"),
        "version = 1\n\n[presets.carryctx-core]\nversion = \"0.5.8\"\nsource = \"packs/carryctx-core\"\nintegrity = \"sha256-deadbeef\"\n[presets.carryctx-core.permissions_granted]\nrequires_filesystem = true\nrequires_network = false\nrequires_env = []\n\n[presets.zeta-pack]\nversion = \"1.1.0\"\nsource = \"local/zeta\"\nintegrity = \"sha256-cafebabe\"\n[presets.zeta-pack.permissions_granted]\nrequires_filesystem = false\nrequires_network = true\nrequires_env = [\"KEY\"]\n",
    )
    .unwrap();

    let output = run(&dir, &bin, &["--json", "preset", "list"]);
    assert_eq!(exit_code(&output), 0);
    let envelope = assert_success_envelope(&output, "preset.list");
    let presets = envelope["data"]["presets"]
        .as_array()
        .expect("presets array");
    assert_eq!(presets.len(), 2, "lockfile presets must be serialized");
    assert_eq!(presets[0]["name"], "carryctx-core", "sorted by name");
    assert_eq!(presets[1]["name"], "zeta-pack");
    assert_eq!(presets[0]["version"], "0.5.8");
    assert_eq!(presets[0]["permissionsGranted"]["filesystem"], true);

    // Text mode keeps working.
    let text = run(&dir, &bin, &["preset", "list"]);
    let out = stdout_str(&text);
    assert!(
        out.contains("carryctx-core"),
        "text list shows presets: {out}"
    );
}

#[test]
fn preset_show_emits_valid_escaped_json() {
    let (dir, bin) = common::setup_test_project("preset_show_escape");
    common::init_and_agent(&dir, &bin);

    std::fs::create_dir_all(dir.join(".carryctx")).unwrap();
    std::fs::write(
        dir.join(".carryctx").join("tricky.md"),
        "# Title with \"quotes\"\n\nLine\twith special 中文 content\n",
    )
    .unwrap();

    let output = run(&dir, &bin, &["--json", "preset", "show", "tricky.md"]);
    assert_eq!(exit_code(&output), 0, "{}", stderr_str(&output));
    let envelope = assert_success_envelope(&output, "preset.show");
    let content = envelope["data"]["content"]
        .as_str()
        .expect("content string");
    assert!(
        content.contains(r#""quotes""#) && content.contains("中文"),
        "content must round-trip unescaped through JSON parsing"
    );

    // Missing presets produce RESOURCE_NOT_FOUND instead of a bare message.
    let missing = run(&dir, &bin, &["--json", "preset", "show", "absent-pack"]);
    assert_eq!(exit_code(&missing), 7);
    let envelope = assert_error_envelope(&missing, "preset.show");
    assert_eq!(envelope["error"]["code"], "RESOURCE_NOT_FOUND");
}

#[test]
fn outside_git_repo_failure_prints_message_in_both_modes() {
    let unique = std::env::temp_dir().join(format!("carryctx_nogit_{}", unique_suffix()));
    std::fs::create_dir_all(&unique).unwrap();
    let bin = common::test_binary();

    // Text mode: previously silent with exit 4.
    let text = common::run_cmd(&unique, &bin, &["task", "list"]);
    assert_eq!(exit_code(&text), 4, "git discovery failure exits GIT(4)");
    let err = stderr_str(&text);
    assert!(
        err.contains("Error") && (err.contains("git") || err.contains("Git")),
        "text mode must surface the failure: {err}"
    );

    // JSON mode: standard error envelope on stderr.
    let json = common::run_cmd(&unique, &bin, &["--json", "task", "list"]);
    assert_eq!(exit_code(&json), 4);
    let envelope = assert_error_envelope(&json, "runtime.open");
    assert_eq!(envelope["error"]["code"], "GIT_ERROR");

    let _ = std::fs::remove_dir_all(&unique);
}

// ── helpers ──────────────────────────────────────────────────────────────

fn unique_suffix() -> String {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("clock after epoch")
        .as_nanos();
    format!("{nanos:x}")
}