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    // Observers hear the task's tick or stop beside it (spec 095); inside a
191    // feature run, the feature's deliverer does.
192    let delivering = crate::hooks::deliver::Deliverer::start(path, state);
193    // An observer nobody trusted hears nothing: said once per run.
194    if delivering.is_some()
195        && let Some(p) = &options.progress
196        && let Some(text) = crate::hooks::report::untrusted_notice(path, state)
197    {
198        p.event(&progress::Event::Notice { text });
199    }
200    // A unit that is a bug runs as one bug, never task by task.
201    if options.bug_home.is_none()
202        && let Some(slug) = bug_spec(path, feature)
203    {
204        if let Some(p) = &options.progress {
205            p.event(&progress::Event::Notice {
206                text: format!("{slug} is a bug: it runs as one, not task by task"),
207            });
208        }
209        return crate::bug::run_with(path, Some(&slug), None, state, provider, secret, options);
210    }
211    let first = run_task_once(
212        path,
213        feature,
214        task,
215        state,
216        Arc::clone(&provider),
217        secret,
218        options,
219    );
220    match first.data() {
221        Some(CommandData::Run(r)) if r.attempt_status == CHANGED_CODE => {
222            if let Some(p) = &options.progress {
223                p.event(&progress::Event::Notice {
224                    text: format!("{task} changed code, so it runs as code"),
225                });
226            }
227            run_task_once(path, feature, task, state, provider, secret, options)
228        }
229        _ => first,
230    }
231}
232
233/// The outcome of a planning attempt that changed something outside its
234/// unit: saved and undone, and the task is code from then on.
235pub const CHANGED_CODE: &str = "planning_changed_code";
236
237/// One task's run, phase by phase — each a file of `task/`: the task
238/// opened (`open`), the worktree made ready (`ready`), the tests written
239/// first (`tests`), the attempt (`attempt`), judged beyond its verdict
240/// (`judge`), ticked or saved (`tick`). Results are read-only to later
241/// phases; what one phase changes for another travels in [`Carried`].
242fn run_task_once(
243    path: &Path,
244    feature: Option<&str>,
245    task: &str,
246    state: &Path,
247    provider: std::sync::Arc<dyn agentplane::model::ModelProvider>,
248    secret: Option<&str>,
249    options: &RunOptions,
250) -> CommandResult {
251    // In place: the person's checkout, switched and switched back around the task.
252    if options.in_place && options.session.is_none() {
253        return in_session("run", path, feature, state, options, |o| {
254            run_task(path, feature, task, state, Arc::clone(&provider), secret, o)
255        });
256    }
257    let (opened, started) = ok!(open::task(path, feature, task, state, secret, options));
258    let (ready, mut carried) = ok!(ready::make(
259        &opened,
260        started,
261        task,
262        state,
263        secret,
264        options,
265        Arc::clone(&provider),
266    ));
267    let mut tests = ok!(tests::first(
268        &opened,
269        &ready,
270        &mut carried,
271        task,
272        state,
273        secret,
274        options,
275    ));
276    let attempted = ok!(attempt::run(
277        path,
278        &opened,
279        &ready,
280        &mut tests,
281        &mut carried,
282        task,
283        state,
284        secret,
285        options,
286    ));
287    let (attempted, judged) = judge::after(&opened, &ready, &tests, attempted, task, secret);
288    tick::finish(
289        path, feature, &opened, &ready, tests, attempted, carried, judged, task, state, secret,
290        options,
291    )
292}
293
294/// The code of a run the collection check decided: a file that never ran
295/// (`TESTS-NOT-COLLECTED`), or one speccoder cannot tell about.
296fn collection_code(
297    report: &speccoder_core::RunReport,
298    attempt_status: &str,
299) -> Option<&'static str> {
300    if attempt_status == "collection_unknown" {
301        return Some("TESTS-COLLECTION-UNKNOWN");
302    }
303    match &report.verdict {
304        Some(speccoder_core::verify::Verdict::Failed { reasons })
305            if reasons
306                .first()
307                .is_some_and(|r| r.starts_with(speccoder_core::collection::REASON_PREFIX)) =>
308        {
309            Some("TESTS-NOT-COLLECTED")
310        }
311        _ => None,
312    }
313}
314
315/// Judges the attempt's changed test files against what the run collected:
316/// a file no test ran from fails the verdict (its reason
317/// first); for an otherwise passing attempt, a file speccoder cannot tell
318/// about returns the stop's message. Listings run only then.
319/// What the collection check came to beyond the verdict's reasons.
320enum Collected {
321    /// A file speccoder cannot tell about: the stop's message.
322    Unknown(String),
323    /// A listing changed the worktree: the integrity finding.
324    Changed(String),
325}
326
327fn judge_collection(
328    dirs: (&Path, &Path, &Path),
329    runner: &sandbox::Runner,
330    otherwise_passing: bool,
331    report: &mut speccoder_core::RunReport,
332    live: &dyn progress::Progress,
333    task: &str,
334) -> Option<Collected> {
335    let (project, wt_root, tmp) = dirs;
336    // Listings run the project's code: the tree they leave must be the one judged.
337    let before = worktree::checkpoint(wt_root, tmp).ok();
338    let checks = std::fs::read_to_string(project.join(crate::verify::config::FILE))
339        .ok()
340        .and_then(|t| crate::verify::config::parse(&t).ok())
341        .unwrap_or_default()
342        .into_iter()
343        .filter(|c| c.tier == crate::verify::config::Tier::Fast)
344        .collect::<Vec<_>>();
345    let results = report
346        .verification
347        .as_ref()
348        .map(|v| v.checks.clone())
349        .unwrap_or_default();
350    let c = crate::collection::judge(&crate::collection::Input {
351        root: project,
352        changes: &report.changes,
353        checks: &checks,
354        results: &results,
355        runner,
356        listings: otherwise_passing,
357    })?;
358    if !c.listing.is_empty()
359        && let Some(before) = &before
360    {
361        let changed: Vec<String> = worktree::checkpoint(wt_root, tmp)
362            .and_then(|after| worktree::diff(wt_root, before, &after))
363            .map(|d| {
364                d.into_iter()
365                    .map(|c| c.path)
366                    .filter(|p| !speccoder_core::collection::is_build_or_dependency(p))
367                    .collect()
368            })
369            .unwrap_or_else(|e| vec![format!("(the tree could not be read: {})", e.0)]);
370        if !changed.is_empty() {
371            report.collection = Some(c);
372            return Some(Collected::Changed(format!(
373                "integrity: a test listing changed the worktree: {}",
374                changed.join(", ")
375            )));
376        }
377    }
378    live.event(&progress::Event::CollectionChecked {
379        task: task.to_owned(),
380        files: c
381            .files
382            .iter()
383            .map(|f| progress::CollectionFile {
384                path: f.path.clone(),
385                state: f.state,
386                decided_by: f.decided_by,
387            })
388            .collect(),
389    });
390    let never = c.reasons();
391    let unknown: Vec<String> = c
392        .unknown()
393        .map(|f| {
394            format!(
395                "speccoder cannot tell whether the runner ran `{}` ({})",
396                f.path,
397                f.why.as_deref().unwrap_or("no report or listing names it")
398            )
399        })
400        .collect();
401    report.collection = Some(c);
402    if !never.is_empty() {
403        let mut reasons = never;
404        if let Some(speccoder_core::verify::Verdict::Failed { reasons: more }) =
405            report.verdict.take()
406        {
407            reasons.extend(more);
408        }
409        report.verdict = Some(speccoder_core::verify::Verdict::Failed { reasons });
410        return None;
411    }
412    (otherwise_passing && !unknown.is_empty()).then(|| Collected::Unknown(unknown.join("; ")))
413}
414
415/// `note`, with what the check itself said last (its own reason) and, for
416/// the causes that are known, the fix.
417fn with_cause(note: &str, c: &speccoder_core::verify::CheckResult) -> String {
418    let said = c
419        .stderr_tail
420        .lines()
421        .chain(c.stdout_tail.lines())
422        .map(str::trim)
423        .find(|l| l.starts_with("error"))
424        .map(|l| l.chars().take(200).collect::<String>());
425    let fix = match said.as_deref() {
426        Some(l) if l.contains("profile `speccoder` not found") => Some(
427            "`.config/nextest.toml` is not committed — `git add .config/nextest.toml && git commit -m \"speccoder: nextest profile\"`",
428        ),
429        Some(l) if l.contains("no tests to run") => Some(
430            "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",
431        ),
432        Some(l) if l.contains("must be present") || l.contains("no targets") => Some(
433            "the project has nothing to build yet; if the first task creates it, run with --allow-failing-baseline",
434        ),
435        _ => None,
436    };
437    match (said, fix) {
438        (Some(s), Some(f)) => format!("{note} ({s}); {f}"),
439        (Some(s), None) => format!("{note} ({s})"),
440        _ => note.to_owned(),
441    }
442}
443
444/// Why a failing baseline check is broken rather than failing tests: it
445/// could not start, or it failed without any test result to show for it.
446/// `None`: it passed, or its tests ran and some failed.
447/// What the sandbox denied it comes last: often the cause itself.
448#[must_use]
449pub fn broken(c: &speccoder_core::verify::CheckResult) -> Option<String> {
450    let why = broken_why(c)?;
451    Some(match c.sandbox.denied.first() {
452        Some(first) => {
453            let others = c.sandbox.denied.len() - 1 + c.sandbox.more;
454            let more = if others > 0 {
455                format!(" (and {others} more)")
456            } else {
457                String::new()
458            };
459            format!("{why} — the sandbox denied {first}{more}")
460        }
461        None => why,
462    })
463}
464
465fn broken_why(c: &speccoder_core::verify::CheckResult) -> Option<String> {
466    use speccoder_core::verify::CheckStatus;
467    if !c.status.is_failure() || c.status == CheckStatus::TimedOut {
468        return None;
469    }
470    if let Some(note) = &c.note {
471        return Some(with_cause(note, c));
472    }
473    if c.tests.as_ref().is_some_and(|t| !t.is_empty()) {
474        return None;
475    }
476    let summary = crate::verify::summary::parse(&c.stdout_tail, &c.stderr_tail, c.exit_code);
477    // Only what is unambiguous: a command that cannot start, a build that
478    // fails, or a test runner that ran no test. A script or `grep` that
479    // fails until the task is done is a failing check, not a broken one.
480    let runner = c
481        .argv
482        .first()
483        .map(|a| a.rsplit('/').next().unwrap_or(a))
484        .is_some_and(|a| {
485            matches!(
486                a,
487                "cargo"
488                    | "pytest"
489                    | "python"
490                    | "python3"
491                    | "uv"
492                    | "npm"
493                    | "npx"
494                    | "pnpm"
495                    | "yarn"
496                    | "bun"
497                    | "go"
498                    | "jest"
499                    | "vitest"
500                    | "mvn"
501                    | "gradle"
502                    | "dotnet"
503                    | "mix"
504                    | "swift"
505            )
506        });
507    let cannot_start = matches!(c.exit_code, Some(126 | 127));
508    let is_broken = match &summary {
509        _ if cannot_start => true,
510        Some(s) if s.build_failed => true,
511        Some(s) => s.passed + s.failed + s.errors == 0,
512        None => runner,
513    };
514    match is_broken {
515        false => None,
516        true => {
517            let first = c
518                .stderr_tail
519                .lines()
520                .chain(c.stdout_tail.lines())
521                .map(str::trim)
522                .find(|l| l.to_lowercase().contains("error"))
523                .or_else(|| c.stderr_tail.lines().map(str::trim).find(|l| !l.is_empty()))
524                .unwrap_or("it failed without running a test")
525                .chars()
526                .take(160)
527                .collect::<String>();
528            Some(first)
529        }
530    }
531}
532
533/// The task stops for the agent's sign-in: its own ways, a command one
534/// names as a step of the person's own (a terminal of theirs: it reads the
535/// keyboard). Nothing was attempted.
536fn login(
537    fail: impl FnOnce(CommandStatus, String) -> CommandResult,
538    shown: &str,
539    agent: &crate::acp::agent::Agent,
540    ways: &[crate::acp::session::SignIn],
541) -> CommandResult {
542    let words: Vec<String> = ways
543        .iter()
544        .filter(|w| w.command.is_none())
545        .map(|w| {
546            format!(
547                "→ {}",
548                w.description.clone().unwrap_or_else(|| w.name.clone())
549            )
550        })
551        .collect();
552    let mut commands: Vec<Vec<String>> = ways
553        .iter()
554        .filter_map(|w| w.command.as_deref())
555        .map(|c| c.split_whitespace().map(str::to_owned).collect())
556        .collect();
557    if words.is_empty()
558        && commands.is_empty()
559        && let Some(p) = agent.preset()
560    {
561        commands.push(p.login.split_whitespace().map(str::to_owned).collect());
562    }
563    commands.dedup();
564    let argvs: Vec<speccoder_core::step::Argvs> = commands.into_iter().map(|c| vec![c]).collect();
565    let mut fix: Vec<String> = argvs
566        .iter()
567        .map(|a| speccoder_core::step::render(a))
568        .collect();
569    fix.extend(words);
570    fix.push("speccoder doctor".to_owned());
571    fail(
572        CommandStatus::NeedsHuman,
573        format!("{shown} needs signing in before it can make the attempt; nothing was attempted"),
574    )
575    .with_code("EXECUTOR-LOGIN")
576    .with_fix(fix)
577    .with_commands(argvs)
578}
579
580/// The red class of a story task's turned scenarios, from the evidence
581/// the oracle gave it.
582fn story_red(report: &speccoder_core::RunReport) -> Option<speccoder_core::verify::RedClass> {
583    let a = report
584        .acceptance
585        .as_ref()
586        .filter(|a| a["oracle"].is_string())?;
587    serde_json::from_value::<speccoder_core::verify::RedClass>(a["red_class"].clone())
588        .ok()
589        .filter(|c| c.is_red())
590}
591
592/// The bundle the implementer is given: with the story's oracle, when the
593/// task is judged by one.
594fn with_oracle(bundle: &serde_json::Value, oracle: &serde_json::Value) -> serde_json::Value {
595    let mut b = bundle.clone();
596    if !oracle.is_null() {
597        b["oracle"] = oracle.clone();
598    }
599    b
600}
601
602/// The tick's record of a person's rulings on the task's tests:
603/// `Ruling: tests-wrong by <who> — <why>`.
604fn ruling_trailers(ruled: &[crate::acceptance_at::Ruling]) -> String {
605    ruled
606        .iter()
607        .map(|r| {
608            format!(
609                "Ruling: tests-wrong by {} — {}\n",
610                r.by,
611                r.reason.replace('\n', " ")
612            )
613        })
614        .collect()
615}
616
617/// The frozen test a `wrong_test` stop names (speccoder's own words:
618/// "frozen test `tests/x.py`").
619fn frozen_test_named(reason: &str) -> Option<String> {
620    Some(
621        reason
622            .split("frozen test `")
623            .nth(1)?
624            .split('`')
625            .next()?
626            .trim_start_matches("./")
627            .to_owned(),
628    )
629}