1use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use agentplane::model::ModelProvider;
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21use speccoder_core::acceptance::{Decided, PreFrozenAcceptance, Producer, SealedRef, VisibleTest};
22use speccoder_core::actions::Via;
23use speccoder_core::context::{ContextEntry, ContextKind};
24use speccoder_core::ladder::Rung;
25use speccoder_core::oracle::{
26 Ambiguity, AuthoredBy, Expectation, HeldOutSummary, OracleDiscarded, OracleOp, OracleRejected,
27 OracleState, OracleTest, OracleView, Reading, Resolution, Untestable,
28};
29use speccoder_core::snapshot::ProjectSnapshot;
30use speccoder_core::verify::{RedClass, classify_red};
31use speccoder_core::{CommandData, CommandResult, CommandStatus};
32
33use crate::format::{Adapter, OracleRequirement};
34use crate::integrity::sha256_hex;
35use crate::{sandbox, substrate, tools, worktree};
36
37pub const DIR: &str = "oracle";
39
40pub const LIMIT: usize = 4;
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct Draft {
46 pub requirement: DraftRequirement,
48 pub samples: u8,
50 pub tests: Vec<DraftTest>,
52 pub discarded: Vec<OracleDiscarded>,
54 pub rejected: Vec<OracleRejected>,
56 pub expectations: Samples<Expectation>,
58 pub untestable: Samples<Untestable>,
60 pub ambiguities: Vec<Ambiguity>,
62 pub held_out: HeldOutSummary,
64 pub sealed: Option<SealedRef>,
66 pub notes: Vec<String>,
68 pub runs: Vec<String>,
70 pub context: Vec<ContextEntry>,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub struct DraftRequirement {
78 pub key: String,
80 pub title: String,
82 pub text: String,
84 pub sha256: String,
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct DraftTest {
91 pub path: String,
93 pub sha256: String,
95 pub scenarios: Vec<String>,
97 pub argv: Vec<String>,
99 pub red_class: RedClass,
101 pub authored_by: AuthoredBy,
103 pub edited_by: Option<String>,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(bound(deserialize = "T: Deserialize<'de>"))]
110pub struct Samples<T> {
111 pub sample1: Vec<T>,
113 pub sample2: Vec<T>,
115}
116
117impl<T> Default for Samples<T> {
118 fn default() -> Self {
119 Self {
120 sample1: Vec::new(),
121 sample2: Vec::new(),
122 }
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128pub struct OracleEntry {
129 pub requirement_sha256: String,
131 pub manifest_sha256: String,
133 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub held_out_sha256: Option<String>,
136 pub by: String,
138 pub via: Via,
140 pub at: u64,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct Frozen {
148 pub requirement_sha256: String,
150 pub wording: String,
152 pub manifest_sha256: String,
154 pub tests: Vec<FrozenTest>,
156}
157
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub struct FrozenTest {
161 pub path: String,
163 pub sha256: String,
165 pub argv: Vec<String>,
167 pub scenarios: Vec<String>,
169}
170
171pub type Loaded = (Draft, Vec<(String, String)>);
173
174type Kept = (String, String, Vec<String>, Vec<String>);
176
177#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Tampered(pub String);
180
181fn slug(key: &str) -> String {
182 key.chars()
183 .map(|c| {
184 if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
185 c
186 } else {
187 '_'
188 }
189 })
190 .collect()
191}
192
193#[must_use]
195pub fn dir(project_state: &Path, unit: &str, key: &str) -> PathBuf {
196 project_state.join(DIR).join(unit).join(slug(key))
197}
198
199fn now() -> u64 {
200 std::time::SystemTime::now()
201 .duration_since(std::time::UNIX_EPOCH)
202 .map_or(0, |d| d.as_secs())
203}
204
205fn digest_of(text: &str) -> String {
206 format!("sha256:{}", sha256_hex(text.as_bytes()))
207}
208
209fn write_atomic(file: &Path, text: &str) -> Result<(), String> {
210 if let Some(parent) = file.parent() {
211 std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
212 }
213 let tmp = file.with_extension("json.tmp");
214 std::fs::write(&tmp, text).map_err(|e| format!("{}: {e}", tmp.display()))?;
215 std::fs::rename(&tmp, file).map_err(|e| format!("{}: {e}", file.display()))
216}
217
218pub fn store(
221 project_state: &Path,
222 unit: &str,
223 draft: &Draft,
224 contents: &[(String, String)],
225) -> Result<(), String> {
226 let d = dir(project_state, unit, &draft.requirement.key);
227 let _ = std::fs::remove_dir_all(d.join("files"));
228 for t in &draft.tests {
229 let content = contents
230 .iter()
231 .find(|(p, _)| *p == t.path)
232 .map(|(_, c)| c)
233 .ok_or_else(|| format!("{} has no content", t.path))?;
234 if digest_of(content) != t.sha256 {
235 return Err(format!("{} does not match its digest", t.path));
236 }
237 let file = d.join("files").join(&t.path);
238 if let Some(parent) = file.parent() {
239 std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
240 }
241 std::fs::write(&file, content).map_err(|e| format!("{}: {e}", file.display()))?;
242 }
243 let text = serde_json::to_string_pretty(draft).map_err(|e| e.to_string())?;
244 write_atomic(&d.join("draft.json"), &text)
245}
246
247pub fn load(project_state: &Path, unit: &str, key: &str) -> Result<Option<Loaded>, Tampered> {
250 let d = dir(project_state, unit, key);
251 let Ok(text) = std::fs::read_to_string(d.join("draft.json")) else {
252 return Ok(None);
253 };
254 let draft: Draft = serde_json::from_str(&text)
255 .map_err(|e| Tampered(format!("the oracle draft of {key} is not valid: {e}")))?;
256 let mut contents = Vec::new();
257 for t in &draft.tests {
258 let content = std::fs::read_to_string(d.join("files").join(&t.path))
259 .map_err(|_| Tampered(format!("the test {} of {key} is missing", t.path)))?;
260 if digest_of(&content) != t.sha256 {
261 return Err(Tampered(format!("the test {} of {key} changed", t.path)));
262 }
263 contents.push((t.path.clone(), content));
264 }
265 Ok(Some((draft, contents)))
266}
267
268#[must_use]
270pub fn load_frozen(project_state: &Path, unit: &str, key: &str) -> Option<Frozen> {
271 std::fs::read_to_string(dir(project_state, unit, key).join("frozen.json"))
272 .ok()
273 .and_then(|t| serde_json::from_str(&t).ok())
274}
275
276#[must_use]
279pub fn manifest_digest<'a>(
280 tests: impl IntoIterator<Item = (&'a str, &'a str, &'a [String])>,
281) -> String {
282 let mut lines: Vec<String> = tests
283 .into_iter()
284 .map(|(path, sha, argv)| {
285 format!(
286 "{path}={sha} argv={}",
287 serde_json::to_string(argv).unwrap_or_default()
288 )
289 })
290 .collect();
291 lines.sort();
292 digest_of(&lines.join("\n"))
293}
294
295impl Draft {
296 pub fn red(&self) -> impl Iterator<Item = &DraftTest> {
298 self.tests.iter().filter(|t| t.red_class.is_red())
299 }
300
301 #[must_use]
303 pub fn manifest(&self) -> Option<String> {
304 let red: Vec<&DraftTest> = self.red().collect();
305 (!red.is_empty()).then(|| {
306 manifest_digest(
307 red.iter()
308 .map(|t| (t.path.as_str(), t.sha256.as_str(), t.argv.as_slice())),
309 )
310 })
311 }
312
313 pub fn open_ambiguities(&self) -> impl Iterator<Item = &Ambiguity> {
315 self.ambiguities.iter().filter(|a| a.open())
316 }
317
318 fn all_notes(&self) -> Vec<String> {
320 self.rejected
321 .iter()
322 .map(|r| format!("Rejected `{}`: {}", r.path, r.reason))
323 .chain(self.notes.iter().cloned())
324 .collect()
325 }
326}
327
328#[derive(Debug, Clone, Copy)]
330pub struct ViewConfig {
331 pub samples: u8,
333 pub strength_target: Option<u8>,
335 pub held_out: bool,
337 pub acceptance: bool,
339}
340
341impl ViewConfig {
342 #[must_use]
344 pub fn at(root: &Path) -> Self {
345 let rc = crate::verify::find_config(root)
346 .and_then(|d| std::fs::read_to_string(d.join(crate::verify::config::FILE)).ok())
347 .and_then(|t| substrate::run_config::parse(&t).ok())
348 .unwrap_or_default();
349 Self::of(&rc)
350 }
351
352 #[must_use]
354 pub fn of(rc: &substrate::run_config::RunConfig) -> Self {
355 Self {
356 samples: rc.oracle_samples,
357 strength_target: rc.strength.min.map(|m| {
358 let percent = (m * 100.0).round().clamp(0.0, 100.0);
360 format!("{percent:.0}").parse().unwrap_or(0)
361 }),
362 held_out: rc.held_out,
363 acceptance: rc.acceptance,
364 }
365 }
366}
367
368fn test_view(t: &DraftTest, content: &str) -> OracleTest {
369 OracleTest {
370 path: t.path.clone(),
371 content: content.to_owned(),
372 scenarios: t.scenarios.clone(),
373 red_class: crate::pipeline::class_word(t.red_class),
374 red: t.red_class.is_red(),
375 authored_by: t.authored_by,
376 edited_by: t.edited_by.clone(),
377 }
378}
379
380#[must_use]
384pub fn view(
385 project_state: &Path,
386 unit: &str,
387 req: &OracleRequirement,
388 entry: Option<&OracleEntry>,
389 cfg: ViewConfig,
390) -> OracleView {
391 let digest = req.digest();
392 let mut v = OracleView {
393 req: req.key.clone(),
394 title: req.title.clone(),
395 scenarios: req.scenarios.clone(),
396 state: OracleState::None,
397 frozen_on: None,
398 frozen_by: None,
399 frozen_at: None,
400 tests: Vec::new(),
401 discarded: Vec::new(),
402 rejected: Vec::new(),
403 uncovered: req.scenarios.iter().map(|s| s.id.clone()).collect(),
404 untestable: Vec::new(),
405 ambiguities: Vec::new(),
406 held_out: HeldOutSummary {
407 state: if cfg.held_out { "absent" } else { "off" }.to_owned(),
408 count: 0,
409 manifest_sha256: None,
410 reason: None,
411 discarded: Vec::new(),
412 },
413 strength_target: cfg.strength_target,
414 calls: cfg.samples,
415 ambiguity_check: cfg.samples >= 2,
416 manifest_sha256: None,
417 error: (!cfg.acceptance)
418 .then(|| "acceptance tests are off ([acceptance] generate = false)".to_owned()),
419 };
420 let loaded = load(project_state, unit, &req.key);
421 let draft = match loaded {
422 Ok(d) => d,
423 Err(t) => {
424 v.state = OracleState::Failed;
425 v.error = Some(t.0);
426 None
427 }
428 };
429 let current = draft
430 .as_ref()
431 .filter(|(d, _)| d.requirement.sha256 == digest);
432 if let Some((d, contents)) = current {
433 let content = |p: &str| {
434 contents
435 .iter()
436 .find(|(q, _)| q == p)
437 .map(|(_, c)| c.as_str())
438 .unwrap_or_default()
439 };
440 v.tests = d
441 .tests
442 .iter()
443 .map(|t| test_view(t, content(&t.path)))
444 .collect();
445 v.discarded.clone_from(&d.discarded);
446 v.rejected.clone_from(&d.rejected);
447 v.untestable.clone_from(&d.untestable.sample1);
448 v.ambiguities.clone_from(&d.ambiguities);
449 v.held_out = if cfg.held_out {
450 d.held_out.clone()
451 } else {
452 HeldOutSummary {
453 state: "off".to_owned(),
454 count: 0,
455 manifest_sha256: None,
456 reason: None,
457 discarded: Vec::new(),
458 }
459 };
460 v.manifest_sha256 = d.manifest();
461 let covered: Vec<&String> = d.red().flat_map(|t| t.scenarios.iter()).collect();
462 v.uncovered.retain(|s| !covered.contains(&s));
463 v.state = if d.open_ambiguities().next().is_some() {
464 OracleState::Ambiguous
465 } else if d.red().next().is_none() {
466 OracleState::NotRed
467 } else {
468 OracleState::Written
469 };
470 } else if draft.is_some() {
471 v.error = Some("written for an earlier wording: write them again".to_owned());
472 }
473 if let Some(e) = entry {
474 if e.requirement_sha256 == digest {
475 v.frozen_by = Some(e.by.clone());
476 v.frozen_at = Some(e.at);
477 v.state = match crate::pre_frozen::load(project_state, unit, &req.key) {
478 Ok(Some((rec, files))) => {
479 let drafted = current.map(|(d, _)| d);
482 v.tests = rec
483 .visible
484 .iter()
485 .map(|t| {
486 let same = drafted.and_then(|d| {
487 d.tests
488 .iter()
489 .find(|x| x.path == t.path && x.sha256 == t.sha256)
490 });
491 OracleTest {
492 path: t.path.clone(),
493 content: files
494 .iter()
495 .find(|(p, _)| *p == t.path)
496 .map(|(_, c)| c.clone())
497 .unwrap_or_default(),
498 scenarios: t.cites.clone(),
499 red_class: same.map_or_else(
500 || crate::pipeline::class_word(RedClass::Assertion),
501 |x| crate::pipeline::class_word(x.red_class),
502 ),
503 red: true,
504 authored_by: same.map_or(AuthoredBy::Model, |x| x.authored_by),
505 edited_by: same.and_then(|x| x.edited_by.clone()),
506 }
507 })
508 .collect();
509 v.manifest_sha256 = Some(e.manifest_sha256.clone());
510 let covered: Vec<&String> =
511 rec.visible.iter().flat_map(|t| t.cites.iter()).collect();
512 v.uncovered = req
513 .scenarios
514 .iter()
515 .map(|s| s.id.clone())
516 .filter(|s| !covered.contains(&s))
517 .collect();
518 if cfg.held_out {
519 v.held_out = match &rec.held_out_sealed {
520 Some(h) => HeldOutSummary {
521 state: "kept".to_owned(),
522 count: h.count,
523 manifest_sha256: Some(format!("sha256:{}", h.manifest_sha256)),
524 reason: None,
525 discarded: Vec::new(),
526 },
527 None => HeldOutSummary {
528 state: "absent".to_owned(),
529 count: 0,
530 manifest_sha256: None,
531 reason: Some("none_kept".to_owned()),
532 discarded: Vec::new(),
533 },
534 };
535 }
536 OracleState::Frozen
537 }
538 Ok(None) => OracleState::FrozenElsewhere,
539 Err(t) => {
540 v.error = Some(format!("the frozen set was tampered with: {}", t.0));
541 OracleState::Frozen
542 }
543 };
544 } else if current.is_none() {
545 v.state = OracleState::Lapsed;
546 v.frozen_on = load_frozen(project_state, unit, &req.key).map(|f| f.wording);
547 v.frozen_by = Some(e.by.clone());
548 v.frozen_at = Some(e.at);
549 }
550 } else if let Ok(Some((rec, _))) = crate::pre_frozen::load(project_state, unit, &req.key)
551 && rec.producer == Producer::Run
552 && rec.is_current(&digest)
553 {
554 v.state = OracleState::Frozen;
556 v.frozen_by = Some(rec.decided.by.clone());
557 v.frozen_at = Some(rec.decided.at);
558 }
559 v
560}
561
562pub fn open_ambiguities(
569 project_state: &Path,
570 unit: &str,
571 requirements: &[OracleRequirement],
572) -> Result<Vec<(String, String)>, Tampered> {
573 let mut out = Vec::new();
574 for r in requirements {
575 let Some((d, _)) = load(project_state, unit, &r.key)? else {
576 continue;
577 };
578 if d.requirement.sha256 != r.digest() {
579 continue;
580 }
581 out.extend(
582 d.open_ambiguities()
583 .map(|a| (d.requirement.key.clone(), a.scenario.clone())),
584 );
585 }
586 Ok(out)
587}
588
589#[must_use]
591pub fn rung(format: &dyn Adapter, root: &Path, unit: &str) -> Rung {
592 speccoder_core::ladder::rung_of(unit, &format.standing_units(root))
593}
594
595#[derive(Debug, Clone)]
597pub struct Request<'a> {
598 pub req: &'a str,
600 pub op: OracleOp,
602 pub path: Option<&'a str>,
604 pub scenario: Option<&'a str>,
606 pub reading: Option<Reading>,
608 pub text: Option<&'a str>,
610}
611
612impl Request<'_> {
613 #[must_use]
615 pub fn needs_model(&self) -> bool {
616 matches!(self.op, OracleOp::Write | OracleOp::Again)
617 || (self.op == OracleOp::Reading && self.reading == Some(Reading::B))
618 }
619}
620
621struct Ctx {
623 root: PathBuf,
624 feature: String,
625 dir: String,
626 format: &'static dyn Adapter,
627 snapshot: ProjectSnapshot,
628 plane_dir: PathBuf,
629 config: substrate::run_config::RunConfig,
630 sandbox: sandbox::Config,
631 worktree: crate::prepare::Config,
632 state: PathBuf,
634 policy: tools::policy::Policy,
635 model: Option<substrate::model_config::ModelConfig>,
636}
637
638fn refuse(status: CommandStatus, code: &str, message: &str) -> CommandResult {
639 CommandResult::new("review", status, message).with_code(code)
640}
641
642fn open(path: &Path, feature: Option<&str>, state: &Path) -> Result<Ctx, Box<CommandResult>> {
643 let inspected = crate::inspect(path, feature);
644 let Some(CommandData::Inspect(snapshot)) = inspected.data() else {
645 return Err(Box::new(CommandResult::carried("review", &inspected)));
646 };
647 let snapshot = (**snapshot).clone();
648 let Some(f) = snapshot.feature.as_ref() else {
649 return Err(Box::new(CommandResult::new(
650 "review",
651 CommandStatus::SelectionNeeded,
652 inspected.message(),
653 )));
654 };
655 let root = PathBuf::from(&snapshot.root);
656 let config_root = crate::verify::find_config(&root).ok_or_else(|| {
657 Box::new(refuse(
658 CommandStatus::ConfigError,
659 "CONFIG-MISSING",
660 "the project has no speccoder.toml",
661 ))
662 })?;
663 let text =
664 std::fs::read_to_string(config_root.join(crate::verify::config::FILE)).unwrap_or_default();
665 let config = substrate::run_config::parse(&text).map_err(|e| {
666 Box::new(refuse(
667 CommandStatus::ConfigError,
668 "CONFIG-INVALID",
669 &format!("speccoder.toml: {e}"),
670 ))
671 })?;
672 let sandbox = sandbox::parse(&text).map_err(|e| {
673 Box::new(refuse(
674 CommandStatus::ConfigError,
675 "CONFIG-INVALID",
676 &format!("speccoder.toml: {e}"),
677 ))
678 })?;
679 let worktree_config = crate::prepare::parse(&text).map_err(|e| {
680 Box::new(refuse(
681 CommandStatus::ConfigError,
682 "CONFIG-INVALID",
683 &format!("speccoder.toml: {e}"),
684 ))
685 })?;
686 let format = crate::format::of(&snapshot);
687 let policy =
688 tools::policy::Policy::new(&crate::verify::check_argvs(&config_root), &config.allow)
689 .with_prefixes(config.allow_prefix.clone())
690 .rules(format.rules());
691 let model = substrate::model_config::parse(&text).ok().flatten();
692 Ok(Ctx {
693 feature: f.feature.name.clone(),
694 dir: f.feature.dir.clone(),
695 plane_dir: worktree::project_state_dir(state, &root),
696 root,
697 format,
698 snapshot,
699 config,
700 sandbox,
701 worktree: worktree_config,
702 state: state.to_path_buf(),
703 policy,
704 model,
705 })
706}
707
708fn project_in(root: &Path, worktree_root: &Path) -> PathBuf {
710 let canonical = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
711 let top = crate::git::Git::at(root)
712 .toplevel()
713 .ok()
714 .flatten()
715 .map_or_else(|| root.to_path_buf(), |t| canonical(&t));
716 match canonical(root).strip_prefix(&top) {
717 Ok(rel) if !rel.as_os_str().is_empty() => worktree_root.join(rel),
718 _ => worktree_root.to_path_buf(),
719 }
720}
721
722pub(crate) struct UnitLock(PathBuf);
726
727impl UnitLock {
728 pub(crate) fn take(project_state: &Path, unit: &str) -> Result<Self, String> {
729 let path = project_state.join(DIR).join(format!("{unit}.lock"));
730 if let Some(parent) = path.parent() {
731 std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
732 }
733 if std::fs::metadata(&path)
735 .ok()
736 .and_then(|m| m.modified().ok())
737 .and_then(|m| m.elapsed().ok())
738 .is_some_and(|age| age.as_secs() > 3600)
739 {
740 let _ = std::fs::remove_file(&path);
741 }
742 std::fs::OpenOptions::new()
743 .write(true)
744 .create_new(true)
745 .open(&path)
746 .map(|_| Self(path))
747 .map_err(|_| {
748 format!("{unit}'s tests are being written or frozen elsewhere right now: look again when that ends")
749 })
750 }
751}
752
753impl Drop for UnitLock {
754 fn drop(&mut self) {
755 let _ = std::fs::remove_file(&self.0);
756 }
757}
758
759fn stage(options: &crate::RunOptions, req: &str, stage: &str, n: u32, of: u32) {
761 if let Some(p) = &options.progress {
762 p.event(&crate::progress::Event::Oracle {
763 step: crate::progress::OracleEvent::Stage {
764 requirement: req.to_owned(),
765 stage: stage.to_owned(),
766 n,
767 of,
768 },
769 });
770 }
771}
772
773#[must_use]
776pub fn tests(
777 path: &Path,
778 feature: Option<&str>,
779 request: &Request<'_>,
780 via: Via,
781 state: Option<&Path>,
782 options: &crate::RunOptions,
783) -> CommandResult {
784 let Some(state) = state.map(Path::to_path_buf).or_else(worktree::state_dir) else {
785 return refuse(
786 CommandStatus::ConfigError,
787 "NO-STATE-DIR",
788 "no state directory (set SPECCODER_STATE_DIR or HOME)",
789 );
790 };
791 if !request.needs_model() {
792 return tests_with(path, feature, request, via, &state, None, options);
793 }
794 let ctx = match open(path, feature, &state) {
795 Ok(c) => c,
796 Err(r) => return *r,
797 };
798 if let Err(r) = check(&ctx, request) {
799 return *r;
800 }
801 let Some(model) = ctx.model.as_ref() else {
802 return refuse(
803 CommandStatus::ConfigError,
804 "CONFIG",
805 "speccoder.toml has no [model] section: the test author needs a model",
806 );
807 };
808 match substrate::model_config::open_driver(model) {
809 Ok((provider, _)) => {
810 tests_with(path, feature, request, via, &state, Some(provider), options)
811 }
812 Err(e) => substrate::model_config::refused("review", &e),
813 }
814}
815
816#[must_use]
818pub fn tests_with(
819 path: &Path,
820 feature: Option<&str>,
821 request: &Request<'_>,
822 via: Via,
823 state: &Path,
824 provider: Option<Arc<dyn ModelProvider>>,
825 options: &crate::RunOptions,
826) -> CommandResult {
827 let ctx = match open(path, feature, state) {
828 Ok(c) => c,
829 Err(r) => return *r,
830 };
831 let req = match check(&ctx, request) {
832 Ok(r) => r,
833 Err(r) => return *r,
834 };
835 let _lock = match UnitLock::take(&ctx.plane_dir, &ctx.feature) {
836 Ok(l) => l,
837 Err(e) => return refuse(CommandStatus::GitPrecondition, "RUN-ACTIVE", &e),
838 };
839 let who = crate::approvals::Who::local_in(&ctx.root, via);
840 let done = match request.op {
841 OracleOp::Write => write(&ctx, &req, provider, options),
842 OracleOp::Reject => reject(&ctx, &req, request, &who.name),
843 OracleOp::Again => again(&ctx, &req, request, &who.name, provider, options),
844 OracleOp::Edit => edit(&ctx, &req, request, &who.name),
845 OracleOp::Reading => reading(&ctx, &req, request, &who.name, provider, options),
846 };
847 match done {
848 Ok(message) => {
849 let r = crate::review::report_in(path, feature, Some(state));
850 let status = r.status();
851 r.reworded(status, &message)
852 }
853 Err(r) => *r,
854 }
855}
856
857fn check(ctx: &Ctx, request: &Request<'_>) -> Result<OracleRequirement, Box<CommandResult>> {
860 let unit_rung = rung(ctx.format, &ctx.root, &ctx.feature);
861 if unit_rung != Rung::Feature {
862 return Err(Box::new(
863 refuse(
864 CommandStatus::UsageError,
865 "REVIEW-TESTS-OWN-PIPELINE",
866 &format!(
867 "{} is a {} unit: its tests are written and confirmed by its own pipeline",
868 ctx.feature,
869 if unit_rung == Rung::Quick {
870 "quick-change"
871 } else {
872 "bug"
873 }
874 ),
875 )
876 .with_fix(vec![if unit_rung == Rung::Quick {
877 "speccoder do \"…\"".to_owned()
878 } else {
879 format!("speccoder bug confirm {}/<task>", ctx.feature)
880 }]),
881 ));
882 }
883 if !ctx.config.acceptance {
884 return Err(Box::new(refuse(
885 CommandStatus::ConfigError,
886 "ACCEPTANCE-OFF",
887 "acceptance tests are off ([acceptance] generate = false): no tests are written at review",
888 )));
889 }
890 let requirements = ctx.format.oracle_requirements(&ctx.snapshot);
891 let Some(req) = requirements
892 .iter()
893 .find(|r| r.key.eq_ignore_ascii_case(request.req))
894 .cloned()
895 else {
896 return Err(Box::new(refuse(
897 CommandStatus::UsageError,
898 "REVIEW-NO-SCENARIOS",
899 &format!(
900 "the spec has no requirement {}; it names {}",
901 request.req,
902 if requirements.is_empty() {
903 "none with scenarios".to_owned()
904 } else {
905 requirements
906 .iter()
907 .map(|r| r.key.as_str())
908 .collect::<Vec<_>>()
909 .join(", ")
910 }
911 ),
912 )));
913 };
914 if req.scenarios.is_empty() {
915 return Err(Box::new(refuse(
916 CommandStatus::UsageError,
917 "REVIEW-NO-SCENARIOS",
918 &format!(
919 "{} has no acceptance scenarios to write tests from",
920 req.key
921 ),
922 )));
923 }
924 let (entries, _) = crate::review::oracle_entries(&ctx.root, &ctx.dir)
927 .map_err(|e| Box::new(refuse(CommandStatus::NeedsHuman, "REVIEW-UNREADABLE", &e)))?;
928 if let Some(e) = entries
929 .get(&req.key)
930 .filter(|e| e.requirement_sha256 == req.digest())
931 {
932 return Err(Box::new(refuse(
933 CommandStatus::UsageError,
934 "ORACLE-FROZEN",
935 &format!(
936 "{}'s tests were frozen with the approval by {}: the run uses them as frozen — reword {} to lapse the freeze, then write its tests again",
937 req.key, e.by, req.key
938 ),
939 )));
940 }
941 Ok(req)
942}
943
944type Outcome = Result<String, Box<CommandResult>>;
945
946fn failed(message: impl Into<String>) -> Box<CommandResult> {
947 Box::new(refuse(
948 CommandStatus::RunFailed,
949 "ORACLE-AUTHOR-FAILED",
950 &message.into(),
951 ))
952}
953
954fn usage(message: &str) -> Box<CommandResult> {
955 Box::new(refuse(CommandStatus::UsageError, "USAGE", message))
956}
957
958fn existing(ctx: &Ctx, req: &OracleRequirement) -> Result<Loaded, Box<CommandResult>> {
959 match load(&ctx.plane_dir, &ctx.feature, &req.key) {
960 Ok(Some((d, c))) if d.requirement.sha256 == req.digest() => Ok((d, c)),
961 Ok(Some(_)) => Err(usage(&format!(
962 "{}'s tests were written for an earlier wording: write them again (`speccoder review tests {} --write`)",
963 req.key, req.key
964 ))),
965 Ok(None) => Err(usage(&format!(
966 "{} has no tests yet: `speccoder review tests {} --write`",
967 req.key, req.key
968 ))),
969 Err(t) => Err(Box::new(refuse(
970 CommandStatus::NeedsHuman,
971 "ORACLE-TAMPERED",
972 &t.0,
973 ))),
974 }
975}
976
977enum Held<'a, T> {
980 Own(T),
981 Lent(&'a T),
982}
983
984impl<T> std::ops::Deref for Held<'_, T> {
985 type Target = T;
986 fn deref(&self) -> &T {
987 match self {
988 Self::Own(t) => t,
989 Self::Lent(t) => t,
990 }
991 }
992}
993
994struct Author<'a> {
995 ctx: &'a Ctx,
996 rt: Held<'a, tokio::runtime::Runtime>,
997 plane: Held<'a, substrate::Plane>,
998 bundle: Value,
999 instructions: Vec<crate::instructions::Instruction>,
1000 test_layout: String,
1002}
1003
1004impl<'a> Author<'a> {
1005 fn open(
1006 ctx: &'a Ctx,
1007 req: &OracleRequirement,
1008 provider: Option<Arc<dyn ModelProvider>>,
1009 options: &crate::RunOptions,
1010 ) -> Result<Self, Box<CommandResult>> {
1011 let (Some(provider), Some(model)) = (provider, ctx.model.as_ref()) else {
1012 return Err(Box::new(refuse(
1013 CommandStatus::ConfigError,
1014 "CONFIG",
1015 "the test author needs a model ([model] in speccoder.toml)",
1016 )));
1017 };
1018 let rt = crate::pipeline::tokio_runtime().map_err(failed)?;
1019 let plane = rt
1020 .block_on(async {
1021 substrate::Plane::open_with(
1022 &ctx.plane_dir,
1023 model,
1024 provider,
1025 None,
1026 substrate::Hooks {
1027 format: Some(ctx.format),
1028 progress: options.progress.clone(),
1029 ..substrate::Hooks::default()
1030 },
1031 )
1032 })
1033 .map_err(|e| failed(e.0))?;
1034 Ok(Self::with(ctx, req, Held::Own(rt), Held::Own(plane)))
1035 }
1036
1037 fn lent(
1039 ctx: &'a Ctx,
1040 req: &OracleRequirement,
1041 rt: &'a tokio::runtime::Runtime,
1042 plane: &'a substrate::Plane,
1043 ) -> Self {
1044 Self::with(ctx, req, Held::Lent(rt), Held::Lent(plane))
1045 }
1046
1047 fn with(
1048 ctx: &'a Ctx,
1049 req: &OracleRequirement,
1050 rt: Held<'a, tokio::runtime::Runtime>,
1051 plane: Held<'a, substrate::Plane>,
1052 ) -> Self {
1053 let unit_dir = ctx.root.join(&ctx.dir);
1054 let [constitution, _, plan, _] = ctx.format.convergence_texts(&ctx.root, &unit_dir);
1055 let bundle = json!({
1056 "feature": ctx.feature,
1057 "constitution": constitution,
1058 "plan": plan,
1059 "story": req.text,
1060 "task": {
1061 "id": format!("req-{}", req.key),
1062 "title": format!("Acceptance tests for {}: {}", req.key, req.title),
1063 "phase": "Review",
1064 "subsection": "",
1065 "story": req.key,
1066 "parallel": false,
1067 },
1068 "dependencies": [],
1069 });
1070 let instructions =
1071 crate::instructions::collect(&ctx.root, &ctx.root, &[], &ctx.config.instructions);
1072 Self {
1073 ctx,
1074 rt,
1075 plane,
1076 bundle,
1077 instructions,
1078 test_layout: crate::layout::text_at(&ctx.root),
1079 }
1080 }
1081
1082 fn context(
1084 &self,
1085 req: &OracleRequirement,
1086 notes: &[String],
1087 ) -> speccoder_core::context::ContextManifest {
1088 let mut m = crate::context::Manifest::new();
1089 m.push(
1090 ContextKind::Story,
1091 "person",
1092 "/requirement",
1093 req.text.as_bytes(),
1094 );
1095 for s in &req.scenarios {
1096 m.push(
1097 ContextKind::Scenario,
1098 "person",
1099 &format!("/scenarios/{}", s.id),
1100 s.text.as_bytes(),
1101 );
1102 }
1103 m.push(
1104 ContextKind::Constitution,
1105 "worktree",
1106 "/bundle/constitution",
1107 self.bundle["constitution"]
1108 .as_str()
1109 .unwrap_or_default()
1110 .as_bytes(),
1111 );
1112 m.push(
1113 ContextKind::Plan,
1114 "worktree",
1115 "/bundle/plan",
1116 self.bundle["plan"].as_str().unwrap_or_default().as_bytes(),
1117 );
1118 m.push(
1119 ContextKind::TestLayout,
1120 "worktree",
1121 "/test_layout",
1122 self.test_layout.as_bytes(),
1123 );
1124 for (i, n) in notes.iter().enumerate() {
1125 let kind = if n.starts_with("Rejected `") {
1126 ContextKind::Rejection
1127 } else if n.starts_with("Comment ") {
1128 ContextKind::Comment
1129 } else {
1130 ContextKind::Note
1131 };
1132 m.push(kind, "person", &format!("/notes/{i}"), n.as_bytes());
1133 }
1134 m.finish()
1135 }
1136
1137 #[allow(clippy::too_many_arguments)]
1139 fn call(
1140 &self,
1141 req: &OracleRequirement,
1142 files: &[String],
1143 manifest: &str,
1144 notes: &[String],
1145 again: Option<(&str, &str)>,
1146 sample: u8,
1147 ) -> Result<(Value, String, Vec<ContextEntry>), String> {
1148 let context = self.context(req, notes);
1149 let suite = crate::pipeline::acceptance::suite(&self.ctx.root, &req.text);
1150 let input = substrate::acceptance::review_input(&substrate::acceptance::ReviewParts {
1151 bundle: self.bundle.clone(),
1152 requirement: json!({ "key": req.key, "title": req.title, "text": req.text }),
1153 scenarios: &req.scenarios,
1154 files,
1155 manifest,
1156 notes,
1157 again,
1158 instructions: &self.instructions,
1159 context: &context,
1160 sample,
1161 test_layout: Some(&self.test_layout),
1162 suite: &suite,
1163 });
1164 let task = format!("req-{}", req.key);
1165 let outcome = self
1166 .rt
1167 .block_on(self.plane.acceptance(&self.ctx.feature, &task, input))
1168 .map_err(|e| format!("the test author failed: {}", e.0))?;
1169 let output = outcome
1170 .output
1171 .as_ref()
1172 .map(|o| o.peek().clone())
1173 .unwrap_or_default();
1174 let answer = output["answer"].clone();
1175 if !matches!(outcome.status, agentplane::prelude::RunStatus::Succeeded) || answer.is_null()
1176 {
1177 let status = format!("{:?}", outcome.status);
1178 return Err(substrate::provider_refusal(&status).map_or_else(
1179 || {
1180 format!(
1181 "the test author did not answer: {}",
1182 substrate::why_not(&outcome.status)
1183 )
1184 },
1185 |r| format!("the model provider refused the request: {r}"),
1186 ));
1187 }
1188 Ok((answer, outcome.run_id.to_string(), context.entries))
1189 }
1190}
1191
1192fn expectations(
1198 answer: &Value,
1199 req: &OracleRequirement,
1200) -> Result<(Vec<Expectation>, Vec<Untestable>), String> {
1201 let canonical = |id: &str| {
1202 req.scenarios
1203 .iter()
1204 .find(|s| s.id.eq_ignore_ascii_case(id.trim()))
1205 .map(|s| s.id.clone())
1206 .ok_or_else(|| {
1207 format!(
1208 "the test author's expectations name `{id}`, which {} does not have",
1209 req.key
1210 )
1211 })
1212 };
1213 let list = |field: &str| -> Result<Value, String> {
1214 match &answer[field] {
1215 Value::Null => Ok(Value::Array(Vec::new())),
1216 v @ Value::Array(_) => Ok(v.clone()),
1217 _ => Err(format!("the test author's `{field}` is not a list")),
1218 }
1219 };
1220 let mut e: Vec<Expectation> = serde_json::from_value(list("expectations")?)
1221 .map_err(|x| format!("the test author's expectations cannot be read: {x}"))?;
1222 let mut u: Vec<Untestable> = serde_json::from_value(list("untestable")?)
1223 .map_err(|x| format!("the test author's untestable list cannot be read: {x}"))?;
1224 for x in &mut e {
1225 x.scenario = canonical(&x.scenario)?;
1226 }
1227 for x in &mut u {
1228 x.scenario = canonical(&x.scenario)?;
1229 }
1230 if e.is_empty() && u.is_empty() {
1231 return Err(
1232 "the test author stated no expectation for any scenario: the readings cannot be compared"
1233 .to_owned(),
1234 );
1235 }
1236 Ok((e, u))
1237}
1238
1239struct Bench {
1242 root: PathBuf,
1245 _scratch: Option<worktree::Scratch>,
1246 project: PathBuf,
1247 runner: sandbox::Runner,
1248 tmp: PathBuf,
1249}
1250
1251impl Bench {
1252 fn open(ctx: &Ctx) -> Result<Self, Box<CommandResult>> {
1253 let tmp = ctx.plane_dir.join("tmp");
1254 let scratch = worktree::scratch(&ctx.root, &tmp)
1255 .map_err(|e| failed(format!("the scratch worktree could not be made: {}", e.0)))?;
1256 let project = project_in(&ctx.root, &scratch.path);
1257 let (runner, notice) = sandbox::runner(&scratch.path, &ctx.sandbox)
1258 .map_err(|e| Box::new(refuse(CommandStatus::ConfigError, "CONFIG", &e)))?;
1259 if !runner.is_sandboxed() {
1262 return Err(Box::new(
1263 refuse(
1264 CommandStatus::ConfigError,
1265 "SANDBOX-UNAVAILABLE",
1266 &format!(
1267 "the red check runs model-written tests and needs the OS sandbox: {}",
1268 notice.unwrap_or_else(|| "commands would run unsandboxed".to_owned())
1269 ),
1270 )
1271 .with_fix(vec![
1272 "set [sandbox] mode = \"auto\" on a machine with a sandbox backend (speccoder doctor)".to_owned(),
1273 ]),
1274 ));
1275 }
1276 crate::include::copy(&scratch.path, &project, &ctx.root, &ctx.worktree.include).map_err(
1278 |e| {
1279 Box::new(refuse(
1280 CommandStatus::ConfigError,
1281 "PREPARE-FAILED",
1282 &format!("the files [worktree] include names could not be copied: {e}"),
1283 ))
1284 },
1285 )?;
1286 if ctx.worktree.prepare && crate::prepare::needed(&project) {
1287 crate::prepare::prepare(&crate::prepare::Prepare {
1288 worktree: &scratch.path,
1289 project: &project,
1290 config: &ctx.worktree,
1291 runner: &runner,
1292 state: Some(&ctx.state),
1293 })
1294 .map_err(|f| {
1295 Box::new(
1296 refuse(CommandStatus::ConfigError, "PREPARE-FAILED", &f.message)
1297 .with_fix(f.fix)
1298 .with_commands(f.commands),
1299 )
1300 })?;
1301 }
1302 Ok(Self {
1303 root: scratch.path.clone(),
1304 _scratch: Some(scratch),
1305 project,
1306 runner,
1307 tmp,
1308 })
1309 }
1310
1311 fn here(ctx: &Ctx, wt_root: &Path, runner: sandbox::Runner) -> Self {
1314 Self {
1315 root: wt_root.to_path_buf(),
1316 _scratch: None,
1317 project: ctx.root.clone(),
1318 runner,
1319 tmp: ctx.plane_dir.join("tmp"),
1320 }
1321 }
1322
1323 fn files(&self) -> (Vec<String>, String) {
1324 let files: Vec<String> = worktree::checkpoint(&self.root, &self.tmp)
1325 .and_then(|c| worktree::files(&self.root, &c))
1326 .unwrap_or_default()
1327 .into_iter()
1328 .take(400)
1329 .collect();
1330 let manifest = crate::pipeline::MANIFESTS
1331 .iter()
1332 .find_map(|m| {
1333 std::fs::read_to_string(self.project.join(m))
1334 .ok()
1335 .map(|t| format!("{m}:\n{t}"))
1336 })
1337 .map(|t| t.chars().take(8192).collect::<String>())
1338 .unwrap_or_default();
1339 (files, manifest)
1340 }
1341
1342 fn red(
1348 &self,
1349 tests: &[(String, String, Vec<String>)],
1350 ) -> Result<Vec<Result<RedClass, &'static str>>, String> {
1351 let mut out = Vec::new();
1352 for (path, content, argv) in tests {
1353 let full = self.project.join(path);
1354 let _ = std::fs::remove_file(&full);
1355 let run = || crate::pipeline::acceptance_run(&self.project, argv, &self.runner);
1356 let (bare, summary) = run();
1357 if classify_red(&bare, summary.as_ref()).is_red() {
1358 out.push(Err("red_without_it"));
1359 continue;
1360 }
1361 if let Some(parent) = full.parent() {
1362 std::fs::create_dir_all(parent).map_err(|e| format!("{path}: {e}"))?;
1363 }
1364 std::fs::write(&full, content).map_err(|e| format!("{path}: {e}"))?;
1365 let (first, summary) = run();
1366 let class = classify_red(&first, summary.as_ref());
1367 let class = if !class.is_red() {
1368 class
1369 } else {
1370 let (second, summary) = run();
1371 if classify_red(&second, summary.as_ref()).is_red() {
1372 class
1373 } else {
1374 RedClass::Flaky
1375 }
1376 };
1377 std::fs::remove_file(&full).map_err(|e| format!("{path}: {e}"))?;
1378 out.push(Ok(class));
1379 }
1380 Ok(out)
1381 }
1382}
1383
1384fn keep(
1386 ctx: &Ctx,
1387 bench: &Bench,
1388 answer: &Value,
1389 req: &OracleRequirement,
1390 taken: &[(String, Vec<String>)],
1391) -> (Vec<Kept>, Vec<OracleDiscarded>) {
1392 let (valid, refused) =
1393 crate::pipeline::validate_answer(answer, &bench.project, &ctx.policy, &req.scenarios);
1394 let mut discarded: Vec<OracleDiscarded> = refused
1395 .into_iter()
1396 .map(|r| OracleDiscarded {
1397 path: r.path,
1398 why: r.why.to_owned(),
1399 })
1400 .collect();
1401 let set_argv: Vec<String> = crate::pipeline::acceptance::argv_of(&answer["argv"]);
1402 let layout = crate::layout::detect(&bench.project, &crate::verify::check_argvs(&ctx.root));
1403 let mut kept = Vec::new();
1404 for f in valid {
1405 let mut discard = |why: &str| {
1406 discarded.push(OracleDiscarded {
1407 path: f.path.clone(),
1408 why: why.to_owned(),
1409 });
1410 };
1411 if f.cited.is_empty() {
1412 discard("cites_no_scenario");
1413 continue;
1414 }
1415 if taken.iter().any(|(p, _)| *p == f.path)
1416 || kept.iter().any(|(p, ..): &(String, _, _, _)| *p == f.path)
1417 {
1418 discard("exists");
1419 continue;
1420 }
1421 let argv = if f.argv.is_empty() {
1422 set_argv.clone()
1423 } else {
1424 f.argv.clone()
1425 };
1426 if taken.iter().any(|(_, a)| *a == argv)
1429 || kept
1430 .iter()
1431 .any(|(.., a): &(_, _, _, Vec<String>)| *a == argv)
1432 {
1433 discard("command_shared");
1434 continue;
1435 }
1436 if argv.is_empty()
1437 || !crate::pipeline::test_command_allowed(
1438 &ctx.policy,
1439 Some(&layout),
1440 &argv,
1441 &[f.path.as_str()],
1442 )
1443 {
1444 discard("command_not_allowed");
1445 continue;
1446 }
1447 if kept.len() + taken.len() >= LIMIT {
1448 discard("limit");
1449 continue;
1450 }
1451 kept.push((f.path, f.content, f.cited, argv));
1452 }
1453 (kept, discarded)
1454}
1455
1456fn write(
1459 ctx: &Ctx,
1460 req: &OracleRequirement,
1461 provider: Option<Arc<dyn ModelProvider>>,
1462 options: &crate::RunOptions,
1463) -> Outcome {
1464 let samples = ctx.config.oracle_samples.clamp(1, 2);
1465 let author = Author::open(ctx, req, provider, options)?;
1466 let bench = Bench::open(ctx)?;
1467 let earlier = load(&ctx.plane_dir, &ctx.feature, &req.key).map_err(|t| {
1470 Box::new(
1471 refuse(
1472 CommandStatus::NeedsHuman,
1473 "ORACLE-TAMPERED",
1474 &format!(
1475 "{}: writing anew would lose the rejections and notes it holds",
1476 t.0
1477 ),
1478 )
1479 .with_fix(vec![format!(
1480 "→ restore it, or remove {} to start {}'s tests over",
1481 dir(&ctx.plane_dir, &ctx.feature, &req.key).display(),
1482 req.key
1483 )]),
1484 )
1485 })?;
1486 let (rejected, mut notes) = earlier
1487 .as_ref()
1488 .filter(|(d, _)| d.requirement.sha256 == req.digest())
1489 .map(|(d, _)| (d.rejected.clone(), d.notes.clone()))
1490 .unwrap_or_default();
1491 notes.dedup();
1492 let told: Vec<String> = rejected
1493 .iter()
1494 .map(|r| format!("Rejected `{}`: {}", r.path, r.reason))
1495 .chain(notes.iter().cloned())
1496 .collect();
1497 let (draft, contents) = draft(
1498 ctx, req, &author, &bench, samples, &told, rejected, notes, true, options,
1499 )?;
1500 store(&ctx.plane_dir, &ctx.feature, &draft, &contents).map_err(failed)?;
1501 let red = draft.red().count();
1502 let open = draft.open_ambiguities().count();
1503 Ok(format!(
1504 "wrote {} test(s) for {}: {red} red{}{}",
1505 draft.tests.len(),
1506 req.key,
1507 if draft.held_out.state == "kept" {
1508 format!(", {} held out", draft.held_out.count)
1509 } else {
1510 String::new()
1511 },
1512 if open > 0 {
1513 format!(
1514 "; {} — {open} scenario(s) read two ways: choose a reading or reword (`speccoder review tests {} --reading A|B <scenario>`)",
1515 req.key, req.key
1516 )
1517 } else {
1518 String::new()
1519 }
1520 ))
1521}
1522
1523#[allow(clippy::too_many_arguments)]
1526fn draft(
1527 ctx: &Ctx,
1528 req: &OracleRequirement,
1529 author: &Author<'_>,
1530 bench: &Bench,
1531 samples: u8,
1532 told: &[String],
1533 rejected: Vec<OracleRejected>,
1534 notes: Vec<String>,
1535 with_held_out: bool,
1536 options: &crate::RunOptions,
1537) -> Result<Loaded, Box<CommandResult>> {
1538 let (files, manifest) = bench.files();
1539 let of = u32::from(samples);
1540 stage(options, &req.key, "writing", 1, of);
1541 let (first, run1, mut context) = author
1542 .call(req, &files, &manifest, told, None, 1)
1543 .map_err(failed)?;
1544 let read = |answer: &Value| {
1547 let got = expectations(answer, req);
1548 if samples >= 2 {
1549 got.map_err(failed)
1550 } else {
1551 Ok(got.unwrap_or_default())
1552 }
1553 };
1554 let (e1, u1) = read(&first)?;
1555 let mut runs = vec![run1];
1556 let (mut e2, mut u2) = (Vec::new(), Vec::new());
1557 if samples >= 2 {
1558 stage(options, &req.key, "writing", 2, of);
1559 let (second, run2, more) = author
1560 .call(req, &files, &manifest, told, None, 2)
1561 .map_err(failed)?;
1562 (e2, u2) = read(&second)?;
1563 runs.push(run2);
1564 for c in more {
1565 if !context.contains(&c) {
1566 context.push(c);
1567 }
1568 }
1569 stage(options, &req.key, "comparing", 1, 1);
1570 }
1571 let ambiguities = if samples >= 2 {
1572 speccoder_core::oracle::compare(&e1, &u1, &e2, &u2)
1573 } else {
1574 Vec::new()
1575 };
1576 let (kept, mut discarded) = keep(ctx, bench, &first, req, &[]);
1577 stage(options, &req.key, "checking_red", 1, 1);
1578 let plan: Vec<(String, String, Vec<String>)> = kept
1579 .iter()
1580 .map(|(p, c, _, a)| (p.clone(), c.clone(), a.clone()))
1581 .collect();
1582 let classes = bench.red(&plan).map_err(failed)?;
1583 let mut tests: Vec<DraftTest> = Vec::new();
1584 let mut contents: Vec<(String, String)> = Vec::new();
1585 for ((path, content, cited, argv), class) in kept.into_iter().zip(classes) {
1586 match class {
1587 Ok(red_class) => {
1588 tests.push(DraftTest {
1589 path: path.clone(),
1590 sha256: digest_of(&content),
1591 scenarios: cited,
1592 argv,
1593 red_class,
1594 authored_by: AuthoredBy::Model,
1595 edited_by: None,
1596 });
1597 contents.push((path, content));
1598 }
1599 Err(why) => discarded.push(OracleDiscarded {
1600 path,
1601 why: why.to_owned(),
1602 }),
1603 }
1604 }
1605 let (held_out, sealed) = if with_held_out {
1607 held_out(ctx, author, bench, req, &tests, options)
1608 } else {
1609 (
1610 HeldOutSummary {
1611 state: "off".to_owned(),
1612 count: 0,
1613 manifest_sha256: None,
1614 reason: None,
1615 discarded: Vec::new(),
1616 },
1617 None,
1618 )
1619 };
1620 let draft = Draft {
1621 requirement: DraftRequirement {
1622 key: req.key.clone(),
1623 title: req.title.clone(),
1624 text: req.text.clone(),
1625 sha256: req.digest(),
1626 },
1627 samples,
1628 tests,
1629 discarded,
1630 rejected,
1631 expectations: Samples {
1632 sample1: e1,
1633 sample2: e2,
1634 },
1635 untestable: Samples {
1636 sample1: u1,
1637 sample2: u2,
1638 },
1639 ambiguities,
1640 held_out,
1641 sealed,
1642 notes,
1643 runs,
1644 context,
1645 };
1646 Ok((draft, contents))
1647}
1648
1649fn held_out(
1653 ctx: &Ctx,
1654 author: &Author<'_>,
1655 bench: &Bench,
1656 req: &OracleRequirement,
1657 tests: &[DraftTest],
1658 options: &crate::RunOptions,
1659) -> (HeldOutSummary, Option<SealedRef>) {
1660 let summary = |state: &str, reason: Option<&str>| HeldOutSummary {
1661 state: state.to_owned(),
1662 count: 0,
1663 manifest_sha256: None,
1664 reason: reason.map(str::to_owned),
1665 discarded: Vec::new(),
1666 };
1667 if !ctx.config.held_out {
1668 return (summary("off", None), None);
1669 }
1670 let red: Vec<&DraftTest> = tests.iter().filter(|t| t.red_class.is_red()).collect();
1671 if red.is_empty() {
1672 return (summary("absent", Some("not_red")), None);
1673 }
1674 stage(options, &req.key, "held_out", 1, 1);
1675 let visible = crate::pipeline::PreparedAcceptance {
1676 report: json!({ "files": red.iter().map(|t| t.path.clone()).collect::<Vec<_>>() }),
1677 argv: red.first().map(|t| t.argv.clone()),
1678 more_argv: Vec::new(),
1679 red: true,
1680 red_class: Some(RedClass::Assertion),
1681 held_out: None,
1682 generation_failed: None,
1683 skip_cause: None,
1684 };
1685 let task = format!("req-{}", req.key);
1686 let store = crate::held_out::sealed_dir(&ctx.plane_dir, &ctx.feature, &req.key);
1687 let (report, sha) = crate::pipeline::prepare_held_out(
1688 &crate::pipeline::AcceptanceSetup {
1689 rt: &author.rt,
1690 plane: &author.plane,
1691 project: &bench.project,
1692 worktree: &bench.root,
1693 tmp: &bench.tmp,
1694 policy: &ctx.policy,
1695 feature: &ctx.feature,
1696 task: &task,
1697 bundle: author.bundle.clone(),
1698 scenarios: &req.scenarios,
1699 instructions: &author.instructions,
1700 runner: &bench.runner,
1701 layout: None,
1702 told: &[],
1703 },
1704 &visible,
1705 &req.scenarios,
1706 &store,
1707 false,
1708 );
1709 match sha {
1710 Some(sha) => {
1711 let count = report["kept"]
1712 .as_u64()
1713 .and_then(|n| usize::try_from(n).ok())
1714 .unwrap_or(0);
1715 (
1716 HeldOutSummary {
1717 state: "kept".to_owned(),
1718 count,
1719 manifest_sha256: Some(format!("sha256:{sha}")),
1720 reason: None,
1721 discarded: Vec::new(),
1722 },
1723 Some(SealedRef {
1724 key: req.key.clone(),
1725 manifest_sha256: sha,
1726 count,
1727 }),
1728 )
1729 }
1730 None => (
1731 HeldOutSummary {
1732 discarded: report["discarded"]
1733 .as_array()
1734 .into_iter()
1735 .flatten()
1736 .filter_map(|d| d["reason"].as_str().map(str::to_owned))
1737 .collect(),
1738 ..summary(
1739 "absent",
1740 Some(report["reason"].as_str().unwrap_or("none_kept")),
1741 )
1742 },
1743 None,
1744 ),
1745 }
1746}
1747
1748fn reject(ctx: &Ctx, req: &OracleRequirement, r: &Request<'_>, by: &str) -> Outcome {
1749 let Some(path) = r.path else {
1750 return Err(usage("name the test to reject (--reject PATH)"));
1751 };
1752 let Some(reason) = r.text.map(str::trim).filter(|t| !t.is_empty()) else {
1753 return Err(usage(
1754 "a rejection needs a reason: why is this test wrong? (--reason \"…\")",
1755 ));
1756 };
1757 let (mut d, contents) = existing(ctx, req)?;
1758 let Some(at) = d.tests.iter().position(|t| t.path == path) else {
1759 return Err(usage(&format!("{} has no test {path}", req.key)));
1760 };
1761 d.tests.remove(at);
1762 d.rejected.push(OracleRejected {
1763 path: path.to_owned(),
1764 reason: reason.to_owned(),
1765 by: by.to_owned(),
1766 at: now(),
1767 });
1768 store(&ctx.plane_dir, &ctx.feature, &d, &contents).map_err(failed)?;
1769 Ok(format!(
1770 "rejected {path} of {}: \"{reason}\" — later author calls for {} are told",
1771 req.key, req.key
1772 ))
1773}
1774
1775fn edit(ctx: &Ctx, req: &OracleRequirement, r: &Request<'_>, by: &str) -> Outcome {
1776 let Some(path) = r.path else {
1777 return Err(usage("name the test to edit (--edit PATH)"));
1778 };
1779 let Some(content) = r.text.filter(|t| !t.trim().is_empty()) else {
1780 return Err(usage("an edit needs the test's new content (--from FILE)"));
1781 };
1782 let (mut d, mut contents) = existing(ctx, req)?;
1783 let Some(at) = d.tests.iter().position(|t| t.path == path) else {
1784 return Err(usage(&format!("{} has no test {path}", req.key)));
1785 };
1786 let bench = Bench::open(ctx)?;
1787 let plan = [(
1788 path.to_owned(),
1789 content.to_owned(),
1790 d.tests[at].argv.clone(),
1791 )];
1792 let checked = bench
1793 .red(&plan)
1794 .map_err(failed)?
1795 .pop()
1796 .unwrap_or(Ok(RedClass::Unclassified));
1797 let class = checked.unwrap_or(RedClass::Unclassified);
1799 let t = &mut d.tests[at];
1800 t.sha256 = digest_of(content);
1801 t.red_class = class;
1802 t.authored_by = AuthoredBy::Person;
1803 t.edited_by = Some(by.to_owned());
1804 if let Some(c) = contents.iter_mut().find(|(p, _)| p == path) {
1805 c.1 = content.to_owned();
1806 }
1807 store(&ctx.plane_dir, &ctx.feature, &d, &contents).map_err(failed)?;
1808 Ok(format!(
1809 "edited {path} of {}: {}",
1810 req.key,
1811 if class.is_red() {
1812 format!("red ({})", crate::pipeline::class_word(class))
1813 } else if checked.is_err() {
1814 "its command is red without it — it decides nothing about this test, which cannot be frozen".to_owned()
1815 } else {
1816 format!(
1817 "not red ({}) — no evidence, it cannot be frozen",
1818 crate::pipeline::class_word(class)
1819 )
1820 }
1821 ))
1822}
1823
1824#[allow(clippy::too_many_arguments)]
1827fn rewrite(
1828 ctx: &Ctx,
1829 req: &OracleRequirement,
1830 mut d: Draft,
1831 mut contents: Vec<(String, String)>,
1832 replaced: &[String],
1833 note: String,
1834 again: Option<(&str, &str)>,
1835 only: Option<&str>,
1836 provider: Option<Arc<dyn ModelProvider>>,
1837 options: &crate::RunOptions,
1838) -> Result<(Draft, Vec<String>), Box<CommandResult>> {
1839 let author = Author::open(ctx, req, provider, options)?;
1840 let bench = Bench::open(ctx)?;
1841 let (files, manifest) = bench.files();
1842 d.notes.push(note);
1843 let told = d.all_notes();
1844 stage(options, &req.key, "writing", 1, 1);
1845 let (answer, run, context) = author
1846 .call(req, &files, &manifest, &told, again, 1)
1847 .map_err(failed)?;
1848 d.runs.push(run);
1849 for c in context {
1850 if !d.context.contains(&c) {
1851 d.context.push(c);
1852 }
1853 }
1854 let keep_paths: Vec<(String, Vec<String>)> = d
1855 .tests
1856 .iter()
1857 .filter(|t| !replaced.contains(&t.path))
1858 .map(|t| (t.path.clone(), t.argv.clone()))
1859 .collect();
1860 let mut answer = answer;
1862 if let Some(files) = answer["files"].as_array_mut() {
1863 files.retain(|f| {
1864 only.is_none_or(|s| {
1865 f["scenarios"]
1866 .as_array()
1867 .is_some_and(|c| c.iter().any(|v| v.as_str() == Some(s)))
1868 })
1869 });
1870 }
1871 let (new, discarded) = keep(ctx, &bench, &answer, req, &keep_paths);
1872 if new.is_empty() {
1873 return Err(failed(format!(
1874 "the test author wrote no usable test{}",
1875 discarded
1876 .first()
1877 .map(|x| format!(" ({} {})", x.path, x.why))
1878 .unwrap_or_default()
1879 )));
1880 }
1881 d.tests.retain(|t| !replaced.contains(&t.path));
1882 contents.retain(|(p, _)| !replaced.contains(p));
1883 d.discarded.extend(discarded);
1884 stage(options, &req.key, "checking_red", 1, 1);
1885 let plan: Vec<(String, String, Vec<String>)> = new
1887 .iter()
1888 .map(|(p, c, _, a)| (p.clone(), c.clone(), a.clone()))
1889 .collect();
1890 let classes = bench.red(&plan).map_err(failed)?;
1891 let mut written = Vec::new();
1892 for ((path, content, cited, argv), class) in new.into_iter().zip(classes) {
1893 let red_class = match class {
1894 Ok(c) => c,
1895 Err(why) => {
1896 d.discarded.push(OracleDiscarded {
1897 path,
1898 why: why.to_owned(),
1899 });
1900 continue;
1901 }
1902 };
1903 d.tests.push(DraftTest {
1904 sha256: digest_of(&content),
1905 scenarios: cited,
1906 argv,
1907 red_class,
1908 authored_by: AuthoredBy::Model,
1909 edited_by: None,
1910 path: path.clone(),
1911 });
1912 contents.push((path.clone(), content));
1913 written.push(path);
1914 }
1915 store(&ctx.plane_dir, &ctx.feature, &d, &contents).map_err(failed)?;
1916 Ok((d, written))
1917}
1918
1919fn again(
1920 ctx: &Ctx,
1921 req: &OracleRequirement,
1922 r: &Request<'_>,
1923 _by: &str,
1924 provider: Option<Arc<dyn ModelProvider>>,
1925 options: &crate::RunOptions,
1926) -> Outcome {
1927 let Some(path) = r.path else {
1928 return Err(usage("name the test to write again (--again PATH)"));
1929 };
1930 let comment = r
1931 .text
1932 .map(str::trim)
1933 .filter(|t| !t.is_empty())
1934 .unwrap_or("write it again");
1935 let (d, contents) = existing(ctx, req)?;
1936 let Some(content) = contents
1937 .iter()
1938 .find(|(p, _)| p == path)
1939 .map(|(_, c)| c.clone())
1940 else {
1941 return Err(usage(&format!("{} has no test {path}", req.key)));
1942 };
1943 let (d, written) = rewrite(
1944 ctx,
1945 req,
1946 d,
1947 contents,
1948 &[path.to_owned()],
1949 format!("Comment on `{path}`: {comment}"),
1950 Some((path, &content)),
1951 None,
1952 provider,
1953 options,
1954 )?;
1955 let red = d
1956 .tests
1957 .iter()
1958 .filter(|t| written.contains(&t.path) && t.red_class.is_red())
1959 .count();
1960 Ok(format!(
1961 "wrote {path} of {} again: {}",
1962 req.key,
1963 if written.is_empty() {
1964 "nothing kept — its command is red without it, so it decides nothing".to_owned()
1965 } else if red == written.len() {
1966 "red".to_owned()
1967 } else {
1968 "not red — no evidence, it cannot be frozen".to_owned()
1969 }
1970 ))
1971}
1972
1973fn reading(
1974 ctx: &Ctx,
1975 req: &OracleRequirement,
1976 r: &Request<'_>,
1977 by: &str,
1978 provider: Option<Arc<dyn ModelProvider>>,
1979 options: &crate::RunOptions,
1980) -> Outcome {
1981 let (Some(scenario), Some(choice)) = (r.scenario, r.reading) else {
1982 return Err(usage(
1983 "name the reading and the scenario (--reading A|B US1-2)",
1984 ));
1985 };
1986 let (mut d, contents) = existing(ctx, req)?;
1987 let Some(item) = d.ambiguities.iter_mut().find(|a| a.scenario == scenario) else {
1988 return Err(usage(&format!(
1989 "{} has no ambiguity on {scenario}",
1990 req.key
1991 )));
1992 };
1993 item.resolution = Some(Resolution {
1994 reading: choice,
1995 by: by.to_owned(),
1996 at: now(),
1997 });
1998 let meant = if choice == Reading::A {
1999 item.a.clone()
2000 } else {
2001 item.b.clone()
2002 };
2003 if choice == Reading::A {
2004 d.notes.push(format!(
2005 "For {scenario} the person means reading A: given {}, expect {}",
2006 meant.given, meant.expect
2007 ));
2008 store(&ctx.plane_dir, &ctx.feature, &d, &contents).map_err(failed)?;
2009 return Ok(format!(
2010 "{scenario} of {}: reading A is meant — the tests stay",
2011 req.key
2012 ));
2013 }
2014 let replaced: Vec<String> = d
2015 .tests
2016 .iter()
2017 .filter(|t| t.scenarios.iter().any(|s| s == scenario))
2018 .map(|t| t.path.clone())
2019 .collect();
2020 let (_, written) = rewrite(
2021 ctx,
2022 req,
2023 d,
2024 contents,
2025 &replaced,
2026 format!(
2027 "For {scenario} the person means reading B: given {}, expect {}",
2028 meant.given, meant.expect
2029 ),
2030 None,
2031 Some(scenario),
2032 provider,
2033 options,
2034 )?;
2035 Ok(format!(
2036 "{scenario} of {}: reading B is meant — wrote {} anew",
2037 req.key,
2038 written.join(", ")
2039 ))
2040}
2041
2042#[derive(Debug, Clone)]
2045pub struct Freezable {
2046 pub req: OracleRequirement,
2048 pub draft: Draft,
2050 pub contents: Vec<(String, String)>,
2052 pub manifest: String,
2054}
2055
2056pub fn freezable(
2059 project_state: &Path,
2060 unit: &str,
2061 requirements: &[OracleRequirement],
2062) -> Result<Vec<Freezable>, Tampered> {
2063 let mut out = Vec::new();
2064 for r in requirements {
2065 let Some((draft, contents)) = load(project_state, unit, &r.key)? else {
2066 continue;
2067 };
2068 if draft.requirement.sha256 != r.digest() || draft.open_ambiguities().next().is_some() {
2069 continue;
2070 }
2071 let Some(manifest) = draft.manifest() else {
2072 continue;
2073 };
2074 let red: Vec<String> = draft.red().map(|t| t.path.clone()).collect();
2075 out.push(Freezable {
2076 req: r.clone(),
2077 contents: contents
2078 .into_iter()
2079 .filter(|(p, _)| red.contains(p))
2080 .collect(),
2081 draft,
2082 manifest,
2083 });
2084 }
2085 Ok(out)
2086}
2087
2088pub fn freeze(
2092 project_state: &Path,
2093 unit: &str,
2094 f: &Freezable,
2095 approval_digest: &str,
2096 decided: Decided,
2097 producer: Producer,
2098) -> Result<PreFrozenAcceptance, String> {
2099 let red: Vec<&DraftTest> = f.draft.red().collect();
2100 freeze_tests(
2101 project_state,
2102 unit,
2103 f,
2104 &red,
2105 approval_digest,
2106 decided,
2107 producer,
2108 )
2109}
2110
2111fn freeze_tests(
2113 project_state: &Path,
2114 unit: &str,
2115 f: &Freezable,
2116 red: &[&DraftTest],
2117 approval_digest: &str,
2118 decided: Decided,
2119 producer: Producer,
2120) -> Result<PreFrozenAcceptance, String> {
2121 let sealed = match &f.draft.sealed {
2122 Some(s) => {
2123 crate::held_out::open_sealed(project_state, unit, s)
2124 .map_err(|t| format!("{}'s held-out set was tampered with: {}", f.req.key, t.0))?;
2125 Some(s.clone())
2126 }
2127 None => None,
2128 };
2129 let record = PreFrozenAcceptance {
2130 unit: unit.to_owned(),
2131 requirement: f.req.key.clone(),
2132 wording_digest: f.draft.requirement.sha256.clone(),
2133 approval_digest: approval_digest.to_owned(),
2134 visible: red
2135 .iter()
2136 .map(|t| VisibleTest {
2137 path: t.path.clone(),
2138 sha256: t.sha256.clone(),
2139 cites: t.scenarios.clone(),
2140 })
2141 .collect(),
2142 held_out_sealed: sealed,
2143 producer,
2144 decided,
2145 };
2146 crate::pre_frozen::store(project_state, &record, &f.contents)?;
2147 let frozen = Frozen {
2148 requirement_sha256: f.draft.requirement.sha256.clone(),
2149 wording: format!(
2150 "{}\n{}",
2151 f.draft.requirement.title, f.draft.requirement.text
2152 ),
2153 manifest_sha256: f.manifest.clone(),
2154 tests: red
2155 .iter()
2156 .map(|t| FrozenTest {
2157 path: t.path.clone(),
2158 sha256: t.sha256.clone(),
2159 argv: t.argv.clone(),
2160 scenarios: t.scenarios.clone(),
2161 })
2162 .collect(),
2163 };
2164 let text = serde_json::to_string_pretty(&frozen).map_err(|e| e.to_string())?;
2165 write_atomic(
2166 &dir(project_state, unit, &f.req.key).join("frozen.json"),
2167 &text,
2168 )?;
2169 Ok(record)
2170}
2171
2172fn not_kept(t: &DraftTest, many: bool) -> Option<String> {
2179 if many && t.scenarios.len() > 1 {
2180 return Some(format!(
2181 "it tests {} together — one file per scenario, so each turns green on its own",
2182 t.scenarios.join(", ")
2183 ));
2184 }
2185 (!usable(t)).then(|| format!("it did not fail on an assertion ({:?})", t.red_class))
2186}
2187
2188fn usable(t: &DraftTest) -> bool {
2189 match t.red_class {
2190 RedClass::Assertion | RedClass::Passed => true,
2191 RedClass::Absent => [".rs", ".go", ".java", ".kt", ".cs", ".swift"]
2192 .iter()
2193 .any(|e| t.path.ends_with(e)),
2194 _ => false,
2195 }
2196}
2197
2198#[derive(Debug)]
2202pub(crate) struct RunOracle {
2203 pub tests: Vec<FrozenTest>,
2206 pub contents: Vec<(String, String)>,
2208 pub contracts: Vec<Expectation>,
2210 pub untestable: Vec<Untestable>,
2212}
2213
2214#[allow(clippy::too_many_arguments)]
2221pub(crate) fn write_for_run(
2222 project: &Path,
2223 wt_root: &Path,
2224 feature: &str,
2225 state: &Path,
2226 story: &str,
2227 runner: sandbox::Runner,
2228 (rt, plane): (&tokio::runtime::Runtime, &substrate::Plane),
2229 (only, told): (&[String], &[String]),
2230 run: &str,
2231 options: &crate::RunOptions,
2232) -> Result<RunOracle, Box<CommandResult>> {
2233 let ctx = open(project, Some(feature), state)?;
2234 let requirements = ctx.format.oracle_requirements(&ctx.snapshot);
2235 let whole = (story == ctx.feature && !requirements.iter().any(|r| r.key == story)).then(|| {
2237 OracleRequirement {
2238 key: story.to_owned(),
2239 title: ctx.feature.clone(),
2240 text: requirements
2241 .iter()
2242 .map(|r| format!("{}: {}\n{}", r.key, r.title, r.text))
2243 .collect::<Vec<_>>()
2244 .join("\n\n"),
2245 scenarios: requirements
2246 .iter()
2247 .flat_map(|r| r.scenarios.clone())
2248 .collect(),
2249 }
2250 });
2251 let Some(mut req) = whole.or_else(|| requirements.into_iter().find(|r| r.key == story)) else {
2252 return Err(Box::new(refuse(
2253 CommandStatus::NeedsHuman,
2254 "ORACLE-UNWRITTEN",
2255 &format!("{story} has no scenarios to write tests for"),
2256 )));
2257 };
2258 if !only.is_empty() {
2260 req.scenarios.retain(|s| only.contains(&s.id));
2261 }
2262 let _lock = UnitLock::take(&ctx.plane_dir, &ctx.feature)
2263 .map_err(|e| Box::new(refuse(CommandStatus::GitPrecondition, "RUN-ACTIVE", &e)))?;
2264 let author = Author::lent(&ctx, &req, rt, plane);
2265 let many = req.scenarios.len() > 1;
2266 let bench = Bench::here(&ctx, wt_root, runner);
2267 let kept = |d: &Draft| -> Vec<String> {
2268 let mut covered: Vec<String> = d
2269 .tests
2270 .iter()
2271 .filter(|t| not_kept(t, many).is_none())
2272 .flat_map(|t| t.scenarios.iter().cloned())
2273 .collect();
2274 covered.sort();
2275 covered.dedup();
2276 covered
2277 };
2278 let (mut draft, mut contents) = draft(
2279 &ctx,
2280 &req,
2281 &author,
2282 &bench,
2283 1,
2284 told,
2285 Vec::new(),
2286 told.to_vec(),
2287 only.is_empty(),
2288 options,
2289 )?;
2290 let missing = |d: &Draft| -> Vec<String> {
2291 let covered = kept(d);
2292 req.scenarios
2293 .iter()
2294 .map(|s| s.id.clone())
2295 .filter(|id| !covered.contains(id))
2296 .collect()
2297 };
2298 let untestable: Vec<String> = draft
2302 .untestable
2303 .sample1
2304 .iter()
2305 .map(|u| u.scenario.clone())
2306 .collect();
2307 let broke =
2308 !draft.discarded.is_empty() || draft.tests.iter().any(|t| not_kept(t, many).is_some());
2309 let left: Vec<String> = missing(&draft)
2310 .into_iter()
2311 .filter(|id| !untestable.contains(id))
2312 .collect();
2313 if broke && !left.is_empty() {
2314 let told: Vec<String> = draft
2315 .discarded
2316 .iter()
2317 .map(|d| format!("Not kept `{}`: {}", d.path, d.why))
2318 .chain(draft.tests.iter().filter_map(|t| {
2319 not_kept(t, many).map(|why| format!("Not kept `{}`: {why}", t.path))
2320 }))
2321 .chain(std::iter::once(format!(
2322 "Write tests again for {} — each must build and be collected without the code it tests existing yet: exercise the story through its interface, import the code under test inside each test",
2323 left.join(", ")
2324 )))
2325 .collect();
2326 let (second, more) = self::draft(
2327 &ctx,
2328 &req,
2329 &author,
2330 &bench,
2331 1,
2332 &told,
2333 Vec::new(),
2334 told.clone(),
2335 only.is_empty(),
2336 options,
2337 )?;
2338 if missing(&second).len() < left.len() {
2339 (draft, contents) = (second, more);
2340 }
2341 }
2342 if only.is_empty() {
2344 store(&ctx.plane_dir, &ctx.feature, &draft, &contents).map_err(failed)?;
2345 }
2346 let keep: Vec<&DraftTest> = draft
2347 .tests
2348 .iter()
2349 .filter(|t| not_kept(t, many).is_none())
2350 .collect();
2351 if keep.is_empty() && draft.tests.is_empty() && draft.discarded.is_empty() {
2354 return Ok(RunOracle {
2355 tests: Vec::new(),
2356 contents: Vec::new(),
2357 contracts: draft.expectations.sample1.clone(),
2358 untestable: draft.untestable.sample1.clone(),
2359 });
2360 }
2361 if keep.is_empty() {
2362 return Err(Box::new(refuse(
2363 CommandStatus::NeedsHuman,
2364 "ORACLE-UNWRITTEN",
2365 &format!(
2366 "no test written for {story} could be used ({} not kept)",
2367 draft.tests.len() + draft.discarded.len()
2368 ),
2369 )));
2370 }
2371 let manifest = manifest_digest(
2372 keep.iter()
2373 .map(|t| (t.path.as_str(), t.sha256.as_str(), t.argv.as_slice())),
2374 );
2375 let paths: Vec<&str> = keep.iter().map(|t| t.path.as_str()).collect();
2376 let kept_contents: Vec<(String, String)> = contents
2377 .iter()
2378 .filter(|(p, _)| paths.contains(&p.as_str()))
2379 .cloned()
2380 .collect();
2381 let f = Freezable {
2382 req: req.clone(),
2383 draft: draft.clone(),
2384 contents: kept_contents.clone(),
2385 manifest,
2386 };
2387 if only.is_empty() {
2390 freeze_tests(
2391 &ctx.plane_dir,
2392 &ctx.feature,
2393 &f,
2394 &keep,
2395 &format!(
2396 "run:{run}{}",
2397 if only.is_empty() { "" } else { ":amendment" }
2398 ),
2399 Decided {
2400 by: "speccoder run".to_owned(),
2401 via: Via::Terminal,
2402 at: now(),
2403 },
2404 Producer::Run,
2405 )
2406 .map_err(failed)?;
2407 }
2408 Ok(RunOracle {
2409 tests: keep
2410 .iter()
2411 .map(|t| FrozenTest {
2412 path: t.path.clone(),
2413 sha256: t.sha256.clone(),
2414 argv: t.argv.clone(),
2415 scenarios: t.scenarios.clone(),
2416 })
2417 .collect(),
2418 contents: kept_contents,
2419 contracts: draft.expectations.sample1.clone(),
2420 untestable: draft.untestable.sample1.clone(),
2421 })
2422}
2423
2424pub(crate) fn refreeze(
2431 project_state: &Path,
2432 unit: &str,
2433 key: &str,
2434 tests: Vec<FrozenTest>,
2435) -> Result<(), String> {
2436 let mut frozen = load_frozen(project_state, unit, key)
2437 .ok_or_else(|| format!("{key} has no frozen oracle here"))?;
2438 frozen.manifest_sha256 = manifest_digest(
2439 tests
2440 .iter()
2441 .map(|t| (t.path.as_str(), t.sha256.as_str(), t.argv.as_slice())),
2442 );
2443 frozen.tests = tests;
2444 let text = serde_json::to_string_pretty(&frozen).map_err(|e| e.to_string())?;
2445 write_atomic(&dir(project_state, unit, key).join("frozen.json"), &text)
2446}
2447
2448#[derive(Debug)]
2450pub(crate) enum TaskReuse {
2451 Ready {
2453 record: Box<PreFrozenAcceptance>,
2455 files: Vec<(String, String)>,
2457 tests: Vec<crate::pipeline::ReusedTest>,
2459 manifest: String,
2461 },
2462 Reused {
2464 req: String,
2466 },
2467 Elsewhere {
2469 req: String,
2471 },
2472 Lapsed {
2474 req: String,
2476 frozen: String,
2478 current: String,
2480 },
2481 Tampered(String),
2483 Unreadable(String),
2485}
2486
2487pub(crate) fn for_task(
2492 project_state: &Path,
2493 project: &Path,
2494 wt_root: &Path,
2495 format: &dyn Adapter,
2496 snapshot: &ProjectSnapshot,
2497 scenarios: &[speccoder_core::spec::ScenarioRef],
2498) -> Option<TaskReuse> {
2499 let f = snapshot.feature.as_ref()?;
2500 let unit = f.feature.name.as_str();
2501 let (entries, approval) = match crate::review::oracle_entries(project, &f.feature.dir) {
2502 Ok(x) => x,
2503 Err(e) => return Some(TaskReuse::Unreadable(e)),
2505 };
2506 if entries.is_empty() {
2507 return None;
2508 }
2509 let ids: Vec<&str> = scenarios.iter().map(|s| s.id.as_str()).collect();
2510 let requirements = format.oracle_requirements(snapshot);
2511 let (req, entry) = requirements.iter().find_map(|r| {
2512 let e = entries.get(&r.key)?;
2513 r.scenarios
2514 .iter()
2515 .any(|s| ids.contains(&s.id.as_str()))
2516 .then_some((r, e))
2517 })?;
2518 let digest = req.digest();
2519 if entry.requirement_sha256 != digest {
2520 return Some(TaskReuse::Lapsed {
2521 req: req.key.clone(),
2522 frozen: entry.requirement_sha256.clone(),
2523 current: digest,
2524 });
2525 }
2526 let (record, files) = match crate::pre_frozen::load(project_state, unit, &req.key) {
2527 Ok(Some(x)) => x,
2528 Ok(None) => {
2529 return Some(TaskReuse::Elsewhere {
2530 req: req.key.clone(),
2531 });
2532 }
2533 Err(t) => return Some(TaskReuse::Tampered(t.0)),
2534 };
2535 let needle = format!("Acceptance: review manifest={} ", entry.manifest_sha256);
2539 let reused = crate::git::Git::at(wt_root)
2540 .run(&[
2541 "log",
2542 "--format=%H",
2543 "--fixed-strings",
2544 &format!("--grep={needle}"),
2545 "HEAD",
2546 ])
2547 .map(|out| !out.is_empty());
2548 match reused {
2549 Ok(true) => {
2550 return Some(TaskReuse::Reused {
2551 req: req.key.clone(),
2552 });
2553 }
2554 Ok(false) => {}
2555 Err(e) => {
2556 return Some(TaskReuse::Unreadable(format!(
2557 "the worktree's history cannot be read: {}",
2558 e.0
2559 )));
2560 }
2561 }
2562 if !record.is_current(&digest) {
2563 return Some(TaskReuse::Lapsed {
2564 req: req.key.clone(),
2565 frozen: record.wording_digest.clone(),
2566 current: digest,
2567 });
2568 }
2569 let Some(frozen) = load_frozen(project_state, unit, &req.key) else {
2570 return Some(TaskReuse::Tampered(format!(
2571 "{}'s frozen commands are missing from the state directory",
2572 req.key
2573 )));
2574 };
2575 let manifest = manifest_digest(
2576 frozen
2577 .tests
2578 .iter()
2579 .map(|t| (t.path.as_str(), t.sha256.as_str(), t.argv.as_slice())),
2580 );
2581 let same_files = frozen.tests.len() == record.visible.len()
2582 && frozen.tests.iter().all(|t| {
2583 record
2584 .visible
2585 .iter()
2586 .any(|v| v.path == t.path && v.sha256 == t.sha256)
2587 });
2588 if manifest != entry.manifest_sha256 || manifest != frozen.manifest_sha256 || !same_files {
2589 return Some(TaskReuse::Tampered(format!(
2590 "{}'s frozen tests no longer match the manifest review.json names",
2591 req.key
2592 )));
2593 }
2594 if approval.as_deref() != Some(record.approval_digest.as_str()) {
2597 return Some(TaskReuse::Tampered(format!(
2598 "{}'s frozen set names another approval than review.json{}",
2599 req.key,
2600 if approval.is_none() {
2601 " (which records none)"
2602 } else {
2603 ""
2604 }
2605 )));
2606 }
2607 let sealed = record
2608 .held_out_sealed
2609 .as_ref()
2610 .map(|h| format!("sha256:{}", h.manifest_sha256));
2611 if sealed != entry.held_out_sha256 {
2612 return Some(TaskReuse::Tampered(format!(
2613 "{}'s frozen held-out set is not the one review.json names",
2614 req.key
2615 )));
2616 }
2617 let tests = frozen
2618 .tests
2619 .iter()
2620 .map(|t| crate::pipeline::ReusedTest {
2621 path: t.path.clone(),
2622 cites: t.scenarios.clone(),
2623 argv: t.argv.clone(),
2624 green: false,
2625 })
2626 .collect();
2627 Some(TaskReuse::Ready {
2628 record: Box::new(record),
2629 files,
2630 tests,
2631 manifest,
2632 })
2633}
2634
2635pub(crate) fn note_lapse(project_state: &Path, unit: &str, req: &str, frozen: &str) -> bool {
2638 let file = project_state.join(DIR).join(unit).join("lapsed.json");
2639 let mut seen: Vec<String> = std::fs::read_to_string(&file)
2640 .ok()
2641 .and_then(|t| serde_json::from_str(&t).ok())
2642 .unwrap_or_default();
2643 let key = format!("{req}={frozen}");
2644 if seen.contains(&key) {
2645 return false;
2646 }
2647 seen.push(key);
2648 let _ = write_atomic(&file, &serde_json::to_string(&seen).unwrap_or_default());
2649 true
2650}
2651
2652#[must_use]
2654pub fn autopilot_denials(
2655 task: &str,
2656 tool_calls: &[Value],
2657) -> Vec<speccoder_core::oracle::AutopilotDenial> {
2658 tool_calls
2659 .iter()
2660 .enumerate()
2661 .filter(|(_, c)| {
2662 c["decision"] == "deny" && c["reason"].as_str() == Some(tools::policy::AUTOPILOT_DENIED)
2663 })
2664 .map(|(i, c)| {
2665 let object: Option<tools::policy::Object> =
2666 serde_json::from_value(c["object"].clone()).ok();
2667 speccoder_core::oracle::AutopilotDenial {
2668 task: task.to_owned(),
2669 turn: c["turn"]
2670 .as_u64()
2671 .and_then(|n| u32::try_from(n).ok())
2672 .unwrap_or_else(|| u32::try_from(i + 1).unwrap_or(u32::MAX)),
2673 class: object
2674 .as_ref()
2675 .map(|o| o.class().as_str().to_owned())
2676 .unwrap_or_default(),
2677 object: object.as_ref().map_or_else(
2678 || {
2679 c["arguments"]["path"]
2680 .as_str()
2681 .map(str::to_owned)
2682 .or_else(|| {
2683 c["arguments"]["argv"].as_array().map(|a| {
2684 a.iter()
2685 .filter_map(Value::as_str)
2686 .collect::<Vec<_>>()
2687 .join(" ")
2688 })
2689 })
2690 .unwrap_or_else(|| c["tool"].as_str().unwrap_or_default().to_owned())
2691 },
2692 tools::policy::Object::describe,
2693 ),
2694 reason: tools::policy::AUTOPILOT_DENIED.to_owned(),
2695 }
2696 })
2697 .collect()
2698}
2699
2700#[must_use]
2702pub fn last_denials(
2703 project_state: &Path,
2704 unit: &str,
2705) -> Vec<speccoder_core::oracle::AutopilotDenial> {
2706 std::fs::read_to_string(project_state.join(DIR).join(unit).join("autopilot.json"))
2707 .ok()
2708 .and_then(|t| serde_json::from_str(&t).ok())
2709 .unwrap_or_default()
2710}
2711
2712pub(crate) fn record_denials(
2714 project_state: &Path,
2715 unit: &str,
2716 denials: &[speccoder_core::oracle::AutopilotDenial],
2717) {
2718 let file = project_state.join(DIR).join(unit).join("autopilot.json");
2719 if denials.is_empty() {
2720 let _ = std::fs::remove_file(file);
2721 return;
2722 }
2723 let _ = write_atomic(
2724 &file,
2725 &serde_json::to_string_pretty(denials).unwrap_or_default(),
2726 );
2727}
2728
2729#[cfg(test)]
2730mod tests {
2731 use super::*;
2732
2733 fn draft(content: &str) -> Draft {
2734 Draft {
2735 requirement: DraftRequirement {
2736 key: "US1".to_owned(),
2737 title: "Greet".to_owned(),
2738 text: "### User Story 1 - Greet".to_owned(),
2739 sha256: "sha256:w".to_owned(),
2740 },
2741 samples: 2,
2742 tests: vec![DraftTest {
2743 path: "tests/acceptance_us1.rs".to_owned(),
2744 sha256: digest_of(content),
2745 scenarios: vec!["US1-1".to_owned()],
2746 argv: vec!["cargo".to_owned(), "test".to_owned()],
2747 red_class: RedClass::Assertion,
2748 authored_by: AuthoredBy::Model,
2749 edited_by: None,
2750 }],
2751 discarded: Vec::new(),
2752 rejected: Vec::new(),
2753 expectations: Samples::default(),
2754 untestable: Samples::default(),
2755 ambiguities: Vec::new(),
2756 held_out: HeldOutSummary {
2757 state: "absent".to_owned(),
2758 count: 0,
2759 manifest_sha256: None,
2760 reason: None,
2761 discarded: Vec::new(),
2762 },
2763 sealed: None,
2764 notes: Vec::new(),
2765 runs: Vec::new(),
2766 context: Vec::new(),
2767 }
2768 }
2769
2770 #[test]
2771 fn a_draft_round_trips_and_a_changed_test_is_tampering() {
2772 let state = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
2773 let d = draft("#[test] fn t() {}");
2774 let files = vec![(
2775 "tests/acceptance_us1.rs".to_owned(),
2776 "#[test] fn t() {}".to_owned(),
2777 )];
2778 store(state.path(), "001-greet", &d, &files).unwrap_or_else(|e| panic!("{e}"));
2779 let (back, contents) = load(state.path(), "001-greet", "US1")
2780 .unwrap_or_else(|e| panic!("{e:?}"))
2781 .unwrap_or_else(|| panic!("stored"));
2782 assert_eq!(back, d);
2783 assert_eq!(contents, files);
2784 std::fs::write(
2785 dir(state.path(), "001-greet", "US1").join("files/tests/acceptance_us1.rs"),
2786 "changed",
2787 )
2788 .unwrap_or_else(|e| panic!("{e}"));
2789 assert!(load(state.path(), "001-greet", "US1").is_err());
2790 assert!(store(state.path(), "001-greet", &d, &[]).is_err());
2791 assert!(
2792 load(state.path(), "001-greet", "US2")
2793 .unwrap_or_default()
2794 .is_none()
2795 );
2796 }
2797
2798 #[test]
2799 fn the_manifest_names_paths_contents_and_commands() {
2800 let argv = vec!["cargo".to_owned()];
2801 let other = vec!["make".to_owned()];
2802 let a = manifest_digest([("a", "sha256:1", argv.as_slice())]);
2803 assert_eq!(a, manifest_digest([("a", "sha256:1", argv.as_slice())]));
2804 assert_ne!(a, manifest_digest([("a", "sha256:2", argv.as_slice())]));
2805 assert_ne!(a, manifest_digest([("a", "sha256:1", other.as_slice())]));
2806 let both = manifest_digest([("a", "s", argv.as_slice()), ("b", "s", argv.as_slice())]);
2807 assert_eq!(
2808 both,
2809 manifest_digest([("b", "s", argv.as_slice()), ("a", "s", argv.as_slice())])
2810 );
2811 let mut d = draft("x");
2812 assert!(d.manifest().is_some());
2813 d.tests[0].red_class = RedClass::Passed;
2814 assert!(d.manifest().is_none());
2815 assert_eq!(slug("cap: a / b"), "cap__a___b");
2816 }
2817
2818 #[test]
2819 fn a_lapse_is_noted_once() {
2820 let state = tempfile::tempdir().unwrap_or_else(|e| panic!("{e}"));
2821 assert!(note_lapse(state.path(), "u", "US1", "sha256:a"));
2822 assert!(!note_lapse(state.path(), "u", "US1", "sha256:a"));
2823 assert!(note_lapse(state.path(), "u", "US1", "sha256:b"));
2824 }
2825}