speccoder-runtime 0.8.4

Application services of speccoder: the only crate that executes anything.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! What to do next, from a command's result: its status and payload
//! classified into an [`Outcome`], whose steps every renderer shows — the
//! human `Next:` block, `data.next`, the TUI footer.

use speccoder_core::next::{Outcome, next};
use speccoder_core::{CommandData, CommandResult, CommandStatus, RunReport};

/// `result` with its next steps and its code attached; `feature` is the
/// `--feature` the command was given, carried to speccoder's own commands.
/// A code the result already names is kept; otherwise the outcome's, or
/// the status's default — every non-ok result leaves with one.
#[must_use]
pub fn attach(result: CommandResult, feature: Option<&str>) -> CommandResult {
    // A code that says exactly what is wrong decides what comes next; the
    // status alone ("a config error") would send a missing key to `init`.
    if result.next().is_empty()
        && let Some(steps) = result.code().and_then(|c| by_code(c.name))
    {
        return result.with_next(steps);
    }
    let outcome = classify(&result);
    // Steps already attached (an in-place run's) are kept.
    let mut result = match &outcome {
        Some(o) if result.next().is_empty() => {
            let steps = next(o, feature);
            result.with_next(steps)
        }
        _ => result,
    };
    if !result.has_explicit_code() {
        let task = outcome.as_ref().and_then(outcome_task);
        let named = outcome
            .as_ref()
            .and_then(outcome_code)
            .or_else(|| regression_only(&result).then_some("REGRESSION-ONLY"))
            .and_then(speccoder_core::codes::lookup)
            .filter(|e| e.status == result.status())
            .or_else(|| speccoder_core::codes::default_for(result.status()));
        if let Some(entry) = named {
            let mut fix =
                speccoder_core::codes::fixes(entry, result.command(), task.as_deref(), feature);
            if entry.name == "REGRESSION-ONLY"
                && let Some(why) = regression_fix(&result, feature)
            {
                fix = why;
            }
            // The stop's own lines (a ruling it offers) first, then the
            // catalog's not already there.
            // A line the same but for naming the feature is the same line.
            let bare = |l: &str| {
                let mut words: Vec<&str> = l.split(' ').collect();
                if let Some(i) = words.iter().position(|w| *w == "--feature") {
                    words.drain(i..(i + 2).min(words.len()));
                }
                words.join(" ")
            };
            let mut own = result.given_fix().to_vec();
            let have: Vec<String> = own.iter().map(|l| bare(l)).collect();
            own.extend(fix.into_iter().filter(|l| !have.contains(&bare(l))));
            result = result.with_code(entry.name).with_fix(own);
        }
    }
    result
}

/// Next steps for a failure whose code names it precisely.
fn by_code(code: &str) -> Option<Vec<speccoder_core::next::NextStep>> {
    let step = |command: &str, why: &str| speccoder_core::next::NextStep {
        command: command.to_owned(),
        why: why.to_owned(),
    };
    Some(match code {
        "KEY-MISSING" => vec![step(
            "speccoder doctor",
            "check the rest of the setup once the key is set",
        )],
        "SETUP-INCOMPLETE" => vec![
            step(
                "speccoder fix --dry-run",
                "what the fix commits, changing nothing",
            ),
            step("speccoder run", "run again once it is committed"),
        ],
        "CONFIG-INVALID" => vec![step(
            "speccoder config",
            "every key, its value, and what is wrong",
        )],
        "NOTHING-TO-HAND-OFF" => vec![step(
            "speccoder run",
            "tick tasks first: a pull request carries their evidence",
        )],
        "NO-CHECKS" => vec![step(
            "speccoder config",
            "every key: add a check under Checks",
        )],
        "CONFIG-EXISTS" => vec![step(
            "speccoder config",
            "every key and its value: change what you need",
        )],
        "CONFIG-NOT-TRACKED" => vec![step(
            "speccoder config commit",
            "speccoder reads committed configuration only",
        )],
        "GITHUB-AUTH" => vec![step(
            "speccoder auth login --with-token",
            "sign in to GitHub (the token goes to the keychain)",
        )],
        "GITHUB-FAILED" | "NO-REMOTE" => {
            vec![step("speccoder doctor", "check the rest of the setup")]
        }
        // Outside a project: start one, or see what speccoder does first.
        "NO-PROJECT" | "NO-REPOSITORY" => vec![
            step(
                "speccoder new \"<what you are building>\"",
                "start a project here: the stack's and the spec format's own tools, then one commit",
            ),
            step(
                "speccoder sample",
                "a recorded run, replayed — no model, no key, no network",
            ),
        ],
        _ => return None,
    })
}

