返回 CodeWhale
1 mod artifact;
2 #[cfg(test)]
3 mod tests;
4
5 use std::collections::HashMap;
6 use std::fs::{self, File, OpenOptions};
7 use std::io::Write;
8 use std::path::{Component, Path, PathBuf};
9 use std::process::{Command, Stdio};
10 use std::thread;
11 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
12
13 use artifact::{Artifact, ArtifactStore};
14 use codewhale_sandbox::SandboxResourceLimits;
15 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
16 use codewhale_sandbox::{CommandSpec, SandboxManager, SandboxPolicy, SandboxType};
17 use serde::{Deserialize, Serialize};
18 use serde_json::{Value, json};
19 use sha2::{Digest, Sha256};
20 use tokio_util::sync::CancellationToken;
21
22 const AUTHORIZED_WORKFLOW_SHA256: &str =
23 "d97de6db9c5526149cbeee843b7fe692e3a37965a040dd948becc5f177a8acc5";
24
25 #[derive(Clone, Deserialize, Serialize)]
26 #[serde(deny_unknown_fields)]
27 struct Gate {
28 candidate_argv: Vec<String>,
29 cases_path: PathBuf,
30 timeout_secs: u64,
31 min_tests: u64,
32 holdout: bool,
33 }
34 #[derive(Clone, Deserialize, Serialize)]
35 #[serde(deny_unknown_fields)]
36 struct Case {
37 input: Value,
38 expected: Value,
39 }
40
41 #[derive(Clone, Deserialize, Serialize)]
42 #[serde(deny_unknown_fields)]
43 struct Spec {
44 version: u32,
45 objective: String,
46 baseline_sha: String,
47 allowed_write_roots: Vec<String>,
48 protected_paths: Vec<String>,
49 isolation_backend: String,
50 max_wall_secs: u64,
51 hard_gates: Vec<Gate>,
52 }
53
54 pub(super) struct VerifiedCandidateEvaluator {
55 spec: Spec,
56 spec_path: PathBuf,
57 spec_hash: String,
58 manifest_hash: String,
59 binary_hash: String,
60 executable_hashes: HashMap<String, String>,
61 gate_cases: Vec<Vec<Case>>,
62 case_hashes: Vec<String>,
63 store: ArtifactStore,
64 sandbox_probe: Value,
65 root: PathBuf,
66 repo: PathBuf,
67 started: Option<Instant>,
68 started_at_ms: Option<u64>,
69 evaluation_elapsed: Duration,
70 evaluated: HashMap<String, Value>,
71 }
72
73 fn candidate_id(value: &str) -> Result<(), String> {
74 if value.is_empty()
75 || value.len() > 64
76 || !value
77 .bytes()
78 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
79 {
80 return Err("invalid candidate identifier".to_string());
81 }
82 Ok(())
83 }
84
85 fn validate_scope(
86 artifact: &Artifact,
87 allowed: &[String],
88 protected: &[String],
89 ) -> Result<(), String> {
90 if artifact.entries.is_empty() {
91 return Err("empty candidate artifact".to_string());
92 }
93 for entry in &artifact.entries {
94 normalized_path(&entry.path)?;
95 if !allowed.iter().any(|root| in_scope(&entry.path, root))
96 || protected.iter().any(|root| in_scope(&entry.path, root))
97 || protected_git_path(&entry.path)
98 || protected_test_path(&entry.path)
99 || in_scope(&entry.path, ".codewhale")
100 {
101 return Err(format!("protected or out-of-scope path: {}", entry.path));
102 }
103 }
104 Ok(())
105 }
106
107 fn hash(bytes: &[u8]) -> String {
108 Sha256::digest(bytes)
109 .iter()
110 .map(|byte| format!("{byte:02x}"))
111 .collect()
112 }
113
114 pub(super) fn authorized_workflow_source(source: &str) -> bool {
115 hash(source.as_bytes()) == AUTHORIZED_WORKFLOW_SHA256
116 }
117
118 fn git(cwd: &Path, args: &[&str]) -> Result<std::process::Output, String> {
119 let output = codewhale_dependencies::Git::workspace_command(cwd)
120 .map_err(|error| format!("git {}: {error}", args.join(" ")))?
121 .args(args)
122 .output()
123 .map_err(|error| format!("git {}: {error}", args.join(" ")))?;
124 if !output.status.success() {
125 return Err(format!(
126 "git {}: {}",
127 args.join(" "),
128 String::from_utf8_lossy(&output.stderr).trim()
129 ));
130 }
131 Ok(output)
132 }
133
134 fn git_text(cwd: &Path, args: &[&str]) -> Result<String, String> {
135 String::from_utf8(git(cwd, args)?.stdout)
136 .map(|text| text.trim().to_string())
137 .map_err(|error| error.to_string())
138 }
139
140 fn normalized_path(value: &str) -> Result<String, String> {
141 #[cfg(unix)]
142 if value.contains('\\') {
143 return Err(format!("invalid repo-relative path {value:?}"));
144 }
145 let value = value.replace('\\', "/");
146 if value.is_empty()
147 || value.starts_with('/')
148 || value
149 .split('/')
150 .any(|part| part.is_empty() || part == "." || part == "..")
151 || Path::new(&value)
152 .components()
153 .any(|part| !matches!(part, Component::Normal(_)))
154 {
155 return Err(format!("invalid repo-relative path {value:?}"));
156 }
157 Ok(value)
158 }
159
160 fn in_scope(path: &str, root: &str) -> bool {
161 path == root || path.starts_with(&format!("{root}/"))
162 }
163
164 fn protected_test_path(path: &str) -> bool {
165 let file = path.rsplit('/').next().unwrap_or(path);
166 path.starts_with("tests/")
167 || path.contains("/tests/")
168 || file.starts_with("test_")
169 || file.ends_with("_test.rs")
170 || file.ends_with("_tests.rs")
171 || file.ends_with(".test.js")
172 || file.ends_with(".test.ts")
173 || file.ends_with(".spec.js")
174 || file.ends_with(".spec.ts")
175 }
176
177 fn protected_git_path(path: &str) -> bool {
178 path.split('/').any(|part| {
179 matches!(
180 part,
181 ".git" | ".gitattributes" | ".gitmodules" | ".gitconfig" | ".lfsconfig"
182 )
183 })
184 }
185
186 fn same_json(actual: &Value, expected: &Value) -> bool {
187 match (actual, expected) {
188 (Value::Number(a), Value::Number(b)) => {
189 if a == b {
190 return true;
191 }
192 if a.is_f64() == b.is_f64() {
193 return false;
194 }
195 let (integer, decimal) = if a.is_f64() { (b, a) } else { (a, b) };
196 let integer = integer
197 .as_i64()
198 .map(|value| value as i128)
199 .or_else(|| integer.as_u64().map(|value| value as i128));
200 integer.is_some_and(|value| {
201 value.unsigned_abs() <= (1u128 << 53) && decimal.as_f64() == Some(value as f64)
202 })
203 }
204 (Value::Array(a), Value::Array(b)) => {
205 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| same_json(x, y))
206 }
207 (Value::Object(a), Value::Object(b)) => {
208 a.len() == b.len()
209 && a.iter()
210 .all(|(key, value)| b.get(key).is_some_and(|other| same_json(value, other)))
211 }
212 _ => actual == expected,
213 }
214 }
215
216 struct SandboxRun {
217 exit_code: Option<i32>,
218 stop_reason: Option<String>,
219 stdout: String,
220 stderr: String,
221 wall_ms: u128,
222 }
223
224 struct GateExecution {
225 receipts: Vec<Value>,
226 test_count: u64,
227 failure: Option<String>,
228 feedback: String,
229 stop_reason: Option<String>,
230 }
231
232 fn isolated_command(
233 source: &Path,
234 scratch: &Path,
235 program: &str,
236 args: Vec<String>,
237 timeout: Duration,
238 ) -> Result<codewhale_sandbox::ExecEnv, String> {
239 #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))]
240 {
241 let _ = (source, scratch, program, args, timeout);
242 Err("UNSUPPORTED_ISOLATION: candidate gates require Linux bubblewrap".to_string())
243 }
244 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
245 {
246 let mut manager = SandboxManager::with_bwrap_preference(true);
247 let mut readable = ["/usr", "/lib", "/lib64", "/etc/alternatives"]
248 .into_iter()
249 .map(PathBuf::from)
250 .filter(|path| path.exists())
251 .collect::<Vec<_>>();
252 readable.push(source.to_path_buf());
253 manager.set_readable_paths(readable);
254 let spec = CommandSpec::program(program, args, scratch.to_path_buf(), timeout).with_policy(
255 SandboxPolicy::WorkspaceWrite {
256 writable_roots: Vec::new(),
257 network_access: false,
258 exclude_tmpdir: true,
259 exclude_slash_tmp: true,
260 },
261 );
262 let env = manager.prepare(&spec);
263 if env.sandbox_type != SandboxType::LinuxBubblewrap
264 || env.command.first().map(String::as_str) != Some("/usr/bin/bwrap")
265 || !env.command.iter().any(|arg| arg == "--unshare-all")
266 || !env.command.iter().any(|arg| arg == "--die-with-parent")
267 || env.command.iter().any(|arg| arg == "--share-net")
268 || !env.command.windows(3).any(|part| {
269 part[0] == "--ro-bind"
270 && part[1] == source.to_string_lossy()
271 && part[2] == source.to_string_lossy()
272 })
273 {
274 return Err(
275 "UNSUPPORTED_ISOLATION: resolved sandbox is not the strict Linux backend"
276 .to_string(),
277 );
278 }
279 Ok(env)
280 }
281 }
282
283 fn run_isolated(
284 env: &codewhale_sandbox::ExecEnv,
285 input: &[u8],
286 stdout_path: &Path,
287 stderr_path: &Path,
288 timeout: Duration,
289 cancel: Option<&CancellationToken>,
290 ) -> Result<SandboxRun, String> {
291 let input_path = stdout_path.with_extension("input.json");
292 fs::write(&input_path, input).map_err(|error| error.to_string())?;
293 let stdin = File::open(&input_path).map_err(|error| error.to_string())?;
294 let stdout = File::create(stdout_path).map_err(|error| error.to_string())?;
295 let stderr = File::create(stderr_path).map_err(|error| error.to_string())?;
296 let mut command = Command::new(env.program());
297 command
298 .args(env.args())
299 .current_dir(&env.cwd)
300 .env_clear()
301 .envs(&env.env)
302 .env("HOME", &env.cwd)
303 .env("PATH", "/usr/bin:/bin")
304 .env("PYTHONDONTWRITEBYTECODE", "1")
305 .stdin(Stdio::from(stdin))
306 .stdout(Stdio::from(stdout))
307 .stderr(Stdio::from(stderr));
308 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
309 {
310 use std::os::unix::process::CommandExt;
311 unsafe {
312 command.pre_exec(|| {
313 // The evaluator command needs only stdin/stdout/stderr. Close
314 // every inherited host descriptor before bubblewrap starts.
315 let result = libc::syscall(libc::SYS_close_range, 3u32, u32::MAX, 0u32);
316 if result != 0 {
317 return Err(std::io::Error::last_os_error());
318 }
319 Ok(())
320 });
321 }
322 }
323 let started = Instant::now();
324 let mut child = env
325 .spawn_background_limited(
326 command,
327 SandboxResourceLimits {
328 address_space_bytes: 512 * 1024 * 1024,
329 file_size_bytes: 1024 * 1024,
330 open_files: 64,
331 processes: 4096,
332 cpu_seconds: timeout.as_secs().clamp(1, 8),
333 },
334 )
335 .map_err(|error| error.to_string())?;
336 let (exit_code, stop_reason) = loop {
337 if cancel.is_some_and(CancellationToken::is_cancelled) {
338 let _ = child.kill();
339 break (None, Some("cancelled".to_string()));
340 }
341 if started.elapsed() >= timeout {
342 let _ = child.kill();
343 break (None, Some("timeout".to_string()));
344 }
345 if fs::metadata(stdout_path).is_ok_and(|meta| meta.len() > 1024 * 1024)
346 || fs::metadata(stderr_path).is_ok_and(|meta| meta.len() > 1024 * 1024)
347 {
348 let _ = child.kill();
349 break (None, Some("output limit".to_string()));
350 }
351 if let Some(status) = child.try_wait().map_err(|error| error.to_string())? {
352 break (status.code(), None);
353 }
354 thread::sleep(Duration::from_millis(20));
355 };
356 child.wait().map_err(|error| error.to_string())?;
357 let stdout = fs::read(stdout_path).map_err(|error| error.to_string())?;
358 let stderr = fs::read(stderr_path).map_err(|error| error.to_string())?;
359 Ok(SandboxRun {
360 exit_code,
361 stop_reason,
362 stdout: String::from_utf8_lossy(&stdout[..stdout.len().min(1024 * 1024)]).into_owned(),
363 stderr: String::from_utf8_lossy(&stderr[..stderr.len().min(1024 * 1024)]).into_owned(),
364 wall_ms: started.elapsed().as_millis(),
365 })
366 }
367
368 fn probe_isolation(root: &Path, denied_paths: &[PathBuf]) -> Result<Value, String> {
369 let source = root.join("probe-source");
370 let scratch = root.join("probe-scratch");
371 fs::create_dir(&source).map_err(|error| error.to_string())?;
372 fs::create_dir(&scratch).map_err(|error| error.to_string())?;
373 let secret = root.join("probe-secret");
374 fs::write(&secret, b"synthetic marker").map_err(|error| error.to_string())?;
375 let code = r#"import json,os,sys
376 blocked=[]
377 for path in sys.argv[1:]:
378 try:
379 open(path).read()
380 blocked.append(False)
381 except OSError:
382 blocked.append(True)
383 open('scratch-marker','w').write('ok')
384 print(json.dumps({'secret_blocked':blocked[0],
385 'oracle_paths_blocked':all(blocked[1:]),
386 'network_namespace':os.readlink('/proc/self/ns/net')}))
387 "#;
388 let mut args = vec![
389 "-c".to_string(),
390 code.to_string(),
391 secret.to_string_lossy().into_owned(),
392 ];
393 args.extend(
394 denied_paths
395 .iter()
396 .map(|path| path.to_string_lossy().into_owned()),
397 );
398 let env = isolated_command(
399 &source,
400 &scratch,
401 "/usr/bin/python3",
402 args,
403 Duration::from_secs(5),
404 )?;
405 let run = run_isolated(
406 &env,
407 b"",
408 &root.join("probe.stdout"),
409 &root.join("probe.stderr"),
410 Duration::from_secs(5),
411 None,
412 )?;
413 let measured: Value = serde_json::from_str(&run.stdout).map_err(|_| {
414 format!(
415 "UNSUPPORTED_ISOLATION: probe output invalid: {}",
416 run.stderr
417 )
418 })?;
419 let host_net = fs::read_link("/proc/self/ns/net").map_err(|error| error.to_string())?;
420 if run.exit_code != Some(0)
421 || measured.get("secret_blocked") != Some(&Value::Bool(true))
422 || measured.get("oracle_paths_blocked") != Some(&Value::Bool(true))
423 || measured.get("network_namespace").and_then(Value::as_str)
424 == Some(host_net.to_string_lossy().as_ref())
425 || fs::read(scratch.join("scratch-marker")).ok().as_deref() != Some(b"ok")
426 {
427 return Err(format!(
428 "UNSUPPORTED_ISOLATION: capability probe failed: {}",
429 run.stderr
430 ));
431 }
432 let version = Command::new("/usr/bin/bwrap")
433 .arg("--version")
434 .output()
435 .map_err(|error| error.to_string())?;
436 Ok(json!({
437 "backend": "linux-bwrap", "version": String::from_utf8_lossy(&version.stdout).trim(),
438 "read_grants": ["/usr", "/lib", "/lib64", "/etc/alternatives", "sealed candidate tree"],
439 "writable_grants": ["private scratch", "private /tmp"],
440 "network": "unshared", "pid_namespace": "unshared",
441 "secret_blocked": true, "oracle_paths_blocked": true,
442 "probe_exit": run.exit_code,
443 "resource_limits": {"address_space_bytes": 512 * 1024 * 1024,
444 "file_size_bytes": 1024 * 1024, "open_files": 64,
445 "processes_rlimit": 4096, "cpu_seconds_per_case": 8},
446 }))
447 }
448
449 impl VerifiedCandidateEvaluator {
450 pub(super) fn freeze(
451 manifest_path: &Path,
452 workspace: &Path,
453 run_id: &str,
454 brief: &str,
455 ) -> Result<Self, String> {
456 candidate_id(run_id)?;
457 let repo = PathBuf::from(git_text(workspace, &["rev-parse", "--show-toplevel"])?)
458 .canonicalize()
459 .map_err(|error| error.to_string())?;
460 let status = git_text(
461 &repo,
462 &["status", "--porcelain", "--untracked-files=normal"],
463 )?;
464 if status.lines().any(|line| line != "?? .codewhale/") {
465 return Err("evaluator requires a clean parent checkout".to_string());
466 }
467 let spec_path = manifest_path
468 .canonicalize()
469 .map_err(|error| error.to_string())?;
470 if spec_path.starts_with(&repo) {
471 return Err("evaluator spec must live outside the candidate checkout".to_string());
472 }
473 let spec_bytes = fs::read(&spec_path).map_err(|error| error.to_string())?;
474 if spec_bytes.len() > 128 * 1024 {
475 return Err("evaluator spec exceeds 128 KiB".to_string());
476 }
477 let mut spec: Spec =
478 serde_json::from_slice(&spec_bytes).map_err(|error| error.to_string())?;
479 let baseline_sha = git_text(&repo, &["rev-parse", "HEAD"])?;
480 if spec.version != 1
481 || spec.objective != brief
482 || spec.baseline_sha != baseline_sha
483 || spec.isolation_backend != "linux-bwrap"
484 || spec.allowed_write_roots.is_empty()
485 || spec.hard_gates.is_empty()
486 || spec.hard_gates.len() > 12
487 || spec.max_wall_secs == 0
488 || spec.max_wall_secs > 3600
489 {
490 return Err(
491 "evaluator spec, baseline or bounds differ from frozen request".to_string(),
492 );
493 }
494 for root in &mut spec.allowed_write_roots {
495 *root = normalized_path(root)?;
496 }
497 for root in &mut spec.protected_paths {
498 *root = normalized_path(root)?;
499 }
500 if !spec
501 .hard_gates
502 .iter()
503 .any(|gate| !gate.holdout && gate.min_tests > 0)
504 || !spec
505 .hard_gates
506 .iter()
507 .any(|gate| gate.holdout && gate.min_tests > 0)
508 {
509 return Err("public and held-out gates must both require nonzero cases".to_string());
510 }
511 let mut gate_cases = Vec::new();
512 let mut case_hashes = Vec::new();
513 for gate in &mut spec.hard_gates {
514 if gate.candidate_argv.len() != 2
515 || !Path::new(&gate.candidate_argv[0]).is_absolute()
516 || gate.timeout_secs == 0
517 || gate.timeout_secs > 1800
518 || gate.min_tests == 0
519 {
520 return Err("invalid process-level gate command or bound".to_string());
521 }
522 let candidate_program = normalized_path(&gate.candidate_argv[1])?;
523 if !spec
524 .allowed_write_roots
525 .iter()
526 .any(|root| in_scope(&candidate_program, root))
527 {
528 return Err("candidate program is outside allowed write scope".to_string());
529 }
530 let cases_path = gate
531 .cases_path
532 .canonicalize()
533 .map_err(|error| error.to_string())?;
534 if cases_path.starts_with(&repo) {
535 return Err("trusted cases must live outside candidate checkout".to_string());
536 }
537 let bytes = fs::read(&cases_path).map_err(|error| error.to_string())?;
538 if bytes.len() > 2 * 1024 * 1024 {
539 return Err("trusted case bundle exceeds 2 MiB".to_string());
540 }
541 let cases: Vec<Case> =
542 serde_json::from_slice(&bytes).map_err(|error| error.to_string())?;
543 if cases.is_empty() || cases.len() > 256 || cases.len() < gate.min_tests as usize {
544 return Err("trusted case bundle has invalid test count".to_string());
545 }
546 gate_cases.push(cases);
547 case_hashes.push(hash(&bytes));
548 gate.cases_path = cases_path;
549 }
550 let root = std::env::temp_dir().join(format!(
551 "codewhale-evaluator-{run_id}-{}",
552 uuid::Uuid::new_v4().simple()
553 ));
554 #[cfg(unix)]
555 {
556 use std::os::unix::fs::DirBuilderExt;
557 let mut builder = fs::DirBuilder::new();
558 builder.mode(0o700);
559 builder.create(&root).map_err(|error| error.to_string())?;
560 }
561 #[cfg(not(unix))]
562 fs::create_dir(&root).map_err(|error| error.to_string())?;
563 let frozen = (|| {
564 let store = ArtifactStore::freeze(&repo, &root)?;
565 let denied_paths = std::iter::once(spec_path.clone())
566 .chain(spec.hard_gates.iter().map(|gate| gate.cases_path.clone()))
567 .collect::<Vec<_>>();
568 let sandbox_probe = probe_isolation(&root, &denied_paths)?;
569 let binary_hash = hash(
570 &fs::read(std::env::current_exe().map_err(|error| error.to_string())?)
571 .map_err(|error| error.to_string())?,
572 );
573 let mut executable_hashes = HashMap::new();
574 for executable in std::iter::once("/usr/bin/bwrap").chain(
575 spec.hard_gates
576 .iter()
577 .map(|gate| gate.candidate_argv[0].as_str()),
578 ) {
579 let bytes = fs::read(executable).map_err(|error| error.to_string())?;
580 executable_hashes.insert(executable.to_string(), hash(&bytes));
581 }
582 let manifest = json!({
583 "version": 1,
584 "run_id": run_id,
585 "spec_sha256": hash(&spec_bytes),
586 "baseline_sha": spec.baseline_sha,
587 "baseline_id": store.baseline_id(),
588 "public_fixture_sha256": case_hashes.iter().zip(&spec.hard_gates)
589 .filter(|(_, gate)| !gate.holdout)
590 .map(|(digest, _)| digest).collect::<Vec<_>>(),
591 "oracle_sha256": case_hashes,
592 "gate_policy_sha256": hash(&serde_json::to_vec(&spec.hard_gates)
593 .map_err(|error| error.to_string())?),
594 "native_binary_sha256": binary_hash,
595 "executable_sha256": executable_hashes,
596 "sandbox_probe": sandbox_probe,
597 "isolation_backend": spec.isolation_backend,
598 "allowed_write_roots": spec.allowed_write_roots,
599 "protected_paths": spec.protected_paths,
600 "capture_policy": artifact::capture_policy(),
601 "review_only": true,
602 });
603 let manifest_bytes =
604 serde_json::to_vec_pretty(&manifest).map_err(|error| error.to_string())?;
605 let mut file = OpenOptions::new()
606 .write(true)
607 .create_new(true)
608 .open(root.join("manifest.json"))
609 .map_err(|error| error.to_string())?;
610 file.write_all(&manifest_bytes)
611 .map_err(|error| error.to_string())?;
612 file.sync_all().map_err(|error| error.to_string())?;
613 Ok(Self {
614 spec,
615 spec_path,
616 spec_hash: hash(&spec_bytes),
617 manifest_hash: hash(&manifest_bytes),
618 binary_hash,
619 executable_hashes,
620 gate_cases,
621 case_hashes,
622 store,
623 sandbox_probe,
624 root: root.clone(),
625 repo,
626 started: None,
627 started_at_ms: None,
628 evaluation_elapsed: Duration::ZERO,
629 evaluated: HashMap::new(),
630 })
631 })();
632 if frozen.is_err() {
633 let _ = fs::remove_dir_all(&root);
634 }
635 frozen
636 }
637
638 fn verify_frozen_inputs(&self) -> Result<(), String> {
639 self.store.verify_baseline()?;
640 if hash(&fs::read(&self.spec_path).map_err(|error| error.to_string())?) != self.spec_hash
641 || hash(&fs::read(self.root.join("manifest.json")).map_err(|error| error.to_string())?)
642 != self.manifest_hash
643 || hash(
644 &fs::read(std::env::current_exe().map_err(|error| error.to_string())?)
645 .map_err(|error| error.to_string())?,
646 ) != self.binary_hash
647 {
648 return Err("frozen spec, manifest or evaluator binary changed".to_string());
649 }
650 for (gate, digest) in self.spec.hard_gates.iter().zip(&self.case_hashes) {
651 if hash(&fs::read(&gate.cases_path).map_err(|error| error.to_string())?) != *digest {
652 return Err("frozen oracle/fixture bundle changed".to_string());
653 }
654 }
655 for (executable, digest) in &self.executable_hashes {
656 if hash(&fs::read(executable).map_err(|error| error.to_string())?) != *digest {
657 return Err(format!("frozen execution binary changed: {executable}"));
658 }
659 }
660 Ok(())
661 }
662
663 pub(super) fn summary(&self) -> Value {
664 json!({
665 "manifest": self.root.join("manifest.json"),
666 "run_root": self.root,
667 "baseline_sha": self.spec.baseline_sha,
668 "baseline_id": self.store.baseline_id(),
669 "spec_sha256": self.spec_hash,
670 "sandbox_probe": self.sandbox_probe,
671 "capture_policy": artifact::capture_policy(),
672 "evaluation_started_at_ms": self.started_at_ms,
673 "evaluation_elapsed_ms": self.evaluation_elapsed.as_millis(),
674 "review_only": true
675 })
676 }
677
678 pub(super) fn evaluate(
679 &mut self,
680 id: &str,
681 worktree: &Path,
682 completed: bool,
683 cancel: &CancellationToken,
684 ) -> Result<Value, String> {
685 candidate_id(id)?;
686 if !completed || cancel.is_cancelled() {
687 return Err("candidate worker has not completed or run was cancelled".to_string());
688 }
689 if self.evaluated.contains_key(id)
690 || self.root.join(format!("{id}-evaluation.json")).exists()
691 {
692 return Err("candidate already evaluated".to_string());
693 }
694 self.verify_frozen_inputs()?;
695 let worktree = worktree.canonicalize().map_err(|error| error.to_string())?;
696 if worktree == self.repo
697 || git_text(&worktree, &["rev-parse", "HEAD"])? != self.spec.baseline_sha
698 {
699 return Err(
700 "candidate worktree starting HEAD differs from frozen baseline".to_string(),
701 );
702 }
703 let common_dir = |cwd: &Path| -> Result<PathBuf, String> {
704 let raw = git_text(cwd, &["rev-parse", "--git-common-dir"])?;
705 let path = PathBuf::from(raw);
706 let path = if path.is_absolute() {
707 path
708 } else {
709 cwd.join(path)
710 };
711 path.canonicalize().map_err(|error| error.to_string())
712 };
713 if common_dir(&worktree)? != common_dir(&self.repo)? {
714 return Err("candidate worktree does not belong to frozen repository".to_string());
715 }
716 self.begin_evaluation()?;
717 let result = (|| {
718 let artifact =
719 self.store
720 .capture(&worktree, id, Vec::new(), &self.spec.protected_paths)?;
721 self.run_candidate(id, &artifact, false, cancel)
722 })();
723 self.finish_evaluation();
724 if let Ok(receipt) = &result {
725 self.evaluated.insert(id.to_string(), receipt.clone());
726 }
727 result
728 }
729
730 pub(super) fn replay(&mut self, id: &str, cancel: &CancellationToken) -> Result<Value, String> {
731 candidate_id(id)?;
732 if cancel.is_cancelled() {
733 return Err("evaluation cancelled".to_string());
734 }
735 self.verify_frozen_inputs()?;
736 let original = self
737 .evaluated
738 .get(id)
739 .ok_or("missing original evaluation")?;
740 if original.get("status").and_then(Value::as_str) != Some("PASS") {
741 return Err("only a verified public candidate can be replayed".to_string());
742 }
743 let bytes = fs::read(self.root.join("artifacts").join(format!("{id}.json")))
744 .map_err(|error| error.to_string())?;
745 let digest = hash(&bytes);
746 if original
747 .get("artifact_manifest_sha256")
748 .and_then(Value::as_str)
749 != Some(digest.as_str())
750 {
751 return Err("sealed artifact manifest changed".to_string());
752 }
753 let artifact = self.store.load(id)?;
754 for (key, expected) in [
755 ("artifact_id", artifact.artifact_id.as_str()),
756 ("candidate_tree_hash", artifact.candidate_tree_hash.as_str()),
757 ("baseline_id", self.store.baseline_id()),
758 ("baseline_sha", self.spec.baseline_sha.as_str()),
759 ("spec_sha256", self.spec_hash.as_str()),
760 ("frozen_manifest_sha256", self.manifest_hash.as_str()),
761 ("native_binary_sha256", self.binary_hash.as_str()),
762 ] {
763 if original.get(key).and_then(Value::as_str) != Some(expected) {
764 return Err(format!(
765 "original receipt {key} differs from frozen spec/artifact"
766 ));
767 }
768 }
769 if original.get("oracle_sha256") != Some(&json!(self.case_hashes))
770 || original.get("executable_sha256") != Some(&json!(self.executable_hashes))
771 || original.get("sandbox_probe") != Some(&self.sandbox_probe)
772 {
773 return Err(
774 "original receipt oracle or execution identity differs from frozen spec"
775 .to_string(),
776 );
777 }
778 self.begin_evaluation()?;
779 let result = self.run_candidate(id, &artifact, true, cancel);
780 self.finish_evaluation();
781 result
782 }
783
784 fn begin_evaluation(&mut self) -> Result<(), String> {
785 self.started_at_ms = Some(
786 SystemTime::now()
787 .duration_since(UNIX_EPOCH)
788 .map_err(|error| error.to_string())?
789 .as_millis() as u64,
790 );
791 self.started = Some(Instant::now());
792 Ok(())
793 }
794
795 fn finish_evaluation(&mut self) {
796 if let Some(started) = self.started.take() {
797 self.evaluation_elapsed += started.elapsed();
798 }
799 }
800
801 fn run_candidate(
802 &self,
803 id: &str,
804 artifact: &Artifact,
805 replay: bool,
806 cancel: &CancellationToken,
807 ) -> Result<Value, String> {
808 let suffix = if replay { "replay" } else { "evaluation" };
809 let artifact_bytes = fs::read(self.root.join("artifacts").join(format!("{id}.json")))
810 .map_err(|error| error.to_string())?;
811 let artifact_manifest_sha256 = hash(&artifact_bytes);
812 let scope = validate_scope(
813 artifact,
814 &self.spec.allowed_write_roots,
815 &self.spec.protected_paths,
816 );
817 let mut status = "REJECTED";
818 let mut execution_status = "NOT_STARTED";
819 let mut reason = scope.as_ref().err().cloned();
820 let mut gates = Vec::new();
821 let mut test_count = 0u64;
822 let mut public_feedback = String::new();
823 let mut stop_reason = None;
824 if scope.is_ok() {
825 let execution = self.execute_gates(id, artifact, replay, cancel);
826 match execution {
827 Ok(outcome) => {
828 gates = outcome.receipts;
829 test_count = outcome.test_count;
830 public_feedback = outcome.feedback;
831 stop_reason = outcome.stop_reason;
832 execution_status = if stop_reason.is_some() {
833 "STOPPED"
834 } else {
835 "COMPLETE"
836 };
837 reason = outcome.failure.or_else(|| stop_reason.clone());
838 status = if stop_reason.is_some() {
839 "UNKNOWN"
840 } else if reason.is_none() && test_count > 0 {
841 "PASS"
842 } else {
843 "FAIL"
844 };
845 }
846 Err(error) => {
847 execution_status = "INCOMPLETE";
848 status = "UNKNOWN";
849 reason = Some(error);
850 }
851 }
852 }
853 let material = self.store.review_material(artifact)?;
854 let review_complete = material.is_some();
855 let now = SystemTime::now()
856 .duration_since(UNIX_EPOCH)
857 .map_err(|error| error.to_string())?
858 .as_millis();
859 let receipt_path = self.root.join(format!("{id}-{suffix}.json"));
860 let receipt = json!({
861 "version": 1,
862 "candidate_id": id,
863 "status": status,
864 "execution_status": execution_status,
865 "stop_reason": stop_reason,
866 "reason": reason,
867 "spec_sha256": self.spec_hash,
868 "frozen_manifest_sha256": self.manifest_hash,
869 "baseline_sha": self.spec.baseline_sha,
870 "baseline_id": self.store.baseline_id(),
871 "artifact_id": artifact.artifact_id,
872 "candidate_tree_hash": artifact.candidate_tree_hash,
873 "artifact_manifest_sha256": artifact_manifest_sha256,
874 "oracle_sha256": self.case_hashes,
875 "native_binary_sha256": self.binary_hash,
876 "executable_sha256": self.executable_hashes,
877 "sandbox_probe": self.sandbox_probe,
878 "changed_paths": artifact.entries.iter().map(|entry| &entry.path).collect::<Vec<_>>(),
879 "excluded_generated_paths": artifact.excluded_generated_paths,
880 "capture_policy": artifact::capture_policy(),
881 "gates": gates,
882 "test_count": test_count,
883 "public_failure_feedback": public_feedback,
884 "review_material_sha256": material.as_ref().map(|text| hash(text.as_bytes())),
885 "review_material_bytes": material.as_ref().map(String::len),
886 "review_material": material,
887 "review_complete": review_complete,
888 "evaluation_started_at_ms": self.started_at_ms,
889 "evaluation_elapsed_ms": self.evaluation_elapsed.as_millis() + self.started.map_or(0, |started| started.elapsed().as_millis()),
890 "execution_deadline_at_ms": self.started_at_ms.map(|started| started + Duration::from_secs(self.spec.max_wall_secs).saturating_sub(self.evaluation_elapsed).as_millis() as u64),
891 "receipt_path": receipt_path,
892 "observed_at_ms": now,
893 "review_only": true,
894 });
895 let bytes = serde_json::to_vec_pretty(&receipt).map_err(|error| error.to_string())?;
896 let mut file = OpenOptions::new()
897 .write(true)
898 .create_new(true)
899 .open(&receipt_path)
900 .map_err(|error| error.to_string())?;
901 file.write_all(&bytes).map_err(|error| error.to_string())?;
902 file.sync_all().map_err(|error| error.to_string())?;
903 Ok(receipt)
904 }
905
906 fn execute_gates(
907 &self,
908 id: &str,
909 artifact: &Artifact,
910 replay: bool,
911 cancel: &CancellationToken,
912 ) -> Result<GateExecution, String> {
913 let owned = tempfile::Builder::new()
914 .prefix("candidate-")
915 .tempdir_in(&self.root)
916 .map_err(|error| error.to_string())?;
917 let source = owned.path().join("source");
918 self.store.materialize(artifact, &source)?;
919 let mut receipts = Vec::new();
920 let mut test_count = 0u64;
921 let mut failure = None;
922 let mut feedback = String::new();
923 let mut stop_reason = None;
924 let overall_started = self.started.ok_or("evaluation clock was not started")?;
925 for (gate_index, gate) in self.spec.hard_gates.iter().enumerate() {
926 if gate.holdout && !replay {
927 continue;
928 }
929 let started = Instant::now();
930 let mut passed_count = 0u64;
931 let mut observed_count = 0u64;
932 let mut logs = Vec::new();
933 for (case_index, case) in self.gate_cases[gate_index].iter().enumerate() {
934 let gate_remaining =
935 Duration::from_secs(gate.timeout_secs).saturating_sub(started.elapsed());
936 let overall_remaining = Duration::from_secs(self.spec.max_wall_secs)
937 .saturating_sub(self.evaluation_elapsed + overall_started.elapsed());
938 let reason = if cancel.is_cancelled() {
939 Some("cancelled")
940 } else if overall_remaining.is_zero() {
941 Some("aggregate_evaluation_deadline")
942 } else if gate_remaining.is_zero() {
943 Some("gate_timeout")
944 } else {
945 None
946 };
947 if let Some(reason) = reason {
948 stop_reason = Some(reason.to_string());
949 failure.get_or_insert_with(|| reason.to_string());
950 break;
951 }
952 let remaining = gate_remaining.min(overall_remaining);
953 let scratch = owned
954 .path()
955 .join(format!("scratch-{gate_index}-{case_index}"));
956 fs::create_dir(&scratch).map_err(|error| error.to_string())?;
957 let program = &gate.candidate_argv[0];
958 let args = vec![
959 source
960 .join(&gate.candidate_argv[1])
961 .to_string_lossy()
962 .into_owned(),
963 ];
964 let timeout = remaining.min(Duration::from_secs(8));
965 let env = isolated_command(&source, &scratch, program, args, timeout)?;
966 let log_name = format!(
967 "{id}-{}-g{gate_index}-c{case_index}",
968 if replay { "replay" } else { "evaluation" }
969 );
970 let stdout = self.root.join(format!("{log_name}.stdout.log"));
971 let stderr = self.root.join(format!("{log_name}.stderr.log"));
972 let input = serde_json::to_vec(&case.input).map_err(|error| error.to_string())?;
973 let run = run_isolated(&env, &input, &stdout, &stderr, timeout, Some(cancel))?;
974 observed_count += 1;
975 test_count += 1;
976 let actual = serde_json::from_str::<Value>(run.stdout.trim());
977 let passed = run.exit_code == Some(0)
978 && run.stop_reason.is_none()
979 && actual
980 .as_ref()
981 .is_ok_and(|value| same_json(value, &case.expected));
982 if passed {
983 passed_count += 1;
984 } else {
985 failure.get_or_insert_with(|| {
986 format!("gate {gate_index} case {} failed", case_index + 1)
987 });
988 if !gate.holdout && feedback.len() < 2400 {
989 feedback.push_str(&format!(
990 "case {} input={} expected={} actual={} exit={:?} stop={:?} stderr={}\n",
991 case_index + 1, case.input, case.expected,
992 actual.unwrap_or_else(|_| Value::String(run.stdout.clone())),
993 run.exit_code, run.stop_reason,
994 run.stderr.chars().take(200).collect::<String>()
995 ).chars().take(2400 - feedback.len()).collect::<String>());
996 }
997 }
998 logs.push(json!({
999 "case": case_index + 1, "stdout": stdout, "stderr": stderr,
1000 "sandbox_argv": env.command,
1001 "exit_code": run.exit_code, "stop_reason": run.stop_reason,
1002 "wall_ms": run.wall_ms, "passed": passed
1003 }));
1004 if run.stop_reason.is_some() {
1005 stop_reason = Some(match run.stop_reason.as_deref() {
1006 Some("timeout")
1007 if self.evaluation_elapsed + overall_started.elapsed()
1008 >= Duration::from_secs(self.spec.max_wall_secs) =>
1009 {
1010 "aggregate_evaluation_deadline".to_string()
1011 }
1012 Some("timeout")
1013 if started.elapsed() >= Duration::from_secs(gate.timeout_secs) =>
1014 {
1015 "gate_timeout".to_string()
1016 }
1017 Some("timeout") => "case_timeout".to_string(),
1018 Some(reason) => reason.to_string(),
1019 None => unreachable!(),
1020 });
1021 break;
1022 }
1023 }
1024 let gate_pass = observed_count == self.gate_cases[gate_index].len() as u64
1025 && passed_count == observed_count
1026 && passed_count >= gate.min_tests;
1027 receipts.push(json!({
1028 "candidate_argv": gate.candidate_argv,
1029 "cases_sha256": self.case_hashes[gate_index],
1030 "holdout": gate.holdout,
1031 "test_count": observed_count,
1032 "passed_count": passed_count,
1033 "min_tests": gate.min_tests,
1034 "status": if gate_pass { "PASS" } else { "FAIL" },
1035 "logs": logs
1036 }));
1037 if !gate_pass {
1038 if failure.is_none() {
1039 failure = Some(format!(
1040 "gate {gate_index} did not execute all required cases"
1041 ));
1042 }
1043 break;
1044 }
1045 }
1046 Ok(GateExecution {
1047 receipts,
1048 test_count,
1049 failure,
1050 feedback,
1051 stop_reason,
1052 })
1053 }
1054 }
1055
1055 lines RUST