Skip to main content

sail_api/
jobs.rs

1//! Versioned, bounded local project-job protocol, independent of the SMT cache.
2
3use std::collections::BTreeMap;
4use std::fmt::Write as _;
5use std::io::{self, Read, Write};
6use std::path::{Path, PathBuf};
7
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11/// Project job protocol version.
12pub const VERSION: u32 = 1;
13/// Maximum request or response frame (32 MiB).
14pub const MAX_FRAME: usize = 32 * 1024 * 1024;
15
16/// A verification request. The environment belongs to its submitting client.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct Submission {
19    /// Explicit backend/repair mode; old endpoints are never used for these requests.
20    #[serde(default)]
21    pub mode: Mode,
22    /// Absolute Cargo project directory.
23    pub project_dir: PathBuf,
24    /// Verification arguments, without the `verify` subcommand or output flags.
25    pub args: Vec<String>,
26    /// Force fresh verification even when a proof receipt exists.
27    pub force: bool,
28    /// UTF-8 process environment, captured by the submitting client.
29    pub environment: BTreeMap<String, String>,
30    /// Content revision observed by the submitting client.
31    pub input_revision: Option<String>,
32}
33
34/// Verification execution mode, negotiated through the version-two job endpoint.
35#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(tag = "kind", content = "selection", rename_all = "snake_case")]
37pub enum Mode {
38    /// Existing stock pinned Verus verification.
39    #[default]
40    Stock,
41    /// Direct standalone Verus file; requires explicit endpoint support.
42    Standalone,
43    /// Exact standalone repair focus plus independent full-file validation.
44    StandaloneRepair {
45        /// Exact crate-qualified function reported by Verus.
46        function: String,
47    },
48    /// Optional explicitly selected Sail-managed interactive engine.
49    Interactive,
50    /// One engine batch containing focus and independent full validation.
51    Repair(crate::repair::Selection),
52}
53
54/// Durable lifecycle, independent of the proof outcome.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum Lifecycle {
58    /// Waiting for the single verification worker.
59    Queued,
60    /// The verification process is running.
61    Running,
62    /// A complete verification result is available (including failed proofs).
63    Completed,
64    /// Explicitly cancelled by a client.
65    Cancelled,
66    /// Cancelled because a newer input revision was requested.
67    Superseded,
68    /// Startup, persistence, process, or restart failure.
69    InfrastructureError,
70}
71impl Lifecycle {
72    /// Whether no more worker events are expected.
73    #[must_use]
74    pub const fn terminal(self) -> bool {
75        !matches!(self, Self::Queued | Self::Running)
76    }
77}
78
79/// How the result's input revision relates to current inputs.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(rename_all = "snake_case")]
82pub enum Currentness {
83    /// The runner established a coherent current revision.
84    Current,
85    /// Inputs changed during or since verification.
86    Historical,
87    /// Input coverage or result attribution could not be established.
88    Unknown,
89}
90
91/// Persistent status, safe to inspect while verification runs.
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct Status {
94    /// Protocol/store format version.
95    pub version: u32,
96    /// Durable job id.
97    pub id: String,
98    /// Absolute project directory.
99    pub project_dir: PathBuf,
100    /// Requested arguments; never broadened silently.
101    pub args: Vec<String>,
102    /// Lifecycle, distinct from proof verdict.
103    pub state: Lifecycle,
104    /// Submission time, milliseconds since the Unix epoch.
105    pub submitted_at_ms: u64,
106    /// Start time, if started.
107    pub started_at_ms: Option<u64>,
108    /// Completion time, if terminal.
109    pub finished_at_ms: Option<u64>,
110    /// Process exit status, if available.
111    pub exit_code: Option<i32>,
112    /// Input revision before the run.
113    pub input_revision: Option<String>,
114    /// Result currentness.
115    pub currentness: Currentness,
116    /// Stable infrastructure error code and explanatory text, when present.
117    pub error: Option<String>,
118}
119
120/// A job result preserving the managed runner's versioned document.
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct ResultDocument {
123    /// Qualified contract snapshot metadata; absent for ordinary project jobs.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub contracts: Option<Box<crate::contracts::Evidence>>,
126    /// Independent focus/full repair evidence, when this was an engine batch.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub repair: Option<Box<crate::repair::ResultDocument>>,
129    /// Job status and provenance.
130    pub job: Status,
131    /// Managed project result, only after a complete worker output.
132    pub result: Option<Value>,
133}
134
135/// A bounded slice of a job's diagnostics or target events.
136#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct Chunk {
138    /// Byte offset of the next slice.
139    pub next: u64,
140    /// UTF-8 text (lossy only for diagnostics from non-UTF-8 subprocesses).
141    pub text: String,
142    /// Whether this job has reached a terminal state.
143    pub complete: bool,
144}
145
146/// One local RPC.
147#[derive(Debug, Clone, Serialize, Deserialize)]
148#[serde(tag = "operation", rename_all = "snake_case")]
149pub enum Request {
150    /// Negotiate and inspect optional daemon-owned preparation.
151    PreparationStatus,
152    /// Enqueue optional work; never changes the original verification result.
153    Prepare(crate::preparation::Submission),
154    /// Hold foreground priority until this connection closes.
155    Foreground {
156        /// Preparation protocol version.
157        version: u32,
158        /// Originating working directory.
159        project_dir: PathBuf,
160        /// Arguments used to resolve the workspace scheduling key.
161        args: Vec<String>,
162    },
163    /// Fail-closed negotiation before any non-stock submission.
164    Capabilities,
165    /// Start a bounded owned mutation campaign over an authenticated source job.
166    SubmitMutation(crate::mutation::Submission),
167    /// Prepare separate exact scalar literal-contract witness queries; starts no verifier.
168    PrepareLiteralWitness {
169        /// Complete original source with its exact content identity.
170        source: crate::contracts::Submission,
171        /// Maximum selected literal candidates, between one and eight.
172        max_mutants: usize,
173    },
174    /// Rebuild an original-source witness plan and validate one concrete model.
175    ValidateLiteralWitness {
176        /// Full exact original source-bound plan.
177        plan: Box<crate::literal_witness::Plan>,
178        /// Exact deterministic original candidate identity.
179        candidate_id: String,
180        /// Complete original SAT model response from the pinned runtime.
181        result: Box<crate::runtime::QueryResult>,
182    },
183    /// Reauthenticate and read a retained mutation campaign.
184    Mutation {
185        /// Exact retained campaign identity.
186        id: String,
187    },
188    /// Cancel actual source jobs in one campaign.
189    CancelMutation {
190        /// Exact retained campaign identity.
191        id: String,
192    },
193    /// Read requirement-aware assurance for an authenticated neutral source job.
194    Assurance {
195        /// Exact durable source-job identity.
196        id: String,
197    },
198    /// Submit exact neutral source with Sail-owned execution controls.
199    SubmitContracts(crate::contracts::Submission),
200    /// Read bounded version-one proof observations using a resumable cursor.
201    ProofEvents {
202        /// Durable job identity.
203        id: String,
204        /// Last consumed event; stream identity must match on reconnect.
205        cursor: crate::proof::Cursor,
206        /// Maximum event count, clamped by the service.
207        limit: usize,
208    },
209    /// Explain an exact reported target/function, preserving raw evidence.
210    Explain {
211        /// Durable completed job identity.
212        id: String,
213        /// Complete Cargo target identity.
214        target: crate::proof::Target,
215        /// Exact crate-qualified function.
216        function: String,
217        /// Optional exact obligation id.
218        obligation: Option<String>,
219    },
220    /// Save independent immutable proof evidence outside job retention.
221    SaveBaseline {
222        /// Completed evidence source.
223        id: String,
224        /// Immutable owner-selected name.
225        name: String,
226    },
227    /// List retained immutable named baselines.
228    Baselines,
229    /// Read immutable evidence for its recorded revision, never current inputs.
230    GetBaseline {
231        /// Exact retained baseline name.
232        name: String,
233    },
234    /// Compare explicit completed evidence with an earlier job or baseline.
235    Compare {
236        /// Earlier named baseline or durable job.
237        before: crate::evidence::Reference,
238        /// Later completed job identity.
239        after: String,
240    },
241    /// Submit or coalesce an identical in-flight request.
242    Submit {
243        /// Requested verification.
244        submission: Submission,
245    },
246    /// List retained jobs, optionally for one canonical project directory.
247    List {
248        /// Project filter.
249        project_dir: Option<PathBuf>,
250    },
251    /// Inspect one job without waiting for verification.
252    Status {
253        /// Job id.
254        id: String,
255    },
256    /// Read one completed or in-progress result.
257    Result {
258        /// Job id.
259        id: String,
260    },
261    /// Cancel one job and its entire process group.
262    Cancel {
263        /// Job id.
264        id: String,
265        /// New edits supersede this run.
266        superseded: bool,
267    },
268    /// Read bounded stderr diagnostics from a byte offset.
269    Logs {
270        /// Job id.
271        id: String,
272        /// Byte offset.
273        offset: u64,
274    },
275    /// Read bounded JSON-lines target events from a byte offset.
276    Events {
277        /// Job id.
278        id: String,
279        /// Byte offset.
280        offset: u64,
281    },
282}
283
284/// A response or a stable user-facing error.
285#[derive(Debug, Clone, Serialize, Deserialize)]
286#[serde(tag = "response", content = "value", rename_all = "snake_case")]
287pub enum Response {
288    /// Optional preparation negotiation, status, or handoff acknowledgement.
289    Preparation(crate::preparation::Status),
290    /// Supported product contracts; does not claim an optional engine is installed.
291    Capabilities {
292        /// Independent proof stream version.
293        proof_version: u32,
294        /// Neutral source submission version; absent on older services.
295        #[serde(default, skip_serializing_if = "Option::is_none")]
296        neutral_contracts_version: Option<u32>,
297        /// Explicit supported source profiles; older endpoints advertise none.
298        #[serde(default, skip_serializing_if = "Vec::is_empty")]
299        neutral_contract_profiles: Vec<u32>,
300        /// Requirement assurance view version; absent on older services.
301        #[serde(default, skip_serializing_if = "Option::is_none")]
302        assurance_version: Option<u32>,
303        /// Bounded mutation protocol, absent on older services.
304        #[serde(default, skip_serializing_if = "Option::is_none")]
305        mutation_version: Option<u32>,
306        /// Non-stock submission modes are understood and never ignored.
307        /// Absent from services without the engine, which decode as false.
308        #[serde(default)]
309        repair: bool,
310        /// Direct-file jobs are understood; false on older endpoints.
311        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
312        standalone: bool,
313        /// Standalone repair is explicitly understood; absent on older endpoints.
314        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
315        standalone_repair: bool,
316    },
317    /// Authenticated bounded mutation evidence, independent of proof tiers.
318    Mutation(Box<crate::mutation::View>),
319    /// Deterministic source-admitted witness queries, separate from native mutation.
320    LiteralWitness(Box<crate::literal_witness::Plan>),
321    /// Concrete original-source counterexample; never a native Verus kill.
322    LiteralWitnessValidated(Box<crate::literal_witness::Validated>),
323    /// Ordered, resumable proof observations.
324    ProofEvents(crate::proof::Page),
325    /// Exact establishing evidence for a failure or proof.
326    Explanation(Box<crate::evidence::Explanation>),
327    /// Snapshot-scoped contract-to-code evidence grouped by requirement identity.
328    Assurance(Box<crate::assurance::View>),
329    /// Independently retained immutable evidence.
330    Baseline(Box<crate::evidence::Baseline>),
331    /// Immutable baseline names.
332    Baselines(Vec<String>),
333    /// Scoped, configuration-aware proof comparison.
334    Comparison(crate::evidence::Comparison),
335    /// One status.
336    Status(Status),
337    /// Retained jobs, oldest first.
338    List(Vec<Status>),
339    /// A result with its lifecycle and provenance.
340    Result(ResultDocument),
341    /// Diagnostics or target events.
342    Chunk(Chunk),
343    /// Stable error text, prefixed with a `SAIL` code.
344    Error(String),
345}
346
347#[derive(Serialize, Deserialize)]
348struct Envelope<T> {
349    version: u32,
350    body: T,
351}
352
353/// Writes a bounded versioned frame.
354///
355/// # Errors
356/// Returns invalid data for oversized frames or serialization errors, or an I/O error.
357pub fn write_frame<T: Serialize>(writer: &mut impl Write, body: &T) -> io::Result<()> {
358    let bytes = serde_json::to_vec(&Envelope {
359        version: VERSION,
360        body,
361    })
362    .map_err(io::Error::other)?;
363    if bytes.len() > MAX_FRAME {
364        return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
365    }
366    let size = u32::try_from(bytes.len()).map_err(io::Error::other)?;
367    writer.write_all(&size.to_be_bytes())?;
368    writer.write_all(&bytes)?;
369    writer.flush()
370}
371
372/// Reads a bounded frame, refusing unsupported versions before dispatch.
373///
374/// # Errors
375/// Returns invalid data for malformed, oversized, or unsupported frames, or an I/O error.
376pub fn read_frame<T: serde::de::DeserializeOwned>(reader: &mut impl Read) -> io::Result<T> {
377    let mut length = [0; 4];
378    reader.read_exact(&mut length)?;
379    let size = usize::try_from(u32::from_be_bytes(length)).map_err(io::Error::other)?;
380    if size > MAX_FRAME {
381        return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
382    }
383    let mut bytes = vec![0; size];
384    reader.read_exact(&mut bytes)?;
385    let envelope: Envelope<T> = serde_json::from_slice(&bytes).map_err(io::Error::other)?;
386    if envelope.version != VERSION {
387        return Err(io::Error::other("SAIL0802: incompatible job protocol"));
388    }
389    Ok(envelope.body)
390}
391
392/// Resolve the configured cache root without accessing the filesystem.
393///
394/// # Errors
395/// Returns `SAIL3001` when no cache or home environment setting is available.
396pub fn cache_directory() -> io::Result<PathBuf> {
397    let var = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty());
398    var("SAIL_CACHE_DIR")
399        .map(PathBuf::from)
400        .or_else(|| var("XDG_CACHE_HOME").map(|root| PathBuf::from(root).join("sail")))
401        .or_else(|| var("HOME").map(|root| PathBuf::from(root).join(".cache/sail")))
402        .ok_or_else(|| {
403            io::Error::other(
404                "error[SAIL3001]: none of SAIL_CACHE_DIR, XDG_CACHE_HOME or HOME is set",
405            )
406        })
407}
408
409/// The longest Unix socket path, in bytes, this platform accepts
410/// (`sun_path` less its terminating NUL: 108 bytes on Linux, 104 on macOS
411/// and the BSDs).
412pub const MAX_SOCKET_PATH: usize = if cfg!(target_os = "linux") { 107 } else { 103 };
413
414/// Default cache-service endpoint for the current protocol:
415/// `<cache>/daemon-v<N>-workspace-v2-proof-v1.sock`.
416///
417/// When that path, or the job endpoint beside it, would exceed
418/// [`MAX_SOCKET_PATH`] (a deep `HOME` or a long `SAIL_CACHE_DIR`), the
419/// endpoint moves to a private per-cache directory `/tmp/sail-<hash>/`,
420/// where `<hash>` names the cache. That directory is created mode 0700 and
421/// used only when it is a real directory that no other user can access and
422/// this user can write; otherwise the long path is returned unchanged, and
423/// starting the daemon reports that it is too long.
424#[must_use]
425pub fn default_cache_socket(cache: &Path) -> PathBuf {
426    let socket = cache.join(format!(
427        "daemon-v{}-workspace-v2-proof-v1.sock",
428        crate::protocol::PROTOCOL_VERSION
429    ));
430    if socket_fits(&socket) {
431        return socket;
432    }
433    short_socket(&socket).unwrap_or(socket)
434}
435
436/// Whether both the cache endpoint and its job endpoint fit in `sun_path`.
437#[must_use]
438pub fn socket_fits(cache_socket: &Path) -> bool {
439    let absolute = std::path::absolute(cache_socket).unwrap_or_else(|_| cache_socket.to_owned());
440    absolute.as_os_str().len() <= MAX_SOCKET_PATH
441        && socket_path(cache_socket).as_os_str().len() <= MAX_SOCKET_PATH
442}
443
444#[cfg(unix)]
445fn short_socket(socket: &Path) -> Option<PathBuf> {
446    use std::os::unix::fs::{DirBuilderExt as _, MetadataExt as _};
447    let name = socket.file_name()?;
448    let digest = sail_key::sha256(endpoint_path(socket).as_os_str().as_encoded_bytes());
449    let hash = digest
450        .iter()
451        .take(8)
452        .fold(String::new(), |mut value, byte| {
453            let _ = write!(value, "{byte:02x}");
454            value
455        });
456    let directory = Path::new("/tmp").join(format!("sail-{hash}"));
457    // An existing directory is accepted only when it is private.
458    let _ = std::fs::DirBuilder::new().mode(0o700).create(&directory);
459    let metadata = std::fs::symlink_metadata(&directory).ok()?;
460    if !metadata.is_dir() || metadata.mode() & 0o077 != 0 {
461        return None;
462    }
463    // Only its owner can create a file in a 0700 directory, so this proves
464    // the directory is this user's and no other user's daemon can be there.
465    let probe = directory.join(format!(".probe-{}", std::process::id()));
466    std::fs::File::create(&probe).ok()?;
467    std::fs::remove_file(&probe).ok()?;
468    let short = directory.join(name);
469    socket_fits(&short).then_some(short)
470}
471
472#[cfg(not(unix))]
473fn short_socket(_socket: &Path) -> Option<PathBuf> {
474    None
475}
476
477/// Resolve a cache endpoint using the caller's working directory.
478/// Relative cache roots and explicit overrides belong to that caller.
479#[must_use]
480pub fn cache_socket(cache: &Path, explicit: Option<&Path>, cwd: &Path) -> PathBuf {
481    // Anchor a relative cache first, so the length check sees the caller's path.
482    let socket = explicit.map_or_else(|| default_cache_socket(&cwd.join(cache)), Path::to_path_buf);
483    if socket.is_absolute() {
484        socket
485    } else {
486        cwd.join(socket)
487    }
488}
489
490/// Resolve the job endpoint with the same environment semantics as the CLI.
491///
492/// # Errors
493/// Returns the cache configuration error without starting a service.
494pub fn configured_socket(cwd: &Path) -> io::Result<PathBuf> {
495    let explicit = std::env::var_os("SAIL_DAEMON_SOCKET")
496        .filter(|value| !value.is_empty())
497        .map(PathBuf::from);
498    Ok(socket_path(&cache_socket(
499        &cache_directory()?,
500        explicit.as_deref(),
501        cwd,
502    )))
503}
504
505/// The job endpoint alongside a cache endpoint, without changing cache protocol.
506/// Relative paths and existing filesystem aliases identify the same endpoint.
507#[must_use]
508pub fn socket_path(cache_socket: &Path) -> PathBuf {
509    let cache_socket = endpoint_path(cache_socket);
510    let digest = sail_key::sha256(cache_socket.as_os_str().as_encoded_bytes());
511    let suffix = digest
512        .iter()
513        .take(4)
514        .fold(String::new(), |mut value, byte| {
515            let _ = write!(value, "{byte:02x}");
516            value
517        });
518    cache_socket.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
519}
520
521fn endpoint_path(path: &Path) -> PathBuf {
522    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
523    // Resolve the socket itself when it exists, including a symlink to a live
524    // endpoint. Before startup, resolve its nearest existing ancestor instead.
525    // This also covers aliases whose socket parent has not been created yet.
526    for ancestor in absolute.ancestors() {
527        if let Ok(resolved) = ancestor.canonicalize()
528            && let Ok(suffix) = absolute.strip_prefix(ancestor)
529        {
530            return if suffix.as_os_str().is_empty() {
531                resolved
532            } else {
533                resolved.join(suffix)
534            };
535        }
536    }
537    absolute
538}
539
540/// A timeout-bounded local client. Every call receives a complete fresh frame.
541#[cfg(unix)]
542#[derive(Debug, Clone)]
543pub struct Client {
544    socket: PathBuf,
545}
546#[cfg(unix)]
547impl Client {
548    /// Independently evaluate a complete scalar model through the source owner.
549    /// # Errors
550    /// Refuses older services, changed plans, models and invalid counterexamples.
551    pub fn validate_literal_witness(
552        &self,
553        plan: crate::literal_witness::Plan,
554        candidate_id: String,
555        result: &crate::runtime::QueryResult,
556    ) -> io::Result<crate::literal_witness::Validated> {
557        let prepared = plan
558            .prepared
559            .iter()
560            .find(|p| p.candidate.id == candidate_id)
561            .cloned()
562            .ok_or_else(|| io::Error::other("SAIL3145: missing literal witness candidate"))?;
563        match self.call(&Request::ValidateLiteralWitness {
564            plan: Box::new(plan),
565            candidate_id,
566            result: Box::new(result.clone()),
567        })? {
568            Response::LiteralWitnessValidated(value)
569                if value.prepared == prepared && value.model_result == *result =>
570            {
571                Ok(*value)
572            }
573            Response::Error(message) => Err(io::Error::other(message)),
574            _ => Err(io::Error::other(
575                "SAIL3145: incompatible concrete witness response",
576            )),
577        }
578    }
579    /// Prepare separate source-admitted scalar literal witness queries.
580    /// This starts no verification or mutation campaign and has no local fallback.
581    /// # Errors
582    /// Refuses unavailable or older services, changed input and invalid query links.
583    pub fn literal_witnesses(
584        &self,
585        source: &crate::contracts::Submission,
586        max_mutants: usize,
587    ) -> io::Result<crate::literal_witness::Plan> {
588        source.validate().map_err(io::Error::other)?;
589        match self.call(&Request::PrepareLiteralWitness {
590            source: source.clone(),
591            max_mutants,
592        })? {
593            Response::LiteralWitness(plan)
594                if plan.baseline == *source && plan.max_mutants == max_mutants =>
595            {
596                plan.validate().map_err(io::Error::other)?;
597                Ok(*plan)
598            }
599            Response::Error(message) => Err(io::Error::other(message)),
600            _ => Err(io::Error::other(
601                "SAIL3145: incompatible literal witness response",
602            )),
603        }
604    }
605    /// Submit a bounded owned mutation campaign through the existing job service.
606    /// # Errors
607    /// Refuses incompatible services, invalid baselines or invalid budgets.
608    pub fn submit_mutation(
609        &self,
610        submission: crate::mutation::Submission,
611    ) -> io::Result<crate::mutation::View> {
612        if !matches!(
613            self.call(&Request::Capabilities)?,
614            Response::Capabilities {
615                mutation_version: Some(crate::mutation::VERSION),
616                ..
617            }
618        ) {
619            return Err(io::Error::other(
620                "SAIL3144: running service has no compatible mutation API",
621            ));
622        }
623        let expected = submission.clone();
624        let result = self.mutation_call(&Request::SubmitMutation(submission))?;
625        if result.submission != expected {
626            return Err(io::Error::other(
627                "SAIL3144: mutation submission attribution differs",
628            ));
629        }
630        Ok(result)
631    }
632    /// Reauthenticate an exact durable campaign and all original result links.
633    /// # Errors
634    /// Missing, changed or incompatible evidence is an explicit error.
635    pub fn mutation(&self, id: &str) -> io::Result<crate::mutation::View> {
636        let result = self.mutation_call(&Request::Mutation { id: id.into() })?;
637        if result.id != id {
638            return Err(io::Error::other(
639                "SAIL3144: mutation campaign attribution differs",
640            ));
641        }
642        Ok(result)
643    }
644    /// Request cancellation of actual campaign jobs; inspect the returned lifecycle.
645    /// # Errors
646    /// Missing campaigns and service failures remain explicit.
647    pub fn cancel_mutation(&self, id: &str) -> io::Result<crate::mutation::View> {
648        let result = self.mutation_call(&Request::CancelMutation { id: id.into() })?;
649        if result.id != id {
650            return Err(io::Error::other(
651                "SAIL3144: mutation cancellation attribution differs",
652            ));
653        }
654        Ok(result)
655    }
656    fn mutation_call(&self, request: &Request) -> io::Result<crate::mutation::View> {
657        match self.call(request)? {
658            Response::Mutation(view) if view.version == crate::mutation::VERSION => {
659                crate::mutation::validate_view(&view).map_err(io::Error::other)?;
660                Ok(*view)
661            }
662            Response::Error(message) => Err(io::Error::other(message)),
663            _ => Err(io::Error::other("SAIL3144: incompatible mutation response")),
664        }
665    }
666    /// Read source-snapshot requirement assurance after version negotiation.
667    ///
668    /// # Errors
669    /// Refuses unsupported services, unknown jobs and invalid stored evidence.
670    pub fn requirement_assurance(&self, id: &str) -> io::Result<crate::assurance::View> {
671        if id.is_empty() || id.len() > 256 || id.contains('\0') {
672            return Err(io::Error::other("SAIL3143: invalid assurance job identity"));
673        }
674        if !matches!(
675            self.call(&Request::Capabilities)?,
676            Response::Capabilities {
677                assurance_version: Some(crate::assurance::VERSION),
678                ..
679            }
680        ) {
681            return Err(io::Error::other(
682                "SAIL3143: endpoint does not support requirement assurance",
683            ));
684        }
685        match self.call(&Request::Assurance { id: id.into() })? {
686            Response::Assurance(view)
687                if view.version == crate::assurance::VERSION && view.job_id == id =>
688            {
689                Ok(*view)
690            }
691            Response::Error(message) => Err(io::Error::other(message)),
692            _ => Err(io::Error::other(
693                "SAIL3143: invalid assurance response attribution",
694            )),
695        }
696    }
697
698    /// Submit neutral source only after explicit capability negotiation.
699    /// # Errors
700    /// Refuses older services, invalid source or transport failures without fallback.
701    pub fn submit_contracts(&self, submission: crate::contracts::Submission) -> io::Result<Status> {
702        submission.validate().map_err(io::Error::other)?;
703        let supported = match self.call(&Request::Capabilities)? {
704            Response::Capabilities {
705                neutral_contracts_version: Some(crate::contracts::VERSION),
706                neutral_contract_profiles,
707                ..
708            } => submission.profile == 1 || neutral_contract_profiles.contains(&submission.profile),
709            _ => false,
710        };
711        if !supported {
712            return Err(io::Error::other(
713                "SAIL3142: endpoint does not support the selected neutral source profile",
714            ));
715        }
716        match self.call(&Request::SubmitContracts(submission))? {
717            Response::Status(status) => Ok(status),
718            Response::Error(message) => Err(io::Error::other(message)),
719            _ => Err(io::Error::other(
720                "SAIL3142: unexpected neutral submission response",
721            )),
722        }
723    }
724
725    /// A client for `socket`; no connection or side effect until a call.
726    #[must_use]
727    pub fn new(socket: impl Into<PathBuf>) -> Self {
728        Self {
729            socket: socket.into(),
730        }
731    }
732    /// Sends one RPC with five-second I/O deadlines.
733    ///
734    /// # Errors
735    /// Returns connection, framing, timeout, or server errors.
736    pub fn call(&self, request: &Request) -> io::Result<Response> {
737        self.call_with(request, |_| {})
738    }
739    /// Like [`Client::call`], first handing `connected` a clone of the
740    /// connected stream. Another thread can shut that clone down to abandon
741    /// the call; `connected` is not called when the connection fails.
742    ///
743    /// # Errors
744    /// Returns connection, framing, timeout, or server errors.
745    pub fn call_with(
746        &self,
747        request: &Request,
748        connected: impl FnOnce(std::os::unix::net::UnixStream),
749    ) -> io::Result<Response> {
750        if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::Interactive | Mode::Repair(_)))
751            && !matches!(
752                self.call(&Request::Capabilities)?,
753                Response::Capabilities {
754                    proof_version: crate::proof::VERSION,
755                    repair: true,
756                    ..
757                }
758            )
759        {
760            return Err(io::Error::other(
761                "SAIL0903: endpoint does not support proof/repair contracts",
762            ));
763        }
764        if matches!(request, Request::Submit { submission } if submission.mode == Mode::Standalone)
765            && !matches!(
766                self.call(&Request::Capabilities)?,
767                Response::Capabilities {
768                    standalone: true,
769                    ..
770                }
771            )
772        {
773            return Err(io::Error::other(
774                "SAIL3150: endpoint does not support standalone file jobs; restart Sail's daemon",
775            ));
776        }
777        if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::StandaloneRepair { .. }))
778            && !matches!(
779                self.call(&Request::Capabilities)?,
780                Response::Capabilities {
781                    proof_version: crate::proof::VERSION,
782                    repair: true,
783                    standalone_repair: true,
784                    ..
785                }
786            )
787        {
788            return Err(io::Error::other(
789                "SAIL3150: endpoint does not support standalone repair; restart Sail's daemon",
790            ));
791        }
792        let mut stream =
793            crate::client::connect_stream(&self.socket, std::time::Duration::from_secs(5))?;
794        connected(stream.try_clone()?);
795        write_frame(&mut stream, request)?;
796        match read_frame(&mut stream)? {
797            Response::Error(message) => Err(io::Error::other(message)),
798            response => Ok(response),
799        }
800    }
801}
802
803#[cfg(test)]
804mod tests {
805    use super::*;
806    #[test]
807    fn baseline_read_has_exact_additive_wire_identity() {
808        let request = Request::GetBaseline {
809            name: "--json".into(),
810        };
811        assert_eq!(
812            serde_json::to_value(&request).unwrap_or_else(|error| unreachable!("{error}")),
813            serde_json::json!({"operation":"get_baseline","name":"--json"})
814        );
815        let mut bytes = Vec::new();
816        assert!(write_frame(&mut bytes, &request).is_ok());
817        assert!(matches!(read_frame::<Request>(&mut bytes.as_slice()),
818            Ok(Request::GetBaseline { name }) if name == "--json"));
819        assert!(
820            serde_json::from_value::<Request>(
821                serde_json::json!({"operation":"unknown_baseline","name":"--json"})
822            )
823            .is_err()
824        );
825    }
826
827    #[test]
828    fn endpoint_resolution_anchors_only_relative_settings_to_each_caller() {
829        let a = Path::new("/workspace/a");
830        let b = Path::new("/workspace/b");
831        assert_ne!(
832            cache_socket(Path::new("cache"), None, a),
833            cache_socket(Path::new("cache"), None, b)
834        );
835        assert_eq!(
836            cache_socket(Path::new("/shared/cache"), None, a),
837            cache_socket(Path::new("/shared/cache"), None, b)
838        );
839        assert_eq!(
840            cache_socket(
841                Path::new("ignored"),
842                Some(Path::new("sockets/service.sock")),
843                a
844            ),
845            a.join("sockets/service.sock")
846        );
847        assert_eq!(
848            cache_socket(
849                Path::new("ignored"),
850                Some(Path::new("/explicit/service.sock")),
851                b
852            ),
853            Path::new("/explicit/service.sock")
854        );
855        assert_eq!(
856            cache_socket(Path::new("cache"), None, a),
857            default_cache_socket(&a.join("cache"))
858        );
859    }
860
861    #[cfg(unix)]
862    #[test]
863    fn endpoint_aliases_share_the_same_namespace_before_and_after_startup() {
864        use std::os::unix::fs::symlink;
865        let root = std::env::temp_dir().join(format!("sail-job-socket-{}", std::process::id()));
866        let canonical = root.join("actual");
867        assert!(std::fs::create_dir_all(&canonical).is_ok());
868        let canonical = canonical
869            .canonicalize()
870            .unwrap_or_else(|e| unreachable!("{e}"));
871        let alias = root.join("alias");
872        assert!(symlink(&canonical, &alias).is_ok());
873        let endpoint = canonical.join("nested/cache.sock");
874        assert_eq!(
875            socket_path(&endpoint),
876            socket_path(&alias.join("nested/cache.sock"))
877        );
878        assert!(std::fs::create_dir_all(endpoint.parent().unwrap_or(&canonical)).is_ok());
879        let current = std::env::current_dir().unwrap_or_else(|e| unreachable!("{e}"));
880        let relative = PathBuf::from("../".repeat(current.components().count().saturating_sub(1)))
881            .join(endpoint.strip_prefix("/").unwrap_or(&endpoint));
882        assert_eq!(socket_path(&endpoint), socket_path(&relative));
883        let listener = std::os::unix::net::UnixListener::bind(&endpoint)
884            .unwrap_or_else(|e| unreachable!("{e}"));
885        let socket_alias = root.join("cache-alias.sock");
886        assert!(symlink(&endpoint, &socket_alias).is_ok());
887        assert_eq!(socket_path(&endpoint), socket_path(&socket_alias));
888        let hash = sail_key::sha256(endpoint.as_os_str().as_encoded_bytes());
889        let suffix = hash.iter().take(4).fold(String::new(), |mut s, b| {
890            let _ = write!(s, "{b:02x}");
891            s
892        });
893        assert_eq!(
894            socket_path(&endpoint),
895            endpoint.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
896        );
897        drop(listener);
898        let _ = std::fs::remove_dir_all(root);
899    }
900    /// A deep cache directory (as under a long `HOME` or `SAIL_CACHE_DIR`)
901    /// gets a short, private, per-cache endpoint; a short one is unchanged.
902    #[cfg(unix)]
903    #[test]
904    fn long_cache_paths_get_a_short_private_socket() {
905        use std::os::unix::fs::MetadataExt as _;
906        let short = Path::new("/tmp/c");
907        assert_eq!(
908            default_cache_socket(short),
909            short.join(format!(
910                "daemon-v{}-workspace-v2-proof-v1.sock",
911                crate::protocol::PROTOCOL_VERSION
912            ))
913        );
914        let deep = Path::new("/nonexistent").join("d".repeat(120));
915        let socket = default_cache_socket(&deep);
916        assert!(socket.starts_with("/tmp"), "{}", socket.display());
917        assert!(socket_fits(&socket));
918        assert_eq!(socket, default_cache_socket(&deep), "deterministic");
919        let directory = socket.parent().unwrap_or(Path::new("/"));
920        let mode = std::fs::metadata(directory).map(|m| m.mode() & 0o777);
921        assert!(matches!(mode, Ok(0o700)), "{mode:?}");
922        assert_ne!(
923            socket,
924            default_cache_socket(&Path::new("/nonexistent").join("e".repeat(120))),
925            "one directory per cache"
926        );
927        // Another user's (here: a non-private) directory is never used.
928        assert!(
929            std::fs::set_permissions(
930                directory,
931                std::os::unix::fs::PermissionsExt::from_mode(0o755)
932            )
933            .is_ok()
934        );
935        assert!(!default_cache_socket(&deep).starts_with("/tmp"));
936        let _ = std::fs::remove_dir_all(directory);
937    }
938
939    #[test]
940    fn versions_and_size_are_checked() {
941        let mut bytes = Vec::new();
942        assert!(write_frame(&mut bytes, &Request::List { project_dir: None }).is_ok());
943        assert!(matches!(
944            read_frame::<Request>(&mut bytes.as_slice()),
945            Ok(Request::List { .. })
946        ));
947        let huge = u32::MAX.to_be_bytes();
948        assert!(read_frame::<Request>(&mut huge.as_slice()).is_err());
949        let body = br#"{"version":2,"body":{"operation":"list","project_dir":null}}"#;
950        let mut wrong = u32::try_from(body.len())
951            .unwrap_or(0)
952            .to_be_bytes()
953            .to_vec();
954        wrong.extend_from_slice(body);
955        assert!(read_frame::<Request>(&mut wrong.as_slice()).is_err());
956    }
957}