Skip to main content

surjection_core/
error.rs

1//! Typed core errors. The CLI and the GUI localize from [`ErrorCode`]; the
2//! message is English diagnostic detail, never state.
3
4use std::fmt;
5use std::path::{Path, PathBuf};
6
7use crate::access::ReadOnlyKind;
8
9/// Stable error code, serialized as `snake_case` (the same string as
10/// [`ErrorCode::as_str`]).
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
12#[cfg_attr(feature = "specta", derive(specta::Type))]
13#[serde(rename_all = "snake_case")]
14#[non_exhaustive]
15pub enum ErrorCode {
16    /// A path argument, override or path field is unusable (for example
17    /// relative, or personal where a placeholder is required).
18    InvalidPath,
19    /// The user profile directory could not be determined.
20    ProfileNotFound,
21    /// A file could not be read or written.
22    IoError,
23    /// A file is not valid UTF-8, or not valid in its format (TOML, JSON, JSONC).
24    ParseError,
25    /// A store file declares a `schema` version this build does not read.
26    UnsupportedSchema,
27    /// A required field is absent.
28    MissingField,
29    /// A field has the wrong type or a value outside its allowed set.
30    InvalidValue,
31    /// An identifier breaks the rules of SPEC 5.1.
32    InvalidId,
33    /// An id disagrees with the file or directory name that holds it.
34    IdMismatch,
35    /// A field is present where the rest of the definition forbids it
36    /// (for example `url` on a stdio server).
37    FieldNotAllowed,
38    /// A `client.<id>` key is not in that client's passthrough allowlist.
39    PassthroughNotAllowed,
40    /// A template or secret reference does not parse (SPEC 11.2).
41    InvalidRef,
42    /// A client id is not in the adapter table. Warning: kept as written.
43    UnknownClient,
44    /// An OS name is not `windows`, `linux` or `macos`. Warning: kept as written.
45    UnknownOs,
46    /// Another process holds `state/surjection.lock` and the wait timed out.
47    Locked,
48    /// The store repository could not be read or written.
49    GitError,
50    /// An entity with this id already exists.
51    AlreadyExists,
52    /// No entity with this id exists.
53    NotFound,
54    /// A native client file parses, but a value on the path being read or
55    /// edited has another kind (for example `mcpServers` is an array).
56    UnexpectedShape,
57    /// A client has no target on this operating system (Claude Desktop on
58    /// Linux).
59    NotSupportedOnOs,
60    /// A client has no target in the requested scope (Claude Desktop at
61    /// project scope).
62    ScopeNotSupported,
63    /// A client cannot run a server over this transport (HTTP on Claude
64    /// Desktop). The target is blocked; nothing is dropped silently.
65    UnsupportedTransport,
66    /// A client has no native field for a set server field (`cwd` on Claude
67    /// Desktop). The target is blocked; nothing is dropped silently.
68    UnsupportedField,
69    /// Warning: an MSIX install keeps its own copy of a client file, so both
70    /// copies are written (Claude Desktop on Windows).
71    MsixDualWrite,
72    /// Warning: a client treats another entry name as the same server (Pi
73    /// counts names that differ only in `-` and `_` as one), so writing the
74    /// entry would clash with it.
75    Collision,
76    /// Clients with different units for the same timeout key read one file
77    /// (omp `timeout` in milliseconds and Pi `timeout` in seconds, both in
78    /// `$PI_CODING_AGENT_DIR/mcp.json`; gate V2 OMP-10), and the entry sets
79    /// that key. The entry is blocked; no unit is guessed.
80    TimeoutUnitConflict,
81    /// Warning: an installed extension takes over the client's MCP support
82    /// (Pi with `pi-mcp-adapter`), so the client's own MCP config may not be
83    /// what loads.
84    ClientMcpReplacedByExtension,
85    /// A client file kept changing between planning and writing (SPEC 8.4
86    /// step 1, after three re-plans). The file is left as it is.
87    FileChangedDuringApply,
88    /// The entry a resolution was chosen for changed (in the file or in the
89    /// store) since the resolver showed it; nothing was done (SPEC 13.4).
90    EntryChanged,
91    /// The edited file did not read back as planned: an owned entry differs
92    /// from the desired one, or something outside the owned entries changed
93    /// (SPEC 8.4 step 3). The file is left as it is.
94    SelfCheckFailed,
95    /// Another process kept a client file open for longer than the retry
96    /// window (Windows sharing violation, SPEC 8.4 step 4).
97    FileLocked,
98    /// The delivery mode a server asks for (`delivery.mode`) cannot bring a
99    /// reference to this client and field, or a value cannot be written
100    /// without changing its meaning (a literal `${` the client would
101    /// expand). The entry is blocked; nothing is written in plain text.
102    DeliveryUnavailable,
103    /// Warning: a known client has no adapter in this build yet, so nothing
104    /// is written for it.
105    NoAdapter,
106    /// A native entry holds literal values that may be secrets; importing it
107    /// needs secret extraction (SPEC 11.7) instead of copying the values.
108    NeedsSecretExtraction,
109    /// The operation changes state that later operations changed too and
110    /// needs an explicit confirmation (rolling back an older apply, SPEC 8.7).
111    ConfirmationRequired,
112    /// Warning: an apply run did not finish; its journal lists what each
113    /// file got (SPEC 8.4 step 6). Nothing is replayed.
114    UnfinishedApply,
115    /// A staged store file or commit message holds what looks like a
116    /// secret, or a value resolved during this process (SPEC 11.8). Nothing
117    /// is written or committed.
118    LeakDetected,
119    /// A secret reference has no value: env var unset, keyring entry or
120    /// 1Password item absent, alias not defined (SPEC 11.3 `missing`).
121    MissingSecret,
122    /// 1Password (or the keyring) needs sign-in or approval (SPEC 11.3
123    /// `locked`).
124    SecretLocked,
125    /// A secret provider is not on this machine ("1Password CLI not
126    /// found", no Secret Service; SPEC 11.3 `provider_unavailable`).
127    ProviderUnavailable,
128    /// A secret provider is older than a feature needs (SPEC 11.11).
129    ProviderTooOld,
130    /// A secret provider failed for another reason, or the value cannot be
131    /// read from here (SPEC 11.3 `error`, `unverifiable`).
132    SecretError,
133    /// `launch` delivery needs the absolute path of the `surject` binary
134    /// and it could not be resolved (SPEC 11.4, 11.5). The entry is
135    /// blocked; nothing falls back to `inline`.
136    LauncherNotFound,
137    /// A provider reference has no delivery mode that keeps its value out
138    /// of the client's config file for this client and field (SPEC 11.4
139    /// rule 2). Fixes: export to the environment, or allow `inline` for
140    /// the server.
141    NoSecretFreeDelivery,
142    /// `inline` delivery would write a secret value into a shared file
143    /// (SPEC 11.4 rule 3). Fixes: `env` or `launch`, or the project-local
144    /// layer.
145    SecretInSharedFile,
146    /// Warning: a `${env:NAME}` reference is written as the value of
147    /// Surjection's own environment, because the client cannot expand it
148    /// there and `launch` cannot carry it (SPEC 11.4 rule 1).
149    InlineEnvFallback,
150    /// A remote cannot be reached (drive unplugged, share unmounted, host
151    /// offline, SPEC 9.6). Retried later; never blocks local work.
152    RemoteUnreachable,
153    /// A machine subfolder of a folder remote lists objects that have not
154    /// arrived yet (a sync tool still copying, SPEC 9.6). Retried later.
155    RemoteIncomplete,
156    /// Info: a file under a folder remote matches a sync tool's conflict or
157    /// temp pattern; it is never read and never deleted (SPEC 9.6).
158    SyncArtifactIgnored,
159    /// A pull found fields both sides changed differently (SPEC 9.9). HEAD
160    /// is unchanged; `state/merge/MERGE_STATE.json` lists the conflicts.
161    MergeConflict,
162    /// A git remote refused the push (not a fast-forward even after the
163    /// pull and one retry, or a protected ref; SPEC 9.8).
164    RemoteRejected,
165    /// A git remote refused the credentials, or none were available.
166    RemoteAuthFailed,
167    /// An external program Surjection needs for this (git, gh) is not
168    /// installed or not on `PATH`.
169    ToolNotFound,
170    /// Warning: a foreign client entry that the client itself skips (gate
171    /// V1 CC-5); importing it starts a server the client never ran.
172    ClientSkipsEntry,
173    /// A project entry's `from` names no store server (SPEC 6.2); that
174    /// entry is blocked, the rest of the project applies.
175    UnknownTemplate,
176    /// Warning: a project suppresses a system server for a client that has
177    /// no way to hide a user server in a project (SPEC 6.3).
178    CannotSuppressInProject,
179    /// Warning: a project entry uses `unset`, but the client merges project
180    /// entries over user ones field by field (Codex), so the inherited key
181    /// still reaches it. The entry is written anyway.
182    UnsetNotExpressible,
183    /// A project's manifests are not trusted on this machine, or changed
184    /// since they were trusted (SPEC 17); nothing in that project is
185    /// written until `surject project trust <P>`.
186    TrustRequired,
187    /// Warning: a client loads the same server twice, once through another
188    /// tool's file it also reads (SPEC 6.4 `client-compat:`).
189    DuplicateViaCompat,
190    /// Warning: a client runs same-named entries of its own files as
191    /// separate servers (Grok Build's user and project files, gate V2 CUR-5),
192    /// so two servers of that name run (SPEC 6.4).
193    DuplicateAcrossLayers,
194    /// A private (local-layer) entry would go to a project file that the
195    /// project's git repository tracks (SPEC 6.5); the entry is blocked.
196    PrivateInTrackedFile,
197    /// Warning: Claude Code's `projects` map already holds this folder
198    /// under another spelling of its path (case or separators), so the
199    /// client may read the other key (gate V1 FB-1).
200    ProjectKeySpelling,
201    /// Warning: a shared project file gets `${project}` as this machine's
202    /// absolute folder; teammates see a path that is not theirs.
203    PersonalPathInSharedFile,
204    /// Warning: a client Surjection only reads (`vscode-legacy`, SPEC 7.3) is
205    /// named where something would be written for it; nothing is written.
206    ReadOnlyClient,
207    /// A native value is one the client prompts the user for (VS Code
208    /// `${input:...}`): it has no store form and must be set up as a secret
209    /// by hand before the entry can be imported.
210    NeedsManualSecret,
211    /// The native file can be read but not edited without risking its
212    /// meaning (SPEC 7.2): a JSON5 file that is not also JSONC, or a YAML
213    /// file whose target entry cannot be located unambiguously (anchors,
214    /// aliases, flow style). The target is blocked; the file is untouched.
215    ReadOnlyFormat,
216    /// Info: a client lists each new server of its project file as disabled
217    /// until the user enables it once in the client (Grok Build > Customize >
218    /// MCPs, gate V2 CUR-2). The toggle is the client's own state, so
219    /// Surjection cannot read it; the entry is written anyway.
220    ClientEnableRequired,
221    /// Info: a client reads its file only at launch (Claude Desktop, gate V2
222    /// AP-6), and the file was written; the change loads after a full quit
223    /// and restart of the client.
224    RestartRequired,
225    /// A skill's source (git repository or folder) cannot be reached or no
226    /// longer holds the skill (SPEC 12.4). The store copy is left intact.
227    SourceUnreachable,
228    /// An install or update from a source the user has not trusted, without
229    /// the user's answer to the trust prompt (#24). Nothing was written;
230    /// ask the user (app dialog, interactive prompt, `--trust-source`).
231    SourceTrustRequired,
232    /// A block in `sources.toml` matches the source (#24); nothing is
233    /// fetched or written until the block is removed.
234    SourceBlocked,
235    /// The desktop app's update check or install failed, or updates are
236    /// turned off or not part of this build (SPEC 16.4).
237    UpdateFailed,
238    /// A client file or folder this account cannot write (access denied, a
239    /// read-only attribute, another owner, a read-only share or mount),
240    /// found by the probe while planning or refused by the OS at write
241    /// time (SPEC 8.2, #4). The target is blocked and left as it is; the
242    /// rest of the run goes on. [`CoreError::read_only`] gives the kind.
243    ReadOnlyTarget,
244    /// The built-in scan's verdict on a skill (or MCP server source) is
245    /// `dangerous` (SPEC 17); nothing is installed or updated unless the
246    /// user explicitly chooses to install anyway (`--allow-dangerous`).
247    ScanBlocked,
248    /// A server added from a Git repository runs from this machine's
249    /// checkout (`<SURJECTION_HOME>/servers/<id>`), which is missing or not at
250    /// the commit the server file names (#5). The entry is blocked until
251    /// `surject server checkout <id>` (or the app's Restore) brings it to
252    /// that commit; the old code never runs with the new command.
253    CheckoutOutOfDate,
254    /// A server added from a local folder on another machine (#5): the
255    /// folder is that machine's, so the entry is blocked here.
256    FolderOnOtherMachine,
257    /// Online catalogs are off on this machine (#26): nothing was
258    /// contacted. The user turns them on (Install > Browse, or
259    /// `surject catalog online on`).
260    CatalogsOff,
261    /// Online catalogs are on, but the catalog's host is not approved yet
262    /// (M60, #40: a host added since the user turned catalogs on, such as
263    /// skills.sh after an upgrade from before 0.9): nothing was contacted.
264    /// The user allows it (Settings > Catalogs, Install > Browse, or
265    /// `surject catalog online on`).
266    CatalogHostWaiting,
267    /// A catalog could not be reached or answered with an error (timeout,
268    /// HTTP status, rate limit, a body too large or not JSON).
269    CatalogUnreachable,
270    /// The optional external scanner (SkillSpector, #30) cannot do what was
271    /// asked: it is turned off on this machine, or the step does not apply
272    /// (no uv to prepare with, already set up on `PATH`); nothing ran.
273    ScannerUnavailable,
274    /// The external scanner could not be downloaded (network, HTTP status,
275    /// a redirect to a host Surjection does not download from, too large).
276    ScannerDownloadFailed,
277    /// The external scanner's download is not the pinned build (size or
278    /// SHA-256); it was deleted and nothing was installed.
279    ScannerVerificationFailed,
280    /// The user canceled the operation (a scanner install); nothing was
281    /// changed.
282    Canceled,
283    /// The external scanner is on, installed and has a token, but the
284    /// install or update carries no external report (its scan has not
285    /// run): run the scan, then try again. Nothing was changed.
286    ExternalScanRequired,
287    /// "Check this address" (#47) would contact a host the user has not
288    /// allowed (never asked, or answered no): nothing was contacted. The
289    /// user answers the host prompt (the app, a terminal) or passes
290    /// `--allow-host`.
291    HostWaiting,
292}
293
294impl ErrorCode {
295    pub const fn as_str(self) -> &'static str {
296        match self {
297            ErrorCode::InvalidPath => "invalid_path",
298            ErrorCode::ProfileNotFound => "profile_not_found",
299            ErrorCode::IoError => "io_error",
300            ErrorCode::ParseError => "parse_error",
301            ErrorCode::UnsupportedSchema => "unsupported_schema",
302            ErrorCode::MissingField => "missing_field",
303            ErrorCode::InvalidValue => "invalid_value",
304            ErrorCode::InvalidId => "invalid_id",
305            ErrorCode::IdMismatch => "id_mismatch",
306            ErrorCode::FieldNotAllowed => "field_not_allowed",
307            ErrorCode::PassthroughNotAllowed => "passthrough_not_allowed",
308            ErrorCode::InvalidRef => "invalid_ref",
309            ErrorCode::UnknownClient => "unknown_client",
310            ErrorCode::UnknownOs => "unknown_os",
311            ErrorCode::Locked => "locked",
312            ErrorCode::GitError => "git_error",
313            ErrorCode::AlreadyExists => "already_exists",
314            ErrorCode::NotFound => "not_found",
315            ErrorCode::UnexpectedShape => "unexpected_shape",
316            ErrorCode::NotSupportedOnOs => "not_supported_on_os",
317            ErrorCode::ScopeNotSupported => "scope_not_supported",
318            ErrorCode::UnsupportedTransport => "unsupported_transport",
319            ErrorCode::UnsupportedField => "unsupported_field",
320            ErrorCode::MsixDualWrite => "msix_dual_write",
321            ErrorCode::Collision => "collision",
322            ErrorCode::TimeoutUnitConflict => "timeout_unit_conflict",
323            ErrorCode::ClientMcpReplacedByExtension => "client_mcp_replaced_by_extension",
324            ErrorCode::FileChangedDuringApply => "file_changed_during_apply",
325            ErrorCode::EntryChanged => "entry_changed",
326            ErrorCode::SelfCheckFailed => "self_check_failed",
327            ErrorCode::FileLocked => "file_locked",
328            ErrorCode::DeliveryUnavailable => "delivery_unavailable",
329            ErrorCode::NoAdapter => "no_adapter",
330            ErrorCode::NeedsSecretExtraction => "needs_secret_extraction",
331            ErrorCode::ConfirmationRequired => "confirmation_required",
332            ErrorCode::UnfinishedApply => "unfinished_apply",
333            ErrorCode::LeakDetected => "leak_detected",
334            ErrorCode::MissingSecret => "missing_secret",
335            ErrorCode::SecretLocked => "secret_locked",
336            ErrorCode::ProviderUnavailable => "provider_unavailable",
337            ErrorCode::ProviderTooOld => "provider_too_old",
338            ErrorCode::SecretError => "secret_error",
339            ErrorCode::LauncherNotFound => "launcher_not_found",
340            ErrorCode::NoSecretFreeDelivery => "no_secret_free_delivery",
341            ErrorCode::SecretInSharedFile => "secret_in_shared_file",
342            ErrorCode::InlineEnvFallback => "inline_env_fallback",
343            ErrorCode::RemoteUnreachable => "remote_unreachable",
344            ErrorCode::RemoteIncomplete => "remote_incomplete",
345            ErrorCode::SyncArtifactIgnored => "sync_artifact_ignored",
346            ErrorCode::MergeConflict => "merge_conflict",
347            ErrorCode::RemoteRejected => "remote_rejected",
348            ErrorCode::RemoteAuthFailed => "remote_auth_failed",
349            ErrorCode::ToolNotFound => "tool_not_found",
350            ErrorCode::ClientSkipsEntry => "client_skips_entry",
351            ErrorCode::UnknownTemplate => "unknown_template",
352            ErrorCode::CannotSuppressInProject => "cannot_suppress_in_project",
353            ErrorCode::UnsetNotExpressible => "unset_not_expressible",
354            ErrorCode::TrustRequired => "trust_required",
355            ErrorCode::DuplicateViaCompat => "duplicate_via_compat",
356            ErrorCode::DuplicateAcrossLayers => "duplicate_across_layers",
357            ErrorCode::PrivateInTrackedFile => "private_in_tracked_file",
358            ErrorCode::ProjectKeySpelling => "project_key_spelling",
359            ErrorCode::PersonalPathInSharedFile => "personal_path_in_shared_file",
360            ErrorCode::ReadOnlyClient => "read_only_client",
361            ErrorCode::NeedsManualSecret => "needs_manual_secret",
362            ErrorCode::ReadOnlyFormat => "read_only_format",
363            ErrorCode::ClientEnableRequired => "client_enable_required",
364            ErrorCode::RestartRequired => "restart_required",
365            ErrorCode::SourceUnreachable => "source_unreachable",
366            ErrorCode::SourceTrustRequired => "source_trust_required",
367            ErrorCode::SourceBlocked => "source_blocked",
368            ErrorCode::UpdateFailed => "update_failed",
369            ErrorCode::ReadOnlyTarget => "read_only_target",
370            ErrorCode::ScanBlocked => "scan_blocked",
371            ErrorCode::CheckoutOutOfDate => "checkout_out_of_date",
372            ErrorCode::FolderOnOtherMachine => "folder_on_other_machine",
373            ErrorCode::CatalogsOff => "catalogs_off",
374            ErrorCode::CatalogHostWaiting => "catalog_host_waiting",
375            ErrorCode::CatalogUnreachable => "catalog_unreachable",
376            ErrorCode::ScannerUnavailable => "scanner_unavailable",
377            ErrorCode::ScannerDownloadFailed => "scanner_download_failed",
378            ErrorCode::ScannerVerificationFailed => "scanner_verification_failed",
379            ErrorCode::Canceled => "canceled",
380            ErrorCode::ExternalScanRequired => "external_scan_required",
381            ErrorCode::HostWaiting => "host_waiting",
382        }
383    }
384}
385
386impl fmt::Display for ErrorCode {
387    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
388        f.write_str(self.as_str())
389    }
390}
391
392#[derive(Debug, Clone, PartialEq, Eq)]
393pub struct CoreError {
394    code: ErrorCode,
395    message: String,
396    path: Option<PathBuf>,
397    /// Why the target is read only, for [`ErrorCode::ReadOnlyTarget`].
398    read_only: Option<ReadOnlyKind>,
399}
400
401impl CoreError {
402    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
403        Self {
404            code,
405            message: message.into(),
406            path: None,
407            read_only: None,
408        }
409    }
410
411    pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
412        self.path = Some(path.into());
413        self
414    }
415
416    /// Attaches the kind of a `read_only_target` error.
417    pub fn with_read_only(mut self, kind: ReadOnlyKind) -> Self {
418        self.read_only = Some(kind);
419        self
420    }
421
422    /// The kind of a `read_only_target` error.
423    pub fn read_only(&self) -> Option<ReadOnlyKind> {
424        self.read_only
425    }
426
427    pub fn code(&self) -> ErrorCode {
428        self.code
429    }
430
431    pub fn message(&self) -> &str {
432        &self.message
433    }
434
435    pub fn path(&self) -> Option<&Path> {
436        self.path.as_deref()
437    }
438}
439
440impl fmt::Display for CoreError {
441    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442        f.write_str(&self.message)?;
443        if let Some(path) = &self.path {
444            write!(f, ": {}", path.display())?;
445        }
446        Ok(())
447    }
448}
449
450impl std::error::Error for CoreError {}