tftio-clanker 0.2.0

Launch AI harnesses with runtime-configured context, domains, models, and prompts
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
//! Context resolution for harness launches.

use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::config::{Config, ContextName, DomainName, InvalidName, ModelName, SkillName};

/// Source that supplied the resolved context.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextSource {
    /// Explicit `--context` launch flag.
    CommandLine,
    /// `CONTEXT_OVERRIDE` environment variable.
    OverrideEnvironment,
    /// Nearest `.clanker` TOML file at or above the current directory.
    ClankerFile,
    /// `CONTEXT` environment variable.
    Environment,
    /// Hostname map from runtime configuration.
    Hostname,
    /// Runtime configuration fallback.
    Fallback,
}

impl ContextSource {
    /// Stable label used in session markers, JSON output, and errors.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::CommandLine => "--context",
            Self::OverrideEnvironment => "CONTEXT_OVERRIDE",
            Self::ClankerFile => ".clanker",
            Self::Environment => "CONTEXT",
            Self::Hostname => "hostname",
            Self::Fallback => "fallback",
        }
    }
}

/// A resolved context and the precedence tier that supplied it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedContext {
    /// Validated context name.
    pub name: ContextName,
    /// Winning precedence tier.
    pub source: ContextSource,
}

/// Parsed cwd `.clanker` values shared by all launch axes.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DirectoryConfig {
    /// Optional context selection.
    pub context: Option<ContextName>,
    /// Optional domain selection used by subcommand mode.
    pub domain: Option<DomainName>,
    /// Optional model selection used by subcommand mode.
    pub model: Option<ModelName>,
    /// Optional bake-specific repo configuration.
    pub bake: Option<BakeConfig>,
}

/// Per-repo bake configuration from directory-form `.clanker/config.toml`.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BakeConfig {
    /// Optional explicit skill curation overriding the selected domain list.
    pub skills: Option<Vec<SkillName>>,
}

/// Context resolution failures at environment and dotfile boundaries.
#[derive(Debug, thiserror::Error)]
pub enum ContextError {
    /// An environment value is not a safe context name.
    #[error("invalid context from {origin}: {error}")]
    InvalidName {
        /// Source label.
        origin: &'static str,
        /// Name parse failure.
        error: InvalidName,
    },
    /// A context file could not be read.
    #[error("failed to read context file {path}: {source}")]
    Read {
        /// Failing path.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// `.clanker` TOML is invalid.
    #[error("failed to parse directory config {path}: {source}")]
    Parse {
        /// Failing path.
        path: PathBuf,
        /// TOML parse error.
        source: toml::de::Error,
    },
    /// A directory-form `.clanker` exists without its required config file.
    #[error(".clanker directory is missing required config file {path}")]
    MissingDirectoryConfig {
        /// Expected directory-form config path.
        path: PathBuf,
    },
    /// Bake configuration was placed in a legacy flat `.clanker` file.
    #[error(
        "[bake] is only supported in directory-form .clanker/config.toml, not flat file {path}"
    )]
    BakeInFlatFile {
        /// Flat file containing an unsupported bake table.
        path: PathBuf,
    },
    /// The resolved context is not in the configured registry.
    #[error(
        "unknown context `{name}` from {origin}; add it to defaults.contexts or fix the selection"
    )]
    UnknownContext {
        /// Rejected context name.
        name: ContextName,
        /// Winning precedence tier that supplied it.
        origin: &'static str,
    },
}

/// Resolve context using the pinned precedence chain.
///
/// Empty environment values fall through. The nearest `.clanker` at or above
/// the current directory wins. The winning context must be a member of the
/// configured `defaults.contexts` registry.
///
/// # Errors
/// Returns [`ContextError`] when a supplied name is invalid, a present
/// dotfile cannot be read or parsed, or the resolved context is not
/// registered.
pub fn resolve_context(
    current_dir: &Path,
    command_line: Option<&ContextName>,
    context_override: Option<&str>,
    context_environment: Option<&str>,
    hostname: &str,
    config: &Config,
) -> Result<ResolvedContext, ContextError> {
    let directory_config = read_directory_config(current_dir)?;
    resolve_context_with_directory(
        command_line,
        context_override,
        context_environment,
        hostname,
        config,
        directory_config.as_ref(),
    )
}

