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::VerificationFailed { .. } => "VERIFICATION-FAILED",
120        Outcome::SuspectedGaming { .. } => "SUSPECTED-GAMING",
121        Outcome::TestsOverStrict { .. } => "TESTS-OVER-STRICT",
122        Outcome::AcceptanceWeak { .. } => "ACCEPTANCE-WEAK",
123        Outcome::NotDemonstrated { .. } => "NOT-DEMONSTRATED",
124        Outcome::RunFailed { .. } => "RUN-FAILED",
125        Outcome::Interrupted { .. } => "INTERRUPTED",
126        Outcome::NothingReady => "TASK-NOT-READY",
127        Outcome::ChecklistsOpen => "CHECKLISTS-OPEN",
128        Outcome::ConfigError => "CONFIG",
129        Outcome::GitPrecondition => "GIT",
130        Outcome::ArchiveAwaiting { .. } => "ARCHIVE-AWAITING",
131        _ => return None,
132    })
133}
134
135fn outcome_task(outcome: &Outcome) -> Option<String> {
136    match outcome {
137        Outcome::NeedsApproval { task }
138        | Outcome::Blocked { task }
139        | Outcome::BudgetExhausted { task }
140        | Outcome::VerificationFailed { task }
141        | Outcome::SuspectedGaming { task }
142        | Outcome::TestsOverStrict { task }
143        | Outcome::AcceptanceWeak { task }
144        | Outcome::NotDemonstrated { task }
145        | Outcome::Interrupted { task }
146        | Outcome::TaskPassed { task, .. } => Some(task.clone()),
147        Outcome::RunFailed { task } => task.clone(),
148        _ => None,
149    }
150}
151
152/// The fix for why a tick was regression-only (the last such tick's reason).
153fn regression_fix(result: &CommandResult, feature: Option<&str>) -> Option<Vec<String>> {
154    use speccoder_core::regression::RegressionReason as R;
155    let reason = match result.data() {
156        Some(CommandData::Run(r)) => r.regression.clone(),
157        Some(CommandData::Feature(f)) => f.attempts.iter().rev().find_map(|a| a.regression.clone()),
158        _ => None,
159    }?
160    .reason;
161    let f = feature.map_or_else(String::new, |f| format!(" --feature {f}"));
162    let checks = format!("speccoder doctor{f}");
163    let converge = format!("speccoder converge{f}");
164    Some(match reason {
165        R::AcceptanceOff => vec!["→ set [acceptance] generate = true in speccoder.toml".to_owned()],
166        R::NoScenarios { story } => vec![
167            format!("→ add an acceptance scenario to {story}, then converge"),
168            converge,
169        ],
170        R::AlreadyPassing { .. } | R::NoStory => vec![
171            format!("{checks}  (the plan checks: behaviour planned before its story)"),
172            converge,
173        ],
174        R::AuthorWroteNone
175        | R::AuthorFailed { .. }
176        | R::NotRed { .. }
177        | R::TestsNotCollected
178        | R::Unrecorded => vec![checks, converge],
179        // Design documents: nothing to test, nothing to do.
180        R::PlanningWork => Vec::new(),
181    })
182}
183
184/// An `ok` run that ticked a task on the regression checks alone.
185fn regression_only(result: &CommandResult) -> bool {
186    use speccoder_core::verify::Verdict;
187    let is = |r: &RunReport| r.ticked && r.verdict == Some(Verdict::RegressionOnly);
188    result.status() == CommandStatus::Ok
189        && match result.data() {
190            Some(CommandData::Run(r)) => is(r),
191            Some(CommandData::Feature(f)) => f.attempts.iter().any(is),
192            _ => false,
193        }
194}
195
196/// The steps of a result from an in-place run, in place: `speccoder run`,
197/// `accept` and `converge` gain `--in-place` (a worktree-mode run would not
198/// see git-ignored specs, and is refused while the session holds them).
199#[must_use]
200pub fn in_place(result: CommandResult) -> CommandResult {
201    let steps = result
202        .next()
203        .iter()
204        .cloned()
205        .map(|mut s| {
206            for verb in ["run", "accept", "converge"] {
207                let head = format!("speccoder {verb}");
208                if (s.command == head || s.command.starts_with(&format!("{head} ")))
209                    && !s.command.contains("--in-place")
210                {
211                    s.command = format!("{head} --in-place{}", &s.command[head.len()..]);
212                }
213            }
214            s
215        })
216        .collect();
217    result.with_next(steps)
218}
219
220fn classify(result: &CommandResult) -> Option<Outcome> {
221    let status = result.status();
222    match (result.command(), status, result.data()) {
223        // An in-place refusal or stop names its own fix.
224        (_, _, Some(CommandData::InPlace(_))) => None,
225        (_, _, Some(CommandData::Checklists(_))) => Some(Outcome::ChecklistsOpen),
226        ("spec", CommandStatus::NeedsHuman, Some(CommandData::Archive(a)))
227            if a.stage == "awaiting_confirmation" =>
228        {
229            Some(Outcome::ArchiveAwaiting {
230                change: a.change.clone(),
231            })
232        }
233        ("run", _, Some(CommandData::Run(r))) => Some(of_run(status, r)),
234        ("run", _, Some(CommandData::Feature(f))) => match (status, f.attempts.last()) {
235            (CommandStatus::Ok, _) if f.stop.starts_with("feature done") => {
236                Some(Outcome::FeatureDone)
237            }
238            (CommandStatus::Ok, Some(last)) => Some(Outcome::TaskPassed {
239                task: last.task.clone(),
240                ready: 1,
241            }),
242            (CommandStatus::Ok, None) => Some(Outcome::FeatureDone),
243            (CommandStatus::TaskNotReady, _) => Some(Outcome::NothingReady),
244            (_, Some(last)) => Some(of_run(status, last)),
245            (_, None) => of_status(status),
246        },
247        ("report", CommandStatus::Ok, Some(CommandData::Report(r))) if !r.planning.is_empty() => {
248            Some(Outcome::Planning {
249                skills: r.planning.clone(),
250            })
251        }
252        ("report", CommandStatus::Ok, Some(CommandData::Report(r))) => Some(Outcome::ReportShown {
253            ready: r.totals.ready,
254            stale: r.totals.stale,
255            open_approvals: r
256                .tasks
257                .iter()
258                .filter(|t| {
259                    t.last_attempt
260                        .as_ref()
261                        .is_some_and(|a| a.outcome == "needs_approval")
262                })
263                .count(),
264        }),
265        ("approvals", CommandStatus::Ok, Some(CommandData::Approvals(a))) => {
266            Some(Outcome::ApprovalsListed {
267                first: a.pending.first().map(|p| p.task.clone()),
268            })
269        }
270        ("approve" | "reject" | "accept" | "skip" | "nudge", CommandStatus::Ok, _) => {
271            Some(Outcome::Decided)
272        }
273        _ => of_status(status),
274    }
275}
276
277/// One task run's outcome.
278fn of_run(status: CommandStatus, r: &RunReport) -> Outcome {
279    let task = r.task.clone();
280    let suspected = r.monitor.as_ref().is_some_and(|m| m["suspected"] == true);
281    match (status, r.attempt_status.as_str()) {
282        (CommandStatus::Ok, _) => Outcome::TaskPassed { task, ready: 1 },
283        _ if suspected => Outcome::SuspectedGaming { task },
284        (_, "over_strict") => Outcome::TestsOverStrict { task },
285        (_, "acceptance_weak") => Outcome::AcceptanceWeak { task },
286        (_, "needs_approval") => Outcome::NeedsApproval { task },
287        (_, "blocked") => Outcome::Blocked { task },
288        (_, "budget_exhausted" | "incomplete" | "denied") => Outcome::BudgetExhausted { task },
289        (_, "interrupted") => Outcome::Interrupted { task },
290        (_, "not_demonstrated") => Outcome::NotDemonstrated { task },
291        (CommandStatus::VerificationFailed, _) => Outcome::VerificationFailed { task },
292        (CommandStatus::ConfigError, _) => Outcome::ConfigError,
293        (CommandStatus::GitPrecondition, _) => Outcome::GitPrecondition,
294        _ => Outcome::RunFailed { task: Some(task) },
295    }
296}
297
298/// Steps that depend only on how a command failed.
299fn of_status(status: CommandStatus) -> Option<Outcome> {
300    match status {
301        CommandStatus::ConfigError => Some(Outcome::ConfigError),
302        CommandStatus::GitPrecondition => Some(Outcome::GitPrecondition),
303        _ => None,
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    #[test]
312    fn decisions_and_config_errors_get_their_steps() {
313        let decided = attach(CommandResult::ok("approve", "approved"), Some("001-x"));
314        assert_eq!(decided.next()[0].command, "speccoder run --feature 001-x");
315        let config = attach(
316            CommandResult::new("verify", CommandStatus::ConfigError, "x"),
317            None,
318        );
319        assert_eq!(config.next()[0].command, "speccoder init");
320        assert!(
321            attach(CommandResult::ok("inspect", "x"), None)
322                .next()
323                .is_empty()
324        );
325    }
326
327    #[test]
328    fn steps_after_an_in_place_run_stay_in_place() {
329        let decided = in_place(attach(
330            CommandResult::ok("approve", "approved"),
331            Some("001-x"),
332        ));
333        assert_eq!(
334            decided.next()[0].command,
335            "speccoder run --in-place --feature 001-x"
336        );
337        let refused = attach(
338            CommandResult::new("run", CommandStatus::GitPrecondition, "x")
339                .with_data(CommandData::InPlace(Box::new(
340                    speccoder_core::InPlaceReport { paths: Vec::new() },
341                )))
342                .with_code("DIRTY-CHECKOUT")
343                .with_fix(vec!["git stash -u".to_owned()]),
344            None,
345        );
346        assert!(refused.next().is_empty(), "the fix lines say what to do");
347    }
348}