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            result = result.with_code(entry.name).with_fix(fix);
48        }
49    }
50    result
51}
52
53/// Next steps for a failure whose code names it precisely.
54fn by_code(code: &str) -> Option<Vec<speccoder_core::next::NextStep>> {
55    let step = |command: &str, why: &str| speccoder_core::next::NextStep {
56        command: command.to_owned(),
57        why: why.to_owned(),
58    };
59    Some(match code {
60        "KEY-MISSING" => vec![step(
61            "speccoder doctor",
62            "check the rest of the setup once the key is set",
63        )],
64        "SETUP-INCOMPLETE" => vec![
65            step(
66                "speccoder fix --dry-run",
67                "what the fix commits, changing nothing",
68            ),
69            step("speccoder run", "run again once it is committed"),
70        ],
71        "CONFIG-INVALID" => vec![step(
72            "speccoder config",
73            "every key, its value, and what is wrong",
74        )],
75        "NOTHING-TO-HAND-OFF" => vec![step(
76            "speccoder run",
77            "tick tasks first: a pull request carries their evidence",
78        )],
79        "NO-CHECKS" => vec![step(
80            "speccoder config",
81            "every key: add a check under Checks",
82        )],
83        "CONFIG-EXISTS" => vec![step(
84            "speccoder config",
85            "every key and its value: change what you need",
86        )],
87        "CONFIG-NOT-TRACKED" => vec![step(
88            "speccoder config commit",
89            "speccoder reads committed configuration only",
90        )],
91        "GITHUB-AUTH" => vec![step(
92            "speccoder auth login --with-token",
93            "sign in to GitHub (the token goes to the keychain)",
94        )],
95        "GITHUB-FAILED" | "NO-REMOTE" => {
96            vec![step("speccoder doctor", "check the rest of the setup")]
97        }
98        // Outside a project: start one, or see what speccoder does first.
99        "NO-PROJECT" | "NO-REPOSITORY" => vec![
100            step(
101                "speccoder new \"<what you are building>\"",
102                "start a project here: the stack's and the spec format's own tools, then one commit",
103            ),
104            step(
105                "speccoder sample",
106                "a recorded run, replayed — no model, no key, no network",
107            ),
108        ],
109        _ => return None,
110    })
111}
112
113/// The catalog code an outcome stands for.
114const fn outcome_code(outcome: &Outcome) -> Option<&'static str> {
115    Some(match outcome {
116        Outcome::NeedsApproval { .. } => "NEEDS-APPROVAL",
117        Outcome::Blocked { .. } => "BLOCKED",
118        Outcome::BudgetExhausted { .. } => "BUDGET-EXHAUSTED",
119        Outcome::Incomplete { .. } => "ATTEMPT-INCOMPLETE",
120        Outcome::VerificationFailed { .. } => "VERIFICATION-FAILED",
121        Outcome::SuspectedGaming { .. } => "SUSPECTED-GAMING",
122        Outcome::TestsOverStrict { .. } => "TESTS-OVER-STRICT",
123        Outcome::AcceptanceWeak { .. } => "ACCEPTANCE-WEAK",
124        Outcome::NotDemonstrated { .. } => "NOT-DEMONSTRATED",
125        Outcome::RunFailed { .. } => "RUN-FAILED",
126        Outcome::Interrupted { .. } => "INTERRUPTED",
127        Outcome::NothingReady => "TASK-NOT-READY",
128        Outcome::ChecklistsOpen => "CHECKLISTS-OPEN",
129        Outcome::ConfigError => "CONFIG",
130        Outcome::GitPrecondition => "GIT",
131        Outcome::ArchiveAwaiting { .. } => "ARCHIVE-AWAITING",
132        _ => return None,
133    })
134}
135
136fn outcome_task(outcome: &Outcome) -> Option<String> {
137    match outcome {
138        Outcome::NeedsApproval { task }
139        | Outcome::Blocked { task }
140        | Outcome::BudgetExhausted { task }
141        | Outcome::Incomplete { task }
142        | Outcome::VerificationFailed { task }
143        | Outcome::SuspectedGaming { task }
144        | Outcome::TestsOverStrict { task }
145        | Outcome::AcceptanceWeak { task }
146        | Outcome::NotDemonstrated { task }
147        | Outcome::Interrupted { task }
148        | Outcome::TaskPassed { task, .. } => Some(task.clone()),
149        Outcome::RunFailed { task } => task.clone(),
150        _ => None,
151    }
152}
153
154/// The fix for why a tick was regression-only (the last such tick's reason).
155fn regression_fix(result: &CommandResult, feature: Option<&str>) -> Option<Vec<String>> {
156    use speccoder_core::regression::RegressionReason as R;
157    let reason = match result.data() {
158        Some(CommandData::Run(r)) => r.regression.clone(),
159        Some(CommandData::Feature(f)) => f.attempts.iter().rev().find_map(|a| a.regression.clone()),
160        _ => None,
161    }?
162    .reason;
163    let f = feature.map_or_else(String::new, |f| format!(" --feature {f}"));
164    let checks = format!("speccoder doctor{f}");
165    let converge = format!("speccoder converge{f}");
166    Some(match reason {
167        R::AcceptanceOff => vec!["→ set [acceptance] generate = true in speccoder.toml".to_owned()],
168        R::NoScenarios { story } => vec![
169            format!("→ add an acceptance scenario to {story}, then converge"),
170            converge,
171        ],
172        R::AlreadyPassing { .. } | R::NoStory => vec![
173            format!("{checks}  (the plan checks: behaviour planned before its story)"),
174            converge,
175        ],
176        R::AuthorWroteNone
177        | R::AuthorFailed { .. }
178        | R::NotRed { .. }
179        | R::TestsNotCollected
180        | R::Unrecorded => vec![checks, converge],
181        // Design documents: nothing to test, nothing to do.
182        R::PlanningWork => Vec::new(),
183    })
184}
185
186/// An `ok` run that ticked a task on the regression checks alone.
187fn regression_only(result: &CommandResult) -> bool {
188    use speccoder_core::verify::Verdict;
189    let is = |r: &RunReport| r.ticked && r.verdict == Some(Verdict::RegressionOnly);
190    result.status() == CommandStatus::Ok
191        && match result.data() {
192            Some(CommandData::Run(r)) => is(r),
193            Some(CommandData::Feature(f)) => f.attempts.iter().any(is),
194            _ => false,
195        }
196}
197
198/// The steps of a result from an in-place run, in place: `speccoder run`,
199/// `accept` and `converge` gain `--in-place` (a worktree-mode run would not
200/// see git-ignored specs, and is refused while the session holds them).
201#[must_use]
202pub fn in_place(result: CommandResult) -> CommandResult {
203    let steps = result
204        .next()
205        .iter()
206        .cloned()
207        .map(|mut s| {
208            for verb in ["run", "accept", "converge"] {
209                let head = format!("speccoder {verb}");
210                if (s.command == head || s.command.starts_with(&format!("{head} ")))
211                    && !s.command.contains("--in-place")
212                {
213                    s.command = format!("{head} --in-place{}", &s.command[head.len()..]);
214                }
215            }
216            s
217        })
218        .collect();
219    result.with_next(steps)
220}
221
222fn classify(result: &CommandResult) -> Option<Outcome> {
223    let status = result.status();
224    match (result.command(), status, result.data()) {
225        // An in-place refusal or stop names its own fix.
226        (_, _, Some(CommandData::InPlace(_))) => None,
227        (_, _, Some(CommandData::Checklists(_))) => Some(Outcome::ChecklistsOpen),
228        ("spec", CommandStatus::NeedsHuman, Some(CommandData::Archive(a)))
229            if a.stage == "awaiting_confirmation" =>
230        {
231            Some(Outcome::ArchiveAwaiting {
232                change: a.change.clone(),
233            })
234        }
235        ("run", _, Some(CommandData::Run(r))) => Some(of_run(status, r)),
236        ("run", _, Some(CommandData::Feature(f))) => match (status, f.attempts.last()) {
237            (CommandStatus::Ok, _) if f.stop.starts_with("feature done") => {
238                Some(Outcome::FeatureDone)
239            }
240            (CommandStatus::Ok, Some(last)) => Some(Outcome::TaskPassed {
241                task: last.task.clone(),
242                ready: 1,
243            }),
244            (CommandStatus::Ok, None) => Some(Outcome::FeatureDone),
245            (CommandStatus::TaskNotReady, _) => Some(Outcome::NothingReady),
246            (_, Some(last)) => Some(of_run(status, last)),
247            (_, None) => of_status(status),
248        },
249        ("report", CommandStatus::Ok, Some(CommandData::Report(r))) if !r.planning.is_empty() => {
250            Some(Outcome::Planning {
251                skills: r.planning.clone(),
252            })
253        }
254        ("report", CommandStatus::Ok, Some(CommandData::Report(r))) => Some(Outcome::ReportShown {
255            ready: r.totals.ready,
256            stale: r.totals.stale,
257            open_approvals: r
258                .tasks
259                .iter()
260                .filter(|t| {
261                    t.last_attempt
262                        .as_ref()
263                        .is_some_and(|a| a.outcome == "needs_approval")
264                })
265                .count(),
266        }),
267        ("approvals", CommandStatus::Ok, Some(CommandData::Approvals(a))) => {
268            Some(Outcome::ApprovalsListed {
269                first: a.pending.first().map(|p| p.task.clone()),
270            })
271        }
272        ("approve" | "reject" | "accept" | "skip" | "nudge", CommandStatus::Ok, _) => {
273            Some(Outcome::Decided)
274        }
275        _ => of_status(status),
276    }
277}
278
279/// One task run's outcome.
280fn of_run(status: CommandStatus, r: &RunReport) -> Outcome {
281    let task = r.task.clone();
282    let suspected = r.monitor.as_ref().is_some_and(|m| m["suspected"] == true);
283    match (status, r.attempt_status.as_str()) {
284        (CommandStatus::Ok, _) => Outcome::TaskPassed { task, ready: 1 },
285        _ if suspected => Outcome::SuspectedGaming { task },
286        (_, "over_strict") => Outcome::TestsOverStrict { task },
287        (_, "acceptance_weak") => Outcome::AcceptanceWeak { task },
288        (_, "needs_approval") => Outcome::NeedsApproval { task },
289        (_, "blocked") => Outcome::Blocked { task },
290        (_, "incomplete") => Outcome::Incomplete { task },
291        (_, "budget_exhausted" | "denied") => Outcome::BudgetExhausted { task },
292        (_, "interrupted") => Outcome::Interrupted { task },
293        (_, "not_demonstrated") => Outcome::NotDemonstrated { task },
294        (CommandStatus::VerificationFailed, _) => Outcome::VerificationFailed { task },
295        (CommandStatus::ConfigError, _) => Outcome::ConfigError,
296        (CommandStatus::GitPrecondition, _) => Outcome::GitPrecondition,
297        _ => Outcome::RunFailed { task: Some(task) },
298    }
299}
300
301/// Steps that depend only on how a command failed.
302fn of_status(status: CommandStatus) -> Option<Outcome> {
303    match status {
304        CommandStatus::ConfigError => Some(Outcome::ConfigError),
305        CommandStatus::GitPrecondition => Some(Outcome::GitPrecondition),
306        _ => None,
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    #[test]
315    fn decisions_and_config_errors_get_their_steps() {
316        let decided = attach(CommandResult::ok("approve", "approved"), Some("001-x"));
317        assert_eq!(decided.next()[0].command, "speccoder run --feature 001-x");
318        let config = attach(
319            CommandResult::new("verify", CommandStatus::ConfigError, "x"),
320            None,
321        );
322        assert_eq!(config.next()[0].command, "speccoder init");
323        assert!(
324            attach(CommandResult::ok("inspect", "x"), None)
325                .next()
326                .is_empty()
327        );
328    }
329
330    #[test]
331    fn steps_after_an_in_place_run_stay_in_place() {
332        let decided = in_place(attach(
333            CommandResult::ok("approve", "approved"),
334            Some("001-x"),
335        ));
336        assert_eq!(
337            decided.next()[0].command,
338            "speccoder run --in-place --feature 001-x"
339        );
340        let refused = attach(
341            CommandResult::new("run", CommandStatus::GitPrecondition, "x")
342                .with_data(CommandData::InPlace(Box::new(
343                    speccoder_core::InPlaceReport { paths: Vec::new() },
344                )))
345                .with_code("DIRTY-CHECKOUT")
346                .with_fix(vec!["git stash -u".to_owned()]),
347            None,
348        );
349        assert!(refused.next().is_empty(), "the fix lines say what to do");
350    }
351}