sail-api 0.3.1

Embeddable library API, daemon wire protocol and structured output schema
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//! Versioned, bounded local project-job protocol, independent of the SMT cache.

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Project job protocol version.
pub const VERSION: u32 = 1;
/// Capability-set version a service advertises in [`Response::Capabilities`].
///
/// Absent (read as 1) on 0.2 services, whose set included the neutral source
/// jobs, mutation, literal witness and assurance operations. Version 2 is the
/// Sail 0.3 set without them (ADR 0109). The frame [`VERSION`] is unchanged, so
/// 0.2 clients and retained records keep working for ordinary jobs.
pub const CAPABILITIES_VERSION: u32 = 2;
/// Maximum request or response frame (32 MiB).
pub const MAX_FRAME: usize = 32 * 1024 * 1024;

/// A verification request. The environment belongs to its submitting client.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Submission {
    /// Explicit backend/repair mode; old endpoints are never used for these requests.
    #[serde(default)]
    pub mode: Mode,
    /// Absolute Cargo project directory.
    pub project_dir: PathBuf,
    /// Verification arguments, without the `verify` subcommand or output flags.
    pub args: Vec<String>,
    /// Force fresh verification even when a proof receipt exists.
    pub force: bool,
    /// UTF-8 process environment, captured by the submitting client.
    pub environment: BTreeMap<String, String>,
    /// Content revision observed by the submitting client.
    pub input_revision: Option<String>,
}

/// Verification execution mode, negotiated through the version-two job endpoint.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "selection", rename_all = "snake_case")]
pub enum Mode {
    /// Existing stock pinned Verus verification.
    #[default]
    Stock,
    /// Direct standalone Verus file; requires explicit endpoint support.
    Standalone,
    /// Exact standalone repair focus plus independent full-file validation.
    StandaloneRepair {
        /// Exact crate-qualified function reported by Verus.
        function: String,
    },
    /// Optional explicitly selected Sail-managed interactive engine.
    Interactive,
    /// One engine batch containing focus and independent full validation.
    Repair(crate::repair::Selection),
}

/// Durable lifecycle, independent of the proof outcome.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Lifecycle {
    /// Waiting for the single verification worker.
    Queued,
    /// The verification process is running.
    Running,
    /// A complete verification result is available (including failed proofs).
    Completed,
    /// Explicitly cancelled by a client.
    Cancelled,
    /// Cancelled because a newer input revision was requested.
    Superseded,
    /// Startup, persistence, process, or restart failure.
    InfrastructureError,
}
impl Lifecycle {
    /// Whether no more worker events are expected.
    #[must_use]
    pub const fn terminal(self) -> bool {
        !matches!(self, Self::Queued | Self::Running)
    }
}

/// How the result's input revision relates to current inputs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Currentness {
    /// The runner established a coherent current revision.
    Current,
    /// Inputs changed during or since verification.
    Historical,
    /// Input coverage or result attribution could not be established.
    Unknown,
}

/// Persistent status, safe to inspect while verification runs.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Status {
    /// Protocol/store format version.
    pub version: u32,
    /// Durable job id.
    pub id: String,
    /// Absolute project directory.
    pub project_dir: PathBuf,
    /// Requested arguments; never broadened silently.
    pub args: Vec<String>,
    /// Lifecycle, distinct from proof verdict.
    pub state: Lifecycle,
    /// Submission time, milliseconds since the Unix epoch.
    pub submitted_at_ms: u64,
    /// Start time, if started.
    pub started_at_ms: Option<u64>,
    /// Completion time, if terminal.
    pub finished_at_ms: Option<u64>,
    /// Process exit status, if available.
    pub exit_code: Option<i32>,
    /// Input revision before the run.
    pub input_revision: Option<String>,
    /// Result currentness.
    pub currentness: Currentness,
    /// Stable infrastructure error code and explanatory text, when present.
    pub error: Option<String>,
}

/// Stable refusal for a record written by the neutral source jobs that Sail
/// 0.2 offered and 0.3.0 removed. Such a record is never read as an ordinary
/// job result.
pub const RETIRED_NEUTRAL_RECORD: &str = "SAIL3161: this record was written by a neutral source job, which Sail 0.3.0 removed; it cannot be read as verification evidence";

