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 replay_store: Arc::new(mlua_swarm::store::replay::InMemoryReplayStore::new()),
1251 base_url: None,
1252 sync_timeout_secs: 300,
1253 }
1254 }
1255
1256 fn greeting_task_req(greeting: &str) -> TaskLaunchRequest {
1257 TaskLaunchRequest {
1258 blueprint: BlueprintRef::Inline {
1259 value: Box::new(greeting_blueprint()),
1260 },
1261 init_ctx: json!({ "greeting": greeting }),
1262 project_root: None,
1263 work_dir: None,
1264 task_metadata: None,
1265 ttl_secs: None,
1266 operator: None,
1267 operator_sid: None,
1268 timeout_secs: None,
1269 goal: Some("projection test goal".to_string()),
1270 detach: false,
1271 check_policy: None,
1272 }
1273 }
1274
1275 fn declared_projection_name_blueprint(projection_name: &str) -> Blueprint {
1281 Blueprint {
1282 schema_version: current_schema_version(),
1283 id: "projection-test-declared-name-bp".into(),
1284 flow: serde_json::from_value(json!({
1285 "kind": "step",
1286 "ref": mlua_swarm::worker::baseline::AG_IDENTITY,
1287 "in": {"op": "path", "at": "$.greeting"},
1288 "out": {"op": "path", "at": "$.out"},
1289 }))
1290 .expect("flow parse"),
1291 agents: vec![AgentDef {
1292 name: mlua_swarm::worker::baseline::AG_IDENTITY.into(),
1293 kind: AgentKind::RustFn,
1294 spec: json!({"fn_id": mlua_swarm::worker::baseline::AG_IDENTITY}),
1295 profile: None,
1296 meta: Some(AgentMeta {
1297 projection_name: Some(projection_name.to_string()),
1298 ..Default::default()
1299 }),
1300 runner: None,
1301 runner_ref: None,
1302 verdict: None,
1303 }],
1304 operators: vec![],
1305 metas: vec![],
1306 hints: CompilerHints::default(),
1307 strategy: CompilerStrategy::default(),
1308 metadata: BlueprintMetadata::default(),
1309 spawner_hints: Default::default(),
1310 default_agent_kind: AgentKind::Operator,
1311 default_operator_kind: None,
1312 default_init_ctx: None,
1313 default_agent_ctx: None,
1314 default_context_policy: None,
1315 projection_placement: None,
1316 audits: vec![],
1317 degradation_policy: None,
1318 runners: vec![],
1319 default_runner: None,
1320 check_policy: None,
1321 }
1322 }
1323
1324 fn declared_task_req(greeting: &str, projection_name: &str) -> TaskLaunchRequest {
1325 TaskLaunchRequest {
1326 blueprint: BlueprintRef::Inline {
1327 value: Box::new(declared_projection_name_blueprint(projection_name)),
1328 },
1329 init_ctx: json!({ "greeting": greeting }),
1330 project_root: None,
1331 work_dir: None,
1332 task_metadata: None,
1333 ttl_secs: None,
1334 operator: None,
1335 operator_sid: None,
1336 timeout_secs: None,
1337 goal: Some("projection test goal (declared name)".to_string()),
1338 detach: false,
1339 check_policy: None,
1340 }
1341 }
1342
1343 fn strict_greeting_blueprint() -> Blueprint {
1352 Blueprint {
1353 check_policy: Some(CheckPolicy::Strict),
1354 ..greeting_blueprint()
1355 }
1356 }
1357
1358 fn strict_greeting_task_req(greeting: &str, project_root: Option<&str>) -> TaskLaunchRequest {
1359 TaskLaunchRequest {
1360 blueprint: BlueprintRef::Inline {
1361 value: Box::new(strict_greeting_blueprint()),
1362 },
1363 init_ctx: json!({ "greeting": greeting }),
1364 project_root: project_root.map(String::from),
1365 work_dir: None,
1366 task_metadata: None,
1367 ttl_secs: None,
1368 operator: None,
1369 operator_sid: None,
1370 timeout_secs: None,
1371 goal: Some("pre-dispatch guard test goal".to_string()),
1372 detach: false,
1373 check_policy: None,
1374 }
1375 }
1376
1377 #[tokio::test]
1384 async fn tasks_start_rejects_strict_launch_with_no_roots_as_400() {
1385 let state = test_state();
1386 let result =
1390 crate::tasks_start(State(state), Json(strict_greeting_task_req("hello", None))).await;
1391 let err = match result {
1392 Err(e) => e,
1393 Ok(_) => {
1394 panic!("strict check_policy + no roots must be rejected before dispatch, got Ok")
1395 }
1396 };
1397 assert_eq!(err.status, StatusCode::BAD_REQUEST);
1398 assert!(
1399 err.message.contains("pre-dispatch"),
1400 "expected a pre-dispatch guard message, got: {}",
1401 err.message
1402 );
1403 }
1404
1405 #[tokio::test]
1410 async fn tasks_start_strict_launch_with_project_root_succeeds() {
1411 let state = test_state();
1412 let reply = crate::tasks_start(
1413 State(state),
1414 Json(strict_greeting_task_req("hello", Some("/repo"))),
1415 )
1416 .await
1417 .expect("strict check_policy + project_root supplied must pass the guard");
1418 assert_eq!(reply.1, StatusCode::OK);
1419 assert_eq!(reply.0.final_ctx["out"]["echoed"], "hello");
1420 }
1421
1422 #[tokio::test]
1432 async fn steps_list_undeclared_step_resolves_to_single_canonical_entry() {
1433 let state = test_state();
1434 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hello")))
1435 .await
1436 .expect("tasks_start")
1437 .0;
1438
1439 let resp = steps_list(
1440 State(state.clone()),
1441 Path((posted.task_id.to_string(), "latest".to_string())),
1442 )
1443 .await
1444 .expect("steps_list")
1445 .0;
1446
1447 assert_eq!(resp.task_id, posted.task_id.to_string());
1448 assert_eq!(resp.run_id, posted.run_id.to_string());
1449 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
1450 assert_eq!(resp.steps.len(), 1, "steps: {:?}", resp.steps);
1451 let entry = &resp.steps[0];
1452 assert_eq!(entry.name, identity_name);
1453 assert_eq!(entry.source, ProjectionSource::DataPlane);
1454 }
1455
1456 #[tokio::test]
1461 async fn step_get_resolves_alias_name_to_canonical_entry() {
1462 let state = test_state();
1463 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hi")))
1464 .await
1465 .expect("tasks_start")
1466 .0;
1467
1468 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
1469 let via_ref = step_get(
1470 State(state.clone()),
1471 Path((
1472 posted.task_id.to_string(),
1473 "latest".to_string(),
1474 identity_name.to_string(),
1475 )),
1476 Query(StepPathQuery::default()),
1477 )
1478 .await
1479 .expect("step_get via own ref name")
1480 .0;
1481 let via_alias = step_get(
1482 State(state.clone()),
1483 Path((
1484 posted.task_id.to_string(),
1485 "latest".to_string(),
1486 "out".to_string(),
1487 )),
1488 Query(StepPathQuery::default()),
1489 )
1490 .await
1491 .expect("step_get via out-top alias")
1492 .0;
1493
1494 assert_eq!(via_ref.name, identity_name);
1495 assert_eq!(
1496 via_alias.name, identity_name,
1497 "alias lookup must report the canonical name"
1498 );
1499 assert_eq!(
1500 via_ref.sha256, via_alias.sha256,
1501 "same OUTPUT regardless of which name was queried"
1502 );
1503 }
1504
1505 #[tokio::test]
1510 async fn declared_projection_name_e2e_resolves_via_canonical_and_alias() {
1511 let state = test_state();
1512 let posted = crate::tasks_start(
1513 State(state.clone()),
1514 Json(declared_task_req("hi", "plan-out")),
1515 )
1516 .await
1517 .expect("tasks_start")
1518 .0;
1519
1520 let list = steps_list(
1521 State(state.clone()),
1522 Path((posted.task_id.to_string(), "latest".to_string())),
1523 )
1524 .await
1525 .expect("steps_list")
1526 .0;
1527 assert_eq!(list.steps.len(), 1, "steps: {:?}", list.steps);
1528 assert_eq!(list.steps[0].name, "plan-out");
1529 assert_eq!(list.steps[0].source, ProjectionSource::DataPlane);
1530
1531 let by_canonical = step_get(
1532 State(state.clone()),
1533 Path((
1534 posted.task_id.to_string(),
1535 "latest".to_string(),
1536 "plan-out".to_string(),
1537 )),
1538 Query(StepPathQuery::default()),
1539 )
1540 .await
1541 .expect("step_get canonical")
1542 .0;
1543 assert_eq!(by_canonical.name, "plan-out");
1544
1545 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
1546 let by_ref_alias = step_get(
1547 State(state.clone()),
1548 Path((
1549 posted.task_id.to_string(),
1550 "latest".to_string(),
1551 identity_name.to_string(),
1552 )),
1553 Query(StepPathQuery::default()),
1554 )
1555 .await
1556 .expect("step_get ref alias")
1557 .0;
1558 assert_eq!(by_ref_alias.name, "plan-out");
1559 assert_eq!(by_ref_alias.sha256, by_canonical.sha256);
1560
1561 let by_out_alias = step_get(
1562 State(state.clone()),
1563 Path((
1564 posted.task_id.to_string(),
1565 "latest".to_string(),
1566 "out".to_string(),
1567 )),
1568 Query(StepPathQuery::default()),
1569 )
1570 .await
1571 .expect("step_get out-top alias")
1572 .0;
1573 assert_eq!(by_out_alias.name, "plan-out");
1574 assert_eq!(by_out_alias.sha256, by_canonical.sha256);
1575 }
1576
1577 #[tokio::test]
1584 async fn declared_projection_name_materialized_file_stem_is_canonical() {
1585 let dir = tempfile::TempDir::new().unwrap();
1586 let state = test_state();
1587 let mut req = declared_task_req("materialized-declared", "plan-out");
1588 req.work_dir = Some(dir.path().to_string_lossy().into_owned());
1589 let posted = crate::tasks_start(State(state.clone()), Json(req))
1590 .await
1591 .expect("tasks_start")
1592 .0;
1593
1594 let summary = step_get(
1595 State(state.clone()),
1596 Path((
1597 posted.task_id.to_string(),
1598 "latest".to_string(),
1599 "plan-out".to_string(),
1600 )),
1601 Query(StepPathQuery::default()),
1602 )
1603 .await
1604 .expect("step_get")
1605 .0;
1606
1607 let file_path = summary.file_path.expect("materialized file_path present");
1608 assert!(
1609 file_path.ends_with("plan-out.md"),
1610 "materialized file stem must be the canonical name: {file_path}"
1611 );
1612 }
1613
1614 #[tokio::test]
1626 async fn declared_projection_placement_e2e_write_and_read_back_converge() {
1627 let project_root_dir = tempfile::TempDir::new().unwrap();
1628 let state = test_state();
1629 let mut bp = declared_projection_name_blueprint("plan-out");
1630 bp.projection_placement = Some(ProjectionPlacementSpec {
1631 root: Some("project_root".to_string()),
1632 dir_template: Some("custom/{task_id}/out".to_string()),
1633 });
1634 let req = TaskLaunchRequest {
1635 blueprint: BlueprintRef::Inline {
1636 value: Box::new(bp),
1637 },
1638 init_ctx: json!({ "greeting": "materialized-custom-placement" }),
1639 project_root: Some(project_root_dir.path().to_string_lossy().into_owned()),
1640 work_dir: None,
1641 task_metadata: None,
1642 ttl_secs: None,
1643 operator: None,
1644 operator_sid: None,
1645 timeout_secs: None,
1646 goal: Some("projection placement test goal".to_string()),
1647 detach: false,
1648 check_policy: None,
1649 };
1650 let posted = crate::tasks_start(State(state.clone()), Json(req))
1651 .await
1652 .expect("tasks_start")
1653 .0;
1654
1655 let summary = step_get(
1656 State(state.clone()),
1657 Path((
1658 posted.task_id.to_string(),
1659 "latest".to_string(),
1660 "plan-out".to_string(),
1661 )),
1662 Query(StepPathQuery::default()),
1663 )
1664 .await
1665 .expect("step_get")
1666 .0;
1667
1668 let file_path = summary.file_path.expect("materialized file_path present");
1677 let path = std::path::Path::new(&file_path);
1678 assert!(
1679 path.starts_with(project_root_dir.path()),
1680 "file must be rooted at project_root (root_preference=ProjectRoot): {file_path}"
1681 );
1682 assert!(
1683 file_path.ends_with("out/plan-out.md"),
1684 "file must follow the custom dir_template's tail: {file_path}"
1685 );
1686 assert!(
1687 file_path.contains("/custom/"),
1688 "file must follow the custom dir_template's prefix segment: {file_path}"
1689 );
1690 assert!(
1691 path.exists(),
1692 "the write side must have materialized the file the read-back reports: {file_path}"
1693 );
1694 }
1695
1696 #[tokio::test]
1703 async fn declared_projection_name_colliding_with_another_steps_ref_is_rejected_at_register_time(
1704 ) {
1705 use mlua_flow_ir::{Expr, Node as FlowNode};
1706 use mlua_swarm::worker::adapter::WorkerResult;
1707 use mlua_swarm::{RustFnInProcessSpawnerFactory, SpawnerRegistry};
1708
1709 let factory = RustFnInProcessSpawnerFactory::new()
1710 .register_fn("step-a", |inv| async move {
1711 Ok(WorkerResult {
1712 value: json!(inv.prompt),
1713 ok: true,
1714 })
1715 })
1716 .register_fn("step-b", |inv| async move {
1717 Ok(WorkerResult {
1718 value: json!(inv.prompt),
1719 ok: true,
1720 })
1721 });
1722 let mut reg = SpawnerRegistry::new();
1723 reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(factory));
1724
1725 let engine = Engine::new_with_layers(EngineCfg::default(), crate::default_layer_registry());
1726 let data_store: Arc<dyn mlua_swarm::store::output::OutputStore> =
1727 Arc::new(InMemoryOutputStore::new());
1728 engine.set_output_store(data_store.clone());
1729 let compiler = mlua_swarm::Compiler::new(reg);
1730 let launch = Arc::new(mlua_swarm::TaskLaunchService::new(engine.clone(), compiler));
1731 let state = AppState {
1732 engine,
1733 sessions: Arc::new(Mutex::new(crate::SessionStore::default())),
1734 task_app: Arc::new(mlua_swarm::TaskApplication::new_inline_only(launch)),
1735 ws_operator_factory: None,
1736 data_store,
1737 operator_sessions: Arc::new(Mutex::new(HashMap::new())),
1738 roles_to_sid: Arc::new(Mutex::new(HashMap::new())),
1739 task_store: Arc::new(InMemoryTaskStore::new()),
1740 run_store: Arc::new(InMemoryRunStore::new()),
1741 replay_store: Arc::new(mlua_swarm::store::replay::InMemoryReplayStore::new()),
1742 base_url: None,
1743 sync_timeout_secs: 300,
1744 };
1745
1746 let flow = FlowNode::Seq {
1747 children: vec![
1748 FlowNode::Step {
1749 ref_: "step-a".to_string(),
1750 in_: Expr::Path {
1751 at: "$.greeting".parse().expect("literal test path: $.greeting"),
1752 },
1753 out: Expr::Path {
1754 at: "$.a_out".parse().expect("literal test path: $.a_out"),
1755 },
1756 },
1757 FlowNode::Step {
1758 ref_: "step-b".to_string(),
1759 in_: Expr::Path {
1760 at: "$.greeting".parse().expect("literal test path: $.greeting"),
1761 },
1762 out: Expr::Path {
1763 at: "$.b_out".parse().expect("literal test path: $.b_out"),
1764 },
1765 },
1766 ],
1767 };
1768 let blueprint = Blueprint {
1769 schema_version: current_schema_version(),
1770 id: "projection-test-collision-bp".into(),
1771 flow,
1772 agents: vec![
1773 AgentDef {
1774 name: "step-a".into(),
1775 kind: AgentKind::RustFn,
1776 spec: json!({"fn_id": "step-a"}),
1777 profile: None,
1778 meta: Some(AgentMeta {
1781 projection_name: Some("step-b".to_string()),
1782 ..Default::default()
1783 }),
1784 runner: None,
1785 runner_ref: None,
1786 verdict: None,
1787 },
1788 AgentDef {
1789 name: "step-b".into(),
1790 kind: AgentKind::RustFn,
1791 spec: json!({"fn_id": "step-b"}),
1792 profile: None,
1793 meta: None,
1794 runner: None,
1795 runner_ref: None,
1796 verdict: None,
1797 },
1798 ],
1799 operators: vec![],
1800 metas: vec![],
1801 hints: CompilerHints::default(),
1802 strategy: CompilerStrategy::default(),
1803 metadata: BlueprintMetadata::default(),
1804 spawner_hints: Default::default(),
1805 default_agent_kind: AgentKind::Operator,
1806 default_operator_kind: None,
1807 default_init_ctx: None,
1808 default_agent_ctx: None,
1809 default_context_policy: None,
1810 projection_placement: None,
1811 audits: vec![],
1812 degradation_policy: None,
1813 runners: vec![],
1814 default_runner: None,
1815 check_policy: None,
1816 };
1817
1818 let req = TaskLaunchRequest {
1819 blueprint: BlueprintRef::Inline {
1820 value: Box::new(blueprint),
1821 },
1822 init_ctx: json!({ "greeting": "hi" }),
1823 project_root: None,
1824 work_dir: None,
1825 task_metadata: None,
1826 ttl_secs: None,
1827 operator: None,
1828 operator_sid: None,
1829 timeout_secs: None,
1830 goal: None,
1831 detach: false,
1832 check_policy: None,
1833 };
1834
1835 let result = crate::tasks_start(State(state), Json(req)).await;
1839 let err = match result {
1840 Err(e) => e,
1841 Ok(_) => {
1842 panic!("declared projection_name colliding with another step's own ref must reject")
1843 }
1844 };
1845 assert_eq!(err.status, StatusCode::BAD_REQUEST);
1846 }
1847
1848 #[tokio::test]
1857 async fn steps_list_run_scoped_lookup_does_not_bleed_across_tasks_sharing_a_producer_name() {
1858 let state = test_state();
1859 let first = crate::tasks_start(State(state.clone()), Json(greeting_task_req("first-task")))
1860 .await
1861 .expect("first tasks_start")
1862 .0;
1863 let second =
1864 crate::tasks_start(State(state.clone()), Json(greeting_task_req("second-task")))
1865 .await
1866 .expect("second tasks_start")
1867 .0;
1868
1869 let first_steps = steps_list(
1870 State(state.clone()),
1871 Path((first.task_id.to_string(), "latest".to_string())),
1872 )
1873 .await
1874 .expect("first steps_list")
1875 .0;
1876 let second_steps = steps_list(
1877 State(state.clone()),
1878 Path((second.task_id.to_string(), "latest".to_string())),
1879 )
1880 .await
1881 .expect("second steps_list")
1882 .0;
1883
1884 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
1885 let first_entry = first_steps
1886 .steps
1887 .iter()
1888 .find(|s| s.name == identity_name)
1889 .expect("first entry present");
1890 let second_entry = second_steps
1891 .steps
1892 .iter()
1893 .find(|s| s.name == identity_name)
1894 .expect("second entry present");
1895 assert_eq!(first_entry.source, ProjectionSource::DataPlane);
1896 assert_eq!(second_entry.source, ProjectionSource::DataPlane);
1897 assert_ne!(
1898 first_entry.sha256, second_entry.sha256,
1899 "each Task's own greeting must resolve, not the globally-latest submission"
1900 );
1901 }
1902
1903 #[tokio::test]
1906 async fn steps_list_latest_resolves_newest_run_explicit_pin_still_works() {
1907 let state = test_state();
1908 let first = crate::tasks_start(State(state.clone()), Json(greeting_task_req("first")))
1909 .await
1910 .expect("tasks_start")
1911 .0;
1912 let (status, rekicked) = crate::tasks::task_rekick(
1913 State(state.clone()),
1914 Path(first.task_id.to_string()),
1915 Some(Json(crate::tasks::RunKickRequest {
1916 init_ctx_override: Some(json!({ "greeting": "second" })),
1917 task_input_override: None,
1918 timeout_secs: None,
1919 detach: false,
1920 })),
1921 )
1922 .await
1923 .expect("task_rekick");
1924 assert_eq!(status, StatusCode::CREATED);
1925
1926 let latest = steps_list(
1927 State(state.clone()),
1928 Path((first.task_id.to_string(), "latest".to_string())),
1929 )
1930 .await
1931 .expect("steps_list latest")
1932 .0;
1933 assert_eq!(latest.run_id, rekicked.0.run_id.to_string());
1934
1935 let pinned = steps_list(
1936 State(state.clone()),
1937 Path((first.task_id.to_string(), first.run_id.to_string())),
1938 )
1939 .await
1940 .expect("steps_list pinned")
1941 .0;
1942 assert_eq!(pinned.run_id, first.run_id.to_string());
1943 }
1944
1945 #[tokio::test]
1948 async fn step_get_preview_is_utf8_boundary_safe_and_truncated_flag_is_correct() {
1949 let state = test_state();
1950 let long_value = "あ".repeat(300); let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req(&long_value)))
1955 .await
1956 .expect("tasks_start")
1957 .0;
1958
1959 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
1960 let summary = step_get(
1961 State(state.clone()),
1962 Path((
1963 posted.task_id.to_string(),
1964 "latest".to_string(),
1965 identity_name.to_string(),
1966 )),
1967 Query(StepPathQuery::default()),
1968 )
1969 .await
1970 .expect("step_get")
1971 .0;
1972
1973 assert!(
1974 summary.preview.len() <= 512 + "…".len(),
1975 "preview must stay near the 512-byte cap: {} bytes",
1976 summary.preview.len()
1977 );
1978 assert!(
1979 summary.truncated,
1980 "a 900-byte body must be reported truncated"
1981 );
1982 assert!(
1983 summary.preview.ends_with('…'),
1984 "truncated preview must end with an ellipsis: {}",
1985 summary.preview
1986 );
1987 assert!(summary.preview.chars().all(|c| c != '\u{FFFD}'));
1993 }
1994
1995 #[tokio::test]
1998 async fn step_content_in_memory_fallback_is_json_with_matching_etag() {
1999 let state = test_state();
2000 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hi")))
2001 .await
2002 .expect("tasks_start")
2003 .0;
2004
2005 let resp = step_content(
2006 State(state.clone()),
2007 Path((
2008 posted.task_id.to_string(),
2009 "latest".to_string(),
2010 "out".to_string(),
2011 )),
2012 Query(StepPathQuery::default()),
2013 )
2014 .await
2015 .expect("step_content")
2016 .into_response();
2017
2018 assert_eq!(resp.status(), StatusCode::OK);
2019 let content_type = resp
2020 .headers()
2021 .get(header::CONTENT_TYPE)
2022 .expect("content-type header")
2023 .to_str()
2024 .expect("ascii");
2025 assert_eq!(content_type, "application/json");
2026 let etag = resp
2027 .headers()
2028 .get(header::ETAG)
2029 .expect("etag header")
2030 .to_str()
2031 .expect("ascii")
2032 .to_string();
2033 let body_bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
2034 .await
2035 .expect("body bytes");
2036 let expected_sha = hex::encode(sha2::Sha256::digest(&body_bytes));
2037 assert_eq!(etag, format!("\"sha256:{expected_sha}\""));
2038 let parsed: Value = serde_json::from_slice(&body_bytes).expect("valid json body");
2039 assert_eq!(parsed["echoed"], json!("hi"));
2040 }
2041
2042 #[tokio::test]
2047 async fn step_content_materialized_file_is_served_as_markdown() {
2048 let dir = tempfile::TempDir::new().unwrap();
2049 let state = test_state();
2050 let mut req = greeting_task_req("materialized");
2051 req.work_dir = Some(dir.path().to_string_lossy().into_owned());
2052 let posted = crate::tasks_start(State(state.clone()), Json(req))
2053 .await
2054 .expect("tasks_start")
2055 .0;
2056
2057 let identity_name = mlua_swarm::worker::baseline::AG_IDENTITY;
2058 let resp = step_content(
2059 State(state.clone()),
2060 Path((
2061 posted.task_id.to_string(),
2062 "latest".to_string(),
2063 identity_name.to_string(),
2064 )),
2065 Query(StepPathQuery::default()),
2066 )
2067 .await
2068 .expect("step_content")
2069 .into_response();
2070
2071 assert_eq!(resp.status(), StatusCode::OK);
2072 let content_type = resp
2073 .headers()
2074 .get(header::CONTENT_TYPE)
2075 .expect("content-type header")
2076 .to_str()
2077 .expect("ascii");
2078 assert_eq!(content_type, "text/markdown; charset=utf-8");
2079 let body_bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
2080 .await
2081 .expect("body bytes");
2082 let body_str = String::from_utf8(body_bytes.to_vec()).expect("utf8 body");
2083 assert!(
2084 body_str.contains("```json"),
2085 "materialized file must carry the fenced json block: {body_str}"
2086 );
2087 }
2088
2089 #[tokio::test]
2092 async fn step_content_path_narrow_returns_json_fragment() {
2093 let state = test_state();
2094 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("narrowed")))
2095 .await
2096 .expect("tasks_start")
2097 .0;
2098
2099 let resp = step_content(
2100 State(state.clone()),
2101 Path((
2102 posted.task_id.to_string(),
2103 "latest".to_string(),
2104 "out".to_string(),
2105 )),
2106 Query(StepPathQuery {
2107 path: Some("echoed".to_string()),
2108 }),
2109 )
2110 .await
2111 .expect("step_content narrowed")
2112 .into_response();
2113
2114 assert_eq!(resp.status(), StatusCode::OK);
2115 let content_type = resp
2116 .headers()
2117 .get(header::CONTENT_TYPE)
2118 .expect("content-type header")
2119 .to_str()
2120 .expect("ascii");
2121 assert_eq!(content_type, "application/json");
2122 let body_bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
2123 .await
2124 .expect("body bytes");
2125 let parsed: Value = serde_json::from_slice(&body_bytes).expect("valid json body");
2126 assert_eq!(parsed, json!("narrowed"));
2127 }
2128
2129 #[tokio::test]
2132 async fn steps_list_unknown_task_returns_404() {
2133 let state = test_state();
2134 let err = steps_list(
2135 State(state),
2136 Path(("T-does-not-exist".to_string(), "latest".to_string())),
2137 )
2138 .await
2139 .expect_err("unknown task must 404");
2140 assert_eq!(err.status, StatusCode::NOT_FOUND);
2141 }
2142
2143 #[tokio::test]
2144 async fn steps_list_unknown_run_returns_404() {
2145 let state = test_state();
2146 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hi")))
2147 .await
2148 .expect("tasks_start")
2149 .0;
2150 let err = steps_list(
2151 State(state),
2152 Path((posted.task_id.to_string(), "R-does-not-exist".to_string())),
2153 )
2154 .await
2155 .expect_err("unknown run must 404");
2156 assert_eq!(err.status, StatusCode::NOT_FOUND);
2157 }
2158
2159 #[tokio::test]
2160 async fn step_get_unknown_step_returns_404() {
2161 let state = test_state();
2162 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hi")))
2163 .await
2164 .expect("tasks_start")
2165 .0;
2166 let err = step_get(
2167 State(state),
2168 Path((
2169 posted.task_id.to_string(),
2170 "latest".to_string(),
2171 "does-not-exist".to_string(),
2172 )),
2173 Query(StepPathQuery::default()),
2174 )
2175 .await
2176 .expect_err("unknown step must 404");
2177 assert_eq!(err.status, StatusCode::NOT_FOUND);
2178 }
2179
2180 #[tokio::test]
2183 async fn old_ctx_route_returns_404_not_found_by_router() {
2184 let engine = Engine::new(EngineCfg::default());
2185 let router = mlua_swarm_server_router_for_test(engine);
2186 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
2187 .await
2188 .expect("bind ephemeral port");
2189 let addr = listener.local_addr().expect("local addr");
2190 tokio::spawn(async move {
2191 let _ = axum::serve(listener, router).await;
2192 });
2193 let client = reqwest::Client::new();
2194 let resp = client
2195 .get(format!("http://{addr}/v1/tasks/T-anything/ctx"))
2196 .send()
2197 .await
2198 .expect("request");
2199 assert_eq!(resp.status(), reqwest::StatusCode::NOT_FOUND);
2200 }
2201
2202 fn mlua_swarm_server_router_for_test(engine: Engine) -> axum::Router {
2206 crate::build_router(engine)
2207 }
2208
2209 #[test]
2212 fn mcp_query_adapter_project_builds_query_ref() {
2213 let adapter = McpQueryAdapter::new(
2214 Arc::new(InMemoryOutputStore::new()),
2215 Arc::new(InMemoryRunStore::new()),
2216 Engine::new(EngineCfg::default()),
2217 );
2218 let key = ProjectionKey {
2219 task_id: "T-abc".to_string(),
2220 run_id: None,
2221 step: Some("planner".to_string()),
2222 path: None,
2223 };
2224 let ctx_data = json!({"planner": {"plan": "do it"}});
2225 let reference = adapter.project(&key, &ctx_data).expect("project");
2226 match &reference {
2227 ProjectionRef::Query { endpoint, key: k } => {
2228 assert!(endpoint.contains("/steps/planner/content"));
2229 assert_eq!(k, &key);
2230 }
2231 other => panic!("expected Query ref, got {other:?}"),
2232 }
2233 let line = adapter.pointer_line(&reference);
2234 assert!(line.contains("T-abc"));
2235 }
2236
2237 #[test]
2238 fn mcp_query_adapter_project_rejects_key_not_present_in_ctx_data() {
2239 let adapter = McpQueryAdapter::new(
2240 Arc::new(InMemoryOutputStore::new()),
2241 Arc::new(InMemoryRunStore::new()),
2242 Engine::new(EngineCfg::default()),
2243 );
2244 let key = ProjectionKey {
2245 task_id: "T-abc".to_string(),
2246 run_id: None,
2247 step: Some("missing".to_string()),
2248 path: None,
2249 };
2250 let err = adapter.project(&key, &json!({"planner": {}})).unwrap_err();
2251 assert!(matches!(err, ProjectionError::NotFound(_)));
2252 }
2253
2254 #[tokio::test(flavor = "multi_thread")]
2255 async fn mcp_query_adapter_fetch_bridges_to_resolve_async() {
2256 let state = test_state();
2257 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("bridged")))
2258 .await
2259 .expect("tasks_start")
2260 .0;
2261
2262 let adapter = McpQueryAdapter::new(
2263 state.data_store.clone(),
2264 state.run_store.clone(),
2265 state.engine.clone(),
2266 );
2267 let key = ProjectionKey {
2268 task_id: posted.task_id.to_string(),
2269 run_id: None,
2270 step: Some("out".to_string()),
2271 path: Some("echoed".to_string()),
2272 };
2273 let value = adapter.fetch(&key).expect("fetch");
2281 assert_eq!(value, json!("bridged"));
2282 }
2283
2284 #[tokio::test]
2297 async fn resolve_async_path_narrows_within_data_plane_final_content() {
2298 let state = test_state();
2299 let posted = crate::tasks_start(State(state.clone()), Json(greeting_task_req("hi")))
2300 .await
2301 .expect("tasks_start")
2302 .0;
2303
2304 let adapter = McpQueryAdapter::new(
2305 state.data_store.clone(),
2306 state.run_store.clone(),
2307 state.engine.clone(),
2308 );
2309 let key = ProjectionKey {
2310 task_id: posted.task_id.to_string(),
2311 run_id: None,
2312 step: Some(mlua_swarm::worker::baseline::AG_IDENTITY.to_string()),
2313 path: Some("echoed".to_string()),
2314 };
2315 let (_run, value) = adapter.resolve_async(&key).await.expect("resolve_async");
2316 assert_eq!(value, json!("hi"));
2317 }
2318
2319 #[tokio::test(flavor = "multi_thread")]
2330 async fn steps_list_returns_in_flight_step_output_before_run_completes() {
2331 use mlua_flow_ir::{Expr, Node as FlowNode};
2332 use mlua_swarm::worker::adapter::WorkerResult;
2333 use mlua_swarm::{RustFnInProcessSpawnerFactory, SpawnerRegistry};
2334
2335 let started = Arc::new(tokio::sync::Notify::new());
2336 let gate = Arc::new(tokio::sync::Notify::new());
2337 let started_bg = started.clone();
2338 let gate_bg = gate.clone();
2339
2340 let factory = RustFnInProcessSpawnerFactory::new()
2341 .register_fn("step1", |inv| async move {
2342 Ok(WorkerResult {
2343 value: json!({ "step1_out": inv.prompt }),
2344 ok: true,
2345 })
2346 })
2347 .register_fn("step2", move |_inv| {
2348 let started = started_bg.clone();
2349 let gate = gate_bg.clone();
2350 async move {
2351 started.notify_one();
2352 gate.notified().await;
2353 Ok(WorkerResult {
2354 value: json!("step2 done"),
2355 ok: true,
2356 })
2357 }
2358 });
2359 let mut reg = SpawnerRegistry::new();
2360 reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(factory));
2361
2362 let engine = Engine::new_with_layers(EngineCfg::default(), crate::default_layer_registry());
2363 let data_store: Arc<dyn mlua_swarm::store::output::OutputStore> =
2364 Arc::new(InMemoryOutputStore::new());
2365 engine.set_output_store(data_store.clone());
2366 let compiler = mlua_swarm::Compiler::new(reg);
2367 let launch = Arc::new(mlua_swarm::TaskLaunchService::new(engine.clone(), compiler));
2368 let state = AppState {
2369 engine,
2370 sessions: Arc::new(Mutex::new(crate::SessionStore::default())),
2371 task_app: Arc::new(mlua_swarm::TaskApplication::new_inline_only(launch)),
2372 ws_operator_factory: None,
2373 data_store,
2374 operator_sessions: Arc::new(Mutex::new(HashMap::new())),
2375 roles_to_sid: Arc::new(Mutex::new(HashMap::new())),
2376 task_store: Arc::new(InMemoryTaskStore::new()),
2377 run_store: Arc::new(InMemoryRunStore::new()),
2378 replay_store: Arc::new(mlua_swarm::store::replay::InMemoryReplayStore::new()),
2379 base_url: None,
2380 sync_timeout_secs: 300,
2381 };
2382
2383 let flow = FlowNode::Seq {
2384 children: vec![
2385 FlowNode::Step {
2386 ref_: "step1".to_string(),
2387 in_: Expr::Path {
2388 at: "$.greeting".parse().expect("literal test path: $.greeting"),
2389 },
2390 out: Expr::Path {
2391 at: "$.step1".parse().expect("literal test path: $.step1"),
2392 },
2393 },
2394 FlowNode::Step {
2395 ref_: "step2".to_string(),
2396 in_: Expr::Path {
2397 at: "$.step1".parse().expect("literal test path: $.step1"),
2398 },
2399 out: Expr::Path {
2400 at: "$.step2".parse().expect("literal test path: $.step2"),
2401 },
2402 },
2403 ],
2404 };
2405 let blueprint = Blueprint {
2406 schema_version: current_schema_version(),
2407 id: "projection-test-in-flight-bp".into(),
2408 flow,
2409 agents: vec![
2410 AgentDef {
2411 name: "step1".into(),
2412 kind: AgentKind::RustFn,
2413 spec: json!({"fn_id": "step1"}),
2414 profile: None,
2415 meta: None,
2416 runner: None,
2417 runner_ref: None,
2418 verdict: None,
2419 },
2420 AgentDef {
2421 name: "step2".into(),
2422 kind: AgentKind::RustFn,
2423 spec: json!({"fn_id": "step2"}),
2424 profile: None,
2425 meta: None,
2426 runner: None,
2427 runner_ref: None,
2428 verdict: None,
2429 },
2430 ],
2431 operators: vec![],
2432 metas: vec![],
2433 hints: CompilerHints::default(),
2434 strategy: CompilerStrategy::default(),
2435 metadata: BlueprintMetadata::default(),
2436 spawner_hints: Default::default(),
2437 default_agent_kind: AgentKind::Operator,
2438 default_operator_kind: None,
2439 default_init_ctx: None,
2440 default_agent_ctx: None,
2441 default_context_policy: None,
2442 projection_placement: None,
2443 audits: vec![],
2444 degradation_policy: None,
2445 runners: vec![],
2446 default_runner: None,
2447 check_policy: None,
2448 };
2449
2450 let req = TaskLaunchRequest {
2451 blueprint: BlueprintRef::Inline {
2452 value: Box::new(blueprint),
2453 },
2454 init_ctx: json!({ "greeting": "hi" }),
2455 project_root: None,
2456 work_dir: None,
2457 task_metadata: None,
2458 ttl_secs: None,
2459 operator: None,
2460 operator_sid: None,
2461 timeout_secs: None,
2462 goal: None,
2463 detach: false,
2464 check_policy: None,
2465 };
2466
2467 let state_bg = state.clone();
2468 let launch_handle =
2469 tokio::spawn(async move { crate::tasks_start(State(state_bg), Json(req)).await });
2470
2471 started.notified().await;
2475
2476 let in_flight_tasks = state.task_store.list().await.expect("task_store list");
2477 assert_eq!(in_flight_tasks.len(), 1, "exactly one Task minted");
2478 let task_id = in_flight_tasks[0].id.clone();
2479
2480 let resp = steps_list(
2481 State(state.clone()),
2482 Path((task_id.to_string(), "latest".to_string())),
2483 )
2484 .await
2485 .expect("steps_list while step2 is still in flight");
2486 let step1_entry = resp
2487 .steps
2488 .iter()
2489 .find(|s| s.name == "step1")
2490 .expect("step1 must already be visible");
2491 assert_eq!(step1_entry.source, ProjectionSource::DataPlane);
2492
2493 gate.notify_one();
2496 let posted = launch_handle.await.expect("join").expect("tasks_start").0;
2497 assert_eq!(posted.final_ctx["step2"], json!("step2 done"));
2498 }
2499}