carryctx 0.8.1

Local-first project lifecycle control for coding agents and human collaborators.
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
//! Regression tests for CTX-0070 issue #97: `config get/set/unset` TOML
//! handling. Dotted keys must land in the right table, values keep their
//! types, reads query the typed config, and scope flags are enforced.

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)
}

fn json_envelope(output: &std::process::Output) -> Value {
    serde_json::from_str(stdout_str(output).trim()).unwrap_or_else(|e| {
        panic!(
            "stdout must be a JSON envelope ({e}): {}",
            stdout_str(output)
        )
    })
}

fn json_envelope_stderr(output: &std::process::Output) -> Value {
    serde_json::from_str(stderr_str(output).trim()).unwrap_or_else(|e| {
        panic!(
            "stderr must be a JSON error envelope ({e}): {}",
            stderr_str(output)
        )
    })
}

fn project_with_config(name: &str, initial: &str) -> (std::path::PathBuf, std::path::PathBuf) {
    let (dir, bin) = common::setup_test_project(name);
    common::init_and_agent(&dir, &bin);
    let cfg_dir = dir.join(".carryctx");
    std::fs::create_dir_all(&cfg_dir).unwrap();
    std::fs::write(cfg_dir.join("config.toml"), initial).unwrap();
    (dir, bin)
}

fn read_project_config(dir: &std::path::Path) -> String {
    std::fs::read_to_string(dir.join(".carryctx").join("config.toml")).unwrap()
}

#[test]
fn set_dotted_key_under_existing_table_keeps_tables_intact() {
    // Regression: `config set task.strict_completion true` appended at EOF and
    // landed INSIDE the last `[verification]` table.
    let (dir, bin) = project_with_config(
        "cfg_set_dotted",
        "# managed header\n[verification]\ncommands = [\"cargo test\"]\n",
    );

    let out = run(
        &dir,
        &bin,
        &[
            "--json",
            "config",
            "set",
            "--cfg-project",
            "task.strict_completion",
            "true",
        ],
    );
    assert_eq!(
        exit_code(&out),
        0,
        "set must succeed; stderr={}",
        stderr_str(&out)
    );
    let envelope = json_envelope(&out);
    assert_eq!(envelope["data"]["value"], true, "typed preview in envelope");

    let file = read_project_config(&dir);
    assert!(
        file.contains("# managed header"),
        "comments preserved:\n{file}"
    );
    assert!(
        file.contains("commands = [\"cargo test\"]"),
        "existing table content preserved:\n{file}"
    );
    // strict_completion must not appear in the [verification] section body.
    let verification_body = file.split("[verification]").nth(1).expect("table present");
    let verification_body = match verification_body.split_once('[') {
        Some((before_next_table, _)) => before_next_table,
        None => verification_body,
    };
    assert!(
        !verification_body.contains("strict_completion"),
        "key must not leak into [verification]:\n{file}"
    );

    // The typed value is readable through the loader.
    let get = run(
        &dir,
        &bin,
        &["--json", "config", "get", "task.strict_completion"],
    );
    assert_eq!(exit_code(&get), 0);
    let envelope = json_envelope(&get);
    assert_eq!(envelope["data"]["value"], true, "bool round-trips typed");
}

#[test]
fn set_and_get_nested_keys_round_trip() {
    let (dir, bin) = project_with_config("cfg_roundtrip", "");

    // bool
    run(
        &dir,
        &bin,
        &[
            "--json",
            "config",
            "set",
            "--cfg-project",
            "context.include_git_status",
            "false",
        ],
    );
    // int
    run(
        &dir,
        &bin,
        &[
            "--json",
            "config",
            "set",
            "--cfg-project",
            "context.max_events",
            "250",
        ],
    );
    // string with spaces and quotes
    run(
        &dir,
        &bin,
        &[
            "--json",
            "config",
            "set",
            "--cfg-project",
            "project.name",
            "My \"Demo\" 项目 🚀",
        ],
    );

    for (key, expected) in [
        ("context.include_git_status", Value::Bool(false)),
        ("context.max_events", Value::Number(250.into())),
        (
            "project.name",
            Value::String("My \"Demo\" 项目 🚀".to_string()),
        ),
    ] {
        let get = run(&dir, &bin, &["--json", "config", "get", key]);
        assert_eq!(exit_code(&get), 0, "{key} get failed: {}", stderr_str(&get));
        let envelope = json_envelope(&get);
        assert_eq!(envelope["data"]["key"], key);
        assert_eq!(envelope["data"]["value"], expected, "{key} round-trip");
    }
}

