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