Skip to main content

mlua_swarm/application/
task.rs

1//! `TaskApplication` — the `POST /v1/tasks` entry point.
2//!
3//! Input: `BlueprintRef` (Inline / Id) plus a `TaskSpec`. Output:
4//! `(CapToken, StepId, version)`. Once the Blueprint is resolved, the
5//! engine-side operations (`bind` + `attach` + `start_task`) are
6//! delegated to [`TaskLaunchService`].
7
8use super::semver_resolve::SemverResolveError;
9use super::Application;
10use crate::blueprint::store::{BlueprintId, BlueprintStore, BlueprintStoreError, BlueprintVersion};
11use crate::blueprint::Blueprint;
12use crate::core::config::CheckPolicy;
13use crate::core::ctx::OperatorKind;
14use crate::service::{
15    TaskInputSpec, TaskLaunchError, TaskLaunchInput, TaskLaunchOutput, TaskLaunchService,
16};
17use crate::store::run::RunContext;
18use crate::types::{CapToken, Role};
19use async_trait::async_trait;
20use serde::{Deserialize, Serialize};
21use serde_json::Value;
22use std::collections::HashMap;
23use std::sync::Arc;
24use std::time::Duration;
25use thiserror::Error;
26
27/// How a task entry says the Blueprint should be resolved.
28#[derive(Debug, Clone, Serialize, Deserialize)]
29#[serde(tag = "kind", rename_all = "snake_case")]
30pub enum BlueprintRef {
31    /// The Blueprint value is embedded directly in the request; no
32    /// store lookup happens.
33    Inline {
34        /// The Blueprint to run as-is.
35        value: Box<Blueprint>,
36    },
37    /// Resolve the Blueprint from the `BlueprintStore` by id.
38    Id {
39        /// The `BlueprintId` to look up in the store.
40        id: BlueprintId,
41        /// Which generation to pick; defaults to `Latest`.
42        #[serde(default)]
43        version: VersionSelector,
44    },
45}
46
47/// How to pick a generation — a `version` inside the store.
48#[derive(Debug, Clone, Default, Serialize, Deserialize)]
49#[serde(tag = "kind", rename_all = "snake_case")]
50pub enum VersionSelector {
51    /// Use the store's current head version.
52    #[default]
53    Latest,
54    /// Use one exact, previously-committed version.
55    Fixed {
56        /// The exact version to read.
57        value: BlueprintVersion,
58    },
59    /// Scan the store's history and pick the highest version whose
60    /// `BlueprintMetadata.version_label` satisfies `req`.
61    SemverReq {
62        /// The semver requirement every candidate label is matched
63        /// against.
64        req: semver::VersionReq,
65    },
66}
67
68/// Input to [`TaskApplication::handle`] — the `POST /v1/tasks` request
69/// body once decoded.
70#[derive(Debug, Clone)]
71pub struct TaskApplicationInput {
72    /// Accepts both Inline (a Blueprint value directly) and Id
73    /// (store fetch + a `VersionSelector`).
74    pub blueprint: BlueprintRef,
75    /// Caller-supplied id for the Operator that owns this run.
76    pub operator_id: String,
77    /// The Operator's role for this run.
78    pub role: Role,
79    /// How long the attached session is allowed to live.
80    pub ttl: Duration,
81    /// Initial `ctx` for flow.ir `eval`. Read by every `Step.in`.
82    pub init_ctx: Value,
83    /// "Runtime Global" tier of the `OperatorKind` cascade. `Some(_)` is
84    /// always an explicit request — including `Some(OperatorKind::Automate)`
85    /// — that outranks the BP-level tiers (`OperatorDef.kind` /
86    /// `Blueprint.default_operator_kind`); `None` leaves it unspecified so
87    /// those tiers / the final default decide. Under `MainAi` /
88    /// `Composite`, `MainAIMiddleware`'s `spawn_hook` before/after
89    /// callbacks become effective. See
90    /// `crate::core::ctx::collapse_operator_kind`.
91    pub operator_kind: Option<crate::core::ctx::OperatorKind>,
92    /// `SeniorBridge` registry ID. `None` — none in use;
93    /// `Some(id)` — attach a bridge previously registered on the
94    /// engine.
95    pub bridge_id: Option<String>,
96    /// `SpawnHook` registry ID. Same shape as above — attach a hook
97    /// previously registered on the engine.
98    pub hook_id: Option<String>,
99    /// Operator registry ID — used on the path that hands the whole
100    /// spawn off to an external Operator.
101    pub operator_backend_id: Option<String>,
102    /// "Runtime Agent-level" tier (highest priority) of the `OperatorKind`
103    /// cascade — per-agent override, keyed by `AgentDef.name`. Empty by
104    /// default. See `crate::core::ctx::collapse_operator_kind` for the full tier
105    /// list.
106    pub operator_kind_overrides: HashMap<String, OperatorKind>,
107    /// Task-level canonical execution context (issue #19 ST2). When
108    /// `Some`, the resolved sibling fields (`project_root` / `work_dir`
109    /// / `task_metadata`) are threaded down to [`TaskLaunchInput`] and
110    /// consumed by
111    /// [`crate::middleware::task_input::TaskInputMiddleware::new_from_fields`].
112    /// `None` — no Task-level context is layered on the spawner stack
113    /// (default; keeps the wire body opt-in).
114    pub task_input: Option<TaskInputSpec>,
115    /// The "launch request" tier (tier 1) of the
116    /// `check_policy` cascade, threaded straight down to
117    /// [`TaskLaunchInput::check_policy`]. `None` (the default via
118    /// [`Self::automate`]) leaves this tier unspecified — the Blueprint tier
119    /// / server-wide default decide. Wired from the `POST /v1/tasks`
120    /// request body's top-level `check_policy` field.
121    pub check_policy: Option<CheckPolicy>,
122}
123
124impl TaskApplicationInput {
125    /// Helper for existing callers on the default path — no hooks and no
126    /// per-agent `OperatorKind` overrides. Leaves the "Runtime Global" tier
127    /// unspecified (`None`), so the BP-level tiers / final default
128    /// (`OperatorKind::Automate`) decide — this preserves today's
129    /// behaviour for every existing caller without silently forcing
130    /// `Automate` as an explicit override that would outrank a BP-declared
131    /// `MainAi`/`Composite` kind.
132    pub fn automate(
133        blueprint: BlueprintRef,
134        operator_id: impl Into<String>,
135        role: Role,
136        ttl: Duration,
137        init_ctx: Value,
138    ) -> Self {
139        Self {
140            blueprint,
141            operator_id: operator_id.into(),
142            role,
143            ttl,
144            init_ctx,
145            operator_kind: None,
146            bridge_id: None,
147            hook_id: None,
148            operator_backend_id: None,
149            operator_kind_overrides: HashMap::new(),
150            task_input: None,
151            check_policy: None,
152        }
153    }
154}
155
156/// Result of a successful [`TaskApplication::handle`] call.
157#[derive(Debug, Clone)]
158pub struct TaskApplicationOutput {
159    /// The capability token for the attached session.
160    pub token: CapToken,
161    /// The final `ctx` after the flow ran to completion.
162    pub final_ctx: Value,
163    /// Only `Some` when resolution went through the store
164    /// (`BlueprintRef::Id`); `None` on the Inline path.
165    pub bound_version: Option<BlueprintVersion>,
166}
167
168/// Failure modes of [`TaskApplication::handle`] and
169/// [`TaskApplication::resolve`].
170#[derive(Debug, Error)]
171pub enum TaskApplicationError {
172    /// `BlueprintRef::Id` was used but this `TaskApplication` was
173    /// built via [`TaskApplication::new_inline_only`] (no store).
174    #[error("store not configured (BlueprintRef::Id requires store)")]
175    NoStore,
176    /// The `BlueprintStore` returned an error while resolving the ref.
177    #[error("store: {0}")]
178    Store(#[from] BlueprintStoreError),
179    /// `TaskLaunchService::launch` failed after resolution succeeded.
180    #[error("launch: {0}")]
181    Launch(#[from] TaskLaunchError),
182    /// A stored version's `version_label` is not valid semver.
183    #[error("invalid semver version_label {label:?}: {source}")]
184    InvalidSemver {
185        /// The offending label string.
186        label: String,
187        /// The underlying semver parse error.
188        #[source]
189        source: semver::Error,
190    },
191    /// No stored version's label satisfies the `SemverReq`.
192    #[error("no version matches semver req: {req}")]
193    NoMatchingVersion {
194        /// The requirement string that matched nothing.
195        req: String,
196    },
197}
198
199impl From<SemverResolveError> for TaskApplicationError {
200    fn from(e: SemverResolveError) -> Self {
201        match e {
202            SemverResolveError::Store(e) => TaskApplicationError::Store(e),
203            SemverResolveError::InvalidSemver { label, source } => {
204                TaskApplicationError::InvalidSemver { label, source }
205            }
206            SemverResolveError::NoMatchingVersion { req } => {
207                TaskApplicationError::NoMatchingVersion { req }
208            }
209        }
210    }
211}
212
213/// The `POST /v1/tasks` [`Application`] — resolves a `BlueprintRef` and
214/// runs it to completion through [`TaskLaunchService`].
215pub struct TaskApplication {
216    launch: Arc<TaskLaunchService>,
217    /// Only needed when resolving `BlueprintRef::Id`; `None` in
218    /// Inline-only mode.
219    store: Option<Arc<dyn BlueprintStore>>,
220}
221
222impl TaskApplication {
223    /// Build a `TaskApplication` that can resolve both `Inline` and
224    /// `Id` `BlueprintRef`s (the `Id` path reads through `store`).
225    pub fn new(launch: Arc<TaskLaunchService>, store: Arc<dyn BlueprintStore>) -> Self {
226        Self {
227            launch,
228            store: Some(store),
229        }
230    }
231
232    /// Build a `TaskApplication` restricted to `Inline` `BlueprintRef`s
233    /// — no store is configured, so `Id` resolution always fails with
234    /// `TaskApplicationError::NoStore`.
235    pub fn new_inline_only(launch: Arc<TaskLaunchService>) -> Self {
236        Self {
237            launch,
238            store: None,
239        }
240    }
241
242    /// Resolve a `BlueprintRef` and return the real Blueprint plus,
243    /// when it went through the store, the resolved version.
244    pub async fn resolve(
245        &self,
246        bp_ref: &BlueprintRef,
247    ) -> Result<(Blueprint, Option<BlueprintVersion>), TaskApplicationError> {
248        match bp_ref {
249            BlueprintRef::Inline { value } => Ok((value.as_ref().clone(), None)),
250            BlueprintRef::Id { id, version } => {
251                let store = self.store.as_ref().ok_or(TaskApplicationError::NoStore)?;
252                let bp_id = id.clone();
253                let traced = match version {
254                    VersionSelector::Latest => store.read_head(&bp_id).await?,
255                    VersionSelector::Fixed { value } => store.read_version(&bp_id, *value).await?,
256                    VersionSelector::SemverReq { req } => {
257                        let v = super::semver_resolve::resolve_semver(store.as_ref(), &bp_id, req)
258                            .await?;
259                        store.read_version(&bp_id, v).await?
260                    }
261                };
262                let ver = traced.trace.version;
263                Ok((traced.value, Some(ver)))
264            }
265        }
266    }
267
268    /// Pre-flight compile check: resolve `bp_ref` and drive it through
269    /// `Compiler::compile` without launching. Returns `Ok(())` when the
270    /// Blueprint would compile cleanly (every `operator_ref` /
271    /// `meta_ref` / `audits[].agent` / verdict cond shape resolves), or
272    /// the same `TaskApplicationError` variants
273    /// [`Self::handle_with_run`] would surface for a resolve or compile
274    /// failure. No engine attach, no spawn, no `RunRecord` mutation.
275    ///
276    /// Used by `POST /v1/runs/:id/rerun-from` (GH #71 Layer A) as a
277    /// fast-fail gate: a deterministic compile-time failure — the
278    /// canonical case is an unbound `operator_ref` after an operator was
279    /// removed from `Blueprint.operators` between the original dispatch
280    /// and the rerun — surfaces as a `422` here BEFORE the handler
281    /// physically truncates the replay log via
282    /// `ReplayStore::delete_from`. Without this pre-check the same
283    /// failure fires later inside the detached `tokio::spawn`, after the
284    /// truncation has already consumed the pre-cut entries and left the
285    /// caller with no replay log to retry against.
286    pub async fn precompile(&self, bp_ref: &BlueprintRef) -> Result<(), TaskApplicationError> {
287        let (bp, _v) = self.resolve(bp_ref).await?;
288        self.launch
289            .compiler()
290            .compile(&bp)
291            .map_err(TaskLaunchError::from)?;
292        Ok(())
293    }
294
295    /// Resolve the `BlueprintRef` (Inline / Id) and run the flow to
296    /// completion through `TaskLaunchService::launch`, threading `run_ctx`
297    /// (issue #13 run_id propagation) into the launch input.
298    ///
299    /// [`Application::handle`] delegates here with `run_ctx: None` — a
300    /// separate method rather than a new field on [`TaskApplicationInput`]
301    /// so the pre-existing exhaustive `TaskApplicationInput { .. }` struct
302    /// literal in `mlua-swarm-cli`'s MCP adapter (which has no `run_ctx`)
303    /// keeps compiling unchanged. Server entry points that mint a `RunId`
304    /// up front (`POST /v1/tasks`, `POST /v1/tasks/:id/runs`) call this
305    /// directly with `Some(run_ctx)`.
306    pub async fn handle_with_run(
307        &self,
308        input: TaskApplicationInput,
309        run_ctx: Option<RunContext>,
310    ) -> Result<TaskApplicationOutput, TaskApplicationError> {
311        let (blueprint, bound_version) = self.resolve(&input.blueprint).await?;
312        let TaskLaunchOutput { token, final_ctx } = self
313            .launch
314            .launch(TaskLaunchInput {
315                blueprint,
316                operator_id: input.operator_id,
317                role: input.role,
318                ttl: input.ttl,
319                operator_kind: input.operator_kind,
320                bridge_id: input.bridge_id,
321                hook_id: input.hook_id,
322                operator_backend_id: input.operator_backend_id,
323                operator_kind_overrides: input.operator_kind_overrides,
324                init_ctx: input.init_ctx,
325                run_ctx,
326                task_input: input.task_input,
327                check_policy: input.check_policy,
328            })
329            .await?;
330        Ok(TaskApplicationOutput {
331            token,
332            final_ctx,
333            bound_version,
334        })
335    }
336}
337
338#[async_trait]
339impl Application for TaskApplication {
340    type Input = TaskApplicationInput;
341    type Output = TaskApplicationOutput;
342    type Error = TaskApplicationError;
343
344    fn name(&self) -> &str {
345        "task"
346    }
347
348    /// Resolve the `BlueprintRef` (Inline / Id) and run the flow to
349    /// completion through `TaskLaunchService::launch`. Delegates to
350    /// [`TaskApplication::handle_with_run`] with `run_ctx: None` (no run
351    /// tracing) — callers that need `RunRecord.step_entries` tracing call
352    /// `handle_with_run` directly instead.
353    async fn handle(&self, input: Self::Input) -> Result<Self::Output, Self::Error> {
354        self.handle_with_run(input, None).await
355    }
356}
357
358// ──────────────────────────────────────────────────────────────────────────
359// UT
360// ──────────────────────────────────────────────────────────────────────────
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365    use crate::blueprint::compiler::{Compiler, SpawnerRegistry};
366    use crate::blueprint::store::{
367        blueprint_version, BlueprintId, BlueprintStore, BlueprintStoreError, CommitMetadata,
368        InMemoryBlueprintStore,
369    };
370    use crate::blueprint::{
371        current_schema_version, AgentKind, Blueprint, BlueprintMetadata, CompilerHints,
372        CompilerStrategy,
373    };
374    use crate::core::config::EngineCfg;
375    use crate::core::ctx::OperatorKind;
376    use crate::core::engine::Engine;
377    use mlua_flow_ir::Node as FlowNode;
378
379    fn empty_bp() -> Blueprint {
380        Blueprint {
381            schema_version: current_schema_version(),
382            id: "ut-bp".into(),
383            flow: FlowNode::Seq { children: vec![] },
384            agents: vec![],
385            operators: vec![],
386            metas: vec![],
387            hints: CompilerHints::default(),
388            strategy: CompilerStrategy::default(),
389            metadata: BlueprintMetadata::default(),
390            spawner_hints: Default::default(),
391            default_agent_kind: AgentKind::Operator,
392            default_operator_kind: None,
393            default_init_ctx: None,
394            default_agent_ctx: None,
395            default_context_policy: None,
396            projection_placement: None,
397            audits: vec![],
398            degradation_policy: None,
399            runners: vec![],
400            default_runner: None,
401            check_policy: None,
402            blueprint_ref_includes: Vec::new(),
403        }
404    }
405
406    fn bp_with_label(id: &str, version_label: Option<&str>) -> Blueprint {
407        Blueprint {
408            schema_version: current_schema_version(),
409            id: id.into(),
410            flow: FlowNode::Seq { children: vec![] },
411            agents: vec![],
412            operators: vec![],
413            metas: vec![],
414            hints: CompilerHints::default(),
415            strategy: CompilerStrategy::default(),
416            metadata: BlueprintMetadata {
417                description: None,
418                origin: Default::default(),
419                tags: vec![],
420                version_label: version_label.map(|s| s.to_string()),
421                project_name_alias: None,
422                default_run_ttl_secs: None,
423                strict_verdict_handling: None,
424            },
425            spawner_hints: Default::default(),
426            default_agent_kind: AgentKind::Operator,
427            default_operator_kind: None,
428            default_init_ctx: None,
429            default_agent_ctx: None,
430            default_context_policy: None,
431            projection_placement: None,
432            audits: vec![],
433            degradation_policy: None,
434            runners: vec![],
435            default_runner: None,
436            check_policy: None,
437            blueprint_ref_includes: Vec::new(),
438        }
439    }
440
441    fn build_app_with_store() -> (TaskApplication, Arc<dyn BlueprintStore>) {
442        let reg = SpawnerRegistry::new();
443        let compiler = Compiler::new(reg);
444        let engine = Engine::new(EngineCfg::default());
445        let launch = Arc::new(TaskLaunchService::new(engine, compiler));
446        let store: Arc<dyn BlueprintStore> = Arc::new(InMemoryBlueprintStore::new());
447        (TaskApplication::new(launch, store.clone()), store)
448    }
449
450    fn build_app_inline_only() -> TaskApplication {
451        let reg = SpawnerRegistry::new();
452        let compiler = Compiler::new(reg);
453        let engine = Engine::new(EngineCfg::default());
454        let launch = Arc::new(TaskLaunchService::new(engine, compiler));
455        TaskApplication::new_inline_only(launch)
456    }
457
458    async fn seed(store: &Arc<dyn BlueprintStore>, bp: &Blueprint) -> BlueprintVersion {
459        let id = bp.id.clone();
460        let v = blueprint_version(bp).expect("hash");
461        store
462            .write_new(&id, bp, &[], CommitMetadata::seed(id.clone(), v, 0))
463            .await
464            .expect("seed");
465        v
466    }
467
468    #[test]
469    fn automate_helper_sets_defaults() {
470        let input = TaskApplicationInput::automate(
471            BlueprintRef::Inline {
472                value: Box::new(empty_bp()),
473            },
474            "op-1",
475            Role::Operator,
476            Duration::from_secs(10),
477            serde_json::json!({}),
478        );
479        assert!(
480            input.operator_kind.is_none(),
481            "automate() leaves the Runtime Global tier unspecified (None), \
482             not an explicit Some(Automate) override"
483        );
484        assert!(input.bridge_id.is_none());
485        assert!(input.hook_id.is_none());
486        assert_eq!(input.operator_id, "op-1");
487    }
488
489    #[test]
490    fn struct_literal_allows_callback_ids() {
491        let input = TaskApplicationInput {
492            blueprint: BlueprintRef::Inline {
493                value: Box::new(empty_bp()),
494            },
495            operator_id: "op-2".into(),
496            role: Role::Operator,
497            ttl: Duration::from_secs(5),
498            init_ctx: serde_json::json!({}),
499            operator_kind: Some(OperatorKind::MainAi),
500            bridge_id: Some("br-x".into()),
501            hook_id: Some("hk-y".into()),
502            operator_backend_id: None,
503            operator_kind_overrides: HashMap::new(),
504            task_input: None,
505            check_policy: None,
506        };
507        assert!(matches!(input.operator_kind, Some(OperatorKind::MainAi)));
508        assert_eq!(input.bridge_id.as_deref(), Some("br-x"));
509        assert_eq!(input.hook_id.as_deref(), Some("hk-y"));
510    }
511
512    // ──────────────────────────────────────────────────────────────────
513    // resolve / resolve_semver carve
514    // ──────────────────────────────────────────────────────────────────
515
516    #[tokio::test]
517    async fn resolve_inline_returns_bp_and_no_version() {
518        let app = build_app_inline_only();
519        let bp = empty_bp();
520        let (got, ver) = app
521            .resolve(&BlueprintRef::Inline {
522                value: Box::new(bp.clone()),
523            })
524            .await
525            .expect("resolve inline ok");
526        assert_eq!(got.id, bp.id);
527        assert!(ver.is_none(), "the Inline path yields bound_version=None");
528    }
529
530    #[tokio::test]
531    async fn resolve_id_latest_returns_bp_and_version() {
532        let (app, store) = build_app_with_store();
533        let bp = bp_with_label("rid-latest", Some("0.1.0"));
534        let v = seed(&store, &bp).await;
535        let (got, ver) = app
536            .resolve(&BlueprintRef::Id {
537                id: bp.id.clone(),
538                version: VersionSelector::Latest,
539            })
540            .await
541            .expect("resolve id latest ok");
542        assert_eq!(got.id, bp.id);
543        assert_eq!(ver, Some(v), "Latest = seed version");
544    }
545
546    #[tokio::test]
547    async fn resolve_id_fixed_picks_exact_version() {
548        let (app, store) = build_app_with_store();
549        let id = "rid-fixed";
550        let bp1 = bp_with_label(id, Some("1.0.0"));
551        let bp2 = bp_with_label(id, Some("2.0.0"));
552        let v1 = seed(&store, &bp1).await;
553        let _v2 = seed(&store, &bp2).await;
554        let (got, ver) = app
555            .resolve(&BlueprintRef::Id {
556                id: BlueprintId::new(id),
557                version: VersionSelector::Fixed { value: v1 },
558            })
559            .await
560            .expect("resolve id fixed ok");
561        assert_eq!(ver, Some(v1));
562        assert_eq!(
563            got.metadata.version_label.as_deref(),
564            Some("1.0.0"),
565            "Fixed{{v1}} resolves to v1 = 1.0.0"
566        );
567    }
568
569    #[tokio::test]
570    async fn resolve_id_semver_picks_highest_matching() {
571        let (app, store) = build_app_with_store();
572        let id = "rid-semver";
573        let _ = seed(&store, &bp_with_label(id, Some("1.0.0"))).await;
574        let _ = seed(&store, &bp_with_label(id, Some("1.2.0"))).await;
575        let _ = seed(&store, &bp_with_label(id, Some("2.0.0"))).await;
576        let req = semver::VersionReq::parse("^1").expect("req");
577        let (got, ver) = app
578            .resolve(&BlueprintRef::Id {
579                id: BlueprintId::new(id),
580                version: VersionSelector::SemverReq { req },
581            })
582            .await
583            .expect("resolve semver ok");
584        assert!(ver.is_some());
585        assert_eq!(
586            got.metadata.version_label.as_deref(),
587            Some("1.2.0"),
588            "^1 max = 1.2.0 (2.0.0 is out of range; 1.0.0 is lower)"
589        );
590    }
591
592    #[tokio::test]
593    async fn resolve_id_semver_no_match_errs() {
594        let (app, store) = build_app_with_store();
595        let id = "rid-semver-nomatch";
596        let _ = seed(&store, &bp_with_label(id, Some("1.0.0"))).await;
597        let req = semver::VersionReq::parse("^3").expect("req");
598        let err = app
599            .resolve(&BlueprintRef::Id {
600                id: BlueprintId::new(id),
601                version: VersionSelector::SemverReq { req },
602            })
603            .await
604            .expect_err("expected NoMatchingVersion");
605        match err {
606            TaskApplicationError::NoMatchingVersion { req } => {
607                assert!(req.contains("^3"), "req string carry: {req}");
608            }
609            other => panic!("expected NoMatchingVersion, got {other:?}"),
610        }
611    }
612
613    #[tokio::test]
614    async fn resolve_id_semver_invalid_label_errs() {
615        let (app, store) = build_app_with_store();
616        let id = "rid-semver-bad";
617        let _ = seed(&store, &bp_with_label(id, Some("not-semver"))).await;
618        let req = semver::VersionReq::parse("^1").expect("req");
619        let err = app
620            .resolve(&BlueprintRef::Id {
621                id: BlueprintId::new(id),
622                version: VersionSelector::SemverReq { req },
623            })
624            .await
625            .expect_err("expected InvalidSemver");
626        match err {
627            TaskApplicationError::InvalidSemver { label, .. } => {
628                assert_eq!(label, "not-semver");
629            }
630            other => panic!("expected InvalidSemver, got {other:?}"),
631        }
632    }
633
634    #[tokio::test]
635    async fn resolve_id_without_store_errs_no_store() {
636        let app = build_app_inline_only();
637        let err = app
638            .resolve(&BlueprintRef::Id {
639                id: BlueprintId::new("anything"),
640                version: VersionSelector::Latest,
641            })
642            .await
643            .expect_err("expected NoStore");
644        assert!(matches!(err, TaskApplicationError::NoStore), "got {err:?}");
645    }
646
647    #[tokio::test]
648    async fn resolve_id_not_found_errs_store() {
649        let (app, _store) = build_app_with_store();
650        let err = app
651            .resolve(&BlueprintRef::Id {
652                id: BlueprintId::new("never-seeded"),
653                version: VersionSelector::Latest,
654            })
655            .await
656            .expect_err("expected Store(IdNotFound|HeadEmpty)");
657        match err {
658            TaskApplicationError::Store(
659                BlueprintStoreError::IdNotFound(_) | BlueprintStoreError::HeadEmpty(_),
660            ) => {}
661            other => panic!("expected Store(IdNotFound|HeadEmpty), got {other:?}"),
662        }
663    }
664}