返回 CodeWhale
lifecycle_portable_tests.rs
根目录 / crates / tui / src / commands / groups / session / lifecycle_portable_tests.rs
1 //! FEAT-023 Phase 4/6: portable lifecycle handler tests (Tasks 4.2/4.4/4.6).
2 //!
3 //! Deterministic composition tests: canned lifecycle outcomes drive each
4 //! portable handler and the exact baseline messages/actions are asserted
5 //! byte-for-byte. The public dispatch seam integration (real bundle) is
6 //! exercised in Phase 6 and the end-to-end parity matrix in Phase 7.
7
8 use codewhale_command_contract::facets::{
9 SessionArchiveReceipt, SessionBranchOutcome, SessionForkFromReceipt, SessionForkReceipt,
10 SessionNewReceipt, SessionSaveReceipt, TreeBodyProjection,
11 };
12 use codewhale_command_contract::handler::CommandContexts;
13 use std::path::PathBuf;
14
15 use codewhale_command_contract::outcome::SessionAction;
16
17 use super::lifecycle_test_support::{CannedLifecycle, sync_payload};
18
19 fn missing_lifecycle() -> CommandContexts<'static> {
20 CommandContexts::empty()
21 }
22
23 // ---- /branch (Task 4.5) ----
24
25 #[test]
26 fn every_contextual_lifecycle_handler_fails_safely_without_its_facet() {
27 type Handler = fn(CommandContexts<'_>, Option<&str>) -> super::CommandResult;
28 let handlers: [(&str, Handler, Option<&str>); 7] = [
29 ("branch", super::branch::branch_contextual, Some("entry-1")),
30 ("fork", super::fork::fork_contextual, Some("session-1")),
31 ("load", super::load::load_contextual, Some("session.json")),
32 ("new", super::new::new_contextual, None),
33 ("save", super::save::save_contextual, None),
34 ("sessions", super::sessions::sessions_contextual, None),
35 ("tree", super::tree::tree_contextual, None),
36 ];
37
38 for (name, handler, arg) in handlers {
39 let result = handler(missing_lifecycle(), arg);
40 assert!(result.is_error, "/{name}: {result:?}");
41 assert_eq!(
42 result.message.as_deref(),
43 Some("Error: Command capability unavailable: session_lifecycle"),
44 "/{name}"
45 );
46 assert!(result.action.is_none(), "/{name}");
47 }
48 }
49
50 #[test]
51 fn branch_composes_exact_baseline_messages() {
52 // Blocked transition first.
53 let mut canned = CannedLifecycle {
54 blocked: true,
55 blockers: vec!["shell_a3f2 running 5h 18m cw-leftovers.ps1".to_string()],
56 ..CannedLifecycle::default()
57 };
58 let result = super::branch::branch_portable(&mut canned, Some("entry-1"));
59 assert_eq!(
60 result.message.as_deref(),
61 Some(
62 "Error: Cannot branch while runtime work is active:\n • shell_a3f2 running 5h 18m cw-leftovers.ps1\n\nWait for the work to finish, or stop what you can: Ctrl+C stops a running turn, and /jobs cancel-all cancels running shell jobs."
63 )
64 );
65 assert_eq!(canned.transition_checks.get(), 1);
66 assert!(canned.branch_entries.is_empty());
67
68 // No-arg with an active leaf hint.
69 let mut canned = CannedLifecycle {
70 leaf_hint: Some("entry-7".to_string()),
71 ..CannedLifecycle::default()
72 };
73 let result = super::branch::branch_portable(&mut canned, None);
74 assert_eq!(
75 result.message.as_deref(),
76 Some(
77 "Current leaf: entry-7\nUse `/branch <entry_id>` to move the leaf (history is never rewritten).\nUse `/tree` to list entry ids."
78 )
79 );
80
81 // No-arg without a leaf -> usage fallback.
82 let mut canned = CannedLifecycle::default();
83 let result = super::branch::branch_portable(&mut canned, None);
84 assert!(
85 result
86 .message
87 .as_deref()
88 .is_some_and(|m| m.starts_with("Usage: /branch <entry_id>")),
89 "{result:?}"
90 );
91
92 // Success message uses deterministic receipt fields.
93 let mut canned = CannedLifecycle {
94 branch: Ok(SessionBranchOutcome {
95 leaf_display: "entry-3".to_string(),
96 journal_entries_before: 5,
97 sync: sync_payload("branched-session"),
98 }),
99 ..CannedLifecycle::default()
100 };
101 let result = super::branch::branch_portable(&mut canned, Some("entry-3"));
102 assert_eq!(
103 result.message.as_deref(),
104 Some(
105 "Branched to entry entry-3 (leaf now entry-3); journal entries 5 (history preserved, leaf moved only)"
106 )
107 );
108 assert!(
109 matches!(result.action, Some(SessionAction::SyncSession(codewhale_command_contract::facets::SessionSyncPayload { session_id: Some(ref id), .. })) if id == "branched-session")
110 );
111 assert_eq!(canned.branch_entries, ["entry-3"]);
112
113 // Host stage error passes through unchanged.
114 let mut canned = CannedLifecycle {
115 branch: Err("could not load session x: boom".to_string()),
116 ..CannedLifecycle::default()
117 };
118 let result = super::branch::branch_portable(&mut canned, Some("x"));
119 assert!(result.is_error);
120 assert_eq!(
121 result.message.as_deref(),
122 Some("Error: could not load session x: boom")
123 );
124 }
125
126 // ---- /fork (Task 4.3) ----
127
128 #[test]
129 fn fork_composes_exact_baseline_messages_and_actions() {
130 // Picker aliases push the picker and return the baseline message.
131 let mut canned = CannedLifecycle::default();
132 let result = super::fork::fork_portable(&mut canned, Some("picker"));
133 assert_eq!(
134 result.message.as_deref(),
135 Some("Fork picker: select a session and then run `/fork <id>` to fork it.")
136 );
137 assert_eq!(
138 canned.picker_calls,
139 [None],
140 "bare picker must be opened without preselection"
141 );
142 assert_eq!(
143 canned.transition_checks.get(),
144 0,
145 "picker aliases bypass the transition gate"
146 );
147
148 // Blocked active fork.
149 let mut canned = CannedLifecycle {
150 blocked: true,
151 ..CannedLifecycle::default()
152 };
153 let result = super::fork::fork_portable(&mut canned, None);
154 assert!(result.is_error);
155 assert!(
156 result
157 .message
158 .as_deref()
159 .unwrap_or_default()
160 .contains("runtime work is active"),
161 "{result:?}"
162 );
163 assert_eq!(canned.transition_checks.get(), 1);
164
165 // Active fork success -> message + SyncSession action from the receipt.
166 let mut canned = CannedLifecycle {
167 fork_active: Ok(SessionForkReceipt {
168 parent_label: "parent1".to_string(),
169 fork_label: "child2".to_string(),
170 sync: sync_payload("child2"),
171 }),
172 ..CannedLifecycle::default()
173 };
174 let result = super::fork::fork_portable(&mut canned, None);
175 assert_eq!(
176 result.message.as_deref(),
177 Some("Forked session parent1 -> child2")
178 );
179 assert!(matches!(
180 result.action,
181 Some(SessionAction::SyncSession(codewhale_command_contract::facets::SessionSyncPayload { session_id: Some(ref id), .. })) if id == "child2"
182 ));
183 assert_eq!(canned.transition_checks.get(), 1);
184
185 // Explicit fork success appends spawn_depth.
186 let mut canned = CannedLifecycle {
187 fork_from: Ok(SessionForkFromReceipt {
188 parent_label: "aaaa".to_string(),
189 fork_label: "bbbb".to_string(),
190 spawn_depth: 2,
191 sync: sync_payload("bbbb"),
192 }),
193 ..CannedLifecycle::default()
194 };
195 let result = super::fork::fork_portable(&mut canned, Some("aaaa"));
196 assert_eq!(
197 result.message.as_deref(),
198 Some("Forked session aaaa -> bbbb (spawn_depth 2)")
199 );
200 assert_eq!(canned.fork_sources, ["aaaa"]);
201 assert_eq!(canned.transition_checks.get(), 1);
202 }
203
204 // ---- /load (Task 4.3) ----
205
206 #[test]
207 fn load_composes_exact_baseline_outcomes() {
208 let mut canned = CannedLifecycle {
209 blocked: true,
210 ..CannedLifecycle::default()
211 };
212 let result = super::load::load_portable(&mut canned, Some("x.json"));
213 assert!(result.is_error);
214 assert!(
215 result
216 .message
217 .as_deref()
218 .unwrap_or_default()
219 .contains("runtime work is active")
220 );
221 assert_eq!(canned.transition_checks.get(), 1);
222 assert!(canned.load_paths.is_empty());
223
224 let mut canned = CannedLifecycle::default();
225 let result = super::load::load_portable(&mut canned, None);
226 assert_eq!(
227 result.message.as_deref(),
228 Some("Error: Usage: /load <path>")
229 );
230 assert_eq!(canned.transition_checks.get(), 1);
231 assert!(canned.load_paths.is_empty());
232
233 let mut canned = CannedLifecycle {
234 load: Ok(PathBuf::from("/tmp/loaded.json")),
235 ..CannedLifecycle::default()
236 };
237 let result = super::load::load_portable(&mut canned, Some("/tmp/loaded.json"));
238 assert!(result.message.is_none(), "no premature receipt: {result:?}");
239 assert!(matches!(
240 result.action,
241 Some(SessionAction::LoadSession(ref p)) if p == &PathBuf::from("/tmp/loaded.json")
242 ));
243 assert_eq!(canned.load_paths, ["/tmp/loaded.json"]);
244 assert_eq!(canned.transition_checks.get(), 1);
245
246 let mut canned = CannedLifecycle {
247 load: Err("Failed to read session file: nope".to_string()),
248 ..CannedLifecycle::default()
249 };
250 let result = super::load::load_portable(&mut canned, Some("missing.json"));
251 assert_eq!(
252 result.message.as_deref(),
253 Some("Error: Failed to read session file: nope")
254 );
255 }
256
257 // ---- /new (Task 4.3) ----
258
259 #[test]
260 fn new_composes_exact_baseline_outcomes() {
261 // Unknown argument usage.
262 let mut canned = CannedLifecycle::default();
263 let result = super::new::new_portable(&mut canned, Some("--bogus"));
264 assert!(result.is_error);
265 assert!(
266 result
267 .message
268 .as_deref()
269 .unwrap_or_default()
270 .contains("Unknown argument: --bogus"),
271 "{result:?}"
272 );
273 let result = super::new::new_portable(&mut canned, Some("creator standard"));
274 assert!(result.is_error);
275 assert!(
276 result
277 .message
278 .as_deref()
279 .unwrap_or_default()
280 .contains("Unknown argument: standard"),
281 "{result:?}"
282 );
283 assert!(
284 canned.fresh_modes.is_empty(),
285 "a bad argument asks the host nothing"
286 );
287 assert_eq!(
288 canned.transition_checks.get(),
289 0,
290 "argument validation precedes the transition gate"
291 );
292
293 // Blocked.
294 let mut canned = CannedLifecycle {
295 blocked: true,
296 blockers: vec!["shell_a3f2 running 5h 18m cw-leftovers.ps1".to_string()],
297 ..CannedLifecycle::default()
298 };
299 let result = super::new::new_portable(&mut canned, None);
300 assert!(result.is_error);
301 let message = result.message.as_deref().unwrap_or_default();
302 assert!(
303 message.contains("Cannot start a new session while runtime work is active"),
304 "{message}"
305 );
306 assert!(message.contains("shell_a3f2"), "{message}");
307 assert!(message.contains("/jobs cancel-all"), "{message}");
308 assert!(
309 message.contains("`/new --force` only discards draft or queued input"),
310 "the flag's real scope stays stated where the flag exists: {message}"
311 );
312 assert_eq!(canned.transition_checks.get(), 1);
313 assert!(canned.fresh_forces.is_empty());
314
315 // Preparation -> pending request; the Engine still owns confirmation.
316 let mut canned = CannedLifecycle {
317 fresh: Ok(SessionNewReceipt {
318 truncated_id: "new-123".to_string(),
319 sync: sync_payload("new-123"),
320 }),
321 ..CannedLifecycle::default()
322 };
323 let result = super::new::new_portable(&mut canned, Some("--force"));
324 assert!(result.message.is_none());
325 assert!(matches!(
326 result.action,
327 Some(SessionAction::NewSession { sync: codewhale_command_contract::facets::SessionSyncPayload { session_id: Some(ref id), .. }, force: true, .. }) if id == "new-123"
328 ));
329 assert_eq!(canned.fresh_forces, [true]);
330 assert_eq!(canned.fresh_modes, [None]);
331 assert_eq!(canned.transition_checks.get(), 1);
332
333 let mut canned = CannedLifecycle {
334 fresh: Ok(SessionNewReceipt {
335 truncated_id: "new-456".to_string(),
336 sync: sync_payload("new-456"),
337 }),
338 ..CannedLifecycle::default()
339 };
340 let result = super::new::new_portable(&mut canned, Some("--force creator"));
341 assert!(!result.is_error, "{result:?}");
342 assert_eq!(canned.fresh_forces, [true]);
343 assert_eq!(canned.fresh_modes, [Some("creator".to_string())]);
344
345 // Host blocker error passes through.
346 let mut canned = CannedLifecycle {
347 fresh: Err("Cannot start a new session while the composer has unsent text. Run `/new --force` to discard pending work and start a fresh session.".to_string()),
348 ..CannedLifecycle::default()
349 };
350 let result = super::new::new_portable(&mut canned, None);
351 assert!(result.is_error);
352 assert!(
353 result
354 .message
355 .as_deref()
356 .unwrap_or_default()
357 .contains("/new --force")
358 );
359 }
360
361 // ---- /save (Task 4.3) ----
362
363 #[test]
364 fn save_composes_exact_baseline_receipt() {
365 let mut canned = CannedLifecycle {
366 save: Ok(SessionSaveReceipt {
367 display_path: "/tmp/abc.json".to_string(),
368 truncated_id: "abc123".to_string(),
369 }),
370 ..CannedLifecycle::default()
371 };
372 let result = super::save::save_portable(&mut canned, Some("/tmp/abc.json"));
373 assert_eq!(
374 result.message.as_deref(),
375 Some("Session saved to /tmp/abc.json (ID: abc123)")
376 );
377 assert!(result.action.is_none());
378 assert_eq!(canned.save_paths, [Some("/tmp/abc.json".to_string())]);
379
380 let mut canned = CannedLifecycle {
381 save: Err("Failed to save session: boom".to_string()),
382 ..CannedLifecycle::default()
383 };
384 let result = super::save::save_portable(&mut canned, None);
385 assert_eq!(
386 result.message.as_deref(),
387 Some("Error: Failed to save session: boom")
388 );
389 }
390
391 // ---- /sessions (Task 4.5) ----
392
393 #[test]
394 fn sessions_composes_exact_baseline_outcomes() {
395 // Bare -> picker push, no message/action.
396 let mut canned = CannedLifecycle::default();
397 let result = super::sessions::sessions_portable(&mut canned, None);
398 assert_eq!(result.message, None);
399 assert_eq!(result.action, None);
400 assert_eq!(canned.picker_calls, [None]);
401
402 // show/list/picker aliases.
403 for alias in ["show", "list", "picker"] {
404 let mut canned = CannedLifecycle::default();
405 let result = super::sessions::sessions_portable(&mut canned, Some(alias));
406 assert_eq!(result.message, None, "{alias}");
407 assert_eq!(canned.picker_calls, [None], "{alias}");
408 }
409
410 // open with preselection.
411 let mut canned = CannedLifecycle::default();
412 let _result = super::sessions::sessions_portable(&mut canned, Some("open abc123"));
413 assert_eq!(canned.picker_calls, [Some("abc123".to_string())]);
414
415 // open without id -> usage.
416 let result = super::sessions::sessions_portable(&mut canned, Some("open"));
417 assert_eq!(
418 result.message.as_deref(),
419 Some("Error: usage: /sessions open <session-id>")
420 );
421
422 // archive/unarchive messages.
423 let mut canned = CannedLifecycle {
424 archived: Ok(SessionArchiveReceipt {
425 truncated_id: "zzz".to_string(),
426 title: "My Session".to_string(),
427 }),
428 ..CannedLifecycle::default()
429 };
430 let result = super::sessions::sessions_portable(&mut canned, Some("archive zzz"));
431 assert_eq!(
432 result.message.as_deref(),
433 Some("Archived session zzz (My Session)")
434 );
435 assert_eq!(canned.archive_calls, [("zzz".to_string(), true)]);
436 let mut canned = CannedLifecycle {
437 archived: Ok(SessionArchiveReceipt {
438 truncated_id: "zzz".to_string(),
439 title: "My Session".to_string(),
440 }),
441 ..CannedLifecycle::default()
442 };
443 let result = super::sessions::sessions_portable(&mut canned, Some("restore zzz"));
444 assert_eq!(
445 result.message.as_deref(),
446 Some("Restored session zzz (My Session)")
447 );
448 assert_eq!(canned.archive_calls, [("zzz".to_string(), false)]);
449
450 // prune parsing + messages.
451 let result = super::sessions::sessions_portable(&mut canned, Some("prune"));
452 assert!(
453 result
454 .message
455 .as_deref()
456 .unwrap_or_default()
457 .contains("usage: /sessions prune <days>")
458 );
459 let result = super::sessions::sessions_portable(&mut canned, Some("prune abc"));
460 assert_eq!(
461 result.message.as_deref(),
462 Some("Error: expected a positive integer number of days, got `abc`")
463 );
464 let mut canned = CannedLifecycle {
465 prune: Ok(0),
466 ..CannedLifecycle::default()
467 };
468 let result = super::sessions::sessions_portable(&mut canned, Some("prune 30"));
469 assert_eq!(
470 result.message.as_deref(),
471 Some("no sessions older than 30d to prune")
472 );
473 assert_eq!(canned.prune_days, [30]);
474 let mut canned = CannedLifecycle {
475 prune: Ok(2),
476 ..CannedLifecycle::default()
477 };
478 let result = super::sessions::sessions_portable(&mut canned, Some("prune 30"));
479 assert_eq!(
480 result.message.as_deref(),
481 Some("pruned 2 sessions older than 30d")
482 );
483 assert_eq!(canned.prune_days, [30]);
484
485 // Unknown subcommand.
486 let result = super::sessions::sessions_portable(&mut canned, Some("teleport"));
487 assert!(
488 result
489 .message
490 .as_deref()
491 .unwrap_or_default()
492 .contains("unknown subcommand `teleport`")
493 );
494 }
495
496 // ---- /tree (Task 4.5) ----
497
498 #[test]
499 fn tree_composes_exact_baseline_messages() {
500 let mut canned = CannedLifecycle {
501 tree: Ok(TreeBodyProjection::Journal {
502 rendered: "journal body".to_string(),
503 }),
504 ..CannedLifecycle::default()
505 };
506 let result = super::tree::tree_portable(&mut canned, None);
507 assert_eq!(
508 result.message.as_deref(),
509 Some(
510 "journal body\nUse `/branch <entry_id>` to branch (moves leaf only, never rewrites history).\nUse `/fork [session_id]` to fork this session at any node.\n"
511 )
512 );
513
514 let mut canned = CannedLifecycle {
515 tree: Ok(TreeBodyProjection::Linear {
516 rendered: "linear body".to_string(),
517 }),
518 ..CannedLifecycle::default()
519 };
520 let result = super::tree::tree_portable(&mut canned, None);
521 assert_eq!(
522 result.message.as_deref(),
523 Some("linear body\nUse `/branch <n>` with entry id after journal is saved.\n")
524 );
525
526 let mut canned = CannedLifecycle {
527 tree: Ok(TreeBodyProjection::EmptySession),
528 ..CannedLifecycle::default()
529 };
530 let result = super::tree::tree_portable(&mut canned, None);
531 assert!(
532 result
533 .message
534 .as_deref()
535 .unwrap_or_default()
536 .contains("(empty session — no entries yet)")
537 );
538
539 let mut canned = CannedLifecycle {
540 tree: Ok(TreeBodyProjection::NoSession),
541 ..CannedLifecycle::default()
542 };
543 let result = super::tree::tree_portable(&mut canned, None);
544 assert!(
545 result
546 .message
547 .as_deref()
548 .unwrap_or_default()
549 .contains("No active session")
550 );
551
552 let mut canned = CannedLifecycle {
553 tree: Err("could not open sessions directory: boom".to_string()),
554 ..CannedLifecycle::default()
555 };
556 let result = super::tree::tree_portable(&mut canned, None);
557 assert_eq!(
558 result.message.as_deref(),
559 Some("Error: could not open sessions directory: boom")
560 );
561 }
562
562 lines RUST