返回 CodeWhale
tasks.rs
根目录 / crates / engine / src / tools / tasks.rs
1 //! Durable task, gate, and PR-attempt tools.
2
3 use std::path::{Path, PathBuf};
4 use std::time::Instant;
5
6 use async_trait::async_trait;
7 use chrono::Utc;
8 use serde_json::{Value, json};
9 use tokio::process::Command;
10 use uuid::Uuid;
11
12 use crate::task_manager::{
13 NewTaskRequest, TaskArtifactRef, TaskAttemptRecord, TaskCancelDisposition, TaskGateRecord,
14 TaskRecord,
15 };
16 use crate::tools::shell::BashTool;
17 use crate::tools::spec::{
18 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
19 optional_bool, optional_bool_opt, optional_str, optional_u64, required_str,
20 };
21 use crate::work_graph::{
22 CancelOutcome, OperationIntent, OperationObservation, OperationOwnerSnapshot, OwnerState,
23 task_owner_snapshot,
24 };
25 use codewhale_dependencies::ExternalTool;
26 use codewhale_execpolicy::command_safety::{SafetyAnalysis, SafetyLevel, analyze_command};
27
28 const MAX_SUMMARY_CHARS: usize = 900;
29 const DEFAULT_GATE_TIMEOUT_MS: u64 = 120_000;
30 const MAX_GATE_TIMEOUT_MS: u64 = 600_000;
31
32 fn build_gate_command_parts(command: &str) -> (String, Vec<String>) {
33 (
34 "/bin/sh".to_string(),
35 vec!["-c".to_string(), command.to_string()],
36 )
37 }
38
39 /// Gate commands run workspace code, so they start like an `exec_shell`
40 /// command: inside this session's sandbox, from the sanitized environment.
41 fn build_gate_command(
42 command: &str,
43 cwd: &Path,
44 context: &ToolContext,
45 timeout: std::time::Duration,
46 ) -> Result<Command, ToolError> {
47 let (program, args) = build_gate_command_parts(command);
48 crate::tools::shell::sandboxed_runner_command(context, &program, args, cwd, timeout)
49 }
50
51 fn task_shell_wait_input(mut input: Value) -> Value {
52 if let Some(object) = input.as_object_mut() {
53 if object.get("wait").is_none_or(Value::is_null)
54 && object.get("block").is_none_or(Value::is_null)
55 {
56 object.insert("wait".to_string(), Value::Bool(false));
57 }
58 if object.get("task_ids").is_some_and(Value::is_null) {
59 object.remove("task_ids");
60 }
61 if object.get("task_ids").is_some_and(|v| !v.is_null())
62 && object.get("until").is_none_or(Value::is_null)
63 {
64 object.insert("until".to_string(), Value::String("any".to_string()));
65 }
66 }
67 input
68 }
69
70 /// Whether a `task_shell_wait` call asks to stop its task rather than poll it.
71 ///
72 /// Only an absent, null or false `cancel` is a poll. Any other value counts as
73 /// a stop here, so approval holds the call and names it as one before
74 /// execution judges the value's type.
75 pub fn task_shell_wait_requests_cancel(input: &Value) -> bool {
76 input
77 .get("cancel")
78 .is_some_and(|cancel| !cancel.is_null() && cancel.as_bool() != Some(false))
79 }
80
81 /// Unified durable-task tool (piagent phase B).
82 ///
83 /// The model sees one tool, `tasks`, with an `action` parameter routing to
84 /// the per-action logic below. The per-action `task_*` / `pr_attempt_*`
85 /// execution aliases were removed in v0.9.3.
86 ///
87 /// `TaskShellWaitTool` stays separate: the registry gates it behind
88 /// `allow_shell` (see `with_runtime_task_shell_tools`),
89 /// which differs from every other action in this family.
90 pub struct TasksTool {
91 name: &'static str,
92 read_only: bool,
93 }
94
95 pub struct TaskShellWaitTool;
96
97 /// Actions the Plan-mode read-only surface exposes.
98 const READ_ACTIONS: &[&str] = &["list", "read", "pr_attempt_list", "pr_attempt_read"];
99 const ALL_ACTIONS: &[&str] = &[
100 "create",
101 "list",
102 "read",
103 "cancel",
104 "gate_run",
105 "pr_attempt_record",
106 "pr_attempt_list",
107 "pr_attempt_read",
108 "pr_attempt_preflight",
109 "suggest",
110 ];
111
112 impl TasksTool {
113 pub const fn new(name: &'static str) -> Self {
114 Self {
115 name,
116 read_only: false,
117 }
118 }
119
120 /// Plan-mode variant: only the read-only actions are advertised and routed.
121 pub const fn read_only(name: &'static str) -> Self {
122 Self {
123 name,
124 read_only: true,
125 }
126 }
127
128 fn allowed_actions(&self) -> &'static [&'static str] {
129 if self.read_only {
130 READ_ACTIONS
131 } else {
132 ALL_ACTIONS
133 }
134 }
135
136 fn resolve_action<'a>(&'a self, input: &'a Value) -> Result<&'a str, ToolError> {
137 let action = input.get("action").and_then(Value::as_str).ok_or_else(|| {
138 ToolError::invalid_input(format!(
139 "tasks: missing `action` (one of: {})",
140 self.allowed_actions().join(", ")
141 ))
142 })?;
143 if self.allowed_actions().contains(&action) {
144 Ok(action)
145 } else {
146 Err(ToolError::invalid_input(format!(
147 "tasks: invalid action `{action}` (one of: {})",
148 self.allowed_actions().join(", ")
149 )))
150 }
151 }
152
153 fn action_is_read(action: &str) -> bool {
154 READ_ACTIONS.contains(&action)
155 }
156
157 fn action_requires_approval(action: &str) -> bool {
158 !Self::action_is_read(action) && action != "suggest"
159 }
160 }
161
162 #[async_trait]
163 impl ToolSpec for TasksTool {
164 fn name(&self) -> &'static str {
165 self.name
166 }
167
168 fn description(&self) -> &'static str {
169 if self.read_only {
170 "Inspect durable tasks and their PR attempts. Actions: \"list\", \"read\", \"pr_attempt_list\", \"pr_attempt_read\"."
171 } else {
172 "Manage durable background tasks through TaskManager. Durable tasks are restart-aware executable work, distinct from sub-agents. Actions: \"create\" (enqueue; approval), \"list\", \"read\", \"cancel\" (approval), \"gate_run\" (run an approved verification gate command and return structured evidence; approval), \"pr_attempt_record\" (approval), \"pr_attempt_list\", \"pr_attempt_read\", \"pr_attempt_preflight\" (approval), \"suggest\" (offer the person a task as a card they can Start or Hide; starts nothing — never create it yourself after suggesting). Run long shell work with the shell tool (background=true to detach immediately; a foreground command still running after 30s moves to the background by itself)."
173 }
174 }
175
176 fn input_schema(&self) -> Value {
177 let actions: Vec<&str> = self.allowed_actions().to_vec();
178 let mut properties = serde_json::Map::new();
179 properties.insert(
180 "action".to_string(),
181 json!({
182 "type": "string",
183 "enum": actions,
184 "description": "Action to perform."
185 }),
186 );
187 if !self.read_only {
188 properties.insert(
189 "prompt".to_string(),
190 json!({ "type": "string", "description": "Work prompt for the durable task (action=create), or the prompt Start would send (action=suggest)." }),
191 );
192 properties.insert(
193 "name".to_string(),
194 json!({ "type": "string", "description": "Short run name shown in queues; omit to derive from the prompt. (action=create; for action=suggest, the card's title)" }),
195 );
196 properties.insert(
197 "model_provider".to_string(),
198 json!({ "type": "string", "description": "Provider kind for the pinned model. Omit to inherit the configured provider." }),
199 );
200 properties.insert(
201 "model_provider_id".to_string(),
202 json!({ "type": "string", "description": "Exact configured provider id, including named custom routes. Keeps the model on that route." }),
203 );
204 properties.insert(
205 "model".to_string(),
206 json!({ "type": "string", "description": "(action=create)" }),
207 );
208 properties.insert(
209 "workspace".to_string(),
210 json!({ "type": "string", "description": "Workspace path; defaults to current workspace. (action=create)" }),
211 );
212 properties.insert(
213 "mode".to_string(),
214 json!({ "type": "string", "enum": ["agent", "plan"], "description": "(action=create)" }),
215 );
216 properties.insert(
217 "allow_shell".to_string(),
218 json!({ "type": "boolean", "description": "(action=create)" }),
219 );
220 properties.insert(
221 "trust_mode".to_string(),
222 json!({ "type": "boolean", "description": "(action=create)" }),
223 );
224 properties.insert(
225 "auto_approve".to_string(),
226 json!({ "type": "boolean", "description": "(action=create)" }),
227 );
228 properties.insert(
229 "gate".to_string(),
230 json!({
231 "type": "string",
232 "enum": ["fmt", "check", "clippy", "test", "custom"],
233 "description": "Gate category. (action=gate_run)"
234 }),
235 );
236 properties.insert(
237 "command".to_string(),
238 json!({ "type": "string", "description": "Command to run. (action=gate_run)" }),
239 );
240 properties.insert(
241 "cwd".to_string(),
242 json!({ "type": "string", "description": "Optional working directory within the workspace. (action=gate_run)" }),
243 );
244 properties.insert(
245 "timeout_ms".to_string(),
246 json!({ "type": "integer", "minimum": 1000, "maximum": 600000, "description": "(action=gate_run)" }),
247 );
248 properties.insert(
249 "attempt_group_id".to_string(),
250 json!({ "type": "string", "description": "(action=pr_attempt_record)" }),
251 );
252 properties.insert(
253 "attempt_index".to_string(),
254 json!({ "type": "integer", "minimum": 1, "description": "(action=pr_attempt_record)" }),
255 );
256 properties.insert(
257 "attempt_count".to_string(),
258 json!({ "type": "integer", "minimum": 1, "description": "(action=pr_attempt_record)" }),
259 );
260 properties.insert(
261 "summary".to_string(),
262 json!({ "type": "string", "description": "Attempt summary (action=pr_attempt_record)." }),
263 );
264 properties.insert(
265 "verification".to_string(),
266 json!({ "type": "array", "items": { "type": "string" }, "description": "(action=pr_attempt_record)" }),
267 );
268 }
269 properties.insert(
270 "attempt_id".to_string(),
271 json!({ "type": "string", "description": "(action=pr_attempt_read/preflight)" }),
272 );
273 properties.insert(
274 "task_id".to_string(),
275 json!({ "type": "string", "description": "Full task id or unambiguous prefix (action=read/cancel); task id, defaults to active task (action=pr_attempt_*)." }),
276 );
277 properties.insert(
278 "limit".to_string(),
279 json!({ "type": "integer", "minimum": 1, "maximum": 100, "default": 20, "description": "(action=list)" }),
280 );
281 json!({
282 "type": "object",
283 "properties": properties,
284 "additionalProperties": false
285 })
286 }
287
288 fn capabilities(&self) -> Vec<ToolCapability> {
289 if self.read_only {
290 vec![ToolCapability::ReadOnly]
291 } else {
292 vec![
293 ToolCapability::ExecutesCode,
294 ToolCapability::RequiresApproval,
295 ]
296 }
297 }
298
299 fn approval_requirement(&self) -> ApprovalRequirement {
300 if self.read_only {
301 ApprovalRequirement::Auto
302 } else {
303 ApprovalRequirement::Required
304 }
305 }
306
307 fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement {
308 match self.resolve_action(input) {
309 Ok(action) if Self::action_requires_approval(action) => ApprovalRequirement::Required,
310 Ok(_) => ApprovalRequirement::Auto,
311 Err(_) => self.approval_requirement(),
312 }
313 }
314
315 fn is_read_only_for(&self, input: &Value) -> bool {
316 match self.resolve_action(input) {
317 Ok(action) => Self::action_is_read(action),
318 Err(_) => self.is_read_only(),
319 }
320 }
321
322 fn supports_parallel_for(&self, input: &Value) -> bool {
323 self.is_read_only_for(input)
324 }
325
326 fn refusal_before_approval(&self, input: &Value, context: &ToolContext) -> Option<ToolResult> {
327 if context.auto_approve || self.resolve_action(input).ok()? != "gate_run" {
328 return None;
329 }
330 let command = input.get("command")?.as_str()?;
331 dangerous_gate_block(&analyze_command(command))
332 }
333
334 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
335 crate::tools::execution_envelope::enforce_tool_denial(
336 context,
337 self.name(),
338 &json!({"action": self.resolve_action(&input)?}),
339 )?;
340 match self.resolve_action(&input)? {
341 "create" => self.execute_create(&input, context).await,
342 "list" => self.execute_list(&input, context).await,
343 "read" => self.execute_read(&input, context).await,
344 "cancel" => self.execute_cancel(&input, context).await,
345 "gate_run" => self.execute_gate_run(&input, context).await,
346 "pr_attempt_record" => self.execute_pr_attempt_record(&input, context).await,
347 "pr_attempt_list" => self.execute_pr_attempt_list(&input, context).await,
348 "pr_attempt_read" => self.execute_pr_attempt_read(&input, context).await,
349 "pr_attempt_preflight" => self.execute_pr_attempt_preflight(&input, context).await,
350 "suggest" => execute_suggest(&input),
351 action => Err(ToolError::invalid_input(format!(
352 "tasks: invalid action `{action}`"
353 ))),
354 }
355 }
356 }
357
358 fn execute_suggest(input: &Value) -> Result<ToolResult, ToolError> {
359 let prompt = required_str(input, "prompt")?.trim();
360 let title = optional_str(input, "name")?
361 .map(str::trim)
362 .filter(|name| !name.is_empty())
363 .unwrap_or(prompt);
364 if prompt.is_empty() {
365 return Err(ToolError::invalid_input("tasks: suggest needs a prompt"));
366 }
367 ToolResult::json(&json!({
368 "summary": format!("Suggested to the person: {title}. Nothing was started; they choose Start or Hide."),
369 "suggestion": { "title": title, "prompt": prompt },
370 }))
371 .map_err(|e| ToolError::execution_failed(e.to_string()))
372 }
373
374 fn dangerous_gate_block(safety: &SafetyAnalysis) -> Option<ToolResult> {
375 if safety.level != SafetyLevel::Dangerous {
376 return None;
377 }
378 Some(
379 ToolResult::error(format!(
380 "BLOCKED: gate command classified dangerous: {}",
381 safety.reasons.join("; ")
382 ))
383 .with_metadata(json!({
384 "safety_level": "dangerous",
385 "blocked": true,
386 "reasons": safety.reasons,
387 })),
388 )
389 }
390
391 impl TasksTool {
392 async fn execute_create(
393 &self,
394 input: &Value,
395 context: &ToolContext,
396 ) -> Result<ToolResult, ToolError> {
397 let manager = context
398 .runtime
399 .task_manager
400 .as_ref()
401 .ok_or_else(|| ToolError::not_available("TaskManager is not attached"))?;
402 // A task may run in another directory only where this session could
403 // already reach: inside its workspace, or anywhere in trust mode.
404 let workspace = match optional_str(input, "workspace")? {
405 Some(raw) => context.resolve_path(raw)?,
406 None => context.workspace.clone(),
407 };
408 let prompt = required_str(input, "prompt")?.to_string();
409 // Authority declarations: read strictly (a malformed value that
410 // silently reads as "unset" is a restriction that evaporates), then
411 // capped at what this session holds.
412 let (allow_shell, trust_mode, auto_approve) = context.cap_delegated_authority(
413 optional_bool_opt(input, "allow_shell")?,
414 optional_bool_opt(input, "trust_mode")?,
415 optional_bool_opt(input, "auto_approve")?,
416 );
417 let req = NewTaskRequest {
418 destination_thread_id: None,
419 prompt: prompt.clone(),
420 name: optional_str(input, "name")?.map(ToString::to_string),
421 model: optional_str(input, "model")?.map(ToString::to_string),
422 model_provider: optional_str(input, "model_provider")?.map(ToString::to_string),
423 model_provider_id: optional_str(input, "model_provider_id")?.map(ToString::to_string),
424 workspace: Some(workspace),
425 mode: optional_str(input, "mode")?.map(ToString::to_string),
426 allow_shell,
427 trust_mode,
428 auto_approve,
429 // The task runs on the posture this session is in. The bits above
430 // are declarations the engine only reads when no posture is given,
431 // and a task started from a session must not run under authority
432 // that session was never granted.
433 permission_posture: Some(
434 codewhale_runtime::runtime_policy::approval_wire(context.approval_mode).to_string(),
435 ),
436 disallowed_tools: context.disallowed_tools.clone(),
437 owner_session_id: Some(context.state_namespace.clone()),
438 };
439 let task_id = crate::task_manager::TaskManager::new_task_id();
440 if let Some(work) = context.runtime.work.as_ref()
441 && let Err(err) = work.register_operation(
442 &context.state_namespace,
443 OperationIntent::new(
444 format!("task:{task_id}"),
445 prompt,
446 true,
447 "task_create",
448 &task_id,
449 ),
450 )
451 {
452 // Bookkeeping must not veto the task: every later reconcile is
453 // guarded by `has_operation_binding`, so an unbound task merely
454 // goes unreported on the Work surface.
455 tracing::warn!(
456 task_id = %task_id,
457 error = %err,
458 "task work-graph registration skipped; running unbound"
459 );
460 }
461 let task = match manager.add_task_with_id(req, task_id.clone()).await {
462 Ok(task) => task,
463 Err(err) => {
464 if let Some(work) = context.runtime.work.as_ref() {
465 let _ = work.reconcile_operation(
466 &context.state_namespace,
467 OperationOwnerSnapshot::new(
468 format!("task:{task_id}"),
469 OwnerState::Failed,
470 1,
471 Utc::now().timestamp_millis(),
472 ),
473 );
474 }
475 return Err(ToolError::execution_failed(err.to_string()));
476 }
477 };
478 let lifecycle_warning = reconcile_task_record(context, &task).err().map(|err| {
479 tracing::warn!(task_id = %task.id, error = %err, "task was created but Work lifecycle reconciliation failed");
480 err.to_string()
481 });
482 task_result_with_lifecycle_warning("task_create", &task, lifecycle_warning.as_deref())
483 }
484
485 async fn execute_list(
486 &self,
487 input: &Value,
488 context: &ToolContext,
489 ) -> Result<ToolResult, ToolError> {
490 let manager = context
491 .runtime
492 .task_manager
493 .as_ref()
494 .ok_or_else(|| ToolError::not_available("TaskManager is not attached"))?;
495 let limit = optional_u64(input, "limit", 20)?.clamp(1, 100) as usize;
496 let tasks = manager
497 .list_tasks_for_owner(Some(limit), None, &context.state_namespace)
498 .await
499 .map_err(|error| ToolError::execution_failed(error.to_string()))?;
500 ToolResult::json(&json!({
501 "summary": format!("{} durable task(s)", tasks.len()),
502 "tasks": tasks,
503 }))
504 .map_err(|e| ToolError::execution_failed(e.to_string()))
505 }
506
507 async fn execute_read(
508 &self,
509 input: &Value,
510 context: &ToolContext,
511 ) -> Result<ToolResult, ToolError> {
512 let task = read_task_for_input(input, context).await?;
513 task_result("task_read", &task)
514 }
515
516 async fn execute_cancel(
517 &self,
518 input: &Value,
519 context: &ToolContext,
520 ) -> Result<ToolResult, ToolError> {
521 let manager = context
522 .runtime
523 .task_manager
524 .as_ref()
525 .ok_or_else(|| ToolError::not_available("TaskManager is not attached"))?;
526 let task_id = required_str(input, "task_id")?;
527 let cancellation = if context.runtime.active_task_id.as_deref() == Some(task_id) {
528 // `active_task_id` is stamped from the immutable runtime thread
529 // record, not model input. Preserve self-cancel for a running task,
530 // but fail closed for ownerless legacy records.
531 manager.cancel_task_for_active_runtime(task_id).await
532 } else {
533 manager
534 .cancel_task_for_owner(task_id, &context.state_namespace)
535 .await
536 }
537 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
538 let task = cancellation.task;
539 let cancel_outcome = match cancellation.disposition {
540 TaskCancelDisposition::Forced => CancelOutcome::Forced,
541 TaskCancelDisposition::Requested => CancelOutcome::Requested,
542 TaskCancelDisposition::AlreadyFinished => CancelOutcome::AlreadyFinished,
543 };
544 let mut lifecycle_warnings = Vec::new();
545 if let Some(work) = context.runtime.work.as_ref() {
546 let external = format!("task:{}", task.id);
547 if work.has_operation_binding(Some(&context.state_namespace), &external)
548 && let Err(err) = work.reconcile_observation(
549 &context.state_namespace,
550 &external,
551 OperationObservation::CancelUpdate {
552 outcome: cancel_outcome,
553 at: Utc::now().timestamp_millis(),
554 },
555 )
556 {
557 tracing::warn!(task_id = %task.id, error = %err, "task was cancelled but Work cancel reconciliation failed");
558 lifecycle_warnings.push(err);
559 }
560 }
561 if let Err(err) = reconcile_task_record(context, &task) {
562 tracing::warn!(task_id = %task.id, error = %err, "task cancellation succeeded but owner-state reconciliation failed");
563 lifecycle_warnings.push(err.to_string());
564 }
565 let lifecycle_warning =
566 (!lifecycle_warnings.is_empty()).then(|| lifecycle_warnings.join("; "));
567 task_result_with_lifecycle_warning("task_cancel", &task, lifecycle_warning.as_deref())
568 }
569
570 async fn execute_gate_run(
571 &self,
572 input: &Value,
573 context: &ToolContext,
574 ) -> Result<ToolResult, ToolError> {
575 crate::tools::execution_envelope::enforce_tool_denial(context, "task_gate_run", input)?;
576 if context.shell_policy != codewhale_agent_contract::worker_profile::ShellPolicy::Full {
577 return Err(ToolError::permission_denied(
578 "Gate commands require full shell permission.",
579 ));
580 }
581 let gate = required_str(input, "gate")?.to_string();
582 let command = required_str(input, "command")?.to_string();
583 let timeout_ms = optional_u64(input, "timeout_ms", DEFAULT_GATE_TIMEOUT_MS)?
584 .clamp(1_000, MAX_GATE_TIMEOUT_MS);
585 let cwd = resolve_cwd(context, optional_str(input, "cwd")?)?;
586
587 if !context.auto_approve
588 && let Some(blocked) = dangerous_gate_block(&analyze_command(&command))
589 {
590 return Ok(blocked);
591 }
592
593 let started = Instant::now();
594 let mut cmd = build_gate_command(
595 &command,
596 &cwd,
597 context,
598 std::time::Duration::from_millis(timeout_ms),
599 )?;
600 // Contained: when the timeout elapses the gate's whole process tree
601 // is killed, instead of leaving it running behind a "timeout" result,
602 // and what it wrote until then still reaches the log.
603 let output = codewhale_runtime::process_tree::contained_output_until(
604 &mut cmd,
605 tokio::time::sleep(std::time::Duration::from_millis(timeout_ms)),
606 )
607 .await;
608
609 let duration_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
610 let (exit_code, stdout, stderr, timed_out, spawn_error) = match output {
611 Ok(run) => (
612 if run.stopped {
613 None
614 } else {
615 run.output.status.code()
616 },
617 String::from_utf8_lossy(&run.output.stdout).to_string(),
618 String::from_utf8_lossy(&run.output.stderr).to_string(),
619 run.stopped,
620 None,
621 ),
622 Err(err) => (
623 None,
624 String::new(),
625 String::new(),
626 false,
627 Some(err.to_string()),
628 ),
629 };
630
631 let full_log = format!(
632 "$ {command}\n\n[stdout]\n{stdout}\n\n[stderr]\n{stderr}\n{}",
633 spawn_error
634 .as_ref()
635 .map(|e| format!("\n[spawn_error]\n{e}\n"))
636 .unwrap_or_default()
637 );
638 let summary_source = if !stderr.trim().is_empty() {
639 stderr.as_str()
640 } else if !stdout.trim().is_empty() {
641 stdout.as_str()
642 } else {
643 spawn_error.as_deref().unwrap_or("(no output)")
644 };
645 let summary = summarize(summary_source, MAX_SUMMARY_CHARS);
646 let status = if timed_out {
647 "timeout"
648 } else if spawn_error.is_some() {
649 "failed"
650 } else if exit_code == Some(0) {
651 "passed"
652 } else {
653 "failed"
654 };
655 let classification = classify_gate_failure(&gate, status, timed_out, &stderr, &stdout);
656 let log_path = write_runtime_artifact(context, "gate", &full_log).await?;
657 let gate_record = TaskGateRecord {
658 id: format!("gate_{}", &Uuid::new_v4().to_string()[..8]),
659 gate: gate.clone(),
660 command: command.clone(),
661 cwd: cwd.clone(),
662 exit_code,
663 status: status.to_string(),
664 classification,
665 duration_ms,
666 summary: summary.clone(),
667 log_path: log_path.clone(),
668 recorded_at: Utc::now(),
669 };
670
671 let content = json!({
672 "gate": gate_record,
673 "stdout_summary": summarize(&stdout, MAX_SUMMARY_CHARS),
674 "stderr_summary": summarize(&stderr, MAX_SUMMARY_CHARS),
675 });
676 let mut metadata = json!({
677 "command": command,
678 "cwd": cwd,
679 "exit_code": exit_code,
680 "duration_ms": duration_ms,
681 "timed_out": timed_out,
682 "task_updates": {
683 "gate": gate_record,
684 "artifacts": artifact_updates("gate_log", log_path.clone(), &summary)
685 }
686 });
687 if let Some(path) = log_path {
688 metadata["artifact_path"] = json!(path);
689 }
690 let mut result =
691 ToolResult::json(&content).map_err(|e| ToolError::execution_failed(e.to_string()))?;
692 result.success = status == "passed";
693 Ok(result.with_metadata(metadata))
694 }
695
696 async fn execute_pr_attempt_record(
697 &self,
698 input: &Value,
699 context: &ToolContext,
700 ) -> Result<ToolResult, ToolError> {
701 let task_id = read_task_for_input(input, context).await?.id;
702 let base_sha = git_output(&context.workspace, &["rev-parse", "HEAD"])
703 .await
704 .ok();
705 let head_sha = base_sha.clone();
706 let branch = git_output(&context.workspace, &["rev-parse", "--abbrev-ref", "HEAD"])
707 .await
708 .ok();
709 let (diff, changed_files) = attempt_diff(&context.workspace).await?;
710 if diff.trim().is_empty() {
711 return Ok(ToolResult::error(
712 "No working-tree diff to record as an attempt.",
713 ));
714 }
715 let patch_path = write_task_artifact_for(context, &task_id, "attempt_patch", &diff).await?;
716 let attempt = TaskAttemptRecord {
717 id: format!("attempt_{}", &Uuid::new_v4().to_string()[..8]),
718 attempt_group_id: optional_str(input, "attempt_group_id")?
719 .map(ToString::to_string)
720 .unwrap_or_else(|| format!("attempt_group_{}", &Uuid::new_v4().to_string()[..8])),
721 attempt_index: optional_u64(input, "attempt_index", 1)?.max(1) as u32,
722 attempt_count: optional_u64(input, "attempt_count", 1)?.max(1) as u32,
723 base_ref: branch.clone(),
724 base_sha,
725 head_ref: branch,
726 head_sha,
727 summary: required_str(input, "summary")?.to_string(),
728 changed_files,
729 patch_path: patch_path.clone(),
730 verification: input
731 .get("verification")
732 .and_then(Value::as_array)
733 .map(|items| {
734 items
735 .iter()
736 .filter_map(Value::as_str)
737 .map(ToString::to_string)
738 .collect()
739 })
740 .unwrap_or_default(),
741 selected: false,
742 recorded_at: Utc::now(),
743 };
744 let metadata = json!({
745 "task_id": task_id,
746 "task_updates": {
747 "attempt": attempt,
748 "artifacts": artifact_updates("attempt_patch", patch_path.clone(), "Captured git diff for PR attempt")
749 }
750 });
751 if context.runtime.active_task_id.as_deref() != Some(task_id.as_str())
752 && let Some(manager) = context.runtime.task_manager.as_ref()
753 {
754 manager
755 .record_tool_metadata(&task_id, &metadata)
756 .await
757 .map_err(|e| ToolError::execution_failed(e.to_string()))?;
758 }
759 Ok(ToolResult::json(&metadata)
760 .map_err(|e| ToolError::execution_failed(e.to_string()))?
761 .with_metadata(metadata))
762 }
763
764 async fn execute_pr_attempt_list(
765 &self,
766 input: &Value,
767 context: &ToolContext,
768 ) -> Result<ToolResult, ToolError> {
769 let task = read_task_for_input(input, context).await?;
770 ToolResult::json(&json!({ "task_id": task.id, "attempts": task.attempts }))
771 .map_err(|e| ToolError::execution_failed(e.to_string()))
772 }
773
774 async fn execute_pr_attempt_read(
775 &self,
776 input: &Value,
777 context: &ToolContext,
778 ) -> Result<ToolResult, ToolError> {
779 let task = read_task_for_input(input, context).await?;
780 let attempt_id = required_str(input, "attempt_id")?;
781 let attempt = task
782 .attempts
783 .iter()
784 .find(|attempt| attempt.id == attempt_id)
785 .ok_or_else(|| ToolError::invalid_input(format!("Attempt not found: {attempt_id}")))?;
786 ToolResult::json(attempt).map_err(|e| ToolError::execution_failed(e.to_string()))
787 }
788
789 async fn execute_pr_attempt_preflight(
790 &self,
791 input: &Value,
792 context: &ToolContext,
793 ) -> Result<ToolResult, ToolError> {
794 let manager = context
795 .runtime
796 .task_manager
797 .as_ref()
798 .ok_or_else(|| ToolError::not_available("TaskManager is not attached"))?;
799 let task = read_task_for_input(input, context).await?;
800 let attempt_id = required_str(input, "attempt_id")?;
801 let attempt = task
802 .attempts
803 .iter()
804 .find(|attempt| attempt.id == attempt_id)
805 .ok_or_else(|| ToolError::invalid_input(format!("Attempt not found: {attempt_id}")))?;
806 let patch_ref = attempt
807 .patch_path
808 .as_ref()
809 .ok_or_else(|| ToolError::invalid_input("Attempt has no patch artifact"))?;
810 let patch_path = manager.artifact_absolute_path(patch_ref);
811 let workspace = context.workspace.clone();
812 let out = tokio::task::spawn_blocking(move || {
813 codewhale_dependencies::Git::command()
814 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "git not found"))?
815 .args(["apply", "--check"])
816 .arg(&patch_path)
817 .current_dir(&workspace)
818 .output()
819 })
820 .await
821 .map_err(|join_err| {
822 // Surface the otherwise-discarded join error for debugging; the
823 // returned ToolError (and thus user-facing behavior) is unchanged.
824 tracing::debug!(error = %join_err, "git apply --check spawn_blocking task failed to join");
825 ToolError::execution_failed(format!("git apply --check panicked: {join_err}"))
826 })?
827 .map_err(|e| ToolError::execution_failed(format!("git apply --check failed: {e}")))?;
828 let stdout = String::from_utf8_lossy(&out.stdout).to_string();
829 let stderr = String::from_utf8_lossy(&out.stderr).to_string();
830 ToolResult::json(&json!({
831 "attempt_id": attempt_id,
832 "patch_path": patch_ref,
833 "would_apply": out.status.success(),
834 "exit_code": out.status.code(),
835 "stdout_summary": summarize(&stdout, MAX_SUMMARY_CHARS),
836 "stderr_summary": summarize(&stderr, MAX_SUMMARY_CHARS),
837 "mutated_worktree": false
838 }))
839 .map_err(|e| ToolError::execution_failed(e.to_string()))
840 }
841 }
842
843 #[async_trait]
844 impl ToolSpec for TaskShellWaitTool {
845 fn name(&self) -> &'static str {
846 "task_shell_wait"
847 }
848
849 fn description(&self) -> &'static str {
850 "Poll or wait on a single background shell task (`task_id`) or multiple tasks (`task_ids` with `until=\"any\"|\"all\"`) without blocking the agent indefinitely, or stop one task with cancel=true. Completion is delivered automatically; use this only for early output, explicit barriers, or gate evidence. If `gate` is supplied and the single shell task has completed, records structured gate evidence on the active durable task."
851 }
852
853 fn input_schema(&self) -> Value {
854 json!({
855 "type": "object",
856 "properties": {
857 "task_id": { "type": "string", "description": "Background shell task id." },
858 "task_ids": {
859 "type": "array",
860 "items": { "type": "string" },
861 "minItems": 1,
862 "description": "Background shell task ids to poll or wait on together (mutually exclusive with task_id, cancel, and gate)."
863 },
864 "until": {
865 "type": "string",
866 "enum": ["any", "all"],
867 "description": "With task_ids and wait=true, return when any task finishes (default) or when all finish."
868 },
869 "wait": { "type": "boolean", "default": false },
870 "timeout_ms": { "type": "integer", "minimum": 1000, "maximum": 600000 },
871 "cancel": { "type": "boolean", "description": "Stop (kill) the task instead of polling; not valid with gate." },
872 "gate": { "type": "string", "enum": ["fmt", "check", "clippy", "test", "custom"] },
873 "command": { "type": "string", "description": "Original command, used when recording gate evidence." }
874 },
875 "additionalProperties": false
876 })
877 }
878
879 fn capabilities(&self) -> Vec<ToolCapability> {
880 vec![ToolCapability::ReadOnly, ToolCapability::WritesFiles]
881 }
882
883 fn approval_requirement(&self) -> ApprovalRequirement {
884 ApprovalRequirement::Required
885 }
886
887 fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement {
888 if self.is_read_only_for(input) {
889 ApprovalRequirement::Auto
890 } else {
891 ApprovalRequirement::Required
892 }
893 }
894
895 fn is_read_only_for(&self, input: &Value) -> bool {
896 // Recording a gate writes task evidence and `cancel` kills a process;
897 // neither is a read-only poll.
898 input.get("gate").is_none_or(Value::is_null) && !task_shell_wait_requests_cancel(input)
899 }
900
901 fn supports_parallel_for(&self, input: &Value) -> bool {
902 self.is_read_only_for(input)
903 }
904
905 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
906 crate::tools::execution_envelope::enforce_tool_denial(context, self.name(), &input)?;
907 if let Some(task_ids) = input.get("task_ids").filter(|v| !v.is_null()) {
908 if input.get("task_id").is_some_and(|v| !v.is_null()) {
909 return Err(ToolError::invalid_input(
910 "Provide either `task_id` or `task_ids`, not both.",
911 ));
912 }
913 if optional_bool(&input, "cancel", false)? {
914 return Err(ToolError::invalid_input(
915 "cancel=true requires a single `task_id` and cannot be used with `task_ids`.",
916 ));
917 }
918 if optional_str(&input, "gate")?.is_some() {
919 return Err(ToolError::invalid_input(
920 "`gate` records evidence for a single `task_id` and cannot be used with `task_ids`.",
921 ));
922 }
923 let _ = optional_str(&input, "until")?;
924 if task_ids.as_array().is_some_and(Vec::is_empty) {
925 return Err(ToolError::invalid_input(
926 "`task_ids` must contain at least one background shell task id.",
927 ));
928 }
929 }
930 // The shell cancel action lives on the hidden compatibility tool, which
931 // no model catalog offers. Without this route a model that owns a stuck
932 // background command can watch it but never stop it. The delegate
933 // re-checks deny rules under `exec_shell_cancel` and only kills a task
934 // this session owns.
935 if optional_bool(&input, "cancel", false)? {
936 if optional_str(&input, "gate")?.is_some() {
937 return Err(ToolError::invalid_input(
938 "cancel=true stops the task and cannot record a gate; nothing was stopped. Send `gate` on a separate call without cancel.",
939 ));
940 }
941 return BashTool::alias("exec_shell_cancel", "cancel")
942 .execute(
943 json!({"task_id": required_str(&input, "task_id")?}),
944 context,
945 )
946 .await;
947 }
948 let shell_input = task_shell_wait_input(input.clone());
949 let result = BashTool::alias("exec_shell_wait", "wait")
950 .execute(shell_input, context)
951 .await?;
952 let Some(gate) = optional_str(&input, "gate")? else {
953 return Ok(result);
954 };
955 let status = result
956 .metadata
957 .as_ref()
958 .and_then(|m| m.get("status"))
959 .and_then(Value::as_str)
960 .unwrap_or("Running");
961 if status == "Running" {
962 return Ok(result);
963 }
964 let exit_code = result
965 .metadata
966 .as_ref()
967 .and_then(|m| m.get("exit_code"))
968 .and_then(Value::as_i64)
969 .and_then(|v| i32::try_from(v).ok());
970 let duration_ms = result
971 .metadata
972 .as_ref()
973 .and_then(|m| m.get("duration_ms"))
974 .and_then(Value::as_u64)
975 .unwrap_or_default();
976 let command = optional_str(&input, "command")?.unwrap_or("(background shell)");
977 let log_path = write_runtime_artifact(context, "background_gate", &result.content).await?;
978 let gate_status = if exit_code == Some(0) {
979 "passed"
980 } else if status == "TimedOut" {
981 "timeout"
982 } else {
983 "failed"
984 };
985 let gate_record = TaskGateRecord {
986 id: format!("gate_{}", &Uuid::new_v4().to_string()[..8]),
987 gate: gate.to_string(),
988 command: command.to_string(),
989 cwd: context.workspace.clone(),
990 exit_code,
991 status: gate_status.to_string(),
992 classification: classify_gate_failure(
993 gate,
994 gate_status,
995 status == "TimedOut",
996 &result.content,
997 "",
998 ),
999 duration_ms,
1000 summary: summarize(&result.content, MAX_SUMMARY_CHARS),
1001 log_path: log_path.clone(),
1002 recorded_at: Utc::now(),
1003 };
1004 let mut metadata = result.metadata.clone().unwrap_or_else(|| json!({}));
1005 metadata["background"] = json!(true);
1006 metadata["task_updates"] = json!({
1007 "gate": gate_record,
1008 "artifacts": artifact_updates("background_gate_log", log_path, "Background shell gate output")
1009 });
1010 Ok(result.with_metadata(metadata))
1011 }
1012 }
1013
1014 fn reconcile_task_record(context: &ToolContext, task: &TaskRecord) -> Result<(), ToolError> {
1015 let Some(work) = context.runtime.work.as_ref() else {
1016 return Ok(());
1017 };
1018 let external = format!("task:{}", task.id);
1019 if !work.has_operation_binding(Some(&context.state_namespace), &external) {
1020 return Ok(());
1021 }
1022 work.reconcile_operation(
1023 &context.state_namespace,
1024 task_owner_snapshot(
1025 &task.id,
1026 task.status,
1027 task.lifecycle_seq,
1028 task.created_at,
1029 task.started_at,
1030 task.ended_at,
1031 ),
1032 )
1033 .map(|_| ())
1034 .map_err(ToolError::execution_failed)
1035 }
1036
1037 fn task_result(label: &str, task: &TaskRecord) -> Result<ToolResult, ToolError> {
1038 task_result_with_lifecycle_warning(label, task, None)
1039 }
1040
1041 fn task_result_with_lifecycle_warning(
1042 label: &str,
1043 task: &TaskRecord,
1044 lifecycle_warning: Option<&str>,
1045 ) -> Result<ToolResult, ToolError> {
1046 ToolResult::json(&json!({
1047 "summary": format!("{label}: {} ({:?})", task.id, task.status),
1048 "task": task,
1049 "lifecycle_warning": lifecycle_warning,
1050 "execution_ownership": if task.execution_scope.is_some() { "scope_bound" } else { "unverified" },
1051 }))
1052 .map_err(|e| ToolError::execution_failed(e.to_string()))
1053 }
1054
1055 fn resolve_cwd(context: &ToolContext, raw: Option<&str>) -> Result<PathBuf, ToolError> {
1056 match raw {
1057 Some(path) => {
1058 let resolved = context.resolve_path(path)?;
1059 if resolved.is_dir() {
1060 Ok(resolved)
1061 } else {
1062 Err(ToolError::invalid_input(format!(
1063 "cwd must be a directory: {path}"
1064 )))
1065 }
1066 }
1067 None => Ok(context.workspace.clone()),
1068 }
1069 }
1070
1071 async fn write_runtime_artifact(
1072 context: &ToolContext,
1073 label: &str,
1074 content: &str,
1075 ) -> Result<Option<PathBuf>, ToolError> {
1076 let Some(task_id) = context.runtime.active_task_id.as_deref() else {
1077 return Ok(None);
1078 };
1079 let manager = context.runtime.task_manager.as_ref();
1080 if let Some(manager) = manager {
1081 return manager
1082 .write_task_artifact(task_id, label, content)
1083 .map(Some)
1084 .map_err(|e| ToolError::execution_failed(e.to_string()));
1085 }
1086 let Some(data_dir) = context.runtime.task_data_dir.as_ref() else {
1087 return Ok(None);
1088 };
1089 let artifact_dir = data_dir.join("artifacts").join(task_id);
1090 let filename = format!(
1091 "{}_{}.txt",
1092 Utc::now().format("%Y%m%dT%H%M%S%.3fZ"),
1093 sanitize_filename(label)
1094 );
1095 let absolute = artifact_dir.join(filename);
1096 let content_owned = content.to_owned();
1097 let abs = absolute.clone();
1098 tokio::task::spawn_blocking(move || {
1099 std::fs::create_dir_all(&artifact_dir)?;
1100 std::fs::write(&abs, content_owned)?;
1101 Ok::<(), std::io::Error>(())
1102 })
1103 .await
1104 .map_err(|e| {
1105 // Surface the otherwise-discarded join error for debugging; the
1106 // returned ToolError (and thus user-facing behavior) is unchanged.
1107 tracing::debug!(error = %e, "artifact write spawn_blocking task failed to join");
1108 ToolError::execution_failed(format!("artifact write task panicked: {e}"))
1109 })?
1110 .map_err(|e| ToolError::execution_failed(format!("write artifact: {e}")))?;
1111 Ok(Some(
1112 absolute
1113 .strip_prefix(data_dir)
1114 .map(PathBuf::from)
1115 .unwrap_or(absolute),
1116 ))
1117 }
1118
1119 async fn write_task_artifact_for(
1120 context: &ToolContext,
1121 task_id: &str,
1122 label: &str,
1123 content: &str,
1124 ) -> Result<Option<PathBuf>, ToolError> {
1125 if let Some(manager) = context.runtime.task_manager.as_ref() {
1126 return manager
1127 .write_task_artifact(task_id, label, content)
1128 .map(Some)
1129 .map_err(|e| ToolError::execution_failed(e.to_string()));
1130 }
1131 if context.runtime.active_task_id.as_deref() != Some(task_id) {
1132 return Ok(None);
1133 }
1134 write_runtime_artifact(context, label, content).await
1135 }
1136
1137 fn artifact_updates(label: &str, path: Option<PathBuf>, summary: &str) -> Value {
1138 match path {
1139 Some(path) => json!([TaskArtifactRef {
1140 label: label.to_string(),
1141 path,
1142 summary: summarize(summary, 240),
1143 created_at: Utc::now(),
1144 }]),
1145 None => json!([]),
1146 }
1147 }
1148
1149 async fn read_task_for_input(
1150 input: &Value,
1151 context: &ToolContext,
1152 ) -> Result<TaskRecord, ToolError> {
1153 let manager = context
1154 .runtime
1155 .task_manager
1156 .as_ref()
1157 .ok_or_else(|| ToolError::not_available("TaskManager is not attached"))?;
1158 let task_id = task_id_from_input_or_context(input, context)?;
1159 if context.runtime.active_task_id.as_deref() == Some(task_id.as_str()) {
1160 // Runtime thread construction stamps `active_task_id` from its durable
1161 // thread record. It is not a tool parameter, so an owned task may read
1162 // itself even though its execution engine has a distinct namespace.
1163 manager
1164 .get_task_for_active_runtime(&task_id)
1165 .await
1166 .map_err(|e| ToolError::execution_failed(e.to_string()))
1167 } else {
1168 manager
1169 .get_task_for_owner(&task_id, &context.state_namespace)
1170 .await
1171 .map_err(|e| ToolError::execution_failed(e.to_string()))
1172 }
1173 }
1174
1175 fn task_id_from_input_or_context(
1176 input: &Value,
1177 context: &ToolContext,
1178 ) -> Result<String, ToolError> {
1179 optional_str(input, "task_id")?
1180 .map(ToString::to_string)
1181 .or_else(|| context.runtime.active_task_id.clone())
1182 .ok_or_else(|| {
1183 ToolError::invalid_input("task_id is required when no durable task is active")
1184 })
1185 }
1186
1187 /// The working-tree patch and changed paths an attempt records, read without
1188 /// running repository-configured diff drivers or filters.
1189 async fn attempt_diff(workspace: &Path) -> Result<(String, Vec<String>), ToolError> {
1190 let review = codewhale_dependencies::Git::REVIEW_DIFF_ARGS;
1191 let diff = git_output(
1192 workspace,
1193 &[&["diff", "--binary", "--no-color"][..], &review[..]].concat(),
1194 )
1195 .await?;
1196 let changed_files = git_output(
1197 workspace,
1198 &[&["diff", "--name-only"][..], &review[..]].concat(),
1199 )
1200 .await?
1201 .lines()
1202 .filter(|line| !line.trim().is_empty())
1203 .map(ToString::to_string)
1204 .collect();
1205 Ok((diff, changed_files))
1206 }
1207
1208 async fn git_output(workspace: &Path, args: &[&str]) -> Result<String, ToolError> {
1209 let args_owned: Vec<String> = args.iter().map(|s| (*s).to_owned()).collect();
1210 let cwd = workspace.to_path_buf();
1211 // Reads repository content, so repository-configured filters, fsmonitor
1212 // and hooks stay off.
1213 let out = tokio::task::spawn_blocking(move || {
1214 codewhale_dependencies::Git::review_command(&cwd)
1215 .map_err(|e| std::io::Error::other(format!("{e:#}")))?
1216 .args(&args_owned)
1217 .output()
1218 })
1219 .await
1220 .map_err(|e| {
1221 // Surface the otherwise-discarded join error for debugging; the
1222 // returned ToolError (and thus user-facing behavior) is unchanged.
1223 tracing::debug!(error = %e, "git spawn_blocking task failed to join");
1224 ToolError::execution_failed(format!("git task panicked: {e}"))
1225 })?
1226 .map_err(|e| ToolError::execution_failed(format!("failed to run git: {e}")))?;
1227 if !out.status.success() {
1228 return Err(ToolError::execution_failed(format!(
1229 "git {} failed: {}",
1230 args.join(" "),
1231 String::from_utf8_lossy(&out.stderr).trim()
1232 )));
1233 }
1234 Ok(String::from_utf8_lossy(&out.stdout).trim_end().to_string())
1235 }
1236
1237 fn classify_gate_failure(
1238 gate: &str,
1239 status: &str,
1240 timed_out: bool,
1241 stderr: &str,
1242 stdout: &str,
1243 ) -> String {
1244 if timed_out {
1245 return "timeout".to_string();
1246 }
1247 if status == "passed" {
1248 return "passed".to_string();
1249 }
1250 let haystack = format!("{stderr}\n{stdout}").to_ascii_lowercase();
1251 if haystack.contains("address already in use") || haystack.contains("port") {
1252 "environment_port_binding".to_string()
1253 } else if gate == "clippy" || haystack.contains("warning:") {
1254 "lint_failure".to_string()
1255 } else if gate == "test" || haystack.contains("test result: failed") {
1256 "test_failure".to_string()
1257 } else if haystack.contains("error: could not compile")
1258 || haystack.contains("compilation failed")
1259 {
1260 "compile_error".to_string()
1261 } else {
1262 "environment_or_tooling_failure".to_string()
1263 }
1264 }
1265
1266 fn summarize(text: &str, limit: usize) -> String {
1267 let mut out = String::new();
1268 for (idx, ch) in text.chars().enumerate() {
1269 if idx >= limit.saturating_sub(3) {
1270 out.push_str("...");
1271 return out;
1272 }
1273 if ch.is_control() && ch != '\n' && ch != '\t' {
1274 continue;
1275 }
1276 out.push(ch);
1277 }
1278 if out.trim().is_empty() {
1279 "(no output)".to_string()
1280 } else {
1281 out
1282 }
1283 }
1284
1285 fn sanitize_filename(input: &str) -> String {
1286 let mut out = String::new();
1287 for ch in input.chars() {
1288 if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' {
1289 out.push(ch);
1290 } else {
1291 out.push('_');
1292 }
1293 }
1294 if out.is_empty() {
1295 "artifact".to_string()
1296 } else {
1297 out
1298 }
1299 }
1300
1301 #[cfg(test)]
1302 mod tests {
1303 use super::*;
1304 use crate::tools::spec::ToolSpec;
1305
1306 /// Recording an attempt reads the working-tree patch; repository diff
1307 /// drivers and clean filters must not run, and the patch stays a patch.
1308 #[cfg(unix)]
1309 #[tokio::test]
1310 async fn attempt_diff_runs_no_repository_configured_commands() {
1311 use std::os::unix::fs::PermissionsExt;
1312 let tmp = tempfile::tempdir().expect("tempdir");
1313 let outside = tempfile::tempdir().expect("tempdir");
1314 let marker = outside.path().join("marker");
1315 let script = |name: &str, body: &str| {
1316 let path = outside.path().join(name);
1317 std::fs::write(
1318 &path,
1319 format!("#!/bin/sh\necho {name} >> '{}'\n{body}", marker.display()),
1320 )
1321 .expect("write script");
1322 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).expect("chmod");
1323 path.display().to_string()
1324 };
1325 let clean = script("clean.sh", "cat\n");
1326 let external = script("external.sh", "");
1327 let textconv = script("textconv.sh", "cat \"$1\"\n");
1328 let repo = tmp.path();
1329 let git = |args: &[&str]| {
1330 let status = codewhale_dependencies::Git::status(args, repo).expect("git should spawn");
1331 assert!(status.success(), "git {args:?} failed");
1332 };
1333 git(&["init", "-q"]);
1334 git(&["config", "user.email", "t@example.com"]);
1335 git(&["config", "user.name", "Test"]);
1336 git(&["config", "commit.gpgsign", "false"]);
1337 std::fs::write(
1338 repo.join(".gitattributes"),
1339 "a.md diff=conv\nf.txt filter=x\n",
1340 )
1341 .expect("attrs");
1342 std::fs::write(repo.join("a.md"), "one\n").expect("write");
1343 std::fs::write(repo.join("f.txt"), "one\n").expect("write");
1344 git(&["add", "."]);
1345 git(&["commit", "-q", "-m", "init"]);
1346 git(&["config", "filter.x.clean", &clean]);
1347 git(&["config", "diff.conv.textconv", &textconv]);
1348 std::fs::write(repo.join("a.md"), "two\n").expect("modify");
1349 std::fs::write(repo.join("f.txt"), "two\n").expect("modify");
1350 git(&["config", "diff.external", &external]);
1351
1352 let (diff, changed) = attempt_diff(repo).await.expect("attempt diff");
1353 assert!(
1354 !marker.exists(),
1355 "recording ran a repository-configured command: {}",
1356 std::fs::read_to_string(&marker).unwrap_or_default()
1357 );
1358 assert!(diff.contains("+two"), "{diff}");
1359 assert_eq!(changed, vec!["a.md".to_string(), "f.txt".to_string()]);
1360 }
1361
1362 #[test]
1363 fn create_mode_enum_advertises_neither_operate_nor_yolo() {
1364 let canonical = TasksTool::new("tasks").input_schema();
1365 assert_eq!(
1366 canonical["properties"]["mode"]["enum"],
1367 json!(["agent", "plan"])
1368 );
1369 }
1370
1371 #[test]
1372 fn gate_classifier_detects_timeout() {
1373 assert_eq!(
1374 classify_gate_failure("test", "timeout", true, "", ""),
1375 "timeout"
1376 );
1377 }
1378
1379 #[test]
1380 fn canonical_schema_lists_all_actions_and_union_fields() {
1381 let schema = TasksTool::new("tasks").input_schema();
1382 let actions = schema["properties"]["action"]["enum"]
1383 .as_array()
1384 .expect("action enum");
1385 for action in [
1386 "create",
1387 "list",
1388 "read",
1389 "cancel",
1390 "gate_run",
1391 "pr_attempt_record",
1392 "pr_attempt_list",
1393 "pr_attempt_read",
1394 "pr_attempt_preflight",
1395 ] {
1396 assert!(
1397 actions.iter().any(|value| value.as_str() == Some(action)),
1398 "canonical schema must offer action {action}"
1399 );
1400 }
1401 for field in [
1402 "prompt",
1403 "task_id",
1404 "gate",
1405 "command",
1406 "attempt_id",
1407 "limit",
1408 ] {
1409 assert!(
1410 schema["properties"][field].is_object(),
1411 "canonical schema must carry union field {field}"
1412 );
1413 }
1414 assert_eq!(schema["additionalProperties"], json!(false));
1415 }
1416
1417 #[test]
1418 fn read_only_variant_only_offers_read_actions() {
1419 let tool = TasksTool::read_only("tasks");
1420 let schema = tool.input_schema();
1421 assert_eq!(
1422 schema["properties"]["action"]["enum"],
1423 json!(["list", "read", "pr_attempt_list", "pr_attempt_read"])
1424 );
1425 assert!(!schema["properties"]["prompt"].is_object());
1426 assert!(!schema["properties"]["gate"].is_object());
1427 // pr_attempt_read is a read action: its id field must be advertised
1428 // on the read-only surface too.
1429 assert!(schema["properties"]["attempt_id"].is_object());
1430 assert!(schema["properties"]["task_id"].is_object());
1431 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Auto);
1432 assert!(tool.is_read_only());
1433 assert_eq!(tool.capabilities(), vec![ToolCapability::ReadOnly]);
1434 }
1435
1436 #[test]
1437 fn canonical_routes_approval_and_read_only_by_action() {
1438 let canonical = TasksTool::new("tasks");
1439 assert!(canonical.model_visible());
1440 assert_eq!(
1441 canonical.approval_requirement_for(&json!({"action": "list"})),
1442 ApprovalRequirement::Auto
1443 );
1444 assert_eq!(
1445 canonical.approval_requirement_for(&json!({"action": "cancel"})),
1446 ApprovalRequirement::Required
1447 );
1448 assert_eq!(
1449 canonical.approval_requirement_for(&json!({"action": "gate_run"})),
1450 ApprovalRequirement::Required
1451 );
1452 assert!(canonical.is_read_only_for(&json!({"action": "pr_attempt_read"})));
1453 assert!(!canonical.is_read_only_for(&json!({"action": "create"})));
1454 }
1455
1456 #[test]
1457 fn canonical_rejects_unknown_or_missing_action() {
1458 let tool = TasksTool::new("tasks");
1459 let err = tool
1460 .resolve_action(&json!({}))
1461 .expect_err("missing action must fail");
1462 assert!(err.to_string().contains("missing `action`"));
1463 let err = tool
1464 .resolve_action(&json!({"action": "explode"}))
1465 .expect_err("unknown action must fail");
1466 assert!(err.to_string().contains("invalid action"));
1467
1468 let read_only = TasksTool::read_only("tasks");
1469 let err = read_only
1470 .resolve_action(&json!({"action": "gate_run"}))
1471 .expect_err("read-only surface must reject exec actions");
1472 assert!(err.to_string().contains("invalid action"));
1473 }
1474
1475 #[test]
1476 fn background_shell_schema_is_explicit() {
1477 let wait_schema = TaskShellWaitTool.input_schema();
1478 assert!(wait_schema.get("required").is_none());
1479 assert_eq!(wait_schema["additionalProperties"], false);
1480 assert!(wait_schema["properties"]["task_id"].is_object());
1481 assert_eq!(wait_schema["properties"]["task_ids"]["minItems"], 1);
1482 assert_eq!(
1483 wait_schema["properties"]["until"]["enum"],
1484 json!(["any", "all"])
1485 );
1486 assert!(wait_schema["properties"]["gate"].is_object());
1487 let description = TaskShellWaitTool.description();
1488 assert!(description.contains("task_ids"), "{description}");
1489 assert!(description.contains("until"), "{description}");
1490 }
1491
1492 #[test]
1493 fn runtime_surface_hardening_task_gate_recording_requires_approval() {
1494 let tool = TaskShellWaitTool;
1495 for input in [
1496 json!({"task_id": "shell_1"}),
1497 json!({"task_id": "shell_1", "gate": null}),
1498 ] {
1499 assert_eq!(
1500 tool.approval_requirement_for(&input),
1501 ApprovalRequirement::Auto
1502 );
1503 assert!(tool.is_read_only_for(&input));
1504 }
1505 for gate in ["fmt", "check", "clippy", "test", "custom"] {
1506 let input = json!({"task_id": "shell_1", "gate": gate, "command": "cargo check"});
1507 assert_eq!(
1508 tool.approval_requirement_for(&input),
1509 ApprovalRequirement::Required
1510 );
1511 assert!(!tool.is_read_only_for(&input));
1512 }
1513 assert!(tool.capabilities().contains(&ToolCapability::WritesFiles));
1514 assert!(!tool.is_read_only());
1515 assert!(tool.supports_parallel_for(&json!({"task_ids": ["shell_1", "shell_2"]})));
1516 assert!(!tool.supports_parallel_for(&json!({"task_id": "shell_1", "cancel": true})));
1517 }
1518
1519 #[test]
1520 fn task_shell_wait_keeps_its_documented_nonblocking_default() {
1521 assert_eq!(
1522 task_shell_wait_input(json!({"task_id": "shell_1"}))["wait"],
1523 false
1524 );
1525 assert_eq!(
1526 task_shell_wait_input(json!({"task_id": "shell_1", "wait": true}))["wait"],
1527 true
1528 );
1529 assert_eq!(
1530 task_shell_wait_input(json!({"task_id": "shell_1", "block": true}))["block"],
1531 true
1532 );
1533 assert_eq!(
1534 task_shell_wait_input(json!({"task_id": "shell_1", "wait": null}))["wait"],
1535 false
1536 );
1537 assert_eq!(
1538 task_shell_wait_input(json!({"task_id": "shell_1", "block": null}))["wait"],
1539 false
1540 );
1541 let many_default = task_shell_wait_input(json!({"task_ids": ["shell_1", "shell_2"]}));
1542 assert_eq!(many_default["wait"], false);
1543 assert_eq!(many_default["until"], "any");
1544 let many_all = task_shell_wait_input(
1545 json!({"task_ids": ["shell_1", "shell_2"], "wait": true, "until": "all"}),
1546 );
1547 assert_eq!(many_all["wait"], true);
1548 assert_eq!(many_all["until"], "all");
1549 let single_with_null_many =
1550 task_shell_wait_input(json!({"task_id": "shell_1", "task_ids": null}));
1551 assert_eq!(single_with_null_many["wait"], false);
1552 assert!(single_with_null_many.get("task_ids").is_none());
1553 }
1554
1555 #[tokio::test]
1556 async fn task_shell_wait_null_is_a_nonblocking_snapshot() {
1557 let workspace = tempfile::tempdir().expect("workspace");
1558 let context = ToolContext::new(workspace.path());
1559 let started = BashTool::new("Bash")
1560 .execute(json!({"command": "sleep 2", "background": true}), &context)
1561 .await
1562 .expect("start background shell");
1563 let task_id = started
1564 .metadata
1565 .as_ref()
1566 .and_then(|metadata| metadata.get("task_id"))
1567 .and_then(Value::as_str)
1568 .expect("task id")
1569 .to_string();
1570
1571 let before = std::time::Instant::now();
1572 let snapshot = TaskShellWaitTool
1573 .execute(
1574 json!({"task_id": task_id, "wait": null, "timeout_ms": 5_000}),
1575 &context,
1576 )
1577 .await
1578 .expect("poll background shell");
1579 assert!(
1580 before.elapsed() < std::time::Duration::from_secs(1),
1581 "task_shell_wait wait:null must preserve the nonblocking default"
1582 );
1583 assert_eq!(
1584 snapshot
1585 .metadata
1586 .as_ref()
1587 .and_then(|metadata| metadata.get("status"))
1588 .and_then(Value::as_str),
1589 Some("Running")
1590 );
1591
1592 BashTool::alias("exec_shell_cancel", "cancel")
1593 .execute(json!({"task_id": task_id}), &context)
1594 .await
1595 .expect("cancel background shell");
1596 }
1597
1598 // A foreground command that outlives its wait moves to the background, and
1599 // the model that owns it sees only the task shell tools: the shell cancel
1600 // action is on a hidden tool. `task_shell_wait` has to be able to stop the
1601 // task it polls, and stopping is not a read-only poll.
1602 #[tokio::test]
1603 async fn task_shell_wait_cancel_stops_the_background_task() {
1604 let workspace = tempfile::tempdir().expect("workspace");
1605 let context = ToolContext::new(workspace.path());
1606 let started = BashTool::new("Bash")
1607 .execute(json!({"command": "sleep 30", "background": true}), &context)
1608 .await
1609 .expect("start background shell");
1610 let task_id = started
1611 .metadata
1612 .as_ref()
1613 .and_then(|metadata| metadata.get("task_id"))
1614 .and_then(Value::as_str)
1615 .expect("task id")
1616 .to_string();
1617
1618 let tool = TaskShellWaitTool;
1619 assert!(tool.input_schema()["properties"]["cancel"].is_object());
1620 for held in [json!(true), json!("true"), json!(1)] {
1621 let input = json!({"task_id": task_id, "cancel": held});
1622 assert_eq!(
1623 tool.approval_requirement_for(&input),
1624 ApprovalRequirement::Required,
1625 "{input}"
1626 );
1627 assert!(!tool.is_read_only_for(&input), "{input}");
1628 }
1629 for polled in [json!(false), Value::Null] {
1630 let input = json!({"task_id": task_id, "cancel": polled});
1631 assert!(tool.is_read_only_for(&input), "{input}");
1632 }
1633
1634 let with_gate = tool
1635 .execute(
1636 json!({"task_id": task_id, "cancel": true, "gate": "test"}),
1637 &context,
1638 )
1639 .await
1640 .expect_err("cancel cannot record a gate");
1641 assert!(with_gate.to_string().contains("cancel=true"), "{with_gate}");
1642
1643 let canceled = tool
1644 .execute(json!({"task_id": task_id, "cancel": true}), &context)
1645 .await
1646 .expect("cancel background shell");
1647 assert!(
1648 canceled.content.contains("Canceled background command")
1649 && canceled.content.contains(&task_id),
1650 "{}",
1651 canceled.content
1652 );
1653 assert_eq!(
1654 canceled
1655 .metadata
1656 .as_ref()
1657 .and_then(|metadata| metadata.get("status"))
1658 .and_then(Value::as_str),
1659 Some("Killed")
1660 );
1661 }
1662
1663 #[tokio::test]
1664 async fn task_shell_wait_many_rejects_conflicting_fields() {
1665 let workspace = tempfile::tempdir().expect("workspace");
1666 let context = ToolContext::new(workspace.path());
1667 let tool = TaskShellWaitTool;
1668
1669 assert!(tool.is_read_only_for(&json!({
1670 "task_ids": ["shell_1", "shell_2"],
1671 "wait": true,
1672 "until": "all"
1673 })));
1674 assert_eq!(
1675 tool.approval_requirement_for(&json!({
1676 "task_ids": ["shell_1", "shell_2"],
1677 "wait": true,
1678 "until": "all"
1679 })),
1680 ApprovalRequirement::Auto
1681 );
1682
1683 let both = tool
1684 .execute(
1685 json!({"task_id": "shell_1", "task_ids": ["shell_1", "shell_2"]}),
1686 &context,
1687 )
1688 .await
1689 .expect_err("task_id and task_ids must be mutually exclusive");
1690 assert!(both.to_string().contains("not both"), "{both}");
1691
1692 let with_cancel = tool
1693 .execute(json!({"task_ids": ["shell_1"], "cancel": true}), &context)
1694 .await
1695 .expect_err("cancel=true cannot be combined with task_ids");
1696 assert!(
1697 with_cancel.to_string().contains("cancel=true"),
1698 "{with_cancel}"
1699 );
1700
1701 let with_gate = tool
1702 .execute(json!({"task_ids": ["shell_1"], "gate": "test"}), &context)
1703 .await
1704 .expect_err("gate cannot be combined with task_ids");
1705 assert!(with_gate.to_string().contains("gate"), "{with_gate}");
1706
1707 let empty = tool
1708 .execute(json!({"task_ids": []}), &context)
1709 .await
1710 .expect_err("empty task_ids must fail");
1711 assert!(empty.to_string().contains("task_ids"), "{empty}");
1712 }
1713
1714 #[tokio::test]
1715 async fn task_shell_wait_many_supports_snapshot_any_and_all() {
1716 let workspace = tempfile::tempdir().expect("workspace");
1717 let context = ToolContext::new(workspace.path());
1718 let tool = TaskShellWaitTool;
1719
1720 let fast = BashTool::new("Bash")
1721 .execute(
1722 json!({"command": "printf 'fast\\n'", "background": true}),
1723 &context,
1724 )
1725 .await
1726 .expect("start fast background shell");
1727 let slow = BashTool::new("Bash")
1728 .execute(json!({"command": "sleep 30", "background": true}), &context)
1729 .await
1730 .expect("start slow background shell");
1731 let fast_id = fast
1732 .metadata
1733 .as_ref()
1734 .and_then(|metadata| metadata.get("task_id"))
1735 .and_then(Value::as_str)
1736 .expect("fast id")
1737 .to_string();
1738 let slow_id = slow
1739 .metadata
1740 .as_ref()
1741 .and_then(|metadata| metadata.get("task_id"))
1742 .and_then(Value::as_str)
1743 .expect("slow id")
1744 .to_string();
1745
1746 let before_snapshot = std::time::Instant::now();
1747 let snapshot = tool
1748 .execute(
1749 json!({"task_ids": [fast_id, slow_id], "timeout_ms": 5_000}),
1750 &context,
1751 )
1752 .await
1753 .expect("snapshot multi wait");
1754 assert!(
1755 before_snapshot.elapsed() < std::time::Duration::from_secs(1),
1756 "omitted wait must stay nonblocking for task_ids"
1757 );
1758 assert_eq!(
1759 snapshot.metadata.as_ref().and_then(|m| m.get("until")),
1760 Some(&json!("any"))
1761 );
1762
1763 let before_any = std::time::Instant::now();
1764 let any_result = tool
1765 .execute(
1766 json!({"task_ids": [fast_id, slow_id], "wait": true, "timeout_ms": 5_000}),
1767 &context,
1768 )
1769 .await
1770 .expect("until=any default wait");
1771 assert!(
1772 before_any.elapsed() < std::time::Duration::from_secs(3),
1773 "default until=any must return as soon as one task completes"
1774 );
1775 let any_meta = any_result.metadata.as_ref().expect("metadata");
1776 assert_eq!(any_meta["until"], json!("any"));
1777 assert_eq!(any_meta["timed_out"], json!(false));
1778 assert_eq!(any_meta["statuses"][fast_id.as_str()], json!("Completed"));
1779 assert_eq!(any_meta["statuses"][slow_id.as_str()], json!("Running"));
1780
1781 BashTool::alias("exec_shell_cancel", "cancel")
1782 .execute(json!({"task_id": slow_id}), &context)
1783 .await
1784 .expect("cancel slow background shell");
1785
1786 let first = BashTool::new("Bash")
1787 .execute(
1788 json!({"command": "printf 'one\\n'", "background": true}),
1789 &context,
1790 )
1791 .await
1792 .expect("start first background shell");
1793 let second = BashTool::new("Bash")
1794 .execute(json!({"command": "sleep 1", "background": true}), &context)
1795 .await
1796 .expect("start second background shell");
1797 let first_id = first
1798 .metadata
1799 .as_ref()
1800 .and_then(|metadata| metadata.get("task_id"))
1801 .and_then(Value::as_str)
1802 .expect("first id")
1803 .to_string();
1804 let second_id = second
1805 .metadata
1806 .as_ref()
1807 .and_then(|metadata| metadata.get("task_id"))
1808 .and_then(Value::as_str)
1809 .expect("second id")
1810 .to_string();
1811
1812 let all_result = tool
1813 .execute(
1814 json!({
1815 "task_ids": [first_id, second_id],
1816 "wait": true,
1817 "until": "all",
1818 "timeout_ms": 8_000
1819 }),
1820 &context,
1821 )
1822 .await
1823 .expect("until=all wait");
1824 let all_meta = all_result.metadata.as_ref().expect("metadata");
1825 assert_eq!(all_meta["until"], json!("all"));
1826 assert_eq!(all_meta["timed_out"], json!(false));
1827 assert_eq!(all_meta["statuses"][first_id.as_str()], json!("Completed"));
1828 assert_eq!(all_meta["statuses"][second_id.as_str()], json!("Completed"));
1829 }
1830
1831 async fn noop_task_manager(
1832 workspace: &std::path::Path,
1833 ) -> crate::task_manager::SharedTaskManager {
1834 struct NoopExecutor;
1835
1836 #[async_trait::async_trait]
1837 impl crate::task_manager::TaskExecutor for NoopExecutor {
1838 async fn execute(
1839 &self,
1840 _task: crate::task_manager::ExecutionTask,
1841 _events: tokio::sync::mpsc::Sender<crate::task_manager::TaskExecutionEvent>,
1842 _cancel: tokio_util::sync::CancellationToken,
1843 ) -> crate::task_manager::TaskExecutionResult {
1844 crate::task_manager::TaskExecutionResult {
1845 status: crate::task_manager::TaskStatus::Completed,
1846 result_text: Some("noop".to_string()),
1847 error: None,
1848 terminal_reason: crate::task_manager::TaskTerminalReason::Completed,
1849 }
1850 }
1851 }
1852
1853 crate::task_manager::TaskManager::start_with_executor(
1854 crate::task_manager::TaskManagerConfig {
1855 data_dir: workspace.to_path_buf(),
1856 worker_count: 1,
1857 default_workspace: workspace.to_path_buf(),
1858 default_model: "deepseek-v4-pro".to_string(),
1859 default_mode: "agent".to_string(),
1860 allow_shell: false,
1861 trust_mode: false,
1862 execution_limits: crate::task_manager::TaskExecutionLimits::default(),
1863 human_waits_answerable: false,
1864 },
1865 std::sync::Arc::new(NoopExecutor),
1866 )
1867 .await
1868 .expect("task manager")
1869 }
1870
1871 #[tokio::test]
1872 async fn create_carries_the_session_deny_rules_onto_the_task_and_its_thread() {
1873 let workspace = tempfile::tempdir().expect("workspace");
1874 let manager = noop_task_manager(workspace.path()).await;
1875 let mut context = ToolContext::new(workspace.path());
1876 context.shell_policy = codewhale_agent_contract::worker_profile::ShellPolicy::None;
1877 context.disallowed_tools = vec!["mcp_secret_*".to_string()];
1878 context.runtime.task_manager = Some(manager.clone());
1879
1880 TasksTool::new("tasks")
1881 .execute(json!({"action": "create", "prompt": "probe"}), &context)
1882 .await
1883 .expect("create accepted");
1884
1885 let queued = manager.list_tasks(Some(1)).await.expect("queued task");
1886 let created = manager.get_task(&queued[0].id).await.expect("created task");
1887 let record = serde_json::to_value(&created).expect("record json");
1888 assert_eq!(record["disallowed_tools"], json!(["mcp_secret_*"]));
1889 let thread = serde_json::to_value(
1890 crate::task_manager::ExecutionTask::from(&created).thread_request(),
1891 )
1892 .expect("thread request json");
1893 assert_eq!(thread["disallowed_tools"], json!(["mcp_secret_*"]));
1894 }
1895
1896 /// Creating a task from a session runs it on the posture that session
1897 /// holds: `auto_approve` is a legacy bit the engine only reads when no
1898 /// posture is given, so a task cannot talk itself into more authority than
1899 /// the session that asked for it was granted.
1900 #[tokio::test]
1901 async fn create_pins_the_session_posture_on_the_task() {
1902 let workspace = tempfile::tempdir().expect("workspace");
1903 let manager = noop_task_manager(workspace.path()).await;
1904
1905 let mut context = ToolContext::new(workspace.path());
1906 context.approval_mode = codewhale_execpolicy::ApprovalMode::Auto;
1907 context.shell_policy = codewhale_agent_contract::worker_profile::ShellPolicy::None;
1908 context.runtime.task_manager = Some(manager.clone());
1909
1910 TasksTool::new("tasks")
1911 .execute(
1912 json!({
1913 "action": "create",
1914 "prompt": "run the sweep",
1915 "auto_approve": true,
1916 "trust_mode": true,
1917 "allow_shell": true,
1918 "mode": "yolo"
1919 }),
1920 &context,
1921 )
1922 .await
1923 .expect("create accepted");
1924
1925 let queued = manager.list_tasks(Some(1)).await.expect("queued task");
1926 let created = manager.get_task(&queued[0].id).await.expect("created task");
1927 assert_eq!(
1928 created.permission_posture.as_deref(),
1929 Some("auto_review"),
1930 "the task runs under its session's posture, not the model's legacy bit"
1931 );
1932 // Requested authority the session does not hold is not stored.
1933 assert!(!created.auto_approve);
1934 assert!(!created.trust_mode);
1935 assert!(!created.allow_shell);
1936
1937 // The turn the task starts runs under the pinned posture: neither the
1938 // legacy bit nor a legacy full-access mode alias can re-derive one.
1939 let turn = crate::task_manager::ExecutionTask::from(&created).turn_request();
1940 assert_eq!(turn.permission_posture.as_deref(), Some("auto_review"));
1941 assert_eq!(turn.auto_approve, None);
1942 let policy = codewhale_runtime::runtime_policy::RuntimePolicyProjection::from_request(
1943 turn.mode.as_deref().expect("mode"),
1944 turn.permission_posture.as_deref(),
1945 turn.auto_approve,
1946 )
1947 .expect("policy");
1948 assert_eq!(policy.permission, codewhale_execpolicy::ApprovalMode::Auto);
1949
1950 // A workspace outside what the session can reach is refused.
1951 let outside = TasksTool::new("tasks")
1952 .execute(
1953 json!({"action": "create", "prompt": "look", "workspace": "/"}),
1954 &context,
1955 )
1956 .await;
1957 assert!(
1958 outside.is_err(),
1959 "a workspace outside the session is refused"
1960 );
1961 }
1962
1963 #[cfg(unix)]
1964 #[tokio::test]
1965 async fn timed_out_gate_run_kills_the_gate_process_tree() {
1966 let workspace = tempfile::tempdir().expect("workspace");
1967 let context = ToolContext::new(workspace.path())
1968 .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::Full);
1969 let result = TasksTool::new("tasks")
1970 .execute(
1971 json!({
1972 "action": "gate_run",
1973 "gate": "test",
1974 "command": "echo gate-started; sleep 300 & echo $! > gate-child.pid; wait",
1975 "timeout_ms": 5_000
1976 }),
1977 &context,
1978 )
1979 .await
1980 .expect("gate runs");
1981 assert!(!result.success, "a timed-out gate must not report success");
1982 let metadata = result.metadata.expect("metadata");
1983 assert_eq!(metadata["timed_out"], true, "{metadata}");
1984 // What the gate wrote before the timeout is kept.
1985 assert!(
1986 result.content.contains("gate-started"),
1987 "{}",
1988 result.content
1989 );
1990 let child = codewhale_runtime::process_tree::read_pid_file(
1991 &workspace.path().join("gate-child.pid"),
1992 std::time::Duration::from_secs(5),
1993 );
1994 assert!(
1995 codewhale_runtime::process_tree::wait_for_pid_exit(
1996 child,
1997 std::time::Duration::from_secs(5)
1998 ),
1999 "the timed-out gate's process is still running"
2000 );
2001 }
2002
2003 #[cfg(unix)]
2004 #[tokio::test]
2005 async fn gate_run_reports_success_only_when_gate_passes() {
2006 let workspace = tempfile::tempdir().expect("workspace");
2007 let context = ToolContext::new(workspace.path())
2008 .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::Full);
2009
2010 let failed = TasksTool::new("tasks")
2011 .execute(
2012 json!({
2013 "action": "gate_run",
2014 "gate": "test",
2015 "command": "echo failing-gate >&2; exit 1"
2016 }),
2017 &context,
2018 )
2019 .await
2020 .expect("failed gate returns ToolResult");
2021 assert!(
2022 !failed.success,
2023 "a non-zero gate exit must return ToolResult.success == false"
2024 );
2025 let failed_body: Value = serde_json::from_str(&failed.content).expect("json body");
2026 assert_eq!(failed_body["gate"]["status"], "failed");
2027 assert_eq!(failed_body["gate"]["exit_code"], 1);
2028
2029 let passed = TasksTool::new("tasks")
2030 .execute(
2031 json!({
2032 "action": "gate_run",
2033 "gate": "test",
2034 "command": "echo ok"
2035 }),
2036 &context,
2037 )
2038 .await
2039 .expect("passing gate returns ToolResult");
2040 assert!(
2041 passed.success,
2042 "a zero-exit gate must return ToolResult.success == true"
2043 );
2044 let passed_body: Value = serde_json::from_str(&passed.content).expect("json body");
2045 assert_eq!(passed_body["gate"]["status"], "passed");
2046 assert_eq!(passed_body["gate"]["exit_code"], 0);
2047 }
2048
2049 #[test]
2050 fn gate_command_uses_non_login_shell_invocation() {
2051 // A login shell would source profile files that can re-export
2052 // credentials the sanitized child environment just removed.
2053 let (program, args) = build_gate_command_parts("echo hello");
2054 assert_eq!(program, "/bin/sh");
2055 assert_eq!(args, vec!["-c".to_string(), "echo hello".to_string()]);
2056 }
2057
2058 /// A gate command is workspace code: under a read-only posture it either
2059 /// runs inside the enforcing sandbox, where its write fails, or is refused
2060 /// outright where no enforcing sandbox exists. It never runs raw.
2061 #[cfg(unix)]
2062 #[tokio::test]
2063 async fn gate_command_is_confined_by_the_session_sandbox() {
2064 let tmp = crate::test_support::sandbox_visible_tempdir();
2065 let written = tmp.path().join("written-by-gate.txt");
2066 let mut context = ToolContext::new(tmp.path());
2067 context.elevated_sandbox_policy = Some(codewhale_sandbox::SandboxPolicy::read_only());
2068 let command = format!(
2069 "printf ran; printf x > '{}' 2>/dev/null; true",
2070 written.display()
2071 );
2072 match build_gate_command(
2073 &command,
2074 tmp.path(),
2075 &context,
2076 std::time::Duration::from_secs(30),
2077 ) {
2078 Ok(mut cmd) => {
2079 let output = cmd.output().await.expect("sandboxed gate command runs");
2080 assert_eq!(String::from_utf8_lossy(&output.stdout), "ran");
2081 }
2082 Err(error) => assert!(
2083 error.to_string().contains("nothing was run"),
2084 "only a missing enforcing sandbox may refuse: {error}"
2085 ),
2086 }
2087 assert!(!written.exists(), "a read-only posture must stop the write");
2088 }
2089
2090 #[cfg(unix)]
2091 #[tokio::test]
2092 async fn gate_command_does_not_inherit_parent_secret_env() {
2093 use crate::test_support::{EnvVarGuard, lock_test_env};
2094 let _env_lock = lock_test_env();
2095 let _secret = EnvVarGuard::set("CODEWHALE_TEST_GATE_SECRET", "gate-secret-value");
2096 let tmp = tempfile::tempdir().expect("tempdir");
2097 let output = build_gate_command(
2098 "printf 'secret=%s\\n' \"${CODEWHALE_TEST_GATE_SECRET-unset}\"; printf 'path-ok\\n'",
2099 tmp.path(),
2100 &ToolContext::new(tmp.path()),
2101 std::time::Duration::from_secs(30),
2102 )
2103 .expect("gate command builds")
2104 .output()
2105 .await
2106 .expect("gate command runs");
2107 let stdout = String::from_utf8_lossy(&output.stdout);
2108 assert!(output.status.success(), "{stdout}");
2109 assert!(stdout.contains("secret=unset"), "{stdout}");
2110 assert!(!stdout.contains("gate-secret-value"), "{stdout}");
2111 assert!(stdout.contains("path-ok"), "{stdout}");
2112 }
2113 }
2114
2114 lines RUST