defect-config 0.1.0-alpha.4

Layered TOML configuration loading and merging for the defect agent.
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
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
use super::*;

use std::fs;

use tempfile::TempDir;

/// Write a profile at `<root>/.config/defect/agents/<name>/` (user) or
/// `<root>/proj/.defect/agents/<name>/` (project).
fn write_profile(agents_dir: &Path, name: &str, config_toml: &str, system_md: Option<&str>) {
    let dir = agents_dir.join(name);
    fs::create_dir_all(&dir).expect("mkdir profile");
    fs::write(dir.join("config.toml"), config_toml).expect("write config.toml");
    if let Some(md) = system_md {
        fs::write(dir.join("system.md"), md).expect("write system.md");
    }
}

/// Write a single-file profile to `<agents_dir>/<name>.md`.
fn write_single_file(agents_dir: &Path, name: &str, contents: &str) {
    fs::create_dir_all(agents_dir).expect("mkdir agents");
    fs::write(agents_dir.join(format!("{name}.md")), contents).expect("write .md");
}

/// Create a repo root containing `.git` (so that `find_repo_root` hits it), returning
/// `(tmp, repo_root)`.
fn repo(tmp: &TempDir) -> PathBuf {
    let root = tmp.path().join("proj");
    fs::create_dir_all(root.join(".git")).expect("mkdir .git");
    root
}

fn opts_with(tmp: &TempDir, repo_root: &Path) -> LoadConfigOptions {
    LoadConfigOptions {
        cwd: repo_root.to_path_buf(),
        xdg_config_home: Some(tmp.path().join("xdg")),
        ..LoadConfigOptions::default()
    }
}

#[test]
fn discovers_project_and_user_profiles() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);

    let user_agents = tmp.path().join("xdg/defect/agents");
    write_profile(
        &user_agents,
        "userbot",
        "description = \"a user-layer agent\"\n",
        Some("you are userbot"),
    );

    let project_agents = repo_root.join(".defect/agents");
    write_profile(
        &project_agents,
        "reviewer",
        "description = \"review diffs\"\n[tools]\nallow = [\"read_file\"]\n",
        Some("you are reviewer"),
    );

    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert_eq!(profiles.len(), 2);
    assert_eq!(profiles["userbot"].description, "a user-layer agent");
    assert_eq!(profiles["reviewer"].tool_allow, vec!["read_file"]);
    assert_eq!(profiles["reviewer"].system_prompt_text, "you are reviewer");
}

#[test]
fn project_overrides_user_on_name_collision() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);

    write_profile(
        &tmp.path().join("xdg/defect/agents"),
        "bot",
        "description = \"user version\"\n",
        Some("user prompt"),
    );
    write_profile(
        &repo_root.join(".defect/agents"),
        "bot",
        "description = \"project version\"\n",
        Some("project prompt"),
    );

    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert_eq!(profiles.len(), 1);
    assert_eq!(profiles["bot"].description, "project version");
    assert_eq!(profiles["bot"].system_prompt_text, "project prompt");
}

#[test]
fn missing_description_is_hard_error() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "bad",
        "model = \"x\"\n",
        Some("prompt"),
    );

    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must fail");
    assert!(matches!(err, ConfigError::Invalid { .. }));
}

#[test]
fn allow_omitted_defaults_to_read_only_set() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "reader",
        "description = \"reads\"\n",
        Some("prompt"),
    );

    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert_eq!(profiles["reader"].tool_allow, vec!["read_file", "search"]);
}

#[test]
fn hooks_omitted_yields_empty() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "plain",
        "description = \"no hooks\"\n",
        Some("prompt"),
    );

    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert!(profiles["plain"].hooks.is_empty());
}

#[test]
fn profile_hooks_parsed_with_name_and_source() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "guard",
        "description = \"hooked\"\n\
         [[hooks.before_tool_apply]]\n\
         name = \"redact\"\n\
         match = { tool = \"bash\" }\n\
         handler = { type = \"builtin\", name = \"redact-secrets\" }\n",
        Some("prompt"),
    );

    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    let entries = profiles["guard"].hooks.get("before_tool_apply");
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].name.as_deref(), Some("redact"));
    assert_eq!(entries[0].matcher.tool.as_deref(), Some("bash"));
    // Project-level discovery ⇒ source = Project.
    assert_eq!(entries[0].source, crate::types::ConfigSource::Project);
}

#[test]
fn profile_hooks_unknown_event_is_hard_error() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "typo",
        "description = \"bad event\"\n\
         [[hooks.before_tool_aply]]\n\
         handler = { type = \"builtin\", name = \"redact-secrets\" }\n",
        Some("prompt"),
    );

    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must fail");
    assert!(matches!(err, ConfigError::Invalid { .. }));
}

#[test]
fn single_file_profile_hooks_parsed() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "inline",
        "+++\n\
         description = \"inline hooked\"\n\
         [[hooks.after_session_enter]]\n\
         handler = { type = \"builtin\", name = \"skill-manifest\" }\n\
         +++\nyou are inline\n",
    );

    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    let entries = profiles["inline"].hooks.get("after_session_enter");
    assert_eq!(entries.len(), 1);
    // Single-file variant without name ⇒ None (assembly-time fallback to anonymous).
    assert_eq!(entries[0].name, None);
}