/// The catalog code an outcome stands for.
const fn outcome_code(outcome: &Outcome) -> Option<&'static str> {
    Some(match outcome {
        Outcome::NeedsApproval { .. } => "NEEDS-APPROVAL",
        Outcome::Blocked { .. } => "BLOCKED",
        Outcome::BudgetExhausted { .. } => "BUDGET-EXHAUSTED",
        Outcome::Incomplete { .. } => "ATTEMPT-INCOMPLETE",
        Outcome::VerificationFailed { .. } => "VERIFICATION-FAILED",
        Outcome::SuspectedGaming { .. } => "SUSPECTED-GAMING",
        Outcome::TestsOverStrict { .. } => "TESTS-OVER-STRICT",
        Outcome::AcceptanceWeak { .. } => "ACCEPTANCE-WEAK",
        Outcome::NotDemonstrated { .. } => "NOT-DEMONSTRATED",
        Outcome::RunFailed { .. } => "RUN-FAILED",
        Outcome::Interrupted { .. } => "INTERRUPTED",
        Outcome::NothingReady => "TASK-NOT-READY",
        Outcome::ChecklistsOpen => "CHECKLISTS-OPEN",
        Outcome::ConfigError => "CONFIG",
        Outcome::GitPrecondition => "GIT",
        Outcome::ArchiveAwaiting { .. } => "ARCHIVE-AWAITING",
        _ => return None,
    })
}

fn outcome_task(outcome: &Outcome) -> Option<String> {
    match outcome {
        Outcome::NeedsApproval { task }
        | Outcome::Blocked { task }
        | Outcome::BudgetExhausted { task }
        | Outcome::Incomplete { task }
        | Outcome::VerificationFailed { task }
        | Outcome::SuspectedGaming { task }
        | Outcome::TestsOverStrict { task }
        | Outcome::AcceptanceWeak { task }
        | Outcome::NotDemonstrated { task }
        | Outcome::Interrupted { task }
        | Outcome::TaskPassed { task, .. } => Some(task.clone()),
        Outcome::RunFailed { task } => task.clone(),
        _ => None,
    }
}

/// The fix for why a tick was regression-only (the last such tick's reason).
fn regression_fix(result: &CommandResult, feature: Option<&str>) -> Option<Vec<String>> {
    use speccoder_core::regression::RegressionReason as R;
    let reason = match result.data() {
        Some(CommandData::Run(r)) => r.regression.clone(),
        Some(CommandData::Feature(f)) => f.attempts.iter().rev().find_map(|a| a.regression.clone()),
        _ => None,
    }?
    .reason;
    let f = feature.map_or_else(String::new, |f| format!(" --feature {f}"));
    let checks = format!("speccoder doctor{f}");
    let converge = format!("speccoder converge{f}");
    Some(match reason {
        R::AcceptanceOff => vec!["→ set [acceptance] generate = true in speccoder.toml".to_owned()],
        R::NoScenarios { story } => vec![
            format!("→ add an acceptance scenario to {story}, then converge"),
            converge,
        ],
        R::AlreadyPassing | R::NoStory => vec![
            format!("{checks}  (the plan checks: behaviour planned before its story)"),
            converge,
        ],
        R::AuthorWroteNone
        | R::AuthorFailed { .. }
        | R::NotRed { .. }
        | R::TestsNotCollected
        | R::Unrecorded => vec![checks, converge],
        // Design documents, or a person's decision: nothing to do here.
        R::PlanningWork | R::StoryVerified | R::InProgress => Vec::new(),
        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()],
    })
}

/// An `ok` run that ticked a task on the regression checks alone.
fn regression_only(result: &CommandResult) -> bool {
    use speccoder_core::verify::Verdict;
    let is = |r: &RunReport| r.ticked && r.verdict == Some(Verdict::RegressionOnly);
    result.status() == CommandStatus::Ok
        && match result.data() {
            Some(CommandData::Run(r)) => is(r),
            Some(CommandData::Feature(f)) => f.attempts.iter().any(is),
            _ => false,
        }
}

