Skip to main content

speccoder_runtime/
next.rs

1//! What to do next, from a command's result: its status and payload
2//! classified into an [`Outcome`], whose steps every renderer shows — the
3//! human `Next:` block, `data.next`, the TUI footer.
4
5use speccoder_core::next::{Outcome, next};
6use speccoder_core::{CommandData, CommandResult, CommandStatus, RunReport};
7
8/// `result` with its next steps and its code attached; `feature` is the
9/// `--feature` the command was given, carried to speccoder's own commands.
10/// A code the result already names is kept; otherwise the outcome's, or
11/// the status's default — every non-ok result leaves with one.
12#[must_use]
13pub fn attach(result: CommandResult, feature: Option<&str>) -> CommandResult {
14    // A code that says exactly what is wrong decides what comes next; the
15    // status alone ("a config error") would send a missing key to `init`.
16    if result.next().is_empty()
17        && let Some(steps) = result.code().and_then(|c| by_code(c.name))
18    {
19        return result.with_next(steps);
20    }
21    let outcome = classify(&result);
22    // Steps already attached (an in-place run's) are kept.
23    let mut result = match &outcome {
24        Some(o) if result.next().is_empty() => {
25            let steps = next(o, feature);
26            result.with_next(steps)
27        }
28        _ => result,
29    };
30    if !result.has_explicit_code() {
31        let task = outcome.as_ref().and_then(outcome_task);
32        let named = outcome
33            .as_ref()
34            .and_then(outcome_code)
35            .or_else(|| regression_only(&result).then_some("REGRESSION-ONLY"))
36            .and_then(speccoder_core::codes::lookup)
37            .filter(|e| e.status == result.status())
38            .or_else(|| speccoder_core::codes::default_for(result.status()));
39        if let Some(entry) = named {
40            let mut fix =
41                speccoder_core::codes::fixes(entry, result.command(), task.as_deref(), feature);
42            if entry.name == "REGRESSION-ONLY"
43                && let Some(why) = regression_fix(&result, feature)
44            {
45                fix = why;
46            }
47            // The stop's own lines (a ruling it offers) first, then the
48            // catalog's not already there.
49            // A line the same but for naming the feature is the same line.
50            let bare = |l: &str| {
51                let mut words: Vec<&str> = l.split(' ').collect();
52                if let Some(i) = words.iter().position(|w| *w == "--feature") {
53                    words.drain(i..(i + 2).min(words.len()));
54                }
55                words.join(" ")
56            };
57            let mut own = result.given_fix().to_vec();
58            let have: Vec<String> = own.iter().map(|l| bare(l)).collect();
59            own.extend(fix.into_iter().filter(|l| !have.contains(&bare(l))));
60            result = result.with_code(entry.name).with_fix(own);
61        }
62    }
63    result
64}
65
66/// Next steps for a failure whose code names it precisely.
67fn by_code(code: &str) -> Option<Vec<speccoder_core::next::NextStep>> {
68    let step = |command: &str, why: &str| speccoder_core::next::NextStep {
69        command: command.to_owned(),
70        why: why.to_owned(),
71    };
72    Some(match code {
73        "KEY-MISSING" => vec![step(
74            "speccoder doctor",
75            "check the rest of the setup once the key is set",
76        )],
77        "SETUP-INCOMPLETE" => vec![
78            step(
79                "speccoder fix --dry-run",
80                "what the fix commits, changing nothing",
81            ),
82            step("speccoder run", "run again once it is committed"),
83        ],
84        "CONFIG-INVALID" => vec![step(
85            "speccoder config",
86            "every key, its value, and what is wrong",
87        )],
88        "NOTHING-TO-HAND-OFF" => vec![step(
89            "speccoder run",
90            "tick tasks first: a pull request carries their evidence",
91        )],
92        "NO-CHECKS" => vec![step(
93            "speccoder config",
94            "every key: add a check under Checks",
95        )],
96        "CONFIG-EXISTS" => vec![step(
97            "speccoder config",
98            "every key and its value: change what you need",
99        )],
100        "CONFIG-NOT-TRACKED" => vec![step(
101            "speccoder config commit",
102            "speccoder reads committed configuration only",
103        )],
104        "GITHUB-AUTH" => vec![step(
105            "speccoder auth login --with-token",
106            "sign in to GitHub (the token goes to the keychain)",
107        )],
108        "GITHUB-FAILED" | "NO-REMOTE" => {
109            vec![step("speccoder doctor", "check the rest of the setup")]
110        }
111        // Outside a project: start one, or see what speccoder does first.
112        "NO-PROJECT" | "NO-REPOSITORY" => vec![
113            step(
114                "speccoder new \"<what you are building>\"",
115                "start a project here: the stack's and the spec format's own tools, then one commit",
116            ),
117            step(
118                "speccoder sample",
119                "a recorded run, replayed — no model, no key, no network",
120            ),
121        ],
122        _ => return None,
123    })
124}
125
126/// The catalog code an outcome stands for.
127const fn outcome_code(outcome: &Outcome) -> Option<&'static str> {
128    Some(match outcome {
129        Outcome::NeedsApproval { .. } => "NEEDS-APPROVAL",
130        Outcome::Blocked { .. } => "BLOCKED",
131        Outcome::BudgetExhausted { .. } => "BUDGET-EXHAUSTED",
132        Outcome::Incomplete { .. } => "ATTEMPT-INCOMPLETE",
133        Outcome::VerificationFailed { .. } => "VERIFICATION-FAILED",
134        Outcome::SuspectedGaming { .. } => "SUSPECTED-GAMING",
135        Outcome::TestsOverStrict { .. } => "TESTS-OVER-STRICT",
136        Outcome::AcceptanceWeak { .. } => "ACCEPTANCE-WEAK",
137        Outcome::NotDemonstrated { .. } => "NOT-DEMONSTRATED",
138        Outcome::RunFailed { .. } => "RUN-FAILED",
139        Outcome::Interrupted { .. } => "INTERRUPTED",
140        Outcome::NothingReady => "TASK-NOT-READY",
141        Outcome::ChecklistsOpen => "CHECKLISTS-OPEN",
142        Outcome::ConfigError => "CONFIG",
143        Outcome::GitPrecondition => "GIT",
144        Outcome::ArchiveAwaiting { .. } => "ARCHIVE-AWAITING",
145        _ => return None,
146    })
147}
148
149fn outcome_task(outcome: &Outcome) -> Option<String> {
150    match outcome {
151        Outcome::NeedsApproval { task }
152        | Outcome::Blocked { task }
153        | Outcome::BudgetExhausted { task }
154        | Outcome::Incomplete { task }
155        | Outcome::VerificationFailed { task }
156        | Outcome::SuspectedGaming { task }
157        | Outcome::TestsOverStrict { task }
158        | Outcome::AcceptanceWeak { task }
159        | Outcome::NotDemonstrated { task }
160        | Outcome::Interrupted { task }
161        | Outcome::TaskPassed { task, .. } => Some(task.clone()),
162        Outcome::RunFailed { task } => task.clone(),
163        _ => None,
164    }
165}
166
167/// The fix for why a tick was regression-only (the last such tick's reason).
168fn regression_fix(result: &CommandResult, feature: Option<&str>) -> Option<Vec<String>> {
169    use speccoder_core::regression::RegressionReason as R;
170    let reason = match result.data() {
171        Some(CommandData::Run(r)) => r.regression.clone(),
172        Some(CommandData::Feature(f)) => f.attempts.iter().rev().find_map(|a| a.regression.clone()),
173        _ => None,
174    }?
175    .reason;
176    let f = feature.map_or_else(String::new, |f| format!(" --feature {f}"));
177    let checks = format!("speccoder doctor{f}");
178    let converge = format!("speccoder converge{f}");
179    Some(match reason {
180        R::AcceptanceOff => vec!["→ set [acceptance] generate = true in speccoder.toml".to_owned()],
181        R::NoScenarios { story } => vec![
182            format!("→ add an acceptance scenario to {story}, then converge"),
183            converge,
184        ],
185        R::AlreadyPassing | R::NoStory => vec![
186            format!("{checks}  (the plan checks: behaviour planned before its story)"),
187            converge,
188        ],
189        R::AuthorWroteNone
190        | R::AuthorFailed { .. }
191        | R::NotRed { .. }
192        | R::TestsNotCollected
193        | R::Unrecorded => vec![checks, converge],
194        // Design documents, or a person's decision: nothing to do here.
195        R::PlanningWork | R::StoryVerified | R::InProgress => Vec::new(),
196        R::RegressionUnchecked => vec!["set `junit` on the test check in speccoder.toml, so a regression is told apart from the story's red tests".to_string()],
197    })
198}
199
200/// An `ok` run that ticked a task on the regression checks alone.
201fn regression_only(result: &CommandResult) -> bool {
202    use speccoder_core::verify::Verdict;
203    let is = |r: &RunReport| r.ticked && r.verdict == Some(Verdict::RegressionOnly);
204    result.status() == CommandStatus::Ok
205        && match result.data() {
206            Some(CommandData::Run(r)) => is(r),
207            Some(CommandData::Feature(f)) => f.attempts.iter().any(is),
208            _ => false,
209        }
210}
211
212/// The steps of a result from an in-place run, in place: `speccoder run`,
213/// `accept` and `converge` gain `--in-place` (a worktree-mode run would not
214/// see git-ignored specs, and is refused while the session holds them).
215#[must_use]
216pub fn in_place(result: CommandResult) -> CommandResult {
217    let steps = result
218        .next()
219        .iter()
220        .cloned()
221        .map(|mut s| {
222            for verb in ["run", "accept", "converge"] {
223                let head = format!("speccoder {verb}");
224                if (s.command == head || s.command.starts_with(&format!("{head} ")))
225                    && !s.command.contains("--in-place")
226                {
227                    s.command = format!("{head} --in-place{}", &s.command[head.len()..]);
228                }
229            }
230            s
231        })
232        .collect();
233    result.with_next(steps)
234}
235
236fn classify(result: &CommandResult) -> Option<Outcome> {
237    let status = result.status();
238    match (result.command(), status, result.data()) {
239        // An in-place refusal or stop names its own fix.
240        (_, _, Some(CommandData::InPlace(_))) => None,
241        (_, _, Some(CommandData::Checklists(_))) => Some(Outcome::ChecklistsOpen),
242        ("spec", CommandStatus::NeedsHuman, Some(CommandData::Archive(a)))
243            if a.stage == "awaiting_confirmation" =>
244        {
245            Some(Outcome::ArchiveAwaiting {
246                change: a.change.clone(),
247            })
248        }
249        ("run", _, Some(CommandData::Run(r))) => Some(of_run(status, r)),
250        ("run", _, Some(CommandData::Feature(f))) => match (status, f.attempts.last()) {
251            (CommandStatus::Ok, _) if f.stop.starts_with("feature done") => {
252                Some(Outcome::FeatureDone)
253            }
254            (CommandStatus::Ok, Some(last)) => Some(Outcome::TaskPassed {
255                task: last.task.clone(),
256                ready: 1,
257            }),
258            (CommandStatus::Ok, None) => Some(Outcome::FeatureDone),
259            (CommandStatus::TaskNotReady, _) => Some(Outcome::NothingReady),
260            (_, Some(last)) => Some(of_run(status, last)),
261            (_, None) => of_status(status),
262        },
263        ("report", CommandStatus::Ok, Some(CommandData::Report(r))) if !r.planning.is_empty() => {
264            Some(Outcome::Planning {
265                skills: r.planning.clone(),
266            })
267        }
268        ("report", CommandStatus::Ok, Some(CommandData::Report(r))) => Some(Outcome::ReportShown {
269            ready: r.totals.ready,
270            stale: r.totals.stale,
271            open_approvals: r
272                .tasks
273                .iter()
274                .filter(|t| {
275                    t.last_attempt
276                        .as_ref()
277                        .is_some_and(|a| a.outcome == "needs_approval")
278                })
279                .count(),
280        }),
281        ("approvals", CommandStatus::Ok, Some(CommandData::Approvals(a))) => {
282            Some(Outcome::ApprovalsListed {
283                first: a.pending.first().map(|p| p.task.clone()),
284            })
285        }
286        ("approve" | "reject" | "accept" | "skip" | "nudge", CommandStatus::Ok, _) => {
287            Some(Outcome::Decided)
288        }
289        _ => of_status(status),
290    }
291}
292
293/// One task run's outcome.
294fn of_run(status: CommandStatus, r: &RunReport) -> Outcome {
295    let task = r.task.clone();
296    let suspected = r.monitor.as_ref().is_some_and(|m| m["suspected"] == true);
297    match (status, r.attempt_status.as_str()) {
298        (CommandStatus::Ok, _) => Outcome::TaskPassed { task, ready: 1 },
299        _ if suspected => Outcome::SuspectedGaming { task },
300        (_, "over_strict") => Outcome::TestsOverStrict { task },
301        (_, "acceptance_weak") => Outcome::AcceptanceWeak { task },
302        (_, "needs_approval") => Outcome::NeedsApproval { task },
303        (_, "blocked") => Outcome::Blocked { task },
304        (_, "incomplete") => Outcome::Incomplete { task },
305        (_, "budget_exhausted" | "denied") => Outcome::BudgetExhausted { task },
306        (_, "interrupted") => Outcome::Interrupted { task },
307        (_, "not_demonstrated") => Outcome::NotDemonstrated { task },
308        (CommandStatus::VerificationFailed, _) => Outcome::VerificationFailed { task },
309        (CommandStatus::ConfigError, _) => Outcome::ConfigError,
310        (CommandStatus::GitPrecondition, _) => Outcome::GitPrecondition,
311        _ => Outcome::RunFailed { task: Some(task) },
312    }
313}
314
315/// Steps that depend only on how a command failed.
316fn of_status(status: CommandStatus) -> Option<Outcome> {
317    match status {
318        CommandStatus::ConfigError => Some(Outcome::ConfigError),
319        CommandStatus::GitPrecondition => Some(Outcome::GitPrecondition),
320        _ => None,
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[test]
329    fn decisions_and_config_errors_get_their_steps() {
330        let decided = attach(CommandResult::ok("approve", "approved"), Some("001-x"));
331        assert_eq!(decided.next()[0].command, "speccoder run --feature 001-x");
332        let config = attach(
333            CommandResult::new("verify", CommandStatus::ConfigError, "x"),
334            None,
335        );
336        assert_eq!(config.next()[0].command, "speccoder init");
337        assert!(
338            attach(CommandResult::ok("inspect", "x"), None)
339                .next()
340                .is_empty()
341        );
342    }
343
344    #[test]
345    fn a_stop_keeps_the_fix_lines_it_offers_before_the_catalog_s() {
346        let r = CommandResult::new("run", CommandStatus::NeedsHuman, "x").with_fix(vec![
347            "speccoder task rule T029 --tests-wrong --reason \"…\"".to_owned(),
348        ]);
349        let r = attach(r, None);
350        assert!(r.has_explicit_code());
351        assert_eq!(
352            r.fix().first().map(String::as_str),
353            Some("speccoder task rule T029 --tests-wrong --reason \"…\"")
354        );
355        assert!(r.fix().len() > 1, "{:?}", r.fix());
356    }
357
358    /// A run that stopped incomplete: its own ruling line first, the
359    /// code's lines after it, each once; attaching again changes nothing,
360    /// and steps already attached are kept.
361    #[test]
362    fn a_run_stop_keeps_its_ruling_and_attach_is_idempotent() {
363        let ruling = "speccoder task rule T029 --tests-wrong --reason \"…\"";
364        let report = crate::pipeline::outcome::bare_report("001-x", "T029", "/w", "incomplete");
365        let r = CommandResult::new("run", CommandStatus::NeedsHuman, "x")
366            .with_data(CommandData::Run(Box::new(report)))
367            .with_fix(vec![
368                ruling.to_owned(),
369                "speccoder task nudge T029 --feature 001-x --note \"…\"".to_owned(),
370            ]);
371        let once = attach(r, Some("001-x"));
372        assert_eq!(once.code().map(|c| c.name), Some("ATTEMPT-INCOMPLETE"));
373        let fix = once.fix();
374        assert_eq!(fix.first().map(String::as_str), Some(ruling));
375        assert_eq!(fix.iter().filter(|f| f.as_str() == ruling).count(), 1);
376        // One nudge, though the stop's names the feature and the catalog's not.
377        assert_eq!(
378            fix.iter()
379                .filter(|f| f.starts_with("speccoder task nudge T029"))
380                .count(),
381            1,
382            "{fix:?}"
383        );
384        assert!(
385            fix.iter()
386                .any(|f| f.starts_with("speccoder task nudge T029")),
387            "{fix:?}"
388        );
389        let next = once.next().to_vec();
390        let twice = attach(once, Some("001-x"));
391        assert_eq!(twice.fix(), fix);
392        assert_eq!(twice.next(), next.as_slice());
393    }
394
395    #[test]
396    fn steps_after_an_in_place_run_stay_in_place() {
397        let decided = in_place(attach(
398            CommandResult::ok("approve", "approved"),
399            Some("001-x"),
400        ));
401        assert_eq!(
402            decided.next()[0].command,
403            "speccoder run --in-place --feature 001-x"
404        );
405        let refused = attach(
406            CommandResult::new("run", CommandStatus::GitPrecondition, "x")
407                .with_data(CommandData::InPlace(Box::new(
408                    speccoder_core::InPlaceReport { paths: Vec::new() },
409                )))
410                .with_code("DIRTY-CHECKOUT")
411                .with_fix(vec!["git stash -u".to_owned()]),
412            None,
413        );
414        assert!(refused.next().is_empty(), "the fix lines say what to do");
415    }
416}