cflx 0.6.189

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
//! Placeholder expansion utilities for command templates.

use std::borrow::Cow;

const PLACEHOLDER_CHANGE_ID: &str = "{change_id}";
const PLACEHOLDER_PROMPT: &str = "{prompt}";
const PLACEHOLDER_CONFLICT_FILES: &str = "{conflict_files}";
#[allow(dead_code)]
const PLACEHOLDER_PROPOSAL: &str = "{proposal}";
const PLACEHOLDER_WORKSPACE_DIR: &str = "{workspace_dir}";
const PLACEHOLDER_REPO_ROOT: &str = "{repo_root}";

/// Expand `{change_id}` placeholder in a command template.
///
/// # Example
///
/// ```ignore
/// let template = "agent run --apply {change_id}";
/// let result = expand_change_id(template, "update-auth");
/// assert_eq!(result, "agent run --apply update-auth");
/// ```
pub fn expand_change_id(template: &str, change_id: &str) -> String {
    expand_placeholder(template, PLACEHOLDER_CHANGE_ID, change_id)
}

/// Expand `{prompt}` placeholder in a command template.
///
/// Prompts are shell-escaped via `shlex::try_quote()` on POSIX platforms.
/// If the placeholder is already inside single quotes in the template,
/// the outer quotes are removed to avoid double-quoting.
///
/// # Example
///
/// ```ignore
/// let template = "claude '{prompt}'";
/// let result = expand_prompt(template, "Select the next change");
/// assert_eq!(result, "claude 'Select the next change'");
/// ```
pub fn expand_prompt(template: &str, prompt: &str) -> String {
    expand_placeholder(template, PLACEHOLDER_PROMPT, prompt)
}

/// Expand `{conflict_files}` placeholder in a command template.
#[allow(dead_code)]
pub fn expand_conflict_files(template: &str, conflict_files: &str) -> String {
    expand_placeholder(template, PLACEHOLDER_CONFLICT_FILES, conflict_files)
}

/// Expand `{proposal}` placeholder in a command template for proposing new changes.
///
/// # Example
///
/// ```ignore
/// let template = "opencode run '{proposal}'";
/// let result = expand_proposal(template, "Add user authentication feature");
/// assert_eq!(result, "opencode run 'Add user authentication feature'");
/// ```
#[allow(dead_code)]
pub fn expand_proposal(template: &str, proposal: &str) -> String {
    expand_placeholder(template, PLACEHOLDER_PROPOSAL, proposal)
}

/// Expand `{workspace_dir}` and `{repo_root}` placeholders in a command template.
pub fn expand_worktree_command(template: &str, workspace_dir: &str, repo_root: &str) -> String {
    let command = expand_placeholder(template, PLACEHOLDER_WORKSPACE_DIR, workspace_dir);
    expand_placeholder(&command, PLACEHOLDER_REPO_ROOT, repo_root)
}

pub fn expand_env_value(value: &str) -> String {
    let mut result = String::with_capacity(value.len());
    let mut chars = value.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch != '$' {
            result.push(ch);
            continue;
        }

        if chars.peek() == Some(&'{') {
            chars.next();
            let mut name = String::new();
            for next in chars.by_ref() {
                if next == '}' {
                    break;
                }
                name.push(next);
            }
            result.push_str(&std::env::var(name).unwrap_or_default());
            continue;
        }

        let mut name = String::new();
        while let Some(&next) = chars.peek() {
            if next == '_' || next.is_ascii_alphanumeric() {
                name.push(next);
                chars.next();
            } else {
                break;
            }
        }

        if name.is_empty() {
            result.push('$');
        } else {
            result.push_str(&std::env::var(name).unwrap_or_default());
        }
    }

    result
}

pub(crate) fn expand_placeholder(template: &str, placeholder: &str, value: &str) -> String {
    if !template.contains(placeholder) {
        return template.to_string();
    }

    let mut result = String::with_capacity(template.len() + value.len());
    let mut last_index = 0;

    for (index, _) in template.match_indices(placeholder) {
        let in_single_quotes = is_within_single_quotes(template, index);
        result.push_str(&template[last_index..index]);
        result.push_str(&escape_shell_value(value, in_single_quotes));
        last_index = index + placeholder.len();
    }

    result.push_str(&template[last_index..]);
    result
}

