tftio-clanker 0.2.4

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
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
//! Fail-closed prompter composition and harness-specific prompt injection.
//!
//! Any composition or injection failure aborts the launch; `--no-prompt` is
//! the only way to launch without a composed prompt.

use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsString;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::config::{Config, HarnessConfig, InjectionConfig, ModelFamily};
use crate::launch::expand_path;

const FILE_PLACEHOLDER: &str = "{file}";
const TEXT_PLACEHOLDER: &str = "{text}";

/// Prompt material and process mutations produced for one launch.
#[derive(Debug, Default)]
pub struct PromptInjection {
    /// Rendered prompt text, when composition and injection succeeded.
    pub prompt: Option<String>,
    /// Arguments prepended before model and harness arguments.
    pub arguments: Vec<OsString>,
    /// Environment applied for env-file injection.
    pub environment: BTreeMap<OsString, OsString>,
    /// Prompt cache path used by file-based injection.
    pub cache_path: Option<PathBuf>,
}

/// Failures composing or injecting the launch prompt.
#[derive(Debug, thiserror::Error)]
pub enum PromptError {
    /// A configured prompter path is invalid.
    #[error("prompter path: {0}")]
    Path(String),
    /// The prompter bundle could not be located or loaded.
    #[error("prompter unavailable: {0}")]
    Unavailable(String),
    /// Requested profiles are absent from the prompter bundle.
    #[error("unknown prompter profile(s): {}", profiles.join(", "))]
    UnknownProfiles {
        /// Every requested profile missing from the bundle.
        profiles: Vec<String>,
    },
    /// Prompt rendering failed.
    #[error("prompt rendering failed: {0}")]
    Render(String),
    /// Rendered prompt bytes are not valid UTF-8.
    #[error("rendered prompt is not valid UTF-8: {0}")]
    NonUtf8(#[from] std::string::FromUtf8Error),
    /// Prompt cache directory could not be created.
    #[error("failed to create prompt cache {path}: {source}")]
    CacheDirectory {
        /// Cache directory path.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// Prompt file could not be created or written.
    #[error("failed to write prompt file {path}: {source}")]
    CacheFile {
        /// Prompt file path.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },
}

/// Compose configured profiles and build the harness injection mutation.
///
/// # Errors
/// Returns [`PromptError`] when the bundle is unavailable, any requested
/// profile is unknown, rendering fails, or the prompt file cannot be written.
pub fn compose_and_inject(
    profiles: &[String],
    family: &ModelFamily,
    harness: &HarnessConfig,
    config: &Config,
    home: &Path,
    persist_file: bool,
) -> Result<PromptInjection, PromptError> {
    let bundle = expand_path(&config.defaults.prompter_bundle, home)
        .map_err(|error| PromptError::Path(error.to_string()))?;
    let bundle_config = bundle.join("config.toml");
    let available = tftio_lib::prompt::available_profiles(Some(&bundle_config))
        .map_err(|error| PromptError::Unavailable(error.to_string()))?
        .into_iter()
        .collect::<BTreeSet<_>>();

    let unknown: Vec<String> = profiles
        .iter()
        .filter(|profile| !available.contains(*profile))
        .cloned()
        .collect();
    if !unknown.is_empty() {
        return Err(PromptError::UnknownProfiles { profiles: unknown });
    }

    let mut injection = PromptInjection::default();
    if profiles.is_empty() {
        return Ok(injection);
    }

    let prompt = tftio_lib::prompt::render_to_vec(
        profiles,
        Some(family.as_prompter_family()),
        Some(&bundle_config),
    )
    .map_err(|error| PromptError::Render(error.to_string()))?;
    let prompt = String::from_utf8(prompt)?;

    match &harness.injection {
        InjectionConfig::ArgText { args } => {
            injection.arguments = args
                .iter()
                .map(|argument| OsString::from(argument.replace(TEXT_PLACEHOLDER, &prompt)))
                .collect();
        }
        InjectionConfig::ArgFile { args } => {
            let path = prepare_prompt_file(config, home, &prompt, persist_file)?;
            let display = path.display().to_string();
            injection.arguments = args
                .iter()
                .map(|argument| OsString::from(argument.replace(FILE_PLACEHOLDER, &display)))
                .collect();
            injection.cache_path = Some(path);
        }
        InjectionConfig::EnvFile { environment } => {
            let path = prepare_prompt_file(config, home, &prompt, persist_file)?;
            injection.environment.insert(
                OsString::from(environment),
                OsString::from(path.as_os_str()),
            );
            injection.cache_path = Some(path);
        }
    }
    injection.prompt = Some(prompt);
    Ok(injection)
}

fn prepare_prompt_file(
    config: &Config,
    home: &Path,
    prompt: &str,
    persist: bool,
) -> Result<PathBuf, PromptError> {
    let cache = expand_path(&config.defaults.prompt_cache, home)
        .map_err(|error| PromptError::Path(error.to_string()))?;
    if !persist {
        return Ok(cache.join("dry-run-prompt.md"));
    }

    fs::create_dir_all(&cache).map_err(|source| PromptError::CacheDirectory {
        path: cache.clone(),
        source,
    })?;
    let now = SystemTime::now();
    gc_prompt_cache(
        &cache,
        Duration::from_secs(config.defaults.prompt_cache_ttl_seconds),
        now,
    );
    let timestamp = now
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let path = cache.join(format!("{}-{timestamp}.md", std::process::id()));
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(&path)
        .map_err(|source| PromptError::CacheFile {
            path: path.clone(),
            source,
        })?;
    file.write_all(prompt.as_bytes())
        .map_err(|source| PromptError::CacheFile {
            path: path.clone(),
            source,
        })?;
    Ok(path)
}

fn gc_prompt_cache(cache: &Path, ttl: Duration, now: SystemTime) {
    let Ok(entries) = fs::read_dir(cache) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let Ok(metadata) = entry.metadata() else {
            continue;
        };
        let Ok(modified) = metadata.modified() else {
            continue;
        };
        let Ok(age) = now.duration_since(modified) else {
            continue;
        };
        if age > ttl {
            let _ignored = fs::remove_file(path);
        }
    }
}

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

    fn write_bundle(home: &Path) {
        let prompter = home.join(".local/prompter");
        fs::create_dir_all(prompter.join("library/families/gpt")).unwrap();
        fs::write(
            prompter.join("config.toml"),
            r#"
library = "library"

[core.base]
depends_on = ["base.md"]
"#,
        )
        .unwrap();
        fs::write(prompter.join("library/base.md"), "BASE\n").unwrap();
        fs::write(prompter.join("library/families/gpt/base.md"), "GPT BASE\n").unwrap();
    }

    fn sample_config() -> Config {
        toml::from_str(
            r#"
[defaults]
domain = "eng"
contexts = ["personal"]
context_fallback = "personal"
context_by_hostname = {}
shim_path = "~/unused"
sandbox_wrapper = "~/unused"
prompter_bundle = "~/.local/prompter"
skills_bundle = "~/unused"
prompt_cache = "~/.cache/clanker/prompts"
prompt_cache_ttl_seconds = 3600

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

[harness.codex]
bin = "codex"
family = "gpt"
default_args = []
[harness.codex.injection]
kind = "arg-file"
args = ["-c", "model_instructions_file={file}"]

[harness.gemini]
bin = "gemini"
family = "gemini"
default_args = []
[harness.gemini.injection]
kind = "env-file"
environment = "GEMINI_SYSTEM_MD"

[model]

[domain.eng]
profiles = ["core.base"]
skills = []
env = {}
"#,
        )
        .unwrap()
    }

    fn harness<'a>(config: &'a Config, name: &str) -> &'a HarnessConfig {
        config.harness.get(name).unwrap()
    }

    #[test]
    fn arg_text_injection_substitutes_prompt_into_arguments() {
        let home = TempDir::new().unwrap();
        write_bundle(home.path());
        let config = sample_config();
        let claude = harness(&config, "claude");

        let injection = compose_and_inject(
            &["core.base".to_string()],
            &claude.family,
            claude,
            &config,
            home.path(),
            false,
        )
        .unwrap();

        assert!(
            injection
                .prompt
                .as_deref()
                .is_some_and(|prompt| prompt.contains("BASE\n"))
        );
        assert!(
            injection
                .arguments
                .iter()
                .any(|argument| argument.to_string_lossy() == "--append-system-prompt")
        );
        assert!(
            injection
                .arguments
                .iter()
                .any(|argument| argument.to_string_lossy().contains("BASE\n"))
        );
        assert!(injection.cache_path.is_none());
    }

    #[test]
    fn arg_file_injection_persists_prompt_and_injects_path() {
        let home = TempDir::new().unwrap();
        write_bundle(home.path());
        let config = sample_config();
        let codex = harness(&config, "codex");

        let injection = compose_and_inject(
            &["core.base".to_string()],
            &codex.family,
            codex,
            &config,
            home.path(),
            true,
        )
        .unwrap();

        let cache_path = injection
            .cache_path
            .expect("arg-file injection writes a file");
        assert!(cache_path.is_file());
        assert!(
            fs::read_to_string(&cache_path)
                .unwrap()
                .contains("GPT BASE\n")
        );
        let rendered = cache_path.display().to_string();
        assert!(
            injection
                .arguments
                .iter()
                .any(|argument| argument.to_string_lossy()
                    == format!("model_instructions_file={rendered}"))
        );
    }

    #[test]
    fn env_file_injection_exports_prompt_path() {
        let home = TempDir::new().unwrap();
        write_bundle(home.path());
        let config = sample_config();
        let gemini = harness(&config, "gemini");

        let injection = compose_and_inject(
            &["core.base".to_string()],
            &gemini.family,
            gemini,
            &config,
            home.path(),
            true,
        )
        .unwrap();

        let cache_path = injection
            .cache_path
            .expect("env-file injection writes a file");
        assert_eq!(
            injection
                .environment
                .get(std::ffi::OsStr::new("GEMINI_SYSTEM_MD")),
            Some(&OsString::from(cache_path.as_os_str()))
        );
        assert!(injection.arguments.is_empty());
    }

    #[test]
    fn unknown_profile_fails_closed() {
        let home = TempDir::new().unwrap();
        write_bundle(home.path());
        let config = sample_config();
        let claude = harness(&config, "claude");

        let error = compose_and_inject(
            &["core.base".to_string(), "missing.profile".to_string()],
            &claude.family,
            claude,
            &config,
            home.path(),
            false,
        )
        .unwrap_err();

        assert!(matches!(error, PromptError::UnknownProfiles { .. }));
        assert!(error.to_string().contains("missing.profile"));
    }

    #[test]
    fn empty_profiles_yield_no_prompt() {
        let home = TempDir::new().unwrap();
        write_bundle(home.path());
        let config = sample_config();
        let claude = harness(&config, "claude");

        let injection =
            compose_and_inject(&[], &claude.family, claude, &config, home.path(), true).unwrap();

        assert!(injection.prompt.is_none());
        assert!(injection.arguments.is_empty());
        assert!(injection.cache_path.is_none());
    }

    #[test]
    fn missing_bundle_reports_unavailable() {
        let home = TempDir::new().unwrap();
        // No prompter bundle written: the configured path does not exist.
        let config = sample_config();
        let claude = harness(&config, "claude");

        let error = compose_and_inject(
            &["core.base".to_string()],
            &claude.family,
            claude,
            &config,
            home.path(),
            false,
        )
        .unwrap_err();

        assert!(matches!(error, PromptError::Unavailable(_)));
    }

    #[test]
    fn prompt_cache_gc_removes_only_expired_files() {
        let temp = TempDir::new().unwrap();
        let expired = temp.path().join("expired.md");
        let current = temp.path().join("current.md");
        fs::write(&expired, "old").unwrap();
        std::thread::sleep(Duration::from_millis(5));
        fs::write(&current, "new").unwrap();
        let now = SystemTime::now();
        let expired_modified = fs::metadata(&expired).unwrap().modified().unwrap();
        let current_modified = fs::metadata(&current).unwrap().modified().unwrap();
        let threshold = now
            .duration_since(expired_modified)
            .unwrap()
            .checked_sub(Duration::from_millis(1))
            .unwrap();
        assert!(now.duration_since(current_modified).unwrap() < threshold);

        gc_prompt_cache(temp.path(), threshold, now);

        assert!(!expired.exists());
        assert!(current.exists());
    }

    #[test]
    fn gc_ignores_a_missing_cache_directory() {
        let temp = TempDir::new().unwrap();
        let absent = temp.path().join("no-such-cache");
        gc_prompt_cache(&absent, Duration::from_secs(0), SystemTime::now());
        assert!(!absent.exists());
    }

    #[test]
    fn gc_keeps_files_modified_after_the_reference_instant() {
        let temp = TempDir::new().unwrap();
        let kept = temp.path().join("future.md");
        fs::write(&kept, "keep").unwrap();
        // A reference instant before the file's modification time makes the age
        // computation fail, so the entry is skipped rather than deleted.
        gc_prompt_cache(temp.path(), Duration::from_secs(0), UNIX_EPOCH);
        assert!(kept.exists());
    }
}