cflx 0.6.20

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
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
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use thiserror::Error;
use unicode_normalization::UnicodeNormalization;

#[derive(Debug, Error)]
pub enum SpecTestAnnotationError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Spec parsing error: {0}")]
    Parse(String),
}

type Result<T> = std::result::Result<T, SpecTestAnnotationError>;

static REQUIREMENT_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^### Requirement:\s*(.+)\s*$").unwrap());
static SCENARIO_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^#### Scenario:\s*(.+)\s*$").unwrap());
static UI_ONLY_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)ui[-_ ]?only").unwrap());
static ANNOTATION_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"//\s*OPENSPEC:\s*(\S+)").unwrap());

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct SpecScenarioRef {
    spec_path: String,
    requirement_slug: String,
    scenario_slug: String,
}

impl SpecScenarioRef {
    fn new(spec_path: String, requirement_slug: String, scenario_slug: String) -> Self {
        Self {
            spec_path,
            requirement_slug,
            scenario_slug,
        }
    }

    fn format_reference(&self) -> String {
        format!(
            "{}#{}/{}",
            self.spec_path, self.requirement_slug, self.scenario_slug
        )
    }
}

impl fmt::Display for SpecScenarioRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.format_reference())
    }
}

#[derive(Debug, Clone)]
struct SpecScenario {
    reference: SpecScenarioRef,
    ui_only: bool,
}

#[derive(Debug, Clone)]
struct SpecReference {
    reference: SpecScenarioRef,
    location: String,
}

#[derive(Debug, Default)]
struct AnnotationScanResult {
    references: Vec<SpecReference>,
    broken: Vec<BrokenReference>,
}

#[derive(Debug, Clone)]
struct BrokenReference {
    reference: String,
    location: String,
    reason: String,
}

#[derive(Debug, Default)]
struct SpecCheckReport {
    missing: Vec<SpecScenarioRef>,
    broken: Vec<BrokenReference>,
}

impl SpecCheckReport {
    fn format_report(&self) -> String {
        let mut output = Vec::new();
        if !self.missing.is_empty() {
            output.push("Missing spec coverage:".to_string());
            for missing in &self.missing {
                output.push(format!("  - {}", missing));
            }
        }
        if !self.broken.is_empty() {
            if !output.is_empty() {
                output.push("".to_string());
            }
            output.push("Broken spec references:".to_string());
            for broken in &self.broken {
                output.push(format!(
                    "  - {} ({}): {}",
                    broken.reference, broken.location, broken.reason
                ));
            }
        }
        output.join("\n")
    }
}

fn slugify_heading(input: &str) -> String {
    let normalized = input.nfkc().collect::<String>().to_lowercase();
    let mut slug = String::new();
    let mut last_was_dash = false;

    for ch in normalized.chars() {
        if ch.is_alphanumeric() {
            slug.push(ch);
            last_was_dash = false;
        } else if !last_was_dash {
            slug.push('-');
            last_was_dash = true;
        }
    }

    while slug.starts_with('-') {
        slug.remove(0);
    }
    while slug.ends_with('-') {
        slug.pop();
    }

    slug
}

fn normalize_path(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

#[allow(clippy::too_many_arguments)]
fn finalize_scenario(
    scenario_title: Option<String>,
    lines: &[String],
    current_requirement: &Option<String>,
    current_requirement_slug: &Option<String>,
    spec_path_string: &str,
    spec_path: &Path,
    scenarios: &mut Vec<SpecScenario>,
) -> Result<()> {
    if let Some(scenario_title) = scenario_title {
        let requirement_title = current_requirement.clone().ok_or_else(|| {
            SpecTestAnnotationError::Parse(format!(
                "Scenario '{}' appears before any requirement in {}",
                scenario_title,
                spec_path.display()
            ))
        })?;
        let requirement_slug = current_requirement_slug
            .clone()
            .unwrap_or_else(|| slugify_heading(&requirement_title));
        let scenario_slug = slugify_heading(&scenario_title);
        let ui_only = lines.iter().any(|line| UI_ONLY_REGEX.is_match(line));

        scenarios.push(SpecScenario {
            reference: SpecScenarioRef::new(
                spec_path_string.to_string(),
                requirement_slug,
                scenario_slug,
            ),
            ui_only,
        });
    }
    Ok(())
}

fn collect_spec_files(dir: &Path, specs: &mut Vec<PathBuf>) -> Result<()> {
    let entries = fs::read_dir(dir)?;
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_spec_files(&path, specs)?;
        } else if path.file_name().is_some_and(|name| name == "spec.md") {
            specs.push(path);
        }
    }
    Ok(())
}