fn escape_shell_value(value: &str, in_single_quotes: bool) -> String {
    if cfg!(windows) {
        return sanitize_windows_value(value);
    }

    let sanitized = sanitize_posix_value(value);
    let quoted =
        shlex::try_quote(sanitized.as_ref()).unwrap_or_else(|_| Cow::Borrowed(sanitized.as_ref()));

    if in_single_quotes {
        if quoted.as_ref().starts_with('\'') && quoted.as_ref().ends_with('\'') {
            return strip_outer_single_quotes(quoted.as_ref()).to_string();
        }
        return escape_for_single_quoted_context(sanitized.as_ref());
    }

    quoted.to_string()
}

fn sanitize_posix_value(value: &str) -> Cow<'_, str> {
    if value.contains('\0') {
        Cow::Owned(value.replace('\0', ""))
    } else {
        Cow::Borrowed(value)
    }
}

fn sanitize_windows_value(value: &str) -> String {
    value
        .chars()
        .map(|c| match c {
            '\0' | '\r' | '\n' => ' ',
            _ => c,
        })
        .collect()
}

fn escape_for_single_quoted_context(value: &str) -> String {
    let sanitized = sanitize_posix_value(value);
    sanitized.as_ref().replace('\'', r"'\''")
}

fn strip_outer_single_quotes(value: &str) -> &str {
    if value.starts_with('\'') && value.ends_with('\'') && value.len() >= 2 {
        &value[1..value.len() - 1]
    } else {
        value
    }
}

