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
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! Harness launch planning and Unix exec handoff.

use std::collections::{BTreeMap, BTreeSet};
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::process::Command;

use serde::Serialize;

use crate::cli::{DefaultArgsMode, LaunchRequest};
use crate::config::{Config, DomainConfig, DomainName, HarnessName, InvalidName, ModelName};
use crate::context::{
    ContextError, ResolvedContext, read_directory_config, resolve_context,
    resolve_context_with_directory,
};
use crate::prompt::{PromptError, compose_and_inject};

const CONTEXT_PLACEHOLDER: &str = "{context}";

pub(crate) const SESSION_ACTIVE_ENVIRONMENT: &str = "CLANKER_SESSION";
pub(crate) const SESSION_MARKER_VALUE: &str = "1";
pub(crate) const SESSION_VERSION_ENVIRONMENT: &str = "CLANKER_SESSION_VERSION";
pub(crate) const SESSION_VERSION: &str = "2";
pub(crate) const SESSION_INVOCATION_ENVIRONMENT: &str = "CLANKER_SESSION_INVOCATION";
pub(crate) const SESSION_HARNESS_ENVIRONMENT: &str = "CLANKER_SESSION_HARNESS";
pub(crate) const SESSION_CONTEXT_ENVIRONMENT: &str = "CLANKER_SESSION_CONTEXT";
pub(crate) const SESSION_CONTEXT_SOURCE_ENVIRONMENT: &str = "CLANKER_SESSION_CONTEXT_SOURCE";
pub(crate) const SESSION_DOMAINS_ENVIRONMENT: &str = "CLANKER_SESSION_DOMAINS";
pub(crate) const SESSION_MODEL_ENVIRONMENT: &str = "CLANKER_SESSION_MODEL";
pub(crate) const SESSION_FAMILY_ENVIRONMENT: &str = "CLANKER_SESSION_FAMILY";

/// Process-edge values required to build a launch plan.
#[derive(Debug, Clone, Copy)]
pub struct LaunchInputs<'a> {
    /// Home directory used for `~` expansion.
    pub home: &'a Path,
    /// Current working directory used for dotfile lookup.
    pub current_dir: &'a Path,
    /// Short hostname used for configured fallback selection.
    pub hostname: &'a str,
    /// `CONTEXT_OVERRIDE` value.
    pub context_override: Option<&'a str>,
    /// `CONTEXT` value.
    pub context_environment: Option<&'a str>,
    /// `CLANKER_DOMAIN_OVERRIDE` value.
    pub domain_override: Option<&'a str>,
    /// `CLANKER_DOMAIN` value.
    pub domain_environment: Option<&'a str>,
    /// `CLANKER_MODEL` value.
    pub model_environment: Option<&'a str>,
    /// Inherited `PATH` value.
    pub inherited_path: Option<&'a OsStr>,
    /// Inherited environment used for configured secret indirection.
    pub inherited_environment: &'a BTreeMap<OsString, OsString>,
}

/// Fully resolved process launch without prompt injection.
#[derive(Debug, Clone)]
pub struct LaunchPlan {
    /// Name through which clanker was invoked.
    pub invocation: String,
    /// Configured harness key.
    pub harness: HarnessName,
    /// Resolved context.
    pub context: ResolvedContext,
    /// Resolved domains in command-mode composition order.
    pub domains: Vec<DomainName>,
    /// Resolved model alias in command mode.
    pub model: Option<ModelName>,
    /// Resolved prompter family in command mode.
    pub family: Option<String>,
    /// Executable name or path.
    pub executable: OsString,
    /// Verbatim harness arguments.
    pub args: Vec<OsString>,
    /// Environment overrides applied to the inherited process environment.
    pub environment: BTreeMap<OsString, OsString>,
    /// Environment keys whose values must be redacted from dry-run output.
    pub secret_environment: BTreeSet<OsString>,
    /// Rendered prompt text when injection succeeded.
    pub prompt: Option<String>,
    /// File used for file-based prompt injection.
    pub prompt_file: Option<PathBuf>,
}

/// Serializable dry-run projection of [`LaunchPlan`].
#[derive(Debug, Serialize)]
pub struct LaunchPlanOutput {
    invocation: String,
    harness: String,
    context: String,
    context_source: &'static str,
    domains: Vec<String>,
    model: Option<String>,
    family: Option<String>,
    executable: String,
    args: Vec<String>,
    environment: BTreeMap<String, String>,
    prompt: Option<String>,
    prompt_file: Option<String>,
}

