1pub mod model;
2
3use std::collections::{HashMap, VecDeque};
4use std::path::{Path, PathBuf};
5use std::sync::Mutex;
6use std::time::{Duration, SystemTime, UNIX_EPOCH};
7
8use tokio::process::Command;
9use uuid::Uuid;
10
11use crate::config::TaskMode;
12use crate::just::model::{
13 JustDump, JustRecipe, Recipe, RecipeSource, TaskError, TaskExecution, TaskExecutionSummary,
14};
15
16#[derive(Debug, thiserror::Error)]
21pub enum JustError {
22 #[error("just command not found: {0}")]
23 NotFound(String),
24 #[error("just command failed (exit {code}): {stderr}")]
25 CommandFailed { code: i32, stderr: String },
26 #[error("failed to parse just dump json: {0}")]
27 ParseError(#[from] serde_json::Error),
28 #[error("I/O error while reading justfile: {0}")]
29 Io(#[from] std::io::Error),
30}
31
32pub async fn list_recipes(
46 justfile_path: &Path,
47 mode: &TaskMode,
48 workdir: Option<&Path>,
49) -> Result<Vec<Recipe>, JustError> {
50 list_recipes_with_source(justfile_path, mode, workdir, RecipeSource::Project).await
51}
52
53pub async fn list_recipes_merged(
63 project_path: &Path,
64 global_path: Option<&Path>,
65 mode: &TaskMode,
66 project_workdir: Option<&Path>,
67) -> Result<Vec<Recipe>, JustError> {
68 let project_recipes = if tokio::fs::metadata(project_path).await.is_ok() {
72 list_recipes_with_source(project_path, mode, project_workdir, RecipeSource::Project).await?
73 } else {
74 Vec::new()
75 };
76
77 let global_path = match global_path {
78 Some(p) => p,
79 None => return Ok(project_recipes),
80 };
81
82 let global_recipes =
85 list_recipes_with_source(global_path, mode, project_workdir, RecipeSource::Global).await?;
86
87 let project_names: std::collections::HashSet<&str> =
89 project_recipes.iter().map(|r| r.name.as_str()).collect();
90
91 let global_only: Vec<Recipe> = global_recipes
93 .into_iter()
94 .filter(|r| !project_names.contains(r.name.as_str()))
95 .collect();
96
97 let mut merged = project_recipes;
99 merged.extend(global_only);
100 Ok(merged)
101}
102
103async fn list_recipes_with_source(
105 justfile_path: &Path,
106 mode: &TaskMode,
107 workdir: Option<&Path>,
108 source: RecipeSource,
109) -> Result<Vec<Recipe>, JustError> {
110 let dump = dump_json(justfile_path, workdir).await?;
111
112 let mut recipes: Vec<Recipe> = dump
113 .recipes
114 .into_values()
115 .filter(|r| !r.private)
116 .map(|raw| {
117 let allow_agent = is_allow_agent(&raw);
118 Recipe::from_just_recipe_with_source(raw, allow_agent, source)
119 })
120 .collect();
121
122 recipes.sort_by(|a, b| a.name.cmp(&b.name));
123
124 match mode {
125 TaskMode::AgentOnly => Ok(recipes.into_iter().filter(|r| r.allow_agent).collect()),
126 TaskMode::All => Ok(recipes),
127 }
128}
129
130async fn dump_json(justfile_path: &Path, workdir: Option<&Path>) -> Result<JustDump, JustError> {
136 let mut cmd = Command::new("just");
137 cmd.arg("--justfile")
138 .arg(justfile_path)
139 .arg("--dump")
140 .arg("--dump-format")
141 .arg("json")
142 .arg("--unstable");
143 if let Some(dir) = workdir {
144 cmd.current_dir(dir);
145 }
146 let output = cmd
147 .output()
148 .await
149 .map_err(|e| JustError::NotFound(e.to_string()))?;
150
151 if !output.status.success() {
152 let code = output.status.code().unwrap_or(-1);
153 let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
154 return Err(JustError::CommandFailed { code, stderr });
155 }
156
157 let json_str = String::from_utf8_lossy(&output.stdout);
158 let dump: JustDump = serde_json::from_str(&json_str)?;
159 Ok(dump)
160}
161
162fn has_allow_agent_group_attribute(recipe: &JustRecipe) -> bool {
164 recipe
165 .attributes
166 .iter()
167 .any(|a| a.group() == Some("allow-agent"))
168}
169
170fn has_allow_agent_doc(recipe: &JustRecipe) -> bool {
180 recipe
181 .doc
182 .as_deref()
183 .is_some_and(|d| d.split_whitespace().any(|t| t == "[allow-agent]"))
184}
185
186fn is_allow_agent(recipe: &JustRecipe) -> bool {
188 has_allow_agent_group_attribute(recipe) || has_allow_agent_doc(recipe)
189}
190
191pub fn resolve_justfile_path(override_path: Option<&str>, workdir: Option<&Path>) -> PathBuf {
193 match override_path {
194 Some(p) => PathBuf::from(p),
195 None => match workdir {
196 Some(dir) => dir.join("justfile"),
197 None => PathBuf::from("justfile"),
198 },
199 }
200}
201
202const MAX_OUTPUT_BYTES: usize = 100 * 1024; const HEAD_BYTES: usize = 50 * 1024; const TAIL_BYTES: usize = 50 * 1024; pub fn truncate_output(output: &str) -> (String, bool) {
218 if output.len() <= MAX_OUTPUT_BYTES {
219 return (output.to_string(), false);
220 }
221
222 let head_end = safe_byte_boundary(output, HEAD_BYTES);
224 let tail_start_raw = output.len().saturating_sub(TAIL_BYTES);
226 let tail_start = safe_tail_start(output, tail_start_raw);
227
228 let head = &output[..head_end];
229 let tail = &output[tail_start..];
230 let truncated_bytes = output.len() - head_end - (output.len() - tail_start);
231
232 (
233 format!("{head}\n...[truncated {truncated_bytes} bytes]...\n{tail}"),
234 true,
235 )
236}
237
238fn safe_byte_boundary(s: &str, limit: usize) -> usize {
240 if limit >= s.len() {
241 return s.len();
242 }
243 let mut idx = limit;
245 while idx > 0 && !s.is_char_boundary(idx) {
246 idx -= 1;
247 }
248 idx
249}
250
251fn safe_tail_start(s: &str, hint: usize) -> usize {
253 if hint >= s.len() {
254 return s.len();
255 }
256 let mut idx = hint;
257 while idx < s.len() && !s.is_char_boundary(idx) {
258 idx += 1;
259 }
260 idx
261}
262
263pub fn validate_arg_value(value: &str) -> Result<(), TaskError> {
278 const REJECTED_CONTROL_CHARS: &[&str] = &["\n", "\r"];
279 for pattern in REJECTED_CONTROL_CHARS {
280 if value.contains(pattern) {
281 return Err(TaskError::DangerousArgument(value.to_string()));
282 }
283 }
284 Ok(())
285}
286
287pub async fn execute_recipe(
301 recipe_name: &str,
302 args: &HashMap<String, String>,
303 justfile_path: &Path,
304 timeout: Duration,
305 mode: &TaskMode,
306 workdir: Option<&Path>,
307) -> Result<TaskExecution, TaskError> {
308 let recipes = list_recipes(justfile_path, mode, workdir).await?;
310 let recipe = recipes
311 .iter()
312 .find(|r| r.name == recipe_name)
313 .ok_or_else(|| TaskError::RecipeNotFound(recipe_name.to_string()))?;
314
315 for value in args.values() {
317 validate_arg_value(value)?;
318 }
319
320 execute_with_justfile(recipe, args, justfile_path, workdir, timeout).await
321}
322
323pub async fn execute_recipe_merged(
329 recipe_name: &str,
330 args: &HashMap<String, String>,
331 project_justfile_path: &Path,
332 global_justfile_path: Option<&Path>,
333 timeout: Duration,
334 mode: &TaskMode,
335 project_workdir: Option<&Path>,
336) -> Result<TaskExecution, TaskError> {
337 let recipes = list_recipes_merged(
339 project_justfile_path,
340 global_justfile_path,
341 mode,
342 project_workdir,
343 )
344 .await?;
345
346 let recipe = recipes
347 .iter()
348 .find(|r| r.name == recipe_name)
349 .ok_or_else(|| TaskError::RecipeNotFound(recipe_name.to_string()))?;
350
351 for value in args.values() {
353 validate_arg_value(value)?;
354 }
355
356 let effective_justfile = match recipe.source {
358 RecipeSource::Global => global_justfile_path
359 .ok_or_else(|| TaskError::RecipeNotFound(recipe_name.to_string()))?,
360 RecipeSource::Project => project_justfile_path,
361 };
362
363 execute_with_justfile(recipe, args, effective_justfile, project_workdir, timeout).await
364}
365
366async fn execute_with_justfile(
372 recipe: &Recipe,
373 args: &HashMap<String, String>,
374 effective_justfile: &Path,
375 project_workdir: Option<&Path>,
376 timeout: Duration,
377) -> Result<TaskExecution, TaskError> {
378 let positional: Vec<&str> = recipe
380 .parameters
381 .iter()
382 .filter_map(|p| args.get(&p.name).map(|v| v.as_str()))
383 .collect();
384
385 let started_at = SystemTime::now()
386 .duration_since(UNIX_EPOCH)
387 .unwrap_or_default()
388 .as_secs();
389 let start_instant = std::time::Instant::now();
390
391 let mut cmd = Command::new("just");
392 cmd.arg("--justfile").arg(effective_justfile);
393 if let Some(dir) = project_workdir {
394 cmd.arg("--working-directory").arg(dir);
395 cmd.current_dir(dir);
396 }
397 cmd.arg(&recipe.name);
398 for arg in &positional {
399 cmd.arg(arg);
400 }
401
402 let run_result = tokio::time::timeout(timeout, cmd.output()).await;
403 let duration_ms = start_instant.elapsed().as_millis() as u64;
404
405 let output = match run_result {
406 Err(_) => return Err(TaskError::Timeout),
407 Ok(Err(io_err)) => return Err(TaskError::Io(io_err)),
408 Ok(Ok(out)) => out,
409 };
410
411 let exit_code = output.status.code();
412 let raw_stdout = String::from_utf8_lossy(&output.stdout).into_owned();
413 let raw_stderr = String::from_utf8_lossy(&output.stderr).into_owned();
414 let (stdout, stdout_truncated) = truncate_output(&raw_stdout);
415 let (stderr, stderr_truncated) = truncate_output(&raw_stderr);
416 let truncated = stdout_truncated || stderr_truncated;
417
418 Ok(TaskExecution {
419 id: Uuid::new_v4().to_string(),
420 task_name: recipe.name.clone(),
421 args: args.clone(),
422 exit_code,
423 stdout,
424 stderr,
425 started_at,
426 duration_ms,
427 truncated,
428 })
429}
430
431pub struct TaskLogStore {
440 logs: Mutex<VecDeque<TaskExecution>>,
441 max_entries: usize,
442}
443
444impl TaskLogStore {
445 pub fn new(max_entries: usize) -> Self {
446 Self {
447 logs: Mutex::new(VecDeque::new()),
448 max_entries,
449 }
450 }
451
452 pub fn push(&self, execution: TaskExecution) {
454 let mut guard = self.logs.lock().expect("log store lock poisoned");
455 if guard.len() >= self.max_entries {
456 guard.pop_front();
457 }
458 guard.push_back(execution);
459 }
460
461 pub fn get(&self, id: &str) -> Option<TaskExecution> {
463 let guard = self.logs.lock().expect("log store lock poisoned");
464 guard.iter().find(|e| e.id == id).cloned()
465 }
466
467 pub fn recent(&self, n: usize) -> Vec<TaskExecutionSummary> {
469 let guard = self.logs.lock().expect("log store lock poisoned");
470 guard
471 .iter()
472 .rev()
473 .take(n)
474 .map(TaskExecutionSummary::from_execution)
475 .collect()
476 }
477}
478
479#[cfg(test)]
480mod tests {
481 use super::*;
482 use crate::just::model::RecipeAttribute;
483
484 fn make_recipe(name: &str, attributes: Vec<RecipeAttribute>) -> JustRecipe {
485 make_recipe_with_doc(name, attributes, None)
486 }
487
488 fn make_recipe_with_doc(
489 name: &str,
490 attributes: Vec<RecipeAttribute>,
491 doc: Option<&str>,
492 ) -> JustRecipe {
493 crate::just::model::JustRecipe {
494 name: name.to_string(),
495 namepath: name.to_string(),
496 doc: doc.map(str::to_string),
497 attributes,
498 parameters: vec![],
499 private: false,
500 quiet: false,
501 }
502 }
503
504 #[test]
505 fn has_allow_agent_group_attribute_true() {
506 let recipe = make_recipe(
507 "build",
508 vec![RecipeAttribute::Object(
509 [("group".to_string(), Some("allow-agent".to_string()))]
510 .into_iter()
511 .collect(),
512 )],
513 );
514 assert!(has_allow_agent_group_attribute(&recipe));
515 }
516
517 #[test]
518 fn has_allow_agent_group_attribute_false_no_attrs() {
519 let recipe = make_recipe("deploy", vec![]);
520 assert!(!has_allow_agent_group_attribute(&recipe));
521 }
522
523 #[test]
524 fn has_allow_agent_group_attribute_false_other_group() {
525 let recipe = make_recipe(
526 "build",
527 vec![RecipeAttribute::Object(
528 [("group".to_string(), Some("ci".to_string()))]
529 .into_iter()
530 .collect(),
531 )],
532 );
533 assert!(!has_allow_agent_group_attribute(&recipe));
534 }
535
536 #[test]
537 fn has_allow_agent_group_attribute_false_legacy_agent_literal() {
538 let recipe = make_recipe(
541 "build",
542 vec![RecipeAttribute::Object(
543 [("group".to_string(), Some("agent".to_string()))]
544 .into_iter()
545 .collect(),
546 )],
547 );
548 assert!(!has_allow_agent_group_attribute(&recipe));
549 }
550
551 #[test]
552 fn has_allow_agent_doc_true() {
553 let recipe = make_recipe_with_doc("build", vec![], Some("[allow-agent]"));
554 assert!(has_allow_agent_doc(&recipe));
555 }
556
557 #[test]
558 fn has_allow_agent_doc_false_no_doc() {
559 let recipe = make_recipe("build", vec![]);
560 assert!(!has_allow_agent_doc(&recipe));
561 }
562
563 #[test]
564 fn has_allow_agent_doc_false_other_doc() {
565 let recipe = make_recipe_with_doc("build", vec![], Some("Build the project"));
566 assert!(!has_allow_agent_doc(&recipe));
567 }
568
569 #[test]
570 fn has_allow_agent_doc_false_substring_in_prose() {
571 let recipe = make_recipe_with_doc(
573 "build",
574 vec![],
575 Some("do not add-[allow-agent]-here casually"),
576 );
577 assert!(!has_allow_agent_doc(&recipe));
578 }
579
580 #[test]
581 fn has_allow_agent_doc_true_with_surrounding_whitespace() {
582 let recipe = make_recipe_with_doc("build", vec![], Some(" [allow-agent] "));
583 assert!(has_allow_agent_doc(&recipe));
584 }
585
586 #[test]
587 fn is_allow_agent_pattern_a() {
588 let recipe = make_recipe(
589 "build",
590 vec![RecipeAttribute::Object(
591 [("group".to_string(), Some("allow-agent".to_string()))]
592 .into_iter()
593 .collect(),
594 )],
595 );
596 assert!(is_allow_agent(&recipe));
597 }
598
599 #[test]
600 fn is_allow_agent_pattern_b() {
601 let recipe = make_recipe_with_doc("build", vec![], Some("[allow-agent]"));
602 assert!(is_allow_agent(&recipe));
603 }
604
605 #[test]
606 fn is_allow_agent_pattern_a_plus_other_groups() {
607 let recipe = make_recipe(
611 "build",
612 vec![
613 RecipeAttribute::Object(
614 [("group".to_string(), Some("allow-agent".to_string()))]
615 .into_iter()
616 .collect(),
617 ),
618 RecipeAttribute::Object(
619 [("group".to_string(), Some("profile".to_string()))]
620 .into_iter()
621 .collect(),
622 ),
623 ],
624 );
625 assert!(is_allow_agent(&recipe));
626 }
627
628 #[test]
629 fn is_allow_agent_neither() {
630 let recipe = make_recipe("deploy", vec![]);
631 assert!(!is_allow_agent(&recipe));
632 }
633
634 #[test]
635 fn is_allow_agent_non_agent_group_only() {
636 let recipe = make_recipe_with_doc(
641 "foo",
642 vec![RecipeAttribute::Object(
643 [("group".to_string(), Some("profile".to_string()))]
644 .into_iter()
645 .collect(),
646 )],
647 Some("[allow-agent]"),
648 );
649 assert!(is_allow_agent(&recipe));
650 }
651
652 #[test]
653 fn resolve_justfile_path_override() {
654 let p = resolve_justfile_path(Some("/custom/justfile"), None);
655 assert_eq!(p, PathBuf::from("/custom/justfile"));
656 }
657
658 #[test]
659 fn resolve_justfile_path_default() {
660 let p = resolve_justfile_path(None, None);
661 assert_eq!(p, PathBuf::from("justfile"));
662 }
663
664 #[test]
665 fn resolve_justfile_path_with_workdir() {
666 let workdir = Path::new("/some/project");
667 let p = resolve_justfile_path(None, Some(workdir));
668 assert_eq!(p, PathBuf::from("/some/project/justfile"));
669 }
670
671 #[test]
672 fn resolve_justfile_path_override_ignores_workdir() {
673 let workdir = Path::new("/some/project");
675 let p = resolve_justfile_path(Some("/custom/justfile"), Some(workdir));
676 assert_eq!(p, PathBuf::from("/custom/justfile"));
677 }
678
679 #[test]
684 fn truncate_output_short_input_unchanged() {
685 let input = "hello";
686 let (result, truncated) = truncate_output(input);
687 assert!(!truncated);
688 assert_eq!(result, input);
689 }
690
691 #[test]
692 fn truncate_output_long_input_truncated() {
693 let input = "x".repeat(200 * 1024);
695 let (result, truncated) = truncate_output(&input);
696 assert!(truncated);
697 assert!(result.contains("...[truncated"));
698 assert!(result.len() < input.len());
700 }
701
702 #[test]
703 fn truncate_output_utf8_boundary() {
704 let char_3bytes = '日';
707 let count = (MAX_OUTPUT_BYTES / 3) + 10;
709 let input: String = std::iter::repeat_n(char_3bytes, count).collect();
710 let (result, truncated) = truncate_output(&input);
711 assert!(std::str::from_utf8(result.as_bytes()).is_ok());
713 if truncated {
714 assert!(result.contains("...[truncated"));
715 }
716 }
717
718 #[test]
723 fn validate_arg_value_safe_values() {
724 assert!(validate_arg_value("hello world").is_ok());
725 assert!(validate_arg_value("value_123-abc").is_ok());
726 assert!(validate_arg_value("path/to/file.txt").is_ok());
727 }
728
729 #[test]
730 fn validate_arg_value_semicolon_allowed() {
731 assert!(validate_arg_value("foo; rm -rf /").is_ok());
732 }
733
734 #[test]
735 fn validate_arg_value_pipe_allowed() {
736 assert!(validate_arg_value("foo | cat /etc/passwd").is_ok());
737 }
738
739 #[test]
740 fn validate_arg_value_and_and_allowed() {
741 assert!(validate_arg_value("foo && evil").is_ok());
742 }
743
744 #[test]
745 fn validate_arg_value_backtick_allowed() {
746 assert!(validate_arg_value("foo`id`").is_ok());
747 }
748
749 #[test]
750 fn validate_arg_value_dollar_paren_allowed() {
751 assert!(validate_arg_value("$(id)").is_ok());
752 }
753
754 #[test]
755 fn validate_arg_value_newline_rejected() {
756 assert!(validate_arg_value("foo\nbar").is_err());
757 }
758
759 #[test]
760 fn validate_arg_value_carriage_return_rejected() {
761 assert!(validate_arg_value("foo\rbar").is_err());
762 }
763
764 #[test]
765 fn validate_arg_value_shell_metacharacters_allowed() {
766 assert!(validate_arg_value("https://example.com?a=1&b=2").is_ok());
769 assert!(validate_arg_value("value with ${VAR} reference").is_ok());
770 assert!(validate_arg_value(".items[] | select(.name)").is_ok());
771 assert!(validate_arg_value("echo hello; echo world").is_ok());
772 assert!(validate_arg_value("foo || bar").is_ok());
773 assert!(validate_arg_value("result=$(cmd)").is_ok());
774 assert!(validate_arg_value("hello `world`").is_ok());
775 }
776
777 fn make_execution(id: &str, task_name: &str) -> TaskExecution {
782 TaskExecution {
783 id: id.to_string(),
784 task_name: task_name.to_string(),
785 args: HashMap::new(),
786 exit_code: Some(0),
787 stdout: "".to_string(),
788 stderr: "".to_string(),
789 started_at: 0,
790 duration_ms: 0,
791 truncated: false,
792 }
793 }
794
795 #[test]
796 fn task_log_store_push_and_get() {
797 let store = TaskLogStore::new(10);
798 let exec = make_execution("id-1", "build");
799 store.push(exec);
800 let retrieved = store.get("id-1").expect("should find id-1");
801 assert_eq!(retrieved.task_name, "build");
802 }
803
804 #[test]
805 fn task_log_store_get_missing() {
806 let store = TaskLogStore::new(10);
807 assert!(store.get("nonexistent").is_none());
808 }
809
810 #[test]
811 fn task_log_store_evicts_oldest_when_full() {
812 let store = TaskLogStore::new(3);
813 store.push(make_execution("id-1", "a"));
814 store.push(make_execution("id-2", "b"));
815 store.push(make_execution("id-3", "c"));
816 store.push(make_execution("id-4", "d")); assert!(store.get("id-1").is_none(), "id-1 should be evicted");
818 assert!(store.get("id-4").is_some(), "id-4 should exist");
819 }
820
821 #[test]
822 fn task_log_store_recent_newest_first() {
823 let store = TaskLogStore::new(10);
824 store.push(make_execution("id-1", "a"));
825 store.push(make_execution("id-2", "b"));
826 store.push(make_execution("id-3", "c"));
827 let recent = store.recent(2);
828 assert_eq!(recent.len(), 2);
829 assert_eq!(recent[0].id, "id-3", "newest should be first");
830 assert_eq!(recent[1].id, "id-2");
831 }
832
833 #[test]
834 fn task_log_store_recent_n_larger_than_store() {
835 let store = TaskLogStore::new(10);
836 store.push(make_execution("id-1", "a"));
837 let recent = store.recent(5);
838 assert_eq!(recent.len(), 1);
839 }
840}