1use std::path::Path;
4use std::sync::Arc;
5
6use speccoder_core::stage::{Stage, StageState};
7use speccoder_core::{CommandData, CommandResult, CommandStatus};
8
9use crate::pipeline::*;
10use crate::{
11 approvals, attempts, external, git, integrity, mcp, mutation, progress, resume, sandbox,
12 substrate, tools, verify, worktree,
13};
14
15#[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
41pub 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#[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#[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#[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
111pub(crate) fn run_task(
115 path: &Path,
116 feature: Option<&str>,
117 task: &str,
118 state: &Path,
119 provider: std::sync::Arc<dyn agentplane::model::ModelProvider>,
120 secret: Option<&str>,
121 options: &RunOptions,
122) -> CommandResult {
123 let first = run_task_once(
124 path,
125 feature,
126 task,
127 state,
128 Arc::clone(&provider),
129 secret,
130 options,
131 );
132 match first.data() {
133 Some(CommandData::Run(r)) if r.attempt_status == CHANGED_CODE => {
134 if let Some(p) = &options.progress {
135 p.event(&progress::Event::Notice {
136 text: format!("{task} changed code, so it runs as code"),
137 });
138 }
139 run_task_once(path, feature, task, state, provider, secret, options)
140 }
141 _ => first,
142 }
143}
144
145pub const CHANGED_CODE: &str = "planning_changed_code";
148
149#[allow(clippy::too_many_lines)] fn run_task_once(
151 path: &Path,
152 feature: Option<&str>,
153 task: &str,
154 state: &Path,
155 provider: std::sync::Arc<dyn agentplane::model::ModelProvider>,
156 secret: Option<&str>,
157 options: &RunOptions,
158) -> CommandResult {
159 use speccoder_core::RunReport;
160 if options.in_place && options.session.is_none() {
162 return in_session("run", path, feature, state, options, |o| {
163 run_task(path, feature, task, state, Arc::clone(&provider), secret, o)
164 });
165 }
166 let approver = options.approver.clone();
167 use speccoder_core::snapshot::TaskState;
168
169 let refuse =
170 |status: CommandStatus, m: String| CommandResult::new("run", status, &redact(&m, secret));
171
172 let s = match setup(path, feature, state, "run") {
174 Ok(s) => s,
175 Err(r) => return *r,
176 };
177 let native = options.bug_home.clone();
179 let feature_name = match (&native, s.snapshot.feature.as_ref()) {
180 (Some(n), _) => n.unit.clone(),
181 (None, Some(f)) => f.feature.name.clone(),
182 (None, None) => {
183 return refuse(
184 CommandStatus::SelectionNeeded,
185 "no feature selected; pass --feature".to_owned(),
186 );
187 }
188 };
189 let plane_dir = match &options.lane {
192 Some(lane) => s.plane_dir.join("lanes").join(lane),
193 None => s.plane_dir.clone(),
194 };
195 let live: Arc<dyn progress::Progress> = Arc::new(progress::Live::new(
197 &plane_dir,
198 s.model.prices,
199 options.progress.clone(),
200 ));
201
202 let wt = match &native {
204 Some(n) => crate::commands::worktree_of(&s.snapshot, &n.unit, &n.dir, state),
205 None => workspace(path, Some(&feature_name), state, options),
206 };
207 let Some(CommandData::Worktree(w)) = wt.data() else {
208 return CommandResult::carried("run", &wt);
209 };
210 if wt.status() != CommandStatus::Ok {
211 return CommandResult::carried("run", &wt).with_data(CommandData::Worktree(w.clone()));
212 }
213 let (Some(wt_path), Some(project_dir)) = (w.path.clone(), w.project_dir.clone()) else {
214 return refuse(CommandStatus::Error, "worktree without a path".to_owned());
215 };
216 let (wt_path, project_dir) = match &options.lane {
217 None => (wt_path, project_dir),
218 Some(lane) => match lane_worktree(path, state, &feature_name, lane, &wt_path, &project_dir)
219 {
220 Ok(paths) => paths,
221 Err(e) => return refuse(CommandStatus::GitPrecondition, e),
222 },
223 };
224 let project = std::path::PathBuf::from(&project_dir);
225 let wt_root = std::path::PathBuf::from(&wt_path);
226 super::bisect::prune(&wt_root, &s.plane_dir.join("tmp"));
228 let tmp = plane_dir.join("tmp");
229
230 let elsewhere = if options.lane.is_none() {
236 match crate::approvals::waiting_elsewhere(&project, &plane_dir, &feature_name, task) {
237 Ok(e) => e,
238 Err(e) => {
239 return refuse(
240 CommandStatus::Error,
241 format!(
242 "the calls waiting for a person could not be read, so whether another task's attempt holds the worktree is unknown: {e}"
243 ),
244 );
245 }
246 }
247 } else {
248 crate::approvals::Elsewhere::default()
249 };
250 if let Some((other, covers)) = elsewhere.waiting {
251 return refuse(
252 CommandStatus::NeedsHuman,
253 format!(
254 "{other} waits for a person ({covers}) and its attempt holds the worktree: decide it (`speccoder task approve {other}` or `reject`), then `speccoder run --task {other}`"
255 ),
256 );
257 }
258 if options.lane.is_none()
260 && let Some(other) = crate::strength::held_elsewhere(&plane_dir, &feature_name, task)
261 {
262 return refuse(
263 CommandStatus::NeedsHuman,
264 format!(
265 "{other}'s acceptance tests reject an implementation the spec appears to allow, and its attempt holds the worktree: `speccoder task rule {other} --tests-right --reason …` or `speccoder run --task {other} --fresh-acceptance`"
266 ),
267 )
268 .with_code("TESTS-OVER-STRICT");
269 }
270 let commits_per_task = verify::find_config(&project)
274 .and_then(|root| std::fs::read_to_string(root.join(verify::config::FILE)).ok())
275 .and_then(|t| substrate::run_config::parse(&t).ok())
276 .is_none_or(|c| c.commit_per_task);
277 let marker_path = resume::path(&plane_dir, &feature_name, task);
280 if options.fresh_acceptance && options.lane.is_none() {
283 let _ = std::fs::remove_file(&marker_path);
284 crate::strength::release(&crate::strength::dir(&s.plane_dir, &feature_name, task));
285 }
286 let head_now = git::Git::at(&wt_root)
287 .line(&["rev-parse", "HEAD"])
288 .unwrap_or_default();
289 let autopilot = options.mode == speccoder_core::oracle::RunMode::Autopilot;
294 let interrupted = resume::load(&marker_path).filter(|m| {
295 m.head == head_now && options.lane.is_none() && !head_now.is_empty() && !autopilot
296 });
297 if let Some(m) = &interrupted {
300 if let (Some(id), Ok(mut run)) = (&m.run_id, options.run_id.lock()) {
301 *run = crate::pipeline::RunId(id.clone());
302 }
303 if let Ok(mut asked) = options.asked.lock() {
304 *asked = (*asked).max(m.asked);
305 }
306 if let Ok(mut g) = options.run_grants.lock() {
307 for o in &m.run_grants {
308 if !g.contains(o) {
309 g.push(o.clone());
310 }
311 }
312 }
313 }
314 let marker_guard = resume::Guard::new(marker_path.clone());
315 let resumed_from = interrupted.as_ref().map(|_| {
318 std::fs::read_to_string(plane_dir.join(progress::FILE))
319 .ok()
320 .and_then(|t| serde_json::from_str::<progress::LiveState>(&t).ok())
321 .filter(|l| l.task == task)
322 .map_or((None, None), |l| (l.stage, l.last_call))
323 });
324 let mut set_aside = None;
325 if interrupted.is_none()
327 && commits_per_task
328 && options.session.is_none()
329 && worktree::require_clean(&wt_root).is_err()
330 {
331 let left = worktree::leftovers(&wt_root);
335 if !left.is_empty() {
336 let mut what = Vec::new();
337 if !left.commit.is_empty() {
338 what.push(format!("{} is not committed", left.commit.join(", ")));
339 }
340 if !left.ignore.is_empty() {
341 what.push(format!("{} is not git-ignored", left.ignore.join(", ")));
342 }
343 let checkout = std::path::Path::new(&s.snapshot.root);
344 let remedy = crate::code::setup_remedy(checkout, Some(&feature_name));
345 let command = remedy
346 .as_ref()
347 .map_or_else(|| left.fix(checkout, &wt_root, &[]), |r| r.command.clone());
348 return refuse(
349 CommandStatus::GitPrecondition,
350 format!(
351 "{} — the checks write it on every run, so each run would find it in the worktree and set it aside",
352 what.join(" and "),
353 ),
354 )
355 .with_code("SETUP-INCOMPLETE")
356 .with_fix(vec!["speccoder fix".to_owned(), command])
357 .with_remedy(remedy);
358 }
359 match set_aside_leftovers(&wt_root, &tmp, &feature_name, task) {
360 Ok(reference) => set_aside = Some(reference),
361 Err(e) => return refuse(CommandStatus::GitPrecondition, e),
362 }
363 }
364
365 let format = crate::format::at(&project);
367 let Some(snap) = format.inspect(
368 &project,
369 if native.is_some() {
370 None
371 } else {
372 Some(&feature_name)
373 },
374 ) else {
375 return refuse(
376 CommandStatus::NotAProject,
377 format.messages().no_project_in_worktree.to_owned(),
378 );
379 };
380 if native.is_some()
381 && crate::bug::state::load(&s.plane_dir, &feature_name, task)
382 .is_some_and(|b| b.outcome == speccoder_core::bug::Outcome::Fixed)
383 {
384 return refuse(
385 CommandStatus::TaskNotReady,
386 format!("{task} is already fixed"),
387 )
388 .with_code("TASK-DONE");
389 }
390 if native.is_none() {
393 let Some(st) = snap
394 .feature
395 .as_ref()
396 .and_then(|f| f.schedule.as_ref())
397 .and_then(|sch| sch.tasks.iter().find(|t| t.id == task))
398 else {
399 return refuse(
400 CommandStatus::NotFound,
401 format!("no task {task} in {feature_name}"),
402 );
403 };
404 match st.state {
405 TaskState::Done => {
406 return refuse(
407 CommandStatus::TaskNotReady,
408 format!("{task} is already done"),
409 )
410 .with_code("TASK-DONE");
411 }
412 TaskState::Blocked => {
413 return refuse(
414 CommandStatus::TaskNotReady,
415 format!("{task} is blocked by {}", st.blocked_by.join(", ")),
416 )
417 .with_code("TASK-BLOCKED");
418 }
419 TaskState::Ready => {}
420 }
421 }
422 let checklists_overridden = if native.is_some() {
425 false
426 } else {
427 match checklist_gate(&project, Some(&feature_name), options.ignore_checklists) {
428 Ok(overridden) => overridden,
429 Err(stop) => return *stop,
430 }
431 };
432 let parsed_task = snap
433 .feature
434 .as_ref()
435 .and_then(|f| f.tasks.as_ref())
436 .and_then(|t| t.tasks.iter().find(|t| t.id == task).cloned());
437 let tasks_file = snap
438 .feature
439 .as_ref()
440 .and_then(|f| f.tasks.as_ref())
441 .map(|t| project.join(&t.path));
442
443 let bundle = match native
444 .as_ref()
445 .map(|n| n.bundle(&project))
446 .map_or_else(|| format.bundle(&snap, task), Ok)
447 {
448 Ok(b) => b,
449 Err(_) => {
450 return refuse(
451 CommandStatus::NotFound,
452 format!("no task {task} in the worktree's {feature_name}"),
453 );
454 }
455 };
456 let acceptance_story = native
459 .is_none()
460 .then(|| crate::acceptance_at::story_at(&s.plane_dir, &feature_name, task))
461 .flatten();
462 let story_task: Option<String> = acceptance_story.as_ref().and_then(|st| {
463 snap.feature
464 .as_ref()
465 .and_then(|f| f.tasks.as_ref())
466 .and_then(|t| {
467 t.tasks
468 .iter()
469 .find(|t| t.story.as_deref() == Some(st.as_str()))
470 })
471 .map(|t| t.id.clone())
472 });
473 let bundle = match (&acceptance_story, &story_task) {
474 (Some(st), Some(other)) => {
475 let mut b = bundle;
476 if let Ok(of) = format.bundle(&snap, other) {
477 b.story = of.story;
478 }
479 b.task.story.clone_from(st);
480 b
481 }
482 _ => bundle,
483 };
484 let Some(config_root) = verify::find_config(&project) else {
485 return refuse(
486 CommandStatus::ConfigError,
487 "the worktree has no speccoder.toml (is it committed?)".to_owned(),
488 )
489 .with_code("CONFIG-MISSING");
490 };
491 let config_text =
492 std::fs::read_to_string(config_root.join(verify::config::FILE)).unwrap_or_default();
493 let run_config = match substrate::run_config::parse(&config_text) {
494 Ok(c) => c,
495 Err(e) => {
496 return refuse(CommandStatus::ConfigError, format!("speccoder.toml: {e}"))
497 .with_code("CONFIG-INVALID");
498 }
499 };
500 if run_config.review_required
503 && let Some(f) = snap.feature.as_ref()
504 && let Some(t) = crate::review::totals_of(&project, format, &feature_name, &f.feature.dir)
505 && !t.complete()
506 {
507 return refuse(
508 CommandStatus::NeedsHuman,
509 format!(
510 "{feature_name}'s spec is not approved yet ({} approved; {} to review, {} with changes requested, {} changed since, {} open question(s); committed review only) and [review] required is on",
511 t.approved, t.open, t.changes_requested, t.lapsed, t.questions
512 ),
513 )
514 .with_code("REVIEW-PENDING");
515 }
516 if run_config.review_required {
519 let ambiguous = match crate::oracle::open_ambiguities(
520 &s.plane_dir,
521 &feature_name,
522 &format.oracle_requirements(&snap),
523 ) {
524 Ok(a) => a,
525 Err(t) => {
526 return refuse(
527 CommandStatus::NeedsHuman,
528 format!(
529 "{}: whether it is read two ways is unknown and [review] required is on",
530 t.0
531 ),
532 )
533 .with_code("ORACLE-TAMPERED");
534 }
535 };
536 if let Some((req, scenario)) = ambiguous.first() {
537 return refuse(
538 CommandStatus::NeedsHuman,
539 format!(
540 "{req} is read two ways ({scenario}) and [review] required is on: choose a reading or reword it first"
541 ),
542 )
543 .with_code("REVIEW-AMBIGUOUS")
544 .with_fix(vec![
545 format!("speccoder review tests {req} --reading A {scenario}"),
546 format!("speccoder review tests {req} --reading B {scenario}"),
547 ]);
548 }
549 }
550 let executor = match external::parse(&config_text) {
551 Ok(e) => e,
552 Err(e) => {
553 return refuse(CommandStatus::ConfigError, format!("speccoder.toml: {e}"))
554 .with_code("CONFIG-INVALID");
555 }
556 };
557 let executor = match options.agent.as_deref() {
559 None => executor,
560 Some("native") => None,
561 Some(id) => match external::for_agent(id, executor.as_ref()) {
562 Ok(e) => Some(e),
563 Err(e) => return refuse(CommandStatus::UsageError, e),
564 },
565 };
566 let sandbox_config = match sandbox::parse(&config_text) {
568 Ok(c) => c,
569 Err(e) => {
570 return refuse(CommandStatus::ConfigError, format!("speccoder.toml: {e}"))
571 .with_code("CONFIG-INVALID");
572 }
573 };
574 let (runner, sandbox_notice) = match sandbox::runner(&wt_root, &sandbox_config) {
575 Ok(r) => r,
576 Err(e) => return refuse(CommandStatus::ConfigError, e),
577 };
578 if options.mode == speccoder_core::oracle::RunMode::Autopilot && !runner.is_sandboxed() {
580 return refuse(
581 CommandStatus::ConfigError,
582 "autopilot needs the OS sandbox, and commands here would run unsandboxed".to_owned(),
583 )
584 .with_code("SANDBOX-UNAVAILABLE");
585 }
586 let mutation_config = match mutation::parse(&config_text) {
587 Ok(c) => c,
588 Err(e) => {
589 return refuse(CommandStatus::ConfigError, format!("speccoder.toml: {e}"))
590 .with_code("CONFIG-INVALID");
591 }
592 };
593 let worktree_config = match crate::prepare::parse(&config_text) {
594 Ok(c) => c,
595 Err(e) => {
596 return refuse(CommandStatus::ConfigError, format!("speccoder.toml: {e}"))
597 .with_code("CONFIG-INVALID");
598 }
599 };
600 let check_argvs = verify::check_argvs(&config_root);
601 let unit_dir = snap
605 .feature
606 .as_ref()
607 .map(|f| f.feature.dir.clone())
608 .unwrap_or_default();
609 let changed_code = crate::attempts::list(&wt_root, &feature_name)
610 .iter()
611 .any(|a| a.task == task && a.outcome == CHANGED_CODE);
612 let planning: Option<String> = parsed_task
613 .as_ref()
614 .filter(|t| {
615 native.is_none()
616 && !changed_code
617 && speccoder_core::lane::by_paths(&t.title, &unit_dir, &format.rules().judged)
618 == speccoder_core::lane::Lane::Planning
619 })
620 .map(|_| {
621 let prefix = project
622 .strip_prefix(&wt_root)
623 .map(|p| p.to_string_lossy().replace('\\', "/"))
624 .unwrap_or_default();
625 if prefix.is_empty() {
626 unit_dir.trim_end_matches('/').to_owned()
627 } else {
628 format!("{prefix}/{}", unit_dir.trim_end_matches('/'))
629 }
630 });
631 let policy = tools::policy::Policy::new(&check_argvs, &run_config.allow)
632 .with_prefixes(run_config.allow_prefix.clone())
633 .rules(format.rules());
634 let policy = match &planning {
635 Some(dir) => policy.planning(dir),
636 None => policy,
637 };
638 let (policy, runner, carve_notice) = match options.session.as_ref().and_then(|s| s.lock().ok())
641 {
642 Some(s) => s.confine(policy, runner),
643 None => (policy, runner, None),
644 };
645 let sandbox_notice = sandbox_notice.or(carve_notice);
646 if let Some(e) = options.session.as_ref().and_then(|s| {
649 s.lock().ok().and_then(|s| {
650 if interrupted.is_some() {
652 s.check_before_tick(&policy).err()
653 } else {
654 s.check(&policy).err()
655 }
656 })
657 }) {
658 return e.result("run");
659 }
660
661 let wt_root_canonical = std::fs::canonicalize(&wt_root)
662 .unwrap_or_else(|_| wt_root.clone())
663 .display()
664 .to_string();
665
666 let this_run = options.run();
669 let (decisions, task_grants) = match approvals::Decisions::load(&s.plane_dir) {
670 Ok(mut d) => {
671 if !autopilot
674 && d.claim(&feature_name, task, this_run.as_str())
675 && let Err(e) = d.save(&s.plane_dir)
676 {
677 return refuse(CommandStatus::Error, e);
678 }
679 (
680 d.for_task(&feature_name, task),
681 if autopilot {
682 Vec::new()
683 } else {
684 d.for_run(&feature_name, task, this_run.as_str())
685 },
686 )
687 }
688 Err(e) => return refuse(CommandStatus::ConfigError, e),
689 };
690
691 if let Some((stage, last_call)) = &resumed_from {
692 live.event(&progress::Event::Resumed {
693 task: task.to_owned(),
694 stage: *stage,
695 last_call: last_call.clone(),
696 });
697 }
698 live.event(&progress::Event::TaskStarted {
699 feature: feature_name.clone(),
700 task: task.to_owned(),
701 title: parsed_task
702 .as_ref()
703 .map(|t| t.title.clone())
704 .unwrap_or_default(),
705 });
706 if planning.is_some()
707 && let Some(t) = &parsed_task
708 {
709 live.event(&progress::Event::Notice {
710 text: format!(
711 "📐 planning · writes {}",
712 speccoder_core::lane::task_paths(&t.title, &unit_dir).join(", ")
713 ),
714 });
715 }
716 let fail = |status: CommandStatus, m: String| {
718 live.event(&progress::Event::TaskFinished {
719 task: task.to_owned(),
720 outcome: "error".to_owned(),
721 message: redact(&m, secret),
722 run: None,
723 input_tokens: 0,
724 output_tokens: 0,
725 cache_read_tokens: 0,
726 cache_write_tokens: 0,
727 usd: None,
728 regression: None,
729 });
730 refuse(status, m)
731 };
732 let mut prepare_notes: Vec<String> = Vec::new();
736 let mut copied_files: Vec<String> = Vec::new();
739 if options.session.is_none() {
740 match crate::include::copy(
741 &wt_root,
742 &project,
743 Path::new(&s.snapshot.root),
744 &worktree_config.include,
745 ) {
746 Ok(c) => {
747 copied_files.clone_from(&c.files);
748 if !c.now.is_empty() {
749 prepare_notes.push(format!(
750 "copied from your checkout ([worktree] include): {}",
751 c.now.join(", ")
752 ));
753 }
754 prepare_notes.extend(
755 c.skipped
756 .iter()
757 .map(|n| format!("not copied ([worktree] include): {n}")),
758 );
759 for n in &prepare_notes {
760 live.event(&progress::Event::Notice { text: n.clone() });
761 }
762 }
763 Err(e) => {
764 return fail(
765 CommandStatus::ConfigError,
766 format!("the files [worktree] include names could not be copied: {e}"),
767 )
768 .with_code("PREPARE-FAILED");
769 }
770 }
771 }
772 let prepares =
773 options.session.is_none() && worktree_config.prepare && crate::prepare::needed(&project);
774 if prepares {
775 let began = std::time::Instant::now();
776 stage(
777 &*live,
778 task,
779 Stage::Prepare,
780 StageState::Started,
781 None,
782 None,
783 );
784 let prepared = crate::prepare::prepare(&crate::prepare::Prepare {
785 worktree: &wt_root,
786 project: &project,
787 config: &worktree_config,
788 runner: &runner,
789 state: Some(state),
790 });
791 match prepared {
792 Ok(None) => {}
793 Ok(Some(p)) => {
794 stage(
795 &*live,
796 task,
797 Stage::Prepare,
798 if p.done.is_empty() {
799 StageState::Skipped
800 } else {
801 StageState::Passed
802 },
803 Some(if p.done.is_empty() {
804 "reused: the lockfiles are unchanged".to_owned()
805 } else {
806 p.done.join(", ")
807 }),
808 Some(began),
809 );
810 }
811 Err(f) => {
812 stage(
813 &*live,
814 task,
815 Stage::Prepare,
816 StageState::Failed,
817 Some(f.message.clone()),
818 Some(began),
819 );
820 return fail(CommandStatus::ConfigError, f.message)
821 .with_code("PREPARE-FAILED")
822 .with_fix(f.fix)
823 .with_commands(f.commands);
824 }
825 }
826 } else if options.session.is_none() {
827 crate::prepare::forget(&wt_root);
829 }
830
831 let began = std::time::Instant::now();
833 stage(
834 &*live,
835 task,
836 Stage::Baseline,
837 StageState::Started,
838 None,
839 None,
840 );
841 let baseline = match verify::run_checks(&project, Some(verify::config::Tier::Fast), &runner) {
842 Ok(b) => b,
843 Err(e) => {
844 stage(
845 &*live,
846 task,
847 Stage::Baseline,
848 StageState::Failed,
849 None,
850 Some(began),
851 );
852 return fail(CommandStatus::ConfigError, format!("baseline: {e}"));
853 }
854 };
855 if !options.allow_failing_baseline
860 && let Some((c, why)) = baseline
861 .checks
862 .iter()
863 .find_map(|c| broken(c).map(|w| (c, w)))
864 {
865 stage(
866 &*live,
867 task,
868 Stage::Baseline,
869 StageState::Failed,
870 Some(format!("`{}` cannot run", c.name)),
871 Some(began),
872 );
873 let checkout = std::path::Path::new(&s.snapshot.root);
876 if let Some(remedy) = crate::code::setup_remedy(checkout, Some(&feature_name)) {
877 return fail(
878 CommandStatus::GitPrecondition,
879 format!(
880 "check `{}` cannot run in the worktree: your checkout has not committed its setup — {why}",
881 c.name
882 ),
883 )
884 .with_code("SETUP-INCOMPLETE")
885 .with_fix(vec!["speccoder fix".to_owned(), remedy.command.clone()])
886 .with_remedy(Some(remedy));
887 }
888 return fail(
889 CommandStatus::ConfigError,
890 if why.contains("git add") || why.contains("--allow-failing-baseline") {
893 format!(
894 "check `{}` cannot run on the untouched code, so it could never judge {task}: {why}",
895 c.name
896 )
897 } else {
898 format!(
899 "check `{}` cannot run on the untouched code, so it could never judge {task}: {why} — fix the check (a file it needs may be uncommitted: `git status`), or run with --allow-failing-baseline",
900 c.name
901 )
902 },
903 )
904 .with_code("CHECK-BROKEN");
905 }
906 let failing = baseline
908 .checks
909 .iter()
910 .filter(|c| c.status.is_failure())
911 .count();
912 stage(
913 &*live,
914 task,
915 Stage::Baseline,
916 StageState::Passed,
917 (failing > 0).then(|| format!("{failing} check(s) already failing")),
918 Some(began),
919 );
920
921 let rt = match tokio_runtime() {
922 Ok(rt) => rt,
923 Err(e) => return fail(CommandStatus::RunFailed, e),
924 };
925 let bundle_value = match serde_json::to_value(&bundle) {
926 Ok(v) => v,
927 Err(e) => return fail(CommandStatus::Error, e.to_string()),
928 };
929 let instructions = crate::instructions::collect(
933 &wt_root,
934 &project,
935 &speccoder_core::scope::named_paths(&bundle.task.title),
936 &run_config.instructions,
937 );
938 let attempt_instructions: &[crate::instructions::Instruction] = if executor.is_none() {
939 &instructions
940 } else {
941 &[]
942 };
943
944 let servers = match mcp::parse(&config_text) {
946 Ok(s) => s,
947 Err(e) => {
948 return fail(CommandStatus::ConfigError, format!("speccoder.toml: {e}"))
949 .with_code("CONFIG-INVALID");
950 }
951 };
952 let mut connected = if servers.is_empty() {
953 mcp::Connected::default()
954 } else {
955 live.event(&progress::Event::Notice {
956 text: format!("starting {} MCP server(s)", servers.len()),
957 });
958 rt.block_on(mcp::connect(&servers, &project, &runner))
959 };
960 let approved_tools: Vec<String> = task_grants
962 .iter()
963 .filter_map(|g| g.tool_name().map(str::to_owned))
964 .collect();
965 let pinned = mcp::pin_reviewed(&s.plane_dir, &mut connected.tools, &approved_tools);
966 connected.notices.extend(pinned);
967
968 let tools_server = match tools::WorkspaceTools::new(&wt_root, policy.clone()) {
971 Ok(t) => std::sync::Arc::new(t.with_runner(runner.clone())),
972 Err(e) => return fail(CommandStatus::Error, e.to_string()),
973 };
974 let swept =
977 match crate::approvals::expire_due(&plane_dir, agentplane::core::Timestamp::now_utc()) {
978 Ok(p) => p,
979 Err(e) => {
980 return fail(
981 CommandStatus::RunFailed,
982 format!("the calls past their deadline could not be denied: {e}"),
983 );
984 }
985 };
986 let present = crate::approvals::PresentContext {
988 root: None,
989 sandbox: runner.is_sandboxed().then(|| {
990 if cfg!(target_os = "macos") {
991 "Seatbelt".to_owned()
992 } else {
993 "Landlock+seccomp".to_owned()
994 }
995 }),
996 network: match sandbox_config.network {
997 sandbox::Network::Off => "none",
998 sandbox::Network::Loopback => "loopback",
999 sandbox::Network::On => "unrestricted",
1000 }
1001 .to_owned(),
1002 file_text: None,
1003 };
1004 let plane = match rt.block_on(async {
1005 substrate::Plane::open_with(
1006 &plane_dir,
1007 &s.model,
1008 provider,
1009 Some(tools_server),
1010 substrate::Hooks {
1011 progress: Some(Arc::clone(&live)),
1012 mcp: connected.clients.clone(),
1013 mcp_tools: connected.tools.clone(),
1014 format: Some(format),
1015 present: present.clone(),
1016 },
1017 )
1018 }) {
1019 Ok(p) => p,
1020 Err(e) => return fail(CommandStatus::RunFailed, e.0),
1021 };
1022 let mut notices: Vec<String> = elsewhere
1023 .replaced_journal
1024 .iter()
1025 .chain(swept.iter())
1026 .chain(plane.replaced_journal.iter())
1027 .map(|p| {
1028 format!(
1029 "the journal could not be read by this build and was moved to {}; past runs stay in git",
1030 p.display()
1031 )
1032 })
1033 .chain(connected.notices.iter().cloned())
1034 .chain(sandbox_notice.clone())
1035 .chain(prepare_notes.iter().cloned())
1036 .chain(resumed_from.as_ref().map(|(stage, last_call)| {
1037 format!(
1038 "Resuming — {task} was interrupted during {}{}; finished calls will not repeat.",
1039 stage.map_or("a run", speccoder_core::stage::Stage::name),
1040 last_call
1041 .as_ref()
1042 .map(|c| format!(" ({c})"))
1043 .unwrap_or_default()
1044 )
1045 }))
1046 .collect();
1047
1048 let demand_red =
1051 run_config.acceptance && planning.is_none() && format.is_convergence(&bundle.task.phase);
1052 let start = match &interrupted {
1058 Some(_) => match git::Git::at(&wt_root).line(&["rev-parse", "HEAD^{tree}"]) {
1059 Ok(tree) => worktree::Checkpoint(tree),
1060 Err(e) => return fail(CommandStatus::GitPrecondition, e.0),
1061 },
1062 None => match worktree::checkpoint(&wt_root, &tmp) {
1063 Ok(c) => c,
1064 Err(e) => return fail(CommandStatus::GitPrecondition, e.0),
1065 },
1066 };
1067
1068 let began = std::time::Instant::now();
1069 let bug_ctx = super::bug::Ctx {
1074 rt: &rt,
1075 plane: &plane,
1076 project: &project,
1077 wt_root: &wt_root,
1078 wt_path: &wt_path,
1079 tmp: &tmp,
1080 policy: &policy,
1081 runner: &runner,
1082 state: &s.plane_dir,
1083 feature: &feature_name,
1084 task,
1085 bundle: &bundle_value,
1086 instructions: &instructions,
1087 live: &*live,
1088 approver: approver.as_deref(),
1089 held_out: run_config.held_out,
1090 max_tries: run_config.reproduce_tries,
1091 bug_test: run_config.bug_test.as_deref(),
1092 start: &start,
1093 };
1094 let mut bug_fix = match super::bug::phase(&s.plane_dir, &feature_name, task, &project, format) {
1095 Err(e) => return fail(CommandStatus::NeedsHuman, e),
1096 Ok(None) => None,
1097 Ok(Some(super::bug::Phase::Fix(f))) => Some(*f),
1098 Ok(Some(super::bug::Phase::Reproduce(b))) if interrupted.is_none() => {
1099 match super::bug::reproduce(&bug_ctx, *b) {
1100 Ok(f) => Some(f),
1101 Err(stop) => return *stop,
1102 }
1103 }
1104 Ok(Some(super::bug::Phase::Reproduce(_))) => None,
1105 };
1106 let bug_candidate = bug_fix.as_ref().and_then(|f| {
1107 f.bug.candidate.clone().and_then(|c| {
1108 crate::bug::state::extra(&s.plane_dir, &f.bug.unit, &f.bug.task)
1109 .candidate_patch
1110 .map(|d| (d, c))
1111 })
1112 });
1113 let test_layout = crate::layout::detect(&project, &check_argvs);
1116 let test_layout_text = test_layout.text();
1117 let story_files = super::commit::story_files(&wt_root, &feature_name);
1118 let scenarios = match &bug_fix {
1119 Some(f) => super::bug::scenarios(&f.bug),
1120 None => format.scenarios(&snap, story_task.as_deref().unwrap_or(task)),
1121 };
1122 let mut review_frozen: Option<(speccoder_core::acceptance::PreFrozenAcceptance, String)> = None;
1125 let mut review_reuse = None;
1126 if bug_fix.is_none() && run_config.acceptance && !options.fresh_acceptance && planning.is_none()
1127 {
1128 match crate::oracle::for_task(&s.plane_dir, &project, &wt_root, format, &snap, &scenarios) {
1129 Some(r @ crate::oracle::TaskReuse::Ready { .. }) => review_reuse = Some(r),
1130 Some(crate::oracle::TaskReuse::Reused { req }) => notices.push(format!(
1131 "{req}'s frozen tests were reused by an earlier task of this run: this task's acceptance tests are authored"
1132 )),
1133 Some(crate::oracle::TaskReuse::Elsewhere { req }) => {
1134 notices.push(format!("{req}: frozen oracle not present here — authoring"))
1135 }
1136 Some(crate::oracle::TaskReuse::Lapsed {
1137 req,
1138 frozen,
1139 current,
1140 }) => {
1141 if crate::oracle::note_lapse(&s.plane_dir, &feature_name, &req, &frozen) {
1142 live.event(&progress::Event::Oracle {
1143 step: progress::OracleEvent::Lapsed {
1144 unit: feature_name.clone(),
1145 requirement: req.clone(),
1146 frozen_wording_sha256: frozen,
1147 current_wording_sha256: current,
1148 },
1149 });
1150 }
1151 notices.push(format!(
1152 "{req}'s wording changed since its tests were frozen at review: the frozen oracle lapsed — authoring"
1153 ));
1154 }
1155 Some(crate::oracle::TaskReuse::Tampered(why)) => {
1156 return fail(
1157 CommandStatus::NeedsHuman,
1158 format!("{why}: the task stops for a person, nothing is ticked"),
1159 )
1160 .with_code("ORACLE-TAMPERED");
1161 }
1162 Some(crate::oracle::TaskReuse::Unreadable(why)) => {
1163 return fail(
1164 CommandStatus::NeedsHuman,
1165 format!("{why}: whether its tests are frozen is unknown, so the task stops for a person, nothing is ticked"),
1166 )
1167 .with_code("REVIEW-UNREADABLE");
1168 }
1169 None => {}
1170 }
1171 }
1172 let mut acceptance = if let Some(prepared) = interrupted
1173 .as_ref()
1174 .and_then(|m| m.acceptance.clone())
1175 .and_then(|a| serde_json::from_value::<PreparedAcceptance>(a).ok())
1176 {
1177 let mut prepared = prepared;
1181 if let Some(sealed) = bug_fix
1182 .as_ref()
1183 .and_then(|f| f.record.held_out_sealed.as_ref())
1184 {
1185 prepared.held_out = Some(sealed.manifest_sha256.clone());
1186 prepared.report["held_out"] = serde_json::json!({
1187 "state": "on",
1188 "manifest": format!("sha256:{}", sealed.manifest_sha256),
1189 "kept": sealed.count,
1190 });
1191 }
1192 Some(prepared)
1193 } else if let Some(f) = &bug_fix {
1194 stage(&*live, task, Stage::Red, StageState::Started, None, None);
1195 match super::bug::reuse(&bug_ctx, f) {
1196 Ok(a) => Some(a),
1197 Err(e) => {
1198 let _ = worktree::restore(&wt_root, &tmp, &start);
1199 stage(
1200 &*live,
1201 task,
1202 Stage::Red,
1203 StageState::Failed,
1204 Some(e.clone()),
1205 Some(began),
1206 );
1207 return fail(CommandStatus::NeedsHuman, e);
1208 }
1209 }
1210 } else if let Some(reuse) = review_reuse.take() {
1211 stage(&*live, task, Stage::Red, StageState::Started, None, None);
1214 let crate::oracle::TaskReuse::Ready {
1215 record,
1216 files,
1217 tests,
1218 manifest,
1219 } = reuse
1220 else {
1221 return fail(CommandStatus::Error, "no frozen oracle".to_owned());
1222 };
1223 match reuse_pre_frozen(
1224 &project,
1225 &record,
1226 &files,
1227 &tests,
1228 &runner,
1229 RedRule::RunTime,
1230 Some(&SealedCheck {
1231 state: &s.plane_dir,
1232 unit: &feature_name,
1233 wt_root: &wt_root,
1234 tmp: &tmp,
1235 policy: &policy,
1236 }),
1237 ) {
1238 Ok(mut a) => {
1239 a.report["pre_frozen"]["manifest"] = serde_json::json!(manifest);
1240 notices.push(format!(
1241 "acceptance tests frozen at review by {} ({}) for {}: no author call",
1242 record.decided.by, record.decided.via, record.requirement
1243 ));
1244 review_frozen = Some((*record, manifest));
1245 Some(a)
1246 }
1247 Err(e) => {
1248 let _ = worktree::restore(&wt_root, &tmp, &start);
1249 stage(
1250 &*live,
1251 task,
1252 Stage::Red,
1253 StageState::Failed,
1254 Some(e.clone()),
1255 Some(began),
1256 );
1257 return fail(CommandStatus::NeedsHuman, e).with_code("ORACLE-TAMPERED");
1258 }
1259 }
1260 } else if run_config.acceptance && planning.is_none() && format.acceptance_testable(&bundle) {
1261 stage(&*live, task, Stage::Red, StageState::Started, None, None);
1262 Some(prepare_acceptance(&AcceptanceSetup {
1263 rt: &rt,
1264 plane: &plane,
1265 project: &project,
1266 worktree: &wt_root,
1267 tmp: &tmp,
1268 policy: &policy,
1269 feature: &feature_name,
1270 task,
1271 bundle: bundle_value.clone(),
1272 scenarios: &scenarios,
1273 instructions: &instructions,
1274 runner: &runner,
1275 layout: Some(&test_layout),
1276 story_files: &story_files,
1277 }))
1278 } else {
1279 None
1280 };
1281 if review_frozen.is_none()
1282 && acceptance
1283 .as_ref()
1284 .is_some_and(|a| a.report["source"] == "review")
1285 && let Some(crate::oracle::TaskReuse::Ready {
1286 record, manifest, ..
1287 }) = review_reuse.take()
1288 {
1289 review_frozen = Some((*record, manifest));
1290 }
1291 let held_out_store = match (&bug_fix, &review_frozen) {
1294 (Some(f), _) => crate::held_out::sealed_dir(&s.plane_dir, &f.bug.unit, &f.bug.requirement),
1295 (None, Some((r, _))) => {
1296 crate::held_out::sealed_dir(&s.plane_dir, &feature_name, &r.requirement)
1297 }
1298 (None, None) => crate::held_out::dir(&s.plane_dir, &feature_name, task),
1299 };
1300 if let Some(a) = acceptance
1301 .as_mut()
1302 .filter(|a| a.report.get("held_out").is_none())
1303 {
1304 if !run_config.held_out {
1305 a.report["held_out"] = serde_json::json!({ "state": "off" });
1306 } else if a.argv.is_none() {
1307 a.report["held_out"] =
1308 serde_json::json!({ "state": "absent", "reason": "no_visible_tests" });
1309 } else if !a.red {
1310 a.report["held_out"] = serde_json::json!({ "state": "absent", "reason": "not_red" });
1311 } else if scenarios.is_empty() {
1312 a.report["held_out"] =
1313 serde_json::json!({ "state": "absent", "reason": "no_scenarios" });
1314 } else {
1315 let (held, sha) = prepare_held_out(
1316 &AcceptanceSetup {
1317 rt: &rt,
1318 plane: &plane,
1319 project: &project,
1320 worktree: &wt_root,
1321 tmp: &tmp,
1322 policy: &policy,
1323 feature: &feature_name,
1324 task,
1325 bundle: bundle_value.clone(),
1326 scenarios: &scenarios,
1327 instructions: &instructions,
1328 runner: &runner,
1329 layout: Some(&test_layout),
1330 story_files: &story_files,
1331 },
1332 a,
1333 &scenarios,
1334 &held_out_store,
1335 story_checkpoint(
1336 snap.feature.as_ref().and_then(|f| f.tasks.as_ref()),
1337 task,
1338 &scenarios,
1339 ),
1340 );
1341 a.report["held_out"] = held;
1342 a.held_out = sha;
1343 }
1344 }
1345 if run_config.held_out && !run_config.acceptance {
1346 notices.push(
1347 "[acceptance] held_out has no effect while generate = false: no held-out tests"
1348 .to_owned(),
1349 );
1350 }
1351 match &acceptance {
1352 None => stage(
1353 &*live,
1354 task,
1355 Stage::Red,
1356 StageState::Skipped,
1357 Some(if planning.is_some() {
1358 "planning work: design documents".to_owned()
1359 } else {
1360 "no acceptance examples".to_owned()
1361 }),
1362 None,
1363 ),
1364 Some(a) if a.red => stage(
1365 &*live,
1366 task,
1367 Stage::Red,
1368 StageState::Passed,
1369 a.red_class.map(class_word),
1370 Some(began),
1371 ),
1372 Some(a) => stage(
1373 &*live,
1374 task,
1375 Stage::Red,
1376 StageState::Failed,
1377 Some(a.red_class.map_or_else(
1378 || "not demonstrated".to_owned(),
1379 |c| format!("not demonstrated ({})", class_word(c)),
1380 )),
1381 Some(began),
1382 ),
1383 }
1384
1385 if let Some(why) = acceptance
1389 .as_ref()
1390 .and_then(|a| a.generation_failed.clone())
1391 {
1392 let reason = format!(
1393 "the acceptance tests could not be written ({why}); nothing was attempted — run again once the model answers, or set [acceptance] generate = false to rely on the checks alone"
1394 );
1395 let _ = worktree::restore(&wt_root, &tmp, &start);
1396 let report = RunReport {
1397 reason: Some(reason.clone()),
1398 acceptance: acceptance.as_ref().map(|a| a.report.clone()),
1399 set_aside,
1400 notices: notices.clone(),
1401 ..bare_report(&feature_name, task, &wt_path, "acceptance_failed")
1402 };
1403 live.event(&finished_event(
1404 task,
1405 &report,
1406 "acceptance_failed",
1407 false,
1408 redact(&reason, secret),
1409 ));
1410 return CommandResult::new("run", CommandStatus::NeedsHuman, &redact(&reason, secret))
1411 .with_code("ACCEPTANCE-UNWRITTEN")
1412 .with_data(CommandData::Run(Box::new(report)));
1413 }
1414
1415 if demand_red && !acceptance.as_ref().is_some_and(|a| a.red) {
1416 let why = undemonstrated_why(acceptance.as_ref());
1417 let reason = format!(
1418 "convergence gap not demonstrated: {why}; a person decides whether {task} is real"
1419 );
1420 let saved = attempts::save(
1422 &wt_root,
1423 &tmp,
1424 &feature_name,
1425 task,
1426 &attempts::Record {
1427 run: None,
1428 outcome: "not_demonstrated",
1429 reason: &reason,
1430 pending: None,
1431 usage: None,
1432 },
1433 )
1434 .ok()
1435 .map(|s| s.reference);
1436 let _ = worktree::restore(&wt_root, &tmp, &start);
1437 let report = RunReport {
1438 reason: Some(reason.clone()),
1439 acceptance: acceptance.as_ref().map(|a| a.report.clone()),
1440 saved_attempt: saved,
1441 set_aside,
1442 notices: notices.clone(),
1443 ..bare_report(&feature_name, task, &wt_path, "not_demonstrated")
1444 };
1445 live.event(&finished_event(
1446 task,
1447 &report,
1448 "not_demonstrated",
1449 false,
1450 redact(&reason, secret),
1451 ));
1452 return CommandResult::new("run", CommandStatus::NeedsHuman, &redact(&reason, secret))
1453 .with_data(CommandData::Run(Box::new(report)));
1454 }
1455
1456 let before = match &interrupted {
1459 Some(m) => worktree::Checkpoint(m.before.clone()),
1460 None => match worktree::checkpoint(&wt_root, &tmp) {
1461 Ok(c) => c,
1462 Err(e) => return fail(CommandStatus::GitPrecondition, e.0),
1463 },
1464 };
1465 let acceptance_saved = acceptance
1466 .as_ref()
1467 .and_then(|a| serde_json::to_value(a).ok());
1468 let frozen: Vec<String> = worktree::files(&wt_root, &before)
1470 .unwrap_or_default()
1471 .into_iter()
1472 .filter(|p| tools::paths::is_test_path(p))
1473 .collect();
1474 let mut usage: Option<serde_json::Value> = None;
1475 let mut samples: Vec<(RunReport, String, worktree::Checkpoint, serde_json::Value)> = Vec::new();
1478 let mut held_out_log: Vec<serde_json::Value> = Vec::new();
1480 let mut bug_weak: Option<speccoder_core::strength::Permitted> = None;
1482 let mut refused_account = false;
1484 let (mut report, attempt_status) = loop {
1485 let mut earlier: Vec<speccoder_core::EarlierAttempt> = Vec::new();
1486 let mut digest: Option<serde_json::Value> = None;
1487 let mut attempt_no = interrupted
1490 .as_ref()
1491 .filter(|m| m.sample == samples.len())
1492 .map_or(1, |m| m.attempt.max(1));
1493 let (mut report, attempt_status) = loop {
1494 let hidden: Vec<String> = options
1496 .session
1497 .as_ref()
1498 .and_then(|s| s.lock().ok().map(|s| s.hidden.clone()))
1499 .unwrap_or_default();
1500 let (task_grants, approved_once) = match approvals::Decisions::load(&s.plane_dir) {
1506 Ok(_) if autopilot => (Vec::new(), Vec::new()),
1509 Ok(mut d) => {
1510 let once = d.take_once(&feature_name, task, this_run.as_str());
1511 if !once.is_empty()
1512 && let Err(e) = d.save(&s.plane_dir)
1513 {
1514 return fail(CommandStatus::Error, e);
1515 }
1516 (d.for_run(&feature_name, task, this_run.as_str()), once)
1517 }
1518 Err(e) => return fail(CommandStatus::ConfigError, e),
1519 };
1520 let run_approved: Vec<crate::tools::policy::Object> = options
1522 .run_grants
1523 .lock()
1524 .map(|g| g.clone())
1525 .unwrap_or_default();
1526 let input = substrate::attempt::input(
1528 bundle_value.clone(),
1529 &substrate::attempt::Settings {
1530 checks: &check_argvs,
1531 allow: &run_config.allow,
1532 allow_prefix: &run_config.allow_prefix,
1533 max_turns: run_config.max_turns,
1534 max_tool_calls: run_config.max_tool_calls,
1535 reasoning: s.model.reasoning_summary,
1536 frozen: &frozen,
1537 approved: &task_grants,
1538 rejected: &decisions.rejected,
1539 run_approved: &run_approved,
1540 approved_once: &approved_once,
1541 nudges: &decisions.nudges,
1542 mcp: &connected.tools,
1543 root: &wt_root_canonical,
1544 frozen_additions: run_config.frozen_additions,
1545 asks: if options.lane.is_some() {
1548 "stop"
1549 } else {
1550 "tasks"
1551 },
1552 wait_secs: run_config.approval_wait.as_secs(),
1553 network_allow: &sandbox_config.network_allow,
1554 network_allow_prefix: &sandbox_config.network_allow_prefix,
1555 run_id: this_run.as_str(),
1556 asked: options.asked_now(),
1557 budget: run_config.approval_budget,
1558 prompts: approver.is_some() && options.lane.is_none(),
1559 in_place: options.session.is_some(),
1560 hidden: &hidden,
1561 autopilot: options.mode == speccoder_core::oracle::RunMode::Autopilot,
1562 planning: planning.as_deref(),
1563 },
1564 digest.as_ref(),
1565 attempt_instructions,
1566 (!test_layout.runners.is_empty()).then_some(test_layout_text.as_str()),
1568 );
1569 let attempt_began = std::time::Instant::now();
1570 let attempt_detail = if run_config.best_of > 1 {
1571 format!(
1572 "{attempt_no}/{} · sample {}/{}",
1573 run_config.max_attempts,
1574 samples.len() + 1,
1575 run_config.best_of
1576 )
1577 } else {
1578 format!("{attempt_no}/{}", run_config.max_attempts)
1579 };
1580 stage(
1581 &*live,
1582 task,
1583 Stage::Attempt,
1584 StageState::Started,
1585 Some(attempt_detail.clone()),
1586 None,
1587 );
1588 let judged_before = integrity::JudgeSnapshot::take(&wt_root, &policy);
1591 let (run_id, succeeded, mut output) = if let Some((diff, cand)) = &bug_candidate {
1594 let held: Vec<String> = bug_fix
1595 .as_ref()
1596 .and_then(|f| {
1597 f.bug
1598 .held_out_sealed
1599 .clone()
1600 .map(|h| (f.bug.unit.clone(), h))
1601 })
1602 .and_then(|(unit, h)| {
1603 crate::held_out::open_sealed(&s.plane_dir, &unit, &h).ok()
1604 })
1605 .map(|(m, _)| m.files.into_iter().map(|f| f.path).collect())
1606 .unwrap_or_default();
1607 match super::bug::apply_candidate(&bug_ctx, diff, cand, &frozen, &held) {
1608 Ok(x) => x,
1609 Err(stop) => return *stop,
1610 }
1611 } else if let Some(exec) = &executor {
1612 let allow: Vec<Vec<String>> = check_argvs
1613 .iter()
1614 .chain(&run_config.allow)
1615 .cloned()
1616 .collect();
1617 let prompt = external::prompt_in(format.wording(), &bundle_value, digest.as_ref());
1618 let withheld = acceptance
1619 .as_ref()
1620 .and_then(|a| a.held_out.as_ref())
1621 .map(|_| held_out_store.as_path());
1622 if withheld.is_some()
1623 && !notices
1624 .iter()
1625 .any(|n| n.starts_with("held-out set withheld"))
1626 {
1627 notices.push("held-out set withheld from the external agent, not sealed: it runs with your permissions; a copied held-out literal stops the tick".to_owned());
1628 }
1629 let _ = allow;
1630 let o = match &exec.kind {
1631 external::Kind::Command(argv) => {
1632 external::run(argv, exec.timeout, &wt_root, &prompt, &tmp)
1633 }
1634 external::Kind::Acp(agent) => {
1635 let policy = match substrate::attempt::policy_of(
1638 &input.peek()["settings"],
1639 format.rules(),
1640 ) {
1641 Ok(p) => p,
1642 Err(e) => return fail(CommandStatus::RunFailed, e.to_string()),
1643 };
1644 let tools = match tools::WorkspaceTools::new(&wt_root, policy.clone()) {
1645 Ok(t) => t.with_runner(runner.clone()),
1646 Err(e) => {
1647 return fail(
1648 CommandStatus::Error,
1649 format!("{}: {e}", wt_root.display()),
1650 );
1651 }
1652 };
1653 let governor = Arc::new(crate::acp::govern::Governor::new(
1654 crate::acp::govern::Setup {
1655 root: std::fs::canonicalize(&wt_root)
1656 .unwrap_or_else(|_| wt_root.clone()),
1657 tools,
1658 policy,
1659 approver: approver.clone().filter(|_| options.lane.is_none()),
1661 present: present.clone(),
1662 task: format!("{feature_name}/{task}"),
1663 task_title: parsed_task
1664 .as_ref()
1665 .map(|t| t.title.clone())
1666 .unwrap_or_default(),
1667 run: Some(this_run.to_string()),
1668 frozen_additions: run_config.frozen_additions,
1669 run_approved: run_approved.clone(),
1670 approved_once: approved_once.clone(),
1671 progress: Some((task.to_owned(), Arc::clone(&live))),
1672 copied: copied_files.clone(),
1673 agent: agent.id.clone(),
1674 },
1675 ));
1676 let a = external::run_acp(
1677 exec,
1678 agent,
1679 &wt_root,
1680 &prompt,
1681 &runner,
1682 governor,
1683 Some((task.to_owned(), Arc::clone(&live))),
1684 );
1685 if let Some(ways) = &a.sign_in {
1686 return login(fail, &a.agent, agent, ways);
1687 }
1688 for n in a.outcome.output["acp"]["notices"]
1689 .as_array()
1690 .into_iter()
1691 .flatten()
1692 .filter_map(serde_json::Value::as_str)
1693 {
1694 notices.push(format!("{}: {n}", a.agent));
1695 }
1696 a.outcome
1697 }
1698 };
1699 (o.run_id, true, o.output)
1700 } else {
1701 let key = match &interrupted {
1703 Some(m) if m.attempt == attempt_no && m.sample == samples.len() => {
1704 m.key.clone()
1705 }
1706 _ => resume::new_key(&feature_name, task),
1707 };
1708 let _ = resume::save(
1709 &marker_path,
1710 &resume::Marker {
1711 key: key.clone(),
1712 before: before.0.clone(),
1713 head: head_now.clone(),
1714 attempt: attempt_no,
1715 sample: samples.len(),
1716 acceptance: acceptance_saved.clone(),
1717 run_id: Some(this_run.to_string()),
1718 asked: options.asked_now(),
1719 run_grants: run_approved.clone(),
1720 },
1721 );
1722 marker_guard.arm();
1723 let outcome = match rt.block_on(plane.attempt_keyed(
1724 &feature_name,
1725 task,
1726 input,
1727 &key,
1728 )) {
1729 Ok((o, resumed)) => {
1730 if resumed {
1731 notices.push(format!(
1732 "resumed run {} of an interrupted process: finished model and tool calls were read back from the journal, not repeated",
1733 o.run_id
1734 ));
1735 }
1736 o
1737 }
1738 Err(e) => return fail(CommandStatus::RunFailed, e.0),
1739 };
1740 let context = crate::approvals::PresentContext {
1744 root: Some(wt_root.clone()),
1745 ..present.clone()
1746 };
1747 let (outcome, waiting) = match rt.block_on(plane.decide_inline(
1748 outcome,
1749 approver.as_deref(),
1750 &context,
1751 )) {
1752 Ok(x) => {
1753 notices.extend(crate::actions::allow_always_inline(
1756 path,
1757 &feature_name,
1758 &x.always,
1759 state,
1760 ));
1761 (x.outcome, x.waiting)
1762 }
1763 Err(e) => return fail(CommandStatus::RunFailed, e.0),
1764 };
1765 if let Some(task_row) = waiting {
1766 marker_guard.keep();
1769 let action = &task_row.justification.proposed_action;
1770 let mut report = bare_report(&feature_name, task, &wt_path, "needs_approval");
1771 report.run_id = outcome.run_id.to_string();
1772 report.notices = notices;
1773 report.tool_calls = action["log"].as_array().cloned().unwrap_or_default();
1774 report.tool_calls.push(serde_json::json!({
1776 "tool": action["tool"],
1777 "arguments": action["arguments"],
1778 "decision": "approval",
1779 "reason": action["request"]["reason"],
1780 "object": action["request"]["object"],
1781 "waiting": true,
1782 "call": task_row.id.to_hex(),
1783 }));
1784 report.pending = Some(serde_json::json!({
1785 "tool": action["tool"],
1786 "arguments": action["arguments"],
1787 "reason": action["request"]["reason"],
1788 "object": action["request"]["object"],
1789 "request": action["request"],
1790 "call": task_row.id.to_hex(),
1791 "deadline": task_row.due_at.map(|t| t.unix_timestamp()),
1792 "waiting": true,
1793 "batched": action["request"]["batched"],
1794 }));
1795 if let (Some(n), Ok(mut asked)) = (
1798 action["request"]["asked"]
1799 .as_u64()
1800 .and_then(|n| u32::try_from(n).ok()),
1801 options.asked.lock(),
1802 ) {
1803 *asked = (*asked).max(n);
1804 }
1805 report.reason = Some(format!(
1806 "waiting for a person: {} — `speccoder task approve {task}` or `speccoder task reject {task} --reason …`, then `speccoder run`",
1807 task_row.justification.summary.peek()
1808 ));
1809 let (status, message) = status_and_message(&report, "needs_approval", false);
1810 live.event(&finished_event(
1811 task,
1812 &report,
1813 "needs_approval",
1814 false,
1815 redact(&message, secret),
1816 ));
1817 return CommandResult::new("run", status, &redact(&message, secret))
1818 .with_data(CommandData::Run(Box::new(report)));
1819 }
1820 let succeeded = matches!(outcome.status, agentplane::prelude::RunStatus::Succeeded);
1821 refused_account = outcome
1822 .failed_effect
1823 .as_ref()
1824 .is_some_and(agentplane::journal::FailedEffect::refuses_the_account);
1825 let mut output = outcome
1826 .output
1827 .as_ref()
1828 .map(|o| o.peek().clone())
1829 .unwrap_or(serde_json::Value::Null);
1830 if !succeeded && output["reason"].as_str().is_none() {
1831 if !output.is_object() {
1832 output = serde_json::json!({});
1833 }
1834 let reason = if rt.block_on(plane.holds_a_pre_054_decision(outcome.run_id)) {
1837 substrate::PRE_054_DECISION.to_owned()
1838 } else {
1839 format!("{:?}", outcome.status)
1840 };
1841 output["reason"] = serde_json::Value::String(redact(&reason, secret));
1842 }
1843 (outcome.run_id.to_string(), succeeded, output)
1844 };
1845 if bug_candidate.is_some()
1846 && let Some(c) = bug_fix.as_mut().and_then(|f| f.bug.candidate.as_mut())
1847 {
1848 c.applied = true;
1849 }
1850 if let Some(argv) = run_config.format.as_ref().filter(|_| {
1853 succeeded && matches!(output["status"].as_str(), Some("completed" | "incomplete"))
1854 }) {
1855 use verify::process::CommandRunner as _;
1856 let ran = runner.run(&verify::process::Invocation {
1857 argv: argv.clone(),
1858 cwd: project.clone(),
1859 env: verify::process::scrubbed_env(std::env::vars()),
1860 timeout: std::time::Duration::from_secs(300),
1861 output_cap: verify::process::OUTPUT_CAP,
1862 });
1863 if ran.exit_code != Some(0) {
1864 notices.push(format!(
1865 "the formatter (`{}`) did not succeed",
1866 argv.join(" ")
1867 ));
1868 }
1869 }
1870 if prepares {
1874 let began = std::time::Instant::now();
1875 match crate::prepare::recheck(&crate::prepare::Prepare {
1876 worktree: &wt_root,
1877 project: &project,
1878 config: &worktree_config,
1879 runner: &runner,
1880 state: Some(state),
1881 }) {
1882 Ok(done) if done.is_empty() => {}
1883 Ok(done) => {
1884 stage(
1885 &*live,
1886 task,
1887 Stage::Prepare,
1888 StageState::Passed,
1889 Some(format!(
1890 "{}: the attempt changed its lockfile",
1891 done.join(", ")
1892 )),
1893 Some(began),
1894 );
1895 }
1896 Err(f) => {
1897 stage(
1898 &*live,
1899 task,
1900 Stage::Prepare,
1901 StageState::Failed,
1902 Some(f.message.clone()),
1903 Some(began),
1904 );
1905 let reason = redact(&f.message, secret);
1909 let saved = attempts::save(
1910 &wt_root,
1911 &tmp,
1912 &feature_name,
1913 task,
1914 &attempts::Record {
1915 run: (!run_id.is_empty()).then_some(run_id.as_str()),
1916 outcome: "prepare_failed",
1917 reason: &reason,
1918 pending: None,
1919 usage: output.get("usage"),
1920 },
1921 )
1922 .and_then(|saved| {
1923 worktree::restore(&wt_root, &tmp, &before).map(|_| saved)
1924 });
1925 let message = match saved {
1926 Ok(saved) => format!(
1927 "{} — the attempt is saved as {} and undone",
1928 f.message, saved.reference
1929 ),
1930 Err(e) => format!("{} — saving the attempt failed: {}", f.message, e.0),
1931 };
1932 return fail(CommandStatus::ConfigError, message)
1933 .with_code("PREPARE-FAILED")
1934 .with_fix(f.fix)
1935 .with_commands(f.commands);
1936 }
1937 }
1938 }
1939 let after = match worktree::checkpoint(&wt_root, &tmp) {
1940 Ok(c) => c,
1941 Err(e) => return fail(CommandStatus::GitPrecondition, e.0),
1942 };
1943 let raw_changes = worktree::diff(&wt_root, &before, &after).unwrap_or_default();
1944 if let (Some(n), Ok(mut asked)) = (
1949 output["asked"].as_u64().and_then(|n| u32::try_from(n).ok()),
1950 options.asked.lock(),
1951 ) {
1952 *asked = n;
1953 }
1954 let approved_writes = approved_writes(&task_grants, &output["tool_calls"]);
1955 let patch = worktree::patch(&wt_root, &before, &after).unwrap_or_default();
1956 if let Some(name) = crate::include::added_secret(&patch) {
1959 let _ = worktree::restore(&wt_root, &tmp, &before);
1960 return fail(
1961 CommandStatus::NeedsHuman,
1962 format!(
1963 "the attempt's change adds the value of {name}, copied from your checkout ([worktree] include): undone, nothing judged or committed"
1964 ),
1965 )
1966 .with_code("SECRET-IN-DIFF");
1967 }
1968 let findings = attempt_findings(&Audited {
1969 wt_root: &wt_root,
1970 policy: &policy,
1971 judged_before: &judged_before,
1972 raw_changes: &raw_changes,
1973 patch: &patch,
1974 frozen: &frozen,
1975 frozen_additions: run_config.frozen_additions,
1976 approved_writes: &approved_writes,
1977 command_drift: &output["integrity"],
1978 });
1979 let changes = changes_of(raw_changes);
1980
1981 let quarantined = !succeeded
1986 && output["reason"]
1987 .as_str()
1988 .is_some_and(|r| r.starts_with("Quarantined("));
1989 if quarantined {
1990 output["reason"] = serde_json::Value::String(
1991 "the attempt was interrupted while a tool call was running; whether it finished cannot be known, so it was not run again. The attempt is saved and undone; run again to start a fresh attempt".to_owned(),
1992 );
1993 }
1994 let mut attempt_status = if succeeded {
1995 output["status"].as_str().unwrap_or("failed").to_owned()
1996 } else if quarantined {
1997 "interrupted".to_owned()
1998 } else {
1999 "failed".to_owned()
2000 };
2001 if attempt_status == "completed" && changes.is_empty() && output.get("acp").is_some() {
2005 attempt_status = "blocked".to_owned();
2006 output["reason"] = serde_json::json!(format!(
2007 "{} ended its turn without changing anything",
2008 output["acp"]["agent"].as_str().unwrap_or("the agent")
2009 ));
2010 }
2011 let mut report = RunReport {
2012 run_id: run_id.clone(),
2013 model_report: output.get("report").cloned(),
2014 reason: output["reason"].as_str().map(str::to_owned),
2015 pending: output.get("pending").cloned(),
2016 tool_calls: output["tool_calls"].as_array().cloned().unwrap_or_default(),
2017 changes,
2018 usage: output.get("usage").cloned(),
2019 integrity: findings.clone(),
2020 acceptance: acceptance.as_ref().map(|a| a.report.clone()),
2021 set_aside: set_aside.clone(),
2022 notices: notices.clone(),
2023 agent: external::agent_attempt(&output),
2024 ..bare_report(&feature_name, task, &wt_path, &attempt_status)
2025 };
2026 if let Err(e) = record_inline_approvals(
2027 &s.plane_dir,
2028 &feature_name,
2029 task,
2030 &report.tool_calls,
2031 &options.run_grants,
2032 this_run.as_str(),
2033 ) {
2034 report.notices.push(format!(
2035 "the decisions made in this attempt were not recorded ({e}): later attempts ask again"
2036 ));
2037 }
2038 for c in report
2040 .tool_calls
2041 .iter()
2042 .filter(|c| c["approved_by"] == "person")
2043 {
2044 if let Some(name) = c["tool"].as_str().filter(|n| n.starts_with(mcp::PREFIX)) {
2045 mcp::mark_reviewed(&s.plane_dir, &connected.tools, name);
2046 }
2047 }
2048
2049 stage(
2050 &*live,
2051 task,
2052 Stage::Attempt,
2053 if attempt_status == "completed" {
2054 StageState::Passed
2055 } else {
2056 StageState::Failed
2057 },
2058 Some(if attempt_status == "completed" {
2059 attempt_detail
2060 } else {
2061 format!("{attempt_detail} {attempt_status}")
2062 }),
2063 Some(attempt_began),
2064 );
2065 if attempt_status == "integrity" {
2068 report.verdict = Some(speccoder_core::verify::Verdict::Failed {
2069 reasons: findings.clone(),
2070 });
2071 }
2072 let judged = matches!(attempt_status.as_str(), "completed" | "incomplete");
2074 if judged {
2075 let began = std::time::Instant::now();
2076 stage(&*live, task, Stage::Verify, StageState::Started, None, None);
2077 if let Err(e) = judge_checks(
2078 &project,
2079 &runner,
2080 &baseline,
2081 acceptance.as_ref(),
2082 &findings,
2083 &mut report,
2084 ) {
2085 stage(
2086 &*live,
2087 task,
2088 Stage::Verify,
2089 StageState::Failed,
2090 None,
2091 Some(began),
2092 );
2093 return fail(CommandStatus::ConfigError, format!("verification: {e}"));
2094 }
2095 if let Some(dir) = planning.as_ref().filter(|_| {
2099 matches!(
2100 report.verdict,
2101 Some(
2102 speccoder_core::verify::Verdict::Verified
2103 | speccoder_core::verify::Verdict::RegressionOnly
2104 )
2105 )
2106 }) {
2107 let inside = format!("{dir}/");
2108 let outside: Vec<&str> = report
2109 .changes
2110 .iter()
2111 .filter(|(p, _)| !p.starts_with(&inside))
2112 .map(|(p, _)| p.as_str())
2113 .collect();
2114 let reason = if !outside.is_empty() {
2115 Some(format!(
2116 "a planning task changed code: {}",
2117 outside.join(", ")
2118 ))
2119 } else if !report.changes.iter().any(|(_, kind)| kind != "deleted") {
2120 Some(format!("wrote no planning file under {inside}"))
2121 } else {
2122 None
2123 };
2124 if !outside.is_empty() {
2125 attempt_status = CHANGED_CODE.to_owned();
2127 report.attempt_status = CHANGED_CODE.to_owned();
2128 }
2129 if let Some(r) = reason {
2130 report.verdict =
2131 Some(speccoder_core::verify::Verdict::Failed { reasons: vec![r] });
2132 }
2133 }
2134 let otherwise_passing = attempt_status == "completed"
2138 && findings.is_empty()
2139 && matches!(
2140 report.verdict,
2141 Some(
2142 speccoder_core::verify::Verdict::Verified
2143 | speccoder_core::verify::Verdict::RegressionOnly
2144 )
2145 );
2146 match judge_collection(
2147 (&project, &wt_root, &tmp),
2148 &runner,
2149 otherwise_passing,
2150 &mut report,
2151 &*live,
2152 task,
2153 ) {
2154 Some(Collected::Unknown(why)) => {
2155 attempt_status = "collection_unknown".to_owned();
2156 report.verdict = None;
2157 report.reason = Some(why);
2158 }
2159 Some(Collected::Changed(finding)) => {
2161 report.integrity.push(finding.clone());
2162 report.verdict = Some(speccoder_core::verify::Verdict::Failed {
2163 reasons: vec![finding],
2164 });
2165 attempt_status = "integrity".to_owned();
2166 }
2167 None => {}
2168 }
2169 let checks_held = report.verification.as_ref().is_some_and(|v| v.passed);
2170 stage_with_tail(
2171 &*live,
2172 task,
2173 Stage::Verify,
2174 if checks_held {
2175 StageState::Passed
2176 } else {
2177 StageState::Failed
2178 },
2179 None,
2180 Some(began),
2181 report
2182 .verification
2183 .as_ref()
2184 .map(failing_tail)
2185 .unwrap_or_default(),
2186 );
2187 }
2188 if judged || attempt_status == "integrity" {
2189 stage(
2190 &*live,
2191 task,
2192 Stage::Audit,
2193 if findings.is_empty() {
2194 StageState::Passed
2195 } else {
2196 StageState::Failed
2197 },
2198 findings
2199 .first()
2200 .map(|f| f.trim_start_matches("integrity: ").to_owned()),
2201 None,
2202 );
2203 }
2204
2205 let visibly_passed = judged
2209 && findings.is_empty()
2210 && attempt_status == "completed"
2211 && matches!(
2212 report.verdict,
2213 Some(
2214 speccoder_core::verify::Verdict::Verified
2215 | speccoder_core::verify::Verdict::RegressionOnly
2216 )
2217 );
2218 if let Some(sha) = acceptance
2219 .as_ref()
2220 .and_then(|a| a.held_out.clone())
2221 .filter(|_| visibly_passed)
2222 {
2223 let patch = worktree::patch(&wt_root, &before, &after).unwrap_or_default();
2224 let mut known = format!(
2225 "{}\n{}\n{}",
2226 bundle_value["story"].as_str().unwrap_or_default(),
2227 bundle_value["plan"].as_str().unwrap_or_default(),
2228 bundle_value["constitution"].as_str().unwrap_or_default()
2229 );
2230 for p in report
2231 .acceptance
2232 .as_ref()
2233 .and_then(|a| a["files"].as_array().cloned())
2234 .unwrap_or_default()
2235 {
2236 if let Some(p) = p.as_str() {
2237 known.push_str(
2238 &std::fs::read_to_string(project.join(p)).unwrap_or_default(),
2239 );
2240 }
2241 }
2242 match judge_held_out(
2243 &held_out_store,
2244 &sha,
2245 &scenarios,
2246 &known,
2247 &wt_root,
2248 &project,
2249 &tmp,
2250 &before,
2251 &patch,
2252 &runner,
2253 &policy,
2254 ) {
2255 Ok(j) => {
2256 let failed_ids: Vec<String> =
2257 j.failed.iter().map(|s| s.id.clone()).collect();
2258 held_out_log.push(serde_json::json!({
2259 "attempt": held_out_log.len() + 1,
2260 "outcome": if failed_ids.is_empty() { "passed" } else { "failed" },
2261 "scenarios": failed_ids,
2262 }));
2263 if let Some(v) = report.verdict.take() {
2264 let mut v = speccoder_core::verify::with_held_out(v, &j.held_out);
2265 if let speccoder_core::verify::Verdict::Failed { reasons } = &mut v
2266 && !j.failed.is_empty()
2267 && let Some(last) = reasons.last_mut()
2268 {
2269 *last = speccoder_core::retry::held_out_reason(&j.failed);
2270 }
2271 report.verdict = Some(v);
2272 }
2273 }
2274 Err((outcome, why)) => {
2275 held_out_log.push(serde_json::json!({
2276 "attempt": held_out_log.len() + 1,
2277 "outcome": outcome,
2278 }));
2279 report.verdict = None;
2280 report.reason = Some(why);
2281 attempt_status = "held_out".to_owned();
2282 }
2283 }
2284 }
2285 if let Some(fix) = bug_fix.as_mut().filter(|_| {
2288 attempt_status == "completed"
2289 && findings.is_empty()
2290 && matches!(
2291 report.verdict,
2292 Some(
2293 speccoder_core::verify::Verdict::Verified
2294 | speccoder_core::verify::Verdict::RegressionOnly
2295 )
2296 )
2297 }) {
2298 let keep = crate::strength::dir(&s.plane_dir, &feature_name, task);
2299 let judging = super::bug::Judging {
2300 before: &before,
2301 baseline: &baseline,
2302 verification: report.verification.as_ref(),
2303 base: report
2304 .verdict
2305 .clone()
2306 .unwrap_or(speccoder_core::verify::Verdict::RegressionOnly),
2307 keep: &keep,
2308 };
2309 match super::bug::judge(&bug_ctx, fix, &judging) {
2310 Ok(j) => {
2311 report.verdict = Some(j.verdict);
2312 if let Some(weak) = j.weak {
2313 report.reason = Some(format!(
2314 "reproduction too weak: a fix that special-cases {}'s input passes ({}); `speccoder task rule {task} --tests-right --reason …` if the tests are right",
2315 weak.scenario, weak.rationale
2316 ));
2317 bug_weak = Some(weak);
2318 attempt_status = "repro_weak".to_owned();
2319 }
2320 }
2321 Err(e) => {
2322 report.integrity.push(e.clone());
2323 report.reason = Some(e);
2324 report.verdict = None;
2325 attempt_status = "integrity".to_owned();
2326 }
2327 }
2328 }
2329 if let Some(h) = report
2330 .acceptance
2331 .as_mut()
2332 .and_then(|a| a.get_mut("held_out"))
2333 .filter(|h| h["state"] == "on")
2334 {
2335 let failed = held_out_log
2336 .iter()
2337 .filter(|o| o["outcome"] == "failed")
2338 .count();
2339 h["attempts"] = serde_json::json!(held_out_log);
2340 h["gap"] = serde_json::json!(failed > 0);
2341 }
2342
2343 let passing = attempt_status == "completed"
2345 && matches!(
2346 report.verdict,
2347 Some(
2348 speccoder_core::verify::Verdict::Verified
2349 | speccoder_core::verify::Verdict::RegressionOnly
2350 )
2351 );
2352 if passing && mutation_config.as_ref().is_none_or(|m| !m.suite) {
2353 stage(
2354 &*live,
2355 task,
2356 Stage::Mutation,
2357 StageState::Skipped,
2358 Some(if mutation_config.is_none() {
2359 "not configured".to_owned()
2360 } else {
2361 "suite = false: for acceptance strength only".to_owned()
2362 }),
2363 None,
2364 );
2365 }
2366 if let Some(m) = mutation_config.as_ref().filter(|m| passing && m.suite) {
2367 let began = std::time::Instant::now();
2368 stage(
2369 &*live,
2370 task,
2371 Stage::Mutation,
2372 StageState::Started,
2373 None,
2374 None,
2375 );
2376 let patch = worktree::patch(&wt_root, &before, &after).unwrap_or_default();
2377 let scratch = runner.scratch().unwrap_or_else(|| tmp.clone());
2378 if let Some(result) = mutation::run(m, &project, &patch, &scratch, &runner) {
2379 if m.mode == mutation::Mode::Require
2380 && let Some(reason) = mutation::failure(&result)
2381 {
2382 report.verdict = Some(speccoder_core::verify::Verdict::Failed {
2383 reasons: vec![reason],
2384 });
2385 }
2386 report.mutation = Some(result);
2387 }
2388 let held = !matches!(
2389 report.verdict,
2390 Some(speccoder_core::verify::Verdict::Failed { .. })
2391 );
2392 stage(
2393 &*live,
2394 task,
2395 Stage::Mutation,
2396 if held {
2397 StageState::Passed
2398 } else {
2399 StageState::Failed
2400 },
2401 report
2402 .mutation
2403 .as_ref()
2404 .and_then(crate::mutation::trailer)
2405 .map(|t| t.trim().trim_start_matches("Mutation: ").to_owned()),
2406 Some(began),
2407 );
2408 }
2409
2410 usage = add_usage(usage.as_ref(), report.usage.as_ref());
2411 let (Some(speccoder_core::verify::Verdict::Failed { reasons }), Some(verification)) =
2413 (report.verdict.clone(), report.verification.as_ref())
2414 else {
2415 break (report, attempt_status);
2416 };
2417 if attempt_status != "completed" {
2418 break (report, attempt_status);
2419 }
2420 let discarded: Vec<String> = report.changes.iter().map(|(p, _)| p.clone()).collect();
2421 let mut d =
2422 speccoder_core::retry::digest(attempt_no, &reasons, verification, &discarded);
2423 d.uncollected = report
2424 .collection
2425 .as_ref()
2426 .map(speccoder_core::collection::Collection::retry_lines)
2427 .unwrap_or_default();
2428 let fingerprint = speccoder_core::retry::fingerprint(&d);
2429 let stop = if bug_candidate.is_some() {
2430 Some("a candidate is judged, never retried".to_owned())
2431 } else {
2432 retry_stop(
2433 &findings,
2434 verification,
2435 earlier.last().map(|e| e.fingerprint.as_str()),
2436 &fingerprint,
2437 attempt_no,
2438 run_config.max_attempts,
2439 )
2440 };
2441 if let Some(stop) = stop {
2442 report.retry_stop = Some(stop);
2443 break (report, attempt_status);
2444 }
2445 if let Err(e) = worktree::restore(&wt_root, &tmp, &before) {
2446 report.retry_stop = Some(format!("cannot undo the attempt: {}", e.0));
2447 break (report, attempt_status);
2448 }
2449 earlier.push(speccoder_core::EarlierAttempt {
2450 run_id: report.run_id.clone(),
2451 attempt_status: attempt_status.clone(),
2452 verdict: report.verdict.clone(),
2453 fingerprint,
2454 digest: d.clone(),
2455 usage: report.usage.clone(),
2456 });
2457 digest = serde_json::to_value(&d).ok();
2458 attempt_no += 1;
2459 };
2460 report.earlier = earlier;
2461 if run_config.best_of <= 1 {
2462 break (report, attempt_status);
2463 }
2464 let end = match worktree::checkpoint(&wt_root, &tmp) {
2465 Ok(c) => c,
2466 Err(e) => return fail(CommandStatus::GitPrecondition, e.0),
2467 };
2468 let patch = worktree::patch(&wt_root, &before, &end).unwrap_or_default();
2469 let summary = sample_summary(&report, &attempt_status, &patch);
2470 samples.push((report, attempt_status, end, summary));
2471 if samples.len() >= run_config.best_of as usize {
2472 let best = best_sample(&samples);
2473 let summaries: Vec<serde_json::Value> = samples
2474 .iter()
2475 .enumerate()
2476 .map(|(i, s)| {
2477 let mut v = s.3.clone();
2478 v["kept"] = serde_json::json!(i == best);
2479 v
2480 })
2481 .collect();
2482 let (mut chosen, status, end, _) = samples.swap_remove(best);
2483 if best != samples.len() {
2484 if let Err(e) = worktree::restore(&wt_root, &tmp, &end) {
2486 return fail(CommandStatus::GitPrecondition, e.0);
2487 }
2488 }
2489 chosen.samples = summaries;
2490 break (chosen, status);
2491 }
2492 if let Err(e) = worktree::restore(&wt_root, &tmp, &before) {
2493 return fail(CommandStatus::GitPrecondition, e.0);
2494 }
2495 };
2496 report.usage = usage;
2497 {
2500 use speccoder_core::context::ContextKind as K;
2501 let part = |k: &str| {
2502 bundle_value[k]
2503 .as_str()
2504 .unwrap_or_default()
2505 .as_bytes()
2506 .to_vec()
2507 };
2508 let mut m = crate::context::Manifest::new();
2509 m.push(
2510 K::Constitution,
2511 "worktree",
2512 "/bundle/constitution",
2513 &part("constitution"),
2514 )
2515 .push(K::Plan, "worktree", "/bundle/plan", &part("plan"))
2516 .push(K::Story, "worktree", "/bundle/story", &part("story"))
2517 .push(
2518 K::Task,
2519 "worktree",
2520 "/bundle/task",
2521 serde_json::to_string(&bundle_value["task"])
2522 .unwrap_or_default()
2523 .as_bytes(),
2524 )
2525 .push(
2526 K::TestLayout,
2527 "worktree",
2528 "/test_layout",
2529 test_layout_text.as_bytes(),
2530 );
2531 report.context = Some(m.finish());
2532 }
2533 report.scope = parsed_task.as_ref().map(|t| scope_of(&report, &t.title));
2535
2536 let strength_dir = crate::strength::dir(&s.plane_dir, &feature_name, task);
2540 let mut attempt_status = attempt_status;
2541 let verified = attempt_status == "completed"
2542 && matches!(
2543 report.verdict,
2544 Some(speccoder_core::verify::Verdict::Verified)
2545 );
2546 let visible_argv = acceptance
2547 .as_ref()
2548 .filter(|a| a.red)
2549 .and_then(|a| a.argv.clone());
2550 if verified && !run_config.strength.enabled {
2551 stage(
2552 &*live,
2553 task,
2554 Stage::Strength,
2555 StageState::Skipped,
2556 Some("strength = false".to_owned()),
2557 None,
2558 );
2559 }
2560 if let Some(argv) = visible_argv.filter(|_| verified && run_config.strength.enabled) {
2561 use speccoder_core::strength::{Gate, gate, over_strict};
2562 let began = std::time::Instant::now();
2563 stage(
2564 &*live,
2565 task,
2566 Stage::Strength,
2567 StageState::Started,
2568 None,
2569 None,
2570 );
2571 let fin = worktree::checkpoint(&wt_root, &tmp);
2572 let patch = fin
2573 .as_ref()
2574 .ok()
2575 .and_then(|now| worktree::patch(&wt_root, &start, now).ok())
2576 .unwrap_or_default();
2577 let mut notes = Vec::new();
2578 let held: Vec<(crate::held_out::HeldOutFile, String)> =
2579 match acceptance.as_ref().and_then(|a| a.held_out.clone()) {
2580 None => Vec::new(),
2581 Some(sha) => match crate::held_out::load_verified(&held_out_store, &sha) {
2582 Ok((manifest, contents)) => manifest
2583 .files
2584 .into_iter()
2585 .zip(contents.into_iter().map(|(_, c)| c))
2586 .collect(),
2587 Err(t) => {
2588 notes.push(format!("held-out set not overlaid: {}", t.0));
2589 Vec::new()
2590 }
2591 },
2592 };
2593 let rulings = crate::strength::rulings(&strength_dir);
2594 let mut commands = vec![argv];
2595 let measure = |commands: &[Vec<String>]| {
2596 crate::strength::measure(
2597 &crate::strength::Setup {
2598 wt_root: &wt_root,
2599 project: &project,
2600 tmp: &tmp,
2601 runner: &runner,
2602 policy: &policy,
2603 acceptance: commands,
2604 held_out: &held,
2605 mutation: mutation_config.as_ref(),
2606 patch: &patch,
2607 config: &run_config.strength,
2608 keep: &strength_dir,
2609 rulings: &rulings,
2610 },
2611 |changed| {
2612 let input = substrate::near_miss::input(
2614 &bundle_value,
2615 changed,
2616 &crate::mutation::source_patch(&patch),
2617 run_config.strength.near_miss,
2618 run_config.strength.permitted,
2619 );
2620 match rt.block_on(plane.near_miss(&feature_name, task, input)) {
2621 Ok(o) => {
2622 let out = o
2623 .output
2624 .as_ref()
2625 .map(|v| v.peek().clone())
2626 .unwrap_or_default();
2627 let ok = matches!(o.status, agentplane::prelude::RunStatus::Succeeded)
2628 && !out["answer"].is_null();
2629 crate::strength::Authored {
2630 answer: if ok {
2631 Ok(out["answer"].clone())
2632 } else {
2633 Err(format!(
2634 "the variant author did not answer ({})",
2635 o.status.as_str()
2636 ))
2637 },
2638 run_id: Some(o.run_id.to_string()),
2639 usage: Some(out["usage"].clone()).filter(|u| !u.is_null()),
2640 }
2641 }
2642 Err(e) => crate::strength::Authored {
2643 answer: Err(redact(&e.0, secret)),
2644 run_id: None,
2645 usage: None,
2646 },
2647 }
2648 },
2649 )
2650 };
2651 let mut measured = measure(&commands);
2652 let min = run_config.strength.min;
2655 if let (Ok(a), Ok(fin)) = (&measured, &fin)
2656 && gate(min, &a.combined, false) == Gate::Failed
2657 && over_strict(&a.permitted).is_empty()
2658 {
2659 let visible_tests: Vec<(String, String)> = report
2660 .acceptance
2661 .as_ref()
2662 .and_then(|a| a["files"].as_array().cloned())
2663 .unwrap_or_default()
2664 .iter()
2665 .filter_map(|p| p.as_str())
2666 .map(|p| {
2667 (
2668 p.to_owned(),
2669 std::fs::read_to_string(project.join(p)).unwrap_or_default(),
2670 )
2671 })
2672 .collect();
2673 let setup = AcceptanceSetup {
2674 rt: &rt,
2675 plane: &plane,
2676 project: &project,
2677 worktree: &wt_root,
2678 tmp: &tmp,
2679 policy: &policy,
2680 feature: &feature_name,
2681 task,
2682 bundle: bundle_value.clone(),
2683 scenarios: &scenarios,
2684 instructions: &instructions,
2685 runner: &runner,
2686 layout: Some(&test_layout),
2687 story_files: &story_files,
2688 };
2689 let weak = crate::strength::weak(a);
2690 match strengthen(&setup, &visible_tests, weak, &before, fin) {
2691 Ok(added) => {
2692 if let Some(acc) = report.acceptance.as_mut() {
2693 if let Some(files) = acc["files"].as_array_mut() {
2694 files.extend(added.files.iter().map(|f| serde_json::json!(f)));
2695 }
2696 acc["strengthened"] = serde_json::json!({
2697 "files": added.files,
2698 "argv": added.argv,
2699 "run_id": added.report["run_id"],
2700 "usage": added.report["usage"],
2701 });
2702 }
2703 report.usage = add_usage(report.usage.as_ref(), Some(&added.report["usage"]));
2704 commands.push(added.argv);
2705 let mut again = measure(&commands);
2706 if let Ok(b) = again.as_mut() {
2707 b.gate = gate(min, &b.combined, true);
2708 b.notes.insert(
2709 0,
2710 "strengthened once with added acceptance tests".to_owned(),
2711 );
2712 }
2713 measured = again;
2714 }
2715 Err(why) => {
2716 if let Ok(a) = measured.as_mut() {
2717 a.notes
2718 .insert(0, format!("could not strengthen the set: {why}"));
2719 }
2720 }
2721 }
2722 }
2723 match measured {
2724 Ok(mut a) => {
2725 if a.gate == Gate::Off {
2726 a.gate = gate(min, &a.combined, false);
2727 }
2728 a.notes.extend(notes);
2729 let findings = over_strict(&a.permitted);
2730 if !findings.is_empty() {
2731 attempt_status = "over_strict".to_owned();
2732 report.reason = Some(format!(
2733 "an acceptance test rejects an implementation the spec appears to allow: {}",
2734 findings
2735 .iter()
2736 .map(|p| format!("{} ({})", p.scenario, p.rationale))
2737 .collect::<Vec<_>>()
2738 .join("; ")
2739 ));
2740 } else if a.gate == Gate::Failed {
2741 attempt_status = "acceptance_weak".to_owned();
2742 report.reason = Some(format!(
2743 "acceptance set too weak: strength {} is below min_strength {}{}",
2744 speccoder_core::strength::summary(&a.combined, None),
2745 min.unwrap_or_default(),
2746 a.notes
2747 .first()
2748 .map(|n| format!(" ({n})"))
2749 .unwrap_or_default()
2750 ));
2751 } else {
2752 crate::strength::release(&strength_dir);
2753 }
2754 report.usage = add_usage(report.usage.as_ref(), a.usage.as_ref());
2756 report.strength = Some(a);
2757 }
2758 Err(e) => {
2759 report.integrity.push(e.clone());
2760 report.reason = Some(e);
2761 report.verdict = None;
2762 attempt_status = "integrity".to_owned();
2763 }
2764 }
2765 report.attempt_status.clone_from(&attempt_status);
2766 let held_up = attempt_status == "completed";
2767 stage(
2768 &*live,
2769 task,
2770 Stage::Strength,
2771 if held_up {
2772 StageState::Passed
2773 } else {
2774 StageState::Failed
2775 },
2776 report.strength.as_ref().map(|a| {
2777 speccoder_core::strength::summary(&a.combined, a.notes.first().map(String::as_str))
2778 }),
2779 Some(began),
2780 );
2781 }
2782
2783 let verdict_passed = attempt_status == "completed"
2787 && matches!(
2788 report.verdict,
2789 Some(
2790 speccoder_core::verify::Verdict::Verified
2791 | speccoder_core::verify::Verdict::RegressionOnly
2792 )
2793 );
2794 let mut suspected = false;
2795 if !run_config.monitor && verdict_passed {
2796 stage(
2797 &*live,
2798 task,
2799 Stage::Monitor,
2800 StageState::Skipped,
2801 Some("not enabled".to_owned()),
2802 None,
2803 );
2804 }
2805 if run_config.monitor && verdict_passed {
2806 let began = std::time::Instant::now();
2807 stage(
2808 &*live,
2809 task,
2810 Stage::Monitor,
2811 StageState::Started,
2812 None,
2813 None,
2814 );
2815 let patch = worktree::checkpoint(&wt_root, &tmp)
2816 .and_then(|now| worktree::patch(&wt_root, &start, &now))
2817 .unwrap_or_default();
2818 let calls: Vec<serde_json::Value> = report
2819 .tool_calls
2820 .iter()
2821 .map(|c| {
2822 let tool = c["tool"].as_str().unwrap_or_default();
2823 serde_json::json!({ "tool": tool, "target": progress::target(tool, &c["arguments"]), "decision": c["decision"] })
2824 })
2825 .collect();
2826 let input = substrate::monitor::input(&bundle_value, &patch, &calls, &frozen);
2827 let (monitor, suspicion) = monitor_attempt(&rt, &plane, &feature_name, task, input, secret);
2828 report.monitor = Some(monitor);
2829 suspected = suspicion;
2830 stage(
2831 &*live,
2832 task,
2833 Stage::Monitor,
2834 if suspected {
2835 StageState::Failed
2836 } else {
2837 StageState::Passed
2838 },
2839 suspected.then(|| "suspects gaming".to_owned()),
2840 Some(began),
2841 );
2842 }
2843
2844 let in_place_stop = options
2847 .session
2848 .as_ref()
2849 .filter(|_| verdict_passed && !suspected)
2850 .and_then(|s| {
2851 s.lock()
2852 .ok()
2853 .and_then(|s| s.check_before_tick(&policy).err())
2854 });
2855 if let Some(e) = &in_place_stop {
2856 report.reason = Some(e.line());
2857 report.verdict = None;
2858 attempt_status = e.code.to_lowercase().replace('-', "_");
2860 report.attempt_status.clone_from(&attempt_status);
2861 }
2862 let passed = verdict_passed && !suspected && in_place_stop.is_none();
2863 if passed
2867 && matches!(
2868 report.verdict,
2869 Some(speccoder_core::verify::Verdict::RegressionOnly)
2870 )
2871 {
2872 use speccoder_core::regression::{Regression, RegressionFacts, RegressionReason, decide};
2873 let facts = RegressionFacts {
2874 acceptance_on: run_config.acceptance,
2875 story: acceptance_story
2877 .clone()
2878 .or_else(|| bug_fix.as_ref().map(|f| f.bug.requirement.clone()))
2879 .or_else(|| parsed_task.as_ref().and_then(|t| t.story.clone())),
2880 scenarios: scenarios.len(),
2881 skip: acceptance.as_ref().and_then(|a| a.skip_cause.clone()),
2882 red_class: acceptance.as_ref().and_then(|a| {
2884 if a.red
2885 && report
2886 .acceptance
2887 .as_ref()
2888 .is_some_and(|r| r["green_flaky"] == true)
2889 {
2890 Some(speccoder_core::verify::RedClass::Flaky)
2891 } else {
2892 a.red_class
2893 }
2894 }),
2895 };
2896 let mut reason = if planning.is_some() {
2897 RegressionReason::PlanningWork
2898 } else {
2899 decide(&facts)
2900 };
2901 if matches!(reason, RegressionReason::AlreadyPassing { .. })
2904 && bug_fix.is_none()
2905 && let Some(a) = acceptance.as_ref()
2906 && let Some(argv) = a.argv.as_ref()
2907 {
2908 let mut files: Vec<(String, String)> = a.report["files"]
2909 .as_array()
2910 .into_iter()
2911 .flatten()
2912 .filter_map(|f| f.as_str())
2913 .filter_map(|f| {
2914 std::fs::read_to_string(project.join(f))
2915 .ok()
2916 .map(|c| (f.to_owned(), c))
2917 })
2918 .collect();
2919 let prefix = project
2920 .strip_prefix(&wt_root)
2921 .map(|p| p.to_string_lossy().replace('\\', "/"))
2922 .unwrap_or_default();
2923 let mut command = Some(argv.clone());
2926 if a.report["appended"] == true
2927 && let Some(story) = a.report["story_file"].as_str()
2928 {
2929 let at = if prefix.is_empty() {
2930 story.to_owned()
2931 } else {
2932 format!("{prefix}/{story}")
2933 };
2934 let old = crate::git::Git::at(&wt_root)
2935 .run(&["show", &format!("HEAD:{at}")])
2936 .map(|b| String::from_utf8_lossy(&b).into_owned())
2937 .unwrap_or_default();
2938 command = None;
2939 if let Some((_, content)) = files.iter_mut().find(|(f, _)| f == story)
2940 && let Some(added) = content.strip_prefix(old.as_str()).map(str::to_owned)
2941 {
2942 command = super::bisect::section_command(argv, story, &added);
2943 let imports: String = old
2944 .lines()
2945 .filter(|l| {
2946 let t = l.trim_start();
2947 ["use ", "import ", "from ", "package ", "extern crate "]
2948 .iter()
2949 .any(|k| t.starts_with(k))
2950 })
2951 .map(|l| format!("{l}\n"))
2952 .collect();
2953 *content = format!("{imports}{added}");
2954 }
2955 }
2956 let timeout = std::fs::read_to_string(project.join(crate::verify::config::FILE))
2957 .ok()
2958 .and_then(|t| crate::verify::config::parse(&t).ok())
2959 .and_then(|cs| {
2960 cs.into_iter()
2961 .filter(|c| c.tier == crate::verify::config::Tier::Fast)
2962 .map(|c| c.timeout)
2963 .max()
2964 })
2965 .unwrap_or(std::time::Duration::from_secs(600));
2966 let found = match &command {
2967 Some(argv) => super::bisect::search(&super::bisect::Search {
2968 repo: &wt_root,
2969 prefix: &prefix,
2970 feature: &feature_name,
2971 task,
2972 files: &files,
2973 argv,
2974 scratch: &s.plane_dir.join("tmp"),
2975 sandbox: &sandbox_config,
2976 timeout,
2977 worktree: &worktree_config,
2978 checkout: Path::new(&s.snapshot.root),
2979 state: Some(state),
2980 }),
2981 None => super::bisect::Found {
2983 implemented_by: None,
2984 runs: 0,
2985 },
2986 };
2987 live.event(&progress::Event::RegressionBisected {
2988 task: task.to_owned(),
2989 runs: found.runs,
2990 result: found.implemented_by.as_ref().map(|i| match i {
2991 speccoder_core::regression::ImplementedBy::Task { task, .. } => task.clone(),
2992 speccoder_core::regression::ImplementedBy::BeforeFeature { .. } => {
2993 "before_feature".to_owned()
2994 }
2995 }),
2996 });
2997 reason = RegressionReason::AlreadyPassing {
2998 implemented_by: found.implemented_by,
2999 };
3000 }
3001 report.regression = Some(Regression::of(reason));
3002 }
3003 if passed && let (Some(t), Some(file)) = (&parsed_task, &tasks_file) {
3004 let began = std::time::Instant::now();
3005 stage(&*live, task, Stage::Commit, StageState::Started, None, None);
3006 let message = tick_message(&TickFacts {
3007 feature: &feature_name,
3008 task,
3009 title: &t.title,
3010 report: &report,
3011 red: acceptance
3012 .as_ref()
3013 .and_then(|a| a.red_class.filter(|c| a.red && c.is_red())),
3014 checklists_overridden,
3015 extra: bug_fix
3016 .as_ref()
3017 .map(|f| {
3018 super::bug::trailers(
3019 f,
3020 &report
3021 .verdict
3022 .as_ref()
3023 .map(super::outcome::verdict_word)
3024 .unwrap_or_default(),
3025 &crate::strength::rulings(&strength_dir),
3026 )
3027 })
3028 .or_else(|| review_frozen.as_ref().map(|(r, m)| r.trailer(m)))
3030 .unwrap_or_default(),
3031 });
3032 match &options.session {
3033 None => {
3035 match format.tick(file, task, &t.line_hash) {
3036 Ok(()) => report.ticked = true,
3037 Err(e) => report.integrity.push(format!("tick refused: {e}")),
3038 }
3039 if report.ticked && run_config.commit_per_task {
3040 match commit_attempt(&wt_root, &message) {
3041 Ok(id) => report.commit = Some(id),
3042 Err(e) => report.integrity.push(format!("commit failed: {e}")),
3043 }
3044 }
3045 }
3046 Some(session) => {
3049 let digest =
3050 crate::in_place::intent_digest(&project, &policy, format.messages().tasks_file);
3051 if let Ok(mut s) = session.lock() {
3052 let done = s.commit_and_tick(
3053 &plane_dir,
3054 file,
3055 &t.line_hash,
3056 &message,
3057 &digest,
3058 || format.tick(file, task, &t.line_hash),
3059 );
3060 report.ticked = done.ticked;
3061 report.commit = done.commit;
3062 report.integrity.extend(done.problems);
3063 }
3064 }
3065 }
3066 report.instructions = attempt_instructions
3067 .iter()
3068 .map(|i| speccoder_core::InstructionFile {
3069 path: i.path.clone(),
3070 sha256: i.sha256.clone(),
3071 bytes: i.bytes,
3072 cut: i.cut,
3073 })
3074 .collect();
3075 if let Some(commit) = report
3077 .commit
3078 .clone()
3079 .filter(|_| report.ticked && run_config.attest.enabled)
3080 {
3081 let verdict = report
3082 .verdict
3083 .as_ref()
3084 .map(super::outcome::verdict_word)
3085 .unwrap_or_default();
3086 let sandboxed = sandbox_config.mode != sandbox::Mode::Off && sandbox::backend().is_ok();
3087 let feature_dir = snap
3088 .feature
3089 .as_ref()
3090 .map(|f| f.feature.dir.clone())
3091 .unwrap_or_default();
3092 let requirements = format.requirement_ids(Path::new(&snap.root), &feature_dir);
3093 let tick = crate::attest::Tick {
3094 repo: &wt_root,
3095 config: &config_text,
3096 attest: &run_config.attest,
3097 format: &format!("{:?}", format.kind()).to_lowercase(),
3098 feature: &feature_name,
3099 feature_dir: &feature_dir,
3100 task,
3101 title: &t.title,
3102 line_hash: &t.line_hash,
3103 section: t.story.as_deref(),
3104 section_text: bundle_value["story"].as_str().unwrap_or_default(),
3105 requirements: &requirements,
3106 commit: &commit,
3107 verdict: &verdict,
3108 sandbox: serde_json::json!({
3109 "mode": format!("{:?}", sandbox_config.mode).to_lowercase(),
3110 "backend": sandboxed.then_some(if cfg!(target_os = "macos") { "seatbelt" } else { "landlock" }),
3111 "network": format!("{:?}", sandbox_config.network).to_lowercase(),
3112 }),
3113 executor: serde_json::json!({
3114 "kind": if bug_candidate.is_some() { "candidate".to_owned() } else { executor.as_ref().map_or_else(|| "native".to_owned(), |e| e.kind.name().to_owned()) },
3115 "candidate": bug_candidate.as_ref().map(|(_, c)| serde_json::json!({ "origin": c.origin, "digest": c.digest, "head_sha": c.head_sha })),
3116 }),
3117 model: serde_json::json!({ "provider": s.model.provider, "model": s.model.model }),
3118 bug: bug_fix
3119 .as_ref()
3120 .map(|f| super::bug::predicate_fields(&f.bug, &f.record)),
3121 };
3122 report.attestation = Some(crate::attest::record_tick(&tick, &report));
3123 }
3124 let committed = report.ticked && (report.commit.is_some() || !run_config.commit_per_task);
3125 stage(
3126 &*live,
3127 task,
3128 Stage::Commit,
3129 if committed {
3130 StageState::Passed
3131 } else {
3132 StageState::Failed
3133 },
3134 report.commit.as_ref().map(|c| c.chars().take(7).collect()),
3135 Some(began),
3136 );
3137 }
3138 if passed && let Some(n) = &native {
3141 let began = std::time::Instant::now();
3142 stage(&*live, task, Stage::Commit, StageState::Started, None, None);
3143 let verdict = report
3144 .verdict
3145 .as_ref()
3146 .map(super::outcome::verdict_word)
3147 .unwrap_or_default();
3148 let message = tick_message(&TickFacts {
3149 feature: &feature_name,
3150 task,
3151 title: &n.title,
3152 report: &report,
3153 red: acceptance
3154 .as_ref()
3155 .and_then(|a| a.red_class.filter(|c| a.red && c.is_red())),
3156 checklists_overridden: false,
3157 extra: bug_fix
3158 .as_ref()
3159 .map(|f| {
3160 super::bug::trailers(f, &verdict, &crate::strength::rulings(&strength_dir))
3161 })
3162 .unwrap_or_default(),
3163 });
3164 match commit_attempt(&wt_root, &message) {
3165 Ok(id) => report.commit = Some(id),
3166 Err(e) => report.integrity.push(format!("commit failed: {e}")),
3167 }
3168 if let Some(commit) = report.commit.clone().filter(|_| run_config.attest.enabled) {
3169 let sandboxed = sandbox_config.mode != sandbox::Mode::Off && sandbox::backend().is_ok();
3170 let tick = crate::attest::Tick {
3171 repo: &wt_root,
3172 config: &config_text,
3173 attest: &run_config.attest,
3174 format: &format!("{:?}", format.kind()).to_lowercase(),
3175 feature: &feature_name,
3176 feature_dir: &n.dir,
3177 task,
3178 title: &n.title,
3179 line_hash: "",
3180 section: None,
3181 section_text: &n.story,
3182 requirements: &[],
3183 commit: &commit,
3184 verdict: &verdict,
3185 sandbox: serde_json::json!({
3186 "mode": format!("{:?}", sandbox_config.mode).to_lowercase(),
3187 "backend": sandboxed.then_some(if cfg!(target_os = "macos") { "seatbelt" } else { "landlock" }),
3188 "network": format!("{:?}", sandbox_config.network).to_lowercase(),
3189 }),
3190 executor: serde_json::json!({
3191 "kind": if bug_candidate.is_some() { "candidate" } else if executor.is_some() { "external" } else { "native" },
3192 }),
3193 model: serde_json::json!({ "provider": s.model.provider, "model": s.model.model }),
3194 bug: bug_fix
3195 .as_ref()
3196 .map(|f| super::bug::predicate_fields(&f.bug, &f.record)),
3197 };
3198 report.attestation = Some(crate::attest::record_tick(&tick, &report));
3199 }
3200 stage(
3201 &*live,
3202 task,
3203 Stage::Commit,
3204 if report.commit.is_some() {
3205 StageState::Passed
3206 } else {
3207 StageState::Failed
3208 },
3209 report.commit.as_ref().map(|c| c.chars().take(7).collect()),
3210 Some(began),
3211 );
3212 }
3213
3214 if attempt_status == "repro_weak"
3219 && let Some(weak) = &bug_weak
3220 && let Err(e) = crate::strength::hold(&strength_dir, &[weak])
3221 {
3222 report
3223 .integrity
3224 .push(format!("holding the attempt failed: {e}"));
3225 }
3226 if attempt_status == "over_strict" || attempt_status == "repro_weak" {
3227 let findings = report
3228 .strength
3229 .as_ref()
3230 .map(|a| speccoder_core::strength::over_strict(&a.permitted))
3231 .unwrap_or_default();
3232 if attempt_status == "over_strict"
3233 && let Err(e) = crate::strength::hold(&strength_dir, &findings)
3234 {
3235 report
3236 .integrity
3237 .push(format!("holding the attempt failed: {e}"));
3238 }
3239 marker_guard.keep();
3240 }
3241 if !passed && attempt_status != "over_strict" && attempt_status != "repro_weak" {
3244 let (outcome, reason) = saved_outcome(&report, &attempt_status, suspected);
3245 let run = (!report.run_id.is_empty()).then_some(report.run_id.as_str());
3246 let reason = redact(&reason, secret);
3247 let record = attempts::Record {
3248 run,
3249 outcome: &outcome,
3250 reason: &reason,
3251 pending: report.pending.as_ref(),
3252 usage: report.usage.as_ref(),
3253 };
3254 match attempts::save(&wt_root, &tmp, &feature_name, task, &record)
3255 .and_then(|saved| worktree::restore(&wt_root, &tmp, &start).map(|_| saved))
3256 {
3257 Ok(saved) => report.saved_attempt = Some(saved.reference),
3258 Err(e) => report
3259 .integrity
3260 .push(format!("saving the attempt failed: {}", e.0)),
3261 }
3262 }
3263
3264 let (status, mut message) = status_and_message(&report, &attempt_status, suspected);
3265 if status == CommandStatus::RunFailed
3268 && let Some(region) = s.model.region.as_deref()
3269 && report
3270 .reason
3271 .as_deref()
3272 .and_then(substrate::provider_refusal)
3273 .is_some()
3274 {
3275 message.push_str(&format!(
3276 " — Amazon Bedrock, region {region}, model {}",
3277 s.model.model
3278 ));
3279 }
3280 let refusal = |result: CommandResult| {
3283 if !result.has_explicit_code()
3284 && refused_account
3285 && result.status() == CommandStatus::RunFailed
3286 {
3287 result.with_code("PROVIDER-REFUSED").with_fix(
3288 substrate::model_config::provider_refused_fix(
3289 &s.model,
3290 crate::aws::detect_here().as_ref(),
3291 feature,
3292 ),
3293 )
3294 } else {
3295 result
3296 }
3297 };
3298 if let Some(fix) = bug_fix.as_mut() {
3299 return refusal(super::bug::finished(
3300 &bug_ctx,
3301 fix,
3302 report,
3303 &attempt_status,
3304 passed,
3305 status,
3306 redact(&message, secret),
3307 ));
3308 }
3309 live.event(&finished_event(
3310 task,
3311 &report,
3312 &attempt_status,
3313 suspected,
3314 redact(&message, secret),
3315 ));
3316 let code = collection_code(&report, &attempt_status);
3317 let result = CommandResult::new("run", status, &redact(&message, secret));
3318 match code {
3319 Some(c) => result.with_code(c),
3320 None => refusal(result),
3321 }
3322 .with_data(CommandData::Run(Box::new(report)))
3323}
3324
3325fn collection_code(
3328 report: &speccoder_core::RunReport,
3329 attempt_status: &str,
3330) -> Option<&'static str> {
3331 if attempt_status == "collection_unknown" {
3332 return Some("TESTS-COLLECTION-UNKNOWN");
3333 }
3334 match &report.verdict {
3335 Some(speccoder_core::verify::Verdict::Failed { reasons })
3336 if reasons
3337 .first()
3338 .is_some_and(|r| r.starts_with(speccoder_core::collection::REASON_PREFIX)) =>
3339 {
3340 Some("TESTS-NOT-COLLECTED")
3341 }
3342 _ => None,
3343 }
3344}
3345
3346enum Collected {
3352 Unknown(String),
3354 Changed(String),
3356}
3357
3358fn judge_collection(
3359 dirs: (&Path, &Path, &Path),
3360 runner: &sandbox::Runner,
3361 otherwise_passing: bool,
3362 report: &mut speccoder_core::RunReport,
3363 live: &dyn progress::Progress,
3364 task: &str,
3365) -> Option<Collected> {
3366 let (project, wt_root, tmp) = dirs;
3367 let before = worktree::checkpoint(wt_root, tmp).ok();
3369 let checks = std::fs::read_to_string(project.join(crate::verify::config::FILE))
3370 .ok()
3371 .and_then(|t| crate::verify::config::parse(&t).ok())
3372 .unwrap_or_default()
3373 .into_iter()
3374 .filter(|c| c.tier == crate::verify::config::Tier::Fast)
3375 .collect::<Vec<_>>();
3376 let results = report
3377 .verification
3378 .as_ref()
3379 .map(|v| v.checks.clone())
3380 .unwrap_or_default();
3381 let c = crate::collection::judge(&crate::collection::Input {
3382 root: project,
3383 changes: &report.changes,
3384 checks: &checks,
3385 results: &results,
3386 runner,
3387 listings: otherwise_passing,
3388 })?;
3389 if !c.listing.is_empty()
3390 && let Some(before) = &before
3391 {
3392 let changed: Vec<String> = worktree::checkpoint(wt_root, tmp)
3393 .and_then(|after| worktree::diff(wt_root, before, &after))
3394 .map(|d| {
3395 d.into_iter()
3396 .map(|c| c.path)
3397 .filter(|p| !speccoder_core::collection::is_build_or_dependency(p))
3398 .collect()
3399 })
3400 .unwrap_or_else(|e| vec![format!("(the tree could not be read: {})", e.0)]);
3401 if !changed.is_empty() {
3402 report.collection = Some(c);
3403 return Some(Collected::Changed(format!(
3404 "integrity: a test listing changed the worktree: {}",
3405 changed.join(", ")
3406 )));
3407 }
3408 }
3409 live.event(&progress::Event::CollectionChecked {
3410 task: task.to_owned(),
3411 files: c
3412 .files
3413 .iter()
3414 .map(|f| progress::CollectionFile {
3415 path: f.path.clone(),
3416 state: f.state,
3417 decided_by: f.decided_by,
3418 })
3419 .collect(),
3420 });
3421 let never = c.reasons();
3422 let unknown: Vec<String> = c
3423 .unknown()
3424 .map(|f| {
3425 format!(
3426 "speccoder cannot tell whether the runner ran `{}` ({})",
3427 f.path,
3428 f.why.as_deref().unwrap_or("no report or listing names it")
3429 )
3430 })
3431 .collect();
3432 report.collection = Some(c);
3433 if !never.is_empty() {
3434 let mut reasons = never;
3435 if let Some(speccoder_core::verify::Verdict::Failed { reasons: more }) =
3436 report.verdict.take()
3437 {
3438 reasons.extend(more);
3439 }
3440 report.verdict = Some(speccoder_core::verify::Verdict::Failed { reasons });
3441 return None;
3442 }
3443 (otherwise_passing && !unknown.is_empty()).then(|| Collected::Unknown(unknown.join("; ")))
3444}
3445
3446fn with_cause(note: &str, c: &speccoder_core::verify::CheckResult) -> String {
3449 let said = c
3450 .stderr_tail
3451 .lines()
3452 .chain(c.stdout_tail.lines())
3453 .map(str::trim)
3454 .find(|l| l.starts_with("error"))
3455 .map(|l| l.chars().take(200).collect::<String>());
3456 let fix = match said.as_deref() {
3457 Some(l) if l.contains("profile `speccoder` not found") => Some(
3458 "`.config/nextest.toml` is not committed — `git add .config/nextest.toml && git commit -m \"speccoder: nextest profile\"`",
3459 ),
3460 Some(l) if l.contains("no tests to run") => Some(
3461 "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",
3462 ),
3463 Some(l) if l.contains("must be present") || l.contains("no targets") => Some(
3464 "the project has nothing to build yet; if the first task creates it, run with --allow-failing-baseline",
3465 ),
3466 _ => None,
3467 };
3468 match (said, fix) {
3469 (Some(s), Some(f)) => format!("{note} ({s}); {f}"),
3470 (Some(s), None) => format!("{note} ({s})"),
3471 _ => note.to_owned(),
3472 }
3473}
3474
3475#[must_use]
3479pub fn broken(c: &speccoder_core::verify::CheckResult) -> Option<String> {
3480 use speccoder_core::verify::CheckStatus;
3481 if !c.status.is_failure() || c.status == CheckStatus::TimedOut {
3482 return None;
3483 }
3484 if let Some(note) = &c.note {
3485 return Some(with_cause(note, c));
3486 }
3487 if c.tests.as_ref().is_some_and(|t| !t.is_empty()) {
3488 return None;
3489 }
3490 let summary = crate::verify::summary::parse(&c.stdout_tail, &c.stderr_tail, c.exit_code);
3491 let runner = c
3495 .argv
3496 .first()
3497 .map(|a| a.rsplit('/').next().unwrap_or(a))
3498 .is_some_and(|a| {
3499 matches!(
3500 a,
3501 "cargo"
3502 | "pytest"
3503 | "python"
3504 | "python3"
3505 | "uv"
3506 | "npm"
3507 | "npx"
3508 | "pnpm"
3509 | "yarn"
3510 | "bun"
3511 | "go"
3512 | "jest"
3513 | "vitest"
3514 | "mvn"
3515 | "gradle"
3516 | "dotnet"
3517 | "mix"
3518 | "swift"
3519 )
3520 });
3521 let cannot_start = matches!(c.exit_code, Some(126 | 127));
3522 let is_broken = match &summary {
3523 _ if cannot_start => true,
3524 Some(s) if s.build_failed => true,
3525 Some(s) => s.passed + s.failed + s.errors == 0,
3526 None => runner,
3527 };
3528 match is_broken {
3529 false => None,
3530 true => {
3531 let first = c
3532 .stderr_tail
3533 .lines()
3534 .chain(c.stdout_tail.lines())
3535 .map(str::trim)
3536 .find(|l| l.to_lowercase().contains("error"))
3537 .or_else(|| c.stderr_tail.lines().map(str::trim).find(|l| !l.is_empty()))
3538 .unwrap_or("it failed without running a test")
3539 .chars()
3540 .take(160)
3541 .collect::<String>();
3542 Some(first)
3543 }
3544 }
3545}
3546
3547fn login(
3551 fail: impl FnOnce(CommandStatus, String) -> CommandResult,
3552 shown: &str,
3553 agent: &crate::acp::agent::Agent,
3554 ways: &[crate::acp::session::SignIn],
3555) -> CommandResult {
3556 let words: Vec<String> = ways
3557 .iter()
3558 .filter(|w| w.command.is_none())
3559 .map(|w| {
3560 format!(
3561 "→ {}",
3562 w.description.clone().unwrap_or_else(|| w.name.clone())
3563 )
3564 })
3565 .collect();
3566 let mut commands: Vec<Vec<String>> = ways
3567 .iter()
3568 .filter_map(|w| w.command.as_deref())
3569 .map(|c| c.split_whitespace().map(str::to_owned).collect())
3570 .collect();
3571 if words.is_empty()
3572 && commands.is_empty()
3573 && let Some(p) = agent.preset()
3574 {
3575 commands.push(p.login.split_whitespace().map(str::to_owned).collect());
3576 }
3577 commands.dedup();
3578 let argvs: Vec<speccoder_core::step::Argvs> = commands.into_iter().map(|c| vec![c]).collect();
3579 let mut fix: Vec<String> = argvs
3580 .iter()
3581 .map(|a| speccoder_core::step::render(a))
3582 .collect();
3583 fix.extend(words);
3584 fix.push("speccoder doctor".to_owned());
3585 fail(
3586 CommandStatus::NeedsHuman,
3587 format!("{shown} needs signing in before it can make the attempt; nothing was attempted"),
3588 )
3589 .with_code("EXECUTOR-LOGIN")
3590 .with_fix(fix)
3591 .with_commands(argvs)
3592}