1use std::path::PathBuf;
11use thiserror::Error;
12
13pub type Result<T> = std::result::Result<T, Error>;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ErrorCode {
24 NotInitialized,
26 AlreadyInitialized,
27 DatabaseError,
28
29 SessionNotFound,
31 IssueNotFound,
32 CheckpointNotFound,
33 ProjectNotFound,
34 NoActiveSession,
35 AmbiguousId,
36
37 InvalidStatus,
39 InvalidType,
40 InvalidPriority,
41 InvalidArgument,
42 InvalidSessionStatus,
43 RequiredField,
44
45 CycleDetected,
47 HasDependents,
48
49 SyncError,
51
52 ConfigError,
54
55 IoError,
57 JsonError,
58
59 EmbeddingError,
61
62 InternalError,
64}
65
66impl ErrorCode {
67 #[must_use]
69 pub const fn as_str(&self) -> &str {
70 match self {
71 Self::NotInitialized => "NOT_INITIALIZED",
72 Self::AlreadyInitialized => "ALREADY_INITIALIZED",
73 Self::DatabaseError => "DATABASE_ERROR",
74 Self::SessionNotFound => "SESSION_NOT_FOUND",
75 Self::IssueNotFound => "ISSUE_NOT_FOUND",
76 Self::CheckpointNotFound => "CHECKPOINT_NOT_FOUND",
77 Self::ProjectNotFound => "PROJECT_NOT_FOUND",
78 Self::NoActiveSession => "NO_ACTIVE_SESSION",
79 Self::AmbiguousId => "AMBIGUOUS_ID",
80 Self::InvalidStatus => "INVALID_STATUS",
81 Self::InvalidType => "INVALID_TYPE",
82 Self::InvalidPriority => "INVALID_PRIORITY",
83 Self::InvalidArgument => "INVALID_ARGUMENT",
84 Self::InvalidSessionStatus => "INVALID_SESSION_STATUS",
85 Self::RequiredField => "REQUIRED_FIELD",
86 Self::CycleDetected => "CYCLE_DETECTED",
87 Self::HasDependents => "HAS_DEPENDENTS",
88 Self::SyncError => "SYNC_ERROR",
89 Self::ConfigError => "CONFIG_ERROR",
90 Self::IoError => "IO_ERROR",
91 Self::JsonError => "JSON_ERROR",
92 Self::EmbeddingError => "EMBEDDING_ERROR",
93 Self::InternalError => "INTERNAL_ERROR",
94 }
95 }
96
97 #[must_use]
99 pub const fn exit_code(&self) -> u8 {
100 match self {
101 Self::InternalError => 1,
102 Self::NotInitialized | Self::AlreadyInitialized | Self::DatabaseError => 2,
103 Self::SessionNotFound
104 | Self::IssueNotFound
105 | Self::CheckpointNotFound
106 | Self::ProjectNotFound
107 | Self::NoActiveSession
108 | Self::AmbiguousId => 3,
109 Self::InvalidStatus
110 | Self::InvalidType
111 | Self::InvalidPriority
112 | Self::InvalidArgument
113 | Self::InvalidSessionStatus
114 | Self::RequiredField => 4,
115 Self::CycleDetected | Self::HasDependents => 5,
116 Self::SyncError => 6,
117 Self::ConfigError => 7,
118 Self::IoError | Self::JsonError => 8,
119 Self::EmbeddingError => 9,
120 }
121 }
122
123 #[must_use]
128 pub const fn is_retryable(&self) -> bool {
129 matches!(
130 self,
131 Self::InvalidStatus
132 | Self::InvalidType
133 | Self::InvalidPriority
134 | Self::InvalidArgument
135 | Self::InvalidSessionStatus
136 | Self::RequiredField
137 | Self::AmbiguousId
138 | Self::DatabaseError
139 )
140 }
141}
142
143#[derive(Error, Debug)]
147pub enum Error {
148 #[error("Not initialized: run `sc init` first")]
149 NotInitialized,
150
151 #[error("Already initialized at {path}")]
152 AlreadyInitialized { path: PathBuf },
153
154 #[error("Session not found: {id}")]
155 SessionNotFound { id: String },
156
157 #[error("Session not found: {id} (did you mean: {}?)", similar.join(", "))]
158 SessionNotFoundSimilar { id: String, similar: Vec<String> },
159
160 #[error("No active session")]
161 NoActiveSession,
162
163 #[error("No active session (recent sessions available)")]
164 NoActiveSessionWithRecent {
165 recent: Vec<(String, String, String)>,
167 },
168
169 #[error("Invalid session status: expected {expected}, got {actual}")]
170 InvalidSessionStatus { expected: String, actual: String },
171
172 #[error("Issue not found: {id}")]
173 IssueNotFound { id: String },
174
175 #[error("Issue not found: {id} (did you mean: {}?)", similar.join(", "))]
176 IssueNotFoundSimilar { id: String, similar: Vec<String> },
177
178 #[error("Checkpoint not found: {id}")]
179 CheckpointNotFound { id: String },
180
181 #[error("Checkpoint not found: {id} (did you mean: {}?)", similar.join(", "))]
182 CheckpointNotFoundSimilar { id: String, similar: Vec<String> },
183
184 #[error("Project not found: {id}")]
185 ProjectNotFound { id: String },
186
187 #[error("Database error: {0}")]
188 Database(#[from] rusqlite::Error),
189
190 #[error("IO error: {0}")]
191 Io(#[from] std::io::Error),
192
193 #[error("JSON error: {0}")]
194 Json(#[from] serde_json::Error),
195
196 #[error("Invalid argument: {0}")]
197 InvalidArgument(String),
198
199 #[error("Configuration error: {0}")]
200 Config(String),
201
202 #[error("Embedding error: {0}")]
203 Embedding(String),
204
205 #[error("{0}")]
206 Other(String),
207}
208
209impl Error {
210 #[must_use]
212 pub const fn error_code(&self) -> ErrorCode {
213 match self {
214 Self::NotInitialized => ErrorCode::NotInitialized,
215 Self::AlreadyInitialized { .. } => ErrorCode::AlreadyInitialized,
216 Self::Database(_) => ErrorCode::DatabaseError,
217 Self::SessionNotFound { .. } | Self::SessionNotFoundSimilar { .. } => {
218 ErrorCode::SessionNotFound
219 }
220 Self::IssueNotFound { .. } | Self::IssueNotFoundSimilar { .. } => {
221 ErrorCode::IssueNotFound
222 }
223 Self::CheckpointNotFound { .. } | Self::CheckpointNotFoundSimilar { .. } => {
224 ErrorCode::CheckpointNotFound
225 }
226 Self::ProjectNotFound { .. } => ErrorCode::ProjectNotFound,
227 Self::NoActiveSession | Self::NoActiveSessionWithRecent { .. } => {
228 ErrorCode::NoActiveSession
229 }
230 Self::InvalidSessionStatus { .. } => ErrorCode::InvalidSessionStatus,
231 Self::InvalidArgument(_) => ErrorCode::InvalidArgument,
232 Self::Config(_) => ErrorCode::ConfigError,
233 Self::Embedding(_) => ErrorCode::EmbeddingError,
234 Self::Io(_) => ErrorCode::IoError,
235 Self::Json(_) => ErrorCode::JsonError,
236 Self::Other(_) => ErrorCode::InternalError,
237 }
238 }
239
240 #[must_use]
242 pub const fn exit_code(&self) -> u8 {
243 self.error_code().exit_code()
244 }
245
246 #[must_use]
250 pub fn hint(&self) -> Option<String> {
251 match self {
252 Self::NotInitialized => Some("Run `sc init` to initialize the database".to_string()),
253
254 Self::AlreadyInitialized { path } => Some(format!(
255 "Database already exists at {}. Use `--force` to reinitialize.",
256 path.display()
257 )),
258
259 Self::NoActiveSession => Some(
260 "No session bound to this terminal.\n \
261 Resume: sc session resume <session-id>\n \
262 Start: sc session start \"session name\""
263 .to_string(),
264 ),
265
266 Self::NoActiveSessionWithRecent { recent } => {
267 let mut hint = String::from("Recent sessions you can resume:\n");
268 for (id, name, status) in recent {
269 hint.push_str(&format!(" {id} \"{name}\" ({status})\n"));
270 }
271 hint.push_str(" Resume: sc session resume <session-id>\n");
272 hint.push_str(" Start: sc session start \"session name\"");
273 Some(hint)
274 }
275
276 Self::SessionNotFound { id } => Some(format!(
277 "No session with ID '{id}'. Use `sc session list` to see available sessions."
278 )),
279 Self::SessionNotFoundSimilar { similar, .. } => {
280 Some(format!("Did you mean: {}?", similar.join(", ")))
281 }
282
283 Self::IssueNotFound { id } => Some(format!(
284 "No issue with ID '{id}'. Use `sc issue list` to see available issues."
285 )),
286 Self::IssueNotFoundSimilar { similar, .. } => {
287 Some(format!("Did you mean: {}?", similar.join(", ")))
288 }
289
290 Self::CheckpointNotFound { id } => Some(format!(
291 "No checkpoint with ID '{id}'. Use `sc checkpoint list` to see available checkpoints."
292 )),
293 Self::CheckpointNotFoundSimilar { similar, .. } => {
294 Some(format!("Did you mean: {}?", similar.join(", ")))
295 }
296
297 Self::ProjectNotFound { id } => Some(format!(
298 "No project with ID '{id}'. Use `sc project list` to see available projects."
299 )),
300
301 Self::InvalidSessionStatus { expected, actual } => Some(format!(
302 "Session is '{actual}' but needs to be '{expected}'. \
303 Use `sc session list` to check session states."
304 )),
305
306 Self::InvalidArgument(msg) => {
307 if msg.contains("status") {
309 Some(
310 "Valid statuses: backlog, open, in_progress, blocked, closed, deferred. \
311 Synonyms: done→closed, wip→in_progress, todo→open"
312 .to_string(),
313 )
314 } else if msg.contains("type") {
315 Some(
316 "Valid types: task, bug, feature, epic, chore. \
317 Synonyms: story→feature, defect→bug, cleanup→chore"
318 .to_string(),
319 )
320 } else if msg.contains("priority") {
321 Some(
322 "Valid priorities: 0-4, P0-P4, or names: critical, high, medium, low, backlog"
323 .to_string(),
324 )
325 } else {
326 None
327 }
328 }
329
330 Self::Database(_) | Self::Io(_) | Self::Json(_) | Self::Config(_)
331 | Self::Embedding(_) | Self::Other(_) => None,
332 }
333 }
334
335 #[must_use]
340 pub fn to_structured_json(&self) -> serde_json::Value {
341 let code = self.error_code();
342 let mut obj = serde_json::json!({
343 "error": {
344 "code": code.as_str(),
345 "message": self.to_string(),
346 "retryable": code.is_retryable(),
347 "exit_code": code.exit_code(),
348 }
349 });
350
351 if let Some(hint) = self.hint() {
352 obj["error"]["hint"] = serde_json::Value::String(hint);
353 }
354
355 obj
356 }
357}