Skip to main content

speccoder_runtime/pipeline/task/
mod.rs

1//! `speccoder run --task`: one task from baseline to tick, one file per
2//! phase: `open`, `ready`, `tests`, `attempt`, `judge`, `tick`.
3
4use std::path::Path;
5use std::sync::Arc;
6
7use speccoder_core::{CommandData, CommandResult, CommandStatus};
8
9use crate::pipeline::*;
10use crate::{
11    approvals, attempts, external, integrity, mcp, mutation, progress, resume, sandbox, substrate,
12    tools, worktree,
13};
14
15/// `speccoder run`: one attempt at a ready task in its worktree, judged by
16/// the verifier. The provider comes from `[model]` and its key variable.
17#[must_use]
18pub fn run(path: &Path, feature: Option<&str>, task: &str, options: &RunOptions) -> CommandResult {
19    let Some(state) = worktree::state_dir() else {
20        return CommandResult::new(
21            "run",
22            CommandStatus::ConfigError,
23            "no state directory (set SPECCODER_STATE_DIR or HOME)",
24        )
25        .with_code("NO-STATE-DIR");
26    };
27    let model = match setup(path, feature, &state, "run") {
28        Ok(s) => s.model,
29        Err(r) => return *r,
30    };
31    let (driver, key) = match substrate::model_config::open_driver(&model) {
32        Ok((d, k)) => (Ok::<_, String>(d), k.unwrap_or_default()),
33        Err(e) => return substrate::model_config::refused("run", &e),
34    };
35    match driver {
36        Ok(provider) => run_task(path, feature, task, &state, provider, Some(&key), options),
37        Err(e) => CommandResult::new("run", CommandStatus::ConfigError, &redact(&e, Some(&key))),
38    }
39}
40
41/// [`run`] with an explicit state directory and model driver.
42pub fn run_with(
43    path: &Path,
44    feature: Option<&str>,
45    task: &str,
46    state: &Path,
47    provider: std::sync::Arc<dyn agentplane::model::ModelProvider>,
48    secret: Option<&str>,
49) -> CommandResult {
50    run_task(
51        path,
52        feature,
53        task,
54        state,
55        provider,
56        secret,
57        &RunOptions::default(),
58    )
59}
60
61/// [`run_with`] with explicit [`RunOptions`].
62#[must_use]
63pub fn run_with_options(
64    path: &Path,
65    feature: Option<&str>,
66    task: &str,
67    state: &Path,
68    provider: Arc<dyn agentplane::model::ModelProvider>,
69    secret: Option<&str>,
70    options: &RunOptions,
71) -> CommandResult {
72    run_task(path, feature, task, state, provider, secret, options)
73}
74
75/// [`run_with`] asking `approver` inline when a call needs approval.
76#[must_use]
77pub fn run_with_approver(
78    path: &Path,
79    feature: Option<&str>,
80    task: &str,
81    state: &Path,
82    provider: Arc<dyn agentplane::model::ModelProvider>,
83    secret: Option<&str>,
84    approver: Arc<dyn approvals::Approver>,
85) -> CommandResult {
86    let options = RunOptions {
87        approver: Some(approver),
88        ..RunOptions::default()
89    };
90    run_task(path, feature, task, state, provider, secret, &options)
91}
92
93/// Runs a bug of the format's own bug structure: a unit no task list
94/// names, its task `bug:<slug>`, ticked nowhere.
95#[must_use]
96pub fn run_native_bug(
97    root: &Path,
98    bug: &speccoder_core::bug::BugReport,
99    state: &Path,
100    provider: Arc<dyn agentplane::model::ModelProvider>,
101    secret: Option<&str>,
102    options: &RunOptions,
103) -> CommandResult {
104    let options = RunOptions {
105        bug_home: Some(Arc::new(super::bug::NativeBug::of(bug))),
106        ..options.clone()
107    };
108    run_task(root, None, &bug.task, state, provider, secret, &options)
109}
110
111mod attempt;
112mod judge;
113/// One task: its attempt, and — when a planning attempt changed code —
114/// the task again as code (the planning attempt saved and undone, its
115/// saved outcome the reason it is code from now on).
116mod open;
117mod ready;
118mod tests;
119mod tick;
120
121/// A phase's result, or the run's end with what a person sees.
122macro_rules! ok {
123    ($phase:expr) => {
124        match $phase {
125            Ok(x) => x,
126            Err(end) => return *end,
127        }
128    };
129}
130
131/// What opening the task started that later phases carry on.
132pub(super) struct Started {
133    /// Removes the resume marker when the run ends, unless kept.
134    pub(super) marker_guard: crate::resume::Guard,
135    /// The worktree's head an interrupted attempt is resumed at.
136    pub(super) head_now: String,
137    /// Leftovers set aside before the run, named in its report.
138    pub(super) set_aside: Option<String>,
139}
140
141/// What one phase sets and a later phase changes: handed on explicitly,
142/// changed only by a phase that takes it mutably.
143pub(super) struct Carried {
144    /// The worktree's head an interrupted attempt is resumed at (moved by
145    /// the story's oracle commit).
146    pub(super) head_now: String,
147    /// Removes the resume marker when the run ends, unless kept.
148    pub(super) marker_guard: crate::resume::Guard,
149    /// Leftovers set aside before the run, named in its report.
150    pub(super) set_aside: Option<String>,
151    /// The checks on the tree the attempt starts from (re-run after the
152    /// story's oracle is committed).
153    pub(super) baseline: speccoder_core::verify::VerifyReport,
154    /// What the run tells a person, gathered by every phase.
155    pub(super) notices: Vec<String>,
156}
157
158/// An early end recorded as the task run's end (`TaskFinished`), redacted.
159pub(super) fn ended(
160    live: &dyn progress::Progress,
161    task: &str,
162    secret: Option<&str>,
163    status: CommandStatus,
164    m: String,
165) -> CommandResult {
166    live.event(&progress::Event::TaskFinished {
167        task: task.to_owned(),
168        outcome: "error".to_owned(),
169        message: redact(&m, secret),
170        run: None,
171        input_tokens: 0,
172        output_tokens: 0,
173        cache_read_tokens: 0,
174        cache_write_tokens: 0,
175        usd: None,
176        regression: None,
177    });
178    CommandResult::new("run", status, &redact(&m, secret))
179}
180
181pub(crate) fn run_task(
182    path: &Path,
183    feature: Option<&str>,
184    task: &str,
185    state: &Path,
186    provider: std::sync::Arc<dyn agentplane::model::ModelProvider>,
187    secret: Option<&str>,
188    options: &RunOptions,
189) -> CommandResult {
190    // A unit that is a bug runs as one bug, never task by task.
191    if options.bug_home.is_none()
192        && let Some(slug) = bug_spec(path, feature)
193    {
194        if let Some(p) = &options.progress {
195            p.event(&progress::Event::Notice {
196                text: format!("{slug} is a bug: it runs as one, not task by task"),
197            });
198        }
199        return crate::bug::run_with(path, Some(&slug), None, state, provider, secret, options);
200    }
201    let first = run_task_once(
202        path,
203        feature,
204        task,
205        state,
206        Arc::clone(&provider),
207        secret,
208        options,
209    );
210    match first.data() {
211        Some(CommandData::Run(r)) if r.attempt_status == CHANGED_CODE => {
212            if let Some(p) = &options.progress {
213                p.event(&progress::Event::Notice {
214                    text: format!("{task} changed code, so it runs as code"),
215                });
216            }
217            run_task_once(path, feature, task, state, provider, secret, options)
218        }
219        _ => first,
220    }
221}
222
223/// The outcome of a planning attempt that changed something outside its
224/// unit: saved and undone, and the task is code from then on.
225pub const CHANGED_CODE: &str = "planning_changed_code";
226
227/// One task's run, phase by phase — each a file of `task/`: the task
228/// opened (`open`), the worktree made ready (`ready`), the tests written
229/// first (`tests`), the attempt (`attempt`), judged beyond its verdict
230/// (`judge`), ticked or saved (`tick`). Results are read-only to later
231/// phases; what one phase changes for another travels in [`Carried`].
232fn run_task_once(
233    path: &Path,
234    feature: Option<&str>,
235    task: &str,
236    state: &Path,
237    provider: std::sync::Arc<dyn agentplane::model::ModelProvider>,
238    secret: Option<&str>,
239    options: &RunOptions,
240) -> CommandResult {
241    // In place: the person's checkout, switched and switched back around the task.
242    if options.in_place && options.session.is_none() {
243        return in_session("run", path, feature, state, options, |o| {
244            run_task(path, feature, task, state, Arc::clone(&provider), secret, o)
245        });
246    }
247    let (opened, started) = ok!(open::task(path, feature, task, state, secret, options));
248    let (ready, mut carried) = ok!(ready::make(
249        &opened,
250        started,
251        task,
252        state,
253        secret,
254        options,
255        Arc::clone(&provider),
256    ));
257    let mut tests = ok!(tests::first(
258        &opened,
259        &ready,
260        &mut carried,
261        task,
262        state,
263        secret,
264        options,
265    ));
266    let attempted = ok!(attempt::run(
267        path,
268        &opened,
269        &ready,
270        &mut tests,
271        &mut carried,
272        task,
273        state,
274        secret,
275        options,
276    ));
277    let (attempted, judged) = judge::after(&opened, &ready, &tests, attempted, task, secret);
278    tick::finish(
279        path, feature, &opened, &ready, tests, attempted, carried, judged, task, state, secret,
280        options,
281    )
282}
283
284/// The code of a run the collection check decided: a file that never ran
285/// (`TESTS-NOT-COLLECTED`), or one speccoder cannot tell about.
286fn collection_code(
287    report: &speccoder_core::RunReport,
288    attempt_status: &str,
289) -> Option<&'static str> {
290    if attempt_status == "collection_unknown" {
291        return Some("TESTS-COLLECTION-UNKNOWN");
292    }
293    match &report.verdict {
294        Some(speccoder_core::verify::Verdict::Failed { reasons })
295            if reasons
296                .first()
297                .is_some_and(|r| r.starts_with(speccoder_core::collection::REASON_PREFIX)) =>
298        {
299            Some("TESTS-NOT-COLLECTED")
300        }
301        _ => None,
302    }
303}
304
305/// Judges the attempt's changed test files against what the run collected:
306/// a file no test ran from fails the verdict (its reason
307/// first); for an otherwise passing attempt, a file speccoder cannot tell
308/// about returns the stop's message. Listings run only then.
309/// What the collection check came to beyond the verdict's reasons.
310enum Collected {
311    /// A file speccoder cannot tell about: the stop's message.
312    Unknown(String),
313    /// A listing changed the worktree: the integrity finding.
314    Changed(String),
315}
316
317fn judge_collection(
318    dirs: (&Path, &Path, &Path),
319    runner: &sandbox::Runner,
320    otherwise_passing: bool,
321    report: &mut speccoder_core::RunReport,
322    live: &dyn progress::Progress,
323    task: &str,
324) -> Option<Collected> {
325    let (project, wt_root, tmp) = dirs;
326    // Listings run the project's code: the tree they leave must be the one judged.
327    let before = worktree::checkpoint(wt_root, tmp).ok();
328    let checks = std::fs::read_to_string(project.join(crate::verify::config::FILE))
329        .ok()
330        .and_then(|t| crate::verify::config::parse(&t).ok())
331        .unwrap_or_default()
332        .into_iter()
333        .filter(|c| c.tier == crate::verify::config::Tier::Fast)
334        .collect::<Vec<_>>();
335    let results = report
336        .verification
337        .as_ref()
338        .map(|v| v.checks.clone())
339        .unwrap_or_default();
340    let c = crate::collection::judge(&crate::collection::Input {
341        root: project,
342        changes: &report.changes,
343        checks: &checks,
344        results: &results,
345        runner,
346        listings: otherwise_passing,
347    })?;
348    if !c.listing.is_empty()
349        && let Some(before) = &before
350    {
351        let changed: Vec<String> = worktree::checkpoint(wt_root, tmp)
352            .and_then(|after| worktree::diff(wt_root, before, &after))
353            .map(|d| {
354                d.into_iter()
355                    .map(|c| c.path)
356                    .filter(|p| !speccoder_core::collection::is_build_or_dependency(p))
357                    .collect()
358            })
359            .unwrap_or_else(|e| vec![format!("(the tree could not be read: {})", e.0)]);
360        if !changed.is_empty() {
361            report.collection = Some(c);
362            return Some(Collected::Changed(format!(
363                "integrity: a test listing changed the worktree: {}",
364                changed.join(", ")
365            )));
366        }
367    }
368    live.event(&progress::Event::CollectionChecked {
369        task: task.to_owned(),
370        files: c
371            .files
372            .iter()
373            .map(|f| progress::CollectionFile {
374                path: f.path.clone(),
375                state: f.state,
376                decided_by: f.decided_by,
377            })
378            .collect(),
379    });
380    let never = c.reasons();
381    let unknown: Vec<String> = c
382        .unknown()
383        .map(|f| {
384            format!(
385                "speccoder cannot tell whether the runner ran `{}` ({})",
386                f.path,
387                f.why.as_deref().unwrap_or("no report or listing names it")
388            )
389        })
390        .collect();
391    report.collection = Some(c);
392    if !never.is_empty() {
393        let mut reasons = never;
394        if let Some(speccoder_core::verify::Verdict::Failed { reasons: more }) =
395            report.verdict.take()
396        {
397            reasons.extend(more);
398        }
399        report.verdict = Some(speccoder_core::verify::Verdict::Failed { reasons });
400        return None;
401    }
402    (otherwise_passing && !unknown.is_empty()).then(|| Collected::Unknown(unknown.join("; ")))
403}
404
405/// `note`, with what the check itself said last (its own reason) and, for
406/// the causes that are known, the fix.
407fn with_cause(note: &str, c: &speccoder_core::verify::CheckResult) -> String {
408    let said = c
409        .stderr_tail
410        .lines()
411        .chain(c.stdout_tail.lines())
412        .map(str::trim)
413        .find(|l| l.starts_with("error"))
414        .map(|l| l.chars().take(200).collect::<String>());
415    let fix = match said.as_deref() {
416        Some(l) if l.contains("profile `speccoder` not found") => Some(
417            "`.config/nextest.toml` is not committed — `git add .config/nextest.toml && git commit -m \"speccoder: nextest profile\"`",
418        ),
419        Some(l) if l.contains("no tests to run") => Some(
420            "the project has no tests yet; if the first task writes them, run with --allow-failing-baseline, or add `--no-tests=pass` to the check's argv",
421        ),
422        Some(l) if l.contains("must be present") || l.contains("no targets") => Some(
423            "the project has nothing to build yet; if the first task creates it, run with --allow-failing-baseline",
424        ),
425        _ => None,
426    };
427    match (said, fix) {
428        (Some(s), Some(f)) => format!("{note} ({s}); {f}"),
429        (Some(s), None) => format!("{note} ({s})"),
430        _ => note.to_owned(),
431    }
432}
433
434/// Why a failing baseline check is broken rather than failing tests: it
435/// could not start, or it failed without any test result to show for it.
436/// `None`: it passed, or its tests ran and some failed.
437/// What the sandbox denied it comes last: often the cause itself.
438#[must_use]
439pub fn broken(c: &speccoder_core::verify::CheckResult) -> Option<String> {
440    let why = broken_why(c)?;
441    Some(match c.sandbox.denied.first() {
442        Some(first) => {
443            let others = c.sandbox.denied.len() - 1 + c.sandbox.more;
444            let more = if others > 0 {
445                format!(" (and {others} more)")
446            } else {
447                String::new()
448            };
449            format!("{why} — the sandbox denied {first}{more}")
450        }
451        None => why,
452    })
453}
454
455fn broken_why(c: &speccoder_core::verify::CheckResult) -> Option<String> {
456    use speccoder_core::verify::CheckStatus;
457    if !c.status.is_failure() || c.status == CheckStatus::TimedOut {
458        return None;
459    }
460    if let Some(note) = &c.note {
461        return Some(with_cause(note, c));
462    }
463    if c.tests.as_ref().is_some_and(|t| !t.is_empty()) {
464        return None;
465    }
466    let summary = crate::verify::summary::parse(&c.stdout_tail, &c.stderr_tail, c.exit_code);
467    // Only what is unambiguous: a command that cannot start, a build that
468    // fails, or a test runner that ran no test. A script or `grep` that
469    // fails until the task is done is a failing check, not a broken one.
470    let runner = c
471        .argv
472        .first()
473        .map(|a| a.rsplit('/').next().unwrap_or(a))
474        .is_some_and(|a| {
475            matches!(
476                a,
477                "cargo"
478                    | "pytest"
479                    | "python"
480                    | "python3"
481                    | "uv"
482                    | "npm"
483                    | "npx"
484                    | "pnpm"
485                    | "yarn"
486                    | "bun"
487                    | "go"
488                    | "jest"
489                    | "vitest"
490                    | "mvn"
491                    | "gradle"
492                    | "dotnet"
493                    | "mix"
494                    | "swift"
495            )
496        });
497    let cannot_start = matches!(c.exit_code, Some(126 | 127));
498    let is_broken = match &summary {
499        _ if cannot_start => true,
500        Some(s) if s.build_failed => true,
501        Some(s) => s.passed + s.failed + s.errors == 0,
502        None => runner,
503    };
504    match is_broken {
505        false => None,
506        true => {
507            let first = c
508                .stderr_tail
509                .lines()
510                .chain(c.stdout_tail.lines())
511                .map(str::trim)
512                .find(|l| l.to_lowercase().contains("error"))
513                .or_else(|| c.stderr_tail.lines().map(str::trim).find(|l| !l.is_empty()))
514                .unwrap_or("it failed without running a test")
515                .chars()
516                .take(160)
517                .collect::<String>();
518            Some(first)
519        }
520    }
521}
522
523/// The task stops for the agent's sign-in: its own ways, a command one
524/// names as a step of the person's own (a terminal of theirs: it reads the
525/// keyboard). Nothing was attempted.
526fn login(
527    fail: impl FnOnce(CommandStatus, String) -> CommandResult,
528    shown: &str,
529    agent: &crate::acp::agent::Agent,
530    ways: &[crate::acp::session::SignIn],
531) -> CommandResult {
532    let words: Vec<String> = ways
533        .iter()
534        .filter(|w| w.command.is_none())
535        .map(|w| {
536            format!(
537                "→ {}",
538                w.description.clone().unwrap_or_else(|| w.name.clone())
539            )
540        })
541        .collect();
542    let mut commands: Vec<Vec<String>> = ways
543        .iter()
544        .filter_map(|w| w.command.as_deref())
545        .map(|c| c.split_whitespace().map(str::to_owned).collect())
546        .collect();
547    if words.is_empty()
548        && commands.is_empty()
549        && let Some(p) = agent.preset()
550    {
551        commands.push(p.login.split_whitespace().map(str::to_owned).collect());
552    }
553    commands.dedup();
554    let argvs: Vec<speccoder_core::step::Argvs> = commands.into_iter().map(|c| vec![c]).collect();
555    let mut fix: Vec<String> = argvs
556        .iter()
557        .map(|a| speccoder_core::step::render(a))
558        .collect();
559    fix.extend(words);
560    fix.push("speccoder doctor".to_owned());
561    fail(
562        CommandStatus::NeedsHuman,
563        format!("{shown} needs signing in before it can make the attempt; nothing was attempted"),
564    )
565    .with_code("EXECUTOR-LOGIN")
566    .with_fix(fix)
567    .with_commands(argvs)
568}
569
570/// The red class of a story task's turned scenarios, from the evidence
571/// the oracle gave it.
572fn story_red(report: &speccoder_core::RunReport) -> Option<speccoder_core::verify::RedClass> {
573    let a = report
574        .acceptance
575        .as_ref()
576        .filter(|a| a["oracle"].is_string())?;
577    serde_json::from_value::<speccoder_core::verify::RedClass>(a["red_class"].clone())
578        .ok()
579        .filter(|c| c.is_red())
580}
581
582/// The bundle the implementer is given: with the story's oracle, when the
583/// task is judged by one.
584fn with_oracle(bundle: &serde_json::Value, oracle: &serde_json::Value) -> serde_json::Value {
585    let mut b = bundle.clone();
586    if !oracle.is_null() {
587        b["oracle"] = oracle.clone();
588    }
589    b
590}
591
592/// The tick's record of a person's rulings on the task's tests:
593/// `Ruling: tests-wrong by <who> — <why>`.
594fn ruling_trailers(ruled: &[crate::acceptance_at::Ruling]) -> String {
595    ruled
596        .iter()
597        .map(|r| {
598            format!(
599                "Ruling: tests-wrong by {} — {}\n",
600                r.by,
601                r.reason.replace('\n', " ")
602            )
603        })
604        .collect()
605}
606
607/// The frozen test a `wrong_test` stop names (speccoder's own words:
608/// "frozen test `tests/x.py`").
609fn frozen_test_named(reason: &str) -> Option<String> {
610    Some(
611        reason
612            .split("frozen test `")
613            .nth(1)?
614            .split('`')
615            .next()?
616            .trim_start_matches("./")
617            .to_owned(),
618    )
619}