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
//! Parsing of the `[hooks]` section.
//!
//! Hook configuration types.
//!
//! ## Shape
//!
//! `[hooks]` is a table whose keys are mount-point `event_name`s (snake_case, e.g.
//! `before_turn_end`) and whose values are arrays of hook entries for that event. The set
//! of valid event names is `defect_agent::hooks::step::ALL_EVENT_NAMES` — misspelled or
//! unknown event keys **hard fail** (they are not silently dropped). The special key
//! `disable` is not an event; it is an array of disable directives.
//!
//! ## Why hooks do not go through `ConfigToml::try_into`
//!
//! All other sections first flatten every layer into a single TOML via
//! `merge_toml_values`, then decode. But the merge semantics for hook arrays are
//! **append + dedupe** — TOML's default array overwrite would let a project-local layer
//! silently remove upstream hooks, mirroring claude-code issue #106. Therefore hooks must
//! be merged by appending arrays at the layer stage, and each hook must retain its source
//! [`ConfigSource`] for trust gating.
//!
//! The entry point of this module is [`parse_layer_hooks`]: it extracts the hooks
//! declared in a single layer from the raw [`toml::Value`] and returns them tagged with a
//! source label. Cross-layer merging (append + dedupe + apply disable) happens in
//! [`crate::loader`].

use std::collections::BTreeMap;
use std::path::PathBuf;

use defect_agent::hooks::step::is_known_event;
use defect_agent::tool::SafetyClass;
use serde::Deserialize;
use toml::Value as TomlValue;

use crate::types::{
    ConfigError, ConfigSource, HookCommandSpec, HookEntry, HookHandlerSpec, HookMatcher,
    HookPromptRender, HookPromptSpec, HookShellKind, HooksConfig,
};