/// The wire form of [`ResultDocument`]. It also recognises the retired
/// `contracts` member, so a neutral record is refused instead of having that
/// member silently ignored.
#[derive(Deserialize)]
struct ResultDocumentWire {
    #[serde(default)]
    contracts: Option<serde::de::IgnoredAny>,
    #[serde(default)]
    repair: Option<Box<crate::repair::ResultDocument>>,
    job: Status,
    result: Option<Value>,
}
impl TryFrom<ResultDocumentWire> for ResultDocument {
    type Error = &'static str;
    fn try_from(wire: ResultDocumentWire) -> Result<Self, Self::Error> {
        if wire.contracts.is_some() {
            return Err(RETIRED_NEUTRAL_RECORD);
        }
        Ok(Self {
            repair: wire.repair,
            job: wire.job,
            result: wire.result,
        })
    }
}

/// A job result preserving the managed runner's versioned document.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "ResultDocumentWire")]
pub struct ResultDocument {
    /// Independent focus/full repair evidence, when this was an engine batch.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repair: Option<Box<crate::repair::ResultDocument>>,
    /// Job status and provenance.
    pub job: Status,
    /// Managed project result, only after a complete worker output.
    pub result: Option<Value>,
}

/// A bounded slice of a job's diagnostics or target events.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Chunk {
    /// Byte offset of the next slice.
    pub next: u64,
    /// UTF-8 text (lossy only for diagnostics from non-UTF-8 subprocesses).
    pub text: String,
    /// Whether this job has reached a terminal state.
    pub complete: bool,
}

/// One local RPC.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "operation", rename_all = "snake_case")]
pub enum Request {
    /// Negotiate and inspect optional daemon-owned preparation.
    PreparationStatus,
    /// Enqueue optional work; never changes the original verification result.
    Prepare(crate::preparation::Submission),
    /// Hold foreground priority until this connection closes.
    Foreground {
        /// Preparation protocol version.
        version: u32,
        /// Originating working directory.
        project_dir: PathBuf,
        /// Arguments used to resolve the workspace scheduling key.
        args: Vec<String>,
    },
    /// Fail-closed negotiation before any non-stock submission.
    Capabilities,
    /// Legacy attributed submission; services since 0.3 refuse this operation.
    SubmitAttributed {
        /// Requested stock or standalone verification.
        submission: Submission,
        /// Canonical, non-empty submitter attributions.
        requirements: Vec<crate::attribution::RequirementAttribution>,
    },
    /// Legacy assurance read; services since 0.3 refuse this operation.
    AttributedAssurance {
        /// Exact durable job identity.
        id: String,
    },
    /// Read bounded version-one proof observations using a resumable cursor.
    ProofEvents {
        /// Durable job identity.
        id: String,
        /// Last consumed event; stream identity must match on reconnect.
        cursor: crate::proof::Cursor,
        /// Maximum event count, clamped by the service.
        limit: usize,
    },
    /// Explain an exact reported target/function, preserving raw evidence.
    Explain {
        /// Durable completed job identity.
        id: String,
        /// Complete Cargo target identity.
        target: crate::proof::Target,
        /// Exact crate-qualified function.
        function: String,
        /// Optional exact obligation id.
        obligation: Option<String>,
    },
    /// Save independent immutable proof evidence outside job retention.
    SaveBaseline {
        /// Completed evidence source.
        id: String,
        /// Immutable owner-selected name.
        name: String,
    },
    /// List retained immutable named baselines.
    Baselines,
    /// Read immutable evidence for its recorded revision, never current inputs.
    GetBaseline {
        /// Exact retained baseline name.
        name: String,
    },
    /// Compare explicit completed evidence with an earlier job or baseline.
    Compare {
        /// Earlier named baseline or durable job.
        before: crate::evidence::Reference,
        /// Later completed job identity.
        after: String,
    },
    /// Submit or coalesce an identical in-flight request.
    Submit {
        /// Requested verification.
        submission: Submission,
    },
    /// List retained jobs, optionally for one canonical project directory.
    List {
        /// Project filter.
        project_dir: Option<PathBuf>,
    },
    /// Inspect one job without waiting for verification.
    Status {
        /// Job id.
        id: String,
    },
    /// Read one completed or in-progress result.
    Result {
        /// Job id.
        id: String,
    },
    /// Cancel one job and its entire process group.
    Cancel {
        /// Job id.
        id: String,
        /// New edits supersede this run.
        superseded: bool,
    },
    /// Read bounded stderr diagnostics from a byte offset.
    Logs {
        /// Job id.
        id: String,
        /// Byte offset.
        offset: u64,
    },
    /// Read bounded JSON-lines target events from a byte offset.
    Events {
        /// Job id.
        id: String,
        /// Byte offset.
        offset: u64,
    },
}