/// The steps of a result from an in-place run, in place: `speccoder run`,
/// `accept` and `converge` gain `--in-place` (a worktree-mode run would not
/// see git-ignored specs, and is refused while the session holds them).
#[must_use]
pub fn in_place(result: CommandResult) -> CommandResult {
    let steps = result
        .next()
        .iter()
        .cloned()
        .map(|mut s| {
            for verb in ["run", "accept", "converge"] {
                let head = format!("speccoder {verb}");
                if (s.command == head || s.command.starts_with(&format!("{head} ")))
                    && !s.command.contains("--in-place")
                {
                    s.command = format!("{head} --in-place{}", &s.command[head.len()..]);
                }
            }
            s
        })
        .collect();
    result.with_next(steps)
}

fn classify(result: &CommandResult) -> Option<Outcome> {
    let status = result.status();
    match (result.command(), status, result.data()) {
        // An in-place refusal or stop names its own fix.
        (_, _, Some(CommandData::InPlace(_))) => None,
        (_, _, Some(CommandData::Checklists(_))) => Some(Outcome::ChecklistsOpen),
        ("spec", CommandStatus::NeedsHuman, Some(CommandData::Archive(a)))
            if a.stage == "awaiting_confirmation" =>
        {
            Some(Outcome::ArchiveAwaiting {
                change: a.change.clone(),
            })
        }
        ("run", _, Some(CommandData::Run(r))) => Some(of_run(status, r)),
        ("run", _, Some(CommandData::Feature(f))) => match (status, f.attempts.last()) {
            (CommandStatus::Ok, _) if f.stop.starts_with("feature done") => {
                Some(Outcome::FeatureDone)
            }
            (CommandStatus::Ok, Some(last)) => Some(Outcome::TaskPassed {
                task: last.task.clone(),
                ready: 1,
            }),
            (CommandStatus::Ok, None) => Some(Outcome::FeatureDone),
            (CommandStatus::TaskNotReady, _) => Some(Outcome::NothingReady),
            (_, Some(last)) => Some(of_run(status, last)),
            (_, None) => of_status(status),
        },
        ("report", CommandStatus::Ok, Some(CommandData::Report(r))) if !r.planning.is_empty() => {
            Some(Outcome::Planning {
                skills: r.planning.clone(),
            })
        }
        ("report", CommandStatus::Ok, Some(CommandData::Report(r))) => Some(Outcome::ReportShown {
            ready: r.totals.ready,
            stale: r.totals.stale,
            open_approvals: r
                .tasks
                .iter()
                .filter(|t| {
                    t.last_attempt
                        .as_ref()
                        .is_some_and(|a| a.outcome == "needs_approval")
                })
                .count(),
        }),
        ("approvals", CommandStatus::Ok, Some(CommandData::Approvals(a))) => {
            Some(Outcome::ApprovalsListed {
                first: a.pending.first().map(|p| p.task.clone()),
            })
        }
        ("approve" | "reject" | "accept" | "skip" | "nudge", CommandStatus::Ok, _) => {
            Some(Outcome::Decided)
        }
        _ => of_status(status),
    }
}

/// One task run's outcome.
fn of_run(status: CommandStatus, r: &RunReport) -> Outcome {
    let task = r.task.clone();
    let suspected = r.monitor.as_ref().is_some_and(|m| m["suspected"] == true);
    match (status, r.attempt_status.as_str()) {
        (CommandStatus::Ok, _) => Outcome::TaskPassed { task, ready: 1 },
        _ if suspected => Outcome::SuspectedGaming { task },
        (_, "over_strict") => Outcome::TestsOverStrict { task },
        (_, "acceptance_weak") => Outcome::AcceptanceWeak { task },
        (_, "needs_approval") => Outcome::NeedsApproval { task },
        (_, "blocked") => Outcome::Blocked { task },
        (_, "incomplete") => Outcome::Incomplete { task },
        (_, "budget_exhausted" | "denied") => Outcome::BudgetExhausted { task },
        (_, "interrupted") => Outcome::Interrupted { task },
        (_, "not_demonstrated") => Outcome::NotDemonstrated { task },
        (CommandStatus::VerificationFailed, _) => Outcome::VerificationFailed { task },
        (CommandStatus::ConfigError, _) => Outcome::ConfigError,
        (CommandStatus::GitPrecondition, _) => Outcome::GitPrecondition,
        _ => Outcome::RunFailed { task: Some(task) },
    }
}