impl From<&LaunchPlan> for LaunchPlanOutput {
    fn from(plan: &LaunchPlan) -> Self {
        Self {
            invocation: plan.invocation.clone(),
            harness: plan.harness.to_string(),
            context: plan.context.name.to_string(),
            context_source: plan.context.source.label(),
            domains: plan.domains.iter().map(ToString::to_string).collect(),
            model: plan.model.as_ref().map(ToString::to_string),
            family: plan.family.clone(),
            executable: plan.executable.to_string_lossy().into_owned(),
            args: plan
                .args
                .iter()
                .map(|argument| argument.to_string_lossy().into_owned())
                .collect(),
            environment: plan
                .environment
                .iter()
                .map(|(key, value)| {
                    (
                        key.to_string_lossy().into_owned(),
                        if plan.secret_environment.contains(key) {
                            "<redacted>".to_string()
                        } else {
                            value.to_string_lossy().into_owned()
                        },
                    )
                })
                .collect(),
            prompt: plan.prompt.clone(),
            prompt_file: plan
                .prompt_file
                .as_ref()
                .map(|path| path.display().to_string()),
        }
    }
}

/// Failures resolving or executing a launch.
#[derive(Debug, thiserror::Error)]
pub enum LaunchError {
    /// Symlink invocation name does not follow the multi-call contract.
    #[error("invoked as `{0}`; expected a <harness>-launch symlink")]
    InvalidInvocation(String),
    /// Harness key does not exist in runtime configuration.
    #[error("unknown harness `{0}` in clanker config")]
    UnknownHarness(String),
    /// Domain key does not exist in runtime configuration.
    #[error("unknown domain `{0}` in clanker config")]
    UnknownDomain(String),
    /// Model key does not exist in runtime configuration.
    #[error("unknown model `{0}` in clanker config")]
    UnknownModel(String),
    /// A configured model cannot be used with the selected harness.
    #[error("model `{model}` requires harness `{required}`, not `{selected}`")]
    ModelHarnessMismatch {
        /// Selected model alias.
        model: ModelName,
        /// Harness required by the model.
        required: HarnessName,
        /// Harness selected for this launch.
        selected: HarnessName,
    },
    /// A configured secret source variable is absent.
    #[error(
        "model `{model}` requires environment variable `{source_variable}` for `{target}`; add `{source_variable}` to the SOPS-backed shell environment"
    )]
    MissingModelSecret {
        /// Selected model alias.
        model: ModelName,
        /// Target environment variable.
        target: String,
        /// Source secret environment variable.
        source_variable: String,
    },
    /// An ambient axis name is invalid.
    #[error("invalid {axis} from {origin}: {error}")]
    InvalidAxisName {
        /// Axis label.
        axis: &'static str,
        /// Value source.
        origin: &'static str,
        /// Name validation failure.
        error: InvalidName,
    },
    /// Context resolution failed.
    #[error(transparent)]
    Context(#[from] ContextError),
    /// A context-derived harness config directory does not exist.
    #[error(
        "{invocation}: config directory {} does not exist; create it or select a different context",
        path.display()
    )]
    MissingConfigDirectory {
        /// Invocation name.
        invocation: String,
        /// Missing directory path.
        path: PathBuf,
    },
    /// Prompt composition or injection failed.
    #[error(transparent)]
    Prompt(#[from] PromptError),
    /// A runtime path uses unsupported tilde syntax.
    #[error("unsupported configured path `{0}`; use `~` or `~/...`")]
    UnsupportedTilde(String),
    /// Configured shim path could not be joined with inherited `PATH`.
    #[error("failed to build launch PATH: {0}")]
    PathList(#[from] std::env::JoinPathsError),
    /// Final process exec failed.
    #[error("failed to exec `{executable}`: {source}")]
    Exec {
        /// Executable that failed.
        executable: String,
        /// Underlying OS error.
        source: std::io::Error,
    },
}

/// Build a launch plan from a `<harness>-launch` invocation name.
///
/// # Errors
/// Returns [`LaunchError`] for invalid invocation names, unknown harnesses,
/// context failures, or invalid configured paths.
pub fn build_symlink_plan(
    invocation: &str,
    args: Vec<OsString>,
    config: &Config,
    inputs: LaunchInputs<'_>,
) -> Result<LaunchPlan, LaunchError> {
    let harness = invocation
        .strip_suffix("-launch")
        .filter(|name| !name.is_empty())
        .ok_or_else(|| LaunchError::InvalidInvocation(invocation.to_string()))?;
    let harness = HarnessName::new(harness)
        .map_err(|_| LaunchError::InvalidInvocation(invocation.to_string()))?;
    build_harness_plan(invocation, harness, args, config, inputs)
}

/// Build a no-prompt launch plan for an explicitly selected harness.
///
/// # Errors
/// Returns [`LaunchError`] for unknown harnesses, context failures, or invalid
/// configured paths.
pub fn build_harness_plan(
    invocation: &str,
    harness: HarnessName,
    args: Vec<OsString>,
    config: &Config,
    inputs: LaunchInputs<'_>,
) -> Result<LaunchPlan, LaunchError> {
    let context = resolve_context(
        inputs.current_dir,
        None,
        inputs.context_override,
        inputs.context_environment,
        inputs.hostname,
        config,
    )?;
    let mut plan =
        build_harness_plan_for_context(invocation, harness, args, config, inputs, context)?;
    apply_session_environment(&mut plan);
    Ok(plan)
}

fn build_harness_plan_for_context(
    invocation: &str,
    harness: HarnessName,
    args: Vec<OsString>,
    config: &Config,
    inputs: LaunchInputs<'_>,
    context: ResolvedContext,
) -> Result<LaunchPlan, LaunchError> {
    let harness_config = config
        .harness
        .get(&harness)
        .ok_or_else(|| LaunchError::UnknownHarness(harness.to_string()))?;
    let shim_path = expand_path(&config.defaults.shim_path, inputs.home)?;
    let mut path_parts = vec![shim_path];
    if let Some(inherited) = inputs.inherited_path {
        path_parts.extend(std::env::split_paths(inherited));
    }
    let launch_path = std::env::join_paths(path_parts)?;

    let mut environment = BTreeMap::new();
    environment.insert(OsString::from("PATH"), launch_path);
    environment.insert(
        OsString::from("CONTEXT"),
        OsString::from(context.name.as_str()),
    );
    if let Some(config_dir) = &harness_config.config_dir {
        let configured = config_dir
            .path
            .replace(CONTEXT_PLACEHOLDER, context.name.as_str());
        let path = expand_path(&configured, inputs.home)?;
        if !path.is_dir() {
            return Err(LaunchError::MissingConfigDirectory {
                invocation: invocation.to_string(),
                path,
            });
        }
        environment.insert(
            OsString::from(&config_dir.environment),
            path.as_os_str().to_os_string(),
        );
    }

    Ok(LaunchPlan {
        invocation: invocation.to_string(),
        harness,
        context,
        domains: Vec::new(),
        model: None,
        family: None,
        executable: OsString::from(&harness_config.bin),
        args,
        environment,
        secret_environment: BTreeSet::new(),
        prompt: None,
        prompt_file: None,
    })
}

/// Build a fully composed command-mode launch plan.
///
/// # Errors
/// Returns [`LaunchError`] for invalid or unknown axes, model/harness
/// incompatibility, missing model secrets, context failures, or invalid paths.
pub fn build_command_plan(
    invocation: &str,
    request: &LaunchRequest,
    config: &Config,
    inputs: LaunchInputs<'_>,
    persist_prompt_file: bool,
) -> Result<LaunchPlan, LaunchError> {
    let directory_config = read_directory_config(inputs.current_dir)?;
    let context = resolve_context_with_directory(
        request.context.as_ref(),
        inputs.context_override,
        inputs.context_environment,
        inputs.hostname,
        config,
        directory_config.as_ref(),
    )?;
    let domains = resolve_domains(request, directory_config.as_ref(), config, inputs)?;
    let domain_configs = domains
        .iter()
        .map(|domain| {
            config
                .domain
                .get(domain)
                .ok_or_else(|| LaunchError::UnknownDomain(domain.to_string()))
        })
        .collect::<Result<Vec<_>, _>>()?;
    let model = resolve_model(request, directory_config.as_ref(), &domain_configs, inputs)?;
    if let Some(model) = &model {
        if !config.model.contains_key(model) {
            return Err(LaunchError::UnknownModel(model.to_string()));
        }
    }
    let model_config = model.as_ref().and_then(|name| config.model.get(name));

    let mut plan = build_harness_plan_for_context(
        invocation,
        request.harness.clone(),
        request.passthrough.clone(),
        config,
        inputs,
        context,
    )?;
    plan.domains.clone_from(&domains);

    if let (Some(model_name), Some(model_config)) = (&model, model_config) {
        if model_config.harness == request.harness {
            plan.model = Some(model_name.clone());
        } else {
            return Err(LaunchError::ModelHarnessMismatch {
                model: model_name.clone(),
                required: model_config.harness.clone(),
                selected: request.harness.clone(),
            });
        }
    }

    let harness_config = config
        .harness
        .get(&request.harness)
        .ok_or_else(|| LaunchError::UnknownHarness(request.harness.to_string()))?;
    let applied_model = plan.model.as_ref().and_then(|name| config.model.get(name));
    let family = applied_model
        .and_then(|model| model.family.as_ref())
        .unwrap_or(&harness_config.family);
    plan.family = Some(family.as_prompter_family().as_str().to_string());

    let mut arguments: Vec<OsString> = match request.default_args {
        DefaultArgsMode::Suppress => Vec::new(),
        DefaultArgsMode::Apply => harness_config
            .default_args
            .iter()
            .map(OsString::from)
            .collect(),
    };
    if !request.no_prompt {
        let mut profiles = domain_configs
            .iter()
            .flat_map(|domain| domain.profiles.iter().cloned())
            .collect::<Vec<_>>();
        profiles.extend(request.profiles.iter().cloned());
        let injection = compose_and_inject(
            &profiles,
            family,
            harness_config,
            config,
            inputs.home,
            persist_prompt_file,
        )?;
        arguments.extend(injection.arguments);
        plan.environment.extend(injection.environment);
        plan.prompt = injection.prompt;
        plan.prompt_file = injection.cache_path;
    }
    if let Some(model_config) = applied_model {
        arguments.extend(model_config.harness_args.iter().map(OsString::from));
    }
    arguments.append(&mut plan.args);
    plan.args = arguments;

    apply_domain_environment(&mut plan, &domain_configs);
    if let (Some(model_name), Some(model_config)) = (plan.model.clone(), applied_model) {
        apply_model_environment(&mut plan, &model_name, model_config, inputs)?;
    }

    if request.sandbox {
        let wrapper = expand_path(&config.defaults.sandbox_wrapper, inputs.home)?;
        let mut sandbox_arguments = vec![plan.executable.clone()];
        sandbox_arguments.append(&mut plan.args);
        plan.executable = wrapper.into_os_string();
        plan.args = sandbox_arguments;
    }

    apply_session_environment(&mut plan);
    Ok(plan)
}

fn resolve_domains(
    request: &LaunchRequest,
    directory_config: Option<&crate::context::DirectoryConfig>,
    config: &Config,
    inputs: LaunchInputs<'_>,
) -> Result<Vec<DomainName>, LaunchError> {
    let domains = if request.domains.is_empty() {
        vec![resolve_fallback_domain(directory_config, config, inputs)?]
    } else {
        request.domains.clone()
    };

    for domain in &domains {
        if !config.domain.contains_key(domain) {
            return Err(LaunchError::UnknownDomain(domain.to_string()));
        }
    }
    Ok(domains)
}

fn resolve_fallback_domain(
    directory_config: Option<&crate::context::DirectoryConfig>,
    config: &Config,
    inputs: LaunchInputs<'_>,
) -> Result<DomainName, LaunchError> {
    if let Some(domain) = parse_optional_domain(inputs.domain_override, "CLANKER_DOMAIN_OVERRIDE")?
    {
        Ok(domain)
    } else if let Some(domain) = directory_config.and_then(|directory| directory.domain.clone()) {
        Ok(domain)
    } else if let Some(domain) = parse_optional_domain(inputs.domain_environment, "CLANKER_DOMAIN")?
    {
        Ok(domain)
    } else {
        Ok(config.defaults.domain.clone())
    }
}

fn resolve_model(
    request: &LaunchRequest,
    directory_config: Option<&crate::context::DirectoryConfig>,
    domains: &[&DomainConfig],
    inputs: LaunchInputs<'_>,
) -> Result<Option<ModelName>, LaunchError> {
    if let Some(model) = &request.model {
        return Ok(Some(model.clone()));
    }
    if let Some(model) = directory_config.and_then(|directory| directory.model.clone()) {
        return Ok(Some(model));
    }
    if let Some(model) = parse_optional_model(inputs.model_environment, "CLANKER_MODEL")? {
        return Ok(Some(model));
    }
    Ok(domains
        .iter()
        .find_map(|domain| domain.default_model.clone()))
}

fn parse_optional_domain(
    value: Option<&str>,
    origin: &'static str,
) -> Result<Option<DomainName>, LaunchError> {
    parse_optional_axis(value, "domain", origin, DomainName::new)
}

fn parse_optional_model(
    value: Option<&str>,
    origin: &'static str,
) -> Result<Option<ModelName>, LaunchError> {
    parse_optional_axis(value, "model", origin, ModelName::new)
}

fn parse_optional_axis<T>(
    value: Option<&str>,
    axis: &'static str,
    origin: &'static str,
    parse: impl FnOnce(String) -> Result<T, InvalidName>,
) -> Result<Option<T>, LaunchError> {
    let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
        return Ok(None);
    };
    parse(value.to_string())
        .map(Some)
        .map_err(|error| LaunchError::InvalidAxisName {
            axis,
            origin,
            error,
        })
}

