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