fn is_within_single_quotes(template: &str, index: usize) -> bool {
    let mut in_single_quotes = false;
    let mut escaped = false;

    for (position, ch) in template.char_indices() {
        if position >= index {
            break;
        }

        if escaped {
            escaped = false;
            continue;
        }

        if ch == '\\' {
            escaped = true;
            continue;
        }

        if ch == '\'' {
            in_single_quotes = !in_single_quotes;
        }
    }

    in_single_quotes
}

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

    #[test]
    fn test_expand_env_value_from_parent_environment() {
        unsafe {
            std::env::set_var("CFLX_EXPAND_A", "alpha");
            std::env::set_var("CFLX_EXPAND_B", "beta");
            std::env::remove_var("CFLX_EXPAND_MISSING");
        }

        assert_eq!(
            expand_env_value(
                "$CFLX_EXPAND_A/${CFLX_EXPAND_B}/$CFLX_EXPAND_MISSING/${CFLX_EXPAND_A}"
            ),
            "alpha/beta//alpha"
        );
        assert_eq!(
            expand_env_value("$(echo nope) `${CFLX_EXPAND_A:-x}`"),
            "$(echo nope) ``"
        );
    }

    #[test]
    fn test_expand_change_id() {
        let template = "agent run --apply {change_id}";
        let result = expand_change_id(template, "update-auth");
        assert_eq!(result, "agent run --apply update-auth");
    }

    #[test]
    fn test_expand_change_id_multiple() {
        let template = "agent --id {change_id} --name {change_id}";
        let result = expand_change_id(template, "fix-bug");
        assert_eq!(result, "agent --id fix-bug --name fix-bug");
    }

    #[test]
    fn test_expand_change_id_with_whitespace() {
        let template = "agent run --apply {change_id}";
        let result = expand_change_id(template, "fix bug");
        assert_eq!(result, "agent run --apply 'fix bug'");
    }

    #[test]
    fn test_expand_prompt_unquoted_template() {
        let template = "claude {prompt}";
        let result = expand_prompt(template, "Select the next change");
        assert_eq!(result, "claude 'Select the next change'");
    }

    #[test]
    fn test_expand_prompt_single_quoted_template() {
        let template = "claude '{prompt}'";
        let result = expand_prompt(template, "Select the next change");
        assert_eq!(result, "claude 'Select the next change'");
    }

    #[test]
    fn test_expand_prompt_in_apply_command() {
        let template = "claude -p '/openspec:apply {change_id} {prompt}'";
        let command = expand_change_id(template, "fix-bug");
        let command = expand_prompt(&command, "Custom instructions");
        assert_eq!(
            command,
            "claude -p '/openspec:apply fix-bug Custom instructions'"
        );
    }

    #[test]
    fn test_expand_prompt_with_empty_string() {
        let template = "claude -p '/openspec:archive {change_id} {prompt}'";
        let command = expand_change_id(template, "add-feature");
        let command = expand_prompt(&command, "");
        assert_eq!(command, "claude -p '/openspec:archive add-feature '");
    }

    #[test]
    fn test_backward_compatible_no_prompt_placeholder() {
        // Commands without {prompt} placeholder should continue to work
        let template = "claude -p '/openspec:apply {change_id}'";
        let command = expand_change_id(template, "fix-bug");
        let command = expand_prompt(&command, "Ignored prompt");
        // The {prompt} replacement does nothing since placeholder doesn't exist
        assert_eq!(command, "claude -p '/openspec:apply fix-bug'");
    }

    #[test]
    fn test_expand_conflict_files() {
        let template = "resolve --files {conflict_files}";
        let result = expand_conflict_files(template, "file1.rs,file2.rs");
        let expected = format!(
            "resolve --files {}",
            shlex::try_quote("file1.rs,file2.rs").unwrap()
        );
        assert_eq!(result, expected);
    }

    #[test]
    fn test_expand_conflict_files_with_spaces() {
        let template = "resolve --files {conflict_files}";
        let result = expand_conflict_files(template, "file 1.rs file 2.rs");
        let expected = format!(
            "resolve --files {}",
            shlex::try_quote("file 1.rs file 2.rs").unwrap()
        );
        assert_eq!(result, expected);
    }

    #[test]
    fn test_expand_proposal() {
        let template = "opencode run {proposal}";
        let result = expand_proposal(template, "Add user authentication feature");
        assert_eq!(result, "opencode run 'Add user authentication feature'");
    }

    #[test]
    fn test_expand_proposal_multiline() {
        let template = "claude {proposal}";
        let text = "Feature request:\n- Add login\n- Add logout";
        let result = expand_proposal(template, text);
        assert_eq!(
            result,
            "claude 'Feature request:\n- Add login\n- Add logout'"
        );
    }

    #[test]
    fn test_expand_worktree_command() {
        let template = "run --cwd {workspace_dir} --repo {repo_root}";
        let result = expand_worktree_command(template, "/tmp/worktree", "/repo/root");
        assert_eq!(result, "run --cwd /tmp/worktree --repo /repo/root");
    }

    #[test]
    fn test_expand_worktree_command_escaped() {
        let template = "cmd {workspace_dir} {repo_root}";
        let result = expand_worktree_command(template, "/tmp/work tree", "/repo/root path");
        assert_eq!(result, "cmd '/tmp/work tree' '/repo/root path'");
    }

    #[test]
    fn test_expand_worktree_command_tmux_c_template() {
        let template = "tmux new-window -n wt -c {workspace_dir} -- opencode";
        let result = expand_worktree_command(template, "/tmp/work tree", "/repo/root");

        assert_eq!(
            result,
            "tmux new-window -n wt -c '/tmp/work tree' -- opencode"
        );
    }

    #[test]
    fn test_expand_worktree_command_cwd_based_template_still_works() {
        let template = "opencode run --repo {repo_root}";
        let result = expand_worktree_command(template, "/tmp/work tree", "/repo/root path");

        assert_eq!(result, "opencode run --repo '/repo/root path'");
    }

    #[test]
    fn test_expand_prompt_with_single_quotes() {
        let template = "claude -p 'apply {prompt}'";
        let result = expand_prompt(template, "it's a test");
        assert_eq!(result, "claude -p 'apply it'\\''s a test'");
    }

    #[test]
    fn test_expand_prompt_multiline() {
        let template = "claude {prompt}";
        let text = "Line 1\nLine 2\nLine 3";
        let result = expand_prompt(template, text);
        assert_eq!(result, "claude 'Line 1\nLine 2\nLine 3'");
    }

    #[test]
    fn test_expand_prompt_with_special_chars() {
        let template = "claude {prompt}";
        let prompt = "$HOME `echo` ! \\\\";
        let result = expand_prompt(template, prompt);
        let expected = format!("claude {}", shlex::try_quote(prompt).unwrap());
        assert_eq!(result, expected);
    }

    #[test]
    fn test_expand_prompt_multibyte_chars() {
        let template = "claude {prompt}";
        let result = expand_prompt(template, "こんにちは 🌟");
        assert_eq!(result, "claude 'こんにちは 🌟'");
    }

    #[test]
    fn test_expand_prompt_quoted_template_no_double_quotes() {
        let template = "claude '{prompt}'";
        let result = expand_prompt(template, "Hello world");
        assert_eq!(result, "claude 'Hello world'");
    }
}