fn apply_domain_environment(plan: &mut LaunchPlan, domains: &[&DomainConfig]) {
    let mut environment = BTreeMap::new();
    for domain in domains {
        for (key, value) in &domain.env {
            environment
                .entry(OsString::from(key))
                .or_insert_with(|| OsString::from(value));
        }
    }
    plan.environment.extend(environment);
}

fn apply_model_environment(
    plan: &mut LaunchPlan,
    model_name: &ModelName,
    model: &crate::config::ModelConfig,
    inputs: LaunchInputs<'_>,
) -> Result<(), LaunchError> {
    plan.environment.extend(
        model
            .env
            .iter()
            .map(|(key, value)| (OsString::from(key), OsString::from(value))),
    );
    for (target, source) in &model.env_from_secrets {
        let source_key = OsStr::new(source);
        let value = inputs
            .inherited_environment
            .get(source_key)
            .ok_or_else(|| LaunchError::MissingModelSecret {
                model: model_name.clone(),
                target: target.clone(),
                source_variable: source.clone(),
            })?;
        let target = OsString::from(target);
        plan.environment.insert(target.clone(), value.clone());
        plan.secret_environment.insert(target);
    }
    Ok(())
}

fn apply_session_environment(plan: &mut LaunchPlan) {
    let domains = plan
        .domains
        .iter()
        .map(DomainName::as_str)
        .collect::<Vec<_>>()
        .join(",");
    let values = [
        (SESSION_ACTIVE_ENVIRONMENT, SESSION_MARKER_VALUE),
        (SESSION_VERSION_ENVIRONMENT, SESSION_VERSION),
        (SESSION_INVOCATION_ENVIRONMENT, plan.invocation.as_str()),
        (SESSION_HARNESS_ENVIRONMENT, plan.harness.as_str()),
        (SESSION_CONTEXT_ENVIRONMENT, plan.context.name.as_str()),
        (
            SESSION_CONTEXT_SOURCE_ENVIRONMENT,
            plan.context.source.label(),
        ),
        (SESSION_DOMAINS_ENVIRONMENT, domains.as_str()),
        (
            SESSION_MODEL_ENVIRONMENT,
            plan.model.as_ref().map_or("", ModelName::as_str),
        ),
        (
            SESSION_FAMILY_ENVIRONMENT,
            plan.family.as_deref().unwrap_or(""),
        ),
    ];
    plan.environment.extend(
        values
            .into_iter()
            .map(|(key, value)| (OsString::from(key), OsString::from(value))),
    );
}

