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                commands: Vec::new(),
164            })
165            .into_iter()
166            .collect()
167    }
168
169    fn tool(&self) -> Option<(&'static str, &'static str)> {
170        Some((
171            "specify",
172            "uv tool install specify-cli --from git+https://github.com/github/spec-kit.git",
173        ))
174    }
175
176    fn kind(&self) -> FormatKind {
177        FormatKind::Speckit
178    }
179
180    fn detect(&self, start: &Path) -> Option<PathBuf> {
181        Detect::root(self, start)
182    }
183
184    fn inspect(&self, start: &Path, feature: Option<&str>) -> Option<ProjectSnapshot> {
185        speccoder_speckit::inspect(start, feature).ok()
186    }
187
188    fn open(&self, start: &Path, feature: Option<&str>) -> Option<ProjectSnapshot> {
189        let env = std::env::var(texts::FEATURE_ENV)
190            .ok()
191            .filter(|v| !v.is_empty());
192        speccoder_speckit::inspect_with(start, feature, env.as_deref()).ok()
193    }
194
195    fn parse_tasks(&self, path: &str, text: &str) -> (ParsedTasks, Vec<Diagnostic>) {
196        speccoder_speckit::tasks::parse(path, text)
197    }
198
199    fn rules(&self) -> &'static Rules {
200        &RULES
201    }
202
203    fn wording(&self) -> &'static Wording {
204        &WORDING
205    }
206
207    fn messages(&self) -> &'static Messages {
208        &MESSAGES
209    }
210
211    fn planning(&self) -> &'static Planning {
212        &PLANNING
213    }
214
215    fn current_pointer(&self) -> Option<&'static str> {
216        Some(texts::POINTER)
217    }
218
219    fn set_current(&self, root: &Path, unit_dir: Option<&str>) -> Result<String, String> {
220        // Spec Kit's own per-checkout pointer (git-ignored by `.specify/.gitignore`).
221        let file = root.join(texts::POINTER);
222        match unit_dir {
223            Some(dir) => {
224                let text =
225                    serde_json::to_string_pretty(&serde_json::json!({ "feature_directory": dir }))
226                        .map_err(|e| e.to_string())?;
227                std::fs::write(&file, format!("{text}\n"))
228                    .map_err(|e| format!("{}: {e}", file.display()))?;
229            }
230            None => match std::fs::remove_file(&file) {
231                Ok(()) => {}
232                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
233                Err(e) => return Err(format!("{}: {e}", file.display())),
234            },
235        }
236        Ok(texts::POINTER.to_owned())
237    }
238
239    fn bundle(&self, snapshot: &ProjectSnapshot, task_id: &str) -> Result<Bundle, BundleError> {
240        let feature: &FeatureSnapshot = snapshot.feature.as_ref().ok_or(BundleError::NoFeature)?;
241        let tasks = feature.tasks.as_ref().ok_or(BundleError::NoTasks)?;
242        let task = tasks
243            .tasks
244            .iter()
245            .find(|t| t.id == task_id)
246            .ok_or_else(|| BundleError::NotFound(task_id.to_owned()))?;
247        let ws = Workspace::at(Path::new(&snapshot.root));
248        let read = |rel: &str| {
249            ws.as_ref()
250                .and_then(|ws| ws.read_text(rel).ok())
251                .map(|t| cap(&t))
252                .unwrap_or_default()
253        };
254        let dir = &feature.feature.dir;
255        let spec = read(&format!("{dir}/spec.md"));
256
257        let dependencies = feature
258            .schedule
259            .as_ref()
260            .and_then(|s| s.tasks.iter().find(|t| t.id == task.id))
261            .map(|st| {
262                st.depends_on
263                    .iter()
264                    .filter_map(|d| tasks.tasks.iter().find(|t| t.id == d.id))
265                    .map(|t| DependencyContext {
266                        id: t.id.clone(),
267                        title: t.title.clone(),
268                        done: t.done,
269                    })
270                    .collect()
271            })
272            .unwrap_or_default();
273        let story_tasks = task
274            .story
275            .as_deref()
276            .map(|label| {
277                tasks
278                    .tasks
279                    .iter()
280                    .filter(|t| t.id != task.id && t.story.as_deref() == Some(label))
281                    .map(|t| DependencyContext {
282                        id: t.id.clone(),
283                        title: t.title.clone(),
284                        done: t.done,
285                    })
286                    .collect()
287            })
288            .unwrap_or_default();
289
290        Ok(Bundle {
291            feature: feature.feature.name.clone(),
292            constitution: read(texts::CONSTITUTION),
293            plan: read(&format!("{dir}/plan.md")),
294            // A Convergence task closes a gap found against the whole spec; it
295            // gets the whole spec, so its acceptance tests have a source.
296            story: match task.story.as_deref() {
297                // A labelled task whose `### User Story N` section is missing
298                // (a spec that left the template's headings) still has the spec
299                // as its intent: acceptance tests are derived from all of it.
300                Some(label) => {
301                    let section = story_section(&spec, label);
302                    if section.trim().is_empty() {
303                        spec.clone()
304                    } else {
305                        section
306                    }
307                }
308                None if self.is_convergence(task.phase.as_deref().unwrap_or_default()) => {
309                    spec.clone()
310                }
311                None => String::new(),
312            },
313            task: TaskContext {
314                id: task.id.clone(),
315                title: task.title.clone(),
316                phase: task.phase.clone().unwrap_or_default(),
317                subsection: task.subsection.clone().unwrap_or_default(),
318                story: task.story.clone().unwrap_or_default(),
319                parallel: task.parallel,
320            },
321            dependencies,
322            story_tasks,
323        })
324    }
325
326    fn scenarios(&self, snapshot: &ProjectSnapshot, task: &str) -> Vec<ScenarioRef> {
327        let Some(f) = snapshot.feature.as_ref() else {
328            return Vec::new();
329        };
330        let label = f
331            .tasks
332            .as_ref()
333            .and_then(|t| t.tasks.iter().find(|t| t.id == task))
334            .and_then(|t| t.story.clone());
335        let spec = Workspace::at(Path::new(&snapshot.root))
336            .and_then(|ws| ws.read_text(&format!("{}/spec.md", f.feature.dir)).ok())
337            .unwrap_or_default();
338        // A labelled task whose story is missing has the whole spec as its
339        // intent, as in its bundle.
340        let own = speccoder_speckit::stories::scenario_refs(&spec, label.as_deref());
341        if own.is_empty() && label.is_some() {
342            speccoder_speckit::stories::scenario_refs(&spec, None)
343        } else {
344            own
345        }
346    }
347
348    fn acceptance_testable(&self, bundle: &Bundle) -> bool {
349        bundle.story.to_lowercase().contains("acceptance")
350    }
351
352    /// Each user story with its scenarios, keyed `USn`, citing `USn-k`.
353    fn oracle_requirements(
354        &self,
355        snapshot: &ProjectSnapshot,
356    ) -> Vec<crate::format::OracleRequirement> {
357        let Some(f) = snapshot.feature.as_ref() else {
358            return Vec::new();
359        };
360        let spec = Workspace::at(Path::new(&snapshot.root))
361            .and_then(|ws| ws.read_text(&format!("{}/spec.md", f.feature.dir)).ok())
362            .unwrap_or_default();
363        let (stories, _) = speccoder_speckit::stories::requirements("spec.md", &spec);
364        stories
365            .into_iter()
366            .map(|r| crate::format::OracleRequirement {
367                scenarios: speccoder_speckit::stories::scenario_refs(&spec, Some(&r.key)),
368                key: r.key,
369                title: r.title,
370                text: r.text,
371            })
372            .collect()
373    }
374
375    /// `NNN-quick-changes` and `NNN-bugfixes`.
376    fn standing_units(&self, root: &Path) -> Vec<(String, speccoder_core::ladder::Rung)> {
377        use speccoder_core::ladder::Rung;
378        let mut out: Vec<(String, Rung)> =
379            std::fs::read_dir(root.join(speccoder_speckit::features::SPECS))
380                .into_iter()
381                .flatten()
382                .flatten()
383                .map(|e| e.file_name().to_string_lossy().into_owned())
384                .filter(|n| speccoder_speckit::features::prefix(n).is_some())
385                .filter_map(|n| {
386                    let rung = if n.ends_with("-quick-changes") {
387                        Rung::Quick
388                    } else if n.ends_with("-bugfixes") {
389                        Rung::Bug
390                    } else {
391                        return None;
392                    };
393                    Some((n, rung))
394                })
395                .collect();
396        out.push((".specify/bugs".to_owned(), Rung::Bug));
397        out
398    }
399
400    /// A Convergence phase, appended by converge.
401    fn is_convergence(&self, phase: &str) -> bool {
402        phase.to_lowercase().contains("convergence")
403    }
404
405    fn convergence_texts(&self, root: &Path, unit_dir: &Path) -> [String; 4] {
406        let read = |p: PathBuf| std::fs::read_to_string(p).unwrap_or_default();
407        [
408            read(root.join(texts::CONSTITUTION)),
409            read(unit_dir.join("spec.md")),
410            read(unit_dir.join("plan.md")),
411            read(unit_dir.join("tasks.md")),
412        ]
413    }
414
415    fn checklists(&self, root: &Path, unit_dir: &str) -> Vec<ChecklistStatus> {
416        speccoder_speckit::checklists::status(root, unit_dir)
417    }
418
419    fn requirements_file(&self) -> Option<&'static str> {
420        Some("spec.md")
421    }
422
423    fn record_change(
424        &self,
425        root: &Path,
426        request: &str,
427        checks: &[String],
428    ) -> Result<super::Recorded, String> {
429        quick::record(root, request, checks)
430    }
431
432    fn extensions(&self, root: &Path) -> Option<crate::format::Inventory> {
433        extensions::inventory(root)
434    }
435
436    fn bug_unit(
437        &self,
438        root: &Path,
439    ) -> Result<speccoder_core::bug::BugHome, crate::format::BugRefusal> {
440        bug::unit(root)
441    }
442
443    fn record_bug(
444        &self,
445        root: &Path,
446        home: &speccoder_core::bug::BugHome,
447        triad: &speccoder_core::bug::Triad,
448    ) -> Result<crate::format::RecordedBug, crate::format::BugRefusal> {
449        bug::record(root, home, triad)
450    }
451
452    fn bug_step(&self) -> Option<crate::format::BugStep> {
453        Some(bug::STEP)
454    }
455
456    fn bug_dir(&self, home: &speccoder_core::bug::BugHome, slug: &str) -> Option<(String, String)> {
457        bug::dir(home, slug)
458    }
459
460    fn bug_slug(&self, root: &Path, _home: &speccoder_core::bug::BugHome, title: &str) -> String {
461        bug::slug(root, title)
462    }
463
464    fn read_bug(
465        &self,
466        root: &Path,
467        home: &speccoder_core::bug::BugHome,
468        key: &str,
469    ) -> Result<crate::format::ReadBug, crate::format::BugRefusal> {
470        bug::read(root, home, key)
471    }
472
473    fn requirements_in(&self, text: &str) -> Vec<(String, String)> {
474        // `- **FR-001**: …` and `- **SC-001**: …` define the identifiers.
475        text.lines()
476            .filter_map(|line| {
477                let rest = line.trim_start().strip_prefix("- **")?;
478                let id = rest.split("**").next()?;
479                let (kind, number) = id.split_once('-')?;
480                (matches!(kind, "FR" | "SC")
481                    && !number.is_empty()
482                    && number.chars().all(|c| c.is_ascii_digit()))
483                .then(|| (id.to_owned(), line.trim_end().to_owned()))
484            })
485            .collect()
486    }
487
488    fn tick(&self, tasks_file: &Path, task: &str, line_hash: &str) -> Result<(), String> {
489        speccoder_speckit::mark_task_complete(tasks_file, task, line_hash)
490    }
491
492    fn append(
493        &self,
494        tasks_file: &Path,
495        file_hash: &str,
496        items: &[String],
497    ) -> Result<Vec<String>, String> {
498        speccoder_speckit::append_convergence(tasks_file, file_hash, items)
499    }
500
501    fn commit_precondition(
502        &self,
503        _root: &Path,
504        join: &dyn Fn(&str) -> String,
505        unit_dir: &str,
506    ) -> CommitPrecondition {
507        precondition(&join(texts::MARKER), &join(unit_dir))
508    }
509}
510
511/// What a Spec Kit worktree needs committed, given the repository-relative
512/// `.specify` and feature directories.
513#[must_use]
514pub fn precondition(specify_dir: &str, feature_dir: &str) -> CommitPrecondition {
515    CommitPrecondition {
516        // The feature directory: nothing untracked, ignored or modified.
517        strict: vec![feature_dir.to_owned()],
518        // .specify: Spec Kit ignores its own per-checkout files (feature.json);
519        // those are fine. Untracked or modified files are not.
520        tracked: vec![specify_dir.to_owned()],
521        runtime,
522        essentials: vec![
523            format!("{specify_dir}/init-options.json"),
524            format!("{feature_dir}/spec.md"),
525        ],
526        message: "the feature's Spec Kit artifacts are not committed, so a worktree would not contain them",
527        hint: "commit them (git add .specify specs/<feature> && git commit), or run in place: speccoder run --in-place",
528        no_commits_hint: "commit the Spec Kit artifacts first (git add .specify specs && git commit)",
529    }
530}
531
532/// Runtime state is not an artifact: Spec Kit's own workflow runs
533/// (`.specify/workflows/runs/`, dirty while `specify workflow run` drives
534/// speccoder) and Python bytecode caches of installed step types.
535fn runtime(p: &str) -> bool {
536    p.contains("/workflows/runs/")
537        || p.starts_with(".specify/workflows/runs/")
538        || p.split('/').any(|c| c == "__pycache__")
539}
540
541#[cfg(test)]
542mod tests {
543    use super::*;
544
545    #[test]
546    fn requirement_ids_are_the_bold_fr_and_sc_items() {
547        let dir = tempfile::tempdir().unwrap();
548        std::fs::create_dir_all(dir.path().join("specs/001-x")).unwrap();
549        std::fs::write(
550            dir.path().join("specs/001-x/spec.md"),
551            "## 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",
552        )
553        .unwrap();
554        let ids: Vec<String> = SpecKit
555            .requirement_ids(dir.path(), "specs/001-x")
556            .into_iter()
557            .map(|(id, hash)| {
558                assert_eq!(hash.len(), 64);
559                id
560            })
561            .collect();
562        assert_eq!(ids, ["FR-001", "FR-002", "SC-001"]);
563    }
564}