返回 CodeWhale
restore.rs
根目录 / crates / tui / src / commands / groups / skills / restore.rs
1 //! `/restore` slash command — roll back the workspace to a prior snapshot.
2 //!
3 //! `/restore` (no arg) lists the 20 most recent snapshots so the user can
4 //! see what's available. `/restore list [N]` lists more snapshots, capped
5 //! at 100. `/restore <N>` restores the *N*th-most-recent snapshot, where
6 //! `N=1` is the newest. Without trusted/full access we refuse to mutate files unless
7 //! the user has explicitly trusted the workspace (`/trust on` or Full Access) —
8 //! the user can always view the list, just not one-shot revert without a
9 //! safety net.
10 //!
11 //! FEAT-022 Phase 4: portable contextual dispatch. `SnapshotRepo` and the
12 //! approval state stay host-side (`CommandSkillGroupContext` delegates); the
13 //! portable handler owns all parsing, formatting, and the trust gate.
14
15 use chrono::TimeZone;
16
17 use codewhale_command_contract::facets::{CommandSkillGroupContext, SnapshotEntry};
18 use codewhale_command_contract::handler::{CommandContexts, CommandHandler};
19 use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand};
20
21 use crate::commands::CommandResult;
22
23 const DEFAULT_LIST_LIMIT: usize = 20;
24 const MAX_LIST_LIMIT: usize = 100;
25 const MAX_RESTORE_INDEX: usize = 1000;
26
27 pub(in crate::commands) const COMMAND_INFO: CommandInfo = CommandInfo {
28 name: "restore",
29 aliases: &[],
30 usage: "/restore [N|list [N]]",
31 description_key: "cmd_restore_description",
32 };
33
34 pub(in crate::commands) struct RestoreCmd;
35
36 impl RegisterCommand<CommandResult> for RestoreCmd {
37 fn info() -> &'static CommandInfo {
38 &COMMAND_INFO
39 }
40
41 fn handler() -> CommandHandler<CommandResult> {
42 CommandHandler::Contextual {
43 capabilities: codewhale_command_contract::handler::CommandCapabilities::SKILL_GROUP,
44 handler: restore_contextual,
45 }
46 }
47 }
48
49 /// Contextual `/restore` dispatch (FEAT-022 D4): exactly the skill-group facet
50 /// (snapshot list/restore + approval state — no `MODE_POLICY` declaration).
51 fn restore_contextual(contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult {
52 let mut parts = contexts.into_parts();
53 let Some(skill_group) = parts.skill_group.as_deref_mut() else {
54 return CommandResult::error("Command capability unavailable: skill_group");
55 };
56 restore(skill_group, arg)
57 }
58
59 /// Portable `/restore` dispatch — byte-identical to the baseline handler.
60 ///
61 /// The host owns `SnapshotRepo` open/list/restore and the yolo/trust posture;
62 /// the handler composes every message, error, listing, and the trust gate.
63 fn restore(group: &mut dyn CommandSkillGroupContext, arg: Option<&str>) -> CommandResult {
64 let Some(arg) = arg.map(str::trim).filter(|s| !s.is_empty()) else {
65 let snapshots = match group.snapshot_list(DEFAULT_LIST_LIMIT) {
66 Ok(s) => s,
67 Err(err) => return CommandResult::error(err),
68 };
69 if snapshots.is_empty() {
70 return no_snapshots_message();
71 }
72 return CommandResult::message(format_listing(&snapshots));
73 };
74
75 if let Some(limit) = match parse_list_arg(arg) {
76 Ok(limit) => limit,
77 Err(message) => return CommandResult::error(message),
78 } {
79 let snapshots = match group.snapshot_list(limit) {
80 Ok(s) => s,
81 Err(err) => return CommandResult::error(err),
82 };
83 if snapshots.is_empty() {
84 return no_snapshots_message();
85 }
86 return CommandResult::message(format_listing(&snapshots));
87 }
88
89 let n: usize = match arg.parse() {
90 Ok(n) if (1..=MAX_RESTORE_INDEX).contains(&n) => n,
91 Ok(n) if n > MAX_RESTORE_INDEX => {
92 return CommandResult::error(format!(
93 "Restore index must be <= {MAX_RESTORE_INDEX}; got {n}. Use /restore list [N] to inspect snapshots first.",
94 ));
95 }
96 _ => {
97 return CommandResult::error(format!(
98 "Usage: /restore <N> or /restore list [N] (N is 1-based; got '{arg}')",
99 ));
100 }
101 };
102 let snapshots = match group.snapshot_list(n.max(DEFAULT_LIST_LIMIT)) {
103 Ok(s) => s,
104 Err(err) => return CommandResult::error(err),
105 };
106 if snapshots.is_empty() {
107 return no_snapshots_message();
108 }
109
110 if n > snapshots.len() {
111 return CommandResult::error(format!(
112 "Only {} snapshot(s) available; asked for #{n}.",
113 snapshots.len(),
114 ));
115 }
116
117 // Sessions without trusted/full access get a confirmation gate. We don't have a true
118 // modal-confirmation path inside slash commands today, so the gate
119 // is "require trust mode" — `/trust on` or Full Access. Unlike `/undo`,
120 // which only reverses what the last request changed, this is a
121 // whole-folder rollback to a point the user picks from every session's
122 // snapshots, so it overwrites later edits. Users in plain Agent mode get
123 // a clear message naming both ways to proceed.
124 let approval = group.approval_state();
125 if !(approval.yolo || approval.trust_mode) {
126 return CommandResult::message(format!(
127 "Did not restore #{n} ('{}'): `/restore` rolls every file in this folder back to that point, including edits made after it. Nothing was changed.\n\
128 To take back only your last request, use `/undo`. To roll everything back, run `/trust on` or select Full Access with Shift+Tab, then re-run `/restore {n}`.",
129 snapshots[n - 1].label,
130 ));
131 }
132
133 let target = &snapshots[n - 1];
134 if let Err(err) = group.restore_snapshot(&target.id) {
135 return CommandResult::error(err);
136 }
137
138 CommandResult::message(format!(
139 "Restored snapshot #{n} ('{}', {}). Workspace files have been reverted; conversation history is unchanged.",
140 target.label,
141 short_sha(target.id.as_str()),
142 ))
143 }
144
145 fn parse_list_arg(arg: &str) -> Result<Option<usize>, String> {
146 let mut parts = arg.split_whitespace();
147 let action = match parts.next() {
148 Some(action) => action,
149 None => return Ok(None),
150 };
151 if action != "list" {
152 return Ok(None);
153 }
154 let Some(value) = parts.next() else {
155 return Ok(Some(DEFAULT_LIST_LIMIT));
156 };
157 if parts.next().is_some() {
158 return Err(format!(
159 "Usage: /restore list [N] (got extra arguments in '{arg}')",
160 ));
161 }
162 match value.parse::<usize>() {
163 Ok(limit @ 1..=MAX_LIST_LIMIT) => Ok(Some(limit)),
164 Ok(limit) if limit > MAX_LIST_LIMIT => Err(format!(
165 "Restore list limit must be <= {MAX_LIST_LIMIT}; got {limit}.",
166 )),
167 _ => Err(format!(
168 "Usage: /restore list [N] (N must be >= 1; got '{value}')",
169 )),
170 }
171 }
172
173 fn no_snapshots_message() -> CommandResult {
174 CommandResult::message(
175 "No snapshots yet. Send a message to create the first pre-turn snapshot.",
176 )
177 }
178
179 fn format_listing(snapshots: &[SnapshotEntry]) -> String {
180 let mut out = String::from(
181 "Recent snapshots (newest first; pass /restore <N> to revert; /restore list 50 shows more):\n",
182 );
183 for (i, s) in snapshots.iter().enumerate() {
184 out.push_str(&format!(
185 " #{:<2} {} {} {}\n",
186 i + 1,
187 format_snapshot_time(s.timestamp),
188 short_sha(s.id.as_str()),
189 s.label,
190 ));
191 }
192 out
193 }
194
195 fn format_snapshot_time(timestamp: i64) -> String {
196 match chrono::Utc.timestamp_opt(timestamp, 0).single() {
197 Some(dt) => dt.format("%Y-%m-%d %H:%M UTC").to_string(),
198 None => "unknown time".to_string(),
199 }
200 }
201
202 fn short_sha(sha: &str) -> &str {
203 &sha[..sha.len().min(8)]
204 }
205
206 #[cfg(test)]
207 mod tests {
208 use super::*;
209 use codewhale_command_contract::facets::{
210 CommandApprovalState, RemoteRegistryOutcome, ReviewOutcome, SkillActivationError,
211 SkillMutationReceipt, SkillRecommendation, SkillSyncOutcome, SkillTargetScope,
212 };
213
214 struct FakeSkillGroup {
215 snapshots: Result<Vec<SnapshotEntry>, String>,
216 restore: Result<(), String>,
217 approval: CommandApprovalState,
218 }
219 impl FakeSkillGroup {
220 fn new(snapshots: Vec<SnapshotEntry>) -> Self {
221 Self {
222 snapshots: Ok(snapshots),
223 restore: Ok(()),
224 approval: CommandApprovalState {
225 yolo: true,
226 trust_mode: false,
227 },
228 }
229 }
230 }
231 impl CommandSkillGroupContext for FakeSkillGroup {
232 fn skill_registry_projection(
233 &self,
234 ) -> codewhale_command_contract::facets::SkillRegistryProjection {
235 unimplemented!("not used by restore tests")
236 }
237 fn activate_skill(
238 &mut self,
239 _name: &str,
240 ) -> Result<codewhale_command_contract::facets::SkillActivationOutcome, SkillActivationError>
241 {
242 unimplemented!("not used by restore tests")
243 }
244 fn install_skill(
245 &mut self,
246 _scope: Option<SkillTargetScope>,
247 _spec: &str,
248 ) -> Result<SkillMutationReceipt, String> {
249 unimplemented!("not used by restore tests")
250 }
251 fn update_skill(
252 &mut self,
253 _scope: Option<SkillTargetScope>,
254 _name: &str,
255 ) -> Result<SkillMutationReceipt, String> {
256 unimplemented!("not used by restore tests")
257 }
258 fn uninstall_skill(
259 &mut self,
260 _scope: Option<SkillTargetScope>,
261 _name: &str,
262 ) -> Result<SkillMutationReceipt, String> {
263 unimplemented!("not used by restore tests")
264 }
265 fn trust_skill(
266 &mut self,
267 _scope: Option<SkillTargetScope>,
268 _name: &str,
269 ) -> Result<SkillMutationReceipt, String> {
270 unimplemented!("not used by restore tests")
271 }
272 fn fetch_remote_registry(&mut self) -> Result<RemoteRegistryOutcome, String> {
273 unimplemented!("not used by restore tests")
274 }
275 fn recommend_skills(&mut self, _task: &str) -> Result<Vec<SkillRecommendation>, String> {
276 unimplemented!("not used by restore tests")
277 }
278 fn sync_registry(&mut self) -> Result<SkillSyncOutcome, String> {
279 unimplemented!("not used by restore tests")
280 }
281 fn run_review(&mut self) -> Result<ReviewOutcome, String> {
282 unimplemented!("not used by restore tests")
283 }
284 fn snapshot_list(&mut self, limit: usize) -> Result<Vec<SnapshotEntry>, String> {
285 match &self.snapshots {
286 Ok(snapshots) => Ok(snapshots.iter().take(limit).cloned().collect()),
287 Err(err) => Err(err.clone()),
288 }
289 }
290 fn restore_snapshot(&mut self, _id: &str) -> Result<(), String> {
291 self.restore.clone()
292 }
293 fn approval_state(&self) -> CommandApprovalState {
294 self.approval
295 }
296 }
297
298 fn snap(label: &str, id: &str, timestamp: i64) -> SnapshotEntry {
299 SnapshotEntry {
300 id: id.to_string(),
301 label: label.to_string(),
302 timestamp,
303 }
304 }
305
306 #[test]
307 fn restore_with_no_snapshots_shows_empty_message() {
308 let mut group = FakeSkillGroup::new(vec![]);
309 let result = restore(&mut group, None);
310 let msg = result.message.expect("expected message");
311 assert!(msg.contains("No snapshots"));
312 }
313
314 #[test]
315 fn restore_lists_when_no_arg_provided() {
316 let mut group = FakeSkillGroup::new(vec![
317 snap("post-turn:1", "11111111", 1_700_000_000),
318 snap("pre-turn:1", "22222222", 1_699_000_000),
319 ]);
320 let result = restore(&mut group, None);
321 let msg = result.message.expect("expected message");
322 assert!(msg.contains("post-turn:1"));
323 assert!(msg.contains("pre-turn:1"));
324 assert!(msg.contains("#1"));
325 assert!(msg.contains("#2"));
326 assert!(msg.contains("2023-11-14 22:13 UTC"), "{msg}");
327 }
328
329 #[test]
330 fn restore_list_subcommand_accepts_explicit_limit() {
331 let mut group = FakeSkillGroup::new(vec![
332 snap("turn:1", "11111111", 1_700_000_000),
333 snap("turn:2", "22222222", 1_699_000_000),
334 snap("turn:3", "33333333", 1_698_000_000),
335 ]);
336 let result = restore(&mut group, Some("list 2"));
337 let msg = result.message.expect("expected message");
338 assert!(msg.contains("#2"), "{msg}");
339 assert!(!msg.contains("#3"), "{msg}");
340 }
341
342 #[test]
343 fn restore_list_subcommand_rejects_invalid_limit() {
344 let mut group = FakeSkillGroup::new(vec![]);
345 let result = restore(&mut group, Some("list nope"));
346 assert!(result.is_error);
347 assert!(result.message.unwrap().contains("Usage: /restore list [N]"));
348 }
349
350 #[test]
351 fn restore_list_subcommand_rejects_limit_above_cap() {
352 let mut group = FakeSkillGroup::new(vec![]);
353 let result = restore(&mut group, Some("list 101"));
354 assert!(result.is_error);
355 assert!(
356 result
357 .message
358 .unwrap()
359 .contains("Restore list limit must be <= 100")
360 );
361 }
362
363 #[test]
364 fn restore_numeric_index_rejects_unbounded_query() {
365 let mut group = FakeSkillGroup::new(vec![]);
366 let result = restore(&mut group, Some("1001"));
367 assert!(result.is_error);
368 assert!(
369 result
370 .message
371 .unwrap()
372 .contains("Restore index must be <= 1000")
373 );
374 }
375
376 #[test]
377 fn restore_in_yolo_reverts_workspace() {
378 let mut group = FakeSkillGroup::new(vec![
379 snap("post-turn:1", "22222222", 1_700_000_000),
380 snap("pre-turn:1", "11111111", 1_699_000_000),
381 ]);
382 let result = restore(&mut group, Some("2"));
383 assert!(!result.is_error);
384 assert!(result.message.unwrap().contains("Restored snapshot #2"));
385 }
386
387 #[test]
388 fn restore_outside_trust_mode_refuses() {
389 let mut group = FakeSkillGroup::new(vec![snap("pre-turn:1", "11111111", 1_700_000_000)]);
390 group.approval = CommandApprovalState {
391 yolo: false,
392 trust_mode: false,
393 };
394 let result = restore(&mut group, Some("1"));
395 let msg = result.message.expect("expected message");
396 assert!(msg.starts_with("Did not restore #1"), "{msg}");
397 assert!(msg.contains("/trust on"));
398 assert!(
399 msg.contains("/undo"),
400 "the untrusted way back is named: {msg}"
401 );
402 }
403
404 #[test]
405 fn restore_invalid_index_returns_error() {
406 let mut group = FakeSkillGroup::new(vec![snap("pre-turn:1", "11111111", 1_700_000_000)]);
407 let result = restore(&mut group, Some("99"));
408 let msg = result.message.expect("expected message");
409 assert!(msg.contains("Only 1 snapshot"));
410 }
411
412 #[test]
413 fn restore_zero_index_returns_error() {
414 let mut group = FakeSkillGroup::new(vec![snap("pre-turn:1", "11111111", 1_700_000_000)]);
415 let result = restore(&mut group, Some("0"));
416 assert!(result.is_error);
417 assert!(result.message.unwrap().contains("Usage:"));
418 }
419
420 #[test]
421 fn restore_host_error_reaches_boundary() {
422 let mut group = FakeSkillGroup::new(vec![]);
423 group.snapshots = Err("Snapshot repo unavailable for /ws: boom".to_string());
424 let result = restore(&mut group, None);
425 assert!(result.is_error);
426 assert_eq!(
427 result.message.unwrap(),
428 "Error: Snapshot repo unavailable for /ws: boom"
429 );
430 }
431
432 #[test]
433 fn restore_missing_facet_errors_are_safe() {
434 let result = restore_contextual(CommandContexts::empty(), Some("1"));
435 assert!(result.is_error);
436 assert_eq!(
437 result.message.unwrap(),
438 "Error: Command capability unavailable: skill_group"
439 );
440 }
441 }
442
442 lines RUST