| 1 | use super::{ |
| 2 | SharedWorkflowControllers, SharedWorkflowLifecycles, SharedWorkflowRuns, |
| 3 | WorkflowDispatchFailure, WorkflowRunRecord, WorkflowRunStatus, WorkflowUiEvent, |
| 4 | WorkflowUiEventKind, WorkflowWorkLifecycle, |
| 5 | }; |
| 6 | use serde::{Deserialize, Serialize}; |
| 7 | use std::collections::HashMap; |
| 8 | use std::io::BufRead; |
| 9 | use std::path::{Path, PathBuf}; |
| 10 | use std::sync::{Arc, Mutex, OnceLock}; |
| 11 | use tracing::warn; |
| 12 | |
| 13 | pub(super) const CODEWHALE_DIR: &str = ".codewhale"; |
| 14 | pub(super) const WORKFLOW_RUNS_FILE: &str = "workflow-runs.jsonl"; |
| 15 | |
| 16 | /// Per-workspace workflow state shared across tool-registry rebuilds. |
| 17 | pub(super) struct WorkflowWorkspaceState { |
| 18 | pub runs: SharedWorkflowRuns, |
| 19 | pub controllers: SharedWorkflowControllers, |
| 20 | lifecycles: SharedWorkflowLifecycles, |
| 21 | journal: WorkflowRunJournal, |
| 22 | } |
| 23 | |
| 24 | impl WorkflowWorkspaceState { |
| 25 | pub fn open(workspace: &Path) -> Arc<Self> { |
| 26 | Self::open_inner(workspace, true) |
| 27 | } |
| 28 | |
| 29 | /// Hydrate the journal without rewriting leftover `running` rows to |
| 30 | /// `failed`. Host reads do not claim runtime ownership; host cancel can |
| 31 | /// still mark a controller-less run cancelled instead of assuming a crash. |
| 32 | pub fn open_preserving_running(workspace: &Path) -> Arc<Self> { |
| 33 | Self::open_inner(workspace, false) |
| 34 | } |
| 35 | |
| 36 | fn open_inner(workspace: &Path, recover_orphans: bool) -> Arc<Self> { |
| 37 | let journal = WorkflowRunJournal::open(workspace); |
| 38 | let runs = Arc::new(Mutex::new(journal.hydrate_runs(recover_orphans))); |
| 39 | Arc::new(Self { |
| 40 | runs, |
| 41 | controllers: Arc::new(Mutex::new(HashMap::new())), |
| 42 | lifecycles: Arc::new(Mutex::new(HashMap::new())), |
| 43 | journal, |
| 44 | }) |
| 45 | } |
| 46 | |
| 47 | pub fn attach_lifecycle(&self, run_id: &str, lifecycle: WorkflowWorkLifecycle) { |
| 48 | self.lifecycles |
| 49 | .lock() |
| 50 | .unwrap_or_else(|poison| poison.into_inner()) |
| 51 | .entry(run_id.to_string()) |
| 52 | .or_insert(lifecycle); |
| 53 | } |
| 54 | |
| 55 | pub fn reconcile_snapshot(&self, record: &WorkflowRunRecord) { |
| 56 | let lifecycle = self |
| 57 | .lifecycles |
| 58 | .lock() |
| 59 | .unwrap_or_else(|poison| poison.into_inner()) |
| 60 | .get(&record.run_id) |
| 61 | .cloned(); |
| 62 | if let Some(lifecycle) = lifecycle |
| 63 | && let Err(err) = lifecycle.reconcile_record(record) |
| 64 | { |
| 65 | warn!( |
| 66 | run_id = record.run_id, |
| 67 | "workflow Work reconciliation failed: {err}" |
| 68 | ); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | pub fn reconcile_cancel(&self, run_id: &str, outcome: super::CancelOutcome) { |
| 73 | let lifecycle = self |
| 74 | .lifecycles |
| 75 | .lock() |
| 76 | .unwrap_or_else(|poison| poison.into_inner()) |
| 77 | .get(run_id) |
| 78 | .cloned(); |
| 79 | if let Some(lifecycle) = lifecycle |
| 80 | && let Err(err) = lifecycle.reconcile_cancel(outcome) |
| 81 | { |
| 82 | warn!(run_id, "workflow cancellation reconciliation failed: {err}"); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | pub fn mark_owner_missing(&self, run_id: &str) { |
| 87 | let lifecycle = self |
| 88 | .lifecycles |
| 89 | .lock() |
| 90 | .unwrap_or_else(|poison| poison.into_inner()) |
| 91 | .get(run_id) |
| 92 | .cloned(); |
| 93 | if let Some(lifecycle) = lifecycle { |
| 94 | lifecycle.reconcile_missing(); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | pub fn try_record_snapshot(&self, record: &WorkflowRunRecord) -> Result<(), String> { |
| 99 | self.journal |
| 100 | .append_snapshot(record) |
| 101 | .map_err(|err| err.to_string()) |
| 102 | } |
| 103 | |
| 104 | pub fn record_snapshot(&self, record: &WorkflowRunRecord) { |
| 105 | if let Err(err) = self.try_record_snapshot(record) { |
| 106 | warn!("workflow journal snapshot failed: {err}"); |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | pub fn record_progress(&self, run_id: &str, message: &str) { |
| 111 | if let Err(err) = self.journal.append_progress(run_id, message) { |
| 112 | warn!("workflow journal progress failed: {err}"); |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | pub fn record_event(&self, run_id: &str, event: &WorkflowUiEvent) { |
| 117 | if let Err(err) = self.journal.append_event(run_id, event) { |
| 118 | warn!("workflow journal event failed: {err}"); |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | /// Durable journal location for full-fidelity run detail (#2974). |
| 123 | pub fn journal_path(&self) -> &Path { |
| 124 | &self.journal.ledger_path |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | fn workspace_store() -> &'static Mutex<HashMap<PathBuf, Arc<WorkflowWorkspaceState>>> { |
| 129 | static STORE: OnceLock<Mutex<HashMap<PathBuf, Arc<WorkflowWorkspaceState>>>> = OnceLock::new(); |
| 130 | STORE.get_or_init(|| Mutex::new(HashMap::new())) |
| 131 | } |
| 132 | |
| 133 | pub(super) fn shared_workflow_state(workspace: &Path) -> Arc<WorkflowWorkspaceState> { |
| 134 | let key = workspace |
| 135 | .canonicalize() |
| 136 | .unwrap_or_else(|_| workspace.to_path_buf()); |
| 137 | let mut store = workspace_store() |
| 138 | .lock() |
| 139 | .unwrap_or_else(|poison| poison.into_inner()); |
| 140 | store |
| 141 | .entry(key) |
| 142 | .or_insert_with(|| WorkflowWorkspaceState::open(workspace)) |
| 143 | .clone() |
| 144 | } |
| 145 | |
| 146 | /// Read-only lookup that never creates workspace state, a journal |
| 147 | /// directory, or a ledger file. Used by the human-only `/structcopy` |
| 148 | /// command (#2033), which must stay side-effect free. |
| 149 | pub(super) fn peek_shared_workflow_state(workspace: &Path) -> Option<Arc<WorkflowWorkspaceState>> { |
| 150 | let key = workspace |
| 151 | .canonicalize() |
| 152 | .unwrap_or_else(|_| workspace.to_path_buf()); |
| 153 | workspace_store() |
| 154 | .lock() |
| 155 | .unwrap_or_else(|poison| poison.into_inner()) |
| 156 | .get(&key) |
| 157 | .cloned() |
| 158 | } |
| 159 | |
| 160 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 161 | #[serde(tag = "kind", rename_all = "snake_case")] |
| 162 | enum WorkflowJournalRecord { |
| 163 | // Boxed: a full run record dwarfs the progress variant |
| 164 | // (clippy::large_enum_variant). |
| 165 | Snapshot { |
| 166 | run: Box<WorkflowRunRecord>, |
| 167 | }, |
| 168 | Progress { |
| 169 | run_id: String, |
| 170 | message: String, |
| 171 | }, |
| 172 | Event { |
| 173 | run_id: String, |
| 174 | event: Box<WorkflowUiEvent>, |
| 175 | }, |
| 176 | } |
| 177 | |
| 178 | #[derive(Debug)] |
| 179 | struct WorkflowRunJournal { |
| 180 | /// State directory the ledger must stay inside; links below it are refused. |
| 181 | /// A home workspace makes this the resolved `~/.codewhale` target, while |
| 182 | /// every other workspace passes itself here with `.codewhale` still inside |
| 183 | /// the ledger path. See [`WorkflowRunJournal::open`]. |
| 184 | root: PathBuf, |
| 185 | ledger_path: PathBuf, |
| 186 | } |
| 187 | |
| 188 | impl WorkflowRunJournal { |
| 189 | /// Opening has no side effects: `.codewhale/` and the ledger appear with |
| 190 | /// the first appended record, and only through the confined helpers, so a |
| 191 | /// linked `.codewhale` never receives an empty `state/` or ledger. |
| 192 | /// |
| 193 | /// A home workspace resolves `~/.codewhale` to its target, because that |
| 194 | /// junction is where the user chose to keep application state. Any other |
| 195 | /// workspace keeps itself as the root with `.codewhale` inside the walked |
| 196 | /// path, so a repository-supplied link is refused as before. |
| 197 | fn open(workspace: &Path) -> Self { |
| 198 | let (root, ledger_path) = |
| 199 | codewhale_util::files::workspace_state_path(workspace, Path::new(WORKFLOW_RUNS_FILE)); |
| 200 | Self { root, ledger_path } |
| 201 | } |
| 202 | |
| 203 | fn hydrate_runs(&self, recover_orphans: bool) -> HashMap<String, WorkflowRunRecord> { |
| 204 | let file = match codewhale_util::fs_confined::open_read(&self.root, &self.ledger_path) { |
| 205 | Ok(file) => file, |
| 206 | Err(err) => { |
| 207 | if err.kind() != std::io::ErrorKind::NotFound { |
| 208 | warn!( |
| 209 | "workflow journal unreadable ({}): {err}", |
| 210 | self.ledger_path.display() |
| 211 | ); |
| 212 | } |
| 213 | return HashMap::new(); |
| 214 | } |
| 215 | }; |
| 216 | let mut runs = HashMap::new(); |
| 217 | for line in std::io::BufReader::new(file).lines() { |
| 218 | let Ok(line) = line else { continue }; |
| 219 | let trimmed = line.trim(); |
| 220 | if trimmed.is_empty() { |
| 221 | continue; |
| 222 | } |
| 223 | let record = match serde_json::from_str::<WorkflowJournalRecord>(trimmed) { |
| 224 | Ok(record) => record, |
| 225 | Err(err) => { |
| 226 | warn!("workflow journal skipped malformed line: {err}"); |
| 227 | continue; |
| 228 | } |
| 229 | }; |
| 230 | match record { |
| 231 | WorkflowJournalRecord::Snapshot { run } => { |
| 232 | let mut run = *run; |
| 233 | run.normalize_bounded_ledgers(); |
| 234 | runs.insert(run.run_id.clone(), run); |
| 235 | } |
| 236 | WorkflowJournalRecord::Progress { run_id, message } => { |
| 237 | if let Some(run) = runs.get_mut(&run_id) { |
| 238 | run.push_progress(message); |
| 239 | } |
| 240 | } |
| 241 | WorkflowJournalRecord::Event { run_id, event } => { |
| 242 | if let Some(run) = runs.get_mut(&run_id) { |
| 243 | let event = *event; |
| 244 | if let WorkflowUiEventKind::TaskDispatchFailed { |
| 245 | label, |
| 246 | phase, |
| 247 | message, |
| 248 | .. |
| 249 | } = &event.kind |
| 250 | { |
| 251 | run.push_dispatch_failure(WorkflowDispatchFailure { |
| 252 | at_ms: event.at_ms, |
| 253 | label: label.clone(), |
| 254 | phase: phase.clone(), |
| 255 | message: message.clone(), |
| 256 | }); |
| 257 | } |
| 258 | run.push_event(event); |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | // Journals written before #2974 have no counters; rebuild them |
| 264 | // from the retained tail so summaries stay truthful. |
| 265 | for run in runs.values_mut() { |
| 266 | run.normalize_bounded_ledgers(); |
| 267 | run.events_total = run.events_total.max(run.events.len() as u64); |
| 268 | } |
| 269 | // A run journaled as Running belongs to a process that is gone; |
| 270 | // without this it would show as live forever after a restart. |
| 271 | // Host reads and cancellation skip this owner-only rewrite. |
| 272 | if recover_orphans { |
| 273 | let mut recovered = Vec::new(); |
| 274 | for run in runs.values_mut() { |
| 275 | if run.status == WorkflowRunStatus::Running { |
| 276 | run.status = WorkflowRunStatus::Failed; |
| 277 | run.lifecycle_seq = run.lifecycle_seq.saturating_add(1); |
| 278 | run.completed_at_ms.get_or_insert_with(super::now_ms); |
| 279 | run.error = Some( |
| 280 | "process exited before the run completed (recovered on startup)" |
| 281 | .to_string(), |
| 282 | ); |
| 283 | recovered.push(run.clone()); |
| 284 | } |
| 285 | } |
| 286 | // The recovery decision is owner truth, not a presentation-only |
| 287 | // repair. Append it so another restart replays the same terminal |
| 288 | // sequence instead of rediscovering and incrementing it again. |
| 289 | for run in recovered { |
| 290 | if let Err(err) = self.append_snapshot(&run) { |
| 291 | warn!( |
| 292 | run_id = run.run_id, |
| 293 | "workflow recovery snapshot append failed: {err}" |
| 294 | ); |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | runs |
| 299 | } |
| 300 | |
| 301 | fn append_record(&self, record: &WorkflowJournalRecord) -> std::io::Result<()> { |
| 302 | let mut line = |
| 303 | serde_json::to_string(record).map_err(|err| std::io::Error::other(err.to_string()))?; |
| 304 | line.push('\n'); |
| 305 | let snapshot = matches!(record, WorkflowJournalRecord::Snapshot { .. }); |
| 306 | if snapshot && self.ends_with_torn_line() { |
| 307 | line.insert(0, '\n'); |
| 308 | } |
| 309 | codewhale_util::fs_confined::append_durable(&self.root, &self.ledger_path, line.as_bytes()) |
| 310 | } |
| 311 | |
| 312 | fn ends_with_torn_line(&self) -> bool { |
| 313 | use std::io::{Read, Seek, SeekFrom}; |
| 314 | let Ok(mut file) = |
| 315 | codewhale_util::fs_confined::open_read_shared(&self.root, &self.ledger_path) |
| 316 | else { |
| 317 | return false; |
| 318 | }; |
| 319 | let mut last = [0u8; 1]; |
| 320 | file.seek(SeekFrom::End(-1)).is_ok() |
| 321 | && file.read_exact(&mut last).is_ok() |
| 322 | && last[0] != b'\n' |
| 323 | } |
| 324 | |
| 325 | fn append_snapshot(&self, record: &WorkflowRunRecord) -> std::io::Result<()> { |
| 326 | self.append_record(&WorkflowJournalRecord::Snapshot { |
| 327 | run: Box::new(record.clone()), |
| 328 | }) |
| 329 | } |
| 330 | |
| 331 | fn append_progress(&self, run_id: &str, message: &str) -> std::io::Result<()> { |
| 332 | self.append_record(&WorkflowJournalRecord::Progress { |
| 333 | run_id: run_id.to_string(), |
| 334 | message: message.to_string(), |
| 335 | }) |
| 336 | } |
| 337 | |
| 338 | fn append_event(&self, run_id: &str, event: &WorkflowUiEvent) -> std::io::Result<()> { |
| 339 | self.append_record(&WorkflowJournalRecord::Event { |
| 340 | run_id: run_id.to_string(), |
| 341 | event: Box::new(event.clone()), |
| 342 | }) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | #[cfg(test)] |
| 347 | mod tests { |
| 348 | use super::super::{WORKFLOW_RUN_DISPATCH_FAILURES_MAX_RETAINED, WorkflowUiEventKind}; |
| 349 | use super::*; |
| 350 | use std::io::Write; |
| 351 | |
| 352 | /// #5582: a degraded run must never project as an ordinary success |
| 353 | /// to owner-level consumers. |
| 354 | #[test] |
| 355 | fn owner_snapshot_keeps_degraded_distinct_from_completed() { |
| 356 | use crate::work_graph::OwnerState; |
| 357 | assert_eq!( |
| 358 | crate::tools::workflow::owner_state_for_run_status(WorkflowRunStatus::Degraded), |
| 359 | OwnerState::Degraded |
| 360 | ); |
| 361 | assert_eq!( |
| 362 | crate::tools::workflow::owner_state_for_run_status(WorkflowRunStatus::Completed), |
| 363 | OwnerState::Completed |
| 364 | ); |
| 365 | } |
| 366 | |
| 367 | fn sample_record(run_id: &str, status: WorkflowRunStatus) -> WorkflowRunRecord { |
| 368 | WorkflowRunRecord { |
| 369 | run_id: run_id.to_string(), |
| 370 | owner_session_id: Some("session-journal".to_string()), |
| 371 | status, |
| 372 | lifecycle_seq: 1, |
| 373 | started_at_ms: 1, |
| 374 | completed_at_ms: None, |
| 375 | source_path: None, |
| 376 | workflow_id: Some("fixture".to_string()), |
| 377 | workflow_goal: Some("journal test".to_string()), |
| 378 | child_ids: Vec::new(), |
| 379 | progress_count: 0, |
| 380 | progress: Vec::new(), |
| 381 | events: Vec::new(), |
| 382 | schema_errors: Vec::new(), |
| 383 | schema_repairs: Vec::new(), |
| 384 | schema_repair_count: 0, |
| 385 | dispatch_failure_count: 0, |
| 386 | dispatch_failures: Vec::new(), |
| 387 | result: None, |
| 388 | execution: None, |
| 389 | error: None, |
| 390 | verify_on_complete: false, |
| 391 | verification: None, |
| 392 | plan_approval: None, |
| 393 | gate_status: Vec::new(), |
| 394 | usage: None, |
| 395 | events_total: 0, |
| 396 | events_dropped: 0, |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | /// Opening the journal creates nothing; the first record creates the |
| 401 | /// ledger under a private `.codewhale/`. |
| 402 | #[test] |
| 403 | fn opening_the_journal_creates_nothing_until_a_record_is_appended() { |
| 404 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 405 | let state = WorkflowWorkspaceState::open(tmp.path()); |
| 406 | assert!(!tmp.path().join(CODEWHALE_DIR).exists()); |
| 407 | state.record_snapshot(&sample_record("workflow_lazy", WorkflowRunStatus::Running)); |
| 408 | assert!(state.journal_path().is_file()); |
| 409 | } |
| 410 | |
| 411 | /// A linked `.codewhale` gets no empty `state/` or ledger, and appends and |
| 412 | /// reads are refused instead of writing through the link. |
| 413 | #[cfg(unix)] |
| 414 | #[test] |
| 415 | fn journal_never_writes_through_a_linked_codewhale_dir() { |
| 416 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 417 | let workspace = tmp.path().join("workspace"); |
| 418 | let outside = tmp.path().join("outside"); |
| 419 | std::fs::create_dir_all(&workspace).expect("mkdir workspace"); |
| 420 | std::fs::create_dir_all(&outside).expect("mkdir outside"); |
| 421 | std::os::unix::fs::symlink(&outside, workspace.join(CODEWHALE_DIR)).expect("link"); |
| 422 | |
| 423 | let journal = WorkflowRunJournal::open(&workspace); |
| 424 | assert!(journal.hydrate_runs(true).is_empty()); |
| 425 | let err = journal |
| 426 | .append_snapshot(&sample_record("workflow_link", WorkflowRunStatus::Running)) |
| 427 | .expect_err("append through a linked .codewhale must be refused"); |
| 428 | assert!(!err.to_string().is_empty()); |
| 429 | |
| 430 | // The state-level entry points degrade to a warning, not a write. |
| 431 | let state = WorkflowWorkspaceState::open(&workspace); |
| 432 | state.record_progress("workflow_link", "phase: scan"); |
| 433 | assert_eq!( |
| 434 | std::fs::read_dir(&outside).expect("read outside").count(), |
| 435 | 0 |
| 436 | ); |
| 437 | } |
| 438 | |
| 439 | #[test] |
| 440 | fn workflow_journal_hydrates_snapshots_and_progress() { |
| 441 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 442 | let state = WorkflowWorkspaceState::open(tmp.path()); |
| 443 | let running = sample_record("workflow_abc", WorkflowRunStatus::Running); |
| 444 | state.record_snapshot(&running); |
| 445 | state.record_progress("workflow_abc", "phase: scan"); |
| 446 | state.record_event( |
| 447 | "workflow_abc", |
| 448 | &WorkflowUiEvent::at( |
| 449 | 5, |
| 450 | "session-journal", |
| 451 | WorkflowUiEventKind::PhaseStarted { |
| 452 | title: "scan".to_string(), |
| 453 | }, |
| 454 | ), |
| 455 | ); |
| 456 | |
| 457 | let completed = WorkflowRunRecord { |
| 458 | status: WorkflowRunStatus::Completed, |
| 459 | completed_at_ms: Some(99), |
| 460 | progress: vec!["phase: scan".to_string()], |
| 461 | events: vec![WorkflowUiEvent::at( |
| 462 | 5, |
| 463 | "session-journal", |
| 464 | WorkflowUiEventKind::PhaseStarted { |
| 465 | title: "scan".to_string(), |
| 466 | }, |
| 467 | )], |
| 468 | ..sample_record("workflow_abc", WorkflowRunStatus::Completed) |
| 469 | }; |
| 470 | state.record_snapshot(&completed); |
| 471 | state.record_event( |
| 472 | "workflow_abc", |
| 473 | &WorkflowUiEvent::at( |
| 474 | 6, |
| 475 | "session-journal", |
| 476 | WorkflowUiEventKind::HandoffPromoted { |
| 477 | artifact_id: "workflow_abc:scout-1:scout-gate:findings".to_string(), |
| 478 | gate_id: "scout-gate".to_string(), |
| 479 | kind: "findings".to_string(), |
| 480 | from_role: "scout".to_string(), |
| 481 | to_role: "implementer".to_string(), |
| 482 | producer_task_id: "scout-1".to_string(), |
| 483 | }, |
| 484 | ), |
| 485 | ); |
| 486 | state.record_event( |
| 487 | "workflow_abc", |
| 488 | &WorkflowUiEvent::at( |
| 489 | 7, |
| 490 | "session-journal", |
| 491 | WorkflowUiEventKind::HandoffConsumed { |
| 492 | artifact_id: "workflow_abc:scout-1:scout-gate:findings".to_string(), |
| 493 | kind: "findings".to_string(), |
| 494 | from_role: "scout".to_string(), |
| 495 | to_role: "implementer".to_string(), |
| 496 | consumer_task_id: "implementer-1".to_string(), |
| 497 | }, |
| 498 | ), |
| 499 | ); |
| 500 | |
| 501 | let reloaded = WorkflowWorkspaceState::open(tmp.path()); |
| 502 | let runs = reloaded |
| 503 | .runs |
| 504 | .lock() |
| 505 | .expect("runs lock") |
| 506 | .get("workflow_abc") |
| 507 | .cloned() |
| 508 | .expect("hydrated run"); |
| 509 | assert_eq!(runs.status, WorkflowRunStatus::Completed); |
| 510 | assert_eq!(runs.progress, vec!["phase: scan"]); |
| 511 | assert_eq!(runs.events.len(), 3); |
| 512 | assert_eq!(runs.events[0].event_type(), "phase_started"); |
| 513 | let promoted = serde_json::to_value(&runs.events[1]).expect("promoted receipt"); |
| 514 | assert_eq!(promoted["type"], "handoff_promoted"); |
| 515 | assert_eq!( |
| 516 | promoted["artifact_id"], |
| 517 | "workflow_abc:scout-1:scout-gate:findings" |
| 518 | ); |
| 519 | assert_eq!(promoted["gate_id"], "scout-gate"); |
| 520 | assert_eq!(promoted["producer_task_id"], "scout-1"); |
| 521 | assert!(promoted.get("payload").is_none(), "{promoted}"); |
| 522 | let consumed = serde_json::to_value(&runs.events[2]).expect("consumed receipt"); |
| 523 | assert_eq!(consumed["type"], "handoff_consumed"); |
| 524 | assert_eq!(consumed["artifact_id"], promoted["artifact_id"]); |
| 525 | assert_eq!(consumed["consumer_task_id"], "implementer-1"); |
| 526 | assert!(consumed.get("payload").is_none(), "{consumed}"); |
| 527 | assert_eq!(runs.completed_at_ms, Some(99)); |
| 528 | |
| 529 | // The event-line replay above must also survive compaction into a |
| 530 | // final Snapshot record containing both handoff variants. |
| 531 | reloaded.record_snapshot(&runs); |
| 532 | let reopened = WorkflowWorkspaceState::open(tmp.path()); |
| 533 | let compacted = reopened |
| 534 | .runs |
| 535 | .lock() |
| 536 | .expect("runs lock") |
| 537 | .get("workflow_abc") |
| 538 | .cloned() |
| 539 | .expect("snapshot with handoff receipts"); |
| 540 | assert_eq!( |
| 541 | compacted |
| 542 | .events |
| 543 | .iter() |
| 544 | .map(WorkflowUiEvent::event_type) |
| 545 | .collect::<Vec<_>>(), |
| 546 | vec!["phase_started", "handoff_promoted", "handoff_consumed"] |
| 547 | ); |
| 548 | } |
| 549 | |
| 550 | #[test] |
| 551 | fn workflow_journal_rebuilds_a_bounded_exact_rejection_ledger() { |
| 552 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 553 | let state = WorkflowWorkspaceState::open(tmp.path()); |
| 554 | state.record_snapshot(&sample_record( |
| 555 | "workflow_rejections", |
| 556 | WorkflowRunStatus::Running, |
| 557 | )); |
| 558 | let total = WORKFLOW_RUN_DISPATCH_FAILURES_MAX_RETAINED + 5; |
| 559 | for index in 0..total { |
| 560 | let message = format!("invalid task options {index}"); |
| 561 | state.record_progress( |
| 562 | "workflow_rejections", |
| 563 | &format!("dispatch failed for rejected-{index}: {message}"), |
| 564 | ); |
| 565 | state.record_event( |
| 566 | "workflow_rejections", |
| 567 | &WorkflowUiEvent::at( |
| 568 | index as u64, |
| 569 | "session-journal", |
| 570 | WorkflowUiEventKind::TaskDispatchFailed { |
| 571 | label: Some(format!("rejected-{index}")), |
| 572 | phase: Some("fan-out".to_string()), |
| 573 | message, |
| 574 | queue_ticket: None, |
| 575 | }, |
| 576 | ), |
| 577 | ); |
| 578 | } |
| 579 | drop(state); |
| 580 | |
| 581 | let reloaded = WorkflowWorkspaceState::open(tmp.path()); |
| 582 | let run = reloaded |
| 583 | .runs |
| 584 | .lock() |
| 585 | .expect("runs lock") |
| 586 | .get("workflow_rejections") |
| 587 | .cloned() |
| 588 | .expect("hydrated rejection run"); |
| 589 | assert_eq!(run.progress_count, total as u64); |
| 590 | assert_eq!(run.progress.len(), total); |
| 591 | assert_eq!(run.dispatch_failure_count, total as u64); |
| 592 | assert_eq!( |
| 593 | run.dispatch_failures.len(), |
| 594 | WORKFLOW_RUN_DISPATCH_FAILURES_MAX_RETAINED |
| 595 | ); |
| 596 | assert_eq!( |
| 597 | run.dispatch_failures |
| 598 | .first() |
| 599 | .and_then(|failure| failure.label.as_deref()), |
| 600 | Some("rejected-5") |
| 601 | ); |
| 602 | drop(reloaded); |
| 603 | |
| 604 | // Restart recovery appends a compact snapshot. Replaying the |
| 605 | // journal again must not double-count its earlier event lines. |
| 606 | let reopened = WorkflowWorkspaceState::open(tmp.path()); |
| 607 | let run = reopened |
| 608 | .runs |
| 609 | .lock() |
| 610 | .expect("runs lock") |
| 611 | .get("workflow_rejections") |
| 612 | .cloned() |
| 613 | .expect("rehydrated rejection run"); |
| 614 | assert_eq!(run.dispatch_failure_count, total as u64); |
| 615 | assert_eq!( |
| 616 | run.dispatch_failures.len(), |
| 617 | WORKFLOW_RUN_DISPATCH_FAILURES_MAX_RETAINED |
| 618 | ); |
| 619 | } |
| 620 | |
| 621 | #[test] |
| 622 | fn workflow_journal_marks_orphaned_running_runs_failed() { |
| 623 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 624 | let state = WorkflowWorkspaceState::open(tmp.path()); |
| 625 | state.record_snapshot(&sample_record( |
| 626 | "workflow_orphan", |
| 627 | WorkflowRunStatus::Running, |
| 628 | )); |
| 629 | |
| 630 | let reloaded = WorkflowWorkspaceState::open(tmp.path()); |
| 631 | let run = reloaded |
| 632 | .runs |
| 633 | .lock() |
| 634 | .expect("runs lock") |
| 635 | .get("workflow_orphan") |
| 636 | .cloned() |
| 637 | .expect("hydrated run"); |
| 638 | assert_eq!(run.status, WorkflowRunStatus::Failed); |
| 639 | assert_eq!( |
| 640 | run.lifecycle_seq, 2, |
| 641 | "restart recovery is a durable owner lifecycle transition" |
| 642 | ); |
| 643 | assert!( |
| 644 | run.completed_at_ms.is_some(), |
| 645 | "restart recovery must terminalize the durable owner record" |
| 646 | ); |
| 647 | assert!( |
| 648 | run.error |
| 649 | .as_deref() |
| 650 | .is_some_and(|error| error.contains("process exited")), |
| 651 | "expected orphan recovery error, got {:?}", |
| 652 | run.error |
| 653 | ); |
| 654 | |
| 655 | let reopened = WorkflowWorkspaceState::open(tmp.path()); |
| 656 | let replayed = reopened |
| 657 | .runs |
| 658 | .lock() |
| 659 | .expect("runs lock") |
| 660 | .get("workflow_orphan") |
| 661 | .cloned() |
| 662 | .expect("durably recovered run"); |
| 663 | assert_eq!(replayed.status, WorkflowRunStatus::Failed); |
| 664 | assert_eq!( |
| 665 | replayed.lifecycle_seq, 2, |
| 666 | "reopening must replay the recovery snapshot without another transition" |
| 667 | ); |
| 668 | } |
| 669 | |
| 670 | #[test] |
| 671 | fn recovery_snapshot_survives_a_torn_last_line() { |
| 672 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 673 | let state = WorkflowWorkspaceState::open(tmp.path()); |
| 674 | state.record_snapshot(&sample_record("workflow_torn", WorkflowRunStatus::Running)); |
| 675 | std::fs::OpenOptions::new() |
| 676 | .append(true) |
| 677 | .open(state.journal_path()) |
| 678 | .expect("open journal") |
| 679 | .write_all(br#"{"kind":"progress","run_id":"workflow_to"#) |
| 680 | .expect("write torn tail"); |
| 681 | |
| 682 | WorkflowWorkspaceState::open(tmp.path()); |
| 683 | let reopened = WorkflowWorkspaceState::open_preserving_running(tmp.path()); |
| 684 | let run = reopened |
| 685 | .runs |
| 686 | .lock() |
| 687 | .expect("runs lock") |
| 688 | .get("workflow_torn") |
| 689 | .cloned() |
| 690 | .expect("hydrated run"); |
| 691 | assert_eq!( |
| 692 | run.status, |
| 693 | WorkflowRunStatus::Failed, |
| 694 | "the recovery snapshot must not be glued onto the torn line" |
| 695 | ); |
| 696 | assert_eq!(run.lifecycle_seq, 2); |
| 697 | } |
| 698 | |
| 699 | #[test] |
| 700 | fn host_cancel_hydrates_a_journal_without_live_process_state() { |
| 701 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 702 | let state = WorkflowWorkspaceState::open(tmp.path()); |
| 703 | let record = sample_record("workflow_prior", WorkflowRunStatus::Running); |
| 704 | state.record_snapshot(&record); |
| 705 | drop(state); |
| 706 | |
| 707 | assert!( |
| 708 | peek_shared_workflow_state(tmp.path()).is_none(), |
| 709 | "writing the journal must not insert process-wide live state" |
| 710 | ); |
| 711 | |
| 712 | let line = super::super::host_cancel_workflow( |
| 713 | tmp.path(), |
| 714 | "workflow_prior", |
| 715 | Some("session-journal"), |
| 716 | ) |
| 717 | .expect("a journaled run must be visible to host cancel after restart"); |
| 718 | assert_eq!(line.run_id, "workflow_prior"); |
| 719 | assert_eq!(line.status, "cancelled"); |
| 720 | assert!( |
| 721 | line.error |
| 722 | .as_deref() |
| 723 | .is_some_and(|error| error.contains("no live process")), |
| 724 | "controller-less cancel must leave an honest receipt, got {:?}", |
| 725 | line.error |
| 726 | ); |
| 727 | |
| 728 | let reopened = WorkflowWorkspaceState::open(tmp.path()); |
| 729 | let replayed = reopened |
| 730 | .runs |
| 731 | .lock() |
| 732 | .expect("runs lock") |
| 733 | .get("workflow_prior") |
| 734 | .cloned() |
| 735 | .expect("cancelled journal line"); |
| 736 | assert_eq!(replayed.status, WorkflowRunStatus::Cancelled); |
| 737 | } |
| 738 | |
| 739 | #[test] |
| 740 | fn host_stage_is_derived_from_typed_owner_events() { |
| 741 | let mut record = sample_record("workflow_stage", WorkflowRunStatus::Running); |
| 742 | record.push_event(WorkflowUiEvent::at( |
| 743 | 1, |
| 744 | "session-journal", |
| 745 | WorkflowUiEventKind::RunStarted { |
| 746 | workflow_id: Some("fixture".to_string()), |
| 747 | workflow_goal: Some("review release".to_string()), |
| 748 | source_path: None, |
| 749 | max_concurrent: None, |
| 750 | }, |
| 751 | )); |
| 752 | assert_eq!(super::super::host_workflow_stage(&record), "queued"); |
| 753 | |
| 754 | record.push_event(WorkflowUiEvent::at( |
| 755 | 2, |
| 756 | "session-journal", |
| 757 | WorkflowUiEventKind::PhaseStarted { |
| 758 | title: "review".to_string(), |
| 759 | }, |
| 760 | )); |
| 761 | assert_eq!(super::super::host_workflow_stage(&record), "running"); |
| 762 | |
| 763 | record.push_event(WorkflowUiEvent::at( |
| 764 | 3, |
| 765 | "session-journal", |
| 766 | WorkflowUiEventKind::TaskStarted(Box::new(super::super::WorkflowTaskStartedEvent { |
| 767 | task_id: "reviewer-1".to_string(), |
| 768 | label: Some("reviewer".to_string()), |
| 769 | role: None, |
| 770 | profile: None, |
| 771 | model: None, |
| 772 | strength: None, |
| 773 | thinking: None, |
| 774 | requested_reasoning: None, |
| 775 | effective_reasoning: None, |
| 776 | resolved_role: Some("reviewer".to_string()), |
| 777 | resolved_profile: None, |
| 778 | resolved_provider: "local".to_string(), |
| 779 | resolved_model: "stub".to_string(), |
| 780 | route_source: "session".to_string(), |
| 781 | child_route: None, |
| 782 | worktree: false, |
| 783 | workspace: None, |
| 784 | git_branch: None, |
| 785 | parent_task_id: None, |
| 786 | depth: 0, |
| 787 | workflow_run_id: Some("workflow_stage".to_string()), |
| 788 | workflow_phase_id: Some("review".to_string()), |
| 789 | workflow_task_label: Some("reviewer".to_string()), |
| 790 | workflow_child_index: Some(0), |
| 791 | queue_ticket: None, |
| 792 | fleet_receipt: None, |
| 793 | })), |
| 794 | )); |
| 795 | assert_eq!(super::super::host_workflow_stage(&record), "waiting"); |
| 796 | |
| 797 | record.push_event(WorkflowUiEvent::at( |
| 798 | 4, |
| 799 | "session-journal", |
| 800 | WorkflowUiEventKind::TaskCompleted { |
| 801 | task_id: "reviewer-1".to_string(), |
| 802 | status: super::super::IrWorkflowRunStatus::Succeeded, |
| 803 | reason: None, |
| 804 | kind: None, |
| 805 | usage: None, |
| 806 | }, |
| 807 | )); |
| 808 | assert_eq!(super::super::host_workflow_stage(&record), "running"); |
| 809 | |
| 810 | record.status = WorkflowRunStatus::Completed; |
| 811 | assert_eq!(super::super::host_workflow_stage(&record), "completed"); |
| 812 | record.status = WorkflowRunStatus::Failed; |
| 813 | assert_eq!(super::super::host_workflow_stage(&record), "failed"); |
| 814 | record.status = WorkflowRunStatus::Cancelled; |
| 815 | assert_eq!(super::super::host_workflow_stage(&record), "cancelled"); |
| 816 | } |
| 817 | |
| 818 | #[test] |
| 819 | fn host_run_details_derive_phases_and_child_states_from_the_journal() { |
| 820 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 821 | let state = WorkflowWorkspaceState::open(tmp.path()); |
| 822 | let mut record = sample_record("workflow_detail", WorkflowRunStatus::Running); |
| 823 | record.workflow_goal = Some("audit provider errors".to_string()); |
| 824 | for message in ["phase: scan", "child slow-1 done", "child slow-2 failed"] { |
| 825 | record.push_progress(message.to_string()); |
| 826 | } |
| 827 | state.record_snapshot(&record); |
| 828 | drop(state); |
| 829 | |
| 830 | let phase: WorkflowUiEvent = serde_json::from_value(serde_json::json!({ |
| 831 | "at_ms": 1, |
| 832 | "owner_session_id": "session-journal", |
| 833 | "type": "phase_started", |
| 834 | "title": "scan" |
| 835 | })) |
| 836 | .expect("phase_started event"); |
| 837 | let started: WorkflowUiEvent = WorkflowUiEvent::at( |
| 838 | 2, |
| 839 | "session-journal", |
| 840 | WorkflowUiEventKind::TaskStarted(Box::new(super::super::WorkflowTaskStartedEvent { |
| 841 | task_id: "child-1".to_string(), |
| 842 | label: Some("slow-1".to_string()), |
| 843 | role: None, |
| 844 | profile: None, |
| 845 | model: None, |
| 846 | strength: None, |
| 847 | thinking: None, |
| 848 | requested_reasoning: None, |
| 849 | effective_reasoning: None, |
| 850 | resolved_role: Some("explore".to_string()), |
| 851 | resolved_profile: None, |
| 852 | resolved_provider: "deepseek".to_string(), |
| 853 | resolved_model: "deepseek-v4-flash".to_string(), |
| 854 | route_source: "session".to_string(), |
| 855 | child_route: None, |
| 856 | worktree: false, |
| 857 | workspace: None, |
| 858 | git_branch: None, |
| 859 | parent_task_id: None, |
| 860 | depth: 0, |
| 861 | workflow_run_id: Some("workflow_detail".to_string()), |
| 862 | workflow_phase_id: Some("scan".to_string()), |
| 863 | workflow_task_label: None, |
| 864 | workflow_child_index: Some(0), |
| 865 | queue_ticket: None, |
| 866 | fleet_receipt: None, |
| 867 | })), |
| 868 | ); |
| 869 | let completed: WorkflowUiEvent = serde_json::from_value(serde_json::json!({ |
| 870 | "at_ms": 3, |
| 871 | "owner_session_id": "session-journal", |
| 872 | "type": "task_completed", |
| 873 | "task_id": "child-1", |
| 874 | "status": "failed" |
| 875 | })) |
| 876 | .expect("task_completed event"); |
| 877 | let replay = WorkflowWorkspaceState::open_preserving_running(tmp.path()); |
| 878 | replay.record_event("workflow_detail", &phase); |
| 879 | replay.record_event("workflow_detail", &started); |
| 880 | replay.record_event("workflow_detail", &completed); |
| 881 | drop(replay); |
| 882 | |
| 883 | let details = super::super::host_workflow_run_details(tmp.path(), Some("session-journal")); |
| 884 | assert_eq!(details.len(), 1, "one journaled run"); |
| 885 | let detail = &details[0]; |
| 886 | assert_eq!(detail.line.run_id, "workflow_detail"); |
| 887 | assert_eq!(detail.line.status, "running"); |
| 888 | assert!(peek_shared_workflow_state(tmp.path()).is_none()); |
| 889 | assert_eq!(detail.line.label, "audit provider errors"); |
| 890 | assert_eq!(detail.phases, vec!["scan".to_string()]); |
| 891 | assert_eq!(detail.children.len(), 1); |
| 892 | let child = &detail.children[0]; |
| 893 | assert_eq!(child.task_id, "child-1"); |
| 894 | assert_eq!(child.label.as_deref(), Some("slow-1")); |
| 895 | assert_eq!(child.role.as_deref(), Some("explore")); |
| 896 | assert_eq!(child.model.as_deref(), Some("deepseek-v4-flash")); |
| 897 | assert_eq!(child.phase.as_deref(), Some("scan")); |
| 898 | assert_eq!( |
| 899 | child.state, "failed", |
| 900 | "terminal event must win over running" |
| 901 | ); |
| 902 | assert_eq!(detail.progress_tail.len(), 3); |
| 903 | assert!(!detail.has_result); |
| 904 | |
| 905 | // Session ownership fences the projection: a foreign session |
| 906 | // sees nothing, exactly like every other host control. |
| 907 | assert!( |
| 908 | super::super::host_workflow_run_details(tmp.path(), Some("session-other")).is_empty() |
| 909 | ); |
| 910 | } |
| 911 | } |
| 912 |