tftio-prompter 4.0.2

A CLI tool for composing reusable prompt snippets from a library using TOML profiles
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
//! Profile rendering and output formatting.
use crate::config::Config;
use crate::config::load_bundle;
use crate::profile::{FamilyName, resolve_profile_for_family};
use crate::{
    FragmentOutput, Framing, PrompterError, RenderOutput, default_post_prompt, default_pre_prompt,
    format_system_prefix,
};
use chrono::Local;
use std::collections::HashSet;
use std::env;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use tftio_lib::{JsonOutput, render_response};

/// Render one or more profiles to the given writer.
///
/// # Errors
/// Returns an error if profile resolution fails (missing files, cycles, unknown
/// profiles), if reading a fragment fails, or if writing to the sink fails.
#[allow(
    clippy::too_many_arguments,
    reason = "stable 4.x public rendering API; the parameters are the rendering knobs and cannot be repacked without a breaking change"
)]
pub fn render_to_writer(
    cfg: &Config,
    mut w: impl Write,
    profiles: &[String],
    family: Option<&FamilyName>,
    separator: Option<&str>,
    pre_prompt: Option<&str>,
    post_prompt: Option<&str>,
    framing: Framing,
    output: JsonOutput,
) -> Result<(), PrompterError> {
    let mut seen_files = HashSet::new();
    let mut files: Vec<(PathBuf, PathBuf)> = Vec::new();

    // Resolve all profiles with shared deduplication
    for profile in profiles {
        let mut stack = Vec::new();
        resolve_profile_for_family(
            profile,
            cfg,
            family,
            &mut seen_files,
            &mut stack,
            &mut files,
        )?;
    }

    if output.is_json() {
        return write_json_render(&mut w, &files, profiles, pre_prompt, framing);
    }

    // Text output mode. Bare framing suppresses every auto-injected piece —
    // the default pre-prompt, the date/system prefix, and the default (and
    // config) post-prompt — leaving only the fragment bodies. An explicit
    // -p/-P still wins: the user asked for that exact text.
    let default_pre = default_pre_prompt();
    let pre_prompt_text = match (pre_prompt, framing) {
        (Some(explicit), _) => Some(explicit),
        (None, Framing::Full) => Some(default_pre.as_str()),
        (None, Framing::Bare) => None,
    };
    if let Some(text) = pre_prompt_text {
        w.write_all(text.as_bytes()).map_err(PrompterError::Write)?;
    }

    // Date/system stamp is auto-injected, so it appears only in full framing;
    // it is the cache-buster bare exists to drop.
    if framing.is_full() {
        w.write_all(b"\n").map_err(PrompterError::Write)?;
        let prefix = format_system_prefix();
        w.write_all(prefix.as_bytes())
            .map_err(PrompterError::Write)?;
    }

    let sep = separator.unwrap_or("");
    for (index, (path, _library_root)) in files.iter().enumerate() {
        // Newline before each file. In bare framing the leading newline is
        // dropped so the output begins directly with the first fragment.
        if framing.is_full() || index > 0 {
            w.write_all(b"\n").map_err(PrompterError::Write)?;
        }

        let bytes = fs::read(path).map_err(|source| PrompterError::Io {
            path: path.clone(),
            source,
        })?;
        w.write_all(&bytes).map_err(PrompterError::Write)?;

        // Write separator after each file if provided
        if !sep.is_empty() {
            w.write_all(sep.as_bytes()).map_err(PrompterError::Write)?;
        }
    }

    // Post-prompt: explicit -P wins. Full falls back to the config post-prompt
    // then the default; bare emits nothing without an explicit -P. The full
    // framing keeps its two-newline lead-in; bare writes the explicit text
    // verbatim so nothing is auto-injected.
    let default_post = default_post_prompt();
    let post_prompt_text = match framing {
        Framing::Full => Some(
            post_prompt
                .or(cfg.post_prompt.as_deref())
                .unwrap_or(&default_post),
        ),
        Framing::Bare => post_prompt,
    };
    if let Some(text) = post_prompt_text {
        if framing.is_full() {
            w.write_all(b"\n\n").map_err(PrompterError::Write)?;
        }
        w.write_all(text.as_bytes()).map_err(PrompterError::Write)?;
    }

    Ok(())
}

