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}
288
289impl ErrorCode {
290 pub const fn as_str(self) -> &'static str {
291 match self {
292 ErrorCode::InvalidPath => "invalid_path",
293 ErrorCode::ProfileNotFound => "profile_not_found",
294 ErrorCode::IoError => "io_error",
295 ErrorCode::ParseError => "parse_error",
296 ErrorCode::UnsupportedSchema => "unsupported_schema",
297 ErrorCode::MissingField => "missing_field",
298 ErrorCode::InvalidValue => "invalid_value",
299 ErrorCode::InvalidId => "invalid_id",
300 ErrorCode::IdMismatch => "id_mismatch",
301 ErrorCode::FieldNotAllowed => "field_not_allowed",
302 ErrorCode::PassthroughNotAllowed => "passthrough_not_allowed",
303 ErrorCode::InvalidRef => "invalid_ref",
304 ErrorCode::UnknownClient => "unknown_client",
305 ErrorCode::UnknownOs => "unknown_os",
306 ErrorCode::Locked => "locked",
307 ErrorCode::GitError => "git_error",
308 ErrorCode::AlreadyExists => "already_exists",
309 ErrorCode::NotFound => "not_found",
310 ErrorCode::UnexpectedShape => "unexpected_shape",
311 ErrorCode::NotSupportedOnOs => "not_supported_on_os",
312 ErrorCode::ScopeNotSupported => "scope_not_supported",
313 ErrorCode::UnsupportedTransport => "unsupported_transport",
314 ErrorCode::UnsupportedField => "unsupported_field",
315 ErrorCode::MsixDualWrite => "msix_dual_write",
316 ErrorCode::Collision => "collision",
317 ErrorCode::TimeoutUnitConflict => "timeout_unit_conflict",
318 ErrorCode::ClientMcpReplacedByExtension => "client_mcp_replaced_by_extension",
319 ErrorCode::FileChangedDuringApply => "file_changed_during_apply",
320 ErrorCode::EntryChanged => "entry_changed",
321 ErrorCode::SelfCheckFailed => "self_check_failed",
322 ErrorCode::FileLocked => "file_locked",
323 ErrorCode::DeliveryUnavailable => "delivery_unavailable",
324 ErrorCode::NoAdapter => "no_adapter",
325 ErrorCode::NeedsSecretExtraction => "needs_secret_extraction",
326 ErrorCode::ConfirmationRequired => "confirmation_required",
327 ErrorCode::UnfinishedApply => "unfinished_apply",
328 ErrorCode::LeakDetected => "leak_detected",
329 ErrorCode::MissingSecret => "missing_secret",
330 ErrorCode::SecretLocked => "secret_locked",
331 ErrorCode::ProviderUnavailable => "provider_unavailable",
332 ErrorCode::ProviderTooOld => "provider_too_old",
333 ErrorCode::SecretError => "secret_error",
334 ErrorCode::LauncherNotFound => "launcher_not_found",
335 ErrorCode::NoSecretFreeDelivery => "no_secret_free_delivery",
336 ErrorCode::SecretInSharedFile => "secret_in_shared_file",
337 ErrorCode::InlineEnvFallback => "inline_env_fallback",
338 ErrorCode::RemoteUnreachable => "remote_unreachable",
339 ErrorCode::RemoteIncomplete => "remote_incomplete",
340 ErrorCode::SyncArtifactIgnored => "sync_artifact_ignored",
341 ErrorCode::MergeConflict => "merge_conflict",
342 ErrorCode::RemoteRejected => "remote_rejected",
343 ErrorCode::RemoteAuthFailed => "remote_auth_failed",
344 ErrorCode::ToolNotFound => "tool_not_found",
345 ErrorCode::ClientSkipsEntry => "client_skips_entry",
346 ErrorCode::UnknownTemplate => "unknown_template",
347 ErrorCode::CannotSuppressInProject => "cannot_suppress_in_project",
348 ErrorCode::UnsetNotExpressible => "unset_not_expressible",
349 ErrorCode::TrustRequired => "trust_required",
350 ErrorCode::DuplicateViaCompat => "duplicate_via_compat",
351 ErrorCode::DuplicateAcrossLayers => "duplicate_across_layers",
352 ErrorCode::PrivateInTrackedFile => "private_in_tracked_file",
353 ErrorCode::ProjectKeySpelling => "project_key_spelling",
354 ErrorCode::PersonalPathInSharedFile => "personal_path_in_shared_file",
355 ErrorCode::ReadOnlyClient => "read_only_client",
356 ErrorCode::NeedsManualSecret => "needs_manual_secret",
357 ErrorCode::ReadOnlyFormat => "read_only_format",
358 ErrorCode::ClientEnableRequired => "client_enable_required",
359 ErrorCode::RestartRequired => "restart_required",
360 ErrorCode::SourceUnreachable => "source_unreachable",
361 ErrorCode::SourceTrustRequired => "source_trust_required",
362 ErrorCode::SourceBlocked => "source_blocked",
363 ErrorCode::UpdateFailed => "update_failed",
364 ErrorCode::ReadOnlyTarget => "read_only_target",
365 ErrorCode::ScanBlocked => "scan_blocked",
366 ErrorCode::CheckoutOutOfDate => "checkout_out_of_date",
367 ErrorCode::FolderOnOtherMachine => "folder_on_other_machine",
368 ErrorCode::CatalogsOff => "catalogs_off",
369 ErrorCode::CatalogHostWaiting => "catalog_host_waiting",
370 ErrorCode::CatalogUnreachable => "catalog_unreachable",
371 ErrorCode::ScannerUnavailable => "scanner_unavailable",
372 ErrorCode::ScannerDownloadFailed => "scanner_download_failed",
373 ErrorCode::ScannerVerificationFailed => "scanner_verification_failed",
374 ErrorCode::Canceled => "canceled",
375 ErrorCode::ExternalScanRequired => "external_scan_required",
376 }
377 }
378}
379
380impl fmt::Display for ErrorCode {
381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382 f.write_str(self.as_str())
383 }
384}
385
386#[derive(Debug, Clone, PartialEq, Eq)]
387pub struct CoreError {
388 code: ErrorCode,
389 message: String,
390 path: Option<PathBuf>,
391 /// Why the target is read only, for [`ErrorCode::ReadOnlyTarget`].
392 read_only: Option<ReadOnlyKind>,
393}
394
395impl CoreError {
396 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
397 Self {
398 code,
399 message: message.into(),
400 path: None,
401 read_only: None,
402 }
403 }
404
405 pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
406 self.path = Some(path.into());
407 self
408 }
409
410 /// Attaches the kind of a `read_only_target` error.
411 pub fn with_read_only(mut self, kind: ReadOnlyKind) -> Self {
412 self.read_only = Some(kind);
413 self
414 }
415
416 /// The kind of a `read_only_target` error.
417 pub fn read_only(&self) -> Option<ReadOnlyKind> {
418 self.read_only
419 }
420
421 pub fn code(&self) -> ErrorCode {
422 self.code
423 }
424
425 pub fn message(&self) -> &str {
426 &self.message
427 }
428
429 pub fn path(&self) -> Option<&Path> {
430 self.path.as_deref()
431 }
432}
433
434impl fmt::Display for CoreError {
435 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436 f.write_str(&self.message)?;
437 if let Some(path) = &self.path {
438 write!(f, ": {}", path.display())?;
439 }
440 Ok(())
441 }
442}
443
444impl std::error::Error for CoreError {}