#[test]
fn unknown_key_is_hard_error() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "typo",
        "description = \"x\"\nmdoel = \"oops\"\n",
        Some("prompt"),
    );

    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must fail");
    assert!(matches!(err, ConfigError::Invalid { .. }));
}

#[test]
fn prompt_file_escaping_profile_dir_is_rejected() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    // Place a secret in the repo root that the profile attempts to read via
    // `../../secret.md`.
    fs::write(repo_root.join("secret.md"), "TOPSECRET").expect("write secret");
    write_profile(
        &repo_root.join(".defect/agents"),
        "escaper",
        "description = \"x\"\n[prompt]\nfile = \"../../secret.md\"\n",
        Some("decoy"),
    );

    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must reject escape");
    match err {
        ConfigError::Invalid { message, .. } => {
            assert!(message.contains("prompt.file"), "got: {message}");
        }
        other => panic!("expected Invalid, got {other:?}"),
    }
}

#[test]
fn empty_when_no_agents_dirs() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert!(profiles.is_empty());
}

#[test]
fn subdir_without_config_toml_is_skipped() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    let agents = repo_root.join(".defect/agents");
    fs::create_dir_all(agents.join("not-a-profile")).expect("mkdir");
    write_profile(&agents, "real", "description = \"r\"\n", Some("p"));

    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert_eq!(profiles.len(), 1);
    assert!(profiles.contains_key("real"));
}

// --- single-file variant (+++ TOML frontmatter) ---

#[test]
fn discovers_single_file_profile() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "reviewer",
        "+++\ndescription = \"review diffs\"\nmodel = \"opus\"\n[tools]\nallow = [\"read_file\"]\n+++\nYou are a reviewer.\n",
    );

    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert_eq!(profiles.len(), 1);
    let p = &profiles["reviewer"];
    assert_eq!(p.description, "review diffs");
    assert_eq!(p.model.as_deref(), Some("opus"));
    assert_eq!(p.tool_allow, vec!["read_file"]);
    assert_eq!(p.system_prompt_text, "You are a reviewer.");
}

#[test]
fn single_file_allow_omitted_defaults_read_only() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "reader",
        "+++\ndescription = \"reads\"\n+++\nbody\n",
    );
    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert_eq!(profiles["reader"].tool_allow, vec!["read_file", "search"]);
}

#[test]
fn single_file_missing_frontmatter_errors() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "bad",
        "no frontmatter here\njust text\n",
    );
    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must fail");
    assert!(matches!(err, ConfigError::Invalid { .. }));
}

#[test]
fn single_file_missing_description_errors() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "bad",
        "+++\nmodel = \"x\"\n+++\nbody\n",
    );
    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must fail");
    assert!(matches!(err, ConfigError::Invalid { .. }));
}

#[test]
fn single_file_prompt_table_is_rejected() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "bad",
        "+++\ndescription = \"d\"\n[prompt]\nfile = \"x.md\"\n+++\nbody\n",
    );
    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must reject [prompt]");
    match err {
        ConfigError::Invalid { message, .. } => {
            assert!(message.contains("[prompt]"), "got: {message}");
        }
        other => panic!("expected Invalid, got {other:?}"),
    }
}

#[test]
fn single_file_unknown_key_errors() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "typo",
        "+++\ndescription = \"d\"\nmdoel = \"oops\"\n+++\nbody\n",
    );
    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must fail");
    assert!(matches!(err, ConfigError::Invalid { .. }));
}

#[test]
fn folder_and_single_file_same_name_same_layer_conflicts() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    let agents = repo_root.join(".defect/agents");
    write_profile(
        &agents,
        "dup",
        "description = \"folder\"\n",
        Some("folder prompt"),
    );
    write_single_file(
        &agents,
        "dup",
        "+++\ndescription = \"file\"\n+++\nfile prompt\n",
    );

    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must conflict");
    match err {
        ConfigError::Invalid { message, .. } => {
            assert!(message.contains("duplicate"), "got: {message}");
        }
        other => panic!("expected Invalid, got {other:?}"),
    }
}

#[test]
fn single_file_project_overrides_user() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &tmp.path().join("xdg/defect/agents"),
        "bot",
        "+++\ndescription = \"user\"\n+++\nuser prompt\n",
    );
    write_single_file(
        &repo_root.join(".defect/agents"),
        "bot",
        "+++\ndescription = \"project\"\n+++\nproject prompt\n",
    );
    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert_eq!(profiles.len(), 1);
    assert_eq!(profiles["bot"].description, "project");
    assert_eq!(profiles["bot"].system_prompt_text, "project prompt");
}

// Single-file YAML frontmatter (delimited by `---`, requires the `yaml` feature)

