1use speccoder_core::next::{Outcome, next};
6use speccoder_core::{CommandData, CommandResult, CommandStatus, RunReport};
7
8#[must_use]
13pub fn attach(result: CommandResult, feature: Option<&str>) -> CommandResult {
14 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 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
53fn 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 "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
113const 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
152fn 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 })
180}
181
182fn regression_only(result: &CommandResult) -> bool {
184 use speccoder_core::verify::Verdict;
185 let is = |r: &RunReport| r.ticked && r.verdict == Some(Verdict::RegressionOnly);
186 result.status() == CommandStatus::Ok
187 && match result.data() {
188 Some(CommandData::Run(r)) => is(r),
189 Some(CommandData::Feature(f)) => f.attempts.iter().any(is),
190 _ => false,
191 }
192}
193
194#[must_use]
198pub fn in_place(result: CommandResult) -> CommandResult {
199 let steps = result
200 .next()
201 .iter()
202 .cloned()
203 .map(|mut s| {
204 for verb in ["run", "accept", "converge"] {
205 let head = format!("speccoder {verb}");
206 if (s.command == head || s.command.starts_with(&format!("{head} ")))
207 && !s.command.contains("--in-place")
208 {
209 s.command = format!("{head} --in-place{}", &s.command[head.len()..]);
210 }
211 }
212 s
213 })
214 .collect();
215 result.with_next(steps)
216}
217
218fn classify(result: &CommandResult) -> Option<Outcome> {
219 let status = result.status();
220 match (result.command(), status, result.data()) {
221 (_, _, Some(CommandData::InPlace(_))) => None,
223 (_, _, Some(CommandData::Checklists(_))) => Some(Outcome::ChecklistsOpen),
224 ("spec", CommandStatus::NeedsHuman, Some(CommandData::Archive(a)))
225 if a.stage == "awaiting_confirmation" =>
226 {
227 Some(Outcome::ArchiveAwaiting {
228 change: a.change.clone(),
229 })
230 }
231 ("run", _, Some(CommandData::Run(r))) => Some(of_run(status, r)),
232 ("run", _, Some(CommandData::Feature(f))) => match (status, f.attempts.last()) {
233 (CommandStatus::Ok, _) if f.stop.starts_with("feature done") => {
234 Some(Outcome::FeatureDone)
235 }
236 (CommandStatus::Ok, Some(last)) => Some(Outcome::TaskPassed {
237 task: last.task.clone(),
238 ready: 1,
239 }),
240 (CommandStatus::Ok, None) => Some(Outcome::FeatureDone),
241 (CommandStatus::TaskNotReady, _) => Some(Outcome::NothingReady),
242 (_, Some(last)) => Some(of_run(status, last)),
243 (_, None) => of_status(status),
244 },
245 ("report", CommandStatus::Ok, Some(CommandData::Report(r))) if !r.planning.is_empty() => {
246 Some(Outcome::Planning {
247 skills: r.planning.clone(),
248 })
249 }
250 ("report", CommandStatus::Ok, Some(CommandData::Report(r))) => Some(Outcome::ReportShown {
251 ready: r.totals.ready,
252 stale: r.totals.stale,
253 open_approvals: r
254 .tasks
255 .iter()
256 .filter(|t| {
257 t.last_attempt
258 .as_ref()
259 .is_some_and(|a| a.outcome == "needs_approval")
260 })
261 .count(),
262 }),
263 ("approvals", CommandStatus::Ok, Some(CommandData::Approvals(a))) => {
264 Some(Outcome::ApprovalsListed {
265 first: a.pending.first().map(|p| p.task.clone()),
266 })
267 }
268 ("approve" | "reject" | "accept" | "skip" | "nudge", CommandStatus::Ok, _) => {
269 Some(Outcome::Decided)
270 }
271 _ => of_status(status),
272 }
273}
274
275fn of_run(status: CommandStatus, r: &RunReport) -> Outcome {
277 let task = r.task.clone();
278 let suspected = r.monitor.as_ref().is_some_and(|m| m["suspected"] == true);
279 match (status, r.attempt_status.as_str()) {
280 (CommandStatus::Ok, _) => Outcome::TaskPassed { task, ready: 1 },
281 _ if suspected => Outcome::SuspectedGaming { task },
282 (_, "over_strict") => Outcome::TestsOverStrict { task },
283 (_, "acceptance_weak") => Outcome::AcceptanceWeak { task },
284 (_, "needs_approval") => Outcome::NeedsApproval { task },
285 (_, "blocked") => Outcome::Blocked { task },
286 (_, "budget_exhausted" | "incomplete" | "denied") => Outcome::BudgetExhausted { task },
287 (_, "interrupted") => Outcome::Interrupted { task },
288 (_, "not_demonstrated") => Outcome::NotDemonstrated { task },
289 (CommandStatus::VerificationFailed, _) => Outcome::VerificationFailed { task },
290 (CommandStatus::ConfigError, _) => Outcome::ConfigError,
291 (CommandStatus::GitPrecondition, _) => Outcome::GitPrecondition,
292 _ => Outcome::RunFailed { task: Some(task) },
293 }
294}
295
296fn of_status(status: CommandStatus) -> Option<Outcome> {
298 match status {
299 CommandStatus::ConfigError => Some(Outcome::ConfigError),
300 CommandStatus::GitPrecondition => Some(Outcome::GitPrecondition),
301 _ => None,
302 }
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308
309 #[test]
310 fn decisions_and_config_errors_get_their_steps() {
311 let decided = attach(CommandResult::ok("approve", "approved"), Some("001-x"));
312 assert_eq!(decided.next()[0].command, "speccoder run --feature 001-x");
313 let config = attach(
314 CommandResult::new("verify", CommandStatus::ConfigError, "x"),
315 None,
316 );
317 assert_eq!(config.next()[0].command, "speccoder init");
318 assert!(
319 attach(CommandResult::ok("inspect", "x"), None)
320 .next()
321 .is_empty()
322 );
323 }
324
325 #[test]
326 fn steps_after_an_in_place_run_stay_in_place() {
327 let decided = in_place(attach(
328 CommandResult::ok("approve", "approved"),
329 Some("001-x"),
330 ));
331 assert_eq!(
332 decided.next()[0].command,
333 "speccoder run --in-place --feature 001-x"
334 );
335 let refused = attach(
336 CommandResult::new("run", CommandStatus::GitPrecondition, "x")
337 .with_data(CommandData::InPlace(Box::new(
338 speccoder_core::InPlaceReport { paths: Vec::new() },
339 )))
340 .with_code("DIRTY-CHECKOUT")
341 .with_fix(vec!["git stash -u".to_owned()]),
342 None,
343 );
344 assert!(refused.next().is_empty(), "the fix lines say what to do");
345 }
346}