#[test]
fn set_overwrites_scalar_in_place_without_duplicating() {
    let (dir, bin) = project_with_config("cfg_overwrite", "[context]\nmax_events = 100\n");
    run(
        &dir,
        &bin,
        &[
            "--json",
            "config",
            "set",
            "--cfg-project",
            "context.max_events",
            "7",
        ],
    );
    let file = read_project_config(&dir);
    assert!(!file.contains("100"), "old value replaced:\n{file}");
    assert_eq!(
        file.matches("max_events").count(),
        1,
        "no duplicates:\n{file}"
    );

    let get = run(
        &dir,
        &bin,
        &["--json", "config", "get", "context.max_events"],
    );
    assert_eq!(json_envelope(&get)["data"]["value"], 7);
}

#[test]
fn unset_removes_only_the_target_leaf() {
    let (dir, bin) = project_with_config(
        "cfg_unset",
        "[task]\nstrict_completion = true\nsingle_active_task_per_agent = false\n\n[verification]\ncommands = []\n",
    );

    let out = run(
        &dir,
        &bin,
        &[
            "--json",
            "config",
            "unset",
            "--cfg-project",
            "task.strict_completion",
        ],
    );
    assert_eq!(exit_code(&out), 0, "{}", stderr_str(&out));
    let file = read_project_config(&dir);
    assert!(!file.contains("strict_completion"), "leaf removed:\n{file}");
    assert!(
        file.contains("single_active_task_per_agent"),
        "sibling kept:\n{file}"
    );
    assert!(
        file.contains("[verification]"),
        "other tables kept:\n{file}"
    );

    // Unsetting an absent key succeeds without creating the file.
    let absent = run(
        &dir,
        &bin,
        &["--json", "config", "unset", "--global", "never.set.key"],
    );
    assert_eq!(exit_code(&absent), 0);
}

#[test]
fn get_queries_typed_config_not_raw_lines() {
    // Regression: line-prefix matching returned empty for nested keys and the
    // wrong hit on prefix collisions.
    let (dir, bin) = project_with_config(
        "cfg_get_typed",
        "[task]\nstrict_completion = false\n\n[git]\nmain_branch = \"trunk\"\n",
    );

    let get = run(
        &dir,
        &bin,
        &["--json", "config", "get", "task.strict_completion"],
    );
    assert_eq!(exit_code(&get), 0);
    assert_eq!(
        json_envelope(&get)["data"]["value"],
        false,
        "nested dotted key must resolve"
    );

    // Prefix collision: 'task' vs 'task_prefix' style names.
    let collision = run(&dir, &bin, &["--json", "config", "get", "proj"]);
    assert_eq!(exit_code(&collision), 0);
    assert_eq!(
        json_envelope(&collision)["data"]["value"],
        Value::Null,
        "unknown/prefix keys return null, not a wrong line"
    );

    // Whole-table lookup works too.
    let table = run(&dir, &bin, &["--json", "config", "get", "git"]);
    let value = json_envelope(&table)["data"]["value"].clone();
    assert_eq!(
        value["main_branch"], "trunk",
        "table keys resolve as objects"
    );
}

