返回 CodeWhale
task_manager.rs
根目录 / crates / engine / src / task_manager.rs
1 //! Persistent background task manager for Codewhale agent work.
2 //!
3 //! Tasks are durable across restarts and execute with a bounded worker pool.
4 //! Execution uses the shared runtime provider route and links every task to
5 //! runtime thread/turn records for unified timelines.
6
7 use std::collections::{HashMap, HashSet, VecDeque};
8 use std::fs;
9 use std::path::{Path, PathBuf};
10 use std::sync::Arc;
11 #[cfg(any(test, feature = "test-support"))]
12 use std::time::Duration as StdDuration;
13 use std::time::Duration;
14
15 use anyhow::{Context, Result, anyhow, bail};
16 use async_trait::async_trait;
17 use chrono::{DateTime, Utc};
18 use serde::{Deserialize, Serialize};
19 use serde_json::{Value, json};
20 use tokio::sync::{Mutex, Notify, mpsc, oneshot};
21 use tokio::time::{Instant, sleep};
22 use tokio_util::sync::CancellationToken;
23 use uuid::Uuid;
24
25 use crate::runtime_threads::{
26 RUNTIME_STORE_FAILURE_EVENT, RuntimeEventRecord, RuntimeProcessOwnerLock, RuntimeTurnStatus,
27 ThreadOrigin, manager::CreateThreadRequest, manager::RuntimeThreadManager,
28 manager::RuntimeThreadManagerConfig, manager::SharedRuntimeThreadManager,
29 manager::StartTurnRequest, manager::summarize_text,
30 };
31 use codewhale_runtime::config::Config;
32 use codewhale_util::utils::spawn_supervised;
33
34 const DEFAULT_WORKERS: usize = 2;
35 const MAX_WORKERS: usize = 8;
36 const TIMELINE_SUMMARY_LIMIT: usize = 240;
37 const TIMELINE_ENTRY_LIMIT: usize = 256;
38 const TIMELINE_HEAD_KEEP: usize = 8;
39 const ARTIFACT_THRESHOLD: usize = 1200;
40 const TASK_EVENT_CHANNEL_CAPACITY: usize = 256;
41 const EVENT_CURSOR_BATCH: usize = 256;
42 const DESTINATION_BUSY_RETRY: Duration = Duration::from_secs(2);
43 const EVENT_CATCHUP_POLL: Duration = Duration::from_millis(200);
44 /// Ceiling for the park-poll backoff: while a prompt waits on a human the
45 /// turn loop backs its journal poll off from the catch-up cadence up to
46 /// this bound; an arriving decision wakes it through the event
47 /// subscription, so this only bounds the empty polls.
48 const PARKED_POLL_CAP: Duration = Duration::from_secs(2);
49 // v4 binds execution to a trusted Runtime scope. Older executors must not
50 // ignore its eligibility or generation fence.
51 const CURRENT_TASK_SCHEMA_VERSION: u32 = 4;
52 const DENY_RULES_TASK_SCHEMA_VERSION: u32 = 5;
53 const MAX_SUPPORTED_TASK_SCHEMA_VERSION: u32 = DENY_RULES_TASK_SCHEMA_VERSION;
54
55 const fn required_task_schema_version(disallowed_tools: &[String]) -> u32 {
56 if disallowed_tools.is_empty() {
57 CURRENT_TASK_SCHEMA_VERSION
58 } else {
59 DENY_RULES_TASK_SCHEMA_VERSION
60 }
61 }
62 const STORE_REFRESH_INTERVAL: Duration = Duration::from_millis(200);
63 /// How long a worker with nothing claimable naps between queue-fingerprint
64 /// checks. An in-process notify still wakes it at once; this only bounds how
65 /// soon it notices another process's queue write, so an idle session stats the
66 /// queue about once a second per worker instead of five times (#6728, #6573).
67 const STORE_SETTLED_NAP: Duration = Duration::from_secs(1);
68 /// Retry an empty claim while queue metadata is missing or too recent to
69 /// distinguish writes on a coarse-mtime filesystem. Once settled, idle workers
70 /// wait for admission notifications or queue changes instead of reloading every
71 /// task record on a timer (#6728).
72 const STORE_IDLE_POLL_INTERVAL: Duration = Duration::from_secs(2);
73 /// Ceiling for the retry delay after a claim fails (e.g. "Task store is busy").
74 /// A failed claim has already waited out `lock_store`'s 5s deadline, so work
75 /// written by another process can wait up to about 13s after contention; an
76 /// in-process submission or a queue change ends the backoff early.
77 const STORE_BUSY_BACKOFF_MAX: Duration = Duration::from_secs(8);
78 /// A read snapshot is only trusted once both stamps are at least this old, so
79 /// a write landing in the same coarse mtime tick as the load (1s or 2s on
80 /// some filesystems) cannot hide behind an unchanged stamp (#6573).
81 const READ_SNAPSHOT_SETTLE: Duration = Duration::from_secs(2);
82
83 /// Only lock contention at the first worker claim may acknowledge a scheduled
84 /// retry. Corrupt state and other lock/I/O errors still fail initialization.
85 #[derive(Debug)]
86 struct TaskStoreBusy;
87
88 impl std::fmt::Display for TaskStoreBusy {
89 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90 formatter.write_str("Task store is busy; state is unavailable")
91 }
92 }
93
94 impl std::error::Error for TaskStoreBusy {}
95
96 const fn default_task_schema_version() -> u32 {
97 CURRENT_TASK_SCHEMA_VERSION
98 }
99
100 /// Durable task status.
101 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
102 #[serde(rename_all = "snake_case")]
103 pub enum TaskStatus {
104 Queued,
105 Running,
106 Completed,
107 Failed,
108 Canceled,
109 }
110
111 /// What the manager actually did while handling a cancellation request.
112 ///
113 /// This is returned from the same state-lock transaction as the task record,
114 /// so callers never have to infer an outcome from a stale pre-cancel read.
115 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
116 pub enum TaskCancelDisposition {
117 Forced,
118 Requested,
119 AlreadyFinished,
120 }
121
122 #[derive(Debug, Clone)]
123 pub struct TaskCancellation {
124 pub task: TaskRecord,
125 pub disposition: TaskCancelDisposition,
126 }
127
128 impl TaskStatus {
129 #[cfg(any(test, feature = "test-support"))]
130 #[must_use]
131 pub fn is_terminal(self) -> bool {
132 matches!(self, Self::Completed | Self::Failed | Self::Canceled)
133 }
134 }
135
136 /// Why a durable task left the running state. Stored on the task record so
137 /// receipts and status views can show a forced timeout separately from a
138 /// cooperative cancel.
139 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
140 pub enum TaskTerminalReason {
141 Completed,
142 Canceled,
143 CancelTimeout,
144 Shutdown,
145 WallTimeout,
146 HumanWaitTimeout,
147 IdleTimeout,
148 Failed,
149 }
150
151 impl TaskTerminalReason {
152 #[must_use]
153 pub const fn as_str(self) -> &'static str {
154 match self {
155 Self::Completed => "completed",
156 Self::Canceled => "canceled",
157 Self::CancelTimeout => "cancel_timeout",
158 Self::Shutdown => "shutdown",
159 Self::WallTimeout => "wall_timeout",
160 Self::HumanWaitTimeout => "human_wait_timeout",
161 Self::IdleTimeout => "idle_timeout",
162 Self::Failed => "failed",
163 }
164 }
165
166 #[must_use]
167 pub const fn task_status(self) -> TaskStatus {
168 match self {
169 Self::Completed => TaskStatus::Completed,
170 Self::Canceled | Self::CancelTimeout | Self::Shutdown => TaskStatus::Canceled,
171 Self::WallTimeout | Self::HumanWaitTimeout | Self::IdleTimeout | Self::Failed => {
172 TaskStatus::Failed
173 }
174 }
175 }
176
177 #[must_use]
178 pub fn receipt_message(self) -> String {
179 match self {
180 Self::Completed => "Task completed".to_string(),
181 Self::Canceled => "Task canceled".to_string(),
182 Self::CancelTimeout => {
183 "Task did not terminalize after cancellation; worker released".to_string()
184 }
185 Self::Shutdown => "Task canceled because the task manager shut down".to_string(),
186 Self::WallTimeout => {
187 "Task exceeded its wall-time deadline without completing".to_string()
188 }
189 Self::HumanWaitTimeout => {
190 "Task stayed parked on a human answer past the fail-safe cap".to_string()
191 }
192 Self::IdleTimeout => {
193 "Task made no model or tool progress before the idle deadline".to_string()
194 }
195 Self::Failed => "Task ended unexpectedly".to_string(),
196 }
197 }
198
199 fn after_grace(self) -> Self {
200 match self {
201 Self::Canceled => Self::CancelTimeout,
202 other => other,
203 }
204 }
205 }
206
207 /// Durable tool-call status within a task timeline.
208 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
209 #[serde(rename_all = "snake_case")]
210 pub enum TaskToolStatus {
211 Running,
212 Success,
213 Failed,
214 Canceled,
215 }
216
217 /// Timeline entry for a task execution.
218 #[derive(Debug, Clone, Serialize, Deserialize)]
219 pub struct TaskTimelineEntry {
220 pub timestamp: DateTime<Utc>,
221 pub kind: String,
222 pub summary: String,
223 #[serde(skip_serializing_if = "Option::is_none")]
224 pub detail_path: Option<PathBuf>,
225 }
226
227 /// Tool call summary for a task.
228 #[derive(Debug, Clone, Serialize, Deserialize)]
229 pub struct TaskToolCallSummary {
230 pub id: String,
231 pub name: String,
232 pub status: TaskToolStatus,
233 pub started_at: DateTime<Utc>,
234 pub ended_at: Option<DateTime<Utc>>,
235 pub duration_ms: Option<u64>,
236 #[serde(skip_serializing_if = "Option::is_none")]
237 pub input_summary: Option<String>,
238 #[serde(skip_serializing_if = "Option::is_none")]
239 pub output_summary: Option<String>,
240 #[serde(skip_serializing_if = "Option::is_none")]
241 pub detail_path: Option<PathBuf>,
242 #[serde(skip_serializing_if = "Option::is_none")]
243 pub patch_ref: Option<PathBuf>,
244 }
245
246 /// Checklist item stored on durable tasks. This is the durable form behind the
247 /// model-visible checklist/todo compatibility tools.
248 #[derive(Debug, Clone, Serialize, Deserialize)]
249 pub struct TaskChecklistItem {
250 pub id: u32,
251 pub content: String,
252 pub status: String,
253 }
254
255 /// Checklist state associated with a task.
256 #[derive(Debug, Clone, Serialize, Deserialize, Default)]
257 pub struct TaskChecklistState {
258 pub items: Vec<TaskChecklistItem>,
259 pub completion_pct: u8,
260 pub in_progress_id: Option<u32>,
261 pub updated_at: Option<DateTime<Utc>>,
262 }
263
264 /// Structured verification evidence attached to a task.
265 #[derive(Debug, Clone, Serialize, Deserialize)]
266 pub struct TaskGateRecord {
267 pub id: String,
268 pub gate: String,
269 pub command: String,
270 pub cwd: PathBuf,
271 pub exit_code: Option<i32>,
272 pub status: String,
273 pub classification: String,
274 pub duration_ms: u64,
275 pub summary: String,
276 #[serde(skip_serializing_if = "Option::is_none")]
277 pub log_path: Option<PathBuf>,
278 pub recorded_at: DateTime<Utc>,
279 }
280
281 /// PR-attempt metadata and artifacts attached to a task.
282 #[derive(Debug, Clone, Serialize, Deserialize)]
283 pub struct TaskAttemptRecord {
284 pub id: String,
285 pub attempt_group_id: String,
286 pub attempt_index: u32,
287 pub attempt_count: u32,
288 #[serde(skip_serializing_if = "Option::is_none")]
289 pub base_ref: Option<String>,
290 #[serde(skip_serializing_if = "Option::is_none")]
291 pub base_sha: Option<String>,
292 #[serde(skip_serializing_if = "Option::is_none")]
293 pub head_ref: Option<String>,
294 #[serde(skip_serializing_if = "Option::is_none")]
295 pub head_sha: Option<String>,
296 pub summary: String,
297 pub changed_files: Vec<String>,
298 #[serde(skip_serializing_if = "Option::is_none")]
299 pub patch_path: Option<PathBuf>,
300 pub verification: Vec<String>,
301 pub selected: bool,
302 pub recorded_at: DateTime<Utc>,
303 }
304
305 /// Durable artifact reference produced by task-aware tools.
306 #[derive(Debug, Clone, Serialize, Deserialize)]
307 pub struct TaskArtifactRef {
308 pub label: String,
309 pub path: PathBuf,
310 pub summary: String,
311 pub created_at: DateTime<Utc>,
312 }
313
314 /// GitHub write/read evidence attached to a task timeline.
315 #[derive(Debug, Clone, Serialize, Deserialize)]
316 pub struct TaskGithubEvent {
317 pub id: String,
318 pub action: String,
319 pub target: String,
320 pub number: u64,
321 pub summary: String,
322 pub url: Option<String>,
323 pub recorded_at: DateTime<Utc>,
324 }
325
326 /// Durable task record.
327 #[derive(Debug, Clone, Serialize, Deserialize)]
328 pub struct TaskRecord {
329 #[serde(default, skip_serializing_if = "Option::is_none")]
330 thread_origin: Option<ThreadOrigin>,
331 #[serde(default = "default_task_schema_version")]
332 pub schema_version: u32,
333 pub id: String,
334 pub prompt: String,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub name: Option<String>,
337 pub model: String,
338 #[serde(default, skip_serializing_if = "Option::is_none")]
339 pub model_provider: Option<String>,
340 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub model_provider_id: Option<String>,
342 pub workspace: PathBuf,
343 pub mode: String,
344 pub allow_shell: bool,
345 pub trust_mode: bool,
346 /// A record without the field (written before it existed) is not
347 /// auto-approved: a missing grant never widens authority.
348 #[serde(default)]
349 pub auto_approve: bool,
350 /// Permission posture the task's own thread starts on (`ask`,
351 /// `auto_review`, `full_access`). Absent on records written before the
352 /// field existed and on the in-process callers that still express authority
353 /// through `auto_approve` alone; the thread request then derives the
354 /// posture from that bit exactly as it always did.
355 #[serde(default, skip_serializing_if = "Option::is_none")]
356 pub permission_posture: Option<String>,
357 #[serde(default, skip_serializing_if = "Vec::is_empty")]
358 pub disallowed_tools: Vec<String>,
359 pub status: TaskStatus,
360 pub created_at: DateTime<Utc>,
361 pub started_at: Option<DateTime<Utc>>,
362 pub ended_at: Option<DateTime<Utc>>,
363 pub duration_ms: Option<u64>,
364 #[serde(skip_serializing_if = "Option::is_none")]
365 pub result_summary: Option<String>,
366 #[serde(skip_serializing_if = "Option::is_none")]
367 pub result_detail_path: Option<PathBuf>,
368 #[serde(skip_serializing_if = "Option::is_none")]
369 pub error: Option<String>,
370 #[serde(default, skip_serializing_if = "Option::is_none")]
371 pub terminal_reason: Option<String>,
372 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub thread_id: Option<String>,
374 #[serde(default, skip_serializing_if = "Option::is_none")]
375 pub turn_id: Option<String>,
376 #[serde(default, skip_serializing_if = "Option::is_none")]
377 pub owner_session_id: Option<String>,
378 #[serde(default, skip_serializing_if = "Option::is_none")]
379 pub destination_thread_id: Option<String>,
380 /// Trusted execution provenance, distinct from model-visible ownership.
381 #[serde(default, skip_serializing_if = "Option::is_none")]
382 pub execution_scope: Option<String>,
383 #[serde(default, skip_serializing_if = "Option::is_none")]
384 pub execution_generation: Option<String>,
385 /// Durable cancellation acknowledged by the actual execution owner.
386 #[serde(default)]
387 pub cancel_requested_seq: u64,
388 #[serde(default)]
389 pub runtime_event_count: usize,
390 /// Monotonic owner-lifecycle sequence used by Work Graph reconciliation.
391 /// Output/progress events do not advance this counter; only lifecycle
392 /// transitions do, so replay after restart is stable.
393 #[serde(default)]
394 pub lifecycle_seq: u64,
395 #[serde(default)]
396 pub checklist: TaskChecklistState,
397 #[serde(default)]
398 pub gates: Vec<TaskGateRecord>,
399 #[serde(default)]
400 pub attempts: Vec<TaskAttemptRecord>,
401 #[serde(default)]
402 pub artifacts: Vec<TaskArtifactRef>,
403 #[serde(default)]
404 pub github_events: Vec<TaskGithubEvent>,
405 pub tool_calls: Vec<TaskToolCallSummary>,
406 pub timeline: Vec<TaskTimelineEntry>,
407 }
408
409 /// Lightweight task view.
410 #[derive(Debug, Clone, Serialize, Deserialize)]
411 pub struct TaskSummary {
412 pub id: String,
413 pub status: TaskStatus,
414 pub prompt_summary: String,
415 #[serde(default, skip_serializing_if = "Option::is_none")]
416 pub name: Option<String>,
417 pub model: String,
418 #[serde(default, skip_serializing_if = "Option::is_none")]
419 pub model_provider: Option<String>,
420 #[serde(default, skip_serializing_if = "Option::is_none")]
421 pub model_provider_id: Option<String>,
422 pub mode: String,
423 pub workspace: PathBuf,
424 pub created_at: DateTime<Utc>,
425 pub started_at: Option<DateTime<Utc>>,
426 pub ended_at: Option<DateTime<Utc>>,
427 pub duration_ms: Option<u64>,
428 #[serde(default)]
429 pub lifecycle_seq: u64,
430 #[serde(skip_serializing_if = "Option::is_none")]
431 pub error: Option<String>,
432 #[serde(default, skip_serializing_if = "Option::is_none")]
433 pub terminal_reason: Option<String>,
434 #[serde(default, skip_serializing_if = "Option::is_none")]
435 pub thread_id: Option<String>,
436 #[serde(default, skip_serializing_if = "Option::is_none")]
437 pub turn_id: Option<String>,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
439 pub owner_session_id: Option<String>,
440 pub execution_binding_known: bool,
441 }
442
443 impl From<&TaskRecord> for TaskSummary {
444 fn from(value: &TaskRecord) -> Self {
445 Self {
446 id: value.id.clone(),
447 status: value.status,
448 prompt_summary: summarize_text(&value.prompt, TIMELINE_SUMMARY_LIMIT),
449 name: value.name.clone(),
450 model: value.model.clone(),
451 model_provider: value.model_provider.clone(),
452 model_provider_id: value.model_provider_id.clone(),
453 mode: value.mode.clone(),
454 workspace: value.workspace.clone(),
455 created_at: value.created_at,
456 started_at: value.started_at,
457 ended_at: value.ended_at,
458 duration_ms: value.duration_ms,
459 lifecycle_seq: value.lifecycle_seq,
460 error: value.error.clone(),
461 terminal_reason: value.terminal_reason.clone(),
462 thread_id: value.thread_id.clone(),
463 turn_id: value.turn_id.clone(),
464 owner_session_id: value.owner_session_id.clone(),
465 execution_binding_known: value.execution_scope.is_some()
466 && (value.status != TaskStatus::Running || value.execution_generation.is_some()),
467 }
468 }
469 }
470
471 /// Count totals by status for task dashboards.
472 #[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
473 pub struct TaskCounts {
474 pub queued: usize,
475 pub running: usize,
476 pub completed: usize,
477 pub failed: usize,
478 pub canceled: usize,
479 }
480
481 /// Request to enqueue a new task.
482 #[derive(Debug, Clone, Serialize, Deserialize)]
483 pub struct NewTaskRequest {
484 pub prompt: String,
485 /// Caller-given run name, stored as-given. Absent names stay absent —
486 /// titles derived from the prompt are a presentation concern.
487 #[serde(default)]
488 pub name: Option<String>,
489 pub model: Option<String>,
490 #[serde(default)]
491 pub model_provider: Option<String>,
492 #[serde(default)]
493 pub model_provider_id: Option<String>,
494 pub workspace: Option<PathBuf>,
495 pub mode: Option<String>,
496 pub allow_shell: Option<bool>,
497 pub trust_mode: Option<bool>,
498 pub auto_approve: Option<bool>,
499 /// Posture for the thread this task runs on. Takes precedence over
500 /// `auto_approve`, which the runtime only reads when no posture is given.
501 pub permission_posture: Option<String>,
502 #[serde(default, skip_serializing_if = "Vec::is_empty")]
503 pub disallowed_tools: Vec<String>,
504 pub owner_session_id: Option<String>,
505 #[serde(default, skip_serializing_if = "Option::is_none")]
506 pub destination_thread_id: Option<String>,
507 }
508
509 impl NewTaskRequest {
510 /// Preserve values already resolved into a staged or accepted task.
511 pub fn from_task(task: &TaskRecord) -> Self {
512 Self {
513 prompt: task.prompt.clone(),
514 name: task.name.clone(),
515 model: Some(task.model.clone()),
516 model_provider: task.model_provider.clone(),
517 model_provider_id: task.model_provider_id.clone(),
518 workspace: Some(task.workspace.clone()),
519 mode: Some(task.mode.clone()),
520 allow_shell: Some(task.allow_shell),
521 trust_mode: Some(task.trust_mode),
522 auto_approve: Some(task.auto_approve),
523 permission_posture: task.permission_posture.clone(),
524 disallowed_tools: task.disallowed_tools.clone(),
525 owner_session_id: task.owner_session_id.clone(),
526 destination_thread_id: task.destination_thread_id.clone(),
527 }
528 }
529
530 #[cfg(any(test, feature = "test-support"))]
531 #[must_use]
532 pub fn from_prompt(prompt: impl Into<String>) -> Self {
533 Self {
534 prompt: prompt.into(),
535 name: None,
536 model: None,
537 model_provider: None,
538 model_provider_id: None,
539 workspace: None,
540 mode: None,
541 allow_shell: None,
542 trust_mode: None,
543 auto_approve: Some(true),
544 permission_posture: None,
545 disallowed_tools: Vec::new(),
546 owner_session_id: None,
547 destination_thread_id: None,
548 }
549 }
550 }
551
552 /// Task manager startup options.
553 #[derive(Debug, Clone)]
554 pub struct TaskManagerConfig {
555 pub data_dir: PathBuf,
556 pub worker_count: usize,
557 pub default_workspace: PathBuf,
558 pub default_model: String,
559 pub default_mode: String,
560 pub allow_shell: bool,
561 pub trust_mode: bool,
562 pub execution_limits: TaskExecutionLimits,
563 /// Whether a host is attached that can actually deliver an approval or
564 /// user-input decision to tasks run by this manager — today only the
565 /// runtime API server, whose HTTP `POST /v1/approvals/{id}` and
566 /// user-input endpoints reach a task thread's engine turn. A pending
567 /// prompt on an answerable manager is a human-paced wait: the wall clock
568 /// pauses for it (bounded by `human_wait_cap`), extending the turn
569 /// layer's own human-wait exclusion to the durable task layer. A prompt
570 /// on an unanswerable manager can never be answered, so arming the
571 /// window there would park the worker on the fail-safe cap; the wall
572 /// clock keeps running instead, exactly as before this opt-in.
573 /// Defaults to `false`: opt in only where the delivery channel exists.
574 /// The gate arms the built-in engine executor's journal tracking; a
575 /// custom executor that emits the `HumanWaitStarted`/`HumanWaitEnded`
576 /// pair is self-declaring its waits answerable, and the supervisor
577 /// honors the pair regardless of this flag.
578 pub human_waits_answerable: bool,
579 }
580
581 /// Deadlines and persistence cadence for one durable execution.
582 #[derive(Debug, Clone, Copy)]
583 pub struct TaskExecutionLimits {
584 pub wall_time: Duration,
585 pub idle_progress: Duration,
586 pub cancel_grace: Duration,
587 pub persist_debounce: Duration,
588 /// Fail-safe ceiling for the human-wait windows of one task, applied
589 /// both to each open window and to the windows summed across the whole
590 /// execution. Human-paced waits are excluded from `wall_time` — a slow
591 /// answer must not end the task — but prompts that nobody will ever
592 /// answer must still release the worker eventually.
593 pub human_wait_cap: Duration,
594 }
595
596 impl Default for TaskExecutionLimits {
597 fn default() -> Self {
598 Self {
599 wall_time: Duration::from_secs(30 * 60),
600 idle_progress: Duration::from_secs(2 * 60),
601 cancel_grace: Duration::from_secs(5),
602 persist_debounce: Duration::from_millis(250),
603 human_wait_cap: Duration::from_secs(30 * 60),
604 }
605 }
606 }
607
608 #[cfg(test)]
609 impl TaskExecutionLimits {
610 fn short_for_tests() -> Self {
611 Self {
612 wall_time: Duration::from_millis(400),
613 idle_progress: Duration::from_millis(150),
614 cancel_grace: Duration::from_millis(50),
615 persist_debounce: Duration::from_millis(10),
616 human_wait_cap: Duration::from_millis(300),
617 }
618 }
619 }
620
621 /// Pure watchdog for cancel grace, wall time, idle progress, and human-wait
622 /// exclusion.
623 struct ExecutionGuard {
624 started_at: Instant,
625 last_progress_at: Instant,
626 interrupt_at: Option<Instant>,
627 interrupt_reason: Option<TaskTerminalReason>,
628 /// Open human wait (pending approval or user-input prompt), if any.
629 /// Human-paced wall time is excluded from `wall_time` exactly like the
630 /// turn layer's budget excludes it (`TurnWallClock::begin_human_wait` in
631 /// `codewhale-runtime`: "the budget bounds what the agent spends on its
632 /// own, not how long a person takes to answer") — an answer submitted
633 /// past the budget must complete the task, not be collected and dropped.
634 human_wait_since: Option<Instant>,
635 human_wait_total: Duration,
636 limits: TaskExecutionLimits,
637 }
638
639 #[derive(Debug)]
640 enum GuardAction {
641 Run { wait: Duration },
642 Interrupt { reason: TaskTerminalReason },
643 Terminalize { reason: TaskTerminalReason },
644 }
645
646 impl ExecutionGuard {
647 fn new(limits: TaskExecutionLimits, now: Instant) -> Self {
648 Self {
649 started_at: now,
650 last_progress_at: now,
651 interrupt_at: None,
652 interrupt_reason: None,
653 human_wait_since: None,
654 human_wait_total: Duration::ZERO,
655 limits,
656 }
657 }
658
659 /// Mark the start of a human-paced wait (idempotent). Only the first
660 /// begin of an unmatched begin/end pair takes effect, and none does once
661 /// the wall deadline has already passed: that crossing still ends the
662 /// task instead of being moved past the prompt.
663 ///
664 /// Windows merge rather than stack: the first begin sets the origin and
665 /// any end closes the whole window. That is sound because the engine
666 /// blocks inside a single prompt at a time — approval and user-input
667 /// waits are serial within a turn, and parallel batches exclude
668 /// interactive tools — so overlapping windows never reach this guard
669 /// today. If a future change lets nested prompts surface concurrently,
670 /// switch to paired (counted) windows first.
671 fn begin_human_wait(&mut self, now: Instant) {
672 if self.human_wait_since.is_none() && self.wall_deadline().is_none_or(|wall| now < wall) {
673 self.human_wait_since = Some(now);
674 }
675 }
676
677 /// Mark the end of a human-paced wait (idempotent). The idle budget
678 /// restarts fresh: the engine is expected to think and act again after
679 /// an answer, and window silence was expected, not idleness.
680 fn end_human_wait(&mut self, now: Instant) {
681 if let Some(since) = self.human_wait_since.take() {
682 self.human_wait_total += now.saturating_duration_since(since);
683 self.last_progress_at = now;
684 }
685 }
686
687 /// Wall time attributable to the engine itself: excludes every closed
688 /// human-wait window and the currently open one.
689 fn engine_wall_elapsed(&self, now: Instant) -> Duration {
690 let open = self
691 .human_wait_since
692 .map(|since| now.saturating_duration_since(since))
693 .unwrap_or_default();
694 now.saturating_duration_since(self.started_at)
695 .saturating_sub(self.human_wait_total)
696 .saturating_sub(open)
697 }
698
699 fn wall_deadline(&self) -> Option<Instant> {
700 self.started_at
701 .checked_add(self.limits.wall_time)
702 .and_then(|deadline| deadline.checked_add(self.human_wait_total))
703 }
704
705 /// Attribute the timeout to the limit that was crossed first, not to the
706 /// one this tick happens to check first. When the watchdog is starved
707 /// past both deadlines (a >=250 ms scheduler stall on a loaded CI runner
708 /// is enough with the test budgets), the idle limit that expired earlier
709 /// is still the truthful reason; a tie keeps the wall limit's precedence
710 /// (issue #5898). The wall deadline moves with every closed human-wait
711 /// window, so it stays `wall_time` away from the engine-owned elapsed
712 /// time rather than from the raw wall clock.
713 fn crossed_deadline(&self, now: Instant) -> Option<TaskTerminalReason> {
714 let idle_deadline = self.last_progress_at.checked_add(self.limits.idle_progress);
715 match (self.wall_deadline(), idle_deadline) {
716 (Some(wall), Some(idle)) if now >= wall && wall <= idle => {
717 Some(TaskTerminalReason::WallTimeout)
718 }
719 (_, Some(idle)) if now >= idle => Some(TaskTerminalReason::IdleTimeout),
720 (Some(wall), _) if now >= wall => Some(TaskTerminalReason::WallTimeout),
721 _ => None,
722 }
723 }
724
725 fn note_progress(&mut self, now: Instant) {
726 self.last_progress_at = now;
727 }
728
729 fn note_interrupt(&mut self, now: Instant, reason: TaskTerminalReason) {
730 if self.interrupt_at.is_none() {
731 self.interrupt_at = Some(now);
732 self.interrupt_reason = Some(reason);
733 }
734 }
735
736 fn evaluate(&self, now: Instant, cancel: bool, shutdown: bool) -> GuardAction {
737 if let Some(interrupt_at) = self.interrupt_at {
738 let elapsed = now.saturating_duration_since(interrupt_at);
739 if elapsed >= self.limits.cancel_grace {
740 let reason = self
741 .interrupt_reason
742 .unwrap_or(TaskTerminalReason::CancelTimeout)
743 .after_grace();
744 return GuardAction::Terminalize { reason };
745 }
746 return GuardAction::Run {
747 wait: self.limits.cancel_grace.saturating_sub(elapsed),
748 };
749 }
750
751 let wall_elapsed = self.engine_wall_elapsed(now);
752 // The human-wait exclusion is bounded by a fail-safe cap: a prompt
753 // that sits unanswered far past any plausible human pace still
754 // releases the worker instead of parking it forever. While the
755 // window is open both clocks pause — silence during a human decision
756 // is expected, not idleness — and the idle budget restarts when the
757 // window closes (see `end_human_wait`).
758 let idle_elapsed = now.saturating_duration_since(self.last_progress_at);
759 let pending = if shutdown {
760 Some(TaskTerminalReason::Shutdown)
761 } else if cancel {
762 Some(TaskTerminalReason::Canceled)
763 } else if let Some(since) = self.human_wait_since {
764 let parked = now.saturating_duration_since(since);
765 if self.human_wait_total.saturating_add(parked) >= self.limits.human_wait_cap {
766 Some(TaskTerminalReason::HumanWaitTimeout)
767 } else {
768 None
769 }
770 } else if self.human_wait_total >= self.limits.human_wait_cap {
771 // The aggregate bound: each window may close under the cap, but
772 // a task chaining prompts must not sum its way past the cap once
773 // per prompt. With no window open right now, the closed windows
774 // alone can cross it, so the accumulated total terminalizes the
775 // task even between windows.
776 Some(TaskTerminalReason::HumanWaitTimeout)
777 } else {
778 self.crossed_deadline(now)
779 };
780 if let Some(reason) = pending {
781 return GuardAction::Interrupt { reason };
782 }
783
784 let mut wait = self
785 .limits
786 .wall_time
787 .saturating_sub(wall_elapsed)
788 .min(self.limits.idle_progress.saturating_sub(idle_elapsed));
789 if let Some(since) = self.human_wait_since {
790 // Both clocks are paused; the only deadline left is the
791 // fail-safe cap. A parked window can last hours, so polling
792 // the journal at the catch-up cadence for that whole span is
793 // waste: back the poll off, doubling with each parked second
794 // up to PARKED_POLL_CAP. An arriving decision wakes this loop
795 // early — the turn loop through the runtime event
796 // subscription, the worker supervisor through the forwarded
797 // task event — so the backoff never delays an answer; it only
798 // thins the empty polls, and only while the event bus is
799 // quiet. The cap wait excludes the already-closed windows too:
800 // the aggregate budget, not this window alone, bounds the
801 // sleep.
802 let parked = now.saturating_duration_since(since);
803 let cap_wait = self
804 .limits
805 .human_wait_cap
806 .saturating_sub(self.human_wait_total)
807 .saturating_sub(parked);
808 let backoff = EVENT_CATCHUP_POLL
809 .saturating_mul(1u32 << parked.as_secs().min(4))
810 .min(PARKED_POLL_CAP);
811 wait = cap_wait.min(backoff);
812 } else {
813 wait = wait.min(EVENT_CATCHUP_POLL);
814 }
815 GuardAction::Run {
816 wait: wait.max(Duration::from_millis(1)),
817 }
818 }
819
820 fn preserve_timeout_reason(&self, result: TaskExecutionResult) -> TaskExecutionResult {
821 if result.terminal_reason != TaskTerminalReason::Canceled {
822 return result;
823 }
824 match self.interrupt_reason {
825 Some(
826 reason @ (TaskTerminalReason::WallTimeout
827 | TaskTerminalReason::HumanWaitTimeout
828 | TaskTerminalReason::IdleTimeout),
829 ) => TaskExecutionResult::from_reason(reason, result.result_text),
830 _ => result,
831 }
832 }
833 }
834
835 impl TaskManagerConfig {
836 #[must_use]
837 pub fn from_runtime(
838 config: &Config,
839 workspace: PathBuf,
840 default_model: Option<String>,
841 worker_count: Option<usize>,
842 ) -> Self {
843 Self {
844 data_dir: default_tasks_dir(),
845 worker_count: worker_count.unwrap_or(DEFAULT_WORKERS),
846 default_workspace: workspace,
847 default_model: default_model.unwrap_or_else(|| config.default_model()),
848 default_mode: "agent".to_string(),
849 allow_shell: config.allow_shell(),
850 trust_mode: false,
851 execution_limits: TaskExecutionLimits {
852 human_wait_cap: config.task_human_wait_cap(),
853 ..TaskExecutionLimits::default()
854 },
855 human_waits_answerable: false,
856 }
857 }
858 }
859
860 #[derive(Debug, Clone)]
861 pub struct ExecutionTask {
862 thread_origin: Option<ThreadOrigin>,
863 id: String,
864 prompt: String,
865 model: String,
866 model_provider: Option<String>,
867 model_provider_id: Option<String>,
868 workspace: PathBuf,
869 mode_label: String,
870 allow_shell: bool,
871 trust_mode: bool,
872 auto_approve: bool,
873 permission_posture: Option<String>,
874 disallowed_tools: Vec<String>,
875 destination_thread_id: Option<String>,
876 }
877
878 impl From<&TaskRecord> for ExecutionTask {
879 fn from(task: &TaskRecord) -> Self {
880 Self {
881 thread_origin: task.thread_origin,
882 id: task.id.clone(),
883 prompt: task.prompt.clone(),
884 model: task.model.clone(),
885 model_provider: task.model_provider.clone(),
886 model_provider_id: task.model_provider_id.clone(),
887 workspace: task.workspace.clone(),
888 mode_label: task.mode.clone(),
889 allow_shell: task.allow_shell,
890 trust_mode: task.trust_mode,
891 auto_approve: task.auto_approve,
892 permission_posture: task.permission_posture.clone(),
893 disallowed_tools: task.disallowed_tools.clone(),
894 destination_thread_id: task.destination_thread_id.clone(),
895 }
896 }
897 }
898
899 impl ExecutionTask {
900 pub fn thread_request(&self) -> CreateThreadRequest {
901 CreateThreadRequest {
902 model: Some(self.model.clone()),
903 model_provider: self.model_provider.clone(),
904 model_provider_id: self.model_provider_id.clone(),
905 workspace: Some(self.workspace.clone()),
906 mode: Some(self.mode_label.clone()),
907 allow_shell: Some(self.allow_shell),
908 trust_mode: Some(self.trust_mode),
909 auto_approve: Some(self.auto_approve),
910 permission_posture: self.permission_posture.clone(),
911 disallowed_tools: self.disallowed_tools.clone(),
912 task_id: Some(self.id.clone()),
913 ..Default::default()
914 }
915 }
916
917 /// The turn request for this task. A task that carries a pinned posture
918 /// runs its turn under that posture: the legacy `auto_approve` bit is only
919 /// sent for records that predate the pinned posture, because a per-turn
920 /// `auto_approve` without a posture re-derives the permission from the
921 /// bit alone and would override what the thread was created with.
922 pub fn turn_request(&self) -> StartTurnRequest {
923 let pinned = self.permission_posture.is_some();
924 StartTurnRequest {
925 prompt: self.prompt.clone(),
926 input_summary: Some(summarize_text(&self.prompt, TIMELINE_SUMMARY_LIMIT)),
927 model: Some(self.model.clone()),
928 mode: Some(self.mode_label.clone()),
929 permission_posture: self.permission_posture.clone(),
930 allow_shell: Some(self.allow_shell),
931 trust_mode: Some(self.trust_mode),
932 auto_approve: (!pinned).then_some(self.auto_approve),
933 ..Default::default()
934 }
935 }
936 }
937
938 /// Event stream produced by an executor while a task runs.
939 #[derive(Debug, Clone)]
940 pub enum TaskExecutionEvent {
941 ThreadLinked {
942 thread_id: String,
943 turn_id: String,
944 },
945 Status {
946 message: String,
947 },
948 MessageDelta {
949 content: String,
950 },
951 ToolStarted {
952 id: String,
953 name: String,
954 input: Value,
955 },
956 ToolProgress {
957 id: String,
958 output: String,
959 },
960 /// Emitted while a journal-tracked tool is in flight but the journal is
961 /// silent, so the worker supervisor's idle watchdog counts the window as
962 /// progress instead of idle. Supervisor-side liveness signal only: never
963 /// persisted and never shown on the task timeline.
964 ToolHeartbeat,
965 /// A human-paced wait (pending approval or user-input prompt) opened or
966 /// closed, so the worker supervisor's wall clock can exclude it exactly
967 /// like the turn loop's own guard does. Supervisor-side signal only:
968 /// never persisted and never shown on the task timeline. The built-in
969 /// engine executor emits the pair only where `human_waits_answerable`
970 /// armed the window; a custom executor that emits it is self-declaring
971 /// its waits answerable, and the supervisor honors the pair regardless
972 /// of that flag. `at` is when the prompt was recorded — the journal
973 /// timestamp for the built-in executor — so the supervisor can open
974 /// and close the window at the recorded instant rather than at
975 /// channel-consumption time.
976 HumanWaitStarted {
977 at: DateTime<Utc>,
978 },
979 HumanWaitEnded {
980 at: DateTime<Utc>,
981 },
982 ToolCompleted {
983 id: String,
984 name: String,
985 success: bool,
986 output: String,
987 metadata: Option<Value>,
988 },
989 Error {
990 message: String,
991 },
992 RuntimeEvent {
993 seq: u64,
994 event: String,
995 summary: String,
996 },
997 }
998
999 /// Final executor result.
1000 #[derive(Debug, Clone)]
1001 pub struct TaskExecutionResult {
1002 pub status: TaskStatus,
1003 pub result_text: Option<String>,
1004 pub error: Option<String>,
1005 pub terminal_reason: TaskTerminalReason,
1006 }
1007
1008 impl TaskExecutionResult {
1009 fn failed(error: impl Into<String>) -> Self {
1010 Self {
1011 status: TaskStatus::Failed,
1012 result_text: None,
1013 error: Some(error.into()),
1014 terminal_reason: TaskTerminalReason::Failed,
1015 }
1016 }
1017
1018 fn from_reason(reason: TaskTerminalReason, result_text: Option<String>) -> Self {
1019 let error = match reason {
1020 TaskTerminalReason::Completed | TaskTerminalReason::Canceled => None,
1021 _ => Some(reason.receipt_message()),
1022 };
1023 Self {
1024 status: reason.task_status(),
1025 result_text,
1026 error,
1027 terminal_reason: reason,
1028 }
1029 }
1030 }
1031
1032 /// Abstraction for task execution.
1033 #[async_trait]
1034 pub trait TaskExecutor: Send + Sync {
1035 async fn execute(
1036 &self,
1037 task: ExecutionTask,
1038 events: mpsc::Sender<TaskExecutionEvent>,
1039 cancel: CancellationToken,
1040 ) -> TaskExecutionResult;
1041
1042 /// Test seam for the server wiring pin: the built-in executor as the
1043 /// manager actually received it, so the pin reads the answerability flag
1044 /// where `start_with_runtime_manager` forwarded it. Custom executors
1045 /// keep the default — there is nothing to expose.
1046 #[cfg(any(test, feature = "test-support"))]
1047 fn as_engine_executor(&self) -> Option<&EngineTaskExecutor> {
1048 None
1049 }
1050 }
1051
1052 /// Executor backed by the shared runtime and its canonical provider resolver.
1053 pub struct EngineTaskExecutor {
1054 runtime_threads: SharedRuntimeThreadManager,
1055 limits: TaskExecutionLimits,
1056 /// Whether a host exists that can actually deliver an approval or
1057 /// user-input decision to this runtime surface. Only the runtime API
1058 /// server's HTTP decision endpoints reach a task thread's engine turn;
1059 /// a host without such a channel — the TUI's private task runtime —
1060 /// cannot answer a prompt, so arming the human-wait window for it
1061 /// would park the worker on the fail-safe cap instead of the wall.
1062 answerable_waits: bool,
1063 }
1064
1065 impl EngineTaskExecutor {
1066 #[must_use]
1067 pub fn new(
1068 runtime_threads: SharedRuntimeThreadManager,
1069 limits: TaskExecutionLimits,
1070 answerable_waits: bool,
1071 ) -> Self {
1072 Self {
1073 runtime_threads,
1074 limits,
1075 answerable_waits,
1076 }
1077 }
1078
1079 /// Whether this executor arms human-wait windows. Test seam for the
1080 /// server wiring pin, which reads the flag where it lands.
1081 #[cfg(any(test, feature = "test-support"))]
1082 #[must_use]
1083 pub fn answerable_waits(&self) -> bool {
1084 self.answerable_waits
1085 }
1086 }
1087
1088 #[async_trait]
1089 impl TaskExecutor for EngineTaskExecutor {
1090 async fn execute(
1091 &self,
1092 task: ExecutionTask,
1093 events: mpsc::Sender<TaskExecutionEvent>,
1094 cancel: CancellationToken,
1095 ) -> TaskExecutionResult {
1096 if cancel.is_cancelled() {
1097 return TaskExecutionResult::from_reason(TaskTerminalReason::Canceled, None);
1098 }
1099 let (thread_id, turn) = if let Some(destination) = task.destination_thread_id.clone() {
1100 if !task.disallowed_tools.is_empty() {
1101 match self.runtime_threads.get_thread(&destination).await {
1102 Ok(thread)
1103 if deny_rules_cover(&thread.disallowed_tools, &task.disallowed_tools) => {}
1104 Ok(_) => {
1105 return TaskExecutionResult::failed(format!(
1106 "Destination thread {destination} does not run under the deny rules this task was created with"
1107 ));
1108 }
1109 Err(err) => {
1110 return TaskExecutionResult::failed(format!(
1111 "Destination thread {destination} cannot take this turn: {err}"
1112 ));
1113 }
1114 }
1115 }
1116 let deadline = Instant::now() + self.limits.wall_time;
1117 let turn = loop {
1118 match self
1119 .runtime_threads
1120 .start_scheduled_turn(&destination, &task.prompt, &task.id, &task.workspace)
1121 .await
1122 {
1123 Ok(Some(turn)) => break turn,
1124 Ok(None) if Instant::now() < deadline => {
1125 tokio::select! {
1126 () = cancel.cancelled() => {
1127 return TaskExecutionResult::from_reason(
1128 TaskTerminalReason::Canceled,
1129 None,
1130 );
1131 }
1132 () = tokio::time::sleep(DESTINATION_BUSY_RETRY) => {}
1133 }
1134 }
1135 Ok(None) => {
1136 return TaskExecutionResult::failed(format!(
1137 "Destination thread {destination} stayed busy past the task wall-time budget"
1138 ));
1139 }
1140 Err(err) => {
1141 return TaskExecutionResult::failed(format!(
1142 "Destination thread {destination} cannot take this turn: {err}"
1143 ));
1144 }
1145 }
1146 };
1147 (destination, turn)
1148 } else {
1149 let thread = match self
1150 .runtime_threads
1151 .create_thread_with_origin(task.thread_request(), task.thread_origin)
1152 .await
1153 {
1154 Ok(thread) => thread,
1155 Err(err) => {
1156 return TaskExecutionResult::failed(format!(
1157 "Failed to create runtime thread: {err}"
1158 ));
1159 }
1160 };
1161
1162 if cancel.is_cancelled() {
1163 return TaskExecutionResult::from_reason(TaskTerminalReason::Canceled, None);
1164 }
1165 match self
1166 .runtime_threads
1167 .start_task_turn(&thread.id, task.turn_request(), &task.id)
1168 .await
1169 {
1170 Ok(turn) => (thread.id, turn),
1171 Err(err) => {
1172 return TaskExecutionResult::failed(format!("Failed to start task: {err}"));
1173 }
1174 }
1175 };
1176
1177 emit_task_event(
1178 &events,
1179 TaskExecutionEvent::ThreadLinked {
1180 thread_id: thread_id.clone(),
1181 turn_id: turn.id.clone(),
1182 },
1183 )
1184 .await;
1185 emit_task_event(
1186 &events,
1187 TaskExecutionEvent::Status {
1188 message: format!("Task {} started", task.id),
1189 },
1190 )
1191 .await;
1192
1193 drive_engine_turn(
1194 self.runtime_threads.as_ref(),
1195 &thread_id,
1196 &turn.id,
1197 events,
1198 cancel,
1199 self.limits,
1200 self.answerable_waits,
1201 )
1202 .await
1203 }
1204
1205 #[cfg(any(test, feature = "test-support"))]
1206 fn as_engine_executor(&self) -> Option<&EngineTaskExecutor> {
1207 Some(self)
1208 }
1209 }
1210
1211 /// Drive one engine turn to its terminal state under the supervisor guard.
1212 ///
1213 /// `answerable_waits` carries [`EngineTaskExecutor`]'s answerability
1214 /// decision: with no host able to deliver a decision, a pending prompt is
1215 /// not a human-paced wait but a prompt nobody will answer, so the wall
1216 /// clock keeps running and releases the worker at its own deadline.
1217 async fn drive_engine_turn(
1218 runtime_threads: &RuntimeThreadManager,
1219 thread_id: &str,
1220 turn_id: &str,
1221 events: mpsc::Sender<TaskExecutionEvent>,
1222 cancel: CancellationToken,
1223 limits: TaskExecutionLimits,
1224 answerable_waits: bool,
1225 ) -> TaskExecutionResult {
1226 let mut subscription = runtime_threads.subscribe_events();
1227 let guard_started_at = Instant::now();
1228 let guard_started_wall = Utc::now();
1229 let mut guard = ExecutionGuard::new(limits, guard_started_at);
1230 let mut final_text = RuntimeTaskOutput::default();
1231 let mut cursor = 0u64;
1232 let mut terminal_status: Option<RuntimeTurnStatus> = None;
1233 let mut terminal_error: Option<String> = None;
1234 // Approval requests this turn is waiting on, each with the deadline the
1235 // runtime bridge will resolve it by (#6118).
1236 let mut pending_approvals: HashMap<String, Instant> = HashMap::new();
1237 // Journal ids of tool items currently in flight. The journal records a
1238 // tool call only at start/completion — nothing in between — so the
1239 // idle-progress deadline would run unopposed during any silent build,
1240 // test suite, or MCP call and kill healthy work at the idle limit. A
1241 // tool that is still running IS progress; the wall-time budget remains
1242 // the backstop for a hung one (a genuinely stuck tool also hits its own
1243 // execution timeout long before a 30-minute wall budget in the common
1244 // case). Both lifecycle edges are keyed by the journal item id:
1245 // item.started also carries the engine tool-use id under "tool", but
1246 // the terminal events only carry "item", so keying the insert by
1247 // tool-use id would never drain the set.
1248 let mut running_tools: HashSet<String> = HashSet::new();
1249
1250 loop {
1251 let batch = match runtime_threads
1252 .events_from_offset_async(thread_id, cursor, Some(EVENT_CURSOR_BATCH))
1253 .await
1254 {
1255 Ok((batch, next_cursor)) => {
1256 cursor = next_cursor;
1257 batch
1258 }
1259 Err(err) => {
1260 return TaskExecutionResult {
1261 status: TaskStatus::Failed,
1262 result_text: final_text.into_result(true),
1263 error: Some(format!("Failed to read runtime events: {err}")),
1264 terminal_reason: TaskTerminalReason::Failed,
1265 };
1266 }
1267 };
1268
1269 let more_pending = batch.len() >= EVENT_CURSOR_BATCH;
1270 for event in batch {
1271 if event.thread_id != thread_id {
1272 continue;
1273 }
1274 if event
1275 .turn_id
1276 .as_deref()
1277 .is_some_and(|event_turn| event_turn != turn_id)
1278 {
1279 continue;
1280 }
1281 match event.event.as_str() {
1282 "item.started" => {
1283 // Journal tool items carry a `tool` payload key;
1284 // non-tool items do not. A silent context compaction is
1285 // therefore invisible to this set (disclosed gap: a
1286 // background task mid-compaction can still hit the idle
1287 // deadline — compaction has no heartbeat of its own).
1288 if event.payload.get("tool").is_some()
1289 && let Some(item_id) = journal_item_id(&event)
1290 {
1291 running_tools.insert(item_id);
1292 }
1293 }
1294 "item.completed" | "item.failed" => {
1295 if let Some(item_id) = journal_item_id(&event) {
1296 running_tools.remove(&item_id);
1297 }
1298 }
1299 _ => {}
1300 }
1301 match event.event.as_str() {
1302 // An approval parks the turn on an external decision until
1303 // the runtime bridge answers or its own window closes; note
1304 // that deadline so the idle watchdog stays off it (#6118).
1305 "approval.required" => {
1306 let approval_id = event
1307 .payload
1308 .get("approval_id")
1309 .and_then(Value::as_str)
1310 .map(ToString::to_string)
1311 .unwrap_or_else(|| format!("approval-{}", event.seq));
1312 let until = match runtime_threads.approval_decision_timeout() {
1313 Some(wait) => Instant::now() + wait,
1314 // `0` waits indefinitely by configuration. On an
1315 // unanswerable manager the wall deadline still
1316 // bounds the run; on an answerable one
1317 // (`human_waits_answerable`) the wall pauses while
1318 // the prompt is pending and `human_wait_cap` bounds
1319 // it instead.
1320 None => Instant::now() + limits.wall_time,
1321 };
1322 pending_approvals.insert(approval_id, until);
1323 }
1324 "approval.decided" => {
1325 if let Some(approval_id) =
1326 event.payload.get("approval_id").and_then(Value::as_str)
1327 {
1328 pending_approvals.remove(approval_id);
1329 }
1330 }
1331 _ => {}
1332 }
1333 match event.event.as_str() {
1334 // A pending approval or user-input prompt is a human-paced
1335 // wait: exclude it from the wall clock exactly like the
1336 // turn layer's budget does (`TurnWallClock::begin_human_wait`
1337 // in `codewhale-runtime`), and publish the window so the
1338 // worker supervisor's guard follows in lockstep. Both arms
1339 // are gated on `answerable_waits`, so the window pair only
1340 // flows where a decision can actually be delivered. Every
1341 // wait exit emits one of the paired closing events (the
1342 // decision, the interrupt deny, the bridge's timeout
1343 // denial, or the cancellation), so the window cannot stick
1344 // open; the guard's fail-safe cap bounds the pathological
1345 // case regardless.
1346 "approval.required" | "user_input.required" if answerable_waits => {
1347 guard.begin_human_wait(journal_instant(
1348 guard_started_at,
1349 guard_started_wall,
1350 event.timestamp,
1351 Instant::now(),
1352 ));
1353 emit_task_event(
1354 &events,
1355 TaskExecutionEvent::HumanWaitStarted {
1356 at: event.timestamp,
1357 },
1358 )
1359 .await;
1360 }
1361 "approval.decided"
1362 | "approval.timeout"
1363 | "user_input.answered"
1364 | "user_input.canceled"
1365 if answerable_waits =>
1366 {
1367 guard.end_human_wait(journal_instant(
1368 guard_started_at,
1369 guard_started_wall,
1370 event.timestamp,
1371 Instant::now(),
1372 ));
1373 emit_task_event(
1374 &events,
1375 TaskExecutionEvent::HumanWaitEnded {
1376 at: event.timestamp,
1377 },
1378 )
1379 .await;
1380 }
1381 _ => {}
1382 }
1383 if runtime_event_is_progress(&event) {
1384 guard.note_progress(Instant::now());
1385 }
1386 if let Some((status, error)) =
1387 ingest_runtime_event(&event, &mut final_text, &events).await
1388 {
1389 // The decision window closed on a pending approval: the
1390 // runtime already denied the tool, and an unattended run has
1391 // no operator to answer, so stop the turn instead of letting
1392 // it keep burning under a failure nobody sees (#6118).
1393 if event.event.as_str() == "approval.timeout" {
1394 let _ = runtime_threads.interrupt_turn(thread_id, turn_id).await;
1395 }
1396 terminal_status = Some(status);
1397 terminal_error = error;
1398 }
1399 }
1400
1401 if terminal_status.is_some() {
1402 break;
1403 }
1404
1405 // While an approval is pending the turn is deliberately waiting on an
1406 // external decision, not drifting: keep the idle deadline from firing
1407 // so the bridge's own window can resolve and record it. Entries expire
1408 // with their window, so a decision that never arrives cannot suspend
1409 // the watchdog forever (#6118).
1410 let now = Instant::now();
1411 pending_approvals.retain(|_, until| now < *until);
1412 if !pending_approvals.is_empty() {
1413 guard.note_progress(now);
1414 }
1415
1416 // Steady-state progress refresh: the journal is silent for the whole
1417 // execution window of an in-flight tool, so the idle check must be
1418 // suppressed for as long as any tool is running — not only on event
1419 // arrival. The loop below wakes at least every EVENT_CATCHUP_POLL,
1420 // so this runs throughout silent builds, test suites, and MCP calls.
1421 if !running_tools.is_empty() {
1422 guard.note_progress(now);
1423 // The worker supervisor (run_task) feeds its own guard from the
1424 // task-event channel and cannot see this journal-derived set, so
1425 // without a heartbeat its idle deadline would still fire on the
1426 // only production path that runs this loop. Publish the in-flight
1427 // window on that channel; the heartbeat refreshes the supervisor's
1428 // idle clock and is deliberately not persisted or surfaced.
1429 emit_task_event(&events, TaskExecutionEvent::ToolHeartbeat).await;
1430 }
1431
1432 match guard.evaluate(now, cancel.is_cancelled(), false) {
1433 GuardAction::Interrupt { reason } => {
1434 let _ = runtime_threads.interrupt_turn(thread_id, turn_id).await;
1435 emit_task_event(
1436 &events,
1437 TaskExecutionEvent::Status {
1438 message: reason.receipt_message(),
1439 },
1440 )
1441 .await;
1442 guard.note_interrupt(Instant::now(), reason);
1443 }
1444 GuardAction::Terminalize { reason } => {
1445 return TaskExecutionResult::from_reason(reason, final_text.into_result(true));
1446 }
1447 GuardAction::Run { wait } => {
1448 if more_pending {
1449 continue;
1450 }
1451 tokio::select! {
1452 _ = cancel.cancelled(), if !cancel.is_cancelled() => {}
1453 _ = subscription.recv() => {}
1454 _ = sleep(wait) => {}
1455 }
1456 }
1457 }
1458 }
1459
1460 let result = match terminal_status.unwrap_or(RuntimeTurnStatus::Failed) {
1461 RuntimeTurnStatus::Completed => TaskExecutionResult {
1462 status: TaskStatus::Completed,
1463 result_text: final_text.into_result(false),
1464 error: None,
1465 terminal_reason: TaskTerminalReason::Completed,
1466 },
1467 RuntimeTurnStatus::Interrupted | RuntimeTurnStatus::Canceled => TaskExecutionResult {
1468 status: TaskStatus::Canceled,
1469 result_text: final_text.into_result(true),
1470 error: None,
1471 terminal_reason: TaskTerminalReason::Canceled,
1472 },
1473 RuntimeTurnStatus::Queued | RuntimeTurnStatus::InProgress | RuntimeTurnStatus::Failed => {
1474 TaskExecutionResult {
1475 status: TaskStatus::Failed,
1476 result_text: final_text.into_result(true),
1477 error: terminal_error
1478 .or_else(|| Some(TaskTerminalReason::Failed.receipt_message())),
1479 terminal_reason: TaskTerminalReason::Failed,
1480 }
1481 }
1482 };
1483 guard.preserve_timeout_reason(result)
1484 }
1485
1486 fn journal_instant(
1487 anchor: Instant,
1488 anchor_wall: DateTime<Utc>,
1489 timestamp: DateTime<Utc>,
1490 now: Instant,
1491 ) -> Instant {
1492 let mapped = match timestamp.signed_duration_since(anchor_wall).to_std() {
1493 Ok(offset) => anchor.checked_add(offset).unwrap_or(now),
1494 Err(_) => anchor,
1495 };
1496 mapped.min(now)
1497 }
1498
1499 async fn emit_task_event(events: &mpsc::Sender<TaskExecutionEvent>, event: TaskExecutionEvent) {
1500 let _ = events.send(event).await;
1501 }
1502
1503 fn optional_nonzero_text(text: String) -> Option<String> {
1504 if text.trim().is_empty() {
1505 None
1506 } else {
1507 Some(text)
1508 }
1509 }
1510
1511 /// A task result is the last message, not concatenated progress commentary.
1512 /// Only interrupted/failed execution may return a still-streaming message.
1513 #[derive(Default)]
1514 struct RuntimeTaskOutput {
1515 text: String,
1516 completed: bool,
1517 }
1518
1519 impl RuntimeTaskOutput {
1520 fn into_result(self, allow_partial: bool) -> Option<String> {
1521 (self.completed || allow_partial)
1522 .then(|| optional_nonzero_text(self.text))
1523 .flatten()
1524 }
1525 }
1526
1527 fn append_message_delta(result_text: &mut String, event: &TaskExecutionEvent) {
1528 if let TaskExecutionEvent::MessageDelta { content } = event {
1529 result_text.push_str(content);
1530 }
1531 }
1532
1533 fn runtime_event_is_progress(event: &RuntimeEventRecord) -> bool {
1534 matches!(
1535 event.event.as_str(),
1536 "item.delta" | "item.started" | "item.completed" | "item.failed" | "turn.completed"
1537 )
1538 }
1539
1540 /// The journal receipt id of the item a lifecycle event carries. Every
1541 /// lifecycle edge (`item.started` / `item.completed` / `item.failed`) repeats
1542 /// it under `payload.item.id`, which is what makes it a stable tracking key
1543 /// across both edges of one tool call.
1544 fn journal_item_id(event: &RuntimeEventRecord) -> Option<String> {
1545 event
1546 .payload
1547 .get("item")
1548 .and_then(|item| item.get("id"))
1549 .and_then(Value::as_str)
1550 .map(str::to_string)
1551 }
1552
1553 async fn ingest_runtime_event(
1554 event: &RuntimeEventRecord,
1555 final_text: &mut RuntimeTaskOutput,
1556 events: &mpsc::Sender<TaskExecutionEvent>,
1557 ) -> Option<(RuntimeTurnStatus, Option<String>)> {
1558 emit_task_event(
1559 events,
1560 TaskExecutionEvent::RuntimeEvent {
1561 seq: event.seq,
1562 event: event.event.clone(),
1563 summary: summarize_text(&event.payload.to_string(), TIMELINE_SUMMARY_LIMIT),
1564 },
1565 )
1566 .await;
1567
1568 match event.event.as_str() {
1569 "item.delta" => {
1570 let kind = event
1571 .payload
1572 .get("kind")
1573 .and_then(Value::as_str)
1574 .unwrap_or_default();
1575 if kind == "agent_message" {
1576 if let Some(content) = event.payload.get("delta").and_then(Value::as_str) {
1577 final_text.text.push_str(content);
1578 final_text.completed = false;
1579 emit_task_event(
1580 events,
1581 TaskExecutionEvent::MessageDelta {
1582 content: content.to_string(),
1583 },
1584 )
1585 .await;
1586 }
1587 } else if kind == "tool_call" {
1588 let output = event
1589 .payload
1590 .get("delta")
1591 .and_then(Value::as_str)
1592 .unwrap_or_default()
1593 .to_string();
1594 emit_task_event(
1595 events,
1596 TaskExecutionEvent::ToolProgress {
1597 id: event.item_id.clone().unwrap_or_default(),
1598 output,
1599 },
1600 )
1601 .await;
1602 }
1603 None
1604 }
1605 "item.started" => {
1606 if event.payload.pointer("/item/kind").and_then(Value::as_str) == Some("agent_message")
1607 {
1608 *final_text = RuntimeTaskOutput::default();
1609 }
1610 if let Some(tool) = event.payload.get("tool") {
1611 let id = tool
1612 .get("id")
1613 .and_then(Value::as_str)
1614 .unwrap_or_default()
1615 .to_string();
1616 let name = tool
1617 .get("name")
1618 .and_then(Value::as_str)
1619 .unwrap_or_default()
1620 .to_string();
1621 let input = tool.get("input").cloned().unwrap_or_else(|| json!({}));
1622 emit_task_event(events, TaskExecutionEvent::ToolStarted { id, name, input }).await;
1623 }
1624 None
1625 }
1626 "item.completed" | "item.failed" => {
1627 if let Some(item) = event.payload.get("item") {
1628 let kind = item.get("kind").and_then(Value::as_str).unwrap_or_default();
1629 if kind == "tool_call" || kind == "file_change" || kind == "command_execution" {
1630 let metadata = item.get("metadata");
1631 // Starts carry the call execution ID; item.id is Runtime's
1632 // separate receipt ID. Runtime preserves the call identity
1633 // in terminal metadata, including errors and redacted input.
1634 let id = metadata
1635 .and_then(|meta| {
1636 meta.get("tool_result_for")
1637 .or_else(|| meta.get("tool_use_id"))
1638 .or_else(|| meta.get("tool_call_id"))
1639 })
1640 .and_then(Value::as_str)
1641 .filter(|id| !id.is_empty())
1642 .or_else(|| item.get("id").and_then(Value::as_str))
1643 .unwrap_or_default()
1644 .to_string();
1645 let name = metadata
1646 .and_then(|meta| meta.get("tool_name"))
1647 .and_then(Value::as_str)
1648 .filter(|name| !name.is_empty())
1649 .unwrap_or_else(|| {
1650 item.get("summary")
1651 .and_then(Value::as_str)
1652 .unwrap_or("tool")
1653 .split(':')
1654 .next()
1655 .unwrap_or("tool")
1656 .trim()
1657 })
1658 .to_string();
1659 let output = item
1660 .get("detail")
1661 .and_then(Value::as_str)
1662 .unwrap_or_default()
1663 .to_string();
1664 emit_task_event(
1665 events,
1666 TaskExecutionEvent::ToolCompleted {
1667 id,
1668 name,
1669 success: event.event == "item.completed",
1670 output,
1671 metadata: metadata.cloned(),
1672 },
1673 )
1674 .await;
1675 } else if kind == "agent_message" {
1676 // The completed item is authoritative even when catch-up
1677 // did not receive its deltas. Replacing avoids duplication.
1678 final_text.text = item
1679 .get("detail")
1680 .and_then(Value::as_str)
1681 .or_else(|| item.get("summary").and_then(Value::as_str))
1682 .unwrap_or_default()
1683 .to_string();
1684 final_text.completed = event.event == "item.completed";
1685 } else if kind == "status" {
1686 let message = item
1687 .get("detail")
1688 .and_then(Value::as_str)
1689 .or_else(|| item.get("summary").and_then(Value::as_str))
1690 .unwrap_or_default()
1691 .to_string();
1692 emit_task_event(events, TaskExecutionEvent::Status { message }).await;
1693 } else if kind == "error" {
1694 let message = item
1695 .get("detail")
1696 .and_then(Value::as_str)
1697 .or_else(|| item.get("summary").and_then(Value::as_str))
1698 .unwrap_or_default()
1699 .to_string();
1700 emit_task_event(events, TaskExecutionEvent::Error { message }).await;
1701 }
1702 }
1703 None
1704 }
1705 "turn.completed" => {
1706 if let Some(turn_payload) = event.payload.get("turn") {
1707 let status = turn_payload
1708 .get("status")
1709 .and_then(Value::as_str)
1710 .unwrap_or("failed");
1711 let terminal_status = match status {
1712 "completed" => RuntimeTurnStatus::Completed,
1713 "interrupted" => RuntimeTurnStatus::Interrupted,
1714 "canceled" => RuntimeTurnStatus::Canceled,
1715 _ => RuntimeTurnStatus::Failed,
1716 };
1717 let terminal_error = turn_payload
1718 .get("error")
1719 .and_then(Value::as_str)
1720 .map(ToString::to_string);
1721 Some((terminal_status, terminal_error))
1722 } else {
1723 Some((RuntimeTurnStatus::Completed, None))
1724 }
1725 }
1726 RUNTIME_STORE_FAILURE_EVENT => {
1727 // The runtime's own store failed. The notice names the file and
1728 // the next action; `terminal` means no `turn.completed` can
1729 // follow, so the driver stops waiting instead of idling out (#5931).
1730 let message = event
1731 .payload
1732 .get("message")
1733 .and_then(Value::as_str)
1734 .unwrap_or("Session runtime store failure")
1735 .to_string();
1736 emit_task_event(
1737 events,
1738 TaskExecutionEvent::Error {
1739 message: message.clone(),
1740 },
1741 )
1742 .await;
1743 event
1744 .payload
1745 .get("terminal")
1746 .and_then(Value::as_bool)
1747 .unwrap_or(false)
1748 .then_some((RuntimeTurnStatus::Failed, Some(message)))
1749 }
1750
1751 "approval.timeout" => Some((
1752 RuntimeTurnStatus::Failed,
1753 Some(
1754 "Tool approval was not answered within the decision window; the runtime denied the tool and the run stopped."
1755 .to_string(),
1756 ),
1757 )),
1758 _ => None,
1759 }
1760 }
1761
1762 /// Thread-safe task manager.
1763 pub type SharedTaskManager = Arc<TaskManager>;
1764
1765 pub struct TaskManagerShutdownGuard(std::sync::Weak<TaskManager>);
1766
1767 impl Drop for TaskManagerShutdownGuard {
1768 fn drop(&mut self) {
1769 if let Some(manager) = self.0.upgrade() {
1770 manager.shutdown();
1771 if let Ok(runtime) = tokio::runtime::Handle::try_current() {
1772 runtime.spawn(async move {
1773 if let Err(error) = manager.shutdown_and_wait().await {
1774 tracing::error!(%error, "Task service shutdown failed");
1775 }
1776 });
1777 }
1778 }
1779 }
1780 }
1781
1782 /// A process generation stays live as long as either the manager or actual
1783 /// Runtime work retains it. The Runtime's existing scope lock excludes another
1784 /// executor for that scope; this generation lock proves a particular owner died.
1785 #[derive(Debug)]
1786 pub struct TaskExecutionLease {
1787 scope: String,
1788 generation: String,
1789 _scope_owner: Arc<RuntimeProcessOwnerLock>,
1790 _generation_owner: RuntimeProcessOwnerLock,
1791 }
1792
1793 impl TaskExecutionLease {
1794 fn new(
1795 root: &Path,
1796 scope: String,
1797 scope_owner: Arc<RuntimeProcessOwnerLock>,
1798 ) -> Result<Arc<Self>> {
1799 validate_execution_id(&scope, 64)?;
1800 let generation = Uuid::new_v4().simple().to_string();
1801 let path = execution_lease_path(root, &scope, &generation)?;
1802 let owner = RuntimeProcessOwnerLock::try_acquire_file(&path, true)?
1803 .context("Task execution generation is already owned")?;
1804 Ok(Arc::new(Self {
1805 scope,
1806 generation,
1807 _scope_owner: scope_owner,
1808 _generation_owner: owner,
1809 }))
1810 }
1811 }
1812
1813 fn validate_execution_id(value: &str, length: usize) -> Result<()> {
1814 if value.len() != length || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
1815 bail!("Invalid task execution identity");
1816 }
1817 Ok(())
1818 }
1819
1820 fn execution_lease_path(root: &Path, scope: &str, generation: &str) -> Result<PathBuf> {
1821 validate_execution_id(scope, 64)?;
1822 validate_execution_id(generation, 32)?;
1823 Ok(root
1824 .join("execution-owners")
1825 .join(format!("{scope}.{generation}.lock")))
1826 }
1827
1828 #[cfg(any(test, feature = "test-support"))]
1829 pub fn test_execution_scope(name: &str) -> String {
1830 use sha2::{Digest, Sha256};
1831 Sha256::digest(name.as_bytes())
1832 .iter()
1833 .map(|byte| format!("{byte:02x}"))
1834 .collect()
1835 }
1836
1837 pub struct TaskManager {
1838 cfg: TaskManagerConfig,
1839 default_workspace: Mutex<PathBuf>,
1840 executor: Arc<dyn TaskExecutor>,
1841 /// The runtime thread store this manager drives, when it owns one.
1842 runtime_threads: Option<SharedRuntimeThreadManager>,
1843 tasks_dir: PathBuf,
1844 artifacts_dir: PathBuf,
1845 queue_path: PathBuf,
1846 state: Mutex<ManagerState>,
1847 notify: Notify,
1848 cancel_token: CancellationToken,
1849 execution_lease: Arc<TaskExecutionLease>,
1850 workers: Mutex<Vec<TaskWorker>>,
1851 shutdown_drain: Mutex<()>,
1852 /// Full store loads performed by this manager (tests only, #6573).
1853 #[cfg(any(test, feature = "test-support"))]
1854 store_loads: std::sync::atomic::AtomicUsize,
1855 /// Queue fingerprint reads performed by worker loops (tests only, #6728).
1856 #[cfg(any(test, feature = "test-support"))]
1857 fingerprint_reads: std::sync::atomic::AtomicUsize,
1858 }
1859
1860 type InspectionReply = oneshot::Sender<Result<ClaimSchedule>>;
1861
1862 struct TaskWorker {
1863 inspect: mpsc::Sender<InspectionReply>,
1864 join: tokio::task::JoinHandle<()>,
1865 }
1866
1867 /// Cheap stat-only view of the shared queue file. Everything that makes work
1868 /// claimable rewrites `queue.json` through an atomic rename: admission writes
1869 /// it before promoting the task record, and claims, cancels and startup
1870 /// recovery write it too. Running tasks flush their records into `tasks/`
1871 /// every few hundred milliseconds but leave the queue alone, so the tasks
1872 /// directory is deliberately not part of the fingerprint. Startup still rebuilds
1873 /// missing queue entries from durable records. Failed claims retry independently,
1874 /// including a queue removal whose task-status write failed. Missing or recent
1875 /// metadata keeps a fallback deadline until it can be trusted.
1876 #[derive(Debug, Clone, PartialEq, Eq)]
1877 struct StoreFingerprint(Option<(std::time::SystemTime, u64, u64)>);
1878
1879 impl StoreFingerprint {
1880 fn read(path: &Path) -> Self {
1881 Self(fs::metadata(path).ok().and_then(|meta| {
1882 #[cfg(unix)]
1883 let inode = std::os::unix::fs::MetadataExt::ino(&meta);
1884 #[cfg(not(unix))]
1885 let inode = 0;
1886 Some((meta.modified().ok()?, meta.len(), inode))
1887 }))
1888 }
1889
1890 /// True when the stamp is old enough that a later write cannot share it.
1891 fn settled(&self, now: std::time::SystemTime) -> bool {
1892 self.0.as_ref().is_none_or(|(modified, _, _)| {
1893 now.duration_since(*modified)
1894 .is_ok_and(|age| age >= READ_SNAPSHOT_SETTLE)
1895 })
1896 }
1897 }
1898
1899 /// Stat-only view of everything `load_state` reads, for read-only callers
1900 /// (#6573). Every task and queue write is an atomic rename, which bumps the
1901 /// tasks directory's or the queue file's mtime, so an unchanged snapshot
1902 /// means an unchanged store. The TUI task panel lists tasks every 2.5s; with
1903 /// this, an idle session answers from memory instead of taking the
1904 /// cross-process store lock and re-parsing every task record each time.
1905 #[derive(Debug, Clone, PartialEq, Eq)]
1906 struct ReadSnapshot {
1907 queue: StoreFingerprint,
1908 tasks_dir: StoreFingerprint,
1909 }
1910
1911 impl ReadSnapshot {
1912 fn read(tasks_dir: &Path, queue_path: &Path) -> Self {
1913 Self {
1914 queue: StoreFingerprint::read(queue_path),
1915 tasks_dir: StoreFingerprint::read(tasks_dir),
1916 }
1917 }
1918
1919 fn settled(&self, now: std::time::SystemTime) -> bool {
1920 self.queue.settled(now) && self.tasks_dir.settled(now)
1921 }
1922 }
1923
1924 /// When an idle worker should next claim from the shared store (#6573).
1925 ///
1926 /// A worker claims when it was notified in-process, when the queue
1927 /// fingerprint changed since its last attempt, or when a retry deadline passed.
1928 /// Settled empty claims have no deadline. Unreadable/recent metadata gets a
1929 /// fallback and failed claims get exponential backoff ("Task store is busy"). Workers
1930 /// keep checking the fingerprint every tick during a backoff, so a queue
1931 /// write from another process still gets an early retry.
1932 #[derive(Debug, Clone)]
1933 struct ClaimSchedule {
1934 seen: Option<StoreFingerprint>,
1935 next_claim: Option<Instant>,
1936 failure_backoff: Duration,
1937 }
1938
1939 impl ClaimSchedule {
1940 fn new(now: Instant) -> Self {
1941 Self {
1942 seen: None,
1943 next_claim: Some(now),
1944 failure_backoff: STORE_REFRESH_INTERVAL,
1945 }
1946 }
1947
1948 fn should_claim(&self, fingerprint: &StoreFingerprint, now: Instant, woken: bool) -> bool {
1949 woken
1950 || self.seen.as_ref() != Some(fingerprint)
1951 || self.next_claim.is_some_and(|deadline| now >= deadline)
1952 }
1953
1954 /// How long the worker may sleep before its next pass. Nothing claimable
1955 /// (a settled empty queue, no retry deadline) only needs to notice another
1956 /// process's queue write; pending work or a retry deadline keeps the
1957 /// short tick.
1958 fn nap(&self) -> Duration {
1959 if self.next_claim.is_none() {
1960 STORE_SETTLED_NAP
1961 } else {
1962 STORE_REFRESH_INTERVAL
1963 }
1964 }
1965
1966 fn claimed_task(&mut self, now: Instant) {
1967 self.seen = None;
1968 self.next_claim = Some(now);
1969 self.failure_backoff = STORE_REFRESH_INTERVAL;
1970 }
1971
1972 fn found_nothing(
1973 &mut self,
1974 fingerprint: StoreFingerprint,
1975 now: Instant,
1976 wall_now: std::time::SystemTime,
1977 ) {
1978 // Re-read a recent stamp after its coarse mtime tick has passed before
1979 // trusting it indefinitely. Missing metadata never proves no change.
1980 let settled = fingerprint.0.as_ref().is_some_and(|(modified, _, _)| {
1981 wall_now
1982 .duration_since(*modified)
1983 .is_ok_and(|age| age >= STORE_IDLE_POLL_INTERVAL)
1984 });
1985 self.seen = Some(fingerprint);
1986 self.next_claim = (!settled).then_some(now + STORE_IDLE_POLL_INTERVAL);
1987 self.failure_backoff = STORE_REFRESH_INTERVAL;
1988 }
1989
1990 /// Returns the delay before the next claim unless the queue changes.
1991 fn claim_failed(&mut self, fingerprint: StoreFingerprint, now: Instant) -> Duration {
1992 let delay = self.failure_backoff;
1993 self.seen = Some(fingerprint);
1994 self.next_claim = Some(now + delay);
1995 self.failure_backoff = (delay * 2).min(STORE_BUSY_BACKOFF_MAX);
1996 delay
1997 }
1998 }
1999
2000 /// The "store is busy" error, naming the lock holder when its record can be
2001 /// read. Reading the record is best effort and never fails the caller (#6573).
2002 fn store_busy_error(lock_path: &Path) -> anyhow::Error {
2003 match RuntimeProcessOwnerLock::read_holder(lock_path) {
2004 Some((pid, held_for)) => anyhow::Error::new(TaskStoreBusy).context(format!(
2005 "Task store is busy; state is unavailable (lock held by pid {pid} for {}s)",
2006 held_for.as_secs()
2007 )),
2008 None => TaskStoreBusy.into(),
2009 }
2010 }
2011
2012 struct ManagerState {
2013 tasks: HashMap<String, TaskRecord>,
2014 queue: VecDeque<String>,
2015 running_cancel: HashMap<String, CancellationToken>,
2016 /// Uncommitted typed deltas, reapplied to a fresh record before persistence.
2017 pending_events: HashMap<String, Vec<TaskExecutionEvent>>,
2018 /// Store snapshot that `tasks` and `queue` exactly reflect, set only by a
2019 /// read-only refresh and cleared by every path that may change them.
2020 read_snapshot: Option<ReadSnapshot>,
2021 }
2022
2023 #[derive(Debug, Serialize, Deserialize, Default)]
2024 struct QueueFile {
2025 queue: Vec<String>,
2026 }
2027
2028 impl TaskManager {
2029 /// Start the manager with the default DeepSeek executor.
2030 ///
2031 /// Interactive callers pass an initial session id to isolate new hosts,
2032 /// or the saved store binding to retain the same authority across resume.
2033 pub async fn start(
2034 cfg: TaskManagerConfig,
2035 api_config: Config,
2036 plugin_registry: Arc<codewhale_plugins::PluginRegistry>,
2037 session_id: &str,
2038 binding: Option<&crate::runtime_threads::RuntimeStoreBinding>,
2039 ) -> Result<SharedTaskManager> {
2040 // Resolve the sessions root's canonical spelling off this runtime
2041 // once, so the saved-store confinement checks here and in later
2042 // `/resume` / `/load` switches are pure comparisons (#6522).
2043 crate::runtime_threads::prepare_canonical_sessions_root().await;
2044 let runtime_threads = Arc::new(RuntimeThreadManager::open_for_session(
2045 api_config.clone(),
2046 cfg.default_workspace.clone(),
2047 RuntimeThreadManagerConfig::for_session(cfg.data_dir.clone(), session_id),
2048 plugin_registry,
2049 binding,
2050 )?);
2051 let workspace = cfg.default_workspace.clone();
2052 let workers = tokio::task::spawn_blocking(move || {
2053 crate::tools::subagent::new_shared_worker_authority(workspace)
2054 })
2055 .await?;
2056 runtime_threads.attach_subagent_manager(workers).await?;
2057 Self::start_with_runtime_manager(cfg, api_config, runtime_threads).await
2058 }
2059
2060 /// Start the manager with an injected runtime thread manager.
2061 ///
2062 /// Whether prompts on this manager's tasks are answerable human-paced
2063 /// waits is `cfg.human_waits_answerable` — the TUI's `start` leaves it
2064 /// `false`, the runtime API server opts in. See that field for the
2065 /// contract.
2066 pub async fn start_with_runtime_manager(
2067 cfg: TaskManagerConfig,
2068 _api_config: Config,
2069 runtime_threads: SharedRuntimeThreadManager,
2070 ) -> Result<SharedTaskManager> {
2071 let executor: Arc<dyn TaskExecutor> = Arc::new(EngineTaskExecutor::new(
2072 runtime_threads.clone(),
2073 cfg.execution_limits,
2074 cfg.human_waits_answerable,
2075 ));
2076 let identity = runtime_threads.task_execution_identity();
2077 let manager = Self::start_with_executor_and_runtime(
2078 cfg,
2079 executor,
2080 Some(runtime_threads.clone()),
2081 identity,
2082 )
2083 .await?;
2084 runtime_threads.attach_task_manager(manager.clone());
2085 Ok(manager)
2086 }
2087
2088 /// Start the manager with a custom executor (used for tests).
2089 #[cfg(any(test, feature = "test-support"))]
2090 pub async fn start_with_executor(
2091 cfg: TaskManagerConfig,
2092 executor: Arc<dyn TaskExecutor>,
2093 ) -> Result<SharedTaskManager> {
2094 Self::start_with_executor_in_scope(cfg, executor, "test").await
2095 }
2096
2097 #[cfg(any(test, feature = "test-support"))]
2098 pub async fn start_with_executor_in_scope(
2099 cfg: TaskManagerConfig,
2100 executor: Arc<dyn TaskExecutor>,
2101 scope: &str,
2102 ) -> Result<SharedTaskManager> {
2103 let scope = test_execution_scope(scope);
2104 let path = cfg
2105 .data_dir
2106 .join("execution-owners")
2107 .join(format!("test-{scope}.lock"));
2108 let owner = RuntimeProcessOwnerLock::try_acquire_file(&path, true)?
2109 .context("Mock Runtime execution scope is already owned")?;
2110 Self::start_with_executor_and_runtime(cfg, executor, None, (scope, Arc::new(owner))).await
2111 }
2112
2113 async fn start_with_executor_and_runtime(
2114 cfg: TaskManagerConfig,
2115 executor: Arc<dyn TaskExecutor>,
2116 runtime_threads: Option<SharedRuntimeThreadManager>,
2117 identity: (String, Arc<RuntimeProcessOwnerLock>),
2118 ) -> Result<SharedTaskManager> {
2119 let workers = cfg.worker_count.clamp(1, MAX_WORKERS);
2120 let tasks_dir = cfg.data_dir.join("tasks");
2121 let artifacts_dir = cfg.data_dir.join("artifacts");
2122 let queue_path = cfg.data_dir.join("queue.json");
2123 tokio::fs::create_dir_all(&tasks_dir)
2124 .await
2125 .with_context(|| format!("Failed to create tasks dir {}", tasks_dir.display()))?;
2126 tokio::fs::create_dir_all(&artifacts_dir)
2127 .await
2128 .with_context(|| {
2129 format!(
2130 "Failed to create task artifacts dir {}",
2131 artifacts_dir.display()
2132 )
2133 })?;
2134
2135 let execution_lease = TaskExecutionLease::new(&cfg.data_dir, identity.0, identity.1)?;
2136 let cancel_token = CancellationToken::new();
2137 let default_workspace = cfg.default_workspace.clone();
2138 let manager = Arc::new(Self {
2139 cfg,
2140 default_workspace: Mutex::new(default_workspace),
2141 executor,
2142 runtime_threads,
2143 tasks_dir,
2144 artifacts_dir,
2145 queue_path,
2146 state: Mutex::new(ManagerState {
2147 tasks: HashMap::new(),
2148 queue: VecDeque::new(),
2149 running_cancel: HashMap::new(),
2150 pending_events: HashMap::new(),
2151 read_snapshot: None,
2152 }),
2153 notify: Notify::new(),
2154 cancel_token: cancel_token.clone(),
2155 execution_lease: execution_lease.clone(),
2156 workers: Mutex::new(Vec::new()),
2157 shutdown_drain: Mutex::new(()),
2158 #[cfg(any(test, feature = "test-support"))]
2159 store_loads: std::sync::atomic::AtomicUsize::new(0),
2160 #[cfg(any(test, feature = "test-support"))]
2161 fingerprint_reads: std::sync::atomic::AtomicUsize::new(0),
2162 });
2163
2164 {
2165 let mut state = manager.state.lock().await;
2166 let _transaction = manager.lock_store().await?;
2167 manager.refresh_locked_offloaded(&mut state).await?;
2168 manager.recover_dead_executions_locked(&mut state)?;
2169 manager.persist_queue_locked(&state.queue)?;
2170 }
2171 if let Some(runtime) = &manager.runtime_threads {
2172 runtime.retain_task_execution_lease(execution_lease)?;
2173 }
2174
2175 manager.initialize_workers(workers).await?;
2176 Ok(manager)
2177 }
2178
2179 /// Establish each worker's first claim/retry boundary after loading state.
2180 async fn initialize_workers(self: &Arc<Self>, workers: usize) -> Result<Vec<ClaimSchedule>> {
2181 let mut startup_guard = self.shutdown_guard();
2182 for _ in 0..workers {
2183 let manager_clone = Arc::clone(self);
2184 let (inspect, inspections) = mpsc::channel(1);
2185 let worker = spawn_supervised(
2186 "task-manager-worker",
2187 std::panic::Location::caller(),
2188 async move {
2189 manager_clone.worker_loop(inspections).await;
2190 },
2191 );
2192 self.workers.lock().await.push(TaskWorker {
2193 inspect,
2194 join: worker,
2195 });
2196 }
2197
2198 // Spawning is not initialization completion. Each worker acknowledges
2199 // its first queue inspection after committing its scheduling decision,
2200 // before executing any claimed task. A retry remains an explicit part
2201 // of that result; startup does not promise a globally idle store.
2202 let inspected = self.inspect_workers().await;
2203 if inspected.is_err() {
2204 self.shutdown_and_wait().await?;
2205 }
2206 startup_guard.0 = std::sync::Weak::new();
2207 inspected
2208 }
2209
2210 /// Inspect through every worker's normal claim path and await its reply.
2211 ///
2212 /// The reply belongs to this request, so a fast worker cannot acknowledge
2213 /// another worker's inspection or race ahead of a subscriber. It is sent
2214 /// only after the store operation and schedule update finish. This is a
2215 /// per-worker boundary, not a global snapshot or a task-completion promise:
2216 /// a claimed task executes after the acknowledgement, and another process
2217 /// may subsequently change the queue. No elapsed quiet period proves any
2218 /// of these operations complete (the former #6573 test assumed it did).
2219 async fn inspect_workers(&self) -> Result<Vec<ClaimSchedule>> {
2220 if self.cancel_token.is_cancelled() {
2221 bail!("Task worker inspection requested after shutdown");
2222 }
2223 let senders: Vec<_> = self
2224 .workers
2225 .lock()
2226 .await
2227 .iter()
2228 .map(|worker| worker.inspect.clone())
2229 .collect();
2230 let mut replies = Vec::with_capacity(senders.len());
2231 for sender in senders {
2232 let (reply, received) = oneshot::channel();
2233 sender
2234 .send(reply)
2235 .await
2236 .map_err(|_| anyhow!("Task worker stopped before queue inspection"))?;
2237 replies.push(received);
2238 }
2239 let mut schedules = Vec::with_capacity(replies.len());
2240 for reply in replies {
2241 schedules.push(
2242 reply
2243 .await
2244 .context("Task worker stopped during queue inspection")??,
2245 );
2246 }
2247 Ok(schedules)
2248 }
2249
2250 /// Request shutdown. Ownership remains retained through actual execution.
2251 pub fn shutdown(&self) {
2252 self.cancel_token.cancel();
2253 }
2254
2255 /// Test seam for the server wiring pin: the built-in engine executor
2256 /// this manager runs tasks on, so the pin can read the answerability
2257 /// flag where the config forward actually landed.
2258 #[cfg(any(test, feature = "test-support"))]
2259 #[must_use]
2260 pub fn engine_executor(&self) -> Option<&EngineTaskExecutor> {
2261 self.executor.as_engine_executor()
2262 }
2263
2264 pub fn shutdown_guard(self: &Arc<Self>) -> TaskManagerShutdownGuard {
2265 TaskManagerShutdownGuard(Arc::downgrade(self))
2266 }
2267
2268 pub async fn shutdown_and_wait(&self) -> Result<()> {
2269 self.shutdown();
2270 let _drain = self.shutdown_drain.lock().await;
2271 if let Some(runtime) = &self.runtime_threads {
2272 runtime.close_execution_admission().await;
2273 }
2274 // Waiting through the admission fence settles requests that passed
2275 // their admission check before shutdown was requested.
2276 {
2277 let _transaction = self.lock_store().await?;
2278 }
2279 let mut failure = None;
2280 {
2281 let mut workers = self.workers.lock().await;
2282 while let Some(worker) = workers.last_mut() {
2283 // Await by reference: canceling this caller leaves the join in
2284 // the manager, so a later drain still waits for actual exit.
2285 let result = (&mut worker.join).await;
2286 workers.pop();
2287 if let Err(error) = result {
2288 failure = Some(anyhow!("Task worker shutdown failed: {error}"));
2289 }
2290 }
2291 }
2292 if let Some(runtime) = &self.runtime_threads {
2293 runtime.shutdown_and_wait().await?;
2294 }
2295 failure.map_or(Ok(()), Err)
2296 }
2297
2298 pub fn execution_scope(&self) -> &str {
2299 &self.execution_lease.scope
2300 }
2301
2302 /// Apply `edit` to the runtime threads' authoritative config and reload
2303 /// it, so runtime-chat and queued runtime turns see a setting the UI just
2304 /// persisted instead of their startup snapshot. No runtime manager is a
2305 /// no-op.
2306 pub async fn reload_runtime_config_with(
2307 &self,
2308 edit: impl FnOnce(&mut codewhale_runtime::config::Config),
2309 ) -> Result<()> {
2310 let Some(runtime) = &self.runtime_threads else {
2311 return Ok(());
2312 };
2313 let mut config = runtime.read_config().clone();
2314 edit(&mut config);
2315 runtime.reload_config(config).await.map(|_| ())
2316 }
2317
2318 pub fn session_store_binding(&self) -> Option<crate::runtime_threads::RuntimeStoreBinding> {
2319 self.runtime_threads
2320 .as_ref()
2321 .map(|runtime| runtime.session_store_binding())
2322 }
2323
2324 /// In-memory approvals, user-input prompts, and dynamic tool calls still
2325 /// waiting on an answer. A host that releases its store with any of these
2326 /// open strands the waiters; see
2327 /// [`RuntimeThreadManager::has_unsettled_requests`].
2328 pub fn has_unsettled_requests(&self) -> bool {
2329 self.runtime_threads
2330 .as_ref()
2331 .is_some_and(|runtime| runtime.has_unsettled_requests())
2332 }
2333
2334 /// Whether the store this host holds can be released for a session switch.
2335 /// `None` when no Runtime is attached (nothing to release).
2336 pub async fn current_store_is_disposable(&self) -> Option<anyhow::Result<bool>> {
2337 match self.runtime_threads.as_ref() {
2338 Some(runtime) => Some(runtime.current_store_is_disposable().await),
2339 None => None,
2340 }
2341 }
2342
2343 pub async fn prepare_store_release(
2344 &self,
2345 ) -> Result<Option<crate::runtime_threads::manager::RuntimeStoreRelease>> {
2346 match &self.runtime_threads {
2347 Some(runtime) => Ok(Some(runtime.prepare_store_release().await?)),
2348 None => Ok(None),
2349 }
2350 }
2351
2352 pub async fn set_default_workspace(&self, workspace: PathBuf) {
2353 let mut default_workspace = self.default_workspace.lock().await;
2354 *default_workspace = workspace;
2355 }
2356
2357 pub async fn default_workspace(&self) -> PathBuf {
2358 self.default_workspace.lock().await.clone()
2359 }
2360
2361 /// Enqueue a new task.
2362 pub async fn add_task(&self, req: NewTaskRequest) -> Result<TaskRecord> {
2363 self.add_task_with_id(req, Self::new_task_id()).await
2364 }
2365
2366 /// Allocate the durable owner identity before queue insertion so callers
2367 /// can register graph spawn intent first.
2368 #[must_use]
2369 pub fn new_task_id() -> String {
2370 format!("task_{}", &Uuid::new_v4().simple().to_string()[..16])
2371 }
2372
2373 /// Read the exact durable task binding without adopting another process's
2374 /// queue. Used by the automation dispatcher while it owns the store claim.
2375 pub fn read_bound_task(&self, task_id: &str) -> Result<Option<TaskRecord>> {
2376 if task_id.is_empty()
2377 || !task_id
2378 .bytes()
2379 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
2380 {
2381 bail!("Invalid durable task id");
2382 }
2383 read_bound_task_file(&self.tasks_dir.join(format!("{task_id}.json")), task_id)
2384 }
2385
2386 /// Recover a persisted automation admission under its cross-process
2387 /// dispatch lock. A promoted task is accepted work, including failed or
2388 /// interrupted work; returning it must never enqueue it again.
2389 pub(crate) async fn recover_task_admission(
2390 &self,
2391 request: NewTaskRequest,
2392 task_id: String,
2393 ) -> Result<TaskRecord> {
2394 validate_preallocated_task_id(&task_id)?;
2395 if let Some(task) = self.read_bound_task(&task_id)? {
2396 validate_bound_task_request(&task, &request)?;
2397 return Ok(task);
2398 }
2399 let staged_path = self.tasks_dir.join(format!(".{task_id}.json.pending"));
2400 let admission = if let Some(staged) = read_bound_task_file(&staged_path, &task_id)? {
2401 validate_bound_task_request(&staged, &request)?;
2402 if staged.status != TaskStatus::Queued
2403 || staged.started_at.is_some()
2404 || staged.thread_id.is_some()
2405 || staged.turn_id.is_some()
2406 {
2407 bail!("Unpromoted task stage contains execution evidence; refusing to replay it");
2408 }
2409 // The original resolved settings remain durable in this stage
2410 // until promotion, including if recovery itself is interrupted.
2411 self.admit_task_record(staged, true).await
2412 } else {
2413 self.add_task_with_origin(
2414 request.clone(),
2415 task_id.clone(),
2416 Some(ThreadOrigin::Automation),
2417 )
2418 .await
2419 };
2420 match admission {
2421 Ok(task) => Ok(task),
2422 Err(error) => {
2423 // Preserve a task promoted before a torn response; do not
2424 // replace its identity or convert accepted work into a retry.
2425 if let Some(task) = self.read_bound_task(&task_id)? {
2426 validate_bound_task_request(&task, &request)?;
2427 Ok(task)
2428 } else {
2429 Err(error)
2430 }
2431 }
2432 }
2433 }
2434
2435 /// Enqueue using a preallocated id. This is crate-visible only for the
2436 /// model tool's register-before-work transaction.
2437 pub async fn add_task_with_id(
2438 &self,
2439 req: NewTaskRequest,
2440 task_id: String,
2441 ) -> Result<TaskRecord> {
2442 self.add_task_with_origin(req, task_id, None).await
2443 }
2444
2445 async fn add_task_with_origin(
2446 &self,
2447 req: NewTaskRequest,
2448 task_id: String,
2449 thread_origin: Option<ThreadOrigin>,
2450 ) -> Result<TaskRecord> {
2451 let prompt = req.prompt.trim().to_string();
2452 if prompt.is_empty() {
2453 bail!("Task prompt cannot be empty");
2454 }
2455 if (req.model_provider.is_some() || req.model_provider_id.is_some())
2456 && req
2457 .model
2458 .as_deref()
2459 .is_none_or(|model| model.trim().is_empty())
2460 {
2461 bail!("A pinned task provider requires an explicit model");
2462 }
2463 // The worker runs this same projection when it opens the task's
2464 // thread. Running it here as well refuses an unknown mode or posture
2465 // at the boundary the request crossed, instead of after the task has
2466 // sat in the durable queue and a worker has claimed it.
2467 codewhale_runtime::runtime_policy::RuntimePolicyProjection::from_request(
2468 req.mode
2469 .as_deref()
2470 .filter(|mode| !mode.trim().is_empty())
2471 .unwrap_or(&self.cfg.default_mode),
2472 req.permission_posture.as_deref(),
2473 req.auto_approve,
2474 )?;
2475 validate_preallocated_task_id(&task_id)?;
2476 let disallowed_tools = normalize_deny_rules(req.disallowed_tools);
2477
2478 let task = TaskRecord {
2479 thread_origin,
2480 schema_version: required_task_schema_version(&disallowed_tools),
2481 // 16 random hex chars (was 8; ~60 bits of entropy once UUIDv4's
2482 // fixed version nibble is discounted): task ids live in durable
2483 // state that accumulates across restarts, and a collision
2484 // overwrites a record while leaving a duplicate queue entry.
2485 // `resolve_task_id` matches by prefix, so short references still
2486 // work.
2487 id: task_id,
2488 prompt,
2489 name: req
2490 .name
2491 .map(|name| name.trim().to_string())
2492 .filter(|name| !name.is_empty()),
2493 model: req.model.unwrap_or_else(|| self.cfg.default_model.clone()),
2494 model_provider: req.model_provider,
2495 model_provider_id: req.model_provider_id,
2496 workspace: match req.workspace {
2497 Some(workspace) => workspace,
2498 None => self.default_workspace().await,
2499 },
2500 mode: req.mode.unwrap_or_else(|| self.cfg.default_mode.clone()),
2501 allow_shell: req.allow_shell.unwrap_or(self.cfg.allow_shell),
2502 trust_mode: req.trust_mode.unwrap_or(self.cfg.trust_mode),
2503 // Auto-approval must be opted into explicitly
2504 // (GHSA-72w5-pf8h-xfp4).
2505 auto_approve: req.auto_approve.unwrap_or(false),
2506 permission_posture: req.permission_posture,
2507 disallowed_tools,
2508 status: TaskStatus::Queued,
2509 created_at: Utc::now(),
2510 started_at: None,
2511 ended_at: None,
2512 duration_ms: None,
2513 result_summary: None,
2514 result_detail_path: None,
2515 error: None,
2516 terminal_reason: None,
2517 thread_id: None,
2518 turn_id: None,
2519 owner_session_id: req.owner_session_id,
2520 destination_thread_id: req.destination_thread_id,
2521 execution_scope: Some(self.execution_scope().to_string()),
2522 execution_generation: None,
2523 cancel_requested_seq: 0,
2524 runtime_event_count: 0,
2525 lifecycle_seq: 1,
2526 checklist: TaskChecklistState::default(),
2527 gates: Vec::new(),
2528 attempts: Vec::new(),
2529 artifacts: Vec::new(),
2530 github_events: Vec::new(),
2531 tool_calls: Vec::new(),
2532 timeline: vec![TaskTimelineEntry {
2533 timestamp: Utc::now(),
2534 kind: "queued".to_string(),
2535 summary: "Task queued".to_string(),
2536 detail_path: None,
2537 }],
2538 };
2539
2540 self.admit_task_record(task, false).await
2541 }
2542
2543 async fn admit_task_record(&self, task: TaskRecord, recover_stage: bool) -> Result<TaskRecord> {
2544 {
2545 let mut state = self.state.lock().await;
2546 let _transaction = self.lock_store().await?;
2547 self.refresh_locked_offloaded(&mut state).await?;
2548 if self.cancel_token.is_cancelled() {
2549 bail!("Task manager is shutting down; admission is closed");
2550 }
2551 if task.execution_scope.as_deref() != Some(self.execution_scope()) {
2552 bail!(
2553 "Task execution scope is unverified or belongs to another Runtime; refusing adoption"
2554 );
2555 }
2556 let task_path = self.tasks_dir.join(format!("{}.json", task.id));
2557 // The staged extension is intentionally not `.json`, so startup
2558 // replay ignores an interrupted create until the queue write has
2559 // succeeded and this file is atomically promoted.
2560 let staged_task_path = self.tasks_dir.join(format!(".{}.json.pending", task.id));
2561 if recover_stage {
2562 if let Some(accepted) = self.read_bound_task(&task.id)? {
2563 validate_bound_task_request(&accepted, &NewTaskRequest::from_task(&task))?;
2564 return Ok(accepted);
2565 }
2566 let current = read_bound_task_file(&staged_task_path, &task.id)?
2567 .context("Unaccepted task stage disappeared during recovery")?;
2568 if serde_json::to_value(&current)? != serde_json::to_value(&task)? {
2569 bail!("Unaccepted task stage changed during recovery");
2570 }
2571 }
2572 if state.tasks.contains_key(&task.id)
2573 || task_path.exists()
2574 || (!recover_stage && staged_task_path.exists())
2575 {
2576 bail!("Task id already exists: {}", task.id);
2577 }
2578 let mut next_queue = state.queue.clone();
2579 if !next_queue.contains(&task.id) {
2580 next_queue.push_back(task.id.clone());
2581 }
2582
2583 // Stage the owner record, then persist its queue membership, then
2584 // atomically promote it. A crash before promotion leaves either an
2585 // ignored staged file or a queue entry with no task (which replay
2586 // drops); a crash after promotion leaves the complete runnable
2587 // pair. In-memory scheduling is published only after all three.
2588 if !recover_stage {
2589 write_json_atomic(&staged_task_path, &task)?;
2590 }
2591 if let Err(err) = self.persist_queue_locked(&next_queue) {
2592 if !recover_stage
2593 && let Err(cleanup_err) = tokio::fs::remove_file(&staged_task_path).await
2594 {
2595 tracing::warn!(
2596 task_id = %task.id,
2597 error = %cleanup_err,
2598 "failed to remove ignored staged task after queue write failure"
2599 );
2600 }
2601 return Err(err);
2602 }
2603 if let Err(promote_err) = tokio::fs::rename(&staged_task_path, &task_path).await {
2604 let rollback_error = self.persist_queue_locked(&state.queue).err();
2605 let cleanup_error = if recover_stage {
2606 None
2607 } else {
2608 tokio::fs::remove_file(&staged_task_path).await.err()
2609 };
2610 let mut message =
2611 format!("Failed to promote staged task {}: {promote_err}", task.id);
2612 if let Some(rollback_error) = rollback_error {
2613 message.push_str(&format!("; queue rollback also failed: {rollback_error:#}"));
2614 }
2615 if let Some(cleanup_error) = cleanup_error {
2616 message.push_str(&format!(
2617 "; ignored staged-file cleanup also failed: {cleanup_error}"
2618 ));
2619 }
2620 bail!(message);
2621 }
2622 state.queue = next_queue;
2623 state.tasks.insert(task.id.clone(), task.clone());
2624 }
2625 self.notify.notify_one();
2626 Ok(task)
2627 }
2628
2629 /// List tasks, newest first.
2630 pub async fn list_tasks(&self, limit: Option<usize>) -> Result<Vec<TaskSummary>> {
2631 self.list_tasks_scoped(limit, None).await
2632 }
2633
2634 /// List tasks, newest first, optionally scoped to a workspace.
2635 pub async fn list_tasks_scoped(
2636 &self,
2637 limit: Option<usize>,
2638 workspace: Option<&Path>,
2639 ) -> Result<Vec<TaskSummary>> {
2640 self.list_tasks_visible_to(limit, workspace, None).await
2641 }
2642
2643 /// List tasks owned by a session, newest first, optionally scoped to a workspace.
2644 ///
2645 /// Ownerless legacy records fail closed and are not model-visible.
2646 pub async fn list_tasks_for_owner(
2647 &self,
2648 limit: Option<usize>,
2649 workspace: Option<&Path>,
2650 owner_session_id: &str,
2651 ) -> Result<Vec<TaskSummary>> {
2652 self.list_tasks_visible_to(limit, workspace, Some(owner_session_id))
2653 .await
2654 }
2655
2656 async fn list_tasks_visible_to(
2657 &self,
2658 limit: Option<usize>,
2659 workspace: Option<&Path>,
2660 owner_session_id: Option<&str>,
2661 ) -> Result<Vec<TaskSummary>> {
2662 let mut state = self.state.lock().await;
2663 self.refresh_for_read(&mut state).await?;
2664 let mut items = state
2665 .tasks
2666 .values()
2667 .filter(|record| {
2668 workspace.is_none_or(|workspace| record.workspace.as_path() == workspace)
2669 && owner_session_id.is_none_or(|owner_session_id| {
2670 record.owner_session_id.as_deref() == Some(owner_session_id)
2671 })
2672 })
2673 .map(TaskSummary::from)
2674 .collect::<Vec<_>>();
2675 items.sort_by_key(|i| std::cmp::Reverse(i.created_at));
2676 if let Some(limit) = limit {
2677 items.truncate(limit);
2678 }
2679 Ok(items)
2680 }
2681
2682 /// Retrieve a task by full id or prefix.
2683 pub async fn get_task(&self, id_or_prefix: &str) -> Result<TaskRecord> {
2684 self.get_task_visible_to(id_or_prefix, None).await
2685 }
2686
2687 /// Retrieve a session-owned task by full id or prefix.
2688 ///
2689 /// Ownership is applied before id resolution so foreign records cannot
2690 /// disclose their existence through exact matches or prefix ambiguity.
2691 pub async fn get_task_for_owner(
2692 &self,
2693 id_or_prefix: &str,
2694 owner_session_id: &str,
2695 ) -> Result<TaskRecord> {
2696 self.get_task_visible_to(id_or_prefix, Some(owner_session_id))
2697 .await
2698 }
2699
2700 /// Retrieve a task the interactive operator can inspect by full id or prefix.
2701 ///
2702 /// Scheduled automations have no session owner because they can outlive the
2703 /// session that configured them. They remain operator-visible only while
2704 /// bound to this manager's verified Runtime execution scope. Session-owned
2705 /// tasks keep their existing isolation, and unscoped legacy records remain
2706 /// hidden.
2707 pub async fn get_task_for_interactive_session(
2708 &self,
2709 id_or_prefix: &str,
2710 owner_session_id: &str,
2711 ) -> Result<TaskRecord> {
2712 let mut state = self.state.lock().await;
2713 self.refresh_for_read(&mut state).await?;
2714 let id = resolve_task_id_visible_to_operator(
2715 &state.tasks,
2716 id_or_prefix,
2717 owner_session_id,
2718 self.execution_scope(),
2719 )?;
2720 state
2721 .tasks
2722 .get(&id)
2723 .cloned()
2724 .ok_or_else(|| anyhow!("Task not found: {id_or_prefix}"))
2725 }
2726
2727 /// Retrieve the exact owned task stamped onto a trusted runtime thread.
2728 ///
2729 /// The runtime thread supplies a full durable id rather than model input.
2730 /// An ownerless task needs the current trusted execution scope. Legacy
2731 /// ownerless tasks without that provenance still fail closed.
2732 pub async fn get_task_for_active_runtime(&self, task_id: &str) -> Result<TaskRecord> {
2733 let mut state = self.state.lock().await;
2734 self.refresh_for_read(&mut state).await?;
2735 state
2736 .tasks
2737 .get(task_id)
2738 .filter(|task| match task.execution_scope.as_deref() {
2739 Some(scope) => scope == self.execution_scope(),
2740 None => task.owner_session_id.is_some(),
2741 })
2742 .cloned()
2743 .ok_or_else(|| anyhow!("Task not found: {task_id}"))
2744 }
2745
2746 async fn get_task_visible_to(
2747 &self,
2748 id_or_prefix: &str,
2749 owner_session_id: Option<&str>,
2750 ) -> Result<TaskRecord> {
2751 let mut state = self.state.lock().await;
2752 self.refresh_for_read(&mut state).await?;
2753 let id = resolve_task_id_visible_to(&state.tasks, id_or_prefix, owner_session_id)?;
2754 state
2755 .tasks
2756 .get(&id)
2757 .cloned()
2758 .ok_or_else(|| anyhow!("Task not found: {id_or_prefix}"))
2759 }
2760
2761 /// Cancel a queued or running task by id/prefix.
2762 pub async fn cancel_task(&self, id_or_prefix: &str) -> Result<TaskCancellation> {
2763 self.cancel_task_visible_to(id_or_prefix, None, None).await
2764 }
2765
2766 /// Cancel a queued or running task owned by the given session.
2767 ///
2768 /// Ownerless legacy and foreign records fail closed.
2769 pub async fn cancel_task_for_owner(
2770 &self,
2771 id_or_prefix: &str,
2772 owner_session_id: &str,
2773 ) -> Result<TaskCancellation> {
2774 self.cancel_task_visible_to(id_or_prefix, Some(owner_session_id), None)
2775 .await
2776 }
2777
2778 /// Cancel a task visible to the interactive operator.
2779 ///
2780 /// This is the cancellation counterpart to
2781 /// [`Self::get_task_for_interactive_session`]. It exists for human TUI
2782 /// actions, including the automation view's cancel button; model and child
2783 /// task APIs retain session-only visibility.
2784 pub async fn cancel_task_for_interactive_session(
2785 &self,
2786 id_or_prefix: &str,
2787 owner_session_id: &str,
2788 ) -> Result<TaskCancellation> {
2789 self.cancel_task_visible_to(
2790 id_or_prefix,
2791 Some(owner_session_id),
2792 Some(self.execution_scope()),
2793 )
2794 .await
2795 }
2796
2797 /// Cancel the exact owned task stamped onto a trusted runtime thread.
2798 pub async fn cancel_task_for_active_runtime(&self, task_id: &str) -> Result<TaskCancellation> {
2799 self.get_task_for_active_runtime(task_id).await?;
2800 self.cancel_task(task_id).await
2801 }
2802
2803 async fn cancel_task_visible_to(
2804 &self,
2805 id_or_prefix: &str,
2806 owner_session_id: Option<&str>,
2807 operator_execution_scope: Option<&str>,
2808 ) -> Result<TaskCancellation> {
2809 let mut state = self.state.lock().await;
2810 let _transaction = self.lock_store().await?;
2811 self.refresh_locked_offloaded(&mut state).await?;
2812 let id = match (owner_session_id, operator_execution_scope) {
2813 (Some(owner_session_id), Some(execution_scope)) => resolve_task_id_visible_to_operator(
2814 &state.tasks,
2815 id_or_prefix,
2816 owner_session_id,
2817 execution_scope,
2818 )?,
2819 _ => resolve_task_id_visible_to(&state.tasks, id_or_prefix, owner_session_id)?,
2820 };
2821 let now = Utc::now();
2822
2823 let mut cancel_running = false;
2824 let disposition = {
2825 let task = state
2826 .tasks
2827 .get_mut(&id)
2828 .ok_or_else(|| anyhow!("Task not found: {id}"))?;
2829 match task.status {
2830 TaskStatus::Queued => {
2831 task.status = TaskStatus::Canceled;
2832 task.lifecycle_seq = task.lifecycle_seq.saturating_add(1);
2833 task.ended_at = Some(now);
2834 task.duration_ms = Some(0);
2835 push_timeline_entry(
2836 task,
2837 TaskTimelineEntry {
2838 timestamp: now,
2839 kind: "canceled".to_string(),
2840 summary: "Task canceled before execution".to_string(),
2841 detail_path: None,
2842 },
2843 );
2844 state.queue.retain(|queued_id| queued_id != &id);
2845 TaskCancelDisposition::Forced
2846 }
2847 TaskStatus::Running => {
2848 cancel_running = true;
2849 task.lifecycle_seq = task.lifecycle_seq.saturating_add(1);
2850 task.cancel_requested_seq = task.lifecycle_seq;
2851 push_timeline_entry(
2852 task,
2853 TaskTimelineEntry {
2854 timestamp: now,
2855 kind: "cancel_requested".to_string(),
2856 summary: "Cancellation requested".to_string(),
2857 detail_path: None,
2858 },
2859 );
2860 TaskCancelDisposition::Requested
2861 }
2862 TaskStatus::Completed | TaskStatus::Failed | TaskStatus::Canceled => {
2863 TaskCancelDisposition::AlreadyFinished
2864 }
2865 }
2866 };
2867
2868 if cancel_running && let Some(token) = state.running_cancel.get(&id) {
2869 token.cancel();
2870 }
2871
2872 self.persist_changed_task_locked(&mut state, &id)?;
2873 self.persist_queue_locked(&state.queue)?;
2874 let task = state
2875 .tasks
2876 .get(&id)
2877 .cloned()
2878 .ok_or_else(|| anyhow!("Task not found: {id}"))?;
2879 Ok(TaskCancellation { task, disposition })
2880 }
2881
2882 /// Return aggregate status counters.
2883 pub async fn counts(&self) -> Result<TaskCounts> {
2884 let mut state = self.state.lock().await;
2885 self.refresh_for_read(&mut state).await?;
2886 let mut counts = TaskCounts::default();
2887 for task in state.tasks.values() {
2888 match task.status {
2889 TaskStatus::Queued => counts.queued += 1,
2890 TaskStatus::Running => counts.running += 1,
2891 TaskStatus::Completed => counts.completed += 1,
2892 TaskStatus::Failed => counts.failed += 1,
2893 TaskStatus::Canceled => counts.canceled += 1,
2894 }
2895 }
2896 Ok(counts)
2897 }
2898
2899 /// Root directory for durable task state.
2900 #[must_use]
2901 pub fn data_dir(&self) -> PathBuf {
2902 self.cfg.data_dir.clone()
2903 }
2904
2905 /// Live events from the runtime thread store this manager drives, when it
2906 /// owns one. The TUI taps `runtime.store_failure` here (#5931).
2907 #[must_use]
2908 pub fn subscribe_runtime_events(
2909 &self,
2910 ) -> Option<tokio::sync::broadcast::Receiver<RuntimeEventRecord>> {
2911 self.runtime_threads
2912 .as_ref()
2913 .map(|runtime| runtime.subscribe_events())
2914 }
2915
2916 /// Resolve a task artifact reference to an absolute path.
2917 #[must_use]
2918 pub fn artifact_absolute_path(&self, path: &Path) -> PathBuf {
2919 if path.is_absolute() {
2920 path.to_path_buf()
2921 } else {
2922 self.cfg.data_dir.join(path)
2923 }
2924 }
2925
2926 /// Write a durable task artifact and return the persisted path reference.
2927 pub fn write_task_artifact(
2928 &self,
2929 task_id: &str,
2930 label: &str,
2931 content: &str,
2932 ) -> Result<PathBuf> {
2933 self.write_artifact(task_id, label, content)
2934 }
2935
2936 /// Apply model-visible tool metadata to a task and persist it.
2937 pub async fn record_tool_metadata(
2938 &self,
2939 id_or_prefix: &str,
2940 metadata: &Value,
2941 ) -> Result<TaskRecord> {
2942 let mut state = self.state.lock().await;
2943 let _transaction = self.lock_store().await?;
2944 self.refresh_locked_offloaded(&mut state).await?;
2945 let id = resolve_task_id(&state.tasks, id_or_prefix)?;
2946 let updated = {
2947 let task = state
2948 .tasks
2949 .get_mut(&id)
2950 .ok_or_else(|| anyhow!("Task not found: {id}"))?;
2951 self.apply_task_update_metadata(task, Some(metadata))?;
2952 task.clone()
2953 };
2954 self.persist_changed_task_locked(&mut state, &id)?;
2955 Ok(updated)
2956 }
2957
2958 async fn claim_next_task(&self) -> Result<Option<(String, ExecutionTask, CancellationToken)>> {
2959 let mut state = self.state.lock().await;
2960 let _transaction = self.lock_store().await?;
2961 // The worker loop runs this repeatedly; keep the directory scan and
2962 // JSON parsing off the async runtime threads (#6573).
2963 let (tasks_dir, queue_path) = (self.tasks_dir.clone(), self.queue_path.clone());
2964 let loaded = tokio::task::spawn_blocking(move || load_state(&tasks_dir, &queue_path))
2965 .await
2966 .context("Task store load was interrupted")??;
2967 self.apply_loaded_locked(&mut state, loaded)?;
2968 if self.cancel_token.is_cancelled() {
2969 return Ok(None);
2970 }
2971 let Some(id) = state
2972 .queue
2973 .iter()
2974 .find(|id| {
2975 state.tasks.get(*id).is_some_and(|task| {
2976 task.status == TaskStatus::Queued
2977 && task.execution_scope.as_deref() == Some(self.execution_scope())
2978 })
2979 })
2980 .cloned()
2981 else {
2982 return Ok(None);
2983 };
2984 state.read_snapshot = None;
2985 state.queue.retain(|queued| queued != &id);
2986 let task = state
2987 .tasks
2988 .get_mut(&id)
2989 .context("Claimed task is missing")?;
2990 let now = Utc::now();
2991 task.status = TaskStatus::Running;
2992 task.execution_generation = Some(self.execution_lease.generation.clone());
2993 task.lifecycle_seq = task.lifecycle_seq.saturating_add(1);
2994 task.started_at = Some(now);
2995 task.ended_at = None;
2996 task.duration_ms = None;
2997 task.error = None;
2998 push_timeline_entry(
2999 task,
3000 TaskTimelineEntry {
3001 timestamp: now,
3002 kind: "running".into(),
3003 summary: "Task started".into(),
3004 detail_path: None,
3005 },
3006 );
3007 let request = ExecutionTask::from(&*task);
3008 // Removing queue membership first is recoverable from the still-Queued
3009 // record. Executor polling requires BOTH durable writes to succeed.
3010 self.persist_queue_locked(&state.queue)?;
3011 self.persist_changed_task_locked(&mut state, &id)?;
3012 let cancel = CancellationToken::new();
3013 state.running_cancel.insert(id.clone(), cancel.clone());
3014 Ok(Some((id, request, cancel)))
3015 }
3016
3017 /// Claim and run queued work.
3018 ///
3019 /// Several processes can share one data dir, and every claim takes the
3020 /// cross-process store lock and reloads the whole store. An idle worker
3021 /// therefore only claims when it was notified in-process, when the store
3022 /// fingerprint changed, or when unreadable/recent metadata needs a retry.
3023 /// A settled empty queue does no periodic full reload; failed claims still
3024 /// back off exponentially instead of retrying every tick (#6573, #6728).
3025 async fn worker_loop(self: Arc<Self>, mut inspections: mpsc::Receiver<InspectionReply>) {
3026 let mut schedule = ClaimSchedule::new(Instant::now());
3027 let mut woken = true;
3028 let mut initial_claim = true;
3029 // True while consecutive claims are failing: the first failure of an
3030 // episode is an error, repeats are debug until a claim succeeds (#6573).
3031 let mut claim_failing = false;
3032 // Startup supplies the first inspection request. Waiting for it avoids
3033 // running a recovered task before startup can observe its claim result.
3034 let mut reply = tokio::select! {
3035 _ = self.cancel_token.cancelled() => return,
3036 request = inspections.recv() => request,
3037 };
3038 loop {
3039 if self.cancel_token.is_cancelled() {
3040 break;
3041 }
3042 // Read before claiming so a write racing the claim changes the
3043 // fingerprint and is picked up on the next pass.
3044 #[cfg(any(test, feature = "test-support"))]
3045 self.fingerprint_reads
3046 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3047 let fingerprint = StoreFingerprint::read(&self.queue_path);
3048 if schedule.should_claim(&fingerprint, Instant::now(), woken) {
3049 let startup_claim = std::mem::take(&mut initial_claim);
3050 match self.claim_next_task().await {
3051 Ok(Some((id, request, cancel))) => {
3052 claim_failing = false;
3053 schedule.claimed_task(Instant::now());
3054 if let Some(reply) = reply.take() {
3055 let _ = reply.send(Ok(schedule.clone()));
3056 }
3057 self.run_task(id, request, cancel).await;
3058 woken = true;
3059 continue;
3060 }
3061 Ok(None) => {
3062 claim_failing = false;
3063 schedule.found_nothing(
3064 fingerprint,
3065 Instant::now(),
3066 std::time::SystemTime::now(),
3067 );
3068 }
3069 Err(error) => {
3070 let retry = schedule.claim_failed(fingerprint, Instant::now());
3071 let retry_ms = retry.as_millis() as u64;
3072 if claim_failing {
3073 tracing::debug!(
3074 %error,
3075 retry_ms,
3076 "Task claim still unavailable; executor was not polled"
3077 );
3078 } else {
3079 claim_failing = true;
3080 tracing::error!(
3081 %error,
3082 retry_ms,
3083 "Task claim unavailable; executor was not polled"
3084 );
3085 }
3086 if let Some(reply) = reply.take() {
3087 if startup_claim && error.is::<TaskStoreBusy>() {
3088 // A committed contention retry is worker readiness,
3089 // not a claim that storage is settled or idle.
3090 let _ = reply.send(Ok(schedule.clone()));
3091 } else {
3092 let _ = reply.send(Err(error));
3093 }
3094 }
3095 }
3096 }
3097 }
3098 if let Some(reply) = reply.take() {
3099 let _ = reply.send(Ok(schedule.clone()));
3100 }
3101 woken = false;
3102 tokio::select! {
3103 _ = self.cancel_token.cancelled() => break,
3104 request = inspections.recv() => {
3105 let Some(request) = request else { break };
3106 reply = Some(request);
3107 }
3108 _ = self.notify.notified() => woken = true,
3109 _ = sleep(schedule.nap()) => {},
3110 }
3111 }
3112 }
3113
3114 fn observe_task_cancellation(&self, task_id: &str, cancel: &CancellationToken) -> Result<()> {
3115 let task = self
3116 .read_bound_task(task_id)?
3117 .context("Running task is missing")?;
3118 self.require_execution_owner(&task)?;
3119 if task.cancel_requested_seq > 0 {
3120 cancel.cancel();
3121 }
3122 Ok(())
3123 }
3124
3125 async fn run_task(&self, task_id: String, request: ExecutionTask, cancel: CancellationToken) {
3126 let (event_tx, mut event_rx) = mpsc::channel(TASK_EVENT_CHANNEL_CAPACITY);
3127 let exec_fut = self
3128 .executor
3129 .execute(request.clone(), event_tx, cancel.clone());
3130 tokio::pin!(exec_fut);
3131
3132 let guard_started_at = Instant::now();
3133 let guard_started_wall = Utc::now();
3134 let mut guard = ExecutionGuard::new(self.cfg.execution_limits, guard_started_at);
3135 let mut dirty = false;
3136 let mut accumulated_result_text = String::new();
3137 let persist_debounce = self.cfg.execution_limits.persist_debounce;
3138 let mut persist_deadline = None;
3139
3140 let mut next_store_poll = Instant::now();
3141 let mut execution_started = false;
3142 let mut blocked_event: Option<TaskExecutionEvent> = None;
3143 let mut next_event_retry = Instant::now();
3144 let (mut result, manager_terminalized) = loop {
3145 if Instant::now() >= next_store_poll {
3146 if let Err(error) = self.observe_task_cancellation(&task_id, &cancel) {
3147 tracing::error!(%error, "Task ownership unavailable; requesting Runtime cancellation");
3148 cancel.cancel();
3149 }
3150 next_store_poll = Instant::now() + STORE_REFRESH_INTERVAL;
3151 }
3152 if !execution_started && (cancel.is_cancelled() || self.cancel_token.is_cancelled()) {
3153 let reason = if self.cancel_token.is_cancelled() {
3154 TaskTerminalReason::Shutdown
3155 } else {
3156 TaskTerminalReason::Canceled
3157 };
3158 break (TaskExecutionResult::from_reason(reason, None), true);
3159 }
3160 if Instant::now() >= next_event_retry {
3161 if let Some(event) = blocked_event.take()
3162 && self
3163 .process_execution_event(
3164 &task_id,
3165 event.clone(),
3166 &mut guard,
3167 guard_started_at,
3168 guard_started_wall,
3169 &mut accumulated_result_text,
3170 &mut dirty,
3171 )
3172 .await
3173 .is_err()
3174 {
3175 blocked_event = Some(event);
3176 cancel.cancel();
3177 }
3178 next_event_retry = Instant::now() + STORE_REFRESH_INTERVAL;
3179 }
3180 let mut action = guard.evaluate(
3181 Instant::now(),
3182 cancel.is_cancelled(),
3183 self.cancel_token.is_cancelled(),
3184 );
3185 if matches!(
3186 action,
3187 GuardAction::Interrupt {
3188 reason: TaskTerminalReason::IdleTimeout
3189 }
3190 ) {
3191 // Progress already accepted by the executor must win an idle
3192 // deadline race. Drain only the events queued at this instant
3193 // so a producer cannot keep the watchdog from re-evaluating
3194 // wall time, shutdown, or explicit cancellation indefinitely.
3195 execution_started = true;
3196 let polled_result = tokio::select! {
3197 biased;
3198 result = &mut exec_fut => Some(result),
3199 _ = std::future::ready(()) => None,
3200 };
3201 if let Some(result) = polled_result {
3202 break (guard.preserve_timeout_reason(result), false);
3203 }
3204 let queued = event_rx.len();
3205 for _ in 0..queued {
3206 if blocked_event.is_some() {
3207 break;
3208 }
3209 let Ok(event) = event_rx.try_recv() else {
3210 break;
3211 };
3212 if self
3213 .process_execution_event(
3214 &task_id,
3215 event.clone(),
3216 &mut guard,
3217 guard_started_at,
3218 guard_started_wall,
3219 &mut accumulated_result_text,
3220 &mut dirty,
3221 )
3222 .await
3223 .is_err()
3224 {
3225 blocked_event = Some(event);
3226 cancel.cancel();
3227 }
3228 }
3229 action = guard.evaluate(
3230 Instant::now(),
3231 cancel.is_cancelled(),
3232 self.cancel_token.is_cancelled(),
3233 );
3234 }
3235 match action {
3236 GuardAction::Interrupt { reason } => {
3237 cancel.cancel();
3238 guard.note_interrupt(Instant::now(), reason);
3239 continue;
3240 }
3241 GuardAction::Terminalize { reason } => {
3242 break (TaskExecutionResult::from_reason(reason, None), true);
3243 }
3244 GuardAction::Run { wait } => {
3245 execution_started = true;
3246 // Keep the first dirty event's deadline across heartbeat
3247 // and ownership-poll wakes. An urgent persisted event
3248 // clears dirty and starts a fresh window for later deltas.
3249 let persist_at = if dirty {
3250 *persist_deadline.get_or_insert_with(|| Instant::now() + persist_debounce)
3251 } else {
3252 persist_deadline = None;
3253 Instant::now()
3254 };
3255 tokio::select! {
3256 biased;
3257 exec_result = &mut exec_fut => {
3258 break (guard.preserve_timeout_reason(exec_result), false);
3259 }
3260 // A ready event channel must not starve a due write.
3261 _ = tokio::time::sleep_until(persist_at), if dirty => {
3262 match self.flush_task(&task_id).await {
3263 Ok(()) => {
3264 dirty = false;
3265 persist_deadline = None;
3266 }
3267 Err(err) => {
3268 tracing::error!("Failed to debounce-persist task {task_id}: {err}");
3269 cancel.cancel();
3270 persist_deadline = Some(Instant::now() + persist_debounce);
3271 }
3272 }
3273 }
3274 maybe_event = event_rx.recv(), if blocked_event.is_none() => {
3275 if let Some(event) = maybe_event
3276 && self.process_execution_event(
3277 &task_id, event.clone(), &mut guard, guard_started_at,
3278 guard_started_wall, &mut accumulated_result_text, &mut dirty,
3279 ).await.is_err() {
3280 blocked_event = Some(event);
3281 cancel.cancel();
3282 }
3283 }
3284 _ = self.cancel_token.cancelled(), if !self.cancel_token.is_cancelled() => {
3285 cancel.cancel();
3286 }
3287 _ = sleep(wait.min(STORE_REFRESH_INTERVAL)) => {}
3288 }
3289 }
3290 }
3291 };
3292
3293 // Stop accepting producer events while one event cannot be retained.
3294 // The pending delta set and channel remain bounded during disk failure;
3295 // keep the execution lease until accepted events and the terminal receipt
3296 // have actually been persisted. A storage failure is not completion.
3297 event_rx.close();
3298 loop {
3299 let event = blocked_event.take().or_else(|| event_rx.try_recv().ok());
3300 let Some(event) = event else {
3301 break;
3302 };
3303 while self
3304 .process_execution_event(
3305 &task_id,
3306 event.clone(),
3307 &mut guard,
3308 guard_started_at,
3309 guard_started_wall,
3310 &mut accumulated_result_text,
3311 &mut dirty,
3312 )
3313 .await
3314 .is_err()
3315 {
3316 sleep(STORE_REFRESH_INTERVAL).await;
3317 }
3318 }
3319 if manager_terminalized {
3320 result.result_text = optional_nonzero_text(accumulated_result_text);
3321 }
3322 loop {
3323 match self
3324 .finish_task(
3325 &task_id,
3326 result.clone(),
3327 cancel.clone(),
3328 &request.mode_label,
3329 )
3330 .await
3331 {
3332 Ok(()) => break,
3333 Err(err) => {
3334 tracing::error!(
3335 "Task {task_id} terminal receipt is pending storage recovery: {err}"
3336 );
3337 sleep(STORE_REFRESH_INTERVAL).await;
3338 }
3339 }
3340 }
3341 }
3342
3343 async fn process_execution_event(
3344 &self,
3345 task_id: &str,
3346 event: TaskExecutionEvent,
3347 guard: &mut ExecutionGuard,
3348 guard_started_at: Instant,
3349 guard_started_wall: DateTime<Utc>,
3350 accumulated_result_text: &mut String,
3351 dirty: &mut bool,
3352 ) -> Result<()> {
3353 if matches!(event, TaskExecutionEvent::ToolHeartbeat) {
3354 // Liveness is in-memory only. In particular, leave any real event's
3355 // pending persistence intact; the supervisor still checks execution
3356 // ownership and cancellation on its regular store-poll deadline.
3357 guard.note_progress(Instant::now());
3358 return Ok(());
3359 }
3360 // The human-wait pair moves the supervisor's wall clock in lockstep
3361 // with the turn loop's own guard. In-memory only, like the
3362 // heartbeat: it never touches the record or its persistence.
3363 match event {
3364 TaskExecutionEvent::HumanWaitStarted { at } => {
3365 guard.begin_human_wait(journal_instant(
3366 guard_started_at,
3367 guard_started_wall,
3368 at,
3369 Instant::now(),
3370 ));
3371 return Ok(());
3372 }
3373 TaskExecutionEvent::HumanWaitEnded { at } => {
3374 guard.end_human_wait(journal_instant(
3375 guard_started_at,
3376 guard_started_wall,
3377 at,
3378 Instant::now(),
3379 ));
3380 return Ok(());
3381 }
3382 _ => {}
3383 }
3384 match self.apply_execution_event(task_id, event.clone()).await {
3385 Ok(outcome) => {
3386 if execution_event_is_progress(&event) {
3387 guard.note_progress(Instant::now());
3388 }
3389 append_message_delta(accumulated_result_text, &event);
3390 *dirty = !outcome.persisted;
3391 Ok(())
3392 }
3393 Err(err) => {
3394 tracing::error!("Task {task_id} event is waiting for storage recovery: {err}");
3395 Err(err)
3396 }
3397 }
3398 }
3399
3400 async fn apply_execution_event(
3401 &self,
3402 task_id: &str,
3403 event: TaskExecutionEvent,
3404 ) -> Result<EventApplyOutcome> {
3405 let urgent = execution_event_persist_urgent(&event);
3406 let mut state = self.state.lock().await;
3407 let _transaction = self.lock_store().await?;
3408 self.refresh_locked_offloaded(&mut state).await?;
3409 if state
3410 .pending_events
3411 .get(task_id)
3412 .is_some_and(|events| events.len() >= TASK_EVENT_CHANNEL_CAPACITY)
3413 {
3414 self.persist_changed_task_locked(&mut state, task_id)?;
3415 }
3416 let task = state
3417 .tasks
3418 .get_mut(task_id)
3419 .context("Event task is missing")?;
3420 self.require_execution_owner(task)?;
3421 self.apply_event_to_task(task, event.clone())?;
3422 let pending = state.pending_events.entry(task_id.to_string()).or_default();
3423 pending.push(event);
3424 let persist_now = urgent || pending.len() >= TASK_EVENT_CHANNEL_CAPACITY;
3425 let persisted = if persist_now {
3426 match self.persist_changed_task_locked(&mut state, task_id) {
3427 Ok(()) => true,
3428 Err(error) => {
3429 // This event is already retained in the bounded delta set.
3430 // Return acceptance so the caller must not append it again.
3431 if let Some(cancel) = state.running_cancel.get(task_id) {
3432 cancel.cancel();
3433 }
3434 tracing::error!(%error, "Task event retained pending storage recovery; cancellation requested");
3435 false
3436 }
3437 }
3438 } else {
3439 false
3440 };
3441 Ok(EventApplyOutcome { persisted })
3442 }
3443
3444 fn apply_event_to_task(&self, task: &mut TaskRecord, event: TaskExecutionEvent) -> Result<()> {
3445 let task_id = task.id.clone();
3446 match event {
3447 TaskExecutionEvent::ThreadLinked { thread_id, turn_id } => {
3448 task.thread_id = Some(thread_id.clone());
3449 task.turn_id = Some(turn_id.clone());
3450 push_timeline_entry(
3451 task,
3452 TaskTimelineEntry {
3453 timestamp: Utc::now(),
3454 kind: "runtime_link".to_string(),
3455 summary: format!("Linked runtime thread {thread_id} turn {turn_id}"),
3456 detail_path: None,
3457 },
3458 );
3459 }
3460 TaskExecutionEvent::Status { message } => {
3461 push_timeline_entry(
3462 task,
3463 TaskTimelineEntry {
3464 timestamp: Utc::now(),
3465 kind: "status".to_string(),
3466 summary: summarize_text(&message, TIMELINE_SUMMARY_LIMIT),
3467 detail_path: None,
3468 },
3469 );
3470 }
3471 TaskExecutionEvent::MessageDelta { content } => {
3472 if !content.trim().is_empty() {
3473 push_timeline_entry(
3474 task,
3475 TaskTimelineEntry {
3476 timestamp: Utc::now(),
3477 kind: "message".to_string(),
3478 summary: summarize_text(&content, TIMELINE_SUMMARY_LIMIT),
3479 detail_path: None,
3480 },
3481 );
3482 }
3483 }
3484 TaskExecutionEvent::ToolStarted { id, name, input } => {
3485 let input_summary = summarize_json(&input);
3486 task.tool_calls.push(TaskToolCallSummary {
3487 id: id.clone(),
3488 name: name.clone(),
3489 status: TaskToolStatus::Running,
3490 started_at: Utc::now(),
3491 ended_at: None,
3492 duration_ms: None,
3493 input_summary: input_summary.clone(),
3494 output_summary: None,
3495 detail_path: None,
3496 patch_ref: None,
3497 });
3498 let summary = input_summary
3499 .map(|s| format!("{name} started ({s})"))
3500 .unwrap_or_else(|| format!("{name} started"));
3501 push_timeline_entry(
3502 task,
3503 TaskTimelineEntry {
3504 timestamp: Utc::now(),
3505 kind: "tool_started".to_string(),
3506 summary,
3507 detail_path: None,
3508 },
3509 );
3510 }
3511 TaskExecutionEvent::ToolProgress { id, output } => {
3512 push_timeline_entry(
3513 task,
3514 TaskTimelineEntry {
3515 timestamp: Utc::now(),
3516 kind: "tool_progress".to_string(),
3517 summary: format!(
3518 "{id}: {}",
3519 summarize_text(&output, TIMELINE_SUMMARY_LIMIT.saturating_sub(8))
3520 ),
3521 detail_path: None,
3522 },
3523 );
3524 }
3525 // Supervisor-side liveness only: recording it would put a
3526 // timeline entry behind every poll tick of a silent build.
3527 TaskExecutionEvent::ToolHeartbeat => {}
3528 // Supervisor-side wall-clock signal only (see the variant doc).
3529 TaskExecutionEvent::HumanWaitStarted { .. }
3530 | TaskExecutionEvent::HumanWaitEnded { .. } => {}
3531 TaskExecutionEvent::ToolCompleted {
3532 id,
3533 name,
3534 success,
3535 output,
3536 metadata,
3537 } => {
3538 let now = Utc::now();
3539 let detail_path = self.artifact_if_large(&task_id, &name, &output)?;
3540 let output_summary = summarize_text(&output, TIMELINE_SUMMARY_LIMIT);
3541 let patch_ref = if name == "apply_patch" {
3542 detail_path.clone()
3543 } else {
3544 None
3545 };
3546
3547 if let Some(call) = task.tool_calls.iter_mut().find(|call| call.id == id) {
3548 call.status = if success {
3549 TaskToolStatus::Success
3550 } else {
3551 TaskToolStatus::Failed
3552 };
3553 call.ended_at = Some(now);
3554 call.duration_ms = Some(duration_ms(call.started_at, now));
3555 call.output_summary = Some(output_summary.clone());
3556 call.detail_path = detail_path.clone();
3557 call.patch_ref = patch_ref.clone();
3558
3559 if call.duration_ms.is_none()
3560 && let Some(duration) = metadata
3561 .as_ref()
3562 .and_then(|m| m.get("duration_ms"))
3563 .and_then(Value::as_u64)
3564 {
3565 call.duration_ms = Some(duration);
3566 }
3567 }
3568
3569 let status = if success { "success" } else { "failed" };
3570 push_timeline_entry(
3571 task,
3572 TaskTimelineEntry {
3573 timestamp: now,
3574 kind: "tool_completed".to_string(),
3575 summary: format!("{name} {status}: {output_summary}"),
3576 detail_path: detail_path.clone(),
3577 },
3578 );
3579 if let Some(patch_ref) = patch_ref {
3580 push_timeline_entry(
3581 task,
3582 TaskTimelineEntry {
3583 timestamp: now,
3584 kind: "patch_ref".to_string(),
3585 summary: format!("Patch artifact: {}", patch_ref.display()),
3586 detail_path: Some(patch_ref),
3587 },
3588 );
3589 }
3590
3591 self.apply_task_update_metadata(task, metadata.as_ref())?;
3592 }
3593 TaskExecutionEvent::Error { message } => {
3594 push_timeline_entry(
3595 task,
3596 TaskTimelineEntry {
3597 timestamp: Utc::now(),
3598 kind: "error".to_string(),
3599 summary: summarize_text(&message, TIMELINE_SUMMARY_LIMIT),
3600 detail_path: None,
3601 },
3602 );
3603 }
3604 TaskExecutionEvent::RuntimeEvent {
3605 seq,
3606 event,
3607 summary,
3608 } => {
3609 task.runtime_event_count = task.runtime_event_count.saturating_add(1);
3610 push_timeline_entry(
3611 task,
3612 TaskTimelineEntry {
3613 timestamp: Utc::now(),
3614 kind: "runtime_event".to_string(),
3615 summary: format!("#{seq} {event}: {summary}"),
3616 detail_path: None,
3617 },
3618 );
3619 }
3620 }
3621
3622 Ok(())
3623 }
3624
3625 async fn flush_task(&self, task_id: &str) -> Result<()> {
3626 let mut state = self.state.lock().await;
3627 let _transaction = self.lock_store().await?;
3628 self.refresh_locked_offloaded(&mut state).await?;
3629 let task = state
3630 .tasks
3631 .get(task_id)
3632 .context("Flushed task is missing")?;
3633 self.require_execution_owner(task)?;
3634 self.persist_changed_task_locked(&mut state, task_id)
3635 }
3636
3637 async fn finish_task(
3638 &self,
3639 task_id: &str,
3640 mut result: TaskExecutionResult,
3641 cancel: CancellationToken,
3642 mode_label: &str,
3643 ) -> Result<()> {
3644 let mut state = self.state.lock().await;
3645 let _transaction = self.lock_store().await?;
3646 self.refresh_locked_offloaded(&mut state).await?;
3647 state.running_cancel.remove(task_id);
3648 let task = state
3649 .tasks
3650 .get_mut(task_id)
3651 .context("Finished task is missing")?;
3652 self.require_execution_owner(task)?;
3653
3654 let now = Utc::now();
3655 if (cancel.is_cancelled() || task.cancel_requested_seq > 0)
3656 && result.status == TaskStatus::Completed
3657 {
3658 result.status = TaskStatus::Canceled;
3659 result.result_text = None;
3660 result.error = None;
3661 result.terminal_reason = TaskTerminalReason::Canceled;
3662 }
3663 if self.cancel_token.is_cancelled()
3664 && result.status != TaskStatus::Completed
3665 && matches!(
3666 result.terminal_reason,
3667 TaskTerminalReason::Canceled | TaskTerminalReason::Failed
3668 )
3669 {
3670 result.status = TaskStatus::Canceled;
3671 result.terminal_reason = TaskTerminalReason::Shutdown;
3672 result.error = Some(TaskTerminalReason::Shutdown.receipt_message());
3673 }
3674
3675 task.status = result.status;
3676 task.lifecycle_seq = task.lifecycle_seq.saturating_add(1);
3677 task.mode = mode_label.to_string();
3678 task.ended_at = Some(now);
3679 task.duration_ms = task.started_at.map(|start| duration_ms(start, now));
3680 task.error = result.error.clone();
3681 task.terminal_reason = Some(result.terminal_reason.as_str().to_string());
3682 let finished_summary = if matches!(result.status, TaskStatus::Queued | TaskStatus::Running)
3683 {
3684 format!("Task ended in unexpected state: {mode_label}")
3685 } else {
3686 match result.terminal_reason {
3687 TaskTerminalReason::Completed
3688 | TaskTerminalReason::Canceled
3689 | TaskTerminalReason::Shutdown => result.terminal_reason.receipt_message(),
3690 TaskTerminalReason::Failed
3691 | TaskTerminalReason::WallTimeout
3692 | TaskTerminalReason::HumanWaitTimeout
3693 | TaskTerminalReason::IdleTimeout
3694 | TaskTerminalReason::CancelTimeout => format!(
3695 "{}: {}",
3696 result.terminal_reason.as_str(),
3697 result
3698 .error
3699 .as_deref()
3700 .map(|e| summarize_text(e, TIMELINE_SUMMARY_LIMIT))
3701 .unwrap_or_else(|| result.terminal_reason.receipt_message())
3702 ),
3703 }
3704 };
3705 push_timeline_entry(
3706 task,
3707 TaskTimelineEntry {
3708 timestamp: now,
3709 kind: "finished".to_string(),
3710 summary: finished_summary,
3711 detail_path: None,
3712 },
3713 );
3714
3715 if let Some(text) = result.result_text {
3716 let detail_path = self.artifact_if_large(task_id, "result", &text)?;
3717 task.result_summary = Some(summarize_text(&text, TIMELINE_SUMMARY_LIMIT));
3718 task.result_detail_path = detail_path.clone();
3719 if let Some(detail_path) = detail_path {
3720 push_timeline_entry(
3721 task,
3722 TaskTimelineEntry {
3723 timestamp: now,
3724 kind: "result_ref".to_string(),
3725 summary: format!("Result artifact: {}", detail_path.display()),
3726 detail_path: Some(detail_path),
3727 },
3728 );
3729 }
3730 } else if result.status == TaskStatus::Completed {
3731 task.result_summary = Some("(no textual output)".to_string());
3732 }
3733
3734 self.persist_changed_task_locked(&mut state, task_id)?;
3735 Ok(())
3736 }
3737
3738 fn artifact_if_large(
3739 &self,
3740 task_id: &str,
3741 label: &str,
3742 content: &str,
3743 ) -> Result<Option<PathBuf>> {
3744 if content.len() < ARTIFACT_THRESHOLD {
3745 return Ok(None);
3746 }
3747 self.write_artifact(task_id, label, content).map(Some)
3748 }
3749
3750 fn write_artifact(&self, task_id: &str, label: &str, content: &str) -> Result<PathBuf> {
3751 ensure_safe_storage_id("task id", task_id)?;
3752 let artifact_dir = self.artifacts_dir.join(task_id);
3753 fs::create_dir_all(&artifact_dir)
3754 .with_context(|| format!("Failed to create artifact dir {}", artifact_dir.display()))?;
3755 let stamp = Utc::now().format("%Y%m%dT%H%M%S%.3fZ");
3756 let filename = format!("{stamp}_{}.txt", sanitize_filename(label));
3757 let absolute = artifact_dir.join(filename);
3758 fs::write(&absolute, content)
3759 .with_context(|| format!("Failed to write artifact {}", absolute.display()))?;
3760 let relative = absolute
3761 .strip_prefix(&self.cfg.data_dir)
3762 .map(PathBuf::from)
3763 .unwrap_or(absolute);
3764 Ok(relative)
3765 }
3766
3767 fn apply_task_update_metadata(
3768 &self,
3769 task: &mut TaskRecord,
3770 metadata: Option<&Value>,
3771 ) -> Result<()> {
3772 let Some(updates) = metadata.and_then(|m| m.get("task_updates")) else {
3773 return Ok(());
3774 };
3775 let now = Utc::now();
3776
3777 if let Some(value) = updates.get("checklist") {
3778 let mut checklist: TaskChecklistState = serde_json::from_value(value.clone())
3779 .context("Failed to parse checklist task update")?;
3780 checklist.updated_at = checklist.updated_at.or(Some(now));
3781 task.checklist = checklist;
3782 push_timeline_entry(
3783 task,
3784 TaskTimelineEntry {
3785 timestamp: now,
3786 kind: "checklist".to_string(),
3787 summary: format!(
3788 "Checklist updated: {} item(s), {}% complete",
3789 task.checklist.items.len(),
3790 task.checklist.completion_pct
3791 ),
3792 detail_path: None,
3793 },
3794 );
3795 }
3796
3797 if let Some(value) = updates.get("gate") {
3798 let gate: TaskGateRecord = serde_json::from_value(value.clone())
3799 .context("Failed to parse gate task update")?;
3800 let summary = format!("Gate {} {}: {}", gate.gate, gate.status, gate.summary);
3801 task.gates.retain(|existing| existing.id != gate.id);
3802 task.gates.push(gate.clone());
3803 push_timeline_entry(
3804 task,
3805 TaskTimelineEntry {
3806 timestamp: now,
3807 kind: "gate".to_string(),
3808 summary: summarize_text(&summary, TIMELINE_SUMMARY_LIMIT),
3809 detail_path: gate.log_path,
3810 },
3811 );
3812 }
3813
3814 if let Some(value) = updates.get("attempt") {
3815 let attempt: TaskAttemptRecord = serde_json::from_value(value.clone())
3816 .context("Failed to parse attempt task update")?;
3817 task.attempts.retain(|existing| existing.id != attempt.id);
3818 task.attempts.push(attempt.clone());
3819 push_timeline_entry(
3820 task,
3821 TaskTimelineEntry {
3822 timestamp: now,
3823 kind: "pr_attempt".to_string(),
3824 summary: format!(
3825 "Attempt {}/{} recorded for {}",
3826 attempt.attempt_index, attempt.attempt_count, attempt.attempt_group_id
3827 ),
3828 detail_path: attempt.patch_path,
3829 },
3830 );
3831 }
3832
3833 if let Some(value) = updates.get("artifacts")
3834 && let Some(items) = value.as_array()
3835 {
3836 for item in items {
3837 let artifact: TaskArtifactRef = serde_json::from_value(item.clone())
3838 .context("Failed to parse artifact task update")?;
3839 push_timeline_entry(
3840 task,
3841 TaskTimelineEntry {
3842 timestamp: now,
3843 kind: "artifact".to_string(),
3844 summary: format!("{}: {}", artifact.label, artifact.summary),
3845 detail_path: Some(artifact.path.clone()),
3846 },
3847 );
3848 task.artifacts.push(artifact);
3849 }
3850 }
3851
3852 if let Some(value) = updates.get("github_event") {
3853 let event: TaskGithubEvent = serde_json::from_value(value.clone())
3854 .context("Failed to parse GitHub task update")?;
3855 push_timeline_entry(
3856 task,
3857 TaskTimelineEntry {
3858 timestamp: now,
3859 kind: "github".to_string(),
3860 summary: format!(
3861 "{} {}#{}: {}",
3862 event.action, event.target, event.number, event.summary
3863 ),
3864 detail_path: None,
3865 },
3866 );
3867 task.github_events.push(event);
3868 }
3869
3870 Ok(())
3871 }
3872
3873 /// Acquire the cross-process task-store lock.
3874 ///
3875 /// Polls with exponential backoff (5ms → 50ms) instead of a flat 5ms
3876 /// interval: under contention the old shape woke ~200×/s for up to its
3877 /// whole five-second deadline (#6211 R7c). The deadline and the busy
3878 /// error are unchanged. What this does not do: it does not add the
3879 /// in-process mutex the issue also suggested — in-process contenders
3880 /// just back off against the same file lock.
3881 async fn lock_store(&self) -> Result<RuntimeProcessOwnerLock> {
3882 let path = self.cfg.data_dir.join("task-store.lock");
3883 let deadline = Instant::now() + Duration::from_secs(5);
3884 let mut wait = Duration::from_millis(5);
3885 loop {
3886 if let Some(mut owner) = RuntimeProcessOwnerLock::try_acquire_file(&path, true)? {
3887 // Lets a contender that times out name this process (#6573).
3888 owner.record_holder();
3889 return Ok(owner);
3890 }
3891 if Instant::now() >= deadline {
3892 return Err(store_busy_error(&path));
3893 }
3894 sleep(wait).await;
3895 wait = (wait * 2).min(Duration::from_millis(50));
3896 }
3897 }
3898
3899 async fn refresh_locked_offloaded(&self, state: &mut ManagerState) -> Result<()> {
3900 // Callers go on to change `state`; a failed persist must not leave a
3901 // diverged view that a read-only caller would trust.
3902 state.read_snapshot = None;
3903 let (tasks_dir, queue_path) = (self.tasks_dir.clone(), self.queue_path.clone());
3904 let loaded = tokio::task::spawn_blocking(move || load_state(&tasks_dir, &queue_path))
3905 .await
3906 .context("Task store load was interrupted")??;
3907 self.apply_loaded_locked(state, loaded)
3908 }
3909
3910 /// Bring `state` up to date for a read-only caller (#6573).
3911 ///
3912 /// Skips the cross-process lock and the full reload while the store is
3913 /// provably unchanged since the last read-only refresh. Several TUIs
3914 /// sharing one data dir each list tasks every 2.5s on their event loop;
3915 /// without this, every idle session took the store lock and re-parsed
3916 /// every task record on each poll, contending with the others.
3917 async fn refresh_for_read(&self, state: &mut ManagerState) -> Result<()> {
3918 if let Some(snapshot) = &state.read_snapshot
3919 && *snapshot == ReadSnapshot::read(&self.tasks_dir, &self.queue_path)
3920 {
3921 return Ok(());
3922 }
3923 let _transaction = self.lock_store().await?;
3924 // Taken under the lock and before the load, so any later write
3925 // changes it.
3926 let snapshot = ReadSnapshot::read(&self.tasks_dir, &self.queue_path);
3927 self.refresh_locked_offloaded(state).await?;
3928 if snapshot.settled(std::time::SystemTime::now()) {
3929 state.read_snapshot = Some(snapshot);
3930 }
3931 Ok(())
3932 }
3933
3934 fn apply_loaded_locked(&self, state: &mut ManagerState, loaded: LoadedTaskState) -> Result<()> {
3935 #[cfg(any(test, feature = "test-support"))]
3936 self.store_loads
3937 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3938 state.tasks = loaded.tasks;
3939 state.queue = loaded.queue;
3940 for (id, events) in &state.pending_events {
3941 let task = state
3942 .tasks
3943 .get_mut(id)
3944 .context("Pending task disappeared")?;
3945 self.require_execution_owner(task)?;
3946 for event in events {
3947 self.apply_event_to_task(task, event.clone())?;
3948 }
3949 }
3950 Ok(())
3951 }
3952
3953 fn require_execution_owner(&self, task: &TaskRecord) -> Result<()> {
3954 if task.execution_scope.as_deref() != Some(self.execution_scope())
3955 || task.execution_generation.as_deref() != Some(&self.execution_lease.generation)
3956 || task.status != TaskStatus::Running
3957 {
3958 bail!("Task execution ownership changed; refusing a stale write");
3959 }
3960 Ok(())
3961 }
3962
3963 fn persist_changed_task_locked(&self, state: &mut ManagerState, id: &str) -> Result<()> {
3964 let task = state.tasks.get(id).context("Changed task is missing")?;
3965 self.persist_task_locked(task)?;
3966 state.pending_events.remove(id);
3967 Ok(())
3968 }
3969
3970 fn recover_dead_executions_locked(&self, state: &mut ManagerState) -> Result<()> {
3971 for task in state.tasks.values_mut() {
3972 // Unknown legacy ownership is preserved, never guessed from the
3973 // visibility owner, model spelling, or current process defaults.
3974 if task.status != TaskStatus::Running {
3975 continue;
3976 }
3977 let (Some(scope), Some(generation)) =
3978 (&task.execution_scope, &task.execution_generation)
3979 else {
3980 continue;
3981 };
3982 let path = execution_lease_path(&self.cfg.data_dir, scope, generation)?;
3983 let Some(_dead_owner) = RuntimeProcessOwnerLock::try_acquire_file(&path, false)? else {
3984 continue;
3985 };
3986 let now = Utc::now();
3987 let duration_ms = task.started_at.and_then(|started| {
3988 u64::try_from(now.signed_duration_since(started).num_milliseconds()).ok()
3989 });
3990 task.status = TaskStatus::Failed;
3991 task.lifecycle_seq = task.lifecycle_seq.saturating_add(1);
3992 task.ended_at = Some(now);
3993 task.duration_ms = duration_ms;
3994 task.terminal_reason = Some(TaskTerminalReason::Failed.as_str().to_string());
3995 task.error =
3996 Some("Interrupted by process restart; prior process is not attached".to_string());
3997 for tool in &mut task.tool_calls {
3998 if tool.status == TaskToolStatus::Running {
3999 tool.status = TaskToolStatus::Failed;
4000 tool.ended_at = Some(now);
4001 tool.duration_ms = duration_ms.or_else(|| {
4002 u64::try_from(
4003 now.signed_duration_since(tool.started_at)
4004 .num_milliseconds(),
4005 )
4006 .ok()
4007 });
4008 }
4009 }
4010 push_timeline_entry(
4011 task,
4012 TaskTimelineEntry {
4013 timestamp: now,
4014 kind: "recovered".to_string(),
4015 summary: "Interrupted by process restart; prior process is not attached"
4016 .to_string(),
4017 detail_path: None,
4018 },
4019 );
4020
4021 self.persist_task_locked(task)?;
4022 }
4023 Ok(())
4024 }
4025
4026 fn persist_queue_locked(&self, queue: &VecDeque<String>) -> Result<()> {
4027 write_json_atomic(
4028 &self.queue_path,
4029 &QueueFile {
4030 queue: queue.iter().cloned().collect(),
4031 },
4032 )
4033 }
4034
4035 fn persist_task_locked(&self, task: &TaskRecord) -> Result<()> {
4036 let path = self.tasks_dir.join(format!("{}.json", task.id));
4037 let min_version = required_task_schema_version(&task.disallowed_tools);
4038 if task.schema_version < min_version {
4039 let mut updated = task.clone();
4040 updated.schema_version = min_version;
4041 return write_json_atomic(&path, &updated);
4042 }
4043 write_json_atomic(&path, task)
4044 }
4045 }
4046
4047 fn validate_preallocated_task_id(task_id: &str) -> Result<()> {
4048 if task_id.len() != 21
4049 || !task_id.starts_with("task_")
4050 || !task_id[5..].chars().all(|ch| ch.is_ascii_hexdigit())
4051 {
4052 bail!("Invalid preallocated task id: expected task_<16hex>");
4053 }
4054 Ok(())
4055 }
4056
4057 fn read_bound_task_file(path: &Path, task_id: &str) -> Result<Option<TaskRecord>> {
4058 let bytes = match fs::read(path) {
4059 Ok(bytes) => bytes,
4060 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
4061 Err(error) => return Err(error).context("read bound task"),
4062 };
4063 let task: TaskRecord = serde_json::from_slice(&bytes).context("decode bound task")?;
4064 if task.id != task_id || task.schema_version > MAX_SUPPORTED_TASK_SCHEMA_VERSION {
4065 bail!("Bound task identity or schema does not match its durable admission");
4066 }
4067 Ok(Some(task))
4068 }
4069
4070 pub fn normalize_deny_rules(rules: Vec<String>) -> Vec<String> {
4071 let mut seen = Vec::with_capacity(rules.len());
4072 for rule in rules {
4073 let rule = rule.trim();
4074 if !rule.is_empty() && !seen.iter().any(|existing: &String| existing == rule) {
4075 seen.push(rule.to_string());
4076 }
4077 }
4078 seen
4079 }
4080
4081 fn deny_rule_covers(held: &str, required: &str) -> bool {
4082 let held = held.to_ascii_lowercase();
4083 let required = required.to_ascii_lowercase();
4084 match (held.strip_suffix('*'), required.strip_suffix('*')) {
4085 (Some(held_prefix), Some(required_prefix)) => required_prefix.starts_with(held_prefix),
4086 (Some(held_prefix), None) => required.starts_with(held_prefix),
4087 (None, Some(_)) => false,
4088 (None, None) => held == required,
4089 }
4090 }
4091
4092 pub fn deny_rules_cover(held: &[String], required: &[String]) -> bool {
4093 required
4094 .iter()
4095 .all(|rule| held.iter().any(|held| deny_rule_covers(held, rule)))
4096 }
4097
4098 pub fn validate_bound_task_request(task: &TaskRecord, request: &NewTaskRequest) -> Result<()> {
4099 if task.prompt != request.prompt.trim()
4100 || task.owner_session_id != request.owner_session_id
4101 || task.destination_thread_id != request.destination_thread_id
4102 || task.model_provider != request.model_provider
4103 || task.model_provider_id != request.model_provider_id
4104 || request
4105 .model
4106 .as_ref()
4107 .is_some_and(|value| value != &task.model)
4108 || request
4109 .workspace
4110 .as_ref()
4111 .is_some_and(|value| value != &task.workspace)
4112 || request
4113 .mode
4114 .as_ref()
4115 .is_some_and(|value| value != &task.mode)
4116 || request
4117 .allow_shell
4118 .is_some_and(|value| value != task.allow_shell)
4119 || request
4120 .trust_mode
4121 .is_some_and(|value| value != task.trust_mode)
4122 || request
4123 .permission_posture
4124 .as_deref()
4125 .is_some_and(|value| Some(value) != task.permission_posture.as_deref())
4126 || task.auto_approve != request.auto_approve.unwrap_or(false)
4127 || task.disallowed_tools != normalize_deny_rules(request.disallowed_tools.clone())
4128 {
4129 bail!("Task admission replay does not match the bound request");
4130 }
4131 Ok(())
4132 }
4133
4134 /// A read-only inventory and reconstructed queue. Execution recovery is a
4135 /// separate transaction requiring proof that a particular generation died.
4136 struct LoadedTaskState {
4137 tasks: HashMap<String, TaskRecord>,
4138 queue: VecDeque<String>,
4139 }
4140
4141 fn load_state(tasks_dir: &Path, queue_path: &Path) -> Result<LoadedTaskState> {
4142 let mut tasks = HashMap::new();
4143 if tasks_dir.exists() {
4144 for entry in fs::read_dir(tasks_dir)
4145 .with_context(|| format!("Failed to read tasks dir {}", tasks_dir.display()))?
4146 {
4147 let entry = entry?;
4148 let path = entry.path();
4149 if path.extension().is_none_or(|ext| ext != "json") {
4150 continue;
4151 }
4152 let content = fs::read_to_string(&path)
4153 .with_context(|| format!("Failed to read task file {}", path.display()))?;
4154 let task: TaskRecord = serde_json::from_str(&content)
4155 .with_context(|| format!("Failed to parse task file {}", path.display()))?;
4156 if task.schema_version > MAX_SUPPORTED_TASK_SCHEMA_VERSION {
4157 bail!(
4158 "Task schema v{} is newer than supported v{}",
4159 task.schema_version,
4160 MAX_SUPPORTED_TASK_SCHEMA_VERSION
4161 );
4162 }
4163 ensure_safe_storage_id("task id", &task.id)?;
4164 if path.file_stem().and_then(|stem| stem.to_str()) != Some(task.id.as_str()) {
4165 bail!("Task record identity differs from its path");
4166 }
4167 if let Some(scope) = &task.execution_scope {
4168 validate_execution_id(scope, 64)?;
4169 }
4170 if let Some(generation) = &task.execution_generation {
4171 validate_execution_id(generation, 32)?;
4172 if task.execution_scope.is_none() {
4173 bail!("Task generation has no execution scope");
4174 }
4175 }
4176 tasks.insert(task.id.clone(), task);
4177 }
4178 }
4179
4180 let mut queue = if queue_path.exists() {
4181 let content = fs::read_to_string(queue_path)
4182 .with_context(|| format!("Failed to read queue file {}", queue_path.display()))?;
4183 let parsed: QueueFile = serde_json::from_str(&content)
4184 .with_context(|| format!("Failed to parse queue file {}", queue_path.display()))?;
4185 VecDeque::from(parsed.queue)
4186 } else {
4187 VecDeque::new()
4188 };
4189
4190 queue.retain(|id| {
4191 tasks
4192 .get(id)
4193 .is_some_and(|task| task.status == TaskStatus::Queued)
4194 });
4195
4196 let known = queue.iter().cloned().collect::<HashSet<_>>();
4197 let mut missing = tasks
4198 .values()
4199 .filter(|task| task.status == TaskStatus::Queued && !known.contains(&task.id))
4200 .map(|task| task.id.clone())
4201 .collect::<Vec<_>>();
4202 missing.sort();
4203 for id in missing {
4204 queue.push_back(id);
4205 }
4206
4207 Ok(LoadedTaskState { tasks, queue })
4208 }
4209
4210 struct EventApplyOutcome {
4211 persisted: bool,
4212 }
4213
4214 fn execution_event_is_progress(event: &TaskExecutionEvent) -> bool {
4215 matches!(
4216 event,
4217 TaskExecutionEvent::MessageDelta { .. }
4218 | TaskExecutionEvent::ToolStarted { .. }
4219 | TaskExecutionEvent::ToolProgress { .. }
4220 | TaskExecutionEvent::ToolHeartbeat
4221 | TaskExecutionEvent::ToolCompleted { .. }
4222 )
4223 }
4224
4225 fn execution_event_persist_urgent(event: &TaskExecutionEvent) -> bool {
4226 !matches!(
4227 event,
4228 TaskExecutionEvent::MessageDelta { .. }
4229 | TaskExecutionEvent::ToolProgress { .. }
4230 | TaskExecutionEvent::RuntimeEvent { .. }
4231 // Liveness-only signal (see the variant doc): it arrives up to
4232 // ~5x/s throughout a silent build, and persisting it would
4233 // rewrite the whole task record on every tick while holding the
4234 // manager-wide state lock.
4235 | TaskExecutionEvent::ToolHeartbeat
4236 // Supervisor-side wall-clock signal for human waits (see the
4237 // variant doc): carries no record state.
4238 | TaskExecutionEvent::HumanWaitStarted { .. }
4239 | TaskExecutionEvent::HumanWaitEnded { .. }
4240 )
4241 }
4242
4243 fn timeline_kinds_coalesce(left: &str, right: &str) -> bool {
4244 matches!(
4245 (left, right),
4246 ("message", "message")
4247 | ("tool_progress", "tool_progress")
4248 | ("runtime_event", "runtime_event")
4249 )
4250 }
4251
4252 fn push_timeline_entry(task: &mut TaskRecord, entry: TaskTimelineEntry) {
4253 if let Some(last) = task.timeline.last_mut()
4254 && timeline_kinds_coalesce(last.kind.as_str(), entry.kind.as_str())
4255 {
4256 last.timestamp = entry.timestamp;
4257 last.summary = entry.summary;
4258 last.detail_path = entry.detail_path;
4259 return;
4260 }
4261 task.timeline.push(entry);
4262 trim_task_timeline(&mut task.timeline);
4263 }
4264
4265 fn trim_task_timeline(entries: &mut Vec<TaskTimelineEntry>) {
4266 if entries.len() <= TIMELINE_ENTRY_LIMIT {
4267 return;
4268 }
4269 let overflow = entries.len() - TIMELINE_ENTRY_LIMIT;
4270 let start = TIMELINE_HEAD_KEEP.min(entries.len().saturating_sub(overflow + 1));
4271 let end = start + overflow;
4272 if start >= end || end > entries.len() {
4273 entries.truncate(TIMELINE_ENTRY_LIMIT);
4274 return;
4275 }
4276 entries.drain(start..end);
4277 let omitted = TaskTimelineEntry {
4278 timestamp: Utc::now(),
4279 kind: "omitted".to_string(),
4280 summary: format!("{overflow} earlier events omitted to bound storage"),
4281 detail_path: None,
4282 };
4283 if entries
4284 .get(start)
4285 .is_none_or(|entry| entry.kind != "omitted")
4286 {
4287 entries.insert(start, omitted);
4288 }
4289 if entries.len() > TIMELINE_ENTRY_LIMIT {
4290 let extra = entries.len() - TIMELINE_ENTRY_LIMIT;
4291 let drop_at = (start + 1).min(entries.len().saturating_sub(1));
4292 let drop_end = (drop_at + extra).min(entries.len());
4293 if drop_at < drop_end {
4294 entries.drain(drop_at..drop_end);
4295 } else {
4296 entries.truncate(TIMELINE_ENTRY_LIMIT);
4297 }
4298 }
4299 }
4300
4301 fn resolve_task_id_visible_to(
4302 tasks: &HashMap<String, TaskRecord>,
4303 id_or_prefix: &str,
4304 owner_session_id: Option<&str>,
4305 ) -> Result<String> {
4306 let visible = |record: &TaskRecord| {
4307 owner_session_id.is_none_or(|owner_session_id| {
4308 record.owner_session_id.as_deref() == Some(owner_session_id)
4309 })
4310 };
4311 if tasks.get(id_or_prefix).is_some_and(visible) {
4312 return Ok(id_or_prefix.to_string());
4313 }
4314 let matches = tasks
4315 .iter()
4316 .filter(|(id, record)| id.starts_with(id_or_prefix) && visible(record))
4317 .map(|(id, _)| id)
4318 .cloned()
4319 .collect::<Vec<_>>();
4320 match matches.len() {
4321 0 => bail!("Task not found: {id_or_prefix}"),
4322 1 => Ok(matches[0].clone()),
4323 _ => bail!(
4324 "Ambiguous task prefix '{}': matches {} tasks",
4325 id_or_prefix,
4326 matches.len()
4327 ),
4328 }
4329 }
4330
4331 fn resolve_task_id_visible_to_operator(
4332 tasks: &HashMap<String, TaskRecord>,
4333 id_or_prefix: &str,
4334 owner_session_id: &str,
4335 execution_scope: &str,
4336 ) -> Result<String> {
4337 let visible = |record: &TaskRecord| {
4338 record.owner_session_id.as_deref() == Some(owner_session_id)
4339 || record.owner_session_id.is_none()
4340 && !execution_scope.is_empty()
4341 && record.execution_scope.as_deref() == Some(execution_scope)
4342 };
4343 if tasks.get(id_or_prefix).is_some_and(visible) {
4344 return Ok(id_or_prefix.to_string());
4345 }
4346 let matches = tasks
4347 .iter()
4348 .filter(|(id, record)| id.starts_with(id_or_prefix) && visible(record))
4349 .map(|(id, _)| id)
4350 .cloned()
4351 .collect::<Vec<_>>();
4352 match matches.len() {
4353 0 => bail!("Task not found: {id_or_prefix}"),
4354 1 => Ok(matches[0].clone()),
4355 _ => bail!(
4356 "Ambiguous task prefix '{}': matches {} tasks",
4357 id_or_prefix,
4358 matches.len()
4359 ),
4360 }
4361 }
4362
4363 fn resolve_task_id(tasks: &HashMap<String, TaskRecord>, id_or_prefix: &str) -> Result<String> {
4364 resolve_task_id_visible_to(tasks, id_or_prefix, None)
4365 }
4366
4367 fn summarize_json(value: &Value) -> Option<String> {
4368 let text = serde_json::to_string(value).ok()?;
4369 Some(summarize_text(&text, TIMELINE_SUMMARY_LIMIT))
4370 }
4371
4372 fn ensure_safe_storage_id(kind: &str, value: &str) -> Result<()> {
4373 let mut components = Path::new(value).components();
4374 let Some(component) = components.next() else {
4375 bail!("{kind} must not be empty");
4376 };
4377 if components.next().is_some() || !matches!(component, std::path::Component::Normal(_)) {
4378 bail!("{kind} must be a single path component");
4379 }
4380 Ok(())
4381 }
4382
4383 fn sanitize_filename(input: &str) -> String {
4384 let mut out = String::new();
4385 for ch in input.chars() {
4386 if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' {
4387 out.push(ch);
4388 } else {
4389 out.push('_');
4390 }
4391 }
4392 if out.is_empty() {
4393 "artifact".to_string()
4394 } else {
4395 out
4396 }
4397 }
4398
4399 fn duration_ms(start: DateTime<Utc>, end: DateTime<Utc>) -> u64 {
4400 let millis = (end - start).num_milliseconds();
4401 if millis.is_negative() {
4402 0
4403 } else {
4404 u64::try_from(millis).unwrap_or(u64::MAX)
4405 }
4406 }
4407
4408 fn write_json_atomic<T: Serialize>(path: &Path, value: &T) -> Result<()> {
4409 if let Some(parent) = path.parent() {
4410 fs::create_dir_all(parent)
4411 .with_context(|| format!("Failed to create directory {}", parent.display()))?;
4412 }
4413 let payload = serde_json::to_string_pretty(value)?;
4414 codewhale_util::utils::write_atomic(path, payload.as_bytes())
4415 .with_context(|| format!("Failed to write {}", path.display()))
4416 }
4417
4418 /// Default task manager data location (`~/.codewhale/tasks`, or legacy
4419 /// `~/.deepseek/tasks` when only the legacy directory exists).
4420 #[must_use]
4421 pub fn default_tasks_dir() -> PathBuf {
4422 for var in ["CODEWHALE_TASKS_DIR", "DEEPSEEK_TASKS_DIR"] {
4423 if let Ok(path) = std::env::var(var)
4424 && !path.trim().is_empty()
4425 {
4426 return PathBuf::from(path);
4427 }
4428 }
4429 if let Some(home) = codewhale_paths::codewhale_home_override().ok().flatten() {
4430 return home.join("tasks");
4431 }
4432 codewhale_paths::user_home()
4433 .map(|home| default_tasks_dir_for_home(&home))
4434 .unwrap_or_else(|| PathBuf::from(".codewhale").join("tasks"))
4435 }
4436
4437 fn default_tasks_dir_for_home(home: &Path) -> PathBuf {
4438 let primary = home.join(".codewhale").join("tasks");
4439 if primary.is_dir() {
4440 return primary;
4441 }
4442 let legacy = home.join(".deepseek").join("tasks");
4443 if legacy.is_dir() {
4444 return legacy;
4445 }
4446 primary
4447 }
4448
4449 /// Wait for a task to reach a terminal status (tests and API helpers).
4450 #[cfg(any(test, feature = "test-support"))]
4451 pub async fn wait_for_terminal_state(
4452 manager: &TaskManager,
4453 task_id: &str,
4454 timeout: StdDuration,
4455 ) -> Result<TaskRecord> {
4456 let deadline = std::time::Instant::now() + timeout;
4457 loop {
4458 let task = manager.get_task(task_id).await?;
4459 if task.status.is_terminal() {
4460 return Ok(task);
4461 }
4462 if std::time::Instant::now() >= deadline {
4463 bail!("Timed out waiting for task {task_id}");
4464 }
4465 sleep(StdDuration::from_millis(50)).await;
4466 }
4467 }
4468
4469 #[cfg(test)]
4470 mod tests {
4471 use super::*;
4472 use crate::test_support::{EnvVarGuard, lock_test_env};
4473 use std::fs;
4474 use std::sync::atomic::{AtomicUsize, Ordering};
4475 use tokio::time::Duration;
4476
4477 #[test]
4478 fn deny_rules_cover_only_when_every_required_rule_is_held() {
4479 let rules = |items: &[&str]| items.iter().map(ToString::to_string).collect::<Vec<_>>();
4480 assert!(deny_rules_cover(&[], &[]));
4481 assert!(!deny_rules_cover(&[], &rules(&["mcp_secret_*"])));
4482 assert!(deny_rules_cover(
4483 &rules(&["MCP_secret_*", "Bash"]),
4484 &rules(&["mcp_secret_*"])
4485 ));
4486 assert!(deny_rules_cover(
4487 &rules(&["mcp_*"]),
4488 &rules(&["mcp_secret_*", "mcp_secret_read"])
4489 ));
4490 assert!(!deny_rules_cover(
4491 &rules(&["mcp_secret_read"]),
4492 &rules(&["mcp_secret_*"])
4493 ));
4494 assert!(!deny_rules_cover(
4495 &rules(&["mcp_secret_*"]),
4496 &rules(&["mcp_*"])
4497 ));
4498 assert_eq!(
4499 normalize_deny_rules(rules(&[" a ", "", "a", "b*"])),
4500 rules(&["a", "b*"])
4501 );
4502 }
4503
4504 struct MockExecutor;
4505
4506 /// Poll until the task is claimed as `Running`, or fail at `timeout`.
4507 ///
4508 /// A worker claims the task and installs its cancel token under one state
4509 /// lock, so observing `Running` means a cancel or shutdown now reaches a
4510 /// live executor rather than a still-queued record.
4511 async fn wait_for_running(
4512 manager: &TaskManager,
4513 task_id: &str,
4514 timeout: Duration,
4515 ) -> Result<TaskRecord> {
4516 let deadline = std::time::Instant::now() + timeout;
4517 loop {
4518 let task = manager.get_task(task_id).await?;
4519 if task.status == TaskStatus::Running {
4520 return Ok(task);
4521 }
4522 if task.status.is_terminal() || std::time::Instant::now() >= deadline {
4523 bail!("task {task_id} never started running: {task:?}");
4524 }
4525 sleep(Duration::from_millis(5)).await;
4526 }
4527 }
4528
4529 fn provider_default_model_cases() -> Vec<(&'static str, Config, &'static str)> {
4530 let deepseek = {
4531 let __cw_config_init_0_0 = Some("deepseek".to_string());
4532 let __cw_config_init_0_1 = Some("deepseek-v4-flash".to_string());
4533 let mut __cw_config_init_0_value: Config = Config::default();
4534 __cw_config_init_0_value.provider = __cw_config_init_0_0;
4535 __cw_config_init_0_value.default_text_model = __cw_config_init_0_1;
4536 __cw_config_init_0_value
4537 };
4538
4539 let zai = {
4540 let __cw_config_init_1_0 = Some("zai".to_string());
4541 // Exercise provider-aware rejection of a stale DeepSeek root default.
4542 let __cw_config_init_1_1 =
4543 Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string());
4544 let mut __cw_config_init_1_value: Config = Config::default();
4545 __cw_config_init_1_value.provider = __cw_config_init_1_0;
4546 __cw_config_init_1_value.default_text_model = __cw_config_init_1_1;
4547 __cw_config_init_1_value
4548 };
4549
4550 let mut custom_providers = codewhale_runtime::config::ProvidersConfig::default();
4551 custom_providers.custom.insert(
4552 "acme".to_string(),
4553 codewhale_runtime::config::ProviderConfig {
4554 base_url: Some("http://127.0.0.1:1/v1".to_string()),
4555 model: Some("acme-coder".to_string()),
4556 kind: Some("openai-compatible".to_string()),
4557 ..codewhale_runtime::config::ProviderConfig::default()
4558 },
4559 );
4560 let custom = {
4561 let __cw_config_init_2_0 = Some("acme".to_string());
4562 let __cw_config_init_2_1 = Some(custom_providers);
4563 let mut __cw_config_init_2_value: Config = Config::default();
4564 __cw_config_init_2_value.provider = __cw_config_init_2_0;
4565 __cw_config_init_2_value.providers = __cw_config_init_2_1;
4566 __cw_config_init_2_value
4567 };
4568
4569 vec![
4570 ("deepseek", deepseek, "deepseek-v4-flash"),
4571 (
4572 "zai",
4573 zai,
4574 codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL,
4575 ),
4576 ("custom", custom, "acme-coder"),
4577 ]
4578 }
4579
4580 #[test]
4581 fn task_manager_config_uses_the_active_provider_default() {
4582 for (label, config, expected) in provider_default_model_cases() {
4583 let task_config =
4584 TaskManagerConfig::from_runtime(&config, PathBuf::from("."), None, Some(1));
4585 assert_eq!(
4586 task_config.default_model, expected,
4587 "{label} durable task default"
4588 );
4589 }
4590 }
4591
4592 #[async_trait]
4593 impl TaskExecutor for MockExecutor {
4594 async fn execute(
4595 &self,
4596 task: ExecutionTask,
4597 events: mpsc::Sender<TaskExecutionEvent>,
4598 cancel: CancellationToken,
4599 ) -> TaskExecutionResult {
4600 let _ = events
4601 .send(TaskExecutionEvent::Status {
4602 message: format!("running {}", task.id),
4603 })
4604 .await;
4605 let _ = events
4606 .send(TaskExecutionEvent::ThreadLinked {
4607 thread_id: "thr_test".to_string(),
4608 turn_id: "turn_test".to_string(),
4609 })
4610 .await;
4611 let _ = events
4612 .send(TaskExecutionEvent::ToolStarted {
4613 id: "tool_1".to_string(),
4614 name: "read_file".to_string(),
4615 input: serde_json::json!({ "path": "README.md" }),
4616 })
4617 .await;
4618 sleep(Duration::from_millis(50)).await;
4619 if cancel.is_cancelled() {
4620 return TaskExecutionResult {
4621 status: TaskStatus::Canceled,
4622 result_text: None,
4623 error: None,
4624 terminal_reason: TaskTerminalReason::Canceled,
4625 };
4626 }
4627 let _ = events
4628 .send(TaskExecutionEvent::ToolCompleted {
4629 id: "tool_1".to_string(),
4630 name: "read_file".to_string(),
4631 success: true,
4632 output: "read ok".to_string(),
4633 metadata: Some(serde_json::json!({
4634 "duration_ms": 10,
4635 "task_updates": {
4636 "checklist": {
4637 "items": [
4638 { "id": 1, "content": "read fixture", "status": "in_progress" }
4639 ],
4640 "completion_pct": 0,
4641 "in_progress_id": 1,
4642 "updated_at": null
4643 }
4644 }
4645 })),
4646 })
4647 .await;
4648 TaskExecutionResult {
4649 status: TaskStatus::Completed,
4650 result_text: Some("done".to_string()),
4651 error: None,
4652 terminal_reason: TaskTerminalReason::Completed,
4653 }
4654 }
4655 }
4656
4657 fn test_config(root: PathBuf) -> TaskManagerConfig {
4658 TaskManagerConfig {
4659 default_workspace: root.join("workspace"),
4660 data_dir: root,
4661 worker_count: 1,
4662 default_model: "deepseek-v4-flash".to_string(),
4663 default_mode: "agent".to_string(),
4664 allow_shell: false,
4665 trust_mode: false,
4666 execution_limits: TaskExecutionLimits::default(),
4667 human_waits_answerable: false,
4668 }
4669 }
4670
4671 fn short_test_config(root: PathBuf) -> TaskManagerConfig {
4672 TaskManagerConfig {
4673 execution_limits: TaskExecutionLimits::short_for_tests(),
4674 ..test_config(root)
4675 }
4676 }
4677
4678 fn wall_timeout_test_config(root: PathBuf) -> TaskManagerConfig {
4679 let mut config = short_test_config(root);
4680 config.execution_limits.idle_progress = config
4681 .execution_limits
4682 .wall_time
4683 .saturating_add(config.execution_limits.cancel_grace);
4684 config
4685 }
4686
4687 /// The fixture owns the queue timestamp; model an already settled file
4688 /// directly instead of sleeping for the filesystem's coarse-mtime window.
4689 async fn settle_queue_fixture(manager: &TaskManager) -> Result<()> {
4690 let _transaction = manager.lock_store().await?;
4691 fs::OpenOptions::new()
4692 .write(true)
4693 .open(&manager.queue_path)?
4694 .set_modified(std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(946_684_800))?;
4695 Ok(())
4696 }
4697
4698 async fn inspect_settled_workers(manager: &TaskManager) -> Result<()> {
4699 // This deadline only detects a stuck worker. Success requires a reply
4700 // from every worker, including the result of its scheduling decision.
4701 let schedules =
4702 tokio::time::timeout(Duration::from_secs(10), manager.inspect_workers()).await??;
4703 assert_eq!(
4704 schedules.len(),
4705 manager.cfg.worker_count.clamp(1, MAX_WORKERS)
4706 );
4707 for schedule in schedules {
4708 assert!(schedule.seen.is_some(), "worker must finish an empty claim");
4709 assert!(
4710 schedule.next_claim.is_none(),
4711 "settled queue must not schedule a reload"
4712 );
4713 }
4714 Ok(())
4715 }
4716
4717 /// Re-enter the constructor's worker-readiness boundary after the initial
4718 /// state load, without racing the initial transaction or a wall-clock sleep.
4719 async fn stop_idle_workers_for_initialization_fixture(manager: &TaskManager) {
4720 let workers = std::mem::take(&mut *manager.workers.lock().await);
4721 for worker in workers {
4722 worker.join.abort();
4723 let _ = worker.join.await;
4724 }
4725 assert!(!manager.cancel_token.is_cancelled());
4726 }
4727
4728 #[tokio::test]
4729 async fn initial_worker_contention_acknowledges_retry_and_recovers() -> Result<()> {
4730 let root = tempfile::tempdir()?;
4731 let (started, mut executions) = mpsc::unbounded_channel();
4732 let manager = TaskManager::start_with_executor(
4733 test_config(root.path().to_path_buf()),
4734 Arc::new(ControlledExecutor { started }),
4735 )
4736 .await?;
4737 stop_idle_workers_for_initialization_fixture(&manager).await;
4738 let held =
4739 RuntimeProcessOwnerLock::try_acquire_file(&root.path().join("task-store.lock"), true)?
4740 .context("fixture must own the task store before the first worker claim")?;
4741 let schedules =
4742 tokio::time::timeout(Duration::from_secs(10), manager.initialize_workers(1)).await??;
4743 assert_eq!(schedules.len(), 1);
4744 assert!(
4745 schedules[0].next_claim.is_some(),
4746 "contention must schedule a retry"
4747 );
4748 assert!(
4749 !manager.cancel_token.is_cancelled(),
4750 "startup must retain the retrying worker"
4751 );
4752 drop(held);
4753
4754 let task = manager
4755 .add_task(NewTaskRequest::from_prompt(
4756 "recover after startup contention",
4757 ))
4758 .await?;
4759 let (id, finish) = tokio::time::timeout(Duration::from_secs(10), executions.recv())
4760 .await?
4761 .context("retrying worker must execute work after the lock is released")?;
4762 assert_eq!(id, task.id);
4763 finish
4764 .send(())
4765 .map_err(|_| anyhow!("executor stopped before release"))?;
4766 tokio::time::timeout(Duration::from_secs(10), manager.inspect_workers()).await??;
4767 assert_eq!(
4768 manager.get_task(&task.id).await?.status,
4769 TaskStatus::Completed
4770 );
4771 manager.shutdown_and_wait().await?;
4772 Ok(())
4773 }
4774
4775 #[tokio::test]
4776 async fn initial_worker_corrupt_store_is_not_acknowledged_as_ready() -> Result<()> {
4777 let root = tempfile::tempdir()?;
4778 let manager = TaskManager::start_with_executor(
4779 test_config(root.path().to_path_buf()),
4780 Arc::new(MockExecutor),
4781 )
4782 .await?;
4783 stop_idle_workers_for_initialization_fixture(&manager).await;
4784 {
4785 let _transaction = manager.lock_store().await?;
4786 fs::write(&manager.queue_path, b"invalid queue JSON")?;
4787 }
4788 let result =
4789 tokio::time::timeout(Duration::from_secs(10), manager.initialize_workers(1)).await?;
4790 let error = result
4791 .err()
4792 .context("a corrupt first claim must fail startup")?;
4793 assert!(
4794 !error.is::<TaskStoreBusy>(),
4795 "corruption must never be retry readiness"
4796 );
4797 assert!(format!("{error:#}").contains("queue"));
4798 assert!(manager.cancel_token.is_cancelled());
4799 manager.shutdown_and_wait().await?;
4800 Ok(())
4801 }
4802
4803 #[tokio::test]
4804 async fn inspection_replies_cover_every_worker_and_survive_caller_cancellation() -> Result<()> {
4805 let root = tempfile::tempdir()?;
4806 let manager = TaskManager::start_with_executor(
4807 TaskManagerConfig {
4808 worker_count: 3,
4809 ..test_config(root.path().to_path_buf())
4810 },
4811 Arc::new(MockExecutor),
4812 )
4813 .await?;
4814 // One constructor load and an acknowledged initial claim per worker.
4815 // A reply from one fast worker cannot stand in for the other two.
4816 assert!(manager.store_loads.load(Ordering::Relaxed) >= 4);
4817 settle_queue_fixture(&manager).await?;
4818 inspect_settled_workers(&manager).await?;
4819
4820 let sender = manager.workers.lock().await[0].inspect.clone();
4821 let (reply, received) = oneshot::channel();
4822 sender.send(reply).await?;
4823 drop(received);
4824 // The abandoned reply must not stop the worker or strand the next
4825 // caller. FIFO delivery makes this receipt follow the abandoned one.
4826 inspect_settled_workers(&manager).await?;
4827 manager.shutdown_and_wait().await?;
4828 assert!(manager.inspect_workers().await.is_err());
4829 let (reply, received) = oneshot::channel();
4830 assert!(sender.send(reply).await.is_err());
4831 assert!(received.await.is_err());
4832 Ok(())
4833 }
4834
4835 #[tokio::test]
4836 async fn inspection_never_reports_a_failed_store_as_settled_and_can_recover() -> Result<()> {
4837 let root = tempfile::tempdir()?;
4838 let manager = TaskManager::start_with_executor(
4839 test_config(root.path().to_path_buf()),
4840 Arc::new(MockExecutor),
4841 )
4842 .await?;
4843 let queue = fs::read(&manager.queue_path)?;
4844 {
4845 let _transaction = manager.lock_store().await?;
4846 fs::write(&manager.queue_path, b"invalid queue JSON")?;
4847 }
4848 let inspected =
4849 tokio::time::timeout(Duration::from_secs(10), manager.inspect_workers()).await?;
4850 // If the normal timer already observed the failure, this inspection
4851 // reports its retry state. Otherwise the failed claim replies Err.
4852 // Neither outcome is an acknowledgement of settled storage.
4853 match inspected {
4854 Err(error) => assert!(format!("{error:#}").contains("queue")),
4855 Ok(schedules) => {
4856 assert_eq!(schedules.len(), 1);
4857 assert!(schedules[0].next_claim.is_some());
4858 }
4859 }
4860 {
4861 let _transaction = manager.lock_store().await?;
4862 fs::write(&manager.queue_path, queue)?;
4863 }
4864 settle_queue_fixture(&manager).await?;
4865 inspect_settled_workers(&manager).await?;
4866 manager.shutdown_and_wait().await?;
4867 Ok(())
4868 }
4869
4870 /// Execution starts and ends at messages controlled by the caller, so
4871 /// worker-boundary tests never infer either transition from elapsed time.
4872 struct ControlledExecutor {
4873 started: mpsc::UnboundedSender<(String, oneshot::Sender<()>)>,
4874 }
4875
4876 #[async_trait]
4877 impl TaskExecutor for ControlledExecutor {
4878 async fn execute(
4879 &self,
4880 task: ExecutionTask,
4881 _events: mpsc::Sender<TaskExecutionEvent>,
4882 cancel: CancellationToken,
4883 ) -> TaskExecutionResult {
4884 let (finish, finished) = oneshot::channel();
4885 if self.started.send((task.id, finish)).is_err() {
4886 return TaskExecutionResult::from_reason(TaskTerminalReason::Canceled, None);
4887 }
4888 let reason = tokio::select! {
4889 result = finished => if result.is_ok() {
4890 TaskTerminalReason::Completed
4891 } else {
4892 TaskTerminalReason::Canceled
4893 },
4894 _ = cancel.cancelled() => TaskTerminalReason::Canceled,
4895 };
4896 TaskExecutionResult::from_reason(reason, None)
4897 }
4898 }
4899
4900 /// #6573: idle managers sharing one data dir must not reload the store
4901 /// (and take its cross-process lock) every 200ms per worker.
4902 #[tokio::test]
4903 async fn idle_managers_sharing_a_store_do_not_poll_it_continuously() -> Result<()> {
4904 let root = tempfile::tempdir()?;
4905 let config = || TaskManagerConfig {
4906 worker_count: 2,
4907 ..test_config(root.path().to_path_buf())
4908 };
4909 let (started, mut executions) = mpsc::unbounded_channel();
4910 let first = TaskManager::start_with_executor_in_scope(
4911 config(),
4912 Arc::new(ControlledExecutor { started }),
4913 "first",
4914 )
4915 .await?;
4916 let second =
4917 TaskManager::start_with_executor_in_scope(config(), Arc::new(MockExecutor), "second")
4918 .await?;
4919 settle_queue_fixture(&first).await?;
4920 for manager in [&first, &second] {
4921 inspect_settled_workers(manager).await?;
4922 manager.store_loads.store(0, Ordering::Relaxed);
4923 }
4924
4925 // Each reply proves the real worker evaluated the unchanged queue.
4926 // The schedule assertion also rejects a future fallback reload now,
4927 // without hoping a two-second observation window catches it firing.
4928 for _ in 0..10 {
4929 inspect_settled_workers(&first).await?;
4930 inspect_settled_workers(&second).await?;
4931 }
4932 let loads =
4933 first.store_loads.load(Ordering::Relaxed) + second.store_loads.load(Ordering::Relaxed);
4934 assert_eq!(
4935 loads, 0,
4936 "acknowledged idle inspections must not reload the store"
4937 );
4938
4939 // No inspection request triggers this claim: admission's normal Notify
4940 // must wake a worker. Its started message establishes that boundary.
4941 let task = first
4942 .add_task(NewTaskRequest::from_prompt("wake an idle worker"))
4943 .await?;
4944 let (id, finish) = tokio::time::timeout(Duration::from_secs(10), executions.recv())
4945 .await?
4946 .context("executor stopped before acknowledging start")?;
4947 assert_eq!(id, task.id);
4948 finish
4949 .send(())
4950 .map_err(|_| anyhow!("executor stopped before release"))?;
4951 // The busy worker handles this request only after persisting its task's
4952 // terminal result. A second worker's reply alone cannot satisfy it.
4953 tokio::time::timeout(Duration::from_secs(10), first.inspect_workers()).await??;
4954 assert_eq!(
4955 first.get_task(&task.id).await?.status,
4956 TaskStatus::Completed
4957 );
4958
4959 first.shutdown_and_wait().await?;
4960 second.shutdown_and_wait().await?;
4961 Ok(())
4962 }
4963
4964 /// #6573: the TUI task panel lists tasks every 2.5s. An unchanged store
4965 /// must be answered from memory, without the cross-process lock or a
4966 /// reload, while a write from another process is still seen.
4967 #[tokio::test]
4968 async fn repeated_listing_of_an_unchanged_store_does_not_reload_it() -> Result<()> {
4969 let root = tempfile::tempdir()?;
4970 let lister = TaskManager::start_with_executor_in_scope(
4971 test_config(root.path().to_path_buf()),
4972 Arc::new(MockExecutor),
4973 "lister",
4974 )
4975 .await?;
4976 let writer = TaskManager::start_with_executor_in_scope(
4977 test_config(root.path().to_path_buf()),
4978 Arc::new(MockExecutor),
4979 "writer",
4980 )
4981 .await?;
4982 let first = writer
4983 .add_task(NewTaskRequest::from_prompt("first"))
4984 .await?;
4985 wait_for_terminal_state(&writer, &first.id, Duration::from_secs(2)).await?;
4986 // Let the store's mtimes settle so a snapshot can be trusted.
4987 sleep(READ_SNAPSHOT_SETTLE + Duration::from_millis(300)).await;
4988 assert_eq!(lister.list_tasks(None).await?.len(), 1);
4989
4990 lister.store_loads.store(0, Ordering::Relaxed);
4991 for _ in 0..20 {
4992 assert_eq!(lister.list_tasks(None).await?.len(), 1);
4993 assert_eq!(lister.counts().await?.completed, 1);
4994 }
4995 let loads = lister.store_loads.load(Ordering::Relaxed);
4996 // Only the idle worker's fallback poll may reload in this window.
4997 assert!(
4998 loads <= 1,
4999 "40 read-only calls on an unchanged store reloaded it {loads} times"
5000 );
5001
5002 let second = writer
5003 .add_task(NewTaskRequest::from_prompt("second"))
5004 .await?;
5005 assert!(
5006 lister
5007 .list_tasks(None)
5008 .await?
5009 .iter()
5010 .any(|task| task.id == second.id),
5011 "a write from another process must invalidate the read snapshot"
5012 );
5013
5014 lister.shutdown_and_wait().await?;
5015 writer.shutdown_and_wait().await?;
5016 Ok(())
5017 }
5018
5019 /// #6573: a task running in one process rewrites its record on every
5020 /// persisted event. Those writes must not make idle workers in another
5021 /// process reload the shared store on every tick.
5022 #[tokio::test]
5023 async fn running_task_flushes_do_not_wake_idle_workers_elsewhere() -> Result<()> {
5024 let root = tempfile::tempdir()?;
5025 let (started, mut executions) = mpsc::unbounded_channel();
5026 let busy = TaskManager::start_with_executor_in_scope(
5027 test_config(root.path().to_path_buf()),
5028 Arc::new(ControlledExecutor { started }),
5029 "busy",
5030 )
5031 .await?;
5032 let task = busy
5033 .add_task(NewTaskRequest::from_prompt("stream status"))
5034 .await?;
5035 let (id, finish) = tokio::time::timeout(Duration::from_secs(10), executions.recv())
5036 .await?
5037 .context("executor stopped before acknowledging start")?;
5038 assert_eq!(id, task.id);
5039
5040 let idle = TaskManager::start_with_executor_in_scope(
5041 TaskManagerConfig {
5042 worker_count: 2,
5043 ..test_config(root.path().to_path_buf())
5044 },
5045 Arc::new(MockExecutor),
5046 "idle",
5047 )
5048 .await?;
5049 settle_queue_fixture(&idle).await?;
5050 inspect_settled_workers(&idle).await?;
5051 idle.store_loads.store(0, Ordering::Relaxed);
5052
5053 for chunk in 0..10 {
5054 // Await the production persistence operation, then acknowledge
5055 // every idle worker's inspection of the resulting store. Sending
5056 // an executor event alone would not prove its write had finished.
5057 let outcome = busy
5058 .apply_execution_event(
5059 &task.id,
5060 TaskExecutionEvent::Status {
5061 message: format!("step {chunk}"),
5062 },
5063 )
5064 .await?;
5065 assert!(outcome.persisted);
5066 inspect_settled_workers(&idle).await?;
5067 }
5068 let persisted = busy.read_bound_task(&task.id)?.context("persisted task")?;
5069 assert_eq!(persisted.status, TaskStatus::Running);
5070 assert_eq!(persisted.timeline.last().unwrap().summary, "step 9");
5071 assert_eq!(
5072 idle.store_loads.load(Ordering::Relaxed),
5073 0,
5074 "acknowledged task-record writes must not cause idle queue reloads"
5075 );
5076
5077 finish
5078 .send(())
5079 .map_err(|_| anyhow!("executor stopped before release"))?;
5080 tokio::time::timeout(Duration::from_secs(10), busy.inspect_workers()).await??;
5081 assert_eq!(busy.get_task(&task.id).await?.status, TaskStatus::Completed);
5082 busy.shutdown_and_wait().await?;
5083 idle.shutdown_and_wait().await?;
5084 Ok(())
5085 }
5086
5087 #[test]
5088 fn claim_schedule_backs_off_after_failures_and_retries_on_queue_change() {
5089 let fingerprint = |len| StoreFingerprint(Some((std::time::SystemTime::UNIX_EPOCH, len, 1)));
5090 let start = Instant::now();
5091 let mut schedule = ClaimSchedule::new(start);
5092 assert!(schedule.should_claim(&fingerprint(1), start, false));
5093
5094 // Consecutive failures double the retry delay up to the ceiling.
5095 let mut now = start;
5096 let mut delays = Vec::new();
5097 for _ in 0..8 {
5098 let delay = schedule.claim_failed(fingerprint(1), now);
5099 delays.push(delay.as_millis());
5100 assert!(!schedule.should_claim(&fingerprint(1), now + delay / 2, false));
5101 now += delay;
5102 assert!(schedule.should_claim(&fingerprint(1), now, false));
5103 }
5104 assert_eq!(delays, [200, 400, 800, 1600, 3200, 6400, 8000, 8000]);
5105
5106 // During a backoff, a queue change or an in-process wakeup retries
5107 // at once.
5108 let delay = schedule.claim_failed(fingerprint(1), now);
5109 assert_eq!(delay, STORE_BUSY_BACKOFF_MAX);
5110 assert!(schedule.should_claim(&fingerprint(2), now, false));
5111 assert!(schedule.should_claim(&fingerprint(1), now, true));
5112
5113 // An empty claim on a settled queue resets backoff without scheduling
5114 // another scan, however long the worker stays idle.
5115 schedule.found_nothing(
5116 fingerprint(2),
5117 now,
5118 std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(60),
5119 );
5120 assert!(!schedule.should_claim(&fingerprint(2), now, false));
5121 assert!(!schedule.should_claim(&fingerprint(2), now + Duration::from_secs(86_400), false));
5122 assert_eq!(
5123 schedule.claim_failed(fingerprint(2), now),
5124 STORE_REFRESH_INTERVAL
5125 );
5126 }
5127
5128 #[test]
5129 fn claim_schedule_retries_unknown_or_recent_queue_metadata() {
5130 let now = Instant::now();
5131 let wall_now = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(60);
5132 for fingerprint in [
5133 StoreFingerprint(None),
5134 StoreFingerprint(Some((wall_now, 1, 1))),
5135 ] {
5136 let mut schedule = ClaimSchedule::new(now);
5137 schedule.found_nothing(fingerprint.clone(), now, wall_now);
5138 assert!(!schedule.should_claim(&fingerprint, now, false));
5139 assert!(schedule.should_claim(&fingerprint, now + STORE_IDLE_POLL_INTERVAL, false));
5140 }
5141 }
5142
5143 #[tokio::test]
5144 async fn settled_idle_workers_notice_external_queue_writes_without_notify() -> Result<()> {
5145 let root = tempfile::tempdir()?;
5146 let (started, mut executions) = mpsc::unbounded_channel();
5147 let manager = TaskManager::start_with_executor(
5148 TaskManagerConfig {
5149 worker_count: 2,
5150 ..test_config(root.path().to_path_buf())
5151 },
5152 Arc::new(ControlledExecutor { started }),
5153 )
5154 .await?;
5155 settle_queue_fixture(&manager).await?;
5156 inspect_settled_workers(&manager).await?;
5157
5158 let mut task = sample_task_record();
5159 task.status = TaskStatus::Queued;
5160 task.started_at = None;
5161 let mut second = task.clone();
5162 second.id = "task_0123456789abcdee".into();
5163 {
5164 // Simulate another process's durable admission, under the real
5165 // cross-process transaction lock. No local state or Notify changes.
5166 let _transaction = manager.lock_store().await?;
5167 manager.persist_task_locked(&task)?;
5168 manager.persist_task_locked(&second)?;
5169 manager.persist_queue_locked(&VecDeque::from([task.id.clone(), second.id.clone()]))?;
5170 }
5171 let mut started_ids = Vec::new();
5172 for _ in 0..2 {
5173 // No local Notify or inspection request drives these claims. Wait
5174 // for executor messages proving the normal external-write path ran.
5175 let (id, finish) = tokio::time::timeout(Duration::from_secs(10), executions.recv())
5176 .await?
5177 .context("external task was not acknowledged")?;
5178 started_ids.push(id);
5179 finish
5180 .send(())
5181 .map_err(|_| anyhow!("executor stopped before release"))?;
5182 }
5183 started_ids.sort();
5184 let mut expected_ids = vec![task.id.clone(), second.id.clone()];
5185 expected_ids.sort();
5186 assert_eq!(started_ids, expected_ids);
5187 tokio::time::timeout(Duration::from_secs(10), manager.inspect_workers()).await??;
5188 for id in [&task.id, &second.id] {
5189 assert_eq!(manager.get_task(id).await?.status, TaskStatus::Completed);
5190 }
5191 manager.shutdown_and_wait().await?;
5192 Ok(())
5193 }
5194
5195 /// #6728: with nothing claimable, each worker rechecks the queue about once
5196 /// per STORE_SETTLED_NAP rather than every STORE_REFRESH_INTERVAL. The
5197 /// bound is an upper limit, so a slow machine only lowers the count.
5198 #[tokio::test]
5199 async fn settled_idle_workers_check_the_queue_at_the_settled_nap() -> Result<()> {
5200 let root = tempfile::tempdir()?;
5201 let workers = 2;
5202 let manager = TaskManager::start_with_executor(
5203 TaskManagerConfig {
5204 worker_count: workers,
5205 ..test_config(root.path().to_path_buf())
5206 },
5207 Arc::new(MockExecutor),
5208 )
5209 .await?;
5210 settle_queue_fixture(&manager).await?;
5211 inspect_settled_workers(&manager).await?;
5212 manager.fingerprint_reads.store(0, Ordering::Relaxed);
5213 manager.store_loads.store(0, Ordering::Relaxed);
5214
5215 let started = Instant::now();
5216 sleep(Duration::from_secs(3)).await;
5217 let reads = manager.fingerprint_reads.load(Ordering::Relaxed);
5218 let loads = manager.store_loads.load(Ordering::Relaxed);
5219 let window = started.elapsed();
5220 let ticks = (window.as_millis() / STORE_SETTLED_NAP.as_millis()) as usize + 1;
5221 assert!(
5222 reads <= workers * ticks,
5223 "{workers} idle workers read the queue fingerprint {reads} times in {window:?}; \
5224 expected at most {}",
5225 workers * ticks
5226 );
5227 assert_eq!(loads, 0, "idle workers reloaded a settled store");
5228 manager.shutdown_and_wait().await?;
5229 Ok(())
5230 }
5231
5232 #[test]
5233 fn claim_schedule_naps_long_only_when_nothing_is_claimable() {
5234 let now = Instant::now();
5235 let wall_now = std::time::SystemTime::UNIX_EPOCH + Duration::from_secs(10);
5236 let settled = StoreFingerprint(Some((std::time::SystemTime::UNIX_EPOCH, 1, 1)));
5237 let mut schedule = ClaimSchedule::new(now);
5238 // A fresh schedule has a claim pending.
5239 assert_eq!(schedule.nap(), STORE_REFRESH_INTERVAL);
5240 schedule.found_nothing(settled.clone(), now, wall_now);
5241 assert_eq!(schedule.nap(), STORE_SETTLED_NAP);
5242 // A failed claim keeps the short tick so a queue change is seen early.
5243 schedule.claim_failed(settled.clone(), now);
5244 assert_eq!(schedule.nap(), STORE_REFRESH_INTERVAL);
5245 // Recent or missing metadata retries on a deadline, so it stays short.
5246 schedule.found_nothing(StoreFingerprint(None), now, wall_now);
5247 assert_eq!(schedule.nap(), STORE_REFRESH_INTERVAL);
5248 schedule.claimed_task(now);
5249 assert_eq!(schedule.nap(), STORE_REFRESH_INTERVAL);
5250 }
5251
5252 /// #6573: a busy store names the holder; an unreadable record falls back
5253 /// to the bare message without failing.
5254 #[test]
5255 fn busy_store_error_names_the_lock_holder_when_known() -> Result<()> {
5256 let root = tempfile::tempdir()?;
5257 let path = root.path().join("task-store.lock");
5258 let mut holder =
5259 RuntimeProcessOwnerLock::try_acquire_file(&path, true)?.context("first acquire")?;
5260 holder.record_holder();
5261 assert!(RuntimeProcessOwnerLock::try_acquire_file(&path, true)?.is_none());
5262
5263 let error = store_busy_error(&path);
5264 assert!(
5265 error.is::<TaskStoreBusy>(),
5266 "holder diagnostics must retain typed contention"
5267 );
5268 let message = error.to_string();
5269 assert!(
5270 message.contains(&format!("held by pid {}", std::process::id())),
5271 "{message}"
5272 );
5273
5274 // Releasing clears the record, so a later error cannot name a stale pid.
5275 drop(holder);
5276 assert_eq!(
5277 store_busy_error(&path).to_string(),
5278 "Task store is busy; state is unavailable"
5279 );
5280 // Garbage and a missing file also fall back.
5281 fs::write(&path, "pid=oops since_ms=\n")?;
5282 assert!(RuntimeProcessOwnerLock::read_holder(&path).is_none());
5283 fs::remove_file(&path)?;
5284 assert!(RuntimeProcessOwnerLock::read_holder(&path).is_none());
5285 Ok(())
5286 }
5287
5288 #[tokio::test]
5289 async fn running_task_observes_durable_cancel_without_a_queue_change() -> Result<()> {
5290 let root = tempfile::tempdir()?;
5291 let manager = TaskManager::start_with_executor(
5292 test_config(root.path().to_path_buf()),
5293 Arc::new(CooperativeIdleCancelExecutor),
5294 )
5295 .await?;
5296 let task = manager
5297 .add_task(NewTaskRequest::from_prompt("durable cancel"))
5298 .await?;
5299 wait_for_running(&manager, &task.id, Duration::from_secs(2)).await?;
5300 let queue_before = StoreFingerprint::read(&manager.queue_path);
5301 {
5302 let _transaction = manager.lock_store().await?;
5303 let mut task = manager
5304 .read_bound_task(&task.id)?
5305 .context("running fixture")?;
5306 task.lifecycle_seq += 1;
5307 task.cancel_requested_seq = task.lifecycle_seq;
5308 manager.persist_task_locked(&task)?;
5309 }
5310 let done = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(2)).await?;
5311 assert_eq!(done.status, TaskStatus::Canceled);
5312 assert_eq!(StoreFingerprint::read(&manager.queue_path), queue_before);
5313 manager.shutdown_and_wait().await?;
5314 Ok(())
5315 }
5316
5317 #[tokio::test]
5318 async fn persists_and_recovers_task_records() -> Result<()> {
5319 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
5320 let manager =
5321 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
5322 .await?;
5323
5324 let task = manager
5325 .add_task(NewTaskRequest {
5326 owner_session_id: Some("session-persist".to_string()),
5327 ..NewTaskRequest::from_prompt("test persistence")
5328 })
5329 .await?;
5330 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
5331 assert_eq!(finished.status, TaskStatus::Completed);
5332 assert_eq!(finished.thread_id.as_deref(), Some("thr_test"));
5333 assert_eq!(finished.turn_id.as_deref(), Some("turn_test"));
5334 assert_eq!(finished.checklist.items.len(), 1);
5335 assert_eq!(finished.checklist.in_progress_id, Some(1));
5336 assert!(
5337 finished.lifecycle_seq >= 3,
5338 "queued, running, and terminal owner transitions must advance the sequence"
5339 );
5340
5341 manager.shutdown_and_wait().await?;
5342 drop(manager);
5343
5344 let recovered =
5345 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
5346 .await?;
5347 let loaded = recovered.get_task(&task.id).await?;
5348 assert_eq!(loaded.status, TaskStatus::Completed);
5349 assert_eq!(
5350 loaded.owner_session_id.as_deref(),
5351 Some("session-persist"),
5352 "session ownership should survive persistence and restart"
5353 );
5354 assert!(!loaded.timeline.is_empty());
5355 assert_eq!(loaded.checklist.items[0].content, "read fixture");
5356 Ok(())
5357 }
5358
5359 struct AdmissionCountingExecutor(Arc<AtomicUsize>);
5360
5361 #[async_trait]
5362 impl TaskExecutor for AdmissionCountingExecutor {
5363 async fn execute(
5364 &self,
5365 _task: ExecutionTask,
5366 _events: mpsc::Sender<TaskExecutionEvent>,
5367 _cancel: CancellationToken,
5368 ) -> TaskExecutionResult {
5369 self.0.fetch_add(1, Ordering::SeqCst);
5370 TaskExecutionResult {
5371 status: TaskStatus::Completed,
5372 result_text: Some("admission fixture completed".into()),
5373 error: None,
5374 terminal_reason: TaskTerminalReason::Completed,
5375 }
5376 }
5377 }
5378
5379 #[tokio::test]
5380 async fn automation_admission_persists_new_thread_origin() -> Result<()> {
5381 let root = tempfile::tempdir()?;
5382 let manager = TaskManager::start_with_executor(
5383 test_config(root.path().to_path_buf()),
5384 Arc::new(AdmissionCountingExecutor(Arc::new(AtomicUsize::new(0)))),
5385 )
5386 .await?;
5387 let ordinary_request = serde_json::from_value(json!({
5388 "prompt": "ordinary task",
5389 "thread_origin": { "kind": "automation" }
5390 }))?;
5391 let ordinary = manager.add_task(ordinary_request).await?;
5392 assert_eq!(ordinary.thread_origin, None);
5393 let request = NewTaskRequest::from_prompt("automation task");
5394 let task_id = TaskManager::new_task_id();
5395 manager
5396 .recover_task_admission(request.clone(), task_id.clone())
5397 .await?;
5398 let durable = manager
5399 .read_bound_task(&task_id)?
5400 .context("task was not persisted")?;
5401 let replayed = manager.recover_task_admission(request, task_id).await?;
5402 assert_eq!(durable.thread_origin, Some(ThreadOrigin::Automation));
5403 assert_eq!(replayed.thread_origin, durable.thread_origin);
5404
5405 let runtime = test_runtime_manager().await?;
5406 let task = ExecutionTask::from(&durable);
5407 let thread = runtime
5408 .create_thread_with_origin(task.thread_request(), task.thread_origin)
5409 .await?;
5410 assert_eq!(
5411 runtime.get_thread(&thread.id).await?.origin,
5412 Some(ThreadOrigin::Automation)
5413 );
5414 let fork = runtime.fork_thread(&thread.id).await?;
5415 assert_eq!(fork.origin, None);
5416 manager.shutdown_and_wait().await?;
5417 Ok(())
5418 }
5419
5420 #[tokio::test]
5421 async fn interrupted_task_stage_preserves_resolved_request_and_executes_once() -> Result<()> {
5422 for queue_was_written in [false, true] {
5423 let root = tempfile::tempdir()?;
5424 let tasks_dir = root.path().join("tasks");
5425 fs::create_dir_all(&tasks_dir)?;
5426 let mut staged = sample_task_record();
5427 staged.status = TaskStatus::Queued;
5428 staged.started_at = None;
5429 staged.model = "staged-model".into();
5430 staged.workspace = root.path().join("staged-workspace");
5431 fs::create_dir(&staged.workspace)?;
5432 let mut request = NewTaskRequest::from_task(&staged);
5433 request.model = None;
5434 request.workspace = None;
5435 request.mode = None;
5436 request.allow_shell = None;
5437 request.trust_mode = None;
5438 let staged_path = tasks_dir.join(format!(".{}.json.pending", staged.id));
5439 write_json_atomic(&staged_path, &staged)?;
5440 if queue_was_written {
5441 write_json_atomic(
5442 &root.path().join("queue.json"),
5443 &QueueFile {
5444 queue: vec![staged.id.clone()],
5445 },
5446 )?;
5447 }
5448 let executions = Arc::new(AtomicUsize::new(0));
5449 let mut config = test_config(root.path().to_path_buf());
5450 config.default_model = "new-default-model".into();
5451 config.default_workspace = root.path().join("new-workspace");
5452 config.default_mode = "plan".into();
5453 config.allow_shell = true;
5454 config.trust_mode = true;
5455 let manager = TaskManager::start_with_executor(
5456 config,
5457 Arc::new(AdmissionCountingExecutor(executions.clone())),
5458 )
5459 .await?;
5460 // Interrupt recovery while its admission is waiting for the queue
5461 // lock. The resolved intent must remain durable for another retry.
5462 let stage_before = fs::read(&staged_path)?;
5463 let queue_guard = manager.state.lock().await;
5464 let mut recovery =
5465 Box::pin(manager.recover_task_admission(request.clone(), staged.id.clone()));
5466 assert!(
5467 tokio::time::timeout(Duration::from_millis(25), &mut recovery)
5468 .await
5469 .is_err()
5470 );
5471 assert_eq!(
5472 fs::read(&staged_path)?,
5473 stage_before,
5474 "interrupted recovery must preserve its resolved staged intent"
5475 );
5476 assert!(manager.read_bound_task(&staged.id)?.is_none());
5477 assert_eq!(executions.load(Ordering::SeqCst), 0);
5478 drop(recovery);
5479 drop(queue_guard);
5480 let admitted = manager
5481 .recover_task_admission(request.clone(), staged.id.clone())
5482 .await?;
5483 assert_eq!(admitted.id, staged.id);
5484 assert_eq!(admitted.thread_origin, None);
5485 assert_eq!(admitted.model, staged.model);
5486 assert_eq!(admitted.workspace, staged.workspace);
5487 assert_eq!(admitted.mode, staged.mode);
5488 assert_eq!(admitted.allow_shell, staged.allow_shell);
5489 assert_eq!(admitted.trust_mode, staged.trust_mode);
5490 assert!(
5491 !staged_path.exists(),
5492 "unaccepted stage recovered through TaskManager"
5493 );
5494 let completed =
5495 wait_for_terminal_state(&manager, &admitted.id, Duration::from_secs(5)).await?;
5496 assert_eq!(completed.status, TaskStatus::Completed);
5497 assert!(
5498 completed
5499 .result_summary
5500 .as_deref()
5501 .unwrap_or_default()
5502 .contains("admission fixture completed")
5503 );
5504 assert_eq!(executions.load(Ordering::SeqCst), 1);
5505 let replay = manager
5506 .recover_task_admission(request.clone(), staged.id.clone())
5507 .await?;
5508 assert_eq!(replay.status, TaskStatus::Completed);
5509 assert_eq!(replay.id, staged.id);
5510 let canonical = tasks_dir.join(format!("{}.json", staged.id));
5511 let before = fs::read(&canonical)?;
5512 let mut mismatched = request;
5513 mismatched.prompt = "a different operation".into();
5514 let error = manager
5515 .recover_task_admission(mismatched, staged.id)
5516 .await
5517 .expect_err("mismatched replay must be rejected");
5518 assert!(error.to_string().contains("does not match"));
5519 assert_eq!(
5520 fs::read(canonical)?,
5521 before,
5522 "replay cannot rewrite accepted work"
5523 );
5524 assert_eq!(executions.load(Ordering::SeqCst), 1);
5525 manager.shutdown();
5526 }
5527 Ok(())
5528 }
5529
5530 #[tokio::test]
5531 async fn accepted_task_interrupted_by_restart_is_reconciled_without_execution() -> Result<()> {
5532 let root = tempfile::tempdir()?;
5533 let tasks_dir = root.path().join("tasks");
5534 fs::create_dir_all(&tasks_dir)?;
5535 let mut accepted = sample_task_record();
5536 accepted.execution_generation = Some(Uuid::new_v4().simple().to_string());
5537 let lease_path = execution_lease_path(
5538 root.path(),
5539 accepted.execution_scope.as_deref().unwrap(),
5540 accepted.execution_generation.as_deref().unwrap(),
5541 )?;
5542 drop(
5543 RuntimeProcessOwnerLock::try_acquire_file(&lease_path, true)?
5544 .context("fixture generation")?,
5545 );
5546 let request = NewTaskRequest::from_task(&accepted);
5547 write_json_atomic(&tasks_dir.join(format!("{}.json", accepted.id)), &accepted)?;
5548 write_json_atomic(
5549 &root.path().join("queue.json"),
5550 &QueueFile {
5551 queue: vec![accepted.id.clone()],
5552 },
5553 )?;
5554 let executions = Arc::new(AtomicUsize::new(0));
5555 let manager = TaskManager::start_with_executor(
5556 test_config(root.path().to_path_buf()),
5557 Arc::new(AdmissionCountingExecutor(executions.clone())),
5558 )
5559 .await?;
5560 let recovered = manager
5561 .recover_task_admission(request, accepted.id.clone())
5562 .await?;
5563 assert_eq!(recovered.id, accepted.id);
5564 assert_eq!(recovered.status, TaskStatus::Failed);
5565 assert!(
5566 recovered
5567 .error
5568 .as_deref()
5569 .unwrap_or_default()
5570 .contains("Interrupted by process restart")
5571 );
5572 assert_eq!(manager.list_tasks(None).await?.len(), 1);
5573 assert_eq!(
5574 executions.load(Ordering::SeqCst),
5575 0,
5576 "accepted work cannot be replayed after restart"
5577 );
5578 manager.shutdown();
5579 Ok(())
5580 }
5581
5582 #[tokio::test]
5583 async fn preallocated_task_ids_are_validated_and_collision_safe() -> Result<()> {
5584 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
5585 let manager =
5586 TaskManager::start_with_executor(test_config(root), Arc::new(MockExecutor)).await?;
5587 let request = NewTaskRequest::from_prompt("preallocated owner identity");
5588
5589 let invalid = manager
5590 .add_task_with_id(request.clone(), "task_short".to_string())
5591 .await
5592 .expect_err("invalid preallocated id");
5593 assert!(invalid.to_string().contains("task_<16hex>"), "{invalid:#}");
5594
5595 let id = "task_0123456789abcdef".to_string();
5596 let created = manager
5597 .add_task_with_id(request.clone(), id.clone())
5598 .await?;
5599 assert_eq!(created.id, id);
5600 assert_eq!(
5601 created.schema_version, CURRENT_TASK_SCHEMA_VERSION,
5602 "execution provenance requires readers that preserve the binding"
5603 );
5604 assert_eq!(created.lifecycle_seq, 1);
5605 let collision = manager
5606 .add_task_with_id(request, id)
5607 .await
5608 .expect_err("task id collision");
5609 assert!(
5610 collision.to_string().contains("already exists"),
5611 "{collision:#}"
5612 );
5613 assert_eq!(manager.list_tasks(None).await?.len(), 1);
5614 Ok(())
5615 }
5616
5617 #[tokio::test]
5618 async fn failed_queue_write_leaves_no_replayable_task_record() -> Result<()> {
5619 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
5620 let manager =
5621 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
5622 .await?;
5623 std::fs::remove_file(root.join("queue.json"))?;
5624 std::fs::create_dir(root.join("queue.json"))?;
5625
5626 let id = "task_fedcba9876543210".to_string();
5627 let error = manager
5628 .add_task_with_id(
5629 NewTaskRequest::from_prompt("must not resurrect"),
5630 id.clone(),
5631 )
5632 .await
5633 .expect_err("queue path directory must reject the atomic queue write");
5634 assert!(error.to_string().contains("queue.json"), "{error:#}");
5635 assert!(
5636 manager.list_tasks(None).await.is_err(),
5637 "unavailable storage cannot be reported as empty"
5638 );
5639 assert!(!root.join("tasks").join(format!("{id}.json")).exists());
5640 assert!(
5641 !root
5642 .join("tasks")
5643 .join(format!(".{id}.json.pending"))
5644 .exists(),
5645 "a failed queue write may leave no replayable or staged task record"
5646 );
5647 Ok(())
5648 }
5649
5650 #[tokio::test]
5651 async fn list_tasks_scopes_results_to_workspace_before_limit() -> Result<()> {
5652 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
5653 let manager =
5654 TaskManager::start_with_executor(test_config(root), Arc::new(MockExecutor)).await?;
5655
5656 manager
5657 .add_task(NewTaskRequest {
5658 prompt: "task in workspace a".to_string(),
5659 workspace: Some(PathBuf::from("/tmp/workspace-a")),
5660 ..NewTaskRequest::from_prompt("task in workspace a")
5661 })
5662 .await?;
5663 manager
5664 .add_task(NewTaskRequest {
5665 prompt: "task in workspace b".to_string(),
5666 workspace: Some(PathBuf::from("/tmp/workspace-b")),
5667 ..NewTaskRequest::from_prompt("task in workspace b")
5668 })
5669 .await?;
5670
5671 let scoped = manager
5672 .list_tasks_scoped(Some(1), Some(Path::new("/tmp/workspace-a")))
5673 .await?;
5674 assert_eq!(scoped.len(), 1);
5675 assert_eq!(scoped[0].workspace, PathBuf::from("/tmp/workspace-a"));
5676 Ok(())
5677 }
5678
5679 #[tokio::test]
5680 async fn task_controls_are_session_owned_and_legacy_records_fail_closed() -> Result<()> {
5681 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
5682 let manager =
5683 TaskManager::start_with_executor(test_config(root), Arc::new(MockExecutor)).await?;
5684
5685 let mut session_a = sample_task_record();
5686 session_a.id = "task_dead000000000001".to_string();
5687 session_a.owner_session_id = Some("session-a".to_string());
5688 session_a.status = TaskStatus::Completed;
5689 session_a.created_at = Utc::now() - chrono::Duration::seconds(3);
5690
5691 let mut session_b = sample_task_record();
5692 session_b.id = "task_dead000000000002".to_string();
5693 session_b.owner_session_id = Some("session-b".to_string());
5694 session_b.status = TaskStatus::Completed;
5695 session_b.created_at = Utc::now() - chrono::Duration::seconds(2);
5696
5697 let mut session_b_newest = sample_task_record();
5698 session_b_newest.id = "task_beef000000000002".to_string();
5699 session_b_newest.owner_session_id = Some("session-b".to_string());
5700 session_b_newest.status = TaskStatus::Completed;
5701 session_b_newest.created_at = Utc::now();
5702
5703 let mut legacy = sample_task_record();
5704 legacy.id = "task_dead000000000003".to_string();
5705 legacy.owner_session_id = None;
5706 legacy.execution_scope = None;
5707 legacy.status = TaskStatus::Completed;
5708 legacy.created_at = Utc::now() - chrono::Duration::seconds(1);
5709
5710 {
5711 let mut state = manager.state.lock().await;
5712 for record in [
5713 session_a.clone(),
5714 session_b.clone(),
5715 session_b_newest.clone(),
5716 legacy.clone(),
5717 ] {
5718 manager.persist_task_locked(&record)?;
5719 state.tasks.insert(record.id.clone(), record);
5720 }
5721 }
5722
5723 let session_b_list = manager
5724 .list_tasks_for_owner(Some(1), None, "session-b")
5725 .await?;
5726 assert_eq!(session_b_list.len(), 1);
5727 assert_eq!(session_b_list[0].id, session_b_newest.id);
5728
5729 let session_b_prefix = manager.get_task_for_owner("task_dead", "session-b").await?;
5730 assert_eq!(session_b_prefix.id, session_b.id);
5731 assert!(
5732 manager
5733 .get_task_for_owner(&session_a.id, "session-b")
5734 .await
5735 .unwrap_err()
5736 .to_string()
5737 .contains("Task not found")
5738 );
5739 assert!(
5740 manager
5741 .get_task_for_owner(&legacy.id, "session-b")
5742 .await
5743 .unwrap_err()
5744 .to_string()
5745 .contains("Task not found")
5746 );
5747 assert!(
5748 manager
5749 .get_task_for_active_runtime(&legacy.id)
5750 .await
5751 .unwrap_err()
5752 .to_string()
5753 .contains("Task not found"),
5754 "legacy ownerless active tasks must fail closed"
5755 );
5756 assert_eq!(
5757 manager.get_task_for_active_runtime(&session_a.id).await?.id,
5758 session_a.id
5759 );
5760
5761 assert!(
5762 manager
5763 .cancel_task_for_owner(&session_a.id, "session-b")
5764 .await
5765 .unwrap_err()
5766 .to_string()
5767 .contains("Task not found")
5768 );
5769 assert_eq!(
5770 manager.get_task(&session_a.id).await?.status,
5771 TaskStatus::Completed
5772 );
5773 assert!(
5774 manager
5775 .cancel_task_for_owner(&legacy.id, "session-b")
5776 .await
5777 .unwrap_err()
5778 .to_string()
5779 .contains("Task not found")
5780 );
5781
5782 let own = manager
5783 .cancel_task_for_owner(&session_b.id, "session-b")
5784 .await?;
5785 assert_eq!(own.disposition, TaskCancelDisposition::AlreadyFinished);
5786 let active_own = manager
5787 .cancel_task_for_active_runtime(&session_a.id)
5788 .await?;
5789 assert_eq!(
5790 active_own.disposition,
5791 TaskCancelDisposition::AlreadyFinished
5792 );
5793 assert_eq!(
5794 manager
5795 .get_task_for_owner(&session_a.id, "session-a")
5796 .await?
5797 .id,
5798 session_a.id,
5799 "switching A to B and back must restore A's controls"
5800 );
5801 Ok(())
5802 }
5803
5804 #[tokio::test]
5805 async fn interactive_task_controls_include_only_owned_or_same_scope_records() -> Result<()> {
5806 let root = tempfile::tempdir()?;
5807 let manager = TaskManager::start_with_executor(
5808 test_config(root.path().to_path_buf()),
5809 Arc::new(MockExecutor),
5810 )
5811 .await?;
5812 // Exercise persisted controls without a worker racing to execute the
5813 // queued fixture records. The manager retains its verified scope.
5814 manager.shutdown_and_wait().await?;
5815 let mut scheduled = sample_task_record();
5816 scheduled.id = "task_dead000000000001".to_string();
5817 scheduled.owner_session_id = None;
5818 scheduled.execution_scope = Some(manager.execution_scope().to_string());
5819 scheduled.status = TaskStatus::Queued;
5820
5821 let mut owned = scheduled.clone();
5822 owned.id = "task_beef000000000001".to_string();
5823 owned.owner_session_id = Some("session-a".to_string());
5824 owned.status = TaskStatus::Completed;
5825
5826 let mut foreign_scope = scheduled.clone();
5827 foreign_scope.id = "task_dead000000000002".to_string();
5828 foreign_scope.execution_scope = Some(test_execution_scope("other"));
5829 let mut other_session = scheduled.clone();
5830 other_session.id = "task_dead000000000003".to_string();
5831 other_session.owner_session_id = Some("session-b".to_string());
5832 let mut legacy = scheduled.clone();
5833 legacy.id = "task_dead000000000004".to_string();
5834 legacy.execution_scope = None;
5835 let hidden = [foreign_scope, other_session, legacy];
5836 {
5837 let mut state = manager.state.lock().await;
5838 for record in std::iter::once(&scheduled)
5839 .chain(std::iter::once(&owned))
5840 .chain(hidden.iter())
5841 {
5842 manager.persist_task_locked(record)?;
5843 state.tasks.insert(record.id.clone(), record.clone());
5844 }
5845 }
5846
5847 for record in [&scheduled, &owned] {
5848 assert_eq!(
5849 manager
5850 .get_task_for_interactive_session(&record.id, "session-a")
5851 .await?
5852 .id,
5853 record.id
5854 );
5855 }
5856 // Hidden records sharing this prefix must not make it ambiguous.
5857 assert_eq!(
5858 manager
5859 .get_task_for_interactive_session("task_dead", "session-a")
5860 .await?
5861 .id,
5862 scheduled.id
5863 );
5864 let ambiguous = manager
5865 .get_task_for_interactive_session("task_", "session-a")
5866 .await
5867 .unwrap_err();
5868 assert!(ambiguous.to_string().contains("matches 2 tasks"));
5869 for record in &hidden {
5870 assert!(
5871 manager
5872 .get_task_for_interactive_session(&record.id, "session-a")
5873 .await
5874 .unwrap_err()
5875 .to_string()
5876 .contains("Task not found")
5877 );
5878 assert!(
5879 manager
5880 .cancel_task_for_interactive_session(&record.id, "session-a")
5881 .await
5882 .unwrap_err()
5883 .to_string()
5884 .contains("Task not found")
5885 );
5886 assert_eq!(
5887 manager.get_task(&record.id).await?.status,
5888 TaskStatus::Queued
5889 );
5890 }
5891 // Model and child-session APIs do not inherit the human-only access.
5892 assert!(
5893 manager
5894 .get_task_for_owner(&scheduled.id, "session-a")
5895 .await
5896 .is_err()
5897 );
5898 assert!(
5899 manager
5900 .cancel_task_for_owner(&scheduled.id, "session-a")
5901 .await
5902 .is_err()
5903 );
5904 let canceled = manager
5905 .cancel_task_for_interactive_session("task_dead", "session-a")
5906 .await?;
5907 assert_eq!(canceled.task.id, scheduled.id);
5908 assert_eq!(canceled.task.status, TaskStatus::Canceled);
5909 assert_eq!(
5910 manager.get_task(&scheduled.id).await?.status,
5911 TaskStatus::Canceled
5912 );
5913 manager.shutdown_and_wait().await?;
5914 Ok(())
5915 }
5916
5917 #[test]
5918 fn interactive_task_controls_reject_an_empty_manager_scope() {
5919 let mut record = sample_task_record();
5920 record.owner_session_id = None;
5921 record.execution_scope = Some(String::new());
5922 let id = record.id.clone();
5923 let tasks = HashMap::from([(id.clone(), record)]);
5924 assert!(resolve_task_id_visible_to_operator(&tasks, &id, "session-a", "").is_err());
5925 }
5926
5927 #[tokio::test]
5928 async fn boot_does_not_rewrite_non_recovered_task_files() -> Result<()> {
5929 // #3757 boot-persist narrowing: TaskManager::start must persist only
5930 // the reconciled queue and the running->failed recoveries — a
5931 // completed task's file must be byte-identical across a restart.
5932 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
5933 let manager =
5934 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
5935 .await?;
5936 let task = manager
5937 .add_task(NewTaskRequest::from_prompt("finish then persist"))
5938 .await?;
5939 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
5940 assert_eq!(finished.status, TaskStatus::Completed);
5941 manager.shutdown_and_wait().await?;
5942 drop(manager);
5943
5944 let task_file = root.join("tasks").join(format!("{}.json", task.id));
5945 let before = fs::read(&task_file)?;
5946
5947 let recovered =
5948 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
5949 .await?;
5950 // Give start() a beat to run its (narrowed) boot persist.
5951 sleep(Duration::from_millis(50)).await;
5952 drop(recovered);
5953
5954 let after = fs::read(&task_file)?;
5955 assert_eq!(
5956 before, after,
5957 "a completed task file must not be rewritten on boot"
5958 );
5959 Ok(())
5960 }
5961
5962 #[test]
5963 fn legacy_running_tasks_are_preserved_without_assuming_owner_death() -> Result<()> {
5964 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
5965 let tasks_dir = root.join("tasks");
5966 fs::create_dir_all(&tasks_dir)?;
5967 let queue_path = root.join("queue.json");
5968 let task_id = "task_stale_running".to_string();
5969 let started_at = Utc::now() - chrono::Duration::seconds(30);
5970 let task = TaskRecord {
5971 thread_origin: None,
5972 destination_thread_id: None,
5973 schema_version: CURRENT_TASK_SCHEMA_VERSION,
5974 id: task_id.clone(),
5975 prompt: "long-running shell work".to_string(),
5976 name: None,
5977 model: "deepseek-v4-flash".to_string(),
5978 model_provider: None,
5979 model_provider_id: None,
5980 workspace: PathBuf::from("."),
5981 mode: "agent".to_string(),
5982 allow_shell: true,
5983 trust_mode: false,
5984 auto_approve: false,
5985 permission_posture: None,
5986 status: TaskStatus::Running,
5987 created_at: started_at,
5988 started_at: Some(started_at),
5989 ended_at: None,
5990 duration_ms: None,
5991 result_summary: None,
5992 result_detail_path: None,
5993 error: None,
5994 terminal_reason: None,
5995 thread_id: Some("thr_stale".to_string()),
5996 turn_id: Some("turn_stale".to_string()),
5997 owner_session_id: Some("session-old".to_string()),
5998 execution_scope: None,
5999 execution_generation: None,
6000 cancel_requested_seq: 0,
6001 runtime_event_count: 0,
6002 lifecycle_seq: 2,
6003 checklist: TaskChecklistState::default(),
6004 gates: Vec::new(),
6005 attempts: Vec::new(),
6006 artifacts: Vec::new(),
6007 github_events: Vec::new(),
6008 tool_calls: vec![TaskToolCallSummary {
6009 id: "tool_shell".to_string(),
6010 name: "task_shell_start".to_string(),
6011 status: TaskToolStatus::Running,
6012 started_at,
6013 ended_at: None,
6014 duration_ms: None,
6015 input_summary: Some("shell: sleep 999".to_string()),
6016 output_summary: None,
6017 detail_path: None,
6018 patch_ref: None,
6019 }],
6020 timeline: vec![TaskTimelineEntry {
6021 timestamp: started_at,
6022 kind: "running".to_string(),
6023 summary: "Task started".to_string(),
6024 detail_path: None,
6025 }],
6026 disallowed_tools: Vec::new(),
6027 };
6028 fs::write(
6029 tasks_dir.join(format!("{task_id}.json")),
6030 serde_json::to_string_pretty(&task)?,
6031 )?;
6032 fs::write(
6033 &queue_path,
6034 serde_json::to_string_pretty(&QueueFile {
6035 queue: vec![task_id.clone()],
6036 })?,
6037 )?;
6038
6039 let loaded = load_state(&tasks_dir, &queue_path)?;
6040 let queue = loaded.queue;
6041 let recovered = loaded.tasks.get(&task_id).expect("task loaded");
6042
6043 assert!(queue.is_empty(), "stale running task must not be requeued");
6044 assert_eq!(recovered.status, TaskStatus::Running);
6045 assert!(recovered.ended_at.is_none());
6046 assert!(recovered.error.is_none());
6047 assert_eq!(recovered.tool_calls[0].status, TaskToolStatus::Running);
6048 assert!(!TaskSummary::from(recovered).execution_binding_known);
6049 assert_eq!(
6050 fs::read(tasks_dir.join(format!("{task_id}.json")))?,
6051 serde_json::to_string_pretty(&task)?.as_bytes()
6052 );
6053 Ok(())
6054 }
6055
6056 #[tokio::test]
6057 async fn default_workspace_updates_for_future_tasks() -> Result<()> {
6058 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6059 let new_workspace = crate::test_support::test_scratch_dir("deepseek-workspace");
6060 let manager =
6061 TaskManager::start_with_executor(test_config(root), Arc::new(MockExecutor)).await?;
6062
6063 manager.set_default_workspace(new_workspace.clone()).await;
6064 let task = manager
6065 .add_task(NewTaskRequest::from_prompt("test workspace default"))
6066 .await?;
6067
6068 assert_eq!(manager.default_workspace().await, new_workspace);
6069 assert_eq!(task.workspace, new_workspace);
6070 Ok(())
6071 }
6072
6073 #[tokio::test]
6074 async fn record_tool_metadata_updates_explicit_task() -> Result<()> {
6075 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6076 let manager =
6077 TaskManager::start_with_executor(test_config(root), Arc::new(MockExecutor)).await?;
6078
6079 let task = manager
6080 .add_task(NewTaskRequest::from_prompt("test metadata"))
6081 .await?;
6082 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
6083 let updated = manager
6084 .record_tool_metadata(
6085 &finished.id,
6086 &serde_json::json!({
6087 "task_updates": {
6088 "gate": {
6089 "id": "gate_test",
6090 "gate": "test",
6091 "command": "cargo test -p codewhale-tui --lib",
6092 "cwd": ".",
6093 "exit_code": 0,
6094 "status": "passed",
6095 "classification": "passed",
6096 "duration_ms": 1,
6097 "summary": "ok",
6098 "log_path": null,
6099 "recorded_at": Utc::now()
6100 }
6101 }
6102 }),
6103 )
6104 .await?;
6105
6106 assert_eq!(updated.gates.len(), 1);
6107 assert_eq!(updated.gates[0].classification, "passed");
6108 Ok(())
6109 }
6110
6111 #[tokio::test]
6112 async fn write_task_artifact_rejects_traversal_task_id() -> Result<()> {
6113 let temp = tempfile::tempdir()?;
6114 let root = temp.path().join("tasks-root");
6115 let escaped = temp.path().join("escape");
6116 let manager =
6117 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
6118 .await?;
6119
6120 let err = manager
6121 .write_task_artifact("../escape", "result", "artifact body")
6122 .expect_err("traversal task ids must be rejected");
6123
6124 assert!(err.to_string().contains("single path component"));
6125 assert!(!escaped.exists(), "artifact write escaped the task root");
6126 Ok(())
6127 }
6128
6129 #[tokio::test]
6130 async fn cancel_running_task_marks_canceled() -> Result<()> {
6131 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6132 let manager = TaskManager::start_with_executor(
6133 test_config(root),
6134 Arc::new(CooperativeIdleCancelExecutor),
6135 )
6136 .await?;
6137
6138 let task = manager
6139 .add_task(NewTaskRequest::from_prompt("test cancellation"))
6140 .await?;
6141
6142 wait_for_running(&manager, &task.id, Duration::from_secs(5)).await?;
6143 let cancellation = manager.cancel_task(&task.id).await?;
6144 assert_eq!(cancellation.disposition, TaskCancelDisposition::Requested);
6145 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
6146 assert_eq!(finished.status, TaskStatus::Canceled);
6147 Ok(())
6148 }
6149
6150 #[tokio::test]
6151 async fn cancel_finished_task_returns_atomic_already_finished_outcome() -> Result<()> {
6152 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6153 let manager =
6154 TaskManager::start_with_executor(test_config(root), Arc::new(MockExecutor)).await?;
6155 let task = manager
6156 .add_task(NewTaskRequest::from_prompt("finish before cancellation"))
6157 .await?;
6158 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
6159 assert_eq!(finished.status, TaskStatus::Completed);
6160
6161 let cancellation = manager.cancel_task(&task.id).await?;
6162
6163 assert_eq!(
6164 cancellation.disposition,
6165 TaskCancelDisposition::AlreadyFinished
6166 );
6167 assert_eq!(cancellation.task.status, TaskStatus::Completed);
6168 Ok(())
6169 }
6170
6171 // GHSA-72w5-pf8h-xfp4 — regression: omitted optional fields must not
6172 // silently elevate the spawned task's privileges.
6173 #[tokio::test]
6174 async fn add_task_without_optional_fields_does_not_grant_shell_or_auto_approve() -> Result<()> {
6175 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6176 let manager =
6177 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
6178 .await?;
6179
6180 let req = NewTaskRequest {
6181 destination_thread_id: None,
6182 prompt: "fix TODOs and write a README".to_string(),
6183 name: None,
6184 model: None,
6185 model_provider: None,
6186 model_provider_id: None,
6187 workspace: None,
6188 mode: None,
6189 allow_shell: None,
6190 trust_mode: None,
6191 auto_approve: None,
6192 permission_posture: None,
6193 owner_session_id: None,
6194 disallowed_tools: Vec::new(),
6195 };
6196 let task = manager.add_task(req).await?;
6197
6198 assert!(
6199 !task.allow_shell,
6200 "model-omitted allow_shell must default to false (no silent shell grant)"
6201 );
6202 assert!(
6203 !task.auto_approve,
6204 "model-omitted auto_approve must default to false (no silent auto-approval)"
6205 );
6206 assert!(
6207 !task.trust_mode,
6208 "model-omitted trust_mode must default to false"
6209 );
6210 Ok(())
6211 }
6212
6213 /// A task's own thread starts on the posture the request pinned, and the
6214 /// posture is what the thread's policy is derived from — the legacy
6215 /// `auto_approve` bit is only read when no posture is given.
6216 #[tokio::test]
6217 async fn add_task_pins_the_posture_its_thread_starts_on() -> Result<()> {
6218 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6219 let manager =
6220 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
6221 .await?;
6222
6223 let task = manager
6224 .add_task(NewTaskRequest {
6225 permission_posture: Some("auto_review".to_string()),
6226 ..NewTaskRequest::from_prompt("pin the posture")
6227 })
6228 .await?;
6229
6230 assert_eq!(task.permission_posture.as_deref(), Some("auto_review"));
6231 let request = ExecutionTask::from(&task).thread_request();
6232 assert_eq!(request.permission_posture.as_deref(), Some("auto_review"));
6233 // `from_prompt` asks for auto-approval; the pinned posture outranks it,
6234 // so the thread must not silently run wider than what was requested.
6235 assert_eq!(request.auto_approve, Some(true));
6236 Ok(())
6237 }
6238
6239 /// The worker's thread projection refuses these postures, so admission
6240 /// refuses them too: the request came through the Runtime API, and that
6241 /// is where the refusal belongs, not in a worker after the task was
6242 /// durably queued.
6243 #[tokio::test]
6244 async fn add_task_refuses_a_posture_the_thread_would_reject() -> Result<()> {
6245 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6246 let manager =
6247 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
6248 .await?;
6249
6250 for posture in ["sideways", "never"] {
6251 let error = manager
6252 .add_task(NewTaskRequest {
6253 permission_posture: Some(posture.to_string()),
6254 ..NewTaskRequest::from_prompt("refuse me")
6255 })
6256 .await
6257 .expect_err("a posture the thread cannot honour is refused at admission");
6258 assert!(error.to_string().contains("permission posture"), "{error}");
6259 }
6260 assert!(manager.list_tasks(None).await?.is_empty());
6261 Ok(())
6262 }
6263
6264 /// The Runtime's `POST /v1/tasks` body may omit the posture entirely: it is
6265 /// optional on the wire, and absent means "derive it from the legacy bits",
6266 /// which is what every client that predates the field sends.
6267 #[test]
6268 fn new_task_request_accepts_a_body_without_a_posture() {
6269 let request: NewTaskRequest =
6270 serde_json::from_str(r#"{"prompt":"ship it","mode":"agent"}"#).expect("wire body");
6271 assert!(request.permission_posture.is_none());
6272 assert_eq!(request.mode.as_deref(), Some("agent"));
6273 }
6274
6275 #[tokio::test]
6276 async fn rejects_newer_task_schema_on_recovery() -> Result<()> {
6277 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6278 let manager =
6279 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
6280 .await?;
6281
6282 let task = manager
6283 .add_task(NewTaskRequest::from_prompt("test schema gate"))
6284 .await?;
6285 let _ = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
6286 manager.shutdown_and_wait().await?;
6287 drop(manager);
6288
6289 let task_path = root.join("tasks").join(format!("{}.json", task.id));
6290 let mut value: serde_json::Value = serde_json::from_str(&fs::read_to_string(&task_path)?)?;
6291 value["schema_version"] = serde_json::json!(999);
6292 fs::write(&task_path, serde_json::to_string_pretty(&value)?)?;
6293
6294 match TaskManager::start_with_executor(test_config(root), Arc::new(MockExecutor)).await {
6295 Ok(_) => panic!("manager should reject newer task schema"),
6296 Err(err) => assert!(err.to_string().contains("newer than supported")),
6297 }
6298 Ok(())
6299 }
6300
6301 #[test]
6302 fn default_tasks_dir_falls_back_to_legacy_deepseek_tasks() {
6303 let temp_home = tempfile::tempdir().unwrap();
6304 let home = temp_home.path();
6305 let legacy_tasks = home.join(".deepseek").join("tasks");
6306 std::fs::create_dir_all(&legacy_tasks).unwrap();
6307
6308 assert_eq!(default_tasks_dir_for_home(home), legacy_tasks);
6309 }
6310
6311 #[test]
6312 fn default_tasks_dir_prefers_existing_codewhale_tasks() {
6313 let temp_home = tempfile::tempdir().unwrap();
6314 let home = temp_home.path();
6315 let primary_tasks = home.join(".codewhale").join("tasks");
6316 let legacy_tasks = home.join(".deepseek").join("tasks");
6317 std::fs::create_dir_all(&primary_tasks).unwrap();
6318 std::fs::create_dir_all(&legacy_tasks).unwrap();
6319
6320 assert_eq!(default_tasks_dir_for_home(home), primary_tasks);
6321 }
6322
6323 #[test]
6324 fn default_tasks_dir_falls_back_to_legacy_when_primary_is_file() {
6325 let temp_home = tempfile::tempdir().unwrap();
6326 let home = temp_home.path();
6327 let primary_tasks = home.join(".codewhale").join("tasks");
6328 let legacy_tasks = home.join(".deepseek").join("tasks");
6329 std::fs::create_dir_all(primary_tasks.parent().unwrap()).unwrap();
6330 std::fs::write(&primary_tasks, "not a directory").unwrap();
6331 std::fs::create_dir_all(&legacy_tasks).unwrap();
6332
6333 assert_eq!(default_tasks_dir_for_home(home), legacy_tasks);
6334 }
6335
6336 #[test]
6337 fn default_tasks_dir_ignores_legacy_file_for_new_installs() {
6338 let temp_home = tempfile::tempdir().unwrap();
6339 let home = temp_home.path();
6340 let primary_tasks = home.join(".codewhale").join("tasks");
6341 let legacy_tasks = home.join(".deepseek").join("tasks");
6342 std::fs::create_dir_all(legacy_tasks.parent().unwrap()).unwrap();
6343 std::fs::write(&legacy_tasks, "not a directory").unwrap();
6344
6345 assert_eq!(default_tasks_dir_for_home(home), primary_tasks);
6346 }
6347
6348 #[test]
6349 fn default_tasks_dir_uses_codewhale_tasks_for_new_installs() {
6350 let temp_home = tempfile::tempdir().unwrap();
6351 let home = temp_home.path();
6352
6353 assert_eq!(
6354 default_tasks_dir_for_home(home),
6355 home.join(".codewhale").join("tasks")
6356 );
6357 }
6358
6359 #[test]
6360 fn task_and_runtime_roots_honor_explicit_codewhale_home() {
6361 let _lock = lock_test_env();
6362 let temp_root = tempfile::tempdir().unwrap();
6363 let ambient_home = temp_root.path().join("ambient-home");
6364 let explicit_home = temp_root.path().join("explicit-home");
6365 std::fs::create_dir_all(ambient_home.join(".deepseek").join("tasks")).unwrap();
6366 let _home = EnvVarGuard::set("HOME", &ambient_home);
6367 let _userprofile = EnvVarGuard::set("USERPROFILE", &ambient_home);
6368 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &explicit_home);
6369 let _tasks_override = EnvVarGuard::remove("CODEWHALE_TASKS_DIR");
6370 let _legacy_tasks_override = EnvVarGuard::remove("DEEPSEEK_TASKS_DIR");
6371 let _runtime_override = EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
6372 let _legacy_runtime_override = EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
6373
6374 let task_root = default_tasks_dir();
6375 let task_manager =
6376 TaskManagerConfig::from_runtime(&Config::default(), PathBuf::from("."), None, None);
6377 let runtime = RuntimeThreadManagerConfig::from_task_data_dir(task_manager.data_dir.clone());
6378
6379 assert_eq!(task_root, explicit_home.join("tasks"));
6380 assert_eq!(task_manager.data_dir, task_root);
6381 assert_eq!(runtime.task_data_dir, task_root);
6382 assert_eq!(
6383 runtime.data_dir,
6384 explicit_home.join("tasks").join("runtime")
6385 );
6386 }
6387
6388 #[test]
6389 fn whitespace_codewhale_home_keeps_ambient_legacy_task_and_runtime_fallbacks() {
6390 let _lock = lock_test_env();
6391 let temp_root = tempfile::tempdir().unwrap();
6392 let ambient_home = temp_root.path().join("ambient-home");
6393 let legacy_tasks = ambient_home.join(".deepseek").join("tasks");
6394 std::fs::create_dir_all(&legacy_tasks).unwrap();
6395 let _home = EnvVarGuard::set("HOME", &ambient_home);
6396 let _userprofile = EnvVarGuard::set("USERPROFILE", &ambient_home);
6397 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", " \t ");
6398 let _tasks_override = EnvVarGuard::remove("CODEWHALE_TASKS_DIR");
6399 let _legacy_tasks_override = EnvVarGuard::remove("DEEPSEEK_TASKS_DIR");
6400 let _runtime_override = EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
6401 let _legacy_runtime_override = EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
6402
6403 let task_root = default_tasks_dir();
6404 let task_manager =
6405 TaskManagerConfig::from_runtime(&Config::default(), PathBuf::from("."), None, None);
6406 let runtime = RuntimeThreadManagerConfig::from_task_data_dir(task_manager.data_dir.clone());
6407
6408 assert_eq!(task_root, legacy_tasks);
6409 assert_eq!(task_manager.data_dir, task_root);
6410 assert_eq!(runtime.task_data_dir, task_root);
6411 assert_eq!(runtime.data_dir, task_root.join("runtime"));
6412 }
6413
6414 #[cfg(unix)]
6415 #[test]
6416 fn non_unicode_codewhale_home_is_preserved_by_task_and_runtime_roots() {
6417 use std::os::unix::ffi::OsStringExt;
6418
6419 let _lock = lock_test_env();
6420 let temp_root = tempfile::tempdir().unwrap();
6421 let explicit_home = temp_root.path().join(std::ffi::OsString::from_vec(
6422 b"codewhale-\xff-home".to_vec(),
6423 ));
6424 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &explicit_home);
6425 let _tasks_override = EnvVarGuard::remove("CODEWHALE_TASKS_DIR");
6426 let _legacy_tasks_override = EnvVarGuard::remove("DEEPSEEK_TASKS_DIR");
6427 let _runtime_override = EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
6428 let _legacy_runtime_override = EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
6429
6430 let task_root = default_tasks_dir();
6431 let task_manager =
6432 TaskManagerConfig::from_runtime(&Config::default(), PathBuf::from("."), None, None);
6433 let runtime = RuntimeThreadManagerConfig::from_task_data_dir(task_manager.data_dir.clone());
6434
6435 assert_eq!(task_root, explicit_home.join("tasks"));
6436 assert_eq!(task_manager.data_dir, task_root);
6437 assert_eq!(runtime.task_data_dir, task_root);
6438 assert_eq!(
6439 runtime.data_dir,
6440 explicit_home.join("tasks").join("runtime")
6441 );
6442 }
6443
6444 struct DeafHangExecutor;
6445
6446 #[async_trait]
6447 impl TaskExecutor for DeafHangExecutor {
6448 async fn execute(
6449 &self,
6450 _task: ExecutionTask,
6451 _events: mpsc::Sender<TaskExecutionEvent>,
6452 _cancel: CancellationToken,
6453 ) -> TaskExecutionResult {
6454 std::future::pending().await
6455 }
6456 }
6457
6458 struct PartialThenHangExecutor;
6459
6460 #[async_trait]
6461 impl TaskExecutor for PartialThenHangExecutor {
6462 async fn execute(
6463 &self,
6464 _task: ExecutionTask,
6465 events: mpsc::Sender<TaskExecutionEvent>,
6466 _cancel: CancellationToken,
6467 ) -> TaskExecutionResult {
6468 let _ = events
6469 .send(TaskExecutionEvent::MessageDelta {
6470 content: "partial ".to_string(),
6471 })
6472 .await;
6473 let _ = events
6474 .send(TaskExecutionEvent::MessageDelta {
6475 content: "result".to_string(),
6476 })
6477 .await;
6478 std::future::pending().await
6479 }
6480 }
6481
6482 struct PollCountingHangExecutor {
6483 polls: Arc<AtomicUsize>,
6484 }
6485
6486 #[async_trait]
6487 impl TaskExecutor for PollCountingHangExecutor {
6488 async fn execute(
6489 &self,
6490 _task: ExecutionTask,
6491 _events: mpsc::Sender<TaskExecutionEvent>,
6492 _cancel: CancellationToken,
6493 ) -> TaskExecutionResult {
6494 std::future::poll_fn(|_| {
6495 self.polls.fetch_add(1, Ordering::Relaxed);
6496 std::task::Poll::Pending
6497 })
6498 .await
6499 }
6500 }
6501
6502 struct HeartbeatExecutor;
6503
6504 #[async_trait]
6505 impl TaskExecutor for HeartbeatExecutor {
6506 async fn execute(
6507 &self,
6508 _task: ExecutionTask,
6509 events: mpsc::Sender<TaskExecutionEvent>,
6510 _cancel: CancellationToken,
6511 ) -> TaskExecutionResult {
6512 loop {
6513 let _ = events
6514 .send(TaskExecutionEvent::Status {
6515 message: "heartbeat".to_string(),
6516 })
6517 .await;
6518 sleep(Duration::from_millis(10)).await;
6519 }
6520 }
6521 }
6522
6523 struct ProgressHeartbeatExecutor;
6524
6525 #[async_trait]
6526 impl TaskExecutor for ProgressHeartbeatExecutor {
6527 async fn execute(
6528 &self,
6529 _task: ExecutionTask,
6530 events: mpsc::Sender<TaskExecutionEvent>,
6531 _cancel: CancellationToken,
6532 ) -> TaskExecutionResult {
6533 loop {
6534 let _ = events
6535 .send(TaskExecutionEvent::MessageDelta {
6536 content: "working".to_string(),
6537 })
6538 .await;
6539 sleep(Duration::from_millis(10)).await;
6540 }
6541 }
6542 }
6543
6544 struct CooperativeIdleCancelExecutor;
6545
6546 #[async_trait]
6547 impl TaskExecutor for CooperativeIdleCancelExecutor {
6548 async fn execute(
6549 &self,
6550 _task: ExecutionTask,
6551 _events: mpsc::Sender<TaskExecutionEvent>,
6552 cancel: CancellationToken,
6553 ) -> TaskExecutionResult {
6554 cancel.cancelled().await;
6555 TaskExecutionResult::from_reason(TaskTerminalReason::Canceled, None)
6556 }
6557 }
6558
6559 struct CooperativeProgressCancelExecutor;
6560
6561 #[async_trait]
6562 impl TaskExecutor for CooperativeProgressCancelExecutor {
6563 async fn execute(
6564 &self,
6565 _task: ExecutionTask,
6566 events: mpsc::Sender<TaskExecutionEvent>,
6567 cancel: CancellationToken,
6568 ) -> TaskExecutionResult {
6569 loop {
6570 tokio::select! {
6571 _ = cancel.cancelled() => {
6572 return TaskExecutionResult::from_reason(
6573 TaskTerminalReason::Canceled,
6574 None,
6575 );
6576 }
6577 _ = sleep(Duration::from_millis(10)) => {
6578 let _ = events
6579 .send(TaskExecutionEvent::MessageDelta {
6580 content: "working".to_string(),
6581 })
6582 .await;
6583 }
6584 }
6585 }
6586 }
6587 }
6588
6589 struct PromptRouterExecutor;
6590
6591 #[async_trait]
6592 impl TaskExecutor for PromptRouterExecutor {
6593 async fn execute(
6594 &self,
6595 task: ExecutionTask,
6596 events: mpsc::Sender<TaskExecutionEvent>,
6597 _cancel: CancellationToken,
6598 ) -> TaskExecutionResult {
6599 if task.prompt.starts_with("hang ") {
6600 std::future::pending().await
6601 } else {
6602 // The follow-up task must complete without a single await
6603 // point: `run_task` polls the executor future before its
6604 // guard can observe the (test-shortened) idle/wall budgets,
6605 // so an await-free future always finishes first and an
6606 // interrupt can never be recorded against it. The previous
6607 // MockExecutor delegation (`send(...).await` x4 plus a 50 ms
6608 // sleep) left windows where CI scheduler/storage stalls of
6609 // >=150 ms tripped the idle watchdog mid-flight; the executor
6610 // then observed the cancellation and returned `Canceled`,
6611 // which `preserve_timeout_reason` rewrote into the timeout
6612 // reason -> `Failed` (issue #5898). `try_send` keeps the
6613 // released worker's event pipeline exercised without
6614 // suspending this future.
6615 let _ = events.try_send(TaskExecutionEvent::Status {
6616 message: format!("running after forced release {}", task.id),
6617 });
6618 TaskExecutionResult {
6619 status: TaskStatus::Completed,
6620 result_text: Some("done after hang".to_string()),
6621 error: None,
6622 terminal_reason: TaskTerminalReason::Completed,
6623 }
6624 }
6625 }
6626 }
6627
6628 struct FloodExecutor;
6629
6630 #[async_trait]
6631 impl TaskExecutor for FloodExecutor {
6632 async fn execute(
6633 &self,
6634 _task: ExecutionTask,
6635 events: mpsc::Sender<TaskExecutionEvent>,
6636 _cancel: CancellationToken,
6637 ) -> TaskExecutionResult {
6638 for i in 0..400 {
6639 // Mirror the runtime path: each raw event is followed by its
6640 // derived message delta. Alternating the two non-urgent stream
6641 // kinds prevents timeline coalescing without turning this
6642 // storage-bound test into hundreds of synchronous fsyncs.
6643 let _ = events
6644 .send(TaskExecutionEvent::RuntimeEvent {
6645 seq: i,
6646 event: "item.delta".to_string(),
6647 summary: format!("tick {i}"),
6648 })
6649 .await;
6650 let _ = events
6651 .send(TaskExecutionEvent::MessageDelta {
6652 content: format!("chunk {i}"),
6653 })
6654 .await;
6655 }
6656 TaskExecutionResult {
6657 status: TaskStatus::Completed,
6658 result_text: Some("flooded".to_string()),
6659 error: None,
6660 terminal_reason: TaskTerminalReason::Completed,
6661 }
6662 }
6663 }
6664
6665 struct CompleteAfterCancelExecutor;
6666
6667 #[async_trait]
6668 impl TaskExecutor for CompleteAfterCancelExecutor {
6669 async fn execute(
6670 &self,
6671 _task: ExecutionTask,
6672 _events: mpsc::Sender<TaskExecutionEvent>,
6673 cancel: CancellationToken,
6674 ) -> TaskExecutionResult {
6675 cancel.cancelled().await;
6676 TaskExecutionResult {
6677 status: TaskStatus::Completed,
6678 result_text: Some("late complete".to_string()),
6679 error: None,
6680 terminal_reason: TaskTerminalReason::Completed,
6681 }
6682 }
6683 }
6684
6685 fn sample_task_record() -> TaskRecord {
6686 TaskRecord {
6687 thread_origin: None,
6688 destination_thread_id: None,
6689 schema_version: CURRENT_TASK_SCHEMA_VERSION,
6690 id: "task_0123456789abcdef".to_string(),
6691 prompt: "bound timeline".to_string(),
6692 name: None,
6693 model: "deepseek-v4-flash".to_string(),
6694 model_provider: None,
6695 model_provider_id: None,
6696 workspace: PathBuf::from("."),
6697 mode: "agent".to_string(),
6698 allow_shell: false,
6699 trust_mode: false,
6700 auto_approve: false,
6701 permission_posture: None,
6702 status: TaskStatus::Running,
6703 created_at: Utc::now(),
6704 started_at: Some(Utc::now()),
6705 ended_at: None,
6706 duration_ms: None,
6707 result_summary: None,
6708 result_detail_path: None,
6709 error: None,
6710 terminal_reason: None,
6711 thread_id: None,
6712 turn_id: None,
6713 owner_session_id: None,
6714 execution_scope: Some(test_execution_scope("test")),
6715 execution_generation: None,
6716 cancel_requested_seq: 0,
6717 runtime_event_count: 0,
6718 lifecycle_seq: 2,
6719 checklist: TaskChecklistState::default(),
6720 gates: Vec::new(),
6721 attempts: Vec::new(),
6722 artifacts: Vec::new(),
6723 github_events: Vec::new(),
6724 tool_calls: Vec::new(),
6725 timeline: Vec::new(),
6726 disallowed_tools: Vec::new(),
6727 }
6728 }
6729
6730 /// Records persisted before `auto_approve` existed must load as not
6731 /// auto-approved, and the thread request they build must say so.
6732 #[test]
6733 fn task_record_missing_auto_approve_loads_fail_closed() {
6734 let mut record = sample_task_record();
6735 record.auto_approve = true;
6736 let mut value = serde_json::to_value(&record).expect("serialize");
6737 assert_eq!(value["auto_approve"], serde_json::json!(true));
6738 value
6739 .as_object_mut()
6740 .expect("object")
6741 .remove("auto_approve");
6742 let loaded: TaskRecord = serde_json::from_value(value).expect("legacy record loads");
6743 assert!(!loaded.auto_approve);
6744 assert_eq!(
6745 ExecutionTask::from(&loaded).thread_request().auto_approve,
6746 Some(false)
6747 );
6748 assert_eq!(
6749 ExecutionTask::from(&loaded).turn_request().auto_approve,
6750 Some(false)
6751 );
6752 }
6753
6754 #[test]
6755 fn execution_guard_idle_does_not_reset_without_progress() {
6756 let start = Instant::now();
6757 let limits = TaskExecutionLimits::short_for_tests();
6758 let guard = ExecutionGuard::new(limits, start);
6759 match guard.evaluate(start + limits.idle_progress, false, false) {
6760 GuardAction::Interrupt { reason } => {
6761 assert_eq!(reason, TaskTerminalReason::IdleTimeout);
6762 }
6763 other => panic!("expected idle interrupt, got {other:?}"),
6764 }
6765 }
6766
6767 #[test]
6768 fn execution_guard_reports_the_limit_that_expired_first_when_both_elapsed() {
6769 let start = Instant::now();
6770 let limits = TaskExecutionLimits::short_for_tests();
6771 let guard = ExecutionGuard::new(limits, start);
6772 // A starved watchdog that first ticks after both budgets ran out must
6773 // still report the idle limit, which expired first.
6774 match guard.evaluate(
6775 start + limits.wall_time + limits.idle_progress,
6776 false,
6777 false,
6778 ) {
6779 GuardAction::Interrupt { reason } => {
6780 assert_eq!(reason, TaskTerminalReason::IdleTimeout);
6781 }
6782 other => panic!("expected idle interrupt, got {other:?}"),
6783 }
6784
6785 // Late progress pushes the idle deadline past the wall deadline, so
6786 // the same starved tick reports the wall limit instead.
6787 let mut guard = ExecutionGuard::new(limits, start);
6788 guard.note_progress(start + limits.wall_time - Duration::from_millis(1));
6789 match guard.evaluate(
6790 start + limits.wall_time + limits.idle_progress,
6791 false,
6792 false,
6793 ) {
6794 GuardAction::Interrupt { reason } => {
6795 assert_eq!(reason, TaskTerminalReason::WallTimeout);
6796 }
6797 other => panic!("expected wall interrupt, got {other:?}"),
6798 }
6799 }
6800
6801 #[test]
6802 fn execution_guard_progress_refreshes_idle_until_wall_timeout() {
6803 let start = Instant::now();
6804 let limits = TaskExecutionLimits::short_for_tests();
6805 let mut guard = ExecutionGuard::new(limits, start);
6806 let progressed = start + (limits.idle_progress / 2);
6807 guard.note_progress(progressed);
6808 match guard.evaluate(progressed + (limits.idle_progress / 2), false, false) {
6809 GuardAction::Run { .. } => {}
6810 other => panic!("progress should keep idle from firing, got {other:?}"),
6811 }
6812 // Progress keeps arriving, so the idle deadline never expires before
6813 // the wall deadline does.
6814 guard.note_progress(start + limits.wall_time - (limits.idle_progress / 2));
6815 match guard.evaluate(start + limits.wall_time, false, false) {
6816 GuardAction::Interrupt { reason } => {
6817 assert_eq!(reason, TaskTerminalReason::WallTimeout);
6818 }
6819 other => panic!("expected wall interrupt, got {other:?}"),
6820 }
6821 }
6822
6823 #[test]
6824 fn execution_guard_cancel_grace_terminalizes_stuck_work() {
6825 let start = Instant::now();
6826 let limits = TaskExecutionLimits::short_for_tests();
6827 let mut guard = ExecutionGuard::new(limits, start);
6828 match guard.evaluate(start, true, false) {
6829 GuardAction::Interrupt { reason } => {
6830 assert_eq!(reason, TaskTerminalReason::Canceled);
6831 guard.note_interrupt(start, reason);
6832 }
6833 other => panic!("expected cancel interrupt, got {other:?}"),
6834 }
6835 match guard.evaluate(start + limits.cancel_grace, true, false) {
6836 GuardAction::Terminalize { reason } => {
6837 assert_eq!(reason, TaskTerminalReason::CancelTimeout);
6838 }
6839 other => panic!("expected cancel timeout, got {other:?}"),
6840 }
6841 }
6842
6843 #[test]
6844 fn consecutive_message_deltas_coalesce_on_the_timeline() {
6845 let mut task = sample_task_record();
6846 for i in 0..50 {
6847 push_timeline_entry(
6848 &mut task,
6849 TaskTimelineEntry {
6850 timestamp: Utc::now(),
6851 kind: "message".to_string(),
6852 summary: format!("chunk {i}"),
6853 detail_path: None,
6854 },
6855 );
6856 }
6857 assert_eq!(
6858 task.timeline
6859 .iter()
6860 .filter(|entry| entry.kind == "message")
6861 .count(),
6862 1
6863 );
6864 assert_eq!(
6865 task.timeline.last().map(|e| e.summary.as_str()),
6866 Some("chunk 49")
6867 );
6868 }
6869
6870 #[test]
6871 fn timeline_trim_bounds_growth_and_keeps_a_head() {
6872 let mut task = sample_task_record();
6873 for i in 0..400 {
6874 push_timeline_entry(
6875 &mut task,
6876 TaskTimelineEntry {
6877 timestamp: Utc::now(),
6878 kind: "status".to_string(),
6879 summary: format!("tick {i}"),
6880 detail_path: None,
6881 },
6882 );
6883 }
6884 assert!(task.timeline.len() <= TIMELINE_ENTRY_LIMIT);
6885 assert_eq!(task.timeline[0].summary, "tick 0");
6886 assert!(
6887 task.timeline.iter().any(|entry| entry.kind == "omitted"),
6888 "bounded timeline should record omitted history: {:?}",
6889 task.timeline
6890 .iter()
6891 .map(|e| e.kind.as_str())
6892 .collect::<Vec<_>>()
6893 );
6894 }
6895
6896 #[tokio::test]
6897 async fn never_terminalizing_execution_fails_with_idle_timeout() -> Result<()> {
6898 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6899 let manager =
6900 TaskManager::start_with_executor(short_test_config(root), Arc::new(DeafHangExecutor))
6901 .await?;
6902 let task = manager
6903 .add_task(NewTaskRequest::from_prompt("never finish"))
6904 .await?;
6905 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
6906 assert_eq!(finished.status, TaskStatus::Failed);
6907 assert_eq!(finished.terminal_reason.as_deref(), Some("idle_timeout"));
6908 assert!(
6909 finished
6910 .error
6911 .as_deref()
6912 .is_some_and(|err| err.contains("idle")),
6913 "idle timeout must be visible on the receipt: {finished:?}"
6914 );
6915 Ok(())
6916 }
6917
6918 #[tokio::test]
6919 async fn forced_timeout_keeps_all_partial_message_output() -> Result<()> {
6920 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6921 let manager = TaskManager::start_with_executor(
6922 short_test_config(root),
6923 Arc::new(PartialThenHangExecutor),
6924 )
6925 .await?;
6926 let task = manager
6927 .add_task(NewTaskRequest::from_prompt("retain partial result"))
6928 .await?;
6929 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
6930
6931 assert_eq!(finished.status, TaskStatus::Failed);
6932 assert_eq!(finished.terminal_reason.as_deref(), Some("idle_timeout"));
6933 assert_eq!(finished.result_summary.as_deref(), Some("partial result"));
6934 Ok(())
6935 }
6936
6937 #[tokio::test]
6938 async fn cooperative_cancel_after_idle_timeout_keeps_timeout_reason() -> Result<()> {
6939 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6940 let manager = TaskManager::start_with_executor(
6941 short_test_config(root),
6942 Arc::new(CooperativeIdleCancelExecutor),
6943 )
6944 .await?;
6945 let task = manager
6946 .add_task(NewTaskRequest::from_prompt("cooperative idle timeout"))
6947 .await?;
6948 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
6949 assert_eq!(finished.status, TaskStatus::Failed);
6950 assert_eq!(finished.terminal_reason.as_deref(), Some("idle_timeout"));
6951 assert!(
6952 finished
6953 .error
6954 .as_deref()
6955 .is_some_and(|error| error.contains("idle")),
6956 "cooperative cancellation must retain the timeout receipt: {finished:?}"
6957 );
6958 Ok(())
6959 }
6960
6961 #[tokio::test]
6962 async fn heartbeat_status_does_not_refresh_idle_timeout() -> Result<()> {
6963 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6964 let manager =
6965 TaskManager::start_with_executor(short_test_config(root), Arc::new(HeartbeatExecutor))
6966 .await?;
6967 let task = manager
6968 .add_task(NewTaskRequest::from_prompt("heartbeat only"))
6969 .await?;
6970 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
6971 assert_eq!(finished.status, TaskStatus::Failed);
6972 assert_eq!(finished.terminal_reason.as_deref(), Some("idle_timeout"));
6973 Ok(())
6974 }
6975
6976 #[tokio::test]
6977 async fn active_progress_keeps_idle_alive_until_wall_timeout() -> Result<()> {
6978 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6979 let mut config = short_test_config(root);
6980 config.execution_limits.idle_progress = config.execution_limits.wall_time * 3 / 4;
6981 let manager =
6982 TaskManager::start_with_executor(config, Arc::new(ProgressHeartbeatExecutor)).await?;
6983 let task = manager
6984 .add_task(NewTaskRequest::from_prompt("genuine progress"))
6985 .await?;
6986 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
6987 assert_eq!(finished.status, TaskStatus::Failed);
6988 assert_eq!(finished.terminal_reason.as_deref(), Some("wall_timeout"));
6989 Ok(())
6990 }
6991
6992 #[tokio::test]
6993 async fn cooperative_cancel_after_wall_timeout_keeps_timeout_reason() -> Result<()> {
6994 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
6995 let manager = TaskManager::start_with_executor(
6996 wall_timeout_test_config(root),
6997 Arc::new(CooperativeProgressCancelExecutor),
6998 )
6999 .await?;
7000 let task = manager
7001 .add_task(NewTaskRequest::from_prompt("cooperative wall timeout"))
7002 .await?;
7003 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
7004 assert_eq!(finished.status, TaskStatus::Failed);
7005 assert_eq!(finished.terminal_reason.as_deref(), Some("wall_timeout"));
7006 assert!(
7007 finished
7008 .error
7009 .as_deref()
7010 .is_some_and(|error| error.contains("wall-time")),
7011 "cooperative cancellation must retain the timeout receipt: {finished:?}"
7012 );
7013 Ok(())
7014 }
7015
7016 #[tokio::test]
7017 async fn shutdown_terminalizes_a_stuck_running_task() -> Result<()> {
7018 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
7019 let manager =
7020 TaskManager::start_with_executor(short_test_config(root), Arc::new(DeafHangExecutor))
7021 .await?;
7022 let task = manager
7023 .add_task(NewTaskRequest::from_prompt("stuck during shutdown"))
7024 .await?;
7025 wait_for_running(&manager, &task.id, Duration::from_secs(5)).await?;
7026 manager.shutdown();
7027 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
7028 assert_eq!(finished.status, TaskStatus::Canceled);
7029 assert_eq!(finished.terminal_reason.as_deref(), Some("shutdown"));
7030 Ok(())
7031 }
7032
7033 #[tokio::test]
7034 async fn shutdown_cancel_signal_does_not_spin_during_grace() -> Result<()> {
7035 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
7036 let polls = Arc::new(AtomicUsize::new(0));
7037 let manager = TaskManager::start_with_executor(
7038 short_test_config(root),
7039 Arc::new(PollCountingHangExecutor {
7040 polls: Arc::clone(&polls),
7041 }),
7042 )
7043 .await?;
7044 let task = manager
7045 .add_task(NewTaskRequest::from_prompt("stuck during shutdown"))
7046 .await?;
7047
7048 wait_for_running(&manager, &task.id, Duration::from_secs(5)).await?;
7049
7050 manager.shutdown();
7051 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
7052 assert_eq!(finished.terminal_reason.as_deref(), Some("shutdown"));
7053 assert!(
7054 polls.load(Ordering::Relaxed) <= 10,
7055 "already-canceled shutdown signal repeatedly repolled the executor during grace: {} polls",
7056 polls.load(Ordering::Relaxed)
7057 );
7058 Ok(())
7059 }
7060
7061 #[tokio::test]
7062 async fn forced_idle_timeout_releases_the_worker_for_later_tasks() -> Result<()> {
7063 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
7064 let manager = TaskManager::start_with_executor(
7065 short_test_config(root),
7066 Arc::new(PromptRouterExecutor),
7067 )
7068 .await?;
7069 let stuck = manager
7070 .add_task(NewTaskRequest::from_prompt("hang until idle timeout"))
7071 .await?;
7072 let finished =
7073 wait_for_terminal_state(&manager, &stuck.id, Duration::from_secs(10)).await?;
7074 assert_eq!(
7075 finished.terminal_reason.as_deref(),
7076 Some("idle_timeout"),
7077 "stuck task terminal record: {finished:?}"
7078 );
7079
7080 let next = manager
7081 .add_task(NewTaskRequest::from_prompt("run after hang"))
7082 .await?;
7083 let completed =
7084 wait_for_terminal_state(&manager, &next.id, Duration::from_secs(10)).await?;
7085 assert_eq!(
7086 completed.status,
7087 TaskStatus::Completed,
7088 "follow-up task terminal record: {completed:?}"
7089 );
7090 assert_eq!(
7091 completed.terminal_reason.as_deref(),
7092 Some("completed"),
7093 "follow-up task terminal record: {completed:?}"
7094 );
7095 Ok(())
7096 }
7097
7098 #[tokio::test]
7099 async fn cancel_then_completed_result_is_recorded_as_canceled() -> Result<()> {
7100 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
7101 let manager = TaskManager::start_with_executor(
7102 test_config(root),
7103 Arc::new(CompleteAfterCancelExecutor),
7104 )
7105 .await?;
7106 let task = manager
7107 .add_task(NewTaskRequest::from_prompt("race complete after cancel"))
7108 .await?;
7109 wait_for_running(&manager, &task.id, Duration::from_secs(5)).await?;
7110 let cancellation = manager.cancel_task(&task.id).await?;
7111 assert_eq!(cancellation.disposition, TaskCancelDisposition::Requested);
7112 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
7113 assert_eq!(finished.status, TaskStatus::Canceled);
7114 assert_eq!(finished.terminal_reason.as_deref(), Some("canceled"));
7115 Ok(())
7116 }
7117
7118 #[tokio::test]
7119 async fn long_stream_timeline_is_bounded() -> Result<()> {
7120 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
7121 let manager =
7122 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(FloodExecutor))
7123 .await?;
7124 let task = manager
7125 .add_task(NewTaskRequest::from_prompt("flood the timeline"))
7126 .await?;
7127 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
7128 assert_eq!(finished.status, TaskStatus::Completed);
7129 assert_eq!(finished.runtime_event_count, 400);
7130 assert!(
7131 finished.timeline.len() <= TIMELINE_ENTRY_LIMIT,
7132 "timeline grew to {}",
7133 finished.timeline.len()
7134 );
7135 assert!(
7136 finished
7137 .timeline
7138 .iter()
7139 .any(|entry| entry.kind == "omitted"),
7140 "long streams should drop older timeline entries: {:?}",
7141 finished
7142 .timeline
7143 .iter()
7144 .map(|e| e.kind.as_str())
7145 .collect::<Vec<_>>()
7146 );
7147
7148 let persisted_path = root.join("tasks").join(format!("{}.json", task.id));
7149 let persisted: TaskRecord = serde_json::from_slice(&fs::read(&persisted_path)?)?;
7150 assert_eq!(persisted.status, TaskStatus::Completed);
7151 assert_eq!(persisted.runtime_event_count, 400);
7152 assert!(persisted.timeline.len() <= TIMELINE_ENTRY_LIMIT);
7153 assert!(
7154 persisted
7155 .timeline
7156 .iter()
7157 .any(|entry| entry.kind == "omitted")
7158 );
7159 Ok(())
7160 }
7161
7162 async fn test_runtime_manager() -> Result<RuntimeThreadManager> {
7163 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
7164 std::fs::create_dir_all(&root)?;
7165 RuntimeThreadManager::open(
7166 Config::default(),
7167 PathBuf::from("."),
7168 RuntimeThreadManagerConfig::from_task_data_dir(root),
7169 )
7170 }
7171
7172 async fn drain_task_events(mut rx: mpsc::Receiver<TaskExecutionEvent>) {
7173 while rx.recv().await.is_some() {}
7174 }
7175
7176 struct RuntimeProjectionExecutor(Vec<(&'static str, Value)>);
7177
7178 #[async_trait]
7179 impl TaskExecutor for RuntimeProjectionExecutor {
7180 async fn execute(
7181 &self,
7182 _task: ExecutionTask,
7183 events: mpsc::Sender<TaskExecutionEvent>,
7184 cancel: CancellationToken,
7185 ) -> TaskExecutionResult {
7186 let runtime = test_runtime_manager().await.expect("fixture runtime");
7187 let thread = runtime
7188 .create_thread(CreateThreadRequest::default())
7189 .await
7190 .expect("fixture thread");
7191 for (event, payload) in &self.0 {
7192 runtime
7193 .emit_event_for_test(
7194 &thread.id,
7195 Some("turn_projection"),
7196 event,
7197 payload.clone(),
7198 )
7199 .await
7200 .expect("persist fixture runtime event");
7201 }
7202 drive_engine_turn(
7203 &runtime,
7204 &thread.id,
7205 "turn_projection",
7206 events,
7207 cancel,
7208 TaskExecutionLimits::default(),
7209 false,
7210 )
7211 .await
7212 }
7213 }
7214
7215 async fn project_runtime_task(events: Vec<(&'static str, Value)>) -> Result<TaskRecord> {
7216 let root = tempfile::tempdir()?;
7217 let manager = TaskManager::start_with_executor(
7218 test_config(root.path().to_path_buf()),
7219 Arc::new(RuntimeProjectionExecutor(events)),
7220 )
7221 .await?;
7222 let task = manager
7223 .add_task(NewTaskRequest::from_prompt("runtime projection fixture"))
7224 .await?;
7225 wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
7226 manager.shutdown_and_wait().await?;
7227 // Assert the durable task projection, not just an adapter event.
7228 let path = root.path().join("tasks").join(format!("{}.json", task.id));
7229 Ok(serde_json::from_slice(&fs::read(path)?)?)
7230 }
7231
7232 #[tokio::test]
7233 async fn runtime_task_projection_preserves_provider_ids_and_terminal_tool_statuses()
7234 -> Result<()> {
7235 let mut events = Vec::new();
7236 for (item, provider) in [
7237 ("item_a", "call_a"),
7238 ("item_b", "call_b"),
7239 ("item_c", "call_c"),
7240 ] {
7241 events.push((
7242 "item.started",
7243 json!({
7244 "item": { "id": item, "kind": "tool_call" },
7245 "tool": { "id": provider, "name": "read", "input": {} }
7246 }),
7247 ));
7248 }
7249 // Parallel same-name calls finish out of order. Success preserves
7250 // tool_result_for; errors retain tool_use_id; redaction uses tool_call_id.
7251 for (item, provider, identity_key, terminal) in [
7252 ("item_c", "call_c", "tool_use_id", "item.failed"),
7253 ("item_b", "call_b", "tool_call_id", "item.completed"),
7254 ("item_a", "call_a", "tool_result_for", "item.completed"),
7255 ] {
7256 events.push((
7257 terminal,
7258 json!({ "item": {
7259 "id": item, "kind": "tool_call", "summary": "redacted receipt",
7260 "detail": format!("result for {provider}"),
7261 "metadata": { identity_key: provider, "tool_name": "read" }
7262 }}),
7263 ));
7264 }
7265 // Old event shapes with no metadata retain their existing identity.
7266 events.extend([
7267 ("item.started", json!({ "tool": { "id": "legacy", "name": "read", "input": {} } })),
7268 ("item.completed", json!({ "item": { "id": "legacy", "kind": "tool_call", "summary": "read: ok", "detail": "ok" } })),
7269 ("turn.completed", json!({ "turn": { "status": "completed" } })),
7270 ]);
7271 let task = project_runtime_task(events).await?;
7272 assert_eq!(task.status, TaskStatus::Completed);
7273 assert_eq!(task.tool_calls.len(), 4);
7274 for (call, expected_id, expected_status) in [
7275 (&task.tool_calls[0], "call_a", TaskToolStatus::Success),
7276 (&task.tool_calls[1], "call_b", TaskToolStatus::Success),
7277 (&task.tool_calls[2], "call_c", TaskToolStatus::Failed),
7278 (&task.tool_calls[3], "legacy", TaskToolStatus::Success),
7279 ] {
7280 assert_eq!(call.id, expected_id);
7281 assert_eq!(call.status, expected_status);
7282 assert!(call.ended_at.is_some());
7283 assert!(call.duration_ms.is_some());
7284 }
7285 assert_eq!(
7286 task.tool_calls[0].output_summary.as_deref(),
7287 Some("result for call_a")
7288 );
7289 assert_eq!(
7290 task.tool_calls[2].output_summary.as_deref(),
7291 Some("result for call_c")
7292 );
7293 Ok(())
7294 }
7295
7296 #[tokio::test]
7297 async fn runtime_task_projection_uses_last_completed_message_without_delta_duplication()
7298 -> Result<()> {
7299 let commentary = "Checking fixture state. ".repeat(20);
7300 let task = project_runtime_task(vec![
7301 ("item.started", json!({ "item": { "id": "commentary", "kind": "agent_message" } })),
7302 ("item.delta", json!({ "kind": "agent_message", "delta": commentary })),
7303 ("item.completed", json!({ "item": { "id": "commentary", "kind": "agent_message", "detail": commentary } })),
7304 ("item.started", json!({ "item": { "id": "final", "kind": "agent_message" } })),
7305 ("item.delta", json!({ "kind": "agent_message", "delta": "NOTHING_" })),
7306 ("item.completed", json!({ "item": { "id": "final", "kind": "agent_message", "detail": "NOTHING_TO_REPORT" } })),
7307 ("turn.completed", json!({ "turn": { "status": "completed" } })),
7308 ]).await?;
7309 assert_eq!(task.result_summary.as_deref(), Some("NOTHING_TO_REPORT"));
7310 assert!(task.result_detail_path.is_none());
7311 assert!(
7312 task.timeline.iter().any(|entry| entry.kind == "message"
7313 && entry.summary.starts_with("Checking fixture state."))
7314 );
7315 Ok(())
7316 }
7317
7318 #[tokio::test]
7319 async fn runtime_task_projection_preserves_partial_output_only_for_unfinished_results()
7320 -> Result<()> {
7321 for (status, expected) in [
7322 ("interrupted", "partial final"),
7323 ("failed", "partial final"),
7324 ("completed", "(no textual output)"),
7325 ] {
7326 let task = project_runtime_task(vec![
7327 (
7328 "item.completed",
7329 json!({ "item": { "kind": "agent_message", "detail": "earlier commentary" } }),
7330 ),
7331 (
7332 "item.started",
7333 json!({ "item": { "kind": "agent_message" } }),
7334 ),
7335 (
7336 "item.delta",
7337 json!({ "kind": "agent_message", "delta": "partial final" }),
7338 ),
7339 ("turn.completed", json!({ "turn": { "status": status } })),
7340 ])
7341 .await?;
7342 assert_eq!(task.result_summary.as_deref(), Some(expected), "{status}");
7343 }
7344 Ok(())
7345 }
7346
7347 #[tokio::test]
7348 async fn task_with_deny_rules_refuses_a_destination_thread_that_lacks_them() -> Result<()> {
7349 let runtime = Arc::new(test_runtime_manager().await?);
7350 let open = runtime
7351 .create_thread(CreateThreadRequest::default())
7352 .await?;
7353 let mut record = sample_task_record();
7354 record.destination_thread_id = Some(open.id.clone());
7355 record.disallowed_tools = vec!["mcp_secret_*".to_string()];
7356 let (tx, rx) = mpsc::channel(64);
7357 tokio::spawn(drain_task_events(rx));
7358 let executor =
7359 EngineTaskExecutor::new(runtime, TaskExecutionLimits::short_for_tests(), false);
7360 let result = executor
7361 .execute(ExecutionTask::from(&record), tx, CancellationToken::new())
7362 .await;
7363 assert_eq!(result.status, TaskStatus::Failed);
7364 assert!(
7365 result
7366 .error
7367 .as_deref()
7368 .is_some_and(|error| error.contains("deny rules")),
7369 "{:?}",
7370 result.error
7371 );
7372 Ok(())
7373 }
7374
7375 #[tokio::test]
7376 async fn engine_turn_without_terminal_event_idle_times_out() -> Result<()> {
7377 let runtime = test_runtime_manager().await?;
7378 let thread = runtime
7379 .create_thread(CreateThreadRequest::default())
7380 .await?;
7381 let (tx, rx) = mpsc::channel(64);
7382 tokio::spawn(drain_task_events(rx));
7383 let result = drive_engine_turn(
7384 &runtime,
7385 &thread.id,
7386 "turn_missing",
7387 tx,
7388 CancellationToken::new(),
7389 TaskExecutionLimits::short_for_tests(),
7390 false,
7391 )
7392 .await;
7393 assert_eq!(result.status, TaskStatus::Failed);
7394 assert_eq!(result.terminal_reason, TaskTerminalReason::IdleTimeout);
7395 Ok(())
7396 }
7397
7398 #[tokio::test]
7399 async fn engine_turn_keeps_idle_timeout_when_runtime_interrupts_during_grace() -> Result<()> {
7400 let runtime = Arc::new(test_runtime_manager().await?);
7401 let thread = runtime
7402 .create_thread(CreateThreadRequest::default())
7403 .await?;
7404 let (tx, mut rx) = mpsc::channel(64);
7405 let runtime_for_drive = Arc::clone(&runtime);
7406 let thread_id = thread.id.clone();
7407 let drive = tokio::spawn(async move {
7408 drive_engine_turn(
7409 runtime_for_drive.as_ref(),
7410 &thread_id,
7411 "turn_timeout",
7412 tx,
7413 CancellationToken::new(),
7414 TaskExecutionLimits {
7415 wall_time: Duration::from_secs(2),
7416 idle_progress: Duration::from_millis(80),
7417 cancel_grace: Duration::from_millis(500),
7418 persist_debounce: Duration::from_millis(10),
7419 human_wait_cap: Duration::from_secs(24 * 60 * 60),
7420 },
7421 false,
7422 )
7423 .await
7424 });
7425
7426 tokio::time::timeout(Duration::from_secs(2), async {
7427 loop {
7428 match rx.recv().await {
7429 Some(TaskExecutionEvent::Status { message })
7430 if message.contains("idle deadline") =>
7431 {
7432 break;
7433 }
7434 Some(_) => {}
7435 None => panic!("engine task event stream closed before timeout interrupt"),
7436 }
7437 }
7438 })
7439 .await
7440 .context("engine did not request the idle-timeout interrupt")?;
7441
7442 runtime
7443 .emit_event_for_test(
7444 &thread.id,
7445 Some("turn_timeout"),
7446 "turn.completed",
7447 json!({ "turn": { "status": "interrupted" } }),
7448 )
7449 .await?;
7450 let result = drive.await?;
7451 assert_eq!(result.status, TaskStatus::Failed);
7452 assert_eq!(result.terminal_reason, TaskTerminalReason::IdleTimeout);
7453 Ok(())
7454 }
7455
7456 #[tokio::test]
7457 async fn engine_turn_uses_cursor_catchup_for_completed_event() -> Result<()> {
7458 let runtime = test_runtime_manager().await?;
7459 let thread = runtime
7460 .create_thread(CreateThreadRequest::default())
7461 .await?;
7462 runtime
7463 .emit_event_for_test(
7464 &thread.id,
7465 Some("turn_done"),
7466 "turn.completed",
7467 json!({ "turn": { "status": "completed" } }),
7468 )
7469 .await?;
7470 let (tx, rx) = mpsc::channel(64);
7471 tokio::spawn(drain_task_events(rx));
7472 let result = drive_engine_turn(
7473 &runtime,
7474 &thread.id,
7475 "turn_done",
7476 tx,
7477 CancellationToken::new(),
7478 TaskExecutionLimits::short_for_tests(),
7479 false,
7480 )
7481 .await;
7482 assert_eq!(result.status, TaskStatus::Completed);
7483 assert_eq!(result.terminal_reason, TaskTerminalReason::Completed);
7484 Ok(())
7485 }
7486
7487 #[tokio::test]
7488 async fn pending_approval_suspends_idle_and_timeout_denial_settles_failed() -> Result<()> {
7489 // #6118: a run that needs a tool approval must not die as a silent
7490 // idle-timeout cancel; the pending approval suspends the idle
7491 // watchdog, and the bridge's own deadline denial then settles the
7492 // run Failed with the reason recorded.
7493 let runtime = Arc::new(test_runtime_manager().await?);
7494 let thread = runtime
7495 .create_thread(CreateThreadRequest::default())
7496 .await?;
7497 let thread_id = thread.id.clone();
7498 runtime
7499 .emit_event_for_test(
7500 &thread.id,
7501 Some("turn_approval"),
7502 "approval.required",
7503 json!({
7504 "approval_id": "approval_fixture_1",
7505 "tool_call_id": "call_fixture_1",
7506 "tool_name": "shell",
7507 }),
7508 )
7509 .await?;
7510 let (tx, mut rx) = mpsc::channel(64);
7511 let runtime_for_drive = Arc::clone(&runtime);
7512 let drive = tokio::spawn(async move {
7513 drive_engine_turn(
7514 runtime_for_drive.as_ref(),
7515 &thread_id,
7516 "turn_approval",
7517 tx,
7518 CancellationToken::new(),
7519 TaskExecutionLimits {
7520 wall_time: Duration::from_secs(5),
7521 idle_progress: Duration::from_millis(120),
7522 cancel_grace: Duration::from_millis(200),
7523 persist_debounce: Duration::from_millis(10),
7524 human_wait_cap: Duration::from_secs(24 * 60 * 60),
7525 },
7526 false,
7527 )
7528 .await
7529 });
7530
7531 // Well past the idle window, the pending approval must keep the run
7532 // alive; the old behavior killed it here with no receipt.
7533 tokio::time::sleep(Duration::from_millis(400)).await;
7534 assert!(
7535 !drive.is_finished(),
7536 "a pending approval must suspend the idle watchdog (#6118)"
7537 );
7538 while let Ok(event) = rx.try_recv() {
7539 if let TaskExecutionEvent::Status { message } = event {
7540 assert!(
7541 !message.contains("idle deadline"),
7542 "no idle interrupt may fire while an approval is pending: {message}"
7543 );
7544 }
7545 }
7546
7547 // The decision window closes: the run settles Failed with the reason.
7548 runtime
7549 .emit_event_for_test(
7550 &thread.id,
7551 Some("turn_approval"),
7552 "approval.timeout",
7553 json!({ "approval_id": "approval_fixture_1", "tool_call_id": "call_fixture_1" }),
7554 )
7555 .await?;
7556 let result = tokio::time::timeout(Duration::from_secs(2), drive)
7557 .await
7558 .context("the decision-window denial must settle the run promptly")??;
7559 assert_eq!(result.status, TaskStatus::Failed);
7560 assert_eq!(result.terminal_reason, TaskTerminalReason::Failed);
7561 assert!(
7562 result
7563 .error
7564 .as_deref()
7565 .is_some_and(|error| error.contains("Tool approval was not answered")),
7566 "the run must record why it stopped, got {:?}",
7567 result.error
7568 );
7569 Ok(())
7570 }
7571
7572 #[tokio::test]
7573 async fn resolved_approval_restores_the_idle_watchdog() -> Result<()> {
7574 // #6118 counter-check: the suspension ends with the decision, so a
7575 // run that then stops making progress is idle-killed exactly as
7576 // before.
7577 let runtime = test_runtime_manager().await?;
7578 let thread = runtime
7579 .create_thread(CreateThreadRequest::default())
7580 .await?;
7581 runtime
7582 .emit_event_for_test(
7583 &thread.id,
7584 Some("turn_approval_resolved"),
7585 "approval.required",
7586 json!({
7587 "approval_id": "approval_fixture_2",
7588 "tool_call_id": "call_fixture_2",
7589 "tool_name": "shell",
7590 }),
7591 )
7592 .await?;
7593 runtime
7594 .emit_event_for_test(
7595 &thread.id,
7596 Some("turn_approval_resolved"),
7597 "approval.decided",
7598 json!({
7599 "approval_id": "approval_fixture_2",
7600 "tool_call_id": "call_fixture_2",
7601 "decision": "allow",
7602 }),
7603 )
7604 .await?;
7605 let (tx, rx) = mpsc::channel(64);
7606 tokio::spawn(drain_task_events(rx));
7607 let result = drive_engine_turn(
7608 &runtime,
7609 &thread.id,
7610 "turn_approval_resolved",
7611 tx,
7612 CancellationToken::new(),
7613 TaskExecutionLimits::short_for_tests(),
7614 false,
7615 )
7616 .await;
7617 assert_eq!(result.status, TaskStatus::Failed);
7618 assert_eq!(result.terminal_reason, TaskTerminalReason::IdleTimeout);
7619 Ok(())
7620 }
7621
7622 #[test]
7623 fn human_wait_timeout_reason_is_serialized_and_fails_the_task() {
7624 // The durable record stores `terminal_reason` as this string, so
7625 // receipts and status views must keep naming the fail-safe cap.
7626 assert_eq!(
7627 TaskTerminalReason::HumanWaitTimeout.as_str(),
7628 "human_wait_timeout"
7629 );
7630 assert_eq!(
7631 TaskTerminalReason::HumanWaitTimeout.task_status(),
7632 TaskStatus::Failed
7633 );
7634 assert!(
7635 TaskTerminalReason::HumanWaitTimeout
7636 .receipt_message()
7637 .contains("fail-safe cap")
7638 );
7639 }
7640
7641 /// Limits with generous wall/idle budgets so a test exercises exactly
7642 /// one guard mechanism (the human-wait arithmetic) in isolation.
7643 fn execution_guard_limits(human_wait_cap: Duration) -> TaskExecutionLimits {
7644 TaskExecutionLimits {
7645 wall_time: Duration::from_secs(30),
7646 idle_progress: Duration::from_secs(30),
7647 cancel_grace: Duration::from_millis(50),
7648 persist_debounce: Duration::from_millis(10),
7649 human_wait_cap,
7650 }
7651 }
7652
7653 #[test]
7654 fn execution_guard_parked_backoff_grows_past_the_catchup_poll() {
7655 // Two seconds parked: the doubling has run twice, so the parked
7656 // wait must exceed the 200ms catch-up cadence the backoff exists
7657 // to escape. Asserted as a literal so drifting EVENT_CATCHUP_POLL
7658 // off its documented 200ms fails here instead of silently
7659 // tracking the constant.
7660 let start = Instant::now();
7661 let mut guard = ExecutionGuard::new(
7662 execution_guard_limits(Duration::from_secs(24 * 60 * 60)),
7663 start,
7664 );
7665 guard.begin_human_wait(start);
7666 match guard.evaluate(start + Duration::from_secs(2), false, false) {
7667 GuardAction::Run { wait } => {
7668 assert_eq!(wait, Duration::from_millis(800));
7669 }
7670 other => panic!("expected a parked run, got {other:?}"),
7671 }
7672 }
7673
7674 #[test]
7675 fn execution_guard_parked_backoff_caps_at_two_seconds() {
7676 // Asserted as a literal so moving PARKED_POLL_CAP off its
7677 // documented 2s ceiling fails here instead of silently tracking
7678 // the constant.
7679 let start = Instant::now();
7680 let mut guard = ExecutionGuard::new(
7681 execution_guard_limits(Duration::from_secs(24 * 60 * 60)),
7682 start,
7683 );
7684 guard.begin_human_wait(start);
7685 match guard.evaluate(start + Duration::from_secs(3600), false, false) {
7686 GuardAction::Run { wait } => {
7687 assert_eq!(wait, Duration::from_secs(2));
7688 }
7689 other => panic!("expected a parked run, got {other:?}"),
7690 }
7691 }
7692
7693 #[test]
7694 fn execution_guard_parked_wait_respects_the_aggregate_budget() {
7695 // The parked wake must respect the aggregate budget, not just the
7696 // open window: 10s cap, 7s already closed, 2.5s parked this window
7697 // leaves 500ms — not the 800ms the doubling alone would suggest.
7698 let start = Instant::now();
7699 let mut guard = ExecutionGuard::new(execution_guard_limits(Duration::from_secs(10)), start);
7700 guard.begin_human_wait(start);
7701 guard.end_human_wait(start + Duration::from_secs(7));
7702 guard.begin_human_wait(start + Duration::from_secs(7));
7703 match guard.evaluate(start + Duration::from_millis(9500), false, false) {
7704 GuardAction::Run { wait } => {
7705 assert_eq!(wait, Duration::from_millis(500));
7706 }
7707 other => panic!("expected a parked run, got {other:?}"),
7708 }
7709 }
7710
7711 #[test]
7712 fn execution_guard_spent_aggregate_cap_terminalizes_between_windows() {
7713 // Closed windows alone reach the cap with no window open: the
7714 // guard must terminalize between prompts even though wall and idle
7715 // have barely elapsed. This pins the aggregate arm that only sees
7716 // `human_wait_total`; the open-window arm is pinned by
7717 // human_wait_fail_safe_cap_releases_the_worker.
7718 let start = Instant::now();
7719 let mut guard =
7720 ExecutionGuard::new(execution_guard_limits(Duration::from_millis(200)), start);
7721 guard.begin_human_wait(start);
7722 guard.end_human_wait(start + Duration::from_millis(200));
7723 match guard.evaluate(start + Duration::from_millis(250), false, false) {
7724 GuardAction::Interrupt { reason } => {
7725 assert_eq!(reason, TaskTerminalReason::HumanWaitTimeout);
7726 }
7727 other => panic!("expected the aggregate cap to fire, got {other:?}"),
7728 }
7729 }
7730
7731 #[test]
7732 fn execution_guard_cancel_outranks_a_spent_aggregate_cap() {
7733 // The cap check sits after the shutdown/cancel classification: a
7734 // canceled task must never be mislabeled human_wait_timeout.
7735 let start = Instant::now();
7736 let mut guard =
7737 ExecutionGuard::new(execution_guard_limits(Duration::from_millis(200)), start);
7738 guard.begin_human_wait(start);
7739 guard.end_human_wait(start + Duration::from_millis(200));
7740 match guard.evaluate(start + Duration::from_millis(250), true, false) {
7741 GuardAction::Interrupt { reason } => {
7742 assert_eq!(reason, TaskTerminalReason::Canceled);
7743 }
7744 other => panic!("cancel must outrank the spent cap, got {other:?}"),
7745 }
7746 }
7747
7748 #[test]
7749 fn execution_guard_shutdown_outranks_a_spent_aggregate_cap() {
7750 let start = Instant::now();
7751 let mut guard =
7752 ExecutionGuard::new(execution_guard_limits(Duration::from_millis(200)), start);
7753 guard.begin_human_wait(start);
7754 guard.end_human_wait(start + Duration::from_millis(200));
7755 match guard.evaluate(start + Duration::from_millis(250), false, true) {
7756 GuardAction::Interrupt { reason } => {
7757 assert_eq!(reason, TaskTerminalReason::Shutdown);
7758 }
7759 other => panic!("shutdown must outrank the spent cap, got {other:?}"),
7760 }
7761 }
7762
7763 #[test]
7764 fn execution_guard_cancel_outranks_a_spent_parked_cap() {
7765 // Twin of the aggregate outranking pins with the window still
7766 // OPEN: the parked cap arm sits after the cancel classification
7767 // too, so a canceled task parked past the cap must never be
7768 // mislabeled human_wait_timeout.
7769 let start = Instant::now();
7770 let mut guard =
7771 ExecutionGuard::new(execution_guard_limits(Duration::from_millis(200)), start);
7772 guard.begin_human_wait(start);
7773 match guard.evaluate(start + Duration::from_millis(200), true, false) {
7774 GuardAction::Interrupt { reason } => {
7775 assert_eq!(reason, TaskTerminalReason::Canceled);
7776 }
7777 other => panic!("cancel must outrank the spent parked cap, got {other:?}"),
7778 }
7779 }
7780
7781 #[test]
7782 fn execution_guard_wall_timeout_attribution_follows_the_moved_deadline() {
7783 // Wall budget mostly spent, then a human-wait window closed: the
7784 // wall deadline moves out by the window, and #5898's crossed-first
7785 // attribution must still pick the limit that expired first under
7786 // that moved scheme. Just before the moved deadline the raw clock
7787 // is already past the wall budget, yet the guard must keep running;
7788 // past it, with idle (restarted at the close) crossed too but
7789 // later, the label must be WallTimeout — not IdleTimeout, not a
7790 // quiet Run.
7791 let start = Instant::now();
7792 let limits = TaskExecutionLimits {
7793 wall_time: Duration::from_millis(400),
7794 idle_progress: Duration::from_millis(250),
7795 cancel_grace: Duration::from_millis(50),
7796 persist_debounce: Duration::from_millis(10),
7797 human_wait_cap: Duration::from_secs(24 * 60 * 60),
7798 };
7799 let mut guard = ExecutionGuard::new(limits, start);
7800 guard.note_progress(start + Duration::from_millis(300));
7801 guard.begin_human_wait(start + Duration::from_millis(300));
7802 guard.end_human_wait(start + Duration::from_millis(900));
7803 // Moved wall deadline: 400ms + 600ms window = 1000ms; idle
7804 // restarted at the close: 900ms + 250ms = 1150ms.
7805 match guard.evaluate(start + Duration::from_millis(950), false, false) {
7806 GuardAction::Run { .. } => {}
7807 other => panic!("the moved deadline must not fire before 1000ms, got {other:?}"),
7808 }
7809 match guard.evaluate(start + Duration::from_millis(1200), false, false) {
7810 GuardAction::Interrupt { reason } => {
7811 assert_eq!(reason, TaskTerminalReason::WallTimeout);
7812 }
7813 other => panic!("expected WallTimeout past the moved deadline, got {other:?}"),
7814 }
7815 }
7816
7817 #[test]
7818 fn execution_guard_human_wait_close_restarts_the_idle_budget() {
7819 // Ending a window restarts idle from zero: 100ms after the close
7820 // the guard must still run, though 1.1s have passed since start.
7821 // This composes with #6118's in-window suppression: the watchdog
7822 // is held open while the decision is pending, and this restart
7823 // covers the model's own post-decision latency.
7824 let start = Instant::now();
7825 let limits = TaskExecutionLimits {
7826 wall_time: Duration::from_millis(400),
7827 idle_progress: Duration::from_millis(150),
7828 cancel_grace: Duration::from_millis(500),
7829 persist_debounce: Duration::from_millis(10),
7830 human_wait_cap: Duration::from_secs(24 * 60 * 60),
7831 };
7832 let mut guard = ExecutionGuard::new(limits, start);
7833 guard.begin_human_wait(start);
7834 guard.end_human_wait(start + Duration::from_secs(1));
7835 match guard.evaluate(start + Duration::from_millis(1100), false, false) {
7836 GuardAction::Run { .. } => {}
7837 other => panic!("a closed window must restart idle, got {other:?}"),
7838 }
7839 }
7840
7841 #[test]
7842 fn human_wait_recorded_before_the_wall_deadline_survives_late_consumption() {
7843 let start = Instant::now();
7844 let start_wall = Utc::now();
7845 let limits = TaskExecutionLimits {
7846 wall_time: Duration::from_millis(400),
7847 idle_progress: Duration::from_secs(30),
7848 cancel_grace: Duration::from_millis(50),
7849 persist_debounce: Duration::from_millis(10),
7850 human_wait_cap: Duration::from_secs(30),
7851 };
7852 let consumed_at = start + Duration::from_millis(500);
7853 assert_eq!(
7854 journal_instant(
7855 start,
7856 start_wall,
7857 start_wall + chrono::Duration::milliseconds(100),
7858 consumed_at,
7859 ),
7860 start + Duration::from_millis(100)
7861 );
7862 assert_eq!(
7863 journal_instant(
7864 start,
7865 start_wall,
7866 start_wall - chrono::Duration::seconds(5),
7867 consumed_at,
7868 ),
7869 start
7870 );
7871 assert_eq!(
7872 journal_instant(
7873 start,
7874 start_wall,
7875 start_wall + chrono::Duration::seconds(5),
7876 consumed_at,
7877 ),
7878 consumed_at
7879 );
7880
7881 let mut guard = ExecutionGuard::new(limits, start);
7882 guard.begin_human_wait(journal_instant(
7883 start,
7884 start_wall,
7885 start_wall + chrono::Duration::milliseconds(100),
7886 consumed_at,
7887 ));
7888 match guard.evaluate(consumed_at, false, false) {
7889 GuardAction::Run { .. } => {}
7890 other => panic!(
7891 "a prompt recorded before the wall deadline must survive late consumption, got {other:?}"
7892 ),
7893 }
7894
7895 let mut late = ExecutionGuard::new(limits, start);
7896 late.begin_human_wait(journal_instant(
7897 start,
7898 start_wall,
7899 start_wall + chrono::Duration::milliseconds(450),
7900 consumed_at,
7901 ));
7902 match late.evaluate(consumed_at, false, false) {
7903 GuardAction::Interrupt { reason } => {
7904 assert_eq!(reason, TaskTerminalReason::WallTimeout);
7905 }
7906 other => panic!(
7907 "a prompt recorded after the wall deadline must still time out, got {other:?}"
7908 ),
7909 }
7910 }
7911
7912 #[test]
7913 fn from_runtime_defaults_to_unanswerable_human_waits() {
7914 // The safe default: the TUI builds its private task runtime through
7915 // `from_runtime` and must never arm the human-wait window — no host
7916 // can answer a prompt there. Only the runtime API server opts in,
7917 // via its `server_task_config`.
7918 let cfg =
7919 TaskManagerConfig::from_runtime(&Config::default(), PathBuf::from("."), None, None);
7920 assert!(
7921 !cfg.human_waits_answerable,
7922 "from_runtime must default to unanswerable human waits"
7923 );
7924 }
7925
7926 #[tokio::test]
7927 async fn human_wait_is_excluded_from_the_task_wall_clock() -> Result<()> {
7928 // The engine journals the tool item before its approval/user-input
7929 // gate, so the production shape is: tool in flight, then a prompt
7930 // opens a human-paced window. An answer submitted past the wall
7931 // budget must complete the task, exactly like the turn layer's
7932 // budget excludes the same window (TurnWallClock::begin_human_wait:
7933 // "the budget bounds what the agent spends on its own, not how
7934 // long a person takes to answer").
7935 let runtime = Arc::new(test_runtime_manager().await?);
7936 let thread = runtime
7937 .create_thread(CreateThreadRequest::default())
7938 .await?;
7939 let (tx, mut rx) = mpsc::channel(64);
7940 runtime
7941 .emit_event_for_test(
7942 &thread.id,
7943 Some("turn_human_wait"),
7944 "item.started",
7945 json!({
7946 "item": { "id": "item_human_wait", "status": "in_progress" },
7947 "tool": { "id": "call_1", "name": "request_user_input", "input": {} }
7948 }),
7949 )
7950 .await?;
7951 runtime
7952 .emit_event_for_test(
7953 &thread.id,
7954 Some("turn_human_wait"),
7955 "user_input.required",
7956 json!({ "id": "ui_1", "request": {} }),
7957 )
7958 .await?;
7959
7960 let runtime_for_drive = Arc::clone(&runtime);
7961 let thread_id = thread.id.clone();
7962 let drive = tokio::spawn(async move {
7963 drive_engine_turn(
7964 runtime_for_drive.as_ref(),
7965 &thread_id,
7966 "turn_human_wait",
7967 tx,
7968 CancellationToken::new(),
7969 TaskExecutionLimits {
7970 wall_time: Duration::from_millis(400),
7971 idle_progress: Duration::from_secs(10),
7972 cancel_grace: Duration::from_millis(500),
7973 persist_debounce: Duration::from_millis(10),
7974 human_wait_cap: Duration::from_secs(24 * 60 * 60),
7975 },
7976 true,
7977 )
7978 .await
7979 });
7980
7981 loop {
7982 let event = tokio::time::timeout(Duration::from_secs(10), rx.recv())
7983 .await
7984 .expect("the human-wait window must be published on the task event channel")
7985 .expect("the task event channel closed before the window was published");
7986 assert!(
7987 !matches!(&event, TaskExecutionEvent::Status { message }
7988 if message.contains("wall-time")),
7989 "wall-time interrupt fired while a human decision was pending"
7990 );
7991 if matches!(event, TaskExecutionEvent::HumanWaitStarted { .. }) {
7992 break;
7993 }
7994 }
7995
7996 // Far past the wall budget the decision is still pending: no
7997 // wall-time interrupt may fire while the window is open.
7998 tokio::time::sleep(Duration::from_millis(900)).await;
7999 while let Ok(event) = rx.try_recv() {
8000 assert!(
8001 !matches!(event, TaskExecutionEvent::Status { message }
8002 if message.contains("wall-time")),
8003 "wall-time interrupt fired while a human decision was pending"
8004 );
8005 }
8006
8007 // The answer arrives past the budget: the window closes, the tool
8008 // completes, and the turn completes with no wall-time anywhere.
8009 runtime
8010 .emit_event_for_test(
8011 &thread.id,
8012 Some("turn_human_wait"),
8013 "user_input.answered",
8014 json!({ "id": "ui_1" }),
8015 )
8016 .await?;
8017 runtime
8018 .emit_event_for_test(
8019 &thread.id,
8020 Some("turn_human_wait"),
8021 "item.completed",
8022 json!({ "item": { "id": "item_human_wait", "status": "completed" } }),
8023 )
8024 .await?;
8025 runtime
8026 .emit_event_for_test(
8027 &thread.id,
8028 Some("turn_human_wait"),
8029 "turn.completed",
8030 json!({ "turn": { "status": "completed" } }),
8031 )
8032 .await?;
8033 let result = drive.await?;
8034 assert_eq!(result.status, TaskStatus::Completed);
8035 assert_eq!(result.terminal_reason, TaskTerminalReason::Completed);
8036 Ok(())
8037 }
8038
8039 #[tokio::test]
8040 async fn human_wait_fail_safe_cap_releases_the_worker() -> Result<()> {
8041 // A prompt nobody will ever answer must not park the worker
8042 // forever: past the fail-safe cap the task ends with the dedicated
8043 // terminal reason even though wall and idle never elapsed. This is
8044 // the open-window cap arm; the aggregate between-windows arm is
8045 // pinned by execution_guard_spent_aggregate_cap_terminalizes_between_windows.
8046 let runtime = Arc::new(test_runtime_manager().await?);
8047 let thread = runtime
8048 .create_thread(CreateThreadRequest::default())
8049 .await?;
8050 let (tx, mut rx) = mpsc::channel(64);
8051 let runtime_for_drive = Arc::clone(&runtime);
8052 let thread_id = thread.id.clone();
8053 let drive = tokio::spawn(async move {
8054 drive_engine_turn(
8055 runtime_for_drive.as_ref(),
8056 &thread_id,
8057 "turn_unanswered",
8058 tx,
8059 CancellationToken::new(),
8060 TaskExecutionLimits {
8061 wall_time: Duration::from_secs(30),
8062 idle_progress: Duration::from_secs(30),
8063 cancel_grace: Duration::from_millis(50),
8064 persist_debounce: Duration::from_millis(10),
8065 human_wait_cap: Duration::from_millis(200),
8066 },
8067 true,
8068 )
8069 .await
8070 });
8071
8072 runtime
8073 .emit_event_for_test(
8074 &thread.id,
8075 Some("turn_unanswered"),
8076 "approval.required",
8077 json!({ "approval_id": "ap_1", "tool_call_id": "call_1", "tool_name": "exec_command" }),
8078 )
8079 .await?;
8080
8081 let result = tokio::time::timeout(Duration::from_secs(5), drive)
8082 .await
8083 .expect("the fail-safe cap must release the turn loop")?;
8084 assert_eq!(result.status, TaskStatus::Failed);
8085 assert_eq!(result.terminal_reason, TaskTerminalReason::HumanWaitTimeout);
8086 let _ = rx.try_recv();
8087 Ok(())
8088 }
8089
8090 /// Executor that opens a supervisor-side human wait for `delay` and
8091 /// only then completes — the task survives a wall budget far shorter
8092 /// than the delay if and only if the supervisor's guard honors the
8093 /// HumanWaitStarted/Ended signals.
8094 struct SupervisedHumanWaitExecutor {
8095 delay: Duration,
8096 }
8097
8098 #[async_trait]
8099 impl TaskExecutor for SupervisedHumanWaitExecutor {
8100 async fn execute(
8101 &self,
8102 _task: ExecutionTask,
8103 events: mpsc::Sender<TaskExecutionEvent>,
8104 _cancel: CancellationToken,
8105 ) -> TaskExecutionResult {
8106 let _ = events
8107 .send(TaskExecutionEvent::HumanWaitStarted { at: Utc::now() })
8108 .await;
8109 tokio::time::sleep(self.delay).await;
8110 let _ = events
8111 .send(TaskExecutionEvent::HumanWaitEnded { at: Utc::now() })
8112 .await;
8113 TaskExecutionResult {
8114 status: TaskStatus::Completed,
8115 result_text: None,
8116 error: None,
8117 terminal_reason: TaskTerminalReason::Completed,
8118 }
8119 }
8120 }
8121
8122 #[tokio::test]
8123 async fn supervisor_wall_clock_follows_human_wait_signals() -> Result<()> {
8124 let root = crate::test_support::test_scratch_dir("deepseek-task-test");
8125 let mut config = short_test_config(root);
8126 // Short config's fail-safe cap (300ms) is shorter than the wait
8127 // below; this test pins the wall exclusion, not the fail-safe.
8128 config.execution_limits.human_wait_cap = Duration::from_secs(30);
8129 let manager = TaskManager::start_with_executor(
8130 config,
8131 Arc::new(SupervisedHumanWaitExecutor {
8132 // Two seconds: far past the short wall, with enough margin
8133 // that scheduler starvation on a loaded CI runner cannot
8134 // eat the exclusion before the supervisor sees the
8135 // HumanWaitStarted signal.
8136 delay: Duration::from_secs(2),
8137 }),
8138 )
8139 .await?;
8140 let task = manager
8141 .add_task(NewTaskRequest::from_prompt("human wait past wall"))
8142 .await?;
8143 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
8144 assert_eq!(finished.status, TaskStatus::Completed);
8145 assert_eq!(finished.terminal_reason.as_deref(), Some("completed"));
8146 Ok(())
8147 }
8148
8149 #[tokio::test]
8150 async fn unanswerable_surface_keeps_the_wall_clock_running_through_a_prompt() -> Result<()> {
8151 // The unanswerable default (TUI's private task runtime has no host
8152 // that can deliver an approval or user-input decision): a prompt
8153 // there must not arm the human-wait window at all — no window
8154 // signal, wall excluded nothing — so the wall clock keeps running
8155 // and interrupts the turn at its own deadline, exactly as before
8156 // the opt-in existed.
8157 let runtime = Arc::new(test_runtime_manager().await?);
8158 let thread = runtime
8159 .create_thread(CreateThreadRequest::default())
8160 .await?;
8161 let (tx, mut rx) = mpsc::channel(64);
8162 let runtime_for_drive = Arc::clone(&runtime);
8163 let thread_id = thread.id.clone();
8164 let drive = tokio::spawn(async move {
8165 drive_engine_turn(
8166 runtime_for_drive.as_ref(),
8167 &thread_id,
8168 "turn_unanswerable",
8169 tx,
8170 CancellationToken::new(),
8171 TaskExecutionLimits {
8172 wall_time: Duration::from_millis(300),
8173 idle_progress: Duration::from_secs(30),
8174 cancel_grace: Duration::from_millis(500),
8175 persist_debounce: Duration::from_millis(10),
8176 // The fail-safe cap is the default: if the prompt were
8177 // (wrongly) treated as an answerable wait, the task
8178 // would survive the wall and end much later with
8179 // HumanWaitTimeout instead of WallTimeout.
8180 human_wait_cap: Duration::from_secs(24 * 60 * 60),
8181 },
8182 false,
8183 )
8184 .await
8185 });
8186
8187 runtime
8188 .emit_event_for_test(
8189 &thread.id,
8190 Some("turn_unanswerable"),
8191 "approval.required",
8192 json!({ "approval_id": "ap_1", "tool_call_id": "call_1", "tool_name": "exec_command" }),
8193 )
8194 .await?;
8195
8196 let result = tokio::time::timeout(Duration::from_secs(5), drive)
8197 .await
8198 .expect("the wall clock must release the worker")?;
8199 assert_eq!(result.terminal_reason, TaskTerminalReason::WallTimeout);
8200 let mut saw_window_signal = false;
8201 while let Ok(event) = rx.try_recv() {
8202 if matches!(event, TaskExecutionEvent::HumanWaitStarted { .. }) {
8203 saw_window_signal = true;
8204 }
8205 }
8206 assert!(
8207 !saw_window_signal,
8208 "an unanswerable surface must not publish a human-wait window"
8209 );
8210 Ok(())
8211 }
8212
8213 #[tokio::test]
8214 async fn chained_short_waits_still_terminate_at_the_fail_safe_cap() -> Result<()> {
8215 // Each window is well under the cap, so chaining prompts must not
8216 // park the worker forever: once the windows sum past the cap the
8217 // guard terminalizes. Which arm observes the crossing first is a
8218 // wake-timing detail this test does not pin — with these
8219 // back-to-back windows the open-window check fires mid-window
8220 // (window one's spend is already in the aggregate total); the
8221 // between-windows arm alone is pinned deterministically by
8222 // execution_guard_spent_aggregate_cap_terminalizes_between_windows.
8223 // A fresh window re-counting after the previous one closed is what
8224 // makes this test able to reach two windows at all.
8225 let runtime = Arc::new(test_runtime_manager().await?);
8226 let thread = runtime
8227 .create_thread(CreateThreadRequest::default())
8228 .await?;
8229 let (tx, _rx) = mpsc::channel(64);
8230 let runtime_for_drive = Arc::clone(&runtime);
8231 let thread_id = thread.id.clone();
8232 let drive = tokio::spawn(async move {
8233 drive_engine_turn(
8234 runtime_for_drive.as_ref(),
8235 &thread_id,
8236 "turn_chained",
8237 tx,
8238 CancellationToken::new(),
8239 TaskExecutionLimits {
8240 wall_time: Duration::from_secs(30),
8241 idle_progress: Duration::from_secs(30),
8242 cancel_grace: Duration::from_millis(50),
8243 persist_debounce: Duration::from_millis(10),
8244 // Two 120ms windows sum past this; neither alone does.
8245 human_wait_cap: Duration::from_millis(200),
8246 },
8247 true,
8248 )
8249 .await
8250 });
8251
8252 for round in 0..2 {
8253 runtime
8254 .emit_event_for_test(
8255 &thread.id,
8256 Some("turn_chained"),
8257 "user_input.required",
8258 json!({ "id": format!("ui_{round}"), "request": {} }),
8259 )
8260 .await?;
8261 tokio::time::sleep(Duration::from_millis(120)).await;
8262 runtime
8263 .emit_event_for_test(
8264 &thread.id,
8265 Some("turn_chained"),
8266 "user_input.answered",
8267 json!({ "id": format!("ui_{round}") }),
8268 )
8269 .await?;
8270 tokio::time::sleep(Duration::from_millis(50)).await;
8271 }
8272
8273 let result = tokio::time::timeout(Duration::from_secs(5), drive)
8274 .await
8275 .expect("the fail-safe cap must release the worker")?;
8276 assert_eq!(
8277 result.terminal_reason,
8278 TaskTerminalReason::HumanWaitTimeout,
8279 "chained sub-cap windows must not park the worker forever"
8280 );
8281 Ok(())
8282 }
8283
8284 #[tokio::test]
8285 async fn silent_running_tool_suppresses_idle_until_it_completes() -> Result<()> {
8286 let runtime = Arc::new(test_runtime_manager().await?);
8287 let thread = runtime
8288 .create_thread(CreateThreadRequest::default())
8289 .await?;
8290 let (tx, mut rx) = mpsc::channel(64);
8291 let runtime_for_drive = Arc::clone(&runtime);
8292 let thread_id = thread.id.clone();
8293 let drive = tokio::spawn(async move {
8294 drive_engine_turn(
8295 runtime_for_drive.as_ref(),
8296 &thread_id,
8297 "turn_silent_tool",
8298 tx,
8299 CancellationToken::new(),
8300 TaskExecutionLimits {
8301 wall_time: Duration::from_secs(5),
8302 idle_progress: Duration::from_millis(80),
8303 cancel_grace: Duration::from_millis(500),
8304 persist_debounce: Duration::from_millis(10),
8305 human_wait_cap: Duration::from_secs(24 * 60 * 60),
8306 },
8307 false,
8308 )
8309 .await
8310 });
8311
8312 // Keyed by the journal item id on the started edge; the payload also
8313 // carries the engine tool-use id under "tool" (which must NOT become
8314 // the tracking key: the terminal events only repeat "item").
8315 runtime
8316 .emit_event_for_test(
8317 &thread.id,
8318 Some("turn_silent_tool"),
8319 "item.started",
8320 json!({
8321 "item": { "id": "item_tool_silent", "status": "in_progress" },
8322 "tool": { "id": "call_build", "name": "exec_command", "input": {} }
8323 }),
8324 )
8325 .await?;
8326
8327 // A silent build produces no journal traffic for its whole window;
8328 // far past the idle deadline the watchdog must still not fire.
8329 tokio::time::sleep(Duration::from_millis(400)).await;
8330 let mut seen = Vec::new();
8331 while let Ok(event) = rx.try_recv() {
8332 seen.push(event);
8333 }
8334 assert!(
8335 !seen.iter().any(|event| matches!(
8336 event,
8337 TaskExecutionEvent::Status { message }
8338 if message.contains("idle deadline")
8339 )),
8340 "idle watchdog fired while a tool was still running"
8341 );
8342
8343 runtime
8344 .emit_event_for_test(
8345 &thread.id,
8346 Some("turn_silent_tool"),
8347 "item.completed",
8348 json!({ "item": { "id": "item_tool_silent", "status": "completed" } }),
8349 )
8350 .await?;
8351
8352 // Completion drains the set; silence afterwards must let the idle
8353 // deadline fire again (a drain bug would surface as WallTimeout).
8354 tokio::time::timeout(Duration::from_secs(2), async {
8355 loop {
8356 match rx.recv().await {
8357 Some(TaskExecutionEvent::Status { message })
8358 if message.contains("idle deadline") =>
8359 {
8360 break;
8361 }
8362 Some(_) => {}
8363 None => panic!("task event stream closed before idle deadline"),
8364 }
8365 }
8366 })
8367 .await
8368 .context("idle deadline did not fire after the tool completed")?;
8369 runtime
8370 .emit_event_for_test(
8371 &thread.id,
8372 Some("turn_silent_tool"),
8373 "turn.completed",
8374 json!({ "turn": { "status": "interrupted" } }),
8375 )
8376 .await?;
8377 let result = drive.await?;
8378 assert_eq!(result.status, TaskStatus::Failed);
8379 assert_eq!(result.terminal_reason, TaskTerminalReason::IdleTimeout);
8380 Ok(())
8381 }
8382
8383 #[tokio::test]
8384 async fn silent_running_tool_heartbeats_the_worker_watchdog() -> Result<()> {
8385 // The supervisor's guard (run_task) only sees task events, so the
8386 // steady-state suppression must also publish the in-flight window on
8387 // the event channel — otherwise the production path still idles out
8388 // even though this loop's own guard is satisfied.
8389 let runtime = Arc::new(test_runtime_manager().await?);
8390 let thread = runtime
8391 .create_thread(CreateThreadRequest::default())
8392 .await?;
8393 let (tx, mut rx) = mpsc::channel(64);
8394 let runtime_for_drive = Arc::clone(&runtime);
8395 let thread_id = thread.id.clone();
8396 let drive = tokio::spawn(async move {
8397 drive_engine_turn(
8398 runtime_for_drive.as_ref(),
8399 &thread_id,
8400 "turn_heartbeat",
8401 tx,
8402 CancellationToken::new(),
8403 TaskExecutionLimits {
8404 wall_time: Duration::from_secs(5),
8405 idle_progress: Duration::from_millis(80),
8406 cancel_grace: Duration::from_millis(500),
8407 persist_debounce: Duration::from_millis(10),
8408 human_wait_cap: Duration::from_secs(24 * 60 * 60),
8409 },
8410 false,
8411 )
8412 .await
8413 });
8414
8415 runtime
8416 .emit_event_for_test(
8417 &thread.id,
8418 Some("turn_heartbeat"),
8419 "item.started",
8420 json!({
8421 "item": { "id": "item_tool_hb", "status": "in_progress" },
8422 "tool": { "id": "call_build", "name": "exec_command", "input": {} }
8423 }),
8424 )
8425 .await?;
8426
8427 tokio::time::timeout(Duration::from_secs(2), async {
8428 loop {
8429 match rx.recv().await {
8430 Some(TaskExecutionEvent::ToolHeartbeat) => break,
8431 Some(_) => {}
8432 None => panic!("task event stream closed before any heartbeat"),
8433 }
8434 }
8435 })
8436 .await
8437 .context("no ToolHeartbeat reached the worker channel while a tool was in flight")?;
8438
8439 runtime
8440 .emit_event_for_test(
8441 &thread.id,
8442 Some("turn_heartbeat"),
8443 "item.completed",
8444 json!({ "item": { "id": "item_tool_hb", "status": "completed" } }),
8445 )
8446 .await?;
8447 runtime
8448 .emit_event_for_test(
8449 &thread.id,
8450 Some("turn_heartbeat"),
8451 "turn.completed",
8452 json!({ "turn": { "status": "completed" } }),
8453 )
8454 .await?;
8455 let result = drive.await?;
8456 assert_eq!(result.status, TaskStatus::Completed);
8457 Ok(())
8458 }
8459
8460 #[tokio::test]
8461 async fn hung_running_tool_still_hits_the_wall_budget() -> Result<()> {
8462 let runtime = Arc::new(test_runtime_manager().await?);
8463 let thread = runtime
8464 .create_thread(CreateThreadRequest::default())
8465 .await?;
8466 let (tx, mut rx) = mpsc::channel(64);
8467 let runtime_for_drive = Arc::clone(&runtime);
8468 let thread_id = thread.id.clone();
8469 let drive = tokio::spawn(async move {
8470 drive_engine_turn(
8471 runtime_for_drive.as_ref(),
8472 &thread_id,
8473 "turn_hung_tool",
8474 tx,
8475 CancellationToken::new(),
8476 TaskExecutionLimits {
8477 wall_time: Duration::from_millis(300),
8478 idle_progress: Duration::from_millis(80),
8479 cancel_grace: Duration::from_millis(500),
8480 persist_debounce: Duration::from_millis(10),
8481 human_wait_cap: Duration::from_secs(24 * 60 * 60),
8482 },
8483 false,
8484 )
8485 .await
8486 });
8487
8488 runtime
8489 .emit_event_for_test(
8490 &thread.id,
8491 Some("turn_hung_tool"),
8492 "item.started",
8493 json!({
8494 "item": { "id": "item_tool_hung", "status": "in_progress" },
8495 "tool": { "id": "call_hang", "name": "exec_command", "input": {} }
8496 }),
8497 )
8498 .await?;
8499
8500 // The running-tool suppression only defers the idle watchdog; the
8501 // wall-time budget remains the backstop for a tool that never
8502 // completes.
8503 tokio::time::timeout(Duration::from_secs(2), async {
8504 loop {
8505 match rx.recv().await {
8506 Some(TaskExecutionEvent::Status { message })
8507 if message.contains("wall-time") =>
8508 {
8509 break;
8510 }
8511 Some(_) => {}
8512 None => panic!("task event stream closed before wall deadline"),
8513 }
8514 }
8515 })
8516 .await
8517 .context("wall budget did not fire during a hung tool")?;
8518 runtime
8519 .emit_event_for_test(
8520 &thread.id,
8521 Some("turn_hung_tool"),
8522 "turn.completed",
8523 json!({ "turn": { "status": "interrupted" } }),
8524 )
8525 .await?;
8526 let result = drive.await?;
8527 assert_eq!(result.status, TaskStatus::Failed);
8528 assert_eq!(result.terminal_reason, TaskTerminalReason::WallTimeout);
8529 Ok(())
8530 }
8531
8532 /// Mirrors the fixed runtime contract: a ToolStarted edge, then a silent
8533 /// window longer than the idle deadline fed only by ToolHeartbeat, then
8534 /// completion. Pins the supervisor side of the heartbeat chain — the
8535 /// worker idle watchdog must count heartbeats as progress.
8536 struct ToolHeartbeatExecutor;
8537
8538 const HEARTBEAT_TEST_IDLE_PROGRESS: Duration = Duration::from_millis(500);
8539 const HEARTBEAT_TEST_TICKS: u32 = 40;
8540
8541 #[async_trait]
8542 impl TaskExecutor for ToolHeartbeatExecutor {
8543 async fn execute(
8544 &self,
8545 _task: ExecutionTask,
8546 events: mpsc::Sender<TaskExecutionEvent>,
8547 cancel: CancellationToken,
8548 ) -> TaskExecutionResult {
8549 let _ = events
8550 .send(TaskExecutionEvent::ToolStarted {
8551 id: "tool_hb".to_string(),
8552 name: "exec_command".to_string(),
8553 input: serde_json::json!({}),
8554 })
8555 .await;
8556 for _ in 0..HEARTBEAT_TEST_TICKS {
8557 sleep(Duration::from_millis(30)).await;
8558 if cancel.is_cancelled() {
8559 return TaskExecutionResult {
8560 status: TaskStatus::Canceled,
8561 result_text: None,
8562 error: None,
8563 terminal_reason: TaskTerminalReason::Canceled,
8564 };
8565 }
8566 let _ = events.send(TaskExecutionEvent::ToolHeartbeat).await;
8567 }
8568 let _ = events
8569 .send(TaskExecutionEvent::ToolCompleted {
8570 id: "tool_hb".to_string(),
8571 name: "exec_command".to_string(),
8572 success: true,
8573 output: "build ok".to_string(),
8574 metadata: None,
8575 })
8576 .await;
8577 TaskExecutionResult {
8578 status: TaskStatus::Completed,
8579 result_text: Some("done".to_string()),
8580 error: None,
8581 terminal_reason: TaskTerminalReason::Completed,
8582 }
8583 }
8584 }
8585
8586 #[tokio::test(start_paused = true)]
8587 async fn worker_supervisor_honors_tool_heartbeats_during_silent_tools() -> Result<()> {
8588 let root = tempfile::tempdir()?;
8589 let mut config = short_test_config(root.path().to_path_buf());
8590 config.execution_limits.wall_time = Duration::from_secs(5);
8591 config.execution_limits.idle_progress = HEARTBEAT_TEST_IDLE_PROGRESS;
8592 let manager =
8593 TaskManager::start_with_executor(config, Arc::new(ToolHeartbeatExecutor)).await?;
8594
8595 let task = manager
8596 .add_task(NewTaskRequest::from_prompt("silent build with heartbeats"))
8597 .await?;
8598 let finished = wait_for_terminal_state(&manager, &task.id, Duration::from_secs(10)).await?;
8599 assert_eq!(
8600 finished.status,
8601 TaskStatus::Completed,
8602 "heartbeats from a silent in-flight tool must keep the worker idle watchdog fed"
8603 );
8604 assert!(
8605 !finished
8606 .timeline
8607 .iter()
8608 .any(|entry| entry.summary.contains("heartbeat")),
8609 "heartbeats are supervisor-side liveness only and must not surface on the timeline"
8610 );
8611 Ok(())
8612 }
8613
8614 struct ExposedTaskEventsExecutor {
8615 ready: mpsc::UnboundedSender<mpsc::Sender<TaskExecutionEvent>>,
8616 }
8617
8618 #[async_trait]
8619 impl TaskExecutor for ExposedTaskEventsExecutor {
8620 async fn execute(
8621 &self,
8622 _task: ExecutionTask,
8623 events: mpsc::Sender<TaskExecutionEvent>,
8624 cancel: CancellationToken,
8625 ) -> TaskExecutionResult {
8626 let _ = self.ready.send(events);
8627 cancel.cancelled().await;
8628 TaskExecutionResult::from_reason(TaskTerminalReason::Canceled, None)
8629 }
8630 }
8631
8632 #[tokio::test]
8633 async fn tool_heartbeat_is_liveness_only_and_never_persists() -> Result<()> {
8634 // Drive the actual supervisor beyond both persistence triggers: more
8635 // heartbeats than the pending-event cap, then an idle debounce window.
8636 let root = tempfile::tempdir()?;
8637 let config = test_config(root.path().to_path_buf());
8638 let debounce = config.execution_limits.persist_debounce;
8639 assert!(EVENT_CATCHUP_POLL < debounce);
8640 let (ready, mut receiver) = mpsc::unbounded_channel();
8641 let manager =
8642 TaskManager::start_with_executor(config, Arc::new(ExposedTaskEventsExecutor { ready }))
8643 .await?;
8644 let task = manager
8645 .add_task(NewTaskRequest::from_prompt("heartbeat persistence pin"))
8646 .await?;
8647 let events = tokio::time::timeout(Duration::from_secs(5), receiver.recv())
8648 .await
8649 .context("task never reached its executor")?
8650 .context("executor did not expose its event channel")?;
8651 let path = manager.tasks_dir.join(format!("{}.json", task.id));
8652 let before_bytes = fs::read(&path)?;
8653 let before_fingerprint = StoreFingerprint::read(&path);
8654 let before_loads = manager.store_loads.load(Ordering::Relaxed);
8655 let running: TaskRecord = serde_json::from_slice(&before_bytes)?;
8656 assert_eq!(running.status, TaskStatus::Running);
8657
8658 for _ in 0..TASK_EVENT_CHANNEL_CAPACITY + 8 {
8659 events.send(TaskExecutionEvent::ToolHeartbeat).await?;
8660 }
8661 tokio::time::timeout(Duration::from_secs(5), async {
8662 while events.capacity() != TASK_EVENT_CHANNEL_CAPACITY {
8663 sleep(Duration::from_millis(1)).await;
8664 }
8665 })
8666 .await
8667 .context("supervisor did not consume the heartbeat burst")?;
8668 sleep(debounce * 3).await;
8669 assert_eq!(
8670 manager.store_loads.load(Ordering::Relaxed),
8671 before_loads,
8672 "heartbeats must not even reload the persistent task store"
8673 );
8674 assert!(
8675 !manager
8676 .state
8677 .lock()
8678 .await
8679 .pending_events
8680 .contains_key(&task.id),
8681 "heartbeats must not enter the pending persistence queue"
8682 );
8683 assert_eq!(fs::read(&path)?, before_bytes);
8684 assert_eq!(
8685 StoreFingerprint::read(&path),
8686 before_fingerprint,
8687 "heartbeat traffic must not rewrite even byte-identical task records"
8688 );
8689
8690 // Keep the production heartbeat cadence faster than the default 250ms
8691 // debounce until a real delta is saved. Neither the beats nor the
8692 // supervisor's ownership-poll wakes may restart its persistence window.
8693 events.try_send(TaskExecutionEvent::MessageDelta {
8694 content: "real progress survives".to_string(),
8695 })?;
8696 tokio::time::timeout(Duration::from_secs(5), async {
8697 let mut heartbeat = tokio::time::interval(EVENT_CATCHUP_POLL);
8698 heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
8699 loop {
8700 heartbeat.tick().await;
8701 events.send(TaskExecutionEvent::ToolHeartbeat).await?;
8702 let saved: TaskRecord = serde_json::from_slice(&fs::read(&path)?)?;
8703 if saved.timeline.iter().any(|entry| {
8704 entry.kind == "message" && entry.summary == "real progress survives"
8705 }) {
8706 break Ok::<_, anyhow::Error>(());
8707 }
8708 }
8709 })
8710 .await
8711 .context("continuous heartbeats starved the real delta's persistence deadline")??;
8712
8713 // An urgent edge flushes a newly dirty delta as well as its own data,
8714 // then clears that delta's outstanding deadline.
8715 events.try_send(TaskExecutionEvent::MessageDelta {
8716 content: "urgent progress survives".to_string(),
8717 })?;
8718 events.try_send(TaskExecutionEvent::ToolStarted {
8719 id: "item-1".into(),
8720 name: "bash".into(),
8721 input: serde_json::json!({}),
8722 })?;
8723 tokio::time::timeout(Duration::from_secs(5), async {
8724 loop {
8725 let saved: TaskRecord = serde_json::from_slice(&fs::read(&path)?)?;
8726 if saved
8727 .tool_calls
8728 .iter()
8729 .any(|call| call.id == "item-1" && call.status == TaskToolStatus::Running)
8730 {
8731 assert!(
8732 saved
8733 .timeline
8734 .iter()
8735 .any(|entry| entry.kind == "tool_started")
8736 );
8737 assert!(saved.timeline.iter().any(|entry| {
8738 entry.kind == "message" && entry.summary == "urgent progress survives"
8739 }));
8740 assert!(
8741 !saved
8742 .timeline
8743 .iter()
8744 .any(|entry| entry.summary.contains("heartbeat"))
8745 );
8746 break Ok::<_, anyhow::Error>(());
8747 }
8748 sleep(Duration::from_millis(1)).await;
8749 }
8750 })
8751 .await
8752 .context("real tool lifecycle edge was not persisted")??;
8753 assert_ne!(StoreFingerprint::read(&path), before_fingerprint);
8754 let after_urgent = StoreFingerprint::read(&path);
8755 sleep(debounce * 2).await;
8756 assert_eq!(
8757 StoreFingerprint::read(&path),
8758 after_urgent,
8759 "successful urgent persistence must not leave a pending write deadline"
8760 );
8761 manager.shutdown_and_wait().await?;
8762 Ok(())
8763 }
8764
8765 #[tokio::test]
8766 async fn engine_turn_prefers_runtime_terminal_over_cancel_grace() -> Result<()> {
8767 let runtime = test_runtime_manager().await?;
8768 let thread = runtime
8769 .create_thread(CreateThreadRequest::default())
8770 .await?;
8771 let cancel = CancellationToken::new();
8772 cancel.cancel();
8773 runtime
8774 .emit_event_for_test(
8775 &thread.id,
8776 Some("turn_done"),
8777 "turn.completed",
8778 json!({ "turn": { "status": "interrupted" } }),
8779 )
8780 .await?;
8781 let (tx, rx) = mpsc::channel(64);
8782 tokio::spawn(drain_task_events(rx));
8783 let result = drive_engine_turn(
8784 &runtime,
8785 &thread.id,
8786 "turn_done",
8787 tx,
8788 cancel,
8789 TaskExecutionLimits::short_for_tests(),
8790 false,
8791 )
8792 .await;
8793 assert_eq!(result.status, TaskStatus::Canceled);
8794 assert_eq!(result.terminal_reason, TaskTerminalReason::Canceled);
8795 Ok(())
8796 }
8797
8798 #[tokio::test]
8799 async fn runtime_store_failure_event_reaches_the_task_timeline() -> Result<()> {
8800 // #5931: the runtime's own store fault lands in the task timeline,
8801 // and a terminal one stops the driver instead of idling it out.
8802 let (tx, mut rx) = mpsc::channel(8);
8803 let mut final_text = RuntimeTaskOutput::default();
8804 let path = "/tmp/runtime/turns/turn_store.json";
8805 let event = RuntimeEventRecord {
8806 schema_version: 1,
8807 seq: 7,
8808 timestamp: Utc::now(),
8809 thread_id: "thr_store".to_string(),
8810 turn_id: Some("turn_store".to_string()),
8811 item_id: None,
8812 event: RUNTIME_STORE_FAILURE_EVENT.to_string(),
8813 payload: json!({
8814 "operation": "read",
8815 "record_kind": "turn",
8816 "record_id": "turn_store",
8817 "path": path,
8818 "error": format!("Failed to read turn {path}: No such file"),
8819 "reason": "No such file",
8820 "next_action": format!("Move {path} aside (or delete it) and retry."),
8821 "message": format!(
8822 "Session runtime store: turn turn_store at {path} could not be read: No such file. Move {path} aside (or delete it) and retry."
8823 ),
8824 }),
8825 };
8826
8827 assert!(
8828 ingest_runtime_event(&event, &mut final_text, &tx)
8829 .await
8830 .is_none(),
8831 "a non-terminal store fault leaves the driver waiting"
8832 );
8833 let mut saw_error = false;
8834 while let Ok(received) = rx.try_recv() {
8835 if let TaskExecutionEvent::Error { message } = received {
8836 assert!(message.contains(path), "{message}");
8837 saw_error = true;
8838 }
8839 }
8840 assert!(saw_error, "store fault missing from the task timeline");
8841
8842 let mut terminal = event.clone();
8843 terminal.payload["terminal"] = json!(true);
8844 let (status, error) = ingest_runtime_event(&terminal, &mut final_text, &tx)
8845 .await
8846 .expect("a terminal store fault ends the turn");
8847 assert_eq!(status, RuntimeTurnStatus::Failed);
8848 assert!(error.is_some_and(|message| message.contains(path)));
8849 Ok(())
8850 }
8851
8852 #[tokio::test]
8853 async fn denied_task_uses_v5_schema_while_open_task_stays_v4() -> Result<()> {
8854 let tmp = tempfile::tempdir()?;
8855 let root = tmp.path().to_path_buf();
8856 let manager =
8857 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
8858 .await?;
8859
8860 let open = manager
8861 .add_task(NewTaskRequest {
8862 disallowed_tools: vec![" ".to_string()],
8863 ..NewTaskRequest::from_prompt("open task")
8864 })
8865 .await?;
8866 let mut restricted_req = NewTaskRequest::from_prompt("restricted task");
8867 restricted_req.disallowed_tools = vec!["shell".to_string(), " shell ".to_string()];
8868 let restricted = manager.add_task(restricted_req).await?;
8869
8870 assert_eq!(open.schema_version, CURRENT_TASK_SCHEMA_VERSION);
8871 assert!(open.disallowed_tools.is_empty());
8872 assert_eq!(restricted.schema_version, DENY_RULES_TASK_SCHEMA_VERSION);
8873 assert_eq!(restricted.disallowed_tools, vec!["shell"]);
8874
8875 let _ = wait_for_terminal_state(&manager, &open.id, Duration::from_secs(10)).await?;
8876 let _ = wait_for_terminal_state(&manager, &restricted.id, Duration::from_secs(10)).await?;
8877 manager.shutdown_and_wait().await?;
8878 drop(manager);
8879
8880 let open_json: serde_json::Value = serde_json::from_str(&fs::read_to_string(
8881 root.join("tasks").join(format!("{}.json", open.id)),
8882 )?)?;
8883 assert_eq!(open_json["schema_version"], CURRENT_TASK_SCHEMA_VERSION);
8884 assert!(open_json.get("disallowed_tools").is_none());
8885
8886 let restricted_path = root.join("tasks").join(format!("{}.json", restricted.id));
8887 let mut restricted_json: serde_json::Value =
8888 serde_json::from_str(&fs::read_to_string(&restricted_path)?)?;
8889 assert_eq!(
8890 restricted_json["schema_version"],
8891 DENY_RULES_TASK_SCHEMA_VERSION
8892 );
8893 assert_eq!(restricted_json["disallowed_tools"], json!(["shell"]));
8894
8895 let reloaded =
8896 TaskManager::start_with_executor(test_config(root.clone()), Arc::new(MockExecutor))
8897 .await?;
8898 let reloaded_task = reloaded.get_task(&restricted.id).await?;
8899 assert_eq!(reloaded_task.schema_version, DENY_RULES_TASK_SCHEMA_VERSION);
8900 assert_eq!(reloaded_task.disallowed_tools, vec!["shell"]);
8901 reloaded.shutdown_and_wait().await?;
8902 drop(reloaded);
8903
8904 restricted_json["schema_version"] = json!(MAX_SUPPORTED_TASK_SCHEMA_VERSION + 1);
8905 fs::write(
8906 &restricted_path,
8907 serde_json::to_string_pretty(&restricted_json)?,
8908 )?;
8909 match TaskManager::start_with_executor(test_config(root), Arc::new(MockExecutor)).await {
8910 Ok(_) => panic!("manager should reject task schema v6"),
8911 Err(err) => assert!(err.to_string().contains("newer than supported"), "{err:#}"),
8912 }
8913 Ok(())
8914 }
8915 }
8916
8917 #[cfg(test)]
8918 mod ownership_tests;
8919
8919 lines RUST