/// A response or a stable user-facing error.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "response", content = "value", rename_all = "snake_case")]
pub enum Response {
    /// Optional preparation negotiation, status, or handoff acknowledgement.
    Preparation(crate::preparation::Status),
    /// Supported product contracts; does not claim an optional engine is installed.
    Capabilities {
        /// [`CAPABILITIES_VERSION`]; absent from 0.2 services, which decode as 1.
        #[serde(default = "legacy_capabilities")]
        capabilities_version: u32,
        /// Independent proof stream version.
        proof_version: u32,
        /// Ordinary-job requirement attribution view version; absent on older services.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        attribution_version: Option<u32>,
        /// Non-stock submission modes are understood and never ignored.
        /// Absent from services without the engine, which decode as false.
        #[serde(default)]
        repair: bool,
        /// Direct-file jobs are understood; false on older endpoints.
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        standalone: bool,
        /// Standalone repair is explicitly understood; absent on older endpoints.
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        standalone_repair: bool,
    },
    /// Ordered, resumable proof observations.
    ProofEvents(crate::proof::Page),
    /// Exact establishing evidence for a failure or proof.
    Explanation(Box<crate::evidence::Explanation>),
    /// Submitter-attributed ordinary Verus evidence.
    AttributedAssurance(Box<crate::attribution::View>),
    /// Independently retained immutable evidence.
    Baseline(Box<crate::evidence::Baseline>),
    /// Immutable baseline names.
    Baselines(Vec<String>),
    /// Scoped, configuration-aware proof comparison.
    Comparison(crate::evidence::Comparison),
    /// One status.
    Status(Status),
    /// Retained jobs, oldest first.
    List(Vec<Status>),
    /// A result with its lifecycle and provenance.
    Result(ResultDocument),
    /// Diagnostics or target events.
    Chunk(Chunk),
    /// Stable error text, prefixed with a `SAIL` code.
    Error(String),
}

#[derive(Serialize, Deserialize)]
struct Envelope<T> {
    version: u32,
    body: T,
}

const fn legacy_capabilities() -> u32 {
    1
}

/// Writes a bounded versioned frame.
///
/// # Errors
/// Returns invalid data for oversized frames or serialization errors, or an I/O error.
pub fn write_frame<T: Serialize>(writer: &mut impl Write, body: &T) -> io::Result<()> {
    let bytes = serde_json::to_vec(&Envelope {
        version: VERSION,
        body,
    })
    .map_err(io::Error::other)?;
    if bytes.len() > MAX_FRAME {
        return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
    }
    let size = u32::try_from(bytes.len()).map_err(io::Error::other)?;
    writer.write_all(&size.to_be_bytes())?;
    writer.write_all(&bytes)?;
    writer.flush()
}

/// Reads a bounded frame, refusing unsupported versions before dispatch.
///
/// # Errors
/// Returns invalid data for malformed, oversized, or unsupported frames, or an I/O error.
pub fn read_frame<T: serde::de::DeserializeOwned>(reader: &mut impl Read) -> io::Result<T> {
    let mut length = [0; 4];
    reader.read_exact(&mut length)?;
    let size = usize::try_from(u32::from_be_bytes(length)).map_err(io::Error::other)?;
    if size > MAX_FRAME {
        return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
    }
    let mut bytes = vec![0; size];
    reader.read_exact(&mut bytes)?;
    let envelope: Envelope<T> = serde_json::from_slice(&bytes).map_err(io::Error::other)?;
    if envelope.version != VERSION {
        return Err(io::Error::other("SAIL0802: incompatible job protocol"));
    }
    Ok(envelope.body)
}

