返回 CodeWhale
workflow.rs
根目录 / crates / commands / src / workflow.rs
1 use codewhale_command_contract::handler::{CommandCapabilities, CommandHandler};
2 use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand};
3 use codewhale_command_contract::outcome::CommandResult;
4 use codewhale_command_contract::workflow::*;
5
6 pub struct WorkflowInstruction {
7 display: String,
8 instruction: String,
9 }
10
11 impl WorkflowInstruction {
12 pub fn into_parts(self) -> (String, String) {
13 (self.display, self.instruction)
14 }
15 }
16
17 pub struct OpenWorkflowsManager;
18
19 pub struct WorkflowCmd;
20 impl<A: From<WorkflowInstruction>> RegisterCommand<CommandResult<A>> for WorkflowCmd {
21 fn info() -> &'static CommandInfo {
22 &CommandInfo {
23 name: "workflow",
24 aliases: &["wf"],
25 usage: "/workflow [objective|confirm|run <path>|status [run_id]|cancel [run_id]|settings]",
26 description_key: "cmd_workflow_description",
27 }
28 }
29 fn handler() -> CommandHandler<CommandResult<A>> {
30 CommandHandler::Contextual {
31 capabilities: CommandCapabilities::WORKFLOW_CONTROL
32 .union(CommandCapabilities::WORKFLOW_REVIEW),
33 handler: |mut ctx, arg| {
34 let Some(host) = ctx.take_workflow() else {
35 return CommandResult::error("Command capability unavailable: workflow");
36 };
37 let Some(review) = ctx.take_workflow_review() else {
38 return CommandResult::error("Command capability unavailable: workflow review");
39 };
40 workflow(host, review, arg)
41 },
42 }
43 }
44 }
45
46 pub struct WorkflowsCmd;
47 impl<A: From<OpenWorkflowsManager>> RegisterCommand<CommandResult<A>> for WorkflowsCmd {
48 fn info() -> &'static CommandInfo {
49 &CommandInfo {
50 name: "workflows",
51 aliases: &[],
52 usage: "/workflows",
53 description_key: "cmd_workflows_description",
54 }
55 }
56 fn handler() -> CommandHandler<CommandResult<A>> {
57 CommandHandler::Contextual {
58 capabilities: CommandCapabilities::WORKFLOW_CONTROL,
59 handler: |mut ctx, arg| {
60 let Some(host) = ctx.take_workflow() else {
61 return CommandResult::error("Command capability unavailable: workflow");
62 };
63 workflows(host, arg)
64 },
65 }
66 }
67 }
68
69 pub struct AutoCmd;
70 impl<A> RegisterCommand<CommandResult<A>> for AutoCmd {
71 fn info() -> &'static CommandInfo {
72 &CommandInfo {
73 name: "auto",
74 aliases: &["zidong"],
75 usage: "/auto",
76 description_key: "cmd_auto_description",
77 }
78 }
79 fn handler() -> CommandHandler<CommandResult<A>> {
80 CommandHandler::Contextual {
81 capabilities: CommandCapabilities::AUTO_REVIEW.union(CommandCapabilities::PRESENTATION),
82 handler: |mut ctx, arg| {
83 let Some(host) = ctx.take_auto_review() else {
84 return CommandResult::error("Command capability unavailable: auto_review");
85 };
86 let Some(presentation) = ctx.into_parts().presentation else {
87 return CommandResult::error("Command capability unavailable: presentation");
88 };
89 auto(host, presentation, arg)
90 },
91 }
92 }
93 }
94 fn truncate_workflow_text(text: &str, max_chars: usize) -> String {
95 if text.chars().count() <= max_chars {
96 return text.to_string();
97 }
98
99 let mut truncated: String = text.chars().take(max_chars.saturating_sub(1)).collect();
100 truncated.push('…');
101 truncated
102 }
103
104 fn workflow_display(prefix: &str, objective: Option<&str>) -> String {
105 let display = objective.map_or_else(
106 || format!("{prefix}current work"),
107 |objective| {
108 // Transcript rows are single-line summaries. The full (separately
109 // bounded) objective remains in the typed envelope reviewed by the
110 // model and later used by confirmation.
111 let objective = objective.split_whitespace().collect::<Vec<_>>().join(" ");
112 format!("{prefix}{objective}")
113 },
114 );
115 truncate_workflow_text(&display, WORKFLOW_DISPLAY_MAX_CHARS)
116 }
117
118 fn workflow_draft_instruction(id: &str, objective: Option<&str>) -> String {
119 let envelope = WorkflowDraftEnvelope {
120 id: id.to_string(),
121 objective: objective.map(ToOwned::to_owned),
122 source_path: None,
123 };
124 let encoded =
125 serde_json::to_string(&envelope).expect("workflow draft envelope is serializable");
126 format!(
127 "{WORKFLOW_DRAFT_INSTRUCTION_PREFIX}{encoded}\n\
128 Draft a short, plain-language Workflow proposal for review. Include the objective, 1–4 \
129 phases, estimated workers, and material risks. Do not call tools or execute work. End by \
130 asking the user to run `/workflow confirm` to start or revise the objective instead."
131 )
132 }
133
134 fn workflow_source_draft_instruction(id: &str, source_path: &str) -> String {
135 let envelope = WorkflowDraftEnvelope {
136 id: id.to_string(),
137 objective: None,
138 source_path: Some(source_path.to_string()),
139 };
140 let encoded = serde_json::to_string(&envelope).expect("workflow source draft is serializable");
141 format!(
142 "{WORKFLOW_DRAFT_INSTRUCTION_PREFIX}{encoded}\n\
143 Review the request to run this checked-in Workflow source. State the exact path, explain \
144 that its saved definition will run as-is, identify material risks, and ask the user to \
145 run `/workflow confirm` to start it. Do not call tools, inspect files, or execute work."
146 )
147 }
148
149 fn workflow_confirm_instruction(draft: &WorkflowDraftEnvelope) -> String {
150 let encoded = serde_json::to_string(draft).expect("workflow confirmation is serializable");
151 if let Some(source_path) = draft.source_path.as_deref() {
152 return format!(
153 "{WORKFLOW_CONFIRM_INSTRUCTION_PREFIX}{encoded}\n\
154 The user explicitly confirmed the saved Workflow source at {source_path:?}. Call the \
155 canonical `workflow` tool with `source_path` set to that exact relative path. Run the \
156 saved definition as-is; do not rewrite or replace it. Keep the existing approval, \
157 budget, cancellation, and receipt behavior."
158 );
159 }
160 format!(
161 "{WORKFLOW_CONFIRM_INSTRUCTION_PREFIX}{encoded}\n\
162 The user explicitly confirmed the Workflow proposal from the preceding review turn. \
163 Execute that reviewed plan through the canonical `workflow` tool now. Keep the existing \
164 approval, budget, scheduling, cancellation, and receipt behavior; do not teach or restate \
165 the tool schema."
166 )
167 }
168
169 fn workflow<A: From<WorkflowInstruction>>(
170 host: &mut dyn CommandWorkflowContext,
171 review: &dyn CommandWorkflowReviewContext,
172 arg: Option<&str>,
173 ) -> CommandResult<A> {
174 let arg = arg.map(str::trim).filter(|value| !value.is_empty());
175
176 if let Some(action) = parse_workflow_control_action(host, review, arg) {
177 return action;
178 }
179
180 let id = uuid::Uuid::new_v4().to_string();
181 let objective =
182 arg.map(|objective| truncate_workflow_text(objective, WORKFLOW_OBJECTIVE_MAX_CHARS));
183 let display = workflow_display("Workflow draft: ", objective.as_deref());
184 CommandResult::with_message_and_action(
185 "Drafting a workflow for review. Nothing will run until /workflow confirm.",
186 WorkflowInstruction {
187 display,
188 instruction: workflow_draft_instruction(&id, objective.as_deref()),
189 }
190 .into(),
191 )
192 }
193
194 fn parse_workflow_control_action<A: From<WorkflowInstruction>>(
195 host: &mut dyn CommandWorkflowContext,
196 review: &dyn CommandWorkflowReviewContext,
197 arg: Option<&str>,
198 ) -> Option<CommandResult<A>> {
199 let arg = arg?;
200 let (verb, rest) = split_verb(arg);
201 match verb {
202 "confirm" if rest.is_empty() => Some(match review.pending_draft() {
203 PendingWorkflowDraft::Ready(draft) => {
204 let display = match draft.source_path.as_deref() {
205 Some(path) => workflow_display("Workflow file confirmed: ", Some(path)),
206 None => workflow_display("Workflow confirmed: ", draft.objective.as_deref()),
207 };
208 CommandResult::with_message_and_action(
209 "Workflow confirmed. Starting the reviewed plan...",
210 WorkflowInstruction {
211 display,
212 instruction: workflow_confirm_instruction(&draft),
213 }
214 .into(),
215 )
216 }
217 PendingWorkflowDraft::NotReviewed => CommandResult::error(
218 "The current Workflow draft has not been reviewed yet. Wait for the proposal turn to finish, then run /workflow confirm.",
219 ),
220 PendingWorkflowDraft::NoDraft => CommandResult::error(
221 "There is no Workflow draft to confirm. Use /workflow <objective> to draft one first.",
222 ),
223 }),
224 // Saved definitions use the same two-turn review/confirm gate as a
225 // conversational Workflow. The draft turn has an empty tool catalog;
226 // only the later confirmation can launch the exact checked-in path.
227 "run" if !rest.is_empty() && !rest.contains(char::is_whitespace) => {
228 let path = std::path::Path::new(rest);
229 let unsafe_path = path.is_absolute()
230 || path.components().any(|component| {
231 matches!(
232 component,
233 std::path::Component::ParentDir
234 | std::path::Component::RootDir
235 | std::path::Component::Prefix(_)
236 )
237 });
238 if unsafe_path || rest.chars().count() > WORKFLOW_OBJECTIVE_MAX_CHARS {
239 return Some(CommandResult::error(
240 "Workflow source must be a bounded relative path inside this workspace.",
241 ));
242 }
243 let id = uuid::Uuid::new_v4().to_string();
244 let display = workflow_display("Workflow file draft: ", Some(rest));
245 Some(CommandResult::with_message_and_action(
246 "Reviewing the saved workflow. Nothing will run until /workflow confirm.",
247 WorkflowInstruction {
248 display,
249 instruction: workflow_source_draft_instruction(&id, rest),
250 }
251 .into(),
252 ))
253 }
254 _ => workflow_control(host, verb, rest, WORKFLOW_USAGE),
255 }
256 }
257
258 fn split_verb(arg: &str) -> (&str, &str) {
259 match arg.split_once(char::is_whitespace) {
260 Some((verb, rest)) => (verb, rest.trim()),
261 None => (arg, ""),
262 }
263 }
264
265 fn workflow_control<A>(
266 host: &mut dyn CommandWorkflowContext,
267 verb: &str,
268 rest: &str,
269 usage: &str,
270 ) -> Option<CommandResult<A>> {
271 match verb {
272 "status" | "runs" | "list" | "inspect" => Some(workflow_status(host, rest)),
273 "cancel" | "stop" | "abort" => Some(workflow_cancel(host, rest)),
274 "settings" | "config" => Some(CommandResult::message(render_workflow_summary(
275 host.settings(),
276 ))),
277 "help" | "?" => Some(CommandResult::message(usage)),
278 _ => None,
279 }
280 }
281
282 const WORKFLOW_USAGE: &str =
283 "/workflow <objective> — draft a Workflow for review (does not execute)
284 /workflow — draft a Workflow for the current work
285 /workflow run <path> — review a saved Workflow before it can run
286 /workflow confirm — explicitly start the latest reviewed draft
287 /workflow status [run_id] — runs known to this workspace (no model turn)
288 /workflow cancel [run_id] — stop a running workflow (no model turn)
289 /workflow settings — the effective [workflow] configuration
290 /workflows — the live run dashboard (opens in the TUI)";
291
292 fn describe_run(line: &HostWorkflowRunLine, now_ms: u64) -> String {
293 let elapsed = line
294 .completed_at_ms
295 .unwrap_or(now_ms)
296 .saturating_sub(line.started_at_ms)
297 / 1000;
298 let mut text = format!(
299 "{} {} {} {} {} children",
300 line.run_id,
301 line.status,
302 line.label,
303 codewhale_command_contract::elapsed::format_elapsed_secs(elapsed),
304 line.child_count
305 );
306 if let Some(progress) = line.last_progress.as_deref() {
307 text.push_str(" · ");
308 text.push_str(progress);
309 }
310 if let Some(error) = line.error.as_deref() {
311 text.push_str(" · ");
312 text.push_str(error);
313 }
314 text
315 }
316
317 fn workflow_status<A>(host: &mut dyn CommandWorkflowContext, run_id: &str) -> CommandResult<A> {
318 let runs = host.runs();
319 let now_ms = std::time::SystemTime::now()
320 .duration_since(std::time::UNIX_EPOCH)
321 .map(|d| d.as_millis() as u64)
322 .unwrap_or_default();
323 if !run_id.is_empty() {
324 return match runs.iter().find(|line| line.run_id == run_id) {
325 Some(line) => CommandResult::message(describe_run(line, now_ms)),
326 None => CommandResult::error(format!(
327 "Unknown workflow run '{run_id}'. /workflow status lists the runs this workspace knows."
328 )),
329 };
330 }
331 if runs.is_empty() {
332 return CommandResult::message(
333 "No workflow runs in this workspace yet. /workflow <objective> starts one.",
334 );
335 }
336 let active = runs.iter().filter(|line| line.active).count();
337 let mut lines = vec![format!(
338 "{} workflow run{} · {active} active",
339 runs.len(),
340 if runs.len() == 1 { "" } else { "s" }
341 )];
342 // Newest first; the journal can hold every run the workspace ever made.
343 for line in runs.iter().rev().take(20) {
344 lines.push(describe_run(line, now_ms));
345 }
346 if runs.len() > 20 {
347 lines.push(format!(
348 "… {} older runs in .codewhale/workflow-runs.jsonl",
349 runs.len() - 20
350 ));
351 }
352 CommandResult::message(lines.join("\n"))
353 }
354
355 fn workflow_cancel<A>(host: &mut dyn CommandWorkflowContext, run_id: &str) -> CommandResult<A> {
356 if run_id.contains(char::is_whitespace) {
357 return CommandResult::error("Usage: /workflow cancel [run_id]");
358 }
359 let target = if run_id.is_empty() {
360 let running: Vec<_> = host.runs().into_iter().filter(|line| line.active).collect();
361 match running.as_slice() {
362 [] => return CommandResult::message("No workflow is active."),
363 [only] => only.run_id.clone(),
364 many => {
365 let ids: Vec<&str> = many.iter().map(|line| line.run_id.as_str()).collect();
366 return CommandResult::error(format!(
367 "{} workflows are active; name one: {}",
368 many.len(),
369 ids.join(", ")
370 ));
371 }
372 }
373 } else {
374 run_id.to_string()
375 };
376 match host.cancel(&target) {
377 Ok(line) => CommandResult::message(format!(
378 "Workflow {} {} · {}",
379 line.run_id, line.status, line.label
380 )),
381 Err(reason) => CommandResult::error(reason),
382 }
383 }
384
385 fn workflows<A: From<OpenWorkflowsManager>>(
386 host: &mut dyn CommandWorkflowContext,
387 arg: Option<&str>,
388 ) -> CommandResult<A> {
389 let arg = arg.map(str::trim).filter(|value| !value.is_empty());
390 let Some(arg) = arg else {
391 return CommandResult::action(OpenWorkflowsManager.into());
392 };
393 let (verb, rest) = split_verb(arg);
394 workflow_control(host, verb, rest, WORKFLOWS_USAGE).unwrap_or_else(|| CommandResult::error(
395 "/workflows observes runs — it never launches one. Use /workflow <objective> to run one, or bare /workflow to orchestrate the current work.",
396 ))
397 }
398
399 const WORKFLOWS_USAGE: &str = "/workflows — open the live run dashboard (no model turn)
400 /workflows status [run_id] — the same listing as text
401 /workflows cancel [run_id] — stop a running workflow (no model turn)
402 /workflows settings — the effective [workflow] configuration";
403
404 fn auto<A>(
405 host: &mut dyn CommandAutoReviewContext,
406 presentation: &dyn codewhale_command_contract::facets::CommandPresentationContext,
407 arg: Option<&str>,
408 ) -> CommandResult<A> {
409 if arg.map(str::trim).is_some_and(|value| !value.is_empty()) {
410 return CommandResult::error("Usage: /auto");
411 }
412 let translations = || -> Result<_, String> {
413 Ok((
414 presentation.translate("auto_receipt_on", &[])?,
415 presentation.translate("auto_receipt_plan_note", &[])?,
416 presentation.translate("auto_receipt_broad_allows_paused", &[])?,
417 ))
418 };
419 let (on, plan, paused) = match translations() {
420 Ok(messages) => messages,
421 Err(reason) => return CommandResult::error(reason),
422 };
423 let receipt = match host.enable_auto_review() {
424 Ok(receipt) => receipt,
425 Err(reason) => return CommandResult::error(reason),
426 };
427 let messages = [
428 Some(on),
429 receipt.plan_mode.then_some(plan),
430 receipt.broad_allows_paused.then_some(paused),
431 ];
432 CommandResult::message(messages.into_iter().flatten().collect::<Vec<_>>().join(" "))
433 }
434
435 #[cfg(test)]
436 mod tests {
437 use super::*;
438
439 #[test]
440 fn auto_keeps_posture_when_a_receipt_translation_is_unavailable() {
441 struct Host;
442 impl CommandAutoReviewContext for Host {
443 fn enable_auto_review(&mut self) -> Result<AutoReviewReceipt, String> {
444 panic!("mutated before checking receipts")
445 }
446 }
447 impl codewhale_command_contract::facets::CommandPresentationContext for Host {
448 fn translate(&self, key: &str, _: &[(&str, &str)]) -> Result<String, String> {
449 match key {
450 "auto_receipt_broad_allows_paused" => Err(key.into()),
451 _ => Ok(key.into()),
452 }
453 }
454 }
455 assert!(auto::<()>(&mut Host, &Host, None).is_error);
456 }
457
458 #[test]
459 fn workflows_cannot_dispatch_confirmation_or_saved_sources() {
460 struct EmptyWorkspace;
461 impl CommandWorkflowContext for EmptyWorkspace {
462 fn runs(&self) -> Vec<HostWorkflowRunLine> {
463 panic!("unexpected journal read")
464 }
465 fn cancel(&mut self, _: &str) -> Result<HostWorkflowRunLine, String> {
466 panic!("unexpected cancellation")
467 }
468 fn settings(&self) -> codewhale_command_contract::config::CommandWorkflowSummary {
469 panic!("unexpected settings read")
470 }
471 }
472
473 let CommandHandler::Contextual { handler, .. } =
474 <WorkflowsCmd as RegisterCommand<CommandResult<OpenWorkflowsManager>>>::handler()
475 else {
476 panic!("expected contextual workflow command");
477 };
478 for input in ["confirm", "run checked-in.workflow.js"] {
479 let mut host = EmptyWorkspace;
480 let result = handler(
481 codewhale_command_contract::handler::CommandContexts::empty()
482 .with_workflow(&mut host),
483 Some(input),
484 );
485 assert!(result.is_error);
486 assert!(result.action.is_none());
487 }
488 }
489
490 #[test]
491 fn workflow_settings_reports_live_knobs_without_dead_automatic_line() {
492 struct SettingsHost;
493 impl CommandWorkflowContext for SettingsHost {
494 fn runs(&self) -> Vec<HostWorkflowRunLine> {
495 Vec::new()
496 }
497 fn cancel(&mut self, _: &str) -> Result<HostWorkflowRunLine, String> {
498 unreachable!()
499 }
500 fn settings(&self) -> codewhale_command_contract::config::CommandWorkflowSummary {
501 codewhale_command_contract::config::CommandWorkflowSummary {
502 automatic: false,
503 auto_start_read_only: false,
504 require_approval_for_writes: true,
505 max_children: 12,
506 max_concurrent: 4,
507 max_depth: 3,
508 goal_max_continuations: 10,
509 goal_enforce_token_budget: true,
510 }
511 }
512 }
513
514 let CommandHandler::Contextual { handler, .. } =
515 <WorkflowsCmd as RegisterCommand<CommandResult<OpenWorkflowsManager>>>::handler()
516 else {
517 panic!("expected contextual workflow command");
518 };
519 let mut host = SettingsHost;
520 let result = handler(
521 codewhale_command_contract::handler::CommandContexts::empty().with_workflow(&mut host),
522 Some("settings"),
523 );
524 assert!(!result.is_error);
525 let text = result.message.expect("settings message");
526 assert!(!text.contains("automatic ="), "{text}");
527 assert!(text.contains("auto_start_read_only = off"), "{text}");
528 assert!(text.contains("require_approval_for_writes = on"), "{text}");
529 assert!(
530 text.contains("max_children = 12 · max_concurrent = 4 · max_depth = 3"),
531 "{text}"
532 );
533 }
534 }
535
535 lines RUST