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
//! Typed core errors. The CLI and the GUI localize from [`ErrorCode`]; the
//! message is English diagnostic detail, never state.
use std::fmt;
use std::path::{Path, PathBuf};
use crate::access::ReadOnlyKind;
/// Stable error code, serialized as `snake_case` (the same string as
/// [`ErrorCode::as_str`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "specta", derive(specta::Type))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ErrorCode {
/// A path argument, override or path field is unusable (for example
/// relative, or personal where a placeholder is required).
InvalidPath,
/// The user profile directory could not be determined.
ProfileNotFound,
/// A file could not be read or written.
IoError,
/// A file is not valid UTF-8, or not valid in its format (TOML, JSON, JSONC).
ParseError,
/// A store file declares a `schema` version this build does not read.
UnsupportedSchema,
/// A required field is absent.
MissingField,
/// A field has the wrong type or a value outside its allowed set.
InvalidValue,
/// An identifier breaks the rules of SPEC 5.1.
InvalidId,
/// An id disagrees with the file or directory name that holds it.
IdMismatch,
/// A field is present where the rest of the definition forbids it
/// (for example `url` on a stdio server).
FieldNotAllowed,
/// A `client.<id>` key is not in that client's passthrough allowlist.
PassthroughNotAllowed,
/// A template or secret reference does not parse (SPEC 11.2).
InvalidRef,
/// A client id is not in the adapter table. Warning: kept as written.
UnknownClient,
/// An OS name is not `windows`, `linux` or `macos`. Warning: kept as written.
UnknownOs,
/// Another process holds `state/surjection.lock` and the wait timed out.
Locked,
/// The store repository could not be read or written.
GitError,
/// An entity with this id already exists.
AlreadyExists,
/// No entity with this id exists.
NotFound,
/// A native client file parses, but a value on the path being read or
/// edited has another kind (for example `mcpServers` is an array).
UnexpectedShape,
/// A client has no target on this operating system (Claude Desktop on
/// Linux).
NotSupportedOnOs,
/// A client has no target in the requested scope (Claude Desktop at
/// project scope).
ScopeNotSupported,
/// A client cannot run a server over this transport (HTTP on Claude
/// Desktop). The target is blocked; nothing is dropped silently.
UnsupportedTransport,
/// A client has no native field for a set server field (`cwd` on Claude
/// Desktop). The target is blocked; nothing is dropped silently.
UnsupportedField,
/// Warning: an MSIX install keeps its own copy of a client file, so both
/// copies are written (Claude Desktop on Windows).
MsixDualWrite,
/// Warning: a client treats another entry name as the same server (Pi
/// counts names that differ only in `-` and `_` as one), so writing the
/// entry would clash with it.
Collision,
/// Clients with different units for the same timeout key read one file
/// (omp `timeout` in milliseconds and Pi `timeout` in seconds, both in
/// `$PI_CODING_AGENT_DIR/mcp.json`; gate V2 OMP-10), and the entry sets
/// that key. The entry is blocked; no unit is guessed.
TimeoutUnitConflict,
/// Warning: an installed extension takes over the client's MCP support
/// (Pi with `pi-mcp-adapter`), so the client's own MCP config may not be
/// what loads.
ClientMcpReplacedByExtension,
/// A client file kept changing between planning and writing (SPEC 8.4
/// step 1, after three re-plans). The file is left as it is.
FileChangedDuringApply,
/// The entry a resolution was chosen for changed (in the file or in the
/// store) since the resolver showed it; nothing was done (SPEC 13.4).
EntryChanged,
/// The edited file did not read back as planned: an owned entry differs
/// from the desired one, or something outside the owned entries changed
/// (SPEC 8.4 step 3). The file is left as it is.
SelfCheckFailed,
/// Another process kept a client file open for longer than the retry
/// window (Windows sharing violation, SPEC 8.4 step 4).
FileLocked,
/// The delivery mode a server asks for (`delivery.mode`) cannot bring a
/// reference to this client and field, or a value cannot be written
/// without changing its meaning (a literal `${` the client would
/// expand). The entry is blocked; nothing is written in plain text.
DeliveryUnavailable,
/// Warning: a known client has no adapter in this build yet, so nothing
/// is written for it.
NoAdapter,
/// A native entry holds literal values that may be secrets; importing it
/// needs secret extraction (SPEC 11.7) instead of copying the values.
NeedsSecretExtraction,
/// The operation changes state that later operations changed too and
/// needs an explicit confirmation (rolling back an older apply, SPEC 8.7).
ConfirmationRequired,
/// Warning: an apply run did not finish; its journal lists what each
/// file got (SPEC 8.4 step 6). Nothing is replayed.
UnfinishedApply,
/// A staged store file or commit message holds what looks like a
/// secret, or a value resolved during this process (SPEC 11.8). Nothing
/// is written or committed.
LeakDetected,
/// A secret reference has no value: env var unset, keyring entry or
/// 1Password item absent, alias not defined (SPEC 11.3 `missing`).
MissingSecret,
/// 1Password (or the keyring) needs sign-in or approval (SPEC 11.3
/// `locked`).
SecretLocked,
/// A secret provider is not on this machine ("1Password CLI not
/// found", no Secret Service; SPEC 11.3 `provider_unavailable`).
ProviderUnavailable,
/// A secret provider is older than a feature needs (SPEC 11.11).
ProviderTooOld,
/// A secret provider failed for another reason, or the value cannot be
/// read from here (SPEC 11.3 `error`, `unverifiable`).
SecretError,
/// `launch` delivery needs the absolute path of the `surject` binary
/// and it could not be resolved (SPEC 11.4, 11.5). The entry is
/// blocked; nothing falls back to `inline`.
LauncherNotFound,
/// A provider reference has no delivery mode that keeps its value out
/// of the client's config file for this client and field (SPEC 11.4
/// rule 2). Fixes: export to the environment, or allow `inline` for
/// the server.
NoSecretFreeDelivery,
/// `inline` delivery would write a secret value into a shared file
/// (SPEC 11.4 rule 3). Fixes: `env` or `launch`, or the project-local
/// layer.
SecretInSharedFile,
/// Warning: a `${env:NAME}` reference is written as the value of
/// Surjection's own environment, because the client cannot expand it
/// there and `launch` cannot carry it (SPEC 11.4 rule 1).
InlineEnvFallback,
/// A remote cannot be reached (drive unplugged, share unmounted, host
/// offline, SPEC 9.6). Retried later; never blocks local work.
RemoteUnreachable,
/// A machine subfolder of a folder remote lists objects that have not
/// arrived yet (a sync tool still copying, SPEC 9.6). Retried later.
RemoteIncomplete,
/// Info: a file under a folder remote matches a sync tool's conflict or
/// temp pattern; it is never read and never deleted (SPEC 9.6).
SyncArtifactIgnored,
/// A pull found fields both sides changed differently (SPEC 9.9). HEAD
/// is unchanged; `state/merge/MERGE_STATE.json` lists the conflicts.
MergeConflict,
/// A git remote refused the push (not a fast-forward even after the
/// pull and one retry, or a protected ref; SPEC 9.8).
RemoteRejected,
/// A git remote refused the credentials, or none were available.
RemoteAuthFailed,
/// An external program Surjection needs for this (git, gh) is not
/// installed or not on `PATH`.
ToolNotFound,
/// Warning: a foreign client entry that the client itself skips (gate
/// V1 CC-5); importing it starts a server the client never ran.
ClientSkipsEntry,
/// A project entry's `from` names no store server (SPEC 6.2); that
/// entry is blocked, the rest of the project applies.
UnknownTemplate,
/// Warning: a project suppresses a system server for a client that has
/// no way to hide a user server in a project (SPEC 6.3).
CannotSuppressInProject,
/// Warning: a project entry uses `unset`, but the client merges project
/// entries over user ones field by field (Codex), so the inherited key
/// still reaches it. The entry is written anyway.
UnsetNotExpressible,
/// A project's manifests are not trusted on this machine, or changed
/// since they were trusted (SPEC 17); nothing in that project is
/// written until `surject project trust <P>`.
TrustRequired,
/// Warning: a client loads the same server twice, once through another
/// tool's file it also reads (SPEC 6.4 `client-compat:`).
DuplicateViaCompat,
/// Warning: a client runs same-named entries of its own files as
/// separate servers (Grok Build's user and project files, gate V2 CUR-5),
/// so two servers of that name run (SPEC 6.4).
DuplicateAcrossLayers,
/// A private (local-layer) entry would go to a project file that the
/// project's git repository tracks (SPEC 6.5); the entry is blocked.
PrivateInTrackedFile,
/// Warning: Claude Code's `projects` map already holds this folder
/// under another spelling of its path (case or separators), so the
/// client may read the other key (gate V1 FB-1).
ProjectKeySpelling,
/// Warning: a shared project file gets `${project}` as this machine's
/// absolute folder; teammates see a path that is not theirs.
PersonalPathInSharedFile,
/// Warning: a client Surjection only reads (`vscode-legacy`, SPEC 7.3) is
/// named where something would be written for it; nothing is written.
ReadOnlyClient,
/// A native value is one the client prompts the user for (VS Code
/// `${input:...}`): it has no store form and must be set up as a secret
/// by hand before the entry can be imported.
NeedsManualSecret,
/// The native file can be read but not edited without risking its
/// meaning (SPEC 7.2): a JSON5 file that is not also JSONC, or a YAML
/// file whose target entry cannot be located unambiguously (anchors,
/// aliases, flow style). The target is blocked; the file is untouched.
ReadOnlyFormat,
/// Info: a client lists each new server of its project file as disabled
/// until the user enables it once in the client (Grok Build > Customize >
/// MCPs, gate V2 CUR-2). The toggle is the client's own state, so
/// Surjection cannot read it; the entry is written anyway.
ClientEnableRequired,
/// Info: a client reads its file only at launch (Claude Desktop, gate V2
/// AP-6), and the file was written; the change loads after a full quit
/// and restart of the client.
RestartRequired,
/// A skill's source (git repository or folder) cannot be reached or no
/// longer holds the skill (SPEC 12.4). The store copy is left intact.
SourceUnreachable,
/// An install or update from a source the user has not trusted, without
/// the user's answer to the trust prompt (#24). Nothing was written;
/// ask the user (app dialog, interactive prompt, `--trust-source`).
SourceTrustRequired,
/// A block in `sources.toml` matches the source (#24); nothing is
/// fetched or written until the block is removed.
SourceBlocked,
/// The desktop app's update check or install failed, or updates are
/// turned off or not part of this build (SPEC 16.4).
UpdateFailed,
/// A client file or folder this account cannot write (access denied, a
/// read-only attribute, another owner, a read-only share or mount),
/// found by the probe while planning or refused by the OS at write
/// time (SPEC 8.2, #4). The target is blocked and left as it is; the
/// rest of the run goes on. [`CoreError::read_only`] gives the kind.
ReadOnlyTarget,
/// The built-in scan's verdict on a skill (or MCP server source) is
/// `dangerous` (SPEC 17); nothing is installed or updated unless the
/// user explicitly chooses to install anyway (`--allow-dangerous`).
ScanBlocked,
/// A server added from a Git repository runs from this machine's
/// checkout (`<SURJECTION_HOME>/servers/<id>`), which is missing or not at
/// the commit the server file names (#5). The entry is blocked until
/// `surject server checkout <id>` (or the app's Restore) brings it to
/// that commit; the old code never runs with the new command.
CheckoutOutOfDate,
/// A server added from a local folder on another machine (#5): the
/// folder is that machine's, so the entry is blocked here.
FolderOnOtherMachine,
/// Online catalogs are off on this machine (#26): nothing was
/// contacted. The user turns them on (Install > Browse, or
/// `surject catalog online on`).
CatalogsOff,
/// Online catalogs are on, but the catalog's host is not approved yet
/// (M60, #40: a host added since the user turned catalogs on, such as
/// skills.sh after an upgrade from before 0.9): nothing was contacted.
/// The user allows it (Settings > Catalogs, Install > Browse, or
/// `surject catalog online on`).
CatalogHostWaiting,
/// A catalog could not be reached or answered with an error (timeout,
/// HTTP status, rate limit, a body too large or not JSON).
CatalogUnreachable,
/// The optional external scanner (SkillSpector, #30) cannot do what was
/// asked: it is turned off on this machine, or the step does not apply
/// (no uv to prepare with, already set up on `PATH`); nothing ran.
ScannerUnavailable,
/// The external scanner could not be downloaded (network, HTTP status,
/// a redirect to a host Surjection does not download from, too large).
ScannerDownloadFailed,
/// The external scanner's download is not the pinned build (size or
/// SHA-256); it was deleted and nothing was installed.
ScannerVerificationFailed,
/// The user canceled the operation (a scanner install); nothing was
/// changed.
Canceled,
/// The external scanner is on, installed and has a token, but the
/// install or update carries no external report (its scan has not
/// run): run the scan, then try again. Nothing was changed.
ExternalScanRequired,
/// "Check this address" (#47) would contact a host the user has not
/// allowed (never asked, or answered no): nothing was contacted. The
/// user answers the host prompt (the app, a terminal) or passes
/// `--allow-host`.
HostWaiting,
}
impl ErrorCode {
pub const fn as_str(self) -> &'static str {
match self {
ErrorCode::InvalidPath => "invalid_path",
ErrorCode::ProfileNotFound => "profile_not_found",
ErrorCode::IoError => "io_error",
ErrorCode::ParseError => "parse_error",
ErrorCode::UnsupportedSchema => "unsupported_schema",
ErrorCode::MissingField => "missing_field",
ErrorCode::InvalidValue => "invalid_value",
ErrorCode::InvalidId => "invalid_id",
ErrorCode::IdMismatch => "id_mismatch",
ErrorCode::FieldNotAllowed => "field_not_allowed",
ErrorCode::PassthroughNotAllowed => "passthrough_not_allowed",
ErrorCode::InvalidRef => "invalid_ref",
ErrorCode::UnknownClient => "unknown_client",
ErrorCode::UnknownOs => "unknown_os",
ErrorCode::Locked => "locked",
ErrorCode::GitError => "git_error",
ErrorCode::AlreadyExists => "already_exists",
ErrorCode::NotFound => "not_found",
ErrorCode::UnexpectedShape => "unexpected_shape",
ErrorCode::NotSupportedOnOs => "not_supported_on_os",
ErrorCode::ScopeNotSupported => "scope_not_supported",
ErrorCode::UnsupportedTransport => "unsupported_transport",
ErrorCode::UnsupportedField => "unsupported_field",
ErrorCode::MsixDualWrite => "msix_dual_write",
ErrorCode::Collision => "collision",
ErrorCode::TimeoutUnitConflict => "timeout_unit_conflict",
ErrorCode::ClientMcpReplacedByExtension => "client_mcp_replaced_by_extension",
ErrorCode::FileChangedDuringApply => "file_changed_during_apply",
ErrorCode::EntryChanged => "entry_changed",
ErrorCode::SelfCheckFailed => "self_check_failed",
ErrorCode::FileLocked => "file_locked",
ErrorCode::DeliveryUnavailable => "delivery_unavailable",
ErrorCode::NoAdapter => "no_adapter",
ErrorCode::NeedsSecretExtraction => "needs_secret_extraction",
ErrorCode::ConfirmationRequired => "confirmation_required",
ErrorCode::UnfinishedApply => "unfinished_apply",
ErrorCode::LeakDetected => "leak_detected",
ErrorCode::MissingSecret => "missing_secret",
ErrorCode::SecretLocked => "secret_locked",
ErrorCode::ProviderUnavailable => "provider_unavailable",
ErrorCode::ProviderTooOld => "provider_too_old",
ErrorCode::SecretError => "secret_error",
ErrorCode::LauncherNotFound => "launcher_not_found",
ErrorCode::NoSecretFreeDelivery => "no_secret_free_delivery",
ErrorCode::SecretInSharedFile => "secret_in_shared_file",
ErrorCode::InlineEnvFallback => "inline_env_fallback",
ErrorCode::RemoteUnreachable => "remote_unreachable",
ErrorCode::RemoteIncomplete => "remote_incomplete",
ErrorCode::SyncArtifactIgnored => "sync_artifact_ignored",
ErrorCode::MergeConflict => "merge_conflict",
ErrorCode::RemoteRejected => "remote_rejected",
ErrorCode::RemoteAuthFailed => "remote_auth_failed",
ErrorCode::ToolNotFound => "tool_not_found",
ErrorCode::ClientSkipsEntry => "client_skips_entry",
ErrorCode::UnknownTemplate => "unknown_template",
ErrorCode::CannotSuppressInProject => "cannot_suppress_in_project",
ErrorCode::UnsetNotExpressible => "unset_not_expressible",
ErrorCode::TrustRequired => "trust_required",
ErrorCode::DuplicateViaCompat => "duplicate_via_compat",
ErrorCode::DuplicateAcrossLayers => "duplicate_across_layers",
ErrorCode::PrivateInTrackedFile => "private_in_tracked_file",
ErrorCode::ProjectKeySpelling => "project_key_spelling",
ErrorCode::PersonalPathInSharedFile => "personal_path_in_shared_file",
ErrorCode::ReadOnlyClient => "read_only_client",
ErrorCode::NeedsManualSecret => "needs_manual_secret",
ErrorCode::ReadOnlyFormat => "read_only_format",
ErrorCode::ClientEnableRequired => "client_enable_required",
ErrorCode::RestartRequired => "restart_required",
ErrorCode::SourceUnreachable => "source_unreachable",
ErrorCode::SourceTrustRequired => "source_trust_required",
ErrorCode::SourceBlocked => "source_blocked",
ErrorCode::UpdateFailed => "update_failed",
ErrorCode::ReadOnlyTarget => "read_only_target",
ErrorCode::ScanBlocked => "scan_blocked",
ErrorCode::CheckoutOutOfDate => "checkout_out_of_date",
ErrorCode::FolderOnOtherMachine => "folder_on_other_machine",
ErrorCode::CatalogsOff => "catalogs_off",
ErrorCode::CatalogHostWaiting => "catalog_host_waiting",
ErrorCode::CatalogUnreachable => "catalog_unreachable",
ErrorCode::ScannerUnavailable => "scanner_unavailable",
ErrorCode::ScannerDownloadFailed => "scanner_download_failed",
ErrorCode::ScannerVerificationFailed => "scanner_verification_failed",
ErrorCode::Canceled => "canceled",
ErrorCode::ExternalScanRequired => "external_scan_required",
ErrorCode::HostWaiting => "host_waiting",
}
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoreError {
code: ErrorCode,
message: String,
path: Option<PathBuf>,
/// Why the target is read only, for [`ErrorCode::ReadOnlyTarget`].
read_only: Option<ReadOnlyKind>,
}
impl CoreError {
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
path: None,
read_only: None,
}
}
pub fn with_path(mut self, path: impl Into<PathBuf>) -> Self {
self.path = Some(path.into());
self
}
/// Attaches the kind of a `read_only_target` error.
pub fn with_read_only(mut self, kind: ReadOnlyKind) -> Self {
self.read_only = Some(kind);
self
}
/// The kind of a `read_only_target` error.
pub fn read_only(&self) -> Option<ReadOnlyKind> {
self.read_only
}
pub fn code(&self) -> ErrorCode {
self.code
}
pub fn message(&self) -> &str {
&self.message
}
pub fn path(&self) -> Option<&Path> {
self.path.as_deref()
}
}
impl fmt::Display for CoreError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)?;
if let Some(path) = &self.path {
write!(f, ": {}", path.display())?;
}
Ok(())
}
}
impl std::error::Error for CoreError {}