/// Resolve the configured cache root without accessing the filesystem.
///
/// # Errors
/// Returns `SAIL3001` when no cache or home environment setting is available.
pub fn cache_directory() -> io::Result<PathBuf> {
    let var = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty());
    var("SAIL_CACHE_DIR")
        .map(PathBuf::from)
        .or_else(|| var("XDG_CACHE_HOME").map(|root| PathBuf::from(root).join("sail")))
        .or_else(|| var("HOME").map(|root| PathBuf::from(root).join(".cache/sail")))
        .ok_or_else(|| {
            io::Error::other(
                "error[SAIL3001]: none of SAIL_CACHE_DIR, XDG_CACHE_HOME or HOME is set",
            )
        })
}

/// The longest Unix socket path, in bytes, this platform accepts
/// (`sun_path` less its terminating NUL: 108 bytes on Linux, 104 on macOS
/// and the BSDs).
pub const MAX_SOCKET_PATH: usize = if cfg!(target_os = "linux") { 107 } else { 103 };

/// Default cache-service endpoint for the current protocol:
/// `<cache>/daemon-v<N>-workspace-v2-proof-v1.sock`.
///
/// When that path, or the job endpoint beside it, would exceed
/// [`MAX_SOCKET_PATH`] (a deep `HOME` or a long `SAIL_CACHE_DIR`), the
/// endpoint moves to a private per-cache directory `/tmp/sail-<hash>/`,
/// where `<hash>` names the cache. That directory is created mode 0700 and
/// used only when it is a real directory that no other user can access and
/// this user can write; otherwise the long path is returned unchanged, and
/// starting the daemon reports that it is too long.
#[must_use]
pub fn default_cache_socket(cache: &Path) -> PathBuf {
    let socket = cache.join(format!(
        "daemon-v{}-workspace-v2-proof-v1.sock",
        crate::protocol::PROTOCOL_VERSION
    ));
    if socket_fits(&socket) {
        return socket;
    }
    short_socket(&socket).unwrap_or(socket)
}

/// Whether both the cache endpoint and its job endpoint fit in `sun_path`.
#[must_use]
pub fn socket_fits(cache_socket: &Path) -> bool {
    let absolute = std::path::absolute(cache_socket).unwrap_or_else(|_| cache_socket.to_owned());
    absolute.as_os_str().len() <= MAX_SOCKET_PATH
        && socket_path(cache_socket).as_os_str().len() <= MAX_SOCKET_PATH
}

#[cfg(unix)]
fn short_socket(socket: &Path) -> Option<PathBuf> {
    use std::os::unix::fs::{DirBuilderExt as _, MetadataExt as _};
    let name = socket.file_name()?;
    let digest = sail_key::sha256(endpoint_path(socket).as_os_str().as_encoded_bytes());
    let hash = digest
        .iter()
        .take(8)
        .fold(String::new(), |mut value, byte| {
            let _ = write!(value, "{byte:02x}");
            value
        });
    let directory = Path::new("/tmp").join(format!("sail-{hash}"));
    // An existing directory is accepted only when it is private.
    let _ = std::fs::DirBuilder::new().mode(0o700).create(&directory);
    let metadata = std::fs::symlink_metadata(&directory).ok()?;
    if !metadata.is_dir() || metadata.mode() & 0o077 != 0 {
        return None;
    }
    // Only its owner can create a file in a 0700 directory, so this proves
    // the directory is this user's and no other user's daemon can be there.
    let probe = directory.join(format!(".probe-{}", std::process::id()));
    std::fs::File::create(&probe).ok()?;
    std::fs::remove_file(&probe).ok()?;
    let short = directory.join(name);
    socket_fits(&short).then_some(short)
}

#[cfg(not(unix))]
fn short_socket(_socket: &Path) -> Option<PathBuf> {
    None
}

/// Resolve a cache endpoint using the caller's working directory.
/// Relative cache roots and explicit overrides belong to that caller.
#[must_use]
pub fn cache_socket(cache: &Path, explicit: Option<&Path>, cwd: &Path) -> PathBuf {
    // Anchor a relative cache first, so the length check sees the caller's path.
    let socket = explicit.map_or_else(|| default_cache_socket(&cwd.join(cache)), Path::to_path_buf);
    if socket.is_absolute() {
        socket
    } else {
        cwd.join(socket)
    }
}