/// Resolve context using an already-read cwd `.clanker` document.
///
/// # Errors
/// Returns [`ContextError`] when a supplied environment name is invalid or
/// the resolved context is not in the configured registry.
pub fn resolve_context_with_directory(
    command_line: Option<&ContextName>,
    context_override: Option<&str>,
    context_environment: Option<&str>,
    hostname: &str,
    config: &Config,
    directory_config: Option<&DirectoryConfig>,
) -> Result<ResolvedContext, ContextError> {
    let resolved = if let Some(context) = command_line {
        ResolvedContext {
            name: context.clone(),
            source: ContextSource::CommandLine,
        }
    } else if let Some(context) = parse_optional_context(context_override, "CONTEXT_OVERRIDE")? {
        ResolvedContext {
            name: context,
            source: ContextSource::OverrideEnvironment,
        }
    } else if let Some(context) = directory_config.and_then(|directory| directory.context.clone()) {
        ResolvedContext {
            name: context,
            source: ContextSource::ClankerFile,
        }
    } else if let Some(context) = parse_optional_context(context_environment, "CONTEXT")? {
        ResolvedContext {
            name: context,
            source: ContextSource::Environment,
        }
    } else if let Some(context) = config.defaults.context_by_hostname.get(hostname) {
        ResolvedContext {
            name: context.clone(),
            source: ContextSource::Hostname,
        }
    } else {
        ResolvedContext {
            name: config.defaults.context_fallback.clone(),
            source: ContextSource::Fallback,
        }
    };

    if config.defaults.contexts.contains(&resolved.name) {
        Ok(resolved)
    } else {
        Err(ContextError::UnknownContext {
            name: resolved.name,
            origin: resolved.source.label(),
        })
    }
}

/// Read the nearest `.clanker` file or directory at or above the current directory.
///
/// # Errors
/// Returns [`ContextError`] when the config exists but cannot be read or parsed.
pub fn read_directory_config(current_dir: &Path) -> Result<Option<DirectoryConfig>, ContextError> {
    for directory in current_dir.ancestors() {
        let path = directory.join(".clanker");
        let metadata = match fs::metadata(&path) {
            Ok(metadata) => metadata,
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => continue,
            Err(source) => return Err(ContextError::Read { path, source }),
        };

        if metadata.is_dir() {
            let config_path = path.join("config.toml");
            if !config_path.exists() {
                return Err(ContextError::MissingDirectoryConfig { path: config_path });
            }
            return parse_directory_config_file(&config_path, DirectoryConfigForm::Directory)
                .map(Some);
        }

        return parse_directory_config_file(&path, DirectoryConfigForm::Flat).map(Some);
    }
    Ok(None)
}

#[derive(Debug, Clone, Copy)]
enum DirectoryConfigForm {
    Flat,
    Directory,
}

fn parse_directory_config_file(
    path: &Path,
    form: DirectoryConfigForm,
) -> Result<DirectoryConfig, ContextError> {
    let text = fs::read_to_string(path).map_err(|source| ContextError::Read {
        path: path.to_path_buf(),
        source,
    })?;
    let config: DirectoryConfig = toml::from_str(&text).map_err(|source| ContextError::Parse {
        path: path.to_path_buf(),
        source,
    })?;
    if matches!(form, DirectoryConfigForm::Flat) && config.bake.is_some() {
        return Err(ContextError::BakeInFlatFile {
            path: path.to_path_buf(),
        });
    }
    Ok(config)
}

