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
274        Ok(Bundle {
275            feature: feature.feature.name.clone(),
276            constitution: read(texts::CONSTITUTION),
277            plan: read(&format!("{dir}/plan.md")),
278            // A Convergence task closes a gap found against the whole spec; it
279            // gets the whole spec, so its acceptance tests have a source.
280            story: match task.story.as_deref() {
281                // A labelled task whose `### User Story N` section is missing
282                // (a spec that left the template's headings) still has the spec
283                // as its intent: acceptance tests are derived from all of it.
284                Some(label) => {
285                    let section = story_section(&spec, label);
286                    if section.trim().is_empty() {
287                        spec.clone()
288                    } else {
289                        section
290                    }
291                }
292                None if self.is_convergence(task.phase.as_deref().unwrap_or_default()) => {
293                    spec.clone()
294                }
295                None => String::new(),
296            },
297            task: TaskContext {
298                id: task.id.clone(),
299                title: task.title.clone(),
300                phase: task.phase.clone().unwrap_or_default(),
301                subsection: task.subsection.clone().unwrap_or_default(),
302                story: task.story.clone().unwrap_or_default(),
303                parallel: task.parallel,
304            },
305            dependencies,
306        })
307    }
308
309    fn scenarios(&self, snapshot: &ProjectSnapshot, task: &str) -> Vec<ScenarioRef> {
310        let Some(f) = snapshot.feature.as_ref() else {
311            return Vec::new();
312        };
313        let label = f
314            .tasks
315            .as_ref()
316            .and_then(|t| t.tasks.iter().find(|t| t.id == task))
317            .and_then(|t| t.story.clone());
318        let spec = Workspace::at(Path::new(&snapshot.root))
319            .and_then(|ws| ws.read_text(&format!("{}/spec.md", f.feature.dir)).ok())
320            .unwrap_or_default();
321        // A labelled task whose story is missing has the whole spec as its
322        // intent, as in its bundle.
323        let own = speccoder_speckit::stories::scenario_refs(&spec, label.as_deref());
324        if own.is_empty() && label.is_some() {
325            speccoder_speckit::stories::scenario_refs(&spec, None)
326        } else {
327            own
328        }
329    }
330
331    fn acceptance_testable(&self, bundle: &Bundle) -> bool {
332        bundle.story.to_lowercase().contains("acceptance")
333    }
334
335    /// Each user story with its scenarios, keyed `USn`, citing `USn-k`.
336    fn oracle_requirements(
337        &self,
338        snapshot: &ProjectSnapshot,
339    ) -> Vec<crate::format::OracleRequirement> {
340        let Some(f) = snapshot.feature.as_ref() else {
341            return Vec::new();
342        };
343        let spec = Workspace::at(Path::new(&snapshot.root))
344            .and_then(|ws| ws.read_text(&format!("{}/spec.md", f.feature.dir)).ok())
345            .unwrap_or_default();
346        let (stories, _) = speccoder_speckit::stories::requirements("spec.md", &spec);
347        stories
348            .into_iter()
349            .map(|r| crate::format::OracleRequirement {
350                scenarios: speccoder_speckit::stories::scenario_refs(&spec, Some(&r.key)),
351                key: r.key,
352                title: r.title,
353                text: r.text,
354            })
355            .collect()
356    }
357
358    /// `NNN-quick-changes` and `NNN-bugfixes`.
359    fn standing_units(&self, root: &Path) -> Vec<(String, speccoder_core::ladder::Rung)> {
360        use speccoder_core::ladder::Rung;
361        let mut out: Vec<(String, Rung)> =
362            std::fs::read_dir(root.join(speccoder_speckit::features::SPECS))
363                .into_iter()
364                .flatten()
365                .flatten()
366                .map(|e| e.file_name().to_string_lossy().into_owned())
367                .filter(|n| speccoder_speckit::features::prefix(n).is_some())
368                .filter_map(|n| {
369                    let rung = if n.ends_with("-quick-changes") {
370                        Rung::Quick
371                    } else if n.ends_with("-bugfixes") {
372                        Rung::Bug
373                    } else {
374                        return None;
375                    };
376                    Some((n, rung))
377                })
378                .collect();
379        out.push((".specify/bugs".to_owned(), Rung::Bug));
380        out
381    }
382
383    /// A Convergence phase, appended by converge.
384    fn is_convergence(&self, phase: &str) -> bool {
385        phase.to_lowercase().contains("convergence")
386    }
387
388    fn convergence_texts(&self, root: &Path, unit_dir: &Path) -> [String; 4] {
389        let read = |p: PathBuf| std::fs::read_to_string(p).unwrap_or_default();
390        [
391            read(root.join(texts::CONSTITUTION)),
392            read(unit_dir.join("spec.md")),
393            read(unit_dir.join("plan.md")),
394            read(unit_dir.join("tasks.md")),
395        ]
396    }
397
398    fn checklists(&self, root: &Path, unit_dir: &str) -> Vec<ChecklistStatus> {
399        speccoder_speckit::checklists::status(root, unit_dir)
400    }
401
402    fn requirements_file(&self) -> Option<&'static str> {
403        Some("spec.md")
404    }
405
406    fn record_change(
407        &self,
408        root: &Path,
409        request: &str,
410        checks: &[String],
411    ) -> Result<super::Recorded, String> {
412        quick::record(root, request, checks)
413    }
414
415    fn extensions(&self, root: &Path) -> Option<crate::format::Inventory> {
416        extensions::inventory(root)
417    }
418
419    fn bug_unit(
420        &self,
421        root: &Path,
422    ) -> Result<speccoder_core::bug::BugHome, crate::format::BugRefusal> {
423        bug::unit(root)
424    }
425
426    fn record_bug(
427        &self,
428        root: &Path,
429        home: &speccoder_core::bug::BugHome,
430        triad: &speccoder_core::bug::Triad,
431    ) -> Result<crate::format::RecordedBug, crate::format::BugRefusal> {
432        bug::record(root, home, triad)
433    }
434
435    fn bug_step(&self) -> Option<crate::format::BugStep> {
436        Some(bug::STEP)
437    }
438
439    fn bug_dir(&self, home: &speccoder_core::bug::BugHome, slug: &str) -> Option<(String, String)> {
440        bug::dir(home, slug)
441    }
442
443    fn bug_slug(&self, root: &Path, _home: &speccoder_core::bug::BugHome, title: &str) -> String {
444        bug::slug(root, title)
445    }
446
447    fn read_bug(
448        &self,
449        root: &Path,
450        home: &speccoder_core::bug::BugHome,
451        key: &str,
452    ) -> Result<crate::format::ReadBug, crate::format::BugRefusal> {
453        bug::read(root, home, key)
454    }
455
456    fn requirements_in(&self, text: &str) -> Vec<(String, String)> {
457        // `- **FR-001**: …` and `- **SC-001**: …` define the identifiers.
458        text.lines()
459            .filter_map(|line| {
460                let rest = line.trim_start().strip_prefix("- **")?;
461                let id = rest.split("**").next()?;
462                let (kind, number) = id.split_once('-')?;
463                (matches!(kind, "FR" | "SC")
464                    && !number.is_empty()
465                    && number.chars().all(|c| c.is_ascii_digit()))
466                .then(|| (id.to_owned(), line.trim_end().to_owned()))
467            })
468            .collect()
469    }
470
471    fn tick(&self, tasks_file: &Path, task: &str, line_hash: &str) -> Result<(), String> {
472        speccoder_speckit::mark_task_complete(tasks_file, task, line_hash)
473    }
474
475    fn append(
476        &self,
477        tasks_file: &Path,
478        file_hash: &str,
479        items: &[String],
480    ) -> Result<Vec<String>, String> {
481        speccoder_speckit::append_convergence(tasks_file, file_hash, items)
482    }
483
484    fn commit_precondition(
485        &self,
486        _root: &Path,
487        join: &dyn Fn(&str) -> String,
488        unit_dir: &str,
489    ) -> CommitPrecondition {
490        precondition(&join(texts::MARKER), &join(unit_dir))
491    }
492}
493
494/// What a Spec Kit worktree needs committed, given the repository-relative
495/// `.specify` and feature directories.
496#[must_use]
497pub fn precondition(specify_dir: &str, feature_dir: &str) -> CommitPrecondition {
498    CommitPrecondition {
499        // The feature directory: nothing untracked, ignored or modified.
500        strict: vec![feature_dir.to_owned()],
501        // .specify: Spec Kit ignores its own per-checkout files (feature.json);
502        // those are fine. Untracked or modified files are not.
503        tracked: vec![specify_dir.to_owned()],
504        runtime,
505        essentials: vec![
506            format!("{specify_dir}/init-options.json"),
507            format!("{feature_dir}/spec.md"),
508        ],
509        message: "the feature's Spec Kit artifacts are not committed, so a worktree would not contain them",
510        hint: "commit them (git add .specify specs/<feature> && git commit), or run in place: speccoder run --in-place",
511        no_commits_hint: "commit the Spec Kit artifacts first (git add .specify specs && git commit)",
512    }
513}
514
515/// Runtime state is not an artifact: Spec Kit's own workflow runs
516/// (`.specify/workflows/runs/`, dirty while `specify workflow run` drives
517/// speccoder) and Python bytecode caches of installed step types.
518fn runtime(p: &str) -> bool {
519    p.contains("/workflows/runs/")
520        || p.starts_with(".specify/workflows/runs/")
521        || p.split('/').any(|c| c == "__pycache__")
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527
528    #[test]
529    fn requirement_ids_are_the_bold_fr_and_sc_items() {
530        let dir = tempfile::tempdir().unwrap();
531        std::fs::create_dir_all(dir.path().join("specs/001-x")).unwrap();
532        std::fs::write(
533            dir.path().join("specs/001-x/spec.md"),
534            "## 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",
535        )
536        .unwrap();
537        let ids: Vec<String> = SpecKit
538            .requirement_ids(dir.path(), "specs/001-x")
539            .into_iter()
540            .map(|(id, hash)| {
541                assert_eq!(hash.len(), 64);
542                id
543            })
544            .collect();
545        assert_eq!(ids, ["FR-001", "FR-002", "SC-001"]);
546    }
547}