/// Resolve the job endpoint with the same environment semantics as the CLI.
///
/// # Errors
/// Returns the cache configuration error without starting a service.
pub fn configured_socket(cwd: &Path) -> io::Result<PathBuf> {
    let explicit = std::env::var_os("SAIL_DAEMON_SOCKET")
        .filter(|value| !value.is_empty())
        .map(PathBuf::from);
    Ok(socket_path(&cache_socket(
        &cache_directory()?,
        explicit.as_deref(),
        cwd,
    )))
}

/// The job endpoint alongside a cache endpoint, without changing cache protocol.
/// Relative paths and existing filesystem aliases identify the same endpoint.
#[must_use]
pub fn socket_path(cache_socket: &Path) -> PathBuf {
    let cache_socket = endpoint_path(cache_socket);
    let digest = sail_key::sha256(cache_socket.as_os_str().as_encoded_bytes());
    let suffix = digest
        .iter()
        .take(4)
        .fold(String::new(), |mut value, byte| {
            let _ = write!(value, "{byte:02x}");
            value
        });
    cache_socket.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
}

fn endpoint_path(path: &Path) -> PathBuf {
    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
    // Resolve the socket itself when it exists, including a symlink to a live
    // endpoint. Before startup, resolve its nearest existing ancestor instead.
    // This also covers aliases whose socket parent has not been created yet.
    for ancestor in absolute.ancestors() {
        if let Ok(resolved) = ancestor.canonicalize()
            && let Ok(suffix) = absolute.strip_prefix(ancestor)
        {
            return if suffix.as_os_str().is_empty() {
                resolved
            } else {
                resolved.join(suffix)
            };
        }
    }
    absolute
}

/// A timeout-bounded local client. Every call receives a complete fresh frame.
#[cfg(unix)]
#[derive(Debug, Clone)]
pub struct Client {
    socket: PathBuf,
}
#[cfg(unix)]
impl Client {
    /// Legacy attributed submission, retained for wire compatibility.
    /// Services since 0.3 do not advertise this capability and refuse the call.
    ///
    /// # Errors
    /// Refuses older services, unsupported modes and invalid attributions
    /// without falling back to an unattributed submission.
    pub fn submit_attributed(
        &self,
        submission: Submission,
        requirements: Vec<crate::attribution::RequirementAttribution>,
    ) -> io::Result<Status> {
        let requirements = crate::attribution::canonical(requirements).map_err(io::Error::other)?;
        if !crate::attribution::mode_supported(&submission.mode) {
            return Err(io::Error::other(
                "SAIL3160: requirement attribution applies only to stock and standalone jobs",
            ));
        }
        self.require_attribution()?;
        match self.call(&Request::SubmitAttributed {
            submission,
            requirements,
        })? {
            Response::Status(status) => Ok(status),
            Response::Error(message) => Err(io::Error::other(message)),
            _ => Err(io::Error::other(
                "SAIL3160: unexpected attributed submission response",
            )),
        }
    }

    /// Legacy assurance read, retained for wire compatibility.
    /// Services since 0.3 do not advertise this capability and refuse the call.
    ///
    /// # Errors
    /// Refuses unsupported services, unknown or unattributed jobs and invalid evidence.
    pub fn attributed_assurance(&self, id: &str) -> io::Result<crate::attribution::View> {
        if id.is_empty() || id.len() > 256 || id.contains('\0') {
            return Err(io::Error::other("SAIL3160: invalid assurance job identity"));
        }
        self.require_attribution()?;
        match self.call(&Request::AttributedAssurance { id: id.into() })? {
            Response::AttributedAssurance(view)
                if view.version == crate::attribution::VERSION && view.job_id == id =>
            {
                Ok(*view)
            }
            Response::Error(message) => Err(io::Error::other(message)),
            _ => Err(io::Error::other(
                "SAIL3160: invalid attributed assurance response",
            )),
        }
    }

    fn require_attribution(&self) -> io::Result<()> {
        if matches!(
            self.call(&Request::Capabilities)?,
            Response::Capabilities {
                attribution_version: Some(crate::attribution::VERSION),
                ..
            }
        ) {
            Ok(())
        } else {
            Err(io::Error::other(
                "SAIL3160: endpoint does not support requirement attribution; restart Sail's daemon",
            ))
        }
    }

