1use std::collections::{BTreeMap, BTreeSet, HashMap};
4use std::path::{Component, Path, PathBuf};
5use std::sync::Arc;
6use std::sync::Mutex;
7use std::sync::atomic::{AtomicU32, Ordering};
8
9use anyhow::{Context, Result, bail};
10use perspt_sdk::{CandidateStateWitness, ToolEntry};
11use tempfile::TempDir;
12
13use crate::realize::snapshot_workspace;
14use crate::toolloop::{CandidateCheckpoint, EffectExecutor, EffectOutcome};
15use crate::tools::AgentTools;
16use crate::verifier::{VerifierExecution, run_governed_verifier};
17
18pub use crate::measure::CodingCandidateMeasurer;
19
20pub struct CandidateWorkspace {
23 source_root: PathBuf,
24 overlay_root: PathBuf,
25 _temp: TempDir,
26 overlay_tools: AgentTools,
27 source_tools: AgentTools,
28 tracked: Mutex<BTreeSet<String>>,
31 mutated_paths: Mutex<BTreeSet<String>>,
35 source_preimages: Mutex<BTreeMap<String, Option<Vec<u8>>>>,
38 journal: Mutex<Vec<JournalEntry>>,
42 snapshots: Mutex<HashMap<String, CandidateSnapshot>>,
43 lsp_sessions: crate::tools::handlers::LspSessions,
44 mutations: AtomicU32,
45 node_id: String,
46 generation: u32,
47 graph_revision: String,
48 allow_unisolated_verifiers: bool,
49 verifier_timeouts: crate::verifier::VerifierTimeouts,
51 handlers: Arc<crate::tools::handlers::CandidateHandlerRegistry>,
54 interaction_handler: Arc<dyn crate::tools::handlers::InteractionHandler>,
56 subagent_runner: Option<Arc<dyn crate::tools::handlers::SubagentRunner>>,
58}
59
60impl std::fmt::Debug for CandidateWorkspace {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 f.debug_struct("CandidateWorkspace")
63 .field("source_root", &self.source_root)
64 .field("overlay_root", &self.overlay_root)
65 .field("node_id", &self.node_id)
66 .field("generation", &self.generation)
67 .finish_non_exhaustive()
68 }
69}
70
71impl CandidateWorkspace {
72 pub fn create(
73 source_root: &Path,
74 node_id: impl Into<String>,
75 generation: u32,
76 graph_revision: impl Into<String>,
77 ) -> Result<Self> {
78 Self::create_with_policy(source_root, node_id, generation, graph_revision, false)
79 }
80
81 pub fn create_with_policy(
82 source_root: &Path,
83 node_id: impl Into<String>,
84 generation: u32,
85 graph_revision: impl Into<String>,
86 allow_unisolated_verifiers: bool,
87 ) -> Result<Self> {
88 Self::create_filtered(
89 source_root,
90 node_id,
91 generation,
92 graph_revision,
93 allow_unisolated_verifiers,
94 &[],
95 )
96 }
97
98 pub(crate) fn create_filtered(
101 source_root: &Path,
102 node_id: impl Into<String>,
103 generation: u32,
104 graph_revision: impl Into<String>,
105 allow_unisolated_verifiers: bool,
106 excluded: &[PathBuf],
107 ) -> Result<Self> {
108 let source_root = source_root
109 .canonicalize()
110 .with_context(|| format!("canonicalizing {}", source_root.display()))?;
111 let temp = tempfile::Builder::new()
112 .prefix("perspt-candidate-")
113 .tempdir()?;
114 let overlay_root = temp.path().join("workspace");
115 std::fs::create_dir_all(&overlay_root)?;
116 let overlay_root = overlay_root.canonicalize()?;
117 copy_workspace_filtered(&source_root, &overlay_root, excluded)?;
118 Ok(Self {
119 overlay_tools: AgentTools::new(overlay_root.clone()),
120 source_tools: AgentTools::new(source_root.clone()),
121 source_root,
122 overlay_root,
123 _temp: temp,
124 tracked: Mutex::new(BTreeSet::new()),
125 mutated_paths: Mutex::new(BTreeSet::new()),
126 source_preimages: Mutex::new(BTreeMap::new()),
127 journal: Mutex::new(Vec::new()),
128 snapshots: Mutex::new(HashMap::new()),
129 lsp_sessions: tokio::sync::Mutex::new(HashMap::new()),
130 mutations: AtomicU32::new(0),
131 node_id: node_id.into(),
132 generation,
133 graph_revision: graph_revision.into(),
134 allow_unisolated_verifiers,
135 verifier_timeouts: crate::verifier::VerifierTimeouts::default(),
136 handlers: Arc::new(crate::tools::handlers::CandidateHandlerRegistry::with_builtins()),
137 interaction_handler: Arc::new(crate::tools::handlers::NonInteractiveHandler),
138 subagent_runner: None,
139 })
140 }
141
142 pub fn set_tool_handlers(
145 &mut self,
146 handlers: Arc<crate::tools::handlers::CandidateHandlerRegistry>,
147 ) {
148 self.handlers = handlers;
149 }
150
151 pub fn set_interaction_handler(
153 &mut self,
154 handler: Arc<dyn crate::tools::handlers::InteractionHandler>,
155 ) {
156 self.interaction_handler = handler;
157 }
158
159 pub(crate) fn interaction_handler(
160 &self,
161 ) -> &Arc<dyn crate::tools::handlers::InteractionHandler> {
162 &self.interaction_handler
163 }
164
165 pub fn set_subagent_runner(&mut self, runner: Arc<dyn crate::tools::handlers::SubagentRunner>) {
167 self.subagent_runner = Some(runner);
168 }
169
170 pub(crate) fn subagent_runner(
171 &self,
172 ) -> Option<&Arc<dyn crate::tools::handlers::SubagentRunner>> {
173 self.subagent_runner.as_ref()
174 }
175
176 pub fn overlay_root(&self) -> &Path {
177 &self.overlay_root
178 }
179
180 pub(crate) fn overlay_tools(&self) -> &AgentTools {
181 &self.overlay_tools
182 }
183
184 pub(crate) fn source_tools(&self) -> &AgentTools {
185 &self.source_tools
186 }
187
188 pub(crate) fn lsp_sessions(&self) -> &crate::tools::handlers::LspSessions {
189 &self.lsp_sessions
190 }
191
192 pub(crate) fn unisolated_verifiers_allowed(&self) -> bool {
193 self.allow_unisolated_verifiers
194 }
195
196 pub fn set_verifier_timeouts(&mut self, timeouts: crate::verifier::VerifierTimeouts) {
199 self.verifier_timeouts = timeouts;
200 }
201
202 pub(crate) fn verifier_timeouts(&self) -> crate::verifier::VerifierTimeouts {
203 self.verifier_timeouts
204 }
205
206 pub(crate) fn validate_relative(&self, path: &str) -> Result<String> {
208 validate_relative_path(path)
209 }
210
211 pub fn has_mutated(&self) -> bool {
212 self.mutations.load(Ordering::SeqCst) > 0
213 }
214
215 pub fn node_generation(&self) -> u32 {
217 self.generation
218 }
219
220 pub fn touched_paths(&self) -> Vec<String> {
222 self.mutated_paths.lock().unwrap().iter().cloned().collect()
223 }
224
225 pub fn realized_diff(&self) -> Result<String> {
229 let mut output = String::new();
230 for relative in self.touched_paths() {
231 let before =
232 std::fs::read_to_string(self.source_root.join(&relative)).unwrap_or_default();
233 let after =
234 std::fs::read_to_string(self.overlay_root.join(&relative)).unwrap_or_default();
235 output.push_str(&format!("diff --perspt {relative}\n"));
236 output.push_str(
237 &diffy::PatchFormatter::new()
238 .fmt_patch(&diffy::create_patch(&before, &after))
239 .to_string(),
240 );
241 }
242 Ok(output)
243 }
244
245 pub fn promote(&self) -> Result<Vec<String>> {
250 let paths: Vec<String> = self.mutated_paths.lock().unwrap().iter().cloned().collect();
251 let source = crate::promote::WorkspaceRoot::open(&self.source_root)?;
252 let overlay = crate::promote::WorkspaceRoot::open(&self.overlay_root)?;
253 let mut staged = Vec::new();
254 for rel in &paths {
255 let rel = validate_relative_path(rel)?;
256 let target = source.target_dir(&rel, true)?;
257 let current = target.read_optional()?;
258 let expected = self
259 .source_preimages
260 .lock()
261 .unwrap()
262 .get(&rel)
263 .cloned()
264 .context("mutated path has no source pre-image")?;
265 anyhow::ensure!(
266 current == expected,
267 "workspace path changed since the candidate was created: {rel}"
268 );
269 let after = overlay.read_if_present(&rel)?;
270 staged.push((rel, target, current, after));
271 }
272
273 for (promoted, (rel, target, _before, after)) in staged.iter().enumerate() {
274 if let Err(error) = target.apply(after.as_deref()) {
275 let error = error.context(format!("promoting {rel}"));
276 return Err(rollback_promotion(&staged[..promoted], error));
277 }
278 }
279 Ok(paths)
280 }
281
282 fn scope_snapshot(&self, additional: &[String]) -> Result<CandidateCheckpoint> {
283 let mut tracked = self.tracked.lock().unwrap();
284 for rel in additional {
285 tracked.insert(validate_relative_path(rel)?);
286 }
287 let scope: Vec<String> = tracked.iter().cloned().collect();
288 drop(tracked);
289
290 let witness = self.witness_for(scope)?;
291 let id = uuid::Uuid::new_v4().to_string();
292 self.snapshots.lock().unwrap().insert(
293 id.clone(),
294 CandidateSnapshot {
295 journal_len: self.journal.lock().unwrap().len(),
296 mutations: self.mutations.load(Ordering::SeqCst),
297 mutated: self.mutated_paths.lock().unwrap().clone(),
298 },
299 );
300 Ok(CandidateCheckpoint { id, witness })
301 }
302
303 fn current_witness(&self) -> Result<CandidateStateWitness> {
304 let scope: Vec<String> = self.tracked.lock().unwrap().iter().cloned().collect();
305 self.witness_for(scope)
306 }
307
308 fn witness_for(&self, scope: Vec<String>) -> Result<CandidateStateWitness> {
313 let state = snapshot_workspace(&self.overlay_root, &scope)?;
314 let mutated = self.mutated_paths.lock().unwrap();
315 let barrier_channels = perspt_coding::OperationalSafetyBarrier::default()
316 .measure_channels(mutated.iter().map(String::as_str));
317 Ok(CandidateStateWitness {
318 state_root: state.root_hash(),
319 graph_revision: self.graph_revision.clone(),
320 node_id: self.node_id.clone(),
321 node_generation: self.generation,
322 canonical_scope: scope,
323 barrier_channels,
324 })
325 }
326
327 fn admit_named_paths(
331 &self,
332 call: &perspt_sdk::ProviderToolCall,
333 entry: &ToolEntry,
334 mutating: bool,
335 ) -> Result<Vec<String>> {
336 let named_paths: Vec<String> = ["path", "to", "from"]
337 .iter()
338 .filter_map(|field| call.arguments.get(*field).and_then(|v| v.as_str()))
339 .map(str::to_string)
340 .collect();
341 for rel in &named_paths {
342 validate_relative_path(rel)?;
343 if !entry.effect.is_read_only() {
344 reject_symlink_ancestor(&self.overlay_root, rel)?;
345 }
346 }
347 if mutating {
348 for rel in &named_paths {
349 self.journal_pre_image(rel)?;
350 }
351 }
352 Ok(named_paths)
353 }
354
355 pub(crate) fn admit_external_paths(&self, paths: &[String]) -> Result<()> {
359 for rel in paths {
360 let rel = validate_relative_path(rel)?;
361 reject_symlink_ancestor(&self.overlay_root, &rel)?;
362 self.journal_pre_image(&rel)?;
363 self.tracked.lock().unwrap().insert(rel);
364 }
365 Ok(())
366 }
367
368 pub(crate) fn note_mutated_paths(&self, paths: &[String]) -> Result<()> {
371 let mut mutated = self.mutated_paths.lock().unwrap();
372 for rel in paths {
373 mutated.insert(validate_relative_path(rel)?);
374 }
375 Ok(())
376 }
377
378 pub(crate) async fn import_child_mutations(
382 &self,
383 child: &CandidateWorkspace,
384 ) -> Result<Vec<String>> {
385 let exported = child.export_accepted().await?;
386 if exported.is_empty() {
387 return Ok(Vec::new());
388 }
389 let paths: Vec<String> = exported.iter().map(|seed| seed.path.clone()).collect();
390 self.admit_external_paths(&paths)?;
391 for seed in &exported {
392 let rel = validate_relative_path(&seed.path)?;
393 reject_symlink_ancestor(&self.overlay_root, &rel)?;
394 let target = self.overlay_root.join(&rel);
395 match &seed.content {
396 Some(bytes) => {
397 if let Some(parent) = target.parent() {
398 std::fs::create_dir_all(parent)?;
399 }
400 std::fs::write(&target, bytes)?;
401 }
402 None if target.is_file() => std::fs::remove_file(&target)?,
403 None => {}
404 }
405 self.note_mutated_paths(std::slice::from_ref(&rel))?;
406 self.mutations.fetch_add(1, Ordering::SeqCst);
407 }
408 Ok(paths)
409 }
410
411 pub(crate) fn overlay_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
413 let rel = validate_relative_path(rel)?;
414 match std::fs::read(self.overlay_root.join(&rel)) {
415 Ok(bytes) => Ok(Some(bytes)),
416 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
417 Err(e) => Err(e).with_context(|| format!("reading {rel}")),
418 }
419 }
420
421 pub fn restore_exported(&self, files: &[crate::toolloop::SeedFile]) -> Result<()> {
425 self.restore_files(files, true)
426 }
427
428 pub fn restore_seeded(&self, files: &[crate::toolloop::SeedFile]) -> Result<()> {
435 self.restore_files(files, false)
436 }
437
438 fn restore_files(
439 &self,
440 files: &[crate::toolloop::SeedFile],
441 mark_promotable: bool,
442 ) -> Result<()> {
443 for seed in files {
444 let rel = validate_relative_path(&seed.path)?;
445 reject_symlink_ancestor(&self.overlay_root, &rel)?;
446 self.journal_pre_image(&rel)?;
447 let path = self.overlay_root.join(&rel);
448 match &seed.content {
449 Some(bytes) => {
450 if let Some(parent) = path.parent() {
451 std::fs::create_dir_all(parent)?;
452 }
453 std::fs::write(&path, bytes)?;
454 }
455 None if path.is_file() => std::fs::remove_file(&path)?,
456 None => {}
457 }
458 self.tracked.lock().unwrap().insert(rel.clone());
459 self.source_preimages
460 .lock()
461 .unwrap()
462 .insert(rel.clone(), seed.source_preimage.clone());
463 if mark_promotable {
464 self.mutated_paths.lock().unwrap().insert(rel);
465 self.mutations.fetch_add(1, Ordering::SeqCst);
466 }
467 }
468 Ok(())
469 }
470
471 fn journal_pre_image(&self, rel: &str) -> Result<()> {
473 let path = self.overlay_root.join(rel);
474 let prior = match std::fs::read(&path) {
475 Ok(bytes) => Some(bytes),
476 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
477 Err(e) => return Err(e).with_context(|| format!("journaling {rel}")),
478 };
479 self.source_preimages
480 .lock()
481 .unwrap()
482 .entry(rel.to_string())
483 .or_insert_with(|| prior.clone());
484 self.journal.lock().unwrap().push(JournalEntry {
485 path: rel.to_string(),
486 prior,
487 });
488 Ok(())
489 }
490
491 fn restore_snapshot(&self, checkpoint: &CandidateCheckpoint) -> Result<()> {
495 let snapshots = self.snapshots.lock().unwrap();
496 let snapshot = snapshots
497 .get(&checkpoint.id)
498 .with_context(|| format!("unknown candidate checkpoint {}", checkpoint.id))?;
499 let mut journal = self.journal.lock().unwrap();
500 while journal.len() > snapshot.journal_len {
501 let entry = journal.pop().expect("journal length checked");
502 let path = self.overlay_root.join(&entry.path);
503 match entry.prior {
504 Some(bytes) => {
505 if let Some(parent) = path.parent() {
506 std::fs::create_dir_all(parent)?;
507 }
508 std::fs::write(&path, bytes)?;
509 }
510 None if path.is_file() => std::fs::remove_file(&path)?,
511 None => {}
512 }
513 }
514 self.mutations.store(snapshot.mutations, Ordering::SeqCst);
515 *self.mutated_paths.lock().unwrap() = snapshot.mutated.clone();
516 Ok(())
517 }
518
519 pub(crate) fn commands_for(
527 &self,
528 tool: &str,
529 arguments: &serde_json::Value,
530 ) -> Result<Vec<(String, String, perspt_core::plugin::VerifierStage)>> {
531 use perspt_core::plugin::VerifierStage;
532 let registry = perspt_core::PluginRegistry::new();
533 let plugins = registry.detect_all(&self.overlay_root);
534 if plugins.is_empty() {
535 bail!("no language plugin detected");
536 }
537 let mutated = self.mutated_paths.lock().unwrap().clone();
538 let owned: Vec<usize> = (0..plugins.len())
539 .filter(|&i| mutated.iter().any(|path| plugins[i].owns_file(path)))
540 .collect();
541 let selected: Vec<usize> = if owned.is_empty() {
542 (0..plugins.len()).collect()
543 } else {
544 owned
545 };
546 let filter = match arguments.get("filter").and_then(serde_json::Value::as_str) {
547 Some(raw) => Some(sanitize_test_filter(raw)?),
548 None => None,
549 };
550 let mut commands = Vec::new();
551 for index in selected {
552 let plugin = &plugins[index];
553 let command = match tool {
554 "run_test" => Some((
555 plugin.test_command_with_filter(filter.as_deref()),
556 VerifierStage::Test,
557 )),
558 "run_build" => plugin
559 .build_command()
560 .or_else(|| plugin.syntax_check_command())
561 .map(|command| (command, VerifierStage::Build)),
562 "run_formatter" => plugin
563 .format_command()
564 .map(|command| (command, VerifierStage::Format)),
565 _ => bail!("not a verifier tool: {tool}"),
566 };
567 if let Some((command, stage)) = command {
568 commands.push((plugin.name().to_string(), command, stage));
569 }
570 }
571 if commands.is_empty() {
572 match tool {
573 "run_build" => bail!("active language has no build or syntax command"),
574 "run_formatter" => bail!("active language has no governed formatter command"),
575 other => bail!("active language has no {other} command"),
576 }
577 }
578 Ok(commands)
579 }
580
581 pub(crate) async fn run_governed_verifier(
582 &self,
583 command: &str,
584 stage: Option<perspt_core::plugin::VerifierStage>,
585 ) -> Result<VerifierExecution> {
586 run_governed_verifier(
587 self.overlay_root.clone(),
588 command.to_string(),
589 self.allow_unisolated_verifiers,
590 crate::measure::SHARED_TARGET_SUFFIX.into(),
591 self.verifier_env(),
592 self.verifier_timeouts.for_stage(stage),
593 )
594 .await
595 }
596
597 pub(crate) fn verifier_env(&self) -> Vec<(String, String)> {
602 let venv = self.source_root.join(".venv");
603 if venv.is_dir() {
604 vec![("UV_PROJECT_ENVIRONMENT".into(), venv.display().to_string())]
605 } else {
606 Vec::new()
607 }
608 }
609
610 pub(crate) fn backward_compatibility_tests(&self) -> Result<Option<TestEvidenceWorkspace>> {
616 let registry = perspt_core::PluginRegistry::new();
617 let plugins = registry.detect_all(&self.overlay_root);
618 let preimages = self.source_preimages.lock().unwrap();
619 let touched_tests: Vec<_> = self
620 .mutated_paths
621 .lock()
622 .unwrap()
623 .iter()
624 .filter(|path| plugins.iter().any(|plugin| plugin.is_test_file(path)))
625 .filter_map(|path| {
626 preimages
627 .get(path)
628 .cloned()
629 .map(|content| (path.clone(), content))
630 })
631 .collect();
632 if !touched_tests
633 .iter()
634 .any(|(_, source_preimage)| source_preimage.is_some())
635 {
636 return Ok(None);
637 }
638
639 let temp = tempfile::Builder::new()
640 .prefix("perspt-regression-tests-")
641 .tempdir()?;
642 let root = temp.path().join("workspace");
643 std::fs::create_dir_all(&root)?;
644 let root = root.canonicalize()?;
645 copy_workspace(&self.overlay_root, &root)?;
646 for (relative, source_preimage) in touched_tests {
647 let path = root.join(&relative);
648 match source_preimage {
649 Some(bytes) => {
650 if let Some(parent) = path.parent() {
651 std::fs::create_dir_all(parent)?;
652 }
653 std::fs::write(path, bytes)?;
654 }
655 None if path.is_file() => std::fs::remove_file(path)?,
656 None => {}
657 }
658 }
659 Ok(Some(TestEvidenceWorkspace { _temp: temp, root }))
660 }
661
662 pub(crate) fn external_oracle_tests(
667 &self,
668 configured_path: &Path,
669 ) -> Result<TestEvidenceWorkspace> {
670 let oracle_path = if configured_path.is_absolute() {
671 configured_path.to_path_buf()
672 } else {
673 self.source_root.join(configured_path)
674 };
675 let oracle_path = oracle_path.canonicalize().with_context(|| {
676 format!(
677 "canonicalizing external test oracle {}",
678 oracle_path.display()
679 )
680 })?;
681 anyhow::ensure!(
682 oracle_path.is_dir(),
683 "external test oracle is not a directory: {}",
684 oracle_path.display()
685 );
686 anyhow::ensure!(
687 oracle_path != self.source_root && !self.source_root.starts_with(&oracle_path),
688 "external test oracle must be a dedicated directory, not the workspace or one of \
689 its ancestors: {}",
690 oracle_path.display()
691 );
692 let temp = tempfile::Builder::new()
693 .prefix("perspt-external-oracle-")
694 .tempdir()?;
695 let root = temp.path().join("workspace");
696 std::fs::create_dir_all(&root)?;
697 let root = root.canonicalize()?;
698 copy_workspace(&self.overlay_root, &root)?;
699 copy_workspace(&oracle_path, &root)?;
700 Ok(TestEvidenceWorkspace { _temp: temp, root })
701 }
702}
703
704#[async_trait::async_trait]
705impl EffectExecutor for CandidateWorkspace {
706 async fn checkpoint(&self, scope: &[String]) -> Result<CandidateCheckpoint> {
707 self.scope_snapshot(scope)
708 }
709
710 async fn apply(
711 &self,
712 call: &perspt_sdk::ProviderToolCall,
713 entry: &ToolEntry,
714 ) -> Result<EffectOutcome> {
715 let mutating = crate::toolloop::candidate_mutating_effect(entry.effect);
716 let named_paths = self.admit_named_paths(call, entry, mutating)?;
717
718 let Some(handler) = self.handlers.resolve(&call.name).cloned() else {
719 return Ok(EffectOutcome {
720 output: format!("tool failed: no executor registered for {}", call.name),
721 mutated: false,
722 completed: true,
723 });
724 };
725 let outcome = handler.apply(self, call, entry).await?;
726
727 let mutates_source = outcome.mutated && mutating;
730 if mutates_source {
731 self.mutations.fetch_add(1, Ordering::SeqCst);
732 let mut mutated = self.mutated_paths.lock().unwrap();
733 for rel in &named_paths {
734 mutated.insert(rel.clone());
735 }
736 }
737 Ok(EffectOutcome {
738 output: outcome.output,
739 mutated: mutates_source,
740 completed: outcome.completed,
741 })
742 }
743
744 async fn restore(&self, checkpoint: &CandidateCheckpoint) -> Result<()> {
745 self.restore_snapshot(checkpoint)
746 }
747
748 async fn state_witness(&self) -> Result<CandidateStateWitness> {
749 self.current_witness()
750 }
751
752 async fn export_accepted(&self) -> Result<Vec<crate::toolloop::SeedFile>> {
753 let mutated = self.touched_paths();
754 let preimages = self.source_preimages.lock().unwrap();
755 let mut exported = Vec::with_capacity(mutated.len());
756 for rel in mutated {
757 let path = self.overlay_root.join(&rel);
758 let bytes = match std::fs::read(&path) {
759 Ok(bytes) => Some(bytes),
760 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
761 Err(e) => return Err(e).with_context(|| format!("exporting {rel}")),
762 };
763 let source_preimage = preimages
764 .get(&rel)
765 .cloned()
766 .context("mutated path has no source pre-image")?;
767 exported.push(crate::toolloop::SeedFile {
768 path: rel,
769 content: bytes,
770 source_preimage,
771 });
772 }
773 Ok(exported)
774 }
775}
776
777struct CandidateSnapshot {
778 journal_len: usize,
780 mutations: u32,
781 mutated: BTreeSet<String>,
782}
783
784struct JournalEntry {
786 path: String,
787 prior: Option<Vec<u8>>,
788}
789
790#[derive(Debug)]
791pub(crate) struct TestEvidenceWorkspace {
792 _temp: TempDir,
793 pub(crate) root: PathBuf,
794}
795
796fn sanitize_test_filter(raw: &str) -> Result<String> {
800 let filter = raw.trim();
801 if filter.is_empty() {
802 bail!("'filter' must not be empty");
803 }
804 if !filter
805 .chars()
806 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | ':' | '.' | '-'))
807 {
808 bail!(
809 "'filter' may only contain letters, digits, and _ : . - \
810 (got {filter:?})"
811 );
812 }
813 Ok(filter.to_string())
814}
815
816fn validate_relative_path(path: &str) -> Result<String> {
817 let value = Path::new(path);
818 if value.as_os_str().is_empty()
819 || value.is_absolute()
820 || value.components().any(|component| {
821 matches!(
822 component,
823 Component::ParentDir | Component::RootDir | Component::Prefix(_)
824 )
825 })
826 {
827 bail!("path must be a non-empty workspace-relative path: {path:?}");
828 }
829 Ok(value
830 .components()
831 .filter_map(|component| match component {
832 Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
833 _ => None,
834 })
835 .collect::<Vec<_>>()
836 .join("/"))
837}
838
839type StagedPromotion = (
842 String,
843 crate::promote::TargetDir,
844 Option<Vec<u8>>,
845 Option<Vec<u8>>,
846);
847
848fn rollback_promotion(promoted: &[StagedPromotion], error: anyhow::Error) -> anyhow::Error {
853 let mut failures = Vec::new();
854 for (rel, target, before, _) in promoted {
855 if let Err(restore) = target.apply(before.as_deref()) {
856 failures.push(format!("{rel}: {restore:#}"));
857 }
858 }
859 if failures.is_empty() {
860 error
861 } else {
862 error.context(format!(
863 "rollback left the workspace inconsistent: {}",
864 failures.join("; ")
865 ))
866 }
867}
868
869pub(crate) fn reject_symlink_ancestor(root: &Path, relative: &str) -> Result<()> {
870 let mut current = root.to_path_buf();
871 for component in Path::new(relative).components() {
872 if let Component::Normal(part) = component {
873 current.push(part);
874 match std::fs::symlink_metadata(¤t) {
875 Ok(metadata) if metadata.file_type().is_symlink() => {
876 bail!("mutating through a candidate symlink is forbidden: {relative}")
877 }
878 Ok(_) => {}
879 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
880 Err(error) => return Err(error.into()),
881 }
882 }
883 }
884 Ok(())
885}
886
887fn copy_workspace(source: &Path, destination: &Path) -> Result<()> {
888 copy_workspace_filtered(source, destination, &[])
889}
890
891fn copy_workspace_filtered(source: &Path, destination: &Path, excluded: &[PathBuf]) -> Result<()> {
892 for entry in std::fs::read_dir(source)? {
893 let entry = entry?;
894 let name = entry.file_name();
895 if matches!(
896 name.to_str(),
897 Some(
898 ".git"
899 | ".perspt"
900 | ".perspt-target"
901 | ".perspt-tmp"
902 | ".perspt-home"
903 | ".venv"
904 | ".pytest_cache"
905 | ".ruff_cache"
906 | "__pycache__"
907 | "target"
908 )
909 ) {
910 continue;
911 }
912 let from = entry.path();
913 if excluded.iter().any(|path| path == &from) {
914 continue;
915 }
916 let to = destination.join(&name);
917 let kind = entry.file_type()?;
918 if kind.is_dir() {
919 if name == "node_modules" {
920 link_dependency_dir(&from, &to)?;
921 } else {
922 std::fs::create_dir_all(&to)?;
923 copy_workspace_filtered(&from, &to, excluded)?;
924 }
925 } else if kind.is_file() {
926 std::fs::copy(&from, &to)?;
927 }
928 }
929 Ok(())
930}
931
932#[cfg(unix)]
933fn link_dependency_dir(source: &Path, destination: &Path) -> Result<()> {
934 std::os::unix::fs::symlink(source, destination)?;
935 Ok(())
936}
937
938#[cfg(not(unix))]
939fn link_dependency_dir(source: &Path, destination: &Path) -> Result<()> {
940 std::fs::create_dir_all(destination)?;
941 copy_workspace(source, destination)
942}
943
944#[cfg(test)]
945mod tests {
946 use super::*;
947
948 fn mixed_language_source() -> tempfile::TempDir {
950 let source = tempfile::tempdir().unwrap();
951 std::fs::write(
952 source.path().join("Cargo.toml"),
953 "[package]\nname = \"x\"\nversion = \"0.0.1\"\n",
954 )
955 .unwrap();
956 std::fs::create_dir_all(source.path().join("src")).unwrap();
957 std::fs::write(source.path().join("src/lib.rs"), "").unwrap();
958 std::fs::write(
959 source.path().join("pyproject.toml"),
960 "[project]\nname = \"x\"\nversion = \"0.0.1\"\n",
961 )
962 .unwrap();
963 source
964 }
965
966 #[tokio::test]
967 async fn mixed_repo_interactive_tests_cover_all_plugins_until_a_mutation_selects_one() {
968 let source = mixed_language_source();
969 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
970
971 let all = candidate
972 .commands_for("run_test", &serde_json::json!({}))
973 .unwrap();
974 assert!(all.len() >= 2, "both plugins must run before any mutation");
975
976 candidate
977 .apply(&write_call("src/lib.rs", "pub fn f() {}"), &write_entry())
978 .await
979 .unwrap();
980 let narrowed = candidate
981 .commands_for("run_test", &serde_json::json!({}))
982 .unwrap();
983 assert_eq!(narrowed.len(), 1);
984 assert!(narrowed[0].1.starts_with("cargo test"));
985 }
986
987 #[test]
988 fn run_test_filter_threads_through_and_rejects_injection() {
989 let source = mixed_language_source();
990 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
991
992 let filtered = candidate
993 .commands_for("run_test", &serde_json::json!({"filter": "my_test::case"}))
994 .unwrap();
995 assert!(
996 filtered
997 .iter()
998 .any(|(_, command, _)| command.contains("my_test::case"))
999 );
1000
1001 let injected =
1002 candidate.commands_for("run_test", &serde_json::json!({"filter": "x; rm -rf /"}));
1003 assert!(injected.is_err(), "shell metacharacters must be refused");
1004 }
1005
1006 #[tokio::test]
1009 async fn seeded_files_are_not_promotable_until_touched() {
1010 let source = tempfile::tempdir().unwrap();
1011 std::fs::write(source.path().join("Cargo.toml"), "[package]\n").unwrap();
1012 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1013 candidate
1014 .restore_seeded(&[crate::toolloop::SeedFile {
1015 path: "src/inherited.rs".into(),
1016 content: Some(b"pub fn one() {}".to_vec()),
1017 source_preimage: None,
1018 }])
1019 .unwrap();
1020 assert!(!candidate.has_mutated(), "seeding is not a mutation");
1021 assert!(candidate.touched_paths().is_empty());
1022
1023 candidate
1024 .apply(&write_call("src/own.rs", "pub fn two() {}"), &write_entry())
1025 .await
1026 .unwrap();
1027 assert_eq!(candidate.touched_paths(), vec!["src/own.rs".to_string()]);
1028 assert!(candidate.overlay_root().join("src/inherited.rs").is_file());
1030 }
1031
1032 #[test]
1033 fn paths_cannot_escape_the_candidate() {
1034 assert!(validate_relative_path("src/lib.rs").is_ok());
1035 assert!(validate_relative_path("../outside").is_err());
1036 assert!(validate_relative_path("/tmp/outside").is_err());
1037 }
1038
1039 #[cfg(unix)]
1040 #[test]
1041 fn mutation_cannot_cross_an_overlay_symlink() {
1042 let overlay = tempfile::tempdir().unwrap();
1043 let outside = tempfile::tempdir().unwrap();
1044 std::os::unix::fs::symlink(outside.path(), overlay.path().join("deps")).unwrap();
1045 assert!(reject_symlink_ancestor(overlay.path(), "deps/package/file.rs").is_err());
1046 assert!(reject_symlink_ancestor(overlay.path(), "src/file.rs").is_ok());
1047 }
1048
1049 fn write_call(path: &str, content: &str) -> perspt_sdk::ProviderToolCall {
1050 perspt_sdk::ProviderToolCall {
1051 call_id: uuid::Uuid::new_v4().to_string(),
1052 name: "write_file".into(),
1053 arguments: serde_json::json!({"path": path, "content": content}),
1054 }
1055 }
1056
1057 fn write_entry() -> ToolEntry {
1058 perspt_sdk::base_entries()
1059 .into_iter()
1060 .find(|entry| entry.name == "write_file")
1061 .expect("base catalog has write_file")
1062 }
1063
1064 #[tokio::test]
1065 async fn checkpoint_restore_and_promotion_use_touched_paths() {
1066 let source = tempfile::tempdir().unwrap();
1067 std::fs::write(source.path().join("a.txt"), "old").unwrap();
1068 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1069 let before = candidate.checkpoint(&["a.txt".into()]).await.unwrap();
1070 let entry = write_entry();
1071 candidate
1072 .apply(&write_call("a.txt", "new"), &entry)
1073 .await
1074 .unwrap();
1075 candidate.restore(&before).await.unwrap();
1076 assert_eq!(
1077 std::fs::read_to_string(candidate.overlay_root().join("a.txt")).unwrap(),
1078 "old"
1079 );
1080 assert!(!candidate.has_mutated());
1081 candidate
1082 .apply(&write_call("a.txt", "accepted"), &entry)
1083 .await
1084 .unwrap();
1085 candidate.promote().unwrap();
1086 assert_eq!(
1087 std::fs::read_to_string(source.path().join("a.txt")).unwrap(),
1088 "accepted"
1089 );
1090 }
1091
1092 #[tokio::test]
1093 async fn restore_removes_files_first_created_after_the_checkpoint() {
1094 let source = tempfile::tempdir().unwrap();
1095 std::fs::write(source.path().join("a.txt"), "old").unwrap();
1096 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1097 let accepted = candidate.checkpoint(&[]).await.unwrap();
1098 let entry = write_entry();
1099 candidate
1102 .apply(&write_call("fresh.rs", "fn injected() {}"), &entry)
1103 .await
1104 .unwrap();
1105 assert!(candidate.overlay_root().join("fresh.rs").is_file());
1106 assert!(candidate.touched_paths().contains(&"fresh.rs".to_string()));
1107 candidate.restore(&accepted).await.unwrap();
1108 assert!(!candidate.overlay_root().join("fresh.rs").exists());
1109 assert!(candidate.touched_paths().is_empty());
1110 assert!(!candidate.has_mutated());
1111 }
1112
1113 #[tokio::test]
1114 async fn read_paths_are_never_promoted() {
1115 let source = tempfile::tempdir().unwrap();
1116 std::fs::write(source.path().join("read-only.txt"), "user edit kept").unwrap();
1117 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1118 candidate
1122 .checkpoint(&["read-only.txt".into()])
1123 .await
1124 .unwrap();
1125 std::fs::write(source.path().join("read-only.txt"), "user edit v2").unwrap();
1126 assert!(candidate.touched_paths().is_empty());
1127 candidate.promote().unwrap();
1128 assert_eq!(
1129 std::fs::read_to_string(source.path().join("read-only.txt")).unwrap(),
1130 "user edit v2"
1131 );
1132 }
1133
1134 #[tokio::test]
1135 async fn backward_compatible_view_restores_old_tests_but_keeps_candidate_code() {
1136 let source = tempfile::tempdir().unwrap();
1137 std::fs::create_dir_all(source.path().join("src")).unwrap();
1138 std::fs::create_dir_all(source.path().join("tests")).unwrap();
1139 std::fs::write(
1140 source.path().join("pyproject.toml"),
1141 "[project]\nname='x'\n",
1142 )
1143 .unwrap();
1144 std::fs::write(source.path().join("src/logic.py"), "VALUE = 'old'\n").unwrap();
1145 std::fs::write(
1146 source.path().join("tests/test_logic.py"),
1147 "def test_value(): assert False\n",
1148 )
1149 .unwrap();
1150 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1151 candidate
1152 .apply(
1153 &write_call("src/logic.py", "VALUE = 'candidate'\n"),
1154 &write_entry(),
1155 )
1156 .await
1157 .unwrap();
1158 candidate
1159 .apply(
1160 &write_call("tests/test_logic.py", "def test_value(): pass\n"),
1161 &write_entry(),
1162 )
1163 .await
1164 .unwrap();
1165
1166 let oracle = candidate.backward_compatibility_tests().unwrap().unwrap();
1167 assert_eq!(
1168 std::fs::read_to_string(oracle.root.join("src/logic.py")).unwrap(),
1169 "VALUE = 'candidate'\n"
1170 );
1171 assert_eq!(
1172 std::fs::read_to_string(oracle.root.join("tests/test_logic.py")).unwrap(),
1173 "def test_value(): assert False\n"
1174 );
1175 }
1176
1177 #[tokio::test]
1178 async fn external_oracle_overlays_protected_evidence_onto_candidate_code() {
1179 let source = tempfile::tempdir().unwrap();
1180 std::fs::create_dir_all(source.path().join("src")).unwrap();
1181 std::fs::write(source.path().join("Cargo.toml"), "candidate manifest\n").unwrap();
1182 std::fs::write(source.path().join("src/lib.rs"), "source code\n").unwrap();
1183 let protected = tempfile::tempdir().unwrap();
1184 std::fs::create_dir_all(protected.path().join("tests")).unwrap();
1185 std::fs::write(
1186 protected.path().join("tests/acceptance.rs"),
1187 "protected test\n",
1188 )
1189 .unwrap();
1190 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1191 candidate
1192 .apply(
1193 &write_call("src/lib.rs", "candidate code\n"),
1194 &write_entry(),
1195 )
1196 .await
1197 .unwrap();
1198
1199 let oracle = candidate.external_oracle_tests(protected.path()).unwrap();
1200 assert_eq!(
1201 std::fs::read_to_string(oracle.root.join("src/lib.rs")).unwrap(),
1202 "candidate code\n"
1203 );
1204 assert_eq!(
1205 std::fs::read_to_string(oracle.root.join("tests/acceptance.rs")).unwrap(),
1206 "protected test\n"
1207 );
1208 }
1209
1210 #[test]
1211 fn external_oracle_refuses_the_workspace_as_its_overlay() {
1212 let source = tempfile::tempdir().unwrap();
1213 std::fs::write(source.path().join("Cargo.toml"), "candidate manifest\n").unwrap();
1214 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1215 let error = candidate.external_oracle_tests(source.path()).unwrap_err();
1216 assert!(error.to_string().contains("dedicated directory"));
1217 }
1218
1219 #[tokio::test]
1220 async fn promotion_refuses_a_concurrent_workspace_edit() {
1221 let source = tempfile::tempdir().unwrap();
1222 std::fs::write(source.path().join("a.txt"), "baseline").unwrap();
1223 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1224 candidate
1225 .apply(&write_call("a.txt", "agent edit"), &write_entry())
1226 .await
1227 .unwrap();
1228 std::fs::write(source.path().join("a.txt"), "user edit").unwrap();
1229 assert!(candidate.promote().is_err());
1230 assert_eq!(
1231 std::fs::read_to_string(source.path().join("a.txt")).unwrap(),
1232 "user edit"
1233 );
1234 }
1235
1236 #[cfg(unix)]
1237 #[tokio::test]
1238 async fn promotion_cannot_cross_a_source_workspace_symlink() {
1239 let source = tempfile::tempdir().unwrap();
1240 let outside = tempfile::tempdir().unwrap();
1241 std::os::unix::fs::symlink(outside.path(), source.path().join("linked")).unwrap();
1242 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1243 candidate
1244 .apply(
1245 &write_call("linked/escaped.txt", "must stay in overlay"),
1246 &write_entry(),
1247 )
1248 .await
1249 .unwrap();
1250 assert!(candidate.promote().is_err());
1251 assert!(!outside.path().join("escaped.txt").exists());
1252 }
1253
1254 #[cfg(unix)]
1258 #[tokio::test]
1259 async fn ancestor_swapped_for_symlink_after_admission_is_denied() {
1260 let source = tempfile::tempdir().unwrap();
1261 let outside = tempfile::tempdir().unwrap();
1262 std::fs::create_dir(source.path().join("dir")).unwrap();
1263 std::fs::write(source.path().join("dir/a.txt"), "baseline").unwrap();
1264 let candidate = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1265 candidate
1266 .apply(&write_call("dir/a.txt", "mutated"), &write_entry())
1267 .await
1268 .unwrap();
1269
1270 std::fs::write(outside.path().join("a.txt"), "baseline").unwrap();
1271 std::fs::remove_dir_all(source.path().join("dir")).unwrap();
1272 std::os::unix::fs::symlink(outside.path(), source.path().join("dir")).unwrap();
1273
1274 let error = candidate.promote().unwrap_err();
1275 assert!(
1276 error.to_string().contains("descending into dir"),
1277 "expected symlink refusal, got: {error:#}"
1278 );
1279 assert_eq!(
1280 std::fs::read_to_string(outside.path().join("a.txt")).unwrap(),
1281 "baseline"
1282 );
1283 }
1284
1285 #[tokio::test]
1286 async fn resumed_candidate_keeps_the_original_source_precondition() {
1287 let source = tempfile::tempdir().unwrap();
1288 std::fs::write(source.path().join("a.txt"), "baseline").unwrap();
1289 let first = CandidateWorkspace::create(source.path(), "n1", 0, "r1").unwrap();
1290 first
1291 .apply(&write_call("a.txt", "accepted"), &write_entry())
1292 .await
1293 .unwrap();
1294 let seed = first.export_accepted().await.unwrap();
1295
1296 std::fs::write(source.path().join("a.txt"), "user edit while stopped").unwrap();
1297 let resumed = CandidateWorkspace::create(source.path(), "n1", 0, "r2").unwrap();
1298 resumed.restore_exported(&seed).unwrap();
1299 assert!(resumed.promote().is_err());
1300 assert_eq!(
1301 std::fs::read_to_string(source.path().join("a.txt")).unwrap(),
1302 "user edit while stopped"
1303 );
1304 }
1305}