Skip to main content

speccoder_runtime/format/speckit/
mod.rs

1//! GitHub Spec Kit, the reference format: `.specify/` and `specs/NNN-name/`
2//! with `spec.md`, `plan.md` and `tasks.md`. Parsing is the
3//! `speccoder-speckit` crate's; this adapter is the only runtime code that
4//! knows Spec Kit's paths and words.
5
6pub mod bench;
7pub mod bug;
8pub mod extensions;
9pub mod hooks;
10pub mod preset;
11pub mod python;
12mod quick;
13mod texts;
14pub mod workflow;
15
16use std::path::{Path, PathBuf};
17
18use speccoder_core::ChecklistStatus;
19use speccoder_core::snapshot::{Diagnostic, FeatureSnapshot, ParsedTasks, ProjectSnapshot};
20use speccoder_core::spec::{FormatKind, ScenarioRef};
21
22pub use speccoder_speckit::stories::story_section;
23pub use speccoder_speckit::workspace::Workspace;
24pub use texts::{MESSAGES, PLANNING, RULES, WORDING};
25
26use crate::context::{Bundle, BundleError, DependencyContext, TaskContext, cap};
27use crate::format::{Adapter, CommitPrecondition, Detect, Messages, Planning, Rules, Wording};
28
29/// The Spec Kit adapter.
30#[derive(Debug)]
31pub struct SpecKit;
32
33/// The one instance.
34pub static SPECKIT: SpecKit = SpecKit;
35
36impl Detect for SpecKit {
37    fn kind(&self) -> FormatKind {
38        FormatKind::Speckit
39    }
40
41    fn root(&self, start: &Path) -> Option<PathBuf> {
42        speccoder_speckit::workspace::find_root(start).map(|ws| ws.root().to_path_buf())
43    }
44
45    fn adapter(&self) -> Option<&'static dyn Adapter> {
46        Some(&SPECKIT)
47    }
48}
49
50impl Adapter for SpecKit {
51    fn plan_structure(&self, snapshot: &ProjectSnapshot) -> Option<crate::format::PlanStructure> {
52        use crate::format::{PhaseKind, PlannedTask, code_spans};
53        let feature = snapshot.feature.as_ref()?;
54        let tasks = feature.tasks.as_ref()?;
55        let kind = |phase: &str, story: bool| {
56            let p = phase.to_ascii_lowercase();
57            if p.contains("setup") {
58                PhaseKind::Setup
59            } else if p.contains("foundational") {
60                PhaseKind::Foundational
61            } else if story || p.contains("user story") {
62                PhaseKind::Story
63            } else if p.contains("polish") || p.contains("cross-cutting") {
64                PhaseKind::Polish
65            } else {
66                PhaseKind::Other
67            }
68        };
69        let mut stories = std::collections::BTreeMap::new();
70        let planned = tasks
71            .tasks
72            .iter()
73            .map(|t| {
74                if let Some(st) = &t.story
75                    && !stories.contains_key(st)
76                    && let Ok(b) = self.bundle(snapshot, &t.id)
77                {
78                    stories.insert(st.clone(), b.story);
79                }
80                PlannedTask {
81                    id: t.id.clone(),
82                    title: t.title.clone(),
83                    phase: kind(t.phase.as_deref().unwrap_or_default(), t.story.is_some()),
84                    story: t.story.clone(),
85                    spans: code_spans(&t.title),
86                    done: t.done,
87                }
88            })
89            .collect();
90        Some(crate::format::PlanStructure {
91            tasks: planned,
92            stories,
93        })
94    }
95
96    fn init_steps(&self, choices: &crate::format::FormatInit) -> Vec<crate::format::InitStep> {
97        use speccoder_core::new_project::ExtensionKind;
98        let script = if cfg!(windows) { "ps" } else { "sh" };
99        let mut argv: Vec<String> = [
100            "specify",
101            "init",
102            "--here",
103            "--force",
104            "--non-interactive",
105            "--integration",
106            "claude",
107            "--script",
108            script,
109            "--ignore-agent-tools",
110        ]
111        .map(str::to_owned)
112        .to_vec();
113        if choices.preset {
114            argv.push("--preset".to_owned());
115            argv.push(preset::dir(&choices.state).display().to_string());
116        }
117        for e in &choices.extensions {
118            argv.push("--extension".to_owned());
119            argv.push(e.source.clone());
120        }
121        let hosts: Vec<String> = choices.extensions.iter().filter_map(|e| e.host()).collect();
122        if choices
123            .extensions
124            .iter()
125            .any(|e| e.kind == ExtensionKind::Url)
126        {
127            argv.push("--trust-extension-urls".to_owned());
128        }
129        vec![crate::format::InitStep {
130            argv,
131            hosts,
132            writes: ".specify/, .claude/skills/speckit-*/".to_owned(),
133            env: python::command_env(&|k| std::env::var(k).ok()),
134            marker: ".specify",
135            note: choices
136                .preset
137                .then(|| "with the speccoder preset: tasks that plan for evidence".to_owned()),
138            preset: choices.preset,
139        }]
140    }
141
142    fn prepare_init(&self, choices: &crate::format::FormatInit) -> Result<(), String> {
143        if choices.preset {
144            preset::extract(&choices.state)?;
145        }
146        Ok(())
147    }
148
149    fn doctor_checks(
150        &self,
151        root: &Path,
152        env: &dyn Fn(&str) -> Option<String>,
153    ) -> Vec<speccoder_core::DoctorCheck> {
154        python::warning(root, env)
155            .map(|detail| speccoder_core::DoctorCheck {
156                check: "spec tool python".to_owned(),
157                level: speccoder_core::DoctorLevel::Warn,
158                detail,
159                code: None,
160                fix: python::FIX.iter().map(|f| (*f).to_owned()).collect(),
161                remedy: None,
162                tasks: Vec::new(),
163            })
164            .into_iter()
165            .collect()
166    }
167
168    fn tool(&self) -> Option<(&'static str, &'static str)> {
169        Some((
170            "specify",
171            "uv tool install specify-cli --from git+https://github.com/github/spec-kit.git",
172        ))
173    }
174
175    fn kind(&self) -> FormatKind {
176        FormatKind::Speckit
177    }
178
179    fn detect(&self, start: &Path) -> Option<PathBuf> {
180        Detect::root(self, start)
181    }
182
183    fn inspect(&self, start: &Path, feature: Option<&str>) -> Option<ProjectSnapshot> {
184        speccoder_speckit::inspect(start, feature).ok()
185    }
186
187    fn open(&self, start: &Path, feature: Option<&str>) -> Option<ProjectSnapshot> {
188        let env = std::env::var(texts::FEATURE_ENV)
189            .ok()
190            .filter(|v| !v.is_empty());
191        speccoder_speckit::inspect_with(start, feature, env.as_deref()).ok()
192    }
193
194    fn parse_tasks(&self, path: &str, text: &str) -> (ParsedTasks, Vec<Diagnostic>) {
195        speccoder_speckit::tasks::parse(path, text)
196    }
197
198    fn rules(&self) -> &'static Rules {
199        &RULES
200    }
201
202    fn wording(&self) -> &'static Wording {
203        &WORDING
204    }
205
206    fn messages(&self) -> &'static Messages {
207        &MESSAGES
208    }
209
210    fn planning(&self) -> &'static Planning {
211        &PLANNING
212    }
213
214    fn current_pointer(&self) -> Option<&'static str> {
215        Some(texts::POINTER)
216    }
217
218    fn set_current(&self, root: &Path, unit_dir: Option<&str>) -> Result<String, String> {
219        // Spec Kit's own per-checkout pointer (git-ignored by `.specify/.gitignore`).
220        let file = root.join(texts::POINTER);
221        match unit_dir {
222            Some(dir) => {
223                let text =
224                    serde_json::to_string_pretty(&serde_json::json!({ "feature_directory": dir }))
225                        .map_err(|e| e.to_string())?;
226                std::fs::write(&file, format!("{text}\n"))
227                    .map_err(|e| format!("{}: {e}", file.display()))?;
228            }
229            None => match std::fs::remove_file(&file) {
230                Ok(()) => {}
231                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
232                Err(e) => return Err(format!("{}: {e}", file.display())),
233            },
234        }
235        Ok(texts::POINTER.to_owned())
236    }
237
238    fn bundle(&self, snapshot: &ProjectSnapshot, task_id: &str) -> Result<Bundle, BundleError> {
239        let feature: &FeatureSnapshot = snapshot.feature.as_ref().ok_or(BundleError::NoFeature)?;
240        let tasks = feature.tasks.as_ref().ok_or(BundleError::NoTasks)?;
241        let task = tasks
242            .tasks
243            .iter()
244            .find(|t| t.id == task_id)
245            .ok_or_else(|| BundleError::NotFound(task_id.to_owned()))?;
246        let ws = Workspace::at(Path::new(&snapshot.root));
247        let read = |rel: &str| {
248            ws.as_ref()
249                .and_then(|ws| ws.read_text(rel).ok())
250                .map(|t| cap(&t))
251                .unwrap_or_default()
252        };
253        let dir = &feature.feature.dir;
254        let spec = read(&format!("{dir}/spec.md"));
255
256        let dependencies = feature
257            .schedule
258            .as_ref()
259            .and_then(|s| s.tasks.iter().find(|t| t.id == task.id))
260            .map(|st| {
261                st.depends_on
262                    .iter()
263                    .filter_map(|d| tasks.tasks.iter().find(|t| t.id == d.id))
264                    .map(|t| DependencyContext {
265                        id: t.id.clone(),
266                        title: t.title.clone(),
267                        done: t.done,
268                    })
269                    .collect()
270            })
271            .unwrap_or_default();
272
273        Ok(Bundle {
274            feature: feature.feature.name.clone(),
275            constitution: read(texts::CONSTITUTION),
276            plan: read(&format!("{dir}/plan.md")),
277            // A Convergence task closes a gap found against the whole spec; it
278            // gets the whole spec, so its acceptance tests have a source.
279            story: match task.story.as_deref() {
280                // A labelled task whose `### User Story N` section is missing
281                // (a spec that left the template's headings) still has the spec
282                // as its intent: acceptance tests are derived from all of it.
283                Some(label) => {
284                    let section = story_section(&spec, label);
285                    if section.trim().is_empty() {
286                        spec.clone()
287                    } else {
288                        section
289                    }
290                }
291                None if self.is_convergence(task.phase.as_deref().unwrap_or_default()) => {
292                    spec.clone()
293                }
294                None => String::new(),
295            },
296            task: TaskContext {
297                id: task.id.clone(),
298                title: task.title.clone(),
299                phase: task.phase.clone().unwrap_or_default(),
300                subsection: task.subsection.clone().unwrap_or_default(),
301                story: task.story.clone().unwrap_or_default(),
302                parallel: task.parallel,
303            },
304            dependencies,
305        })
306    }
307
308    fn scenarios(&self, snapshot: &ProjectSnapshot, task: &str) -> Vec<ScenarioRef> {
309        let Some(f) = snapshot.feature.as_ref() else {
310            return Vec::new();
311        };
312        let label = f
313            .tasks
314            .as_ref()
315            .and_then(|t| t.tasks.iter().find(|t| t.id == task))
316            .and_then(|t| t.story.clone());
317        let spec = Workspace::at(Path::new(&snapshot.root))
318            .and_then(|ws| ws.read_text(&format!("{}/spec.md", f.feature.dir)).ok())
319            .unwrap_or_default();
320        // A labelled task whose story is missing has the whole spec as its
321        // intent, as in its bundle.
322        let own = speccoder_speckit::stories::scenario_refs(&spec, label.as_deref());
323        if own.is_empty() && label.is_some() {
324            speccoder_speckit::stories::scenario_refs(&spec, None)
325        } else {
326            own
327        }
328    }
329
330    fn acceptance_testable(&self, bundle: &Bundle) -> bool {
331        bundle.story.to_lowercase().contains("acceptance")
332    }
333
334    /// Each user story with its scenarios, keyed `USn`, citing `USn-k`.
335    fn oracle_requirements(
336        &self,
337        snapshot: &ProjectSnapshot,
338    ) -> Vec<crate::format::OracleRequirement> {
339        let Some(f) = snapshot.feature.as_ref() else {
340            return Vec::new();
341        };
342        let spec = Workspace::at(Path::new(&snapshot.root))
343            .and_then(|ws| ws.read_text(&format!("{}/spec.md", f.feature.dir)).ok())
344            .unwrap_or_default();
345        let (stories, _) = speccoder_speckit::stories::requirements("spec.md", &spec);
346        stories
347            .into_iter()
348            .map(|r| crate::format::OracleRequirement {
349                scenarios: speccoder_speckit::stories::scenario_refs(&spec, Some(&r.key)),
350                key: r.key,
351                title: r.title,
352                text: r.text,
353            })
354            .collect()
355    }
356
357    /// `NNN-quick-changes` and `NNN-bugfixes`.
358    fn standing_units(&self, root: &Path) -> Vec<(String, speccoder_core::ladder::Rung)> {
359        use speccoder_core::ladder::Rung;
360        let mut out: Vec<(String, Rung)> =
361            std::fs::read_dir(root.join(speccoder_speckit::features::SPECS))
362                .into_iter()
363                .flatten()
364                .flatten()
365                .map(|e| e.file_name().to_string_lossy().into_owned())
366                .filter(|n| speccoder_speckit::features::prefix(n).is_some())
367                .filter_map(|n| {
368                    let rung = if n.ends_with("-quick-changes") {
369                        Rung::Quick
370                    } else if n.ends_with("-bugfixes") {
371                        Rung::Bug
372                    } else {
373                        return None;
374                    };
375                    Some((n, rung))
376                })
377                .collect();
378        out.push((".specify/bugs".to_owned(), Rung::Bug));
379        out
380    }
381
382    /// A Convergence phase, appended by converge.
383    fn is_convergence(&self, phase: &str) -> bool {
384        phase.to_lowercase().contains("convergence")
385    }
386
387    fn convergence_texts(&self, root: &Path, unit_dir: &Path) -> [String; 4] {
388        let read = |p: PathBuf| std::fs::read_to_string(p).unwrap_or_default();
389        [
390            read(root.join(texts::CONSTITUTION)),
391            read(unit_dir.join("spec.md")),
392            read(unit_dir.join("plan.md")),
393            read(unit_dir.join("tasks.md")),
394        ]
395    }
396
397    fn checklists(&self, root: &Path, unit_dir: &str) -> Vec<ChecklistStatus> {
398        speccoder_speckit::checklists::status(root, unit_dir)
399    }
400
401    fn requirements_file(&self) -> Option<&'static str> {
402        Some("spec.md")
403    }
404
405    fn record_change(
406        &self,
407        root: &Path,
408        request: &str,
409        checks: &[String],
410    ) -> Result<super::Recorded, String> {
411        quick::record(root, request, checks)
412    }
413
414    fn extensions(&self, root: &Path) -> Option<crate::format::Inventory> {
415        extensions::inventory(root)
416    }
417
418    fn bug_unit(
419        &self,
420        root: &Path,
421    ) -> Result<speccoder_core::bug::BugHome, crate::format::BugRefusal> {
422        bug::unit(root)
423    }
424
425    fn record_bug(
426        &self,
427        root: &Path,
428        home: &speccoder_core::bug::BugHome,
429        triad: &speccoder_core::bug::Triad,
430    ) -> Result<crate::format::RecordedBug, crate::format::BugRefusal> {
431        bug::record(root, home, triad)
432    }
433
434    fn bug_step(&self) -> Option<crate::format::BugStep> {
435        Some(bug::STEP)
436    }
437
438    fn bug_dir(&self, home: &speccoder_core::bug::BugHome, slug: &str) -> Option<(String, String)> {
439        bug::dir(home, slug)
440    }
441
442    fn bug_slug(&self, root: &Path, _home: &speccoder_core::bug::BugHome, title: &str) -> String {
443        bug::slug(root, title)
444    }
445
446    fn read_bug(
447        &self,
448        root: &Path,
449        home: &speccoder_core::bug::BugHome,
450        key: &str,
451    ) -> Result<crate::format::ReadBug, crate::format::BugRefusal> {
452        bug::read(root, home, key)
453    }
454
455    fn requirements_in(&self, text: &str) -> Vec<(String, String)> {
456        // `- **FR-001**: …` and `- **SC-001**: …` define the identifiers.
457        text.lines()
458            .filter_map(|line| {
459                let rest = line.trim_start().strip_prefix("- **")?;
460                let id = rest.split("**").next()?;
461                let (kind, number) = id.split_once('-')?;
462                (matches!(kind, "FR" | "SC")
463                    && !number.is_empty()
464                    && number.chars().all(|c| c.is_ascii_digit()))
465                .then(|| (id.to_owned(), line.trim_end().to_owned()))
466            })
467            .collect()
468    }
469
470    fn tick(&self, tasks_file: &Path, task: &str, line_hash: &str) -> Result<(), String> {
471        speccoder_speckit::mark_task_complete(tasks_file, task, line_hash)
472    }
473
474    fn append(
475        &self,
476        tasks_file: &Path,
477        file_hash: &str,
478        items: &[String],
479    ) -> Result<Vec<String>, String> {
480        speccoder_speckit::append_convergence(tasks_file, file_hash, items)
481    }
482
483    fn commit_precondition(
484        &self,
485        _root: &Path,
486        join: &dyn Fn(&str) -> String,
487        unit_dir: &str,
488    ) -> CommitPrecondition {
489        precondition(&join(texts::MARKER), &join(unit_dir))
490    }
491}
492
493/// What a Spec Kit worktree needs committed, given the repository-relative
494/// `.specify` and feature directories.
495#[must_use]
496pub fn precondition(specify_dir: &str, feature_dir: &str) -> CommitPrecondition {
497    CommitPrecondition {
498        // The feature directory: nothing untracked, ignored or modified.
499        strict: vec![feature_dir.to_owned()],
500        // .specify: Spec Kit ignores its own per-checkout files (feature.json);
501        // those are fine. Untracked or modified files are not.
502        tracked: vec![specify_dir.to_owned()],
503        runtime,
504        essentials: vec![
505            format!("{specify_dir}/init-options.json"),
506            format!("{feature_dir}/spec.md"),
507        ],
508        message: "the feature's Spec Kit artifacts are not committed, so a worktree would not contain them",
509        hint: "commit them (git add .specify specs/<feature> && git commit), or run in place: speccoder run --in-place",
510        no_commits_hint: "commit the Spec Kit artifacts first (git add .specify specs && git commit)",
511    }
512}
513
514/// Runtime state is not an artifact: Spec Kit's own workflow runs
515/// (`.specify/workflows/runs/`, dirty while `specify workflow run` drives
516/// speccoder) and Python bytecode caches of installed step types.
517fn runtime(p: &str) -> bool {
518    p.contains("/workflows/runs/")
519        || p.starts_with(".specify/workflows/runs/")
520        || p.split('/').any(|c| c == "__pycache__")
521}
522
523#[cfg(test)]
524mod tests {
525    use super::*;
526
527    #[test]
528    fn requirement_ids_are_the_bold_fr_and_sc_items() {
529        let dir = tempfile::tempdir().unwrap();
530        std::fs::create_dir_all(dir.path().join("specs/001-x")).unwrap();
531        std::fs::write(
532            dir.path().join("specs/001-x/spec.md"),
533            "## Requirements\n\n- **FR-001**: System MUST parse.\n- **FR-002**: System MUST render.\n  - **FR-X**: not one\n- **Key**: not one\n\n## Success\n\n- **SC-001**: Under a second.\n",
534        )
535        .unwrap();
536        let ids: Vec<String> = SpecKit
537            .requirement_ids(dir.path(), "specs/001-x")
538            .into_iter()
539            .map(|(id, hash)| {
540                assert_eq!(hash.len(), 64);
541                id
542            })
543            .collect();
544        assert_eq!(ids, ["FR-001", "FR-002", "SC-001"]);
545    }
546}