1use std::path::Path;
10use std::time::Instant;
11
12use serde_json::{Value, json};
13use speccoder_core::bug::{
14 self as rules, Basis, BugReport, Final, HeldOutVariant, Outcome, PassToPass, Reproduce,
15 ReproduceTry, Reproduction, Revert, RevertResult, Source, SpecialCase, Stage as BugStage,
16 TryStatement,
17};
18use speccoder_core::context::ContextKind;
19use speccoder_core::stage::{Stage, StageState};
20use speccoder_core::verify::{
21 CheckStatus, HeldOut, RedClass, Verdict, VerifyReport, classify_red, classify_red_one,
22};
23use speccoder_core::{CommandData, CommandResult, CommandStatus};
24
25use super::{AcceptanceSetup, PreparedAcceptance, ReusedTest, bare_report, class_word, stage};
26use crate::approvals::{Approver, ConfirmAnswer, ConfirmRequest, ShownReproduction};
27use crate::bug::{confirm, handoff, state};
28use crate::integrity::sha256_hex;
29use crate::progress::{BugEvent, Event, Progress};
30use crate::tools::policy::{Decision, Policy};
31use crate::{held_out, sandbox, substrate, tools, worktree};
32
33pub(crate) struct Ctx<'a> {
35 pub(crate) rt: &'a tokio::runtime::Runtime,
36 pub(crate) plane: &'a substrate::Plane,
37 pub(crate) project: &'a Path,
38 pub(crate) wt_root: &'a Path,
39 pub(crate) wt_path: &'a str,
40 pub(crate) tmp: &'a Path,
41 pub(crate) policy: &'a Policy,
42 pub(crate) runner: &'a sandbox::Runner,
43 pub(crate) state: &'a Path,
45 pub(crate) feature: &'a str,
46 pub(crate) task: &'a str,
47 pub(crate) bundle: &'a Value,
48 pub(crate) instructions: &'a [crate::instructions::Instruction],
49 pub(crate) live: &'a dyn Progress,
50 pub(crate) approver: Option<&'a dyn Approver>,
51 pub(crate) held_out: bool,
53 pub(crate) max_tries: u32,
55 pub(crate) bug_test: Option<&'a [String]>,
57 pub(crate) start: &'a worktree::Checkpoint,
59}
60
61pub(crate) struct Fix {
63 pub(crate) bug: BugReport,
64 pub(crate) record: speccoder_core::acceptance::PreFrozenAcceptance,
65 pub(crate) files: Vec<(String, String)>,
66}
67
68pub(crate) enum Phase {
70 Reproduce(Box<BugReport>),
72 Fix(Box<Fix>),
74}
75
76fn event(live: &dyn Progress, task: &str, step: BugEvent) {
77 live.event(&Event::Bug {
78 task: task.to_owned(),
79 step,
80 });
81}
82
83pub(crate) fn triad_now(
85 format: &dyn crate::format::Adapter,
86 project: &Path,
87 bug: &BugReport,
88) -> Result<rules::Triad, crate::format::BugRefusal> {
89 let key = if bug.home.kind.native() {
90 bug.task.trim_start_matches("bug:").to_owned()
91 } else {
92 bug.requirement.clone()
93 };
94 let read = format.read_bug(project, &bug.home, &key)?;
95 let current = read.current.first().cloned().unwrap_or_default();
96 rules::Triad::new(¤t, &read.expected, &read.unchanged, sha256_hex)
97 .map_err(|e| crate::format::BugRefusal::new(e.code(), e.message()))
98}
99
100pub(crate) fn phase(
103 plane: &Path,
104 feature: &str,
105 task: &str,
106 project: &Path,
107 format: &dyn crate::format::Adapter,
108) -> Result<Option<Phase>, String> {
109 let Some(mut bug) = state::load(plane, feature, task) else {
110 return Ok(None);
111 };
112 let now =
113 triad_now(format, project, &bug).map_err(|e| format!("{} ({})", e.message, e.code))?;
114 if now.digest != bug.triad.digest {
115 confirm::lapse(plane, &mut bug, now)?;
117 return Ok(Some(Phase::Reproduce(Box::new(bug))));
118 }
119 if bug
120 .confirmation
121 .as_ref()
122 .is_some_and(|c| c.current(&bug.triad.digest))
123 {
124 match crate::pre_frozen::load(plane, &bug.unit, &bug.requirement) {
125 Ok(Some((record, files)))
126 if speccoder_core::acceptance::current(&record, &bug.triad.digest) =>
127 {
128 return Ok(Some(Phase::Fix(Box::new(Fix { bug, record, files }))));
129 }
130 Ok(_) => {}
131 Err(t) => return Err(t.0),
132 }
133 }
134 if matches!(
136 bug.outcome,
137 Outcome::CannotReproduce | Outcome::AlreadySatisfied | Outcome::UnchangedNotHolding
138 ) {
139 bug.tries.clear();
140 bug.rejections.clear();
141 }
142 Ok(Some(Phase::Reproduce(Box::new(bug))))
143}
144
145pub(crate) fn scenarios(bug: &BugReport) -> Vec<speccoder_core::spec::ScenarioRef> {
147 bug.triad
148 .expected
149 .iter()
150 .map(|s| speccoder_core::spec::ScenarioRef {
151 id: s.id.clone(),
152 text: s.text.clone(),
153 })
154 .collect()
155}
156
157fn stop(
159 c: &Ctx<'_>,
160 mut bug: BugReport,
161 outcome: Outcome,
162 code: Option<&str>,
163 message: String,
164 began: Instant,
165) -> CommandResult {
166 let _ = worktree::restore(c.wt_root, c.tmp, c.start);
167 bug.outcome = outcome;
168 bug.stage = if outcome == Outcome::AwaitingConfirmation {
169 BugStage::Confirm
170 } else {
171 BugStage::Done
172 };
173 bug.code = code.map(str::to_owned);
174 if matches!(
175 outcome,
176 Outcome::CannotReproduce | Outcome::AlreadySatisfied | Outcome::UnchangedNotHolding
177 ) {
178 let cost = bug
179 .tries
180 .iter()
181 .filter_map(|t| t.usage.as_ref())
182 .fold(None, |acc: Option<Value>, u| {
183 super::add_usage(acc.as_ref(), Some(u))
184 });
185 bug.handoff = Some(handoff::compose(
186 &bug,
187 outcome,
188 u64::try_from(began.elapsed().as_millis()).unwrap_or(u64::MAX),
189 cost,
190 None,
191 ));
192 }
193 let next = handoff::next(&bug, outcome);
194 let _ = state::save(c.state, &bug);
195 event(
196 c.live,
197 c.task,
198 BugEvent::Outcome {
199 outcome: outcome.as_str().to_owned(),
200 verdict: None,
201 code: bug.code.clone(),
202 next: next.iter().map(|n| n.command.clone()).collect(),
203 },
204 );
205 let status = match outcome {
206 Outcome::AlreadySatisfied => CommandStatus::Ok,
207 _ => CommandStatus::NeedsHuman,
208 };
209 let mut report = bare_report(c.feature, c.task, c.wt_path, outcome.as_str());
210 report.reason = Some(message.clone());
211 report.bug = Some(Box::new(bug));
212 c.live.event(&super::finished_event(
213 c.task,
214 &report,
215 outcome.as_str(),
216 false,
217 message.clone(),
218 ));
219 let mut r = CommandResult::new("run", status, &message)
220 .with_next(next)
221 .with_data(CommandData::Run(Box::new(report)));
222 if let Some(code) = code {
223 r = r.with_code(code);
224 }
225 r
226}
227
228struct Authored {
230 path: String,
231 content: String,
232 statement: String,
233 test: String,
234 argv: Vec<String>,
235}
236
237fn configures_collection(rel: &str) -> bool {
241 let name = rel.rsplit('/').next().unwrap_or(rel);
242 matches!(
243 name,
244 "conftest.py"
245 | "__init__.py"
246 | "pytest.ini"
247 | "tox.ini"
248 | "setup.cfg"
249 | "pyproject.toml"
250 | "package.json"
251 | "Cargo.toml"
252 | "build.rs"
253 | "go.mod"
254 ) || [
255 "jest.config",
256 "jest.setup",
257 "vitest.config",
258 "vitest.setup",
259 "vite.config",
260 "vitest.workspace",
261 "karma.conf",
262 ".mocharc",
263 "babel.config",
264 ".babelrc",
265 ]
266 .iter()
267 .any(|p| name.starts_with(p))
268}
269
270fn validate(
276 answer: &Value,
277 want: &[String],
278 project: &Path,
279 policy: &Policy,
280 template: Option<&[String]>,
281) -> Result<Vec<Authored>, String> {
282 let protected = policy.protected();
283 let mut out: Vec<Authored> = Vec::new();
284 for f in answer["files"].as_array().into_iter().flatten() {
285 let path = f["path"].as_str().unwrap_or_default();
286 let rel = tools::paths::normalise(path).map_err(|e| format!("`{path}`: {}", e.0))?;
287 if !tools::paths::is_test_path(&rel) || protected.write_class(&rel).is_some() {
288 return Err(format!("wrote outside tests (`{rel}`)"));
289 }
290 if configures_collection(&rel) {
291 return Err(format!(
292 "`{rel}` configures how tests run: a reproduction is a test file"
293 ));
294 }
295 if project.join(&rel).exists() || out.iter().any(|a| a.path == rel) {
296 return Err(format!("`{rel}` already exists"));
297 }
298 let statement = f["statement"].as_str().unwrap_or_default().to_owned();
299 if !want.contains(&statement) || out.iter().any(|a| a.statement == statement) {
300 return Err(format!(
301 "`{rel}` cites `{statement}`: one test per statement asked for"
302 ));
303 }
304 let test = f["test"].as_str().unwrap_or_default().trim().to_owned();
305 if test.is_empty() {
306 return Err(format!("`{rel}` names no test"));
307 }
308 let argv = crate::bug::named::argv(project, &rel, &test, template).ok_or_else(|| {
311 format!(
312 "speccoder has no rule to run only `{test}` of `{rel}`; set `[bug] test` in speccoder.toml"
313 )
314 })?;
315 if policy.classify("run_command", &json!({ "argv": argv }), None) != Decision::Allow {
316 return Err(format!("`{}` is not an allowed command", argv.join(" ")));
317 }
318 out.push(Authored {
319 path: rel,
320 content: f["content"].as_str().unwrap_or_default().to_owned(),
321 statement,
322 test,
323 argv,
324 });
325 }
326 if let Some(missing) = want
327 .iter()
328 .find(|w| !out.iter().any(|a| a.statement == **w))
329 {
330 return Err(format!("no test for {missing}"));
331 }
332 Ok(out)
333}
334
335fn baseline_class(
339 c: &Ctx<'_>,
340 argv: &[String],
341 test: &str,
342 reproduces: bool,
343) -> (Vec<RedClass>, String) {
344 let (first, summary) = super::acceptance_run(c.project, argv, c.runner);
345 let one = classify_red_one(&first, summary.as_ref(), test);
346 let excerpt = handoff::cut(&format!("{}\n{}", first.stdout_tail, first.stderr_tail), 20);
347 if !reproduces || one != RedClass::Assertion {
348 return (vec![one], excerpt);
349 }
350 let (second, summary) = super::acceptance_run(c.project, argv, c.runner);
351 let two = classify_red_one(&second, summary.as_ref(), test);
352 (vec![one, rules::bug_class(one, Some(two))], excerpt)
353}
354
355fn manifest(
358 c: &Ctx<'_>,
359 bug: &BugReport,
360 issue: Option<&state::IssueText>,
361) -> speccoder_core::context::ContextManifest {
362 let mut m = crate::context::Manifest::new();
363 m.push(
364 ContextKind::Story,
365 "person",
366 "/triad",
367 bug.triad.canonical().as_bytes(),
368 )
369 .push(
370 ContextKind::Constitution,
371 "worktree",
372 "/bundle/constitution",
373 c.bundle["constitution"]
374 .as_str()
375 .unwrap_or_default()
376 .as_bytes(),
377 )
378 .push(
379 ContextKind::Plan,
380 "worktree",
381 "/bundle/plan",
382 c.bundle["plan"].as_str().unwrap_or_default().as_bytes(),
383 )
384 .push(
385 ContextKind::Task,
386 "worktree",
387 "/bundle/task",
388 c.bundle["task"].to_string().as_bytes(),
389 )
390 .push(
391 ContextKind::TestLayout,
392 "worktree",
393 "/test_layout",
394 crate::layout::text_at(c.project).as_bytes(),
395 );
396 for (i, r) in bug.rejections.iter().enumerate() {
397 m.push(
398 ContextKind::Rejection,
399 "person",
400 &format!("/rejections/{i}"),
401 r.reason.as_bytes(),
402 );
403 }
404 if let (Some(i), Some(issue)) = (bug.issue.as_ref(), issue) {
405 m.push(
406 ContextKind::Issue,
407 &format!("github:{}#{}", i.repo.clone().unwrap_or_default(), i.number),
408 &format!("#{}", i.number),
409 format!("{}\n{}", issue.title, issue.body).as_bytes(),
410 );
411 }
412 m.finish()
413}
414
415fn project_view(c: &Ctx<'_>) -> (Vec<String>, String) {
417 let setup = AcceptanceSetup {
418 rt: c.rt,
419 plane: c.plane,
420 project: c.project,
421 worktree: c.wt_root,
422 tmp: c.tmp,
423 policy: c.policy,
424 feature: c.feature,
425 task: c.task,
426 bundle: c.bundle.clone(),
427 scenarios: &[],
428 instructions: c.instructions,
429 runner: c.runner,
430 layout: None,
431 told: &[],
432 };
433 let files: Vec<String> = worktree::checkpoint(setup.worktree, setup.tmp)
434 .and_then(|cp| worktree::files(setup.worktree, &cp))
435 .unwrap_or_default()
436 .into_iter()
437 .take(400)
438 .collect();
439 let manifest = super::MANIFESTS
440 .iter()
441 .find_map(|m| {
442 std::fs::read_to_string(c.project.join(m))
443 .ok()
444 .map(|t| format!("{m}:\n{t}"))
445 })
446 .map(|t| t.chars().take(8192).collect::<String>())
447 .unwrap_or_default();
448 (files, manifest)
449}
450
451fn author(
453 c: &Ctx<'_>,
454 input: agentplane::core::Tainted<Value>,
455) -> Result<(Value, String, Option<Value>, Option<String>), String> {
456 let outcome =
457 c.rt.block_on(c.plane.acceptance(c.feature, c.task, input))
458 .map_err(|e| format!("the author call failed: {}", e.0))?;
459 let output = outcome
460 .output
461 .as_ref()
462 .map(|o| o.peek().clone())
463 .unwrap_or_default();
464 let answer = output["answer"].clone();
465 if !matches!(outcome.status, agentplane::prelude::RunStatus::Succeeded) || answer.is_null() {
466 return Err(format!(
467 "the author did not answer ({})",
468 crate::substrate::why_not(&outcome.status)
469 ));
470 }
471 let notes = answer["notes"].as_array().map(|n| {
472 n.iter()
473 .filter_map(Value::as_str)
474 .collect::<Vec<_>>()
475 .join(" ")
476 });
477 Ok((
478 answer,
479 outcome.run_id.to_string(),
480 Some(output["usage"].clone()).filter(|u| !u.is_null()),
481 notes,
482 ))
483}
484
485#[allow(clippy::too_many_lines)] pub(crate) fn reproduce(c: &Ctx<'_>, mut bug: BugReport) -> Result<Fix, Box<CommandResult>> {
491 let began = Instant::now();
492 stage(
493 c.live,
494 c.task,
495 Stage::Reproduce,
496 StageState::Started,
497 None,
498 None,
499 );
500 bug.stage = BugStage::Reproduce;
501 bug.max_tries = c.max_tries;
502 let extra = state::extra(c.state, &bug.unit, &bug.task);
503 let expected = bug.expected_ids();
504 let unchanged: Vec<String> = bug.triad.unchanged.iter().map(|s| s.id.clone()).collect();
505 let person: Vec<Reproduction> = bug
506 .reproductions
507 .iter()
508 .filter(|r| r.source == Source::Person)
509 .cloned()
510 .collect();
511 let want: Vec<String> = if person.is_empty() {
514 expected.iter().chain(&unchanged).cloned().collect()
515 } else {
516 unchanged.clone()
517 };
518 let statements = json!(bug.triad.statements().collect::<Vec<_>>());
519 let person_files = state::repro(
520 c.state,
521 &bug.unit,
522 &bug.task,
523 &person.iter().map(|r| r.file.clone()).collect::<Vec<_>>(),
524 );
525 let stop_now = |bug: BugReport, outcome, code, message: String| {
526 stage(
527 c.live,
528 c.task,
529 Stage::Reproduce,
530 if outcome == Outcome::AlreadySatisfied {
531 StageState::Passed
532 } else {
533 StageState::Failed
534 },
535 Some(outcome_word(outcome)),
536 Some(began),
537 );
538 Box::new(stop(c, bug, outcome, code, message, began))
539 };
540 let kept: Vec<(Reproduction, String)> = loop {
541 if u32::try_from(bug.tries.len()).unwrap_or(u32::MAX) >= c.max_tries.max(1) {
544 let saved = state::save(c.state, &bug);
545 match rules::decide_reproduce(&bug.tries, &expected, c.max_tries) {
546 Reproduce::Reproduced { .. } if bug.confirm_digest.is_some() && saved.is_ok() => {
548 let digest = bug.confirm_digest.clone().unwrap_or_default();
549 let message = format!(
550 "the reproductions wait for your confirmation (digest {digest}): speccoder bug confirm {} --digest {digest}",
551 bug.key()
552 );
553 return Err(Box::new(stop(
554 c,
555 bug,
556 Outcome::AwaitingConfirmation,
557 None,
558 message,
559 began,
560 )));
561 }
562 _ => {
563 let message = format!(
564 "cannot reproduce: the {} tries are used up ({} rejected); nothing is fixed",
565 bug.tries.len(),
566 bug.tries
567 .iter()
568 .filter(|t| t
569 .discarded
570 .as_deref()
571 .is_some_and(|d| d.starts_with("rejected")))
572 .count()
573 );
574 return Err(stop_now(
575 bug,
576 Outcome::CannotReproduce,
577 Some("BUG-CANNOT-REPRODUCE"),
578 message,
579 ));
580 }
581 }
582 }
583 let n = u32::try_from(bug.tries.len()).unwrap_or(u32::MAX) + 1;
584 let context = manifest(c, &bug, extra.issue.as_ref());
585 let rejections: Vec<String> = bug.rejections.iter().map(|r| r.reason.clone()).collect();
586 let mut t = ReproduceTry {
587 n,
588 per_statement: Vec::new(),
589 discarded: None,
590 run_id: None,
591 usage: None,
592 rejection: rejections.last().cloned(),
593 };
594 let mut this: Vec<(Reproduction, String)> = Vec::new();
595 for (r, (_, content)) in person.iter().zip(&person_files) {
597 let full = c.project.join(&r.file);
598 if !full.exists() {
599 if let Some(parent) = full.parent() {
600 let _ = std::fs::create_dir_all(parent);
601 }
602 let _ = std::fs::write(&full, content);
603 }
604 let (classes, excerpt) = baseline_class(c, &r.argv, &r.test, true);
605 let class = classes.last().copied().unwrap_or(RedClass::Unclassified);
606 t.per_statement.push(TryStatement {
607 statement: r.statement.clone(),
608 class,
609 excerpt: (class != RedClass::Assertion).then_some(excerpt),
610 });
611 let mut r = r.clone();
612 r.baseline = classes;
613 this.push((r, content.clone()));
614 }
615 if !want.is_empty() {
616 let (files, manifest_text) = project_view(c);
617 let layout_text = crate::layout::text_at(c.project);
618 let input =
619 substrate::acceptance::reproduce_input(&substrate::acceptance::ReproduceParts {
620 set: "reproduce",
621 bundle: c.bundle.clone(),
622 statements: statements.clone(),
623 want: &want,
624 files: &files,
625 manifest: &manifest_text,
626 visible: &[],
627 rejections: &rejections,
628 issue: extra
629 .issue
630 .as_ref()
631 .map(|i| (i.title.as_str(), i.body.as_str())),
632 instructions: c.instructions,
633 context: &context,
634 test_layout: Some(&layout_text),
635 });
636 match author(c, input) {
637 Err(why) => t.discarded = Some(why),
638 Ok((answer, run_id, usage, _notes)) => {
639 t.run_id = Some(run_id);
640 t.usage = usage;
641 match validate(&answer, &want, c.project, c.policy, c.bug_test) {
642 Err(why) => t.discarded = Some(why),
643 Ok(files) => {
644 for f in files {
645 let full = c.project.join(&f.path);
646 if let Some(parent) = full.parent() {
647 let _ = std::fs::create_dir_all(parent);
648 }
649 if std::fs::write(&full, &f.content).is_err() {
650 t.discarded =
651 Some(format!("`{}` could not be written", f.path));
652 break;
653 }
654 let reproduces = f.statement.starts_with('E');
655 let (classes, excerpt) =
656 baseline_class(c, &f.argv, &f.test, reproduces);
657 let class =
658 classes.last().copied().unwrap_or(RedClass::Unclassified);
659 let red_ok = if reproduces {
660 class == RedClass::Assertion
661 } else {
662 class == RedClass::Passed
663 };
664 t.per_statement.push(TryStatement {
665 statement: f.statement.clone(),
666 class,
667 excerpt: (!red_ok).then_some(excerpt),
668 });
669 this.push((
670 Reproduction {
671 statement: f.statement,
672 file: f.path,
673 test: f.test,
674 source: Source::Author,
675 baseline: classes,
676 digest: format!(
677 "sha256:{}",
678 sha256_hex(f.content.as_bytes())
679 ),
680 argv: f.argv,
681 final_: Final::NotRun,
682 revert: Revert::NotRun,
683 },
684 f.content,
685 ));
686 }
687 }
688 }
689 }
690 }
691 }
692 if t.discarded.is_some() {
693 t.per_statement.clear();
694 }
695 let _ = worktree::restore(c.wt_root, c.tmp, c.start);
697 event(
698 c.live,
699 c.task,
700 BugEvent::ReproduceTry {
701 n,
702 of: c.max_tries,
703 per_statement: t
704 .per_statement
705 .iter()
706 .map(|s| crate::progress::StatementClass {
707 statement: s.statement.clone(),
708 class: class_word(s.class),
709 })
710 .collect(),
711 },
712 );
713 bug.tries.push(t);
714 if let Err(e) = state::save(c.state, &bug) {
715 return Err(Box::new(stop(
716 c,
717 bug,
718 Outcome::Recorded,
719 None,
720 format!("the try could not be kept: {e}"),
721 began,
722 )));
723 }
724 match rules::decide_reproduce(&bug.tries, &expected, c.max_tries) {
725 Reproduce::Reproduced { .. } => {
726 let last = bug
727 .tries
728 .last()
729 .map(|t| t.per_statement.clone())
730 .unwrap_or_default();
731 if let Some(u) = last
732 .iter()
733 .find(|s| s.statement.starts_with('U') && s.class != RedClass::Passed)
734 {
735 let words = bug
736 .triad
737 .statement(&u.statement)
738 .map(|s| s.text.clone())
739 .unwrap_or_default();
740 return Err(stop_now(
741 bug,
742 Outcome::UnchangedNotHolding,
743 Some("BUG-UNCHANGED-NOT-HOLDING"),
744 format!(
745 "{} does not hold today: its test fails on the untouched code ({}) — \"{words}\"; nothing is fixed",
746 u.statement,
747 class_word(u.class)
748 ),
749 ));
750 }
751 break this;
752 }
753 Reproduce::Retry => {}
754 Reproduce::AlreadySatisfied => {
755 bug.reproductions = person.clone();
756 bug.reproductions
757 .extend(this.iter().map(|(r, _)| r.clone()));
758 let files: Vec<(String, String)> = this
759 .iter()
760 .map(|(r, c)| (r.file.clone(), c.clone()))
761 .collect();
762 let _ = state::save_repro(c.state, &bug.unit, &bug.task, &files);
763 return Err(stop_now(
764 bug,
765 Outcome::AlreadySatisfied,
766 Some("BUG-ALREADY-SATISFIED"),
767 format!(
768 "every reproduction passed on the untouched code on each of {} tries: nothing to fix, nothing ticked",
769 c.max_tries
770 ),
771 ));
772 }
773 Reproduce::CannotReproduce {
774 reproduced,
775 satisfied,
776 not_demonstrated,
777 } => {
778 let mut said = vec![format!("after {} tries", bug.tries.len())];
779 if !reproduced.is_empty() {
780 said.push(format!("reproduced {}", reproduced.join(", ")));
781 }
782 if !satisfied.is_empty() {
783 said.push(format!(
784 "{} already pass (narrow the triad)",
785 satisfied.join(", ")
786 ));
787 }
788 if !not_demonstrated.is_empty() {
789 said.push(format!("not reproduced {}", not_demonstrated.join(", ")));
790 }
791 return Err(stop_now(
792 bug,
793 Outcome::CannotReproduce,
794 Some("BUG-CANNOT-REPRODUCE"),
795 format!("cannot reproduce: {}; nothing is fixed", said.join("; ")),
796 ));
797 }
798 }
799 };
800 stage(
801 c.live,
802 c.task,
803 Stage::Reproduce,
804 StageState::Passed,
805 Some("assertion".to_owned()),
806 Some(began),
807 );
808
809 bug.held_out.clear();
811 bug.held_out_sealed = None;
812 bug.held_out_reason = None;
813 if c.held_out {
814 let visible: Vec<(String, String)> = kept
815 .iter()
816 .filter(|(r, _)| r.reproduces())
817 .map(|(r, content)| (r.file.clone(), content.clone()))
818 .collect();
819 match seal_variants(c, &mut bug, &visible, &expected, &[]) {
820 Ok(sealed) => bug.held_out_sealed = Some(sealed),
821 Err(why) => bug.held_out_reason = Some(why),
822 }
823 }
824 bug.reproductions = kept.iter().map(|(r, _)| r.clone()).collect();
825 let files: Vec<(String, String)> = kept
826 .iter()
827 .map(|(r, c)| (r.file.clone(), c.clone()))
828 .collect();
829 if let Err(e) = state::save_repro(c.state, &bug.unit, &bug.task, &files) {
830 return Err(Box::new(stop(
831 c,
832 bug,
833 Outcome::Recorded,
834 None,
835 format!("the reproductions could not be kept: {e}"),
836 began,
837 )));
838 }
839 let digest = confirm::digest(&bug.reproductions);
840 bug.confirm_digest = Some(digest.clone());
841 event(
842 c.live,
843 c.task,
844 BugEvent::Reproduced {
845 reproductions: bug
846 .reproductions
847 .iter()
848 .map(|r| crate::progress::ShownReproduction {
849 statement: r.statement.clone(),
850 file: r.file.clone(),
851 test: r.test.clone(),
852 digest: r.digest.clone(),
853 })
854 .collect(),
855 },
856 );
857 let _ = state::save(c.state, &bug);
858
859 if !person.is_empty() {
861 let by = extra
862 .by
863 .clone()
864 .unwrap_or_else(|| crate::approvals::who_in(c.project));
865 let via = extra.via.unwrap_or(speccoder_core::actions::Via::Terminal);
866 return freeze(c, bug, &by, via, Basis::NamedTest, began);
867 }
868 stage(
869 c.live,
870 c.task,
871 Stage::Confirm,
872 StageState::Started,
873 None,
874 None,
875 );
876 let request = ConfirmRequest {
877 bug: bug.key(),
878 title: bug.title.clone(),
879 digest: digest.clone(),
880 reproductions: bug
881 .reproductions
882 .iter()
883 .zip(&files)
884 .map(|(r, (_, content))| ShownReproduction {
885 statement: r.statement.clone(),
886 words: bug
887 .triad
888 .statement(&r.statement)
889 .map(|s| s.text.clone())
890 .unwrap_or_default(),
891 file: r.file.clone(),
892 test: r.test.clone(),
893 argv: r.argv.clone(),
894 excerpt: bug
895 .tries
896 .last()
897 .and_then(|t| t.per_statement.iter().find(|s| s.statement == r.statement))
898 .and_then(|s| s.excerpt.clone())
899 .unwrap_or_default(),
900 content: content.clone(),
901 })
902 .collect(),
903 warning: crate::bug::held_out_warning(&bug),
904 };
905 match c
906 .approver
907 .and_then(|a| a.confirm(&request).map(|ans| (ans, a.via())))
908 {
909 Some((ConfirmAnswer::Confirm, via)) => {
910 let by = crate::approvals::who_in(c.project);
911 freeze(c, bug, &by, via, Basis::Shown, began)
912 }
913 Some((ConfirmAnswer::Reject(reason), via)) => {
914 if let Err(e) = reject(c.state, &mut bug, &reason, via) {
915 return Err(Box::new(stop(
916 c,
917 bug,
918 Outcome::Recorded,
919 None,
920 format!("the rejection could not be kept: {e}"),
921 began,
922 )));
923 }
924 event(c.live, c.task, BugEvent::ConfirmRejected { digest, reason });
925 stage(
926 c.live,
927 c.task,
928 Stage::Confirm,
929 StageState::Failed,
930 Some("rejected".to_owned()),
931 None,
932 );
933 if u32::try_from(bug.tries.len()).unwrap_or(u32::MAX) >= c.max_tries {
934 let message = format!(
935 "cannot reproduce: the reproductions of {} tries were not accepted; nothing is fixed",
936 bug.tries.len()
937 );
938 return Err(stop_now(
939 bug,
940 Outcome::CannotReproduce,
941 Some("BUG-CANNOT-REPRODUCE"),
942 message,
943 ));
944 }
945 reproduce(c, bug)
946 }
947 None => {
948 let next = format!("speccoder bug confirm {} --digest {digest}", bug.key());
949 event(
950 c.live,
951 c.task,
952 BugEvent::ConfirmWaiting {
953 digest: digest.clone(),
954 next: next.clone(),
955 },
956 );
957 stage(
958 c.live,
959 c.task,
960 Stage::Confirm,
961 StageState::Started,
962 Some("waits for you".to_owned()),
963 None,
964 );
965 let message = format!(
966 "{} reproduction(s) fail on the untouched code by an assertion; they wait for your confirmation (digest {digest}): {next}{}",
967 bug.reproductions.iter().filter(|r| r.reproduces()).count(),
968 crate::bug::held_out_warning(&bug)
969 .map(|w| format!(" — {w}"))
970 .unwrap_or_default()
971 );
972 Err(Box::new(stop(
973 c,
974 bug,
975 Outcome::AwaitingConfirmation,
976 None,
977 message,
978 began,
979 )))
980 }
981 }
982}
983
984fn outcome_word(o: Outcome) -> String {
985 o.as_str().replace('_', " ")
986}
987
988pub(crate) fn reject(
992 state_dir: &Path,
993 bug: &mut BugReport,
994 reason: &str,
995 via: speccoder_core::actions::Via,
996) -> Result<(), String> {
997 if let Some(t) = bug.tries.last_mut() {
998 t.discarded = Some(rules::rejected_try(reason));
999 }
1000 bug.rejections.push(rules::Rejection {
1001 digest: bug.confirm_digest.clone().unwrap_or_default(),
1002 reason: reason.to_owned(),
1003 by: crate::approvals::who(),
1004 via,
1005 at: confirm::now(),
1006 });
1007 bug.confirm_digest = None;
1008 bug.outcome = Outcome::Recorded;
1009 bug.stage = BugStage::Reproduce;
1010 state::save(state_dir, bug)
1011}
1012
1013fn freeze(
1014 c: &Ctx<'_>,
1015 mut bug: BugReport,
1016 by: &str,
1017 via: speccoder_core::actions::Via,
1018 basis: Basis,
1019 began: Instant,
1020) -> Result<Fix, Box<CommandResult>> {
1021 match confirm::freeze(c.state, &mut bug, by, via, basis) {
1022 Ok((record, files)) => {
1023 event(
1024 c.live,
1025 c.task,
1026 BugEvent::Confirmed {
1027 digest: record.approval_digest.clone(),
1028 by: by.to_owned(),
1029 via: via.as_str().to_owned(),
1030 basis: if basis == Basis::NamedTest {
1031 "named_test"
1032 } else {
1033 "shown"
1034 }
1035 .to_owned(),
1036 },
1037 );
1038 stage(
1039 c.live,
1040 c.task,
1041 Stage::Confirm,
1042 StageState::Passed,
1043 Some(by.to_owned()),
1044 None,
1045 );
1046 Ok(Fix { bug, record, files })
1047 }
1048 Err(e) => Err(Box::new(stop(
1049 c,
1050 bug,
1051 Outcome::Recorded,
1052 None,
1053 format!("the confirmation could not be recorded: {e}"),
1054 began,
1055 ))),
1056 }
1057}
1058
1059fn seal_variants(
1063 c: &Ctx<'_>,
1064 bug: &mut BugReport,
1065 visible: &[(String, String)],
1066 statements: &[String],
1067 told: &[String],
1068) -> Result<speccoder_core::acceptance::SealedRef, String> {
1069 let (files, manifest_text) = project_view(c);
1070 let context = manifest(c, bug, None);
1071 let input = substrate::acceptance::reproduce_input(&substrate::acceptance::ReproduceParts {
1072 set: "reproduce_held_out",
1073 bundle: c.bundle.clone(),
1074 statements: json!(bug.triad.statements().collect::<Vec<_>>()),
1075 want: statements,
1076 files: &files,
1077 manifest: &manifest_text,
1078 visible,
1079 rejections: told,
1080 issue: None,
1081 instructions: c.instructions,
1082 context: &context,
1083 test_layout: Some(&crate::layout::text_at(c.project)),
1084 });
1085 let (answer, run_id, _, _) =
1086 author(c, input).map_err(|e| format!("the held-out author: {e}"))?;
1087 let protected = c.policy.protected();
1088 let mut kept: Vec<(held_out::HeldOutFile, String)> = Vec::new();
1089 let mut discarded = Vec::new();
1090 for f in answer["files"].as_array().into_iter().flatten() {
1091 let path = f["path"].as_str().unwrap_or_default();
1092 let content = f["content"].as_str().unwrap_or_default();
1093 let cited: Vec<String> = f["scenarios"]
1094 .as_array()
1095 .into_iter()
1096 .flatten()
1097 .filter_map(|s| s.as_str().map(str::to_owned))
1098 .collect();
1099 let argv: Vec<String> = super::acceptance::argv_of(&f["argv"]);
1100 let Ok(rel) = tools::paths::normalise(path) else {
1101 discarded.push(held_out::Discarded {
1102 path: path.to_owned(),
1103 reason: "path".to_owned(),
1104 });
1105 continue;
1106 };
1107 let ok_path = tools::paths::is_test_path(&rel)
1108 && protected.write_class(&rel).is_none()
1109 && !c.project.join(&rel).exists()
1110 && !visible.iter().any(|(p, _)| *p == rel);
1111 let ok_cites = cited.len() == 1
1112 && statements.contains(&cited[0])
1113 && !kept.iter().any(|(k, _)| k.scenarios == cited);
1114 let ok_argv = c
1115 .policy
1116 .classify("run_command", &json!({ "argv": argv }), None)
1117 == Decision::Allow;
1118 if !(ok_path && ok_cites && ok_argv) {
1119 discarded.push(held_out::Discarded {
1120 path: rel,
1121 reason: if ok_path {
1122 if ok_cites {
1123 "command"
1124 } else {
1125 "unknown_scenario"
1126 }
1127 } else {
1128 "path"
1129 }
1130 .to_owned(),
1131 });
1132 continue;
1133 }
1134 kept.push((
1135 held_out::HeldOutFile {
1136 path: rel,
1137 sha256: sha256_hex(content.as_bytes()),
1138 scenarios: cited,
1139 argv,
1140 composition: false,
1141 red_tests: None,
1142 },
1143 content.to_owned(),
1144 ));
1145 }
1146 let mut red: Vec<(held_out::HeldOutFile, String)> = Vec::new();
1148 let once = held_out::overlay_red(c.wt_root, c.project, c.tmp, &kept, c.runner, c.policy)
1151 .map_err(|e| format!("the held-out variants could not be run: {e}"))?;
1152 let twice = held_out::overlay_red(c.wt_root, c.project, c.tmp, &kept, c.runner, c.policy)
1153 .map_err(|e| format!("the held-out variants could not be run: {e}"))?;
1154 for ((f, content), (a, b)) in kept.into_iter().zip(once.iter().zip(&twice)) {
1155 let class = held_out::red_class;
1156 let c2 = rules::bug_class(class(a), Some(class(b)));
1157 bug.held_out.retain(|h| !f.scenarios.contains(&h.statement));
1158 bug.held_out.push(HeldOutVariant {
1159 statement: f.scenarios[0].clone(),
1160 baseline: c2,
1161 final_: Final::NotRun,
1162 });
1163 if c2 == RedClass::Assertion {
1164 red.push((f, content));
1165 } else {
1166 discarded.push(held_out::Discarded {
1167 path: f.path,
1168 reason: "not_red".to_owned(),
1169 });
1170 }
1171 }
1172 let written = red.len();
1173 if let Some(old) = bug.held_out_sealed.clone() {
1175 let (m, contents) = held_out::open_sealed(c.state, &bug.unit, &old)
1176 .map_err(|e| format!("the sealed held-out set could not be opened: {}", e.0))?;
1177 for (f, (_, content)) in m.files.into_iter().zip(contents) {
1178 if !statements.iter().any(|s| f.scenarios.contains(s)) {
1179 red.push((f, content));
1180 }
1181 }
1182 }
1183 if written == 0 {
1184 return Err(if discarded.is_empty() {
1185 "the held-out author wrote no variant".to_owned()
1186 } else {
1187 format!(
1188 "no held-out variant was red on the untouched code by an assertion ({} discarded: {})",
1189 discarded.len(),
1190 discarded
1191 .iter()
1192 .map(|d| d.reason.as_str())
1193 .collect::<Vec<_>>()
1194 .join(", ")
1195 )
1196 });
1197 }
1198 let checkpoint = worktree::checkpoint(c.wt_root, c.tmp)
1199 .map(|cp| cp.0)
1200 .unwrap_or_default();
1201 let manifest = held_out::Manifest {
1202 version: 1,
1203 feature: bug.unit.clone(),
1204 task: bug.task.clone(),
1205 author_run: run_id,
1206 checkpoint,
1207 visible_scenarios: bug.expected_ids(),
1208 files: red.iter().map(|(f, _)| f.clone()).collect(),
1209 discarded,
1210 };
1211 let contents: Vec<(String, String)> = red
1212 .iter()
1213 .map(|(f, c)| (f.path.clone(), c.clone()))
1214 .collect();
1215 held_out::seal(c.state, &bug.unit, &bug.requirement, &manifest, &contents)
1216 .map_err(|e| format!("the held-out variants could not be sealed: {e}"))
1217}
1218
1219pub(crate) fn reuse(c: &Ctx<'_>, fix: &Fix) -> Result<PreparedAcceptance, String> {
1222 let tests: Vec<ReusedTest> = fix
1223 .bug
1224 .reproductions
1225 .iter()
1226 .map(|r| ReusedTest {
1227 path: r.file.clone(),
1228 cites: vec![r.statement.clone()],
1229 argv: r.argv.clone(),
1230 green: !r.reproduces(),
1231 })
1232 .collect();
1233 super::reuse_pre_frozen(
1234 c.project,
1235 &fix.record,
1236 &fix.files,
1237 &tests,
1238 c.runner,
1239 super::RedRule::BugAssertionOnly,
1240 None,
1241 )
1242}
1243
1244pub(crate) struct Judged {
1246 pub(crate) verdict: Verdict,
1248 pub(crate) weak: Option<speccoder_core::strength::Permitted>,
1251}
1252
1253pub(crate) struct Judging<'a> {
1255 pub(crate) before: &'a worktree::Checkpoint,
1256 pub(crate) baseline: &'a VerifyReport,
1257 pub(crate) verification: Option<&'a VerifyReport>,
1258 pub(crate) base: Verdict,
1259 pub(crate) keep: &'a Path,
1261}
1262
1263fn run_class(c: &Ctx<'_>, r: &Reproduction) -> RedClass {
1265 let (run, summary) = super::acceptance_run(c.project, &r.argv, c.runner);
1266 let class = classify_red_one(&run, summary.as_ref(), &r.test);
1267 if run.status == CheckStatus::Passed && class != RedClass::Unclassified {
1268 RedClass::Passed
1269 } else {
1270 class
1271 }
1272}
1273
1274fn in_project(c: &Ctx<'_>, repo_path: &str) -> Option<String> {
1276 let prefix = c
1277 .project
1278 .strip_prefix(c.wt_root)
1279 .map(|p| p.to_string_lossy().replace('\\', "/"))
1280 .unwrap_or_default();
1281 if prefix.is_empty() {
1282 Some(repo_path.to_owned())
1283 } else {
1284 repo_path
1285 .strip_prefix(&format!("{prefix}/"))
1286 .map(str::to_owned)
1287 }
1288}
1289
1290#[allow(clippy::too_many_lines)] pub(crate) fn judge(c: &Ctx<'_>, fix: &mut Fix, j: &Judging<'_>) -> Result<Judged, String> {
1295 let began = Instant::now();
1296 stage(
1297 c.live,
1298 c.task,
1299 Stage::Unchanged,
1300 StageState::Started,
1301 None,
1302 None,
1303 );
1304 let fin = worktree::checkpoint(c.wt_root, c.tmp).map_err(|e| e.0)?;
1305 let judged_before = crate::integrity::JudgeSnapshot::take(c.wt_root, c.policy);
1306 let mut unchanged_ok: Vec<String> = Vec::new();
1308 for r in &mut fix.bug.reproductions {
1309 let class = run_class(c, r);
1310 r.final_ = if class == RedClass::Passed {
1311 Final::Passed
1312 } else {
1313 Final::Failed
1314 };
1315 if !r.reproduces() && r.final_ == Final::Passed {
1316 unchanged_ok.push(r.statement.clone());
1317 }
1318 }
1319 let changes = worktree::diff(c.wt_root, j.before, &fin).map_err(|e| e.0)?;
1321 let changed: Vec<String> = changes
1322 .iter()
1323 .filter_map(|ch| in_project(c, &ch.path))
1324 .filter(|p| !tools::paths::is_test_path(p))
1325 .collect();
1326 let test_files: Vec<(String, String)> = worktree::files(c.wt_root, &fin)
1327 .unwrap_or_default()
1328 .into_iter()
1329 .filter_map(|p| in_project(c, &p))
1330 .filter(|p| tools::paths::is_test_path(p) || changed.contains(p))
1331 .take(400)
1332 .filter_map(|p| {
1333 std::fs::read_to_string(c.project.join(&p))
1334 .ok()
1335 .map(|t| (p, t))
1336 })
1337 .collect();
1338 let baseline_tests: Vec<speccoder_core::verify::TestResult> = j
1339 .baseline
1340 .checks
1341 .iter()
1342 .flat_map(|ch| ch.tests.clone().unwrap_or_default())
1343 .collect();
1344 let final_tests: Vec<speccoder_core::verify::TestResult> = j
1345 .verification
1346 .map(|v| {
1347 v.checks
1348 .iter()
1349 .flat_map(|ch| ch.tests.clone().unwrap_or_default())
1350 .collect()
1351 })
1352 .unwrap_or_default();
1353 let crate_name = std::fs::read_to_string(c.project.join("Cargo.toml"))
1354 .ok()
1355 .and_then(|t| {
1356 t.lines().find_map(|l| {
1357 l.trim().strip_prefix("name").map(|r| {
1358 r.trim_start_matches([' ', '='])
1359 .trim()
1360 .trim_matches('"')
1361 .to_owned()
1362 })
1363 })
1364 });
1365 let unchanged_members: Vec<(String, String, String)> = fix
1366 .bug
1367 .reproductions
1368 .iter()
1369 .filter(|r| !r.reproduces())
1370 .map(|r| (r.statement.clone(), r.file.clone(), r.test.clone()))
1371 .collect();
1372 let mut p2p: PassToPass = crate::bug::unchanged::select(
1373 &changed,
1374 &test_files,
1375 &baseline_tests,
1376 crate_name.as_deref(),
1377 &unchanged_members,
1378 );
1379 crate::bug::unchanged::settle(&mut p2p, &final_tests, &|s| {
1380 unchanged_ok.iter().any(|u| u == s)
1381 });
1382 event(
1383 c.live,
1384 c.task,
1385 BugEvent::UnchangedSelected {
1386 state: if p2p.state == rules::PassToPassState::Selected {
1387 "selected"
1388 } else {
1389 "none_selected"
1390 }
1391 .to_owned(),
1392 count: p2p.members.len(),
1393 },
1394 );
1395
1396 worktree::restore(c.wt_root, c.tmp, j.before).map_err(|e| e.0)?;
1398 let git = crate::git::Git::at(c.wt_root);
1399 for ch in &changes {
1400 if !in_project(c, &ch.path).is_some_and(|p| tools::paths::is_test_path(&p)) {
1401 continue;
1402 }
1403 let full = c.wt_root.join(&ch.path);
1404 match ch.kind {
1405 worktree::ChangeKind::Deleted => {
1406 let _ = std::fs::remove_file(&full);
1407 }
1408 _ => {
1409 let content = git
1410 .run(&["show", &format!("{}:{}", fin.0, ch.path)])
1411 .map_err(|e| e.0)?;
1412 if let Some(parent) = full.parent() {
1413 let _ = std::fs::create_dir_all(parent);
1414 }
1415 std::fs::write(&full, content).map_err(|e| e.to_string())?;
1416 }
1417 }
1418 }
1419 let mut rejected_by = Vec::new();
1420 let mut any_unviable = false;
1421 for r in fix.bug.reproductions.iter_mut().filter(|r| r.reproduces()) {
1422 let class = run_class(c, r);
1423 r.revert = match class {
1424 RedClass::Assertion => {
1425 rejected_by.push(r.statement.clone());
1426 Revert::Rejected
1427 }
1428 RedClass::Passed => Revert::Survived,
1429 _ => {
1430 any_unviable = true;
1431 Revert::Unviable
1432 }
1433 };
1434 }
1435 worktree::restore(c.wt_root, c.tmp, &fin).map_err(|e| e.0)?;
1436 let revert = RevertResult {
1437 outcome: if !rejected_by.is_empty() {
1438 Revert::Rejected
1439 } else if any_unviable {
1440 Revert::Unviable
1441 } else {
1442 Revert::Survived
1443 },
1444 rejected_by,
1445 };
1446 stage(
1447 c.live,
1448 c.task,
1449 Stage::Unchanged,
1450 if p2p.held() && !revert.rejected_by.is_empty() {
1451 StageState::Passed
1452 } else {
1453 StageState::Failed
1454 },
1455 Some(format!(
1456 "{} pass-to-pass, revert {}",
1457 p2p.members.len(),
1458 revert_word(revert.outcome)
1459 )),
1460 Some(began),
1461 );
1462
1463 let mut special: Vec<SpecialCase> = Vec::new();
1465 let mut special_error: Option<String> = None;
1466 let mut weak = None;
1467 if !revert.rejected_by.is_empty()
1468 && fix
1469 .bug
1470 .reproductions
1471 .iter()
1472 .all(|r| r.final_ == Final::Passed)
1473 {
1474 let patch = worktree::patch(c.wt_root, c.start, &fin).unwrap_or_default();
1475 let changed_sources = crate::strength::changed_files(c.wt_root, &patch);
1476 let shown: Vec<(String, String, String)> = fix
1477 .bug
1478 .reproductions
1479 .iter()
1480 .filter(|r| r.reproduces())
1481 .filter_map(|r| {
1482 fix.files
1483 .iter()
1484 .find(|(p, _)| *p == r.file)
1485 .map(|(p, content)| (r.statement.clone(), p.clone(), content.clone()))
1486 })
1487 .collect();
1488 if changed_sources.is_empty() {
1489 special_error =
1490 Some("the fix changes no source file a special case could replace".to_owned());
1491 } else {
1492 let context = manifest(c, &fix.bug, None);
1493 let input = substrate::near_miss::special_case_input(
1494 c.bundle,
1495 &changed_sources,
1496 &crate::mutation::source_patch(&patch),
1497 &shown,
1498 &context,
1499 );
1500 let variants = match c.rt.block_on(c.plane.near_miss(c.feature, c.task, input)) {
1502 Err(e) => {
1503 special_error = Some(format!("the special-case author call failed: {}", e.0));
1504 Vec::new()
1505 }
1506 Ok(o) => {
1507 let answer = o
1508 .output
1509 .as_ref()
1510 .map(|v| v.peek()["answer"].clone())
1511 .unwrap_or_default();
1512 if !matches!(o.status, agentplane::prelude::RunStatus::Succeeded)
1513 || answer.is_null()
1514 {
1515 special_error = Some(format!(
1516 "the special-case author did not answer ({})",
1517 crate::substrate::why_not(&o.status)
1518 ));
1519 Vec::new()
1520 } else {
1521 let v = special_variants(&answer, &changed_sources);
1522 if v.is_empty() {
1523 special_error = Some(
1524 "the special-case author wrote no candidate that changes the fix's source files".to_owned(),
1525 );
1526 }
1527 v
1528 }
1529 }
1530 };
1531 let rulings = crate::strength::rulings(j.keep);
1532 for v in variants {
1533 let statement = v.scenario.clone();
1534 if special.iter().any(|s| s.statement == statement) {
1535 continue;
1536 }
1537 let digest = v.digest();
1538 let ruled = rulings.iter().any(|r| r.digest == digest);
1539 let mut rejected = special_rejected(c, fix, &v, &fin)?;
1540 let mut regenerated = false;
1541 if !rejected && !ruled {
1542 regenerated = true;
1544 let visible: Vec<(String, String)> = shown
1545 .iter()
1546 .filter(|(s, _, _)| *s == statement)
1547 .map(|(_, p, content)| (p.clone(), content.clone()))
1548 .collect();
1549 worktree::restore(c.wt_root, c.tmp, j.before).map_err(|e| e.0)?;
1550 let told = vec![format!(
1551 "a fix that special-cases this input passed the earlier variant: {}",
1552 v.rationale
1553 )];
1554 let resealed = seal_variants(
1555 c,
1556 &mut fix.bug,
1557 &visible,
1558 std::slice::from_ref(&statement),
1559 &told,
1560 );
1561 worktree::restore(c.wt_root, c.tmp, &fin).map_err(|e| e.0)?;
1562 match resealed {
1563 Ok(sealed) => {
1564 fix.bug.held_out_sealed = Some(sealed.clone());
1565 fix.record.held_out_sealed = Some(sealed);
1566 crate::pre_frozen::store(c.state, &fix.record, &fix.files).map_err(
1567 |e| format!("the re-sealed held-out set could not be kept: {e}"),
1568 )?;
1569 rejected = special_rejected(c, fix, &v, &fin)?;
1570 }
1571 Err(why) => {
1573 fix.bug.held_out_reason = Some(why);
1574 }
1575 }
1576 }
1577 if !rejected && !ruled {
1578 weak = Some(speccoder_core::strength::Permitted {
1579 id: format!("special-case-{statement}"),
1580 scenario: statement.clone(),
1581 rationale: v.rationale.clone(),
1582 digest: digest.clone(),
1583 outcome: speccoder_core::strength::PermittedOutcome::Rejected,
1584 failing: None,
1585 patch: None,
1586 });
1587 }
1588 special.push(SpecialCase {
1589 statement,
1590 digest,
1591 rejected,
1592 regenerated,
1593 ruled,
1594 });
1595 }
1596 }
1597 }
1598 let held = match fix.bug.held_out_sealed.clone() {
1601 Some(sealed) => {
1602 let (m, contents) = held_out::open_sealed(c.state, &fix.bug.unit, &sealed)
1603 .map_err(|e| format!("the sealed held-out set could not be opened: {}", e.0))?;
1604 let files: Vec<(held_out::HeldOutFile, String)> = m
1605 .files
1606 .into_iter()
1607 .zip(contents.into_iter().map(|(_, x)| x))
1608 .collect();
1609 let runs =
1610 held_out::overlay_run(c.wt_root, c.project, c.tmp, &files, c.runner, c.policy)?;
1611 let mut failed: Vec<String> = Vec::new();
1612 let mut passed: Vec<String> = Vec::new();
1613 for ((f, _), r) in files.iter().zip(&runs) {
1614 let ok = r
1615 .result
1616 .as_ref()
1617 .is_some_and(|(res, _)| res.status == CheckStatus::Passed);
1618 for st in &f.scenarios {
1619 if ok {
1620 passed.push(st.clone());
1621 } else {
1622 failed.push(st.clone());
1623 }
1624 }
1625 }
1626 if runs.len() != files.len() {
1627 failed.push("held-out".to_owned());
1628 }
1629 for h in &mut fix.bug.held_out {
1630 h.final_ = if failed.contains(&h.statement) {
1631 Final::Failed
1632 } else if passed.contains(&h.statement) {
1633 Final::Passed
1634 } else {
1635 Final::NotRun
1636 };
1637 }
1638 failed.sort();
1639 failed.dedup();
1640 if failed.is_empty() {
1641 HeldOut::Passed { files: files.len() }
1642 } else {
1643 HeldOut::Failed { scenarios: failed }
1644 }
1645 }
1646 None if c.held_out => HeldOut::Absent {
1647 reason: fix
1648 .bug
1649 .held_out_reason
1650 .clone()
1651 .unwrap_or_else(|| "none_kept".to_owned()),
1652 },
1653 None => HeldOut::Off,
1654 };
1655 let now = worktree::checkpoint(c.wt_root, c.tmp).map_err(|e| e.0)?;
1657 if now != fin {
1658 return Err("the bug's judging left changes in the worktree".to_owned());
1659 }
1660 let drift = judged_before.drift(
1661 &crate::integrity::JudgeSnapshot::take(c.wt_root, c.policy),
1662 c.policy,
1663 &std::collections::BTreeSet::new(),
1664 );
1665 if let Some(d) = drift.first() {
1666 return Err(format!("the bug's judging changed judge input {}", d.path));
1667 }
1668 event(
1669 c.live,
1670 c.task,
1671 BugEvent::Discrimination {
1672 revert: revert_word(revert.outcome),
1673 special_case: special
1674 .iter()
1675 .map(|s| crate::progress::ShownSpecialCase {
1676 statement: s.statement.clone(),
1677 rejected: s.rejected || s.ruled,
1678 })
1679 .collect(),
1680 },
1681 );
1682 let verdict = {
1683 let d = rules::Discrimination {
1684 reproductions: &fix.bug.reproductions,
1685 revert: &revert,
1686 special_case: &special,
1687 special_case_error: special_error.as_deref(),
1688 };
1689 rules::bug_verdict(j.base.clone(), &d, &p2p, &held)
1690 };
1691 fix.bug.pass_to_pass = Some(p2p);
1692 fix.bug.revert = Some(revert);
1693 fix.bug.special_case = special;
1694 state::save(c.state, &fix.bug).map_err(|e| format!("the bug could not be kept: {e}"))?;
1695 Ok(Judged { verdict, weak })
1696}
1697
1698fn revert_word(r: Revert) -> String {
1699 match r {
1700 Revert::Rejected => "rejected",
1701 Revert::Survived => "survived",
1702 Revert::Unviable => "unviable",
1703 Revert::NotRun => "not_run",
1704 }
1705 .to_owned()
1706}
1707
1708fn special_variants(answer: &Value, changed: &[(String, String)]) -> Vec<crate::strength::Variant> {
1711 let mut out = Vec::new();
1712 for v in answer["variants"].as_array().into_iter().flatten() {
1713 if v["kind"] != "special_case" {
1714 continue;
1715 }
1716 let mut files = Vec::new();
1717 let mut ok = true;
1718 for f in v["files"].as_array().into_iter().flatten() {
1719 let (Some(path), Some(content)) = (f["path"].as_str(), f["content"].as_str()) else {
1720 ok = false;
1721 break;
1722 };
1723 match tools::paths::normalise(path).ok().and_then(|p| {
1724 changed
1725 .iter()
1726 .find(|(c, _)| *c == p)
1727 .map(|(c, now)| (c.clone(), now.clone()))
1728 }) {
1729 Some((p, now)) if now != content => files.push((p, content.to_owned())),
1730 Some(_) => {}
1731 None => {
1732 ok = false;
1733 break;
1734 }
1735 }
1736 }
1737 if ok && !files.is_empty() {
1738 out.push(crate::strength::Variant {
1739 kind: "special_case".to_owned(),
1740 scenario: v["scenario"].as_str().unwrap_or_default().to_owned(),
1741 rationale: v["rationale"].as_str().unwrap_or_default().to_owned(),
1742 files,
1743 });
1744 }
1745 }
1746 out
1747}
1748
1749fn special_rejected(
1752 c: &Ctx<'_>,
1753 fix: &Fix,
1754 v: &crate::strength::Variant,
1755 fin: &worktree::Checkpoint,
1756) -> Result<bool, String> {
1757 for (p, content) in &v.files {
1758 std::fs::write(c.wt_root.join(p), content).map_err(|e| format!("{p}: {e}"))?;
1759 }
1760 let mut rejected = false;
1761 for r in fix
1762 .bug
1763 .reproductions
1764 .iter()
1765 .filter(|r| r.statement == v.scenario)
1766 {
1767 if run_class(c, r) == RedClass::Assertion {
1768 rejected = true;
1769 }
1770 }
1771 if !rejected
1772 && let Some(sealed) = &fix.bug.held_out_sealed
1773 && let Ok((m, contents)) = held_out::open_sealed(c.state, &fix.bug.unit, sealed)
1774 {
1775 let files: Vec<(held_out::HeldOutFile, String)> = m
1776 .files
1777 .into_iter()
1778 .zip(contents.into_iter().map(|(_, x)| x))
1779 .filter(|(f, _)| f.scenarios.contains(&v.scenario))
1780 .collect();
1781 let runs = held_out::overlay_run(c.wt_root, c.project, c.tmp, &files, c.runner, c.policy)?;
1782 rejected = runs
1783 .iter()
1784 .filter_map(|r| r.result.as_ref())
1785 .any(|(res, s)| classify_red(res, s.as_ref()) == RedClass::Assertion);
1786 }
1787 worktree::restore(c.wt_root, c.tmp, fin).map_err(|e| e.0)?;
1788 Ok(rejected)
1789}
1790
1791pub(crate) fn trailers(
1795 fix: &Fix,
1796 verdict_word: &str,
1797 rulings: &[speccoder_core::strength::Ruling],
1798) -> String {
1799 let outcome = if matches!(verdict_word, "verified" | "attested") {
1800 "fixed"
1801 } else {
1802 "failed"
1803 };
1804 let mut out = format!(
1805 "Bug: {outcome} ({}) triad={}\n",
1806 fix.bug.home.kind.as_str(),
1807 fix.bug.triad.digest
1808 );
1809 out.push_str(
1810 &fix.record
1811 .trailer(&crate::pre_frozen::manifest_digest(&fix.record)),
1812 );
1813 for s in fix
1814 .bug
1815 .special_case
1816 .iter()
1817 .filter(|s| s.ruled && !s.rejected)
1818 {
1819 if let Some(r) = rulings.iter().find(|r| r.digest == s.digest) {
1820 out.push_str(&format!(
1821 "Ruling: tests-right {} {} by {} — {}\n",
1822 s.statement, r.digest, r.by, r.reason
1823 ));
1824 }
1825 }
1826 if let Some(i) = fix.bug.issue.as_ref().filter(|_| outcome == "fixed") {
1827 out.push_str(&format!("Fixes: #{}\n", i.number));
1830 }
1831 out
1832}
1833
1834pub(crate) fn predicate_fields(
1836 bug: &BugReport,
1837 record: &speccoder_core::acceptance::PreFrozenAcceptance,
1838) -> (Value, Value) {
1839 let b = json!({
1840 "home": bug.home.kind.as_str(),
1841 "triad_sha256": bug.triad.digest,
1842 "outcome": bug.outcome.as_str(),
1843 "reproductions": bug.reproductions.iter().map(|r| json!({
1844 "statement": r.statement, "baseline": r.baseline, "final": r.final_, "revert": r.revert,
1845 })).collect::<Vec<_>>(),
1846 "special_case": bug.special_case.iter().map(|s| json!({
1847 "statement": s.statement, "rejected": s.rejected, "regenerated": s.regenerated,
1848 })).collect::<Vec<_>>(),
1849 "pass_to_pass": bug.pass_to_pass.as_ref().map(|p| json!({ "state": p.state, "count": p.members.len() })),
1850 });
1851 let a = json!({
1852 "source": record.producer.source(),
1853 "pre_frozen": {
1854 "manifest_sha256": crate::pre_frozen::manifest_digest(record),
1855 "approval_sha256": record.approval_digest,
1856 "wording_sha256": record.wording_digest,
1857 "by": record.decided.by,
1858 "via": record.decided.via,
1859 },
1860 });
1861 (b, a)
1862}
1863
1864pub(crate) fn finish(
1866 state_dir: &Path,
1867 fix: &mut Fix,
1868 report: &speccoder_core::RunReport,
1869 passed: bool,
1870) {
1871 if let Some(saved) = state::load(state_dir, &fix.bug.unit, &fix.bug.task) {
1873 fix.bug.candidate = saved.candidate;
1874 }
1875 fix.bug.verdict.clone_from(&report.verdict);
1876 fix.bug.run_id = (!report.run_id.is_empty()).then(|| report.run_id.clone());
1877 fix.bug.commit.clone_from(&report.commit);
1878 fix.bug.outcome = if passed {
1879 Outcome::Fixed
1880 } else {
1881 Outcome::Failed
1882 };
1883 fix.bug.stage = if passed {
1884 BugStage::Done
1885 } else {
1886 BugStage::Fix
1887 };
1888 fix.bug.code = (!passed
1889 && fix
1890 .bug
1891 .revert
1892 .as_ref()
1893 .is_some_and(|r| r.rejected_by.is_empty()))
1894 .then(|| "BUG-NOT-DISCRIMINATING".to_owned());
1895 let _ = state::save(state_dir, &fix.bug);
1896}
1897
1898pub(crate) fn apply_candidate(
1903 c: &Ctx<'_>,
1904 diff: &str,
1905 candidate: &rules::Candidate,
1906 frozen: &[String],
1907 held_out_paths: &[String],
1908) -> Result<(String, bool, Value), Box<CommandResult>> {
1909 let refused = |code: &str, paths: Vec<String>, status: CommandStatus, message: String| {
1910 let _ = worktree::restore(c.wt_root, c.tmp, c.start);
1911 if let Some(mut bug) = state::load(c.state, c.feature, c.task) {
1912 if let Some(cand) = bug.candidate.as_mut() {
1913 cand.refused = Some(rules::CandidateRefusal {
1914 code: code.to_owned(),
1915 paths: paths.clone(),
1916 });
1917 }
1918 bug.outcome = Outcome::Failed;
1919 bug.code = Some(code.to_owned());
1920 let _ = state::save(c.state, &bug);
1921 }
1922 let mut report = bare_report(c.feature, c.task, c.wt_path, "candidate_refused");
1923 report.reason = Some(message.clone());
1924 report.bug = state::load(c.state, c.feature, c.task).map(Box::new);
1925 Box::new(
1926 CommandResult::new("run", status, &message)
1927 .with_code(code)
1928 .with_data(CommandData::Run(Box::new(report))),
1929 )
1930 };
1931 let touched = match crate::bug::candidate::touched(c.wt_root, diff) {
1934 Ok(t) => t,
1935 Err(r) => {
1936 let message = format!("the candidate is not applied: {}", r.paths.join("; "));
1937 return Err(refused(
1938 "BUG-CANDIDATE-APPLY",
1939 r.paths,
1940 CommandStatus::GitPrecondition,
1941 message,
1942 ));
1943 }
1944 };
1945 let judged = crate::bug::candidate::judge_paths(&touched, c.policy, frozen, held_out_paths);
1946 if !judged.is_empty() {
1947 return Err(refused(
1948 "BUG-CANDIDATE-JUDGE",
1949 judged.clone(),
1950 CommandStatus::UsageError,
1951 format!(
1952 "the candidate touches what judges it, so it is not applied: {}",
1953 judged.join(", ")
1954 ),
1955 ));
1956 }
1957 if let Err(r) = crate::bug::candidate::apply(c.wt_root, c.tmp, diff) {
1958 let message = format!(
1959 "the candidate does not apply on the branch: {}",
1960 if r.paths.is_empty() {
1961 "git refused it".to_owned()
1962 } else {
1963 r.paths.join("; ")
1964 }
1965 );
1966 return Err(refused(
1967 "BUG-CANDIDATE-APPLY",
1968 r.paths,
1969 CommandStatus::GitPrecondition,
1970 message,
1971 ));
1972 }
1973 if let Some(mut bug) = state::load(c.state, c.feature, c.task) {
1974 if let Some(cand) = bug.candidate.as_mut() {
1975 cand.applied = true;
1976 }
1977 let _ = state::save(c.state, &bug);
1978 }
1979 let short: String = candidate
1980 .digest
1981 .trim_start_matches("sha256:")
1982 .chars()
1983 .take(12)
1984 .collect();
1985 let from = match (&candidate.path, candidate.number) {
1986 (_, Some(n)) => format!("pull request #{n}"),
1987 (Some(p), None) => p.clone(),
1988 (None, None) => "a patch".to_owned(),
1989 };
1990 Ok((
1991 format!("candidate_{short}"),
1992 true,
1993 json!({
1994 "status": "completed",
1995 "report": { "summary": format!("applied {from} as the attempt"), "status": "completed" },
1996 "tool_calls": [],
1997 }),
1998 ))
1999}
2000
2001pub(crate) fn finished(
2004 c: &Ctx<'_>,
2005 fix: &mut Fix,
2006 mut report: speccoder_core::RunReport,
2007 attempt_status: &str,
2008 passed: bool,
2009 status: CommandStatus,
2010 message: String,
2011) -> CommandResult {
2012 let done = passed && (report.ticked || report.commit.is_some());
2013 finish(c.state, fix, &report, done);
2014 let mut status = status;
2015 let mut code = None;
2016 if attempt_status == "repro_weak" {
2017 status = CommandStatus::NeedsHuman;
2018 code = Some("BUG-REPRO-WEAK");
2019 fix.bug.code = Some("BUG-REPRO-WEAK".to_owned());
2020 let _ = state::save(c.state, &fix.bug);
2021 } else if !done
2022 && fix
2023 .bug
2024 .revert
2025 .as_ref()
2026 .is_some_and(|r| r.rejected_by.is_empty())
2027 {
2028 code = Some("BUG-NOT-DISCRIMINATING");
2029 }
2030 let next = handoff::next(&fix.bug, fix.bug.outcome);
2031 event(
2032 c.live,
2033 c.task,
2034 BugEvent::Outcome {
2035 outcome: fix.bug.outcome.as_str().to_owned(),
2036 verdict: report.verdict.as_ref().map(super::outcome::verdict_word),
2037 code: code.map(str::to_owned),
2038 next: next.iter().map(|n| n.command.clone()).collect(),
2039 },
2040 );
2041 report.bug = Some(Box::new(fix.bug.clone()));
2042 c.live.event(&super::finished_event(
2043 c.task,
2044 &report,
2045 attempt_status,
2046 false,
2047 message.clone(),
2048 ));
2049 let mut r =
2050 CommandResult::new("run", status, &message).with_data(CommandData::Run(Box::new(report)));
2051 if let Some(code) = code {
2052 r = r.with_code(code);
2053 }
2054 r
2055}
2056
2057#[derive(Debug, Clone, PartialEq, Eq)]
2060pub struct NativeBug {
2061 pub unit: String,
2063 pub dir: String,
2065 pub task: String,
2067 pub title: String,
2069 pub story: String,
2071}
2072
2073impl NativeBug {
2074 #[must_use]
2076 pub fn of(bug: &BugReport) -> Self {
2077 Self {
2078 unit: bug.unit.clone(),
2079 dir: bug.home.location.clone(),
2080 task: bug.task.clone(),
2081 title: bug.title.clone(),
2082 story: format!(
2083 "A bug, in the reporter's words.\n\n{}",
2084 bug.triad.labelled()
2085 ),
2086 }
2087 }
2088
2089 #[must_use]
2091 pub fn bundle(&self, project: &Path) -> crate::context::Bundle {
2092 let [rules, ..] =
2093 crate::format::at(project).convergence_texts(project, &project.join(&self.dir));
2094 crate::context::Bundle {
2095 feature: self.unit.clone(),
2096 constitution: crate::context::cap(&rules),
2097 plan: String::new(),
2098 story: crate::context::cap(&self.story),
2099 task: crate::context::TaskContext {
2100 id: self.task.clone(),
2101 title: format!("Fix: {}", self.title),
2102 phase: String::new(),
2103 subsection: String::new(),
2104 story: String::new(),
2105 parallel: false,
2106 },
2107 dependencies: Vec::new(),
2108 story_tasks: Vec::new(),
2109 }
2110 }
2111}
2112
2113#[cfg(test)]
2114mod tests {
2115 use super::*;
2116
2117 #[test]
2118 fn a_reproduction_is_a_test_file_run_by_speccoders_own_command() {
2119 let dir = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
2120 let policy = Policy::new(
2121 &[],
2122 &[vec![
2123 "./run-one".to_owned(),
2124 "tests/repro.sh".to_owned(),
2125 "empty".to_owned(),
2126 ]],
2127 );
2128 let template = [
2129 "./run-one".to_owned(),
2130 "{file}".to_owned(),
2131 "{name}".to_owned(),
2132 ];
2133 let want = ["E1".to_owned()];
2134 let answer = |path: &str, test: &str| json!({ "files": [{ "path": path, "content": "x", "statement": "E1", "test": test, "argv": ["sh", "-c", "exit 1"] }] });
2135 let ok = validate(
2137 &answer("tests/repro.sh", "empty"),
2138 &want,
2139 dir.path(),
2140 &policy,
2141 Some(&template),
2142 );
2143 let Ok(files) = ok else {
2144 panic!("{ok:?}", ok = ok.err());
2145 };
2146 assert_eq!(files[0].argv, ["./run-one", "tests/repro.sh", "empty"]);
2147 for path in [
2149 "tests/conftest.py",
2150 "tests/__init__.py",
2151 "tests/vitest.setup.ts",
2152 ] {
2153 let e = validate(
2154 &answer(path, "t"),
2155 &want,
2156 dir.path(),
2157 &policy,
2158 Some(&template),
2159 )
2160 .err();
2161 assert!(
2162 e.as_deref()
2163 .is_some_and(|e| e.contains("configures how tests run")),
2164 "{path}: {e:?}"
2165 );
2166 }
2167 assert!(
2169 validate(
2170 &answer("tests/repro.sh", " "),
2171 &want,
2172 dir.path(),
2173 &policy,
2174 Some(&template)
2175 )
2176 .is_err()
2177 );
2178 assert!(
2179 validate(
2180 &answer("tests/repro.unknown", "t"),
2181 &want,
2182 dir.path(),
2183 &policy,
2184 None
2185 )
2186 .err()
2187 .is_some_and(|e| e.contains("[bug] test"))
2188 );
2189 }
2190}