/// Maps each event bucket to the entries declared under it.
#[derive(Debug, Clone, Default)]
pub(crate) struct LayerHooks {
    pub(crate) entries: HooksConfig,
    /// Disable entries declared by this layer. Disables are not restricted to the
    /// declaring layer; during merging, entries matching the (event, matcher, handler)
    /// triple are removed from the accumulated result.
    pub(crate) disables: Vec<HookDisable>,
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct HookDisable {
    pub(crate) event: String,
    pub(crate) matcher: HookMatcher,
    pub(crate) handler: HookHandlerSpec,
}

/// Extract the hook entries and disable directives declared in a single layer from its
/// raw TOML.
///
/// The `value` parameter must be the top-level [`TomlValue::Table`] for that layer (user
/// / project / project-local / cli) — **not** the result of merging layers.
pub(crate) fn parse_layer_hooks(
    path: PathBuf,
    source: ConfigSource,
    value: &TomlValue,
) -> Result<LayerHooks, ConfigError> {
    let Some(hooks_value) = value.get("hooks") else {
        return Ok(LayerHooks::default());
    };
    let table = hooks_value.as_table().ok_or_else(|| ConfigError::Invalid {
        path: path.clone(),
        message: "[hooks] must be a table of event-name → entries".to_string(),
    })?;

    let mut entries = HooksConfig::default();
    let mut disables = Vec::new();

    for (key, raw) in table {
        if key == "disable" {
            let raw_list: Vec<HookDisableRaw> =
                raw.clone()
                    .try_into()
                    .map_err(|err: toml::de::Error| ConfigError::Invalid {
                        path: path.clone(),
                        message: format!("invalid [[hooks.disable]]: {err}"),
                    })?;
            for d in raw_list {
                if !is_known_event(&d.event) {
                    return Err(ConfigError::Invalid {
                        path: path.clone(),
                        message: format!(
                            "[[hooks.disable]].event = {:?} is not a known hook event name",
                            d.event
                        ),
                    });
                }
                disables.push(HookDisable {
                    event: d.event,
                    matcher: d.matcher.into_typed(),
                    handler: d.handler.into_typed(&path)?,
                });
            }
            continue;
        }

        // The event key must be a known hook point; otherwise hard-fail (do not silently
        // drop misspelled keys).
        if !is_known_event(key) {
            return Err(ConfigError::Invalid {
                path: path.clone(),
                message: format!("[[hooks.{key}]] is not a known hook event name"),
            });
        }
        let raw_list: Vec<HookEntryRaw> =
            raw.clone()
                .try_into()
                .map_err(|err: toml::de::Error| ConfigError::Invalid {
                    path: path.clone(),
                    message: format!("invalid [[hooks.{key}]]: {err}"),
                })?;
        for r in raw_list {
            entries.push(
                key.clone(),
                HookEntry {
                    name: r.name,
                    matcher: r.matcher.into_typed(),
                    handler: r.handler.into_typed(&path)?,
                    source,
                },
            );
        }
    }

    Ok(LayerHooks { entries, disables })
}

/// Converts a subagent profile's `[hooks]` table (already parsed by serde into event-name
/// → raw-entry arrays) into a [`HooksConfig`], attaching the profile's layer `source` to
/// each entry.
///
/// Unlike [`parse_layer_hooks`], a profile is a **single closed truth source** — there is
/// no upstream to append to, deduplicate against, or disable. Therefore the `disable` key
/// is unsupported and no cross-layer merging occurs. Event names are still validated
/// against `ALL_EVENT_NAMES`; a misspelled name is a hard failure (not silently dropped).
/// `path` is used only for error reporting.
pub(crate) fn profile_hooks_from_raw(
    raw: BTreeMap<String, toml::Value>,
    source: ConfigSource,
    path: &std::path::Path,
) -> Result<HooksConfig, ConfigError> {
    let mut entries = HooksConfig::default();
    for (key, value) in raw {
        // `disable` is a cross-layer directive in the top-level config (it removes hooks
        // declared by *other* layers). A profile is a single, self-contained source — there
        // is no other layer to disable — so `disable` has no meaning here. Give a targeted
        // explanation rather than the generic "unknown event name" / "unknown field" serde
        // error, which would wrongly suggest `disable` was a misspelled event.
        if key == "disable" {
            return Err(ConfigError::Invalid {
                path: path.to_path_buf(),
                message: "[[hooks.disable]] is not supported in a profile: a profile is a \
                          single self-contained hook source with no other layer to disable. \
                          Declare only the hooks this profile should run."
                    .into(),
            });
        }
        if !is_known_event(&key) {
            return Err(ConfigError::Invalid {
                path: path.to_path_buf(),
                message: format!("[[hooks.{key}]] is not a known hook event name"),
            });
        }
        // Deserialize this event's entries only after the key is validated, so the
        // `disable` / unknown-event diagnostics above win over serde's field errors.
        let list: Vec<HookEntryRaw> =
            value
                .try_into()
                .map_err(|err: toml::de::Error| ConfigError::Invalid {
                    path: path.to_path_buf(),
                    message: format!("invalid [[hooks.{key}]]: {err}"),
                })?;
        for r in list {
            entries.push(
                key.clone(),
                HookEntry {
                    name: r.name,
                    matcher: r.matcher.into_typed(),
                    handler: r.handler.into_typed(path)?,
                    source,
                },
            );
        }
    }
    Ok(entries)
}

/// Merge multiple [`LayerHooks`] into a final [`HooksConfig`]:
/// - Append event buckets in declaration order (user → project → project-local → cli)
/// - Deduplicate consecutive entries with identical (matcher, handler) pairs, keeping the
///   first occurrence
/// - Apply all [`HookDisable`] entries: remove any (matcher, handler) match from the
///   corresponding bucket, regardless of which layer it came from
pub(crate) fn merge_layer_hooks(layers: Vec<LayerHooks>) -> HooksConfig {
    let mut merged = HooksConfig::default();
    let mut disables: Vec<HookDisable> = Vec::new();

    for layer in layers {
        for (event, list) in layer.entries.buckets {
            merged.buckets.entry(event).or_default().extend(list);
        }
        disables.extend(layer.disables);
    }

    for bucket in merged.buckets.values_mut() {
        dedupe_in_place(bucket);
    }

    for disable in disables {
        if let Some(bucket) = merged.buckets.get_mut(&disable.event) {
            bucket.retain(|entry| {
                !(entry.matcher == disable.matcher && entry.handler == disable.handler)
            });
        }
    }

    merged
}

fn dedupe_in_place(entries: &mut Vec<HookEntry>) {
    let mut i = 0;
    while i < entries.len() {
        let mut j = i + 1;
        while j < entries.len() {
            let dup = match (entries.get(i), entries.get(j)) {
                (Some(a), Some(b)) => a.matcher == b.matcher && a.handler == b.handler,
                _ => false,
            };
            if dup {
                entries.remove(j);
            } else {
                j += 1;
            }
        }
        i += 1;
    }
}

// Raw deserialization shapes

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct HookEntryRaw {
    /// Optional display name (for tracing / observability).
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    #[serde(rename = "match")]
    matcher: HookMatcherRaw,
    handler: HookHandlerRaw,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct HookDisableRaw {
    event: String,
    #[serde(default)]
    #[serde(rename = "match")]
    matcher: HookMatcherRaw,
    handler: HookHandlerRaw,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct HookMatcherRaw {
    tool: Option<String>,
    tool_glob: Option<String>,
    safety: Option<Vec<SafetyClass>>,
}

impl HookMatcherRaw {
    fn into_typed(self) -> HookMatcher {
        HookMatcher {
            tool: self.tool,
            tool_glob: self.tool_glob,
            safety: self.safety.unwrap_or_default(),
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum HookHandlerRaw {
    Builtin {
        name: String,
    },
    Command {
        argv: Option<Vec<String>>,
        argv_windows: Option<Vec<String>>,
        shell: Option<HookShellRaw>,
        command: Option<String>,
        cwd: Option<PathBuf>,
        env: Option<BTreeMap<String, String>>,
        timeout_sec: Option<u64>,
    },
    Prompt {
        model: Option<String>,
        system: String,
        render: HookPromptRenderRaw,
        timeout_sec: Option<u64>,
    },
}

impl HookHandlerRaw {
    fn into_typed(self, path: &std::path::Path) -> Result<HookHandlerSpec, ConfigError> {
        let invalid = |message: String| ConfigError::Invalid {
            path: path.to_path_buf(),
            message,
        };
        match self {
            Self::Builtin { name } => Ok(HookHandlerSpec::Builtin { name }),
            Self::Command {
                argv,
                argv_windows,
                shell,
                command,
                cwd,
                env,
                timeout_sec,
            } => {
                let env = env.unwrap_or_default();
                let spec = match (argv, shell, command) {
                    (Some(argv), None, None) => {
                        if argv.is_empty() {
                            return Err(invalid("command handler `argv` must not be empty".into()));
                        }
                        HookCommandSpec::Argv {
                            argv,
                            argv_windows,
                            cwd,
                            env,
                            timeout_sec,
                        }
                    }
                    (None, Some(shell), Some(command)) => {
                        if argv_windows.is_some() {
                            return Err(invalid(
                                "`argv_windows` is only valid for argv-form command handlers"
                                    .into(),
                            ));
                        }
                        HookCommandSpec::Shell {
                            shell: shell.into_typed(),
                            command,
                            cwd,
                            env,
                            timeout_sec,
                        }
                    }
                    (None, Some(_), None) => {
                        return Err(invalid(
                            "command handler with `shell` set requires `command`".into(),
                        ));
                    }
                    (None, None, _) => {
                        return Err(invalid(
                            "command handler requires either `argv` or (`shell` + `command`)"
                                .into(),
                        ));
                    }
                    (Some(_), Some(_), _) | (Some(_), None, Some(_)) => {
                        return Err(invalid(
                            "command handler must not mix `argv` with `shell`/`command`".into(),
                        ));
                    }
                };
                Ok(HookHandlerSpec::Command(spec))
            }
            Self::Prompt {
                model,
                system,
                render,
                timeout_sec,
            } => Ok(HookHandlerSpec::Prompt(HookPromptSpec {
                model,
                system,
                render: render.into_typed(),
                timeout_sec,
            })),
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
enum HookShellRaw {
    Sh,
    Bash,
    Pwsh,
    Cmd,
    /// `{ type = "custom", program = "...", args = [...] }`
    #[serde(untagged)]
    Custom(HookShellCustomRaw),
}

#[derive(Debug, Deserialize)]
struct HookShellCustomRaw {
    program: String,
    #[serde(default)]
    args: Vec<String>,
}

impl HookShellRaw {
    fn into_typed(self) -> HookShellKind {
        match self {
            Self::Sh => HookShellKind::Sh,
            Self::Bash => HookShellKind::Bash,
            Self::Pwsh => HookShellKind::Pwsh,
            Self::Cmd => HookShellKind::Cmd,
            Self::Custom(raw) => HookShellKind::Custom {
                program: raw.program,
                args: raw.args,
            },
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum HookPromptRenderRaw {
    Json,
    Template { template: String },
}

impl HookPromptRenderRaw {
    fn into_typed(self) -> HookPromptRender {
        match self {
            Self::Json => HookPromptRender::Json,
            Self::Template { template } => HookPromptRender::Template { template },
        }
    }
}