返回 CodeWhale
relay.rs
根目录 / crates / tui / src / commands / groups / session / relay.rs
1 //! `/relay` command — portable handler over the session-control facet.
2
3 use std::fmt::Write as _;
4
5 use super::CommandResult;
6 use codewhale_command_contract::facets::{
7 CommandSessionControlContext, PlanProjection, PlanStepStatus, RelayProjection,
8 };
9 use codewhale_command_contract::handler::{CommandContexts, CommandHandler};
10 use codewhale_command_contract::metadata::{
11 CommandInfo as ContractInfo, RegisterCommand as ContractRegisterCommand,
12 };
13
14 pub(in crate::commands) struct RelayCmd;
15
16 // ---------------------------------------------------------------------------
17 // FEAT-024 Phase 4 (D4/D6/D7): portable contextual registration and handler.
18 // The handler owns complete relay-instruction composition (sections, labels,
19 // list formatting, focus normalization, byte-identical text); the facet
20 // supplies the semantic projection. Missing control authority fails safely
21 // with the exact capability error (never a panic).
22 // ---------------------------------------------------------------------------
23
24 pub(in crate::commands) const CONTRACT_INFO: ContractInfo = ContractInfo {
25 name: "relay",
26 aliases: &["batonpass", "接力"],
27 usage: "/relay [focus]",
28 description_key: "cmd_relay_description",
29 };
30
31 impl ContractRegisterCommand<CommandResult> for RelayCmd {
32 fn info() -> &'static ContractInfo {
33 &CONTRACT_INFO
34 }
35 fn handler() -> CommandHandler<CommandResult> {
36 CommandHandler::Contextual {
37 capabilities: codewhale_command_contract::handler::CommandCapabilities::SESSION_CONTROL,
38 handler: relay_contextual,
39 }
40 }
41 }
42
43 pub(in crate::commands) fn relay_contextual(
44 contexts: CommandContexts<'_>,
45 arg: Option<&str>,
46 ) -> CommandResult {
47 let mut parts = contexts.into_parts();
48 let Some(control) = parts.control.as_deref_mut() else {
49 return CommandResult::error("Command capability unavailable: session_control".to_string());
50 };
51 relay_portable(control, arg)
52 }
53
54 pub(in crate::commands) fn relay_portable(
55 control: &mut dyn CommandSessionControlContext,
56 arg: Option<&str>,
57 ) -> CommandResult {
58 let focus = arg.map(str::trim).filter(|value| !value.is_empty());
59 let projection = control.relay_projection();
60 let status = format!("Preparing session relay at {}...", projection.handoff_path);
61 let message = build_relay_instruction(projection, focus);
62 CommandResult::with_message_and_action(
63 status,
64 codewhale_command_contract::outcome::SessionAction::SendMessage(message),
65 )
66 }
67
68 /// Compose the relay instruction from the portable snapshot.
69 ///
70 /// The relay is written to `projection.handoff_path`, the path the next
71 /// session reads first. A relay written to the legacy location is ignored
72 /// whenever a file exists at that path.
73 fn build_relay_instruction(projection: RelayProjection, focus: Option<&str>) -> String {
74 let mut out = String::new();
75 let _ = writeln!(
76 out,
77 "Create a compact session relay (接力) for a future Codewhale thread."
78 );
79 let _ = writeln!(out);
80 let _ = writeln!(out, "Write or update `{}`.", projection.handoff_path);
81 let _ = writeln!(
82 out,
83 "Write exactly this path so the next session loads it, and title the artifact `# Session relay`."
84 );
85 let _ = writeln!(out);
86 let _ = writeln!(out, "Use this relay structure:");
87 let _ = writeln!(out);
88 let _ = writeln!(out, "{}", projection.compact_template.trim());
89 let _ = writeln!(out);
90 let _ = writeln!(out, "Current session snapshot:");
91 let _ = writeln!(out, "- Workspace: {}", projection.workspace);
92 let _ = writeln!(out, "- Mode: {}", projection.mode);
93 let _ = writeln!(out, "- Model: {}", projection.model);
94 if let Some(focus) = focus {
95 let _ = writeln!(out, "- Requested relay focus: {focus}");
96 }
97 if let Some(objective) = projection.goal_objective.as_deref() {
98 let _ = writeln!(out, "- Goal objective: {objective}");
99 }
100 if let Some(budget) = projection.goal_token_budget {
101 let _ = writeln!(out, "- Goal token budget: {budget}");
102 }
103 match projection.todos {
104 codewhale_command_contract::facets::TodoProjection::Body(body) => {
105 let _ = writeln!(out, "\nCurrent To-do:");
106 let _ = writeln!(out, "{body}");
107 }
108 codewhale_command_contract::facets::TodoProjection::Absent => {}
109 codewhale_command_contract::facets::TodoProjection::Unavailable => {
110 let _ = writeln!(out, "\nTo-do: unavailable because the list is busy.");
111 }
112 }
113 match projection.plan {
114 PlanProjection::Sections(sections) => {
115 let _ = writeln!(
116 out,
117 "\nConversational strategy notes from update_plan (reasoning context, not a Work surface):"
118 );
119 write_plan_field(&mut out, "Title", sections.title.as_deref());
120 write_plan_field(&mut out, "Objective", sections.objective.as_deref());
121 write_plan_field(&mut out, "Context", sections.context_summary.as_deref());
122 write_plan_field(&mut out, "Explanation", sections.explanation.as_deref());
123 write_plan_list(&mut out, "Source", &sections.sources_used);
124 write_plan_list(&mut out, "Critical file", &sections.critical_files);
125 write_plan_list(&mut out, "Constraint", &sections.constraints);
126 write_plan_field(
127 &mut out,
128 "Recommended approach",
129 sections.recommended_approach.as_deref(),
130 );
131 write_plan_field(
132 &mut out,
133 "Verification plan",
134 sections.verification_plan.as_deref(),
135 );
136 write_plan_field(
137 &mut out,
138 "Risks and unknowns",
139 sections.risks_and_unknowns.as_deref(),
140 );
141 write_plan_field(
142 &mut out,
143 "Handoff packet",
144 sections.handoff_packet.as_deref(),
145 );
146 write_plan_list(&mut out, "Replan if", &sections.replan_if);
147 for item in sections.items {
148 let _ = writeln!(
149 out,
150 "- [{}] {}",
151 plan_step_status_label(item.status),
152 item.text
153 );
154 }
155 }
156 PlanProjection::Absent => {}
157 PlanProjection::Busy => {
158 let _ = writeln!(
159 out,
160 "\nStrategy metadata: unavailable because plan state is busy."
161 );
162 }
163 }
164 let _ = writeln!(
165 out,
166 "\nBefore writing, inspect the current transcript context and any live tool evidence you need. Do not invent test results, file changes, blockers, or decisions."
167 );
168 let _ = writeln!(
169 out,
170 "\nKeep it under about 900 words unless the session genuinely needs more. After writing, report the path and the single next action."
171 );
172 out
173 }
174
175 fn plan_step_status_label(status: PlanStepStatus) -> &'static str {
176 match status {
177 PlanStepStatus::Pending => "pending",
178 PlanStepStatus::InProgress => "in_progress",
179 PlanStepStatus::Completed => "completed",
180 }
181 }
182
183 fn write_plan_field(out: &mut String, label: &str, value: Option<&str>) {
184 if let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) {
185 let _ = writeln!(out, "- {label}: {value}");
186 }
187 }
188
189 fn write_plan_list(out: &mut String, label: &str, values: &[String]) {
190 for value in values {
191 let value = value.trim();
192 if !value.is_empty() {
193 let _ = writeln!(out, "- {label}: {value}");
194 }
195 }
196 }
197
198 #[cfg(test)]
199 mod tests {
200 use super::super::control_test_support::message;
201 use super::*;
202 use codewhale_command_contract::facets::{PlanSections, PlanStep, TodoProjection};
203
204 #[test]
205 fn relay_composes_exact_instruction_and_action() {
206 let mut fake = super::super::control_test_support::FakeControl {
207 relay: Some(super::super::control_test_support::relay_projection_fixture()),
208 ..super::super::control_test_support::FakeControl::default()
209 };
210 let result = relay_portable(&mut fake, Some("focus on the handoff"));
211 assert!(!result.is_error);
212 let message = match result.action {
213 Some(codewhale_command_contract::outcome::SessionAction::SendMessage(message)) => {
214 message
215 }
216 other => panic!("expected SendMessage action, got {other:?}"),
217 };
218 assert!(
219 message
220 .contains("Create a compact session relay (接力) for a future Codewhale thread.")
221 );
222 assert!(message.contains("- Workspace: /work"));
223 assert!(message.contains("- Mode: operate"));
224 assert!(message.contains("- Model: model-x"));
225 assert!(message.contains("- Requested relay focus: focus on the handoff"));
226 assert!(message.contains("- Goal objective: objective-y"));
227 assert!(message.contains("- Goal token budget: 900"));
228 assert!(message.contains("\n\nWrite or update `.codewhale/handoff.md`.\nWrite exactly this path so the next session loads it, and title the artifact `# Session relay`.\n"));
229 assert!(!message.contains(".deepseek"));
230 assert!(message.contains("Before writing, inspect the current transcript context"));
231 assert!(message.contains("Keep it under about 900 words"));
232 assert!(!message.contains("Current To-do:"));
233 assert!(!message.contains("strategy notes"));
234 assert!(
235 result
236 .message
237 .as_deref()
238 .is_some_and(|m| m == "Preparing session relay at .codewhale/handoff.md...")
239 );
240 assert_eq!(fake.calls.borrow().as_slice(), ["relay_projection"]);
241 }
242
243 #[test]
244 fn relay_names_the_path_the_host_reads_back() {
245 let mut fake = super::super::control_test_support::FakeControl {
246 relay: Some(RelayProjection {
247 handoff_path: "state/relay.md".to_string(),
248 ..super::super::control_test_support::relay_projection_fixture()
249 }),
250 ..super::super::control_test_support::FakeControl::default()
251 };
252 let result = relay_portable(&mut fake, None);
253 assert_eq!(
254 message(&result),
255 "Preparing session relay at state/relay.md..."
256 );
257 let instruction = match result.action {
258 Some(codewhale_command_contract::outcome::SessionAction::SendMessage(message)) => {
259 message
260 }
261 other => panic!("expected SendMessage, got {other:?}"),
262 };
263 assert!(instruction.contains("Write or update `state/relay.md`."));
264 assert!(!instruction.contains("handoff.md"));
265 }
266
267 #[test]
268 fn relay_render_optional_sections_and_busy_states_exactly() {
269 let mut fake = super::super::control_test_support::FakeControl {
270 relay: Some(RelayProjection {
271 compact_template: "# Session relay".to_string(),
272 handoff_path: ".codewhale/handoff.md".to_string(),
273 workspace: "/work".to_string(),
274 mode: "operate".to_string(),
275 model: "model-x".to_string(),
276 goal_objective: None,
277 goal_token_budget: None,
278 todos: TodoProjection::Unavailable,
279 plan: codewhale_command_contract::facets::PlanProjection::Busy,
280 }),
281 ..super::super::control_test_support::FakeControl::default()
282 };
283 let result = relay_portable(&mut fake, None);
284 let message = match result.action {
285 Some(codewhale_command_contract::outcome::SessionAction::SendMessage(message)) => {
286 message
287 }
288 other => panic!("expected SendMessage, got {other:?}"),
289 };
290 assert!(message.contains("\nTo-do: unavailable because the list is busy."));
291 assert!(message.contains("\nStrategy metadata: unavailable because plan state is busy."));
292 assert!(!message.contains("Requested relay focus"));
293 assert!(!message.contains("Goal objective"));
294 assert!(!message.contains("Goal token budget"));
295 }
296
297 #[test]
298 fn relay_renders_plan_sections_with_exact_labels() {
299 let mut fake = super::super::control_test_support::FakeControl {
300 relay: Some(RelayProjection {
301 compact_template: "template".to_string(),
302 handoff_path: ".codewhale/handoff.md".to_string(),
303 workspace: "/w".to_string(),
304 mode: "m".to_string(),
305 model: "mo".to_string(),
306 goal_objective: None,
307 goal_token_budget: None,
308 todos: TodoProjection::Absent,
309 plan: codewhale_command_contract::facets::PlanProjection::Sections(PlanSections {
310 title: Some("Relay Plan".to_string()),
311 explanation: Some(" because ".to_string()),
312 sources_used: vec!["repo-a".to_string(), " ".to_string()],
313 replan_if: vec!["abort on schema mismatch".to_string(), " ".to_string()],
314 items: vec![PlanStep {
315 status: PlanStepStatus::InProgress,
316 text: "port relay".to_string(),
317 }],
318 ..PlanSections::default()
319 }),
320 }),
321 ..super::super::control_test_support::FakeControl::default()
322 };
323 let result = relay_portable(&mut fake, None);
324 let message = match result.action {
325 Some(codewhale_command_contract::outcome::SessionAction::SendMessage(message)) => {
326 message
327 }
328 other => panic!("expected SendMessage, got {other:?}"),
329 };
330 assert!(message.contains("- Title: Relay Plan"));
331 assert!(message.contains("- Explanation: because"));
332 assert!(message.contains("- Source: repo-a"));
333 assert!(message.contains("- Replan if: abort on schema mismatch"));
334 assert!(message.contains("- [in_progress] port relay"));
335 }
336
337 #[test]
338 fn relay_owns_every_portable_plan_status_label() {
339 assert_eq!(plan_step_status_label(PlanStepStatus::Pending), "pending");
340 assert_eq!(
341 plan_step_status_label(PlanStepStatus::InProgress),
342 "in_progress"
343 );
344 assert_eq!(
345 plan_step_status_label(PlanStepStatus::Completed),
346 "completed"
347 );
348 }
349
350 #[test]
351 fn relay_missing_control_authority_fails_safely() {
352 let contexts = codewhale_command_contract::handler::CommandContexts::empty();
353 let result = relay_contextual(contexts, None);
354 assert!(result.is_error);
355 assert_eq!(
356 message(&result),
357 "Command capability unavailable: session_control"
358 );
359 }
360 }
361
361 lines RUST