Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / infra / agents / runner / src / tests.rs
tests.rs938 lines · 33.0 KiBRaw
| 1 | //! Tests for agent-runner: confinement, edit counts, truncation, timeout + |
| 2 | //! process-group kill, build-semaphore serialization, and the full |
| 3 | //! prepare -> write -> diff -> commit -> bundle flow against a temp bare |
| 4 | //! "mirror" repo. |
| 5 | |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | use std::sync::Arc; |
| 8 | |
| 9 | use super::*; |
| 10 | use proto::{EditRequest, ExecKind, ExecRequest, ReadRequest, ResumeSpec, WriteRequest}; |
| 11 | |
| 12 | fn test_state(slots_dir: &Path, mirror: &Path, num_slots: u32) -> Arc<AppState> { |
| 13 | Arc::new(AppState::new( |
| 14 | slots_dir.to_path_buf(), |
| 15 | mirror.to_path_buf(), |
| 16 | num_slots, |
| 17 | )) |
| 18 | } |
| 19 | |
| 20 | fn make_slot_root() -> tempfile::TempDir { |
| 21 | tempfile::tempdir().expect("tempdir") |
| 22 | } |
| 23 | |
| 24 | fn init_slot_root(dir: &tempfile::TempDir, slot: u32) -> PathBuf { |
| 25 | let root = dir.path().join(format!("slot-{slot}")); |
| 26 | std::fs::create_dir_all(&root).unwrap(); |
| 27 | root |
| 28 | } |
| 29 | |
| 30 | // --------------------------------------------------------------------------- |
| 31 | // Path confinement |
| 32 | // --------------------------------------------------------------------------- |
| 33 | |
| 34 | #[test] |
| 35 | fn confinement_rejects_absolute_paths() { |
| 36 | let dir = make_slot_root(); |
| 37 | let root = init_slot_root(&dir, 0); |
| 38 | assert!(resolve_in_slot(&root, "/etc/passwd").is_err()); |
| 39 | assert!(resolve_in_slot(&root, "/builds/slots/slot-0/x").is_err()); |
| 40 | } |
| 41 | |
| 42 | #[test] |
| 43 | fn confinement_rejects_dotdot_escapes() { |
| 44 | let dir = make_slot_root(); |
| 45 | let root = init_slot_root(&dir, 0); |
| 46 | assert!(resolve_in_slot(&root, "../other").is_err()); |
| 47 | assert!(resolve_in_slot(&root, "a/../../..").is_err()); |
| 48 | assert!(resolve_in_slot(&root, "a/b/../../../../etc").is_err()); |
| 49 | // `..` that stays inside is fine. |
| 50 | let ok = resolve_in_slot(&root, "a/../b").expect("a/../b stays inside"); |
| 51 | assert_eq!(ok, root.join("b")); |
| 52 | } |
| 53 | |
| 54 | #[test] |
| 55 | fn confinement_rejects_git_dir() { |
| 56 | let dir = make_slot_root(); |
| 57 | let root = init_slot_root(&dir, 0); |
| 58 | assert!(resolve_in_slot(&root, ".git/config").is_err()); |
| 59 | assert!(resolve_in_slot(&root, ".git").is_err()); |
| 60 | assert!(resolve_in_slot(&root, "a/.git/hooks").is_ok()); |
| 61 | } |
| 62 | |
| 63 | #[test] |
| 64 | fn confinement_rejects_empty_and_nul() { |
| 65 | let dir = make_slot_root(); |
| 66 | let root = init_slot_root(&dir, 0); |
| 67 | assert!(resolve_in_slot(&root, "").is_err()); |
| 68 | assert!(resolve_in_slot(&root, "a\0b").is_err()); |
| 69 | } |
| 70 | |
| 71 | #[cfg(unix)] |
| 72 | #[test] |
| 73 | fn confinement_rejects_symlink_escape() { |
| 74 | use std::os::unix::fs::symlink; |
| 75 | let dir = make_slot_root(); |
| 76 | let root = init_slot_root(&dir, 0); |
| 77 | let outside = dir.path().join("outside"); |
| 78 | std::fs::create_dir_all(&outside).unwrap(); |
| 79 | std::fs::write(outside.join("secret.txt"), "secret").unwrap(); |
| 80 | // Symlink inside the slot pointing outside. |
| 81 | symlink(&outside, root.join("link")).unwrap(); |
| 82 | // Direct traversal through the symlink. |
| 83 | assert!(resolve_in_slot(&root, "link/secret.txt").is_err()); |
| 84 | // A new file created through a symlinked directory would land outside. |
| 85 | assert!(resolve_in_slot(&root, "link/newfile.txt").is_err()); |
| 86 | // And a symlink directly at the requested path. |
| 87 | symlink(outside.join("secret.txt"), root.join("evil")).unwrap(); |
| 88 | assert!(resolve_in_slot(&root, "evil").is_err()); |
| 89 | // Benign symlink staying inside is allowed. |
| 90 | std::fs::create_dir_all(root.join("real")).unwrap(); |
| 91 | std::fs::write(root.join("real/ok.txt"), "ok").unwrap(); |
| 92 | symlink(root.join("real"), root.join("good")).unwrap(); |
| 93 | assert!(resolve_in_slot(&root, "good/ok.txt").is_ok()); |
| 94 | } |
| 95 | |
| 96 | // --------------------------------------------------------------------------- |
| 97 | // Branch validation |
| 98 | // --------------------------------------------------------------------------- |
| 99 | |
| 100 | #[test] |
| 101 | fn branch_validation() { |
| 102 | assert!(validate_branch("agent/foo").is_ok()); |
| 103 | assert!(validate_branch("agent/foo-bar_baz/qux").is_ok()); |
| 104 | assert!(validate_branch("main").is_err()); |
| 105 | assert!(validate_branch("agent/").is_err()); |
| 106 | assert!(validate_branch("agent/../x").is_err()); |
| 107 | assert!(validate_branch("agent/a..b").is_err()); |
| 108 | assert!(validate_branch("agent/a b").is_err()); |
| 109 | assert!(validate_branch("agent/.hidden").is_err()); |
| 110 | assert!(validate_branch("agent/a.lock").is_err()); |
| 111 | assert!(validate_branch("agent/a:b").is_err()); |
| 112 | } |
| 113 | |
| 114 | // --------------------------------------------------------------------------- |
| 115 | // Edit match counts |
| 116 | // --------------------------------------------------------------------------- |
| 117 | |
| 118 | #[test] |
| 119 | fn edit_requires_exactly_one_match() { |
| 120 | assert_eq!( |
| 121 | apply_edit("aaa bbb", "bbb", "ccc").unwrap(), |
| 122 | "aaa ccc".to_string() |
| 123 | ); |
| 124 | assert!(apply_edit("aaa", "zzz", "ccc").is_err()); // zero matches |
| 125 | assert!(apply_edit("x x x", "x", "y").is_err()); // N matches |
| 126 | assert!(apply_edit("aaa", "", "ccc").is_err()); // empty old |
| 127 | } |
| 128 | |
| 129 | // --------------------------------------------------------------------------- |
| 130 | // Output truncation |
| 131 | // --------------------------------------------------------------------------- |
| 132 | |
| 133 | #[test] |
| 134 | fn truncate_bytes_keeps_head_and_tail() { |
| 135 | let cap = 64usize; |
| 136 | let data: Vec<u8> = (0..200u32).map(|i| b'a' + (i % 26) as u8).collect(); |
| 137 | let (s, truncated) = truncate_bytes(&data, cap); |
| 138 | assert!(truncated); |
| 139 | assert!(s.contains("truncated")); |
| 140 | // Head and tail survive. |
| 141 | assert!(s.starts_with("abcdef")); |
| 142 | let tail: Vec<u8> = data[data.len() - cap / 2..].to_vec(); |
| 143 | assert!(s.ends_with(std::str::from_utf8(&tail).unwrap())); |
| 144 | let (s2, t2) = truncate_bytes(b"small", cap); |
| 145 | assert!(!t2); |
| 146 | assert_eq!(s2, "small"); |
| 147 | } |
| 148 | |
| 149 | // --------------------------------------------------------------------------- |
| 150 | // Exec helpers: need a prepared slot root dir (plain dir, not git). |
| 151 | // --------------------------------------------------------------------------- |
| 152 | |
| 153 | fn exec_state(dir: &tempfile::TempDir, num_slots: u32) -> Arc<AppState> { |
| 154 | // Mirror unused for exec tests; point at the temp dir. |
| 155 | test_state(dir.path(), dir.path(), num_slots) |
| 156 | } |
| 157 | |
| 158 | #[tokio::test] |
| 159 | async fn exec_captures_output_and_exit_code() { |
| 160 | let dir = make_slot_root(); |
| 161 | let state = exec_state(&dir, 2); |
| 162 | init_slot_root(&dir, 0); |
| 163 | let resp = exec_in_slot( |
| 164 | &state, |
| 165 | 0, |
| 166 | &ExecRequest { |
| 167 | command: "echo hello-out; echo hello-err >&2; exit 3".to_string(), |
| 168 | kind: ExecKind::Shell, |
| 169 | timeout_secs: 30, |
| 170 | }, |
| 171 | ) |
| 172 | .await |
| 173 | .unwrap(); |
| 174 | assert_eq!(resp.exit_code, Some(3)); |
| 175 | assert!(resp.stdout.contains("hello-out")); |
| 176 | assert!(resp.stderr.contains("hello-err")); |
| 177 | assert!(!resp.timed_out && !resp.killed && !resp.truncated); |
| 178 | } |
| 179 | |
| 180 | #[tokio::test] |
| 181 | async fn exec_truncates_large_output() { |
| 182 | let dir = make_slot_root(); |
| 183 | let state = exec_state(&dir, 2); |
| 184 | init_slot_root(&dir, 0); |
| 185 | let resp = exec_in_slot( |
| 186 | &state, |
| 187 | 0, |
| 188 | &ExecRequest { |
| 189 | command: "yes OUT | head -c 200000".to_string(), |
| 190 | kind: ExecKind::Shell, |
| 191 | timeout_secs: 30, |
| 192 | }, |
| 193 | ) |
| 194 | .await |
| 195 | .unwrap(); |
| 196 | assert!(resp.truncated, "expected truncated output"); |
| 197 | assert!(resp.stdout.len() < 200_000); |
| 198 | } |
| 199 | |
| 200 | #[tokio::test] |
| 201 | async fn exec_timeout_kills_whole_process_group() { |
| 202 | let dir = make_slot_root(); |
| 203 | let state = exec_state(&dir, 2); |
| 204 | let root = init_slot_root(&dir, 0); |
| 205 | let heartbeat = dir.path().join("heartbeat.log"); |
| 206 | // A background grandchild appends heartbeats forever; the foreground |
| 207 | // sleep keeps the leader alive past the 2s timeout. If killpg kills the |
| 208 | // whole group, heartbeats stop the moment exec returns; if only the |
| 209 | // leader died, they keep growing. |
| 210 | let resp = exec_in_slot( |
| 211 | &state, |
| 212 | 0, |
| 213 | &ExecRequest { |
| 214 | command: format!( |
| 215 | "(while true; do date +%s >> {}; sleep 0.2; done) & sleep 30", |
| 216 | heartbeat.display() |
| 217 | ), |
| 218 | kind: ExecKind::Shell, |
| 219 | timeout_secs: 2, |
| 220 | }, |
| 221 | ) |
| 222 | .await |
| 223 | .unwrap(); |
| 224 | assert!(resp.timed_out, "expected timed_out"); |
| 225 | assert_eq!(resp.exit_code, None); |
| 226 | assert!(root.exists()); |
| 227 | // The whole process group must die: after exec returns, the heartbeat |
| 228 | // file stops growing. A grandchild that survived the killpg would keep |
| 229 | // appending (it loops forever with no exit condition). |
| 230 | let size_after = std::fs::metadata(&heartbeat).unwrap().len(); |
| 231 | tokio::time::sleep(Duration::from_secs(2)).await; |
| 232 | let size_later = std::fs::metadata(&heartbeat).unwrap().len(); |
| 233 | assert_eq!( |
| 234 | size_after, size_later, |
| 235 | "background grandchild survived the process-group kill \ |
| 236 | (heartbeat grew from {size_after} to {size_later} bytes)" |
| 237 | ); |
| 238 | } |
| 239 | |
| 240 | #[tokio::test] |
| 241 | async fn exec_cancel_kills_running_shell() { |
| 242 | let dir = make_slot_root(); |
| 243 | let state = exec_state(&dir, 2); |
| 244 | init_slot_root(&dir, 0); |
| 245 | let state2 = state.clone(); |
| 246 | let handle = tokio::spawn(async move { |
| 247 | exec_in_slot( |
| 248 | &state2, |
| 249 | 0, |
| 250 | &ExecRequest { |
| 251 | command: "sleep 60".to_string(), |
| 252 | kind: ExecKind::Shell, |
| 253 | timeout_secs: 120, |
| 254 | }, |
| 255 | ) |
| 256 | .await |
| 257 | .unwrap() |
| 258 | }); |
| 259 | // Wait until the exec registers itself, then cancel. |
| 260 | let mut saw_running = false; |
| 261 | for _ in 0..100 { |
| 262 | { |
| 263 | if state.running.lock().await.contains_key(&0) { |
| 264 | saw_running = true; |
| 265 | break; |
| 266 | } |
| 267 | } |
| 268 | tokio::time::sleep(Duration::from_millis(50)).await; |
| 269 | } |
| 270 | assert!(saw_running, "exec never registered as running"); |
| 271 | assert!(cancel_slot(&state, 0).await); |
| 272 | let resp = handle.await.unwrap(); |
| 273 | assert!(resp.killed, "expected killed, got {resp:?}"); |
| 274 | assert_eq!(resp.exit_code, None); |
| 275 | assert!(!cancel_slot(&state, 0).await, "nothing left to cancel"); |
| 276 | } |
| 277 | |
| 278 | #[tokio::test] |
| 279 | async fn exec_build_serializes_and_reports_queue_time() { |
| 280 | let dir = make_slot_root(); |
| 281 | let state = exec_state(&dir, 2); |
| 282 | init_slot_root(&dir, 0); |
| 283 | init_slot_root(&dir, 1); |
| 284 | let mk = |cmd: &str| ExecRequest { |
| 285 | command: cmd.to_string(), |
| 286 | kind: ExecKind::Build, |
| 287 | timeout_secs: 60, |
| 288 | }; |
| 289 | let s1 = state.clone(); |
| 290 | let s2 = state.clone(); |
| 291 | let t0 = Instant::now(); |
| 292 | let req1 = mk("date +%s%N; sleep 3"); |
| 293 | let req2 = mk("date +%s%N"); |
| 294 | let (r1, r2) = tokio::join!( |
| 295 | exec_in_slot(&s1, 0, &req1), |
| 296 | async { |
| 297 | // Start the second build slightly later so it must queue. |
| 298 | tokio::time::sleep(Duration::from_millis(300)).await; |
| 299 | exec_in_slot(&s2, 1, &req2).await.unwrap() |
| 300 | } |
| 301 | ); |
| 302 | let r1 = r1.unwrap(); |
| 303 | assert_eq!(r1.exit_code, Some(0)); |
| 304 | // Serialized: total wall time is at least the first build's sleep. |
| 305 | assert!( |
| 306 | t0.elapsed() >= Duration::from_secs(3), |
| 307 | "builds overlapped: {:?}", |
| 308 | t0.elapsed() |
| 309 | ); |
| 310 | assert!( |
| 311 | r2.queued_ms >= 2000, |
| 312 | "second build should have queued ~3s, got {}ms", |
| 313 | r2.queued_ms |
| 314 | ); |
| 315 | // Health flag clears afterwards. |
| 316 | assert!(!state.build_running.load(Ordering::SeqCst)); |
| 317 | } |
| 318 | |
| 319 | #[tokio::test] |
| 320 | async fn exec_build_kill_endpoint_kills_inflight_build() { |
| 321 | let dir = make_slot_root(); |
| 322 | let state = exec_state(&dir, 2); |
| 323 | init_slot_root(&dir, 0); |
| 324 | let s2 = state.clone(); |
| 325 | let handle = tokio::spawn(async move { |
| 326 | exec_in_slot( |
| 327 | &s2, |
| 328 | 0, |
| 329 | &ExecRequest { |
| 330 | command: "sleep 60".to_string(), |
| 331 | kind: ExecKind::Build, |
| 332 | timeout_secs: 120, |
| 333 | }, |
| 334 | ) |
| 335 | .await |
| 336 | .unwrap() |
| 337 | }); |
| 338 | for _ in 0..100 { |
| 339 | if state.build_running.load(Ordering::SeqCst) { |
| 340 | break; |
| 341 | } |
| 342 | tokio::time::sleep(Duration::from_millis(50)).await; |
| 343 | } |
| 344 | assert!(state.build_running.load(Ordering::SeqCst)); |
| 345 | assert!(kill_build(&state).await); |
| 346 | let resp = handle.await.unwrap(); |
| 347 | assert!(resp.killed, "expected killed, got {resp:?}"); |
| 348 | assert!(!kill_build(&state).await); |
| 349 | } |
| 350 | |
| 351 | #[tokio::test] |
| 352 | async fn exec_invalid_slot_is_404() { |
| 353 | let dir = make_slot_root(); |
| 354 | let state = exec_state(&dir, 2); |
| 355 | assert!(parse_slot(&state, "2").is_err()); |
| 356 | assert!(parse_slot(&state, "99").is_err()); |
| 357 | assert!(parse_slot(&state, "-1").is_err()); |
| 358 | assert!(parse_slot(&state, "abc").is_err()); |
| 359 | assert_eq!(parse_slot(&state, "1").unwrap(), 1); |
| 360 | } |
| 361 | |
| 362 | // --------------------------------------------------------------------------- |
| 363 | // Full git flow against a temp bare "mirror" repo. |
| 364 | // --------------------------------------------------------------------------- |
| 365 | |
| 366 | fn git(dir: &Path, args: &[&str]) { |
| 367 | let status = std::process::Command::new("git") |
| 368 | .args(args) |
| 369 | .current_dir(dir) |
| 370 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 371 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 372 | .status() |
| 373 | .expect("spawn git"); |
| 374 | assert!(status.success(), "git {args:?} failed in {dir:?}"); |
| 375 | } |
| 376 | |
| 377 | fn git_out(dir: &Path, args: &[&str]) -> String { |
| 378 | let out = std::process::Command::new("git") |
| 379 | .args(args) |
| 380 | .current_dir(dir) |
| 381 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 382 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 383 | .output() |
| 384 | .expect("spawn git"); |
| 385 | assert!(out.status.success(), "git {args:?} failed: {out:?}"); |
| 386 | String::from_utf8(out.stdout).unwrap().trim().to_string() |
| 387 | } |
| 388 | |
| 389 | /// Build a temp bare mirror with one commit on `main`, plus a surrounding |
| 390 | /// state with isolated slots/mirror dirs. |
| 391 | struct GitFlow { |
| 392 | _tmp: tempfile::TempDir, |
| 393 | state: Arc<AppState>, |
| 394 | } |
| 395 | |
| 396 | fn setup_git_flow() -> GitFlow { |
| 397 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 398 | let seed = tmp.path().join("seed"); |
| 399 | std::fs::create_dir_all(&seed).unwrap(); |
| 400 | git(&seed, &["init", "-b", "main"]); |
| 401 | git(&seed, &["config", "user.email", "[email protected]"]); |
| 402 | git(&seed, &["config", "user.name", "test"]); |
| 403 | std::fs::write(seed.join("README.md"), "hello\n").unwrap(); |
| 404 | // Tracked .gitignore, like the real repo's: ignored build outputs must |
| 405 | // survive prepare's `git clean -fd` (which keeps ignored files). |
| 406 | std::fs::write(seed.join(".gitignore"), "build/\n").unwrap(); |
| 407 | git(&seed, &["add", "-A"]); |
| 408 | git(&seed, &["commit", "-m", "initial"]); |
| 409 | let mirror = tmp.path().join("mirror.git"); |
| 410 | let status = std::process::Command::new("git") |
| 411 | .args([ |
| 412 | "clone", |
| 413 | "--bare", |
| 414 | seed.to_str().unwrap(), |
| 415 | mirror.to_str().unwrap(), |
| 416 | ]) |
| 417 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 418 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 419 | .status() |
| 420 | .unwrap(); |
| 421 | assert!(status.success()); |
| 422 | let slots = tmp.path().join("slots"); |
| 423 | std::fs::create_dir_all(&slots).unwrap(); |
| 424 | let state = Arc::new(AppState::new(slots, mirror, 2)); |
| 425 | GitFlow { _tmp: tmp, state } |
| 426 | } |
| 427 | |
| 428 | #[tokio::test] |
| 429 | async fn gitflow_prepare_write_diff_commit_bundle() { |
| 430 | let flow = setup_git_flow(); |
| 431 | let state = &flow.state; |
| 432 | |
| 433 | // prepare |
| 434 | let base = prepare_slot(state, 0, "agent/test-flow", None).await.unwrap(); |
| 435 | assert_eq!(base.len(), 40); |
| 436 | // prepare is idempotent |
| 437 | let base2 = prepare_slot(state, 0, "agent/test-flow", None).await.unwrap(); |
| 438 | assert_eq!(base, base2); |
| 439 | // bad branch rejected |
| 440 | assert!(prepare_slot(state, 0, "main", None).await.is_err()); |
| 441 | |
| 442 | // clean -fd keeps ignored build outputs: an ignored build/ file created |
| 443 | // after prepare survives the *next* prepare (warm caches persist). |
| 444 | let slot = slot_root(state, 0); |
| 445 | std::fs::create_dir_all(slot.join("build")).unwrap(); |
| 446 | std::fs::write(slot.join("build/warm.txt"), "warm").unwrap(); |
| 447 | prepare_slot(state, 0, "agent/test-flow", None).await.unwrap(); |
| 448 | assert!( |
| 449 | slot.join("build/warm.txt").exists(), |
| 450 | "ignored build/ output must survive prepare" |
| 451 | ); |
| 452 | |
| 453 | // write + edit + read |
| 454 | write_slot_file( |
| 455 | state, |
| 456 | 0, |
| 457 | &WriteRequest { |
| 458 | path: "notes/todo.txt".to_string(), |
| 459 | content: "line1\nline2 needle\nline3\n".to_string(), |
| 460 | }, |
| 461 | ) |
| 462 | .await |
| 463 | .unwrap(); |
| 464 | super::edit_slot_file( |
| 465 | state, |
| 466 | 0, |
| 467 | &EditRequest { |
| 468 | path: "notes/todo.txt".to_string(), |
| 469 | old: "line2 needle".to_string(), |
| 470 | new: "line2 done".to_string(), |
| 471 | }, |
| 472 | ) |
| 473 | .await |
| 474 | .unwrap(); |
| 475 | let read = super::read_slot_file( |
| 476 | state, |
| 477 | 0, |
| 478 | &ReadRequest { |
| 479 | path: "notes/todo.txt".to_string(), |
| 480 | start_line: None, |
| 481 | max_lines: None, |
| 482 | }, |
| 483 | ) |
| 484 | .await |
| 485 | .unwrap(); |
| 486 | assert!(read.content.contains("line2 done")); |
| 487 | assert_eq!(read.total_lines, 3); |
| 488 | assert!(!read.truncated); |
| 489 | |
| 490 | // zero-match and multi-match edits are 409s. |
| 491 | let e0 = super::edit_slot_file( |
| 492 | state, |
| 493 | 0, |
| 494 | &EditRequest { |
| 495 | path: "notes/todo.txt".to_string(), |
| 496 | old: "nope".to_string(), |
| 497 | new: "x".to_string(), |
| 498 | }, |
| 499 | ) |
| 500 | .await; |
| 501 | assert_eq!(e0.unwrap_err().status, StatusCode::CONFLICT); |
| 502 | std::fs::write(slot.join("multi.txt"), "a a a").unwrap(); |
| 503 | let e1 = super::edit_slot_file( |
| 504 | state, |
| 505 | 0, |
| 506 | &EditRequest { |
| 507 | path: "multi.txt".to_string(), |
| 508 | old: "a".to_string(), |
| 509 | new: "b".to_string(), |
| 510 | }, |
| 511 | ) |
| 512 | .await; |
| 513 | assert_eq!(e1.unwrap_err().status, StatusCode::CONFLICT); |
| 514 | |
| 515 | // read paging |
| 516 | let page = super::read_slot_file( |
| 517 | state, |
| 518 | 0, |
| 519 | &ReadRequest { |
| 520 | path: "notes/todo.txt".to_string(), |
| 521 | start_line: Some(2), |
| 522 | max_lines: Some(1), |
| 523 | }, |
| 524 | ) |
| 525 | .await |
| 526 | .unwrap(); |
| 527 | assert_eq!(page.content, "line2 done"); |
| 528 | assert!(page.truncated); |
| 529 | |
| 530 | // list |
| 531 | let list = super::list_slot_dir( |
| 532 | state, |
| 533 | 0, |
| 534 | &proto::ListRequest { |
| 535 | path: ".".to_string(), |
| 536 | }, |
| 537 | ) |
| 538 | .await |
| 539 | .unwrap(); |
| 540 | assert!(list.entries.iter().any(|e| e == "notes/")); |
| 541 | |
| 542 | // diff includes untracked files (multi.txt is untracked). |
| 543 | let diff = diff_slot(state, 0).await.unwrap(); |
| 544 | assert!(diff.diff.contains("todo.txt"), "diff: {}", diff.diff); |
| 545 | assert!(diff.diff.contains("multi.txt"), "diff: {}", diff.diff); |
| 546 | |
| 547 | // commit refuses empty, succeeds with changes. |
| 548 | std::fs::remove_file(slot.join("multi.txt")).unwrap(); |
| 549 | std::fs::remove_file(slot.join("build/warm.txt")).unwrap(); |
| 550 | let sha = commit_slot( |
| 551 | state, |
| 552 | 0, |
| 553 | &proto::CommitRequest { |
| 554 | message: "agent work".to_string(), |
| 555 | }, |
| 556 | ) |
| 557 | .await |
| 558 | .unwrap(); |
| 559 | assert_eq!(sha.len(), 40); |
| 560 | let empty = commit_slot( |
| 561 | state, |
| 562 | 0, |
| 563 | &proto::CommitRequest { |
| 564 | message: "nothing".to_string(), |
| 565 | }, |
| 566 | ) |
| 567 | .await; |
| 568 | assert_eq!(empty.unwrap_err().status, StatusCode::CONFLICT); |
| 569 | |
| 570 | // Bundle verifies, and it imports into a repo holding the base commit. |
| 571 | // (`base..branch` bundles are thin packs whose prerequisite is the base; |
| 572 | // agentd imports into the mirror, which has it. Verify from the slot, and |
| 573 | // fetch into a clone of the mirror — a fresh empty repo correctly fails |
| 574 | // with "lacks these prerequisite commits".) |
| 575 | let (_branch, bytes) = bundle_slot(state, 0).await.unwrap(); |
| 576 | assert!(!bytes.is_empty()); |
| 577 | let bundle_path = state.slots_dir.join("test.bundle"); |
| 578 | std::fs::write(&bundle_path, &bytes).unwrap(); |
| 579 | let verify = std::process::Command::new("git") |
| 580 | .args(["bundle", "verify", bundle_path.to_str().unwrap()]) |
| 581 | .current_dir(&slot) |
| 582 | .output() |
| 583 | .unwrap(); |
| 584 | assert!( |
| 585 | verify.status.success(), |
| 586 | "git bundle verify failed: {verify:?}" |
| 587 | ); |
| 588 | let clone_dir = tempfile::tempdir().unwrap(); |
| 589 | git( |
| 590 | clone_dir.path(), |
| 591 | &[ |
| 592 | "clone", |
| 593 | state.mirror.to_str().unwrap(), |
| 594 | "imported", |
| 595 | ], |
| 596 | ); |
| 597 | let imported = clone_dir.path().join("imported"); |
| 598 | git( |
| 599 | &imported, |
| 600 | &[ |
| 601 | "fetch", |
| 602 | bundle_path.to_str().unwrap(), |
| 603 | "agent/test-flow:refs/heads/fetched", |
| 604 | ], |
| 605 | ); |
| 606 | let fetched = git_out(&imported, &["rev-parse", "fetched"]); |
| 607 | assert_eq!(fetched, sha); |
| 608 | |
| 609 | // bundle with no commits is 409. |
| 610 | prepare_slot(state, 1, "agent/empty-branch", None).await.unwrap(); |
| 611 | let b2 = bundle_slot(state, 1).await; |
| 612 | assert_eq!(b2.unwrap_err().status, StatusCode::CONFLICT); |
| 613 | } |
| 614 | |
| 615 | #[tokio::test] |
| 616 | async fn search_respects_excludes_and_globs() { |
| 617 | let rg_available = std::process::Command::new("rg") |
| 618 | .arg("--version") |
| 619 | .output() |
| 620 | .map(|o| o.status.success()) |
| 621 | .unwrap_or(false); |
| 622 | if !rg_available { |
| 623 | eprintln!("skipping search test: rg not installed"); |
| 624 | return; |
| 625 | } |
| 626 | let dir = make_slot_root(); |
| 627 | let state = exec_state(&dir, 2); |
| 628 | let root = init_slot_root(&dir, 0); |
| 629 | std::fs::write(root.join("hit.kt"), "needle here\n").unwrap(); |
| 630 | std::fs::create_dir_all(root.join("build")).unwrap(); |
| 631 | std::fs::write(root.join("build/hit.kt"), "needle here\n").unwrap(); |
| 632 | let resp = super::search_slot( |
| 633 | &state, |
| 634 | 0, |
| 635 | &proto::SearchRequest { |
| 636 | pattern: "needle".to_string(), |
| 637 | path: None, |
| 638 | glob: None, |
| 639 | fixed_string: false, |
| 640 | }, |
| 641 | ) |
| 642 | .await |
| 643 | .unwrap(); |
| 644 | assert!(resp.matches.contains("hit.kt:1"), "got: {}", resp.matches); |
| 645 | assert!( |
| 646 | !resp.matches.contains("build/"), |
| 647 | "build/ must be excluded: {}", |
| 648 | resp.matches |
| 649 | ); |
| 650 | // glob filter |
| 651 | let resp2 = super::search_slot( |
| 652 | &state, |
| 653 | 0, |
| 654 | &proto::SearchRequest { |
| 655 | pattern: "needle".to_string(), |
| 656 | path: None, |
| 657 | glob: Some("*.java".to_string()), |
| 658 | fixed_string: false, |
| 659 | }, |
| 660 | ) |
| 661 | .await |
| 662 | .unwrap(); |
| 663 | assert!(!resp2.matches.contains("hit.kt"), "glob must filter: {}", resp2.matches); |
| 664 | // fixed strings: regex chars are literal. |
| 665 | std::fs::write(root.join("re.txt"), "a.c\n").unwrap(); |
| 666 | let resp3 = super::search_slot( |
| 667 | &state, |
| 668 | 0, |
| 669 | &proto::SearchRequest { |
| 670 | pattern: "a.c".to_string(), |
| 671 | path: None, |
| 672 | glob: Some("re.txt".to_string()), |
| 673 | fixed_string: true, |
| 674 | }, |
| 675 | ) |
| 676 | .await |
| 677 | .unwrap(); |
| 678 | assert!(resp3.matches.contains("re.txt"), "got: {}", resp3.matches); |
| 679 | } |
| 680 | |
| 681 | // --------------------------------------------------------------------------- |
| 682 | // Resume: park on one slot, resume on another via refs/agent-wip/N. |
| 683 | // --------------------------------------------------------------------------- |
| 684 | |
| 685 | /// Park the slot's current branch: commit everything as a WIP commit, bundle |
| 686 | /// `base..branch`, and import the bundle into the mirror under |
| 687 | /// `refs/agent-wip/<n>` — the same way agentd stores parked work. Returns |
| 688 | /// `(base_sha, wip_sha)`. |
| 689 | fn park_slot_to_wip_ref(state: &Arc<AppState>, slot: u32, wip_n: u32) -> (String, String) { |
| 690 | let slot_path = slot_root(state, slot); |
| 691 | let base_sha = std::fs::read_to_string(slot_path.join(".git").join(AGENT_BASE_FILE)) |
| 692 | .expect("agent-base recorded") |
| 693 | .trim() |
| 694 | .to_string(); |
| 695 | let branch = git_out(&slot_path, &["branch", "--show-current"]); |
| 696 | git(&slot_path, &["add", "-A"]); |
| 697 | git(&slot_path, &["commit", "-m", "WIP"]); |
| 698 | let wip_sha = git_out(&slot_path, &["rev-parse", "HEAD"]); |
| 699 | // Bundle base..branch the way the runner's bundle route does, then import |
| 700 | // into the mirror under refs/agent-wip/<n> the way agentd does. |
| 701 | let range = format!("{base_sha}..{branch}"); |
| 702 | let bundle_bytes = std::process::Command::new("git") |
| 703 | .args(["bundle", "create", "-", &range]) |
| 704 | .current_dir(&slot_path) |
| 705 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 706 | .env("GIT_CONFIG_SYSTEM", "/dev/null") |
| 707 | .output() |
| 708 | .expect("git bundle create"); |
| 709 | assert!(bundle_bytes.status.success(), "git bundle create failed: {bundle_bytes:?}"); |
| 710 | assert!(!bundle_bytes.stdout.is_empty()); |
| 711 | let bundle_path = state.slots_dir.join(format!("park-{wip_n}.bundle")); |
| 712 | std::fs::write(&bundle_path, &bundle_bytes.stdout).unwrap(); |
| 713 | let wip_ref = format!("refs/agent-wip/{wip_n}"); |
| 714 | let fetch_refspec = format!("+refs/heads/{branch}:{wip_ref}"); |
| 715 | git(&state.mirror, &["fetch", bundle_path.to_str().unwrap(), fetch_refspec.as_str()]); |
| 716 | (base_sha, wip_sha) |
| 717 | } |
| 718 | |
| 719 | fn resume_spec(base_sha: &str, wip_n: u32, wip_sha: &str) -> ResumeSpec { |
| 720 | ResumeSpec { |
| 721 | base_sha: base_sha.to_string(), |
| 722 | wip_ref: Some(format!("refs/agent-wip/{wip_n}")), |
| 723 | wip_sha: Some(wip_sha.to_string()), |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | #[tokio::test] |
| 728 | async fn resume_park_round_trip_on_different_slot() { |
| 729 | let flow = setup_git_flow(); |
| 730 | let state = &flow.state; |
| 731 | |
| 732 | // Prepare slot 0 fresh, then make changes incl. a new untracked file. |
| 733 | let base = prepare_slot(state, 0, "agent/parked", None).await.unwrap(); |
| 734 | let slot0 = slot_root(state, 0); |
| 735 | std::fs::write(slot0.join("README.md"), "hello modified\n").unwrap(); |
| 736 | std::fs::write(slot0.join("brand-new.txt"), "brand new\n").unwrap(); |
| 737 | std::fs::create_dir_all(slot0.join("notes")).unwrap(); |
| 738 | std::fs::write(slot0.join("notes/todo.txt"), "todo one\n").unwrap(); |
| 739 | |
| 740 | // Commit as WIP, bundle, import into the mirror as refs/agent-wip/7. |
| 741 | let (park_base, wip_sha) = park_slot_to_wip_ref(state, 0, 7); |
| 742 | assert_eq!(park_base, base); |
| 743 | |
| 744 | // Resume onto slot 1 under a new branch name. |
| 745 | let spec = resume_spec(&base, 7, &wip_sha); |
| 746 | let resumed = prepare_slot(state, 1, "agent/resumed", Some(&spec)).await.unwrap(); |
| 747 | assert_eq!(resumed, base); |
| 748 | let slot1 = slot_root(state, 1); |
| 749 | |
| 750 | // /diff shows exactly the original changes vs base, including the new file. |
| 751 | let diff = diff_slot(state, 1).await.unwrap(); |
| 752 | assert!(diff.diff.contains("README.md"), "diff: {}", diff.diff); |
| 753 | assert!( |
| 754 | diff.diff.contains("brand-new.txt"), |
| 755 | "untracked file must survive resume: {}", |
| 756 | diff.diff |
| 757 | ); |
| 758 | assert!(diff.diff.contains("notes/todo.txt"), "diff: {}", diff.diff); |
| 759 | assert!(std::fs::read_to_string(slot1.join("brand-new.txt")).unwrap() == "brand new\n"); |
| 760 | |
| 761 | // agent-base records the original base, HEAD is soft-reset onto base. |
| 762 | let recorded = std::fs::read_to_string(slot1.join(".git").join(AGENT_BASE_FILE)) |
| 763 | .unwrap() |
| 764 | .trim() |
| 765 | .to_string(); |
| 766 | assert_eq!(recorded, base); |
| 767 | assert_eq!(git_out(&slot1, &["rev-parse", "HEAD"]), base); |
| 768 | |
| 769 | // Commit + bundle on slot 1 produce a single commit base..branch. |
| 770 | let sha = commit_slot(state, 1, &proto::CommitRequest { message: "resumed work".to_string() }) |
| 771 | .await |
| 772 | .unwrap(); |
| 773 | let count = git_out(&slot1, &["rev-list", "--count", format!("{base}..HEAD").as_str()]); |
| 774 | assert_eq!(count, "1", "expected a single commit on top of base"); |
| 775 | let (_branch, bytes) = bundle_slot(state, 1).await.unwrap(); |
| 776 | assert!(!bytes.is_empty()); |
| 777 | // The re-committed tree matches the parked WIP tree. |
| 778 | let wip_tree = git_out(&slot0, &["rev-parse", format!("{wip_sha}^{{tree}}").as_str()]); |
| 779 | let new_tree = git_out(&slot1, &["rev-parse", format!("{sha}^{{tree}}").as_str()]); |
| 780 | assert_eq!(new_tree, wip_tree); |
| 781 | } |
| 782 | |
| 783 | #[tokio::test] |
| 784 | async fn resume_into_same_slot_clears_leftovers() { |
| 785 | let flow = setup_git_flow(); |
| 786 | let state = &flow.state; |
| 787 | |
| 788 | let base = prepare_slot(state, 0, "agent/parked", None).await.unwrap(); |
| 789 | let slot0 = slot_root(state, 0); |
| 790 | std::fs::write(slot0.join("work.txt"), "parked work\n").unwrap(); |
| 791 | let (park_base, wip_sha) = park_slot_to_wip_ref(state, 0, 3); |
| 792 | assert_eq!(park_base, base); |
| 793 | |
| 794 | // Slot 0 now has leftovers from "another task": an unrelated branch, |
| 795 | // stray untracked files, and uncommitted modifications. |
| 796 | git(&slot0, &["checkout", "-B", "agent/other-task"]); |
| 797 | std::fs::write(slot0.join("leftover.txt"), "stale\n").unwrap(); |
| 798 | std::fs::write(slot0.join("README.md"), "stale modification\n").unwrap(); |
| 799 | |
| 800 | let spec = resume_spec(&base, 3, &wip_sha); |
| 801 | let resumed = prepare_slot(state, 0, "agent/resumed-here", Some(&spec)).await.unwrap(); |
| 802 | assert_eq!(resumed, base); |
| 803 | |
| 804 | // Leftovers are gone, parked work is restored. |
| 805 | assert!(!slot0.join("leftover.txt").exists()); |
| 806 | assert_eq!(std::fs::read_to_string(slot0.join("work.txt")).unwrap(), "parked work\n"); |
| 807 | assert_eq!(std::fs::read_to_string(slot0.join("README.md")).unwrap(), "hello\n"); |
| 808 | assert_eq!(git_out(&slot0, &["rev-parse", "HEAD"]), base); |
| 809 | let diff = diff_slot(state, 0).await.unwrap(); |
| 810 | assert!(diff.diff.contains("work.txt"), "diff: {}", diff.diff); |
| 811 | } |
| 812 | |
| 813 | #[tokio::test] |
| 814 | async fn resume_wip_sha_mismatch_is_409() { |
| 815 | let flow = setup_git_flow(); |
| 816 | let state = &flow.state; |
| 817 | |
| 818 | let base = prepare_slot(state, 0, "agent/parked", None).await.unwrap(); |
| 819 | let slot0 = slot_root(state, 0); |
| 820 | std::fs::write(slot0.join("work.txt"), "parked work\n").unwrap(); |
| 821 | let (_park_base, _wip_sha) = park_slot_to_wip_ref(state, 0, 11); |
| 822 | |
| 823 | // Claim a sha the ref does not resolve to. |
| 824 | let bogus = "dddddddddddddddddddddddddddddddddddddddd"; |
| 825 | let spec = resume_spec(&base, 11, bogus); |
| 826 | let err = prepare_slot(state, 1, "agent/resume-bad", Some(&spec)).await.unwrap_err(); |
| 827 | assert_eq!(err.status, StatusCode::CONFLICT, "mismatch must be 409"); |
| 828 | assert!(err.message.contains("expected wip_sha"), "clear error message, got: {}", err.message); |
| 829 | // Slot must not be left claiming the wrong commit: HEAD is the base, not |
| 830 | // the bogus sha, and no branch tracks the bogus content. |
| 831 | let slot1 = slot_root(state, 1); |
| 832 | assert_ne!(git_out(&slot1, &["rev-parse", "HEAD"]), bogus); |
| 833 | } |
| 834 | |
| 835 | #[tokio::test] |
| 836 | async fn resume_without_wip_checks_out_base_even_after_main_moves() { |
| 837 | let flow = setup_git_flow(); |
| 838 | let state = &flow.state; |
| 839 | |
| 840 | // Record today's base, then move mirror main on. |
| 841 | let base = prepare_slot(state, 0, "agent/first", None).await.unwrap(); |
| 842 | { |
| 843 | let work = tempfile::tempdir().unwrap(); |
| 844 | git(work.path(), &["clone", state.mirror.to_str().unwrap(), "w"]); |
| 845 | let w = work.path().join("w"); |
| 846 | git(&w, &["config", "user.email", "[email protected]"]); |
| 847 | git(&w, &["config", "user.name", "test"]); |
| 848 | git(&w, &["checkout", "main"]); |
| 849 | std::fs::write(w.join("moved-on.txt"), "new main\n").unwrap(); |
| 850 | git(&w, &["add", "-A"]); |
| 851 | git(&w, &["commit", "-m", "main moves on"]); |
| 852 | git(&w, &["push", "origin", "main"]); |
| 853 | } |
| 854 | |
| 855 | let spec = ResumeSpec { base_sha: base.clone(), wip_ref: None, wip_sha: None }; |
| 856 | let resumed = prepare_slot(state, 1, "agent/clean-resume", Some(&spec)).await.unwrap(); |
| 857 | assert_eq!(resumed, base); |
| 858 | let slot1 = slot_root(state, 1); |
| 859 | assert_eq!(git_out(&slot1, &["rev-parse", "HEAD"]), base); |
| 860 | assert!(!slot1.join("moved-on.txt").exists()); |
| 861 | assert_eq!( |
| 862 | std::fs::read_to_string(slot1.join(".git").join(AGENT_BASE_FILE)).unwrap().trim(), |
| 863 | base |
| 864 | ); |
| 865 | // Nothing to commit: clean checkout at base. |
| 866 | let empty = |
| 867 | commit_slot(state, 1, &proto::CommitRequest { message: "nothing".to_string() }).await; |
| 868 | assert_eq!(empty.unwrap_err().status, StatusCode::CONFLICT); |
| 869 | } |
| 870 | |
| 871 | #[tokio::test] |
| 872 | async fn resume_rejects_invalid_ref_and_sha_formats() { |
| 873 | let flow = setup_git_flow(); |
| 874 | let state = &flow.state; |
| 875 | let base = prepare_slot(state, 0, "agent/first", None).await.unwrap(); |
| 876 | |
| 877 | // Bad base_sha. |
| 878 | for bad_base in ["", "xyz", "abc123", "g".repeat(40).as_str()] { |
| 879 | let spec = ResumeSpec { base_sha: bad_base.to_string(), wip_ref: None, wip_sha: None }; |
| 880 | let err = prepare_slot(state, 1, "agent/bad", Some(&spec)).await.unwrap_err(); |
| 881 | assert_eq!(err.status, StatusCode::BAD_REQUEST, "base {bad_base:?}"); |
| 882 | } |
| 883 | // Bad wip_ref shapes. |
| 884 | for bad_ref in [ |
| 885 | "refs/agent-wip/", |
| 886 | "refs/agent-wip/abc", |
| 887 | "refs/agent-wip/1/../2", |
| 888 | "refs/heads/main", |
| 889 | "refs/agent-wip//7", |
| 890 | "agent-wip/7", |
| 891 | ] { |
| 892 | let spec = ResumeSpec { |
| 893 | base_sha: base.clone(), |
| 894 | wip_ref: Some(bad_ref.to_string()), |
| 895 | wip_sha: Some("a".repeat(40)), |
| 896 | }; |
| 897 | let err = prepare_slot(state, 1, "agent/bad", Some(&spec)).await.unwrap_err(); |
| 898 | assert_eq!(err.status, StatusCode::BAD_REQUEST, "ref {bad_ref:?}"); |
| 899 | } |
| 900 | // Bad wip_sha. |
| 901 | let spec = ResumeSpec { |
| 902 | base_sha: base.clone(), |
| 903 | wip_ref: Some("refs/agent-wip/7".to_string()), |
| 904 | wip_sha: Some("not-a-sha".to_string()), |
| 905 | }; |
| 906 | let err = prepare_slot(state, 1, "agent/bad", Some(&spec)).await.unwrap_err(); |
| 907 | assert_eq!(err.status, StatusCode::BAD_REQUEST); |
| 908 | // wip_ref without wip_sha and vice versa. |
| 909 | let spec = ResumeSpec { |
| 910 | base_sha: base.clone(), |
| 911 | wip_ref: Some("refs/agent-wip/7".to_string()), |
| 912 | wip_sha: None, |
| 913 | }; |
| 914 | assert_eq!( |
| 915 | prepare_slot(state, 1, "agent/bad", Some(&spec)).await.unwrap_err().status, |
| 916 | StatusCode::BAD_REQUEST |
| 917 | ); |
| 918 | let spec = ResumeSpec { base_sha: base.clone(), wip_ref: None, wip_sha: Some("a".repeat(40)) }; |
| 919 | assert_eq!( |
| 920 | prepare_slot(state, 1, "agent/bad", Some(&spec)).await.unwrap_err().status, |
| 921 | StatusCode::BAD_REQUEST |
| 922 | ); |
| 923 | } |
| 924 | |
| 925 | #[test] |
| 926 | fn legacy_prepare_request_without_resume_still_deserializes() { |
| 927 | let req: proto::PrepareRequest = |
| 928 | serde_json::from_str(r#"{"branch": "agent/x"}"#).expect("legacy JSON"); |
| 929 | assert_eq!(req.branch, "agent/x"); |
| 930 | assert!(req.resume.is_none()); |
| 931 | // And a request with resume parses too. |
| 932 | let req: proto::PrepareRequest = serde_json::from_str( |
| 933 | r#"{"branch": "agent/x", "resume": {"base_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "wip_ref": "refs/agent-wip/7", "wip_sha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}}"#, |
| 934 | ) |
| 935 | .expect("resume JSON"); |
| 936 | let spec = req.resume.expect("resume present"); |
| 937 | assert_eq!(spec.wip_ref.as_deref(), Some("refs/agent-wip/7")); |
| 938 | } |