Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / infra / agents / agentd / src / scheduler.rs
scheduler.rs402 lines · 15.8 KiBRaw
| 1 | //! Scheduler: `AGENTD_SLOTS` workers pull queued tasks from the DB. |
| 2 | //! |
| 3 | //! A worker holds a runner slot only while a task is `running`. Whenever the |
| 4 | //! agent must wait (question, chat, budget, error, Stop) the driver parks |
| 5 | //! the task — persisting the conversation and releasing the slot (`slot = |
| 6 | //! NULL`) — and returns to the claim loop. The queue lives in SQLite so it |
| 7 | //! survives restarts; on startup, tasks left `running` by a previous process |
| 8 | //! are recovered (synthetic results + re-park); see |
| 9 | //! [`Store::recover_interrupted`](crate::store::Store::recover_interrupted). |
| 10 | //! The scheduler loop also polls the release-signal file so the UI banner |
| 11 | //! stays fresh; build preemption itself happens inside the agent loop. |
| 12 | |
| 13 | use crate::agent::{drive_task, DriverCtx, TaskOutcome}; |
| 14 | use crate::models::{Pending, TaskStatus, PENDING_ERROR, PENDING_PLAN, EVENT_STATUS, INBOX_PLAN_APPROVE}; |
| 15 | |
| 16 | /// Restart recovery (replaces `mark_interrupted_running_failed`). |
| 17 | /// |
| 18 | /// For every task left `running` at startup: |
| 19 | /// 1. Append synthetic "interrupted by restart" tool results for any |
| 20 | /// unanswered `tool_call_id`s in the stored history (the protocol must |
| 21 | /// never carry an unanswered call). |
| 22 | /// 2. Try to park from the task's recorded slot (diff → commit "WIP" → |
| 23 | /// bundle → import as `refs/agent-wip/<id>`) and set `queued`; the claim |
| 24 | /// loop will resume it normally. |
| 25 | /// 3. If parking fails, mark the task `failed`. |
| 26 | /// |
| 27 | /// Tasks already parked (`needs_input` / `review` / `queued`) are untouched. |
| 28 | /// Returns the number of tasks recovered (parked + failed). |
| 29 | pub async fn recover_interrupted(ctx: &DriverCtx) -> usize { |
| 30 | let ids = ctx.store.interrupted_running_ids().unwrap_or_default(); |
| 31 | let mut done = 0; |
| 32 | for id in ids { |
| 33 | recover_one(ctx, id).await; |
| 34 | done += 1; |
| 35 | } |
| 36 | done |
| 37 | } |
| 38 | |
| 39 | async fn recover_one(ctx: &DriverCtx, task_id: i64) { |
| 40 | // 1. Synthetic results for unanswered tool calls in stored history. |
| 41 | let unanswered = unanswered_call_ids(ctx, task_id); |
| 42 | for call_id in unanswered { |
| 43 | let msg = crate::openrouter::Message::tool_result( |
| 44 | call_id, |
| 45 | "interrupted by restart: the previous process died before answering; re-check state with git_diff and continue.".to_string(), |
| 46 | ); |
| 47 | if let Err(e) = ctx.store.append_message(task_id, &msg) { |
| 48 | tracing::warn!("recovery append for task {task_id}: {e}"); |
| 49 | } |
| 50 | } |
| 51 | // 2. Park from the slot checkout (usually intact — the builder is a |
| 52 | // separate container). Needs the recorded slot + branch + base. |
| 53 | let task = match ctx.store.get_task(task_id).ok().flatten() { |
| 54 | Some(t) => t, |
| 55 | None => return, |
| 56 | }; |
| 57 | let (Some(slot), branch) = (task.slot, task.branch.clone()) else { |
| 58 | ctx.store |
| 59 | .update_status(task_id, TaskStatus::Failed, Some("interrupted by restart (no slot to recover from)"), None) |
| 60 | .ok(); |
| 61 | return; |
| 62 | }; |
| 63 | if branch.is_empty() { |
| 64 | ctx.store |
| 65 | .update_status(task_id, TaskStatus::Failed, Some("interrupted by restart (no branch)"), None) |
| 66 | .ok(); |
| 67 | return; |
| 68 | } |
| 69 | let pending = Pending::new( |
| 70 | PENDING_ERROR, |
| 71 | None, |
| 72 | serde_json::json!({"message": "interrupted by restart; work re-parked"}), |
| 73 | ); |
| 74 | // Best-effort WIP snapshot from the slot (same shape as the driver park, |
| 75 | // minus stop-flag checks — no driver is running). |
| 76 | let wip_sha: Option<String> = match ctx.runner.diff(slot).await { |
| 77 | Ok(d) if d.diff.trim().is_empty() && d.stat.trim().is_empty() => None, |
| 78 | Ok(_) => { |
| 79 | let committed = ctx |
| 80 | .runner |
| 81 | .commit(slot, &format!("WIP task {task_id}")) |
| 82 | .await |
| 83 | .is_ok(); |
| 84 | if !committed { |
| 85 | None |
| 86 | } else { |
| 87 | match ctx.runner.bundle(slot).await { |
| 88 | Ok(bundle) => { |
| 89 | let tmp = match tempfile::Builder::new() |
| 90 | .prefix("agentd-recover-") |
| 91 | .tempfile() |
| 92 | { |
| 93 | Ok(f) => f.into_temp_path(), |
| 94 | Err(_) => { |
| 95 | return fail_recovery(ctx, task_id, "interrupted by restart (bundle tempfile failed)"); |
| 96 | } |
| 97 | }; |
| 98 | if std::fs::write(&tmp, &bundle).is_err() { |
| 99 | return fail_recovery(ctx, task_id, "interrupted by restart (bundle write failed)"); |
| 100 | } |
| 101 | match crate::git::import_wip_bundle( |
| 102 | &ctx.config.mirror_dir, |
| 103 | &tmp, |
| 104 | &branch, |
| 105 | task_id, |
| 106 | ) |
| 107 | .await |
| 108 | { |
| 109 | Ok(sha) => Some(sha), |
| 110 | Err(_) => { |
| 111 | return fail_recovery(ctx, task_id, "interrupted by restart (WIP import failed)"); |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | Err(_) => { |
| 116 | return fail_recovery(ctx, task_id, "interrupted by restart (bundle failed)"); |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | Err(_) => { |
| 122 | return fail_recovery(ctx, task_id, "interrupted by restart (diff failed)"); |
| 123 | } |
| 124 | }; |
| 125 | match ctx |
| 126 | .store |
| 127 | .park_task(task_id, TaskStatus::Queued, &pending, wip_sha.as_deref()) |
| 128 | { |
| 129 | Ok(_) => { |
| 130 | ctx.emit(task_id, EVENT_STATUS, |
| 131 | serde_json::json!({"message": "recovered after restart; re-queued"}), |
| 132 | ); |
| 133 | } |
| 134 | Err(e) => fail_recovery(ctx, task_id, &format!("interrupted by restart (park: {e})")), |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | /// `tool_call_id`s in stored history with no later matching tool result. |
| 139 | fn unanswered_call_ids(ctx: &DriverCtx, task_id: i64) -> Vec<String> { |
| 140 | let hist = ctx.store.load_messages(task_id).unwrap_or_default(); |
| 141 | let mut answered = std::collections::HashSet::new(); |
| 142 | for m in &hist { |
| 143 | if m.role == "tool" { |
| 144 | if let Some(id) = &m.tool_call_id { |
| 145 | answered.insert(id.clone()); |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | let mut out = Vec::new(); |
| 150 | for m in &hist { |
| 151 | if m.role == "assistant" { |
| 152 | if let Some(calls) = &m.tool_calls { |
| 153 | for c in calls { |
| 154 | if !answered.contains(&c.id) && !out.contains(&c.id) { |
| 155 | out.push(c.id.clone()); |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | out |
| 162 | } |
| 163 | |
| 164 | fn fail_recovery(ctx: &DriverCtx, task_id: i64, reason: &str) { |
| 165 | ctx.store |
| 166 | .update_status(task_id, TaskStatus::Failed, Some(reason), None) |
| 167 | .ok(); |
| 168 | ctx.emit(task_id, EVENT_STATUS, serde_json::json!({"message": reason})); |
| 169 | } |
| 170 | |
| 171 | /// Spawn `slots` worker tasks. Each worker claims the oldest queued task |
| 172 | /// atomically (`claim_queued`), drives it, records the terminal status, and |
| 173 | /// repeats. Returns the join handles. |
| 174 | pub fn spawn_workers(ctx: DriverCtx, slots: usize) -> Vec<tokio::task::JoinHandle<()>> { |
| 175 | let mut handles = Vec::new(); |
| 176 | for slot in 0..slots as u32 { |
| 177 | let ctx = ctx.clone(); |
| 178 | handles.push(tokio::spawn(async move { |
| 179 | worker_loop(ctx, slot).await; |
| 180 | })); |
| 181 | } |
| 182 | handles |
| 183 | } |
| 184 | |
| 185 | async fn worker_loop(ctx: DriverCtx, slot: u32) { |
| 186 | let poll = ctx.config.poll_interval(); |
| 187 | loop { |
| 188 | let claimed = ctx.store.claim_queued(slot); |
| 189 | let task = match claimed { |
| 190 | Ok(Some(t)) => t, |
| 191 | Ok(None) => { |
| 192 | tokio::time::sleep(poll).await; |
| 193 | continue; |
| 194 | } |
| 195 | Err(e) => { |
| 196 | tracing::error!("scheduler claim failed: {e}"); |
| 197 | tokio::time::sleep(poll).await; |
| 198 | continue; |
| 199 | } |
| 200 | }; |
| 201 | let task_id = task.id; |
| 202 | ctx.emit(task_id, EVENT_STATUS, |
| 203 | serde_json::json!({"message": format!("claimed by worker {slot}"), "slot": slot}), |
| 204 | ); |
| 205 | match drive_task(ctx.clone(), task_id, slot).await { |
| 206 | TaskOutcome::Failed { reason } => { |
| 207 | let _ = ctx.store.update_status(task_id, TaskStatus::Failed, Some(&reason), None); |
| 208 | } |
| 209 | TaskOutcome::Parked => { |
| 210 | // Status + pending_json already stored atomically by |
| 211 | // `Store::park_task`; the worker just returns to the claim |
| 212 | // loop (the slot is free — `slot = NULL`). |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | /// Stop a task: set the stop flag the driver checks (top of loop, per tool |
| 219 | /// call, after park import). The runner slot is cancelled ONLY while the |
| 220 | /// task's status is `running`, so a late Stop can never kill the next task to |
| 221 | /// use that slot. The driver parks as `needs_input(stopped)` with work kept. |
| 222 | pub async fn stop_task(ctx: &DriverCtx, task_id: i64) -> Result<bool, String> { |
| 223 | let task = ctx |
| 224 | .store |
| 225 | .get_task(task_id)? |
| 226 | .ok_or_else(|| "task not found".to_string())?; |
| 227 | if task.status.is_terminal() { |
| 228 | return Ok(false); |
| 229 | } |
| 230 | ctx.store.request_stop(task_id)?; |
| 231 | ctx.emit(task_id, EVENT_STATUS, |
| 232 | serde_json::json!({"message": "stop requested by operator"}), |
| 233 | ); |
| 234 | // Kill the runner slot only while the task actually runs there. |
| 235 | if task.status == TaskStatus::Running { |
| 236 | if let Some(slot) = task.slot { |
| 237 | match ctx.runner.cancel_slot(slot).await { |
| 238 | Ok(killed) => return Ok(killed), |
| 239 | Err(e) => { |
| 240 | tracing::warn!("runner cancel slot {slot}: {e}"); |
| 241 | return Ok(false); |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | Ok(true) |
| 247 | } |
| 248 | |
| 249 | /// Approve a parked plan or a review, and discard from more states. |
| 250 | /// |
| 251 | /// * `approve_task(task_id, "plan")` — only in `needs_input(plan)`: sets |
| 252 | /// `plan_approved=1` and posts "approved" via the tagged inbox path, so the |
| 253 | /// pending `propose_plan` call resumes with "Plan approved. Proceed.". |
| 254 | /// * `approve_task(task_id, "review")` — only in `review`: pushes |
| 255 | /// `refs/agent-wip/<id>` → `refs/heads/<branch>` (scoped token, |
| 256 | /// `http.extraHeader`), then status `succeeded`, `pushed=1`, `pushed_sha`, |
| 257 | /// `base_sha = pushed_sha`, pending cleared, local WIP ref deleted, status |
| 258 | /// event emitted. Calls the no-op `crate::hooks::after_push` (never fails |
| 259 | /// the approve). On push failure the task stays in `review` with the error. |
| 260 | /// * `discard_task` — works in any non-terminal state INCLUDING review; |
| 261 | /// deletes the local WIP ref. When the task was pushed before, the UI notes |
| 262 | /// the remote branch remains (the agent token cannot delete it). |
| 263 | pub async fn approve_task( |
| 264 | ctx: &DriverCtx, |
| 265 | task_id: i64, |
| 266 | what: &str, |
| 267 | ) -> Result<&'static str, String> { |
| 268 | let task = ctx |
| 269 | .store |
| 270 | .get_task(task_id)? |
| 271 | .ok_or_else(|| "task not found".to_string())?; |
| 272 | match what { |
| 273 | "plan" => { |
| 274 | if task.status != TaskStatus::NeedsInput |
| 275 | || task.pending.as_ref().map(|p| p.kind.as_str()) != Some(PENDING_PLAN) |
| 276 | { |
| 277 | return Err("no plan awaiting approval".to_string()); |
| 278 | } |
| 279 | ctx.store.approve_plan(task_id)?; |
| 280 | // Tagged inbox row → the resume formats the pending propose_plan |
| 281 | // result as "Plan approved. Proceed." Races behave like other |
| 282 | // messages (same inbox/requeue transaction). |
| 283 | ctx.store |
| 284 | .inbox_post_kind(task_id, "approved", INBOX_PLAN_APPROVE)?; |
| 285 | ctx.emit( |
| 286 | task_id, |
| 287 | EVENT_STATUS, |
| 288 | serde_json::json!({"message": "plan approved by operator"}), |
| 289 | ); |
| 290 | Ok("plan approved") |
| 291 | } |
| 292 | "review" => { |
| 293 | if !ctx.store.claim_approve(task_id)? { |
| 294 | return Err("task is not awaiting review (or an approve is already in progress)".to_string()); |
| 295 | } |
| 296 | let r = approve_review(ctx, &task).await; |
| 297 | if let Err(e) = ctx.store.finish_approve(task_id) { |
| 298 | tracing::error!("finish_approve {task_id}: {e}"); |
| 299 | } |
| 300 | r |
| 301 | } |
| 302 | _ => Err(format!("unknown approve target {what:?}")), |
| 303 | } |
| 304 | } |
| 305 | |
| 306 | async fn approve_review(ctx: &DriverCtx, task: &crate::models::Task) -> Result<&'static str, String> { |
| 307 | let task_id = task.id; |
| 308 | if task.status != TaskStatus::Review { |
| 309 | return Err("task is not awaiting review".to_string()); |
| 310 | } |
| 311 | let wip_sha = task.wip_sha.clone().filter(|s| !s.is_empty()); |
| 312 | let branch = task.branch.clone(); |
| 313 | if branch.is_empty() { |
| 314 | return Err("task has no branch".to_string()); |
| 315 | } |
| 316 | // The WIP ref must still resolve (it was verified at park; re-check). |
| 317 | match crate::git::wip_ref_sha(&ctx.config.mirror_dir, task_id).await { |
| 318 | Ok(Some(found)) => { |
| 319 | if let Some(expected) = &wip_sha { |
| 320 | if &found != expected { |
| 321 | return Err(format!( |
| 322 | "WIP ref mismatch (expected {expected}, found {found})" |
| 323 | )); |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | Ok(None) => return Err("WIP ref missing in mirror; cannot push".to_string()), |
| 328 | Err(e) => return Err(format!("WIP ref check: {e}")), |
| 329 | } |
| 330 | // Push WIP ref → branch via [`crate::git::push_ref`] (scoped token, |
| 331 | // `http.extraHeader`). |
| 332 | if let Err(e) = crate::git::push_ref( |
| 333 | &ctx.config.mirror_dir, |
| 334 | &ctx.config.repo_url, |
| 335 | &format!("refs/agent-wip/{task_id}"), |
| 336 | &format!("refs/heads/{branch}"), |
| 337 | &ctx.config.git_push_token, |
| 338 | ) |
| 339 | .await |
| 340 | { |
| 341 | ctx.emit( |
| 342 | task_id, |
| 343 | EVENT_STATUS, |
| 344 | serde_json::json!({"message": format!("approve push failed: {e}")}), |
| 345 | ); |
| 346 | return Err(format!("push failed (staying in review): {e}")); |
| 347 | } |
| 348 | // Resolve the pushed sha from the local WIP ref (what we pushed). |
| 349 | let pushed_sha = crate::git::wip_ref_sha(&ctx.config.mirror_dir, task_id) |
| 350 | .await |
| 351 | .map_err(|e| format!("read pushed sha: {e}"))? |
| 352 | .ok_or_else(|| "WIP ref vanished after push".to_string())?; |
| 353 | ctx.store.set_pushed(task_id, &pushed_sha)?; |
| 354 | let _ = ctx.store.set_finished_commit( |
| 355 | task_id, |
| 356 | &pushed_sha, |
| 357 | true, |
| 358 | task.summary.as_deref().unwrap_or(""), |
| 359 | ); |
| 360 | ctx.store |
| 361 | .update_status(task_id, TaskStatus::Succeeded, None, None)?; |
| 362 | let _ = crate::git::delete_wip_ref(&ctx.config.mirror_dir, task_id).await; |
| 363 | // Fresh task snapshot for the hook. |
| 364 | if let Some(fresh) = ctx.store.get_task(task_id).ok().flatten() { |
| 365 | // Must never fail the approve: ignore the result entirely. |
| 366 | let _ = crate::hooks::after_push(ctx, &fresh).await; |
| 367 | } |
| 368 | ctx.emit( |
| 369 | task_id, |
| 370 | EVENT_STATUS, |
| 371 | serde_json::json!({"message": format!("approved and pushed {branch}"), "sha": pushed_sha}), |
| 372 | ); |
| 373 | Ok("pushed") |
| 374 | } |
| 375 | |
| 376 | /// Discard a task from any non-terminal state (queued, running, needs_input, |
| 377 | /// review, succeeded-followup-able): terminal `discarded`, and delete the |
| 378 | /// local `refs/agent-wip/<id>`. After a push the remote branch remains — the |
| 379 | /// scoped token cannot delete it (the task page notes this when the task was |
| 380 | /// pushed; see the `pushed` flag on the row). |
| 381 | pub async fn discard_task(ctx: &DriverCtx, task_id: i64) -> Result<bool, String> { |
| 382 | let task = ctx |
| 383 | .store |
| 384 | .get_task(task_id)? |
| 385 | .ok_or_else(|| "task not found".to_string())?; |
| 386 | if task.status.is_terminal() { |
| 387 | return Ok(false); |
| 388 | } |
| 389 | if let Err(e) = crate::git::delete_wip_ref(&ctx.config.mirror_dir, task_id).await { |
| 390 | tracing::warn!("discard delete WIP ref for task {task_id}: {e}"); |
| 391 | } |
| 392 | ctx.store.update_status( |
| 393 | task_id, |
| 394 | TaskStatus::Discarded, |
| 395 | Some("discarded by operator"), |
| 396 | None, |
| 397 | )?; |
| 398 | ctx.emit(task_id, EVENT_STATUS, |
| 399 | serde_json::json!({"message": "task discarded by operator"}), |
| 400 | ); |
| 401 | Ok(true) |
| 402 | } |