Skip to main content

speccoder_runtime/pipeline/
mod.rs

1//! The run pipeline: one task ([`task`]), a feature ([`feature`]), and the
2//! pieces they share.
3
4use std::path::Path;
5use std::sync::Arc;
6
7use speccoder_core::snapshot::{Diagnostic, ProjectSnapshot, Severity};
8use speccoder_core::{CommandData, CommandResult, CommandStatus};
9
10use crate::commands::*;
11use crate::{approvals, progress, substrate, verify, worktree};
12
13pub mod acceptance;
14pub mod bisect;
15pub mod bug;
16pub mod commit;
17pub mod feature;
18pub mod full;
19pub mod judge;
20pub mod lanes;
21pub mod outcome;
22pub mod samples;
23pub mod task;
24
25pub(crate) use acceptance::*;
26pub(crate) use bug::{reject as bug_reject, triad_now as bug_triad_now};
27pub(crate) use commit::*;
28pub use feature::*;
29pub(crate) use judge::*;
30pub(crate) use lanes::*;
31pub(crate) use outcome::*;
32pub(crate) use samples::*;
33pub use task::*;
34
35/// Where a project's run state lives, and its model configuration.
36pub(crate) struct Setup {
37    pub(crate) snapshot: Box<speccoder_core::snapshot::ProjectSnapshot>,
38    pub(crate) model: substrate::model_config::ModelConfig,
39    pub(crate) plane_dir: std::path::PathBuf,
40    /// The project's format.
41    pub(crate) format: &'static dyn crate::format::Adapter,
42}
43
44pub(crate) fn setup(
45    path: &Path,
46    feature: Option<&str>,
47    state: &Path,
48    command: &str,
49) -> Result<Setup, Box<CommandResult>> {
50    let inspected = inspect(path, feature);
51    let Some(CommandData::Inspect(snapshot)) = inspected.data() else {
52        return Err(Box::new(CommandResult::carried(command, &inspected)));
53    };
54    let snapshot = snapshot.clone();
55    preflight(&snapshot, command)?;
56    let config_error =
57        |m: String| Box::new(CommandResult::new(command, CommandStatus::ConfigError, &m));
58    let root = Path::new(&snapshot.root);
59    let config_dir = verify::find_config(root).ok_or_else(|| {
60        config_error(format!(
61            "no speccoder.toml at or above {}; add [model] provider = \"anthropic\", model = \"…\"",
62            root.display()
63        ))
64    })?;
65    let text = std::fs::read_to_string(config_dir.join(verify::config::FILE))
66        .map_err(|e| config_error(format!("speccoder.toml: {e}")))?;
67    let model = substrate::model_config::parse(&text)
68        .map_err(|e| config_error(format!("speccoder.toml: {e}")))?
69        .ok_or_else(|| config_error("speccoder.toml has no [model] section".to_owned()))?;
70    Ok(Setup {
71        format: crate::format::of(&snapshot),
72        plane_dir: worktree::project_state_dir(state, root),
73        snapshot,
74        model,
75    })
76}
77
78/// The format's preflight: errors of the selected unit (and, for `run`,
79/// what the format's own installed tools say) stop a run or proposal before
80/// any model call.
81fn preflight(snapshot: &ProjectSnapshot, command: &str) -> Result<(), Box<CommandResult>> {
82    if !matches!(command, "run" | "propose") {
83        return Ok(());
84    }
85    let format = crate::format::of(snapshot);
86    let mut extra = Vec::new();
87    if command == "run" {
88        match crate::sandbox::runner_at(Path::new(&snapshot.root)) {
89            Ok((runner, _)) => extra = format.crosscheck(snapshot, &runner),
90            Err(e) => extra.push(Diagnostic::new(
91                Severity::Info,
92                "crosscheck_skipped",
93                format!("cross-check skipped: {e}"),
94            )),
95        }
96    }
97    let problems = format.blocking(snapshot).len()
98        + extra
99            .iter()
100            .filter(|d| d.severity == Severity::Error)
101            .count();
102    if problems == 0 {
103        return Ok(());
104    }
105    let mut shown = snapshot.clone();
106    shown.diagnostics.extend(extra);
107    let name = shown
108        .feature
109        .as_ref()
110        .map(|f| f.feature.name.clone())
111        .unwrap_or_default();
112    Err(Box::new(
113        CommandResult::new(
114            command,
115            CommandStatus::DiagnosticsError,
116            &format!(
117                "{} {name} cannot run: {problems} problem(s)",
118                format.wording().unit
119            ),
120        )
121        .with_data(CommandData::Inspect(Box::new(shown))),
122    ))
123}
124
125pub(crate) fn tokio_runtime() -> Result<tokio::runtime::Runtime, String> {
126    tokio::runtime::Builder::new_current_thread()
127        .enable_all()
128        .build()
129        .map_err(|e| format!("cannot start the async runtime: {e}"))
130}
131
132/// Replaces every occurrence of `secret` (never shown, never journaled by speccoder).
133pub(crate) fn redact(text: &str, secret: Option<&str>) -> String {
134    match secret {
135        Some(s) if !s.is_empty() => text.replace(s, "[redacted]"),
136        _ => text.to_owned(),
137    }
138}
139
140/// One `speccoder run` from its fresh start to its end: `run-<unix
141/// secs>-<8 hex>`. Never one attempt's agentplane run (a retry is a new one
142/// of those, in the same run).
143#[derive(
144    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
145)]
146#[serde(transparent)]
147pub struct RunId(pub String);
148
149impl RunId {
150    /// A fresh id.
151    #[must_use]
152    pub fn fresh() -> Self {
153        use sha2::{Digest as _, Sha256};
154        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
155        let now = std::time::SystemTime::now()
156            .duration_since(std::time::UNIX_EPOCH)
157            .unwrap_or_default();
158        let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
159        let digest = Sha256::digest(format!(
160            "{}/{}/{}/{n}",
161            now.as_nanos(),
162            std::process::id(),
163            std::thread::current().name().unwrap_or_default()
164        ));
165        let hex: String = digest.iter().take(4).map(|b| format!("{b:02x}")).collect();
166        Self(format!("run-{}-{hex}", now.as_secs()))
167    }
168
169    /// Its text.
170    #[must_use]
171    pub fn as_str(&self) -> &str {
172        &self.0
173    }
174}
175
176impl Default for RunId {
177    fn default() -> Self {
178        Self::fresh()
179    }
180}
181
182impl std::fmt::Display for RunId {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        f.write_str(&self.0)
185    }
186}
187
188impl RunOptions {
189    /// The run's id now.
190    #[must_use]
191    pub fn run(&self) -> RunId {
192        self.run_id
193            .lock()
194            .map(|r| r.clone())
195            .unwrap_or_else(|_| RunId(String::new()))
196    }
197
198    /// The run's prompts so far.
199    #[must_use]
200    pub fn asked_now(&self) -> u32 {
201        self.asked.lock().map(|a| *a).unwrap_or(0)
202    }
203}
204
205/// How a run behaves beyond its configuration.
206#[derive(Debug, Clone, Default)]
207pub struct RunOptions {
208    /// At most this many tasks in a feature run.
209    pub max_tasks: Option<usize>,
210    /// Who to ask inline when a call needs approval; without one,
211    /// the attempt stops and `speccoder task approve` decides.
212    pub approver: Option<Arc<dyn approvals::Approver>>,
213    /// Where live progress goes: the CLI's printer.
214    pub progress: Option<Arc<dyn progress::Progress>>,
215    /// Ready `[P]` tasks run at once, each in its own worktree; 0 or 1: one at a time.
216    pub parallel: usize,
217    /// Run the task in this lane's worktree instead of the feature's.
218    pub lane: Option<String>,
219    /// Set by a person (an editor's cancel): a feature run stops
220    /// before its next task.
221    pub cancel: Option<Arc<std::sync::atomic::AtomicBool>>,
222    /// Run although the feature's checklists have unchecked items; the
223    /// override is recorded on every commit of the run.
224    pub ignore_checklists: bool,
225    /// Set a task's held or interrupted attempt aside and write its
226    /// acceptance tests anew (`run --task T --fresh-acceptance`).
227    pub fresh_acceptance: bool,
228    /// Attempt although a check cannot run on the untouched code
229    /// (`run --allow-failing-baseline`); otherwise the run stops before any
230    /// model call (`CHECK-BROKEN`).
231    pub allow_failing_baseline: bool,
232    /// Objects a person approved "for this run": shared by every task (and
233    /// lane) of one `speccoder run`, gone with it.
234    pub run_grants: Arc<std::sync::Mutex<Vec<crate::tools::policy::Object>>>,
235    /// The run: one per `speccoder run` from its fresh start; an
236    /// invocation that resumes a suspended attempt adopts that attempt's.
237    /// Grants, the asking count and the batch are keyed by it.
238    pub run_id: Arc<std::sync::Mutex<RunId>>,
239    /// Prompts the run has shown a person (`[approvals] budget` caps them).
240    pub asked: Arc<std::sync::Mutex<u32>>,
241    /// Run in the person's checkout on `speccoder/<feature>` instead of a
242    /// worktree (`run --in-place`).
243    pub in_place: bool,
244    /// The in-place session the runtime opened for this run.
245    pub session: Option<Arc<std::sync::Mutex<crate::in_place::Session>>>,
246    /// Run a bug of the format's own bug structure (no task list names it).
247    pub bug_home: Option<Arc<bug::NativeBug>>,
248    /// How the run asks for a person: `Ask` as today, or
249    /// `Autopilot` — nothing asks, a call that would is refused for the run
250    /// unless a grant in `run_grants` (the ones the person ticked) covers it.
251    pub mode: speccoder_core::oracle::RunMode,
252}
253
254/// Where a task runs, as `worktree` reports it: speccoder's worktree, or in
255/// place the person's checkout on `speccoder/<feature>`.
256pub(crate) fn workspace(
257    path: &Path,
258    feature: Option<&str>,
259    state: &Path,
260    options: &RunOptions,
261) -> CommandResult {
262    let Some(session) = options
263        .session
264        .as_ref()
265        .and_then(|s| s.lock().ok().map(|s| s.clone()))
266    else {
267        if let Some(e) = crate::in_place::session_elsewhere(path, feature, state) {
268            return e.result("run");
269        }
270        return worktree_with(path, feature, state);
271    };
272    CommandResult::new("worktree", CommandStatus::Ok, "in place").with_data(CommandData::Worktree(
273        speccoder_core::WorktreeReport {
274            feature: session.feature.clone(),
275            path: Some(session.checkout.display().to_string()),
276            project_dir: Some(session.project.display().to_string()),
277            branch: Some(session.branch.clone()),
278            base: Some(session.tip.clone()),
279            created: false,
280            refused_paths: Vec::new(),
281        },
282    ))
283}
284
285/// Runs `f` inside an in-place session when one is asked for and none is
286/// open yet: checks and switches the checkout first, switches it back after
287/// — on every way out.
288pub(crate) fn in_session(
289    command: &str,
290    path: &Path,
291    feature: Option<&str>,
292    state: &Path,
293    options: &RunOptions,
294    f: impl FnOnce(&RunOptions) -> CommandResult,
295) -> CommandResult {
296    if !options.in_place || options.session.is_some() {
297        return f(options);
298    }
299    if options.parallel > 1 {
300        return crate::in_place::InPlaceError {
301            code: "IN-PLACE-PARALLEL",
302            message: "an in-place run has one checkout; it cannot run tasks in parallel".to_owned(),
303            paths: Vec::new(),
304            fix: vec!["speccoder run --in-place   (without --parallel)".to_owned()],
305        }
306        .result(command);
307    }
308    let opened = match crate::format::open(path, feature) {
309        Ok(o) => o,
310        Err(r) => return CommandResult::new(command, r.status, &r.message),
311    };
312    let Some(f_name) = opened
313        .snapshot
314        .feature
315        .as_ref()
316        .map(|f| f.feature.name.clone())
317    else {
318        return CommandResult::new(
319            command,
320            CommandStatus::SelectionNeeded,
321            "no feature selected; pass --feature",
322        );
323    };
324    let root = std::path::PathBuf::from(&opened.snapshot.root);
325    let plane_dir = worktree::project_state_dir(state, &root);
326    let policy = crate::tools::policy::Policy::new(&[], &[]).rules(opened.adapter.rules());
327    let mut session = match crate::in_place::Session::begin(&root, &plane_dir, &f_name, &policy) {
328        Ok(s) => s,
329        Err(e) => return e.result(command),
330    };
331    // Ticks a killed run committed but did not write, read on the branch.
332    let format = crate::format::at(&root);
333    if let Some(tasks) = format
334        .inspect(&root, Some(&f_name))
335        .and_then(|snap| snap.feature.and_then(|f| f.tasks))
336    {
337        let file = session.project.join(&tasks.path);
338        session.reconcile(&plane_dir, &file, &tasks, |file, task, hash| {
339            format.tick(file, task, hash)
340        });
341    }
342    let original = session.original.describe();
343    if let Some(p) = &options.progress {
344        p.event(&progress::Event::Notice {
345            text: format!(
346                "in place: on {} in {}; returns to {original} at the end — do not use this checkout until then",
347                session.branch,
348                session.checkout.display()
349            ),
350        });
351        for note in &session.notes {
352            p.event(&progress::Event::Notice { text: note.clone() });
353        }
354    }
355    let shared = Arc::new(std::sync::Mutex::new(session));
356    let inner = RunOptions {
357        session: Some(Arc::clone(&shared)),
358        ..options.clone()
359    };
360    let res = f(&inner);
361    let session = shared.lock().map(|s| s.clone());
362    // An attempt waiting for a person keeps the checkout as it left it: the
363    // session stays, and the next `run --in-place` takes it over and resumes.
364    if let Some(task) = waiting_task(&res) {
365        let notes: String = session
366            .as_ref()
367            .map(|s| s.notes.iter().map(|n| format!("\n{n}")).collect())
368            .unwrap_or_default();
369        let message = format!(
370            "{}{notes}\nthe checkout stays on {} while {task} waits: decide it (`speccoder task approve {task}` or `reject`), then `speccoder run --in-place` continues it — or `speccoder run --in-place --return` gives the checkout back",
371            res.message(),
372            session
373                .as_ref()
374                .map(|s| s.branch.as_str())
375                .unwrap_or("the speccoder branch"),
376        );
377        let status = res.status();
378        return res.reworded(status, &message);
379    }
380    let (back, notes) = match session {
381        Ok(s) => (s.finish(&plane_dir), s.notes),
382        Err(_) => (Ok(()), Vec::new()),
383    };
384    let told: String = notes.iter().map(|n| format!("\n{n}")).collect();
385    match back {
386        Ok(()) => {
387            let message = format!("{} — back on {original}{told}", res.message());
388            let status = res.status();
389            res.reworded(status, &message)
390        }
391        Err(e) => {
392            let message = format!("{}{told}\n{}", res.message(), e.line());
393            res.reworded(CommandStatus::NeedsHuman, &message)
394                .with_code(e.code)
395                .with_fix(e.fix.clone())
396        }
397    }
398}
399
400/// The task whose attempt the result left waiting for a person, if any.
401fn waiting_task(res: &CommandResult) -> Option<String> {
402    let waits = |r: &speccoder_core::RunReport| {
403        r.pending
404            .as_ref()
405            .is_some_and(|p| p["waiting"] == true)
406            .then(|| r.task.clone())
407    };
408    match res.data() {
409        Some(CommandData::Run(r)) => waits(r),
410        Some(CommandData::Feature(f)) => f.attempts.last().and_then(waits),
411        _ => None,
412    }
413}
414
415/// The format's checklist gate: an unchecked item in the feature's
416/// checklists stops a run before any model call, unless a person
417/// overrides it (`run --ignore-checklists`). `Ok(true)`: overridden.
418pub(crate) fn checklist_gate(
419    project: &Path,
420    feature: Option<&str>,
421    ignore: bool,
422) -> Result<bool, Box<CommandResult>> {
423    let format = crate::format::at(project);
424    let Some(snap) = format.inspect(project, feature) else {
425        return Ok(false);
426    };
427    let Some(f) = snap.feature.as_ref() else {
428        return Ok(false);
429    };
430    let lists = format.checklists(Path::new(&snap.root), &f.feature.dir);
431    let open: Vec<String> = lists
432        .iter()
433        .filter(|c| c.open > 0)
434        .map(|c| format!("{} ({} of {} open)", c.file, c.open, c.total))
435        .collect();
436    if open.is_empty() {
437        return Ok(false);
438    }
439    if ignore {
440        return Ok(true);
441    }
442    Err(Box::new(
443        CommandResult::new(
444            "run",
445            CommandStatus::NeedsHuman,
446            &(format.messages().checklists)(&open.join(", ")),
447        )
448        .with_data(CommandData::Checklists(lists)),
449    ))
450}
451
452/// One stage event of `task`; `since` (when the stage began) gives an ended
453/// stage its duration.
454pub(crate) fn stage(
455    live: &dyn crate::progress::Progress,
456    task: &str,
457    stage: speccoder_core::stage::Stage,
458    state: speccoder_core::stage::StageState,
459    detail: Option<String>,
460    since: Option<std::time::Instant>,
461) {
462    stage_with_tail(live, task, stage, state, detail, since, Vec::new());
463}
464
465/// [`stage`] with the last lines of what failed.
466pub(crate) fn stage_with_tail(
467    live: &dyn crate::progress::Progress,
468    task: &str,
469    stage: speccoder_core::stage::Stage,
470    state: speccoder_core::stage::StageState,
471    detail: Option<String>,
472    since: Option<std::time::Instant>,
473    tail: Vec<String>,
474) {
475    live.event(&crate::progress::Event::Stage {
476        task: task.to_owned(),
477        stage,
478        state,
479        detail,
480        elapsed_ms: since.map(|t| u64::try_from(t.elapsed().as_millis()).unwrap_or(u64::MAX)),
481        tail,
482    });
483}
484
485/// The tail of the first failing check of `report`, for a failed stage.
486pub(crate) fn failing_tail(report: &speccoder_core::verify::VerifyReport) -> Vec<String> {
487    report
488        .checks
489        .iter()
490        .find(|c| c.status.is_failure())
491        .map(|c| crate::progress::tail(&format!("{}\n{}", c.stdout_tail, c.stderr_tail)))
492        .unwrap_or_default()
493}