fn parse_spec_file(spec_path: &Path, repo_root: &Path) -> Result<Vec<SpecScenario>> {
    let content = fs::read_to_string(spec_path)?;

    let spec_path_relative = spec_path
        .strip_prefix(repo_root)
        .map_err(|_| {
            SpecTestAnnotationError::Parse(format!(
                "Spec path '{}' is outside repo root",
                spec_path.display()
            ))
        })?
        .to_path_buf();
    let spec_path_string = normalize_path(&spec_path_relative);

    let mut scenarios = Vec::new();
    let mut current_requirement: Option<String> = None;
    let mut current_requirement_slug: Option<String> = None;
    let mut current_scenario: Option<String> = None;
    let mut current_lines: Vec<String> = Vec::new();

    for line in content.lines() {
        if let Some(caps) = REQUIREMENT_REGEX.captures(line) {
            finalize_scenario(
                current_scenario.take(),
                &current_lines,
                &current_requirement,
                &current_requirement_slug,
                &spec_path_string,
                spec_path,
                &mut scenarios,
            )?;
            current_lines.clear();
            let requirement_title = caps[1].trim().to_string();
            current_requirement_slug = Some(slugify_heading(&requirement_title));
            current_requirement = Some(requirement_title);
            continue;
        }

        if let Some(caps) = SCENARIO_REGEX.captures(line) {
            finalize_scenario(
                current_scenario.take(),
                &current_lines,
                &current_requirement,
                &current_requirement_slug,
                &spec_path_string,
                spec_path,
                &mut scenarios,
            )?;
            current_lines.clear();
            current_scenario = Some(caps[1].trim().to_string());
            continue;
        }

        if current_scenario.is_some() {
            current_lines.push(line.to_string());
        }
    }

    finalize_scenario(
        current_scenario.take(),
        &current_lines,
        &current_requirement,
        &current_requirement_slug,
        &spec_path_string,
        spec_path,
        &mut scenarios,
    )?;
    Ok(scenarios)
}

fn collect_spec_scenarios(repo_root: &Path) -> Result<Vec<SpecScenario>> {
    let spec_root = repo_root.join("openspec").join("specs");
    let mut spec_files = Vec::new();
    collect_spec_files(&spec_root, &mut spec_files)?;

    let mut scenarios = Vec::new();
    for spec_file in spec_files {
        scenarios.extend(parse_spec_file(&spec_file, repo_root)?);
    }
    Ok(scenarios)
}

fn collect_rs_files(dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
    let entries = fs::read_dir(dir)?;
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_rs_files(&path, files)?;
        } else if path.extension().is_some_and(|ext| ext == "rs") {
            files.push(path);
        }
    }
    Ok(())
}

fn parse_reference(reference: &str) -> Result<SpecScenarioRef> {
    let (spec_path, rest) = reference.split_once('#').ok_or_else(|| {
        SpecTestAnnotationError::Parse(format!("Missing '#' in reference: {}", reference))
    })?;
    let (requirement_slug, scenario_slug) = rest.split_once('/').ok_or_else(|| {
        SpecTestAnnotationError::Parse(format!("Missing '/' in reference: {}", reference))
    })?;
    if requirement_slug.is_empty() || scenario_slug.is_empty() {
        return Err(SpecTestAnnotationError::Parse(format!(
            "Empty slug in reference: {}",
            reference
        )));
    }

    Ok(SpecScenarioRef::new(
        spec_path.to_string(),
        requirement_slug.to_string(),
        scenario_slug.to_string(),
    ))
}

fn collect_annotations(repo_root: &Path) -> Result<AnnotationScanResult> {
    let mut rs_files = Vec::new();
    for code_root in ["src", "tests"] {
        let path = repo_root.join(code_root);
        if path.exists() {
            collect_rs_files(&path, &mut rs_files)?;
        }
    }

    let mut result = AnnotationScanResult::default();

    for file_path in rs_files {
        let content = fs::read_to_string(&file_path)?;
        for (index, line) in content.lines().enumerate() {
            if let Some(caps) = ANNOTATION_REGEX.captures(line) {
                let reference_text = caps.get(1).unwrap().as_str();
                let location = format!("{}:{}", normalize_path(&file_path), index + 1);
                match parse_reference(reference_text) {
                    Ok(reference) => result.references.push(SpecReference {
                        reference,
                        location,
                    }),
                    Err(err) => result.broken.push(BrokenReference {
                        reference: reference_text.to_string(),
                        location,
                        reason: err.to_string(),
                    }),
                }
            }
        }
    }

    Ok(result)
}

