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 bug;
15pub mod commit;
16pub mod feature;
17pub mod full;
18pub mod judge;
19pub mod lanes;
20pub mod outcome;
21pub mod samples;
22pub mod story;
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 {
136 let text = crate::secrets::mask(text);
137 match secret {
138 Some(s) if !s.is_empty() => text.replace(s, "[redacted]"),
139 _ => text,
140 }
141}
142
143#[derive(
147 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
148)]
149#[serde(transparent)]
150pub struct RunId(pub String);
151
152impl RunId {
153 #[must_use]
155 pub fn fresh() -> Self {
156 use sha2::{Digest as _, Sha256};
157 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
158 let now = std::time::SystemTime::now()
159 .duration_since(std::time::UNIX_EPOCH)
160 .unwrap_or_default();
161 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
162 let digest = Sha256::digest(format!(
163 "{}/{}/{}/{n}",
164 now.as_nanos(),
165 std::process::id(),
166 std::thread::current().name().unwrap_or_default()
167 ));
168 let hex: String = digest.iter().take(4).map(|b| format!("{b:02x}")).collect();
169 Self(format!("run-{}-{hex}", now.as_secs()))
170 }
171
172 #[must_use]
174 pub fn as_str(&self) -> &str {
175 &self.0
176 }
177}
178
179impl Default for RunId {
180 fn default() -> Self {
181 Self::fresh()
182 }
183}
184
185impl std::fmt::Display for RunId {
186 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187 f.write_str(&self.0)
188 }
189}
190
191impl RunOptions {
192 #[must_use]
194 pub fn run(&self) -> RunId {
195 self.run_id
196 .lock()
197 .map(|r| r.clone())
198 .unwrap_or_else(|_| RunId(String::new()))
199 }
200
201 #[must_use]
203 pub fn asked_now(&self) -> u32 {
204 self.asked.lock().map(|a| *a).unwrap_or(0)
205 }
206}
207
208#[derive(Debug, Clone, Default)]
210pub struct RunOptions {
211 pub max_tasks: Option<usize>,
213 pub approver: Option<Arc<dyn approvals::Approver>>,
216 pub progress: Option<Arc<dyn progress::Progress>>,
218 pub parallel: usize,
220 pub lane: Option<String>,
222 pub cancel: Option<Arc<std::sync::atomic::AtomicBool>>,
225 pub ignore_checklists: bool,
228 pub fresh_acceptance: bool,
231 pub allow_failing_baseline: bool,
235 pub run_grants: Arc<std::sync::Mutex<Vec<crate::tools::policy::Object>>>,
238 pub run_id: Arc<std::sync::Mutex<RunId>>,
242 pub asked: Arc<std::sync::Mutex<u32>>,
244 pub in_place: bool,
247 pub session: Option<Arc<std::sync::Mutex<crate::in_place::Session>>>,
249 pub bug_home: Option<Arc<bug::NativeBug>>,
251 pub mode: speccoder_core::oracle::RunMode,
255 pub agent: Option<String>,
258}
259
260pub(crate) fn workspace(
263 path: &Path,
264 feature: Option<&str>,
265 state: &Path,
266 options: &RunOptions,
267) -> CommandResult {
268 let Some(session) = options
269 .session
270 .as_ref()
271 .and_then(|s| s.lock().ok().map(|s| s.clone()))
272 else {
273 if let Some(e) = crate::in_place::session_elsewhere(path, feature, state) {
274 return e.result("run");
275 }
276 return worktree_with(path, feature, state);
277 };
278 CommandResult::new("worktree", CommandStatus::Ok, "in place").with_data(CommandData::Worktree(
279 speccoder_core::WorktreeReport {
280 feature: session.feature.clone(),
281 path: Some(session.checkout.display().to_string()),
282 project_dir: Some(session.project.display().to_string()),
283 branch: Some(session.branch.clone()),
284 base: Some(session.tip.clone()),
285 created: false,
286 refused_paths: Vec::new(),
287 },
288 ))
289}
290
291pub(crate) fn in_session(
295 command: &str,
296 path: &Path,
297 feature: Option<&str>,
298 state: &Path,
299 options: &RunOptions,
300 f: impl FnOnce(&RunOptions) -> CommandResult,
301) -> CommandResult {
302 if !options.in_place || options.session.is_some() {
303 return f(options);
304 }
305 if options.parallel > 1 {
306 return crate::in_place::InPlaceError {
307 code: "IN-PLACE-PARALLEL",
308 message: "an in-place run has one checkout; it cannot run tasks in parallel".to_owned(),
309 paths: Vec::new(),
310 fix: vec!["speccoder run --in-place (without --parallel)".to_owned()],
311 commands: Vec::new(),
312 }
313 .result(command);
314 }
315 let opened = match crate::format::open(path, feature) {
316 Ok(o) => o,
317 Err(r) => return CommandResult::new(command, r.status, &r.message),
318 };
319 let Some(f_name) = opened
320 .snapshot
321 .feature
322 .as_ref()
323 .map(|f| f.feature.name.clone())
324 else {
325 return CommandResult::new(
326 command,
327 CommandStatus::SelectionNeeded,
328 "no feature selected; pass --feature",
329 );
330 };
331 let root = std::path::PathBuf::from(&opened.snapshot.root);
332 let plane_dir = worktree::project_state_dir(state, &root);
333 let policy = crate::tools::policy::Policy::new(&[], &[]).rules(opened.adapter.rules());
334 let mut session = match crate::in_place::Session::begin(&root, &plane_dir, &f_name, &policy) {
335 Ok(s) => s,
336 Err(e) => return e.result(command),
337 };
338 let format = crate::format::at(&root);
340 if let Some(tasks) = format
341 .inspect(&root, Some(&f_name))
342 .and_then(|snap| snap.feature.and_then(|f| f.tasks))
343 {
344 let file = session.project.join(&tasks.path);
345 session.reconcile(&plane_dir, &file, &tasks, |file, task, hash| {
346 format.tick(file, task, hash)
347 });
348 }
349 let original = session.original.describe();
350 if let Some(p) = &options.progress {
351 p.event(&progress::Event::Notice {
352 text: format!(
353 "in place: on {} in {}; returns to {original} at the end — do not use this checkout until then",
354 session.branch,
355 session.checkout.display()
356 ),
357 });
358 for note in &session.notes {
359 p.event(&progress::Event::Notice { text: note.clone() });
360 }
361 }
362 let shared = Arc::new(std::sync::Mutex::new(session));
363 let inner = RunOptions {
364 session: Some(Arc::clone(&shared)),
365 ..options.clone()
366 };
367 let res = f(&inner);
368 let session = shared.lock().map(|s| s.clone());
369 if let Some(task) = waiting_task(&res) {
372 let notes: String = session
373 .as_ref()
374 .map(|s| s.notes.iter().map(|n| format!("\n{n}")).collect())
375 .unwrap_or_default();
376 let message = format!(
377 "{}{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",
378 res.message(),
379 session
380 .as_ref()
381 .map(|s| s.branch.as_str())
382 .unwrap_or("the speccoder branch"),
383 );
384 let status = res.status();
385 return res.reworded(status, &message);
386 }
387 let (back, notes) = match session {
388 Ok(s) => (s.finish(&plane_dir), s.notes),
389 Err(_) => (Ok(()), Vec::new()),
390 };
391 let told: String = notes.iter().map(|n| format!("\n{n}")).collect();
392 match back {
393 Ok(()) => {
394 let message = format!("{} — back on {original}{told}", res.message());
395 let status = res.status();
396 res.reworded(status, &message)
397 }
398 Err(e) => {
399 let message = format!("{}{told}\n{}", res.message(), e.line());
400 res.reworded(CommandStatus::NeedsHuman, &message)
401 .with_code(e.code)
402 .with_fix(e.fix.clone())
403 }
404 }
405}
406
407fn waiting_task(res: &CommandResult) -> Option<String> {
409 let waits = |r: &speccoder_core::RunReport| {
410 r.pending
411 .as_ref()
412 .is_some_and(|p| p["waiting"] == true)
413 .then(|| r.task.clone())
414 };
415 match res.data() {
416 Some(CommandData::Run(r)) => waits(r),
417 Some(CommandData::Feature(f)) => f.attempts.last().and_then(waits),
418 _ => None,
419 }
420}
421
422pub(crate) fn checklist_gate(
426 project: &Path,
427 feature: Option<&str>,
428 ignore: bool,
429) -> Result<bool, Box<CommandResult>> {
430 let format = crate::format::at(project);
431 let Some(snap) = format.inspect(project, feature) else {
432 return Ok(false);
433 };
434 let Some(f) = snap.feature.as_ref() else {
435 return Ok(false);
436 };
437 let lists = format.checklists(Path::new(&snap.root), &f.feature.dir);
438 let open: Vec<String> = lists
439 .iter()
440 .filter(|c| c.open > 0)
441 .map(|c| format!("{} ({} of {} open)", c.file, c.open, c.total))
442 .collect();
443 if open.is_empty() {
444 return Ok(false);
445 }
446 if ignore {
447 return Ok(true);
448 }
449 Err(Box::new(
450 CommandResult::new(
451 "run",
452 CommandStatus::NeedsHuman,
453 &(format.messages().checklists)(&open.join(", ")),
454 )
455 .with_data(CommandData::Checklists(lists)),
456 ))
457}
458
459pub(crate) fn stage(
462 live: &dyn crate::progress::Progress,
463 task: &str,
464 stage: speccoder_core::stage::Stage,
465 state: speccoder_core::stage::StageState,
466 detail: Option<String>,
467 since: Option<std::time::Instant>,
468) {
469 stage_with_tail(live, task, stage, state, detail, since, Vec::new());
470}
471
472pub(crate) fn stage_with_tail(
474 live: &dyn crate::progress::Progress,
475 task: &str,
476 stage: speccoder_core::stage::Stage,
477 state: speccoder_core::stage::StageState,
478 detail: Option<String>,
479 since: Option<std::time::Instant>,
480 tail: Vec<String>,
481) {
482 live.event(&crate::progress::Event::Stage {
483 task: task.to_owned(),
484 stage,
485 state,
486 detail,
487 elapsed_ms: since.map(|t| u64::try_from(t.elapsed().as_millis()).unwrap_or(u64::MAX)),
488 tail,
489 });
490}
491
492pub(crate) fn failing_tail(report: &speccoder_core::verify::VerifyReport) -> Vec<String> {
494 report
495 .checks
496 .iter()
497 .find(|c| c.status.is_failure())
498 .map(|c| crate::progress::tail(&format!("{}\n{}", c.stdout_tail, c.stderr_tail)))
499 .unwrap_or_default()
500}