fn parse_optional_context(
    value: Option<&str>,
    origin: &'static str,
) -> Result<Option<ContextName>, ContextError> {
    let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
        return Ok(None);
    };
    ContextName::new(value)
        .map(Some)
        .map_err(|error| ContextError::InvalidName { origin, error })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::load_config_with_overlay;
    use tempfile::TempDir;

    fn fixture_config(directory: &Path) -> Config {
        let path = directory.join("config.toml");
        fs::write(
            &path,
            r#"
[defaults]
domain = "eng"
contexts = ["personal", "work"]
context_fallback = "personal"
context_by_hostname = { workstation = "work" }
shim_path = "~/.local/clankers/bin"
sandbox_wrapper = "~/.config/sandbox-exec/run-sandboxed.sh"
prompter_bundle = "~/.local/prompter"
skills_bundle = "~/.local/clanker/skills"
prompt_cache = "~/.cache/clanker/prompts"
prompt_cache_ttl_seconds = 86400

[harness.claude]
bin = "claude"
family = "claude"
default_args = []
[harness.claude.injection]
kind = "arg-text"
args = ["--append-system-prompt", "{text}"]

[model]

[domain.eng]
profiles = ["core.base", "domain.eng"]
skills = []
env = {}
"#,
        )
        .unwrap();
        load_config_with_overlay(&path, None).unwrap().config
    }

    #[test]
    fn clanker_context_beats_environment() {
        let temp = TempDir::new().unwrap();
        let config = fixture_config(temp.path());
        fs::write(temp.path().join(".clanker"), "context = \"work\"\n").unwrap();

        let resolved =
            resolve_context(temp.path(), None, None, Some("personal"), "other", &config).unwrap();

        assert_eq!(resolved.name.as_str(), "work");
        assert_eq!(resolved.source, ContextSource::ClankerFile);
    }

    #[test]
    fn nearest_ancestor_clanker_wins() {
        let temp = TempDir::new().unwrap();
        let config = fixture_config(temp.path());
        let parent = temp.path().join("work");
        let current = parent.join("repo/src");
        fs::create_dir_all(&current).unwrap();
        fs::write(parent.join(".clanker"), "context = \"work\"\n").unwrap();

        let inherited =
            resolve_context(&current, None, None, Some("personal"), "other", &config).unwrap();
        assert_eq!(inherited.name.as_str(), "work");
        assert_eq!(inherited.source, ContextSource::ClankerFile);

        fs::write(current.join(".clanker"), "context = \"personal\"\n").unwrap();
        let nearest =
            resolve_context(&current, None, None, Some("work"), "other", &config).unwrap();
        assert_eq!(nearest.name.as_str(), "personal");
        assert_eq!(nearest.source, ContextSource::ClankerFile);
    }

    #[test]
    fn directory_form_config_is_read() {
        let temp = TempDir::new().unwrap();
        let config = fixture_config(temp.path());
        let clanker = temp.path().join(".clanker");
        fs::create_dir_all(&clanker).unwrap();
        fs::write(clanker.join("config.toml"), "context = \"work\"\n").unwrap();

        let resolved =
            resolve_context(temp.path(), None, None, Some("personal"), "other", &config).unwrap();

        assert_eq!(resolved.name.as_str(), "work");
        assert_eq!(resolved.source, ContextSource::ClankerFile);
    }

    #[test]
    fn child_directory_form_beats_parent_flat_file() {
        let temp = TempDir::new().unwrap();
        let config = fixture_config(temp.path());
        let parent = temp.path().join("work");
        let current = parent.join("repo");
        let child_clanker = current.join(".clanker");
        fs::create_dir_all(&child_clanker).unwrap();
        fs::write(parent.join(".clanker"), "context = \"work\"\n").unwrap();
        fs::write(
            child_clanker.join("config.toml"),
            "context = \"personal\"\n",
        )
        .unwrap();

        let resolved =
            resolve_context(&current, None, None, Some("work"), "other", &config).unwrap();

        assert_eq!(resolved.name.as_str(), "personal");
        assert_eq!(resolved.source, ContextSource::ClankerFile);
    }

    #[test]
    fn directory_form_without_config_toml_fails_closed() {
        let temp = TempDir::new().unwrap();
        fs::create_dir_all(temp.path().join(".clanker")).unwrap();

        let error = read_directory_config(temp.path()).unwrap_err();

        let message = error.to_string();
        assert!(message.contains(".clanker/config.toml"));
        assert!(message.contains("missing required config file"));
    }

    #[test]
    fn bake_section_is_rejected_in_flat_file() {
        let temp = TempDir::new().unwrap();
        fs::write(temp.path().join(".clanker"), "[bake]\nskills = []\n").unwrap();

        let error = read_directory_config(temp.path()).unwrap_err();

        let message = error.to_string();
        assert!(message.contains("[bake]"));
        assert!(message.contains(".clanker/config.toml"));
    }

    #[test]
    fn directory_bake_skills_preserve_absent_and_empty_semantics() {
        let temp = TempDir::new().unwrap();
        let clanker = temp.path().join(".clanker");
        fs::create_dir_all(&clanker).unwrap();
        fs::write(clanker.join("config.toml"), "context = \"work\"\n").unwrap();
        let absent = read_directory_config(temp.path()).unwrap().unwrap();
        assert!(absent.bake.is_none());

        fs::write(clanker.join("config.toml"), "[bake]\nskills = []\n").unwrap();
        let empty = read_directory_config(temp.path()).unwrap().unwrap();
        assert!(empty.bake.unwrap().skills.unwrap().is_empty());
    }

    #[test]
    fn unregistered_contexts_are_rejected_per_tier() {
        let temp = TempDir::new().unwrap();
        let config = fixture_config(temp.path());

        let command_line = ContextName::new("staging").unwrap();
        let error = resolve_context(temp.path(), Some(&command_line), None, None, "h", &config)
            .unwrap_err();
        assert!(error.to_string().contains("unknown context `staging`"));
        assert!(error.to_string().contains("--context"));

        let error =
            resolve_context(temp.path(), None, Some("staging"), None, "h", &config).unwrap_err();
        assert!(error.to_string().contains("CONTEXT_OVERRIDE"));

        fs::write(temp.path().join(".clanker"), "context = \"staging\"\n").unwrap();
        let error = resolve_context(temp.path(), None, None, None, "h", &config).unwrap_err();
        assert!(error.to_string().contains(".clanker"));
    }

    #[test]
    fn hostname_then_fallback_complete_the_chain() {
        let temp = TempDir::new().unwrap();
        let config = fixture_config(temp.path());

        let host = resolve_context(temp.path(), None, None, None, "workstation", &config).unwrap();
        assert_eq!(host.name.as_str(), "work");
        assert_eq!(host.source, ContextSource::Hostname);

        let fallback = resolve_context(temp.path(), None, None, None, "other", &config).unwrap();
        assert_eq!(fallback.name.as_str(), "personal");
        assert_eq!(fallback.source, ContextSource::Fallback);
    }
}