fn check_spec_test_annotations(repo_root: &Path) -> Result<SpecCheckReport> {
    let scenarios = collect_spec_scenarios(repo_root)?;
    let annotation_result = collect_annotations(repo_root)?;
    let references = annotation_result.references;

    let mut scenario_map: HashMap<SpecScenarioRef, bool> = HashMap::new();
    for scenario in &scenarios {
        scenario_map.insert(scenario.reference.clone(), scenario.ui_only);
    }

    let mut referenced = HashSet::new();
    for reference in &references {
        referenced.insert(reference.reference.clone());
    }

    let mut report = SpecCheckReport {
        missing: Vec::new(),
        broken: annotation_result.broken,
    };

    for scenario in scenarios {
        if scenario.ui_only {
            continue;
        }
        if !referenced.contains(&scenario.reference) {
            report.missing.push(scenario.reference);
        }
    }

    for reference in references {
        if !scenario_map.contains_key(&reference.reference) {
            report.broken.push(BrokenReference {
                reference: reference.reference.format_reference(),
                location: reference.location,
                reason: "Reference does not match any spec scenario".to_string(),
            });
        }
    }

    Ok(report)
}

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

    #[test]
    fn test_slugify_heading() {
        assert_eq!(slugify_heading("run Subcommand"), "run-subcommand");
        assert_eq!(
            slugify_heading("Running 中に queued-change を外す"),
            "running-中に-queued-change-を外す"
        );
    }

    #[test]
    fn test_spec_annotation_checker_reports_missing_and_broken() {
        let temp_dir = tempfile::tempdir().unwrap();
        let root = temp_dir.path();

        let spec_dir = root.join("openspec/specs/testing");
        fs::create_dir_all(&spec_dir).unwrap();
        fs::write(
            spec_dir.join("spec.md"),
            r#"### Requirement: Sample Requirement

#### Scenario: Covered scenario
- **WHEN** something happens

#### Scenario: Missing scenario
- **WHEN** something else happens

#### Scenario: UI-only scenario
UI-only
"#,
        )
        .unwrap();

        let tests_dir = root.join("tests");
        fs::create_dir_all(&tests_dir).unwrap();
        fs::write(
            tests_dir.join("sample.rs"),
            r#"// OPENSPEC: openspec/specs/testing/spec.md#sample-requirement/covered-scenario
// OPENSPEC: openspec/specs/testing/spec.md#sample-requirement/unknown-scenario
#[test]
fn example() {}
"#,
        )
        .unwrap();

        let report = check_spec_test_annotations(root).unwrap();
        let missing_refs: Vec<String> = report.missing.iter().map(|r| r.to_string()).collect();
        let broken_refs: Vec<String> = report.broken.iter().map(|r| r.reference.clone()).collect();

        assert!(missing_refs.contains(
            &"openspec/specs/testing/spec.md#sample-requirement/missing-scenario".to_string()
        ));
        assert!(!missing_refs.contains(
            &"openspec/specs/testing/spec.md#sample-requirement/ui-only-scenario".to_string()
        ));
        assert!(broken_refs.contains(
            &"openspec/specs/testing/spec.md#sample-requirement/unknown-scenario".to_string()
        ));
    }

    #[test]
    fn test_format_report_includes_sections() {
        let report = SpecCheckReport {
            missing: vec![SpecScenarioRef::new(
                "openspec/specs/testing/spec.md".to_string(),
                "req".to_string(),
                "scenario".to_string(),
            )],
            broken: vec![BrokenReference {
                reference: "openspec/specs/testing/spec.md#req/bad".to_string(),
                location: "tests/sample.rs:1".to_string(),
                reason: "Reference does not match any spec scenario".to_string(),
            }],
        };

        let output = report.format_report();
        assert!(output.contains("Missing spec coverage:"));
        assert!(output.contains("Broken spec references:"));
        assert!(output.contains("openspec/specs/testing/spec.md#req/scenario"));
        assert!(output.contains("tests/sample.rs:1"));
    }
}