Skip to main content

oak_core/
error.rs

1use thiserror::Error;
2
3#[derive(Debug)]
4pub struct FinishPreflightError {
5    pub blocker: FinishBlocker,
6    pub message: String,
7    pub pending_phases: Vec<String>,
8    pub retry_command: Option<String>,
9    pub manual_recovery_commands: Vec<String>,
10}
11
12impl std::fmt::Display for FinishPreflightError {
13    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        f.write_str(&self.message)
15    }
16}
17
18#[derive(Debug)]
19pub struct FinishPhaseError {
20    pub phase: String,
21    pub completed_phases: Vec<String>,
22    pub pending_phases: Vec<String>,
23    pub message: String,
24    pub retry_command: Option<String>,
25    pub manual_recovery_commands: Vec<String>,
26}
27
28impl std::fmt::Display for FinishPhaseError {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.write_str(&self.message)
31    }
32}
33
34#[derive(Debug)]
35pub struct CommitPhaseError {
36    pub phase: String,
37    pub committed: bool,
38    pub pushed: bool,
39    pub published: bool,
40    pub remote_contacted: bool,
41    pub branch: String,
42    pub head_before: Option<String>,
43    pub head_after: Option<String>,
44    pub unpushed_commit_count: usize,
45    pub message: String,
46    pub retry_command: Option<String>,
47    pub manual_recovery_commands: Vec<String>,
48}
49
50impl std::fmt::Display for CommitPhaseError {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.write_str(&self.message)
53    }
54}
55
56#[derive(Error, Debug)]
57pub enum OakError {
58    #[error("Disk full at '{path}': no free storage is available for the repository database or its journal")]
59    DiskFull { path: String },
60
61    #[error(
62        "Repository not found. Run 'oak init' to create a repository here, or 'oak clone <repo>' to clone an existing one."
63    )]
64    RepoNotFound,
65
66    #[error("Repository already exists at this location")]
67    RepoAlreadyExists,
68
69    #[error("No commits yet")]
70    NoCommits,
71
72    #[error("Invalid hash: {0}")]
73    InvalidHash(String),
74
75    #[error("{0}")]
76    InvalidPath(String),
77
78    #[error("Blob not found: {0}")]
79    BlobNotFound(String),
80
81    #[error("Commit not found: {0}")]
82    CommitNotFound(String),
83
84    #[error("Branch not found: {0}")]
85    BranchNotFound(String),
86
87    #[error("Branch '{0}' already exists")]
88    BranchAlreadyExists(String),
89
90    #[error("Branch '{0}' is closed")]
91    BranchClosed(String),
92
93    #[error("No commits in branch")]
94    NoEdits,
95
96    #[error("Manifest not found: {0}")]
97    ManifestNotFound(String),
98
99    #[error("Working directory has uncommitted changes")]
100    UncommittedChanges,
101
102    #[error("Working tree changed while capture was in progress: {detail}. Retry the capture.")]
103    WorktreeCaptureRaced { detail: String },
104
105    #[error("Change capture does not support repository hash format {0:?}")]
106    UnsupportedChangeCaptureFormat(String),
107
108    #[error("Change capture excluded requested path {path:?}: {reason}. {remedy}")]
109    ChangeCaptureScopeExcluded {
110        path: String,
111        reason: String,
112        remedy: String,
113    },
114
115    #[error("Captured blob integrity check failed for {path:?} ({hash}): {detail}")]
116    CapturedBlobIntegrity {
117        path: String,
118        hash: String,
119        detail: String,
120    },
121
122    #[error("Captured tree integrity check failed for {hash}: {detail}")]
123    CapturedTreeIntegrity { hash: String, detail: String },
124
125    #[error("Change capture {capture_id:?} was not found. Rerun `oak change capture --json` to create a durable local lookup record.")]
126    ChangeCaptureNotFound { capture_id: String },
127
128    #[error("Change capture {capture_id:?} failed durable lookup validation: {detail}")]
129    ChangeCaptureIntegrity { capture_id: String, detail: String },
130
131    #[error("{0}")]
132    DirtyWorkingTree(String),
133
134    #[error("Conflict detected: remote has diverged. Pull changes first.")]
135    ConflictDetected,
136
137    #[error(
138        "This branch's local history isn't anchored on the remote's.\nRun 'oak pull' to converge: it re-parents the branch onto the remote and keeps your local commits (overlapping edits open the normal conflict flow).\nIf you want the remote's state instead, 'oak pull --force' re-syncs after parking local commits as '<branch>.orphaned-<timestamp>' — nothing is deleted."
139    )]
140    LocalCommitsNotInRemoteHistory,
141
142    #[error(
143        "The remote branch has commits this clone doesn't have.\nRun 'oak pull' to bring them in and converge (your local commits are kept), then push again."
144    )]
145    RemoteCommitsNotInLocalHistory,
146
147    #[error("Remote repository not configured")]
148    RemoteNotConfigured,
149
150    #[error(
151        "remote has moved to {origin} — run `oak push -r {origin}` to update this repo's remote"
152    )]
153    RemoteMoved { origin: String },
154
155    #[error("Repository '{0}' not found on server")]
156    RemoteRepoNotFound(String),
157
158    #[error("Repository '{0}' already exists on server")]
159    RemoteRepoAlreadyExists(String),
160
161    #[error("Merge failed: {0}")]
162    MergeFailed(String),
163
164    #[error(
165        "Incomplete ancestry while finding common ancestor between '{left}' and '{right}'. Missing commit(s): {missing}. Run 'oak fetch' or 'oak pull --force' to repair local history."
166    )]
167    IncompleteAncestry {
168        left: String,
169        right: String,
170        missing: String,
171    },
172
173    #[error(
174        "Incomplete manifest data while merging '{left}' with '{right}'. Missing manifest(s): {missing}. Run 'oak fetch' or 'oak pull --force' to repair local history."
175    )]
176    IncompleteManifestData {
177        left: String,
178        right: String,
179        missing: String,
180    },
181
182    #[error(
183        "Incomplete commit data while reading {context}. Missing commit(s): {missing}. Run 'oak fetch' or 'oak pull --force' to repair local history."
184    )]
185    IncompleteCommitData { context: String, missing: String },
186
187    #[error(
188        "Incomplete blob data while reading {context}. Missing blob(s): {missing}. Run 'oak fetch' or 'oak pull --force' to repair local history."
189    )]
190    IncompleteBlobData { context: String, missing: String },
191
192    #[error(
193        "No verified common ancestor found between '{left}' and '{right}'. Run 'oak fetch' or 'oak pull --force' to repair local history."
194    )]
195    NoVerifiedCommonAncestor { left: String, right: String },
196
197    #[error("Merge conflict: {0} file(s) modified on both branches since fork")]
198    MergeConflict(usize),
199
200    /// `next_commands`: the exact next steps the assessment that raised this
201    /// derived from its evidence (never `oak merge`).
202    #[error("Merge invariant violation: {detail}")]
203    MergeInvariantViolation {
204        detail: String,
205        next_commands: Vec<String>,
206    },
207
208    /// `next_commands`: as on [`OakError::MergeInvariantViolation`].
209    #[error("Merge prediction uncertified: {detail}")]
210    MergePredictionUncertified {
211        detail: String,
212        next_commands: Vec<String>,
213    },
214
215    /// A remote content-integrity proof ran out of budget before it could
216    /// conclude. This is neither proof of health nor evidence of missing
217    /// content; callers must not treat it as either.
218    #[error("Integrity proof inconclusive: {detail}")]
219    IntegrityInconclusive {
220        detail: String,
221        /// Exact, shell-quoted invocations for the natural next step, in
222        /// preference order (e.g. the narrower `--shallow` clone first).
223        recommended_next_commands: Vec<String>,
224    },
225
226    /// The server's clone admission (integrity snapshot) token is too large to
227    /// send back in the pull request URL. Raised before the pull request is
228    /// sent; nothing was downloaded. The token itself is never echoed.
229    #[error("Clone admission token too large: {detail}")]
230    CloneAdmissionTokenTooLarge {
231        detail: String,
232        /// Exact, shell-quoted invocations that work from the caller's
233        /// working directory (the same clone with `--shallow`), or empty
234        /// when no narrower retry of this invocation exists.
235        recommended_next_commands: Vec<String>,
236    },
237
238    /// The server refused to start an integrity proof because it was busy
239    /// and the client's bounded wait for admission ran out. Nothing was
240    /// downloaded or created.
241    #[error("Integrity proof not admitted: {0}")]
242    IntegrityAdmissionBusy(String),
243
244    #[error("A merge is already in progress. Use 'oak merge --continue' or 'oak merge --abort'.")]
245    MergeInProgress,
246
247    /// A working-tree update (pull, sync, reset, ...) was killed part-way and
248    /// its record is still in `.oak/WORKTREE_UPDATE`. `next_commands` are the
249    /// exact recovery invocations.
250    #[error("{message}")]
251    InterruptedWorktreeUpdate {
252        message: String,
253        next_commands: Vec<String>,
254    },
255
256    /// A working-tree transition (branch creation, pull, sync, switch, ...)
257    /// would have overwritten uncommitted work: a path it writes holds
258    /// content that is neither the snapshot it moves from nor the one it
259    /// moves to, or something the user owns is in the way of it. Refused
260    /// before the first write. `paths` is a bounded sample of `(path, why)`;
261    /// `total` counts them all. The message and the next commands are both
262    /// derived from `transition` and `in_the_way`, so they always agree.
263    #[error(
264        "{}",
265        local_changes_message(command, clean_command.as_deref(), *transition, paths, *total, *in_the_way)
266    )]
267    LocalChangesWouldBeOverwritten {
268        /// The refused invocation, shell-quoted, credentials redacted.
269        command: String,
270        /// `command` with `--clean` added, when that is a valid invocation.
271        clean_command: Option<String>,
272        transition: WorktreeTransition,
273        paths: Vec<(String, String)>,
274        total: usize,
275        /// Some path is in the way in a way a commit does not resolve (an
276        /// ignored file, a file/directory obstruction, a name differing only
277        /// in case): it has to be moved aside first.
278        in_the_way: bool,
279    },
280
281    #[error("No merge in progress.")]
282    NoMergeInProgress,
283
284    /// `oak pull --continue` / `--abort` with no paused parent sync.
285    #[error("Merge failed: No sync in progress.")]
286    NoSyncInProgress,
287
288    /// The named branch is the trunk, which exists only on the server and is
289    /// never checked out locally.
290    #[error("IO error: {0}")]
291    TrunkIsServerOnly(String),
292
293    /// No stored credential for `remote`. Nothing was sent.
294    #[error("Not logged in to {remote}. Run `oak login` first.")]
295    NotLoggedIn { remote: String },
296
297    /// The checkout is not linked to a remote repository yet; linking it
298    /// (`oak push --repo ORG/REPO`) is the fix.
299    #[error("Configuration error: {0}")]
300    RepoNotLinked(String),
301
302    /// An `oak feedback` request failed. Feedback keeps its own exit code
303    /// (1) for remote failures; `code` is the closed machine code, and
304    /// `retryable` is set only where the caller knows the answer.
305    #[error("{message}")]
306    FeedbackFailed {
307        message: String,
308        /// The request was malformed and nothing was sent (exit 2).
309        usage: bool,
310        code: ErrorCode,
311        retryable: Option<bool>,
312        next_commands: Vec<String>,
313        /// `oak feedback transition` only: what was sent and its outcome.
314        transition: Option<serde_json::Value>,
315    },
316
317    /// `oak root pull|push` refused before changing anything.
318    #[error("{message}")]
319    RootRefused {
320        reason: RootRefusal,
321        message: String,
322        /// The paths in conflict (`root_conflict`), else empty.
323        paths: Vec<String>,
324        next_commands: Vec<String>,
325    },
326
327    #[error("IO error: {0}")]
328    Io(#[from] std::io::Error),
329
330    #[error("Database error: {0}")]
331    Database(String),
332
333    #[error("Serialization error: {0}")]
334    Serialization(#[from] serde_json::Error),
335
336    #[error("HTTP error: {0}")]
337    Http(String),
338
339    #[error("Server error: {0}")]
340    Server(String),
341
342    #[error(
343        "{operation} outcome is unconfirmed: {reason}. No automatic mutation retry was attempted; inspect remote state read-only before deciding whether to retry."
344    )]
345    PublicationUnconfirmed {
346        operation: String,
347        reason: String,
348        reconciliation_commands: Vec<String>,
349    },
350
351    #[error(
352        "The server at {remote} refused the request with HTTP {status}: {}",
353        if *status == 403 {
354            "the credential is not allowed to do this"
355        } else {
356            "authentication is required. Run `oak login` (or set OAK_API_KEY) and retry"
357        }
358    )]
359    AuthRequired { remote: String, status: u16 },
360
361    #[error("R2 storage error: {0}")]
362    R2(String),
363
364    #[error("Git operation error: {0}")]
365    Git(String),
366
367    #[error("Configuration error: {0}")]
368    Config(String),
369
370    #[error("{0}")]
371    FinishPreflight(Box<FinishPreflightError>),
372
373    #[error("{0}")]
374    FinishPhaseFailed(Box<FinishPhaseError>),
375
376    #[error("{0}")]
377    CommitPhaseFailed(Box<CommitPhaseError>),
378
379    #[error(
380        "Repository is locked by another process. If no other oak process is running, remove the lock file (.oak/wdlock, or .oak/publication-attempts/wdlock while publishing)"
381    )]
382    RepoLocked,
383
384    #[error("Operation '{op}' is not supported by the {backend} backend")]
385    Unsupported {
386        backend: &'static str,
387        op: &'static str,
388    },
389
390    #[error("Group '{0}' not found in this organization")]
391    GroupNotFound(String),
392
393    #[error("{0}")]
394    InvalidArgument(String),
395
396    /// The command line itself was rejected by the argument parser (unknown
397    /// flag, missing value, conflicting flags). Unlike [`InvalidArgument`],
398    /// which is also raised for conditions that can change, this can never
399    /// succeed unchanged.
400    ///
401    /// [`InvalidArgument`]: OakError::InvalidArgument
402    #[error("{0}")]
403    Usage(String),
404
405    /// `oak commit` on a detached HEAD: there is no branch to record onto.
406    #[error("{0}")]
407    DetachedHeadCommit(String),
408
409    /// The server withheld content because a path-based permission rule
410    /// denies this user (an access boundary on the server). Not a data gap —
411    /// the fix is an access grant, not a re-pull. The message names what was
412    /// withheld (paths when known, blob hashes otherwise).
413    #[error("{0}")]
414    RestrictedContent(String),
415
416    /// A read-modify-write of the branch description (`oak desc --append`)
417    /// was refused because the local copy is not a verified image of the
418    /// remote one. Nothing was written locally or remotely. `state` is a
419    /// stable machine label (`pending_local_edit`, `remote_changed`,
420    /// `remote_unverified`); `refresh_commands` are exact commands that bring
421    /// the local copy up to date or let the caller inspect both sides.
422    #[error("{message}")]
423    DescriptionStale {
424        branch: String,
425        state: DescriptionStaleState,
426        message: String,
427        refresh_commands: Vec<String>,
428    },
429
430    /// The approvals gate or `oak approve` refused (`code` says why). Waiting
431    /// never clears it.
432    #[error("{message}")]
433    ApprovalRefused {
434        /// The closed code for the refusal reason.
435        code: ErrorCode,
436        /// The reason exactly as the server sent it, when this client does
437        /// not know it (`code` is then [`ErrorCode::ApprovalRefused`]).
438        server_code: Option<String>,
439        message: String,
440        missing: Vec<MissingApproval>,
441        /// Other boundaries missing an approval, which the caller can't read.
442        hidden: usize,
443        recommended_next_commands: Vec<String>,
444    },
445
446    /// Publication is impossible with the protocols the server advertises
447    /// (for example the push needs `staged_v1` and the server has not
448    /// activated it). A deterministic server-capability refusal, not a usage
449    /// error: retrying unchanged cannot succeed until the server's
450    /// capabilities or the outgoing history change. `message` names the
451    /// measured totals and the limits they exceed and says whether remote
452    /// state was mutated.
453    #[error("{message}")]
454    PushCapabilityUnavailable {
455        message: String,
456        recommended_next_commands: Vec<String>,
457    },
458
459    /// A partial checkout (a view) holds work outside its directories: the
460    /// server would refuse the push, so it's caught before the commit.
461    #[error("{} path(s) outside this checkout's directories (first: {}); add them (`oak sparse add DIR`), or remove them", paths.len(), paths.first().map(String::as_str).unwrap_or_default())]
462    PathOutsideView {
463        paths: Vec<String>,
464        recommended_next_commands: Vec<String>,
465    },
466}
467
468/// An ownership boundary a merge still needs an approval for.
469#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
470pub struct MissingApproval {
471    /// The boundary's directory (`""` is the repo root).
472    pub path: String,
473    /// The team that owns it.
474    pub owner_team: String,
475    /// Who can approve (principals such as `@team/web`); empty when no one can.
476    pub approvers: Vec<String>,
477}
478
479pub type Result<T> = std::result::Result<T, OakError>;
480
481// ---------------------------------------------------------------------------
482// Machine contract vocabulary
483// ---------------------------------------------------------------------------
484
485/// Generates a closed, field-less enum together with its complete `ALL` list
486/// and its stable wire string, from one table. Adding an entry here is the
487/// only way to add a value, so `ALL` can never fall out of sync.
488#[macro_export]
489macro_rules! closed_vocabulary {
490    (
491        $(#[$meta:meta])*
492        $vis:vis enum $name:ident { $( $(#[$vmeta:meta])* $variant:ident => $wire:literal, )+ }
493    ) => {
494        $(#[$meta])*
495        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
496        $vis enum $name { $( $(#[$vmeta])* $variant, )+ }
497
498        impl $name {
499            /// Every value, in declaration order.
500            pub const ALL: &'static [$name] = &[ $( $name::$variant, )+ ];
501
502            /// The stable machine string.
503            pub const fn as_str(self) -> &'static str {
504                match self { $( $name::$variant => $wire, )+ }
505            }
506        }
507
508        impl std::fmt::Display for $name {
509            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510                f.write_str(self.as_str())
511            }
512        }
513
514        impl ::serde::Serialize for $name {
515            fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error> {
516                serializer.serialize_str(self.as_str())
517            }
518        }
519
520        impl PartialEq<str> for $name {
521            fn eq(&self, other: &str) -> bool { self.as_str() == other }
522        }
523
524        impl PartialEq<&str> for $name {
525            fn eq(&self, other: &&str) -> bool { self.as_str() == *other }
526        }
527    };
528}
529
530closed_vocabulary! {
531    /// The closed set of `error.code` values a `--json` failure can carry.
532    ///
533    /// Codes are append-only: a string, once shipped, is never renamed or
534    /// reused for a different condition. There is deliberately no generic
535    /// member (`error`, `unknown`): a new failure needs a new code here, and
536    /// the CLI's one exhaustive `OakError` mapping (`oak_cli::contract`)
537    /// will not compile until it names one.
538    ///
539    /// `RemoteError` is the only deliberately coarse member: a failure
540    /// reported by, or while talking to, the remote that has not been
541    /// classified further. Classified remote conditions (connection refused,
542    /// rate limited, not found, ...) get their own entries.
543    pub enum ErrorCode {
544        // Usage and configuration.
545        InvalidArgument => "invalid_argument",
546        InvalidHash => "invalid_hash",
547        ConfigurationError => "configuration_error",
548        Unsupported => "unsupported",
549        // Local repository state.
550        RepoNotFound => "repo_not_found",
551        RepoAlreadyExists => "repo_already_exists",
552        RepoLocked => "repo_locked",
553        NoCommits => "no_commits",
554        NoEdits => "no_edits",
555        BranchNotFound => "branch_not_found",
556        BranchAlreadyExists => "branch_already_exists",
557        BranchClosed => "branch_closed",
558        BranchIsServerOnly => "branch_is_server_only",
559        CommitNotFound => "commit_not_found",
560        BlobNotFound => "blob_not_found",
561        ManifestNotFound => "manifest_not_found",
562        GroupNotFound => "group_not_found",
563        RestrictedContent => "restricted_content",
564        // Local machine.
565        DiskFull => "disk_full",
566        IoError => "io_error",
567        DatabaseError => "database_error",
568        SerializationError => "serialization_error",
569        GitError => "git_error",
570        // Working tree.
571        DirtyWorktree => "dirty_worktree",
572        InterruptedWorktreeUpdate => "interrupted_worktree_update",
573        PathOutsideView => "path_outside_view",
574        LocalChangesWouldBeOverwritten => "local_changes_would_be_overwritten",
575        // Change capture.
576        WorktreeCaptureRaced => "worktree_capture_raced",
577        CapturedBlobIntegrity => "captured_blob_integrity",
578        CapturedTreeIntegrity => "captured_tree_integrity",
579        ChangeCaptureNotFound => "change_capture_not_found",
580        ChangeCaptureIntegrity => "change_capture_integrity",
581        CaptureScopeExcluded => "capture_scope_excluded",
582        // History, merges and conflicts.
583        ConflictDetected => "conflict_detected",
584        MergeInProgress => "merge_in_progress",
585        NoMergeInProgress => "no_merge_in_progress",
586        NoSyncInProgress => "no_sync_in_progress",
587        MergeFailed => "merge_failed",
588        MergeInvariantViolation => "merge_invariant_violation",
589        MergePredictionUncertified => "merge_prediction_uncertified",
590        LocalCommitsNotInRemoteHistory => "local_commits_not_in_remote_history",
591        RemoteCommitsNotInLocalHistory => "remote_commits_not_in_local_history",
592        IncompleteAncestry => "incomplete_ancestry",
593        IncompleteManifestData => "incomplete_manifest_data",
594        IncompleteCommitData => "incomplete_commit_data",
595        IncompleteBlobData => "incomplete_blob_data",
596        NoVerifiedCommonAncestor => "no_verified_common_ancestor",
597        // Remote access.
598        RemoteError => "remote_error",
599        RemoteMoved => "remote_moved",
600        RemoteRepoNotFound => "remote_repo_not_found",
601        RemoteRepoAlreadyExists => "remote_repo_already_exists",
602        AuthRequired => "auth_required",
603        AuthDenied => "auth_denied",
604        PublicationUnconfirmed => "publication_unconfirmed",
605        PushCapabilityUnavailable => "push_capability_unavailable",
606        IntegrityInconclusive => "integrity_inconclusive",
607        IntegrityAdmissionBusy => "integrity_admission_busy",
608        CloneAdmissionTokenTooLarge => "clone_admission_token_too_large",
609        // Multi-phase commands.
610        FinishPreflightFailed => "finish_preflight_failed",
611        FinishPhaseFailed => "finish_phase_failed",
612        CommitPhaseFailed => "commit_phase_failed",
613        DescriptionStale => "description_stale",
614        // Approvals.
615        ApprovalsRequired => "approvals_required",
616        ApprovalRefused => "approval_refused",
617        ReviewKeyRequired => "review_key_required",
618        BranchMoved => "branch_moved",
619        SelfApproval => "self_approval",
620        NotAnOwner => "not_an_owner",
621        NothingToApprove => "nothing_to_approve",
622        BoundaryNotTouched => "boundary_not_touched",
623        BoundaryOutsideView => "boundary_outside_view",
624        ServiceAccount => "service_account",
625        ApprovalInternal => "internal",
626        ApprovalNotFound => "not_found",
627        View => "view",
628        // `oak root pull|push`.
629        RootConflict => "root_conflict",
630        PullRequired => "pull_required",
631        HeadMoved => "head_moved",
632        // `oak feedback transition` (keeps its own exit codes).
633        FeedbackTransitionPreflightFailed => "feedback_transition_preflight_failed",
634        FeedbackTransitionUnavailable => "feedback_transition_unavailable",
635        FeedbackTransitionUnconfirmed => "feedback_transition_unconfirmed",
636        FeedbackTransitionRejected => "feedback_transition_rejected",
637        FeedbackTransitionOutputFailed => "feedback_transition_output_failed",
638        FeedbackCapabilityRequestFailed => "feedback_capability_request_failed",
639        FeedbackCapabilityUnauthorized => "feedback_capability_unauthorized",
640        FeedbackCapabilityUnavailable => "feedback_capability_unavailable",
641        FeedbackCapabilityRedirect => "feedback_capability_redirect",
642        FeedbackCapabilityInvalid => "feedback_capability_invalid",
643        FeedbackCapabilityUnsupported => "feedback_capability_unsupported",
644        RevisionConflict => "revision_conflict",
645    }
646}
647
648closed_vocabulary! {
649    /// Why `oak finish` refused before mutating anything
650    /// (`error.finish.blocker`).
651    pub enum FinishBlocker {
652        InvalidDescription => "invalid_description",
653        MergeInProgress => "merge_in_progress",
654        SyncInProgress => "sync_in_progress",
655        NoCurrentBranch => "no_current_branch",
656        BranchNotFound => "branch_not_found",
657        BranchClosed => "branch_closed",
658        RemoteNotConfigured => "remote_not_configured",
659        RemoteIdentityMissing => "remote_identity_missing",
660        AuthMissing => "auth_missing",
661        AuthFailed => "auth_failed",
662        RemoteRepoMissing => "remote_repo_missing",
663        RemoteUnreachable => "remote_unreachable",
664    }
665}
666
667closed_vocabulary! {
668    /// Why `oak desc --append` refused (`error.state`).
669    pub enum DescriptionStaleState {
670        PendingLocalEdit => "pending_local_edit",
671        RemoteChanged => "remote_changed",
672        RemoteUnverified => "remote_unverified",
673        LocalChanged => "local_changed",
674    }
675}
676
677closed_vocabulary! {
678    /// Why `oak root pull|push` refused; the wire string is the error code.
679    pub enum RootRefusal {
680        Conflict => "root_conflict",
681        PullRequired => "pull_required",
682        HeadMoved => "head_moved",
683    }
684}
685
686/// Which kind of working-tree transition refused with
687/// [`OakError::LocalChangesWouldBeOverwritten`]: what resolves the refusal
688/// depends on it. Set by the command that knows (the planner raises
689/// [`WorktreeTransition::Other`]).
690#[derive(Clone, Copy, Debug, PartialEq, Eq)]
691pub enum WorktreeTransition {
692    /// `oak pull` (parent sync), and the watch daemon's pull.
693    Pull,
694    /// `oak switch -c` / `oak start`: a new branch from the newer main.
695    CreateBranch,
696    /// Anything else that moves the tree.
697    Other,
698}
699
700fn local_changes_message(
701    command: &str,
702    clean_command: Option<&str>,
703    transition: WorktreeTransition,
704    paths: &[(String, String)],
705    total: usize,
706    in_the_way: bool,
707) -> String {
708    let mut message = format!(
709        "`{command}` would overwrite or remove local work in {total} path(s), so nothing was \
710         changed:"
711    );
712    for (path, why) in paths {
713        message.push_str(&format!("\n  {path} ({why})"));
714    }
715    if total > paths.len() {
716        message.push_str(&format!("\n  ... and {} more", total - paths.len()));
717    }
718    if in_the_way {
719        message.push_str(&format!(
720            "\nMove these out of the way (rename, move or delete them; a commit does not \
721             resolve this), then run `{command}` again."
722        ));
723        return message;
724    }
725    match transition {
726        WorktreeTransition::Pull => message.push_str(
727            "\nCommit them (`oak commit`) and run `oak pull` again: main is then merged into \
728             this branch, and a path changed on both sides is reported as a conflict to resolve \
729             instead of being overwritten.",
730        ),
731        WorktreeTransition::CreateBranch => {
732            message.push_str(
733                "\nThe new branch starts from the newer main, which has different content at \
734                 these paths than your uncommitted version. Either:\n  - keep your changes on \
735                 the current branch and merge main into it: `oak commit`, then `oak pull` (a \
736                 path changed on both sides is reported as a conflict to resolve); or",
737            );
738            match clean_command {
739                Some(clean) => message.push_str(&format!(
740                    "\n  - create the branch without them: `{clean}` (DISCARDS these \
741                     uncommitted changes)."
742                )),
743                None => message.push_str(&format!(
744                    "\n  - create the branch without them: run `{command}` with `--clean` \
745                     (DISCARDS these uncommitted changes)."
746                )),
747            }
748        }
749        WorktreeTransition::Other => message.push_str(&format!(
750            "\nCommit them (`oak commit`) or move them aside, then run `{command}` again."
751        )),
752    }
753    message
754}
755
756impl ErrorCode {
757    /// The code for an approval refusal reason sent by the server
758    /// (`oak-web` `api/approvals.rs`) or raised by this client. Every reason
759    /// the server emits keeps its exact string; a reason from a newer server
760    /// is `None` and is reported as `approval_refused` plus `server_code`.
761    pub fn from_approval_reason(reason: &str) -> Option<ErrorCode> {
762        Self::APPROVAL_REASONS
763            .iter()
764            .copied()
765            .find(|code| code.as_str() == reason)
766    }
767
768    /// Every approval refusal reason this client knows.
769    pub const APPROVAL_REASONS: &'static [ErrorCode] = &[
770        // Raised by the client.
771        ErrorCode::ApprovalsRequired,
772        ErrorCode::ApprovalRefused,
773        // The server's table.
774        ErrorCode::BoundaryNotTouched,
775        ErrorCode::BoundaryOutsideView,
776        ErrorCode::BranchClosed,
777        ErrorCode::BranchMoved,
778        ErrorCode::ApprovalInternal,
779        ErrorCode::NotAnOwner,
780        ErrorCode::ApprovalNotFound,
781        ErrorCode::NothingToApprove,
782        ErrorCode::ReviewKeyRequired,
783        ErrorCode::SelfApproval,
784        ErrorCode::ServiceAccount,
785        ErrorCode::View,
786    ];
787}
788
789/// The CLI exit-code table (`oak --help`). Closed: a failure exits with one
790/// of these and nothing else; `0` is success and is not a member.
791#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
792pub enum ExitCode {
793    /// 1 — a failure with no more specific class.
794    Failure,
795    /// 2 — the invocation itself is wrong.
796    Usage,
797    /// 3 — the repository is locked by another process (retry).
798    Locked,
799    /// 4 — the working tree blocked the operation.
800    WorktreeBlocked,
801    /// 5 — a merge/sync conflict or an in-progress conflict state.
802    Conflict,
803    /// 6 — network, server, or authentication failure.
804    Remote,
805    /// 7 — merge prediction uncertified.
806    MergeUncertified,
807    /// 8 — integrity proof inconclusive.
808    IntegrityInconclusive,
809}
810
811impl ExitCode {
812    pub const ALL: &'static [ExitCode] = &[
813        ExitCode::Failure,
814        ExitCode::Usage,
815        ExitCode::Locked,
816        ExitCode::WorktreeBlocked,
817        ExitCode::Conflict,
818        ExitCode::Remote,
819        ExitCode::MergeUncertified,
820        ExitCode::IntegrityInconclusive,
821    ];
822
823    pub const fn code(self) -> i32 {
824        match self {
825            ExitCode::Failure => 1,
826            ExitCode::Usage => 2,
827            ExitCode::Locked => 3,
828            ExitCode::WorktreeBlocked => 4,
829            ExitCode::Conflict => 5,
830            ExitCode::Remote => 6,
831            ExitCode::MergeUncertified => 7,
832            ExitCode::IntegrityInconclusive => 8,
833        }
834    }
835}
836
837closed_vocabulary! {
838    /// One member per [`OakError`] variant, so tests can enumerate the
839    /// variants and prove a property holds for every one of them.
840    /// [`OakError::kind`] is an exhaustive match, so adding an `OakError`
841    /// variant without adding its kind here does not compile.
842    pub enum OakErrorKind {
843        DiskFull => "DiskFull",
844        RepoNotFound => "RepoNotFound",
845        RepoAlreadyExists => "RepoAlreadyExists",
846        NoCommits => "NoCommits",
847        InvalidHash => "InvalidHash",
848        InvalidPath => "InvalidPath",
849        BlobNotFound => "BlobNotFound",
850        CommitNotFound => "CommitNotFound",
851        BranchNotFound => "BranchNotFound",
852        BranchAlreadyExists => "BranchAlreadyExists",
853        BranchClosed => "BranchClosed",
854        NoEdits => "NoEdits",
855        ManifestNotFound => "ManifestNotFound",
856        UncommittedChanges => "UncommittedChanges",
857        WorktreeCaptureRaced => "WorktreeCaptureRaced",
858        UnsupportedChangeCaptureFormat => "UnsupportedChangeCaptureFormat",
859        ChangeCaptureScopeExcluded => "ChangeCaptureScopeExcluded",
860        CapturedBlobIntegrity => "CapturedBlobIntegrity",
861        CapturedTreeIntegrity => "CapturedTreeIntegrity",
862        ChangeCaptureNotFound => "ChangeCaptureNotFound",
863        ChangeCaptureIntegrity => "ChangeCaptureIntegrity",
864        DirtyWorkingTree => "DirtyWorkingTree",
865        ConflictDetected => "ConflictDetected",
866        LocalCommitsNotInRemoteHistory => "LocalCommitsNotInRemoteHistory",
867        RemoteCommitsNotInLocalHistory => "RemoteCommitsNotInLocalHistory",
868        RemoteNotConfigured => "RemoteNotConfigured",
869        RemoteMoved => "RemoteMoved",
870        RemoteRepoNotFound => "RemoteRepoNotFound",
871        RemoteRepoAlreadyExists => "RemoteRepoAlreadyExists",
872        MergeFailed => "MergeFailed",
873        IncompleteAncestry => "IncompleteAncestry",
874        IncompleteManifestData => "IncompleteManifestData",
875        IncompleteCommitData => "IncompleteCommitData",
876        IncompleteBlobData => "IncompleteBlobData",
877        NoVerifiedCommonAncestor => "NoVerifiedCommonAncestor",
878        MergeConflict => "MergeConflict",
879        MergeInvariantViolation => "MergeInvariantViolation",
880        MergePredictionUncertified => "MergePredictionUncertified",
881        IntegrityInconclusive => "IntegrityInconclusive",
882        CloneAdmissionTokenTooLarge => "CloneAdmissionTokenTooLarge",
883        IntegrityAdmissionBusy => "IntegrityAdmissionBusy",
884        MergeInProgress => "MergeInProgress",
885        InterruptedWorktreeUpdate => "InterruptedWorktreeUpdate",
886        NoMergeInProgress => "NoMergeInProgress",
887        Io => "Io",
888        Database => "Database",
889        Serialization => "Serialization",
890        Http => "Http",
891        Server => "Server",
892        PublicationUnconfirmed => "PublicationUnconfirmed",
893        AuthRequired => "AuthRequired",
894        R2 => "R2",
895        Git => "Git",
896        Config => "Config",
897        FinishPreflight => "FinishPreflight",
898        FinishPhaseFailed => "FinishPhaseFailed",
899        CommitPhaseFailed => "CommitPhaseFailed",
900        RepoLocked => "RepoLocked",
901        Unsupported => "Unsupported",
902        GroupNotFound => "GroupNotFound",
903        InvalidArgument => "InvalidArgument",
904        Usage => "Usage",
905        DetachedHeadCommit => "DetachedHeadCommit",
906        NoSyncInProgress => "NoSyncInProgress",
907        TrunkIsServerOnly => "TrunkIsServerOnly",
908        NotLoggedIn => "NotLoggedIn",
909        RepoNotLinked => "RepoNotLinked",
910        FeedbackFailed => "FeedbackFailed",
911        RootRefused => "RootRefused",
912        RestrictedContent => "RestrictedContent",
913        DescriptionStale => "DescriptionStale",
914        ApprovalRefused => "ApprovalRefused",
915        PushCapabilityUnavailable => "PushCapabilityUnavailable",
916        PathOutsideView => "PathOutsideView",
917        LocalChangesWouldBeOverwritten => "LocalChangesWouldBeOverwritten",
918    }
919}
920
921impl OakError {
922    /// Name the transition a [`OakError::LocalChangesWouldBeOverwritten`]
923    /// refused, so its message and next commands fit it. Any other error is
924    /// returned unchanged.
925    pub fn in_transition(mut self, kind: WorktreeTransition) -> Self {
926        if let OakError::LocalChangesWouldBeOverwritten { transition, .. } = &mut self {
927            *transition = kind;
928        }
929        self
930    }
931
932    /// Which variant this is. Exhaustive on purpose (no wildcard arm).
933    pub fn kind(&self) -> OakErrorKind {
934        match self {
935            OakError::DiskFull { .. } => OakErrorKind::DiskFull,
936            OakError::RepoNotFound => OakErrorKind::RepoNotFound,
937            OakError::RepoAlreadyExists => OakErrorKind::RepoAlreadyExists,
938            OakError::NoCommits => OakErrorKind::NoCommits,
939            OakError::InvalidHash(_) => OakErrorKind::InvalidHash,
940            OakError::InvalidPath(_) => OakErrorKind::InvalidPath,
941            OakError::BlobNotFound(_) => OakErrorKind::BlobNotFound,
942            OakError::CommitNotFound(_) => OakErrorKind::CommitNotFound,
943            OakError::BranchNotFound(_) => OakErrorKind::BranchNotFound,
944            OakError::BranchAlreadyExists(_) => OakErrorKind::BranchAlreadyExists,
945            OakError::BranchClosed(_) => OakErrorKind::BranchClosed,
946            OakError::NoEdits => OakErrorKind::NoEdits,
947            OakError::ManifestNotFound(_) => OakErrorKind::ManifestNotFound,
948            OakError::UncommittedChanges => OakErrorKind::UncommittedChanges,
949            OakError::WorktreeCaptureRaced { .. } => OakErrorKind::WorktreeCaptureRaced,
950            OakError::UnsupportedChangeCaptureFormat(_) => {
951                OakErrorKind::UnsupportedChangeCaptureFormat
952            }
953            OakError::ChangeCaptureScopeExcluded { .. } => OakErrorKind::ChangeCaptureScopeExcluded,
954            OakError::CapturedBlobIntegrity { .. } => OakErrorKind::CapturedBlobIntegrity,
955            OakError::CapturedTreeIntegrity { .. } => OakErrorKind::CapturedTreeIntegrity,
956            OakError::ChangeCaptureNotFound { .. } => OakErrorKind::ChangeCaptureNotFound,
957            OakError::ChangeCaptureIntegrity { .. } => OakErrorKind::ChangeCaptureIntegrity,
958            OakError::DirtyWorkingTree(_) => OakErrorKind::DirtyWorkingTree,
959            OakError::ConflictDetected => OakErrorKind::ConflictDetected,
960            OakError::LocalCommitsNotInRemoteHistory => {
961                OakErrorKind::LocalCommitsNotInRemoteHistory
962            }
963            OakError::RemoteCommitsNotInLocalHistory => {
964                OakErrorKind::RemoteCommitsNotInLocalHistory
965            }
966            OakError::RemoteNotConfigured => OakErrorKind::RemoteNotConfigured,
967            OakError::RemoteMoved { .. } => OakErrorKind::RemoteMoved,
968            OakError::RemoteRepoNotFound(_) => OakErrorKind::RemoteRepoNotFound,
969            OakError::RemoteRepoAlreadyExists(_) => OakErrorKind::RemoteRepoAlreadyExists,
970            OakError::MergeFailed(_) => OakErrorKind::MergeFailed,
971            OakError::IncompleteAncestry { .. } => OakErrorKind::IncompleteAncestry,
972            OakError::IncompleteManifestData { .. } => OakErrorKind::IncompleteManifestData,
973            OakError::IncompleteCommitData { .. } => OakErrorKind::IncompleteCommitData,
974            OakError::IncompleteBlobData { .. } => OakErrorKind::IncompleteBlobData,
975            OakError::NoVerifiedCommonAncestor { .. } => OakErrorKind::NoVerifiedCommonAncestor,
976            OakError::MergeConflict(_) => OakErrorKind::MergeConflict,
977            OakError::MergeInvariantViolation { .. } => OakErrorKind::MergeInvariantViolation,
978            OakError::MergePredictionUncertified { .. } => OakErrorKind::MergePredictionUncertified,
979            OakError::IntegrityInconclusive { .. } => OakErrorKind::IntegrityInconclusive,
980            OakError::CloneAdmissionTokenTooLarge { .. } => {
981                OakErrorKind::CloneAdmissionTokenTooLarge
982            }
983            OakError::IntegrityAdmissionBusy(_) => OakErrorKind::IntegrityAdmissionBusy,
984            OakError::MergeInProgress => OakErrorKind::MergeInProgress,
985            OakError::InterruptedWorktreeUpdate { .. } => OakErrorKind::InterruptedWorktreeUpdate,
986            OakError::LocalChangesWouldBeOverwritten { .. } => {
987                OakErrorKind::LocalChangesWouldBeOverwritten
988            }
989            OakError::NoMergeInProgress => OakErrorKind::NoMergeInProgress,
990            OakError::Io(_) => OakErrorKind::Io,
991            OakError::Database(_) => OakErrorKind::Database,
992            OakError::Serialization(_) => OakErrorKind::Serialization,
993            OakError::Http(_) => OakErrorKind::Http,
994            OakError::Server(_) => OakErrorKind::Server,
995            OakError::PublicationUnconfirmed { .. } => OakErrorKind::PublicationUnconfirmed,
996            OakError::AuthRequired { .. } => OakErrorKind::AuthRequired,
997            OakError::R2(_) => OakErrorKind::R2,
998            OakError::Git(_) => OakErrorKind::Git,
999            OakError::Config(_) => OakErrorKind::Config,
1000            OakError::FinishPreflight(_) => OakErrorKind::FinishPreflight,
1001            OakError::FinishPhaseFailed(_) => OakErrorKind::FinishPhaseFailed,
1002            OakError::CommitPhaseFailed(_) => OakErrorKind::CommitPhaseFailed,
1003            OakError::RepoLocked => OakErrorKind::RepoLocked,
1004            OakError::Unsupported { .. } => OakErrorKind::Unsupported,
1005            OakError::GroupNotFound(_) => OakErrorKind::GroupNotFound,
1006            OakError::InvalidArgument(_) => OakErrorKind::InvalidArgument,
1007            OakError::Usage(_) => OakErrorKind::Usage,
1008            OakError::DetachedHeadCommit(_) => OakErrorKind::DetachedHeadCommit,
1009            OakError::NoSyncInProgress => OakErrorKind::NoSyncInProgress,
1010            OakError::TrunkIsServerOnly(_) => OakErrorKind::TrunkIsServerOnly,
1011            OakError::NotLoggedIn { .. } => OakErrorKind::NotLoggedIn,
1012            OakError::RepoNotLinked(_) => OakErrorKind::RepoNotLinked,
1013            OakError::FeedbackFailed { .. } => OakErrorKind::FeedbackFailed,
1014            OakError::RootRefused { .. } => OakErrorKind::RootRefused,
1015            OakError::RestrictedContent(_) => OakErrorKind::RestrictedContent,
1016            OakError::DescriptionStale { .. } => OakErrorKind::DescriptionStale,
1017            OakError::ApprovalRefused { .. } => OakErrorKind::ApprovalRefused,
1018            OakError::PushCapabilityUnavailable { .. } => OakErrorKind::PushCapabilityUnavailable,
1019            OakError::PathOutsideView { .. } => OakErrorKind::PathOutsideView,
1020        }
1021    }
1022}
1023
1024#[cfg(test)]
1025mod contract_vocabulary_tests {
1026    use super::*;
1027    use std::collections::HashSet;
1028
1029    #[test]
1030    fn error_codes_are_unique_specific_snake_case() {
1031        let mut seen = HashSet::new();
1032        for code in ErrorCode::ALL {
1033            let wire = code.as_str();
1034            assert!(seen.insert(wire), "duplicate error code {wire}");
1035            assert!(
1036                !matches!(wire, "error" | "generic" | "unknown" | "failure" | "failed"),
1037                "{wire} is a generic code; every failure needs a specific one"
1038            );
1039            assert!(
1040                wire.chars().all(|c| c.is_ascii_lowercase() || c == '_'),
1041                "{wire} is not snake_case"
1042            );
1043        }
1044    }
1045
1046    /// The server's approval refusal codes (oakspace
1047    /// `crates/oak-web/src/server/api/approvals.rs`, every `err(_, CODE, _)`
1048    /// and `code:`), pinned: each must pass through with its exact string.
1049    #[test]
1050    fn every_server_approval_reason_keeps_its_exact_code() {
1051        const SERVER_TABLE: &[&str] = &[
1052            "boundary_not_touched",
1053            "boundary_outside_view",
1054            "branch_closed",
1055            "branch_moved",
1056            "internal",
1057            "not_an_owner",
1058            "not_found",
1059            "nothing_to_approve",
1060            "review_key_required",
1061            "self_approval",
1062            "service_account",
1063            "view",
1064        ];
1065        for reason in SERVER_TABLE {
1066            assert_eq!(
1067                ErrorCode::from_approval_reason(reason).map(ErrorCode::as_str),
1068                Some(*reason)
1069            );
1070        }
1071        assert_eq!(
1072            ErrorCode::from_approval_reason("approvals_required"),
1073            Some(ErrorCode::ApprovalsRequired)
1074        );
1075        assert_eq!(
1076            ErrorCode::from_approval_reason("a_newer_servers_reason"),
1077            None
1078        );
1079    }
1080
1081    #[test]
1082    fn exit_codes_are_the_documented_table() {
1083        let codes: Vec<i32> = ExitCode::ALL.iter().map(|code| code.code()).collect();
1084        assert_eq!(codes, vec![1, 2, 3, 4, 5, 6, 7, 8]);
1085    }
1086
1087    #[test]
1088    fn every_kind_is_listed_once() {
1089        let unique: HashSet<_> = OakErrorKind::ALL.iter().collect();
1090        assert_eq!(unique.len(), OakErrorKind::ALL.len());
1091    }
1092}