#[test]
fn scope_flags_are_enforced_with_clear_errors() {
    let (dir, bin) = project_with_config("cfg_scope", "");

    // --dry-run emits a stdout envelope with operation.applied=false and
    // leaves the file untouched.
    let before = read_project_config(&dir);
    let dry = run(
        &dir,
        &bin,
        &[
            "--json",
            "--dry-run",
            "config",
            "set",
            "--cfg-project",
            "context.max_events",
            "500",
        ],
    );
    assert_eq!(exit_code(&dry), 0);
    let envelope = json_envelope(&dry);
    assert_eq!(envelope["command"], "config.set");
    assert_eq!(envelope["data"]["operation"]["applied"], false);
    assert_eq!(
        read_project_config(&dir),
        before,
        "config set dry-run must not write the file"
    );

    // No scope: clear error instead of silent exit 2.
    let none = run(&dir, &bin, &["--json", "config", "set", "a.b", "c"]);
    assert_eq!(exit_code(&none), 2);
    let stderr = stderr_str(&none);
    assert!(
        stderr.contains("--global") && stderr.contains("--cfg-project"),
        "error must name the scopes: {stderr}"
    );

    let none_text = run(&dir, &bin, &["config", "set", "a.b", "c"]);
    assert_eq!(exit_code(&none_text), 2);
    assert!(
        !stderr_str(&none_text).is_empty(),
        "text mode gets a message too"
    );

    // Multiple scopes rejected as well.
    let both = run(
        &dir,
        &bin,
        &[
            "--json",
            "config",
            "set",
            "--global",
            "--cfg-project",
            "a.b",
            "c",
        ],
    );
    assert_eq!(exit_code(&both), 2);

    // --local is explicitly rejected because nothing reads local.toml yet.
    let local = run(
        &dir,
        &bin,
        &[
            "--json",
            "config",
            "set",
            "--local",
            "agent.default_name",
            "x",
        ],
    );
    assert_eq!(exit_code(&local), 10, "rejected as unsupported");
    assert!(
        stderr_str(&local).contains("local.toml"),
        "rejection explains why: {}",
        stderr_str(&local)
    );
    assert!(
        !dir.join(".carryctx").join("local.toml").exists(),
        "no orphan local.toml may be written"
    );

    let unset_local = run(&dir, &bin, &["--json", "config", "unset", "--local", "a.b"]);
    assert_eq!(exit_code(&unset_local), 10);
}

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

    // Replace the scaffolded config file with a directory: read_to_string on
    // a directory fails even when running as root, unlike a chmod-000 file.
    let cfg = dir.join(".carryctx").join("config.toml");
    std::fs::remove_file(&cfg).unwrap();
    std::fs::create_dir_all(&cfg).unwrap();

    let list = run(&dir, &bin, &["--json", "config", "list"]);
    assert_ne!(exit_code(&list), 0, "unreadable file must fail loudly");
    assert!(
        !stderr_str(&list).is_empty(),
        "failure must carry a message"
    );
}

/// CTX-0082 / issue #108: `config set` used to accept type-mismatched
/// values, after which EVERY command in the project failed CONFIGURATION_ERROR
/// rc=6 — including config get/set themselves. The typed schema gate must
/// reject the write (VALIDATION_FAILED rc=8), leave file bytes unchanged,
/// and keep all project commands working.
#[test]
fn set_rejects_type_mismatch_without_bricking_project_commands() {
    let (dir, bin) = project_with_config(
        "cfg_typed_gate",
        "[verification]\ncommands = [\"cargo test\"]\n",
    );

    let out = run(
        &dir,
        &bin,
        &[
            "--json",
            "config",
            "set",
            "--cfg-project",
            "task.strict_completion",
            "notabool",
        ],
    );
    assert_eq!(
        exit_code(&out),
        8,
        "type-mismatched write must exit 8; stderr={}",
        stderr_str(&out)
    );
    let envelope = json_envelope_stderr(&out);
    assert_eq!(envelope["success"], false);
    assert_eq!(
        envelope["error"]["code"],
        "VALIDATION_FAILED",
        "{}",
        stderr_str(&out)
    );
    let message = envelope["error"]["message"].as_str().unwrap_or_default();
    assert!(
        message.contains("task.strict_completion"),
        "must name the offending key: {message}"
    );
    assert!(
        message.to_lowercase().contains("fix or remove"),
        "must carry a recovery hint: {message}"
    );

    // File bytes are untouched…
    assert_eq!(
        read_project_config(&dir),
        "[verification]\ncommands = [\"cargo test\"]\n"
    );
    // …and no command is bricked afterwards.
    let list = run(&dir, &bin, &["--json", "config", "list"]);
    assert_eq!(exit_code(&list), 0, "{}", stderr_str(&list));
}

#[test]
fn set_accepts_valid_typed_values_end_to_end() {
    let (dir, bin) = project_with_config(
        "cfg_typed_ok",
        "[verification]\ncommands = [\"cargo test\"]\n",
    );

    for (key, value) in [
        ("task.strict_completion", "true"),
        ("task.list_limit", "300"),
        ("session.stale_after", "3h"),
    ] {
        let out = run(
            &dir,
            &bin,
            &["--json", "config", "set", "--cfg-project", key, value],
        );
        assert_eq!(
            exit_code(&out),
            0,
            "set {key}={value} must succeed; stderr={}",
            stderr_str(&out)
        );
    }

    let get = run(&dir, &bin, &["--json", "config", "get", "task.list_limit"]);
    assert_eq!(exit_code(&get), 0);
    assert_eq!(json_envelope(&get)["data"]["value"], 300);

    let validate = run(&dir, &bin, &["--json", "config", "validate"]);
    assert_eq!(exit_code(&validate), 0, "{}", stderr_str(&validate));
}