/// Render the deduplicated fragments as the shared JSON response envelope.
///
/// Bare framing drops the auto-injected default pre-prompt and the date/system
/// stamp, leaving the fragments as the payload; an explicit `pre_prompt` still
/// wins.
fn write_json_render(
    mut w: impl Write,
    files: &[(PathBuf, PathBuf)],
    profiles: &[String],
    pre_prompt: Option<&str>,
    framing: Framing,
) -> Result<(), PrompterError> {
    let pre_prompt_text = match pre_prompt {
        Some(explicit) => explicit.to_string(),
        None if framing.is_full() => default_pre_prompt(),
        None => String::new(),
    };

    let system_info = if framing.is_full() {
        let date = Local::now().format("%Y-%m-%d").to_string();
        let os = env::consts::OS;
        let arch = env::consts::ARCH;
        format!("Today is {date}, and you are running on a {arch}/{os} system.")
    } else {
        String::new()
    };

    let mut fragments = Vec::new();
    for (path, library_root) in files {
        let content = fs::read_to_string(path).map_err(|source| PrompterError::Io {
            path: path.clone(),
            source,
        })?;
        let rel_path = path
            .strip_prefix(library_root)
            .unwrap_or(path)
            .display()
            .to_string();
        fragments.push(FragmentOutput {
            path: rel_path,
            content,
        });
    }

    let payload = serde_json::to_value(RenderOutput {
        profile: profiles.join(", "),
        pre_prompt: pre_prompt_text,
        system_info,
        fragments,
    })?;
    writeln!(
        &mut w,
        "{}",
        render_response("run", JsonOutput::Json, payload, String::new())
    )
    .map_err(PrompterError::Write)
}

/// Render one or more profiles to stdout.
///
/// Convenience function that reads configuration and renders the specified
/// profiles to standard output with optional separator, pre-prompt, and post-prompt.
/// When multiple profiles are provided, files are deduplicated across all profiles.
///
/// # Arguments
/// * `profiles` - Profile names to render (deduplicated in order)
/// * `family` - Optional family used to substitute matching fragment variants
/// * `separator` - Optional separator between files
/// * `pre_prompt` - Optional custom pre-prompt text
/// * `post_prompt` - Optional custom post-prompt text
/// * `framing` - Whether to wrap fragments in framing context or emit bare bodies
/// * `config_override` - Optional configuration file override
/// * `json` - Whether to output in JSON format
///
/// # Errors
/// Returns an error if:
/// - Configuration file cannot be read or parsed
/// - Profile resolution fails
/// - Writing to stdout fails
#[allow(
    clippy::too_many_arguments,
    reason = "stable 4.x public rendering API; the parameters are the rendering knobs and cannot be repacked without a breaking change"
)]
pub fn run_render_stdout(
    profiles: &[String],
    family: Option<&FamilyName>,
    separator: Option<&str>,
    pre_prompt: Option<&str>,
    post_prompt: Option<&str>,
    framing: Framing,
    config_override: Option<&Path>,
    output: JsonOutput,
) -> Result<(), PrompterError> {
    let (_cfg_path, cfg) = load_bundle(config_override)?;
    let stdout = io::stdout();
    let handle = stdout.lock();
    render_to_writer(
        &cfg,
        handle,
        profiles,
        family,
        separator,
        pre_prompt,
        post_prompt,
        framing,
        output,
    )
}

/// Render composed profiles to a byte vector.
///
/// Convenience wrapper around [`render_to_writer`] that handles config
/// resolution and returns the rendered output as bytes. Intended for
/// use by other crates that need prompt composition as a library.
///
/// # Arguments
/// * `profiles` - Profile names to compose
/// * `family` - Optional family used to substitute matching fragment variants
/// * `config_override` - Optional path to custom config file
///
/// # Errors
/// Returns an error if config resolution, profile resolution, or rendering fails.
pub fn render_to_vec(
    profiles: &[String],
    family: Option<&FamilyName>,
    config_override: Option<&Path>,
) -> Result<Vec<u8>, PrompterError> {
    let (_cfg_path, cfg) = load_bundle(config_override)?;
    let mut buf = Vec::new();
    render_to_writer(
        &cfg,
        &mut buf,
        profiles,
        family,
        None,
        None,
        None,
        Framing::Full,
        JsonOutput::Text,
    )?;
    Ok(buf)
}

#[cfg(test)]
#[allow(clippy::wildcard_imports)]
mod tests {
    use super::*;
    use crate::config::ProfileDef;
    use std::collections::HashMap;
    use std::sync::atomic::{AtomicU32, Ordering};

    static COUNTER: AtomicU32 = AtomicU32::new(0);

