1use 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
35pub(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 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
78fn 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
132pub(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#[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 #[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 #[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 #[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 #[must_use]
200 pub fn asked_now(&self) -> u32 {
201 self.asked.lock().map(|a| *a).unwrap_or(0)
202 }
203}
204
205#[derive(Debug, Clone, Default)]
207pub struct RunOptions {
208 pub max_tasks: Option<usize>,
210 pub approver: Option<Arc<dyn approvals::Approver>>,
213 pub progress: Option<Arc<dyn progress::Progress>>,
215 pub parallel: usize,
217 pub lane: Option<String>,
219 pub cancel: Option<Arc<std::sync::atomic::AtomicBool>>,
222 pub ignore_checklists: bool,
225 pub fresh_acceptance: bool,
228 pub allow_failing_baseline: bool,
232 pub run_grants: Arc<std::sync::Mutex<Vec<crate::tools::policy::Object>>>,
235 pub run_id: Arc<std::sync::Mutex<RunId>>,
239 pub asked: Arc<std::sync::Mutex<u32>>,
241 pub in_place: bool,
244 pub session: Option<Arc<std::sync::Mutex<crate::in_place::Session>>>,
246 pub bug_home: Option<Arc<bug::NativeBug>>,
248 pub mode: speccoder_core::oracle::RunMode,
252}
253
254pub(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
285pub(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 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 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
400fn 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
415pub(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
452pub(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
465pub(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
485pub(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}