    /// A client for `socket`; no connection or side effect until a call.
    #[must_use]
    pub fn new(socket: impl Into<PathBuf>) -> Self {
        Self {
            socket: socket.into(),
        }
    }
    /// Sends one RPC with five-second I/O deadlines.
    ///
    /// # Errors
    /// Returns connection, framing, timeout, or server errors.
    pub fn call(&self, request: &Request) -> io::Result<Response> {
        self.call_with(request, |_| {})
    }
    /// Like [`Client::call`], first handing `connected` a clone of the
    /// connected stream. Another thread can shut that clone down to abandon
    /// the call; `connected` is not called when the connection fails.
    ///
    /// # Errors
    /// Returns connection, framing, timeout, or server errors.
    pub fn call_with(
        &self,
        request: &Request,
        connected: impl FnOnce(std::os::unix::net::UnixStream),
    ) -> io::Result<Response> {
        if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::Interactive | Mode::Repair(_)))
            && !matches!(
                self.call(&Request::Capabilities)?,
                Response::Capabilities {
                    proof_version: crate::proof::VERSION,
                    repair: true,
                    ..
                }
            )
        {
            return Err(io::Error::other(
                "SAIL0903: endpoint does not support proof/repair contracts",
            ));
        }
        if matches!(request, Request::Submit { submission } if submission.mode == Mode::Standalone)
            && !matches!(
                self.call(&Request::Capabilities)?,
                Response::Capabilities {
                    standalone: true,
                    ..
                }
            )
        {
            return Err(io::Error::other(
                "SAIL3150: endpoint does not support standalone file jobs; restart Sail's daemon",
            ));
        }
        if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::StandaloneRepair { .. }))
            && !matches!(
                self.call(&Request::Capabilities)?,
                Response::Capabilities {
                    proof_version: crate::proof::VERSION,
                    repair: true,
                    standalone_repair: true,
                    ..
                }
            )
        {
            return Err(io::Error::other(
                "SAIL3150: endpoint does not support standalone repair; restart Sail's daemon",
            ));
        }
        let mut stream =
            crate::client::connect_stream(&self.socket, std::time::Duration::from_secs(5))?;
        connected(stream.try_clone()?);
        write_frame(&mut stream, request)?;
        match read_frame(&mut stream)? {
            Response::Error(message) => Err(io::Error::other(message)),
            response => Ok(response),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn baseline_read_has_exact_additive_wire_identity() {
        let request = Request::GetBaseline {
            name: "--json".into(),
        };
        assert_eq!(
            serde_json::to_value(&request).unwrap_or_else(|error| unreachable!("{error}")),
            serde_json::json!({"operation":"get_baseline","name":"--json"})
        );
        let mut bytes = Vec::new();
        assert!(write_frame(&mut bytes, &request).is_ok());
        assert!(matches!(read_frame::<Request>(&mut bytes.as_slice()),
            Ok(Request::GetBaseline { name }) if name == "--json"));
        assert!(
            serde_json::from_value::<Request>(
                serde_json::json!({"operation":"unknown_baseline","name":"--json"})
            )
            .is_err()
        );
    }

    #[test]
    fn endpoint_resolution_anchors_only_relative_settings_to_each_caller() {
        let a = Path::new("/workspace/a");
        let b = Path::new("/workspace/b");
        assert_ne!(
            cache_socket(Path::new("cache"), None, a),
            cache_socket(Path::new("cache"), None, b)
        );
        assert_eq!(
            cache_socket(Path::new("/shared/cache"), None, a),
            cache_socket(Path::new("/shared/cache"), None, b)
        );
        assert_eq!(
            cache_socket(
                Path::new("ignored"),
                Some(Path::new("sockets/service.sock")),
                a
            ),
            a.join("sockets/service.sock")
        );
        assert_eq!(
            cache_socket(
                Path::new("ignored"),
                Some(Path::new("/explicit/service.sock")),
                b
            ),
            Path::new("/explicit/service.sock")
        );
        assert_eq!(
            cache_socket(Path::new("cache"), None, a),
            default_cache_socket(&a.join("cache"))
        );
    }

    #[cfg(unix)]
    #[test]
    fn endpoint_aliases_share_the_same_namespace_before_and_after_startup() {
        use std::os::unix::fs::symlink;
        let root = std::env::temp_dir().join(format!("sail-job-socket-{}", std::process::id()));
        let canonical = root.join("actual");
        assert!(std::fs::create_dir_all(&canonical).is_ok());
        let canonical = canonical
            .canonicalize()
            .unwrap_or_else(|e| unreachable!("{e}"));
        let alias = root.join("alias");
        assert!(symlink(&canonical, &alias).is_ok());
        let endpoint = canonical.join("nested/cache.sock");
        assert_eq!(
            socket_path(&endpoint),
            socket_path(&alias.join("nested/cache.sock"))
        );
        assert!(std::fs::create_dir_all(endpoint.parent().unwrap_or(&canonical)).is_ok());
        let current = std::env::current_dir().unwrap_or_else(|e| unreachable!("{e}"));
        let relative = PathBuf::from("../".repeat(current.components().count().saturating_sub(1)))
            .join(endpoint.strip_prefix("/").unwrap_or(&endpoint));
        assert_eq!(socket_path(&endpoint), socket_path(&relative));
        let listener = std::os::unix::net::UnixListener::bind(&endpoint)
            .unwrap_or_else(|e| unreachable!("{e}"));
        let socket_alias = root.join("cache-alias.sock");
        assert!(symlink(&endpoint, &socket_alias).is_ok());
        assert_eq!(socket_path(&endpoint), socket_path(&socket_alias));
        let hash = sail_key::sha256(endpoint.as_os_str().as_encoded_bytes());
        let suffix = hash.iter().take(4).fold(String::new(), |mut s, b| {
            let _ = write!(s, "{b:02x}");
            s
        });
        assert_eq!(
            socket_path(&endpoint),
            endpoint.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
        );
        drop(listener);
        let _ = std::fs::remove_dir_all(root);
    }
    /// A deep cache directory (as under a long `HOME` or `SAIL_CACHE_DIR`)
    /// gets a short, private, per-cache endpoint; a short one is unchanged.
    #[cfg(unix)]
    #[test]
    fn long_cache_paths_get_a_short_private_socket() {
        use std::os::unix::fs::MetadataExt as _;
        let short = Path::new("/tmp/c");
        assert_eq!(
            default_cache_socket(short),
            short.join(format!(
                "daemon-v{}-workspace-v2-proof-v1.sock",
                crate::protocol::PROTOCOL_VERSION
            ))
        );
        let deep = Path::new("/nonexistent").join("d".repeat(120));
        let socket = default_cache_socket(&deep);
        assert!(socket.starts_with("/tmp"), "{}", socket.display());
        assert!(socket_fits(&socket));
        assert_eq!(socket, default_cache_socket(&deep), "deterministic");
        let directory = socket.parent().unwrap_or(Path::new("/"));
        let mode = std::fs::metadata(directory).map(|m| m.mode() & 0o777);
        assert!(matches!(mode, Ok(0o700)), "{mode:?}");
        assert_ne!(
            socket,
            default_cache_socket(&Path::new("/nonexistent").join("e".repeat(120))),
            "one directory per cache"
        );
        // Another user's (here: a non-private) directory is never used.
        assert!(
            std::fs::set_permissions(
                directory,
                std::os::unix::fs::PermissionsExt::from_mode(0o755)
            )
            .is_ok()
        );
        assert!(!default_cache_socket(&deep).starts_with("/tmp"));
        let _ = std::fs::remove_dir_all(directory);
    }

    #[test]
    fn versions_and_size_are_checked() {
        let mut bytes = Vec::new();
        assert!(write_frame(&mut bytes, &Request::List { project_dir: None }).is_ok());
        assert!(matches!(
            read_frame::<Request>(&mut bytes.as_slice()),
            Ok(Request::List { .. })
        ));
        let huge = u32::MAX.to_be_bytes();
        assert!(read_frame::<Request>(&mut huge.as_slice()).is_err());
        let body = br#"{"version":2,"body":{"operation":"list","project_dir":null}}"#;
        let mut wrong = u32::try_from(body.len())
            .unwrap_or(0)
            .to_be_bytes()
            .to_vec();
        wrong.extend_from_slice(body);
        assert!(read_frame::<Request>(&mut wrong.as_slice()).is_err());
    }
}