返回 CodeWhale
executor.rs
根目录 / crates / engine / src / fleet / executor.rs
1 //! Fleet executor — runs a Fleet worker as a real `codewhale exec` subprocess.
2 //!
3 //! A Fleet worker IS a headless `codewhale exec` run. There is no separate
4 //! "Fleet worker" execution engine: the sub-agent runtime, full tool surface,
5 //! and recursion depth all come from the one `codewhale exec` runtime, so
6 //! Fleets and sub-agents are one substrate (not two moving targets).
7 //!
8 //! This module is the bridge:
9 //! - [`build_worker_exec_command`] turns a `FleetTaskSpec` + `FleetExecConfig`
10 //! into the `codewhale [route flags] exec --output-format stream-json …`
11 //! argv that a host adapter ([`super::host`]) launches locally or over SSH.
12 //! - [`map_exec_stream_line`] maps one stream-json line emitted by that worker
13 //! into a [`FleetWorkerEventPayload`] for the durable ledger, so the ledger
14 //! persists the worker's own event vocabulary instead of a simulated one.
15 //! - [`classify_worker_exit`] turns the process exit into a terminal event.
16 //!
17 //! The TUI/CLI/Runtime API observe the ledger's compact event stream — they
18 //! never render a child session, which is what keeps the orchestrator light at
19 //! high fanout.
20
21 use anyhow::Result;
22 use codewhale_config::FleetExecConfig;
23 use codewhale_protocol::fleet::{
24 FleetHostSpec, FleetReceipt, FleetResolvedRoute, FleetTaskSpec, FleetWorkerEventPayload,
25 };
26
27 use super::host::{FleetHostAdapter, FleetWorkerCommand};
28 use super::profile::AgentProfile;
29 use super::task_spec::FleetWorkerFinalAnswer;
30 use super::worker_runtime::{
31 ResolvedFleetWorkerRuntime, fleet_task_prompt, fleet_task_prompt_with_profiles,
32 fleet_worker_launch_external_agent, fleet_worker_launch_reasoning_effort,
33 fleet_worker_launch_route,
34 };
35 use crate::tools::spec::{
36 ToolAuthorityEnvelope, ToolMutationAuthority, ToolShellAuthority, ToolVerificationAuthority,
37 };
38 use crate::tools::subagent::AgentWorkerSpec;
39 use codewhale_agent_contract::role::FleetRole;
40
41 #[derive(Clone, Copy, Default)]
42 struct WorkerExecRoute<'a> {
43 model: Option<&'a str>,
44 provider: Option<&'a str>,
45 reasoning_effort: Option<&'a str>,
46 external_agent: Option<&'a str>,
47 external_agent_transport: Option<&'a str>,
48 }
49
50 #[derive(Clone, Copy, Default)]
51 struct WorkerExecLimits {
52 max_turns: Option<u32>,
53 max_tool_calls: Option<u32>,
54 }
55
56 /// Resolve the executable used for Fleet worker subprocesses.
57 ///
58 /// Kept here so every long-lived surface (CLI and Runtime API) launches the
59 /// same configured worker binary instead of silently diverging.
60 pub fn configured_codewhale_binary() -> String {
61 std::env::var("CODEWHALE_FLEET_CODEWHALE_BINARY")
62 .ok()
63 .map(|value| value.trim().to_string())
64 .filter(|value| !value.is_empty())
65 .or_else(|| {
66 let exe = std::env::current_exe().ok()?;
67 let stem = exe.file_stem()?.to_str()?;
68 let cli = matches!(stem, "codewhale" | "codew")
69 || stem.starts_with("codewhale-")
70 || stem.starts_with("codew-");
71 cli.then(|| exe.to_string_lossy().into_owned())
72 })
73 .unwrap_or_else(|| "codewhale".to_string())
74 }
75
76 /// Build the `codewhale exec` argv that runs a fleet task headlessly.
77 ///
78 /// `--auto` is always passed: a headless worker has no human to approve tool
79 /// calls, so it runs with full (policy-gated) tool access. `--output-format
80 /// stream-json` makes the worker emit the NDJSON event stream this module
81 /// parses. A worker launched with the v0.9.1 machine-readable outer authority
82 /// cap is a truthful leaf (`max_spawn_depth = 0`): the nested-agent surface is
83 /// disabled until authority scopes can be intersected across
84 /// process/workspace boundaries.
85 ///
86 /// Secrets are NEVER placed on the argv: provider credentials are resolved by
87 /// the worker process from its own config/keyring exactly like an interactive
88 /// run. The host adapter additionally refuses secret-bearing env keys. The
89 /// `--provider` flag threaded by [`build_worker_exec_command_with_profiles`] is
90 /// a non-secret provider *identifier* only (#4093) — the worker still resolves
91 /// that provider's credentials from its own env/config, so this invariant
92 /// holds.
93 pub fn build_worker_exec_command(
94 codewhale_binary: &str,
95 task_spec: &FleetTaskSpec,
96 exec_config: &FleetExecConfig,
97 model: Option<&str>,
98 ) -> FleetWorkerCommand {
99 let (external_agent, external_agent_transport) =
100 fleet_worker_launch_external_agent(task_spec, &[]);
101 let max_turns = effective_task_max_turns(task_spec, exec_config);
102 let max_tool_calls = task_max_tool_calls(task_spec);
103 build_worker_exec_command_from_prompt(
104 codewhale_binary,
105 fleet_task_prompt(task_spec),
106 exec_config,
107 WorkerExecRoute {
108 model,
109 external_agent: external_agent.as_deref(),
110 external_agent_transport: external_agent_transport.as_deref(),
111 ..WorkerExecRoute::default()
112 },
113 None,
114 WorkerExecLimits {
115 max_turns,
116 max_tool_calls,
117 },
118 )
119 }
120
121 /// Build a worker command after resolving workspace Fleet profile input.
122 ///
123 /// The launched subprocess runs on the worker's RESOLVED route, not blindly on
124 /// the run-level session model (#4093 AC #4): the per-worker model+provider are
125 /// resolved from the task's agent profile via the same explicit-only path the
126 /// receipt uses ([`fleet_worker_launch_route`]). A worker whose profile pins
127 /// provider B thus launches on provider B's model even when the parent session
128 /// is on provider A. Workers with no profile-bound provider fall back to the
129 /// run-level model and emit no `--provider`, so the worker keeps its own
130 /// session default (today's behavior, unchanged).
131 pub fn build_worker_exec_command_with_profiles(
132 codewhale_binary: &str,
133 task_spec: &FleetTaskSpec,
134 exec_config: &FleetExecConfig,
135 model: Option<&str>,
136 agent_profiles: &[AgentProfile],
137 ) -> Result<FleetWorkerCommand> {
138 let (worker_model, worker_provider) =
139 fleet_worker_launch_route(task_spec, agent_profiles, model.unwrap_or_default());
140 let worker_reasoning_effort = fleet_worker_launch_reasoning_effort(task_spec, agent_profiles);
141 let (external_agent, external_agent_transport) =
142 fleet_worker_launch_external_agent(task_spec, agent_profiles);
143 let max_turns = effective_task_max_turns(task_spec, exec_config);
144 let max_tool_calls = task_max_tool_calls(task_spec);
145 Ok(build_worker_exec_command_from_prompt(
146 codewhale_binary,
147 fleet_task_prompt_with_profiles(task_spec, agent_profiles)?,
148 exec_config,
149 WorkerExecRoute {
150 model: Some(worker_model.as_str()),
151 provider: worker_provider.as_deref(),
152 reasoning_effort: worker_reasoning_effort.as_deref(),
153 external_agent: external_agent.as_deref(),
154 external_agent_transport: external_agent_transport.as_deref(),
155 },
156 None,
157 WorkerExecLimits {
158 max_turns,
159 max_tool_calls,
160 },
161 ))
162 }
163
164 /// Build the exact Fleet subprocess command from the coordination-registered
165 /// worker spec. Unlike the compatibility helpers above, production dispatch
166 /// uses the projected objective and carries a machine-readable outer authority
167 /// envelope into the child process.
168 pub fn build_worker_exec_command_with_launch_spec(
169 codewhale_binary: &str,
170 task_spec: &FleetTaskSpec,
171 launch_spec: &AgentWorkerSpec,
172 exec_config: &FleetExecConfig,
173 model: Option<&str>,
174 agent_profiles: &[AgentProfile],
175 ) -> Result<FleetWorkerCommand> {
176 build_worker_exec_command_with_admitted_route(
177 codewhale_binary,
178 task_spec,
179 launch_spec,
180 exec_config,
181 model,
182 agent_profiles,
183 None,
184 )
185 }
186
187 pub(super) fn build_worker_exec_command_with_admitted_route(
188 codewhale_binary: &str,
189 task_spec: &FleetTaskSpec,
190 launch_spec: &AgentWorkerSpec,
191 exec_config: &FleetExecConfig,
192 model: Option<&str>,
193 agent_profiles: &[AgentProfile],
194 admitted: Option<&FleetResolvedRoute>,
195 ) -> Result<FleetWorkerCommand> {
196 let (worker_model, worker_provider) = admitted.map_or_else(
197 || fleet_worker_launch_route(task_spec, agent_profiles, model.unwrap_or_default()),
198 |route| (route.wire_model_id.clone(), Some(route.provider_id.clone())),
199 );
200 let worker_reasoning_effort = fleet_worker_launch_reasoning_effort(task_spec, agent_profiles);
201 let (external_agent, external_agent_transport) =
202 fleet_worker_launch_external_agent(task_spec, agent_profiles);
203 let authority = authority_envelope_for_worker(launch_spec, task_spec)?;
204 // Production dispatch receives an already-hardened launch spec from the
205 // Fleet manager. Its positive max_steps value has therefore already been
206 // intersected with a positive FleetExecConfig.max_turns; zero remains the
207 // explicit unbounded sentinel.
208 let max_turns = (launch_spec.max_steps > 0).then_some(launch_spec.max_steps);
209 let max_tool_calls = task_max_tool_calls(task_spec);
210 Ok(build_worker_exec_command_from_prompt(
211 codewhale_binary,
212 launch_spec.objective.clone(),
213 exec_config,
214 WorkerExecRoute {
215 model: Some(worker_model.as_str()),
216 provider: worker_provider.as_deref(),
217 reasoning_effort: worker_reasoning_effort.as_deref(),
218 external_agent: external_agent.as_deref(),
219 external_agent_transport: external_agent_transport.as_deref(),
220 },
221 Some(&authority),
222 WorkerExecLimits {
223 max_turns,
224 max_tool_calls,
225 },
226 ))
227 }
228
229 pub fn build_worker_exec_command_for_runtime(
230 codewhale_binary: &str,
231 runtime: &ResolvedFleetWorkerRuntime,
232 exec_config: &FleetExecConfig,
233 ) -> FleetWorkerCommand {
234 build_worker_exec_command_from_prompt(
235 codewhale_binary,
236 runtime.launch_spec.objective.clone(),
237 exec_config,
238 WorkerExecRoute {
239 model: Some(runtime.route.model.as_str()),
240 provider: runtime.route.provider.as_deref(),
241 reasoning_effort: runtime.route.reasoning_effort.as_deref(),
242 external_agent: runtime.route.external_agent.as_deref(),
243 external_agent_transport: runtime.route.external_agent_transport.as_deref(),
244 },
245 Some(&runtime.authority),
246 WorkerExecLimits {
247 max_turns: runtime.max_turns,
248 max_tool_calls: runtime.max_tool_calls,
249 },
250 )
251 }
252
253 fn task_max_steps(task_spec: &FleetTaskSpec) -> Option<u32> {
254 task_spec
255 .budget
256 .as_ref()
257 .and_then(|budget| budget.max_steps)
258 .filter(|max_steps| *max_steps > 0)
259 }
260
261 fn task_max_tool_calls(task_spec: &FleetTaskSpec) -> Option<u32> {
262 task_spec
263 .budget
264 .as_ref()
265 .and_then(|budget| budget.max_tool_calls)
266 .filter(|max_tool_calls| *max_tool_calls > 0)
267 }
268
269 fn effective_task_max_turns(
270 task_spec: &FleetTaskSpec,
271 exec_config: &FleetExecConfig,
272 ) -> Option<u32> {
273 match (task_max_steps(task_spec), exec_config.max_turns) {
274 (Some(task_max_steps), fleet_max_turns) if fleet_max_turns > 0 => {
275 Some(task_max_steps.min(fleet_max_turns))
276 }
277 (Some(task_max_steps), _) => Some(task_max_steps),
278 (None, fleet_max_turns) if fleet_max_turns > 0 => Some(fleet_max_turns),
279 (None, _) => None,
280 }
281 }
282
283 pub fn authority_envelope_for_worker(
284 spec: &AgentWorkerSpec,
285 task_spec: &FleetTaskSpec,
286 ) -> Result<ToolAuthorityEnvelope> {
287 let (authority, writable_roots, writable_files, coordination_contracts) =
288 if spec.runtime_profile.permissions.write {
289 let manifest = spec.launch_manifest.as_ref().ok_or_else(|| {
290 anyhow::anyhow!(
291 "write-capable Fleet worker '{}' has no launch manifest",
292 spec.worker_id
293 )
294 })?;
295 (
296 ToolMutationAuthority::ScopedWrite,
297 super::worker_runtime::fleet_runtime_write_roots(task_spec)?,
298 manifest.writable_files.clone(),
299 manifest.coordination_contracts.clone(),
300 )
301 } else {
302 (
303 ToolMutationAuthority::ReadOnly,
304 Vec::new(),
305 Vec::new(),
306 Vec::new(),
307 )
308 };
309 let shell = if authority == ToolMutationAuthority::ReadOnly
310 && matches!(
311 &spec.agent_type,
312 FleetRole::Scout | FleetRole::Reviewer | FleetRole::Planner
313 )
314 && spec.runtime_profile.shell.allows_shell()
315 {
316 // Scout, Reviewer, and Planner get one classifier-bounded
317 // foreground shell. Verifiers keep the dedicated Run surface,
318 // consultants remain shell-less, and writers retain the historical
319 // subprocess contract.
320 ToolShellAuthority::ReadOnly
321 } else {
322 ToolShellAuthority::None
323 };
324 let verification = if authority == ToolMutationAuthority::ReadOnly
325 && matches!(&spec.agent_type, FleetRole::Verifier)
326 && spec.runtime_profile.shell.allows_shell()
327 {
328 ToolVerificationAuthority::Bounded
329 } else {
330 ToolVerificationAuthority::None
331 };
332 ToolAuthorityEnvelope {
333 schema_version: 1,
334 owner: spec.worker_id.clone(),
335 authority,
336 network_access: Some(spec.runtime_profile.permissions.network),
337 shell,
338 verification,
339 writable_roots,
340 writable_files,
341 coordination_contracts,
342 }
343 .normalized()
344 .map_err(anyhow::Error::msg)
345 }
346
347 fn build_worker_exec_command_from_prompt(
348 codewhale_binary: &str,
349 task_prompt: String,
350 exec_config: &FleetExecConfig,
351 route: WorkerExecRoute<'_>,
352 authority: Option<&ToolAuthorityEnvelope>,
353 limits: WorkerExecLimits,
354 ) -> FleetWorkerCommand {
355 let mut args: Vec<String> = Vec::new();
356
357 if let Some(agent_id) = route
358 .external_agent
359 .map(str::trim)
360 .filter(|id| !id.is_empty())
361 {
362 args.push("--agent".to_string());
363 args.push(agent_id.to_string());
364 if let Some(transport) = route
365 .external_agent_transport
366 .map(str::trim)
367 .filter(|t| !t.is_empty())
368 {
369 args.push("--agent-transport".to_string());
370 args.push(transport.to_string());
371 }
372 if let Some(model) = route
373 .model
374 .map(str::trim)
375 .filter(|m| !m.is_empty() && !m.eq_ignore_ascii_case("auto"))
376 {
377 args.push("--model".to_string());
378 args.push(model.to_string());
379 }
380 let read_only =
381 authority.is_some_and(|envelope| envelope.authority == ToolMutationAuthority::ReadOnly);
382 if read_only {
383 args.push("--permission-mode".to_string());
384 args.push("plan".to_string());
385 }
386 args.push("exec".to_string());
387 if !read_only {
388 args.push("--auto".to_string());
389 }
390 args.extend([
391 "--output-format".to_string(),
392 "stream-json".to_string(),
393 "--parent-death-watch".to_string(),
394 ]);
395 if let Some(reasoning_effort) = route
396 .reasoning_effort
397 .map(str::trim)
398 .filter(|e| !e.is_empty())
399 {
400 args.push("--reasoning-effort".to_string());
401 args.push(reasoning_effort.to_string());
402 }
403 args.push(task_prompt);
404 return FleetWorkerCommand::new(codewhale_binary.to_string(), args);
405 }
406
407 // The canonical `codewhale` dispatcher owns these route overrides as
408 // global flags and deliberately rejects them after `exec`. Keep them in
409 // front of the subcommand so Fleet commands work through the installed
410 // dispatcher as well as when a host points directly at `codewhale-tui`.
411 if let Some(model) = route.model.map(str::trim).filter(|m| !m.is_empty()) {
412 args.push("--model".to_string());
413 args.push(model.to_string());
414 }
415
416 if let Some(provider) = route.provider.map(str::trim).filter(|p| !p.is_empty()) {
417 args.push("--provider".to_string());
418 args.push(provider.to_string());
419 }
420
421 args.extend([
422 "exec".to_string(),
423 "--auto".to_string(),
424 "--output-format".to_string(),
425 "stream-json".to_string(),
426 // R7: the worker shuts itself down when the manager dies (stdin EOF).
427 "--parent-death-watch".to_string(),
428 ]);
429
430 // Non-secret thinking tier only (#4137). This is profile metadata and
431 // follows the same explicit-only policy as provider: omit it when the
432 // worker profile inherits the session/default reasoning setting.
433 if let Some(reasoning_effort) = route
434 .reasoning_effort
435 .map(str::trim)
436 .filter(|e| !e.is_empty())
437 {
438 args.push("--reasoning-effort".to_string());
439 args.push(reasoning_effort.to_string());
440 }
441
442 if !exec_config.allowed_tools.is_empty() {
443 args.push("--allowed-tools".to_string());
444 args.push(exec_config.allowed_tools.join(","));
445 }
446 if !exec_config.disallowed_tools.is_empty() {
447 args.push("--disallowed-tools".to_string());
448 args.push(exec_config.disallowed_tools.join(","));
449 }
450 if let Some(max_turns) = limits.max_turns {
451 args.push("--max-turns".to_string());
452 args.push(max_turns.to_string());
453 }
454 if let Some(max_tool_calls) = limits.max_tool_calls {
455 args.push("--max-tool-calls".to_string());
456 args.push(max_tool_calls.to_string());
457 }
458 if !exec_config.append_system_prompt.trim().is_empty() {
459 // One `--flag=value` argument, so the policy is always the value: as a
460 // separate argument, text that reads like one of exec's own options
461 // (`--hooks`) is parsed as that option and the worker fails to start.
462 args.push(format!(
463 "--append-system-prompt={}",
464 exec_config.append_system_prompt
465 ));
466 }
467
468 if let Some(authority) = authority {
469 args.push("--tool-authority-json".to_string());
470 args.push(
471 serde_json::to_string(authority)
472 .expect("validated Fleet tool authority envelope must serialize"),
473 );
474 }
475
476 // The composed task prompt is the final positional argument.
477 args.push(task_prompt);
478
479 FleetWorkerCommand::new(codewhale_binary.to_string(), args)
480 }
481
482 /// Map one `codewhale exec` stream-json line into a fleet ledger event.
483 ///
484 /// Returns `None` for lines that don't correspond to a worker lifecycle
485 /// transition (e.g. `session_capture`, `metadata`). The exec event schema is
486 /// `{"type": "...", ...}` (see `ExecStreamEvent` in `main.rs`).
487 pub fn map_exec_stream_line(line: &str) -> Option<FleetWorkerEventPayload> {
488 let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?;
489 map_exec_stream_value(&value)
490 }
491
492 /// [`map_exec_stream_line`] on an already-parsed line, so the incremental
493 /// stream reader parses each frame exactly once.
494 fn map_exec_stream_value(value: &serde_json::Value) -> Option<FleetWorkerEventPayload> {
495 match value.get("type").and_then(serde_json::Value::as_str)? {
496 "tool_use" => {
497 let tool = value
498 .get("name")
499 .and_then(serde_json::Value::as_str)
500 .unwrap_or("tool")
501 .to_string();
502 let call_id = value
503 .get("id")
504 .and_then(serde_json::Value::as_str)
505 .map(str::to_string);
506 Some(FleetWorkerEventPayload::RunningTool { tool, call_id })
507 }
508 "workflow_event" => Some(FleetWorkerEventPayload::WorkflowEvent {
509 workflow_run_id: value.get("run_id")?.as_str()?.to_string(),
510 event: value.get("event")?.clone(),
511 }),
512 // Streaming model output / tool results mean the worker is alive and
513 // making progress; surface a coarse Running heartbeat.
514 "content" | "delta" | "tool_result" => Some(FleetWorkerEventPayload::Running),
515 // Per-step usage receipts feed the run-level accumulator behind the
516 // fleet usage ceiling (R6, #5567); a malformed line still counts as
517 // liveness.
518 "turn_usage" => {
519 let tokens = |field: &str| {
520 value
521 .get(field)
522 .and_then(serde_json::Value::as_u64)
523 .unwrap_or(0)
524 };
525 let input_tokens = tokens("input_tokens");
526 let output_tokens = tokens("output_tokens");
527 if input_tokens == 0 && output_tokens == 0 {
528 Some(FleetWorkerEventPayload::Running)
529 } else {
530 Some(FleetWorkerEventPayload::UsageReport {
531 input_tokens,
532 output_tokens,
533 })
534 }
535 }
536 "done" | "completed" => Some(FleetWorkerEventPayload::Completed {
537 exit_code: Some(0),
538 summary: None,
539 }),
540 "error" => {
541 let reason = value
542 .get("error")
543 .and_then(serde_json::Value::as_str)
544 .unwrap_or("worker reported an error")
545 .to_string();
546 Some(FleetWorkerEventPayload::Failed {
547 reason,
548 recoverable: false,
549 })
550 }
551 _ => None,
552 }
553 }
554
555 #[derive(Debug)]
556 enum ParsedTerminalRoute {
557 NotTerminal,
558 Valid(FleetWorkerReportedRoute),
559 Invalid,
560 }
561
562 /// The `meta` object of a terminal exec receipt, or `None` for every other
563 /// stream line.
564 fn exec_terminal_meta(
565 value: &serde_json::Value,
566 ) -> Option<&serde_json::Map<String, serde_json::Value>> {
567 if value.get("type").and_then(serde_json::Value::as_str) != Some("metadata") {
568 return None;
569 }
570 let meta = value.get("meta").and_then(serde_json::Value::as_object)?;
571 (meta.get("receipt_kind").and_then(serde_json::Value::as_str) == Some("terminal"))
572 .then_some(meta)
573 }
574
575 /// The worker's visible final answer from a terminal exec receipt: the
576 /// emitter already bounded and redacted `visible_final_answer_excerpt`, and
577 /// `visible_final_answer_chars` is the real pre-truncation length.
578 fn parse_exec_terminal_final_answer(value: &serde_json::Value) -> Option<FleetWorkerFinalAnswer> {
579 let meta = exec_terminal_meta(value)?;
580 let excerpt = meta
581 .get("visible_final_answer_excerpt")
582 .and_then(serde_json::Value::as_str)?
583 .trim();
584 if excerpt.is_empty() {
585 return None;
586 }
587 let chars = meta
588 .get("visible_final_answer_chars")
589 .and_then(serde_json::Value::as_u64)
590 .and_then(|chars| usize::try_from(chars).ok())
591 .unwrap_or_else(|| excerpt.chars().count());
592 Some(FleetWorkerFinalAnswer {
593 excerpt: exec_stream_final_answer_excerpt(excerpt),
594 chars,
595 })
596 }
597
598 /// Parse one allowlisted, secret-free route identity from terminal exec
599 /// metadata. Once a line declares itself as a terminal receipt, malformed
600 /// route fields are distinct from ordinary non-terminal stream noise so a
601 /// prior valid record cannot survive contradictory evidence.
602 fn parse_exec_terminal_route(value: &serde_json::Value) -> ParsedTerminalRoute {
603 let Some(meta) = exec_terminal_meta(value) else {
604 return ParsedTerminalRoute::NotTerminal;
605 };
606
607 if let Some(external_agent_value) = meta.get("external_agent") {
608 let Some(agent) = external_agent_value
609 .as_str()
610 .map(str::trim)
611 .filter(|agent| !agent.is_empty())
612 else {
613 return ParsedTerminalRoute::Invalid;
614 };
615 let model = meta
616 .get("model")
617 .and_then(serde_json::Value::as_str)
618 .map(str::trim)
619 .filter(|model| !model.is_empty())
620 .unwrap_or("default");
621 return ParsedTerminalRoute::Valid(FleetWorkerReportedRoute {
622 provider: format!("external:{agent}"),
623 provider_exact_id: None,
624 model: model.to_string(),
625 });
626 }
627
628 let route = (|| {
629 let provider = meta.get("provider")?.as_str()?.trim();
630 let model = meta.get("model")?.as_str()?.trim();
631 if provider.is_empty() || model.is_empty() {
632 return None;
633 }
634 let provider_kind = codewhale_config::ProviderKind::parse(provider)?;
635 let provider_exact_id = match meta.get("provider_id") {
636 None => None,
637 Some(value) => {
638 let id = value.as_str()?.trim();
639 if id.is_empty() {
640 return None;
641 }
642 Some(id.to_string())
643 }
644 };
645 if provider_exact_id.is_some() && provider_kind != codewhale_config::ProviderKind::Custom {
646 return None;
647 }
648 Some(FleetWorkerReportedRoute {
649 provider: provider.to_string(),
650 provider_exact_id,
651 model: model.to_string(),
652 })
653 })();
654
655 route.map_or(ParsedTerminalRoute::Invalid, ParsedTerminalRoute::Valid)
656 }
657
658 #[cfg(test)]
659 fn map_exec_terminal_route(line: &str) -> Option<FleetWorkerReportedRoute> {
660 let value: serde_json::Value = serde_json::from_str(line).ok()?;
661 match parse_exec_terminal_route(&value) {
662 ParsedTerminalRoute::Valid(route) => Some(route),
663 ParsedTerminalRoute::NotTerminal | ParsedTerminalRoute::Invalid => None,
664 }
665 }
666
667 /// Classify a worker process exit into a terminal fleet event.
668 ///
669 /// `stopped` means the operator stopped the worker (cancellation), which takes
670 /// precedence over the exit code.
671 pub fn classify_worker_exit(exit_code: Option<i32>, stopped: bool) -> FleetWorkerEventPayload {
672 if stopped {
673 return FleetWorkerEventPayload::Cancelled { cancelled_by: None };
674 }
675 match exit_code {
676 Some(0) => FleetWorkerEventPayload::Completed {
677 exit_code: Some(0),
678 summary: None,
679 },
680 Some(code) => FleetWorkerEventPayload::Failed {
681 reason: format!("worker exited with code {code}"),
682 recoverable: false,
683 },
684 None => FleetWorkerEventPayload::Failed {
685 reason: "worker exited without a status code".to_string(),
686 recoverable: false,
687 },
688 }
689 }
690
691 /// Drives fleet workers as real `codewhale exec` subprocesses on the local
692 /// host, incrementally draining each worker's stream-json output into fleet
693 /// ledger events.
694 ///
695 /// The caller (the `codewhale fleet run` loop / `FleetManager`) owns the
696 /// ledger; the executor owns the OS process boundary and the incremental log
697 /// parse. Because the worker is a separate process, its heavy runtime/tool
698 /// construction never touches the orchestrator — the parent only ingests a
699 /// compact event stream, which is what keeps it light at high fanout.
700 pub struct FleetExecutor {
701 workspace: std::path::PathBuf,
702 sessions_dir: Option<std::path::PathBuf>,
703 tailnet_snapshot: Option<std::sync::Arc<super::tailnet::TailnetSnapshot>>,
704 adapter: super::host::LocalProcessFleetHostAdapter,
705 ssh_adapters: std::collections::BTreeMap<String, super::host::SshFleetHostAdapter>,
706 streams: std::collections::BTreeMap<String, WorkerStream>,
707 }
708
709 /// Durable lease identity owned by one concrete host process.
710 #[derive(Debug, Clone, PartialEq, Eq)]
711 pub struct FleetExecutorAttempt {
712 pub run_id: codewhale_protocol::fleet::FleetRunId,
713 pub task_id: String,
714 pub attempt: u32,
715 }
716
717 struct WorkerStream {
718 log_path: std::path::PathBuf,
719 host: WorkerStreamHost,
720 attempt: Option<FleetExecutorAttempt>,
721 offset: u64,
722 // Keep incomplete stream frames as bytes. Decoding each read separately
723 // corrupts valid UTF-8 when a multibyte code point crosses a read boundary.
724 pending: Vec<u8>,
725 terminal: bool,
726 confirmed_stopped: bool,
727 pending_terminal: Option<PendingFleetTerminal>,
728 terminal_route: TerminalRouteEvidence,
729 /// When this worker process was started, for per-task wall-clock limits (R5).
730 started_at: std::time::Instant,
731 /// The worker's visible final answer from its terminal exec receipt. This
732 /// is the task's deliverable for report/summary work that produces no
733 /// file artifact; surfaced as `Completed.summary` and in the receipt note
734 /// so receipts stop reporting "no verifiable output" for a worker that
735 /// wrote a full report. Bounded by the emitter, so nothing accumulates
736 /// here.
737 final_answer: Option<FleetWorkerFinalAnswer>,
738 /// Saved exec session id reported by the worker's `session_capture` event.
739 /// Resolving it via `GET /v1/sessions/{id}` yields the full transcript
740 /// (the worker's final assistant reply).
741 saved_session_id: Option<String>,
742 /// Parent-owned capture identity in the Runtime's existing session store.
743 session_capture: Option<(String, std::path::PathBuf)>,
744 }
745
746 impl WorkerStream {
747 /// Observe one raw stream-json frame: record route evidence, the final
748 /// answer, and the saved-session id, and map it to a ledger payload. The
749 /// frame is parsed exactly once.
750 fn observe_line(&mut self, line: &[u8]) -> Option<FleetWorkerEventPayload> {
751 let Ok(line) = std::str::from_utf8(line) else {
752 // stream-json is a UTF-8 contract. Never accept a lossy-decoded route
753 // receipt: replacement characters could turn corrupt provider/model
754 // bytes into apparently valid provenance.
755 self.terminal_route.observe(ParsedTerminalRoute::Invalid);
756 return None;
757 };
758 let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?;
759 self.terminal_route
760 .observe(parse_exec_terminal_route(&value));
761 if exec_terminal_meta(&value).is_some() {
762 self.final_answer = parse_exec_terminal_final_answer(&value);
763 }
764 if value.get("type").and_then(serde_json::Value::as_str) == Some("session_capture")
765 && let Some(id) = value
766 .get("saved_session_id")
767 .and_then(serde_json::Value::as_str)
768 .map(str::trim)
769 .filter(|id| !id.is_empty())
770 {
771 if self
772 .session_capture
773 .as_ref()
774 .is_some_and(|(expected, _)| expected == id)
775 {
776 self.saved_session_id = Some(id.to_string());
777 } else {
778 // A worker log cannot select an unrelated local transcript.
779 self.session_capture = None;
780 self.saved_session_id = None;
781 }
782 }
783 map_exec_stream_value(&value)
784 }
785 }
786
787 #[derive(Debug, Clone, Default)]
788 enum TerminalRouteEvidence {
789 #[default]
790 Missing,
791 Valid(FleetWorkerReportedRoute),
792 InvalidOrAmbiguous,
793 }
794
795 impl TerminalRouteEvidence {
796 fn observe(&mut self, parsed: ParsedTerminalRoute) {
797 match parsed {
798 ParsedTerminalRoute::NotTerminal => {}
799 ParsedTerminalRoute::Invalid => *self = Self::InvalidOrAmbiguous,
800 ParsedTerminalRoute::Valid(route) => {
801 *self = if matches!(&*self, Self::Missing) {
802 Self::Valid(route)
803 } else {
804 // The stream contract emits exactly one terminal receipt.
805 // Any second record, even an identical one, is ambiguous
806 // provenance and must permanently fail closed.
807 Self::InvalidOrAmbiguous
808 };
809 }
810 }
811 }
812
813 fn reported_route(&self) -> Option<&FleetWorkerReportedRoute> {
814 match self {
815 Self::Valid(route) => Some(route),
816 Self::Missing | Self::InvalidOrAmbiguous => None,
817 }
818 }
819 }
820
821 enum WorkerStreamHost {
822 Local,
823 Ssh(String),
824 }
825
826 #[derive(Debug, Clone)]
827 pub struct FleetWorkerReportedRoute {
828 pub provider: String,
829 pub provider_exact_id: Option<String>,
830 pub model: String,
831 }
832
833 #[derive(Debug, Clone)]
834 pub struct FleetWorkerTerminalEvent {
835 pub payload: FleetWorkerEventPayload,
836 pub exit_code: Option<i32>,
837 /// Non-terminal payloads discovered by the mandatory post-exit drain.
838 pub tail_payloads: Vec<FleetWorkerEventPayload>,
839 pub reported_route: Option<FleetWorkerReportedRoute>,
840 /// The worker's visible final answer from its terminal exec receipt,
841 /// whatever the outcome: a worker that fails after writing most of a
842 /// report keeps the text on its receipt.
843 pub final_answer: Option<FleetWorkerFinalAnswer>,
844 /// Saved exec session id reported by the worker's `session_capture` event,
845 /// when one was persisted on completion.
846 pub saved_session_id: Option<String>,
847 /// A real headless exec process must report its actual route. Callers use
848 /// this bit to distinguish a missing/invalid report (fail closed) from
849 /// pre-launch or simulated paths that only have declared route intent.
850 pub requires_reported_route: bool,
851 }
852
853 #[derive(Debug, Clone)]
854 pub struct FleetPreparedTaskOutcome {
855 pub payload: FleetWorkerEventPayload,
856 pub tail_payloads: Vec<FleetWorkerEventPayload>,
857 pub final_status: Option<super::ledger::FleetTaskLedgerStatus>,
858 pub receipt: FleetReceipt,
859 }
860
861 #[derive(Debug, Clone)]
862 enum PendingFleetTerminal {
863 Observed(Box<FleetWorkerTerminalEvent>),
864 Prepared(Box<FleetPreparedTaskOutcome>),
865 }
866
867 impl FleetExecutor {
868 pub fn refresh_tailnet_inventory(&mut self) {
869 self.tailnet_snapshot = Some(std::sync::Arc::new(super::tailnet::TailnetSnapshot::new(
870 super::tailnet::inventory().map_err(|error| error.to_string()),
871 )));
872 }
873
874 pub fn new(workspace: impl AsRef<std::path::Path>) -> Self {
875 let workspace = workspace.as_ref().to_path_buf();
876 Self {
877 adapter: super::host::LocalProcessFleetHostAdapter::new(&workspace),
878 workspace,
879 sessions_dir: None,
880 tailnet_snapshot: None,
881 ssh_adapters: std::collections::BTreeMap::new(),
882 streams: std::collections::BTreeMap::new(),
883 }
884 }
885
886 /// Share the caller's SessionManager directory; never create a second store.
887 pub fn with_sessions_dir(mut self, sessions_dir: std::path::PathBuf) -> Self {
888 self.sessions_dir = Some(sessions_dir);
889 self
890 }
891
892 /// Start a worker process and begin tracking its event stream.
893 pub fn start_worker(
894 &mut self,
895 worker_id: &str,
896 command: FleetWorkerCommand,
897 cwd: Option<std::path::PathBuf>,
898 ) -> super::host::FleetHostResult<super::host::FleetWorkerHandle> {
899 self.start_worker_on_host(worker_id, &FleetHostSpec::Local, command, cwd)
900 }
901
902 /// Start a worker on the requested fleet host.
903 pub fn start_worker_on_host(
904 &mut self,
905 worker_id: &str,
906 host: &FleetHostSpec,
907 command: FleetWorkerCommand,
908 cwd: Option<std::path::PathBuf>,
909 ) -> super::host::FleetHostResult<super::host::FleetWorkerHandle> {
910 self.start_worker_on_host_inner(worker_id, host, command, cwd, None)
911 }
912
913 /// Start the concrete process for one exact durable Fleet lease.
914 pub fn start_worker_attempt_on_host(
915 &mut self,
916 worker_id: &str,
917 host: &FleetHostSpec,
918 command: FleetWorkerCommand,
919 cwd: Option<std::path::PathBuf>,
920 attempt: FleetExecutorAttempt,
921 ) -> super::host::FleetHostResult<super::host::FleetWorkerHandle> {
922 self.start_worker_on_host_inner(worker_id, host, command, cwd, Some(attempt))
923 }
924
925 fn start_worker_on_host_inner(
926 &mut self,
927 worker_id: &str,
928 host: &FleetHostSpec,
929 command: FleetWorkerCommand,
930 cwd: Option<std::path::PathBuf>,
931 attempt: Option<FleetExecutorAttempt>,
932 ) -> super::host::FleetHostResult<super::host::FleetWorkerHandle> {
933 let mut request = super::host::FleetWorkerStartRequest::new(worker_id, command);
934 request.attempt = attempt.clone();
935 request.cwd = cwd;
936 let session_capture = if matches!(host, FleetHostSpec::Local) {
937 self.sessions_dir.as_ref().map(|dir| {
938 let id = uuid::Uuid::new_v4().to_string();
939 for (key, value) in [
940 ("CODEWHALE_FLEET_CAPTURE_ID", id.clone()),
941 (
942 "CODEWHALE_FLEET_CAPTURE_DIR",
943 dir.to_string_lossy().into_owned(),
944 ),
945 ] {
946 request.env.insert(key.to_string(), value);
947 request.env_allowlist.insert(key.to_string());
948 }
949 // Preserve an explicit local account/config root as well.
950 if let Some(home) = std::env::var_os("CODEWHALE_HOME") {
951 request
952 .env
953 .insert("CODEWHALE_HOME".into(), home.to_string_lossy().into_owned());
954 request.env_allowlist.insert("CODEWHALE_HOME".into());
955 }
956 (id, dir.clone())
957 })
958 } else {
959 // SSH transcripts live remotely and have no local retrieval link.
960 None
961 };
962 let (handle, host) = match host {
963 FleetHostSpec::Local => {
964 let handle = self.adapter.start_worker(request)?;
965 (handle, WorkerStreamHost::Local)
966 }
967 FleetHostSpec::Ssh { .. } | FleetHostSpec::Tailscale { .. } => {
968 let config = super::host::SshFleetHostConfig::from_host_spec(host)?;
969 let key = worker_id.to_string();
970 let adapter = self.ssh_adapters.entry(key.clone()).or_insert(
971 super::host::SshFleetHostAdapter::new(&self.workspace, config)?,
972 );
973 adapter.set_tailnet_snapshot(self.tailnet_snapshot.clone());
974 let handle = adapter.start_worker(request)?;
975 (handle, WorkerStreamHost::Ssh(key))
976 }
977 FleetHostSpec::Docker { image, .. } => {
978 return Err(super::host::FleetHostError {
979 kind: super::host::FleetHostErrorKind::Configuration,
980 message: format!("docker Fleet workers are not wired yet (image {image})"),
981 });
982 }
983 };
984 self.streams.insert(
985 worker_id.to_string(),
986 WorkerStream {
987 log_path: handle.log_path.clone(),
988 host,
989 attempt,
990 offset: 0,
991 pending: Vec::new(),
992 terminal: false,
993 confirmed_stopped: false,
994 pending_terminal: None,
995 terminal_route: TerminalRouteEvidence::default(),
996 started_at: std::time::Instant::now(),
997 final_answer: None,
998 saved_session_id: None,
999 session_capture,
1000 },
1001 );
1002 Ok(handle)
1003 }
1004
1005 pub fn is_tracking(&self, worker_id: &str) -> bool {
1006 self.streams.contains_key(worker_id)
1007 }
1008
1009 pub fn worker_ids(&self) -> Vec<String> {
1010 self.streams.keys().cloned().collect()
1011 }
1012
1013 pub fn tracked_attempt(&self, worker_id: &str) -> Option<FleetExecutorAttempt> {
1014 self.streams
1015 .get(worker_id)
1016 .and_then(|stream| stream.attempt.clone())
1017 }
1018
1019 pub(crate) fn confirmed_stopped_attempts(
1020 &self,
1021 ) -> std::collections::BTreeMap<String, FleetExecutorAttempt> {
1022 self.streams
1023 .iter()
1024 .filter_map(|(id, stream)| {
1025 stream
1026 .confirmed_stopped
1027 .then(|| stream.attempt.clone())
1028 .flatten()
1029 .map(|attempt| (id.clone(), attempt))
1030 })
1031 .collect()
1032 }
1033
1034 pub(crate) fn is_confirmed_stopped(&self, worker_id: &str) -> bool {
1035 self.streams
1036 .get(worker_id)
1037 .is_some_and(|stream| stream.confirmed_stopped)
1038 }
1039
1040 pub(crate) fn prepared_terminal_outcome(
1041 &self,
1042 worker_id: &str,
1043 ) -> Option<FleetPreparedTaskOutcome> {
1044 match self.streams.get(worker_id)?.pending_terminal.as_ref()? {
1045 PendingFleetTerminal::Prepared(outcome) => Some(outcome.as_ref().clone()),
1046 PendingFleetTerminal::Observed(_) => None,
1047 }
1048 }
1049
1050 pub(crate) fn retain_prepared_terminal_outcome(
1051 &mut self,
1052 worker_id: &str,
1053 outcome: FleetPreparedTaskOutcome,
1054 ) -> Result<()> {
1055 let stream = self
1056 .streams
1057 .get_mut(worker_id)
1058 .ok_or_else(|| anyhow::anyhow!("Fleet terminal stream is absent"))?;
1059 anyhow::ensure!(
1060 stream.confirmed_stopped,
1061 "Fleet terminal process is not confirmed stopped"
1062 );
1063 if let Some(attempt) = &stream.attempt {
1064 anyhow::ensure!(
1065 outcome.receipt.run_id == attempt.run_id
1066 && outcome.receipt.task_id == attempt.task_id
1067 && outcome.receipt.attempt == Some(attempt.attempt)
1068 && outcome.receipt.worker_id == worker_id,
1069 "Fleet terminal candidate does not match its tracked attempt"
1070 );
1071 }
1072 stream.pending_terminal = Some(PendingFleetTerminal::Prepared(Box::new(outcome)));
1073 Ok(())
1074 }
1075
1076 pub(crate) fn poll_terminal_for_commit(
1077 &mut self,
1078 worker_id: &str,
1079 ) -> Option<FleetWorkerTerminalEvent> {
1080 if let Some(pending) = self.streams.get(worker_id)?.pending_terminal.as_ref() {
1081 return match pending {
1082 PendingFleetTerminal::Observed(event) => Some(event.as_ref().clone()),
1083 PendingFleetTerminal::Prepared(_) => None,
1084 };
1085 }
1086 let event = self.poll_terminal_with_status(worker_id)?;
1087 self.streams.get_mut(worker_id)?.pending_terminal =
1088 Some(PendingFleetTerminal::Observed(Box::new(event.clone())));
1089 Some(event)
1090 }
1091
1092 /// Wall-clock time this worker process has been running (R5). `None` when
1093 /// the worker is not tracked or its exit was already observed: a process
1094 /// that has exited is not running, so a deadline must not rewrite the
1095 /// outcome that exit produced as a timeout.
1096 #[must_use]
1097 pub fn worker_running_for(&self, worker_id: &str) -> Option<std::time::Duration> {
1098 self.streams
1099 .get(worker_id)
1100 .filter(|stream| !stream.terminal)
1101 .map(|stream| stream.started_at.elapsed())
1102 }
1103
1104 /// Stop a tracked worker at the host boundary.
1105 ///
1106 /// Operator controls run in a separate process from the foreground Fleet
1107 /// manager, so they communicate cancellation through the durable ledger.
1108 /// The manager calls this method after observing that terminal state; the
1109 /// executor is the only owner that can reliably reach the live local/SSH
1110 /// adapter handle.
1111 pub fn stop_worker(&mut self, worker_id: &str) -> Result<()> {
1112 let ssh_key = match self.streams.get(worker_id).map(|stream| &stream.host) {
1113 Some(WorkerStreamHost::Local) => None,
1114 Some(WorkerStreamHost::Ssh(key)) => Some(key.clone()),
1115 None => return Ok(()),
1116 };
1117 if let Some(key) = ssh_key {
1118 let adapter = self.ssh_adapters.get_mut(&key).ok_or_else(|| {
1119 anyhow::anyhow!("tracked SSH Fleet worker {worker_id} has no host adapter")
1120 })?;
1121 adapter.stop_worker(worker_id)?;
1122 } else {
1123 self.adapter.stop_worker(worker_id)?;
1124 }
1125 if let Some(stream) = self.streams.get_mut(worker_id) {
1126 stream.confirmed_stopped = true;
1127 }
1128 Ok(())
1129 }
1130
1131 /// Stop tracking a terminal worker so the scheduler can reuse the same
1132 /// logical worker id for the next queued task.
1133 pub fn forget_worker(&mut self, worker_id: &str) {
1134 let Some(stream) = self.streams.remove(worker_id) else {
1135 return;
1136 };
1137 match stream.host {
1138 WorkerStreamHost::Local => {
1139 let _ = self.adapter.cleanup_worker(worker_id);
1140 }
1141 WorkerStreamHost::Ssh(key) => {
1142 if let Some(adapter) = self.ssh_adapters.get_mut(&key) {
1143 let _ = adapter.cleanup_worker(worker_id);
1144 }
1145 self.ssh_adapters.remove(&key);
1146 }
1147 }
1148 }
1149
1150 /// Maximum bytes drained from a worker log per call, and the cap for the
1151 /// buffered partial line. Event lines are small; the remainder stays for
1152 /// the next drain.
1153 const MAX_DRAIN_BYTES: u64 = 1024 * 1024;
1154
1155 /// Read any newly-written stream-json lines for a worker and map them to
1156 /// fleet ledger events. Safe to call repeatedly; only new bytes are parsed,
1157 /// and a trailing partial line is buffered until its newline arrives.
1158 pub fn drain_events(&mut self, worker_id: &str) -> Vec<FleetWorkerEventPayload> {
1159 let Some(stream) = self.streams.get_mut(worker_id) else {
1160 return Vec::new();
1161 };
1162 let mut events = Vec::new();
1163 let Ok(mut file) = std::fs::File::open(&stream.log_path) else {
1164 return events;
1165 };
1166 use std::io::{Read, Seek, SeekFrom};
1167 if file.seek(SeekFrom::Start(stream.offset)).is_err() {
1168 return events;
1169 }
1170 let mut buf = Vec::new();
1171 if let Ok(read) = file.take(Self::MAX_DRAIN_BYTES).read_to_end(&mut buf) {
1172 stream.offset += read as u64;
1173 stream.pending.extend_from_slice(&buf);
1174 while let Some(idx) = stream.pending.iter().position(|byte| *byte == b'\n') {
1175 let line: Vec<u8> = stream.pending.drain(..=idx).collect();
1176 if let Some(event) = stream.observe_line(&line) {
1177 events.push(event);
1178 }
1179 }
1180 // Whatever remains has no newline; drop it rather than buffering
1181 // a newline-free flood forever.
1182 if stream.pending.len() as u64 > Self::MAX_DRAIN_BYTES {
1183 tracing::debug!(
1184 worker_id,
1185 dropped_bytes = stream.pending.len(),
1186 "fleet drain dropped a newline-free flood exceeding the per-call budget"
1187 );
1188 stream.pending.clear();
1189 }
1190 }
1191 events
1192 }
1193
1194 /// Poll the worker process; once it exits, return the terminal event exactly
1195 /// once. Returns `None` while the worker is still running or already
1196 /// finalized.
1197 pub fn poll_terminal(&mut self, worker_id: &str) -> Option<FleetWorkerEventPayload> {
1198 self.poll_terminal_with_status(worker_id)
1199 .map(|event| event.payload)
1200 }
1201
1202 /// Poll the worker process and include the raw exit code for receipt
1203 /// verification.
1204 pub fn poll_terminal_with_status(
1205 &mut self,
1206 worker_id: &str,
1207 ) -> Option<FleetWorkerTerminalEvent> {
1208 if self.streams.get(worker_id).is_none_or(|s| s.terminal) {
1209 return None;
1210 }
1211 let status = match self.streams.get(worker_id).map(|s| &s.host)? {
1212 WorkerStreamHost::Local => self.adapter.read_status(worker_id).ok()?,
1213 WorkerStreamHost::Ssh(key) => self
1214 .ssh_adapters
1215 .get_mut(key)
1216 .and_then(|adapter| adapter.read_status(worker_id).ok())?,
1217 };
1218 let mut terminal = match status.state {
1219 super::host::FleetHostWorkerState::Running
1220 | super::host::FleetHostWorkerState::Draining
1221 | super::host::FleetHostWorkerState::Unknown => return None,
1222 super::host::FleetHostWorkerState::Stopped => {
1223 classify_worker_exit(status.exit_code, true)
1224 }
1225 super::host::FleetHostWorkerState::Exited
1226 | super::host::FleetHostWorkerState::Failed => {
1227 classify_worker_exit(status.exit_code, false)
1228 }
1229 };
1230 // Once status is terminal the worker can no longer append. Drain one
1231 // final time before snapshotting route evidence so metadata written
1232 // between the scheduler's ordinary drain and this status poll cannot
1233 // be lost when the worker is forgotten.
1234 let mut tail_payloads = self.drain_events(worker_id);
1235 let stream = self.streams.get_mut(worker_id)?;
1236 let trailing_line = std::mem::take(&mut stream.pending);
1237 if trailing_line.iter().any(|byte| !byte.is_ascii_whitespace())
1238 && let Some(payload) = stream.observe_line(&trailing_line)
1239 {
1240 tail_payloads.push(payload);
1241 }
1242 stream.terminal = true;
1243 stream.confirmed_stopped = true;
1244 let final_answer = stream.final_answer.take();
1245 // Surface the visible final answer on a successful completion so
1246 // report/summary tasks (no scorer, no file artifact) show their
1247 // deliverable instead of "no verifiable output". `Failed` has no
1248 // summary slot; the receipt keeps the text via `final_answer`.
1249 if let (Some(answer), FleetWorkerEventPayload::Completed { summary, .. }) =
1250 (final_answer.as_ref(), &mut terminal)
1251 {
1252 *summary = Some(answer.excerpt.clone());
1253 }
1254 Some(FleetWorkerTerminalEvent {
1255 payload: terminal,
1256 exit_code: status.exit_code,
1257 tail_payloads,
1258 reported_route: stream.terminal_route.reported_route().cloned(),
1259 final_answer,
1260 saved_session_id: stream.saved_session_id.take().filter(|id| {
1261 stream
1262 .session_capture
1263 .as_ref()
1264 .is_some_and(|(expected, dir)| {
1265 id == expected
1266 && crate::session_manager::SessionManager::new(dir.clone())
1267 .and_then(|manager| manager.load_session(id))
1268 .is_ok()
1269 })
1270 }),
1271 requires_reported_route: true,
1272 })
1273 }
1274
1275 /// True once every started worker has reached a terminal state.
1276 #[cfg(test)]
1277 pub fn all_terminal(&self) -> bool {
1278 !self.streams.is_empty() && self.streams.values().all(|s| s.terminal)
1279 }
1280 }
1281
1282 pub struct FleetWorkerLaunchRequest<'a> {
1283 pub worker_id: &'a str,
1284 pub host: &'a FleetHostSpec,
1285 pub runtime: &'a ResolvedFleetWorkerRuntime,
1286 pub command: FleetWorkerCommand,
1287 pub cwd: Option<std::path::PathBuf>,
1288 pub attempt: FleetExecutorAttempt,
1289 }
1290
1291 #[derive(Debug, Clone)]
1292 pub struct FleetWorkerLaunchReceipt {
1293 pub log_path: Option<std::path::PathBuf>,
1294 pub transport_receipt: Option<codewhale_protocol::fleet::FleetArtifactRef>,
1295 pub thread_id: Option<String>,
1296 }
1297
1298 pub trait FleetWorkerLauncher: Send {
1299 fn is_tracking(&self, worker_id: &str) -> bool;
1300 fn worker_ids(&self) -> Vec<String>;
1301 fn tracked_attempt(&self, worker_id: &str) -> Option<FleetExecutorAttempt>;
1302 fn confirmed_stopped_attempts(
1303 &self,
1304 ) -> std::collections::BTreeMap<String, FleetExecutorAttempt>;
1305 fn is_confirmed_stopped(&self, worker_id: &str) -> bool;
1306 fn prepared_terminal_outcome(&self, worker_id: &str) -> Option<FleetPreparedTaskOutcome>;
1307 fn retain_prepared_terminal_outcome(
1308 &mut self,
1309 worker_id: &str,
1310 outcome: FleetPreparedTaskOutcome,
1311 ) -> Result<()>;
1312 fn poll_terminal_for_commit(&mut self, worker_id: &str) -> Option<FleetWorkerTerminalEvent>;
1313 fn worker_running_for(&self, worker_id: &str) -> Option<std::time::Duration>;
1314 fn drain_events(&mut self, worker_id: &str) -> Vec<FleetWorkerEventPayload>;
1315 fn stop_worker(&mut self, worker_id: &str) -> Result<()>;
1316 fn forget_worker(&mut self, worker_id: &str);
1317 fn refresh_tailnet_inventory(&mut self);
1318 fn launch_worker(
1319 &mut self,
1320 request: FleetWorkerLaunchRequest<'_>,
1321 ) -> super::host::FleetHostResult<FleetWorkerLaunchReceipt>;
1322 }
1323
1324 impl FleetWorkerLauncher for FleetExecutor {
1325 fn is_tracking(&self, worker_id: &str) -> bool {
1326 Self::is_tracking(self, worker_id)
1327 }
1328
1329 fn worker_ids(&self) -> Vec<String> {
1330 Self::worker_ids(self)
1331 }
1332
1333 fn tracked_attempt(&self, worker_id: &str) -> Option<FleetExecutorAttempt> {
1334 Self::tracked_attempt(self, worker_id)
1335 }
1336
1337 fn confirmed_stopped_attempts(
1338 &self,
1339 ) -> std::collections::BTreeMap<String, FleetExecutorAttempt> {
1340 Self::confirmed_stopped_attempts(self)
1341 }
1342
1343 fn is_confirmed_stopped(&self, worker_id: &str) -> bool {
1344 Self::is_confirmed_stopped(self, worker_id)
1345 }
1346
1347 fn prepared_terminal_outcome(&self, worker_id: &str) -> Option<FleetPreparedTaskOutcome> {
1348 Self::prepared_terminal_outcome(self, worker_id)
1349 }
1350
1351 fn retain_prepared_terminal_outcome(
1352 &mut self,
1353 worker_id: &str,
1354 outcome: FleetPreparedTaskOutcome,
1355 ) -> Result<()> {
1356 Self::retain_prepared_terminal_outcome(self, worker_id, outcome)
1357 }
1358
1359 fn poll_terminal_for_commit(&mut self, worker_id: &str) -> Option<FleetWorkerTerminalEvent> {
1360 Self::poll_terminal_for_commit(self, worker_id)
1361 }
1362
1363 fn worker_running_for(&self, worker_id: &str) -> Option<std::time::Duration> {
1364 Self::worker_running_for(self, worker_id)
1365 }
1366
1367 fn drain_events(&mut self, worker_id: &str) -> Vec<FleetWorkerEventPayload> {
1368 Self::drain_events(self, worker_id)
1369 }
1370
1371 fn stop_worker(&mut self, worker_id: &str) -> Result<()> {
1372 Self::stop_worker(self, worker_id)
1373 }
1374
1375 fn forget_worker(&mut self, worker_id: &str) {
1376 Self::forget_worker(self, worker_id)
1377 }
1378
1379 fn refresh_tailnet_inventory(&mut self) {
1380 Self::refresh_tailnet_inventory(self)
1381 }
1382
1383 fn launch_worker(
1384 &mut self,
1385 request: FleetWorkerLaunchRequest<'_>,
1386 ) -> super::host::FleetHostResult<FleetWorkerLaunchReceipt> {
1387 let handle = self.start_worker_attempt_on_host(
1388 request.worker_id,
1389 request.host,
1390 request.command,
1391 request.cwd,
1392 request.attempt,
1393 )?;
1394 Ok(FleetWorkerLaunchReceipt {
1395 log_path: Some(handle.log_path),
1396 transport_receipt: handle.transport_receipt,
1397 thread_id: None,
1398 })
1399 }
1400 }
1401
1402 /// Character bound for `metadata.visible_final_answer_excerpt`. The excerpt
1403 /// is a status surface (fleet receipts, event labels, runtime API payloads),
1404 /// not the transcript: the full answer lives in the saved session and the
1405 /// worker's stream-json log, and `visible_final_answer_chars` carries the real
1406 /// length so a consumer can tell a bounded excerpt from a short answer.
1407 pub const EXEC_STREAM_FINAL_ANSWER_EXCERPT_CHARS: usize = 4_000;
1408
1409 /// Bound and secret-redact the visible final answer once, at the emitter, so
1410 /// every downstream consumer reads the same excerpt.
1411 pub fn exec_stream_final_answer_excerpt(output: &str) -> String {
1412 let redacted = codewhale_config::persistence::redact_secrets(output.trim());
1413 let mut chars = redacted.chars();
1414 let excerpt: String = chars
1415 .by_ref()
1416 .take(EXEC_STREAM_FINAL_ANSWER_EXCERPT_CHARS)
1417 .collect();
1418 if chars.next().is_some() {
1419 format!("{excerpt}...")
1420 } else {
1421 excerpt
1422 }
1423 }
1424
1425 #[cfg(test)]
1426 mod tests {
1427 use super::*;
1428 use codewhale_config::FleetRole;
1429 use codewhale_config::{
1430 FleetDelegationHints, FleetLoadout, FleetProfile, FleetProfilePermissions, FleetSlot,
1431 };
1432 use codewhale_protocol::fleet::{
1433 FleetHostSpec, FleetTaskBudget, FleetTaskSpec, FleetTaskWorkerProfile, FleetWorkerSpec,
1434 FleetWorkspaceRequirements,
1435 };
1436 use std::collections::BTreeMap;
1437 use tempfile::TempDir;
1438
1439 fn task(instructions: &str) -> FleetTaskSpec {
1440 FleetTaskSpec {
1441 id: "t1".to_string(),
1442 name: "Smoke".to_string(),
1443 description: None,
1444 objective: Some("prove it runs".to_string()),
1445 instructions: instructions.to_string(),
1446 worker: Some(FleetTaskWorkerProfile {
1447 provider: None,
1448 agent_profile: None,
1449 role: Some("reviewer".to_string()),
1450 loadout: None,
1451 model_class: None,
1452 model: None,
1453 external_agent: None,
1454 external_agent_transport: None,
1455 tool_profile: Some("read-only".to_string()),
1456 tools: vec![],
1457 capabilities: vec![],
1458 }),
1459 workspace: None,
1460 input_files: vec![],
1461 context: vec![],
1462 budget: None,
1463 tags: vec![],
1464 expected_artifacts: vec![],
1465 scorer: None,
1466 retry_policy: None,
1467 alert_policy: None,
1468 timeout_seconds: None,
1469 metadata: BTreeMap::new(),
1470 }
1471 }
1472
1473 fn agent_profile(id: &str, role: &str, instructions: &str) -> AgentProfile {
1474 AgentProfile {
1475 native_preset: None,
1476 id: id.to_string(),
1477 display_name: Some(format!("{role} profile")),
1478 description: Some(format!("{role} description")),
1479 requires: Vec::new(),
1480 profile: FleetProfile {
1481 slot: FleetSlot::from_name(role),
1482 role: FleetRole {
1483 name: role.to_string(),
1484 description: None,
1485 instructions: Some(instructions.to_string()),
1486 },
1487 loadout: FleetLoadout::Inherit,
1488 model: None,
1489 provider: None,
1490 reasoning_effort: None,
1491 external_agent: None,
1492 external_agent_transport: None,
1493 permissions: FleetProfilePermissions::default(),
1494 delegation: FleetDelegationHints::default(),
1495 },
1496 source: std::path::PathBuf::from(format!("{id}.toml")),
1497 origin: crate::fleet::roster::ProfileOrigin::Workspace,
1498 plugin_authority: None,
1499 }
1500 }
1501
1502 fn launch_spec(task: &FleetTaskSpec, workspace: &std::path::Path) -> AgentWorkerSpec {
1503 let worker = FleetWorkerSpec {
1504 environment: None,
1505 id: "worker-1".to_string(),
1506 name: "Worker 1".to_string(),
1507 host: FleetHostSpec::Local,
1508 trust_level: None,
1509 labels: BTreeMap::new(),
1510 capabilities: Vec::new(),
1511 max_concurrent_tasks: Some(1),
1512 };
1513 crate::fleet::worker_runtime::fleet_task_to_worker_spec_with_profiles(
1514 "worker-1",
1515 "run-1",
1516 task,
1517 &worker,
1518 "auto",
1519 workspace,
1520 workspace,
1521 &[],
1522 None,
1523 )
1524 .unwrap()
1525 }
1526
1527 fn track_test_stream(
1528 executor: &mut FleetExecutor,
1529 worker_id: &str,
1530 log_path: std::path::PathBuf,
1531 ) {
1532 executor.streams.insert(
1533 worker_id.to_string(),
1534 WorkerStream {
1535 log_path,
1536 host: WorkerStreamHost::Local,
1537 attempt: None,
1538 offset: 0,
1539 pending: Vec::new(),
1540 terminal: false,
1541 confirmed_stopped: false,
1542 pending_terminal: None,
1543 terminal_route: TerminalRouteEvidence::default(),
1544 started_at: std::time::Instant::now(),
1545 final_answer: None,
1546 saved_session_id: None,
1547 session_capture: None,
1548 },
1549 );
1550 }
1551
1552 fn append_test_stream(path: &std::path::Path, bytes: &[u8]) {
1553 use std::io::Write as _;
1554
1555 std::fs::OpenOptions::new()
1556 .append(true)
1557 .open(path)
1558 .unwrap()
1559 .write_all(bytes)
1560 .unwrap();
1561 }
1562
1563 #[test]
1564 fn worker_command_is_a_headless_codewhale_exec_run() {
1565 let exec = FleetExecConfig::default();
1566 let cmd = build_worker_exec_command("codewhale", &task("read the file"), &exec, None);
1567 assert_eq!(cmd.program, "codewhale");
1568 assert_eq!(cmd.args[0], "exec");
1569 assert!(cmd.args.contains(&"--auto".to_string()));
1570 // stream-json so the executor can ingest the worker's event stream.
1571 let joined = cmd.args.join(" ");
1572 assert!(joined.contains("--output-format stream-json"));
1573 // The task instructions ride in the positional prompt (last arg).
1574 assert!(cmd.args.last().unwrap().contains("read the file"));
1575 }
1576
1577 #[test]
1578 fn worker_command_threads_exec_hardening_flags() {
1579 let exec = FleetExecConfig {
1580 allowed_tools: vec!["read_file".to_string(), "grep_files".to_string()],
1581 disallowed_tools: vec!["exec_shell".to_string()],
1582 max_turns: 40,
1583 append_system_prompt: "never push to main".to_string(),
1584 ..FleetExecConfig::default()
1585 };
1586 let cmd = build_worker_exec_command("codewhale", &task("audit"), &exec, Some("glm-5.1"));
1587 let exec_idx = cmd
1588 .args
1589 .iter()
1590 .position(|arg| arg == "exec")
1591 .expect("worker command must contain exec");
1592 let model_idx = cmd
1593 .args
1594 .iter()
1595 .position(|arg| arg == "--model")
1596 .expect("worker command must contain --model");
1597 assert!(
1598 model_idx < exec_idx,
1599 "global --model must precede exec: {:?}",
1600 cmd.args
1601 );
1602 let joined = cmd.args.join(" ");
1603 assert!(joined.contains("--model glm-5.1"));
1604 assert!(joined.contains("--allowed-tools read_file,grep_files"));
1605 assert!(joined.contains("--disallowed-tools exec_shell"));
1606 assert!(joined.contains("--max-turns 40"));
1607 assert!(
1608 cmd.args
1609 .iter()
1610 .any(|a| a == "--append-system-prompt=never push to main")
1611 );
1612 }
1613
1614 #[test]
1615 fn worker_command_threads_positive_task_budgets_and_caps_steps() {
1616 let mut task = task("audit");
1617 task.budget = Some(FleetTaskBudget {
1618 max_steps: Some(75),
1619 max_tool_calls: Some(11),
1620 ..FleetTaskBudget::default()
1621 });
1622 let exec = FleetExecConfig {
1623 max_turns: 40,
1624 ..FleetExecConfig::default()
1625 };
1626
1627 let cmd = build_worker_exec_command("codewhale", &task, &exec, None);
1628 let max_turns_idx = cmd
1629 .args
1630 .iter()
1631 .position(|arg| arg == "--max-turns")
1632 .expect("positive max_steps must reach exec");
1633 let max_tool_calls_idx = cmd
1634 .args
1635 .iter()
1636 .position(|arg| arg == "--max-tool-calls")
1637 .expect("positive max_tool_calls must reach exec");
1638
1639 assert_eq!(cmd.args[max_turns_idx + 1], "40");
1640 assert_eq!(cmd.args[max_tool_calls_idx + 1], "11");
1641 }
1642
1643 #[test]
1644 fn production_worker_command_uses_hardened_launch_spec_steps() {
1645 let tmp = TempDir::new().unwrap();
1646 let mut task = task("audit");
1647 task.budget = Some(FleetTaskBudget {
1648 max_steps: Some(75),
1649 max_tool_calls: Some(11),
1650 ..FleetTaskBudget::default()
1651 });
1652 let mut launch_spec = launch_spec(&task, tmp.path());
1653 // The manager owns this hardening step. A different value here proves
1654 // production argv comes from the registered spec, not a second budget
1655 // projection from the task document.
1656 launch_spec.max_steps = 13;
1657
1658 let cmd = build_worker_exec_command_with_launch_spec(
1659 "codewhale",
1660 &task,
1661 &launch_spec,
1662 &FleetExecConfig {
1663 max_turns: 40,
1664 ..FleetExecConfig::default()
1665 },
1666 None,
1667 &[],
1668 )
1669 .unwrap();
1670 let max_turns_idx = cmd
1671 .args
1672 .iter()
1673 .position(|arg| arg == "--max-turns")
1674 .expect("hardened launch max_steps must reach exec");
1675 let max_tool_calls_idx = cmd
1676 .args
1677 .iter()
1678 .position(|arg| arg == "--max-tool-calls")
1679 .expect("task max_tool_calls must reach exec");
1680
1681 assert_eq!(cmd.args[max_turns_idx + 1], "13");
1682 assert_eq!(cmd.args[max_tool_calls_idx + 1], "11");
1683 }
1684
1685 #[test]
1686 fn worker_command_threads_agent_profile_prompt() {
1687 let mut task = task("audit");
1688 task.worker.as_mut().unwrap().agent_profile = Some("reviewer".to_string());
1689 let cmd = build_worker_exec_command_with_profiles(
1690 "codewhale",
1691 &task,
1692 &FleetExecConfig::default(),
1693 None,
1694 &[agent_profile(
1695 "reviewer",
1696 "reviewer",
1697 "Focus on defects, regressions, and missing tests.",
1698 )],
1699 )
1700 .unwrap();
1701 let prompt = cmd.args.last().unwrap();
1702
1703 assert!(prompt.contains("Fleet profile: reviewer"));
1704 assert!(prompt.contains("Focus on defects, regressions, and missing tests."));
1705 }
1706
1707 #[test]
1708 fn consultant_launch_spec_carries_read_only_authority_with_network_reads() {
1709 let tmp = TempDir::new().unwrap();
1710 let mut task = task("advise on the release candidate");
1711 task.worker.as_mut().unwrap().role = Some("consultant".to_string());
1712 let launch_spec = launch_spec(&task, tmp.path());
1713 assert_eq!(
1714 launch_spec.agent_type,
1715 codewhale_agent_contract::role::FleetRole::Consultant
1716 );
1717 // Counsel only: never writes the workspace, but may read the web.
1718 assert!(!launch_spec.runtime_profile.permissions.write);
1719 assert!(launch_spec.runtime_profile.permissions.network);
1720
1721 let cmd = build_worker_exec_command_with_launch_spec(
1722 "codewhale",
1723 &task,
1724 &launch_spec,
1725 &FleetExecConfig::default(),
1726 None,
1727 &[],
1728 )
1729 .unwrap();
1730
1731 assert_eq!(cmd.args.last(), Some(&launch_spec.objective));
1732 let authority_index = cmd
1733 .args
1734 .iter()
1735 .position(|arg| arg == "--tool-authority-json")
1736 .expect("launch command must carry machine-readable authority");
1737 let authority = ToolAuthorityEnvelope::from_json(&cmd.args[authority_index + 1]).unwrap();
1738 assert_eq!(authority.owner, "worker-1");
1739 assert_eq!(authority.authority, ToolMutationAuthority::ReadOnly);
1740 assert_eq!(authority.network_access, Some(true));
1741 assert_eq!(authority.shell, ToolShellAuthority::None);
1742 assert_eq!(authority.verification, ToolVerificationAuthority::None);
1743 assert!(authority.writable_roots.is_empty());
1744 assert!(authority.writable_files.is_empty());
1745 assert!(authority.coordination_contracts.is_empty());
1746 }
1747
1748 #[test]
1749 fn governed_worker_uses_admitted_inherited_model_and_provider() {
1750 let tmp = TempDir::new().unwrap();
1751 let task = task("read a fixture");
1752 let launch_spec = launch_spec(&task, tmp.path());
1753 let admitted: FleetResolvedRoute = serde_json::from_value(serde_json::json!({
1754 "provider_id": "first-ocean",
1755 "provider_exact_id": "first-ocean",
1756 "provider_kind": "custom",
1757 "wire_model_id": "shared-chat",
1758 "protocol": "chat_completions",
1759 "source": "runtime_route"
1760 }))
1761 .unwrap();
1762 let command = build_worker_exec_command_with_admitted_route(
1763 "codewhale",
1764 &task,
1765 &launch_spec,
1766 &FleetExecConfig::default(),
1767 None,
1768 &[],
1769 Some(&admitted),
1770 )
1771 .unwrap();
1772 assert_eq!(
1773 &command.args[..4],
1774 &["--model", "shared-chat", "--provider", "first-ocean"]
1775 );
1776 }
1777
1778 #[test]
1779 fn scout_reviewer_and_planner_launches_carry_only_read_only_shell_authority() {
1780 let tmp = TempDir::new().unwrap();
1781 for role in ["scout", "reviewer", "planner"] {
1782 let mut task = task("inspect repository and GitHub state");
1783 task.worker.as_mut().unwrap().role = Some(role.to_string());
1784 let launch_spec = launch_spec(&task, tmp.path());
1785 let cmd = build_worker_exec_command_with_launch_spec(
1786 "codewhale",
1787 &task,
1788 &launch_spec,
1789 &FleetExecConfig::default(),
1790 None,
1791 &[],
1792 )
1793 .unwrap();
1794 let authority_index = cmd
1795 .args
1796 .iter()
1797 .position(|arg| arg == "--tool-authority-json")
1798 .expect("launch command must carry machine-readable authority");
1799 let authority =
1800 ToolAuthorityEnvelope::from_json(&cmd.args[authority_index + 1]).unwrap();
1801
1802 assert_eq!(authority.authority, ToolMutationAuthority::ReadOnly);
1803 assert_eq!(authority.network_access, Some(true));
1804 assert_eq!(authority.shell, ToolShellAuthority::ReadOnly);
1805 assert_eq!(authority.verification, ToolVerificationAuthority::None);
1806 }
1807 }
1808
1809 #[test]
1810 fn verifier_launch_carries_only_bounded_verification_process_authority() {
1811 let tmp = TempDir::new().unwrap();
1812 let mut task = task("run the focused release checks");
1813 task.worker.as_mut().unwrap().role = Some("verifier".to_string());
1814 let mut launch_spec = launch_spec(&task, tmp.path());
1815 let authority = authority_envelope_for_worker(&launch_spec, &task).unwrap();
1816
1817 assert_eq!(authority.authority, ToolMutationAuthority::ReadOnly);
1818 assert_eq!(authority.shell, ToolShellAuthority::None);
1819 assert_eq!(authority.verification, ToolVerificationAuthority::Bounded);
1820
1821 launch_spec.runtime_profile.shell =
1822 codewhale_agent_contract::worker_profile::ShellPolicy::None;
1823 let shellless = authority_envelope_for_worker(&launch_spec, &task).unwrap();
1824 assert_eq!(
1825 shellless.verification,
1826 ToolVerificationAuthority::None,
1827 "the parent shell ceiling also removes bounded verification process authority"
1828 );
1829 }
1830
1831 #[test]
1832 fn launch_spec_command_preserves_exact_write_scope() {
1833 let tmp = TempDir::new().unwrap();
1834 let mut task = task("edit the bounded source tree");
1835 let worker = task.worker.as_mut().unwrap();
1836 worker.role = Some("implementer".to_string());
1837 worker.tool_profile = None;
1838 task.workspace = Some(FleetWorkspaceRequirements {
1839 placement: None,
1840 writable_paths: vec![std::path::PathBuf::from("src")],
1841 ..FleetWorkspaceRequirements::default()
1842 });
1843 let launch_spec = launch_spec(&task, tmp.path());
1844
1845 let cmd = build_worker_exec_command_with_launch_spec(
1846 "codewhale",
1847 &task,
1848 &launch_spec,
1849 &FleetExecConfig::default(),
1850 None,
1851 &[],
1852 )
1853 .unwrap();
1854 let authority_index = cmd
1855 .args
1856 .iter()
1857 .position(|arg| arg == "--tool-authority-json")
1858 .expect("launch command must carry machine-readable authority");
1859 let authority = ToolAuthorityEnvelope::from_json(&cmd.args[authority_index + 1]).unwrap();
1860
1861 assert_eq!(authority.authority, ToolMutationAuthority::ScopedWrite);
1862 assert_eq!(authority.network_access, Some(true));
1863 assert_eq!(authority.shell, ToolShellAuthority::None);
1864 assert_eq!(authority.verification, ToolVerificationAuthority::None);
1865 assert_eq!(authority.writable_roots, ["src"]);
1866 assert!(authority.writable_files.is_empty());
1867 assert!(authority.coordination_contracts.is_empty());
1868 assert_eq!(cmd.args.last(), Some(&launch_spec.objective));
1869 }
1870
1871 /// #4093 AC #4 at the LAUNCH boundary (not just the receipt): a worker whose
1872 /// profile pins a DIFFERENT provider+model than the parent session must
1873 /// actually launch on the profile's route and saved reasoning tier. The
1874 /// parent session is DeepSeek here (`--model deepseek-v4-pro`); the profile
1875 /// pins OpenRouter + glm-5.2 + max thinking. The emitted argv must carry
1876 /// OpenRouter's id, the profile's model, and the profile's thinking tier as
1877 /// paired flag/values — never the parent's model. This is the gap the
1878 /// save→load→resolve receipt tests never covered.
1879 #[test]
1880 fn worker_command_launches_profile_bound_provider_and_model_not_the_parent() {
1881 let mut task = task("audit");
1882 task.worker.as_mut().unwrap().agent_profile = Some("cross".to_string());
1883
1884 let mut profile = agent_profile("cross", "scout", "Read first.");
1885 profile.profile.provider = Some("openrouter".to_string());
1886 profile.profile.model = Some("glm-5.2".to_string());
1887 profile.profile.reasoning_effort = Some("max".to_string());
1888
1889 let cmd = build_worker_exec_command_with_profiles(
1890 "codewhale",
1891 &task,
1892 &FleetExecConfig::default(),
1893 Some("deepseek-v4-pro"), // parent/session model on provider A.
1894 &[profile],
1895 )
1896 .unwrap();
1897
1898 // Assert the flag/value PAIRS, so the provider and model are proven to
1899 // ride together rather than merely appearing somewhere on the argv.
1900 let provider_idx = cmd
1901 .args
1902 .iter()
1903 .position(|a| a == "--provider")
1904 .expect("--provider must be threaded for a provider-pinned worker");
1905 let exec_idx = cmd
1906 .args
1907 .iter()
1908 .position(|a| a == "exec")
1909 .expect("worker command must contain exec");
1910 assert_eq!(
1911 cmd.args.get(provider_idx + 1).map(String::as_str),
1912 Some("openrouter"),
1913 "{:?}",
1914 cmd.args
1915 );
1916 assert!(
1917 provider_idx < exec_idx,
1918 "global --provider must precede exec: {:?}",
1919 cmd.args
1920 );
1921 let model_idx = cmd
1922 .args
1923 .iter()
1924 .position(|a| a == "--model")
1925 .expect("--model must be present");
1926 assert_eq!(
1927 cmd.args.get(model_idx + 1).map(String::as_str),
1928 Some("glm-5.2"),
1929 "{:?}",
1930 cmd.args
1931 );
1932 assert!(
1933 model_idx < exec_idx,
1934 "global --model must precede exec: {:?}",
1935 cmd.args
1936 );
1937 let reasoning_idx = cmd
1938 .args
1939 .iter()
1940 .position(|a| a == "--reasoning-effort")
1941 .expect("--reasoning-effort must be present for a thinking-pinned worker");
1942 assert_eq!(
1943 cmd.args.get(reasoning_idx + 1).map(String::as_str),
1944 Some("max"),
1945 "{:?}",
1946 cmd.args
1947 );
1948 assert!(
1949 reasoning_idx > exec_idx,
1950 "exec-only --reasoning-effort must follow exec: {:?}",
1951 cmd.args
1952 );
1953
1954 assert_eq!(
1955 &cmd.args[..exec_idx],
1956 ["--model", "glm-5.2", "--provider", "openrouter"],
1957 "route flags must form the complete global prefix: {:?}",
1958 cmd.args
1959 );
1960 assert_eq!(
1961 &cmd.args[exec_idx..exec_idx + 5],
1962 [
1963 "exec",
1964 "--auto",
1965 "--output-format",
1966 "stream-json",
1967 "--parent-death-watch"
1968 ],
1969 "exec flags must remain behind the subcommand: {:?}",
1970 cmd.args
1971 );
1972
1973 // The parent/session model must NOT leak onto the argv.
1974 assert!(
1975 !cmd.args.iter().any(|a| a == "deepseek-v4-pro"),
1976 "parent model leaked into a profile-pinned worker's argv: {:?}",
1977 cmd.args
1978 );
1979 }
1980
1981 #[test]
1982 fn worker_command_threads_custom_profile_provider_name() {
1983 let mut task = task("format");
1984 task.worker.as_mut().unwrap().agent_profile = Some("local".to_string());
1985
1986 let mut profile = agent_profile("local", "formatter", "Keep edits tight.");
1987 profile.profile.provider = Some("lm-studio".to_string());
1988 profile.profile.model = Some("qwen-2.5-7b".to_string());
1989
1990 let cmd = build_worker_exec_command_with_profiles(
1991 "codewhale",
1992 &task,
1993 &FleetExecConfig::default(),
1994 Some("deepseek-v4-pro"),
1995 &[profile],
1996 )
1997 .unwrap();
1998
1999 let provider_idx = cmd
2000 .args
2001 .iter()
2002 .position(|a| a == "--provider")
2003 .expect("--provider must be threaded for a custom provider pin");
2004 assert_eq!(
2005 cmd.args.get(provider_idx + 1).map(String::as_str),
2006 Some("lm-studio"),
2007 "{:?}",
2008 cmd.args
2009 );
2010 let exec_idx = cmd
2011 .args
2012 .iter()
2013 .position(|a| a == "exec")
2014 .expect("worker command must contain exec");
2015 assert!(
2016 provider_idx < exec_idx,
2017 "global --provider must precede exec: {:?}",
2018 cmd.args
2019 );
2020 let model_idx = cmd
2021 .args
2022 .iter()
2023 .position(|a| a == "--model")
2024 .expect("--model must be present");
2025 assert_eq!(
2026 cmd.args.get(model_idx + 1).map(String::as_str),
2027 Some("qwen-2.5-7b"),
2028 "{:?}",
2029 cmd.args
2030 );
2031 assert!(
2032 model_idx < exec_idx,
2033 "global --model must precede exec: {:?}",
2034 cmd.args
2035 );
2036 }
2037
2038 /// A worker with no profile-bound provider preserves today's behavior: the
2039 /// run-level model on `--model`, and NO `--provider` (the worker keeps its
2040 /// own session default). Guards against regressing profile-less workers.
2041 #[test]
2042 fn worker_command_without_profile_provider_omits_provider_and_keeps_run_model() {
2043 let cmd = build_worker_exec_command_with_profiles(
2044 "codewhale",
2045 &task("read"),
2046 &FleetExecConfig::default(),
2047 Some("deepseek-v4-pro"),
2048 &[],
2049 )
2050 .unwrap();
2051
2052 assert!(
2053 !cmd.args.iter().any(|a| a == "--provider"),
2054 "profile-less worker must not carry --provider: {:?}",
2055 cmd.args
2056 );
2057 assert!(
2058 !cmd.args.iter().any(|a| a == "--reasoning-effort"),
2059 "profile-less worker must not carry --reasoning-effort: {:?}",
2060 cmd.args
2061 );
2062 let model_idx = cmd
2063 .args
2064 .iter()
2065 .position(|a| a == "--model")
2066 .expect("--model must be present");
2067 assert_eq!(
2068 cmd.args.get(model_idx + 1).map(String::as_str),
2069 Some("deepseek-v4-pro"),
2070 "{:?}",
2071 cmd.args
2072 );
2073 let exec_idx = cmd
2074 .args
2075 .iter()
2076 .position(|a| a == "exec")
2077 .expect("worker command must contain exec");
2078 assert!(
2079 model_idx < exec_idx,
2080 "global --model must precede exec: {:?}",
2081 cmd.args
2082 );
2083 }
2084
2085 #[test]
2086 fn zero_max_turns_is_not_passed() {
2087 // Zero task budgets and max_turns mean "no cap"; neither flag should
2088 // appear in the command.
2089 let exec = FleetExecConfig {
2090 max_turns: 0,
2091 ..Default::default()
2092 };
2093 let mut task = task("x");
2094 task.budget = Some(FleetTaskBudget {
2095 max_steps: Some(0),
2096 max_tool_calls: Some(0),
2097 ..FleetTaskBudget::default()
2098 });
2099 let cmd = build_worker_exec_command("codewhale", &task, &exec, None);
2100 assert!(!cmd.args.join(" ").contains("--max-turns"));
2101 assert!(!cmd.args.join(" ").contains("--max-tool-calls"));
2102 }
2103
2104 #[test]
2105 fn stream_line_maps_tool_use_to_running_tool() {
2106 let line = r#"{"type":"tool_use","name":"read_file","id":"call-7","input":{}}"#;
2107 match map_exec_stream_line(line) {
2108 Some(FleetWorkerEventPayload::RunningTool { tool, call_id }) => {
2109 assert_eq!(tool, "read_file");
2110 assert_eq!(call_id.as_deref(), Some("call-7"));
2111 }
2112 other => panic!("expected RunningTool, got {other:?}"),
2113 }
2114 }
2115
2116 #[test]
2117 fn stream_line_maps_done_and_error() {
2118 assert!(matches!(
2119 map_exec_stream_line(r#"{"type":"done"}"#),
2120 Some(FleetWorkerEventPayload::Completed { .. })
2121 ));
2122 match map_exec_stream_line(r#"{"type":"error","error":"boom"}"#) {
2123 Some(FleetWorkerEventPayload::Failed { reason, .. }) => assert_eq!(reason, "boom"),
2124 other => panic!("expected Failed, got {other:?}"),
2125 }
2126 }
2127
2128 #[test]
2129 fn stream_line_maps_workflow_receipt_to_typed_event() {
2130 let line =
2131 r#"{"type":"workflow_event","run_id":"workflow_1","event":{"type":"task_completed"}}"#;
2132 match map_exec_stream_line(line) {
2133 Some(FleetWorkerEventPayload::WorkflowEvent {
2134 workflow_run_id,
2135 event,
2136 }) => {
2137 assert_eq!(workflow_run_id, "workflow_1");
2138 assert_eq!(event["type"], "task_completed");
2139 }
2140 other => panic!("expected typed workflow receipt, got {other:?}"),
2141 }
2142 }
2143
2144 #[test]
2145 fn stream_line_ignores_noise_and_bad_json() {
2146 assert!(map_exec_stream_line(r#"{"type":"session_capture","content":"x"}"#).is_none());
2147 assert!(map_exec_stream_line("not json").is_none());
2148 assert!(map_exec_stream_line("").is_none());
2149 }
2150
2151 #[test]
2152 fn terminal_route_keeps_exact_literal_custom_distinct_from_idless_root_and_redacts() {
2153 let exact = map_exec_terminal_route(
2154 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"custom","model":"literal-model","base_url":"https://must-not-cross.invalid/v1","api_key":"sk-must-not-cross"}}"#,
2155 )
2156 .expect("literal custom terminal route");
2157 assert_eq!(exact.provider, "custom");
2158 assert_eq!(exact.provider_exact_id.as_deref(), Some("custom"));
2159 assert_eq!(exact.model, "literal-model");
2160
2161 let root = map_exec_terminal_route(
2162 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","model":"root-model"}}"#,
2163 )
2164 .expect("idless root custom terminal route");
2165 assert_eq!(root.provider, "custom");
2166 assert_eq!(root.provider_exact_id, None);
2167 assert_eq!(root.model, "root-model");
2168
2169 let named = map_exec_terminal_route(
2170 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"lm-studio","model":"local-model"}}"#,
2171 )
2172 .expect("named custom terminal route");
2173 assert_eq!(named.provider, "custom");
2174 assert_eq!(named.provider_exact_id.as_deref(), Some("lm-studio"));
2175 assert_eq!(named.model, "local-model");
2176
2177 let reported = format!("{exact:?}").to_ascii_lowercase();
2178 for forbidden in ["base_url", "https://", "api_key", "sk-must-not-cross"] {
2179 assert!(
2180 !reported.contains(forbidden),
2181 "allowlisted terminal route leaked {forbidden:?}: {reported}"
2182 );
2183 }
2184
2185 for malformed in [
2186 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"","model":"root-model"}}"#,
2187 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":" ","model":"root-model"}}"#,
2188 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":7,"model":"root-model"}}"#,
2189 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"deepseek","provider_id":"custom-x","model":"deepseek-v4-pro"}}"#,
2190 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"unknown-kind","model":"unknown-model"}}"#,
2191 ] {
2192 assert!(
2193 map_exec_terminal_route(malformed).is_none(),
2194 "malformed present exact id must not collapse to idless root: {malformed}"
2195 );
2196 }
2197 }
2198
2199 #[test]
2200 fn terminal_route_evidence_requires_exactly_one_valid_envelope() {
2201 let route_x = r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"remote-x","model":"worker-model-x"}}"#;
2202 let route_y = r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"remote-y","model":"worker-model-y"}}"#;
2203 let malformed = r#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"","model":"worker-model-x"}}"#;
2204 let noise = r#"{"type":"content","delta":"progress"}"#;
2205
2206 let observe = |lines: &[&str]| {
2207 let mut evidence = TerminalRouteEvidence::default();
2208 for line in lines {
2209 let value: serde_json::Value = serde_json::from_str(line).unwrap();
2210 evidence.observe(parse_exec_terminal_route(&value));
2211 }
2212 evidence.reported_route().cloned()
2213 };
2214
2215 let only = observe(&[noise, route_x]).expect("one valid route");
2216 assert_eq!(only.provider_exact_id.as_deref(), Some("remote-x"));
2217 assert!(
2218 observe(&[route_x, malformed]).is_none(),
2219 "valid then malformed must invalidate stale evidence"
2220 );
2221 assert!(
2222 observe(&[malformed, route_x]).is_none(),
2223 "malformed then valid must remain invalid"
2224 );
2225 assert!(
2226 observe(&[route_x, route_y]).is_none(),
2227 "conflicting valid routes must be ambiguous"
2228 );
2229 assert!(
2230 observe(&[route_x, route_x]).is_none(),
2231 "even identical duplicates violate the exactly-one contract"
2232 );
2233 }
2234
2235 #[test]
2236 fn exit_classification() {
2237 assert!(matches!(
2238 classify_worker_exit(Some(0), false),
2239 FleetWorkerEventPayload::Completed { .. }
2240 ));
2241 for exit_code in [Some(1), Some(75), None] {
2242 assert!(matches!(
2243 classify_worker_exit(exit_code, false),
2244 FleetWorkerEventPayload::Failed {
2245 recoverable: false,
2246 ..
2247 }
2248 ));
2249 }
2250 assert!(matches!(
2251 classify_worker_exit(Some(0), true),
2252 FleetWorkerEventPayload::Cancelled { .. }
2253 ));
2254 }
2255
2256 /// End-to-end: run a REAL subprocess that emits stream-json (standing in for
2257 /// `codewhale exec`), and prove the executor drains its events and terminal
2258 /// exit through the real host adapter — no codewhale binary needed. This is
2259 /// the verifiable proof that a fleet worker is an out-of-process exec run.
2260 #[cfg(unix)]
2261 #[test]
2262 fn executor_runs_real_process_and_drains_stream_json_into_ledger_events() {
2263 let tmp = tempfile::TempDir::new().unwrap();
2264 let mut exec = FleetExecutor::new(tmp.path());
2265 let script = r#"printf '{"type":"tool_use","name":"read_file","id":"c1","input":{}}\n'; printf '{"type":"done"}\n'"#;
2266 let command = FleetWorkerCommand::new("sh", vec!["-c".to_string(), script.to_string()]);
2267 exec.start_worker("w1", command, None).unwrap();
2268
2269 let mut events = Vec::new();
2270 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2271 loop {
2272 events.extend(exec.drain_events("w1"));
2273 if let Some(term) = exec.poll_terminal("w1") {
2274 while !events.iter().any(|e| {
2275 matches!(e, FleetWorkerEventPayload::RunningTool { tool, .. } if tool == "read_file")
2276 }) && std::time::Instant::now() < deadline
2277 {
2278 events.extend(exec.drain_events("w1"));
2279 std::thread::sleep(std::time::Duration::from_millis(20));
2280 }
2281 events.push(term);
2282 break;
2283 }
2284 assert!(
2285 std::time::Instant::now() < deadline,
2286 "worker did not terminate; events so far: {events:?}"
2287 );
2288 std::thread::sleep(std::time::Duration::from_millis(20));
2289 }
2290
2291 assert!(
2292 events.iter().any(|e| matches!(
2293 e,
2294 FleetWorkerEventPayload::RunningTool { tool, .. } if tool == "read_file"
2295 )),
2296 "expected a RunningTool(read_file) event, got {events:?}"
2297 );
2298 assert!(
2299 events
2300 .iter()
2301 .any(|e| matches!(e, FleetWorkerEventPayload::Completed { .. })),
2302 "expected a terminal Completed event, got {events:?}"
2303 );
2304 assert!(exec.all_terminal());
2305 }
2306
2307 #[cfg(unix)]
2308 fn run_worker_to_terminal(script: &str, worker_id: &str) -> FleetWorkerTerminalEvent {
2309 let tmp = tempfile::TempDir::new().unwrap();
2310 let mut exec = FleetExecutor::new(tmp.path());
2311 let command = FleetWorkerCommand::new("sh", vec!["-c".to_string(), script.to_string()]);
2312 exec.start_worker(worker_id, command, None).unwrap();
2313
2314 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2315 loop {
2316 exec.drain_events(worker_id);
2317 if let Some(term) = exec.poll_terminal_with_status(worker_id) {
2318 break term;
2319 }
2320 assert!(
2321 std::time::Instant::now() < deadline,
2322 "worker did not terminate in time"
2323 );
2324 std::thread::sleep(std::time::Duration::from_millis(20));
2325 }
2326 }
2327
2328 #[cfg(unix)]
2329 #[test]
2330 fn completed_worker_surfaces_terminal_final_answer_as_summary() {
2331 // Report/summary tasks produce their deliverable as the final
2332 // assistant reply, not a file artifact. The exec side emits a bounded
2333 // excerpt plus the real length on its terminal receipt; the executor
2334 // reads that (never the streamed `content` deltas, which are the run
2335 // thinking out loud) and attaches it to `Completed.summary` and the
2336 // terminal event so a receipt can show the actual result.
2337 let script = r#"printf '%s\n' '{"type":"content","content":"let me look first"}' '{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"remote-x","model":"worker-model","visible_final_answer_chars":9000,"visible_final_answer_excerpt":"the report..."}}' '{"type":"done"}'"#;
2338 let terminal = run_worker_to_terminal(script, "w1");
2339
2340 match &terminal.payload {
2341 FleetWorkerEventPayload::Completed { summary, .. } => {
2342 assert_eq!(summary.as_deref(), Some("the report..."));
2343 }
2344 other => panic!("expected Completed, got {other:?}"),
2345 }
2346 assert_eq!(
2347 terminal.final_answer,
2348 Some(FleetWorkerFinalAnswer {
2349 excerpt: "the report...".to_string(),
2350 chars: 9000,
2351 })
2352 );
2353 }
2354
2355 #[cfg(unix)]
2356 #[test]
2357 fn failed_worker_keeps_terminal_final_answer_on_terminal_event() {
2358 // A worker that fails after writing most of a report still reports
2359 // its visible answer on the terminal receipt; the executor keeps it
2360 // on the terminal event so the receipt can retain the text.
2361 let script = r#"printf '%s\n' '{"type":"error","error":"boom"}' '{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"remote-x","model":"worker-model","visible_final_answer_chars":12,"visible_final_answer_excerpt":"partial text"}}'; exit 1"#;
2362 let terminal = run_worker_to_terminal(script, "w-failed");
2363
2364 assert!(
2365 matches!(terminal.payload, FleetWorkerEventPayload::Failed { .. }),
2366 "{:?}",
2367 terminal.payload
2368 );
2369 assert_eq!(
2370 terminal
2371 .final_answer
2372 .as_ref()
2373 .map(|answer| answer.excerpt.as_str()),
2374 Some("partial text")
2375 );
2376 }
2377
2378 #[cfg(unix)]
2379 #[test]
2380 fn unbound_worker_session_claim_is_not_advertised() {
2381 // The worker persists its full transcript as a saved session and
2382 // reports the recoverable id via `session_capture.saved_session_id`.
2383 // The executor must capture that id on the terminal event so a caller
2384 // can resolve the final assistant reply through `GET /v1/sessions/{id}`.
2385 let script = r#"printf '%s\n' '{"type":"session_capture","content":"<redacted:log-only>","saved_session_id":"session-abc"}' '{"type":"done"}'"#;
2386 let terminal = run_worker_to_terminal(script, "w-session");
2387
2388 assert!(terminal.saved_session_id.is_none());
2389 assert!(terminal.final_answer.is_none());
2390 }
2391
2392 #[cfg(unix)]
2393 #[test]
2394 fn worker_session_capture_requires_the_parent_id_and_a_saved_local_transcript() {
2395 for (persist, forged) in [(true, false), (false, false), (true, true)] {
2396 let tmp = tempfile::TempDir::new().unwrap();
2397 let sessions_dir = tmp.path().join("runtime-sessions");
2398 let manager =
2399 crate::session_manager::SessionManager::new(sessions_dir.clone()).unwrap();
2400 let mut executor = FleetExecutor::new(tmp.path()).with_sessions_dir(sessions_dir);
2401 let script = if forged {
2402 r#"printf '{"type":"session_capture","saved_session_id":"%s"}\n' "$CODEWHALE_FLEET_CAPTURE_ID"; printf '%s\n' '{"type":"session_capture","saved_session_id":"unrelated-session"}'"#
2403 } else {
2404 r#"printf '{"type":"session_capture","saved_session_id":"%s"}\n' "$CODEWHALE_FLEET_CAPTURE_ID""#
2405 };
2406 executor
2407 .start_worker(
2408 "capture-worker",
2409 FleetWorkerCommand::new("sh", ["-c", script]),
2410 None,
2411 )
2412 .unwrap();
2413 let expected = executor.streams["capture-worker"]
2414 .session_capture
2415 .as_ref()
2416 .unwrap()
2417 .0
2418 .clone();
2419 if persist {
2420 let saved = crate::session_manager::create_saved_session_with_id_and_mode(
2421 expected.clone(),
2422 &[],
2423 "fixture-model",
2424 tmp.path(),
2425 0,
2426 None,
2427 Some("exec"),
2428 );
2429 manager.save_session(&saved).unwrap();
2430 }
2431 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2432 let terminal = loop {
2433 if let Some(terminal) = executor.poll_terminal_with_status("capture-worker") {
2434 break terminal;
2435 }
2436 assert!(std::time::Instant::now() < deadline);
2437 std::thread::sleep(std::time::Duration::from_millis(20));
2438 };
2439 assert_eq!(
2440 terminal.saved_session_id,
2441 (persist && !forged).then_some(expected)
2442 );
2443 }
2444 }
2445
2446 #[test]
2447 fn terminal_final_answer_is_bounded_and_redacted_at_the_worker_boundary() {
2448 let answer = parse_exec_terminal_final_answer(&serde_json::json!({
2449 "type": "metadata", "meta": { "receipt_kind": "terminal",
2450 "visible_final_answer_excerpt": format!("sk-ant-must-not-leak-1234567890 {}", "x".repeat(8000)),
2451 "visible_final_answer_chars": 9000,
2452 }
2453 })).unwrap();
2454 assert!(!answer.excerpt.contains("sk-ant-must-not-leak"));
2455 assert!(
2456 answer.excerpt.chars().count() <= super::EXEC_STREAM_FINAL_ANSWER_EXCERPT_CHARS + 3
2457 );
2458 assert_eq!(answer.chars, 9000);
2459 }
2460
2461 #[test]
2462 fn terminal_final_answer_ignores_empty_and_nonterminal_receipts() {
2463 let parse =
2464 |line: &str| parse_exec_terminal_final_answer(&serde_json::from_str(line).unwrap());
2465 assert!(parse(r#"{"type":"content","content":"streamed"}"#).is_none());
2466 assert!(
2467 parse(r#"{"type":"metadata","meta":{"receipt_kind":"turn","visible_final_answer_excerpt":"x"}}"#)
2468 .is_none()
2469 );
2470 assert!(
2471 parse(r#"{"type":"metadata","meta":{"receipt_kind":"terminal","visible_final_answer_excerpt":" "}}"#)
2472 .is_none()
2473 );
2474 // A receipt without the count falls back to the excerpt length.
2475 assert_eq!(
2476 parse(
2477 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","visible_final_answer_excerpt":"héllo"}}"#
2478 ),
2479 Some(FleetWorkerFinalAnswer {
2480 excerpt: "héllo".to_string(),
2481 chars: 5,
2482 })
2483 );
2484 }
2485
2486 #[cfg(unix)]
2487 #[test]
2488 fn terminal_poll_final_drains_route_metadata_and_tail_payloads() {
2489 let tmp = tempfile::TempDir::new().unwrap();
2490 let mut exec = FleetExecutor::new(tmp.path());
2491 let script = r#"printf '%s\n' '{"type":"content","delta":"tail progress"}'; printf '%s' '{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"remote-x","model":"worker-model-x"}}'"#;
2492 let command = FleetWorkerCommand::new("sh", vec!["-c".to_string(), script.to_string()]);
2493 exec.start_worker("tail-worker", command, None).unwrap();
2494
2495 // Deliberately do not call the ordinary event drain. Poll only after
2496 // exit, reproducing the scheduler gap where the previous poll saw EOF
2497 // just before the worker wrote its terminal tail.
2498 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2499 let terminal = loop {
2500 if let Some(terminal) = exec.poll_terminal_with_status("tail-worker") {
2501 break terminal;
2502 }
2503 assert!(std::time::Instant::now() < deadline, "terminal worker");
2504 std::thread::sleep(std::time::Duration::from_millis(10));
2505 };
2506 let route = terminal.reported_route.expect("final-drained route");
2507 assert_eq!(route.provider, "custom");
2508 assert_eq!(route.provider_exact_id.as_deref(), Some("remote-x"));
2509 assert_eq!(route.model, "worker-model-x");
2510 assert!(
2511 terminal
2512 .tail_payloads
2513 .iter()
2514 .any(|payload| matches!(payload, FleetWorkerEventPayload::Running))
2515 );
2516 }
2517
2518 #[cfg(unix)]
2519 #[test]
2520 fn terminal_poll_trailing_malformed_route_invalidates_prior_valid_route() {
2521 let tmp = tempfile::TempDir::new().unwrap();
2522 let mut exec = FleetExecutor::new(tmp.path());
2523 let script = r#"printf '%s\n' '{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"remote-x","model":"worker-model-x"}}'; printf '%s' '{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"","model":"worker-model-x"}}'"#;
2524 let command = FleetWorkerCommand::new("sh", vec!["-c".to_string(), script.to_string()]);
2525 exec.start_worker("ambiguous-tail-worker", command, None)
2526 .unwrap();
2527
2528 // Keep all output for the terminal drain, but wait for real worker
2529 // exit instead of assuming the shell finishes within one timer tick.
2530 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2531 let terminal = loop {
2532 if let Some(terminal) = exec.poll_terminal_with_status("ambiguous-tail-worker") {
2533 break terminal;
2534 }
2535 assert!(std::time::Instant::now() < deadline, "terminal worker");
2536 std::thread::sleep(std::time::Duration::from_millis(10));
2537 };
2538 assert!(
2539 terminal.reported_route.is_none(),
2540 "malformed trailing terminal evidence must invalidate the prior valid route"
2541 );
2542 }
2543
2544 /// Dogfood smoke (#3166): several concurrent exec-style workers with one
2545 /// injected failure. Proves the executor drives a small fleet to terminal
2546 /// outcomes and that a failing worker is classified distinctly from the
2547 /// passing ones — all without the codewhale binary.
2548 #[cfg(unix)]
2549 #[test]
2550 fn executor_drives_concurrent_workers_with_injected_failure() {
2551 let tmp = tempfile::TempDir::new().unwrap();
2552 let mut exec = FleetExecutor::new(tmp.path());
2553
2554 // Three healthy workers emit a tool_use + done; one injected-failure
2555 // worker emits an error event and exits non-zero.
2556 let ok = r#"printf '{"type":"tool_use","name":"grep_files","id":"c","input":{}}\n{"type":"done"}\n'"#;
2557 let bad = r#"printf '{"type":"error","error":"injected failure"}\n'; exit 7"#;
2558 for id in ["w1", "w2", "w3"] {
2559 exec.start_worker(
2560 id,
2561 FleetWorkerCommand::new("sh", vec!["-c".to_string(), ok.to_string()]),
2562 None,
2563 )
2564 .unwrap();
2565 }
2566 exec.start_worker(
2567 "w-fail",
2568 FleetWorkerCommand::new("sh", vec!["-c".to_string(), bad.to_string()]),
2569 None,
2570 )
2571 .unwrap();
2572
2573 let ids = ["w1", "w2", "w3", "w-fail"];
2574 let mut terminals: std::collections::BTreeMap<&str, FleetWorkerEventPayload> =
2575 std::collections::BTreeMap::new();
2576 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(8);
2577 while terminals.len() < ids.len() {
2578 for id in ids {
2579 let _ = exec.drain_events(id);
2580 if let Some(term) = exec.poll_terminal(id) {
2581 terminals.insert(id, term);
2582 }
2583 }
2584 assert!(
2585 std::time::Instant::now() < deadline,
2586 "not all workers terminated: {terminals:?}"
2587 );
2588 std::thread::sleep(std::time::Duration::from_millis(20));
2589 }
2590
2591 assert!(exec.all_terminal());
2592 for id in ["w1", "w2", "w3"] {
2593 assert!(
2594 matches!(terminals[id], FleetWorkerEventPayload::Completed { .. }),
2595 "{id} should pass, got {:?}",
2596 terminals[id]
2597 );
2598 }
2599 assert!(
2600 matches!(terminals["w-fail"], FleetWorkerEventPayload::Failed { .. }),
2601 "injected-failure worker should fail, got {:?}",
2602 terminals["w-fail"]
2603 );
2604 }
2605
2606 #[test]
2607 fn terminal_route_preserves_multibyte_identity_across_read_boundaries() {
2608 let tmp = tempfile::TempDir::new().unwrap();
2609 let log_path = tmp.path().join("split-utf8.jsonl");
2610 std::fs::write(&log_path, []).unwrap();
2611 let mut executor = FleetExecutor::new(tmp.path());
2612 track_test_stream(&mut executor, "split-utf8", log_path.clone());
2613
2614 let provider_id = "深海鲸-供应商";
2615 let model = "深潜-模型";
2616 let line = format!(
2617 "{{\"type\":\"metadata\",\"meta\":{{\"receipt_kind\":\"terminal\",\"provider\":\"custom\",\"provider_id\":\"{provider_id}\",\"model\":\"{model}\"}}}}\n"
2618 );
2619 let bytes = line.as_bytes();
2620 let provider_start = bytes
2621 .windows("鲸".len())
2622 .position(|window| window == "鲸".as_bytes())
2623 .unwrap();
2624 let model_start = bytes
2625 .windows("潜".len())
2626 .position(|window| window == "潜".as_bytes())
2627 .unwrap();
2628 let provider_split = provider_start + 1;
2629 let model_split = model_start + 2;
2630
2631 append_test_stream(&log_path, &bytes[..provider_split]);
2632 assert!(executor.drain_events("split-utf8").is_empty());
2633 append_test_stream(&log_path, &bytes[provider_split..model_split]);
2634 assert!(executor.drain_events("split-utf8").is_empty());
2635 append_test_stream(&log_path, &bytes[model_split..]);
2636 assert!(executor.drain_events("split-utf8").is_empty());
2637
2638 let route = executor
2639 .streams
2640 .get("split-utf8")
2641 .and_then(|stream| stream.terminal_route.reported_route())
2642 .expect("one exact terminal route");
2643 assert_eq!(route.provider, "custom");
2644 assert_eq!(route.provider_exact_id.as_deref(), Some(provider_id));
2645 assert_eq!(route.model, model);
2646 }
2647
2648 #[test]
2649 fn invalid_utf8_terminal_route_fails_closed_without_lossy_identity() {
2650 let tmp = tempfile::TempDir::new().unwrap();
2651 let log_path = tmp.path().join("invalid-utf8.jsonl");
2652 let mut line = br#"{"type":"metadata","meta":{"receipt_kind":"terminal","provider":"custom","provider_id":"remote-x","model":"worker-model"}}"#.to_vec();
2653 let invalid_at = line
2654 .windows(b"remote-x".len())
2655 .position(|window| window == b"remote-x")
2656 .unwrap()
2657 + 3;
2658 line[invalid_at] = 0xff;
2659 line.push(b'\n');
2660 std::fs::write(&log_path, line).unwrap();
2661
2662 let mut executor = FleetExecutor::new(tmp.path());
2663 track_test_stream(&mut executor, "invalid-utf8", log_path);
2664 assert!(executor.drain_events("invalid-utf8").is_empty());
2665 assert!(matches!(
2666 executor
2667 .streams
2668 .get("invalid-utf8")
2669 .map(|stream| &stream.terminal_route),
2670 Some(TerminalRouteEvidence::InvalidOrAmbiguous)
2671 ));
2672 }
2673
2674 #[test]
2675 fn invalid_utf8_nonterminal_line_cannot_synthesize_route_evidence() {
2676 let tmp = tempfile::TempDir::new().unwrap();
2677 let log_path = tmp.path().join("invalid-nonterminal.jsonl");
2678 let mut line = br#"{"type":"content","delta":"ordinary-output"}"#.to_vec();
2679 let invalid_at = line
2680 .windows(b"ordinary-output".len())
2681 .position(|window| window == b"ordinary-output")
2682 .unwrap()
2683 + 4;
2684 line[invalid_at] = 0xff;
2685 line.push(b'\n');
2686 std::fs::write(&log_path, line).unwrap();
2687
2688 let mut executor = FleetExecutor::new(tmp.path());
2689 track_test_stream(&mut executor, "invalid-nonterminal", log_path);
2690 assert!(executor.drain_events("invalid-nonterminal").is_empty());
2691 assert!(
2692 executor
2693 .streams
2694 .get("invalid-nonterminal")
2695 .and_then(|stream| stream.terminal_route.reported_route())
2696 .is_none()
2697 );
2698 }
2699
2700 #[test]
2701 fn build_worker_exec_command_supports_external_agent_and_read_only_authority() {
2702 let mut t = task("audit the repo");
2703 t.worker.as_mut().unwrap().external_agent = Some("claude".to_string());
2704 t.worker.as_mut().unwrap().external_agent_transport = Some("cli".to_string());
2705 let exec = FleetExecConfig::default();
2706
2707 let write_cmd = build_worker_exec_command_from_prompt(
2708 "codewhale",
2709 "implement fix".to_string(),
2710 &exec,
2711 WorkerExecRoute {
2712 model: Some("claude-sonnet-4-6"),
2713 provider: Some("anthropic"),
2714 reasoning_effort: Some("high"),
2715 external_agent: Some("claude"),
2716 external_agent_transport: Some("cli"),
2717 },
2718 None,
2719 WorkerExecLimits::default(),
2720 );
2721 assert_eq!(
2722 write_cmd.args,
2723 vec![
2724 "--agent",
2725 "claude",
2726 "--agent-transport",
2727 "cli",
2728 "--model",
2729 "claude-sonnet-4-6",
2730 "exec",
2731 "--auto",
2732 "--output-format",
2733 "stream-json",
2734 "--parent-death-watch",
2735 "--reasoning-effort",
2736 "high",
2737 "implement fix",
2738 ]
2739 );
2740
2741 let ro_envelope = ToolAuthorityEnvelope {
2742 schema_version: 1,
2743 owner: "w1".to_string(),
2744 authority: ToolMutationAuthority::ReadOnly,
2745 network_access: Some(false),
2746 shell: ToolShellAuthority::None,
2747 verification: ToolVerificationAuthority::None,
2748 writable_roots: vec![],
2749 writable_files: vec![],
2750 coordination_contracts: vec![],
2751 };
2752 let ro_cmd = build_worker_exec_command_from_prompt(
2753 "codewhale",
2754 "review only".to_string(),
2755 &exec,
2756 WorkerExecRoute {
2757 model: Some("auto"),
2758 provider: Some("deepseek"),
2759 reasoning_effort: None,
2760 external_agent: Some("codex"),
2761 external_agent_transport: None,
2762 },
2763 Some(&ro_envelope),
2764 WorkerExecLimits::default(),
2765 );
2766 assert_eq!(
2767 ro_cmd.args,
2768 vec![
2769 "--agent",
2770 "codex",
2771 "--permission-mode",
2772 "plan",
2773 "exec",
2774 "--output-format",
2775 "stream-json",
2776 "--parent-death-watch",
2777 "review only",
2778 ]
2779 );
2780 assert!(!ro_cmd.args.iter().any(|a| a == "--provider"));
2781 assert!(!ro_cmd.args.iter().any(|a| a == "--tool-authority-json"));
2782 assert!(!ro_cmd.args.iter().any(|a| a == "--auto"));
2783
2784 let direct_cmd = build_worker_exec_command("codewhale", &t, &exec, Some("auto"));
2785 assert!(direct_cmd.args.starts_with(&[
2786 "--agent".to_string(),
2787 "claude".to_string(),
2788 "--agent-transport".to_string(),
2789 "cli".to_string(),
2790 "exec".to_string(),
2791 ]));
2792 }
2793
2794 #[test]
2795 fn external_agent_stream_events_and_terminal_route_parse_cleanly() {
2796 assert!(matches!(
2797 map_exec_stream_line(r#"{"type":"delta","text":"hi"}"#),
2798 Some(FleetWorkerEventPayload::Running)
2799 ));
2800 assert!(matches!(
2801 map_exec_stream_line(r#"{"type":"completed","response":"done"}"#),
2802 Some(FleetWorkerEventPayload::Completed {
2803 exit_code: Some(0),
2804 summary: None,
2805 })
2806 ));
2807 let with_model = map_exec_terminal_route(
2808 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","external_agent":"claude","model":"claude-sonnet-4-6"}}"#,
2809 )
2810 .expect("external terminal route with model");
2811 assert_eq!(with_model.provider, "external:claude");
2812 assert_eq!(with_model.provider_exact_id, None);
2813 assert_eq!(with_model.model, "claude-sonnet-4-6");
2814
2815 let default_model = map_exec_terminal_route(
2816 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","external_agent":"codex"}}"#,
2817 )
2818 .expect("external terminal route with default model");
2819 assert_eq!(default_model.provider, "external:codex");
2820 assert_eq!(default_model.model, "default");
2821
2822 assert!(
2823 map_exec_terminal_route(
2824 r#"{"type":"metadata","meta":{"receipt_kind":"terminal","external_agent":" "}}"#,
2825 )
2826 .is_none()
2827 );
2828 }
2829
2830 #[test]
2831 fn runtime_command_matches_admitted_route_command_exactly() {
2832 let tmp = TempDir::new().unwrap();
2833 let mut t = task("inspect files");
2834 t.budget = Some(FleetTaskBudget {
2835 max_steps: Some(4),
2836 max_tool_calls: Some(12),
2837 max_seconds: None,
2838 max_tokens: None,
2839 });
2840 let worker = FleetWorkerSpec {
2841 environment: None,
2842 id: "worker-1".to_string(),
2843 name: "Worker 1".to_string(),
2844 host: FleetHostSpec::Local,
2845 trust_level: None,
2846 labels: BTreeMap::new(),
2847 capabilities: Vec::new(),
2848 max_concurrent_tasks: Some(1),
2849 };
2850 let spec = launch_spec(&t, tmp.path());
2851 let exec_config = FleetExecConfig::default();
2852 let runtime = crate::fleet::worker_runtime::resolve_fleet_worker_runtime(
2853 &t,
2854 &worker,
2855 spec.clone(),
2856 tmp.path().to_path_buf(),
2857 Some("test-model"),
2858 None,
2859 &[],
2860 None,
2861 &Default::default(),
2862 )
2863 .unwrap();
2864 let from_runtime =
2865 build_worker_exec_command_for_runtime("codewhale", &runtime, &exec_config);
2866 let from_legacy = build_worker_exec_command_with_admitted_route(
2867 "codewhale",
2868 &t,
2869 &spec,
2870 &exec_config,
2871 Some("test-model"),
2872 &[],
2873 None,
2874 )
2875 .unwrap();
2876 assert_eq!(from_runtime.program, from_legacy.program);
2877 assert_eq!(from_runtime.args, from_legacy.args);
2878 }
2879 }
2880
2880 lines RUST