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