返回 CodeWhale
fleet.rs
根目录 / crates / protocol / src / fleet.rs
1 //! Agent Fleet control-plane protocol types.
2 //!
3 //! These types define the durable, serializable contract between the fleet
4 //! manager, workers, CLI/TUI surfaces, and the Runtime API. They are
5 //! intentionally additive: existing runtime-event consumers ignore unknown
6 //! fields and are unaffected by fleet extensions.
7 //!
8 //! See:
9 //! - <https://github.com/codewhale-hq/CodeWhale/issues/3154> (Agent Fleet control plane)
10 //! - <https://github.com/codewhale-hq/CodeWhale/issues/3096> (Runtime API sub-agent direction)
11
12 use std::collections::BTreeMap;
13 use std::path::PathBuf;
14
15 use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
16 use serde_json::Value;
17
18 use super::Status;
19
20 /// Explicit boundary migration for pre-Fleet serialized role tokens.
21 ///
22 /// Call this only at load / parse edges. Runtime code must use Fleet role
23 /// names via `FleetRole::as_str`. Returns `None` for tokens that are
24 /// already canonical or unknown — callers should prefer `FleetRole::parse`
25 /// for full acceptance (canonical + legacy).
26 #[must_use]
27 pub fn migrate_legacy_role_token(token: &str) -> Option<&'static str> {
28 match token.trim().to_ascii_lowercase().as_str() {
29 "worker" | "general-purpose" | "general_purpose" | "default" => Some("general"),
30 "scout" | "exploration" | "explorer" => Some("explore"),
31 "plan" | "planning" | "awaiter" => Some("planner"),
32 "review" | "code-review" | "code_review" => Some("reviewer"),
33 "builder" | "implementer" | "implementation" => Some("implement"),
34 "verifier" | "verify" | "verification" | "validator" | "tester" => Some("test"),
35 "consultant" | "oracle" => Some("advisor"),
36 _ => None,
37 }
38 }
39
40 pub const FLEET_PROTOCOL_VERSION: &str = "0.1.0";
41
42 /// Globally unique identifier for a fleet run.
43 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
44 pub struct FleetRunId(pub String);
45
46 impl From<String> for FleetRunId {
47 fn from(value: String) -> Self {
48 Self(value)
49 }
50 }
51
52 impl From<&str> for FleetRunId {
53 fn from(value: &str) -> Self {
54 Self(value.to_string())
55 }
56 }
57
58 /// Top-level fleet run handle.
59 #[derive(Debug, Clone, Serialize, Deserialize)]
60 pub struct FleetRun {
61 pub id: FleetRunId,
62 pub name: String,
63 pub status: FleetRunStatus,
64 /// Explicit execution target selected by the managed client.
65 ///
66 /// Older CLI-created runs predate target selection and therefore omit
67 /// this field. Runtime API creation always persists it and currently
68 /// accepts only [`FleetRuntimeTarget::ThisComputer`].
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub target: Option<FleetRuntimeTarget>,
71 /// Named Workflow descriptor that owns this Fleet run.
72 ///
73 /// The durable task specs below remain the executable source of truth;
74 /// this descriptor keeps the product identity and scheduling policy
75 /// inspectable without smuggling them through labels.
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub workflow: Option<FleetWorkflowDescriptor>,
78 /// Canonical named roles declared for the run.
79 #[serde(default, skip_serializing_if = "Vec::is_empty")]
80 pub roles: Vec<String>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub coordinator_thread_id: Option<String>,
83 /// Maximum number of workers the manager may drive concurrently.
84 ///
85 /// Older ledgers omit this field; callers fall back to the persisted
86 /// worker roster when resuming those runs.
87 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub max_workers: Option<usize>,
89 /// Optional run-wide usage ceiling (R6, #5567). When the accumulated
90 /// worker usage crosses it, the ledger refuses new task admissions,
91 /// pauses the run, and records exactly one budget alert. Absent on older
92 /// ledgers and by default: unbounded, today's behavior.
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub usage_ceiling: Option<FleetUsageCeiling>,
95 #[serde(default)]
96 pub task_specs: Vec<FleetTaskSpec>,
97 #[serde(default)]
98 pub worker_specs: Vec<FleetWorkerSpec>,
99 #[serde(default)]
100 pub labels: BTreeMap<String, String>,
101 /// Legacy replay-only execution policy from pre-0.9.11 ledgers.
102 ///
103 /// New Fleet runs reject this field: Fleet selects identity, while the
104 /// Runtime owns trust, secrets, approvals, sandboxing, and tool authority.
105 #[serde(skip_serializing_if = "Option::is_none")]
106 pub security_policy: Option<FleetSecurityPolicy>,
107 pub created_at: String,
108 #[serde(skip_serializing_if = "Option::is_none")]
109 pub updated_at: Option<String>,
110 #[serde(skip_serializing_if = "Option::is_none")]
111 pub completed_at: Option<String>,
112 }
113
114 /// Product-level Runtime target for a managed Fleet run.
115 ///
116 /// The enum intentionally names unsupported targets as contract values so a
117 /// client receives a precise capability refusal instead of silently falling
118 /// back to local execution.
119 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
120 #[serde(rename_all = "snake_case")]
121 pub enum FleetRuntimeTarget {
122 ThisComputer,
123 AnotherComputer,
124 Cloud,
125 }
126
127 /// Scheduling shape currently executable by the durable Fleet manager.
128 ///
129 /// Fleet tasks are independent queue entries today, so only parallel
130 /// workflows are advertised. Sequence/pipeline support must not be accepted
131 /// until dependencies are durable in the Fleet ledger.
132 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
133 #[serde(rename_all = "snake_case")]
134 pub enum FleetWorkflowKind {
135 Parallel,
136 }
137
138 /// Durable identity for the Workflow that coordinates a Fleet run.
139 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
140 pub struct FleetWorkflowDescriptor {
141 pub id: String,
142 pub kind: FleetWorkflowKind,
143 }
144
145 /// One privacy-bounded durable event exposed to managed Fleet clients.
146 ///
147 /// `cursor` is an opaque stable digest of the underlying ledger transition.
148 /// Clients persist it and send it back on reconnect; they must not parse it.
149 /// Worker-local sequence numbers remain available separately because they are
150 /// monotonic only within one `(worker, task)` lifecycle, not across a run.
151 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
152 pub struct FleetRuntimeEvent {
153 pub cursor: String,
154 pub event: String,
155 pub run_id: FleetRunId,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub worker_id: Option<String>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
159 pub task_id: Option<String>,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub timestamp: Option<String>,
162 #[serde(default, skip_serializing_if = "Option::is_none")]
163 pub worker_seq: Option<u64>,
164 #[serde(default)]
165 pub payload: Value,
166 }
167
168 /// Bounded durable replay page.
169 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
170 pub struct FleetEventReplay {
171 pub run_id: FleetRunId,
172 pub events: Vec<FleetRuntimeEvent>,
173 #[serde(default)]
174 pub has_more: bool,
175 /// True when a no-cursor request returned only the newest bounded tail.
176 #[serde(default)]
177 pub history_truncated: bool,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub next_cursor: Option<String>,
180 }
181
182 /// Lifecycle status for an entire fleet run.
183 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
184 #[serde(rename_all = "snake_case")]
185 pub enum FleetRunStatus {
186 Pending,
187 Queued,
188 Running,
189 Paused,
190 Completed,
191 Failed,
192 Cancelled,
193 }
194
195 impl Status for FleetRunStatus {
196 fn is_terminal(&self) -> bool {
197 matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
198 }
199 fn is_active(&self) -> bool {
200 matches!(self, Self::Pending | Self::Queued | Self::Running)
201 }
202 fn is_paused(&self) -> bool {
203 matches!(self, Self::Paused)
204 }
205 }
206
207 /// Specification of a single unit of work within a run.
208 #[derive(Debug, Clone, Serialize, Deserialize)]
209 pub struct FleetTaskSpec {
210 pub id: String,
211 pub name: String,
212 #[serde(skip_serializing_if = "Option::is_none")]
213 pub description: Option<String>,
214 #[serde(skip_serializing_if = "Option::is_none")]
215 pub objective: Option<String>,
216 pub instructions: String,
217 #[serde(skip_serializing_if = "Option::is_none")]
218 pub worker: Option<FleetTaskWorkerProfile>,
219 #[serde(skip_serializing_if = "Option::is_none")]
220 pub workspace: Option<FleetWorkspaceRequirements>,
221 #[serde(default)]
222 #[serde(skip_serializing_if = "Vec::is_empty")]
223 pub input_files: Vec<PathBuf>,
224 #[serde(default)]
225 #[serde(skip_serializing_if = "Vec::is_empty")]
226 pub context: Vec<String>,
227 #[serde(skip_serializing_if = "Option::is_none")]
228 pub budget: Option<FleetTaskBudget>,
229 #[serde(default)]
230 #[serde(skip_serializing_if = "Vec::is_empty")]
231 pub tags: Vec<String>,
232 #[serde(default)]
233 pub expected_artifacts: Vec<FleetArtifactKind>,
234 #[serde(skip_serializing_if = "Option::is_none")]
235 pub scorer: Option<FleetScorerSpec>,
236 #[serde(skip_serializing_if = "Option::is_none")]
237 pub retry_policy: Option<FleetRetryPolicy>,
238 #[serde(skip_serializing_if = "Option::is_none")]
239 pub alert_policy: Option<FleetAlertPolicy>,
240 #[serde(default)]
241 pub timeout_seconds: Option<u64>,
242 #[serde(default)]
243 pub metadata: BTreeMap<String, Value>,
244 }
245
246 /// Worker role and tool expectations for a task.
247 #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
248 pub struct FleetTaskWorkerProfile {
249 /// Bounded human selector for one Fleet member.
250 ///
251 /// Accepts member id/name, semantic role, model id/display name, or an
252 /// explicit `route:<provider>/<model>`. `profile` is accepted as a shorter
253 /// authoring alias. Resolution and permission narrowing happen in the Fleet
254 /// runtime layer.
255 #[serde(default, alias = "profile", skip_serializing_if = "Option::is_none")]
256 pub agent_profile: Option<String>,
257 #[serde(skip_serializing_if = "Option::is_none")]
258 pub role: Option<String>,
259 /// Fleet loadout intent such as `auto`, `fast`, or `review`.
260 ///
261 /// This is not a concrete provider/model selection; route resolution owns
262 /// the executable provider/model/wire-model decision.
263 #[serde(default, skip_serializing_if = "Option::is_none")]
264 pub loadout: Option<String>,
265 /// Fleet model class hint such as `strong`, `balanced`, or `fast`.
266 #[serde(default, skip_serializing_if = "Option::is_none")]
267 pub model_class: Option<String>,
268 /// Optional explicit model id for this worker.
269 ///
270 /// Task-level model overrides are visible authoring data. They apply only
271 /// when the selected member does not pin an exact provider/model route;
272 /// conflicting overrides of an exact member route are rejected.
273 #[serde(default, skip_serializing_if = "Option::is_none")]
274 pub model: Option<String>,
275 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pub provider: Option<String>,
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub external_agent: Option<String>,
279 #[serde(default, skip_serializing_if = "Option::is_none")]
280 pub external_agent_transport: Option<String>,
281 #[serde(skip_serializing_if = "Option::is_none")]
282 pub tool_profile: Option<String>,
283 #[serde(default)]
284 #[serde(skip_serializing_if = "Vec::is_empty")]
285 pub tools: Vec<String>,
286 #[serde(default)]
287 #[serde(skip_serializing_if = "Vec::is_empty")]
288 pub capabilities: Vec<String>,
289 }
290
291 /// Workspace and environment constraints needed before a task starts.
292 #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
293 pub struct FleetWorkspaceRequirements {
294 #[serde(default, skip_serializing_if = "Option::is_none")]
295 pub placement: Option<crate::placement::PlacementRequirements>,
296 #[serde(skip_serializing_if = "Option::is_none")]
297 pub root: Option<PathBuf>,
298 #[serde(default)]
299 #[serde(skip_serializing_if = "Vec::is_empty")]
300 pub required_files: Vec<PathBuf>,
301 #[serde(default)]
302 #[serde(skip_serializing_if = "Vec::is_empty")]
303 pub writable_paths: Vec<PathBuf>,
304 #[serde(skip_serializing_if = "Option::is_none")]
305 pub environment: Option<FleetEnvironmentRequirements>,
306 }
307
308 /// Environment variables a task requires or may pass through to workers.
309 #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
310 pub struct FleetEnvironmentRequirements {
311 #[serde(default)]
312 #[serde(skip_serializing_if = "Vec::is_empty")]
313 pub required: Vec<String>,
314 #[serde(default)]
315 #[serde(skip_serializing_if = "Vec::is_empty")]
316 pub allowlist: Vec<String>,
317 }
318
319 /// Budget limits for a task.
320 #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
321 pub struct FleetTaskBudget {
322 #[serde(skip_serializing_if = "Option::is_none")]
323 pub max_tokens: Option<u64>,
324 /// Maximum model turns. `None` and `Some(0)` both mean unbounded.
325 #[serde(skip_serializing_if = "Option::is_none")]
326 pub max_steps: Option<u32>,
327 #[serde(skip_serializing_if = "Option::is_none")]
328 pub max_tool_calls: Option<u32>,
329 #[serde(skip_serializing_if = "Option::is_none")]
330 pub max_seconds: Option<u64>,
331 }
332
333 /// Reference to an artifact produced or consumed by a task.
334 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
335 pub struct FleetArtifactRef {
336 pub kind: FleetArtifactKind,
337 pub path: PathBuf,
338 #[serde(skip_serializing_if = "Option::is_none")]
339 pub checksum: Option<String>,
340 #[serde(skip_serializing_if = "Option::is_none")]
341 pub mime_type: Option<String>,
342 #[serde(default)]
343 pub size_bytes: Option<u64>,
344 }
345
346 /// Kind of artifact a task may produce or consume.
347 #[derive(Debug, Clone, PartialEq, Eq)]
348 pub enum FleetArtifactKind {
349 Log,
350 Patch,
351 TestResult,
352 Report,
353 Checkpoint,
354 Receipt,
355 Other(String),
356 }
357
358 impl FleetArtifactKind {
359 fn as_wire_str(&self) -> &str {
360 match self {
361 Self::Log => "log",
362 Self::Patch => "patch",
363 Self::TestResult => "test_result",
364 Self::Report => "report",
365 Self::Checkpoint => "checkpoint",
366 Self::Receipt => "receipt",
367 Self::Other(kind) => kind.as_str(),
368 }
369 }
370
371 fn from_wire_str(value: &str) -> Self {
372 match value {
373 "log" => Self::Log,
374 "patch" => Self::Patch,
375 "test_result" => Self::TestResult,
376 "report" => Self::Report,
377 "checkpoint" => Self::Checkpoint,
378 "receipt" => Self::Receipt,
379 other => Self::Other(other.to_string()),
380 }
381 }
382 }
383
384 impl Serialize for FleetArtifactKind {
385 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
386 where
387 S: Serializer,
388 {
389 serializer.serialize_str(self.as_wire_str())
390 }
391 }
392
393 impl<'de> Deserialize<'de> for FleetArtifactKind {
394 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
395 where
396 D: Deserializer<'de>,
397 {
398 let value = String::deserialize(deserializer)?;
399 Ok(Self::from_wire_str(&value))
400 }
401 }
402
403 /// Scoring rule used to verify a task result.
404 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
405 #[serde(tag = "kind", rename_all = "snake_case")]
406 pub enum FleetScorerSpec {
407 ExitCode,
408 FileExists {
409 path: PathBuf,
410 },
411 RegexMatch {
412 path: PathBuf,
413 pattern: String,
414 },
415 JsonPath {
416 path: PathBuf,
417 expression: String,
418 },
419 Command {
420 command: String,
421 #[serde(default)]
422 args: Vec<String>,
423 },
424 CodeWhaleVerifierPrompt {
425 prompt: String,
426 },
427 Manual,
428 }
429
430 /// Worker specification.
431 #[derive(Debug, Clone, Serialize, Deserialize)]
432 pub struct FleetWorkerSpec {
433 #[serde(default, skip_serializing_if = "Option::is_none")]
434 pub environment: Option<crate::placement::ExecutionEnvironment>,
435 pub id: String,
436 pub name: String,
437 pub host: FleetHostSpec,
438 /// Legacy replay-only host trust label. New runs reject author-supplied
439 /// values and derive execution authority from Runtime policy instead.
440 #[serde(default)]
441 #[serde(skip_serializing_if = "Option::is_none")]
442 pub trust_level: Option<FleetTrustLevel>,
443 #[serde(default)]
444 pub labels: BTreeMap<String, String>,
445 #[serde(default)]
446 pub capabilities: Vec<String>,
447 #[serde(skip_serializing_if = "Option::is_none")]
448 pub max_concurrent_tasks: Option<usize>,
449 }
450
451 /// Host on which a worker runs.
452 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
453 #[serde(tag = "kind", rename_all = "snake_case")]
454 pub enum FleetHostSpec {
455 Local,
456 Tailscale {
457 node_id: String,
458 user: String,
459 working_directory: PathBuf,
460 codewhale_binary: String,
461 },
462 Ssh {
463 host: String,
464 #[serde(skip_serializing_if = "Option::is_none")]
465 port: Option<u16>,
466 #[serde(skip_serializing_if = "Option::is_none")]
467 user: Option<String>,
468 #[serde(skip_serializing_if = "Option::is_none")]
469 identity: Option<PathBuf>,
470 /// Known hosts file for host-key verification.
471 #[serde(skip_serializing_if = "Option::is_none")]
472 known_hosts: Option<PathBuf>,
473 /// Legacy field retained for decoding; the SSH host adapter rejects it
474 /// when set. Configure `known_hosts` for host-key verification instead.
475 #[serde(skip_serializing_if = "Option::is_none")]
476 host_key_fingerprint: Option<String>,
477 #[serde(skip_serializing_if = "Option::is_none")]
478 working_directory: Option<PathBuf>,
479 #[serde(default)]
480 #[serde(skip_serializing_if = "Vec::is_empty")]
481 env_allowlist: Vec<String>,
482 #[serde(skip_serializing_if = "Option::is_none")]
483 codewhale_binary: Option<String>,
484 },
485 #[serde(alias = "container")]
486 #[serde(alias = "Container")]
487 Docker {
488 image: String,
489 #[serde(default)]
490 args: Vec<String>,
491 },
492 }
493
494 // ── Legacy Runtime-policy wire compatibility ───────────────────────────────
495
496 /// Legacy trust classification retained only to deserialize old Fleet ledgers.
497 ///
498 /// It is not Fleet identity and new run creation rejects it. Current authority
499 /// comes from live Runtime policy; these helper predicates describe the old
500 /// wire vocabulary only.
501 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Default)]
502 #[serde(rename_all = "snake_case")]
503 pub enum FleetTrustLevel {
504 /// Fully isolated: no network, no secrets, no writes outside `.codewhale/fleet/`.
505 /// Suitable for untrusted code review, community PR checks, or third-party tool runs.
506 #[default]
507 Sandbox = 0,
508 /// Local-only worker with access to the workspace and configured secrets.
509 /// Default for local workers. May read repo files but writes are gated.
510 Local = 1,
511 /// Worker on a known remote host with verified identity and a bounded
512 /// set of explicitly granted capabilities. Requires SSH host-key
513 /// verification or equivalent attestation.
514 #[serde(alias = "remote-verified", alias = "remoteVerified")]
515 RemoteVerified = 2,
516 /// Fully trusted worker (e.g. operator's own machine, CI runner).
517 /// Has access to all configured secrets and may perform any action the
518 /// operator can. Reserved for dogfood smoke and operator-owned machines.
519 Operator = 3,
520 }
521
522 impl FleetTrustLevel {
523 /// Whether this trust level is allowed to access provider secrets.
524 #[must_use]
525 pub fn may_access_secrets(&self) -> bool {
526 matches!(self, Self::Operator | Self::RemoteVerified | Self::Local)
527 }
528
529 /// Whether this trust level is allowed to write outside `.codewhale/fleet/`.
530 #[must_use]
531 pub fn may_write_workspace(&self) -> bool {
532 matches!(self, Self::Operator | Self::Local)
533 }
534
535 /// Whether this trust level is allowed network access.
536 #[must_use]
537 pub fn may_access_network(&self) -> bool {
538 matches!(self, Self::Operator | Self::RemoteVerified | Self::Local)
539 }
540 }
541
542 /// Legacy Runtime execution-policy envelope retained for ledger replay.
543 ///
544 /// This type is accepted while reading older protocol data but is rejected for
545 /// new Fleet runs. Fleet membership/selection never grants trust, secrets, or
546 /// capabilities; the Runtime derives those from its live policy boundary.
547 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
548 pub struct FleetSecurityPolicy {
549 /// Default trust level for workers that don't declare one explicitly.
550 #[serde(default)]
551 pub default_trust_level: FleetTrustLevel,
552 /// Secret refs that workers may resolve. An empty list means no secrets
553 /// are available. Each entry is a key name, not a value.
554 #[serde(default)]
555 #[serde(skip_serializing_if = "Vec::is_empty")]
556 pub allowed_secrets: Vec<FleetSecretRef>,
557 /// Capability grants for workers in this run.
558 #[serde(default)]
559 #[serde(skip_serializing_if = "Vec::is_empty")]
560 pub capability_grants: Vec<FleetCapabilityGrant>,
561 /// Maximum trust level any worker in this run may have, even if the
562 /// worker spec requests higher. Defaults to Operator (no ceiling).
563 #[serde(default = "default_max_trust_level")]
564 pub max_trust_level: FleetTrustLevel,
565 /// Require identity verification for remote workers. When true, SSH
566 /// workers must pass host-key verification before being trusted at
567 /// RemoteVerified level; unverified remotes stay at Sandbox.
568 #[serde(default)]
569 pub require_identity_verification: bool,
570 /// Allow conservative parallel execution of read-only tools (#2983).
571 /// When true, workers may batch independent read-only tool calls
572 /// (reads, searches, greps) into concurrent turns. Disabled by default
573 /// to avoid overwhelming providers or hitting rate limits.
574 #[serde(default)]
575 pub allow_parallel_reads: bool,
576 }
577
578 fn default_max_trust_level() -> FleetTrustLevel {
579 FleetTrustLevel::Operator
580 }
581
582 impl Default for FleetSecurityPolicy {
583 fn default() -> Self {
584 Self {
585 default_trust_level: FleetTrustLevel::Sandbox,
586 allowed_secrets: Vec::new(),
587 capability_grants: Vec::new(),
588 max_trust_level: FleetTrustLevel::Operator,
589 require_identity_verification: false,
590 allow_parallel_reads: false,
591 }
592 }
593 }
594
595 /// A reference to a secret that should be resolved at runtime, never
596 /// serialized as a plaintext value.
597 ///
598 /// Secret refs appear in task specs, alert configs, and worker definitions.
599 /// The actual secret value is resolved by the fleet manager from the
600 /// secrets backend (OS keyring, environment, or file store) just before
601 /// the worker starts.
602 #[derive(Debug, Clone, Serialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
603 pub struct FleetSecretRef {
604 /// The secret key name (e.g. `"CODEWHALE_API_KEY"`, `"GH_TOKEN"`).
605 pub key: String,
606 /// Optional source hint for resolution order.
607 /// - `"env"` — resolve from environment variable
608 /// - `"keyring"` — resolve from OS keyring
609 /// - `"file"` — resolve from `~/.codewhale/secrets/`
610 /// - absent / null — try all sources in default order
611 #[serde(skip_serializing_if = "Option::is_none")]
612 pub source: Option<String>,
613 }
614
615 impl FleetSecretRef {
616 /// Create a secret ref from a key name with default resolution.
617 #[must_use]
618 pub fn new(key: impl Into<String>) -> Self {
619 Self {
620 key: key.into(),
621 source: None,
622 }
623 }
624
625 /// Create a secret ref with an explicit source.
626 #[must_use]
627 pub fn with_source(key: impl Into<String>, source: impl Into<String>) -> Self {
628 Self {
629 key: key.into(),
630 source: Some(source.into()),
631 }
632 }
633
634 /// Redacted display form for logging. Shows the key name and source
635 /// but never the resolved value.
636 #[must_use]
637 pub fn redacted(&self) -> String {
638 match &self.source {
639 Some(src) => format!("<secret:{}.{}>", src, self.key),
640 None => format!("<secret:{}>", self.key),
641 }
642 }
643 }
644
645 impl std::fmt::Display for FleetSecretRef {
646 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
647 write!(f, "{}", self.redacted())
648 }
649 }
650
651 impl From<&str> for FleetSecretRef {
652 fn from(key: &str) -> Self {
653 Self::new(key)
654 }
655 }
656
657 impl From<String> for FleetSecretRef {
658 fn from(key: String) -> Self {
659 Self::new(key)
660 }
661 }
662
663 impl<'de> Deserialize<'de> for FleetSecretRef {
664 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
665 where
666 D: Deserializer<'de>,
667 {
668 #[derive(Deserialize)]
669 #[serde(untagged)]
670 enum SecretRefWire {
671 Key(String),
672 Structured {
673 key: String,
674 #[serde(default)]
675 source: Option<String>,
676 },
677 }
678
679 match SecretRefWire::deserialize(deserializer)? {
680 SecretRefWire::Key(key) if !key.trim().is_empty() => Ok(FleetSecretRef::new(key)),
681 SecretRefWire::Key(_) => Err(de::Error::custom("secret ref key cannot be empty")),
682 SecretRefWire::Structured { key, source } if !key.trim().is_empty() => {
683 Ok(FleetSecretRef { key, source })
684 }
685 SecretRefWire::Structured { .. } => {
686 Err(de::Error::custom("secret ref key cannot be empty"))
687 }
688 }
689 }
690 }
691
692 /// How a worker authenticates to the fleet manager.
693 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
694 #[serde(tag = "method", rename_all = "snake_case")]
695 pub enum FleetWorkerAuth {
696 /// No authentication (local workers share the same uid).
697 None,
698 /// SSH key-based authentication with host-key verification.
699 SshKey {
700 /// Path to the SSH identity file (may be a FleetSecretRef in JSON
701 /// as `{"key": "...", "source": "file"}`).
702 identity: PathBuf,
703 /// Known hosts file for host-key verification.
704 #[serde(skip_serializing_if = "Option::is_none")]
705 known_hosts: Option<PathBuf>,
706 /// Legacy metadata; does not enforce key pinning. The SSH host adapter
707 /// rejects `FleetHostSpec::Ssh::host_key_fingerprint` when set; configure
708 /// `known_hosts` on the host spec for host-key verification instead.
709 #[serde(skip_serializing_if = "Option::is_none")]
710 host_key_fingerprint: Option<String>,
711 /// SSH user for the connection.
712 #[serde(skip_serializing_if = "Option::is_none")]
713 user: Option<String>,
714 },
715 /// Token-based authentication for remote workers behind a fleet proxy.
716 Token {
717 /// Reference to the token secret.
718 token_ref: FleetSecretRef,
719 },
720 /// mTLS certificate-based authentication.
721 Mtls {
722 /// Path to the client certificate.
723 cert_path: PathBuf,
724 /// Reference to the private key secret.
725 key_ref: FleetSecretRef,
726 },
727 }
728
729 /// A capability grant that explicitly authorizes a worker to perform
730 /// a specific class of action.
731 ///
732 /// By default, new workers get no grants (least privilege). Grants are
733 /// additive: a worker's effective capabilities are the union of its
734 /// trust-level defaults plus any explicit grants.
735 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
736 pub struct FleetCapabilityGrant {
737 /// The capability being granted (e.g. `"network"`, `"git-push"`,
738 /// `"provider-secrets"`, `"release"`).
739 pub capability: String,
740 /// Optional scope limiting the grant (e.g. `"github.com"` for network,
741 /// `"crates/tui/**"` for file writes).
742 #[serde(skip_serializing_if = "Option::is_none")]
743 pub scope: Option<String>,
744 /// Optional justification for the grant (audit trail).
745 #[serde(skip_serializing_if = "Option::is_none")]
746 pub reason: Option<String>,
747 }
748
749 /// Runtime status of a worker.
750 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
751 #[serde(rename_all = "snake_case")]
752 pub enum FleetWorkerStatus {
753 Unknown,
754 Online,
755 Busy,
756 Offline,
757 Unhealthy,
758 Draining,
759 Retired,
760 }
761
762 impl Status for FleetWorkerStatus {
763 fn is_terminal(&self) -> bool {
764 matches!(self, Self::Retired)
765 }
766 fn is_active(&self) -> bool {
767 matches!(self, Self::Online | Self::Busy)
768 }
769 fn is_paused(&self) -> bool {
770 false
771 }
772 }
773
774 /// Durable inbox entry: a task waiting to be leased to a worker.
775 #[derive(Debug, Clone, Serialize, Deserialize)]
776 pub struct FleetInboxEntry {
777 pub run_id: FleetRunId,
778 pub task_id: String,
779 pub priority: i32,
780 pub enqueued_at: String,
781 #[serde(default)]
782 pub lease_deadline: Option<String>,
783 #[serde(default)]
784 pub attempts: u32,
785 }
786
787 /// Worker event envelope.
788 #[derive(Debug, Clone, Serialize, Deserialize)]
789 pub struct FleetWorkerEvent {
790 pub seq: u64,
791 pub run_id: FleetRunId,
792 pub worker_id: String,
793 pub task_id: String,
794 pub timestamp: String,
795 #[serde(flatten)]
796 pub payload: FleetWorkerEventPayload,
797 #[serde(default)]
798 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
799 pub extra: BTreeMap<String, Value>,
800 }
801
802 /// Union of all worker event payloads.
803 #[derive(Debug, Clone, Serialize, Deserialize)]
804 #[serde(tag = "state", rename_all = "snake_case")]
805 pub enum FleetWorkerEventPayload {
806 Queued,
807 Leased {
808 #[serde(skip_serializing_if = "Option::is_none")]
809 lease_expires_at: Option<String>,
810 },
811 Starting,
812 Running,
813 ModelWait {
814 #[serde(skip_serializing_if = "Option::is_none")]
815 model: Option<String>,
816 },
817 RunningTool {
818 tool: String,
819 #[serde(skip_serializing_if = "Option::is_none")]
820 call_id: Option<String>,
821 },
822 /// Typed receipt emitted by a Workflow running inside this worker.
823 WorkflowEvent {
824 /// Inner Workflow run id. Named distinctly from the outer Fleet run id
825 /// because payloads are flattened into `FleetWorkerEvent`.
826 workflow_run_id: String,
827 event: Value,
828 },
829 Heartbeat {
830 #[serde(default)]
831 #[serde(skip_serializing_if = "Option::is_none")]
832 cpu_percent: Option<f32>,
833 #[serde(default)]
834 #[serde(skip_serializing_if = "Option::is_none")]
835 memory_mb: Option<u64>,
836 },
837 /// Provider-reported usage receipt for one model call inside this
838 /// worker (R6, #5567). Feeds the run-level accumulator that enforces
839 /// [`FleetUsageCeiling`].
840 UsageReport {
841 input_tokens: u64,
842 output_tokens: u64,
843 },
844 Artifact(FleetArtifactRef),
845 Completed {
846 #[serde(default)]
847 #[serde(skip_serializing_if = "Option::is_none")]
848 exit_code: Option<i32>,
849 #[serde(skip_serializing_if = "Option::is_none")]
850 summary: Option<String>,
851 },
852 Failed {
853 reason: String,
854 #[serde(default)]
855 recoverable: bool,
856 },
857 Cancelled {
858 #[serde(skip_serializing_if = "Option::is_none")]
859 cancelled_by: Option<String>,
860 },
861 Interrupted {
862 #[serde(skip_serializing_if = "Option::is_none")]
863 signal: Option<String>,
864 },
865 Stale {
866 #[serde(skip_serializing_if = "Option::is_none")]
867 last_heartbeat_at: Option<String>,
868 },
869 Restarted {
870 #[serde(default)]
871 restart_count: u32,
872 },
873 Escalated {
874 channel: String,
875 #[serde(skip_serializing_if = "Option::is_none")]
876 alert_id: Option<String>,
877 },
878 }
879
880 /// Run-wide usage ceiling (R6, #5567). Token-denominated: workers report
881 /// provider token counts; a cost-denominated ceiling needs priced receipts
882 /// in the worker stream and is deliberately not declared until it can be
883 /// enforced.
884 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
885 pub struct FleetUsageCeiling {
886 /// Maximum input+output tokens accumulated across every worker model
887 /// call in the run.
888 pub max_total_tokens: u64,
889 }
890
891 /// Retry policy for a task or worker.
892 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
893 pub struct FleetRetryPolicy {
894 #[serde(default = "default_retry_max_attempts")]
895 pub max_attempts: u32,
896 #[serde(default = "default_retry_initial_backoff_seconds")]
897 pub initial_backoff_seconds: u64,
898 #[serde(default = "default_retry_max_backoff_seconds")]
899 pub max_backoff_seconds: u64,
900 #[serde(default = "default_retry_backoff_multiplier")]
901 pub backoff_multiplier: u32,
902 }
903
904 impl Default for FleetRetryPolicy {
905 fn default() -> Self {
906 Self {
907 max_attempts: 3,
908 initial_backoff_seconds: 5,
909 max_backoff_seconds: 300,
910 backoff_multiplier: 2,
911 }
912 }
913 }
914
915 fn default_retry_max_attempts() -> u32 {
916 FleetRetryPolicy::default().max_attempts
917 }
918
919 fn default_retry_initial_backoff_seconds() -> u64 {
920 FleetRetryPolicy::default().initial_backoff_seconds
921 }
922
923 fn default_retry_max_backoff_seconds() -> u64 {
924 FleetRetryPolicy::default().max_backoff_seconds
925 }
926
927 fn default_retry_backoff_multiplier() -> u32 {
928 FleetRetryPolicy::default().backoff_multiplier
929 }
930
931 /// Alert/escalation policy attached to a task or run.
932 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
933 pub struct FleetAlertPolicy {
934 #[serde(default)]
935 #[serde(skip_serializing_if = "Vec::is_empty")]
936 pub events: Vec<FleetAlertEventClass>,
937 #[serde(default)]
938 pub channels: Vec<FleetAlertChannel>,
939 #[serde(default)]
940 pub after_attempts: Option<u32>,
941 #[serde(default)]
942 pub after_minutes_stale: Option<u64>,
943 }
944
945 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
946 #[serde(rename_all = "snake_case")]
947 pub enum FleetAlertEventClass {
948 Stale,
949 RestartExhausted,
950 NeedsHuman,
951 BudgetExceeded,
952 VerifierFailed,
953 RunCompleted,
954 }
955
956 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
957 #[serde(tag = "kind", rename_all = "snake_case")]
958 pub enum FleetAlertChannel {
959 Slack {
960 /// Webhook URL, resolved from a secret ref or inline.
961 #[serde(flatten)]
962 webhook: FleetAlertEndpoint,
963 },
964 Webhook {
965 #[serde(flatten)]
966 endpoint: FleetAlertEndpoint,
967 },
968 #[serde(alias = "pager_duty")]
969 #[serde(alias = "pagerduty")]
970 PagerDuty {
971 routing_key: String,
972 severity: String,
973 },
974 }
975
976 /// An alert channel endpoint, supporting both inline URLs and secret refs.
977 ///
978 /// For Slack and generic webhook channels, the URL may be provided directly
979 /// or as a secret reference resolved at send time. When both `url` and
980 /// `url_ref` are present, `url_ref` takes precedence after resolution.
981 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
982 pub struct FleetAlertEndpoint {
983 /// Inline URL (plaintext; only for non-sensitive endpoints).
984 #[serde(
985 alias = "webhook_url",
986 alias = "endpoint_url",
987 skip_serializing_if = "Option::is_none"
988 )]
989 pub url: Option<String>,
990 /// Reference to a secret containing the webhook URL.
991 #[serde(
992 alias = "webhook_url_ref",
993 alias = "webhook_ref",
994 alias = "url_secret_ref",
995 skip_serializing_if = "Option::is_none"
996 )]
997 pub url_ref: Option<FleetSecretRef>,
998 /// Optional HMAC secret for webhook payload signing, as a secret ref.
999 #[serde(
1000 alias = "secret",
1001 alias = "webhook_secret",
1002 alias = "signing_secret",
1003 skip_serializing_if = "Option::is_none"
1004 )]
1005 pub secret_ref: Option<FleetSecretRef>,
1006 }
1007
1008 impl FleetAlertEndpoint {
1009 /// Create an inline URL endpoint (for non-sensitive use).
1010 #[must_use]
1011 pub fn inline(url: impl Into<String>) -> Self {
1012 Self {
1013 url: Some(url.into()),
1014 url_ref: None,
1015 secret_ref: None,
1016 }
1017 }
1018
1019 /// Create a secret-backed URL endpoint.
1020 #[must_use]
1021 pub fn from_secret(url_ref: FleetSecretRef) -> Self {
1022 Self {
1023 url: None,
1024 url_ref: Some(url_ref),
1025 secret_ref: None,
1026 }
1027 }
1028
1029 /// Redacted display form for logging.
1030 #[must_use]
1031 pub fn redacted(&self) -> String {
1032 self.url_ref
1033 .as_ref()
1034 .map_or_else(|| "<inline-url>".to_string(), |r| r.redacted())
1035 }
1036 }
1037
1038 /// Resolved-route detail persisted on a [`FleetReceipt`] (#3154).
1039 ///
1040 /// This is an additive, *plain-strings* snapshot of the route a fleet worker
1041 /// resolved to. It deliberately does NOT depend on any `codewhale-config` route
1042 /// type so the protocol crate stays free of the route model.
1043 ///
1044 /// CRITICAL no-secrets invariant: this struct carries ONLY non-sensitive route
1045 /// shape — provider id/kind, model ids, wire protocol, role/loadout/model-class
1046 /// intent, reasoning tier when known, and deterministic intent sources. It
1047 /// must NEVER hold a credential, API key, bearer token, or a base URL that
1048 /// embeds credentials. There is intentionally no field that could carry a
1049 /// secret.
1050 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1051 pub struct FleetResolvedRoute {
1052 /// Resolved provider canonical id (e.g. `"deepseek"`).
1053 pub provider_id: String,
1054 /// Exact configured provider-table id when the worker used one.
1055 ///
1056 /// This is intentionally additive to `provider_id`: literal
1057 /// `[providers.custom]` resolves to `Some("custom")`, while the legacy
1058 /// idless root custom route resolves to `None`. Keeping the distinction
1059 /// prevents a receipt from silently collapsing two different credential
1060 /// and endpoint authorities into the same generic `custom` label.
1061 #[serde(default, skip_serializing_if = "Option::is_none")]
1062 pub provider_exact_id: Option<String>,
1063 /// Resolved provider kind (e.g. `"deepseek"`).
1064 pub provider_kind: String,
1065 /// Canonical, provider-agnostic model identity, when known.
1066 #[serde(default, skip_serializing_if = "Option::is_none")]
1067 pub canonical_model: Option<String>,
1068 /// Provider-owned wire model id placed on the request.
1069 pub wire_model_id: String,
1070 /// Selected wire protocol (e.g. `"chat_completions"`).
1071 pub protocol: String,
1072 /// Effective Fleet role intent, when one applied.
1073 #[serde(default, skip_serializing_if = "Option::is_none")]
1074 pub role: Option<String>,
1075 /// Effective Fleet loadout intent, when one applied.
1076 #[serde(default, skip_serializing_if = "Option::is_none")]
1077 pub loadout: Option<String>,
1078 /// Original task-level model-class intent, when authored separately from
1079 /// `loadout`. Profile `model_class_hint` is normalized into `loadout`.
1080 #[serde(default, skip_serializing_if = "Option::is_none")]
1081 pub model_class: Option<String>,
1082 /// Runtime model-route seam used by sub-agent routing (`inherit`, `faster`,
1083 /// `auto`, or `fixed`).
1084 #[serde(default, skip_serializing_if = "Option::is_none")]
1085 pub model_route: Option<String>,
1086 /// Concrete reasoning tier, when it is known by the route resolver path.
1087 #[serde(default, skip_serializing_if = "Option::is_none")]
1088 pub reasoning_effort: Option<String>,
1089 /// Deterministic source for the effective role intent.
1090 #[serde(default, skip_serializing_if = "Option::is_none")]
1091 pub role_source: Option<String>,
1092 /// Deterministic source for the effective loadout intent.
1093 #[serde(default, skip_serializing_if = "Option::is_none")]
1094 pub loadout_source: Option<String>,
1095 /// Deterministic source for the model-class hint, when present.
1096 #[serde(default, skip_serializing_if = "Option::is_none")]
1097 pub model_class_source: Option<String>,
1098 /// Deterministic source for the model selector used by the resolver.
1099 #[serde(default, skip_serializing_if = "Option::is_none")]
1100 pub model_source: Option<String>,
1101 #[serde(default, skip_serializing_if = "Option::is_none")]
1102 pub external_agent: Option<String>,
1103 #[serde(default, skip_serializing_if = "Option::is_none")]
1104 pub external_agent_transport: Option<String>,
1105 /// How the route was produced (e.g. `"resolver"`).
1106 pub source: String,
1107 }
1108
1109 /// Effective worker authority persisted on a [`FleetReceipt`] (#3211).
1110 ///
1111 /// This is a non-secret snapshot of the already-computed runtime profile. It
1112 /// records what the worker was allowed to do; it does not grant permissions and
1113 /// does not carry credentials, sandbox paths, or provider endpoints.
1114 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1115 pub struct FleetEffectivePermissions {
1116 /// Whether the worker profile may modify workspace files.
1117 pub write: bool,
1118 /// Whether the worker profile may use network-capable tools.
1119 pub network: bool,
1120 /// Shell posture (`none`, `read_only`, or `full`).
1121 pub shell: String,
1122 /// Tool-surface posture (`inherit` or `explicit`).
1123 pub tool_scope: String,
1124 /// Explicit tool names when `tool_scope` is `explicit`.
1125 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1126 pub tools: Vec<String>,
1127 /// Whether the worker is intended to run detached/background.
1128 pub background: bool,
1129 /// Remaining nested-delegation budget after parent intersection/hardening.
1130 pub max_spawn_depth: u32,
1131 /// Roster profile id that contributed to this worker, when any.
1132 #[serde(default, skip_serializing_if = "Option::is_none")]
1133 pub profile_id: Option<String>,
1134 /// Roster layer for `profile_id` (`built_in`, `config`, or `workspace`).
1135 #[serde(default, skip_serializing_if = "Option::is_none")]
1136 pub profile_origin: Option<String>,
1137 /// How this snapshot was produced (e.g. `"worker_runtime_profile"`).
1138 pub source: String,
1139 }
1140
1141 /// Receipt produced when a task completes verification.
1142 #[derive(Debug, Clone, Serialize, Deserialize)]
1143 pub struct FleetReceipt {
1144 pub run_id: FleetRunId,
1145 pub task_id: String,
1146 pub worker_id: String,
1147 /// Durable lease generation that produced this receipt.
1148 ///
1149 /// Optional for backward compatibility with receipts written before Fleet
1150 /// attempts were fenced explicitly.
1151 #[serde(default, skip_serializing_if = "Option::is_none")]
1152 pub attempt: Option<u32>,
1153 /// Sequence of the terminal worker event finalized with this receipt.
1154 ///
1155 /// Optional so older ledger records remain replayable.
1156 #[serde(default, skip_serializing_if = "Option::is_none")]
1157 pub terminal_seq: Option<u64>,
1158 pub completed_at: String,
1159 pub result: FleetTaskResult,
1160 #[serde(skip_serializing_if = "Option::is_none")]
1161 pub failure_kind: Option<FleetTaskFailureKind>,
1162 #[serde(default)]
1163 pub artifacts: Vec<FleetArtifactRef>,
1164 #[serde(default)]
1165 pub score: Option<FleetScore>,
1166 /// Resolved-route snapshot for this task (#3154).
1167 ///
1168 /// `#[serde(default)]` keeps older ledgers (written before this field
1169 /// existed) deserializable.
1170 #[serde(default, skip_serializing_if = "Option::is_none")]
1171 pub resolved_route: Option<FleetResolvedRoute>,
1172 /// Saved exec session id holding the worker's full transcript, when the
1173 /// local worker persisted its parent-assigned capture in the Runtime's
1174 /// session store (the exec stream's `session_capture.saved_session_id`).
1175 /// Remote-only or unavailable transcripts omit this field. Callers resolve the final
1176 /// assistant reply via `GET /v1/sessions/{id}`.
1177 #[serde(default, skip_serializing_if = "Option::is_none")]
1178 pub saved_session_id: Option<String>,
1179 /// Effective worker authority for this task (#3211).
1180 #[serde(default, skip_serializing_if = "Option::is_none")]
1181 pub effective_permissions: Option<FleetEffectivePermissions>,
1182 }
1183
1184 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1185 #[serde(rename_all = "snake_case")]
1186 pub enum FleetTaskResult {
1187 Pass,
1188 Partial,
1189 Fail,
1190 Skip,
1191 Timeout,
1192 }
1193
1194 /// Source category for a failed task receipt.
1195 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1196 #[serde(rename_all = "snake_case")]
1197 pub enum FleetTaskFailureKind {
1198 Transport,
1199 Task,
1200 Verifier,
1201 }
1202
1203 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1204 pub struct FleetScore {
1205 pub value: f64,
1206 #[serde(skip_serializing_if = "Option::is_none")]
1207 pub max: Option<f64>,
1208 #[serde(skip_serializing_if = "Option::is_none")]
1209 pub notes: Option<String>,
1210 }
1211
1212 #[cfg(test)]
1213 mod tests {
1214 use super::*;
1215
1216 #[test]
1217 fn fleet_run_round_trip() {
1218 let run = FleetRun {
1219 coordinator_thread_id: None,
1220 id: FleetRunId::from("run-001"),
1221 name: "dogfood smoke".to_string(),
1222 status: FleetRunStatus::Running,
1223 target: Some(FleetRuntimeTarget::ThisComputer),
1224 workflow: Some(FleetWorkflowDescriptor {
1225 id: "release-checks".to_string(),
1226 kind: FleetWorkflowKind::Parallel,
1227 }),
1228 roles: vec!["release-checker".to_string()],
1229 max_workers: Some(1),
1230 task_specs: vec![FleetTaskSpec {
1231 id: "task-1".to_string(),
1232 name: "lint".to_string(),
1233 description: None,
1234 objective: Some("Keep the workspace lint-clean".to_string()),
1235 instructions: "run cargo clippy".to_string(),
1236 worker: Some(FleetTaskWorkerProfile {
1237 provider: None,
1238 agent_profile: None,
1239 role: Some("release-checker".to_string()),
1240 loadout: None,
1241 model_class: None,
1242 model: None,
1243 external_agent: None,
1244 external_agent_transport: None,
1245 tool_profile: Some("read-only".to_string()),
1246 tools: vec!["cargo".to_string()],
1247 capabilities: vec!["rust".to_string()],
1248 }),
1249 workspace: Some(FleetWorkspaceRequirements {
1250 placement: None,
1251 root: Some(PathBuf::from(".")),
1252 required_files: vec![PathBuf::from("Cargo.toml")],
1253 writable_paths: vec![],
1254 environment: Some(FleetEnvironmentRequirements {
1255 required: vec!["PATH".to_string()],
1256 allowlist: vec!["RUST_LOG".to_string()],
1257 }),
1258 }),
1259 input_files: vec![PathBuf::from("crates/tui/src/main.rs")],
1260 context: vec!["release gate".to_string()],
1261 budget: Some(FleetTaskBudget {
1262 max_tokens: Some(8000),
1263 max_steps: Some(0),
1264 max_tool_calls: Some(20),
1265 max_seconds: Some(300),
1266 }),
1267 tags: vec!["release".to_string()],
1268 expected_artifacts: vec![FleetArtifactKind::Log],
1269 scorer: Some(FleetScorerSpec::ExitCode),
1270 retry_policy: Some(FleetRetryPolicy::default()),
1271 alert_policy: None,
1272 timeout_seconds: Some(300),
1273 metadata: BTreeMap::new(),
1274 }],
1275 worker_specs: vec![],
1276 labels: BTreeMap::new(),
1277 security_policy: None,
1278 created_at: "2026-06-12T17:00:00Z".to_string(),
1279 updated_at: None,
1280 completed_at: None,
1281 usage_ceiling: None,
1282 };
1283 let json = serde_json::to_string(&run).unwrap();
1284 let back: FleetRun = serde_json::from_str(&json).unwrap();
1285 assert_eq!(back.id, run.id);
1286 assert_eq!(back.status, FleetRunStatus::Running);
1287 assert_eq!(back.target, Some(FleetRuntimeTarget::ThisComputer));
1288 assert_eq!(back.roles, vec!["release-checker"]);
1289 assert_eq!(
1290 back.workflow.as_ref().map(|workflow| workflow.id.as_str()),
1291 Some("release-checks")
1292 );
1293 assert_eq!(back.task_specs.len(), 1);
1294 assert_eq!(
1295 back.task_specs[0].budget.as_ref().unwrap().max_steps,
1296 Some(0)
1297 );
1298 assert_eq!(
1299 back.task_specs[0].worker.as_ref().unwrap().role.as_deref(),
1300 Some("release-checker")
1301 );
1302 assert_eq!(
1303 back.task_specs[0]
1304 .workspace
1305 .as_ref()
1306 .unwrap()
1307 .required_files,
1308 vec![PathBuf::from("Cargo.toml")]
1309 );
1310 }
1311
1312 #[test]
1313 fn worker_profile_carries_agent_profile_and_loadout_intent() {
1314 let json = r#"{
1315 "profile": "adversarial_reviewer",
1316 "role": "reviewer",
1317 "loadout": "auto",
1318 "model_class": "balanced",
1319 "model": "deepseek-v4-pro",
1320 "tool_profile": "read-only",
1321 "tools": ["read_file"],
1322 "capabilities": ["rust"]
1323 }"#;
1324
1325 let profile: FleetTaskWorkerProfile = serde_json::from_str(json).unwrap();
1326
1327 assert_eq!(
1328 profile.agent_profile.as_deref(),
1329 Some("adversarial_reviewer")
1330 );
1331 assert_eq!(profile.role.as_deref(), Some("reviewer"));
1332 assert_eq!(profile.loadout.as_deref(), Some("auto"));
1333 assert_eq!(profile.model_class.as_deref(), Some("balanced"));
1334 assert_eq!(profile.model.as_deref(), Some("deepseek-v4-pro"));
1335 assert_eq!(profile.tool_profile.as_deref(), Some("read-only"));
1336
1337 let serialized = serde_json::to_value(&profile).unwrap();
1338 assert_eq!(serialized["agent_profile"], "adversarial_reviewer");
1339 assert_eq!(serialized["model"], "deepseek-v4-pro");
1340 assert!(serialized.get("profile").is_none());
1341 }
1342
1343 #[test]
1344 fn worker_event_lifecycle_round_trip() {
1345 let events = vec![
1346 FleetWorkerEvent {
1347 seq: 1,
1348 run_id: FleetRunId::from("run-002"),
1349 worker_id: "worker-a".to_string(),
1350 task_id: "task-1".to_string(),
1351 timestamp: "2026-06-12T17:01:00Z".to_string(),
1352 payload: FleetWorkerEventPayload::Queued,
1353 extra: BTreeMap::new(),
1354 },
1355 FleetWorkerEvent {
1356 seq: 2,
1357 run_id: FleetRunId::from("run-002"),
1358 worker_id: "worker-a".to_string(),
1359 task_id: "task-1".to_string(),
1360 timestamp: "2026-06-12T17:01:05Z".to_string(),
1361 payload: FleetWorkerEventPayload::RunningTool {
1362 tool: "bash".to_string(),
1363 call_id: Some("call-1".to_string()),
1364 },
1365 extra: BTreeMap::new(),
1366 },
1367 FleetWorkerEvent {
1368 seq: 3,
1369 run_id: FleetRunId::from("run-002"),
1370 worker_id: "worker-a".to_string(),
1371 task_id: "task-1".to_string(),
1372 timestamp: "2026-06-12T17:02:00Z".to_string(),
1373 payload: FleetWorkerEventPayload::Completed {
1374 exit_code: Some(0),
1375 summary: Some("ok".to_string()),
1376 },
1377 extra: BTreeMap::new(),
1378 },
1379 ];
1380 let json = serde_json::to_string(&events).unwrap();
1381 let back: Vec<FleetWorkerEvent> = serde_json::from_str(&json).unwrap();
1382 assert_eq!(back.len(), 3);
1383 assert!(matches!(back[0].payload, FleetWorkerEventPayload::Queued));
1384 assert!(matches!(
1385 back[2].payload,
1386 FleetWorkerEventPayload::Completed { .. }
1387 ));
1388 }
1389
1390 #[test]
1391 fn workflow_receipt_round_trip_keeps_outer_and_inner_run_ids_distinct() {
1392 let event = FleetWorkerEvent {
1393 seq: 3,
1394 run_id: FleetRunId::from("fleet-run-1"),
1395 worker_id: "worker-a".to_string(),
1396 task_id: "task-1".to_string(),
1397 timestamp: "2026-07-10T00:00:00Z".to_string(),
1398 payload: FleetWorkerEventPayload::WorkflowEvent {
1399 workflow_run_id: "workflow_1".to_string(),
1400 event: serde_json::json!({"type": "task_completed"}),
1401 },
1402 extra: BTreeMap::new(),
1403 };
1404 let value = serde_json::to_value(&event).unwrap();
1405 assert_eq!(value["run_id"], "fleet-run-1");
1406 assert_eq!(value["workflow_run_id"], "workflow_1");
1407 let back: FleetWorkerEvent = serde_json::from_value(value).unwrap();
1408 assert!(matches!(
1409 back.payload,
1410 FleetWorkerEventPayload::WorkflowEvent {
1411 workflow_run_id,
1412 ref event,
1413 } if workflow_run_id == "workflow_1" && event["type"] == "task_completed"
1414 ));
1415 }
1416
1417 #[test]
1418 fn alert_policy_round_trip() {
1419 let policy = FleetAlertPolicy {
1420 events: vec![FleetAlertEventClass::Stale],
1421 channels: vec![FleetAlertChannel::Slack {
1422 webhook: FleetAlertEndpoint::inline("https://hooks.slack.com/test"),
1423 }],
1424 after_attempts: Some(2),
1425 after_minutes_stale: Some(10),
1426 };
1427 let json = serde_json::to_string(&policy).unwrap();
1428 assert!(json.contains("\"events\":[\"stale\"]"));
1429 assert!(json.contains("\"kind\":\"slack\""));
1430 let back: FleetAlertPolicy = serde_json::from_str(&json).unwrap();
1431 assert_eq!(back.events, vec![FleetAlertEventClass::Stale]);
1432 assert_eq!(back.after_attempts, Some(2));
1433 }
1434
1435 #[test]
1436 fn artifact_other_kind_round_trip() {
1437 let artifact = FleetArtifactRef {
1438 kind: FleetArtifactKind::Other("coverage.xml".to_string()),
1439 path: PathBuf::from("/tmp/coverage.xml"),
1440 checksum: Some("sha256:abc".to_string()),
1441 mime_type: Some("application/xml".to_string()),
1442 size_bytes: Some(1024),
1443 };
1444 let json = serde_json::to_string(&artifact).unwrap();
1445 let back: FleetArtifactRef = serde_json::from_str(&json).unwrap();
1446 assert_eq!(back.kind, artifact.kind);
1447 assert_eq!(back.size_bytes, Some(1024));
1448 }
1449
1450 #[test]
1451 fn ssh_host_spec_accepts_minimal_legacy_json() {
1452 let json = r#"{"kind":"ssh","host":"builder.example.test"}"#;
1453 let host: FleetHostSpec = serde_json::from_str(json).unwrap();
1454
1455 match host {
1456 FleetHostSpec::Ssh {
1457 host,
1458 port,
1459 user,
1460 identity,
1461 known_hosts,
1462 host_key_fingerprint,
1463 working_directory,
1464 env_allowlist,
1465 codewhale_binary,
1466 } => {
1467 assert_eq!(host, "builder.example.test");
1468 assert_eq!(port, None);
1469 assert_eq!(user, None);
1470 assert_eq!(identity, None);
1471 assert_eq!(known_hosts, None);
1472 assert_eq!(host_key_fingerprint, None);
1473 assert_eq!(working_directory, None);
1474 assert!(env_allowlist.is_empty());
1475 assert_eq!(codewhale_binary, None);
1476 }
1477 other => panic!("expected ssh host spec, got {other:?}"),
1478 }
1479 }
1480
1481 #[test]
1482 fn artifact_kind_uses_flat_string_json() {
1483 let known = serde_json::to_string(&FleetArtifactKind::TestResult).unwrap();
1484 assert_eq!(known, "\"test_result\"");
1485
1486 let custom =
1487 serde_json::to_string(&FleetArtifactKind::Other("coverage.xml".to_string())).unwrap();
1488 assert_eq!(custom, "\"coverage.xml\"");
1489
1490 let parsed: FleetArtifactKind = serde_json::from_str("\"coverage.xml\"").unwrap();
1491 assert_eq!(parsed, FleetArtifactKind::Other("coverage.xml".to_string()));
1492 }
1493
1494 #[test]
1495 fn retry_policy_missing_fields_use_nonzero_defaults() {
1496 let policy: FleetRetryPolicy = serde_json::from_value(serde_json::json!({})).unwrap();
1497 assert_eq!(policy, FleetRetryPolicy::default());
1498
1499 let policy: FleetRetryPolicy =
1500 serde_json::from_value(serde_json::json!({"max_attempts": 5})).unwrap();
1501 assert_eq!(policy.max_attempts, 5);
1502 assert_eq!(
1503 policy.initial_backoff_seconds,
1504 FleetRetryPolicy::default().initial_backoff_seconds
1505 );
1506 assert_eq!(
1507 policy.max_backoff_seconds,
1508 FleetRetryPolicy::default().max_backoff_seconds
1509 );
1510 assert_eq!(
1511 policy.backoff_multiplier,
1512 FleetRetryPolicy::default().backoff_multiplier
1513 );
1514 }
1515
1516 #[test]
1517 fn sparse_worker_events_omit_absent_optional_fields() {
1518 let heartbeat = FleetWorkerEventPayload::Heartbeat {
1519 cpu_percent: None,
1520 memory_mb: None,
1521 };
1522 let heartbeat_json = serde_json::to_value(&heartbeat).unwrap();
1523 assert_eq!(heartbeat_json, serde_json::json!({"state": "heartbeat"}));
1524
1525 let completed = FleetWorkerEventPayload::Completed {
1526 exit_code: None,
1527 summary: None,
1528 };
1529 let completed_json = serde_json::to_value(&completed).unwrap();
1530 assert_eq!(completed_json, serde_json::json!({"state": "completed"}));
1531 }
1532
1533 #[test]
1534 fn receipt_round_trip() {
1535 let receipt = FleetReceipt {
1536 run_id: FleetRunId::from("run-003"),
1537 task_id: "task-1".to_string(),
1538 worker_id: "worker-b".to_string(),
1539 attempt: Some(2),
1540 terminal_seq: Some(7),
1541 completed_at: "2026-06-12T17:03:00Z".to_string(),
1542 result: FleetTaskResult::Pass,
1543 failure_kind: None,
1544 artifacts: vec![],
1545 score: Some(FleetScore {
1546 value: 0.95,
1547 max: Some(1.0),
1548 notes: None,
1549 }),
1550 resolved_route: None,
1551 saved_session_id: None,
1552 effective_permissions: None,
1553 };
1554 let json = serde_json::to_string(&receipt).unwrap();
1555 let back: FleetReceipt = serde_json::from_str(&json).unwrap();
1556 assert_eq!(back.result, FleetTaskResult::Pass);
1557 assert_eq!(back.score.as_ref().unwrap().value, 0.95);
1558 assert_eq!(back.attempt, Some(2));
1559 assert_eq!(back.terminal_seq, Some(7));
1560 }
1561
1562 #[test]
1563 fn partial_receipt_records_failure_source_when_needed() {
1564 let receipt = FleetReceipt {
1565 run_id: FleetRunId::from("run-004"),
1566 task_id: "task-2".to_string(),
1567 worker_id: "worker-c".to_string(),
1568 attempt: None,
1569 terminal_seq: None,
1570 completed_at: "2026-06-12T17:04:00Z".to_string(),
1571 result: FleetTaskResult::Partial,
1572 failure_kind: Some(FleetTaskFailureKind::Verifier),
1573 artifacts: vec![],
1574 score: Some(FleetScore {
1575 value: 0.5,
1576 max: Some(1.0),
1577 notes: Some("manual verification required".to_string()),
1578 }),
1579 resolved_route: None,
1580 saved_session_id: None,
1581 effective_permissions: None,
1582 };
1583
1584 let json = serde_json::to_string(&receipt).unwrap();
1585 assert!(json.contains("\"result\":\"partial\""));
1586 assert!(json.contains("\"failure_kind\":\"verifier\""));
1587 let back: FleetReceipt = serde_json::from_str(&json).unwrap();
1588 assert_eq!(back.result, FleetTaskResult::Partial);
1589 assert_eq!(back.failure_kind, Some(FleetTaskFailureKind::Verifier));
1590 }
1591
1592 #[test]
1593 fn ssh_host_spec_with_key_pinning_round_trip() {
1594 let spec = FleetHostSpec::Ssh {
1595 host: "builder.trusted.example.com".to_string(),
1596 port: Some(22),
1597 user: Some("codewhale".to_string()),
1598 identity: Some(PathBuf::from("~/.ssh/codewhale_fleet")),
1599 known_hosts: Some(PathBuf::from("~/.ssh/known_hosts")),
1600 host_key_fingerprint: Some("SHA256:aLGqZo1M6c...".to_string()),
1601 working_directory: Some(PathBuf::from("/srv/codewhale/work")),
1602 env_allowlist: vec!["CODEWHALE_PROFILE".to_string()],
1603 codewhale_binary: Some("/usr/local/bin/codewhale".to_string()),
1604 };
1605 let json = serde_json::to_string_pretty(&spec).unwrap();
1606 assert!(json.contains("\"known_hosts\""));
1607 assert!(json.contains("\"host_key_fingerprint\""));
1608 assert!(json.contains("SHA256:aLGqZo1M6c..."));
1609
1610 let back: FleetHostSpec = serde_json::from_str(&json).unwrap();
1611 match back {
1612 FleetHostSpec::Ssh {
1613 host,
1614 known_hosts,
1615 host_key_fingerprint,
1616 ..
1617 } => {
1618 assert_eq!(host, "builder.trusted.example.com");
1619 assert_eq!(known_hosts, Some(PathBuf::from("~/.ssh/known_hosts")));
1620 assert_eq!(
1621 host_key_fingerprint,
1622 Some("SHA256:aLGqZo1M6c...".to_string())
1623 );
1624 }
1625 other => panic!("expected ssh host spec, got {other:?}"),
1626 }
1627 }
1628
1629 #[test]
1630 fn secret_ref_redacted_never_exposes_value() {
1631 let ref_ = FleetSecretRef::new("DEEPSEEK_API_KEY");
1632 let redacted = ref_.redacted();
1633 assert!(redacted.contains("DEEPSEEK_API_KEY"));
1634 assert!(!redacted.contains("sk-"));
1635 assert!(redacted.contains("<secret:"));
1636
1637 let ref_ = FleetSecretRef::with_source("GH_TOKEN", "env");
1638 let redacted = ref_.redacted();
1639 assert!(redacted.contains("env.GH_TOKEN"));
1640 assert!(!redacted.contains("ghp_"));
1641 }
1642
1643 #[test]
1644 fn alert_endpoint_from_secret_round_trip() {
1645 let endpoint = FleetAlertEndpoint::from_secret(FleetSecretRef::new("SLACK_WEBHOOK"));
1646 let json = serde_json::to_string(&endpoint).unwrap();
1647 assert!(json.contains("SLACK_WEBHOOK"));
1648 assert!(!json.contains("hooks.slack.com"));
1649
1650 let back: FleetAlertEndpoint = serde_json::from_str(&json).unwrap();
1651 assert_eq!(back.url_ref.as_ref().unwrap().key, "SLACK_WEBHOOK");
1652 assert_eq!(back.url, None);
1653 }
1654
1655 #[test]
1656 fn secret_ref_accepts_legacy_string_wire_shape() {
1657 let ref_: FleetSecretRef = serde_json::from_str(r#""CODEWHALE_FLEET_TOKEN""#).unwrap();
1658 assert_eq!(ref_, FleetSecretRef::new("CODEWHALE_FLEET_TOKEN"));
1659
1660 let ref_: FleetSecretRef =
1661 serde_json::from_str(r#"{"key":"GH_TOKEN","source":"env"}"#).unwrap();
1662 assert_eq!(ref_, FleetSecretRef::with_source("GH_TOKEN", "env"));
1663 }
1664
1665 #[test]
1666 fn trust_level_accepts_hyphenated_remote_verified() {
1667 let trust: FleetTrustLevel = serde_json::from_str(r#""remote-verified""#).unwrap();
1668 assert_eq!(trust, FleetTrustLevel::RemoteVerified);
1669
1670 let canonical = serde_json::to_string(&trust).unwrap();
1671 assert_eq!(canonical, r#""remote_verified""#);
1672 }
1673
1674 #[test]
1675 fn alert_channel_accepts_legacy_webhook_fields() {
1676 let channel: FleetAlertChannel = serde_json::from_str(
1677 r#"{
1678 "kind": "slack",
1679 "webhook_url": "https://hooks.slack.com/test",
1680 "secret": "SLACK_SIGNING_SECRET"
1681 }"#,
1682 )
1683 .unwrap();
1684
1685 match channel {
1686 FleetAlertChannel::Slack { webhook } => {
1687 assert_eq!(webhook.url.as_deref(), Some("https://hooks.slack.com/test"));
1688 assert_eq!(
1689 webhook.secret_ref,
1690 Some(FleetSecretRef::new("SLACK_SIGNING_SECRET"))
1691 );
1692 }
1693 other => panic!("expected slack channel, got {other:?}"),
1694 }
1695 }
1696
1697 #[test]
1698 fn security_policy_defaults_are_conservative() {
1699 let policy = FleetSecurityPolicy::default();
1700 assert_eq!(policy.default_trust_level, FleetTrustLevel::Sandbox);
1701 assert!(policy.allowed_secrets.is_empty());
1702 assert!(policy.capability_grants.is_empty());
1703 assert_eq!(policy.max_trust_level, FleetTrustLevel::Operator);
1704 assert!(!policy.require_identity_verification);
1705 }
1706
1707 #[test]
1708 fn trust_level_ordinal_reflects_privilege() {
1709 assert!(FleetTrustLevel::Operator > FleetTrustLevel::RemoteVerified);
1710 assert!(FleetTrustLevel::RemoteVerified > FleetTrustLevel::Local);
1711 assert!(FleetTrustLevel::Local > FleetTrustLevel::Sandbox);
1712
1713 assert!(FleetTrustLevel::Operator.may_access_secrets());
1714 assert!(!FleetTrustLevel::Sandbox.may_access_secrets());
1715 assert!(!FleetTrustLevel::Sandbox.may_write_workspace());
1716 assert!(FleetTrustLevel::Operator.may_write_workspace());
1717 }
1718
1719 fn sample_receipt_with_route() -> FleetReceipt {
1720 FleetReceipt {
1721 run_id: FleetRunId::from("run-route"),
1722 task_id: "task-route".to_string(),
1723 worker_id: "worker-route".to_string(),
1724 attempt: Some(1),
1725 terminal_seq: Some(4),
1726 completed_at: "2026-06-23T00:00:00Z".to_string(),
1727 result: FleetTaskResult::Pass,
1728 failure_kind: None,
1729 artifacts: vec![],
1730 score: None,
1731 resolved_route: Some(FleetResolvedRoute {
1732 provider_id: "deepseek".to_string(),
1733 provider_exact_id: None,
1734 provider_kind: "deepseek".to_string(),
1735 canonical_model: Some("deepseek-v4-pro".to_string()),
1736 wire_model_id: "deepseek-v4-pro".to_string(),
1737 protocol: "chat_completions".to_string(),
1738 role: Some("builder".to_string()),
1739 loadout: Some("auto".to_string()),
1740 model_class: Some("balanced".to_string()),
1741 model_route: Some("auto".to_string()),
1742 reasoning_effort: Some("high".to_string()),
1743 role_source: Some("task.role".to_string()),
1744 loadout_source: Some("task.loadout".to_string()),
1745 model_class_source: Some("task.model_class".to_string()),
1746 model_source: Some("task.model".to_string()),
1747 external_agent: None,
1748 external_agent_transport: None,
1749 source: "resolver".to_string(),
1750 }),
1751 saved_session_id: None,
1752 effective_permissions: Some(FleetEffectivePermissions {
1753 write: true,
1754 network: true,
1755 shell: "full".to_string(),
1756 tool_scope: "explicit".to_string(),
1757 tools: vec!["read_file".to_string(), "apply_patch".to_string()],
1758 background: true,
1759 max_spawn_depth: 2,
1760 profile_id: Some("builder".to_string()),
1761 profile_origin: Some("built_in".to_string()),
1762 source: "worker_runtime_profile".to_string(),
1763 }),
1764 }
1765 }
1766
1767 #[test]
1768 fn fleet_resolved_route_round_trips() {
1769 let receipt = sample_receipt_with_route();
1770 let json = serde_json::to_string(&receipt).unwrap();
1771 let back: FleetReceipt = serde_json::from_str(&json).unwrap();
1772 assert_eq!(back.resolved_route, receipt.resolved_route);
1773 assert_eq!(back.effective_permissions, receipt.effective_permissions);
1774 let route = back.resolved_route.unwrap();
1775 assert_eq!(route.provider_id, "deepseek");
1776 assert_eq!(route.wire_model_id, "deepseek-v4-pro");
1777 assert_eq!(route.protocol, "chat_completions");
1778 assert_eq!(route.role.as_deref(), Some("builder"));
1779 assert_eq!(route.loadout.as_deref(), Some("auto"));
1780 assert_eq!(route.model_class.as_deref(), Some("balanced"));
1781 assert_eq!(route.model_route.as_deref(), Some("auto"));
1782 assert_eq!(route.reasoning_effort.as_deref(), Some("high"));
1783 assert_eq!(route.role_source.as_deref(), Some("task.role"));
1784 assert_eq!(route.loadout_source.as_deref(), Some("task.loadout"));
1785 assert_eq!(
1786 route.model_class_source.as_deref(),
1787 Some("task.model_class")
1788 );
1789 assert_eq!(route.model_source.as_deref(), Some("task.model"));
1790 assert_eq!(route.source, "resolver");
1791
1792 let permissions = back
1793 .effective_permissions
1794 .expect("effective permissions should round-trip");
1795 assert!(permissions.write);
1796 assert!(permissions.network);
1797 assert_eq!(permissions.shell, "full");
1798 assert_eq!(permissions.tool_scope, "explicit");
1799 assert_eq!(
1800 permissions.tools,
1801 vec!["read_file".to_string(), "apply_patch".to_string()]
1802 );
1803 assert!(permissions.background);
1804 assert_eq!(permissions.max_spawn_depth, 2);
1805 assert_eq!(permissions.profile_id.as_deref(), Some("builder"));
1806 assert_eq!(permissions.profile_origin.as_deref(), Some("built_in"));
1807 assert_eq!(permissions.source, "worker_runtime_profile");
1808 }
1809
1810 #[test]
1811 fn fleet_receipt_without_resolved_route_still_deserializes() {
1812 // An old ledger receipt JSON written before #3154 has no
1813 // `resolved_route` key; `#[serde(default)]` must keep it readable.
1814 let legacy = r#"{
1815 "run_id": "run-legacy",
1816 "task_id": "task-legacy",
1817 "worker_id": "worker-legacy",
1818 "completed_at": "2026-06-01T00:00:00Z",
1819 "result": "pass",
1820 "artifacts": [],
1821 "score": null
1822 }"#;
1823 let receipt: FleetReceipt = serde_json::from_str(legacy).unwrap();
1824 assert_eq!(receipt.task_id, "task-legacy");
1825 assert!(receipt.resolved_route.is_none());
1826 assert!(receipt.attempt.is_none());
1827 assert!(receipt.terminal_seq.is_none());
1828 }
1829
1830 #[test]
1831 fn fleet_resolved_route_legacy_shape_still_deserializes() {
1832 let legacy = r#"{
1833 "run_id": "run-route",
1834 "task_id": "task-route",
1835 "worker_id": "worker-route",
1836 "completed_at": "2026-06-23T00:00:00Z",
1837 "result": "pass",
1838 "artifacts": [],
1839 "score": null,
1840 "resolved_route": {
1841 "provider_id": "deepseek",
1842 "provider_kind": "deepseek",
1843 "canonical_model": "deepseek-v4-pro",
1844 "wire_model_id": "deepseek-v4-pro",
1845 "protocol": "chat_completions",
1846 "role": "builder",
1847 "loadout": "fast",
1848 "source": "resolver"
1849 }
1850 }"#;
1851
1852 let receipt: FleetReceipt = serde_json::from_str(legacy).unwrap();
1853 let route = receipt.resolved_route.expect("legacy route should parse");
1854 assert_eq!(route.source, "resolver");
1855 assert_eq!(route.role.as_deref(), Some("builder"));
1856 assert_eq!(route.loadout.as_deref(), Some("fast"));
1857 assert_eq!(route.model_class, None);
1858 assert_eq!(route.model_route, None);
1859 assert_eq!(route.reasoning_effort, None);
1860 assert_eq!(route.role_source, None);
1861 assert_eq!(route.loadout_source, None);
1862 assert_eq!(route.model_class_source, None);
1863 assert_eq!(route.model_source, None);
1864 }
1865
1866 #[test]
1867 fn fleet_resolved_route_serialization_carries_no_secrets() {
1868 let receipt = sample_receipt_with_route();
1869 // Scan the serialized resolved-route object: this is the field whose
1870 // no-secrets invariant we are asserting. Scoping to the route value
1871 // avoids false positives from unrelated envelope ids (e.g. a task id
1872 // such as "task-foo" innocently contains the substring "sk-").
1873 let route_json = serde_json::to_string(receipt.resolved_route.as_ref().unwrap()).unwrap();
1874 assert_no_secret_markers(&route_json);
1875 // The envelope as a whole must also stay credential-free.
1876 let receipt_json = serde_json::to_string(&receipt).unwrap();
1877 for needle in SECRET_KEY_MARKERS {
1878 assert!(
1879 !receipt_json.to_ascii_lowercase().contains(needle),
1880 "receipt JSON must not contain secret-key marker {needle:?}: {receipt_json}"
1881 );
1882 }
1883 }
1884
1885 /// Substrings that indicate a leaked credential field/value. These are
1886 /// deliberately specific so legitimate ids/model names do not trip them.
1887 const SECRET_KEY_MARKERS: &[&str] = &[
1888 "api_key",
1889 "apikey",
1890 "api-key",
1891 "authorization",
1892 "bearer ",
1893 "auth_token",
1894 "auth-token",
1895 "password",
1896 "credential",
1897 "sk-ant-",
1898 "sk-proj-",
1899 "sk-or-",
1900 "secret",
1901 ];
1902
1903 fn assert_no_secret_markers(json: &str) {
1904 let haystack = json.to_ascii_lowercase();
1905 for needle in SECRET_KEY_MARKERS {
1906 assert!(
1907 !haystack.contains(needle),
1908 "resolved-route JSON must not contain secret marker {needle:?}: {json}"
1909 );
1910 }
1911 }
1912 }
1913
1914 /// Default maximum sub-agent delegation depth (root -> child -> grandchild ->
1915 /// great-grandchild). Explicit owner values may raise or lower this limit;
1916 /// zero disables delegation.
1917 pub const DEFAULT_SPAWN_DEPTH: u32 = 3;
1918
1919 /// Shell posture, ordered most → least restrictive so `min_with` is the safe
1920 /// side of a clamp.
1921 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1922 #[serde(rename_all = "snake_case")]
1923 pub enum ShellCeiling {
1924 None,
1925 ReadOnly,
1926 Full,
1927 }
1928
1929 impl ShellCeiling {
1930 #[must_use]
1931 pub const fn as_str(self) -> &'static str {
1932 match self {
1933 Self::None => "none",
1934 Self::ReadOnly => "read_only",
1935 Self::Full => "full",
1936 }
1937 }
1938
1939 #[must_use]
1940 pub fn min_with(self, other: Self) -> Self {
1941 if self <= other { self } else { other }
1942 }
1943 }
1944
1945 /// A Runtime child-authority envelope.
1946 ///
1947 /// This type is intentionally not part of `ExactMember`. Exact Fleet files
1948 /// choose identity, route, and reasoning; Runtime intersects its role posture
1949 /// with the live parent after member selection. Keeping the envelope as a
1950 /// separate type lets receipts describe the authority that Runtime actually
1951 /// installed without turning a saved Fleet into a trust boundary.
1952 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1953 pub struct PermissionCeiling {
1954 pub write: bool,
1955 /// Whether the Runtime child may be handed a **model-visible network tool**
1956 /// (fetch, browse, HTTP).
1957 ///
1958 /// This is deliberately *not* a statement about transport. Host-owned
1959 /// provider inference — the ordinary API call CodeWhale makes on the
1960 /// member's behalf — always happens over the network and is not governed
1961 /// by this field. A child with `network_tool = false` still runs on a
1962 /// remote model; it simply has no tool with which to reach the network
1963 /// itself. Receipts disclose that distinction rather than implying an
1964 /// air-gap.
1965 #[serde(alias = "network")]
1966 pub network_tool: bool,
1967 pub shell: ShellCeiling,
1968 /// Nested-delegation budget the Runtime child may consume.
1969 pub delegation_depth: u32,
1970 /// Whether the Runtime child may be handed tools at all.
1971 pub tools: bool,
1972 }
1973
1974 impl PermissionCeiling {
1975 /// The Router's fixed posture: no tools (so no network tool), no shell, no
1976 /// writes, no delegation. Not configurable — see `RouterMember`.
1977 ///
1978 /// The Router itself is still *inferred* by its configured provider over
1979 /// the network; that is host-owned transport, disclosed on the receipt.
1980 pub const ROUTER: Self = Self {
1981 write: false,
1982 network_tool: false,
1983 shell: ShellCeiling::None,
1984 delegation_depth: 0,
1985 tools: false,
1986 };
1987
1988 /// Legacy named presets retained for Runtime compatibility and tests.
1989 ///
1990 /// The exact Fleet parser accepts a historic `permissions` key only as
1991 /// ignored input; no preset selected here is projected onto a member.
1992 pub fn preset(name: &str) -> Option<Self> {
1993 let base = |write, network_tool, shell, delegation_depth| Self {
1994 write,
1995 network_tool,
1996 shell,
1997 delegation_depth,
1998 tools: true,
1999 };
2000 match name.trim().to_ascii_lowercase().as_str() {
2001 "none" => Some(Self::ROUTER),
2002 "analyst" => Some(base(false, false, ShellCeiling::None, 0)),
2003 "read_only" | "readonly" => Some(base(false, false, ShellCeiling::ReadOnly, 0)),
2004 "tester" | "verifier" => Some(base(false, false, ShellCeiling::Full, 0)),
2005 "read_write" | "readwrite" => Some(base(true, false, ShellCeiling::Full, 0)),
2006 "full" => Some(base(true, true, ShellCeiling::Full, 1)),
2007 _ => None,
2008 }
2009 }
2010
2011 /// Narrow this ceiling against the active session posture. Every field
2012 /// takes the more restrictive side, so the result can never grant more
2013 /// than either input.
2014 #[must_use]
2015 pub fn clamp_to(self, session: Self) -> Self {
2016 Self {
2017 write: self.write && session.write,
2018 network_tool: self.network_tool && session.network_tool,
2019 shell: self.shell.min_with(session.shell),
2020 delegation_depth: self.delegation_depth.min(session.delegation_depth),
2021 tools: self.tools && session.tools,
2022 }
2023 }
2024 }
2025
2026 impl Default for PermissionCeiling {
2027 fn default() -> Self {
2028 Self::preset("read_only").expect("read_only is a known preset")
2029 }
2030 }
2031
2031 lines RUST