#[cfg(feature = "yaml")]
#[test]
fn discovers_yaml_frontmatter_profile() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "reviewer",
        "---\ndescription: review diffs\nmodel: opus\ntools:\n  allow: [read_file, search]\n---\nYou are a reviewer.\n",
    );

    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    let p = &profiles["reviewer"];
    assert_eq!(p.description, "review diffs");
    assert_eq!(p.model.as_deref(), Some("opus"));
    assert_eq!(p.tool_allow, vec!["read_file", "search"]);
    assert_eq!(p.system_prompt_text, "You are a reviewer.");
}

#[cfg(feature = "yaml")]
#[test]
fn yaml_unknown_key_errors() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "typo",
        "---\ndescription: d\nmdoel: oops\n---\nbody\n",
    );
    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must fail");
    assert!(matches!(err, ConfigError::Invalid { .. }));
}

#[cfg(feature = "yaml")]
#[test]
fn yaml_prompt_table_is_rejected() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "bad",
        "---\ndescription: d\nprompt:\n  file: x.md\n---\nbody\n",
    );
    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must reject prompt");
    match err {
        ConfigError::Invalid { message, .. } => {
            assert!(message.contains("[prompt]"), "got: {message}");
        }
        other => panic!("expected Invalid, got {other:?}"),
    }
}

/// When the `yaml` feature is disabled, `---` frontmatter must hard-fail with an
/// actionable error (no silent degradation).
#[cfg(not(feature = "yaml"))]
#[test]
fn yaml_frontmatter_without_feature_errors() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_single_file(
        &repo_root.join(".defect/agents"),
        "y",
        "---\ndescription: d\n---\nbody\n",
    );
    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("must fail without yaml");
    match err {
        ConfigError::Invalid { message, .. } => {
            assert!(message.contains("yaml"), "got: {message}");
        }
        other => panic!("expected Invalid, got {other:?}"),
    }
}

#[test]
fn folder_profile_inline_prompt_text() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    // No system.md — prompt comes from inline `[prompt] text`.
    write_profile(
        &repo_root.join(".defect/agents"),
        "inline",
        "description = \"d\"\n[prompt]\ntext = \"inline prompt body\"\n",
        None,
    );
    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert_eq!(profiles["inline"].system_prompt_text, "inline prompt body");
}

#[test]
fn folder_profile_prompt_text_and_file_conflict() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "bad",
        "description = \"d\"\n[prompt]\ntext = \"x\"\nfile = \"system.md\"\n",
        Some("file body"),
    );
    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("conflict");
    match err {
        ConfigError::Invalid { message, .. } => {
            assert!(message.contains("not both"), "got: {message}");
        }
        other => panic!("expected Invalid, got {other:?}"),
    }
}

#[test]
fn profile_default_model_table_accepted() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "m",
        "description = \"d\"\n[default]\nmodel = \"claude-x\"\n",
        Some("sys"),
    );
    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert_eq!(profiles["m"].model.as_deref(), Some("claude-x"));
}

#[test]
fn profile_root_and_default_model_conflict() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "m",
        "description = \"d\"\nmodel = \"a\"\n[default]\nmodel = \"b\"\n",
        Some("sys"),
    );
    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("conflict");
    assert!(matches!(err, ConfigError::Invalid { .. }));
}

#[test]
fn profile_request_limit_fixed() {
    use defect_agent::session::TurnRequestLimit;
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "r",
        "description = \"d\"\nrequest_limit = 50\nrequest_limit_mode = \"fixed\"\n",
        Some("sys"),
    );
    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert!(matches!(
        profiles["r"].request_limit,
        Some(TurnRequestLimit::Fixed(50))
    ));
}

#[test]
fn profile_hooks_disable_is_explanatory_error() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "p",
        "description = \"d\"\n[[hooks.disable]]\nevent = \"before_tool_apply\"\n",
        Some("sys"),
    );
    let err = discover_profiles(&opts_with(&tmp, &repo_root)).expect_err("disable unsupported");
    match err {
        ConfigError::Invalid { message, .. } => {
            assert!(
                message.contains("not supported in a profile"),
                "should explain disable is unsupported, got: {message}"
            );
        }
        other => panic!("expected Invalid, got {other:?}"),
    }
}

#[test]
fn profile_inherit_project_prompt_flag() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "p",
        "description = \"d\"\ninherit_project_prompt = true\n",
        Some("sys"),
    );
    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert!(profiles["p"].inherit_project_prompt);
    // Default is false when omitted.
    write_profile(
        &repo_root.join(".defect/agents"),
        "q",
        "description = \"d\"\n",
        Some("sys"),
    );
    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert!(!profiles["q"].inherit_project_prompt);
}

#[test]
fn profile_request_limit_omitted_is_none() {
    let tmp = TempDir::new().expect("tmp");
    let repo_root = repo(&tmp);
    write_profile(
        &repo_root.join(".defect/agents"),
        "r",
        "description = \"d\"\n",
        Some("sys"),
    );
    let profiles = discover_profiles(&opts_with(&tmp, &repo_root)).expect("discover");
    assert!(profiles["r"].request_limit.is_none());
}