/// Steps that depend only on how a command failed.
fn of_status(status: CommandStatus) -> Option<Outcome> {
    match status {
        CommandStatus::ConfigError => Some(Outcome::ConfigError),
        CommandStatus::GitPrecondition => Some(Outcome::GitPrecondition),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn decisions_and_config_errors_get_their_steps() {
        let decided = attach(CommandResult::ok("approve", "approved"), Some("001-x"));
        assert_eq!(decided.next()[0].command, "speccoder run --feature 001-x");
        let config = attach(
            CommandResult::new("verify", CommandStatus::ConfigError, "x"),
            None,
        );
        assert_eq!(config.next()[0].command, "speccoder init");
        assert!(
            attach(CommandResult::ok("inspect", "x"), None)
                .next()
                .is_empty()
        );
    }

    #[test]
    fn a_stop_keeps_the_fix_lines_it_offers_before_the_catalog_s() {
        let r = CommandResult::new("run", CommandStatus::NeedsHuman, "x").with_fix(vec![
            "speccoder task rule T029 --tests-wrong --reason \"…\"".to_owned(),
        ]);
        let r = attach(r, None);
        assert!(r.has_explicit_code());
        assert_eq!(
            r.fix().first().map(String::as_str),
            Some("speccoder task rule T029 --tests-wrong --reason \"…\"")
        );
        assert!(r.fix().len() > 1, "{:?}", r.fix());
    }

    /// A run that stopped incomplete: its own ruling line first, the
    /// code's lines after it, each once; attaching again changes nothing,
    /// and steps already attached are kept.
    #[test]
    fn a_run_stop_keeps_its_ruling_and_attach_is_idempotent() {
        let ruling = "speccoder task rule T029 --tests-wrong --reason \"…\"";
        let report = crate::pipeline::outcome::bare_report("001-x", "T029", "/w", "incomplete");
        let r = CommandResult::new("run", CommandStatus::NeedsHuman, "x")
            .with_data(CommandData::Run(Box::new(report)))
            .with_fix(vec![
                ruling.to_owned(),
                "speccoder task nudge T029 --feature 001-x --note \"…\"".to_owned(),
            ]);
        let once = attach(r, Some("001-x"));
        assert_eq!(once.code().map(|c| c.name), Some("ATTEMPT-INCOMPLETE"));
        let fix = once.fix();
        assert_eq!(fix.first().map(String::as_str), Some(ruling));
        assert_eq!(fix.iter().filter(|f| f.as_str() == ruling).count(), 1);
        // One nudge, though the stop's names the feature and the catalog's not.
        assert_eq!(
            fix.iter()
                .filter(|f| f.starts_with("speccoder task nudge T029"))
                .count(),
            1,
            "{fix:?}"
        );
        assert!(
            fix.iter()
                .any(|f| f.starts_with("speccoder task nudge T029")),
            "{fix:?}"
        );
        let next = once.next().to_vec();
        let twice = attach(once, Some("001-x"));
        assert_eq!(twice.fix(), fix);
        assert_eq!(twice.next(), next.as_slice());
    }

    #[test]
    fn steps_after_an_in_place_run_stay_in_place() {
        let decided = in_place(attach(
            CommandResult::ok("approve", "approved"),
            Some("001-x"),
        ));
        assert_eq!(
            decided.next()[0].command,
            "speccoder run --in-place --feature 001-x"
        );
        let refused = attach(
            CommandResult::new("run", CommandStatus::GitPrecondition, "x")
                .with_data(CommandData::InPlace(Box::new(
                    speccoder_core::InPlaceReport { paths: Vec::new() },
                )))
                .with_code("DIRTY-CHECKOUT")
                .with_fix(vec!["git stash -u".to_owned()]),
            None,
        );
        assert!(refused.next().is_empty(), "the fix lines say what to do");
    }
}