1use axum::{
123 extract::{Path, Query, State},
124 http::{header, HeaderMap, HeaderValue, StatusCode},
125 response::IntoResponse,
126 Json,
127};
128use mlua_swarm::core::engine::Engine;
129use mlua_swarm::core::projection::{
130 ProjectionAdapter, ProjectionError, ProjectionKey, ProjectionRef,
131};
132use mlua_swarm::core::projection_placement::ProjectionPlacement;
133use mlua_swarm::core::step_naming::StepNaming;
134use mlua_swarm::store::output::{ContentRef, OutputEvent, OutputStore, OutputStoreError};
135use mlua_swarm::store::run::{RunRecord, RunStore};
136use mlua_swarm::{RunId, StepId, TaskId};
137use serde::{Deserialize, Serialize};
138use serde_json::Value;
139use sha2::Digest as _;
140use std::sync::Arc;
141
142use crate::tasks::map_task_store_err;
143use crate::{ApiError, AppState};
144
145pub struct McpQueryAdapter {
153 data_store: Arc<dyn OutputStore>,
154 run_store: Arc<dyn RunStore>,
155 engine: Engine,
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
162#[serde(rename_all = "snake_case")]
163pub enum ProjectionSource {
164 DataPlane,
167 ResultRef,
170}
171
172#[derive(Debug, Clone)]
178pub(crate) struct ResolvedStep {
179 pub(crate) name: String,
182 pub(crate) value: Value,
184 pub(crate) source: ProjectionSource,
186}
187
188fn final_value(event: &OutputEvent) -> Option<Value> {
194 match event {
195 OutputEvent::Final { content, .. } => Some(content_to_value(content)),
196 _ => None,
197 }
198}
199
200fn content_to_value(content: &ContentRef) -> Value {
205 match content {
206 ContentRef::Inline { value } => value.clone(),
207 ContentRef::FileRef {
208 path,
209 mime,
210 size_hint,
211 } => serde_json::json!({
212 "file_ref": path.to_string_lossy(),
213 "mime": mime,
214 "size_hint": size_hint,
215 }),
216 }
217}
218
219fn find_step_id_for_canonical(
228 run: &RunRecord,
229 naming: Option<&StepNaming>,
230 canonical: &str,
231) -> Option<StepId> {
232 run.step_entries
233 .iter()
234 .rev()
235 .find(|entry| {
236 let Some(step_ref) = entry.step_ref.as_deref() else {
237 return false;
238 };
239 match naming {
240 Some(n) => n.canonical_of_producer(step_ref) == Some(canonical),
241 None => step_ref == canonical,
242 }
243 })
244 .map(|entry| entry.step_id.clone())
245}
246
247fn candidate_names<'a>(
256 naming: Option<&'a StepNaming>,
257 canonical: &'a str,
258 raw_step: &'a str,
259) -> Vec<&'a str> {
260 let mut names = vec![canonical];
261 if let Some(entry) = naming.and_then(|n| n.entries().find(|e| e.canonical == canonical)) {
262 for alias in &entry.aliases {
263 if alias != canonical {
264 names.push(alias.as_str());
265 }
266 }
267 }
268 if !names.contains(&raw_step) {
269 names.push(raw_step);
270 }
271 names
272}
273
274impl McpQueryAdapter {
275 pub fn new(
280 data_store: Arc<dyn OutputStore>,
281 run_store: Arc<dyn RunStore>,
282 engine: Engine,
283 ) -> Self {
284 Self {
285 data_store,
286 run_store,
287 engine,
288 }
289 }
290
291 async fn step_naming_for_run(&self, run: &RunRecord) -> Option<Arc<StepNaming>> {
307 resolve_step_naming_for_run(&self.engine, run).await
308 }
309
310 pub(crate) async fn resolve_step_name(&self, run: &RunRecord, raw: &str) -> String {
318 match self.step_naming_for_run(run).await {
319 Some(naming) => naming.resolve(raw).unwrap_or(raw).to_string(),
320 None => raw.to_string(),
321 }
322 }
323
324 async fn resolve_run(
332 &self,
333 task_id: &TaskId,
334 run_id: Option<&str>,
335 ) -> Result<RunRecord, ProjectionError> {
336 match run_id {
337 Some(rid) => {
338 let run_id = RunId::parse(rid.to_string())
339 .map_err(|e| ProjectionError::InvalidKey(format!("run_id: {e}")))?;
340 let run = self.run_store.get(&run_id).await.map_err(|_| {
341 ProjectionError::NotFound(ProjectionKey {
342 task_id: task_id.to_string(),
343 run_id: Some(rid.to_string()),
344 step: None,
345 path: None,
346 })
347 })?;
348 if &run.task_id != task_id {
349 return Err(ProjectionError::NotFound(ProjectionKey {
350 task_id: task_id.to_string(),
351 run_id: Some(rid.to_string()),
352 step: None,
353 path: None,
354 }));
355 }
356 Ok(run)
357 }
358 None => {
359 let mut runs = self.run_store.list_by_task(task_id).await.map_err(|_| {
360 ProjectionError::NotFound(ProjectionKey {
361 task_id: task_id.to_string(),
362 run_id: None,
363 step: None,
364 path: None,
365 })
366 })?;
367 runs.pop().ok_or_else(|| {
368 ProjectionError::NotFound(ProjectionKey {
369 task_id: task_id.to_string(),
370 run_id: None,
371 step: None,
372 path: None,
373 })
374 })
375 }
376 }
377 }
378
379 async fn resolve_async(
399 &self,
400 key: &ProjectionKey,
401 ) -> Result<(RunRecord, Value), ProjectionError> {
402 let task_id = TaskId::parse(key.task_id.clone())
403 .map_err(|e| ProjectionError::InvalidKey(format!("task_id: {e}")))?;
404 let run = self.resolve_run(&task_id, key.run_id.as_deref()).await?;
405
406 let Some(raw_step) = &key.step else {
407 let ctx_data = run.result_ref.clone().unwrap_or(Value::Null);
410 let value = key
411 .resolve(&ctx_data)
412 .cloned()
413 .ok_or_else(|| ProjectionError::NotFound(key.clone()))?;
414 return Ok((run, value));
415 };
416
417 let naming = self.step_naming_for_run(&run).await;
418 let canonical = naming
419 .as_deref()
420 .and_then(|n| n.resolve(raw_step))
421 .unwrap_or(raw_step.as_str())
422 .to_string();
423
424 if let Some(step_id) = find_step_id_for_canonical(&run, naming.as_deref(), &canonical) {
426 match self
427 .data_store
428 .get_latest_by_name_in_run(step_id.as_str(), 1, &canonical)
429 .await
430 {
431 Ok(record) => {
432 if let Some(value) = final_value(&record.event) {
433 let narrowed = match &key.path {
434 None => Some(value),
435 Some(_) => {
436 let path_only = ProjectionKey {
442 task_id: key.task_id.clone(),
443 run_id: key.run_id.clone(),
444 step: None,
445 path: key.path.clone(),
446 };
447 path_only.resolve(&value).cloned()
448 }
449 };
450 if let Some(value) = narrowed {
451 return Ok((run, value));
452 }
453 }
454 }
455 Err(OutputStoreError::NotFound(_)) => {
456 }
459 Err(other) => {
460 return Err(ProjectionError::Io(std::io::Error::other(format!(
461 "OutputStore::get_latest_by_name_in_run: {other}"
462 ))));
463 }
464 }
465 }
466
467 let ctx_data = run.result_ref.clone().unwrap_or(Value::Null);
472 for candidate in candidate_names(naming.as_deref(), &canonical, raw_step) {
473 let candidate_key = ProjectionKey {
474 task_id: key.task_id.clone(),
475 run_id: key.run_id.clone(),
476 step: Some(candidate.to_string()),
477 path: key.path.clone(),
478 };
479 if let Some(value) = candidate_key.resolve(&ctx_data) {
480 return Ok((run, value.clone()));
481 }
482 }
483 Err(ProjectionError::NotFound(key.clone()))
484 }
485
486 pub(crate) async fn list_steps(
492 &self,
493 task_id: &TaskId,
494 run_id: Option<&str>,
495 ) -> Result<(RunRecord, Vec<ResolvedStep>), ProjectionError> {
496 let run = self.resolve_run(task_id, run_id).await?;
497 let steps = self.enumerate_steps(&run).await;
498 Ok((run, steps))
499 }
500
501 pub(crate) async fn list_steps_by_run_id(
509 &self,
510 run_id: &RunId,
511 ) -> Result<(RunRecord, Vec<ResolvedStep>), ProjectionError> {
512 let run = self.run_store.get(run_id).await.map_err(|_| {
513 ProjectionError::NotFound(ProjectionKey {
514 task_id: String::new(),
515 run_id: Some(run_id.to_string()),
516 step: None,
517 path: None,
518 })
519 })?;
520 let steps = self.enumerate_steps(&run).await;
521 Ok((run, steps))
522 }
523
524 async fn enumerate_steps(&self, run: &RunRecord) -> Vec<ResolvedStep> {
531 match self.step_naming_for_run(run).await {
532 Some(naming) => self.enumerate_steps_via_table(run, &naming).await,
533 None => self.enumerate_steps_legacy_union(run).await,
534 }
535 }
536
537 async fn enumerate_steps_via_table(
556 &self,
557 run: &RunRecord,
558 naming: &StepNaming,
559 ) -> Vec<ResolvedStep> {
560 let mut resolved: std::collections::BTreeMap<String, ResolvedStep> =
561 std::collections::BTreeMap::new();
562
563 for entry in &run.step_entries {
564 let Some(step_ref) = entry.step_ref.as_deref() else {
565 continue;
566 };
567 let canonical = naming
568 .canonical_of_producer(step_ref)
569 .unwrap_or(step_ref)
570 .to_string();
571 if let Ok(record) = self
572 .data_store
573 .get_latest_by_name_in_run(entry.step_id.as_str(), 1, &canonical)
574 .await
575 {
576 if let Some(value) = final_value(&record.event) {
577 resolved.insert(
578 canonical.clone(),
579 ResolvedStep {
580 name: canonical,
581 value,
582 source: ProjectionSource::DataPlane,
583 },
584 );
585 }
586 }
587
588 if let Ok(records) = self
604 .data_store
605 .list_for_attempt(entry.step_id.as_str(), 1)
606 .await
607 {
608 for record in records {
609 if let OutputEvent::Artifact { name, content } = &record.event {
610 resolved
611 .entry(name.clone())
612 .or_insert_with(|| ResolvedStep {
613 name: name.clone(),
614 value: content_to_value(content),
615 source: ProjectionSource::DataPlane,
616 });
617 }
618 }
619 }
620 }
621
622 if let Some(Value::Object(map)) = &run.result_ref {
623 for entry in naming.entries() {
624 if resolved.contains_key(&entry.canonical) {
625 continue;
626 }
627 let hit = entry
628 .aliases
629 .iter()
630 .find_map(|alias| map.get(alias))
631 .or_else(|| map.get(&entry.canonical));
632 if let Some(value) = hit {
633 resolved.insert(
634 entry.canonical.clone(),
635 ResolvedStep {
636 name: entry.canonical.clone(),
637 value: value.clone(),
638 source: ProjectionSource::ResultRef,
639 },
640 );
641 }
642 }
643 }
644
645 resolved.into_values().collect()
646 }
647
648 async fn enumerate_steps_legacy_union(&self, run: &RunRecord) -> Vec<ResolvedStep> {
659 let mut out = Vec::new();
660 let mut attempted = std::collections::HashSet::new();
661 let mut resolved_names = std::collections::HashSet::new();
662
663 for entry in &run.step_entries {
664 let Some(name) = &entry.step_ref else {
665 continue;
666 };
667 if !attempted.insert(name.clone()) {
668 continue;
669 }
670 if let Ok(record) = self.data_store.get_latest_by_name(name).await {
671 if let Some(value) = final_value(&record.event) {
672 out.push(ResolvedStep {
673 name: name.clone(),
674 value,
675 source: ProjectionSource::DataPlane,
676 });
677 resolved_names.insert(name.clone());
678 }
679 }
680 }
681
682 if let Some(Value::Object(map)) = &run.result_ref {
683 for (name, value) in map {
684 if resolved_names.contains(name) {
685 continue;
686 }
687 out.push(ResolvedStep {
688 name: name.clone(),
689 value: value.clone(),
690 source: ProjectionSource::ResultRef,
691 });
692 }
693 }
694
695 out
696 }
697}
698
699impl ProjectionAdapter for McpQueryAdapter {
700 fn name(&self) -> &'static str {
701 "mcp-query"
702 }
703
704 fn project(
713 &self,
714 key: &ProjectionKey,
715 ctx_data: &Value,
716 ) -> Result<ProjectionRef, ProjectionError> {
717 if key.task_id.is_empty() {
718 return Err(ProjectionError::InvalidKey(
719 "task_id must not be empty".to_string(),
720 ));
721 }
722 key.resolve(ctx_data)
723 .ok_or_else(|| ProjectionError::NotFound(key.clone()))?;
724 Ok(ProjectionRef::Query {
725 endpoint: format!(
726 "/v1/tasks/{}/runs/{}/steps/{}/content",
727 key.task_id,
728 key.run_id.as_deref().unwrap_or("latest"),
729 key.step.as_deref().unwrap_or("_ctx")
730 ),
731 key: key.clone(),
732 })
733 }
734
735 fn fetch(&self, key: &ProjectionKey) -> Result<Value, ProjectionError> {
736 let handle = tokio::runtime::Handle::try_current().map_err(|e| {
741 ProjectionError::Io(std::io::Error::other(format!(
742 "McpQueryAdapter::fetch requires a Tokio runtime: {e}"
743 )))
744 })?;
745 let (_run, value) =
746 tokio::task::block_in_place(|| handle.block_on(self.resolve_async(key)))?;
747 Ok(value)
748 }
749
750 fn pointer_line(&self, r: &ProjectionRef) -> String {
751 match r {
752 ProjectionRef::Query { endpoint, key } => {
753 format!("projection(mcp-query): {endpoint} task_id={}", key.task_id)
754 }
755 ProjectionRef::File { path } => format!("projection(file): {path}"),
756 }
757 }
758}
759
760#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
766pub struct StepList {
767 pub task_id: String,
769 pub run_id: String,
772 pub steps: Vec<StepSummary>,
776}
777
778#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
782pub struct StepSummary {
783 pub name: String,
785 pub size_bytes: u64,
788 pub content_type: String,
793 pub sha256: String,
796 pub source: ProjectionSource,
798 #[serde(default, skip_serializing_if = "Option::is_none")]
806 pub file_path: Option<String>,
807 pub content_url: String,
812 pub preview: String,
815 pub truncated: bool,
819}
820
821#[derive(Debug, Deserialize, Default, schemars::JsonSchema)]
826pub struct StepPathQuery {
827 #[serde(default)]
830 pub path: Option<String>,
831}
832
833fn narrow_step_value(value: &Value, path: Option<&str>) -> Option<Value> {
837 match path {
838 None => Some(value.clone()),
839 Some(p) => {
840 let path_only = ProjectionKey {
841 task_id: String::new(),
842 run_id: None,
843 step: None,
844 path: Some(p.to_string()),
845 };
846 path_only.resolve(value).cloned()
847 }
848 }
849}
850
851fn materialized_file_path(
858 placement: &ProjectionPlacement,
859 root: &str,
860 step_id: &StepId,
861 name: &str,
862) -> std::path::PathBuf {
863 placement.target_path(root, step_id.as_ref(), name)
864}
865
866async fn resolve_materialized_file(
886 state: &AppState,
887 run: &RunRecord,
888 name: &str,
889) -> Option<(std::path::PathBuf, Vec<u8>)> {
890 let naming = resolve_step_naming_for_run(&state.engine, run).await;
891 let step_id = find_step_id_for_canonical(run, naming.as_deref(), name)?;
892 let view = state.engine.agent_context_for(&step_id, 1).await?;
893 let placement = state
894 .engine
895 .projection_placement_for(&step_id)
896 .await
897 .unwrap_or_default();
898 let root = placement.resolve_root(&view)?;
899 let path = materialized_file_path(&placement, &root, &step_id, name);
900 let bytes = std::fs::read(&path).ok()?;
901 Some((path, bytes))
902}
903
904async fn resolve_step_naming_for_run(engine: &Engine, run: &RunRecord) -> Option<Arc<StepNaming>> {
909 for entry in &run.step_entries {
910 if let Some(naming) = engine.step_naming_for(&entry.step_id).await {
911 return Some(naming);
912 }
913 }
914 None
915}
916
917async fn render_step_body(
924 state: &AppState,
925 run: &RunRecord,
926 step: &ResolvedStep,
927 path: Option<&str>,
928) -> Option<(Vec<u8>, &'static str, Option<String>)> {
929 if path.is_none() {
930 if let Some((file_path, bytes)) = resolve_materialized_file(state, run, &step.name).await {
931 return Some((
932 bytes,
933 "text/markdown; charset=utf-8",
934 Some(file_path.to_string_lossy().into_owned()),
935 ));
936 }
937 }
938 let narrowed = narrow_step_value(&step.value, path)?;
939 let body = serde_json::to_vec_pretty(&narrowed).ok()?;
940 Some((body, "application/json", None))
941}
942
943fn build_preview(body: &[u8]) -> (String, bool) {
950 const MAX_PREVIEW_BYTES: usize = 512;
951 if body.len() <= MAX_PREVIEW_BYTES {
952 return (String::from_utf8_lossy(body).into_owned(), false);
953 }
954 let preview = match std::str::from_utf8(body) {
955 Ok(s) => {
956 let mut end = MAX_PREVIEW_BYTES;
957 while end > 0 && !s.is_char_boundary(end) {
958 end -= 1;
959 }
960 s[..end].to_string()
961 }
962 Err(_) => String::from_utf8_lossy(&body[..MAX_PREVIEW_BYTES]).into_owned(),
963 };
964 (format!("{preview}…"), true)
965}
966
967fn build_content_url(
973 base_url: &Option<Arc<str>>,
974 task_id: &TaskId,
975 run_id: &RunId,
976 name: &str,
977 path: Option<&str>,
978) -> String {
979 let mut url = format!("/v1/tasks/{task_id}/runs/{run_id}/steps/{name}/content");
980 if let Some(p) = path {
981 url.push_str("?path=");
982 url.push_str(p);
983 }
984 match base_url {
985 Some(base) => format!("{}{}", base.trim_end_matches('/'), url),
986 None => url,
987 }
988}
989
990async fn build_step_summary(
993 state: &AppState,
994 run: &RunRecord,
995 step: &ResolvedStep,
996 path: Option<&str>,
997) -> Option<StepSummary> {
998 let (body, content_type, file_path) = render_step_body(state, run, step, path).await?;
999 let sha256 = hex::encode(sha2::Sha256::digest(&body));
1000 let size_bytes = body.len() as u64;
1001 let (preview, truncated) = build_preview(&body);
1002 let content_url = build_content_url(&state.base_url, &run.task_id, &run.id, &step.name, path);
1003 Some(StepSummary {
1004 name: step.name.clone(),
1005 size_bytes,
1006 content_type: content_type.to_string(),
1007 sha256,
1008 source: step.source,
1009 file_path,
1010 content_url,
1011 preview,
1012 truncated,
1013 })
1014}
1015
1016pub(crate) async fn resolve_step_pointer_fields(
1027 state: &AppState,
1028 run: &RunRecord,
1029 step: &ResolvedStep,
1030) -> Option<(u64, Option<String>, String, String)> {
1031 let (body, _content_type, file_path) = render_step_body(state, run, step, None).await?;
1032 let sha256 = hex::encode(sha2::Sha256::digest(&body));
1033 let size_bytes = body.len() as u64;
1034 let content_url = build_content_url(&state.base_url, &run.task_id, &run.id, &step.name, None);
1035 Some((size_bytes, file_path, content_url, sha256))
1036}
1037
1038async fn resolve_run_and_steps(
1047 state: &AppState,
1048 id: &str,
1049 run: &str,
1050) -> Result<(McpQueryAdapter, RunRecord, Vec<ResolvedStep>), ApiError> {
1051 let task_id = TaskId::parse(id.to_string())
1052 .map_err(|e| ApiError::bad_request(format!("invalid task id: {e}")))?;
1053 state
1054 .task_store
1055 .get(&task_id)
1056 .await
1057 .map_err(map_task_store_err)?;
1058 let adapter = McpQueryAdapter::new(
1059 state.data_store.clone(),
1060 state.run_store.clone(),
1061 state.engine.clone(),
1062 );
1063 let run_sel = if run == "latest" { None } else { Some(run) };
1064 let (run_record, steps) = adapter
1065 .list_steps(&task_id, run_sel)
1066 .await
1067 .map_err(map_projection_err)?;
1068 Ok((adapter, run_record, steps))
1069}
1070
1071pub async fn steps_list(
1074 State(state): State<AppState>,
1075 Path((id, run)): Path<(String, String)>,
1076) -> Result<Json<StepList>, ApiError> {
1077 let (_adapter, run_record, steps) = resolve_run_and_steps(&state, &id, &run).await?;
1078 let mut summaries = Vec::with_capacity(steps.len());
1079 for step in &steps {
1080 if let Some(summary) = build_step_summary(&state, &run_record, step, None).await {
1081 summaries.push(summary);
1082 }
1083 }
1084 Ok(Json(StepList {
1085 task_id: run_record.task_id.to_string(),
1086 run_id: run_record.id.to_string(),
1087 steps: summaries,
1088 }))
1089}
1090
1091pub async fn step_get(
1097 State(state): State<AppState>,
1098 Path((id, run, step)): Path<(String, String, String)>,
1099 Query(q): Query<StepPathQuery>,
1100) -> Result<Json<StepSummary>, ApiError> {
1101 let (adapter, run_record, steps) = resolve_run_and_steps(&state, &id, &run).await?;
1102 let canonical = adapter.resolve_step_name(&run_record, &step).await;
1103 let resolved = steps
1104 .into_iter()
1105 .find(|s| s.name == canonical)
1106 .ok_or_else(|| ApiError::not_found(format!("step not found: {step}")))?;
1107 let summary = build_step_summary(&state, &run_record, &resolved, q.path.as_deref())
1108 .await
1109 .ok_or_else(|| ApiError::not_found(format!("path not found: {:?}", q.path)))?;
1110 Ok(Json(summary))
1111}
1112
1113pub async fn step_content(
1119 State(state): State<AppState>,
1120 Path((id, run, step)): Path<(String, String, String)>,
1121 Query(q): Query<StepPathQuery>,
1122) -> Result<impl IntoResponse, ApiError> {
1123 let (adapter, run_record, steps) = resolve_run_and_steps(&state, &id, &run).await?;
1124 let canonical = adapter.resolve_step_name(&run_record, &step).await;
1125 let resolved = steps
1126 .into_iter()
1127 .find(|s| s.name == canonical)
1128 .ok_or_else(|| ApiError::not_found(format!("step not found: {step}")))?;
1129 let (body, content_type, _file_path) =
1130 render_step_body(&state, &run_record, &resolved, q.path.as_deref())
1131 .await
1132 .ok_or_else(|| ApiError::not_found(format!("path not found: {:?}", q.path)))?;
1133 let sha256 = hex::encode(sha2::Sha256::digest(&body));
1134 let mut headers = HeaderMap::new();
1135 headers.insert(
1136 header::CONTENT_TYPE,
1137 HeaderValue::from_str(content_type).expect("content_type is a static ASCII literal"),
1138 );
1139 headers.insert(
1140 header::ETAG,
1141 HeaderValue::from_str(&format!("\"sha256:{sha256}\""))
1142 .expect("hex digest is ASCII-safe for a header value"),
1143 );
1144 Ok((StatusCode::OK, headers, body))
1145}
1146
1147fn map_projection_err(e: ProjectionError) -> ApiError {
1148 match e {
1149 ProjectionError::NotFound(key) => {
1150 ApiError::not_found(format!("projection not found for key {key:?}"))
1151 }
1152 ProjectionError::InvalidKey(msg) => ApiError::bad_request(msg),
1153 other => ApiError::engine(other),
1154 }
1155}
1156
1157#[cfg(test)]
1162mod tests {
1163 use super::*;
1164 use crate::TaskLaunchRequest;
1165 use axum::http::StatusCode;
1166 use mlua_swarm::application::BlueprintRef;
1167 use mlua_swarm::blueprint::{
1168 current_schema_version, AgentDef, AgentKind, AgentMeta, Blueprint, BlueprintMetadata,
1169 CompilerHints, CompilerStrategy, ProjectionPlacementSpec,
1170 };
1171 use mlua_swarm::core::config::{CheckPolicy, EngineCfg};
1172 use mlua_swarm::core::engine::Engine;
1173 use mlua_swarm::store::output::InMemoryOutputStore;
1174 use mlua_swarm::store::run::InMemoryRunStore;
1175 use mlua_swarm::store::task::InMemoryTaskStore;
1176 use serde_json::json;
1177 use std::collections::HashMap;
1178 use tokio::sync::Mutex;
1179
1180 fn greeting_blueprint() -> Blueprint {
1188 Blueprint {
1189 schema_version: current_schema_version(),
1190 id: "projection-test-greeting-bp".into(),
1191 flow: serde_json::from_value(json!({
1192 "kind": "step",
1193 "ref": mlua_swarm::worker::baseline::AG_IDENTITY,
1194 "in": {"op": "path", "at": "$.greeting"},
1195 "out": {"op": "path", "at": "$.out"},
1196 }))
1197 .expect("flow parse"),
1198 agents: vec![AgentDef {
1199 name: mlua_swarm::worker::baseline::AG_IDENTITY.into(),
1200 kind: AgentKind::RustFn,
1201 spec: json!({"fn_id": mlua_swarm::worker::baseline::AG_IDENTITY}),
1202 profile: None,
1203 meta: None,
1204 runner: None,
1205 runner_ref: None,
1206 verdict: None,
1207 }],
1208 operators: vec![],
1209 metas: vec![],
1210 hints: CompilerHints::default(),
1211 strategy: CompilerStrategy::default(),
1212 metadata: BlueprintMetadata::default(),
1213 spawner_hints: Default::default(),
1214 default_agent_kind: AgentKind::Operator,
1215 default_operator_kind: None,
1216 default_init_ctx: None,
1217 default_agent_ctx: None,
1218 default_context_policy: None,
1219 projection_placement: None,
1220 audits: vec![],
1221 degradation_policy: None,
1222 runners: vec![],
1223 default_runner: None,
1224 check_policy: None,
1225 }
1226 }
1227
1228 fn test_state() -> AppState {
1229 let engine = Engine::new_with_layers(EngineCfg::default(), crate::default_layer_registry());
1230 let compiler = mlua_swarm::Compiler::new(crate::default_registry());
1231 let launch = Arc::new(mlua_swarm::TaskLaunchService::new(engine.clone(), compiler));
1232 let data_store: Arc<dyn mlua_swarm::store::output::OutputStore> =
1233 Arc::new(InMemoryOutputStore::new());
1234 engine.set_output_store(data_store.clone());
1240 AppState {
1241 engine,
1242 sessions: Arc::new(Mutex::new(crate::SessionStore::default())),
1243 task_app: Arc::new(mlua_swarm::TaskApplication::new_inline_only(launch)),
1244 ws_operator_factory: None,
1245 data_store,
1246 operator_sessions: Arc::new(Mutex::new(HashMap::new())),
1247 roles_to_sid: Arc::new(Mutex::new(HashMap::new())),
1248 task_store: Arc::new(InMemoryTaskStore::new()),
1249 run_store: Arc::new(InMemoryRunStore::new()),
1250 base_url: None,
1251 sync_timeout_secs: 300,
1252 }
1253 }
1254
1255 fn greeting_task_req(greeting: &str) -> TaskLaunchRequest {
1256 TaskLaunchRequest {
1257 blueprint: BlueprintRef::Inline {
1258 value: Box::new(greeting_blueprint()),
1259 },
1260 init_ctx: json!({ "greeting": greeting }),
1261 project_root: None,
1262 work_dir: None,
1263 task_metadata: None,
1264 ttl_secs: None,
1265 operator: None,
1266 operator_sid: None,
1267 timeout_secs: None,
1268 goal: Some("projection test goal".to_string()),
1269 detach: false,
1270 check_policy: None,
1271 }
1272 }
1273
1274 fn declared_projection_name_blueprint(projection_name: &str) -> Blueprint {
1280 Blueprint {
1281 schema_version: current_schema_version(),
1282 id: "projection-test-declared-name-bp".into(),
1283 flow: serde_json::from_value(json!({
1284 "kind": "step",
1285 "ref": mlua_swarm::worker::baseline::AG_IDENTITY,
1286 "in": {"op": "path", "at": "$.greeting"},
1287 "out": {"op": "path", "at": "$.out"},
1288 }))
1289 .expect("flow parse"),
1290 agents: vec![AgentDef {
1291 name: mlua_swarm::worker::baseline::AG_IDENTITY.into(),
1292 kind: AgentKind::RustFn,
1293 spec: json!({"fn_id": mlua_swarm::worker::baseline::AG_IDENTITY}),
1294 profile: None,
1295 meta: Some(AgentMeta {
1296 projection_name: Some(projection_name.to_string()),
1297 ..Default::default()
1298 }),
1299 runner: None,
1300 runner_ref: None,
1301 verdict: None,
1302 }],
1303 operators: vec![],
1304 metas: vec![],
1305 hints: CompilerHints::default(),
1306 strategy: CompilerStrategy::default(),
1307 metadata: BlueprintMetadata::default(),
1308 spawner_hints: Default::default(),
1309 default_agent_kind: AgentKind::Operator,
1310 default_operator_kind: None,
1311 default_init_ctx: None,
1312 default_agent_ctx: None,
1313 default_context_policy: None,
1314 projection_placement: None,
1315 audits: vec![],
1316 degradation_policy: None,
1317 runners: vec![],
1318 default_runner: None,
1319 check_policy: None,
1320 }
1321 }
1322
1323 fn declared_task_req(greeting: &str, projection_name: &str) -> TaskLaunchRequest {
1324 TaskLaunchRequest {
1325 blueprint: BlueprintRef::Inline {
1326 value: Box::new(declared_projection_name_blueprint(projection_name)),
1327 },
1328 init_ctx: json!({ "greeting": greeting }),
1329 project_root: None,
1330 work_dir: None,
1331 task_metadata: None,
1332 ttl_secs: None,
1333 operator: None,
1334 operator_sid: None,
1335 timeout_secs: None,
1336 goal: Some("projection test goal (declared name)".to_string()),
1337 detach: false,
1338 check_policy: None,
1339 }
1340 }
1341
1342 fn strict_greeting_blueprint() -> Blueprint {
1351 Blueprint {
1352 check_policy: Some(CheckPolicy::Strict),
1353 ..greeting_blueprint()
1354 }
1355 }
1356
1357 fn strict_greeting_task_req(greeting: &str, project_root: Option<&str>) -> TaskLaunchRequest {
1358 TaskLaunchRequest {
1359 blueprint: BlueprintRef::Inline {
1360 value: Box::new(strict_greeting_blueprint()),
1361 },
1362 init_ctx: json!({ "greeting": greeting }),
1363 project_root: project_root.map(String::from),
1364 work_dir: None,
1365 task_metadata: None,
1366 ttl_secs: None,
1367 operator: None,
1368 operator_sid: None,
1369 timeout_secs: None,
1370 goal: Some("pre-dispatch guard test goal".to_string()),
1371 detach: false,
1372 check_policy: None,
1373 }
1374 }
1375
1376 #[tokio::test]
1383 async fn tasks_start_rejects_strict_launch_with_no_roots_as_400() {
1384 let state = test_state();
1385 let result =
1389 crate::tasks_start(State(state), Json(strict_greeting_task_req("hello", None))).await;
1390 let err = match result {
1391 Err(e) => e,
1392 Ok(_) => {
1393 panic!("strict check_policy + no roots must be rejected before dispatch, got Ok")
1394 }
1395 };
1396 assert_eq!(err.status, StatusCode::BAD_REQUEST);
1397 assert!(
1398 err.message.contains("pre-dispatch"),
1399 "expected a pre-dispatch guard message, got: {}",
1400 err.message
1401 );
1402 }
1403
1404 #[tokio::test]
1409 async fn tasks_start_strict_launch_with_project_root_succeeds() {
1410 let state = test_state();
1411 let reply = crate::tasks_start(
1412 State(state),
1413 Json(strict_greeting_task_req("hello", Some("/repo"))),
1414 )
1415 .await
1416 .expect("strict check_policy + project_root supplied must pass the guard");
1417 assert_eq!(reply.1, StatusCode::OK);
1418 assert_eq!(reply.0.final_ctx["out"]["echoed"], "hello");
1419 }
1420
1421 #[tokio::test]
1431 async fn steps_list_undeclared_step_resolves_to_single_canonical_entry() {
1432 let state = test_state();
1433 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hello")))
1434 .await
1435 .expect("tasks_start")
1436 .0;
1437
1438 let resp = steps_list(
1439 State(state.clone()),
1440 Path((posted.task_id.to_string(), "latest".to_string())),
1441 )
1442 .await
1443 .expect("steps_list")
1444 .0;
1445
1446 assert_eq!(resp.task_id, posted.task_id.to_string());
1447 assert_eq!(resp.run_id, posted.run_id.to_string());
1448 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
1449 assert_eq!(resp.steps.len(), 1, "steps: {:?}", resp.steps);
1450 let entry = &resp.steps[0];
1451 assert_eq!(entry.name, identity_name);
1452 assert_eq!(entry.source, ProjectionSource::DataPlane);
1453 }
1454
1455 #[tokio::test]
1460 async fn step_get_resolves_alias_name_to_canonical_entry() {
1461 let state = test_state();
1462 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hi")))
1463 .await
1464 .expect("tasks_start")
1465 .0;
1466
1467 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
1468 let via_ref = step_get(
1469 State(state.clone()),
1470 Path((
1471 posted.task_id.to_string(),
1472 "latest".to_string(),
1473 identity_name.to_string(),
1474 )),
1475 Query(StepPathQuery::default()),
1476 )
1477 .await
1478 .expect("step_get via own ref name")
1479 .0;
1480 let via_alias = step_get(
1481 State(state.clone()),
1482 Path((
1483 posted.task_id.to_string(),
1484 "latest".to_string(),
1485 "out".to_string(),
1486 )),
1487 Query(StepPathQuery::default()),
1488 )
1489 .await
1490 .expect("step_get via out-top alias")
1491 .0;
1492
1493 assert_eq!(via_ref.name, identity_name);
1494 assert_eq!(
1495 via_alias.name, identity_name,
1496 "alias lookup must report the canonical name"
1497 );
1498 assert_eq!(
1499 via_ref.sha256, via_alias.sha256,
1500 "same OUTPUT regardless of which name was queried"
1501 );
1502 }
1503
1504 #[tokio::test]
1509 async fn declared_projection_name_e2e_resolves_via_canonical_and_alias() {
1510 let state = test_state();
1511 let posted = crate::tasks_start(
1512 State(state.clone()),
1513 Json(declared_task_req("hi", "plan-out")),
1514 )
1515 .await
1516 .expect("tasks_start")
1517 .0;
1518
1519 let list = steps_list(
1520 State(state.clone()),
1521 Path((posted.task_id.to_string(), "latest".to_string())),
1522 )
1523 .await
1524 .expect("steps_list")
1525 .0;
1526 assert_eq!(list.steps.len(), 1, "steps: {:?}", list.steps);
1527 assert_eq!(list.steps[0].name, "plan-out");
1528 assert_eq!(list.steps[0].source, ProjectionSource::DataPlane);
1529
1530 let by_canonical = step_get(
1531 State(state.clone()),
1532 Path((
1533 posted.task_id.to_string(),
1534 "latest".to_string(),
1535 "plan-out".to_string(),
1536 )),
1537 Query(StepPathQuery::default()),
1538 )
1539 .await
1540 .expect("step_get canonical")
1541 .0;
1542 assert_eq!(by_canonical.name, "plan-out");
1543
1544 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
1545 let by_ref_alias = step_get(
1546 State(state.clone()),
1547 Path((
1548 posted.task_id.to_string(),
1549 "latest".to_string(),
1550 identity_name.to_string(),
1551 )),
1552 Query(StepPathQuery::default()),
1553 )
1554 .await
1555 .expect("step_get ref alias")
1556 .0;
1557 assert_eq!(by_ref_alias.name, "plan-out");
1558 assert_eq!(by_ref_alias.sha256, by_canonical.sha256);
1559
1560 let by_out_alias = step_get(
1561 State(state.clone()),
1562 Path((
1563 posted.task_id.to_string(),
1564 "latest".to_string(),
1565 "out".to_string(),
1566 )),
1567 Query(StepPathQuery::default()),
1568 )
1569 .await
1570 .expect("step_get out-top alias")
1571 .0;
1572 assert_eq!(by_out_alias.name, "plan-out");
1573 assert_eq!(by_out_alias.sha256, by_canonical.sha256);
1574 }
1575
1576 #[tokio::test]
1583 async fn declared_projection_name_materialized_file_stem_is_canonical() {
1584 let dir = tempfile::TempDir::new().unwrap();
1585 let state = test_state();
1586 let mut req = declared_task_req("materialized-declared", "plan-out");
1587 req.work_dir = Some(dir.path().to_string_lossy().into_owned());
1588 let posted = crate::tasks_start(State(state.clone()), Json(req))
1589 .await
1590 .expect("tasks_start")
1591 .0;
1592
1593 let summary = step_get(
1594 State(state.clone()),
1595 Path((
1596 posted.task_id.to_string(),
1597 "latest".to_string(),
1598 "plan-out".to_string(),
1599 )),
1600 Query(StepPathQuery::default()),
1601 )
1602 .await
1603 .expect("step_get")
1604 .0;
1605
1606 let file_path = summary.file_path.expect("materialized file_path present");
1607 assert!(
1608 file_path.ends_with("plan-out.md"),
1609 "materialized file stem must be the canonical name: {file_path}"
1610 );
1611 }
1612
1613 #[tokio::test]
1625 async fn declared_projection_placement_e2e_write_and_read_back_converge() {
1626 let project_root_dir = tempfile::TempDir::new().unwrap();
1627 let state = test_state();
1628 let mut bp = declared_projection_name_blueprint("plan-out");
1629 bp.projection_placement = Some(ProjectionPlacementSpec {
1630 root: Some("project_root".to_string()),
1631 dir_template: Some("custom/{task_id}/out".to_string()),
1632 });
1633 let req = TaskLaunchRequest {
1634 blueprint: BlueprintRef::Inline {
1635 value: Box::new(bp),
1636 },
1637 init_ctx: json!({ "greeting": "materialized-custom-placement" }),
1638 project_root: Some(project_root_dir.path().to_string_lossy().into_owned()),
1639 work_dir: None,
1640 task_metadata: None,
1641 ttl_secs: None,
1642 operator: None,
1643 operator_sid: None,
1644 timeout_secs: None,
1645 goal: Some("projection placement test goal".to_string()),
1646 detach: false,
1647 check_policy: None,
1648 };
1649 let posted = crate::tasks_start(State(state.clone()), Json(req))
1650 .await
1651 .expect("tasks_start")
1652 .0;
1653
1654 let summary = step_get(
1655 State(state.clone()),
1656 Path((
1657 posted.task_id.to_string(),
1658 "latest".to_string(),
1659 "plan-out".to_string(),
1660 )),
1661 Query(StepPathQuery::default()),
1662 )
1663 .await
1664 .expect("step_get")
1665 .0;
1666
1667 let file_path = summary.file_path.expect("materialized file_path present");
1676 let path = std::path::Path::new(&file_path);
1677 assert!(
1678 path.starts_with(project_root_dir.path()),
1679 "file must be rooted at project_root (root_preference=ProjectRoot): {file_path}"
1680 );
1681 assert!(
1682 file_path.ends_with("out/plan-out.md"),
1683 "file must follow the custom dir_template's tail: {file_path}"
1684 );
1685 assert!(
1686 file_path.contains("/custom/"),
1687 "file must follow the custom dir_template's prefix segment: {file_path}"
1688 );
1689 assert!(
1690 path.exists(),
1691 "the write side must have materialized the file the read-back reports: {file_path}"
1692 );
1693 }
1694
1695 #[tokio::test]
1702 async fn declared_projection_name_colliding_with_another_steps_ref_is_rejected_at_register_time(
1703 ) {
1704 use mlua_flow_ir::{Expr, Node as FlowNode};
1705 use mlua_swarm::worker::adapter::WorkerResult;
1706 use mlua_swarm::{RustFnInProcessSpawnerFactory, SpawnerRegistry};
1707
1708 let factory = RustFnInProcessSpawnerFactory::new()
1709 .register_fn("step-a", |inv| async move {
1710 Ok(WorkerResult {
1711 value: json!(inv.prompt),
1712 ok: true,
1713 })
1714 })
1715 .register_fn("step-b", |inv| async move {
1716 Ok(WorkerResult {
1717 value: json!(inv.prompt),
1718 ok: true,
1719 })
1720 });
1721 let mut reg = SpawnerRegistry::new();
1722 reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(factory));
1723
1724 let engine = Engine::new_with_layers(EngineCfg::default(), crate::default_layer_registry());
1725 let data_store: Arc<dyn mlua_swarm::store::output::OutputStore> =
1726 Arc::new(InMemoryOutputStore::new());
1727 engine.set_output_store(data_store.clone());
1728 let compiler = mlua_swarm::Compiler::new(reg);
1729 let launch = Arc::new(mlua_swarm::TaskLaunchService::new(engine.clone(), compiler));
1730 let state = AppState {
1731 engine,
1732 sessions: Arc::new(Mutex::new(crate::SessionStore::default())),
1733 task_app: Arc::new(mlua_swarm::TaskApplication::new_inline_only(launch)),
1734 ws_operator_factory: None,
1735 data_store,
1736 operator_sessions: Arc::new(Mutex::new(HashMap::new())),
1737 roles_to_sid: Arc::new(Mutex::new(HashMap::new())),
1738 task_store: Arc::new(InMemoryTaskStore::new()),
1739 run_store: Arc::new(InMemoryRunStore::new()),
1740 base_url: None,
1741 sync_timeout_secs: 300,
1742 };
1743
1744 let flow = FlowNode::Seq {
1745 children: vec![
1746 FlowNode::Step {
1747 ref_: "step-a".to_string(),
1748 in_: Expr::Path {
1749 at: "$.greeting".parse().expect("literal test path: $.greeting"),
1750 },
1751 out: Expr::Path {
1752 at: "$.a_out".parse().expect("literal test path: $.a_out"),
1753 },
1754 },
1755 FlowNode::Step {
1756 ref_: "step-b".to_string(),
1757 in_: Expr::Path {
1758 at: "$.greeting".parse().expect("literal test path: $.greeting"),
1759 },
1760 out: Expr::Path {
1761 at: "$.b_out".parse().expect("literal test path: $.b_out"),
1762 },
1763 },
1764 ],
1765 };
1766 let blueprint = Blueprint {
1767 schema_version: current_schema_version(),
1768 id: "projection-test-collision-bp".into(),
1769 flow,
1770 agents: vec![
1771 AgentDef {
1772 name: "step-a".into(),
1773 kind: AgentKind::RustFn,
1774 spec: json!({"fn_id": "step-a"}),
1775 profile: None,
1776 meta: Some(AgentMeta {
1779 projection_name: Some("step-b".to_string()),
1780 ..Default::default()
1781 }),
1782 runner: None,
1783 runner_ref: None,
1784 verdict: None,
1785 },
1786 AgentDef {
1787 name: "step-b".into(),
1788 kind: AgentKind::RustFn,
1789 spec: json!({"fn_id": "step-b"}),
1790 profile: None,
1791 meta: None,
1792 runner: None,
1793 runner_ref: None,
1794 verdict: None,
1795 },
1796 ],
1797 operators: vec![],
1798 metas: vec![],
1799 hints: CompilerHints::default(),
1800 strategy: CompilerStrategy::default(),
1801 metadata: BlueprintMetadata::default(),
1802 spawner_hints: Default::default(),
1803 default_agent_kind: AgentKind::Operator,
1804 default_operator_kind: None,
1805 default_init_ctx: None,
1806 default_agent_ctx: None,
1807 default_context_policy: None,
1808 projection_placement: None,
1809 audits: vec![],
1810 degradation_policy: None,
1811 runners: vec![],
1812 default_runner: None,
1813 check_policy: None,
1814 };
1815
1816 let req = TaskLaunchRequest {
1817 blueprint: BlueprintRef::Inline {
1818 value: Box::new(blueprint),
1819 },
1820 init_ctx: json!({ "greeting": "hi" }),
1821 project_root: None,
1822 work_dir: None,
1823 task_metadata: None,
1824 ttl_secs: None,
1825 operator: None,
1826 operator_sid: None,
1827 timeout_secs: None,
1828 goal: None,
1829 detach: false,
1830 check_policy: None,
1831 };
1832
1833 let result = crate::tasks_start(State(state), Json(req)).await;
1837 let err = match result {
1838 Err(e) => e,
1839 Ok(_) => {
1840 panic!("declared projection_name colliding with another step's own ref must reject")
1841 }
1842 };
1843 assert_eq!(err.status, StatusCode::BAD_REQUEST);
1844 }
1845
1846 #[tokio::test]
1855 async fn steps_list_run_scoped_lookup_does_not_bleed_across_tasks_sharing_a_producer_name() {
1856 let state = test_state();
1857 let first = crate::tasks_start(State(state.clone()), Json(greeting_task_req("first-task")))
1858 .await
1859 .expect("first tasks_start")
1860 .0;
1861 let second =
1862 crate::tasks_start(State(state.clone()), Json(greeting_task_req("second-task")))
1863 .await
1864 .expect("second tasks_start")
1865 .0;
1866
1867 let first_steps = steps_list(
1868 State(state.clone()),
1869 Path((first.task_id.to_string(), "latest".to_string())),
1870 )
1871 .await
1872 .expect("first steps_list")
1873 .0;
1874 let second_steps = steps_list(
1875 State(state.clone()),
1876 Path((second.task_id.to_string(), "latest".to_string())),
1877 )
1878 .await
1879 .expect("second steps_list")
1880 .0;
1881
1882 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
1883 let first_entry = first_steps
1884 .steps
1885 .iter()
1886 .find(|s| s.name == identity_name)
1887 .expect("first entry present");
1888 let second_entry = second_steps
1889 .steps
1890 .iter()
1891 .find(|s| s.name == identity_name)
1892 .expect("second entry present");
1893 assert_eq!(first_entry.source, ProjectionSource::DataPlane);
1894 assert_eq!(second_entry.source, ProjectionSource::DataPlane);
1895 assert_ne!(
1896 first_entry.sha256, second_entry.sha256,
1897 "each Task's own greeting must resolve, not the globally-latest submission"
1898 );
1899 }
1900
1901 #[tokio::test]
1904 async fn steps_list_latest_resolves_newest_run_explicit_pin_still_works() {
1905 let state = test_state();
1906 let first = crate::tasks_start(State(state.clone()), Json(greeting_task_req("first")))
1907 .await
1908 .expect("tasks_start")
1909 .0;
1910 let (status, rekicked) = crate::tasks::task_rekick(
1911 State(state.clone()),
1912 Path(first.task_id.to_string()),
1913 Some(Json(crate::tasks::RunKickRequest {
1914 init_ctx_override: Some(json!({ "greeting": "second" })),
1915 task_input_override: None,
1916 timeout_secs: None,
1917 detach: false,
1918 })),
1919 )
1920 .await
1921 .expect("task_rekick");
1922 assert_eq!(status, StatusCode::CREATED);
1923
1924 let latest = steps_list(
1925 State(state.clone()),
1926 Path((first.task_id.to_string(), "latest".to_string())),
1927 )
1928 .await
1929 .expect("steps_list latest")
1930 .0;
1931 assert_eq!(latest.run_id, rekicked.0.run_id.to_string());
1932
1933 let pinned = steps_list(
1934 State(state.clone()),
1935 Path((first.task_id.to_string(), first.run_id.to_string())),
1936 )
1937 .await
1938 .expect("steps_list pinned")
1939 .0;
1940 assert_eq!(pinned.run_id, first.run_id.to_string());
1941 }
1942
1943 #[tokio::test]
1946 async fn step_get_preview_is_utf8_boundary_safe_and_truncated_flag_is_correct() {
1947 let state = test_state();
1948 let long_value = "あ".repeat(300); let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req(&long_value)))
1953 .await
1954 .expect("tasks_start")
1955 .0;
1956
1957 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
1958 let summary = step_get(
1959 State(state.clone()),
1960 Path((
1961 posted.task_id.to_string(),
1962 "latest".to_string(),
1963 identity_name.to_string(),
1964 )),
1965 Query(StepPathQuery::default()),
1966 )
1967 .await
1968 .expect("step_get")
1969 .0;
1970
1971 assert!(
1972 summary.preview.len() <= 512 + "…".len(),
1973 "preview must stay near the 512-byte cap: {} bytes",
1974 summary.preview.len()
1975 );
1976 assert!(
1977 summary.truncated,
1978 "a 900-byte body must be reported truncated"
1979 );
1980 assert!(
1981 summary.preview.ends_with('…'),
1982 "truncated preview must end with an ellipsis: {}",
1983 summary.preview
1984 );
1985 assert!(summary.preview.chars().all(|c| c != '\u{FFFD}'));
1991 }
1992
1993 #[tokio::test]
1996 async fn step_content_in_memory_fallback_is_json_with_matching_etag() {
1997 let state = test_state();
1998 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hi")))
1999 .await
2000 .expect("tasks_start")
2001 .0;
2002
2003 let resp = step_content(
2004 State(state.clone()),
2005 Path((
2006 posted.task_id.to_string(),
2007 "latest".to_string(),
2008 "out".to_string(),
2009 )),
2010 Query(StepPathQuery::default()),
2011 )
2012 .await
2013 .expect("step_content")
2014 .into_response();
2015
2016 assert_eq!(resp.status(), StatusCode::OK);
2017 let content_type = resp
2018 .headers()
2019 .get(header::CONTENT_TYPE)
2020 .expect("content-type header")
2021 .to_str()
2022 .expect("ascii");
2023 assert_eq!(content_type, "application/json");
2024 let etag = resp
2025 .headers()
2026 .get(header::ETAG)
2027 .expect("etag header")
2028 .to_str()
2029 .expect("ascii")
2030 .to_string();
2031 let body_bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
2032 .await
2033 .expect("body bytes");
2034 let expected_sha = hex::encode(sha2::Sha256::digest(&body_bytes));
2035 assert_eq!(etag, format!("\"sha256:{expected_sha}\""));
2036 let parsed: Value = serde_json::from_slice(&body_bytes).expect("valid json body");
2037 assert_eq!(parsed["echoed"], json!("hi"));
2038 }
2039
2040 #[tokio::test]
2045 async fn step_content_materialized_file_is_served_as_markdown() {
2046 let dir = tempfile::TempDir::new().unwrap();
2047 let state = test_state();
2048 let mut req = greeting_task_req("materialized");
2049 req.work_dir = Some(dir.path().to_string_lossy().into_owned());
2050 let posted = crate::tasks_start(State(state.clone()), Json(req))
2051 .await
2052 .expect("tasks_start")
2053 .0;
2054
2055 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
2056 let resp = step_content(
2057 State(state.clone()),
2058 Path((
2059 posted.task_id.to_string(),
2060 "latest".to_string(),
2061 identity_name.to_string(),
2062 )),
2063 Query(StepPathQuery::default()),
2064 )
2065 .await
2066 .expect("step_content")
2067 .into_response();
2068
2069 assert_eq!(resp.status(), StatusCode::OK);
2070 let content_type = resp
2071 .headers()
2072 .get(header::CONTENT_TYPE)
2073 .expect("content-type header")
2074 .to_str()
2075 .expect("ascii");
2076 assert_eq!(content_type, "text/markdown; charset=utf-8");
2077 let body_bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
2078 .await
2079 .expect("body bytes");
2080 let body_str = String::from_utf8(body_bytes.to_vec()).expect("utf8 body");
2081 assert!(
2082 body_str.contains("```json"),
2083 "materialized file must carry the fenced json block: {body_str}"
2084 );
2085 }
2086
2087 #[tokio::test]
2090 async fn step_content_path_narrow_returns_json_fragment() {
2091 let state = test_state();
2092 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("narrowed")))
2093 .await
2094 .expect("tasks_start")
2095 .0;
2096
2097 let resp = step_content(
2098 State(state.clone()),
2099 Path((
2100 posted.task_id.to_string(),
2101 "latest".to_string(),
2102 "out".to_string(),
2103 )),
2104 Query(StepPathQuery {
2105 path: Some("echoed".to_string()),
2106 }),
2107 )
2108 .await
2109 .expect("step_content narrowed")
2110 .into_response();
2111
2112 assert_eq!(resp.status(), StatusCode::OK);
2113 let content_type = resp
2114 .headers()
2115 .get(header::CONTENT_TYPE)
2116 .expect("content-type header")
2117 .to_str()
2118 .expect("ascii");
2119 assert_eq!(content_type, "application/json");
2120 let body_bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
2121 .await
2122 .expect("body bytes");
2123 let parsed: Value = serde_json::from_slice(&body_bytes).expect("valid json body");
2124 assert_eq!(parsed, json!("narrowed"));
2125 }
2126
2127 #[tokio::test]
2130 async fn steps_list_unknown_task_returns_404() {
2131 let state = test_state();
2132 let err = steps_list(
2133 State(state),
2134 Path(("T-does-not-exist".to_string(), "latest".to_string())),
2135 )
2136 .await
2137 .expect_err("unknown task must 404");
2138 assert_eq!(err.status, StatusCode::NOT_FOUND);
2139 }
2140
2141 #[tokio::test]
2142 async fn steps_list_unknown_run_returns_404() {
2143 let state = test_state();
2144 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hi")))
2145 .await
2146 .expect("tasks_start")
2147 .0;
2148 let err = steps_list(
2149 State(state),
2150 Path((posted.task_id.to_string(), "R-does-not-exist".to_string())),
2151 )
2152 .await
2153 .expect_err("unknown run must 404");
2154 assert_eq!(err.status, StatusCode::NOT_FOUND);
2155 }
2156
2157 #[tokio::test]
2158 async fn step_get_unknown_step_returns_404() {
2159 let state = test_state();
2160 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hi")))
2161 .await
2162 .expect("tasks_start")
2163 .0;
2164 let err = step_get(
2165 State(state),
2166 Path((
2167 posted.task_id.to_string(),
2168 "latest".to_string(),
2169 "does-not-exist".to_string(),
2170 )),
2171 Query(StepPathQuery::default()),
2172 )
2173 .await
2174 .expect_err("unknown step must 404");
2175 assert_eq!(err.status, StatusCode::NOT_FOUND);
2176 }
2177
2178 #[tokio::test]
2181 async fn old_ctx_route_returns_404_not_found_by_router() {
2182 let engine = Engine::new(EngineCfg::default());
2183 let router = mlua_swarm_server_router_for_test(engine);
2184 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
2185 .await
2186 .expect("bind ephemeral port");
2187 let addr = listener.local_addr().expect("local addr");
2188 tokio::spawn(async move {
2189 let _ = axum::serve(listener, router).await;
2190 });
2191 let client = reqwest::Client::new();
2192 let resp = client
2193 .get(format!("http://{addr}/v1/tasks/T-anything/ctx"))
2194 .send()
2195 .await
2196 .expect("request");
2197 assert_eq!(resp.status(), reqwest::StatusCode::NOT_FOUND);
2198 }
2199
2200 fn mlua_swarm_server_router_for_test(engine: Engine) -> axum::Router {
2204 crate::build_router(engine)
2205 }
2206
2207 #[test]
2210 fn mcp_query_adapter_project_builds_query_ref() {
2211 let adapter = McpQueryAdapter::new(
2212 Arc::new(InMemoryOutputStore::new()),
2213 Arc::new(InMemoryRunStore::new()),
2214 Engine::new(EngineCfg::default()),
2215 );
2216 let key = ProjectionKey {
2217 task_id: "T-abc".to_string(),
2218 run_id: None,
2219 step: Some("planner".to_string()),
2220 path: None,
2221 };
2222 let ctx_data = json!({"planner": {"plan": "do it"}});
2223 let reference = adapter.project(&key, &ctx_data).expect("project");
2224 match &reference {
2225 ProjectionRef::Query { endpoint, key: k } => {
2226 assert!(endpoint.contains("/steps/planner/content"));
2227 assert_eq!(k, &key);
2228 }
2229 other => panic!("expected Query ref, got {other:?}"),
2230 }
2231 let line = adapter.pointer_line(&reference);
2232 assert!(line.contains("T-abc"));
2233 }
2234
2235 #[test]
2236 fn mcp_query_adapter_project_rejects_key_not_present_in_ctx_data() {
2237 let adapter = McpQueryAdapter::new(
2238 Arc::new(InMemoryOutputStore::new()),
2239 Arc::new(InMemoryRunStore::new()),
2240 Engine::new(EngineCfg::default()),
2241 );
2242 let key = ProjectionKey {
2243 task_id: "T-abc".to_string(),
2244 run_id: None,
2245 step: Some("missing".to_string()),
2246 path: None,
2247 };
2248 let err = adapter.project(&key, &json!({"planner": {}})).unwrap_err();
2249 assert!(matches!(err, ProjectionError::NotFound(_)));
2250 }
2251
2252 #[tokio::test(flavor = "multi_thread")]
2253 async fn mcp_query_adapter_fetch_bridges_to_resolve_async() {
2254 let state = test_state();
2255 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("bridged")))
2256 .await
2257 .expect("tasks_start")
2258 .0;
2259
2260 let adapter = McpQueryAdapter::new(
2261 state.data_store.clone(),
2262 state.run_store.clone(),
2263 state.engine.clone(),
2264 );
2265 let key = ProjectionKey {
2266 task_id: posted.task_id.to_string(),
2267 run_id: None,
2268 step: Some("out".to_string()),
2269 path: Some("echoed".to_string()),
2270 };
2271 let value = adapter.fetch(&key).expect("fetch");
2279 assert_eq!(value, json!("bridged"));
2280 }
2281
2282 #[tokio::test]
2295 async fn resolve_async_path_narrows_within_data_plane_final_content() {
2296 let state = test_state();
2297 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hi")))
2298 .await
2299 .expect("tasks_start")
2300 .0;
2301
2302 let adapter = McpQueryAdapter::new(
2303 state.data_store.clone(),
2304 state.run_store.clone(),
2305 state.engine.clone(),
2306 );
2307 let key = ProjectionKey {
2308 task_id: posted.task_id.to_string(),
2309 run_id: None,
2310 step: Some(mlua_swarm::worker::baseline::AG_IDENTITY.to_string()),
2311 path: Some("echoed".to_string()),
2312 };
2313 let (_run, value) = adapter.resolve_async(&key).await.expect("resolve_async");
2314 assert_eq!(value, json!("hi"));
2315 }
2316
2317 #[tokio::test(flavor = "multi_thread")]
2328 async fn steps_list_returns_in_flight_step_output_before_run_completes() {
2329 use mlua_flow_ir::{Expr, Node as FlowNode};
2330 use mlua_swarm::worker::adapter::WorkerResult;
2331 use mlua_swarm::{RustFnInProcessSpawnerFactory, SpawnerRegistry};
2332
2333 let started = Arc::new(tokio::sync::Notify::new());
2334 let gate = Arc::new(tokio::sync::Notify::new());
2335 let started_bg = started.clone();
2336 let gate_bg = gate.clone();
2337
2338 let factory = RustFnInProcessSpawnerFactory::new()
2339 .register_fn("step1", |inv| async move {
2340 Ok(WorkerResult {
2341 value: json!({ "step1_out": inv.prompt }),
2342 ok: true,
2343 })
2344 })
2345 .register_fn("step2", move |_inv| {
2346 let started = started_bg.clone();
2347 let gate = gate_bg.clone();
2348 async move {
2349 started.notify_one();
2350 gate.notified().await;
2351 Ok(WorkerResult {
2352 value: json!("step2 done"),
2353 ok: true,
2354 })
2355 }
2356 });
2357 let mut reg = SpawnerRegistry::new();
2358 reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(factory));
2359
2360 let engine = Engine::new_with_layers(EngineCfg::default(), crate::default_layer_registry());
2361 let data_store: Arc<dyn mlua_swarm::store::output::OutputStore> =
2362 Arc::new(InMemoryOutputStore::new());
2363 engine.set_output_store(data_store.clone());
2364 let compiler = mlua_swarm::Compiler::new(reg);
2365 let launch = Arc::new(mlua_swarm::TaskLaunchService::new(engine.clone(), compiler));
2366 let state = AppState {
2367 engine,
2368 sessions: Arc::new(Mutex::new(crate::SessionStore::default())),
2369 task_app: Arc::new(mlua_swarm::TaskApplication::new_inline_only(launch)),
2370 ws_operator_factory: None,
2371 data_store,
2372 operator_sessions: Arc::new(Mutex::new(HashMap::new())),
2373 roles_to_sid: Arc::new(Mutex::new(HashMap::new())),
2374 task_store: Arc::new(InMemoryTaskStore::new()),
2375 run_store: Arc::new(InMemoryRunStore::new()),
2376 base_url: None,
2377 sync_timeout_secs: 300,
2378 };
2379
2380 let flow = FlowNode::Seq {
2381 children: vec![
2382 FlowNode::Step {
2383 ref_: "step1".to_string(),
2384 in_: Expr::Path {
2385 at: "$.greeting".parse().expect("literal test path: $.greeting"),
2386 },
2387 out: Expr::Path {
2388 at: "$.step1".parse().expect("literal test path: $.step1"),
2389 },
2390 },
2391 FlowNode::Step {
2392 ref_: "step2".to_string(),
2393 in_: Expr::Path {
2394 at: "$.step1".parse().expect("literal test path: $.step1"),
2395 },
2396 out: Expr::Path {
2397 at: "$.step2".parse().expect("literal test path: $.step2"),
2398 },
2399 },
2400 ],
2401 };
2402 let blueprint = Blueprint {
2403 schema_version: current_schema_version(),
2404 id: "projection-test-in-flight-bp".into(),
2405 flow,
2406 agents: vec![
2407 AgentDef {
2408 name: "step1".into(),
2409 kind: AgentKind::RustFn,
2410 spec: json!({"fn_id": "step1"}),
2411 profile: None,
2412 meta: None,
2413 runner: None,
2414 runner_ref: None,
2415 verdict: None,
2416 },
2417 AgentDef {
2418 name: "step2".into(),
2419 kind: AgentKind::RustFn,
2420 spec: json!({"fn_id": "step2"}),
2421 profile: None,
2422 meta: None,
2423 runner: None,
2424 runner_ref: None,
2425 verdict: None,
2426 },
2427 ],
2428 operators: vec![],
2429 metas: vec![],
2430 hints: CompilerHints::default(),
2431 strategy: CompilerStrategy::default(),
2432 metadata: BlueprintMetadata::default(),
2433 spawner_hints: Default::default(),
2434 default_agent_kind: AgentKind::Operator,
2435 default_operator_kind: None,
2436 default_init_ctx: None,
2437 default_agent_ctx: None,
2438 default_context_policy: None,
2439 projection_placement: None,
2440 audits: vec![],
2441 degradation_policy: None,
2442 runners: vec![],
2443 default_runner: None,
2444 check_policy: None,
2445 };
2446
2447 let req = TaskLaunchRequest {
2448 blueprint: BlueprintRef::Inline {
2449 value: Box::new(blueprint),
2450 },
2451 init_ctx: json!({ "greeting": "hi" }),
2452 project_root: None,
2453 work_dir: None,
2454 task_metadata: None,
2455 ttl_secs: None,
2456 operator: None,
2457 operator_sid: None,
2458 timeout_secs: None,
2459 goal: None,
2460 detach: false,
2461 check_policy: None,
2462 };
2463
2464 let state_bg = state.clone();
2465 let launch_handle =
2466 tokio::spawn(async move { crate::tasks_start(State(state_bg), Json(req)).await });
2467
2468 started.notified().await;
2472
2473 let in_flight_tasks = state.task_store.list().await.expect("task_store list");
2474 assert_eq!(in_flight_tasks.len(), 1, "exactly one Task minted");
2475 let task_id = in_flight_tasks[0].id.clone();
2476
2477 let resp = steps_list(
2478 State(state.clone()),
2479 Path((task_id.to_string(), "latest".to_string())),
2480 )
2481 .await
2482 .expect("steps_list while step2 is still in flight");
2483 let step1_entry = resp
2484 .steps
2485 .iter()
2486 .find(|s| s.name == "step1")
2487 .expect("step1 must already be visible");
2488 assert_eq!(step1_entry.source, ProjectionSource::DataPlane);
2489
2490 gate.notify_one();
2493 let posted = launch_handle.await.expect("join").expect("tasks_start").0;
2494 assert_eq!(posted.final_ctx["step2"], json!("step2 done"));
2495 }
2496}