| 1 | //! Delivery evidence replacing the old prose-verb/git-status heuristic. |
| 2 | //! The worker ledger retains the spawn baseline; this module only reads files. |
| 3 | |
| 4 | use super::{ |
| 5 | AgentRunVerificationSummary, AgentWorkerSpec, default_agent_run_verification, |
| 6 | normalize_claim_path, |
| 7 | }; |
| 8 | use serde::{Deserialize, Serialize}; |
| 9 | use sha2::{Digest as _, Sha256}; |
| 10 | use std::collections::{BTreeMap, BTreeSet}; |
| 11 | use std::fs; |
| 12 | use std::io::Read as _; |
| 13 | use std::path::{Path, PathBuf}; |
| 14 | use std::process::Command; |
| 15 | |
| 16 | pub(super) const MAX_DELIVERABLES: usize = 16; |
| 17 | const MAX_BASELINE_PATHS: usize = 4096; |
| 18 | |
| 19 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 20 | pub struct DeliverableVerdict { |
| 21 | pub path: String, |
| 22 | pub status: String, |
| 23 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 24 | pub bytes: Option<u64>, |
| 25 | } |
| 26 | |
| 27 | #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] |
| 28 | pub struct DeliveryEvidence { |
| 29 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 30 | baseline: Option<GitDeliveryBaseline>, |
| 31 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 32 | baseline_error: Option<String>, |
| 33 | #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] |
| 34 | pub(super) observed_writes: BTreeSet<String>, |
| 35 | #[serde(default)] |
| 36 | pub(super) checked: bool, |
| 37 | } |
| 38 | |
| 39 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 40 | struct GitDeliveryBaseline { |
| 41 | root: PathBuf, |
| 42 | head: Option<String>, |
| 43 | dirty: BTreeMap<String, String>, |
| 44 | } |
| 45 | |
| 46 | fn git_command(root: &Path) -> Option<Command> { |
| 47 | let mut command = codewhale_dependencies::Git::workspace_command(root).ok()?; |
| 48 | command.args(["-c", "core.untrackedCache=false"]); |
| 49 | Some(command) |
| 50 | } |
| 51 | |
| 52 | fn git_output(root: &Path, args: &[&str]) -> Option<std::process::Output> { |
| 53 | git_command(root)?.args(args).output().ok() |
| 54 | } |
| 55 | |
| 56 | fn git_bytes(root: &Path, args: &[&str]) -> Result<Vec<u8>, String> { |
| 57 | let output = git_output(root, args).ok_or_else(|| "git spawn failed".to_string())?; |
| 58 | if !output.status.success() { |
| 59 | return Err(first_line_lossy(&output.stderr, 200)); |
| 60 | } |
| 61 | Ok(output.stdout) |
| 62 | } |
| 63 | |
| 64 | fn git(root: &Path, args: &[&str]) -> Option<Vec<u8>> { |
| 65 | git_bytes(root, args).ok() |
| 66 | } |
| 67 | |
| 68 | /// `git` that reports stderr on failure, for checkpoint notes. |
| 69 | fn git_captured(root: &Path, args: &[&str]) -> Result<String, String> { |
| 70 | git_bytes(root, args).map(|stdout| String::from_utf8_lossy(&stdout).into_owned()) |
| 71 | } |
| 72 | |
| 73 | /// [`git_captured`] with `paths` fed to git's stdin NUL-terminated, for |
| 74 | /// commands reading `-z --stdin` or `--pathspec-from-file=- --pathspec-file-nul`. |
| 75 | /// No argv length limit applies, so no path count ever needs a wider |
| 76 | /// command instead of the exact list. |
| 77 | fn git_captured_paths(root: &Path, args: &[&str], paths: &[&str]) -> Result<String, String> { |
| 78 | use std::io::Write as _; |
| 79 | use std::process::Stdio; |
| 80 | let mut child = git_command(root) |
| 81 | .ok_or_else(|| "git spawn failed".to_string())? |
| 82 | .args(args) |
| 83 | .stdin(Stdio::piped()) |
| 84 | .stdout(Stdio::piped()) |
| 85 | .stderr(Stdio::piped()) |
| 86 | .spawn() |
| 87 | .map_err(|_| "git spawn failed".to_string())?; |
| 88 | let mut input = Vec::new(); |
| 89 | for path in paths { |
| 90 | input.extend_from_slice(path.as_bytes()); |
| 91 | input.push(0); |
| 92 | } |
| 93 | if let Some(mut stdin) = child.stdin.take() { |
| 94 | // A write error means git exited early; its stderr says why. |
| 95 | let _ = stdin.write_all(&input); |
| 96 | } |
| 97 | let output = child |
| 98 | .wait_with_output() |
| 99 | .map_err(|_| "git wait failed".to_string())?; |
| 100 | if !output.status.success() { |
| 101 | return Err(first_line_lossy(&output.stderr, 200)); |
| 102 | } |
| 103 | Ok(String::from_utf8_lossy(&output.stdout).into_owned()) |
| 104 | } |
| 105 | |
| 106 | fn first_line_lossy(bytes: &[u8], max_chars: usize) -> String { |
| 107 | let line = String::from_utf8_lossy(bytes) |
| 108 | .lines() |
| 109 | .next() |
| 110 | .unwrap_or_default() |
| 111 | .trim() |
| 112 | .to_string(); |
| 113 | if line.is_empty() { |
| 114 | return "git failed with no message".to_string(); |
| 115 | } |
| 116 | line.chars().take(max_chars).collect() |
| 117 | } |
| 118 | |
| 119 | fn status_paths_checked(root: &Path) -> Result<BTreeSet<String>, String> { |
| 120 | let output = git_bytes( |
| 121 | root, |
| 122 | &[ |
| 123 | "status", |
| 124 | "--porcelain=v1", |
| 125 | "-z", |
| 126 | "--untracked-files=all", |
| 127 | "--ignore-submodules=dirty", |
| 128 | ], |
| 129 | ) |
| 130 | .map_err(|err| format!("git status failed: {err}"))?; |
| 131 | let mut entries = output |
| 132 | .split(|byte| *byte == 0) |
| 133 | .filter(|entry| !entry.is_empty()); |
| 134 | let mut paths = BTreeSet::new(); |
| 135 | while let Some(entry) = entries.next() { |
| 136 | let path_bytes = entry |
| 137 | .get(3..) |
| 138 | .ok_or_else(|| "git status returned malformed porcelain entry".to_string())?; |
| 139 | let path = std::str::from_utf8(path_bytes) |
| 140 | .map_err(|_| "git status returned non-UTF-8 path".to_string())?; |
| 141 | paths.insert(path.to_string()); |
| 142 | if entry[..2].iter().any(|byte| matches!(byte, b'R' | b'C')) { |
| 143 | // Porcelain -z emits the destination first, then the source. |
| 144 | if let Some(source) = entries.next() { |
| 145 | let source = std::str::from_utf8(source) |
| 146 | .map_err(|_| "git status returned non-UTF-8 rename source path".to_string())?; |
| 147 | paths.insert(source.to_string()); |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | if paths.len() > MAX_BASELINE_PATHS { |
| 152 | return Err(format!( |
| 153 | "git status exceeded {MAX_BASELINE_PATHS} dirty paths" |
| 154 | )); |
| 155 | } |
| 156 | Ok(paths) |
| 157 | } |
| 158 | |
| 159 | fn status_paths(root: &Path) -> Option<BTreeSet<String>> { |
| 160 | status_paths_checked(root).ok() |
| 161 | } |
| 162 | |
| 163 | fn fingerprint(root: &Path, relative: &str) -> Option<String> { |
| 164 | let mut parent = root.to_path_buf(); |
| 165 | let components = Path::new(relative).components().collect::<Vec<_>>(); |
| 166 | for component in components.iter().take(components.len().saturating_sub(1)) { |
| 167 | parent.push(component); |
| 168 | if fs::symlink_metadata(&parent).is_ok_and(|metadata| metadata.file_type().is_symlink()) { |
| 169 | return Some("symlink_ancestor".into()); |
| 170 | } |
| 171 | } |
| 172 | let path = root.join(relative); |
| 173 | |
| 174 | let metadata = match fs::symlink_metadata(&path) { |
| 175 | Ok(metadata) => metadata, |
| 176 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 177 | return Some("missing".into()); |
| 178 | } |
| 179 | Err(_) => return None, |
| 180 | }; |
| 181 | if metadata.file_type().is_symlink() { |
| 182 | return Some(format!("symlink:{}", fs::read_link(&path).ok()?.display())); |
| 183 | } |
| 184 | if !metadata.is_file() { |
| 185 | return Some("non_file".into()); |
| 186 | } |
| 187 | let mut file = fs::File::open(&path).ok()?; |
| 188 | let mut hash = Sha256::new(); |
| 189 | let mut buffer = [0_u8; 65536]; |
| 190 | loop { |
| 191 | let count = file.read(&mut buffer).ok()?; |
| 192 | if count == 0 { |
| 193 | break; |
| 194 | } |
| 195 | hash.update(&buffer[..count]); |
| 196 | } |
| 197 | Some(format!( |
| 198 | "sha256:{}", |
| 199 | codewhale_runtime::hashing::hex_bytes(hash.finalize()) |
| 200 | )) |
| 201 | } |
| 202 | |
| 203 | fn capture_baseline(workspace: &Path) -> Result<GitDeliveryBaseline, String> { |
| 204 | let root_bytes = git_bytes(workspace, &["rev-parse", "--show-toplevel"]) |
| 205 | .map_err(|err| format!("git rev-parse --show-toplevel failed: {err}"))?; |
| 206 | let root = String::from_utf8(root_bytes) |
| 207 | .map_err(|_| "git rev-parse --show-toplevel returned non-UTF-8 path".to_string())?; |
| 208 | let root = PathBuf::from(root.trim()); |
| 209 | let head = git(&root, &["rev-parse", "--verify", "HEAD"]) |
| 210 | .and_then(|bytes| String::from_utf8(bytes).ok()) |
| 211 | .map(|head| head.trim().to_string()); |
| 212 | let mut dirty = BTreeMap::new(); |
| 213 | for path in status_paths_checked(&root)? { |
| 214 | let path = normalize_claim_path(&path) |
| 215 | .map_err(|_| format!("git baseline path could not be normalized: {path}"))?; |
| 216 | let hash = fingerprint(&root, &path) |
| 217 | .ok_or_else(|| format!("git baseline fingerprint failed for {path}"))?; |
| 218 | dirty.insert(path, hash); |
| 219 | } |
| 220 | Ok(GitDeliveryBaseline { root, head, dirty }) |
| 221 | } |
| 222 | |
| 223 | impl DeliveryEvidence { |
| 224 | pub(super) fn capture(spec: &AgentWorkerSpec) -> Self { |
| 225 | Self::capture_for_handle(&spec.workspace, spec.runtime_profile.permissions.write) |
| 226 | } |
| 227 | |
| 228 | /// Baseline capture that needs only the workspace and write permission — |
| 229 | /// the two spec fields the baseline actually reads. The async spawn path |
| 230 | /// calls this in `spawn_blocking` BEFORE the manager write lock (#6210) |
| 231 | /// and threads the evidence through registration, so git + file |
| 232 | /// fingerprints never run under the lock. |
| 233 | pub(super) fn capture_for_handle(workspace: &Path, write: bool) -> Self { |
| 234 | if !write { |
| 235 | return Self::default(); |
| 236 | } |
| 237 | match capture_baseline(workspace) { |
| 238 | Ok(baseline) => Self { |
| 239 | baseline: Some(baseline), |
| 240 | ..Self::default() |
| 241 | }, |
| 242 | Err(reason) => { |
| 243 | tracing::warn!( |
| 244 | target: "subagent", |
| 245 | workspace = %workspace.display(), |
| 246 | reason = %reason, |
| 247 | "subagent git delivery baseline unavailable" |
| 248 | ); |
| 249 | Self { |
| 250 | baseline_error: Some(reason), |
| 251 | ..Self::default() |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | pub(super) fn has_baseline(&self) -> bool { |
| 258 | self.baseline.is_some() |
| 259 | } |
| 260 | |
| 261 | pub(super) fn clear_baseline(&mut self) { |
| 262 | self.baseline = None; |
| 263 | } |
| 264 | |
| 265 | pub(super) fn changed_paths(&self, workspace: &Path) -> Option<BTreeSet<String>> { |
| 266 | self.changed_paths_checked(workspace).ok() |
| 267 | } |
| 268 | |
| 269 | pub(super) fn changed_paths_checked( |
| 270 | &self, |
| 271 | workspace: &Path, |
| 272 | ) -> Result<BTreeSet<String>, String> { |
| 273 | let Some(baseline) = self.baseline.as_ref() else { |
| 274 | return Err(self |
| 275 | .baseline_error |
| 276 | .clone() |
| 277 | .unwrap_or_else(|| "git delivery baseline unavailable at spawn".to_string())); |
| 278 | }; |
| 279 | // Persisted evidence is data, never authority to inspect another tree |
| 280 | // or pass caller-controlled options to git after a restart. |
| 281 | let current_root_bytes = git_bytes(workspace, &["rev-parse", "--show-toplevel"]) |
| 282 | .map_err(|err| format!("git rev-parse --show-toplevel failed: {err}"))?; |
| 283 | let current_root = String::from_utf8(current_root_bytes) |
| 284 | .map_err(|_| "git rev-parse --show-toplevel returned non-UTF-8 path".to_string())?; |
| 285 | let current_root = PathBuf::from(current_root.trim()); |
| 286 | if !same_path_identity(&baseline.root, ¤t_root) |
| 287 | || baseline.dirty.len() > MAX_BASELINE_PATHS |
| 288 | || baseline |
| 289 | .dirty |
| 290 | .keys() |
| 291 | .any(|path| normalize_claim_path(path).as_ref() != Ok(path)) |
| 292 | || baseline.head.as_ref().is_some_and(|head| { |
| 293 | !matches!(head.len(), 40 | 64) || !head.bytes().all(|byte| byte.is_ascii_hexdigit()) |
| 294 | }) |
| 295 | { |
| 296 | return Err("git delivery baseline no longer matches workspace".to_string()); |
| 297 | } |
| 298 | let mut candidates = status_paths_checked(&baseline.root)?; |
| 299 | candidates.extend(baseline.dirty.keys().cloned()); |
| 300 | if let Some(head) = baseline.head.as_deref() { |
| 301 | let mut args = vec!["diff"]; |
| 302 | args.extend(codewhale_dependencies::Git::REVIEW_DIFF_ARGS); |
| 303 | args.extend(["--name-only", "-z", head, "HEAD", "--"]); |
| 304 | let output = git_bytes(&baseline.root, &args) |
| 305 | .map_err(|err| format!("git diff failed: {err}"))?; |
| 306 | for path in output |
| 307 | .split(|byte| *byte == 0) |
| 308 | .filter(|path| !path.is_empty()) |
| 309 | { |
| 310 | let path = std::str::from_utf8(path) |
| 311 | .map_err(|_| "git diff returned non-UTF-8 path".to_string())?; |
| 312 | candidates.insert(path.to_string()); |
| 313 | } |
| 314 | } |
| 315 | // Git status paths are already repo-relative. Prefer them when the |
| 316 | // worker workspace is the git toplevel by identity; otherwise project |
| 317 | // through a shared canonicalize spelling. Always normalize separators |
| 318 | // so Windows `src\lib.rs` matches claim paths like `src/lib.rs`. |
| 319 | let workspace_root = workspace |
| 320 | .canonicalize() |
| 321 | .map_err(|_| "workspace path canonicalization failed".to_string())?; |
| 322 | let baseline_root = baseline |
| 323 | .root |
| 324 | .canonicalize() |
| 325 | .map_err(|_| "git baseline root canonicalization failed".to_string())?; |
| 326 | let workspace_is_repo_root = same_path_identity(&workspace_root, &baseline_root); |
| 327 | let mut changed = BTreeSet::new(); |
| 328 | for path in candidates { |
| 329 | let Ok(path) = normalize_claim_path(&path) else { |
| 330 | continue; |
| 331 | }; |
| 332 | if let Some(before) = baseline.dirty.get(&path) |
| 333 | && fingerprint(&baseline.root, &path).as_ref() == Some(before) |
| 334 | { |
| 335 | continue; |
| 336 | } |
| 337 | let relative = if workspace_is_repo_root { |
| 338 | path |
| 339 | } else { |
| 340 | let absolute = baseline_root.join(Path::new(&path)); |
| 341 | let Ok(relative) = absolute.strip_prefix(&workspace_root) else { |
| 342 | continue; |
| 343 | }; |
| 344 | let Ok(normalized) = normalize_claim_path(&relative.to_string_lossy()) else { |
| 345 | continue; |
| 346 | }; |
| 347 | normalized |
| 348 | }; |
| 349 | changed.insert(relative); |
| 350 | } |
| 351 | Ok(changed) |
| 352 | } |
| 353 | |
| 354 | /// Commit the worker's uncommitted changes as labeled salvage, and only |
| 355 | /// on an isolated worktree (#6194 item 4, #5529). Synchronous git reads |
| 356 | /// and writes: call under `spawn_blocking`, never under the manager |
| 357 | /// lock. `changed` is the `changed_paths` inventory the caller already |
| 358 | /// computed; the commit is skipped (not forced) when none of it is still |
| 359 | /// uncommitted, and every failure degrades to a note — never an error. |
| 360 | /// |
| 361 | /// Ownership is exact at every size (#6557 D02-11): only paths that are |
| 362 | /// both in `changed` and dirty now are staged and committed. A |
| 363 | /// pre-existing dirty file the worker never touched stays dirty, and a |
| 364 | /// file staged by someone else stays staged but outside the commit |
| 365 | /// (`git commit --only` with the owned pathspecs). Paths travel on stdin |
| 366 | /// as literal pathspecs, so a name like `*.rs` is never a glob and no |
| 367 | /// inventory size widens staging to the whole tree. A dirty tree larger |
| 368 | /// than the baseline bound is refused rather than guessed at. |
| 369 | pub(super) fn checkpoint_uncommitted( |
| 370 | &self, |
| 371 | changed: &BTreeSet<String>, |
| 372 | agent_id: &str, |
| 373 | cause: &str, |
| 374 | isolated_worktree: bool, |
| 375 | ) -> BudgetCheckpointOutcome { |
| 376 | use BudgetCheckpointOutcome::*; |
| 377 | if !isolated_worktree { |
| 378 | // A shared checkout may hold the parent's or a sibling's dirty |
| 379 | // files; auto-commit would sweep them into the checkpoint. |
| 380 | return SkippedNonIsolated; |
| 381 | } |
| 382 | if changed.is_empty() { |
| 383 | return Clean; |
| 384 | } |
| 385 | let Some(baseline) = self.baseline.as_ref() else { |
| 386 | return Failed { |
| 387 | reason: "no delivery baseline".to_string(), |
| 388 | }; |
| 389 | }; |
| 390 | let Some(dirty) = status_paths(&baseline.root) else { |
| 391 | return Failed { |
| 392 | reason: format!( |
| 393 | "git status failed or listed more than {MAX_BASELINE_PATHS} paths; nothing was staged" |
| 394 | ), |
| 395 | }; |
| 396 | }; |
| 397 | // Status spelling is what git matches; `changed` is normalized. |
| 398 | let owned: Vec<&str> = dirty |
| 399 | .iter() |
| 400 | .filter(|path| normalize_claim_path(path).is_ok_and(|path| changed.contains(&path))) |
| 401 | .map(String::as_str) |
| 402 | .collect(); |
| 403 | if owned.is_empty() { |
| 404 | return Clean; |
| 405 | } |
| 406 | match codewhale_dependencies::Git::defines_repository_filters(&baseline.root) { |
| 407 | Ok(false) => {} |
| 408 | Ok(true) => { |
| 409 | return Failed { |
| 410 | reason: "the repository defines its own git filters, which this checkpoint does not run; nothing was staged" |
| 411 | .to_string(), |
| 412 | }; |
| 413 | } |
| 414 | Err(_) => { |
| 415 | return Failed { |
| 416 | reason: |
| 417 | "the repository's git filters could not be inspected; nothing was staged" |
| 418 | .to_string(), |
| 419 | }; |
| 420 | } |
| 421 | } |
| 422 | // `update-index` takes literal paths and stages every status shape: |
| 423 | // edits, new files (`--add`), and deletions or rename sources whose |
| 424 | // file is gone (`--remove`), where `git add <path>` would fail. |
| 425 | if let Err(reason) = git_captured_paths( |
| 426 | &baseline.root, |
| 427 | &["update-index", "--add", "--remove", "-z", "--stdin"], |
| 428 | &owned, |
| 429 | ) { |
| 430 | return Failed { reason }; |
| 431 | } |
| 432 | let cause_short: String = cause |
| 433 | .lines() |
| 434 | .next() |
| 435 | .unwrap_or(cause) |
| 436 | .chars() |
| 437 | .take(120) |
| 438 | .collect(); |
| 439 | let message = format!( |
| 440 | "checkpoint: {agent_id} ({cause_short}) - {} uncommitted file(s) at budget death; unreviewed salvage", |
| 441 | owned.len() |
| 442 | ); |
| 443 | if let Err(reason) = git_captured_paths( |
| 444 | &baseline.root, |
| 445 | &[ |
| 446 | "--literal-pathspecs", |
| 447 | "-c", |
| 448 | "commit.gpgsign=false", |
| 449 | "-c", |
| 450 | "user.name=Codewhale Subagent", |
| 451 | "-c", |
| 452 | "user.email=subagent@codewhale.invalid", |
| 453 | "commit", |
| 454 | "--quiet", |
| 455 | "--only", |
| 456 | "-m", |
| 457 | &message, |
| 458 | "--pathspec-from-file=-", |
| 459 | "--pathspec-file-nul", |
| 460 | ], |
| 461 | &owned, |
| 462 | ) { |
| 463 | return Failed { reason }; |
| 464 | } |
| 465 | match git_captured(&baseline.root, &["rev-parse", "--short", "HEAD"]) { |
| 466 | Ok(sha) => Committed { |
| 467 | sha: sha.trim().to_string(), |
| 468 | }, |
| 469 | Err(reason) => Failed { reason }, |
| 470 | } |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | /// Outcome of the budget-death checkpoint commit. |
| 475 | pub(super) enum BudgetCheckpointOutcome { |
| 476 | /// Uncommitted work is now commit `sha` on the worker branch. |
| 477 | Committed { sha: String }, |
| 478 | /// Nothing attributable to commit (clean tree, or the worker committed). |
| 479 | Clean, |
| 480 | /// Shared checkout: auto-commit would sweep up other writers' work. |
| 481 | SkippedNonIsolated, |
| 482 | /// Nothing was committed; files survive on disk. |
| 483 | Failed { reason: String }, |
| 484 | } |
| 485 | |
| 486 | fn same_path_identity(left: &Path, right: &Path) -> bool { |
| 487 | if left == right { |
| 488 | return true; |
| 489 | } |
| 490 | match (left.canonicalize(), right.canonicalize()) { |
| 491 | (Ok(left), Ok(right)) => left == right, |
| 492 | _ => false, |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | pub(super) fn declared_paths( |
| 497 | paths: &[String], |
| 498 | legacy: Option<&str>, |
| 499 | ) -> Result<Vec<String>, String> { |
| 500 | if paths.len() > MAX_DELIVERABLES { |
| 501 | return Err(format!( |
| 502 | "deliverables accepts at most {MAX_DELIVERABLES} paths" |
| 503 | )); |
| 504 | } |
| 505 | let mut paths = paths.to_vec(); |
| 506 | if paths.is_empty() |
| 507 | && let Some(legacy) = legacy |
| 508 | && !legacy.chars().any(char::is_whitespace) |
| 509 | && (legacy.contains('/') || legacy.contains('.')) |
| 510 | { |
| 511 | paths.push(legacy.to_string()); |
| 512 | } |
| 513 | let mut normalized = Vec::new(); |
| 514 | for path in paths { |
| 515 | let path = normalize_claim_path(&path)?; |
| 516 | if path == "." |
| 517 | || path.split('/').any(|part| { |
| 518 | codewhale_util::git_metadata::is_git_metadata_name(std::ffi::OsStr::new(part)) |
| 519 | }) |
| 520 | { |
| 521 | return Err("deliverables must name files outside git metadata".into()); |
| 522 | } |
| 523 | if !normalized.contains(&path) { |
| 524 | normalized.push(path); |
| 525 | } |
| 526 | } |
| 527 | Ok(normalized) |
| 528 | } |
| 529 | |
| 530 | pub(super) fn safe_deliverable_path(workspace: &Path, path: &str) -> Result<PathBuf, String> { |
| 531 | let path = declared_paths(&[path.to_string()], None)? |
| 532 | .pop() |
| 533 | .ok_or_else(|| "deliverable must name a file".to_string())?; |
| 534 | let root = workspace |
| 535 | .canonicalize() |
| 536 | .map_err(|_| "deliverable workspace is unavailable".to_string())?; |
| 537 | let mut resolved = root.clone(); |
| 538 | for component in Path::new(&path).components() { |
| 539 | resolved.push(component); |
| 540 | match fs::symlink_metadata(&resolved) { |
| 541 | Ok(metadata) if metadata.file_type().is_symlink() => { |
| 542 | return Err("deliverable path traverses a symlink".into()); |
| 543 | } |
| 544 | Ok(_) => {} |
| 545 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} |
| 546 | Err(_) => return Err("deliverable path cannot be inspected".into()), |
| 547 | } |
| 548 | } |
| 549 | if resolved == root || !resolved.starts_with(root) { |
| 550 | return Err("deliverable must be a file inside the worker workspace".into()); |
| 551 | } |
| 552 | Ok(resolved) |
| 553 | } |
| 554 | |
| 555 | pub(super) fn check_deliverable(workspace: &Path, path: &str, allowed: bool) -> DeliverableVerdict { |
| 556 | let mut verdict = DeliverableVerdict { |
| 557 | path: path.into(), |
| 558 | status: "out_of_scope".into(), |
| 559 | bytes: None, |
| 560 | }; |
| 561 | if !allowed { |
| 562 | return verdict; |
| 563 | } |
| 564 | let resolved = match safe_deliverable_path(workspace, path) { |
| 565 | Ok(path) => path, |
| 566 | Err(_) => { |
| 567 | verdict.status = "invalid_path".into(); |
| 568 | return verdict; |
| 569 | } |
| 570 | }; |
| 571 | match fs::symlink_metadata(resolved) { |
| 572 | Ok(metadata) if metadata.is_file() => { |
| 573 | verdict.bytes = Some(metadata.len()); |
| 574 | verdict.status = if metadata.len() == 0 { |
| 575 | "empty" |
| 576 | } else { |
| 577 | "present" |
| 578 | } |
| 579 | .into(); |
| 580 | } |
| 581 | Ok(_) => verdict.status = "not_file".into(), |
| 582 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 583 | verdict.status = "missing".into() |
| 584 | } |
| 585 | Err(_) => verdict.status = "unreadable".into(), |
| 586 | } |
| 587 | verdict |
| 588 | } |
| 589 | |
| 590 | fn citation(token: &str) -> bool { |
| 591 | // A citation may be sentence-final or either side of a Markdown link. |
| 592 | // Normalize punctuation only for citation detection; never rewrite a path. |
| 593 | token.split("](").any(|part| { |
| 594 | let part = part.trim_end_matches(|ch: char| { |
| 595 | matches!( |
| 596 | ch, |
| 597 | '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}' | '\'' | '"' | '`' |
| 598 | ) |
| 599 | }); |
| 600 | let Some((_, line)) = part.rsplit_once(':') else { |
| 601 | return false; |
| 602 | }; |
| 603 | let mut numbers = line.split('-'); |
| 604 | let numeric = |
| 605 | |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()); |
| 606 | numbers.next().is_some_and(numeric) |
| 607 | && numbers.next().is_none_or(numeric) |
| 608 | && numbers.next().is_none() |
| 609 | }) |
| 610 | } |
| 611 | |
| 612 | pub(super) fn explicit_change_paths(summary: &str) -> BTreeSet<String> { |
| 613 | let mut paths = BTreeSet::new(); |
| 614 | let mut in_changes = false; |
| 615 | for line in summary.lines() { |
| 616 | let line = line.trim(); |
| 617 | let is_heading = line.starts_with('#'); |
| 618 | let line = line.trim_start_matches('#').trim(); |
| 619 | let lower = line.to_ascii_lowercase(); |
| 620 | // SUBAGENT_OUTPUT_FORMAT uses a bare Markdown heading, with ordinary |
| 621 | // blank lines before its file bullets. That is an explicit declaration |
| 622 | // boundary just like the compatibility CHANGES: label. |
| 623 | if is_heading && lower == "changes" { |
| 624 | in_changes = true; |
| 625 | continue; |
| 626 | } |
| 627 | if line.is_empty() { |
| 628 | continue; |
| 629 | } |
| 630 | let declaration = ["changes:", "changed files:", "files changed:"] |
| 631 | .into_iter() |
| 632 | .find(|prefix| lower.starts_with(prefix)); |
| 633 | let content = if let Some(prefix) = declaration { |
| 634 | in_changes = true; |
| 635 | &line[prefix.len()..] |
| 636 | } else if in_changes && (line.starts_with('-') || line.starts_with('*')) { |
| 637 | line |
| 638 | } else { |
| 639 | in_changes = false; |
| 640 | continue; |
| 641 | }; |
| 642 | if matches!( |
| 643 | content |
| 644 | .trim() |
| 645 | .trim_end_matches('.') |
| 646 | .to_ascii_lowercase() |
| 647 | .as_str(), |
| 648 | "none" | "no files changed" | "no changes" |
| 649 | ) { |
| 650 | in_changes = false; |
| 651 | continue; |
| 652 | } |
| 653 | let content = content.trim(); |
| 654 | let mut remaining = content |
| 655 | .strip_prefix("- ") |
| 656 | .or_else(|| content.strip_prefix("* ")) |
| 657 | .unwrap_or(content); |
| 658 | // File declarations lead with paths. Stop when their description |
| 659 | // starts instead of interpreting sentence-final prose ("parsing.") |
| 660 | // or a later reference ("see notes.md") as another claimed edit. |
| 661 | while !remaining.is_empty() { |
| 662 | remaining = remaining |
| 663 | .trim_start_matches(|ch: char| ch.is_whitespace() || matches!(ch, ',' | ';')); |
| 664 | let Some(first) = remaining.chars().next() else { |
| 665 | break; |
| 666 | }; |
| 667 | let quoted = matches!(first, '`' | '"' | '\''); |
| 668 | let (token, rest) = if quoted { |
| 669 | let Some((token, rest)) = remaining[1..].split_once(first) else { |
| 670 | break; |
| 671 | }; |
| 672 | (token, rest) |
| 673 | } else { |
| 674 | let end = remaining |
| 675 | .find(|ch: char| ch.is_whitespace() || matches!(ch, ',' | ';')) |
| 676 | .unwrap_or(remaining.len()); |
| 677 | remaining.split_at(end) |
| 678 | }; |
| 679 | remaining = rest; |
| 680 | if citation(token) || token.contains("://") { |
| 681 | break; |
| 682 | } |
| 683 | let token = if quoted { |
| 684 | token |
| 685 | } else { |
| 686 | token |
| 687 | .trim_matches(|ch: char| matches!(ch, '(' | ')' | '[' | ']' | '*' | '-')) |
| 688 | .trim_end_matches(['.', ':', '!', '?']) |
| 689 | }; |
| 690 | let token = token.split_once("](").map_or(token, |(label, _)| label); |
| 691 | if !token.contains('/') && !token.contains('.') { |
| 692 | break; |
| 693 | } |
| 694 | let Ok(path) = normalize_claim_path(token) else { |
| 695 | break; |
| 696 | }; |
| 697 | if path == "." { |
| 698 | break; |
| 699 | } |
| 700 | paths.insert(path); |
| 701 | } |
| 702 | } |
| 703 | paths |
| 704 | } |
| 705 | |
| 706 | pub(super) fn verify_changes( |
| 707 | summary: &str, |
| 708 | write_capable: bool, |
| 709 | evidence: &DeliveryEvidence, |
| 710 | changed: Result<&BTreeSet<String>, &str>, |
| 711 | declared_outputs: &BTreeSet<String>, |
| 712 | ) -> Option<AgentRunVerificationSummary> { |
| 713 | if !write_capable { |
| 714 | return None; |
| 715 | } |
| 716 | let claimed = explicit_change_paths(summary); |
| 717 | let changed_set = changed.ok(); |
| 718 | // A path changing inside a writable scope proves neither the actor nor a |
| 719 | // child write. External tools and people can edit the same checkout, so only |
| 720 | // successful bounded write receipts can support an undeclared-write claim. |
| 721 | let undeclared = evidence |
| 722 | .observed_writes |
| 723 | .iter() |
| 724 | .filter(|path| { |
| 725 | changed_set.is_none_or(|changed| changed.contains(*path)) |
| 726 | && !claimed.contains(*path) |
| 727 | && !declared_outputs.contains(*path) |
| 728 | }) |
| 729 | .cloned() |
| 730 | .collect::<Vec<_>>(); |
| 731 | let missing = match changed { |
| 732 | Ok(changed) => claimed.difference(changed).cloned().collect::<Vec<_>>(), |
| 733 | Err(reason) => { |
| 734 | if !undeclared.is_empty() { |
| 735 | return Some(AgentRunVerificationSummary { |
| 736 | status: "claim_mismatch".into(), |
| 737 | summary: format!( |
| 738 | "Git delivery baseline unavailable ({reason}); observed changes without a change declaration: {undeclared:?}. Inspect the worker receipt." |
| 739 | ), |
| 740 | deliverables: Vec::new(), |
| 741 | }); |
| 742 | } |
| 743 | if !claimed.is_empty() { |
| 744 | let claimed_list = claimed.into_iter().collect::<Vec<_>>(); |
| 745 | return Some(AgentRunVerificationSummary { |
| 746 | status: "verification_incomplete".into(), |
| 747 | summary: format!( |
| 748 | "Could not verify declared file changes ({claimed_list:?}) because git delivery baseline was unavailable ({reason}). Inspect the worker receipt." |
| 749 | ), |
| 750 | deliverables: Vec::new(), |
| 751 | }); |
| 752 | } |
| 753 | return None; |
| 754 | } |
| 755 | }; |
| 756 | if missing.is_empty() && undeclared.is_empty() { |
| 757 | return None; |
| 758 | } |
| 759 | Some(AgentRunVerificationSummary { |
| 760 | status: "claim_mismatch".into(), |
| 761 | summary: format!( |
| 762 | "Compared with the workspace at spawn: declared but unchanged: {missing:?}; observed changes without a change declaration: {undeclared:?}. Inspect the worker receipt." |
| 763 | ), |
| 764 | deliverables: Vec::new(), |
| 765 | }) |
| 766 | } |
| 767 | |
| 768 | /// Everything delivery verification needs, snapshotted under a read lock. |
| 769 | /// `allowed[i]` is the write-scope verdict for `deliverables[i]`. The compute |
| 770 | /// half runs in `spawn_blocking` with no manager lock held (#6210). |
| 771 | #[derive(Debug, Clone)] |
| 772 | pub(super) struct DeliveryVerificationInputs { |
| 773 | pub evidence: DeliveryEvidence, |
| 774 | pub workspace: PathBuf, |
| 775 | pub result_text: String, |
| 776 | pub write_perm: bool, |
| 777 | pub deliverables: Vec<String>, |
| 778 | pub allowed: Vec<bool>, |
| 779 | /// The worker ran in its own isolated worktree and settled in a state that |
| 780 | /// cannot be resumed there; remove the worktree if it changed nothing. |
| 781 | pub remove_worktree_if_unchanged: bool, |
| 782 | } |
| 783 | |
| 784 | /// Pure compute half of worker delivery verification: the git trio + |
| 785 | /// fingerprints (`changed_paths`), claim comparison, and per-deliverable |
| 786 | /// presence checks. Runs off the manager lock; the caller stores the summary. |
| 787 | pub(super) fn compute_delivery_verification( |
| 788 | inputs: &DeliveryVerificationInputs, |
| 789 | ) -> AgentRunVerificationSummary { |
| 790 | let changed = inputs.evidence.changed_paths_checked(&inputs.workspace); |
| 791 | let mut verification = verify_changes( |
| 792 | &inputs.result_text, |
| 793 | inputs.write_perm, |
| 794 | &inputs.evidence, |
| 795 | changed.as_ref().map_err(String::as_str), |
| 796 | &inputs.deliverables.iter().cloned().collect(), |
| 797 | ) |
| 798 | .unwrap_or_else(default_agent_run_verification); |
| 799 | verification.deliverables = inputs |
| 800 | .deliverables |
| 801 | .iter() |
| 802 | .zip(inputs.allowed.iter()) |
| 803 | .map(|(path, allowed)| check_deliverable(&inputs.workspace, path, *allowed)) |
| 804 | .collect(); |
| 805 | let missing = verification |
| 806 | .deliverables |
| 807 | .iter() |
| 808 | .filter(|verdict| verdict.status != "present") |
| 809 | .map(|verdict| format!("{} ({})", verdict.path, verdict.status)) |
| 810 | .collect::<Vec<_>>(); |
| 811 | if !missing.is_empty() { |
| 812 | let prior = if matches!( |
| 813 | verification.status.as_str(), |
| 814 | "claim_mismatch" | "verification_incomplete" |
| 815 | ) { |
| 816 | format!(" {}", verification.summary) |
| 817 | } else { |
| 818 | String::new() |
| 819 | }; |
| 820 | verification.status = "deliverable_missing".to_string(); |
| 821 | verification.summary = format!( |
| 822 | "Declared deliverables not produced as non-empty files in the worker write scope: {}.{prior}", |
| 823 | missing.join(", ") |
| 824 | ); |
| 825 | } else if !inputs.deliverables.is_empty() && verification.status == "self_report_only" { |
| 826 | verification.status = "deliverables_present".to_string(); |
| 827 | verification.summary = "Declared files exist and are non-empty inside the worker write scope; their contents remain a worker self-report.".to_string(); |
| 828 | } |
| 829 | verification |
| 830 | } |
| 831 |