| 1 | //! Active-session Work Graph authority and legacy tool adapters. |
| 2 | |
| 3 | use std::path::Path; |
| 4 | use std::sync::{Arc, Mutex, MutexGuard}; |
| 5 | |
| 6 | use crate::fleet::ledger::FleetLedger; |
| 7 | use crate::tools::plan::{PlanSnapshot, PlanState, SharedPlanState, StepStatus}; |
| 8 | use crate::tools::todo::{SharedTodoList, TodoList, TodoListSnapshot, TodoStatus}; |
| 9 | use codewhale_lane::LaneRegistry; |
| 10 | |
| 11 | use super::{ |
| 12 | BindingId, ChangeCtx, CompatPlanMetadata, CompatTodoBinding, EdgeKind, IdempotencyKey, |
| 13 | NodeKind, NodeState, OperationBinding, OperationIntent, OperationObservation, |
| 14 | OperationOwnerSnapshot, Provenance, Ts, WorkActivityEvent, WorkEdge, WorkEdgeId, WorkGraph, |
| 15 | WorkGraphChange, WorkGraphSnapshot, WorkNode, WorkNodeId, WorkNodePatch, |
| 16 | external_identity_is_well_formed, fleet_task_owner_snapshot, import_legacy, |
| 17 | lane_owner_snapshot, project_plan, project_todos, validate, |
| 18 | }; |
| 19 | use codewhale_models::reasoning_effort_tier::ReasoningEffortTier; |
| 20 | |
| 21 | pub const ACTIVE_OPERATION_SUMMARY_START: &str = "<!-- codewhale:active-work-operations:start -->"; |
| 22 | pub const ACTIVE_OPERATION_SUMMARY_END: &str = "<!-- codewhale:active-work-operations:end -->"; |
| 23 | |
| 24 | #[derive(Debug, Clone, PartialEq)] |
| 25 | pub struct WorkRuntimeSnapshot { |
| 26 | pub graph: WorkGraphSnapshot, |
| 27 | pub todos: TodoListSnapshot, |
| 28 | pub plan: PlanSnapshot, |
| 29 | } |
| 30 | |
| 31 | #[derive(Debug, Default)] |
| 32 | struct ActiveGraph { |
| 33 | session_id: Option<String>, |
| 34 | snapshot: Option<WorkGraphSnapshot>, |
| 35 | pending_publish: bool, |
| 36 | } |
| 37 | |
| 38 | /// One active session graph plus the read-only legacy views it publishes. |
| 39 | pub struct WorkRuntime { |
| 40 | todos: SharedTodoList, |
| 41 | plan: SharedPlanState, |
| 42 | graph: Mutex<ActiveGraph>, |
| 43 | } |
| 44 | |
| 45 | pub type SharedWorkRuntime = Arc<WorkRuntime>; |
| 46 | |
| 47 | impl std::fmt::Debug for WorkRuntime { |
| 48 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 49 | let graph = lock_unpoisoned(&self.graph); |
| 50 | f.debug_struct("WorkRuntime") |
| 51 | .field("session_id", &graph.session_id) |
| 52 | .field("has_graph", &graph.snapshot.is_some()) |
| 53 | .field("pending_publish", &graph.pending_publish) |
| 54 | .finish() |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | #[must_use] |
| 59 | pub fn new_shared_work_runtime(todos: SharedTodoList, plan: SharedPlanState) -> SharedWorkRuntime { |
| 60 | Arc::new(WorkRuntime { |
| 61 | todos, |
| 62 | plan, |
| 63 | graph: Mutex::new(ActiveGraph::default()), |
| 64 | }) |
| 65 | } |
| 66 | |
| 67 | impl WorkRuntime { |
| 68 | #[must_use] |
| 69 | pub fn matches_todos(&self, todos: &SharedTodoList) -> bool { |
| 70 | Arc::ptr_eq(&self.todos, todos) |
| 71 | } |
| 72 | |
| 73 | #[must_use] |
| 74 | pub fn matches_plan(&self, plan: &SharedPlanState) -> bool { |
| 75 | Arc::ptr_eq(&self.plan, plan) |
| 76 | } |
| 77 | |
| 78 | #[must_use] |
| 79 | pub fn has_operation_binding(&self, session_id: Option<&str>, external: &str) -> bool { |
| 80 | let active = lock_unpoisoned(&self.graph); |
| 81 | if let (Some(expected), Some(actual)) = (session_id, active.session_id.as_deref()) |
| 82 | && expected != actual |
| 83 | { |
| 84 | return false; |
| 85 | } |
| 86 | active.snapshot.as_ref().is_some_and(|graph| { |
| 87 | graph.nodes.iter().any(|node| { |
| 88 | node.binding |
| 89 | .as_ref() |
| 90 | .is_some_and(|binding| binding.external == external) |
| 91 | }) |
| 92 | }) |
| 93 | } |
| 94 | |
| 95 | /// Durable owner bindings that still require restore-time confirmation. |
| 96 | /// Terminal operations are excluded because their saved owner receipt is |
| 97 | /// already sufficient and must not be reopened by a missing live handle. |
| 98 | #[must_use] |
| 99 | pub fn reconcilable_durable_bindings(&self, session_id: Option<&str>) -> Vec<String> { |
| 100 | let active = lock_unpoisoned(&self.graph); |
| 101 | if let (Some(expected), Some(actual)) = (session_id, active.session_id.as_deref()) |
| 102 | && expected != actual |
| 103 | { |
| 104 | return Vec::new(); |
| 105 | } |
| 106 | active |
| 107 | .snapshot |
| 108 | .as_ref() |
| 109 | .into_iter() |
| 110 | .flat_map(|graph| graph.nodes.iter()) |
| 111 | .filter(|node| node.state.is_live() || node.state == NodeState::Stale) |
| 112 | .filter_map(|node| node.binding.as_ref()) |
| 113 | .filter(|binding| binding.durable) |
| 114 | .map(|binding| binding.external.clone()) |
| 115 | .collect() |
| 116 | } |
| 117 | |
| 118 | /// Register an Operation before its owner starts work. The operation is |
| 119 | /// first added inert, connected to an Objective/PlanStep, and only then |
| 120 | /// advanced to `Initializing`, so every reducer intermediate satisfies |
| 121 | /// the no-orphan invariant. |
| 122 | pub fn register_operation( |
| 123 | &self, |
| 124 | session_id: &str, |
| 125 | intent: OperationIntent, |
| 126 | ) -> Result<WorkNodeId, String> { |
| 127 | if !external_identity_is_well_formed(&intent.external) { |
| 128 | return Err(format!( |
| 129 | "invalid lifecycle binding external {:?}", |
| 130 | intent.external |
| 131 | )); |
| 132 | } |
| 133 | let todos = retry_lock(&self.todos, 100) |
| 134 | .ok_or_else(|| "To-do state is busy; operation was not registered".to_string())?; |
| 135 | let plan = retry_lock(&self.plan, 100) |
| 136 | .ok_or_else(|| "Plan state is busy; operation was not registered".to_string())?; |
| 137 | let mut active = lock_unpoisoned(&self.graph); |
| 138 | let base = graph_for_update(&mut active, session_id, &plan.snapshot(), &todos.snapshot())?; |
| 139 | if let Some(existing) = base.nodes.iter().find(|node| { |
| 140 | node.binding |
| 141 | .as_ref() |
| 142 | .is_some_and(|binding| binding.external == intent.external) |
| 143 | }) { |
| 144 | let binding = existing.binding.as_ref().expect("binding matched above"); |
| 145 | if binding.durable != intent.durable { |
| 146 | return Err(format!( |
| 147 | "lifecycle binding {} changed durability", |
| 148 | intent.external |
| 149 | )); |
| 150 | } |
| 151 | return Ok(existing.id.clone()); |
| 152 | } |
| 153 | |
| 154 | let mut graph = WorkGraph::from_snapshot(base); |
| 155 | let parent = operation_parent(&mut graph, session_id, &intent.source)?; |
| 156 | let node_id = WorkNodeId::derive(session_id, &format!("operation:{}", intent.external)); |
| 157 | let now = now_ms(); |
| 158 | apply_change( |
| 159 | &mut graph, |
| 160 | session_id, |
| 161 | &intent.source, |
| 162 | WorkGraphChange::AddNode { |
| 163 | node: WorkNode { |
| 164 | id: node_id.clone(), |
| 165 | kind: NodeKind::Operation, |
| 166 | title: bounded_operation_title(&intent.title), |
| 167 | state: NodeState::Ready, |
| 168 | acceptance: intent.acceptance, |
| 169 | binding: Some(OperationBinding { |
| 170 | external: intent.external, |
| 171 | durable: intent.durable, |
| 172 | last_observation: None, |
| 173 | }), |
| 174 | evidence: None, |
| 175 | provenance: Provenance::ToolUpdate { |
| 176 | tool: intent.source.clone(), |
| 177 | call_id: intent.call_id, |
| 178 | }, |
| 179 | created_at: now, |
| 180 | updated_at: now, |
| 181 | }, |
| 182 | }, |
| 183 | )?; |
| 184 | ensure_contains(&mut graph, session_id, &intent.source, &parent, &node_id)?; |
| 185 | let title = graph |
| 186 | .snapshot() |
| 187 | .node(&node_id) |
| 188 | .map(|node| node.title.clone()) |
| 189 | .ok_or_else(|| format!("operation {node_id} disappeared during registration"))?; |
| 190 | patch_existing_node( |
| 191 | &mut graph, |
| 192 | session_id, |
| 193 | &intent.source, |
| 194 | &node_id, |
| 195 | title, |
| 196 | NodeState::Initializing, |
| 197 | )?; |
| 198 | // Registration is where finished shell calls accumulate (#6842): |
| 199 | // keep only the newest ended, non-durable operations. |
| 200 | if super::reducer::evictable_operations(graph.snapshot()).len() |
| 201 | > super::model::ENDED_OPERATION_CAP |
| 202 | { |
| 203 | apply_change( |
| 204 | &mut graph, |
| 205 | session_id, |
| 206 | &intent.source, |
| 207 | WorkGraphChange::PruneEndedOperations { |
| 208 | keep: super::model::ENDED_OPERATION_CAP, |
| 209 | }, |
| 210 | )?; |
| 211 | } |
| 212 | let next = graph.into_snapshot(); |
| 213 | validate_combined(&next, &project_plan(&next), &project_todos(&next))?; |
| 214 | active.snapshot = Some(next); |
| 215 | active.pending_publish = true; |
| 216 | Ok(node_id) |
| 217 | } |
| 218 | |
| 219 | /// Retain a crossed approval boundary as provenance attached to an |
| 220 | /// operation. The completed Approval node is historical evidence only: it |
| 221 | /// does not grant capabilities or change the owner's runtime authority. |
| 222 | pub fn record_operation_approval( |
| 223 | &self, |
| 224 | session_id: &str, |
| 225 | external: &str, |
| 226 | reference: &str, |
| 227 | source: &str, |
| 228 | call_id: &str, |
| 229 | ) -> Result<(), String> { |
| 230 | let todos = retry_lock(&self.todos, 100) |
| 231 | .ok_or_else(|| "To-do state is busy; approval was not recorded".to_string())?; |
| 232 | let plan = retry_lock(&self.plan, 100) |
| 233 | .ok_or_else(|| "Plan state is busy; approval was not recorded".to_string())?; |
| 234 | let mut active = lock_unpoisoned(&self.graph); |
| 235 | let base = graph_for_update(&mut active, session_id, &plan.snapshot(), &todos.snapshot())?; |
| 236 | let operation = base |
| 237 | .nodes |
| 238 | .iter() |
| 239 | .find(|node| { |
| 240 | node.kind == NodeKind::Operation |
| 241 | && node |
| 242 | .binding |
| 243 | .as_ref() |
| 244 | .is_some_and(|binding| binding.external == external) |
| 245 | }) |
| 246 | .map(|node| node.id.clone()) |
| 247 | .ok_or_else(|| format!("operation binding {external} is not registered"))?; |
| 248 | let approval = WorkNodeId::derive( |
| 249 | session_id, |
| 250 | &format!("approval:operation:{external}:{reference}"), |
| 251 | ); |
| 252 | let mut graph = WorkGraph::from_snapshot(base); |
| 253 | if graph.snapshot().node(&approval).is_none() { |
| 254 | let now = now_ms(); |
| 255 | apply_change( |
| 256 | &mut graph, |
| 257 | session_id, |
| 258 | source, |
| 259 | WorkGraphChange::AddNode { |
| 260 | node: WorkNode { |
| 261 | id: approval.clone(), |
| 262 | kind: NodeKind::Approval, |
| 263 | title: bounded_operation_title(&format!( |
| 264 | "verification approved: {reference}" |
| 265 | )), |
| 266 | state: NodeState::Completed, |
| 267 | acceptance: Vec::new(), |
| 268 | binding: None, |
| 269 | evidence: None, |
| 270 | provenance: Provenance::ToolUpdate { |
| 271 | tool: source.to_string(), |
| 272 | call_id: call_id.to_string(), |
| 273 | }, |
| 274 | created_at: now, |
| 275 | updated_at: now, |
| 276 | }, |
| 277 | }, |
| 278 | )?; |
| 279 | } |
| 280 | let edge = WorkEdgeId::derive( |
| 281 | session_id, |
| 282 | &format!( |
| 283 | "requires-approval:{}:{}", |
| 284 | operation.as_str(), |
| 285 | approval.as_str() |
| 286 | ), |
| 287 | ); |
| 288 | if graph.snapshot().edge(&edge).is_none() { |
| 289 | apply_change( |
| 290 | &mut graph, |
| 291 | session_id, |
| 292 | source, |
| 293 | WorkGraphChange::AddEdge { |
| 294 | edge: WorkEdge { |
| 295 | id: edge, |
| 296 | kind: EdgeKind::RequiresApproval, |
| 297 | from: operation, |
| 298 | to: approval, |
| 299 | }, |
| 300 | }, |
| 301 | )?; |
| 302 | } |
| 303 | let next = graph.into_snapshot(); |
| 304 | validate_combined(&next, &project_plan(&next), &project_todos(&next))?; |
| 305 | active.snapshot = Some(next); |
| 306 | active.pending_publish = true; |
| 307 | Ok(()) |
| 308 | } |
| 309 | |
| 310 | /// Apply one owner observation through the reducer. Unknown bindings are |
| 311 | /// rejected rather than materialized after the fact: spawn intent must be |
| 312 | /// registered before work begins. |
| 313 | pub fn reconcile_operation( |
| 314 | &self, |
| 315 | session_id: &str, |
| 316 | snapshot: OperationOwnerSnapshot, |
| 317 | ) -> Result<bool, String> { |
| 318 | let external = snapshot.external.clone(); |
| 319 | self.reconcile_observation(session_id, &external, snapshot.into_observation()) |
| 320 | } |
| 321 | |
| 322 | pub fn reconcile_observation( |
| 323 | &self, |
| 324 | session_id: &str, |
| 325 | external: &str, |
| 326 | observation: OperationObservation, |
| 327 | ) -> Result<bool, String> { |
| 328 | let mut active = lock_unpoisoned(&self.graph); |
| 329 | if active |
| 330 | .session_id |
| 331 | .as_deref() |
| 332 | .is_some_and(|id| id != session_id) |
| 333 | { |
| 334 | return Err(format!( |
| 335 | "lifecycle observation for session {session_id} does not match active session" |
| 336 | )); |
| 337 | } |
| 338 | let base = active |
| 339 | .snapshot |
| 340 | .clone() |
| 341 | .ok_or_else(|| "lifecycle observation arrived before graph registration".to_string())?; |
| 342 | let Some(next) = apply_observation_to_snapshot(&base, session_id, external, observation)? |
| 343 | else { |
| 344 | return Ok(false); |
| 345 | }; |
| 346 | active.snapshot = Some(next); |
| 347 | active.pending_publish = true; |
| 348 | Ok(true) |
| 349 | } |
| 350 | |
| 351 | /// Compact graph-owned continuity injected after context compaction. |
| 352 | /// It contains identities and state only; no raw output or reasoning. |
| 353 | #[must_use] |
| 354 | pub fn active_operation_summary(&self, session_id: Option<&str>) -> Option<String> { |
| 355 | let active = lock_unpoisoned(&self.graph); |
| 356 | if let (Some(expected), Some(actual)) = (session_id, active.session_id.as_deref()) |
| 357 | && expected != actual |
| 358 | { |
| 359 | return None; |
| 360 | } |
| 361 | let graph = active.snapshot.as_ref()?; |
| 362 | let operations = graph |
| 363 | .nodes |
| 364 | .iter() |
| 365 | .filter(|node| { |
| 366 | node.kind == NodeKind::Operation |
| 367 | && (node.state.is_live() || node.state == NodeState::Stale) |
| 368 | }) |
| 369 | .take(24) |
| 370 | .collect::<Vec<_>>(); |
| 371 | if operations.is_empty() { |
| 372 | return None; |
| 373 | } |
| 374 | let mut out = format!( |
| 375 | "{ACTIVE_OPERATION_SUMMARY_START}\n## Active Work Graph Operations\n\nOwner records remain authoritative; reconcile before acting on a restored operation.\n" |
| 376 | ); |
| 377 | for node in operations { |
| 378 | let external = node |
| 379 | .binding |
| 380 | .as_ref() |
| 381 | .map_or("unbound", |binding| binding.external.as_str()); |
| 382 | out.push_str(&format!( |
| 383 | "- `{}` - {} - {}\n", |
| 384 | external, |
| 385 | operation_state_label(node.state), |
| 386 | prompt_safe_title(&node.title) |
| 387 | )); |
| 388 | } |
| 389 | out.push_str(ACTIVE_OPERATION_SUMMARY_END); |
| 390 | Some(out) |
| 391 | } |
| 392 | |
| 393 | /// Record one reasoning-effort configuration change as bounded graph |
| 394 | /// activity. The event contains typed tiers and a non-secret route |
| 395 | /// identity only; there is no field capable of carrying reasoning text. |
| 396 | /// When live operations exist, the most recently updated one receives the |
| 397 | /// historical link. Later terminalization does not invalidate that link. |
| 398 | #[allow(clippy::too_many_arguments)] |
| 399 | pub fn record_reasoning_effort_change( |
| 400 | &self, |
| 401 | session_id: Option<&str>, |
| 402 | requested: ReasoningEffortTier, |
| 403 | effective: ReasoningEffortTier, |
| 404 | provider_kind: codewhale_config::ProviderKind, |
| 405 | provider: &str, |
| 406 | endpoint_identity: Option<&str>, |
| 407 | model: Option<&str>, |
| 408 | ) -> Result<Option<WorkNodeId>, String> { |
| 409 | let todos = retry_lock(&self.todos, 100) |
| 410 | .ok_or_else(|| "To-do state is busy; effort change was not recorded".to_string())?; |
| 411 | let plan = retry_lock(&self.plan, 100) |
| 412 | .ok_or_else(|| "Plan state is busy; effort change was not recorded".to_string())?; |
| 413 | let mut active = lock_unpoisoned(&self.graph); |
| 414 | let session_id = resolved_session_id(&active, session_id); |
| 415 | let base = graph_for_update( |
| 416 | &mut active, |
| 417 | &session_id, |
| 418 | &plan.snapshot(), |
| 419 | &todos.snapshot(), |
| 420 | )?; |
| 421 | let operation = base |
| 422 | .nodes |
| 423 | .iter() |
| 424 | .filter(|node| node.kind == NodeKind::Operation && node.state.is_live()) |
| 425 | .max_by(|left, right| { |
| 426 | left.updated_at |
| 427 | .cmp(&right.updated_at) |
| 428 | .then_with(|| left.id.as_str().cmp(right.id.as_str())) |
| 429 | }) |
| 430 | .map(|node| node.id.clone()); |
| 431 | let now = now_ms(); |
| 432 | let mut graph = WorkGraph::from_snapshot(base); |
| 433 | graph |
| 434 | .apply( |
| 435 | WorkGraphChange::RecordActivity { |
| 436 | event: WorkActivityEvent::ReasoningEffortChanged { |
| 437 | requested, |
| 438 | effective, |
| 439 | provider_kind: Some(provider_kind), |
| 440 | provider: provider.to_string(), |
| 441 | endpoint_identity: endpoint_identity.map(str::to_string), |
| 442 | model: model.map(str::to_string), |
| 443 | ts: now, |
| 444 | operation: operation.clone(), |
| 445 | }, |
| 446 | }, |
| 447 | ChangeCtx { |
| 448 | session_id, |
| 449 | now, |
| 450 | idempotency_key: None, |
| 451 | }, |
| 452 | ) |
| 453 | .map_err(|err| format!("reasoning effort: {err}"))?; |
| 454 | let next = graph.into_snapshot(); |
| 455 | validate_combined(&next, &project_plan(&next), &project_todos(&next))?; |
| 456 | active.snapshot = Some(next); |
| 457 | active.pending_publish = true; |
| 458 | Ok(operation) |
| 459 | } |
| 460 | |
| 461 | /// Apply an `update_plan` payload through the graph and publish both |
| 462 | /// legacy projections only after the candidate graph validates. |
| 463 | pub async fn apply_plan_update( |
| 464 | &self, |
| 465 | session_id: &str, |
| 466 | tool: &str, |
| 467 | plan: &PlanSnapshot, |
| 468 | ) -> Result<PlanSnapshot, String> { |
| 469 | let todos_guard = self.todos.lock().await; |
| 470 | let plan_guard = self.plan.lock().await; |
| 471 | let mut active = lock_unpoisoned(&self.graph); |
| 472 | let base = graph_for_update( |
| 473 | &mut active, |
| 474 | session_id, |
| 475 | &plan_guard.snapshot(), |
| 476 | &todos_guard.snapshot(), |
| 477 | )?; |
| 478 | let next = update_plan_graph(base, session_id, tool, plan)?; |
| 479 | let derived_plan = project_plan(&next); |
| 480 | let derived_todos = project_todos(&next); |
| 481 | let next_plan = PlanState::from_snapshot(&derived_plan); |
| 482 | let next_todos = TodoList::from_snapshot(&derived_todos)?; |
| 483 | validate_combined(&next, &next_plan.snapshot(), &next_todos.snapshot())?; |
| 484 | active.snapshot = Some(next); |
| 485 | active.pending_publish = true; |
| 486 | Ok(derived_plan) |
| 487 | } |
| 488 | |
| 489 | /// Apply a legacy To-do/checklist payload through the graph and publish |
| 490 | /// both projections from the committed candidate. |
| 491 | pub async fn apply_todo_update( |
| 492 | &self, |
| 493 | session_id: &str, |
| 494 | tool: &str, |
| 495 | todos: &TodoListSnapshot, |
| 496 | ) -> Result<TodoListSnapshot, String> { |
| 497 | let todos_guard = self.todos.lock().await; |
| 498 | let plan_guard = self.plan.lock().await; |
| 499 | let mut active = lock_unpoisoned(&self.graph); |
| 500 | let base = graph_for_update( |
| 501 | &mut active, |
| 502 | session_id, |
| 503 | &plan_guard.snapshot(), |
| 504 | &todos_guard.snapshot(), |
| 505 | )?; |
| 506 | let next = update_todo_graph(base, session_id, tool, todos)?; |
| 507 | let derived_plan = project_plan(&next); |
| 508 | let derived_todos = project_todos(&next); |
| 509 | let next_plan = PlanState::from_snapshot(&derived_plan); |
| 510 | let next_todos = TodoList::from_snapshot(&derived_todos)?; |
| 511 | validate_combined(&next, &next_plan.snapshot(), &next_todos.snapshot())?; |
| 512 | active.snapshot = Some(next); |
| 513 | active.pending_publish = true; |
| 514 | Ok(derived_todos) |
| 515 | } |
| 516 | |
| 517 | /// Publish the latest validated legacy views after the caller has queued |
| 518 | /// their graph-backed session/checkpoint write. |
| 519 | #[cfg(any(test, feature = "test-support"))] |
| 520 | pub async fn publish_pending(&self) -> Result<bool, String> { |
| 521 | self.publish_pending_guarded(None).await |
| 522 | } |
| 523 | |
| 524 | pub async fn publish_pending_matching( |
| 525 | &self, |
| 526 | session_id: Option<&str>, |
| 527 | graph: Option<&WorkGraphSnapshot>, |
| 528 | ) -> Result<bool, String> { |
| 529 | self.publish_pending_guarded(Some((session_id, graph))) |
| 530 | .await |
| 531 | } |
| 532 | |
| 533 | async fn publish_pending_guarded( |
| 534 | &self, |
| 535 | expected: Option<(Option<&str>, Option<&WorkGraphSnapshot>)>, |
| 536 | ) -> Result<bool, String> { |
| 537 | let mut todos = self.todos.lock().await; |
| 538 | let mut plan = self.plan.lock().await; |
| 539 | let mut active = lock_unpoisoned(&self.graph); |
| 540 | if !active.pending_publish { |
| 541 | return Ok(false); |
| 542 | } |
| 543 | if expected.is_some_and(|(owner, graph)| { |
| 544 | active.session_id.as_deref() != Some(owner.unwrap_or("unsaved-work")) |
| 545 | || active.snapshot.as_ref() != graph |
| 546 | }) { |
| 547 | return Ok(false); |
| 548 | } |
| 549 | let graph = active |
| 550 | .snapshot |
| 551 | .as_ref() |
| 552 | .ok_or_else(|| "pending Work projection has no graph".to_string())?; |
| 553 | let derived_plan = project_plan(graph); |
| 554 | let derived_todos = project_todos(graph); |
| 555 | let next_plan = PlanState::from_snapshot(&derived_plan); |
| 556 | let next_todos = TodoList::from_snapshot(&derived_todos)?; |
| 557 | validate_combined(graph, &next_plan.snapshot(), &next_todos.snapshot())?; |
| 558 | *plan = next_plan; |
| 559 | *todos = next_todos; |
| 560 | active.pending_publish = false; |
| 561 | Ok(true) |
| 562 | } |
| 563 | |
| 564 | /// Synchronous counterpart for explicit save/rename/fork commands that |
| 565 | /// have already completed their atomic disk write. |
| 566 | pub fn publish_pending_sync_matching( |
| 567 | &self, |
| 568 | session_id: Option<&str>, |
| 569 | expected_graph: Option<&WorkGraphSnapshot>, |
| 570 | ) -> Result<bool, String> { |
| 571 | let mut todos = retry_lock(&self.todos, 100).ok_or_else(|| { |
| 572 | "To-do state is busy; saved Work views were not published".to_string() |
| 573 | })?; |
| 574 | let mut plan = retry_lock(&self.plan, 100) |
| 575 | .ok_or_else(|| "Plan state is busy; saved Work views were not published".to_string())?; |
| 576 | let mut active = lock_unpoisoned(&self.graph); |
| 577 | if !active.pending_publish { |
| 578 | return Ok(false); |
| 579 | } |
| 580 | if active.session_id.as_deref() != Some(session_id.unwrap_or("unsaved-work")) |
| 581 | || active.snapshot.as_ref() != expected_graph |
| 582 | { |
| 583 | return Ok(false); |
| 584 | } |
| 585 | let graph = active |
| 586 | .snapshot |
| 587 | .as_ref() |
| 588 | .ok_or_else(|| "pending Work projection has no graph".to_string())?; |
| 589 | let derived_plan = project_plan(graph); |
| 590 | let derived_todos = project_todos(graph); |
| 591 | let next_plan = PlanState::from_snapshot(&derived_plan); |
| 592 | let next_todos = TodoList::from_snapshot(&derived_todos)?; |
| 593 | validate_combined(graph, &next_plan.snapshot(), &next_todos.snapshot())?; |
| 594 | *plan = next_plan; |
| 595 | *todos = next_todos; |
| 596 | active.pending_publish = false; |
| 597 | Ok(true) |
| 598 | } |
| 599 | |
| 600 | #[must_use] |
| 601 | pub fn has_pending_publish(&self) -> bool { |
| 602 | lock_unpoisoned(&self.graph).pending_publish |
| 603 | } |
| 604 | |
| 605 | /// Latest graph-derived To-do view, including an unpublished transaction. |
| 606 | pub async fn current_todos(&self) -> Result<TodoListSnapshot, String> { |
| 607 | let projected = { |
| 608 | let active = lock_unpoisoned(&self.graph); |
| 609 | active.snapshot.as_ref().map(project_todos) |
| 610 | }; |
| 611 | if let Some(projected) = projected { |
| 612 | return Ok(projected); |
| 613 | } |
| 614 | Ok(self.todos.lock().await.snapshot()) |
| 615 | } |
| 616 | |
| 617 | /// Capture a persistence-ready graph plus fully populated old views. |
| 618 | /// Legacy-only in-memory state is imported once and normalized in place. |
| 619 | pub fn capture(&self, session_id: Option<&str>) -> Result<Option<WorkRuntimeSnapshot>, String> { |
| 620 | self.capture_with_retries(session_id, 100) |
| 621 | } |
| 622 | |
| 623 | /// Non-blocking capture for the render/event loop. |
| 624 | pub fn try_capture( |
| 625 | &self, |
| 626 | session_id: Option<&str>, |
| 627 | ) -> Result<Option<WorkRuntimeSnapshot>, String> { |
| 628 | self.capture_with_retries(session_id, 1) |
| 629 | } |
| 630 | |
| 631 | fn capture_with_retries( |
| 632 | &self, |
| 633 | session_id: Option<&str>, |
| 634 | retries: u32, |
| 635 | ) -> Result<Option<WorkRuntimeSnapshot>, String> { |
| 636 | let todos = retry_lock(&self.todos, retries) |
| 637 | .ok_or_else(|| "To-do state is busy; try saving again".to_string())?; |
| 638 | let plan = retry_lock(&self.plan, retries) |
| 639 | .ok_or_else(|| "Plan state is busy; try saving again".to_string())?; |
| 640 | let mut active = lock_unpoisoned(&self.graph); |
| 641 | let todos_snapshot = todos.snapshot(); |
| 642 | let plan_snapshot = plan.snapshot(); |
| 643 | if todos_snapshot.is_empty() |
| 644 | && plan_snapshot.is_empty() |
| 645 | && active |
| 646 | .snapshot |
| 647 | .as_ref() |
| 648 | .is_none_or(WorkGraphSnapshot::is_empty) |
| 649 | { |
| 650 | return Ok(None); |
| 651 | } |
| 652 | let had_graph = active.snapshot.is_some(); |
| 653 | let had_pending_publish = active.pending_publish; |
| 654 | let session_id = resolved_session_id(&active, session_id); |
| 655 | let graph = graph_for_update(&mut active, &session_id, &plan_snapshot, &todos_snapshot)?; |
| 656 | let derived_plan = project_plan(&graph); |
| 657 | let derived_todos = project_todos(&graph); |
| 658 | validate_combined(&graph, &derived_plan, &derived_todos)?; |
| 659 | if had_graph |
| 660 | && !had_pending_publish |
| 661 | && (derived_plan != plan_snapshot || derived_todos != todos_snapshot) |
| 662 | { |
| 663 | return Err("live Work Graph and legacy views disagree".to_string()); |
| 664 | } |
| 665 | active.snapshot = Some(graph.clone()); |
| 666 | if !had_graph { |
| 667 | active.pending_publish = true; |
| 668 | } |
| 669 | Ok(Some(WorkRuntimeSnapshot { |
| 670 | graph, |
| 671 | todos: derived_todos, |
| 672 | plan: derived_plan, |
| 673 | })) |
| 674 | } |
| 675 | |
| 676 | /// Validate and atomically activate persisted state. Sessions without a |
| 677 | /// graph are deterministically imported from their complete old views. |
| 678 | pub fn restore( |
| 679 | &self, |
| 680 | session_id: &str, |
| 681 | graph: Option<&WorkGraphSnapshot>, |
| 682 | todos: &TodoListSnapshot, |
| 683 | plan: &PlanSnapshot, |
| 684 | ) -> Result<Option<WorkRuntimeSnapshot>, String> { |
| 685 | self.restore_internal(session_id, graph, todos, plan, None) |
| 686 | } |
| 687 | |
| 688 | /// Restore a saved graph and reconcile workspace-scoped durable owners as |
| 689 | /// one candidate transaction. No live state changes until the restored |
| 690 | /// graph, owner observations, and both legacy projections all validate. |
| 691 | pub fn restore_with_workspace_owner_bindings( |
| 692 | &self, |
| 693 | session_id: &str, |
| 694 | workspace: &Path, |
| 695 | graph: Option<&WorkGraphSnapshot>, |
| 696 | todos: &TodoListSnapshot, |
| 697 | plan: &PlanSnapshot, |
| 698 | ) -> Result<Option<WorkRuntimeSnapshot>, String> { |
| 699 | self.restore_internal(session_id, graph, todos, plan, Some(workspace)) |
| 700 | } |
| 701 | |
| 702 | fn restore_internal( |
| 703 | &self, |
| 704 | session_id: &str, |
| 705 | graph: Option<&WorkGraphSnapshot>, |
| 706 | todos: &TodoListSnapshot, |
| 707 | plan: &PlanSnapshot, |
| 708 | workspace: Option<&Path>, |
| 709 | ) -> Result<Option<WorkRuntimeSnapshot>, String> { |
| 710 | let had_graph = graph.is_some(); |
| 711 | let graph = match graph { |
| 712 | Some(graph) => { |
| 713 | validate(graph).map_err(|err| err.to_string())?; |
| 714 | graph.clone() |
| 715 | } |
| 716 | None if todos.is_empty() && plan.is_empty() => WorkGraphSnapshot::new(), |
| 717 | None => import_legacy(session_id, plan, todos)?, |
| 718 | }; |
| 719 | let (mut graph, reconciled_ephemeral) = |
| 720 | mark_restored_ephemeral_operations_stale(graph, session_id)?; |
| 721 | let reconciled_workspace = if let Some(workspace) = workspace { |
| 722 | let (reconciled, changed) = reconcile_workspace_snapshot(graph, session_id, workspace)?; |
| 723 | graph = reconciled; |
| 724 | changed > 0 |
| 725 | } else { |
| 726 | false |
| 727 | }; |
| 728 | let derived_plan = project_plan(&graph); |
| 729 | let derived_todos = project_todos(&graph); |
| 730 | if graph.is_empty() { |
| 731 | if !todos.is_empty() || !plan.is_empty() { |
| 732 | return Err("empty Work Graph cannot carry non-empty legacy views".to_string()); |
| 733 | } |
| 734 | } else if graph.import_digest.is_some() && graph.compat.is_empty() { |
| 735 | return Err("imported Work Graph is missing compatibility projections".to_string()); |
| 736 | } |
| 737 | validate_combined(&graph, &derived_plan, &derived_todos)?; |
| 738 | if had_graph && (&derived_plan != plan || &derived_todos != todos) { |
| 739 | return Err("persisted Work Graph and legacy views disagree".to_string()); |
| 740 | } |
| 741 | let next_plan = PlanState::from_snapshot(&derived_plan); |
| 742 | let next_todos = TodoList::from_snapshot(&derived_todos)?; |
| 743 | let mut todos_guard = retry_lock(&self.todos, 100) |
| 744 | .ok_or_else(|| "To-do state is busy; session was not restored".to_string())?; |
| 745 | let mut plan_guard = retry_lock(&self.plan, 100) |
| 746 | .ok_or_else(|| "Plan state is busy; session was not restored".to_string())?; |
| 747 | let mut active = lock_unpoisoned(&self.graph); |
| 748 | *todos_guard = next_todos; |
| 749 | *plan_guard = next_plan; |
| 750 | active.session_id = Some(session_id.to_string()); |
| 751 | active.snapshot = Some(graph.clone()); |
| 752 | // A legacy load has already restored its complete old views, but its |
| 753 | // newly imported graph still needs one acknowledged graph-bearing |
| 754 | // write (and pre-import archive) before the migration is settled. |
| 755 | active.pending_publish = |
| 756 | reconciled_ephemeral || reconciled_workspace || (!had_graph && !graph.is_empty()); |
| 757 | if graph.is_empty() { |
| 758 | Ok(None) |
| 759 | } else { |
| 760 | Ok(Some(WorkRuntimeSnapshot { |
| 761 | graph, |
| 762 | todos: derived_todos, |
| 763 | plan: derived_plan, |
| 764 | })) |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | pub fn clear(&self, session_id: Option<&str>) -> bool { |
| 769 | let Some(mut todos) = retry_lock(&self.todos, 100) else { |
| 770 | return false; |
| 771 | }; |
| 772 | let Some(mut plan) = retry_lock(&self.plan, 100) else { |
| 773 | return false; |
| 774 | }; |
| 775 | let mut active = lock_unpoisoned(&self.graph); |
| 776 | todos.clear(); |
| 777 | *plan = PlanState::default(); |
| 778 | active.session_id = Some(resolved_session_id(&active, session_id)); |
| 779 | active.snapshot = Some(WorkGraphSnapshot::new()); |
| 780 | active.pending_publish = false; |
| 781 | true |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | fn apply_observation_to_snapshot( |
| 786 | base: &WorkGraphSnapshot, |
| 787 | session_id: &str, |
| 788 | external: &str, |
| 789 | observation: OperationObservation, |
| 790 | ) -> Result<Option<WorkGraphSnapshot>, String> { |
| 791 | let node = base |
| 792 | .nodes |
| 793 | .iter() |
| 794 | .find(|node| { |
| 795 | node.binding |
| 796 | .as_ref() |
| 797 | .is_some_and(|binding| binding.external == external) |
| 798 | }) |
| 799 | .ok_or_else(|| format!("operation binding {external} is not registered"))?; |
| 800 | let stale_owner_recovery = if let OperationObservation::OwnerReported { |
| 801 | state, seq, output, .. |
| 802 | } = &observation |
| 803 | && let Some(previous) = node |
| 804 | .binding |
| 805 | .as_ref() |
| 806 | .and_then(|binding| binding.last_observation.as_ref()) |
| 807 | { |
| 808 | if *seq < previous.seq { |
| 809 | return Err(format!( |
| 810 | "operation owner {external} sequence regressed from {} to {seq}", |
| 811 | previous.seq |
| 812 | )); |
| 813 | } |
| 814 | if *seq == previous.seq { |
| 815 | if node.state != NodeState::Stale { |
| 816 | return Ok(None); |
| 817 | } |
| 818 | if *state != previous.owner_state || *output != previous.output { |
| 819 | return Err(format!( |
| 820 | "operation owner {external} changed observation at sequence {seq}" |
| 821 | )); |
| 822 | } |
| 823 | true |
| 824 | } else { |
| 825 | false |
| 826 | } |
| 827 | } else { |
| 828 | false |
| 829 | }; |
| 830 | if matches!( |
| 831 | &observation, |
| 832 | OperationObservation::OwnerMissing { .. } | OperationObservation::OwnerUnreadable { .. } |
| 833 | ) && node.state == NodeState::Stale |
| 834 | { |
| 835 | return Ok(None); |
| 836 | } |
| 837 | let idempotency_key = match &observation { |
| 838 | OperationObservation::OwnerReported { .. } if stale_owner_recovery => None, |
| 839 | OperationObservation::OwnerReported { seq, .. } => Some(IdempotencyKey { |
| 840 | binding: BindingId::derive(session_id, &format!("binding:{external}")), |
| 841 | seq: *seq, |
| 842 | }), |
| 843 | OperationObservation::OwnerMissing { .. } |
| 844 | | OperationObservation::OwnerUnreadable { .. } |
| 845 | | OperationObservation::CancelUpdate { .. } => None, |
| 846 | }; |
| 847 | let (next, receipt) = super::reducer::apply( |
| 848 | base, |
| 849 | WorkGraphChange::ReconcileOperation { |
| 850 | node: node.id.clone(), |
| 851 | obs: observation, |
| 852 | }, |
| 853 | ChangeCtx { |
| 854 | session_id: session_id.to_string(), |
| 855 | now: now_ms(), |
| 856 | idempotency_key, |
| 857 | }, |
| 858 | ) |
| 859 | .map_err(|err| format!("runtime reconcile: {err}"))?; |
| 860 | Ok((!receipt.no_op).then_some(next)) |
| 861 | } |
| 862 | |
| 863 | fn reconcile_workspace_snapshot( |
| 864 | mut graph: WorkGraphSnapshot, |
| 865 | session_id: &str, |
| 866 | workspace: &Path, |
| 867 | ) -> Result<(WorkGraphSnapshot, usize), String> { |
| 868 | let candidates = graph |
| 869 | .nodes |
| 870 | .iter() |
| 871 | .filter(|node| node.state.is_live() || node.state == NodeState::Stale) |
| 872 | .filter_map(|node| node.binding.as_ref()) |
| 873 | .filter(|binding| binding.durable) |
| 874 | .map(|binding| binding.external.clone()) |
| 875 | .filter(|external| external.starts_with("fleet:") || external.starts_with("lane:")) |
| 876 | .collect::<Vec<_>>(); |
| 877 | if candidates.is_empty() { |
| 878 | return Ok((graph, 0)); |
| 879 | } |
| 880 | |
| 881 | let fleet = candidates |
| 882 | .iter() |
| 883 | .any(|external| external.starts_with("fleet:")) |
| 884 | .then(|| FleetLedger::open(workspace).and_then(|ledger| ledger.rebuild_state())); |
| 885 | if let Some(Err(err)) = fleet.as_ref() { |
| 886 | tracing::warn!( |
| 887 | workspace = %workspace.display(), |
| 888 | error = %err, |
| 889 | "Fleet owner store could not be replayed; restored bindings will be stale" |
| 890 | ); |
| 891 | } |
| 892 | let lanes = candidates |
| 893 | .iter() |
| 894 | .any(|external| external.starts_with("lane:")) |
| 895 | .then(LaneRegistry::open_default); |
| 896 | if let Some(Err(err)) = lanes.as_ref() { |
| 897 | tracing::warn!( |
| 898 | error = %err, |
| 899 | "Lane owner registry could not be opened; restored bindings will be stale" |
| 900 | ); |
| 901 | } |
| 902 | let observed_at = now_ms(); |
| 903 | let mut changed = 0usize; |
| 904 | for external in candidates { |
| 905 | let observation = if let Some(rest) = external.strip_prefix("fleet:") { |
| 906 | rest.split_once('/') |
| 907 | .and_then(|(run_id, task_id)| { |
| 908 | fleet |
| 909 | .as_ref() |
| 910 | .and_then(|state| state.as_ref().ok()) |
| 911 | .and_then(|state| state.tasks.get(&format!("{run_id}:{task_id}"))) |
| 912 | }) |
| 913 | .map(|record| fleet_task_owner_snapshot(record, observed_at).into_observation()) |
| 914 | .unwrap_or(OperationObservation::OwnerMissing { |
| 915 | checked_at: observed_at, |
| 916 | }) |
| 917 | } else if let Some(lane_id) = external.strip_prefix("lane:") { |
| 918 | observe_lane_owner(lanes.as_ref(), lane_id, observed_at) |
| 919 | } else { |
| 920 | continue; |
| 921 | }; |
| 922 | if let Some(next) = |
| 923 | apply_observation_to_snapshot(&graph, session_id, &external, observation)? |
| 924 | { |
| 925 | graph = next; |
| 926 | changed = changed.saturating_add(1); |
| 927 | } |
| 928 | } |
| 929 | Ok((graph, changed)) |
| 930 | } |
| 931 | |
| 932 | fn is_not_found_error(err: &anyhow::Error) -> bool { |
| 933 | err.chain().any(|cause| { |
| 934 | cause |
| 935 | .downcast_ref::<std::io::Error>() |
| 936 | .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::NotFound) |
| 937 | }) |
| 938 | } |
| 939 | |
| 940 | fn observe_lane_owner( |
| 941 | lanes: Option<&anyhow::Result<LaneRegistry>>, |
| 942 | lane_id: &str, |
| 943 | observed_at: Ts, |
| 944 | ) -> OperationObservation { |
| 945 | let Some(Ok(registry)) = lanes else { |
| 946 | return OperationObservation::OwnerMissing { |
| 947 | checked_at: observed_at, |
| 948 | }; |
| 949 | }; |
| 950 | match registry.load(lane_id) { |
| 951 | Ok(record) => lane_owner_snapshot(&record, observed_at).into_observation(), |
| 952 | Err(err) if is_not_found_error(&err) => OperationObservation::OwnerMissing { |
| 953 | checked_at: observed_at, |
| 954 | }, |
| 955 | Err(err) => { |
| 956 | tracing::warn!( |
| 957 | lane_id, |
| 958 | error = %err, |
| 959 | "Lane owner record could not be loaded; restored binding will be stale" |
| 960 | ); |
| 961 | OperationObservation::OwnerUnreadable { |
| 962 | checked_at: observed_at, |
| 963 | reason: err.to_string(), |
| 964 | } |
| 965 | } |
| 966 | } |
| 967 | } |
| 968 | |
| 969 | fn operation_parent( |
| 970 | graph: &mut WorkGraph, |
| 971 | session_id: &str, |
| 972 | source: &str, |
| 973 | ) -> Result<WorkNodeId, String> { |
| 974 | let snapshot = graph.snapshot(); |
| 975 | // Only a step the current plan or To-do projection still lists may adopt |
| 976 | // new work. Replacing a plan keeps the dropped steps as history (their |
| 977 | // ids are reused if the plan grows back, so they are not retired), but a |
| 978 | // step nobody can see must never become an operation's parent. |
| 979 | let projected_step = |node: &&WorkNode, state: NodeState| { |
| 980 | node.kind == NodeKind::PlanStep |
| 981 | && node.state == state |
| 982 | && (snapshot.compat.plan_order.contains(&node.id) |
| 983 | || snapshot |
| 984 | .compat |
| 985 | .todos |
| 986 | .iter() |
| 987 | .any(|binding| binding.node == node.id)) |
| 988 | }; |
| 989 | if let Some(parent) = snapshot |
| 990 | .nodes |
| 991 | .iter() |
| 992 | .find(|node| projected_step(node, NodeState::Active)) |
| 993 | .or_else(|| { |
| 994 | snapshot |
| 995 | .nodes |
| 996 | .iter() |
| 997 | .find(|node| projected_step(node, NodeState::Ready)) |
| 998 | }) |
| 999 | .or_else(|| { |
| 1000 | snapshot |
| 1001 | .nodes |
| 1002 | .iter() |
| 1003 | .find(|node| node.kind == NodeKind::Objective) |
| 1004 | }) |
| 1005 | { |
| 1006 | return Ok(parent.id.clone()); |
| 1007 | } |
| 1008 | |
| 1009 | let now = now_ms(); |
| 1010 | let id = WorkNodeId::derive(session_id, "objective:runtime-operations"); |
| 1011 | apply_change( |
| 1012 | graph, |
| 1013 | session_id, |
| 1014 | source, |
| 1015 | WorkGraphChange::AddNode { |
| 1016 | node: WorkNode { |
| 1017 | id: id.clone(), |
| 1018 | kind: NodeKind::Objective, |
| 1019 | title: "Runtime operations".to_string(), |
| 1020 | state: NodeState::Ready, |
| 1021 | acceptance: Vec::new(), |
| 1022 | binding: None, |
| 1023 | evidence: None, |
| 1024 | provenance: Provenance::RuntimeReconcile { |
| 1025 | source: source.to_string(), |
| 1026 | observed_at: now, |
| 1027 | }, |
| 1028 | created_at: now, |
| 1029 | updated_at: now, |
| 1030 | }, |
| 1031 | }, |
| 1032 | )?; |
| 1033 | Ok(id) |
| 1034 | } |
| 1035 | |
| 1036 | fn mark_restored_ephemeral_operations_stale( |
| 1037 | graph: WorkGraphSnapshot, |
| 1038 | session_id: &str, |
| 1039 | ) -> Result<(WorkGraphSnapshot, bool), String> { |
| 1040 | let candidates = graph |
| 1041 | .nodes |
| 1042 | .iter() |
| 1043 | .filter_map(|node| { |
| 1044 | let binding = node.binding.as_ref()?; |
| 1045 | (!binding.durable && node.state.is_live()).then(|| node.id.clone()) |
| 1046 | }) |
| 1047 | .collect::<Vec<_>>(); |
| 1048 | if candidates.is_empty() { |
| 1049 | return Ok((graph, false)); |
| 1050 | } |
| 1051 | let mut graph = WorkGraph::from_snapshot(graph); |
| 1052 | for node in candidates { |
| 1053 | graph |
| 1054 | .apply( |
| 1055 | WorkGraphChange::ReconcileOperation { |
| 1056 | node, |
| 1057 | obs: OperationObservation::OwnerMissing { |
| 1058 | checked_at: now_ms(), |
| 1059 | }, |
| 1060 | }, |
| 1061 | ChangeCtx { |
| 1062 | session_id: session_id.to_string(), |
| 1063 | now: now_ms(), |
| 1064 | idempotency_key: None, |
| 1065 | }, |
| 1066 | ) |
| 1067 | .map_err(|err| format!("restart reconcile: {err}"))?; |
| 1068 | } |
| 1069 | Ok((graph.into_snapshot(), true)) |
| 1070 | } |
| 1071 | |
| 1072 | fn bounded_operation_title(title: &str) -> String { |
| 1073 | let normalized = title.split_whitespace().collect::<Vec<_>>().join(" "); |
| 1074 | let mut chars = normalized.chars(); |
| 1075 | let bounded = chars.by_ref().take(180).collect::<String>(); |
| 1076 | if chars.next().is_some() { |
| 1077 | format!("{bounded}...") |
| 1078 | } else if bounded.is_empty() { |
| 1079 | "Runtime operation".to_string() |
| 1080 | } else { |
| 1081 | bounded |
| 1082 | } |
| 1083 | } |
| 1084 | |
| 1085 | fn prompt_safe_title(title: &str) -> String { |
| 1086 | bounded_operation_title(&title.replace('`', "'")) |
| 1087 | } |
| 1088 | |
| 1089 | const fn operation_state_label(state: NodeState) -> &'static str { |
| 1090 | match state { |
| 1091 | NodeState::Ready => "ready", |
| 1092 | NodeState::Initializing => "initializing", |
| 1093 | NodeState::Active => "running", |
| 1094 | NodeState::Waiting => "waiting", |
| 1095 | NodeState::Blocked => "blocked", |
| 1096 | NodeState::Completed => "completed", |
| 1097 | NodeState::Verified => "verified", |
| 1098 | NodeState::Stale => "stale", |
| 1099 | NodeState::Superseded => "superseded", |
| 1100 | NodeState::Cancelled => "cancelled", |
| 1101 | NodeState::Failed => "failed", |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | fn graph_for_update( |
| 1106 | active: &mut ActiveGraph, |
| 1107 | session_id: &str, |
| 1108 | plan: &PlanSnapshot, |
| 1109 | todos: &TodoListSnapshot, |
| 1110 | ) -> Result<WorkGraphSnapshot, String> { |
| 1111 | match active.session_id.as_deref() { |
| 1112 | // App session transitions are already blocked while runtime work is |
| 1113 | // active. Rebind the authority namespace without re-keying graph IDs |
| 1114 | // so save-as/fork/new-session flows keep one coherent snapshot. |
| 1115 | Some(active_id) if active_id != session_id => { |
| 1116 | active.session_id = Some(session_id.to_string()); |
| 1117 | } |
| 1118 | None => active.session_id = Some(session_id.to_string()), |
| 1119 | Some(_) => {} |
| 1120 | } |
| 1121 | if let Some(snapshot) = active.snapshot.as_ref() { |
| 1122 | validate(snapshot).map_err(|err| err.to_string())?; |
| 1123 | return Ok(snapshot.clone()); |
| 1124 | } |
| 1125 | let graph = if plan.is_empty() && todos.is_empty() { |
| 1126 | WorkGraphSnapshot::new() |
| 1127 | } else { |
| 1128 | import_legacy(session_id, plan, todos)? |
| 1129 | }; |
| 1130 | active.snapshot = Some(graph.clone()); |
| 1131 | Ok(graph) |
| 1132 | } |
| 1133 | |
| 1134 | fn update_plan_graph( |
| 1135 | base: WorkGraphSnapshot, |
| 1136 | session_id: &str, |
| 1137 | tool: &str, |
| 1138 | plan: &PlanSnapshot, |
| 1139 | ) -> Result<WorkGraphSnapshot, String> { |
| 1140 | let mut graph = WorkGraph::from_snapshot(base); |
| 1141 | let objective = ensure_objective(&mut graph, session_id, tool, plan)?; |
| 1142 | let desired_active_alias = plan.items.iter().enumerate().find_map(|(index, item)| { |
| 1143 | (item.status == StepStatus::InProgress) |
| 1144 | .then(|| graph.snapshot().compat.plan_order.get(index).cloned()) |
| 1145 | .flatten() |
| 1146 | .filter(|node| { |
| 1147 | graph |
| 1148 | .snapshot() |
| 1149 | .compat |
| 1150 | .todos |
| 1151 | .iter() |
| 1152 | .any(|binding| &binding.node == node) |
| 1153 | }) |
| 1154 | }); |
| 1155 | if desired_active_alias.is_some() { |
| 1156 | deactivate_projected_todos(&mut graph, session_id, tool)?; |
| 1157 | } |
| 1158 | |
| 1159 | let mut order = Vec::with_capacity(plan.items.len()); |
| 1160 | for (index, item) in plan.items.iter().enumerate() { |
| 1161 | let id = graph |
| 1162 | .snapshot() |
| 1163 | .compat |
| 1164 | .plan_order |
| 1165 | .get(index) |
| 1166 | .cloned() |
| 1167 | .unwrap_or_else(|| WorkNodeId::derive(session_id, &format!("plan:{index}"))); |
| 1168 | let provenance = tool_provenance(graph.snapshot(), tool); |
| 1169 | upsert_node( |
| 1170 | &mut graph, |
| 1171 | session_id, |
| 1172 | tool, |
| 1173 | WorkNode { |
| 1174 | id: id.clone(), |
| 1175 | kind: NodeKind::PlanStep, |
| 1176 | title: item.step.trim().to_string(), |
| 1177 | state: plan_node_state(&item.status), |
| 1178 | acceptance: Vec::new(), |
| 1179 | binding: None, |
| 1180 | evidence: None, |
| 1181 | provenance, |
| 1182 | created_at: now_ms(), |
| 1183 | updated_at: now_ms(), |
| 1184 | }, |
| 1185 | )?; |
| 1186 | ensure_contains(&mut graph, session_id, tool, &objective, &id)?; |
| 1187 | order.push(id); |
| 1188 | } |
| 1189 | let mut compat = graph.snapshot().compat.clone(); |
| 1190 | compat.plan = CompatPlanMetadata::from_plan_snapshot(plan); |
| 1191 | compat.plan_order = order; |
| 1192 | compat.todos.retain(|binding| { |
| 1193 | binding.plan_index.is_none_or(|index| { |
| 1194 | usize::try_from(index) |
| 1195 | .ok() |
| 1196 | .is_some_and(|i| i < plan.items.len()) |
| 1197 | }) |
| 1198 | }); |
| 1199 | for binding in &mut compat.todos { |
| 1200 | if let Some(index) = binding.plan_index |
| 1201 | && let Some(node) = compat |
| 1202 | .plan_order |
| 1203 | .get(usize::try_from(index).unwrap_or(usize::MAX)) |
| 1204 | { |
| 1205 | binding.node.clone_from(node); |
| 1206 | } |
| 1207 | } |
| 1208 | apply_change( |
| 1209 | &mut graph, |
| 1210 | session_id, |
| 1211 | tool, |
| 1212 | WorkGraphChange::ReplaceCompatProjection { compat }, |
| 1213 | )?; |
| 1214 | Ok(graph.into_snapshot()) |
| 1215 | } |
| 1216 | |
| 1217 | fn update_todo_graph( |
| 1218 | base: WorkGraphSnapshot, |
| 1219 | session_id: &str, |
| 1220 | tool: &str, |
| 1221 | todos: &TodoListSnapshot, |
| 1222 | ) -> Result<WorkGraphSnapshot, String> { |
| 1223 | let mut graph = WorkGraph::from_snapshot(base); |
| 1224 | deactivate_projected_todos(&mut graph, session_id, tool)?; |
| 1225 | let current_plan = project_plan(graph.snapshot()); |
| 1226 | let objective = ensure_objective(&mut graph, session_id, tool, ¤t_plan)?; |
| 1227 | let plan_order = graph.snapshot().compat.plan_order.clone(); |
| 1228 | let mut bindings = Vec::with_capacity(todos.items.len()); |
| 1229 | for item in &todos.items { |
| 1230 | let title = item.content.trim().to_string(); |
| 1231 | let alias = graph |
| 1232 | .snapshot() |
| 1233 | .compat |
| 1234 | .todos |
| 1235 | .iter() |
| 1236 | .find(|binding| binding.legacy_id == item.id) |
| 1237 | .and_then(|binding| { |
| 1238 | binding |
| 1239 | .plan_index |
| 1240 | .map(|index| (index, binding.node.clone())) |
| 1241 | }) |
| 1242 | .filter(|(index, node)| { |
| 1243 | plan_order.get(usize::try_from(*index).unwrap_or(usize::MAX)) == Some(node) |
| 1244 | }); |
| 1245 | let (node, plan_index) = if let Some((index, node)) = alias { |
| 1246 | patch_existing_node( |
| 1247 | &mut graph, |
| 1248 | session_id, |
| 1249 | tool, |
| 1250 | &node, |
| 1251 | title, |
| 1252 | todo_node_state(item.status), |
| 1253 | )?; |
| 1254 | (node, Some(index)) |
| 1255 | } else { |
| 1256 | let node = graph |
| 1257 | .snapshot() |
| 1258 | .compat |
| 1259 | .todos |
| 1260 | .iter() |
| 1261 | .find(|binding| binding.legacy_id == item.id && binding.plan_index.is_none()) |
| 1262 | .map(|binding| binding.node.clone()) |
| 1263 | .unwrap_or_else(|| WorkNodeId::derive(session_id, &format!("todo:{}", item.id))); |
| 1264 | let desired = todo_node_state(item.status); |
| 1265 | let provenance = tool_provenance(graph.snapshot(), tool); |
| 1266 | upsert_node( |
| 1267 | &mut graph, |
| 1268 | session_id, |
| 1269 | tool, |
| 1270 | WorkNode { |
| 1271 | id: node.clone(), |
| 1272 | kind: NodeKind::PlanStep, |
| 1273 | title, |
| 1274 | state: if desired == NodeState::Active { |
| 1275 | NodeState::Ready |
| 1276 | } else { |
| 1277 | desired |
| 1278 | }, |
| 1279 | acceptance: Vec::new(), |
| 1280 | binding: None, |
| 1281 | evidence: None, |
| 1282 | provenance, |
| 1283 | created_at: now_ms(), |
| 1284 | updated_at: now_ms(), |
| 1285 | }, |
| 1286 | )?; |
| 1287 | ensure_contains(&mut graph, session_id, tool, &objective, &node)?; |
| 1288 | if desired == NodeState::Active { |
| 1289 | let clean_title = graph |
| 1290 | .snapshot() |
| 1291 | .node(&node) |
| 1292 | .map(|node| node.title.clone()) |
| 1293 | .ok_or_else(|| format!("node {node} not found after insert"))?; |
| 1294 | patch_existing_node(&mut graph, session_id, tool, &node, clean_title, desired)?; |
| 1295 | } |
| 1296 | (node, None) |
| 1297 | }; |
| 1298 | bindings.push(CompatTodoBinding { |
| 1299 | legacy_id: item.id, |
| 1300 | node, |
| 1301 | plan_index, |
| 1302 | }); |
| 1303 | } |
| 1304 | let mut compat = graph.snapshot().compat.clone(); |
| 1305 | compat.todos = bindings; |
| 1306 | apply_change( |
| 1307 | &mut graph, |
| 1308 | session_id, |
| 1309 | tool, |
| 1310 | WorkGraphChange::ReplaceCompatProjection { compat }, |
| 1311 | )?; |
| 1312 | Ok(graph.into_snapshot()) |
| 1313 | } |
| 1314 | |
| 1315 | fn ensure_objective( |
| 1316 | graph: &mut WorkGraph, |
| 1317 | session_id: &str, |
| 1318 | tool: &str, |
| 1319 | plan: &PlanSnapshot, |
| 1320 | ) -> Result<WorkNodeId, String> { |
| 1321 | let id = graph |
| 1322 | .snapshot() |
| 1323 | .nodes |
| 1324 | .iter() |
| 1325 | .find(|node| node.kind == NodeKind::Objective) |
| 1326 | .map(|node| node.id.clone()) |
| 1327 | .unwrap_or_else(|| WorkNodeId::derive(session_id, "objective")); |
| 1328 | let title = plan |
| 1329 | .objective |
| 1330 | .as_deref() |
| 1331 | .or(plan.title.as_deref()) |
| 1332 | .unwrap_or("Session work") |
| 1333 | .to_string(); |
| 1334 | upsert_node( |
| 1335 | graph, |
| 1336 | session_id, |
| 1337 | tool, |
| 1338 | WorkNode { |
| 1339 | id: id.clone(), |
| 1340 | kind: NodeKind::Objective, |
| 1341 | title, |
| 1342 | state: NodeState::Ready, |
| 1343 | acceptance: Vec::new(), |
| 1344 | binding: None, |
| 1345 | evidence: None, |
| 1346 | provenance: tool_provenance(graph.snapshot(), tool), |
| 1347 | created_at: now_ms(), |
| 1348 | updated_at: now_ms(), |
| 1349 | }, |
| 1350 | )?; |
| 1351 | Ok(id) |
| 1352 | } |
| 1353 | |
| 1354 | fn upsert_node( |
| 1355 | graph: &mut WorkGraph, |
| 1356 | session_id: &str, |
| 1357 | tool: &str, |
| 1358 | node: WorkNode, |
| 1359 | ) -> Result<(), String> { |
| 1360 | if let Some(existing) = graph.snapshot().node(&node.id) { |
| 1361 | if existing.kind != node.kind { |
| 1362 | return Err(format!("node {} changed kind", node.id)); |
| 1363 | } |
| 1364 | patch_existing_node(graph, session_id, tool, &node.id, node.title, node.state) |
| 1365 | } else { |
| 1366 | apply_change(graph, session_id, tool, WorkGraphChange::AddNode { node }) |
| 1367 | } |
| 1368 | } |
| 1369 | |
| 1370 | fn patch_existing_node( |
| 1371 | graph: &mut WorkGraph, |
| 1372 | session_id: &str, |
| 1373 | tool: &str, |
| 1374 | id: &WorkNodeId, |
| 1375 | title: String, |
| 1376 | state: NodeState, |
| 1377 | ) -> Result<(), String> { |
| 1378 | let current = graph |
| 1379 | .snapshot() |
| 1380 | .node(id) |
| 1381 | .ok_or_else(|| format!("node {id} not found"))?; |
| 1382 | if current.title == title && current.state == state { |
| 1383 | // Semantic no-ops must stay no-ops. In particular, terminal nodes are |
| 1384 | // immutable, so refreshing another To-do item must not try to rewrite |
| 1385 | // a settled sibling merely to stamp newer tool provenance. |
| 1386 | return Ok(()); |
| 1387 | } |
| 1388 | let provenance = tool_provenance(graph.snapshot(), tool); |
| 1389 | apply_change( |
| 1390 | graph, |
| 1391 | session_id, |
| 1392 | tool, |
| 1393 | WorkGraphChange::UpdateNode { |
| 1394 | id: id.clone(), |
| 1395 | patch: WorkNodePatch { |
| 1396 | title: Some(title), |
| 1397 | state: Some(state), |
| 1398 | provenance: Some(provenance), |
| 1399 | ..WorkNodePatch::default() |
| 1400 | }, |
| 1401 | }, |
| 1402 | ) |
| 1403 | } |
| 1404 | |
| 1405 | fn ensure_contains( |
| 1406 | graph: &mut WorkGraph, |
| 1407 | session_id: &str, |
| 1408 | tool: &str, |
| 1409 | parent: &WorkNodeId, |
| 1410 | child: &WorkNodeId, |
| 1411 | ) -> Result<(), String> { |
| 1412 | let id = WorkEdgeId::derive( |
| 1413 | session_id, |
| 1414 | &format!("contains:{}:{}", parent.as_str(), child.as_str()), |
| 1415 | ); |
| 1416 | if graph.snapshot().edge(&id).is_some() { |
| 1417 | return Ok(()); |
| 1418 | } |
| 1419 | apply_change( |
| 1420 | graph, |
| 1421 | session_id, |
| 1422 | tool, |
| 1423 | WorkGraphChange::AddEdge { |
| 1424 | edge: WorkEdge { |
| 1425 | id, |
| 1426 | kind: EdgeKind::Contains, |
| 1427 | from: parent.clone(), |
| 1428 | to: child.clone(), |
| 1429 | }, |
| 1430 | }, |
| 1431 | ) |
| 1432 | } |
| 1433 | |
| 1434 | fn deactivate_projected_todos( |
| 1435 | graph: &mut WorkGraph, |
| 1436 | session_id: &str, |
| 1437 | tool: &str, |
| 1438 | ) -> Result<(), String> { |
| 1439 | let active = graph |
| 1440 | .snapshot() |
| 1441 | .compat |
| 1442 | .todos |
| 1443 | .iter() |
| 1444 | .filter_map(|binding| { |
| 1445 | graph |
| 1446 | .snapshot() |
| 1447 | .node(&binding.node) |
| 1448 | .filter(|node| node.state == NodeState::Active) |
| 1449 | .map(|node| (node.id.clone(), node.title.clone())) |
| 1450 | }) |
| 1451 | .collect::<Vec<_>>(); |
| 1452 | for (id, title) in active { |
| 1453 | patch_existing_node(graph, session_id, tool, &id, title, NodeState::Ready)?; |
| 1454 | } |
| 1455 | Ok(()) |
| 1456 | } |
| 1457 | |
| 1458 | fn apply_change( |
| 1459 | graph: &mut WorkGraph, |
| 1460 | session_id: &str, |
| 1461 | tool: &str, |
| 1462 | change: WorkGraphChange, |
| 1463 | ) -> Result<(), String> { |
| 1464 | graph |
| 1465 | .apply( |
| 1466 | change, |
| 1467 | ChangeCtx { |
| 1468 | session_id: session_id.to_string(), |
| 1469 | now: now_ms(), |
| 1470 | idempotency_key: None, |
| 1471 | }, |
| 1472 | ) |
| 1473 | .map(|_| ()) |
| 1474 | .map_err(|err| format!("{tool}: {err}")) |
| 1475 | } |
| 1476 | |
| 1477 | fn validate_combined( |
| 1478 | graph: &WorkGraphSnapshot, |
| 1479 | plan: &PlanSnapshot, |
| 1480 | todos: &TodoListSnapshot, |
| 1481 | ) -> Result<(), String> { |
| 1482 | validate(graph).map_err(|err| err.to_string())?; |
| 1483 | if &project_plan(graph) != plan { |
| 1484 | return Err("Work Graph Plan projection is inconsistent".to_string()); |
| 1485 | } |
| 1486 | if &project_todos(graph) != todos { |
| 1487 | return Err("Work Graph To-do projection is inconsistent".to_string()); |
| 1488 | } |
| 1489 | TodoList::from_snapshot(todos)?; |
| 1490 | Ok(()) |
| 1491 | } |
| 1492 | |
| 1493 | fn tool_provenance(snapshot: &WorkGraphSnapshot, tool: &str) -> Provenance { |
| 1494 | Provenance::ToolUpdate { |
| 1495 | tool: tool.to_string(), |
| 1496 | call_id: format!("{tool}:{}", snapshot.revision.saturating_add(1)), |
| 1497 | } |
| 1498 | } |
| 1499 | |
| 1500 | fn plan_node_state(status: &StepStatus) -> NodeState { |
| 1501 | match status { |
| 1502 | StepStatus::Pending => NodeState::Ready, |
| 1503 | StepStatus::InProgress => NodeState::Active, |
| 1504 | StepStatus::Completed => NodeState::Completed, |
| 1505 | } |
| 1506 | } |
| 1507 | |
| 1508 | fn todo_node_state(status: TodoStatus) -> NodeState { |
| 1509 | match status { |
| 1510 | TodoStatus::Pending => NodeState::Ready, |
| 1511 | TodoStatus::InProgress => NodeState::Active, |
| 1512 | TodoStatus::Completed => NodeState::Completed, |
| 1513 | TodoStatus::Cancelled => NodeState::Cancelled, |
| 1514 | } |
| 1515 | } |
| 1516 | |
| 1517 | fn resolved_session_id(active: &ActiveGraph, requested: Option<&str>) -> String { |
| 1518 | requested |
| 1519 | .map(str::to_string) |
| 1520 | .or_else(|| active.session_id.clone()) |
| 1521 | .unwrap_or_else(|| "unsaved-work".to_string()) |
| 1522 | } |
| 1523 | |
| 1524 | fn now_ms() -> i64 { |
| 1525 | chrono::Utc::now().timestamp_millis() |
| 1526 | } |
| 1527 | |
| 1528 | fn lock_unpoisoned<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> { |
| 1529 | mutex |
| 1530 | .lock() |
| 1531 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 1532 | } |
| 1533 | |
| 1534 | // These callers are synchronous methods reached from tool code on the Tokio |
| 1535 | // runtime, so this contention retry must not park the worker with |
| 1536 | // `thread::sleep`. `yield_now` hands the thread to the holder long enough for |
| 1537 | // its microsecond-scale critical section; if the lock is still contended the |
| 1538 | // caller surfaces the existing "state is busy" error instead of stalling. |
| 1539 | fn retry_lock<T>( |
| 1540 | mutex: &tokio::sync::Mutex<T>, |
| 1541 | retries: u32, |
| 1542 | ) -> Option<tokio::sync::MutexGuard<'_, T>> { |
| 1543 | for _ in 0..retries { |
| 1544 | if let Ok(guard) = mutex.try_lock() { |
| 1545 | return Some(guard); |
| 1546 | } |
| 1547 | std::thread::yield_now(); |
| 1548 | } |
| 1549 | None |
| 1550 | } |
| 1551 | |
| 1552 | #[cfg(test)] |
| 1553 | mod tests { |
| 1554 | use super::*; |
| 1555 | use crate::tools::plan::PlanItemArg; |
| 1556 | use crate::work_graph::{EvidenceKind, EvidenceRef, OwnerState}; |
| 1557 | |
| 1558 | #[test] |
| 1559 | fn operation_lifecycle_is_registered_idempotent_and_receipt_only() { |
| 1560 | let runtime = new_shared_work_runtime( |
| 1561 | crate::tools::todo::new_shared_todo_list(), |
| 1562 | crate::tools::plan::new_shared_plan_state(), |
| 1563 | ); |
| 1564 | let intent = OperationIntent::new( |
| 1565 | "shell:shell_test", |
| 1566 | "silent `owner` command", |
| 1567 | false, |
| 1568 | "exec_shell", |
| 1569 | "shell_test", |
| 1570 | ); |
| 1571 | let node_id = runtime |
| 1572 | .register_operation("session", intent.clone()) |
| 1573 | .expect("register before spawn"); |
| 1574 | assert_eq!( |
| 1575 | runtime.register_operation("session", intent), |
| 1576 | Ok(node_id.clone()), |
| 1577 | "repeat spawn intent must not duplicate the operation" |
| 1578 | ); |
| 1579 | let initialized = runtime |
| 1580 | .capture(Some("session")) |
| 1581 | .expect("capture") |
| 1582 | .expect("graph"); |
| 1583 | let node = initialized.graph.node(&node_id).expect("operation node"); |
| 1584 | assert_eq!(node.state, NodeState::Initializing); |
| 1585 | assert!( |
| 1586 | initialized |
| 1587 | .graph |
| 1588 | .edges |
| 1589 | .iter() |
| 1590 | .any(|edge| { edge.kind == EdgeKind::Contains && edge.to == node_id }) |
| 1591 | ); |
| 1592 | |
| 1593 | let output = EvidenceRef::new( |
| 1594 | EvidenceKind::Receipt { |
| 1595 | owner: "shell".to_string(), |
| 1596 | }, |
| 1597 | "shell:shell_test:output", |
| 1598 | Some(4_096), |
| 1599 | true, |
| 1600 | ) |
| 1601 | .expect("safe logical receipt"); |
| 1602 | assert_eq!( |
| 1603 | runtime.reconcile_operation( |
| 1604 | "session", |
| 1605 | OperationOwnerSnapshot::new("shell:shell_test", OwnerState::Running, 7, 10,) |
| 1606 | .with_output(output), |
| 1607 | ), |
| 1608 | Ok(true) |
| 1609 | ); |
| 1610 | assert_eq!( |
| 1611 | runtime.reconcile_operation( |
| 1612 | "session", |
| 1613 | OperationOwnerSnapshot::new("shell:shell_test", OwnerState::Completed, 7, 11,), |
| 1614 | ), |
| 1615 | Ok(false), |
| 1616 | "the same binding sequence is an idempotent no-op" |
| 1617 | ); |
| 1618 | assert!( |
| 1619 | runtime |
| 1620 | .reconcile_operation( |
| 1621 | "session", |
| 1622 | OperationOwnerSnapshot::new("shell:unknown", OwnerState::Running, 1, 12,), |
| 1623 | ) |
| 1624 | .expect_err("unknown owner must not materialize after spawn") |
| 1625 | .contains("not registered") |
| 1626 | ); |
| 1627 | let running = runtime |
| 1628 | .capture(Some("session")) |
| 1629 | .expect("capture running") |
| 1630 | .expect("graph"); |
| 1631 | let binding = running |
| 1632 | .graph |
| 1633 | .node(&node_id) |
| 1634 | .and_then(|node| node.binding.as_ref()) |
| 1635 | .expect("binding"); |
| 1636 | assert_eq!( |
| 1637 | running.graph.node(&node_id).map(|node| node.state), |
| 1638 | Some(NodeState::Active) |
| 1639 | ); |
| 1640 | assert_eq!( |
| 1641 | binding |
| 1642 | .last_observation |
| 1643 | .as_ref() |
| 1644 | .and_then(|obs| obs.output.as_ref()) |
| 1645 | .and_then(EvidenceRef::raw_bytes), |
| 1646 | Some(4_096) |
| 1647 | ); |
| 1648 | let summary = runtime |
| 1649 | .active_operation_summary(Some("session")) |
| 1650 | .expect("compaction re-anchor"); |
| 1651 | assert!(summary.contains("shell:shell_test"), "{summary}"); |
| 1652 | assert!(summary.contains("silent 'owner' command"), "{summary}"); |
| 1653 | assert!(!summary.contains("4,096"), "{summary}"); |
| 1654 | |
| 1655 | assert_eq!( |
| 1656 | runtime.record_reasoning_effort_change( |
| 1657 | Some("session"), |
| 1658 | ReasoningEffortTier::Low, |
| 1659 | ReasoningEffortTier::High, |
| 1660 | codewhale_config::ProviderKind::Moonshot, |
| 1661 | "moonshot", |
| 1662 | Some(codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL), |
| 1663 | Some("kimi-k2.5"), |
| 1664 | ), |
| 1665 | Ok(Some(node_id.clone())) |
| 1666 | ); |
| 1667 | let activity = runtime |
| 1668 | .capture(Some("session")) |
| 1669 | .expect("capture effort activity") |
| 1670 | .expect("graph") |
| 1671 | .graph |
| 1672 | .activities |
| 1673 | .last() |
| 1674 | .cloned() |
| 1675 | .expect("effort activity"); |
| 1676 | let ts = match &activity { |
| 1677 | WorkActivityEvent::ReasoningEffortChanged { ts, .. } => *ts, |
| 1678 | }; |
| 1679 | assert_eq!( |
| 1680 | activity, |
| 1681 | WorkActivityEvent::ReasoningEffortChanged { |
| 1682 | requested: ReasoningEffortTier::Low, |
| 1683 | effective: ReasoningEffortTier::High, |
| 1684 | provider_kind: Some(codewhale_config::ProviderKind::Moonshot), |
| 1685 | provider: "moonshot".to_string(), |
| 1686 | endpoint_identity: Some( |
| 1687 | codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL.to_string() |
| 1688 | ), |
| 1689 | model: Some("kimi-k2.5".to_string()), |
| 1690 | ts, |
| 1691 | operation: Some(node_id.clone()), |
| 1692 | } |
| 1693 | ); |
| 1694 | |
| 1695 | runtime |
| 1696 | .record_operation_approval( |
| 1697 | "session", |
| 1698 | "shell:shell_test", |
| 1699 | "operate-verification:shell_test", |
| 1700 | "exec_shell", |
| 1701 | "approval_test", |
| 1702 | ) |
| 1703 | .expect("approval provenance"); |
| 1704 | let approved = runtime |
| 1705 | .capture(Some("session")) |
| 1706 | .expect("capture approval") |
| 1707 | .expect("graph"); |
| 1708 | assert!( |
| 1709 | approved |
| 1710 | .graph |
| 1711 | .nodes |
| 1712 | .iter() |
| 1713 | .any(|node| node.kind == NodeKind::Approval) |
| 1714 | ); |
| 1715 | assert!( |
| 1716 | approved |
| 1717 | .graph |
| 1718 | .edges |
| 1719 | .iter() |
| 1720 | .any(|edge| edge.kind == EdgeKind::RequiresApproval) |
| 1721 | ); |
| 1722 | |
| 1723 | runtime |
| 1724 | .reconcile_operation( |
| 1725 | "session", |
| 1726 | OperationOwnerSnapshot::new("shell:shell_test", OwnerState::Completed, 8, 13), |
| 1727 | ) |
| 1728 | .expect("terminal owner report"); |
| 1729 | runtime |
| 1730 | .reconcile_observation( |
| 1731 | "session", |
| 1732 | "shell:shell_test", |
| 1733 | OperationObservation::CancelUpdate { |
| 1734 | outcome: super::super::CancelOutcome::AlreadyFinished, |
| 1735 | at: 14, |
| 1736 | }, |
| 1737 | ) |
| 1738 | .expect("already-finished cancellation receipt"); |
| 1739 | assert_eq!( |
| 1740 | runtime |
| 1741 | .capture(Some("session")) |
| 1742 | .expect("capture terminal") |
| 1743 | .expect("graph") |
| 1744 | .graph |
| 1745 | .node(&node_id) |
| 1746 | .map(|node| node.state), |
| 1747 | Some(NodeState::Completed), |
| 1748 | "already-finished cancellation must not rewrite owner state" |
| 1749 | ); |
| 1750 | } |
| 1751 | |
| 1752 | #[test] |
| 1753 | fn restore_stales_only_live_ephemeral_operations() { |
| 1754 | let runtime = new_shared_work_runtime( |
| 1755 | crate::tools::todo::new_shared_todo_list(), |
| 1756 | crate::tools::plan::new_shared_plan_state(), |
| 1757 | ); |
| 1758 | for id in ["shell:live", "shell:done"] { |
| 1759 | runtime |
| 1760 | .register_operation( |
| 1761 | "session", |
| 1762 | OperationIntent::new(id, id, false, "exec_shell", id), |
| 1763 | ) |
| 1764 | .expect("register shell"); |
| 1765 | } |
| 1766 | runtime |
| 1767 | .reconcile_operation( |
| 1768 | "session", |
| 1769 | OperationOwnerSnapshot::new("shell:live", OwnerState::Running, 1, 1), |
| 1770 | ) |
| 1771 | .expect("live shell"); |
| 1772 | runtime |
| 1773 | .reconcile_operation( |
| 1774 | "session", |
| 1775 | OperationOwnerSnapshot::new("shell:done", OwnerState::Completed, 1, 1), |
| 1776 | ) |
| 1777 | .expect("completed shell"); |
| 1778 | let saved = runtime |
| 1779 | .capture(Some("session")) |
| 1780 | .expect("capture") |
| 1781 | .expect("saved graph"); |
| 1782 | |
| 1783 | let restored = new_shared_work_runtime( |
| 1784 | crate::tools::todo::new_shared_todo_list(), |
| 1785 | crate::tools::plan::new_shared_plan_state(), |
| 1786 | ); |
| 1787 | restored |
| 1788 | .restore("session", Some(&saved.graph), &saved.todos, &saved.plan) |
| 1789 | .expect("restore graph"); |
| 1790 | let graph = restored |
| 1791 | .capture(Some("session")) |
| 1792 | .expect("capture restored") |
| 1793 | .expect("restored graph") |
| 1794 | .graph; |
| 1795 | let state_for = |external: &str| { |
| 1796 | graph |
| 1797 | .nodes |
| 1798 | .iter() |
| 1799 | .find(|node| { |
| 1800 | node.binding |
| 1801 | .as_ref() |
| 1802 | .is_some_and(|binding| binding.external == external) |
| 1803 | }) |
| 1804 | .map(|node| node.state) |
| 1805 | }; |
| 1806 | assert_eq!(state_for("shell:live"), Some(NodeState::Stale)); |
| 1807 | assert_eq!(state_for("shell:done"), Some(NodeState::Completed)); |
| 1808 | assert!(restored.has_pending_publish()); |
| 1809 | } |
| 1810 | |
| 1811 | #[test] |
| 1812 | fn durable_owner_same_sequence_recovers_stale_once_and_rejects_regression() { |
| 1813 | let runtime = new_shared_work_runtime( |
| 1814 | crate::tools::todo::new_shared_todo_list(), |
| 1815 | crate::tools::plan::new_shared_plan_state(), |
| 1816 | ); |
| 1817 | runtime |
| 1818 | .register_operation( |
| 1819 | "session", |
| 1820 | OperationIntent::new( |
| 1821 | "task:task_restore", |
| 1822 | "restored task", |
| 1823 | true, |
| 1824 | "task_create", |
| 1825 | "task_restore", |
| 1826 | ), |
| 1827 | ) |
| 1828 | .expect("register durable owner"); |
| 1829 | let running = OperationOwnerSnapshot::new("task:task_restore", OwnerState::Running, 7, 10); |
| 1830 | assert_eq!( |
| 1831 | runtime.reconcile_operation("session", running.clone()), |
| 1832 | Ok(true) |
| 1833 | ); |
| 1834 | assert_eq!( |
| 1835 | runtime.reconcile_observation( |
| 1836 | "session", |
| 1837 | "task:task_restore", |
| 1838 | OperationObservation::OwnerMissing { checked_at: 11 }, |
| 1839 | ), |
| 1840 | Ok(true) |
| 1841 | ); |
| 1842 | assert_eq!( |
| 1843 | runtime |
| 1844 | .capture(Some("session")) |
| 1845 | .expect("capture stale") |
| 1846 | .expect("graph") |
| 1847 | .graph |
| 1848 | .nodes |
| 1849 | .iter() |
| 1850 | .find(|node| { |
| 1851 | node.binding |
| 1852 | .as_ref() |
| 1853 | .is_some_and(|binding| binding.external == "task:task_restore") |
| 1854 | }) |
| 1855 | .map(|node| node.state), |
| 1856 | Some(NodeState::Stale) |
| 1857 | ); |
| 1858 | |
| 1859 | let replay = OperationOwnerSnapshot::new("task:task_restore", OwnerState::Running, 7, 12); |
| 1860 | assert_eq!( |
| 1861 | runtime.reconcile_operation("session", replay.clone()), |
| 1862 | Ok(true) |
| 1863 | ); |
| 1864 | assert_eq!( |
| 1865 | runtime.reconcile_operation("session", replay), |
| 1866 | Ok(false), |
| 1867 | "same-sequence recovery must happen only while the node is stale" |
| 1868 | ); |
| 1869 | assert_eq!( |
| 1870 | runtime |
| 1871 | .capture(Some("session")) |
| 1872 | .expect("capture recovered") |
| 1873 | .expect("graph") |
| 1874 | .graph |
| 1875 | .nodes |
| 1876 | .iter() |
| 1877 | .find(|node| { |
| 1878 | node.binding |
| 1879 | .as_ref() |
| 1880 | .is_some_and(|binding| binding.external == "task:task_restore") |
| 1881 | }) |
| 1882 | .map(|node| node.state), |
| 1883 | Some(NodeState::Active) |
| 1884 | ); |
| 1885 | assert_eq!( |
| 1886 | runtime.reconcile_operation( |
| 1887 | "session", |
| 1888 | OperationOwnerSnapshot::new("task:task_restore", OwnerState::Waiting, 7, 13,), |
| 1889 | ), |
| 1890 | Ok(false), |
| 1891 | "ordinary same-key duplicates retain the reducer no-op contract" |
| 1892 | ); |
| 1893 | runtime |
| 1894 | .reconcile_observation( |
| 1895 | "session", |
| 1896 | "task:task_restore", |
| 1897 | OperationObservation::OwnerMissing { checked_at: 14 }, |
| 1898 | ) |
| 1899 | .expect("mark owner missing again"); |
| 1900 | assert!( |
| 1901 | runtime |
| 1902 | .reconcile_operation( |
| 1903 | "session", |
| 1904 | OperationOwnerSnapshot::new("task:task_restore", OwnerState::Waiting, 7, 15,), |
| 1905 | ) |
| 1906 | .expect_err("inconsistent replay cannot revive a stale node") |
| 1907 | .contains("changed observation") |
| 1908 | ); |
| 1909 | assert!( |
| 1910 | runtime |
| 1911 | .reconcile_operation( |
| 1912 | "session", |
| 1913 | OperationOwnerSnapshot::new("task:task_restore", OwnerState::Running, 6, 16,), |
| 1914 | ) |
| 1915 | .expect_err("owner sequence cannot regress") |
| 1916 | .contains("sequence regressed") |
| 1917 | ); |
| 1918 | } |
| 1919 | |
| 1920 | #[tokio::test] |
| 1921 | async fn replaced_plan_steps_never_parent_new_operations() { |
| 1922 | let runtime = new_shared_work_runtime( |
| 1923 | crate::tools::todo::new_shared_todo_list(), |
| 1924 | crate::tools::plan::new_shared_plan_state(), |
| 1925 | ); |
| 1926 | let step = |step: &str, status: StepStatus| PlanItemArg { |
| 1927 | step: step.to_string(), |
| 1928 | status, |
| 1929 | }; |
| 1930 | let three = PlanSnapshot { |
| 1931 | items: vec![ |
| 1932 | step("first", StepStatus::Pending), |
| 1933 | step("second", StepStatus::Pending), |
| 1934 | step("third", StepStatus::InProgress), |
| 1935 | ], |
| 1936 | ..PlanSnapshot::default() |
| 1937 | }; |
| 1938 | runtime |
| 1939 | .apply_plan_update("session", "update_plan", &three) |
| 1940 | .await |
| 1941 | .expect("three-step plan"); |
| 1942 | let one = PlanSnapshot { |
| 1943 | items: vec![step("only", StepStatus::Pending)], |
| 1944 | ..PlanSnapshot::default() |
| 1945 | }; |
| 1946 | runtime |
| 1947 | .apply_plan_update("session", "update_plan", &one) |
| 1948 | .await |
| 1949 | .expect("replacement plan"); |
| 1950 | |
| 1951 | let operation = runtime |
| 1952 | .register_operation( |
| 1953 | "session", |
| 1954 | OperationIntent::new( |
| 1955 | "shell:after", |
| 1956 | "after replacement", |
| 1957 | false, |
| 1958 | "exec_shell", |
| 1959 | "c1", |
| 1960 | ), |
| 1961 | ) |
| 1962 | .expect("register operation"); |
| 1963 | let graph = runtime |
| 1964 | .capture(Some("session")) |
| 1965 | .expect("capture") |
| 1966 | .expect("graph") |
| 1967 | .graph; |
| 1968 | assert_eq!(graph.compat.plan_order.len(), 1); |
| 1969 | let parent = graph |
| 1970 | .edges |
| 1971 | .iter() |
| 1972 | .find(|edge| edge.kind == EdgeKind::Contains && edge.to == operation) |
| 1973 | .map(|edge| edge.from.clone()); |
| 1974 | assert_eq!( |
| 1975 | parent, |
| 1976 | Some(graph.compat.plan_order[0].clone()), |
| 1977 | "an orphaned step from the replaced plan must not adopt new work" |
| 1978 | ); |
| 1979 | } |
| 1980 | |
| 1981 | #[test] |
| 1982 | fn legacy_restore_stays_pending_until_first_graph_bearing_write() { |
| 1983 | let todos = crate::tools::todo::new_shared_todo_list(); |
| 1984 | let plan = crate::tools::plan::new_shared_plan_state(); |
| 1985 | let runtime = new_shared_work_runtime(todos.clone(), plan.clone()); |
| 1986 | let legacy_plan = PlanSnapshot { |
| 1987 | items: vec![PlanItemArg { |
| 1988 | step: "Migrate once".to_string(), |
| 1989 | status: StepStatus::InProgress, |
| 1990 | }], |
| 1991 | ..PlanSnapshot::default() |
| 1992 | }; |
| 1993 | |
| 1994 | runtime |
| 1995 | .restore( |
| 1996 | "legacy-session", |
| 1997 | None, |
| 1998 | &TodoListSnapshot::default(), |
| 1999 | &legacy_plan, |
| 2000 | ) |
| 2001 | .expect("restore legacy state"); |
| 2002 | assert!(runtime.has_pending_publish()); |
| 2003 | let captured = runtime |
| 2004 | .capture(Some("legacy-session")) |
| 2005 | .expect("capture imported graph") |
| 2006 | .expect("state"); |
| 2007 | assert!(captured.graph.import_digest.is_some()); |
| 2008 | assert_eq!(plan.blocking_lock().snapshot(), legacy_plan); |
| 2009 | assert_eq!( |
| 2010 | runtime.publish_pending_sync_matching(Some("other-session"), Some(&captured.graph)), |
| 2011 | Ok(false) |
| 2012 | ); |
| 2013 | let mut newer_plan = legacy_plan.clone(); |
| 2014 | newer_plan.items[0].step = "Keep the newer work".to_string(); |
| 2015 | let newer = runtime |
| 2016 | .restore( |
| 2017 | "legacy-session", |
| 2018 | None, |
| 2019 | &TodoListSnapshot::default(), |
| 2020 | &newer_plan, |
| 2021 | ) |
| 2022 | .expect("restore newer work") |
| 2023 | .expect("newer graph"); |
| 2024 | assert_eq!( |
| 2025 | runtime.publish_pending_sync_matching(Some("legacy-session"), Some(&captured.graph)), |
| 2026 | Ok(false) |
| 2027 | ); |
| 2028 | assert!(runtime.has_pending_publish()); |
| 2029 | assert_eq!( |
| 2030 | runtime.publish_pending_sync_matching(Some("legacy-session"), Some(&newer.graph)), |
| 2031 | Ok(true) |
| 2032 | ); |
| 2033 | assert!(!runtime.has_pending_publish()); |
| 2034 | assert!(todos.blocking_lock().snapshot().is_empty()); |
| 2035 | let unsaved = runtime |
| 2036 | .restore( |
| 2037 | "unsaved-work", |
| 2038 | None, |
| 2039 | &TodoListSnapshot::default(), |
| 2040 | &legacy_plan, |
| 2041 | ) |
| 2042 | .expect("restore unsaved work") |
| 2043 | .expect("unsaved graph"); |
| 2044 | assert_eq!( |
| 2045 | runtime.publish_pending_sync_matching(None, Some(&unsaved.graph)), |
| 2046 | Ok(true) |
| 2047 | ); |
| 2048 | } |
| 2049 | |
| 2050 | /// #6842: one Operation node per finished shell call grew without bound. |
| 2051 | #[test] |
| 2052 | fn ended_shell_operations_are_capped_oldest_first() { |
| 2053 | let runtime = new_shared_work_runtime( |
| 2054 | crate::tools::todo::new_shared_todo_list(), |
| 2055 | crate::tools::plan::new_shared_plan_state(), |
| 2056 | ); |
| 2057 | let total = super::super::model::ENDED_OPERATION_CAP + 44; |
| 2058 | let mut ids = Vec::new(); |
| 2059 | for i in 0..total { |
| 2060 | let external = format!("shell:cap_{i}"); |
| 2061 | let intent = |
| 2062 | OperationIntent::new(&external, "ls", false, "exec_shell", format!("c{i}")); |
| 2063 | ids.push( |
| 2064 | runtime |
| 2065 | .register_operation("session", intent) |
| 2066 | .expect("register"), |
| 2067 | ); |
| 2068 | for (seq, state) in [(1, OwnerState::Running), (2, OwnerState::Completed)] { |
| 2069 | runtime |
| 2070 | .reconcile_operation( |
| 2071 | "session", |
| 2072 | OperationOwnerSnapshot::new( |
| 2073 | &external, |
| 2074 | state, |
| 2075 | seq, |
| 2076 | i as i64 * 10 + seq as i64, |
| 2077 | ), |
| 2078 | ) |
| 2079 | .expect("reconcile"); |
| 2080 | } |
| 2081 | } |
| 2082 | let graph = runtime |
| 2083 | .capture(Some("session")) |
| 2084 | .expect("capture") |
| 2085 | .expect("graph") |
| 2086 | .graph; |
| 2087 | crate::work_graph::validate(&graph).expect("pruned graph validates"); |
| 2088 | let operations = graph |
| 2089 | .nodes |
| 2090 | .iter() |
| 2091 | .filter(|node| node.kind == NodeKind::Operation) |
| 2092 | .count(); |
| 2093 | // Pruned to the cap at each registration; the last call then ended. |
| 2094 | assert!( |
| 2095 | operations <= super::super::model::ENDED_OPERATION_CAP + 1, |
| 2096 | "{operations}" |
| 2097 | ); |
| 2098 | assert!(graph.node(&ids[0]).is_none(), "oldest ended call evicted"); |
| 2099 | assert!(graph.node(&ids[total - 1]).is_some(), "newest call kept"); |
| 2100 | assert!( |
| 2101 | graph |
| 2102 | .edges |
| 2103 | .iter() |
| 2104 | .all(|edge| graph.node(&edge.from).is_some() && graph.node(&edge.to).is_some()) |
| 2105 | ); |
| 2106 | } |
| 2107 | |
| 2108 | #[test] |
| 2109 | fn corrupt_lane_record_reconciles_as_unreadable_not_plain_missing() { |
| 2110 | let _lock = crate::test_support::lock_test_env(); |
| 2111 | let home = tempfile::tempdir().expect("temp home"); |
| 2112 | let workspace = tempfile::tempdir().expect("temp workspace"); |
| 2113 | let _home_guard = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2114 | |
| 2115 | let registry = LaneRegistry::open_default().expect("open lane registry"); |
| 2116 | let corrupt_id = "lane-corrupt"; |
| 2117 | std::fs::write(registry.record_path(corrupt_id), "{not valid json") |
| 2118 | .expect("write corrupt lane record"); |
| 2119 | |
| 2120 | let lanes = Some(Ok(registry)); |
| 2121 | let corrupt_obs = observe_lane_owner(lanes.as_ref(), corrupt_id, 100); |
| 2122 | assert!( |
| 2123 | matches!( |
| 2124 | corrupt_obs, |
| 2125 | OperationObservation::OwnerUnreadable { checked_at: 100, ref reason } |
| 2126 | if reason.contains("parse lane record") |
| 2127 | ), |
| 2128 | "corrupt lane record must produce OwnerUnreadable, got {corrupt_obs:?}" |
| 2129 | ); |
| 2130 | |
| 2131 | let absent_obs = observe_lane_owner(lanes.as_ref(), "lane-absent", 101); |
| 2132 | assert_eq!( |
| 2133 | absent_obs, |
| 2134 | OperationObservation::OwnerMissing { checked_at: 101 } |
| 2135 | ); |
| 2136 | |
| 2137 | let runtime = new_shared_work_runtime( |
| 2138 | crate::tools::todo::new_shared_todo_list(), |
| 2139 | crate::tools::plan::new_shared_plan_state(), |
| 2140 | ); |
| 2141 | let external = format!("lane:{corrupt_id}"); |
| 2142 | runtime |
| 2143 | .register_operation( |
| 2144 | "session", |
| 2145 | OperationIntent::new(external.clone(), "Corrupt lane", true, "lane", corrupt_id), |
| 2146 | ) |
| 2147 | .expect("register durable lane"); |
| 2148 | runtime |
| 2149 | .reconcile_operation( |
| 2150 | "session", |
| 2151 | OperationOwnerSnapshot::new(external.clone(), OwnerState::Running, 1, 1), |
| 2152 | ) |
| 2153 | .expect("mark lane running"); |
| 2154 | let snapshot = runtime |
| 2155 | .capture(Some("session")) |
| 2156 | .expect("capture") |
| 2157 | .expect("snapshot") |
| 2158 | .graph; |
| 2159 | |
| 2160 | let (reconciled, changed) = |
| 2161 | reconcile_workspace_snapshot(snapshot, "session", workspace.path()) |
| 2162 | .expect("reconcile workspace"); |
| 2163 | assert_eq!(changed, 1); |
| 2164 | let node = reconciled |
| 2165 | .nodes |
| 2166 | .iter() |
| 2167 | .find(|node| { |
| 2168 | node.binding |
| 2169 | .as_ref() |
| 2170 | .is_some_and(|binding| binding.external == external) |
| 2171 | }) |
| 2172 | .expect("lane node"); |
| 2173 | assert_eq!(node.state, NodeState::Stale); |
| 2174 | assert!( |
| 2175 | reconciled |
| 2176 | .history |
| 2177 | .iter() |
| 2178 | .any(|receipt| receipt.summary == "reconcile_operation_owner_unreadable"), |
| 2179 | "expected unreadable-owner receipt, got {:?}", |
| 2180 | reconciled.history |
| 2181 | ); |
| 2182 | } |
| 2183 | } |
| 2184 |