    fn mk_tmp(prefix: &str) -> PathBuf {
        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!("{prefix}_{}_{n}", std::process::id()))
    }

    fn cfg_one(name: &str, deps: Vec<&str>, lib: &Path) -> Config {
        let mut profiles = HashMap::new();
        profiles.insert(
            name.to_string(),
            ProfileDef {
                deps: deps.into_iter().map(String::from).collect(),
                library_root: lib.to_path_buf(),
            },
        );
        Config {
            profiles,
            post_prompt: None,
        }
    }

    #[test]
    fn text_render_errors_when_fragment_path_is_a_directory() {
        // The dep resolves (the path exists) but reading it as a file fails
        // because it is a directory, surfacing a typed I/O error.
        let lib = mk_tmp("prompter_render_dir_frag");
        fs::create_dir_all(lib.join("a/x.md")).unwrap();
        let cfg = cfg_one("p", vec!["a/x.md"], &lib);
        let mut out = Vec::new();
        let err = render_to_writer(
            &cfg,
            &mut out,
            &["p".to_string()],
            None,
            None,
            None,
            None,
            Framing::Full,
            JsonOutput::Text,
        )
        .unwrap_err();
        assert!(matches!(err, PrompterError::Io { .. }), "err={err}");
        fs::remove_dir_all(&lib).ok();
    }

    #[test]
    fn json_render_full_carries_explicit_pre_prompt_and_system_info() {
        let lib = mk_tmp("prompter_json_pre");
        fs::create_dir_all(lib.join("a")).unwrap();
        fs::write(lib.join("a/x.md"), b"XC\n").unwrap();
        let cfg = cfg_one("p", vec!["a/x.md"], &lib);
        let mut out = Vec::new();
        render_to_writer(
            &cfg,
            &mut out,
            &["p".to_string()],
            None,
            None,
            Some("MY-PRE"),
            None,
            Framing::Full,
            JsonOutput::Json,
        )
        .unwrap();
        let envelope: serde_json::Value =
            serde_json::from_str(std::str::from_utf8(&out).unwrap().trim()).unwrap();
        assert_eq!(envelope["data"]["pre_prompt"].as_str(), Some("MY-PRE"));
        assert!(
            envelope["data"]["system_info"]
                .as_str()
                .unwrap()
                .contains("Today is "),
            "envelope={envelope}"
        );
        assert_eq!(
            envelope["data"]["fragments"][0]["path"].as_str(),
            Some("a/x.md")
        );
        fs::remove_dir_all(&lib).ok();
    }

    #[test]
    fn json_render_bare_drops_pre_prompt_and_system_info() {
        let lib = mk_tmp("prompter_json_bare");
        fs::create_dir_all(lib.join("a")).unwrap();
        fs::write(lib.join("a/x.md"), b"XC\n").unwrap();
        let cfg = cfg_one("p", vec!["a/x.md"], &lib);
        let mut out = Vec::new();
        render_to_writer(
            &cfg,
            &mut out,
            &["p".to_string()],
            None,
            None,
            None,
            None,
            Framing::Bare,
            JsonOutput::Json,
        )
        .unwrap();
        let envelope: serde_json::Value =
            serde_json::from_str(std::str::from_utf8(&out).unwrap().trim()).unwrap();
        assert_eq!(envelope["data"]["pre_prompt"].as_str(), Some(""));
        assert_eq!(envelope["data"]["system_info"].as_str(), Some(""));
        fs::remove_dir_all(&lib).ok();
    }

    #[test]
    fn json_render_errors_when_fragment_path_is_a_directory() {
        let lib = mk_tmp("prompter_json_dir_frag");
        fs::create_dir_all(lib.join("a/x.md")).unwrap();
        let cfg = cfg_one("p", vec!["a/x.md"], &lib);
        let mut out = Vec::new();
        let err = render_to_writer(
            &cfg,
            &mut out,
            &["p".to_string()],
            None,
            None,
            None,
            None,
            Framing::Full,
            JsonOutput::Json,
        )
        .unwrap_err();
        assert!(matches!(err, PrompterError::Io { .. }), "err={err}");
        fs::remove_dir_all(&lib).ok();
    }

    #[test]
    fn render_to_vec_propagates_resolution_error() {
        let dir = mk_tmp("prompter_render_to_vec_err");
        fs::create_dir_all(dir.join("library")).unwrap();
        fs::write(
            dir.join("config.toml"),
            "[root]\ndepends_on = [\"missing.md\"]\n",
        )
        .unwrap();
        let err =
            render_to_vec(&["root".to_string()], None, Some(&dir.join("config.toml"))).unwrap_err();
        assert!(matches!(err, PrompterError::Resolve(_)), "err={err}");
        fs::remove_dir_all(&dir).ok();
    }
}