/// Replace the current process with the resolved harness.
///
/// # Errors
/// Returns [`LaunchError::Exec`] only when the operating system rejects the
/// exec; successful execution never returns.
#[cfg(unix)]
pub fn execute_plan(plan: &LaunchPlan) -> Result<i32, LaunchError> {
    use std::os::unix::process::CommandExt;

    let mut command = Command::new(&plan.executable);
    command.args(&plan.args);
    for (key, value) in &plan.environment {
        command.env(key, value);
    }
    let executable = plan.executable.to_string_lossy().into_owned();
    let source = command.exec();
    Err(LaunchError::Exec { executable, source })
}

pub(crate) fn expand_path(value: &str, home: &Path) -> Result<PathBuf, LaunchError> {
    if value == "~" {
        return Ok(home.to_path_buf());
    }
    if let Some(relative) = value.strip_prefix("~/") {
        return Ok(home.join(relative));
    }
    if value.starts_with('~') {
        return Err(LaunchError::UnsupportedTilde(value.to_string()));
    }
    Ok(PathBuf::from(value))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn expands_only_supported_tilde_forms() {
        let home = Path::new("/tmp/home");
        assert_eq!(expand_path("~", home).unwrap(), home);
        assert_eq!(
            expand_path("~/.config/tool", home).unwrap(),
            home.join(".config/tool")
        );
        assert!(expand_path("~someone/tool", home).is_err());
    }
}