Skip to main content

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