interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
interplane-mv / adapters / aien / src / fix_the_test.rs
| 1 | //! Harness side of the fix-the-test slice (VAC M3b): prepare a task workspace from the fixture, |
| 2 | //! run the task's test command, and build the retained records the provenance verifier checks |
| 3 | //! (`vac-task`, `vac-source-pin`, `vac-test-run/1`). Specification: provenance/BINDING.md. |
| 4 | //! |
| 5 | //! These records are HARNESS evidence. The AIEN daemon only writes the file; it does not run the |
| 6 | //! tests, so a test run is not a daemon effect and the records are unsigned exports. Nothing here |
| 7 | //! grants, approves or decides anything. |
| 8 | use crate::provenance_export::sha256_hex; |
| 9 | use serde_json::{json, Value}; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::process::Command; |
| 12 | |
| 13 | /// The file the scripted proposal replaces. |
| 14 | pub const TARGET: &str = "src/clamp.c"; |
| 15 | |
| 16 | /// A task workspace under git, before the fix. |
| 17 | #[derive(Debug, Clone)] |
| 18 | pub struct Prepared { |
| 19 | pub ws: PathBuf, |
| 20 | pub task_id: String, |
| 21 | /// The one file the task allows to change. |
| 22 | pub target: String, |
| 23 | /// Fixture name recorded in the source pin. |
| 24 | pub repo: String, |
| 25 | pub argv: Vec<String>, |
| 26 | /// Commit of the buggy tree. |
| 27 | pub commit: String, |
| 28 | /// SHA-256 of the target before the change (what the grant's `prior_sha256` must equal). |
| 29 | pub target_blob_sha256: String, |
| 30 | /// The corrected whole file the scripted proposal writes (empty when the change comes from |
| 31 | /// elsewhere, as in the M5 slice). |
| 32 | pub solution: String, |
| 33 | } |
| 34 | |
| 35 | /// What one run of the test command did. |
| 36 | #[derive(Debug, Clone)] |
| 37 | pub struct TestOutcome { |
| 38 | pub exit_code: i32, |
| 39 | pub stdout: Vec<u8>, |
| 40 | pub stderr: Vec<u8>, |
| 41 | pub started_unix_ms: u128, |
| 42 | pub duration_ms: u128, |
| 43 | } |
| 44 | |
| 45 | fn git(ws: &Path, args: &[&str]) -> Result<String, String> { |
| 46 | let out = Command::new("git") |
| 47 | .arg("-C") |
| 48 | .arg(ws) |
| 49 | .args([ |
| 50 | "-c", |
| 51 | "user.name=vac-harness", |
| 52 | "-c", |
| 53 | "user.email=vac-harness@example.invalid", |
| 54 | ]) |
| 55 | .args(["-c", "commit.gpgsign=false"]) |
| 56 | .args(args) |
| 57 | .output() |
| 58 | .map_err(|e| format!("git {args:?}: {e}"))?; |
| 59 | if !out.status.success() { |
| 60 | return Err(format!( |
| 61 | "git {args:?}: {}", |
| 62 | String::from_utf8_lossy(&out.stderr) |
| 63 | )); |
| 64 | } |
| 65 | Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) |
| 66 | } |
| 67 | |
| 68 | fn copy_tree(from: &Path, to: &Path, skip: &[&str]) -> Result<(), String> { |
| 69 | std::fs::create_dir_all(to).map_err(|e| e.to_string())?; |
| 70 | for e in std::fs::read_dir(from).map_err(|e| format!("{}: {e}", from.display()))? { |
| 71 | let e = e.map_err(|e| e.to_string())?; |
| 72 | let name = e.file_name().to_string_lossy().into_owned(); |
| 73 | if skip.contains(&name.as_str()) { |
| 74 | continue; |
| 75 | } |
| 76 | let dst = to.join(&name); |
| 77 | if e.file_type().map_err(|e| e.to_string())?.is_dir() { |
| 78 | copy_tree(&e.path(), &dst, &[])?; |
| 79 | } else { |
| 80 | std::fs::copy(e.path(), &dst).map_err(|e| e.to_string())?; |
| 81 | } |
| 82 | } |
| 83 | Ok(()) |
| 84 | } |
| 85 | |
| 86 | /// `task_id: x`, `test_command: a b c` and `target_file: p` lines of `TASK.md`. `target_file` is the |
| 87 | /// one file the task allows the agent to change; it goes into the task record as `target_path`. |
| 88 | fn parse_task(md: &str) -> Result<(String, Vec<String>, String), String> { |
| 89 | let field = |k: &str| { |
| 90 | md.lines() |
| 91 | .find_map(|l| l.strip_prefix(k).map(|v| v.trim().to_string())) |
| 92 | .filter(|v| !v.is_empty()) |
| 93 | .ok_or_else(|| format!("TASK.md has no {k}")) |
| 94 | }; |
| 95 | let argv: Vec<String> = field("test_command:")? |
| 96 | .split_whitespace() |
| 97 | .map(str::to_string) |
| 98 | .collect(); |
| 99 | Ok((field("task_id:")?, argv, field("target_file:")?)) |
| 100 | } |
| 101 | |
| 102 | /// Copy `fixture` (without `solution/` and `build/`) into `ws`, `git init` and commit it. |
| 103 | pub fn prepare(fixture: &Path, ws: &Path) -> Result<Prepared, String> { |
| 104 | let solution = std::fs::read_to_string(fixture.join("solution/clamp.c")) |
| 105 | .map_err(|e| format!("solution/clamp.c: {e}"))?; |
| 106 | let mut p = prepare_task(fixture, ws, TARGET, "fix_the_test")?; |
| 107 | p.solution = solution; |
| 108 | Ok(p) |
| 109 | } |
| 110 | |
| 111 | /// Copy `fixture` (without `solution/`, `build/` and `target/`) into `ws`, `git init` and commit |
| 112 | /// it. The proposal will write `allowed`: a task that allows a different file is refused here, |
| 113 | /// before any proposal reaches the daemon. |
| 114 | pub fn prepare_task( |
| 115 | fixture: &Path, |
| 116 | ws: &Path, |
| 117 | allowed: &str, |
| 118 | repo: &str, |
| 119 | ) -> Result<Prepared, String> { |
| 120 | let (task_id, argv, target) = parse_task( |
| 121 | &std::fs::read_to_string(fixture.join("TASK.md")).map_err(|e| format!("TASK.md: {e}"))?, |
| 122 | )?; |
| 123 | if target != allowed { |
| 124 | return Err(format!( |
| 125 | "TASK.md target_file {target} is not the proposal target {allowed}: refused" |
| 126 | )); |
| 127 | } |
| 128 | copy_tree(fixture, ws, &["solution", "build", "target"])?; |
| 129 | git(ws, &["init", "-q"])?; |
| 130 | git(ws, &["add", "-A"])?; |
| 131 | git(ws, &["commit", "-q", "-m", "task start: failing test"])?; |
| 132 | let commit = git(ws, &["rev-parse", "HEAD"])?; |
| 133 | let before = std::fs::read(ws.join(&target)).map_err(|e| e.to_string())?; |
| 134 | Ok(Prepared { |
| 135 | ws: ws.to_path_buf(), |
| 136 | task_id, |
| 137 | target, |
| 138 | repo: repo.to_string(), |
| 139 | argv, |
| 140 | commit, |
| 141 | target_blob_sha256: sha256_hex(&before), |
| 142 | solution: String::new(), |
| 143 | }) |
| 144 | } |
| 145 | |
| 146 | /// Run the task's test command in the workspace and keep exactly what it printed. |
| 147 | pub fn run_tests(p: &Prepared) -> Result<TestOutcome, String> { |
| 148 | let started = std::time::SystemTime::now(); |
| 149 | let t0 = std::time::Instant::now(); |
| 150 | let out = Command::new(&p.argv[0]) |
| 151 | .args(&p.argv[1..]) |
| 152 | .current_dir(&p.ws) |
| 153 | .output() |
| 154 | .map_err(|e| format!("{:?}: {e}", p.argv))?; |
| 155 | Ok(TestOutcome { |
| 156 | exit_code: out.status.code().unwrap_or(-1), |
| 157 | stdout: out.stdout, |
| 158 | stderr: out.stderr, |
| 159 | started_unix_ms: started |
| 160 | .duration_since(std::time::UNIX_EPOCH) |
| 161 | .map(|d| d.as_millis()) |
| 162 | .unwrap_or(0), |
| 163 | duration_ms: t0.elapsed().as_millis(), |
| 164 | }) |
| 165 | } |
| 166 | |
| 167 | /// The records of one finished fix-the-test run. |
| 168 | #[derive(Debug, Clone)] |
| 169 | pub struct TestRunEvidence { |
| 170 | pub task: Value, |
| 171 | pub source_pin: Value, |
| 172 | pub test_run: Value, |
| 173 | pub stdout: Vec<u8>, |
| 174 | pub stderr: Vec<u8>, |
| 175 | pub task_id: String, |
| 176 | /// The test exit codes the harness saw. |
| 177 | pub exit_before: i32, |
| 178 | pub exit_after: i32, |
| 179 | pub tree_commit_after: String, |
| 180 | } |
| 181 | |
| 182 | /// Commit the fixed tree and build the three records. `before` ran before the proposal, `after` |
| 183 | /// after the daemon's ack; `blob_after` is the digest of the file as the test saw it. |
| 184 | pub fn evidence( |
| 185 | p: &Prepared, |
| 186 | before: &TestOutcome, |
| 187 | after: &TestOutcome, |
| 188 | ) -> Result<TestRunEvidence, String> { |
| 189 | git(&p.ws, &["add", "-A"])?; |
| 190 | git( |
| 191 | &p.ws, |
| 192 | &[ |
| 193 | "commit", |
| 194 | "-q", |
| 195 | "-m", |
| 196 | "scripted fix applied through the daemon ledger", |
| 197 | ], |
| 198 | )?; |
| 199 | let tree_commit_after = git(&p.ws, &["rev-parse", "HEAD"])?; |
| 200 | let blob_after = sha256_hex(&std::fs::read(p.ws.join(&p.target)).map_err(|e| e.to_string())?); |
| 201 | let task = json!({"kind": "vac-task", "task_id": p.task_id, "repo_commit": p.commit, |
| 202 | "test_cmd": p.argv, "target_path": p.target}); |
| 203 | let source_pin = json!({"kind": "vac-source-pin", "repo": p.repo, "commit": p.commit, |
| 204 | "target_path": p.target, "target_blob_sha256": p.target_blob_sha256}); |
| 205 | let test_run = json!({"kind": "vac-test-run", "v": 1, "task_id": p.task_id, "argv": p.argv, |
| 206 | "cwd_rel": ".", "exit_code": after.exit_code, "test_exit_before": before.exit_code, |
| 207 | "stdout_sha256": sha256_hex(&after.stdout), "stderr_sha256": sha256_hex(&after.stderr), |
| 208 | "started_unix_ms": after.started_unix_ms as u64, "duration_ms": after.duration_ms as u64, |
| 209 | "tree_commit_after": tree_commit_after, "target_blob_sha256_after": blob_after, |
| 210 | "before": {"stdout_sha256": sha256_hex(&before.stdout), "stderr_sha256": sha256_hex(&before.stderr)}}); |
| 211 | Ok(TestRunEvidence { |
| 212 | task, |
| 213 | source_pin, |
| 214 | test_run, |
| 215 | stdout: after.stdout.clone(), |
| 216 | stderr: after.stderr.clone(), |
| 217 | task_id: p.task_id.clone(), |
| 218 | exit_before: before.exit_code, |
| 219 | exit_after: after.exit_code, |
| 220 | tree_commit_after, |
| 221 | }) |
| 222 | } |
| 223 | |
| 224 | /// The `daemon` block of a harness-written row receipt, with no absolute paths: `log` and `home` |
| 225 | /// are relative to the row's root, and `aien_bin` is the file name only (the binary's digest is |
| 226 | /// recorded in the exported records). The daemon's own records are digest-bound and are never |
| 227 | /// rewritten; only this harness-side block is redacted. |
| 228 | pub fn receipt_daemon( |
| 229 | root: &Path, |
| 230 | log: &Path, |
| 231 | home: &Path, |
| 232 | start_ms: u128, |
| 233 | aien_bin: Option<&str>, |
| 234 | ) -> Value { |
| 235 | let rel = |p: &Path| -> String { |
| 236 | match p.strip_prefix(root) { |
| 237 | Ok(r) => r.display().to_string(), |
| 238 | Err(_) => p |
| 239 | .file_name() |
| 240 | .map(|n| n.to_string_lossy().into_owned()) |
| 241 | .unwrap_or_default(), |
| 242 | } |
| 243 | }; |
| 244 | json!({"log": rel(log), "home": rel(home), "start_ms": start_ms, |
| 245 | "aien_bin": aien_bin.map(|b| Path::new(b).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())}) |
| 246 | } |
| 247 | |
| 248 | #[cfg(test)] |
| 249 | mod tests { |
| 250 | use super::*; |
| 251 | |
| 252 | #[test] |
| 253 | fn receipt_daemon_block_has_no_absolute_paths() { |
| 254 | let root = Path::new("/home/someone/out/rows/slice1"); |
| 255 | let v = receipt_daemon( |
| 256 | root, |
| 257 | &root.join("daemon.log"), |
| 258 | &root.join("compose"), |
| 259 | 7, |
| 260 | Some("/home/someone/bin/aien-cli"), |
| 261 | ); |
| 262 | assert_eq!(v["log"], "daemon.log"); |
| 263 | assert_eq!(v["home"], "compose"); |
| 264 | assert_eq!(v["aien_bin"], "aien-cli"); |
| 265 | assert_eq!(v["start_ms"], 7); |
| 266 | // A path outside the root is reduced to its file name, never kept absolute. |
| 267 | let o = receipt_daemon(root, Path::new("/var/x/d.log"), root, 0, None); |
| 268 | assert_eq!(o["log"], "d.log"); |
| 269 | assert!(!o.to_string().contains("/home/") && !o.to_string().contains("/var/")); |
| 270 | assert!(o["aien_bin"].is_null()); |
| 271 | } |
| 272 | |
| 273 | fn fixture() -> PathBuf { |
| 274 | Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/fix_the_test") |
| 275 | } |
| 276 | |
| 277 | #[test] |
| 278 | fn task_fields_parse() { |
| 279 | let (id, argv, target) = |
| 280 | parse_task("# T\n\ntask_id: a/b-1\ntest_command: make test\ntarget_file: src/x.c\n") |
| 281 | .unwrap(); |
| 282 | assert_eq!( |
| 283 | (id.as_str(), argv, target.as_str()), |
| 284 | ("a/b-1", vec!["make".into(), "test".into()], "src/x.c") |
| 285 | ); |
| 286 | assert!(parse_task("task_id: x\n").is_err()); |
| 287 | // No target_file: the task does not say which file may change, so it is refused. |
| 288 | assert!(parse_task("task_id: x\ntest_command: make test\n").is_err()); |
| 289 | } |
| 290 | |
| 291 | #[test] |
| 292 | fn fixture_fails_before_and_passes_after_the_solution() { |
| 293 | let d = tempfile::tempdir().unwrap(); |
| 294 | let p = prepare(&fixture(), &d.path().join("ws")).unwrap(); |
| 295 | assert!( |
| 296 | !p.ws.join("solution").exists(), |
| 297 | "solution stays out of the workspace" |
| 298 | ); |
| 299 | let before = run_tests(&p).unwrap(); |
| 300 | assert_ne!( |
| 301 | before.exit_code, |
| 302 | 0, |
| 303 | "{}", |
| 304 | String::from_utf8_lossy(&before.stdout) |
| 305 | ); |
| 306 | std::fs::write(p.ws.join(TARGET), &p.solution).unwrap(); |
| 307 | let after = run_tests(&p).unwrap(); |
| 308 | assert_eq!( |
| 309 | after.exit_code, |
| 310 | 0, |
| 311 | "{}", |
| 312 | String::from_utf8_lossy(&after.stdout) |
| 313 | ); |
| 314 | let ev = evidence(&p, &before, &after).unwrap(); |
| 315 | assert_eq!(ev.test_run["exit_code"], 0); |
| 316 | assert_eq!( |
| 317 | ev.source_pin["target_blob_sha256"], |
| 318 | json!(p.target_blob_sha256) |
| 319 | ); |
| 320 | assert_eq!( |
| 321 | ev.test_run["target_blob_sha256_after"], |
| 322 | json!(sha256_hex(p.solution.as_bytes())) |
| 323 | ); |
| 324 | assert_ne!(ev.tree_commit_after, p.commit); |
| 325 | } |
| 326 | |
| 327 | #[test] |
| 328 | fn no_build_output_is_tracked() { |
| 329 | let d = tempfile::tempdir().unwrap(); |
| 330 | let p = prepare(&fixture(), &d.path().join("ws")).unwrap(); |
| 331 | run_tests(&p).unwrap(); |
| 332 | let tracked = git(&p.ws, &["ls-files"]).unwrap(); |
| 333 | assert!(!tracked.contains("build/"), "{tracked}"); |
| 334 | } |
| 335 | } |