Skip to main content

mlua_swarm/service/
task_launch.rs

1//! `TaskLaunchService` — the domain service that runs a Blueprint flow
2//! to completion through the engine.
3//!
4//! Responsibilities:
5//! 1. Compile the Blueprint and link it into a `SpawnerAdapter` (via
6//!    `service::linker::link`, wrapped by `EngineDispatcher::with_spawner`).
7//! 2. Acquire an Operator session (via `engine.attach`).
8//! 3. Run flow.ir's `eval_async_externs` through an `EngineDispatcher`
9//!    (threading the service-held `call_extern` registry) and return
10//!    the final `ctx`.
11//! 4. If any step fails (dispatcher error), the eval errors and
12//!    the failure propagates as-is.
13//!
14//! Callers on the Application layer never touch the engine directly —
15//! `bind`, `start_task`, and `eval_async` all stay inside the Service.
16//!
17//! A single-task-spawn API (calling `start_task` directly) is
18//! deliberately absent here: a single spawn can be modeled as a
19//! one-Step flow, and we do not want two interfaces for the same
20//! shape.
21
22use crate::binding::{
23    attest_bound_agents, binding_requests, validate_bound_agent_snapshots, AgentBindingProvider,
24    LegacyWorkerBindingPolicy, UnboundAgent,
25};
26use crate::blueprint::compiler::{materialize_bound_blueprint, CompileError, Compiler};
27use crate::blueprint::{
28    resolve_bound_agents, AuditDef, Blueprint, BoundAgent, EngineDispatcher, Runner,
29};
30use crate::core::agent_context::ContextPolicy;
31use crate::core::config::CheckPolicy;
32use crate::core::ctx::OperatorKind;
33use crate::core::engine::Engine;
34use crate::core::errors::EngineError;
35use crate::middleware::agent_context::AgentContextMiddleware;
36use crate::middleware::project_name_alias::ProjectNameAliasMiddleware;
37use crate::middleware::task_input::TaskInputMiddleware;
38use crate::middleware::worker_binding::WorkerBindingMiddleware;
39use crate::middleware::{AfterRunAuditMiddleware, SpawnerStack};
40use crate::operator::WorkerBinding;
41use crate::service::linker;
42use crate::store::run::{RunContext, SnapshotOrigin};
43use crate::types::{CapToken, Role};
44use mlua_flow_ir::{Externs, NoExterns};
45use serde::{Deserialize, Serialize};
46use serde_json::Value;
47use std::collections::HashMap;
48use std::sync::Arc;
49use std::time::Duration;
50use thiserror::Error;
51
52/// Derive the "BP Agent-level" tier of the `OperatorKind` cascade from a
53/// Blueprint: for every `AgentDef` whose `spec.operator_ref` resolves to an
54/// `OperatorDef` with a `Some` `kind`, map `AgentDef.name -> OperatorKind`.
55///
56/// Deliberately **not** filtered by `AgentDef.kind == AgentKind::Operator`:
57/// the `OperatorKind` cascade is a middleware-level cross-cutting concern
58/// (spawn_hook / senior_bridge gating via `Ctx.operator` — the
59/// operator-delegate third has been withdrawn),
60/// orthogonal to the Worker IMPL axis that `AgentKind` expresses (see the
61/// crate root doc, "Operator is delivered as a cross-cutting overlay through
62/// `Ctx` plus middleware"). A `RustFn` / `Lua` / `Subprocess` agent can
63/// equally declare `spec.operator_ref` to opt into a BP-declared
64/// `OperatorKind` without changing its Worker IMPL. Agents without an
65/// `operator_ref`, an unresolved `operator_ref`, or an `OperatorDef.kind =
66/// None` are simply absent from the map (= that tier falls through for
67/// them). This is a separate, independent consumer of `Blueprint.operators`
68/// from the design-time `operator_ref` validation in
69/// `blueprint::compiler::Compiler::compile` (issue: `OperatorDef`
70/// first-class treatment), which only checks the reference resolves for
71/// `AgentKind::Operator` agents and is unaffected by this function.
72/// Build the `agent name → WorkerBinding` map from
73/// `Blueprint.agents[].profile.worker_binding` — the launch-time sibling of
74/// the compile-time resolution in `OperatorSpawnerFactory::build`. Consumed
75/// by `WorkerBindingMiddleware`, which publishes the binding on `ctx` keyed
76/// by `ctx.agent` like every other agent-keyed table
77/// (`CompiledAgentTable.routes` idiom).
78/// Agents without a declared binding are simply absent (no silent default).
79#[cfg(test)]
80pub(crate) fn derive_worker_bindings(blueprint: &Blueprint) -> HashMap<String, WorkerBinding> {
81    // Kept as a test-facing compatibility name. Production resolves once
82    // and calls `worker_bindings_from_bound_agents` with that snapshot.
83    let bound_agents = resolve_bound_agents(blueprint)
84        .expect("derive_worker_bindings requires a Blueprint with resolvable Runner refs");
85    worker_bindings_from_bound_agents(&bound_agents)
86}
87
88fn worker_bindings_from_bound_agents(
89    bound_agents: &[BoundAgent],
90) -> HashMap<String, WorkerBinding> {
91    bound_agents
92        .iter()
93        .filter_map(|bound| match &bound.runner {
94            Some(Runner::WsOperator { variant, tools })
95            | Some(Runner::WsClaudeCode { variant, tools }) => Some((
96                bound.agent.name.clone(),
97                WorkerBinding {
98                    variant: variant.clone(),
99                    tools: tools.clone(),
100                    request_digest: Some(bound.binding_digest.clone()),
101                    requested_model: bound.agent.profile.as_ref().and_then(|p| p.model.clone()),
102                },
103            )),
104            _ => None,
105        })
106        .collect()
107}
108
109/// Attest a freshly resolved snapshot (or enforce the strict-without-provider
110/// gate) exactly once, applied identically on both first-resolution paths in
111/// [`load_or_resolve_bound_agents`].
112///
113/// `strict` = [`crate::blueprint::CompilerStrategy::strict_binding`]:
114///
115/// - With a provider: every `Bound` outcome is validated and pinned; any
116///   `Unbound` agent fails the launch when `strict`, or (non-strict) is
117///   reported through a `tracing::warn!` and, if a `RunContext` is present, a
118///   `RunRecord.degradations` entry (the existing append-only channel). The
119///   agent stays `DeclarationOnly` either way.
120/// - Without a provider: a `strict` Blueprint that declares any Runner-backed
121///   agent fails fast (`PreDispatch`) because nothing can attest it; a
122///   non-strict Blueprint runs `DeclarationOnly` (the embed use case).
123async fn attest_or_gate_fresh(
124    bound_agents: &mut [BoundAgent],
125    binding_provider: Option<&dyn AgentBindingProvider>,
126    strict: bool,
127    run_ctx: Option<&RunContext>,
128) -> Result<(), TaskLaunchError> {
129    match binding_provider {
130        Some(provider) => {
131            let unbound = attest_bound_agents(provider, bound_agents, strict)
132                .await
133                .map_err(|error| TaskLaunchError::PreDispatch(error.to_string()))?;
134            for agent in &unbound {
135                record_unbound_degradation(agent, run_ctx).await;
136            }
137            Ok(())
138        }
139        None => {
140            if strict && !binding_requests(bound_agents).is_empty() {
141                return Err(TaskLaunchError::PreDispatch(format!(
142                    "strict_binding requires a binding provider but none is injected; \
143                     {} Runner-backed agent(s) cannot be attested",
144                    binding_requests(bound_agents).len()
145                )));
146            }
147            Ok(())
148        }
149    }
150}
151
152/// Record one non-strict unattested agent: a `tracing::warn!` always, plus a
153/// `RunRecord.degradations` append when a `RunContext` carries a run store.
154/// Observational only — a failed append is itself logged and never fails the
155/// launch (degradation recording must not gate a launch the strict decision
156/// already let through).
157async fn record_unbound_degradation(agent: &UnboundAgent, run_ctx: Option<&RunContext>) {
158    tracing::warn!(
159        agent = %agent.agent,
160        reason = %agent.reason,
161        "binding_unattested: agent runs DeclarationOnly (strict_binding is off)"
162    );
163    let Some(run_ctx) = run_ctx else {
164        return;
165    };
166    let entry = crate::store::run::DegradationEntry {
167        tool: "binding".to_string(),
168        error: agent.reason.clone(),
169        fallback: "DeclarationOnly".to_string(),
170        note: Some(format!(
171            "agent '{}' launched without a binding attestation (strict_binding off)",
172            agent.agent
173        )),
174        step_ref: None,
175        attempt: None,
176        at: crate::types::now_unix(),
177    };
178    if let Err(error) = run_ctx
179        .run_store
180        .append_degradation(&run_ctx.run_id, entry)
181        .await
182    {
183        tracing::warn!(
184            agent = %agent.agent,
185            %error,
186            "binding_unattested: failed to record degradation entry"
187        );
188    }
189}
190
191async fn load_or_resolve_bound_agents(
192    blueprint: &Blueprint,
193    run_ctx: Option<&RunContext>,
194    binding_provider: Option<&dyn AgentBindingProvider>,
195    legacy_worker_binding_policy: LegacyWorkerBindingPolicy,
196) -> Result<(Vec<BoundAgent>, SnapshotOrigin), TaskLaunchError> {
197    // Strict binding is a BP-level opt-in only (server config / launch
198    // request cascade is intentionally out of scope for this change).
199    let strict = blueprint.strategy.strict_binding;
200    let resolve_fresh = || match legacy_worker_binding_policy {
201        LegacyWorkerBindingPolicy::Allow => resolve_bound_agents(blueprint),
202        LegacyWorkerBindingPolicy::Reject => {
203            crate::blueprint::resolve_bound_agents_strict(blueprint)
204        }
205    };
206    let Some(run_ctx) = run_ctx else {
207        // No Run context (embed use): nothing to persist, and no snapshot
208        // to backfill — this is an initial launch by definition.
209        let mut bound_agents = resolve_fresh().map_err(CompileError::from)?;
210        attest_or_gate_fresh(&mut bound_agents, binding_provider, strict, None).await?;
211        return Ok((bound_agents, SnapshotOrigin::Launch));
212    };
213
214    let record = run_ctx
215        .run_store
216        .get(&run_ctx.run_id)
217        .await
218        .map_err(|e| TaskLaunchError::PreDispatch(format!("load Run binding snapshot: {e}")))?;
219    if let Some(input_json) = record.input_json.as_deref() {
220        let snapshot: Value = serde_json::from_str(input_json).map_err(|e| {
221            TaskLaunchError::PreDispatch(format!("decode Run launch snapshot: {e}"))
222        })?;
223        if let Some(value) = snapshot.get("bound_agents") {
224            let bound_agents: Vec<BoundAgent> =
225                serde_json::from_value(value.clone()).map_err(|e| {
226                    TaskLaunchError::PreDispatch(format!("decode Run BoundAgent snapshot: {e}"))
227                })?;
228            validate_bound_agent_snapshots(&bound_agents).map_err(|error| {
229                TaskLaunchError::PreDispatch(format!("validate Run BoundAgent snapshot: {error}"))
230            })?;
231            // [Crux D2-b] The fast path reads the PERSISTED origin marker
232            // rather than re-deriving it from `run_ctx.resume`, so a
233            // backfilled Run stays `resume_backfill` (and keeps its legacy
234            // replay keys) across every subsequent resume — the outcome is a
235            // function of the pinned snapshot, not of how many times the Run
236            // was resumed. An absent marker maps to `resume_backfill` (the
237            // safe side — see `SnapshotOrigin::from_snapshot`).
238            let origin = SnapshotOrigin::from_snapshot(&snapshot);
239            return Ok((bound_agents, origin));
240        }
241    }
242
243    let mut bound_agents = resolve_fresh().map_err(CompileError::from)?;
244    attest_or_gate_fresh(&mut bound_agents, binding_provider, strict, Some(run_ctx)).await?;
245    // [Crux D1-b] The origin is decided by the RunContext's explicit `resume`
246    // flag ALONE — never inferred from replay-cursor / step-entry presence,
247    // whose wiring is free to change. A resume / rerun-from re-derives the
248    // snapshot from the current Blueprint (no launch-time pin); an initial
249    // launch persists the authoritative pin.
250    let origin = if run_ctx.resume {
251        SnapshotOrigin::ResumeBackfill
252    } else {
253        SnapshotOrigin::Launch
254    };
255    if let Some(input_json) = record.input_json {
256        let mut snapshot: Value = serde_json::from_str(&input_json).map_err(|e| {
257            TaskLaunchError::PreDispatch(format!("decode Run launch snapshot: {e}"))
258        })?;
259        let object = snapshot.as_object_mut().ok_or_else(|| {
260            TaskLaunchError::PreDispatch("Run launch snapshot must be a JSON object".to_string())
261        })?;
262        // [Crux D1-a] `bound_agents` and its `bound_agents_origin` marker are
263        // written into the SAME snapshot object and persisted in the SAME
264        // `set_input_json` call — never two writes, so no intermediate state
265        // can carry one without the other.
266        object.insert(
267            "bound_agents".to_string(),
268            serde_json::to_value(&bound_agents).map_err(|e| {
269                TaskLaunchError::PreDispatch(format!("encode Run BoundAgent snapshot: {e}"))
270            })?,
271        );
272        object.insert(
273            crate::store::run::BOUND_AGENTS_ORIGIN_KEY.to_string(),
274            serde_json::to_value(origin).map_err(|e| {
275                TaskLaunchError::PreDispatch(format!("encode Run BoundAgent origin: {e}"))
276            })?,
277        );
278        run_ctx
279            .run_store
280            .set_input_json(
281                &run_ctx.run_id,
282                serde_json::to_string(&snapshot).map_err(|e| {
283                    TaskLaunchError::PreDispatch(format!("encode Run launch snapshot: {e}"))
284                })?,
285            )
286            .await
287            .map_err(|e| {
288                TaskLaunchError::PreDispatch(format!("persist Run BoundAgent snapshot: {e}"))
289            })?;
290    }
291    // A resume that had to backfill its bindings is an observed degradation
292    // (the binding identity is no longer a launch-time pin). Append-only,
293    // never fails the launch — mirrors `record_unbound_degradation`.
294    if origin == SnapshotOrigin::ResumeBackfill {
295        record_backfill_degradation(run_ctx, blueprint.id.as_str()).await;
296    }
297    Ok((bound_agents, origin))
298}
299
300/// Record one binding backfill: a pre-binding-snapshot Run was resumed (or
301/// reran) and its `bound_agents` were re-derived from the current Blueprint
302/// rather than restored from a launch-time pin. Same append-only,
303/// never-fail-the-launch posture as [`record_unbound_degradation`] — a failed
304/// append is logged and swallowed (the launch has already committed to
305/// running).
306async fn record_backfill_degradation(run_ctx: &RunContext, blueprint_id: &str) {
307    tracing::warn!(
308        run_id = %run_ctx.run_id,
309        blueprint = %blueprint_id,
310        "binding_backfill: resumed Run had no binding snapshot; bound_agents \
311         re-derived from the current Blueprint (not a launch-time pin)"
312    );
313    let entry = crate::store::run::DegradationEntry {
314        tool: "binding".to_string(),
315        error: "run resumed without a launch-pinned binding snapshot".to_string(),
316        fallback: "resume_backfill".to_string(),
317        note: Some(format!(
318            "run '{}' backfilled bound_agents from Blueprint '{}' at resume time",
319            run_ctx.run_id, blueprint_id
320        )),
321        step_ref: None,
322        attempt: None,
323        at: crate::types::now_unix(),
324    };
325    if let Err(error) = run_ctx
326        .run_store
327        .append_degradation(&run_ctx.run_id, entry)
328        .await
329    {
330        tracing::warn!(
331            run_id = %run_ctx.run_id,
332            %error,
333            "binding_backfill: failed to record degradation entry"
334        );
335    }
336}
337
338/// GH #34 — extract the Blueprint-declared after-run audit hooks
339/// (`Blueprint.audits`), the launch-time input to `AfterRunAuditMiddleware`.
340/// Trivial extraction (unlike [`derive_worker_bindings`] / the agent-context
341/// derivers below, no per-agent lookup is needed — `AuditDef.agent` is a
342/// plain agent-name string already validated against `Blueprint.agents` at
343/// `Compiler::compile` time). `[]` (every pre-#34 Blueprint) means "no
344/// audit layer at all" — see the conditional `.layer(...)` wiring in
345/// [`TaskLaunchService::launch`] (invariant #4: byte-identical behavior).
346fn derive_audits(blueprint: &Blueprint) -> Vec<AuditDef> {
347    blueprint.audits.clone()
348}
349
350/// Issue #21 Phase 1: build the agent-context supply axis's "BP Global" +
351/// "BP Agent-level" context tiers from a Blueprint — the launch-time
352/// sibling of [`derive_worker_bindings`] (same "no silent default"
353/// discipline: an agent's entry is present only when it declares one).
354/// Consumed by `AgentContextMiddleware`, which shallow-merges the two
355/// tiers per spawn (agent wins) and inserts the result into
356/// `ctx.meta.runtime` only-if-absent (see
357/// `crate::middleware::agent_context`'s module doc for the full merge +
358/// precedence narrative).
359///
360/// - `.0` (global) = [`Blueprint::default_agent_ctx`], unchanged.
361/// - `.1` (per-agent) = `AgentDef.name -> AgentMeta.ctx`, entry present
362///   only for agents whose `meta` is `Some` and who declare a `ctx`
363///   (directly via `meta.ctx`, and/or indirectly via
364///   [`AgentMeta::meta_ref`] — GH #21 Phase 2, see below).
365///
366/// # GH #21 Phase 2: `AgentMeta.meta_ref` resolution
367///
368/// When an agent declares `meta.meta_ref`, it is resolved against
369/// [`derive_step_metas`]'s pool and used as the BASE layer UNDER the
370/// agent's own inline `meta.ctx` (inline wins on key collision, shallow
371/// merge — see [`shallow_merge_inline_wins`]). An unresolved `meta_ref`
372/// at this point means the caller launched a Blueprint that bypassed
373/// `Compiler::compile`'s validation (the loud gate for this case, see
374/// `blueprint::compiler::Compiler::compile`'s `UnresolvedMetaRef` check);
375/// this function stays defensive and never panics — it logs a warning and
376/// skips the base layer, letting the agent's own inline `ctx` (if any)
377/// stand alone.
378pub(crate) fn derive_agent_ctx(blueprint: &Blueprint) -> (Option<Value>, HashMap<String, Value>) {
379    let global = blueprint.default_agent_ctx.clone();
380    let meta_pool = derive_step_metas(blueprint);
381    let per_agent = blueprint
382        .agents
383        .iter()
384        .filter_map(|ad| {
385            let meta = ad.meta.as_ref()?;
386            let inline = meta.ctx.clone();
387            let base = meta.meta_ref.as_ref().and_then(|name| {
388                let resolved = meta_pool.get(name).cloned();
389                if resolved.is_none() {
390                    tracing::warn!(
391                        agent = %ad.name,
392                        meta_ref = %name,
393                        "derive_agent_ctx: AgentMeta.meta_ref names an undefined Blueprint.metas entry; skipping the base layer"
394                    );
395                }
396                resolved
397            });
398            let merged = match (base, inline) {
399                (None, None) => None,
400                (Some(base), None) => Some(base),
401                (None, Some(inline)) => Some(inline),
402                (Some(base), Some(inline)) => Some(shallow_merge_inline_wins(base, inline)),
403            };
404            merged.map(|ctx| (ad.name.clone(), ctx))
405        })
406        .collect();
407    (global, per_agent)
408}
409
410/// GH #21 Phase 2: shallow-merge `base` with `inline`, `inline` winning
411/// key collisions. Both sides being JSON `Object`s is the meaningful case
412/// (per-key merge); a non-`Object` `inline` is used as-is (it "wins"
413/// entirely — the malformed-shape case is left to
414/// `AgentContextMiddleware`'s own tier merge, which already warns + skips
415/// a non-`Object` tier value downstream, never failing the spawn).
416pub(crate) fn shallow_merge_inline_wins(base: Value, inline: Value) -> Value {
417    match (base, inline) {
418        (Value::Object(mut base), Value::Object(inline)) => {
419            for (k, v) in inline {
420                base.insert(k, v);
421            }
422            Value::Object(base)
423        }
424        (_, inline) => inline,
425    }
426}
427
428/// GH #21 Phase 2: build the `Blueprint.metas` named pool (`MetaDef.name
429/// -> MetaDef.ctx`) — the launch-time sibling of [`derive_worker_bindings`]
430/// / [`derive_agent_ctx`], resolving the Step tier's shared pool instead
431/// of a per-agent map. Consumed by `EngineDispatcher::with_step_metas`
432/// (the Step tier's `$step_meta.ref` resolver) and, indirectly, by
433/// [`derive_agent_ctx`]'s `AgentMeta.meta_ref` resolution (the Agent
434/// tier shares the same pool).
435fn derive_step_metas(blueprint: &Blueprint) -> HashMap<String, Value> {
436    blueprint
437        .metas
438        .iter()
439        .map(|m| (m.name.clone(), m.ctx.clone()))
440        .collect()
441}
442
443/// Issue #21 Phase 1: build the [`ContextPolicy`] cascade's "BP Global" +
444/// "BP Agent-level" tiers from a Blueprint — same shape and discipline as
445/// [`derive_agent_ctx`], from `Blueprint.default_context_policy` /
446/// `AgentMeta.context_policy` instead. Consumed by
447/// `AgentContextMiddleware`, which resolves the effective policy per spawn
448/// (per-agent tier outranks the BP-global one; pass-all when neither is
449/// declared for the dispatching agent).
450fn derive_context_policies(
451    blueprint: &Blueprint,
452) -> (Option<ContextPolicy>, HashMap<String, ContextPolicy>) {
453    let default_policy = blueprint.default_context_policy.clone();
454    let per_agent = blueprint
455        .agents
456        .iter()
457        .filter_map(|ad| {
458            let meta = ad.meta.as_ref()?;
459            let policy = meta.context_policy.clone()?;
460            Some((ad.name.clone(), policy))
461        })
462        .collect();
463    (default_policy, per_agent)
464}
465
466/// Issue #19 ST3: shallow-merge the "BP Global" default `init_ctx`
467/// (`Blueprint.default_init_ctx`) with the Task-level `init_ctx` — the
468/// second layer of the (eventual 4-layer) init-ctx cascade, following the
469/// same "BP default, Task overrides" shape as the `OperatorKind` cascade
470/// (see `derive_bp_agent_kinds` / `TaskLaunchInput::operator_kind`).
471///
472/// Semantics (deliberately a single rule, no deep merge / JSON Patch):
473///
474/// - `bp_default = None` → `task_init_ctx` passes through unchanged
475///   (pre-#19 Blueprints keep today's exact behavior).
476/// - Both sides are `Value::Object` → shallow key-wise merge, Task wins
477///   on collision (`task_init_ctx`'s keys are applied last).
478/// - `task_init_ctx` is present but not an `Object` (`Null` / `String` /
479///   `Array` / `Number` / `Bool`) → Task fully replaces the BP default;
480///   the caller's non-Object seed is respected as-is.
481fn merge_init_ctx(bp_default: Option<&Value>, task_init_ctx: &Value) -> Value {
482    match (bp_default, task_init_ctx) {
483        (Some(Value::Object(bp_map)), Value::Object(task_map)) => {
484            let mut merged = bp_map.clone();
485            for (k, v) in task_map {
486                merged.insert(k.clone(), v.clone());
487            }
488            Value::Object(merged)
489        }
490        (None, _) => task_init_ctx.clone(),
491        (_, task) => task.clone(),
492    }
493}
494
495/// Issue #19 ST4: 3-layer shallow-merge of the init-ctx cascade — BP
496/// default → Task → Run (lowest to highest priority). Built by chaining
497/// [`merge_init_ctx`] twice rather than introducing a distinct 3-way merge
498/// algorithm, so the Run layer inherits exactly the same "shallow Object
499/// merge, non-Object fully replaces" rule [`merge_init_ctx`] already
500/// established for the BP/Task pair (see its doc for the full semantics).
501///
502/// - `run_override: None` is a no-op — the BP+Task merge passes through
503///   unchanged, so `POST /v1/tasks/:id/runs` with no body (or a body that
504///   omits `init_ctx_override`) preserves today's rekick behavior
505///   byte-for-byte.
506/// - `run_override: Some(_)` layers on top exactly like `task_init_ctx`
507///   layers on top of `bp_default` above: both `Object` → shallow
508///   key-wise merge with Run winning collisions; Run non-`Object` →
509///   fully replaces the BP+Task merge.
510pub fn merge_init_ctx_3layer(
511    bp_default: Option<&Value>,
512    task_init_ctx: &Value,
513    run_override: Option<&Value>,
514) -> Value {
515    let bp_task = merge_init_ctx(bp_default, task_init_ctx);
516    match run_override {
517        Some(run) => merge_init_ctx(Some(&bp_task), run),
518        None => bp_task,
519    }
520}
521
522fn derive_bp_agent_kinds(blueprint: &Blueprint) -> HashMap<String, OperatorKind> {
523    let mut out = HashMap::new();
524    if blueprint.operators.is_empty() {
525        return out;
526    }
527    for agent in &blueprint.agents {
528        let Some(op_ref) = agent.spec.get("operator_ref").and_then(|v| v.as_str()) else {
529            continue;
530        };
531        let Some(op_def) = blueprint.operators.iter().find(|o| o.name == op_ref) else {
532            continue;
533        };
534        if let Some(kind) = op_def.kind {
535            out.insert(agent.name.clone(), OperatorKind::from(kind));
536        }
537    }
538    out
539}
540
541/// Failure modes of [`TaskLaunchService::launch`].
542#[derive(Debug, Error)]
543pub enum TaskLaunchError {
544    /// `Compiler::compile` rejected the Blueprint.
545    #[error("compile: {0}")]
546    Compile(#[from] CompileError),
547    /// `Engine::attach_with_ids` failed.
548    #[error("engine: {0}")]
549    Engine(#[from] EngineError),
550    /// A `Step` inside `flow.ir`'s `eval_async` produced a dispatcher
551    /// error, or a sub-flow raised.
552    ///
553    /// GH #76 error surface: struct variant carrying structured failure detail lifted
554    /// off the eval boundary — `failed_step` / `verdict_value` come from
555    /// the [`crate::store::run::RunContext::last_failure`] breadcrumb the
556    /// dispatcher's Blocked arm writes; `partial_ctx` comes from the same
557    /// `RunContext`'s [`crate::store::run::RunContext::snapshot_partial_ctx`]
558    /// reconstruction of the step-entry trace persisted so far. All three
559    /// new fields are `Option` because dispatch may error via a path that
560    /// does not go through the Blocked arm (upstream flow-ir eval errors,
561    /// e.g. a malformed AST or an unresolved `CallExtern` — `run_ctx`
562    /// itself may be `None`, or the flow may fail before any step was
563    /// dispatched). `Display` preserves the pre-#76 `"flow eval: {message}"`
564    /// prefix byte-for-byte for backwards-compatible stringification.
565    #[error("flow eval: {message}")]
566    FlowEval {
567        /// The stringified underlying error (`EvalError::to_string()` on
568        /// the current write path). Preserves the pre-#76 message text.
569        message: String,
570        /// The `Step.ref` of the step whose Blocked outcome aborted the
571        /// flow, when the dispatcher's Blocked arm was the abort site.
572        /// `None` for abort paths that do not go through the dispatcher
573        /// (see the enum variant doc).
574        failed_step: Option<String>,
575        /// The verdict `Value` the aborting step carried
576        /// (`DispatchOutcome::Blocked(v)`'s `v`). `None` for the same
577        /// reasons as `failed_step`.
578        verdict_value: Option<Value>,
579        /// In-tree partial_ctx surfaces step-entry log (step_id →
580        /// status/binding_digest). Full value-level partial_ctx requires
581        /// upstream mlua-flow-ir support to expose `storage.snapshot()`
582        /// on error. See [`crate::store::run::RunContext::snapshot_partial_ctx`]
583        /// for the reconstructed JSON shape. `None` when `run_ctx` was
584        /// unavailable at the map_err site (e.g. `TaskLaunchService::launch`
585        /// called without a `RunContext`).
586        partial_ctx: Option<Value>,
587    },
588    /// Pre-dispatch validation failed: the launch was rejected before any
589    /// step was dispatched. Raised when the effective check_policy
590    /// (launch request > blueprint > server config) is Strict and the
591    /// launch supplied neither project_root nor work_dir — a strict task
592    /// would deterministically fail at its first submit-time file
593    /// materialize, so the launch fails fast instead.
594    #[error("pre-dispatch: {0}")]
595    PreDispatch(String),
596}
597
598/// Canonical bag of Task-level fields (`project_root` / `work_dir` /
599/// `task_metadata`) — [`TaskLaunchInput::task_input`]'s type.
600///
601/// Issue #19 ST2: replaces the ST1 `resolve_task_level_init_ctx`
602/// fold-back-into-`init_ctx` bridge (removed from
603/// `mlua-swarm-server`'s `run_flow_form`). Callers resolve these three
604/// fields once at the wire boundary — sibling body field first, falling
605/// back to the legacy shape (same three keys nested directly inside
606/// `init_ctx`) only there — and hand the result straight through here;
607/// `init_ctx` itself is no longer mutated to carry them, so it stays a
608/// pure flow-ir eval seed identical to whatever the caller sent.
609///
610/// Each field is independently optional — see
611/// [`crate::middleware::task_input::TaskInputMiddleware::new_from_fields`],
612/// which this is built for.
613///
614/// Issue #19 ST4: also `Serialize`/`Deserialize` so it can travel over the
615/// wire as `RunKickRequest.task_input_override` (`mlua-swarm-server`'s
616/// `tasks` module) and be snapshotted into `TaskRecord.task_input_spec`
617/// (JSON) for rekick to resolve back out of. Every field is
618/// `#[serde(default)]` so a caller may omit any subset (or send `{}`) and
619/// still deserialize.
620#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
621pub struct TaskInputSpec {
622    /// Task-level project root path.
623    #[serde(default)]
624    pub project_root: Option<String>,
625    /// Task-level working directory path.
626    #[serde(default)]
627    pub work_dir: Option<String>,
628    /// Task-level arbitrary metadata bag (a JSON object, or `None`).
629    #[serde(default)]
630    #[schemars(with = "Option<Value>")]
631    pub task_metadata: Option<Value>,
632}
633
634/// Input to [`TaskLaunchService::launch`].
635#[derive(Debug, Clone)]
636pub struct TaskLaunchInput {
637    /// The Blueprint to compile, link, and run.
638    pub blueprint: Blueprint,
639    /// Caller-supplied id for the Operator that owns this run.
640    pub operator_id: String,
641    /// The Operator's role for this run.
642    pub role: Role,
643    /// How long the attached session is allowed to live.
644    pub ttl: Duration,
645    /// "Runtime Global" tier of the `OperatorKind` cascade. `Some(_)` is
646    /// always an explicit request — including `Some(OperatorKind::Automate)`
647    /// — that outranks the BP-level tiers (`OperatorDef.kind` /
648    /// `Blueprint.default_operator_kind`); `None` leaves it unspecified so
649    /// those tiers / the final default decide. Under `MainAi` or
650    /// `Composite`, `MainAIMiddleware`'s `spawn_hook` before/after
651    /// callbacks become effective. See
652    /// `crate::core::ctx::collapse_operator_kind`.
653    pub operator_kind: Option<OperatorKind>,
654    /// `SeniorBridge` registry ID. `None` — no bridge; `Some(id)` —
655    /// attach a bridge previously registered via
656    /// `engine.register_senior_bridge`.
657    pub bridge_id: Option<String>,
658    /// `SpawnHook` registry ID. Same shape as above, via
659    /// `engine.register_spawn_hook`.
660    pub hook_id: Option<String>,
661    /// The one Operator this launch names — a session id (`S-<hex>`), or
662    /// any other key an embedder registered with `engine.register_operator`.
663    ///
664    /// # One input, both axes
665    ///
666    /// This used to be two fields, `operator_backend_id` and
667    /// `operator_pin`, and every caller set them from the same value:
668    ///
669    /// - **Delegate axis.** *Gone.* The value was stored on
670    ///   `LaunchEnvelope.operator_backend_id` and resolved by
671    ///   `OperatorDelegateMiddleware`, which bypassed `inner.spawn` when
672    ///   the Blueprint opted into the `operator_delegate` layer. That
673    ///   layer was removed (it read a launch-time destination and so could
674    ///   not follow a seat handover, and it carried no `system_prompt`);
675    ///   the envelope field outlives it only as the persisted session
676    ///   shape and the launch-time "is this a live session" guard key.
677    /// - **AgentSpec axis.** The binding provider attests this launch's
678    ///   manifests through that session
679    ///   ([`crate::binding::AgentBindingProvider::pinned_to_session`]), and
680    ///   the host records the same id as the Run's first `Assign`
681    ///   (`RunStore::acquire_assignee`) — which is what a dispatch resolves
682    ///   its destination from, freshly each time, so a later handover moves
683    ///   the destination without recompiling anything.
684    ///
685    /// Keeping them apart let a launch say two different things about who
686    /// it belonged to, and nothing above ever wanted to: `POST /v1/tasks`
687    /// wrote the same sid into both, and `POST /v1/tasks/:id/runs` had only
688    /// one value to write. Two axes still read it — that is a fact about
689    /// how a launch reaches an operator, not a reason for the launch to
690    /// carry the answer twice.
691    ///
692    /// The compile deliberately does **not** see this value: baking the
693    /// pinned session into `routes[agent_name]` is exactly the frozen
694    /// destination the per-dispatch lookup replaced.
695    ///
696    /// `None` (the default via [`Self::automate`]) names no operator: the
697    /// binding provider has nothing to attest through (it reports
698    /// `Unbound`). A value that is not a live session id reaches the same
699    /// outcome — with the delegate axis gone, a backend id that names no
700    /// live session no longer has a second path it can still resolve on.
701    pub operator_sid: Option<String>,
702    /// "Runtime Agent-level" tier (highest priority) of the `OperatorKind`
703    /// cascade — per-agent override, keyed by `AgentDef.name`. Empty by
704    /// default (no override for any agent). See
705    /// `crate::core::ctx::collapse_operator_kind` for the full tier list.
706    pub operator_kind_overrides: HashMap<String, OperatorKind>,
707    /// The initial `ctx` (JSON `Value`) that flow.ir's `eval_async`
708    /// starts from. Every `Step.in` `$.<path>` reference reads from
709    /// here. Issue #19 ST2: a pure flow-ir eval seed — no Task-level
710    /// field is folded into it anymore; see [`Self::task_input`].
711    pub init_ctx: Value,
712    /// Task-level canonical fields (issue #19 ST2). `Some` layers a
713    /// [`crate::middleware::task_input::TaskInputMiddleware`] (built via
714    /// [`crate::middleware::task_input::TaskInputMiddleware::new_from_fields`])
715    /// onto the spawner stack just before spawn; `None` is a no-op,
716    /// identical to today's behavior for callers with no Task-level
717    /// fields to propagate.
718    pub task_input: Option<TaskInputSpec>,
719    /// Issue #13 run_id propagation: when `Some`, every step this launch
720    /// dispatches is traced into `RunRecord.step_entries` and exposes its
721    /// `run_id` via `Ctx.meta.runtime["run_id"]` (see
722    /// `EngineDispatcher::with_run`). `None` (the default via
723    /// [`Self::automate`]) preserves the pre-existing behavior — no run
724    /// tracing.
725    pub run_ctx: Option<RunContext>,
726    /// The "launch request" tier (tier 1, highest
727    /// priority) of the `check_policy` cascade
728    /// (`launch request > blueprint > server config`).
729    /// [`TaskLaunchService::launch`]
730    /// collapses `check_policy.or(blueprint.check_policy)` exactly once and
731    /// threads the result into every spawned step's `TaskSpec.check_policy`.
732    /// `None` (the default via [`Self::automate`]) leaves this tier
733    /// unspecified so the Blueprint tier / server-wide default decide —
734    /// backward-compat with every pre-cascade caller.
735    ///
736    /// [`TaskLaunchService::launch`] also collapses this same cascade one
737    /// step further
738    /// (adding the server-wide `EngineCfg.check_policy` tier) into a
739    /// pre-dispatch guard: when the resulting effective policy is
740    /// [`CheckPolicy::Strict`] and neither [`Self::task_input`]'s
741    /// `project_root` nor `work_dir` is set, the launch is rejected with
742    /// `TaskLaunchError::PreDispatch` before any step is dispatched — a
743    /// strict task with no resolvable root would deterministically fail
744    /// at its first submit-time file materialize anyway. Setting this
745    /// field to `Some(CheckPolicy::Warn)` on the launch-request tier is
746    /// the escape hatch: it outranks a Blueprint- or server-declared
747    /// Strict and lets the guard pass.
748    pub check_policy: Option<CheckPolicy>,
749}
750
751impl TaskLaunchInput {
752    /// Helper for existing callers on the default path — no hooks and no
753    /// per-agent `OperatorKind` overrides. Leaves the "Runtime Global" tier
754    /// unspecified (`None`), so the BP-level tiers / final default
755    /// (`OperatorKind::Automate`) decide — this preserves today's
756    /// behaviour for every existing caller without silently forcing
757    /// `Automate` as an explicit override that would outrank a BP-declared
758    /// `MainAi`/`Composite` kind. `run_ctx` and `task_input` both default
759    /// to `None` (no run tracing, no Task-level fields); construct the
760    /// struct literal directly to set either.
761    pub fn automate(
762        blueprint: Blueprint,
763        operator_id: impl Into<String>,
764        role: Role,
765        ttl: Duration,
766        init_ctx: Value,
767    ) -> Self {
768        Self {
769            blueprint,
770            operator_id: operator_id.into(),
771            role,
772            ttl,
773            operator_kind: None,
774            bridge_id: None,
775            hook_id: None,
776            operator_sid: None,
777            operator_kind_overrides: HashMap::new(),
778            init_ctx,
779            task_input: None,
780            run_ctx: None,
781            check_policy: None,
782        }
783    }
784}
785
786/// Result of a successful [`TaskLaunchService::launch`] call.
787#[derive(Debug, Clone)]
788pub struct TaskLaunchOutput {
789    /// The capability token for the attached session.
790    pub token: CapToken,
791    /// The final `ctx` after the flow ran — every `Step.out` has
792    /// been written. Application-layer callers pull the outcome out
793    /// of this `Value` and fold it into a domain status.
794    pub final_ctx: Value,
795}
796
797/// Domain service that compiles, links, and runs a Blueprint's flow to
798/// completion through the [`Engine`]. See the module doc for the full
799/// responsibility list.
800pub struct TaskLaunchService {
801    engine: Engine,
802    compiler: Compiler,
803    /// `call_extern` registry threaded into flow eval. Defaults to
804    /// [`NoExterns`] (= every `call_extern` in a Blueprint raises
805    /// `ExternError`); hosts opt in via [`Self::with_externs`] with an
806    /// `ExternMap` of pure value-shape functions.
807    externs: Arc<dyn Externs + Send + Sync>,
808    /// Optional execution-environment binding implementation. When present,
809    /// fresh Run snapshots require a complete, Core-validated receipt set.
810    binding_provider: Option<Arc<dyn AgentBindingProvider>>,
811    /// Whether fresh Blueprint declarations may use the deprecated
812    /// `profile.worker_binding` Runner fallback.
813    legacy_worker_binding_policy: LegacyWorkerBindingPolicy,
814}
815
816impl TaskLaunchService {
817    /// Build a service bound to one `Engine` and one `Compiler`.
818    pub fn new(engine: Engine, compiler: Compiler) -> Self {
819        Self {
820            engine,
821            compiler,
822            externs: Arc::new(NoExterns),
823            binding_provider: None,
824            legacy_worker_binding_policy: LegacyWorkerBindingPolicy::default(),
825        }
826    }
827
828    /// Replace the `call_extern` registry (builder style). Entries MUST be
829    /// pure functions — no side effects, no flow control; effectful work
830    /// belongs to `Step` / agents, not externs (flow-ir canonical contract).
831    pub fn with_externs(mut self, externs: Arc<dyn Externs + Send + Sync>) -> Self {
832        self.externs = externs;
833        self
834    }
835
836    /// Inject the execution-environment binding provider. Platform plugins
837    /// and Operator/MainAI implementations use this same interface; Core
838    /// retains receipt validation and digest ownership.
839    pub fn with_binding_provider(mut self, provider: Arc<dyn AgentBindingProvider>) -> Self {
840        self.binding_provider = Some(provider);
841        self
842    }
843
844    /// Configure the migration gate for deprecated `profile.worker_binding`.
845    pub fn with_legacy_worker_binding_policy(mut self, policy: LegacyWorkerBindingPolicy) -> Self {
846        self.legacy_worker_binding_policy = policy;
847        self
848    }
849
850    /// The bound `Engine`.
851    pub fn engine(&self) -> &Engine {
852        &self.engine
853    }
854
855    /// The bound `Compiler`.
856    pub fn compiler(&self) -> &Compiler {
857        &self.compiler
858    }
859
860    /// Run the Blueprint's flow to completion and return the final
861    /// `ctx`.
862    ///
863    /// Failure paths:
864    ///
865    /// - `compiler.compile` failure → `TaskLaunchError::Compile`.
866    /// - `engine.attach` failure → `TaskLaunchError::Engine`.
867    /// - A `Step` inside `flow eval` producing a dispatcher error, or
868    ///   a sub-flow raising, → `TaskLaunchError::FlowEval`. There is
869    ///   no silent partial-success completion; failures always
870    ///   propagate.
871    pub async fn launch(
872        &self,
873        mut input: TaskLaunchInput,
874    ) -> Result<TaskLaunchOutput, TaskLaunchError> {
875        // After the stateless-executor refactor, the
876        // caller (Service) does compile + link +
877        // `EngineDispatcher::with_spawner` itself; the engine no longer
878        // holds any global spawner state to touch. The link path (base
879        // `SpawnerAdapter` +
880        // `LayerRegistry` resolution + `SpawnerStack` wrapping) is
881        // concentrated inside `service::linker::link` — Service
882        // scatter is intentionally prevented.
883        // A pinned launch attests through the pinned session instead of the
884        // logical role's current holder, when the injected provider knows
885        // how to do that (`pinned_to_session` defaults to `None`, so an
886        // unpinned launch — and any provider without a session concept —
887        // keeps using `self.binding_provider` unchanged).
888        let pinned_binding_provider: Option<Arc<dyn AgentBindingProvider>> = input
889            .operator_sid
890            .as_deref()
891            .and_then(|pin| self.binding_provider.as_ref()?.pinned_to_session(pin));
892        let binding_provider = pinned_binding_provider
893            .as_deref()
894            .or(self.binding_provider.as_deref());
895        let (bound_agents, snapshot_origin) = load_or_resolve_bound_agents(
896            &input.blueprint,
897            input.run_ctx.as_ref(),
898            binding_provider,
899            self.legacy_worker_binding_policy,
900        )
901        .await?;
902        let binding_digests: HashMap<String, crate::blueprint::BindingDigest> = bound_agents
903            .iter()
904            .map(|bound| (bound.agent.name.clone(), bound.binding_digest.clone()))
905            .collect();
906        if let Some(run_ctx) = input.run_ctx.take() {
907            // [Crux D2-a] A `launch`-origin Run attaches the binding digests to
908            // the RunContext so replay keys distinguish the same step/input run
909            // under different bindings (the property the strict-binding series
910            // introduced). A `resume_backfill`-origin Run does NOT: its
911            // pre-upgrade replay log was hashed WITHOUT binding digests, so
912            // leaving `RunContext.binding_digests` empty makes the engine's
913            // `input_hash` fall back to the legacy form (`binding_digests.get`
914            // → None, see `Engine::dispatch_attempt_with_run_ctx`) and the old
915            // log hits verbatim. This is per-Run, keyed on the snapshot's
916            // origin — it does NOT disable digest keying for launch Runs.
917            input.run_ctx = Some(match snapshot_origin {
918                SnapshotOrigin::Launch => run_ctx.with_binding_digests(binding_digests.clone()),
919                SnapshotOrigin::ResumeBackfill => run_ctx,
920            });
921        }
922        input.blueprint = materialize_bound_blueprint(&input.blueprint, &bound_agents);
923        let compiled = self
924            .compiler
925            .compile_bound(&input.blueprint, &bound_agents)?;
926        // GH #50 (Subtask 2 follow-up): merge this Blueprint's compiled
927        // `AgentDef.verdict` contracts into the engine's runtime registry —
928        // see `Engine::register_verdict_contracts`'s doc for the additive
929        // (last-write-wins per agent name) semantics. This is the ONLY
930        // production call site; every other consumer
931        // (`Engine::verdict_contract_for_task`, and through it
932        // `mlua-swarm-server`'s `worker_submit` / `worker_artifact`
933        // submit-time gate) reads from what this line populates.
934        self.engine
935            .register_verdict_contracts(compiled.router.verdict_contracts.clone());
936        let spawner = linker::link(
937            compiled.router.clone(),
938            &input.blueprint.spawner_hints.layers,
939            &self.engine,
940        );
941        // GH #20 Contract C: materialize an `AgentContextView` exactly
942        // once per spawn, innermost relative to every other layer below
943        // (alias / worker-binding / task-input all insert `ctx.meta.runtime`
944        // keys this layer must observe, so it is added FIRST — later
945        // `.layer()` calls become outer, see `middleware::SpawnerStack`).
946        // Unconditional (always layered): every Blueprint gets this layer
947        // even when it declares no agent-context supply tiers at all
948        // (`derive_agent_ctx` / `derive_context_policies` both return
949        // empty state then, matching the pre-#21 `AgentContextMiddleware`
950        // `Default` behavior byte-for-byte). GH #21 Phase 1: the
951        // receptacle named in the #20 comment above is now wired —
952        // `Blueprint.default_agent_ctx` / `default_context_policy` and
953        // `AgentMeta.ctx` / `context_policy` feed this layer's merge +
954        // policy resolution (see `middleware::agent_context`'s module doc
955        // for the full narrative).
956        let (agent_ctx_global, agent_ctx_per_agent) = derive_agent_ctx(&input.blueprint);
957        let (context_policy_default, context_policy_per_agent) =
958            derive_context_policies(&input.blueprint);
959        let spawner = SpawnerStack::new(spawner)
960            .layer(AgentContextMiddleware::new(
961                agent_ctx_global,
962                agent_ctx_per_agent,
963                context_policy_default,
964                context_policy_per_agent,
965            ))
966            .build();
967        // When `Blueprint.metadata.project_name_alias` is Some, layer a
968        // `ProjectNameAliasMiddleware` on top of the stack that injects the
969        // alias into `Ctx.meta.runtime.project_name_alias` just before spawn.
970        // Downstream operators (for example, the server crate's
971        // `Operator.execute`) read `ctx.meta.runtime.get("project_name_alias")`
972        // and expand it into the Spawn directive prompt body.
973        let spawner = if let Some(alias) = input.blueprint.metadata.project_name_alias.as_deref() {
974            SpawnerStack::new(spawner)
975                .layer(ProjectNameAliasMiddleware::new(alias))
976                .build()
977        } else {
978            spawner
979        };
980        // Layer the Blueprint-baked worker bindings (same ctx.meta.runtime
981        // inject shape as the alias layer above) — see
982        // `derive_worker_bindings`. This used to be how the delegate axis
983        // resolved per-agent variants; that axis is gone and nothing in
984        // this repository reads the key it writes. What keeps the layer
985        // wired is set out in `WorkerBindingMiddleware`'s module doc.
986        let worker_bindings = worker_bindings_from_bound_agents(&bound_agents);
987        let spawner = if worker_bindings.is_empty() {
988            spawner
989        } else {
990            SpawnerStack::new(spawner)
991                .layer(WorkerBindingMiddleware::new(worker_bindings))
992                .build()
993        };
994        // GH #34: Blueprint-declared after-run audit hooks — same
995        // conditional-layering shape as the alias / worker-binding blocks
996        // above. Empty `Blueprint.audits` (every pre-#34 Blueprint) means
997        // no layer at all (invariant #4: byte-identical behavior). The
998        // router handle handed to `AfterRunAuditMiddleware` is
999        // `compiled.router` — the raw name→adapter table `Compiler::compile`
1000        // built (NOT this progressively-wrapped `spawner`) — so an audit
1001        // agent's own dispatch never re-enters this same layer (see
1002        // `AfterRunAuditMiddleware`'s module doc, Recursion guard section).
1003        let audit_defs = derive_audits(&input.blueprint);
1004        let spawner = if audit_defs.is_empty() {
1005            spawner
1006        } else {
1007            SpawnerStack::new(spawner)
1008                .layer(AfterRunAuditMiddleware::new(
1009                    audit_defs,
1010                    compiled.router.clone(),
1011                ))
1012                .build()
1013        };
1014
1015        // Task-level execution context (`project_root` / `work_dir` /
1016        // `task_metadata`) — same conditional-layering shape as the alias /
1017        // worker-binding blocks above. Issue #19 ST2: read directly off
1018        // `input.task_input` (already resolved by the caller) instead of
1019        // extracting it back out of `input.init_ctx` — `init_ctx` is a pure
1020        // flow-ir eval seed now, never folded with these keys.
1021        let spawner = match input.task_input.as_ref().and_then(|spec| {
1022            TaskInputMiddleware::new_from_fields(
1023                spec.project_root.clone(),
1024                spec.work_dir.clone(),
1025                spec.task_metadata.clone(),
1026            )
1027        }) {
1028            Some(task_input) => SpawnerStack::new(spawner).layer(task_input).build(),
1029            None => spawner,
1030        };
1031
1032        // "BP Agent-level" (`OperatorDef.kind` via `operator_ref`) + "BP
1033        // Global" (`Blueprint.default_operator_kind`) tiers of the
1034        // `OperatorKind` cascade, baked here (the only point that has both
1035        // the resolved Blueprint and the launch-time overrides in scope).
1036        let bp_agent_kinds = derive_bp_agent_kinds(&input.blueprint);
1037        let bp_global_kind = input
1038            .blueprint
1039            .default_operator_kind
1040            .map(OperatorKind::from);
1041
1042        // The envelope still records the launch's operator id. Nothing
1043        // dispatches through it any more: the delegate axis that used to
1044        // read it back out via `Engine::resolve_operator_info` was removed
1045        // precisely because it read this launch-time value instead of
1046        // `Run.current`, and so could not follow a seat handover (the gap
1047        // tracked as issue `545411ab`). What the field still carries is the
1048        // persisted session shape and the launch-time guard key — the
1049        // AgentSpec axis reaches its destination through the Run's seat,
1050        // not through here.
1051        let token = self
1052            .engine
1053            .attach_with_ids(
1054                input.operator_id,
1055                input.role,
1056                input.ttl,
1057                input.operator_kind,
1058                input.bridge_id,
1059                input.hook_id,
1060                input.operator_sid,
1061                input.operator_kind_overrides,
1062                bp_agent_kinds,
1063                bp_global_kind,
1064            )
1065            .await?;
1066        // Collapse the `check_policy` cascade EXACTLY ONCE
1067        // here: `launch request > blueprint > server config` (highest to
1068        // lowest priority). `input.check_policy` is the launch-request tier;
1069        // `input.blueprint.check_policy` is the Blueprint tier; a `None`
1070        // result leaves the engine's submit-time sink to fall back to the
1071        // server-wide `EngineCfg.check_policy` (tier 3) on its own — the
1072        // engine's existing `task_policy.unwrap_or(server_policy)` resolution
1073        // is deliberately NOT duplicated here (no double resolution). The
1074        // resolved value is threaded (via `with_check_policy`) into EVERY
1075        // spawned step's `TaskSpec`, not just the first.
1076        let resolved_check_policy = input.check_policy.or(input.blueprint.check_policy);
1077        // Pre-dispatch guard: collapse the same cascade one step further
1078        // (adding the server tier, `EngineCfg.check_policy`, via
1079        // `self.engine.cfg()`) into a SEPARATE local used only for this
1080        // check — `resolved_check_policy` above (the Option stamped onto
1081        // every dispatched step's `TaskSpec`) is left untouched, so the
1082        // "TaskSpec = None -> engine falls back to server default at the
1083        // submit-time sink" contract (cascade test case 4) keeps holding.
1084        // When the effective policy is Strict and the launch supplied
1085        // neither `project_root` nor `work_dir`, a strict task would
1086        // deterministically fail at its first submit-time file
1087        // materialize — fail the launch fast instead of dispatching a
1088        // step that can only ever hit that wall. `check_policy: "warn"` on
1089        // the launch-request tier is the escape hatch (it wins the
1090        // cascade before this fallback ever applies).
1091        let effective_check_policy =
1092            resolved_check_policy.unwrap_or(self.engine.cfg().check_policy);
1093        if effective_check_policy == CheckPolicy::Strict {
1094            let roots_missing = input
1095                .task_input
1096                .as_ref()
1097                .map(|t| t.project_root.is_none() && t.work_dir.is_none())
1098                .unwrap_or(true);
1099            if roots_missing {
1100                return Err(TaskLaunchError::PreDispatch(
1101                    "check_policy=strict requires project_root or work_dir, but the launch \
1102                     supplied neither"
1103                        .to_string(),
1104                ));
1105            }
1106        }
1107        let dispatcher =
1108            EngineDispatcher::with_spawner(self.engine.clone(), token.clone(), spawner);
1109        let dispatcher = dispatcher.with_check_policy(resolved_check_policy);
1110        // GH #76 error surface: clone the `RunContext` (cheap — every field is either
1111        // `Arc<...>` or a scalar) so the eval-boundary `map_err` closure
1112        // can still read `last_failure` / call `snapshot_partial_ctx()`
1113        // after the original is moved into the dispatcher. Sibling to the
1114        // existing `token.clone()` pattern above — the `map_err`
1115        // structured-error lift is now a co-owner of the RunContext state
1116        // the dispatcher writes to.
1117        let map_err_run_ctx = input.run_ctx.clone();
1118        let dispatcher = match input.run_ctx {
1119            Some(run_ctx) => dispatcher.with_run(run_ctx),
1120            None => dispatcher,
1121        };
1122        // GH #21 Phase 2: attach the Step tier's named `MetaDef` pool.
1123        // Unconditional — an empty map (every pre-#21-Phase-2 Blueprint)
1124        // is a no-op, matching `EngineDispatcher::with_spawner`'s default.
1125        let dispatcher = dispatcher.with_step_metas(derive_step_metas(&input.blueprint));
1126        let dispatcher = dispatcher.with_binding_digests(binding_digests);
1127        // GH #23: attach the `StepNaming` table `Compiler::compile` already
1128        // built once for this Blueprint (the sole construction site — see
1129        // `core::step_naming::StepNaming::from_blueprint`'s doc).
1130        // Unconditional — every compile produces one, undeclared Blueprints
1131        // included (canonical falls back to `Step.ref` byte-for-byte).
1132        let dispatcher = dispatcher.with_step_naming(compiled.step_naming.clone());
1133        // GH #27 (follow-up to #23): attach the `ProjectionPlacement`
1134        // resolver `Compiler::compile` already built once for this
1135        // Blueprint (the sole construction site — see
1136        // `core::projection_placement::ProjectionPlacement::from_spec`'s
1137        // doc). Unconditional — every compile produces one, undeclared
1138        // Blueprints included (resolves to `ProjectionPlacement::default()`).
1139        let dispatcher =
1140            dispatcher.with_projection_placement(compiled.projection_placement.clone());
1141        // Issue #19 ST3: BP default + Task init_ctx → merged init_ctx (the
1142        // 2-layer slice of the eventual 4-layer cascade; Run override is
1143        // ST4 carry). `input.blueprint.default_init_ctx` is `None` for
1144        // every pre-#19 Blueprint, so `merge_init_ctx` is a no-op then and
1145        // this preserves today's behavior byte-for-byte.
1146        let merged_init_ctx =
1147            merge_init_ctx(input.blueprint.default_init_ctx.as_ref(), &input.init_ctx);
1148        let eval_result = mlua_flow_ir::eval_async_externs(
1149            &input.blueprint.flow,
1150            merged_init_ctx,
1151            &dispatcher,
1152            &*self.externs,
1153        )
1154        .await;
1155        let final_ctx = match eval_result {
1156            Ok(v) => v,
1157            Err(e) => {
1158                // GH #76 error surface: lift the eval error into the structured
1159                // `TaskLaunchError::FlowEval { .. }` variant. `message`
1160                // preserves the pre-#76 stringified error byte-for-byte
1161                // (the `Display` impl still emits `"flow eval: {message}"`,
1162                // so callers that only match on the stringified error keep
1163                // working). `failed_step` + `verdict_value` are lifted off
1164                // the `RunContext.last_failure` breadcrumb the dispatcher's
1165                // Blocked arm wrote (see `EngineDispatcher::dispatch` for
1166                // the write side); `partial_ctx` is reconstructed from the
1167                // step-entry trace persisted so far via
1168                // `RunContext::snapshot_partial_ctx` — see that method's
1169                // doc for the "metadata-level, not value-level" caveat
1170                // and the upstream mlua-flow-ir carry.
1171                //
1172                // Every new field is `None` when `run_ctx` was not
1173                // supplied by the caller (a legacy `TaskLaunchService::launch`
1174                // call site with no run tracing), or when the abort path
1175                // did not go through the dispatcher's Blocked arm (e.g.
1176                // flow-ir raised `EvalError` before dispatch).
1177                let (failed_step, verdict_value) = match &map_err_run_ctx {
1178                    Some(rc) => {
1179                        let slot = rc.last_failure.lock().ok().and_then(|g| g.clone());
1180                        match slot {
1181                            Some(lf) => (
1182                                lf.step_ref.clone().or_else(|| Some(lf.step_id.to_string())),
1183                                Some(lf.verdict_value.clone()),
1184                            ),
1185                            None => (None, None),
1186                        }
1187                    }
1188                    None => (None, None),
1189                };
1190                let partial_ctx = match &map_err_run_ctx {
1191                    Some(rc) => Some(rc.snapshot_partial_ctx().await),
1192                    None => None,
1193                };
1194                return Err(TaskLaunchError::FlowEval {
1195                    message: e.to_string(),
1196                    failed_step,
1197                    verdict_value,
1198                    partial_ctx,
1199                });
1200            }
1201        };
1202        Ok(TaskLaunchOutput { token, final_ctx })
1203    }
1204}
1205
1206// ──────────────────────────────────────────────────────────────────────────
1207// UT
1208// ──────────────────────────────────────────────────────────────────────────
1209
1210#[cfg(test)]
1211mod tests {
1212    use super::*;
1213    use crate::blueprint::compiler::{RustFnInProcessSpawnerFactory, SpawnerRegistry};
1214    use crate::blueprint::{
1215        current_schema_version, resolve_runner, AgentDef, AgentKind, AgentMeta, AgentProfile,
1216        BlueprintMetadata, CompilerHints, CompilerStrategy, MetaDef, Runner,
1217    };
1218    use crate::core::config::EngineCfg;
1219    use crate::worker::adapter::{WorkerError, WorkerResult};
1220    use mlua_flow_ir::{Expr, JoinMode, Node as FlowNode};
1221    use serde_json::json;
1222    use std::sync::Arc;
1223
1224    fn path(s: &str) -> Expr {
1225        Expr::Path {
1226            at: s.parse().expect("literal test path"),
1227        }
1228    }
1229    fn step(ref_: &str, in_: Expr, out: Expr) -> FlowNode {
1230        FlowNode::Step {
1231            ref_: ref_.to_string(),
1232            in_,
1233            out,
1234        }
1235    }
1236
1237    fn agent(name: &str, fn_id: &str) -> AgentDef {
1238        AgentDef {
1239            name: name.to_string(),
1240            kind: AgentKind::RustFn,
1241            spec: json!({ "fn_id": fn_id }),
1242            profile: None,
1243            meta: Some(AgentMeta::default()),
1244            runner: None,
1245            runner_ref: None,
1246            verdict: None,
1247            lints: None,
1248        }
1249    }
1250
1251    fn build_service(factory: RustFnInProcessSpawnerFactory) -> TaskLaunchService {
1252        let engine = Engine::new(EngineCfg::default());
1253        let mut reg = SpawnerRegistry::new();
1254        reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(factory));
1255        let compiler = Compiler::new(reg);
1256        TaskLaunchService::new(engine, compiler)
1257    }
1258
1259    /// Same as [`build_service`] but with a caller-supplied [`EngineCfg`] —
1260    /// used by the pre-dispatch guard's server-tier test (T4), which needs
1261    /// a non-default `EngineCfg.check_policy`.
1262    fn build_service_with_cfg(
1263        factory: RustFnInProcessSpawnerFactory,
1264        cfg: EngineCfg,
1265    ) -> TaskLaunchService {
1266        let engine = Engine::new(cfg);
1267        let mut reg = SpawnerRegistry::new();
1268        reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(factory));
1269        let compiler = Compiler::new(reg);
1270        TaskLaunchService::new(engine, compiler)
1271    }
1272
1273    fn bp(flow: FlowNode, agents: Vec<AgentDef>) -> Blueprint {
1274        Blueprint {
1275            schema_version: current_schema_version(),
1276            id: "ut".into(),
1277            flow,
1278            agents,
1279            operators: vec![],
1280            metas: vec![],
1281            hints: CompilerHints::default(),
1282            strategy: CompilerStrategy::default(),
1283            metadata: BlueprintMetadata::default(),
1284            spawner_hints: Default::default(),
1285            default_agent_kind: AgentKind::Operator,
1286            default_operator_kind: None,
1287            default_init_ctx: None,
1288            default_agent_ctx: None,
1289            default_context_policy: None,
1290            projection_placement: None,
1291            audits: vec![],
1292            degradation_policy: None,
1293            runners: vec![],
1294            default_runner: None,
1295            subprocesses: vec![],
1296            check_policy: None,
1297            blueprint_ref_includes: Vec::new(),
1298        }
1299    }
1300
1301    fn launch_input(blueprint: Blueprint, init_ctx: Value) -> TaskLaunchInput {
1302        TaskLaunchInput::automate(
1303            blueprint,
1304            "ut-op",
1305            Role::Operator,
1306            Duration::from_secs(30),
1307            init_ctx,
1308        )
1309    }
1310
1311    // ──────────────────────────────────────────────────────────────
1312    // GH #34: `derive_audits` + the conditional `AfterRunAuditMiddleware`
1313    // `.layer(...)` wiring in `TaskLaunchService::launch`
1314    // ──────────────────────────────────────────────────────────────
1315
1316    #[test]
1317    fn derive_audits_empty_by_default() {
1318        let blueprint = bp(
1319            step("echo", path("$.input"), path("$.out")),
1320            vec![agent("echo", "echo")],
1321        );
1322        assert!(
1323            derive_audits(&blueprint).is_empty(),
1324            "audits_absent_no_layer: an undeclared audits Vec must stay empty"
1325        );
1326    }
1327
1328    #[test]
1329    fn derive_audits_returns_blueprint_audits_verbatim() {
1330        let mut blueprint = bp(
1331            step("echo", path("$.input"), path("$.out")),
1332            vec![agent("echo", "echo")],
1333        );
1334        blueprint.audits = vec![crate::blueprint::AuditDef {
1335            agent: "auditor".to_string(),
1336            steps: None,
1337            mode: crate::blueprint::AuditMode::Async,
1338        }];
1339        let got = derive_audits(&blueprint);
1340        assert_eq!(got.len(), 1);
1341        assert_eq!(got[0].agent, "auditor");
1342    }
1343
1344    #[tokio::test]
1345    async fn launch_appends_audit_artifact_when_audits_declared() {
1346        use crate::blueprint::{AuditDef, AuditMode};
1347
1348        let factory = RustFnInProcessSpawnerFactory::new()
1349            .register_fn("echo", |inv| async move {
1350                Ok(WorkerResult {
1351                    value: json!({ "echoed": inv.prompt }),
1352                    ok: true,
1353                    stats: None,
1354                })
1355            })
1356            .register_fn("audit-fn", |_inv| async move {
1357                Ok(WorkerResult {
1358                    value: json!({ "finding": "clean" }),
1359                    ok: true,
1360                    stats: None,
1361                })
1362            });
1363        let svc = build_service(factory);
1364        let mut blueprint = bp(
1365            step("echo", path("$.input"), path("$.out")),
1366            vec![agent("echo", "echo"), agent("auditor", "audit-fn")],
1367        );
1368        blueprint.audits = vec![AuditDef {
1369            agent: "auditor".to_string(),
1370            steps: None,
1371            mode: AuditMode::Sync,
1372        }];
1373        let out = svc
1374            .launch(launch_input(blueprint, json!({ "input": "hi" })))
1375            .await
1376            .expect("launch ok — audits must never alter the audited step's outcome");
1377        assert_eq!(out.final_ctx["out"]["echoed"], "hi");
1378
1379        let audited_task_id = svc
1380            .engine()
1381            .with_state("test.find_audited_task", |s| {
1382                s.tasks
1383                    .iter()
1384                    .find(|(_, t)| t.spec.agent == "echo")
1385                    .map(|(id, _)| id.clone())
1386            })
1387            .await
1388            .expect("with_state")
1389            .expect("the echo task must exist");
1390        let tail = svc.engine().output_tail(&audited_task_id, 1).await;
1391        let found = tail.iter().any(|ev| {
1392            matches!(
1393                ev,
1394                crate::worker::output::OutputEvent::Artifact { name, .. } if name == "audit:echo"
1395            )
1396        });
1397        assert!(
1398            found,
1399            "launch() must wire AfterRunAuditMiddleware end-to-end when Blueprint.audits is declared"
1400        );
1401    }
1402
1403    #[tokio::test]
1404    async fn launch_single_step_writes_out_path() {
1405        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
1406            Ok(WorkerResult {
1407                value: json!({ "echoed": inv.prompt }),
1408                ok: true,
1409                stats: None,
1410            })
1411        });
1412        let svc = build_service(factory);
1413        let blueprint = bp(
1414            step("echo", path("$.input"), path("$.out")),
1415            vec![agent("echo", "echo")],
1416        );
1417        let out = svc
1418            .launch(launch_input(blueprint, json!({ "input": "hi" })))
1419            .await
1420            .expect("launch ok");
1421        assert_eq!(out.final_ctx["out"]["echoed"], "hi");
1422    }
1423
1424    // ──────────────────────────────────────────────────────────────
1425    // check_policy cascade (launch > blueprint > server)
1426    // T2 (cascade 4-case) / T3 (end-to-end strict) / T4 (backward compat)
1427    // ──────────────────────────────────────────────────────────────
1428
1429    /// Launch a single-echo Blueprint with the given launch- and
1430    /// Blueprint-tier `check_policy`, then read back the `check_policy` that
1431    /// the dispatcher stamped onto the dispatched step's `TaskSpec`. The
1432    /// launch may complete (Silent / Warn / None → fail-open) — the in-process
1433    /// RustFn worker fire-and-forgets its submit — so the task and its
1434    /// resolved spec exist regardless of the launch outcome.
1435    ///
1436    /// `task_input` carries a `work_dir` unconditionally (a dummy path, not
1437    /// resolved on disk) so the pre-dispatch guard (a strict effective
1438    /// policy with no roots supplied rejects before dispatch) never fires
1439    /// here — this helper's whole point is "reach dispatch and read back
1440    /// the stamp", so every case (including the two whose
1441    /// `bp_policy`/`launch_policy` alone resolve to Strict) must dispatch
1442    /// uniformly. The guard's own rejection behavior is proven separately
1443    /// (T3/T4 and `strict_blueprint_without_roots_is_rejected_pre_dispatch`).
1444    async fn dispatched_check_policy(
1445        launch_policy: Option<CheckPolicy>,
1446        bp_policy: Option<CheckPolicy>,
1447    ) -> Option<CheckPolicy> {
1448        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
1449            Ok(WorkerResult {
1450                value: json!({ "echoed": inv.prompt }),
1451                ok: true,
1452                stats: None,
1453            })
1454        });
1455        let svc = build_service(factory);
1456        let mut blueprint = bp(
1457            step("echo", path("$.input"), path("$.out")),
1458            vec![agent("echo", "echo")],
1459        );
1460        blueprint.check_policy = bp_policy;
1461        let mut input = launch_input(blueprint, json!({ "input": "hi" }));
1462        input.check_policy = launch_policy;
1463        input.task_input = Some(TaskInputSpec {
1464            project_root: None,
1465            work_dir: Some("/dispatched-check-policy-test-root".to_string()),
1466            task_metadata: None,
1467        });
1468        let _ = svc.launch(input).await;
1469        svc.engine()
1470            .with_state("test.read_dispatched_check_policy", |s| {
1471                s.tasks
1472                    .values()
1473                    .find(|t| t.spec.agent == "echo")
1474                    .and_then(|t| t.spec.check_policy)
1475            })
1476            .await
1477            .expect("with_state")
1478    }
1479
1480    /// T2 case 1: launch `Some(Silent)` + BP `Some(Strict)` → TaskSpec
1481    /// `Some(Silent)` (the launch-request tier outranks the Blueprint tier).
1482    #[tokio::test]
1483    async fn cascade_launch_tier_wins_over_blueprint_tier() {
1484        assert_eq!(
1485            dispatched_check_policy(Some(CheckPolicy::Silent), Some(CheckPolicy::Strict)).await,
1486            Some(CheckPolicy::Silent),
1487        );
1488    }
1489
1490    /// T2 case 2: launch `None` + BP `Some(Strict)` → TaskSpec `Some(Strict)`
1491    /// (the Blueprint tier takes effect when the launch tier is unset).
1492    #[tokio::test]
1493    async fn cascade_blueprint_tier_used_when_launch_absent() {
1494        assert_eq!(
1495            dispatched_check_policy(None, Some(CheckPolicy::Strict)).await,
1496            Some(CheckPolicy::Strict),
1497        );
1498    }
1499
1500    /// T2 case 3: launch `Some(Strict)` + BP `None` → TaskSpec `Some(Strict)`
1501    /// (the launch tier alone resolves when the Blueprint tier is unset).
1502    #[tokio::test]
1503    async fn cascade_launch_tier_alone_when_blueprint_absent() {
1504        assert_eq!(
1505            dispatched_check_policy(Some(CheckPolicy::Strict), None).await,
1506            Some(CheckPolicy::Strict),
1507        );
1508    }
1509
1510    /// T2 case 4: launch `None` + BP `None` → TaskSpec `None`. NOT omitted as
1511    /// "trivial": this is the backward-compat proof — the server-fallback
1512    /// path (`EngineCfg.check_policy` decides at the submit-time sink) is
1513    /// preserved byte-for-byte because the carrier stays `None`.
1514    #[tokio::test]
1515    async fn cascade_both_none_preserves_server_fallback() {
1516        assert_eq!(dispatched_check_policy(None, None).await, None);
1517    }
1518
1519    /// Repurposed 2026-07-16 for the pre-dispatch guard's new contract
1520    /// (the launch-time validation stage of the check_policy cascade
1521    /// work). This test used
1522    /// to prove a strict + no-roots launch dispatched a step that then hit
1523    /// `EngineError::CheckPolicyStrict` at submit time — exactly the path
1524    /// the pre-dispatch guard now forecloses (a strict launch with no
1525    /// resolvable root is rejected BEFORE dispatch instead, see
1526    /// [`TaskLaunchService::launch`]'s guard). The two sub-assertions this
1527    /// test used to make are independently covered elsewhere: the
1528    /// cascade-resolved Strict reaching the dispatched `TaskSpec` is
1529    /// covered by the `cascade_*` tests above; the submit-time sink
1530    /// surfacing `CheckPolicyStrict` on an unresolved root is covered by
1531    /// `crate::core::engine::tests::submit_output_final_check_policy_strict_surfaces_error_when_root_unresolved`
1532    /// (seeds the task directly at the engine layer, bypassing `launch`).
1533    /// This test now asserts the NEW contract directly.
1534    #[tokio::test]
1535    async fn strict_blueprint_without_roots_is_rejected_pre_dispatch() {
1536        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
1537            Ok(WorkerResult {
1538                value: json!({ "echoed": inv.prompt }),
1539                ok: true,
1540                stats: None,
1541            })
1542        });
1543        let svc = build_service(factory);
1544        let mut blueprint = bp(
1545            step("echo", path("$.input"), path("$.out")),
1546            vec![agent("echo", "echo")],
1547        );
1548        blueprint.check_policy = Some(CheckPolicy::Strict);
1549        // No task_input → no work_dir/project_root ever resolves.
1550        let err = svc
1551            .launch(launch_input(blueprint, json!({ "input": "hi" })))
1552            .await
1553            .expect_err("strict check_policy + no roots must be rejected before dispatch");
1554        match err {
1555            TaskLaunchError::PreDispatch(message) => {
1556                assert!(
1557                    message.contains("strict"),
1558                    "message must identify the strict-requires-roots condition: {message}"
1559                );
1560            }
1561            other => panic!("expected TaskLaunchError::PreDispatch, got {other:?}"),
1562        }
1563
1564        // No step was ever dispatched — the guard fires after
1565        // `engine.attach_with_ids` (the token mint) but before the
1566        // dispatcher is ever built / `eval_async_externs` runs.
1567        let dispatched = svc
1568            .engine()
1569            .with_state("test.no_echo_task_dispatched", |s| {
1570                s.tasks.values().any(|t| t.spec.agent == "echo")
1571            })
1572            .await
1573            .expect("with_state");
1574        assert!(
1575            !dispatched,
1576            "the pre-dispatch guard must reject before any step is dispatched"
1577        );
1578    }
1579
1580    /// T4 (cascade backward-compat): backward compat — with NO check_policy
1581    /// anywhere (BP tier + launch tier both `None`), the launch resolves to
1582    /// the server default (Warn) and completes fail-open exactly as before
1583    /// this change (the warn-mode materialize skip never turns a
1584    /// successful submit into a failure).
1585    ///
1586    /// This is ALSO the pre-dispatch guard's backward-compat case (T5):
1587    /// `task_input` is `None` via [`launch_input`]/[`TaskLaunchInput::automate`],
1588    /// so the guard's effective policy resolves to `Warn` (server default,
1589    /// [`EngineCfg::default`]) and never fires — the guard changes nothing
1590    /// about this pre-existing default-path behavior.
1591    #[tokio::test]
1592    async fn launch_without_any_check_policy_completes_fail_open() {
1593        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
1594            Ok(WorkerResult {
1595                value: json!({ "echoed": inv.prompt }),
1596                ok: true,
1597                stats: None,
1598            })
1599        });
1600        let svc = build_service(factory);
1601        let blueprint = bp(
1602            step("echo", path("$.input"), path("$.out")),
1603            vec![agent("echo", "echo")],
1604        );
1605        assert_eq!(blueprint.check_policy, None, "BP tier must be unset");
1606        let out = svc
1607            .launch(launch_input(blueprint, json!({ "input": "hi" })))
1608            .await
1609            .expect("warn-mode fail-open must let the launch complete");
1610        assert_eq!(out.final_ctx["out"]["echoed"], "hi");
1611    }
1612
1613    // ──────────────────────────────────────────────────────────────────
1614    // pre-dispatch validation guard:
1615    // `TaskLaunchService::launch` rejects BEFORE dispatch when the
1616    // effective check_policy is Strict and neither `project_root` nor
1617    // `work_dir` is supplied. T3/T4/T6 live here (T1/T2 are
1618    // handler-level, in `mlua-swarm-server`'s `projection.rs`; T5 is the
1619    // `launch_without_any_check_policy_completes_fail_open` test above;
1620    // the guard-rejection end-to-end case is
1621    // `strict_blueprint_without_roots_is_rejected_pre_dispatch` above,
1622    // Option A's repurpose of the former stage-1 T3).
1623    // ──────────────────────────────────────────────────────────────────
1624
1625    /// T3 (Crux 3, escape hatch): a Blueprint declaring `check_policy:
1626    /// strict` is overridden by the launch-request tier's `check_policy:
1627    /// Some(Warn)` — tier 1 wins the cascade before the guard's
1628    /// effective-policy fallback ever applies, so the guard passes and the
1629    /// launch dispatches normally even though `task_input` is `None` (no
1630    /// project_root/work_dir at all). Regression guard against a future
1631    /// "the guard judges by the BP tier alone, not the effective/cascaded
1632    /// value" narrowing.
1633    #[tokio::test]
1634    async fn strict_blueprint_with_launch_warn_override_bypasses_pre_dispatch_guard() {
1635        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
1636            Ok(WorkerResult {
1637                value: json!({ "echoed": inv.prompt }),
1638                ok: true,
1639                stats: None,
1640            })
1641        });
1642        let svc = build_service(factory);
1643        let mut blueprint = bp(
1644            step("echo", path("$.input"), path("$.out")),
1645            vec![agent("echo", "echo")],
1646        );
1647        blueprint.check_policy = Some(CheckPolicy::Strict);
1648        let mut input = launch_input(blueprint, json!({ "input": "hi" }));
1649        input.check_policy = Some(CheckPolicy::Warn);
1650        assert!(input.task_input.is_none(), "no roots supplied at all");
1651        let out = svc
1652            .launch(input)
1653            .await
1654            .expect("launch-tier warn override must bypass the pre-dispatch guard");
1655        assert_eq!(out.final_ctx["out"]["echoed"], "hi");
1656    }
1657
1658    /// T4 (Crux 2, server tier): with BOTH the launch- and Blueprint-tier
1659    /// `check_policy` unset, the server-wide `EngineCfg.check_policy` (the
1660    /// third cascade tier, read via `self.engine.cfg()`) alone must drive
1661    /// the guard — proof the guard does not stop at the "BP/launch 2-tier"
1662    /// shortcut Crux 2 forbids.
1663    #[tokio::test]
1664    async fn server_tier_strict_alone_triggers_pre_dispatch_guard() {
1665        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
1666            Ok(WorkerResult {
1667                value: json!({ "echoed": inv.prompt }),
1668                ok: true,
1669                stats: None,
1670            })
1671        });
1672        let svc = build_service_with_cfg(
1673            factory,
1674            EngineCfg {
1675                check_policy: CheckPolicy::Strict,
1676                ..EngineCfg::default()
1677            },
1678        );
1679        let blueprint = bp(
1680            step("echo", path("$.input"), path("$.out")),
1681            vec![agent("echo", "echo")],
1682        );
1683        assert_eq!(blueprint.check_policy, None, "BP tier must be unset");
1684        let input = launch_input(blueprint, json!({ "input": "hi" }));
1685        assert!(input.check_policy.is_none(), "launch tier must be unset");
1686        assert!(input.task_input.is_none(), "no roots supplied");
1687        let err = svc.launch(input).await.expect_err(
1688            "server-tier Strict alone (BP/launch tiers both unset) must trigger the guard",
1689        );
1690        match err {
1691            TaskLaunchError::PreDispatch(message) => {
1692                assert!(
1693                    message.contains("strict"),
1694                    "expected the strict-requires-roots message, got: {message}"
1695                );
1696            }
1697            other => panic!("expected TaskLaunchError::PreDispatch, got {other:?}"),
1698        }
1699    }
1700
1701    /// T6 (guard condition, branch 2 of 3): `task_input: Some(_)` with
1702    /// BOTH `project_root` and `work_dir` absent is still `roots_missing`
1703    /// — the outer `Some` alone must not short-circuit the check (branch 1,
1704    /// `task_input: None`, is covered by
1705    /// `strict_blueprint_without_roots_is_rejected_pre_dispatch` above).
1706    #[tokio::test]
1707    async fn pre_dispatch_guard_rejects_when_task_input_present_but_roots_both_none() {
1708        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
1709            Ok(WorkerResult {
1710                value: json!({ "echoed": inv.prompt }),
1711                ok: true,
1712                stats: None,
1713            })
1714        });
1715        let svc = build_service(factory);
1716        let mut blueprint = bp(
1717            step("echo", path("$.input"), path("$.out")),
1718            vec![agent("echo", "echo")],
1719        );
1720        blueprint.check_policy = Some(CheckPolicy::Strict);
1721        let mut input = launch_input(blueprint, json!({ "input": "hi" }));
1722        input.task_input = Some(TaskInputSpec {
1723            project_root: None,
1724            work_dir: None,
1725            task_metadata: Some(json!({ "unrelated": true })),
1726        });
1727        let err = svc
1728            .launch(input)
1729            .await
1730            .expect_err("Some(TaskInputSpec) with both roots None must still be roots_missing");
1731        assert!(
1732            matches!(err, TaskLaunchError::PreDispatch(_)),
1733            "expected TaskLaunchError::PreDispatch, got {err:?}"
1734        );
1735    }
1736
1737    /// T6 (guard condition, branch 3 of 3): `work_dir: Some(_)` alone
1738    /// (with `project_root: None`) is NOT `roots_missing` — either root
1739    /// being present is sufficient, so the guard passes and the launch
1740    /// dispatches normally.
1741    #[tokio::test]
1742    async fn pre_dispatch_guard_passes_when_work_dir_present_and_project_root_absent() {
1743        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
1744            Ok(WorkerResult {
1745                value: json!({ "echoed": inv.prompt }),
1746                ok: true,
1747                stats: None,
1748            })
1749        });
1750        let svc = build_service(factory);
1751        let mut blueprint = bp(
1752            step("echo", path("$.input"), path("$.out")),
1753            vec![agent("echo", "echo")],
1754        );
1755        blueprint.check_policy = Some(CheckPolicy::Strict);
1756        let mut input = launch_input(blueprint, json!({ "input": "hi" }));
1757        input.task_input = Some(TaskInputSpec {
1758            project_root: None,
1759            work_dir: Some("/repo/work".to_string()),
1760            task_metadata: None,
1761        });
1762        let out = svc
1763            .launch(input)
1764            .await
1765            .expect("work_dir alone must satisfy the guard's roots_missing check");
1766        assert_eq!(out.final_ctx["out"]["echoed"], "hi");
1767    }
1768
1769    #[tokio::test]
1770    async fn launch_three_step_seq_threads_ctx_forward() {
1771        let factory = RustFnInProcessSpawnerFactory::new()
1772            .register_fn("upper", |inv| async move {
1773                let s = serde_json::from_str::<String>(&inv.prompt).unwrap_or(inv.prompt);
1774                Ok(WorkerResult {
1775                    value: json!(s.to_uppercase()),
1776                    ok: true,
1777                    stats: None,
1778                })
1779            })
1780            .register_fn("suffix", |inv| async move {
1781                let s = serde_json::from_str::<String>(&inv.prompt).unwrap_or(inv.prompt);
1782                Ok(WorkerResult {
1783                    value: json!(format!("{s}!")),
1784                    ok: true,
1785                    stats: None,
1786                })
1787            })
1788            .register_fn("wrap", |inv| async move {
1789                let s = serde_json::from_str::<String>(&inv.prompt).unwrap_or(inv.prompt);
1790                Ok(WorkerResult {
1791                    value: json!(format!("[{s}]")),
1792                    ok: true,
1793                    stats: None,
1794                })
1795            });
1796        let svc = build_service(factory);
1797        let flow = FlowNode::Seq {
1798            children: vec![
1799                step("upper", path("$.in"), path("$.s1")),
1800                step("suffix", path("$.s1"), path("$.s2")),
1801                step("wrap", path("$.s2"), path("$.s3")),
1802            ],
1803        };
1804        let blueprint = bp(
1805            flow,
1806            vec![
1807                agent("upper", "upper"),
1808                agent("suffix", "suffix"),
1809                agent("wrap", "wrap"),
1810            ],
1811        );
1812        let out = svc
1813            .launch(launch_input(blueprint, json!({ "in": "hello" })))
1814            .await
1815            .expect("launch ok");
1816        assert_eq!(out.final_ctx["s1"], "HELLO");
1817        assert_eq!(out.final_ctx["s2"], "HELLO!");
1818        assert_eq!(out.final_ctx["s3"], "[HELLO!]");
1819    }
1820
1821    #[tokio::test]
1822    async fn launch_fanout_join_all_parallel_completes() {
1823        use std::sync::atomic::{AtomicU32, Ordering};
1824        let counter = Arc::new(AtomicU32::new(0));
1825        let max_seen = Arc::new(AtomicU32::new(0));
1826        let counter_clone = counter.clone();
1827        let max_clone = max_seen.clone();
1828
1829        // Each worker bumps the inflight counter up, sleeps 50ms, then bumps it down.
1830        // When parallel execution is working, max inflight exceeds 1.
1831        let factory = RustFnInProcessSpawnerFactory::new().register_fn("para", move |inv| {
1832            let counter = counter_clone.clone();
1833            let max_seen = max_clone.clone();
1834            async move {
1835                let now = counter.fetch_add(1, Ordering::SeqCst) + 1;
1836                let mut prev = max_seen.load(Ordering::SeqCst);
1837                while now > prev {
1838                    match max_seen.compare_exchange(prev, now, Ordering::SeqCst, Ordering::SeqCst) {
1839                        Ok(_) => break,
1840                        Err(p) => prev = p,
1841                    }
1842                }
1843                tokio::time::sleep(Duration::from_millis(50)).await;
1844                counter.fetch_sub(1, Ordering::SeqCst);
1845                let s = serde_json::from_str::<String>(&inv.prompt).unwrap_or(inv.prompt);
1846                Ok(WorkerResult {
1847                    value: json!(format!("did:{s}")),
1848                    ok: true,
1849                    stats: None,
1850                })
1851            }
1852        });
1853        let svc = build_service(factory);
1854        let flow = FlowNode::Fanout {
1855            items: path("$.items"),
1856            bind: path("$.item"),
1857            body: Box::new(step("para", path("$.item"), path("$.r"))),
1858            join: JoinMode::All,
1859            out: path("$.results"),
1860        };
1861        let blueprint = bp(flow, vec![agent("para", "para")]);
1862        let out = svc
1863            .launch(launch_input(
1864                blueprint,
1865                json!({ "items": ["a", "b", "c", "d"] }),
1866            ))
1867            .await
1868            .expect("launch ok");
1869        let results = out.final_ctx["results"].as_array().expect("array");
1870        assert_eq!(results.len(), 4);
1871        for (i, expected) in ["a", "b", "c", "d"].iter().enumerate() {
1872            assert_eq!(results[i]["r"], json!(format!("did:{expected}")));
1873        }
1874        let max = max_seen.load(Ordering::SeqCst);
1875        assert!(
1876            max >= 2,
1877            "expected parallel execution (max inflight >= 2), got {max}"
1878        );
1879    }
1880
1881    #[tokio::test]
1882    async fn launch_propagates_worker_error_as_flow_eval_err() {
1883        let factory = RustFnInProcessSpawnerFactory::new()
1884            .register_fn("ok", |inv| async move {
1885                Ok(WorkerResult {
1886                    value: json!(inv.prompt),
1887                    ok: true,
1888                    stats: None,
1889                })
1890            })
1891            .register_fn("boom", |_inv| async move {
1892                Err(WorkerError::Failed("intentional boom".into()))
1893            });
1894        let svc = build_service(factory);
1895        let flow = FlowNode::Seq {
1896            children: vec![
1897                step("ok", path("$.input"), path("$.s1")),
1898                step("boom", path("$.s1"), path("$.s2")),
1899                step("ok", path("$.s2"), path("$.s3")),
1900            ],
1901        };
1902        let blueprint = bp(flow, vec![agent("ok", "ok"), agent("boom", "boom")]);
1903        let err = svc
1904            .launch(launch_input(blueprint, json!({ "input": "x" })))
1905            .await
1906            .expect_err("expected fail");
1907        match err {
1908            TaskLaunchError::FlowEval { message: msg, .. } => {
1909                assert!(
1910                    msg.contains("boom") || msg.contains("intentional"),
1911                    "expected error to mention worker failure, got: {msg}"
1912                );
1913            }
1914            other => panic!("expected FlowEval error, got {other:?}"),
1915        }
1916    }
1917
1918    #[tokio::test]
1919    async fn launch_resolves_call_extern_via_registered_externs() {
1920        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
1921            Ok(WorkerResult {
1922                value: json!({ "echoed": inv.prompt }),
1923                ok: true,
1924                stats: None,
1925            })
1926        });
1927        let mut externs = mlua_flow_ir::ExternMap::new();
1928        externs.register("fmt.greet", |args: &[Value]| {
1929            let name = args[0].as_str().unwrap_or("?");
1930            Ok(json!(format!("hello, {name}")))
1931        });
1932        let svc = build_service(factory).with_externs(Arc::new(externs));
1933        let flow = step(
1934            "echo",
1935            Expr::CallExtern {
1936                ref_: "fmt.greet".into(),
1937                args: vec![path("$.who")],
1938            },
1939            path("$.out"),
1940        );
1941        let blueprint = bp(flow, vec![agent("echo", "echo")]);
1942        let out = svc
1943            .launch(launch_input(blueprint, json!({ "who": "swarm" })))
1944            .await
1945            .expect("launch ok");
1946        assert_eq!(out.final_ctx["out"]["echoed"], json!("hello, swarm"));
1947    }
1948
1949    #[tokio::test]
1950    async fn launch_call_extern_without_registry_fails_as_flow_eval() {
1951        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
1952            Ok(WorkerResult {
1953                value: json!(inv.prompt),
1954                ok: true,
1955                stats: None,
1956            })
1957        });
1958        let svc = build_service(factory); // default NoExterns
1959        let flow = step(
1960            "echo",
1961            Expr::CallExtern {
1962                ref_: "fmt.greet".into(),
1963                args: vec![],
1964            },
1965            path("$.out"),
1966        );
1967        let blueprint = bp(flow, vec![agent("echo", "echo")]);
1968        let err = svc
1969            .launch(launch_input(blueprint, json!({})))
1970            .await
1971            .expect_err("expected fail");
1972        match err {
1973            TaskLaunchError::FlowEval { message: msg, .. } => {
1974                assert!(msg.contains("extern"), "expected extern error, got: {msg}");
1975            }
1976            other => panic!("expected FlowEval error, got {other:?}"),
1977        }
1978    }
1979
1980    // ──────────────────────────────────────────────────────────────────
1981    // GH #50 (Subtask 2 follow-up): `TaskLaunchService::launch`'s
1982    // `compiler.compile` → `engine.register_verdict_contracts(...)` call
1983    // site — task_launch-level end-to-end (compile → register →
1984    // `Engine::verdict_contract_for_task` resolves it). The full HTTP
1985    // submit-time-422 round trip is covered separately: handler-level in
1986    // `crates/mlua-swarm-server/src/worker.rs`'s own `#[cfg(test)] mod
1987    // tests` GH #50 section (which seeds `Engine::register_verdict_contracts`
1988    // directly, bypassing this launch path since `mlua-swarm-server`
1989    // cannot depend on this crate's private test helpers) and
1990    // process-boundary-HTTP in
1991    // `crates/mlua-swarm-server/tests/verdict_contract.rs`. This test is
1992    // the missing link between those two: it exercises the REAL
1993    // `TaskLaunchService::launch` call site (not a hand-rolled duplicate
1994    // of its two lines) end-to-end through a real `Compiler::compile`,
1995    // proving the production wiring this follow-up added actually
1996    // populates the registry `Engine::verdict_contract_for_task` reads.
1997    // ──────────────────────────────────────────────────────────────────
1998
1999    #[tokio::test]
2000    async fn launch_registers_the_blueprints_verdict_contracts_into_the_engine() {
2001        let factory = RustFnInProcessSpawnerFactory::new().register_fn("gate", |inv| async move {
2002            Ok(WorkerResult {
2003                value: json!(inv.prompt),
2004                ok: true,
2005                stats: None,
2006            })
2007        });
2008        let svc = build_service(factory);
2009        let mut gate_agent = agent("gate", "gate");
2010        gate_agent.verdict = Some(mlua_swarm_schema::VerdictContract {
2011            channel: mlua_swarm_schema::VerdictChannel::Body,
2012            values: vec!["PASS".to_string(), "BLOCKED".to_string()],
2013        });
2014        let flow = step("gate", path("$.input"), path("$.out"));
2015        let blueprint = bp(flow, vec![gate_agent]);
2016
2017        let out = svc
2018            .launch(launch_input(blueprint, json!({ "input": "PASS" })))
2019            .await
2020            .expect("launch ok");
2021        assert_eq!(out.final_ctx["out"], json!("PASS"));
2022
2023        // `EngineDispatcher::dispatch` calls `engine.start_task` for every
2024        // dispatched Step (`TaskSpec.agent = ref_`) — this single-Step
2025        // Blueprint against a fresh per-test `Engine` (`build_service`)
2026        // leaves exactly one entry in `EngineState.tasks`.
2027        let task_id = svc
2028            .engine()
2029            .with_state("test.find_dispatched_task_id", |s| {
2030                s.tasks.keys().next().cloned()
2031            })
2032            .await
2033            .expect("with_state")
2034            .expect("launch must have dispatched exactly one Step (one TaskState)");
2035
2036        let contract = svc
2037            .engine()
2038            .verdict_contract_for_task(&task_id)
2039            .await
2040            .expect(
2041                "TaskLaunchService::launch must have merged this Blueprint's compiled \
2042                 verdict_contracts into the engine's runtime registry \
2043                 (Engine::register_verdict_contracts, called right after \
2044                 compiler.compile succeeds) — verdict_contract_for_task resolving None \
2045                 here means that production wiring regressed",
2046            );
2047        assert_eq!(contract.channel, mlua_swarm_schema::VerdictChannel::Body);
2048        assert_eq!(
2049            contract.values,
2050            vec!["PASS".to_string(), "BLOCKED".to_string()]
2051        );
2052    }
2053
2054    // ──────────────────────────────────────────────────────────────────
2055    // issue #13 run_id propagation (`TaskLaunchInput.run_ctx`)
2056    // ──────────────────────────────────────────────────────────────────
2057
2058    #[tokio::test]
2059    async fn launch_with_run_ctx_appends_one_step_entry_per_dispatched_step() {
2060        use crate::store::run::{InMemoryRunStore, RunContext, RunRecord, RunStatus, RunStore};
2061        use crate::types::{RunId, TaskId};
2062
2063        let factory = RustFnInProcessSpawnerFactory::new()
2064            .register_fn("upper", |inv| async move {
2065                Ok(WorkerResult {
2066                    value: json!(inv.prompt.to_uppercase()),
2067                    ok: true,
2068                    stats: None,
2069                })
2070            })
2071            .register_fn("suffix", |inv| async move {
2072                let s = serde_json::from_str::<String>(&inv.prompt).unwrap_or(inv.prompt);
2073                Ok(WorkerResult {
2074                    value: json!(format!("{s}!")),
2075                    ok: true,
2076                    stats: None,
2077                })
2078            });
2079        let svc = build_service(factory);
2080        let flow = FlowNode::Seq {
2081            children: vec![
2082                step("upper", path("$.in"), path("$.s1")),
2083                step("suffix", path("$.s1"), path("$.s2")),
2084            ],
2085        };
2086        let blueprint = bp(
2087            flow,
2088            vec![agent("upper", "upper"), agent("suffix", "suffix")],
2089        );
2090
2091        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
2092        let run_id = RunId::new();
2093        run_store
2094            .create(RunRecord {
2095                id: run_id.clone(),
2096                task_id: TaskId::new(),
2097                status: RunStatus::Running,
2098                step_entries: Vec::new(),
2099                degradations: Vec::new(),
2100                operator_sid: None,
2101                current: Default::default(),
2102                next_generation: 0,
2103                result_ref: None,
2104                input_json: Some("{}".to_string()),
2105                created_at: 0,
2106                updated_at: 0,
2107            })
2108            .await
2109            .expect("seed RunRecord");
2110
2111        let mut input = launch_input(blueprint, json!({ "in": "hi" }));
2112        input.run_ctx = Some(RunContext::new(run_id.clone(), run_store.clone()));
2113
2114        let out = svc.launch(input).await.expect("launch ok");
2115        assert_eq!(out.final_ctx["s2"], "HI!");
2116
2117        let run = run_store.get(&run_id).await.expect("run present");
2118        assert_eq!(
2119            run.step_entries.len(),
2120            2,
2121            "expected one step_entry per dispatched step, got {:?}",
2122            run.step_entries
2123        );
2124        assert_eq!(run.step_entries[0].step_ref, Some("upper".to_string()));
2125        assert_eq!(run.step_entries[0].status, Some("passed".to_string()));
2126        assert!(run.step_entries[0].binding_digest.is_some());
2127        assert_eq!(run.step_entries[1].step_ref, Some("suffix".to_string()));
2128        assert_eq!(run.step_entries[1].status, Some("passed".to_string()));
2129        assert!(run.step_entries[1].binding_digest.is_some());
2130        let snapshot: Value = serde_json::from_str(run.input_json.as_deref().unwrap()).unwrap();
2131        assert_eq!(snapshot["bound_agents"].as_array().unwrap().len(), 2);
2132    }
2133
2134    #[tokio::test]
2135    async fn run_snapshot_reuses_bound_agent_after_blueprint_mutation() {
2136        use crate::store::run::{InMemoryRunStore, RunContext, RunRecord, RunStatus, RunStore};
2137        use crate::types::{RunId, TaskId};
2138
2139        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
2140        let run_id = RunId::new();
2141        run_store
2142            .create(RunRecord {
2143                id: run_id.clone(),
2144                task_id: TaskId::new(),
2145                status: RunStatus::Running,
2146                step_entries: Vec::new(),
2147                degradations: Vec::new(),
2148                operator_sid: None,
2149                current: Default::default(),
2150                next_generation: 0,
2151                result_ref: None,
2152                input_json: Some("{}".to_string()),
2153                created_at: 0,
2154                updated_at: 0,
2155            })
2156            .await
2157            .unwrap();
2158        let run_ctx = RunContext::new(run_id, run_store);
2159        let mut original_agent = agent("worker", "worker");
2160        original_agent.profile = Some(crate::blueprint::AgentProfile {
2161            system_prompt: "original role".to_string(),
2162            ..Default::default()
2163        });
2164        let mut blueprint = bp(
2165            step("worker", path("$.input"), path("$.out")),
2166            vec![original_agent],
2167        );
2168
2169        let (original, _) = load_or_resolve_bound_agents(
2170            &blueprint,
2171            Some(&run_ctx),
2172            None,
2173            LegacyWorkerBindingPolicy::Allow,
2174        )
2175        .await
2176        .unwrap();
2177        blueprint.agents[0].profile.as_mut().unwrap().system_prompt = "mutated role".to_string();
2178        let (restored, _) = load_or_resolve_bound_agents(
2179            &blueprint,
2180            Some(&run_ctx),
2181            None,
2182            LegacyWorkerBindingPolicy::Allow,
2183        )
2184        .await
2185        .unwrap();
2186
2187        assert_eq!(restored[0].binding_digest, original[0].binding_digest);
2188        assert_eq!(
2189            restored[0].agent.profile.as_ref().unwrap().system_prompt,
2190            "original role"
2191        );
2192    }
2193
2194    #[tokio::test]
2195    async fn strict_migration_policy_rejects_fresh_legacy_worker_binding() {
2196        let mut legacy_agent = agent("worker", "worker");
2197        legacy_agent.profile = Some(AgentProfile {
2198            worker_binding: Some("legacy-worker".to_string()),
2199            ..Default::default()
2200        });
2201        let blueprint = bp(
2202            step("worker", path("$.input"), path("$.out")),
2203            vec![legacy_agent],
2204        );
2205
2206        let error =
2207            load_or_resolve_bound_agents(&blueprint, None, None, LegacyWorkerBindingPolicy::Reject)
2208                .await
2209                .expect_err("strict migration policy must reject fallback");
2210        assert!(error
2211            .to_string()
2212            .contains("deprecated profile.worker_binding"));
2213    }
2214
2215    #[tokio::test]
2216    async fn run_snapshot_calls_binding_provider_only_on_first_resolution() {
2217        use crate::binding::{AgentBindingProvider, BindingProviderError};
2218        use crate::blueprint::{BindOutcome, BindReceipt, BindRequest};
2219        use crate::store::run::{InMemoryRunStore, RunContext, RunRecord, RunStatus, RunStore};
2220        use crate::types::{RunId, TaskId};
2221        use std::sync::atomic::{AtomicUsize, Ordering};
2222
2223        struct CountingProvider(AtomicUsize);
2224
2225        #[async_trait::async_trait]
2226        impl AgentBindingProvider for CountingProvider {
2227            async fn bind(
2228                &self,
2229                requests: &[BindRequest],
2230            ) -> Result<Vec<BindOutcome>, BindingProviderError> {
2231                self.0.fetch_add(1, Ordering::SeqCst);
2232                Ok(requests
2233                    .iter()
2234                    .map(|request| BindOutcome::Bound {
2235                        receipt: BindReceipt {
2236                            agent: request.agent.clone(),
2237                            request_digest: request.request_digest.clone(),
2238                            provider_id: "operator-main-ai".to_string(),
2239                            provider_revision: Some("test".to_string()),
2240                            resolved_model: request.requested_model.clone(),
2241                            effective_tools: request.requested_tools.clone(),
2242                            launch_variant: request.launch_variant.clone(),
2243                            capability_snapshot_digest: None,
2244                        },
2245                    })
2246                    .collect())
2247            }
2248        }
2249
2250        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
2251        let run_id = RunId::new();
2252        run_store
2253            .create(RunRecord {
2254                id: run_id.clone(),
2255                task_id: TaskId::new(),
2256                status: RunStatus::Running,
2257                step_entries: Vec::new(),
2258                degradations: Vec::new(),
2259                operator_sid: None,
2260                current: Default::default(),
2261                next_generation: 0,
2262                result_ref: None,
2263                input_json: Some("{}".to_string()),
2264                created_at: 0,
2265                updated_at: 0,
2266            })
2267            .await
2268            .unwrap();
2269        let run_ctx = RunContext::new(run_id, run_store);
2270        let mut blueprint = bp(
2271            step("worker", path("$.input"), path("$.out")),
2272            vec![agent("worker", "worker")],
2273        );
2274        blueprint.agents[0].runner = Some(Runner::WsClaudeCode {
2275            variant: "mse-worker".to_string(),
2276            tools: vec!["Read".to_string()],
2277        });
2278        let provider = CountingProvider(AtomicUsize::new(0));
2279
2280        let (first, _) = load_or_resolve_bound_agents(
2281            &blueprint,
2282            Some(&run_ctx),
2283            Some(&provider),
2284            LegacyWorkerBindingPolicy::Allow,
2285        )
2286        .await
2287        .unwrap();
2288        let (restored, _) = load_or_resolve_bound_agents(
2289            &blueprint,
2290            Some(&run_ctx),
2291            Some(&provider),
2292            LegacyWorkerBindingPolicy::Allow,
2293        )
2294        .await
2295        .unwrap();
2296
2297        assert_eq!(provider.0.load(Ordering::SeqCst), 1);
2298        assert!(first[0].attestation.is_some());
2299        assert_eq!(restored, first);
2300    }
2301
2302    // ──────────────────────────────────────────────────────────────────
2303    // D1: snapshot origin marker (`bound_agents_origin`)
2304    // ──────────────────────────────────────────────────────────────────
2305
2306    /// An initial launch (RunContext `resume == false`) that has to resolve
2307    /// fresh persists `bound_agents_origin: "launch"` alongside
2308    /// `bound_agents`, and records NO backfill degradation — a first-time
2309    /// pin is not a degradation.
2310    #[tokio::test]
2311    async fn fresh_resolve_on_launch_persists_launch_origin_no_degradation() {
2312        use crate::store::run::{
2313            InMemoryRunStore, RunContext, RunRecord, RunStatus, RunStore, BOUND_AGENTS_ORIGIN_KEY,
2314        };
2315        use crate::types::{RunId, TaskId};
2316
2317        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
2318        let run_id = RunId::new();
2319        run_store
2320            .create(RunRecord {
2321                id: run_id.clone(),
2322                task_id: TaskId::new(),
2323                status: RunStatus::Running,
2324                step_entries: Vec::new(),
2325                degradations: Vec::new(),
2326                operator_sid: None,
2327                current: Default::default(),
2328                next_generation: 0,
2329                result_ref: None,
2330                input_json: Some("{}".to_string()),
2331                created_at: 0,
2332                updated_at: 0,
2333            })
2334            .await
2335            .unwrap();
2336        // No `.with_resume()` — this is an initial launch.
2337        let run_ctx = RunContext::new(run_id.clone(), run_store.clone());
2338        let blueprint = bp(
2339            step("worker", path("$.input"), path("$.out")),
2340            vec![agent("worker", "worker")],
2341        );
2342
2343        load_or_resolve_bound_agents(
2344            &blueprint,
2345            Some(&run_ctx),
2346            None,
2347            LegacyWorkerBindingPolicy::Allow,
2348        )
2349        .await
2350        .expect("launch resolve ok");
2351
2352        let run = run_store.get(&run_id).await.expect("run present");
2353        let snapshot: Value = serde_json::from_str(run.input_json.as_deref().unwrap()).unwrap();
2354        assert!(
2355            snapshot["bound_agents"].is_array(),
2356            "bound_agents must be persisted"
2357        );
2358        assert_eq!(snapshot[BOUND_AGENTS_ORIGIN_KEY], json!("launch"));
2359        assert_eq!(
2360            SnapshotOrigin::from_snapshot(&snapshot),
2361            SnapshotOrigin::Launch
2362        );
2363        assert!(
2364            run.degradations.is_empty(),
2365            "an initial-launch resolve is not a degradation"
2366        );
2367    }
2368
2369    /// A resume (RunContext `resume == true`) that has to backfill a
2370    /// pre-binding-snapshot Run persists `bound_agents_origin:
2371    /// "resume_backfill"` and appends exactly one backfill degradation
2372    /// (`fallback: "resume_backfill"`).
2373    #[tokio::test]
2374    async fn backfill_on_resume_persists_resume_origin_and_records_degradation() {
2375        use crate::store::run::{
2376            InMemoryRunStore, RunContext, RunRecord, RunStatus, RunStore, BOUND_AGENTS_ORIGIN_KEY,
2377        };
2378        use crate::types::{RunId, TaskId};
2379
2380        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
2381        let run_id = RunId::new();
2382        run_store
2383            .create(RunRecord {
2384                id: run_id.clone(),
2385                task_id: TaskId::new(),
2386                status: RunStatus::Running,
2387                step_entries: Vec::new(),
2388                degradations: Vec::new(),
2389                operator_sid: None,
2390                current: Default::default(),
2391                next_generation: 0,
2392                result_ref: None,
2393                input_json: Some("{}".to_string()),
2394                created_at: 0,
2395                updated_at: 0,
2396            })
2397            .await
2398            .unwrap();
2399        let run_ctx = RunContext::new(run_id.clone(), run_store.clone()).with_resume();
2400        let blueprint = bp(
2401            step("worker", path("$.input"), path("$.out")),
2402            vec![agent("worker", "worker")],
2403        );
2404
2405        load_or_resolve_bound_agents(
2406            &blueprint,
2407            Some(&run_ctx),
2408            None,
2409            LegacyWorkerBindingPolicy::Allow,
2410        )
2411        .await
2412        .expect("resume backfill ok");
2413
2414        let run = run_store.get(&run_id).await.expect("run present");
2415        let snapshot: Value = serde_json::from_str(run.input_json.as_deref().unwrap()).unwrap();
2416        assert_eq!(snapshot[BOUND_AGENTS_ORIGIN_KEY], json!("resume_backfill"));
2417        assert_eq!(
2418            SnapshotOrigin::from_snapshot(&snapshot),
2419            SnapshotOrigin::ResumeBackfill
2420        );
2421        assert_eq!(
2422            run.degradations.len(),
2423            1,
2424            "a resume backfill must record exactly one degradation"
2425        );
2426        assert_eq!(run.degradations[0].tool, "binding");
2427        assert_eq!(run.degradations[0].fallback, "resume_backfill");
2428    }
2429
2430    // ──────────────────────────────────────────────────────────────────
2431    // C1: `strict_binding` gate + optional attestation
2432    // ──────────────────────────────────────────────────────────────────
2433
2434    /// A Runner-backed Blueprint whose single `worker` agent binds through a
2435    /// WS Operator variant `mse-worker` requiring tool `Read`.
2436    fn runner_blueprint(strict_binding: bool) -> Blueprint {
2437        let mut blueprint = bp(
2438            step("worker", path("$.input"), path("$.out")),
2439            vec![agent("worker", "worker")],
2440        );
2441        blueprint.strategy.strict_binding = strict_binding;
2442        blueprint.agents[0].runner = Some(Runner::WsClaudeCode {
2443            variant: "mse-worker".to_string(),
2444            tools: vec!["Read".to_string()],
2445        });
2446        blueprint
2447    }
2448
2449    /// Provider that leaves every request `Unbound` — models a missing /
2450    /// manifest-less execution environment.
2451    struct AlwaysUnboundProvider;
2452
2453    #[async_trait::async_trait]
2454    impl AgentBindingProvider for AlwaysUnboundProvider {
2455        async fn bind(
2456            &self,
2457            requests: &[crate::blueprint::BindRequest],
2458        ) -> Result<Vec<crate::blueprint::BindOutcome>, crate::binding::BindingProviderError>
2459        {
2460            Ok(requests
2461                .iter()
2462                .map(|request| crate::blueprint::BindOutcome::Unbound {
2463                    agent: request.agent.clone(),
2464                    reason: "no capability manifest submitted".to_string(),
2465                })
2466                .collect())
2467        }
2468    }
2469
2470    /// Non-strict + a provider that cannot attest → launch resolution
2471    /// succeeds, the agent stays `DeclarationOnly`, and the gap is recorded
2472    /// as a `RunRecord.degradations` entry.
2473    #[tokio::test]
2474    async fn non_strict_unbound_agent_runs_declaration_only_with_degradation() {
2475        use crate::store::run::{InMemoryRunStore, RunContext, RunRecord, RunStatus, RunStore};
2476        use crate::types::{RunId, TaskId};
2477
2478        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
2479        let run_id = RunId::new();
2480        run_store
2481            .create(RunRecord {
2482                id: run_id.clone(),
2483                task_id: TaskId::new(),
2484                status: RunStatus::Running,
2485                step_entries: Vec::new(),
2486                degradations: Vec::new(),
2487                operator_sid: None,
2488                current: Default::default(),
2489                next_generation: 0,
2490                result_ref: None,
2491                input_json: Some("{}".to_string()),
2492                created_at: 0,
2493                updated_at: 0,
2494            })
2495            .await
2496            .unwrap();
2497        let run_ctx = RunContext::new(run_id.clone(), run_store.clone());
2498
2499        let (bound, _) = load_or_resolve_bound_agents(
2500            &runner_blueprint(false),
2501            Some(&run_ctx),
2502            Some(&AlwaysUnboundProvider),
2503            LegacyWorkerBindingPolicy::Allow,
2504        )
2505        .await
2506        .expect("non-strict launch must succeed even without an attestation");
2507        assert!(
2508            bound[0].attestation.is_none(),
2509            "an unattested agent must stay DeclarationOnly"
2510        );
2511
2512        let run = run_store.get(&run_id).await.expect("run present");
2513        assert_eq!(run.degradations.len(), 1, "expected one degradation entry");
2514        assert_eq!(run.degradations[0].tool, "binding");
2515        assert_eq!(run.degradations[0].fallback, "DeclarationOnly");
2516        assert!(run.degradations[0].error.contains("no capability manifest"));
2517    }
2518
2519    /// Strict + a provider that cannot attest → launch fails, and the error
2520    /// message names the agent and its requested launch variant / tools so an
2521    /// Operator can generate a satisfying manifest.
2522    #[tokio::test]
2523    async fn strict_unbound_agent_fails_with_requirements_in_message() {
2524        let error = load_or_resolve_bound_agents(
2525            &runner_blueprint(true),
2526            None,
2527            Some(&AlwaysUnboundProvider),
2528            LegacyWorkerBindingPolicy::Allow,
2529        )
2530        .await
2531        .expect_err("strict + Unbound must reject the launch");
2532        match error {
2533            TaskLaunchError::PreDispatch(message) => {
2534                assert!(message.contains("worker"), "message: {message}");
2535                assert!(message.contains("mse-worker"), "message: {message}");
2536                assert!(message.contains("Read"), "message: {message}");
2537            }
2538            other => panic!("expected PreDispatch, got {other:?}"),
2539        }
2540    }
2541
2542    /// Strict + no provider at all → launch fails fast: nothing can attest the
2543    /// Runner-backed agent.
2544    #[tokio::test]
2545    async fn strict_without_provider_rejects_runner_backed_launch() {
2546        let error = load_or_resolve_bound_agents(
2547            &runner_blueprint(true),
2548            None,
2549            None,
2550            LegacyWorkerBindingPolicy::Allow,
2551        )
2552        .await
2553        .expect_err("strict + no provider must reject a Runner-backed launch");
2554        match error {
2555            TaskLaunchError::PreDispatch(message) => {
2556                assert!(
2557                    message.contains("strict_binding requires a binding provider"),
2558                    "message: {message}"
2559                );
2560            }
2561            other => panic!("expected PreDispatch, got {other:?}"),
2562        }
2563    }
2564
2565    /// Strict + a correct manifest → the agent is Attested (the pre-C1 pass
2566    /// path still holds under the strict gate).
2567    #[tokio::test]
2568    async fn strict_with_correct_manifest_attests_the_agent() {
2569        use crate::binding::ManifestBindingProvider;
2570        use crate::blueprint::{AgentProviderCapability, AgentProviderManifest};
2571
2572        let provider = ManifestBindingProvider::new(AgentProviderManifest {
2573            provider_id: "operator-main-ai".to_string(),
2574            provider_revision: Some("1".to_string()),
2575            capabilities: vec![AgentProviderCapability {
2576                launch_variant: Some("mse-worker".to_string()),
2577                resolved_model: None,
2578                effective_tools: vec!["Read".to_string()],
2579                capability_snapshot_digest: None,
2580            }],
2581        });
2582        let (bound, _) = load_or_resolve_bound_agents(
2583            &runner_blueprint(true),
2584            None,
2585            Some(&provider),
2586            LegacyWorkerBindingPolicy::Allow,
2587        )
2588        .await
2589        .expect("strict launch with a correct manifest must attest");
2590        assert!(
2591            bound[0].attestation.is_some(),
2592            "a correctly attested agent must carry its attestation"
2593        );
2594    }
2595
2596    // ──────────────────────────────────────────────────────────────────
2597    // C2: spawn-frame self-check inputs (request_digest / requested_model)
2598    // ──────────────────────────────────────────────────────────────────
2599
2600    /// The launch-path `WorkerBinding` map carries the requesting side's
2601    /// self-check inputs: the immutable snapshot's `binding_digest` and the
2602    /// profile's declared model, so a non-strict Operator can compare the
2603    /// spawn frame against its own environment.
2604    #[test]
2605    fn worker_bindings_carry_request_digest_and_model() {
2606        let mut blueprint = runner_blueprint(false);
2607        blueprint.agents[0].profile = Some(AgentProfile {
2608            model: Some("claude-sonnet".to_string()),
2609            ..Default::default()
2610        });
2611        let bound = resolve_bound_agents(&blueprint).expect("resolvable Runner refs");
2612        let bindings = worker_bindings_from_bound_agents(&bound);
2613
2614        let wb = bindings.get("worker").expect("worker binding present");
2615        assert_eq!(
2616            wb.request_digest.as_ref(),
2617            Some(&bound[0].binding_digest),
2618            "the spawn frame must carry the immutable snapshot digest"
2619        );
2620        assert!(wb
2621            .request_digest
2622            .as_ref()
2623            .unwrap()
2624            .as_str()
2625            .starts_with("sha256:"));
2626        assert_eq!(wb.requested_model.as_deref(), Some("claude-sonnet"));
2627    }
2628
2629    /// A Runner-backed agent whose profile declares no model leaves
2630    /// `requested_model` `None` while still carrying the digest.
2631    #[test]
2632    fn worker_bindings_omit_model_when_profile_has_none() {
2633        let bound = resolve_bound_agents(&runner_blueprint(false)).expect("resolvable Runner refs");
2634        let bindings = worker_bindings_from_bound_agents(&bound);
2635        let wb = bindings.get("worker").expect("worker binding present");
2636        assert!(wb.request_digest.is_some());
2637        assert!(wb.requested_model.is_none());
2638    }
2639
2640    #[tokio::test]
2641    async fn launch_without_run_ctx_appends_no_step_entries() {
2642        // `run_ctx: None` (the `automate()` default) must not touch any
2643        // `RunStore` — this is the pre-existing no-tracing behavior, kept
2644        // as a regression guard alongside the `Some` case above.
2645        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
2646            Ok(WorkerResult {
2647                value: json!(inv.prompt),
2648                ok: true,
2649                stats: None,
2650            })
2651        });
2652        let svc = build_service(factory);
2653        let blueprint = bp(
2654            step("echo", path("$.input"), path("$.out")),
2655            vec![agent("echo", "echo")],
2656        );
2657        let input = launch_input(blueprint, json!({ "input": "hi" }));
2658        assert!(
2659            input.run_ctx.is_none(),
2660            "automate() defaults run_ctx to None"
2661        );
2662        let out = svc.launch(input).await.expect("launch ok");
2663        assert_eq!(out.final_ctx["out"], "hi");
2664    }
2665
2666    // ──────────────────────────────────────────────────────────────────
2667    // issue #19 ST2: `TaskLaunchInput.task_input` (direct-sibling-read
2668    // replacement for the ST1 `from_init_ctx(&input.init_ctx)` call)
2669    // ──────────────────────────────────────────────────────────────────
2670
2671    #[tokio::test]
2672    async fn launch_with_task_input_leaves_init_ctx_object_seed_unmutated() {
2673        // Issue #19 ST2 invariant: `init_ctx` is a pure flow-ir eval seed —
2674        // `task_input` must not be folded into it. Regression guard for the
2675        // ST1 `resolve_task_level_init_ctx` fold-back this subtask removes:
2676        // if it ever crept back in here, `project_root` / `work_dir` /
2677        // `task_metadata` would leak into `final_ctx` as extra top-level
2678        // keys nobody wrote via a `Step.out`.
2679        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
2680            Ok(WorkerResult {
2681                value: json!({ "echoed": inv.prompt }),
2682                ok: true,
2683                stats: None,
2684            })
2685        });
2686        let svc = build_service(factory);
2687        let blueprint = bp(
2688            step("echo", path("$.input"), path("$.out")),
2689            vec![agent("echo", "echo")],
2690        );
2691        let mut input = launch_input(blueprint, json!({ "input": "hi" }));
2692        input.task_input = Some(TaskInputSpec {
2693            project_root: Some("/repo".to_string()),
2694            work_dir: Some("/repo/work".to_string()),
2695            task_metadata: Some(json!({ "issue": 19 })),
2696        });
2697        let out = svc.launch(input).await.expect("launch ok");
2698        assert_eq!(out.final_ctx["out"]["echoed"], "hi");
2699        assert!(
2700            out.final_ctx.get("project_root").is_none(),
2701            "task_input must not be folded into the flow-ir ctx seed, got {:?}",
2702            out.final_ctx
2703        );
2704        assert!(out.final_ctx.get("work_dir").is_none());
2705        assert!(out.final_ctx.get("task_metadata").is_none());
2706    }
2707
2708    #[tokio::test]
2709    async fn launch_with_task_input_none_is_a_no_op() {
2710        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
2711            Ok(WorkerResult {
2712                value: json!(inv.prompt),
2713                ok: true,
2714                stats: None,
2715            })
2716        });
2717        let svc = build_service(factory);
2718        let blueprint = bp(
2719            step("echo", path("$.input"), path("$.out")),
2720            vec![agent("echo", "echo")],
2721        );
2722        let mut input = launch_input(blueprint, json!({ "input": "hi" }));
2723        assert!(input.task_input.is_none(), "automate() defaults to None");
2724        input.task_input = None;
2725        let out = svc.launch(input).await.expect("launch ok");
2726        assert_eq!(out.final_ctx["out"], "hi");
2727    }
2728
2729    #[tokio::test]
2730    async fn launch_with_task_input_all_fields_absent_is_a_no_op() {
2731        // `Some(TaskInputSpec::default())` — outer Some, all 3 inner fields
2732        // None — must behave identically to `task_input: None` (mirrors
2733        // `TaskInputMiddleware::new_from_fields`'s own no-op contract).
2734        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
2735            Ok(WorkerResult {
2736                value: json!(inv.prompt),
2737                ok: true,
2738                stats: None,
2739            })
2740        });
2741        let svc = build_service(factory);
2742        let blueprint = bp(
2743            step("echo", path("$.input"), path("$.out")),
2744            vec![agent("echo", "echo")],
2745        );
2746        let mut input = launch_input(blueprint, json!({ "input": "hi" }));
2747        input.task_input = Some(TaskInputSpec::default());
2748        let out = svc.launch(input).await.expect("launch ok");
2749        assert_eq!(out.final_ctx["out"], "hi");
2750    }
2751
2752    // ──────────────────────────────────────────────────────────────────
2753    // issue #19 ST3: `merge_init_ctx` (BP default + Task init_ctx)
2754    // ──────────────────────────────────────────────────────────────────
2755
2756    #[test]
2757    fn merge_init_ctx_bp_default_only_passes_through_when_task_is_empty_object() {
2758        let bp_default = json!({ "seeded": "from-bp" });
2759        let task = json!({});
2760        let merged = merge_init_ctx(Some(&bp_default), &task);
2761        assert_eq!(merged, json!({ "seeded": "from-bp" }));
2762    }
2763
2764    #[test]
2765    fn merge_init_ctx_task_only_passes_through_when_bp_default_is_empty_object() {
2766        let bp_default = json!({});
2767        let task = json!({ "seeded": "from-task" });
2768        let merged = merge_init_ctx(Some(&bp_default), &task);
2769        assert_eq!(merged, json!({ "seeded": "from-task" }));
2770    }
2771
2772    #[test]
2773    fn merge_init_ctx_both_objects_task_wins_on_key_collision() {
2774        let bp_default = json!({ "a": "bp", "b": "bp-only" });
2775        let task = json!({ "a": "task", "c": "task-only" });
2776        let merged = merge_init_ctx(Some(&bp_default), &task);
2777        assert_eq!(
2778            merged,
2779            json!({ "a": "task", "b": "bp-only", "c": "task-only" })
2780        );
2781    }
2782
2783    #[test]
2784    fn merge_init_ctx_non_object_task_fully_replaces_bp_default() {
2785        let bp_default = json!({ "seeded": "from-bp" });
2786        let task = json!("plain-string-seed");
2787        let merged = merge_init_ctx(Some(&bp_default), &task);
2788        assert_eq!(merged, json!("plain-string-seed"));
2789    }
2790
2791    #[test]
2792    fn merge_init_ctx_no_bp_default_is_a_no_op() {
2793        let task = json!({ "input": "hi" });
2794        let merged = merge_init_ctx(None, &task);
2795        assert_eq!(merged, task);
2796    }
2797
2798    // ──────────────────────────────────────────────────────────────────
2799    // issue #19 ST4: `merge_init_ctx_3layer` (BP default + Task + Run)
2800    // ──────────────────────────────────────────────────────────────────
2801
2802    #[test]
2803    fn merge_init_ctx_3layer_no_run_override_equals_bp_task_merge_only() {
2804        // `run_override: None` must be a pure pass-through of the BP+Task
2805        // merge — this is the `POST /v1/tasks/:id/runs` no-body rekick
2806        // path, which must preserve pre-#19 behavior byte-for-byte.
2807        let bp_default = json!({ "a": "bp", "b": "bp-only" });
2808        let task = json!({ "a": "task", "c": "task-only" });
2809        let three_layer = merge_init_ctx_3layer(Some(&bp_default), &task, None);
2810        let two_layer = merge_init_ctx(Some(&bp_default), &task);
2811        assert_eq!(three_layer, two_layer);
2812        assert_eq!(
2813            three_layer,
2814            json!({ "a": "task", "b": "bp-only", "c": "task-only" })
2815        );
2816    }
2817
2818    #[test]
2819    fn merge_init_ctx_3layer_run_object_wins_on_key_collision_over_bp_and_task() {
2820        let bp_default = json!({ "a": "bp", "b": "bp-only" });
2821        let task = json!({ "a": "task", "c": "task-only" });
2822        let run_override = json!({ "a": "run", "d": "run-only" });
2823        let merged = merge_init_ctx_3layer(Some(&bp_default), &task, Some(&run_override));
2824        assert_eq!(
2825            merged,
2826            json!({ "a": "run", "b": "bp-only", "c": "task-only", "d": "run-only" }),
2827            "Run wins on collision (a); BP-only (b) and Task-only (c) keys survive"
2828        );
2829    }
2830
2831    #[test]
2832    fn merge_init_ctx_3layer_run_non_object_fully_replaces_bp_task_merge() {
2833        let bp_default = json!({ "seeded": "from-bp" });
2834        let task = json!({ "seeded": "from-task" });
2835        let run_override = json!("plain-string-run-seed");
2836        let merged = merge_init_ctx_3layer(Some(&bp_default), &task, Some(&run_override));
2837        assert_eq!(merged, json!("plain-string-run-seed"));
2838    }
2839
2840    #[test]
2841    fn merge_init_ctx_3layer_no_bp_default_and_no_run_override_is_task_passthrough() {
2842        let task = json!({ "input": "hi" });
2843        let merged = merge_init_ctx_3layer(None, &task, None);
2844        assert_eq!(merged, task);
2845    }
2846
2847    #[tokio::test]
2848    async fn launch_merges_bp_default_init_ctx_into_task_init_ctx() {
2849        // End-to-end guard: `Blueprint.default_init_ctx` actually reaches
2850        // `eval_async_externs` — not merely unit-tested in isolation.
2851        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", |inv| async move {
2852            Ok(WorkerResult {
2853                value: json!(inv.prompt),
2854                ok: true,
2855                stats: None,
2856            })
2857        });
2858        let svc = build_service(factory);
2859        let mut blueprint = bp(
2860            step("echo", path("$.greeting"), path("$.out")),
2861            vec![agent("echo", "echo")],
2862        );
2863        blueprint.default_init_ctx = Some(json!({ "greeting": "hello from bp" }));
2864        // Task supplies an empty object — BP default alone seeds `$.greeting`.
2865        let out = svc
2866            .launch(launch_input(blueprint, json!({})))
2867            .await
2868            .expect("launch ok");
2869        assert_eq!(out.final_ctx["out"], "hello from bp");
2870    }
2871
2872    // ──────────────────────────────────────────────────────────────────
2873    // issue #21 Phase 1: `derive_agent_ctx` / `derive_context_policies`
2874    // ──────────────────────────────────────────────────────────────────
2875
2876    fn agent_with_meta(name: &str, fn_id: &str, meta: AgentMeta) -> AgentDef {
2877        AgentDef {
2878            name: name.to_string(),
2879            kind: AgentKind::RustFn,
2880            spec: json!({ "fn_id": fn_id }),
2881            profile: None,
2882            meta: Some(meta),
2883            runner: None,
2884            runner_ref: None,
2885            verdict: None,
2886            lints: None,
2887        }
2888    }
2889
2890    #[test]
2891    fn derive_agent_ctx_empty_blueprint_yields_empty_state() {
2892        let blueprint = bp(step("echo", path("$.in"), path("$.out")), vec![]);
2893        let (global, per_agent) = derive_agent_ctx(&blueprint);
2894        assert_eq!(global, None);
2895        assert!(per_agent.is_empty());
2896    }
2897
2898    #[test]
2899    fn derive_agent_ctx_populated_blueprint_yields_correct_maps() {
2900        let mut blueprint = bp(
2901            step("echo", path("$.in"), path("$.out")),
2902            vec![
2903                agent_with_meta(
2904                    "with-ctx",
2905                    "echo",
2906                    AgentMeta {
2907                        ctx: Some(json!({ "org_conventions": "x" })),
2908                        ..Default::default()
2909                    },
2910                ),
2911                agent("no-ctx", "echo"),
2912            ],
2913        );
2914        blueprint.default_agent_ctx = Some(json!({ "seeded": "from-bp" }));
2915        let (global, per_agent) = derive_agent_ctx(&blueprint);
2916        assert_eq!(global, Some(json!({ "seeded": "from-bp" })));
2917        assert_eq!(
2918            per_agent.len(),
2919            1,
2920            "agents without AgentMeta.ctx are absent, not defaulted to null: {per_agent:?}"
2921        );
2922        assert_eq!(
2923            per_agent.get("with-ctx"),
2924            Some(&json!({ "org_conventions": "x" }))
2925        );
2926        assert!(!per_agent.contains_key("no-ctx"));
2927    }
2928
2929    #[test]
2930    fn derive_context_policies_empty_blueprint_yields_empty_state() {
2931        let blueprint = bp(step("echo", path("$.in"), path("$.out")), vec![]);
2932        let (default_policy, per_agent) = derive_context_policies(&blueprint);
2933        assert_eq!(default_policy, None);
2934        assert!(per_agent.is_empty());
2935    }
2936
2937    #[test]
2938    fn derive_context_policies_populated_blueprint_yields_correct_maps() {
2939        let mut blueprint = bp(
2940            step("echo", path("$.in"), path("$.out")),
2941            vec![
2942                agent_with_meta(
2943                    "with-policy",
2944                    "echo",
2945                    AgentMeta {
2946                        context_policy: Some(ContextPolicy {
2947                            include: None,
2948                            exclude: vec!["work_dir".to_string()],
2949                            ..Default::default()
2950                        }),
2951                        ..Default::default()
2952                    },
2953                ),
2954                agent("no-policy", "echo"),
2955            ],
2956        );
2957        blueprint.default_context_policy = Some(ContextPolicy {
2958            include: Some(vec!["project_root".to_string()]),
2959            exclude: vec![],
2960            ..Default::default()
2961        });
2962        let (default_policy, per_agent) = derive_context_policies(&blueprint);
2963        assert_eq!(
2964            default_policy,
2965            Some(ContextPolicy {
2966                include: Some(vec!["project_root".to_string()]),
2967                exclude: vec![],
2968                ..Default::default()
2969            })
2970        );
2971        assert_eq!(per_agent.len(), 1);
2972        assert_eq!(
2973            per_agent.get("with-policy"),
2974            Some(&ContextPolicy {
2975                include: None,
2976                exclude: vec!["work_dir".to_string()],
2977                ..Default::default()
2978            })
2979        );
2980        assert!(!per_agent.contains_key("no-policy"));
2981    }
2982
2983    // ──────────────────────────────────────────────────────────────────
2984    // issue #21 Phase 2: `derive_step_metas` / `AgentMeta.meta_ref`
2985    // resolution inside `derive_agent_ctx`
2986    // ──────────────────────────────────────────────────────────────────
2987
2988    #[test]
2989    fn derive_step_metas_empty_blueprint_yields_empty_map() {
2990        let blueprint = bp(step("echo", path("$.in"), path("$.out")), vec![]);
2991        assert!(derive_step_metas(&blueprint).is_empty());
2992    }
2993
2994    #[test]
2995    fn derive_step_metas_populated_blueprint_yields_name_to_ctx_map() {
2996        let mut blueprint = bp(step("echo", path("$.in"), path("$.out")), vec![]);
2997        blueprint.metas = vec![
2998            MetaDef {
2999                name: "heavy-scan".to_string(),
3000                ctx: json!({ "work_dir": "/x" }),
3001            },
3002            MetaDef {
3003                name: "light-scan".to_string(),
3004                ctx: json!({ "work_dir": "/y" }),
3005            },
3006        ];
3007        let metas = derive_step_metas(&blueprint);
3008        assert_eq!(metas.len(), 2);
3009        assert_eq!(metas.get("heavy-scan"), Some(&json!({ "work_dir": "/x" })));
3010        assert_eq!(metas.get("light-scan"), Some(&json!({ "work_dir": "/y" })));
3011    }
3012
3013    #[test]
3014    fn derive_agent_ctx_meta_ref_resolves_as_base_under_inline_ctx() {
3015        let mut blueprint = bp(
3016            step("echo", path("$.in"), path("$.out")),
3017            vec![agent_with_meta(
3018                "with-meta-ref",
3019                "echo",
3020                AgentMeta {
3021                    ctx: Some(json!({ "work_dir": "/inline-wins" })),
3022                    meta_ref: Some("shared".to_string()),
3023                    ..Default::default()
3024                },
3025            )],
3026        );
3027        blueprint.metas = vec![MetaDef {
3028            name: "shared".to_string(),
3029            ctx: json!({ "work_dir": "/base", "extra": "from-pool" }),
3030        }];
3031        let (_, per_agent) = derive_agent_ctx(&blueprint);
3032        assert_eq!(
3033            per_agent.get("with-meta-ref"),
3034            Some(&json!({ "work_dir": "/inline-wins", "extra": "from-pool" })),
3035            "inline ctx must win the collided key while pool-only keys survive the merge"
3036        );
3037    }
3038
3039    #[test]
3040    fn derive_agent_ctx_meta_ref_alone_uses_pool_ctx_verbatim() {
3041        let mut blueprint = bp(
3042            step("echo", path("$.in"), path("$.out")),
3043            vec![agent_with_meta(
3044                "with-meta-ref-only",
3045                "echo",
3046                AgentMeta {
3047                    meta_ref: Some("shared".to_string()),
3048                    ..Default::default()
3049                },
3050            )],
3051        );
3052        blueprint.metas = vec![MetaDef {
3053            name: "shared".to_string(),
3054            ctx: json!({ "work_dir": "/base" }),
3055        }];
3056        let (_, per_agent) = derive_agent_ctx(&blueprint);
3057        assert_eq!(
3058            per_agent.get("with-meta-ref-only"),
3059            Some(&json!({ "work_dir": "/base" }))
3060        );
3061    }
3062
3063    #[test]
3064    fn derive_agent_ctx_unresolved_meta_ref_never_panics_and_falls_back_to_inline() {
3065        let blueprint = bp(
3066            step("echo", path("$.in"), path("$.out")),
3067            vec![agent_with_meta(
3068                "with-unresolved-meta-ref",
3069                "echo",
3070                AgentMeta {
3071                    ctx: Some(json!({ "work_dir": "/inline-only" })),
3072                    meta_ref: Some("missing".to_string()),
3073                    ..Default::default()
3074                },
3075            )],
3076        );
3077        // No `blueprint.metas` entries at all — `meta_ref` unresolved.
3078        let (_, per_agent) = derive_agent_ctx(&blueprint);
3079        assert_eq!(
3080            per_agent.get("with-unresolved-meta-ref"),
3081            Some(&json!({ "work_dir": "/inline-only" })),
3082            "an unresolved meta_ref must never panic; the agent's own inline ctx still applies"
3083        );
3084    }
3085
3086    // ──────────────────────────────────────────────────────────────────
3087    // GH #46 Milestone 2 Done Criteria #3 (semantics-match): `resolve_runner`
3088    // ──────────────────────────────────────────────────────────────────
3089
3090    /// `resolve_runner` (in `mlua-swarm-schema`) must synthesize the exact
3091    /// same `(variant, tools)` pair `derive_worker_bindings` does today for
3092    /// every agent whose Runner comes solely from the legacy
3093    /// `AgentProfile.worker_binding` fallback (tier 3 of the cascade) — a
3094    /// machine-checked guard against the two paths silently drifting apart
3095    /// once a future change touches one but forgets the other, mirroring
3096    /// `crate::core::explain`'s
3097    /// `explain_agent_ctx_matches_derive_agent_ctx_semantics` drift guard.
3098    /// This is a read-only cross-check: it exercises the schema crate's
3099    /// pure resolver against real Blueprints, without touching the launch
3100    /// path itself (Milestone 3 scope).
3101    #[test]
3102    fn resolve_runner_legacy_fallback_matches_derive_worker_bindings_semantics() {
3103        fn legacy_agent(name: &str, variant: &str, tools: Vec<&str>) -> AgentDef {
3104            AgentDef {
3105                name: name.to_string(),
3106                kind: AgentKind::Operator,
3107                spec: json!({}),
3108                profile: Some(AgentProfile {
3109                    worker_binding: Some(variant.to_string()),
3110                    tools: tools.into_iter().map(str::to_string).collect(),
3111                    ..Default::default()
3112                }),
3113                meta: None,
3114                runner: None,
3115                runner_ref: None,
3116                verdict: None,
3117                lints: None,
3118            }
3119        }
3120
3121        let blueprint = bp(
3122            step("planner", path("$.in"), path("$.out")),
3123            vec![
3124                legacy_agent("planner", "planning-worker", vec!["Read", "Grep"]),
3125                legacy_agent("coder", "code-worker", vec![]),
3126                agent("no-binding", "echo"),
3127            ],
3128        );
3129
3130        let derived = derive_worker_bindings(&blueprint);
3131
3132        for agent_def in &blueprint.agents {
3133            let resolved = resolve_runner(&blueprint, agent_def).expect("no unresolved refs");
3134            match derived.get(&agent_def.name) {
3135                Some(binding) => {
3136                    assert_eq!(
3137                        resolved,
3138                        Some(Runner::WsClaudeCode {
3139                            variant: binding.variant.clone(),
3140                            tools: binding.tools.clone(),
3141                        }),
3142                        "resolve_runner must synthesize the same WsClaudeCode Runner \
3143                         derive_worker_bindings produces for agent '{}'",
3144                        agent_def.name
3145                    );
3146                }
3147                None => {
3148                    assert_eq!(
3149                        resolved, None,
3150                        "agent '{}' has no derive_worker_bindings entry, so resolve_runner \
3151                         must resolve to None too (no other tier declared)",
3152                        agent_def.name
3153                    );
3154                }
3155            }
3156        }
3157    }
3158
3159    #[test]
3160    fn ws_operator_runner_projects_into_the_existing_spawn_binding() {
3161        let mut blueprint = bp(
3162            step("reviewer", path("$.in"), path("$.out")),
3163            vec![agent("reviewer", "echo")],
3164        );
3165        blueprint.agents[0].runner = Some(Runner::WsOperator {
3166            variant: "mse-reviewer".to_string(),
3167            tools: vec!["Read".to_string(), "Grep".to_string()],
3168        });
3169
3170        let derived = derive_worker_bindings(&blueprint);
3171        let binding = derived
3172            .get("reviewer")
3173            .expect("ws_operator must feed the canonical spawn binding path");
3174        assert_eq!(binding.variant, "mse-reviewer");
3175        assert_eq!(binding.tools, ["Read", "Grep"]);
3176    }
3177
3178    // ──────────────────────────────────────────────────────────────────
3179    // D2: replay compat for backfilled Runs (origin drives digest keying)
3180    // ──────────────────────────────────────────────────────────────────
3181
3182    /// Build a single-step `echo` RustFn Blueprint plus a call counter its
3183    /// worker bumps on every real dispatch. A replay HIT never reaches the
3184    /// worker, so the counter is the "was this step actually executed?"
3185    /// probe.
3186    fn counting_echo_service() -> (TaskLaunchService, Arc<std::sync::atomic::AtomicUsize>) {
3187        use std::sync::atomic::{AtomicUsize, Ordering};
3188        let calls = Arc::new(AtomicUsize::new(0));
3189        let counter = calls.clone();
3190        let factory = RustFnInProcessSpawnerFactory::new().register_fn("echo", move |inv| {
3191            let counter = counter.clone();
3192            async move {
3193                counter.fetch_add(1, Ordering::SeqCst);
3194                Ok(WorkerResult {
3195                    value: json!({ "echoed": inv.prompt }),
3196                    ok: true,
3197                    stats: None,
3198                })
3199            }
3200        });
3201        (build_service(factory), calls)
3202    }
3203
3204    async fn seed_legacy_run(run_store: &Arc<dyn crate::store::run::RunStore>) -> crate::RunId {
3205        use crate::store::run::{RunRecord, RunStatus};
3206        use crate::types::TaskId;
3207        let run_id = crate::RunId::new();
3208        run_store
3209            .create(RunRecord {
3210                id: run_id.clone(),
3211                task_id: TaskId::new(),
3212                status: RunStatus::Running,
3213                step_entries: Vec::new(),
3214                degradations: Vec::new(),
3215                operator_sid: None,
3216                current: Default::default(),
3217                next_generation: 0,
3218                result_ref: None,
3219                // No `bound_agents` — a pre-binding-snapshot ("pre-upgrade")
3220                // Run whose resume must backfill.
3221                input_json: Some("{}".to_string()),
3222                created_at: 0,
3223                updated_at: 0,
3224            })
3225            .await
3226            .expect("seed legacy RunRecord");
3227        run_id
3228    }
3229
3230    /// [Crux D2 items 4 + 6] A pre-upgrade Run whose replay log was hashed
3231    /// WITHOUT binding digests replays cleanly through the full launch path
3232    /// on resume, and stays consistent across a second resume (the fast path
3233    /// reads the persisted `resume_backfill` origin, so no digests are ever
3234    /// mixed into the replay key).
3235    #[tokio::test]
3236    async fn backfilled_run_replays_legacy_keys_stably_across_two_resumes() {
3237        use crate::store::replay::{InMemoryReplayStore, ReplayCursor, ReplayStore};
3238        use crate::store::run::{InMemoryRunStore, RunContext, RunStore};
3239        use std::sync::atomic::Ordering;
3240        use std::sync::Mutex;
3241
3242        let (svc, echo_calls) = counting_echo_service();
3243        let blueprint = bp(
3244            step("echo", path("$.input"), path("$.out")),
3245            vec![agent("echo", "echo")],
3246        );
3247        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
3248        let replay_store: Arc<dyn ReplayStore> = Arc::new(InMemoryReplayStore::new());
3249        let run_id = seed_legacy_run(&run_store).await;
3250
3251        // Phase 1 — first resume backfills the snapshot AND, because the
3252        // origin is `resume_backfill`, dispatches with legacy replay keys.
3253        // This is the step that generates the pre-upgrade-shaped replay row.
3254        let rc1 = RunContext::new(run_id.clone(), run_store.clone())
3255            .with_replay_store(replay_store.clone())
3256            .with_resume();
3257        let mut input1 = launch_input(blueprint.clone(), json!({ "input": "hi" }));
3258        input1.run_ctx = Some(rc1);
3259        let out1 = svc.launch(input1).await.expect("phase-1 resume launch ok");
3260        assert_eq!(out1.final_ctx["out"]["echoed"], "hi");
3261        assert_eq!(
3262            echo_calls.load(Ordering::SeqCst),
3263            1,
3264            "phase 1 dispatches the worker once (nothing to replay yet)"
3265        );
3266        let entries = replay_store
3267            .list_by_run(&run_id)
3268            .await
3269            .expect("list replay rows");
3270        assert_eq!(
3271            entries.len(),
3272            1,
3273            "phase 1 must log exactly one legacy-hashed replay row"
3274        );
3275        let run = run_store.get(&run_id).await.expect("run present");
3276        let snap: Value = serde_json::from_str(run.input_json.as_deref().unwrap()).unwrap();
3277        assert_eq!(
3278            SnapshotOrigin::from_snapshot(&snap),
3279            SnapshotOrigin::ResumeBackfill,
3280            "phase 1 must pin the snapshot as resume_backfill"
3281        );
3282
3283        // Phase 2 — second resume. The snapshot now carries bound_agents, so
3284        // load_or_resolve takes the fast path and reads the persisted
3285        // `resume_backfill` origin — digests are again withheld, the legacy
3286        // key matches, and the worker is NOT run a second time.
3287        let cursor = ReplayCursor::from_entries(entries);
3288        let rc2 = RunContext::new(run_id.clone(), run_store.clone())
3289            .with_replay_store(replay_store.clone())
3290            .with_replay_cursor(Arc::new(Mutex::new(cursor)))
3291            .with_resume();
3292        let mut input2 = launch_input(blueprint.clone(), json!({ "input": "hi" }));
3293        input2.run_ctx = Some(rc2);
3294        let out2 = svc.launch(input2).await.expect("phase-2 resume launch ok");
3295        assert_eq!(out2.final_ctx["out"]["echoed"], "hi");
3296        assert_eq!(
3297            echo_calls.load(Ordering::SeqCst),
3298            1,
3299            "phase 2 must REPLAY the legacy-hashed row — the worker must not run again"
3300        );
3301        let run2 = run_store.get(&run_id).await.expect("run present");
3302        let snap2: Value = serde_json::from_str(run2.input_json.as_deref().unwrap()).unwrap();
3303        assert_eq!(
3304            SnapshotOrigin::from_snapshot(&snap2),
3305            SnapshotOrigin::ResumeBackfill,
3306            "origin must stay resume_backfill across resumes (replay key stability)"
3307        );
3308    }
3309
3310    /// [Crux D2 item 5 / D2-a] A `launch`-origin Run mixes binding digests
3311    /// into its replay key, so a legacy-hashed (digest-free) replay row does
3312    /// NOT hit — the worker runs. Proves the fix is per-Run and does not
3313    /// disable digest keying for initial launches.
3314    #[tokio::test]
3315    async fn launch_origin_run_uses_digest_keys_and_misses_legacy_replay_row() {
3316        use crate::store::replay::{InMemoryReplayStore, ReplayCursor, ReplayStore};
3317        use crate::store::run::{InMemoryRunStore, RunContext, RunStore};
3318        use std::sync::atomic::Ordering;
3319        use std::sync::Mutex;
3320
3321        let (svc, echo_calls) = counting_echo_service();
3322        let blueprint = bp(
3323            step("echo", path("$.input"), path("$.out")),
3324            vec![agent("echo", "echo")],
3325        );
3326        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
3327        let replay_store: Arc<dyn ReplayStore> = Arc::new(InMemoryReplayStore::new());
3328
3329        // Produce a legacy-hashed replay row via a backfill (resume) Run.
3330        let backfill_run = seed_legacy_run(&run_store).await;
3331        let rc_bf = RunContext::new(backfill_run.clone(), run_store.clone())
3332            .with_replay_store(replay_store.clone())
3333            .with_resume();
3334        let mut input_bf = launch_input(blueprint.clone(), json!({ "input": "hi" }));
3335        input_bf.run_ctx = Some(rc_bf);
3336        svc.launch(input_bf).await.expect("backfill launch ok");
3337        assert_eq!(echo_calls.load(Ordering::SeqCst), 1);
3338        let legacy_entries = replay_store
3339            .list_by_run(&backfill_run)
3340            .await
3341            .expect("list legacy rows");
3342        assert_eq!(legacy_entries.len(), 1);
3343
3344        // A fresh, `launch`-origin Run (no `with_resume`) fed a cursor built
3345        // from those legacy rows. Its replay key mixes in the binding digest,
3346        // so the legacy (digest-free) key MISSES and the worker runs again.
3347        let launch_run = seed_legacy_run(&run_store).await;
3348        let cursor = ReplayCursor::from_entries(legacy_entries);
3349        let rc_launch = RunContext::new(launch_run.clone(), run_store.clone())
3350            .with_replay_store(replay_store.clone())
3351            .with_replay_cursor(Arc::new(Mutex::new(cursor)));
3352        let mut input_launch = launch_input(blueprint.clone(), json!({ "input": "hi" }));
3353        input_launch.run_ctx = Some(rc_launch);
3354        svc.launch(input_launch)
3355            .await
3356            .expect("launch-origin launch ok");
3357        assert_eq!(
3358            echo_calls.load(Ordering::SeqCst),
3359            2,
3360            "a launch-origin Run keys replay by binding digest, so the \
3361             legacy-hashed row must MISS and the worker must run"
3362        );
3363        let run = run_store.get(&launch_run).await.expect("run present");
3364        let snap: Value = serde_json::from_str(run.input_json.as_deref().unwrap()).unwrap();
3365        assert_eq!(SnapshotOrigin::from_snapshot(&snap), SnapshotOrigin::Launch);
3366    }
3367
3368    // ──────────────────────────────────────────────────────────────────
3369    // GH #76 error surface: TaskLaunchError::FlowEval struct variant + partial_ctx
3370    // ──────────────────────────────────────────────────────────────────
3371
3372    /// The tuple → struct variant swap must keep the Display prefix
3373    /// (`"flow eval: <msg>"`) byte-for-byte, so callers that only match on
3374    /// the stringified error keep working.
3375    #[test]
3376    fn task_launch_error_flow_eval_struct_variant_display_preserves_prefix() {
3377        let err = TaskLaunchError::FlowEval {
3378            message: "dispatcher error at ref foo".to_string(),
3379            failed_step: Some("foo".to_string()),
3380            verdict_value: Some(json!({"verdict": "BLOCKED"})),
3381            partial_ctx: Some(json!({"steps": {}})),
3382        };
3383        assert_eq!(err.to_string(), "flow eval: dispatcher error at ref foo");
3384
3385        // All-`None` shape (upstream flow-ir eval error before dispatch)
3386        // must render identically to the previous tuple form for the same
3387        // message.
3388        let err_bare = TaskLaunchError::FlowEval {
3389            message: "unresolved extern".to_string(),
3390            failed_step: None,
3391            verdict_value: None,
3392            partial_ctx: None,
3393        };
3394        assert_eq!(err_bare.to_string(), "flow eval: unresolved extern");
3395    }
3396
3397    /// End-to-end via `TaskLaunchService::launch`: a `WorkerResult { ok: false }`
3398    /// step drives the dispatcher's Blocked arm, which writes the
3399    /// `RunContext.last_failure` breadcrumb. The map_err closure lifts it
3400    /// into `TaskLaunchError::FlowEval { failed_step, verdict_value, .. }`.
3401    #[tokio::test]
3402    async fn task_launch_flow_eval_error_carries_failed_step_and_verdict_value() {
3403        use crate::store::run::{InMemoryRunStore, RunContext, RunRecord, RunStatus, RunStore};
3404        use crate::types::{RunId, TaskId};
3405
3406        let factory = RustFnInProcessSpawnerFactory::new().register_fn("gate", |_inv| async move {
3407            Ok(WorkerResult {
3408                value: json!({ "verdict": "BLOCKED", "reason": "not applicable" }),
3409                ok: false,
3410                stats: None,
3411            })
3412        });
3413        let svc = build_service(factory);
3414        let blueprint = bp(
3415            step("gate", path("$.input"), path("$.out")),
3416            vec![agent("gate", "gate")],
3417        );
3418
3419        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
3420        let run_id = RunId::new();
3421        run_store
3422            .create(RunRecord {
3423                id: run_id.clone(),
3424                task_id: TaskId::new(),
3425                status: RunStatus::Running,
3426                step_entries: Vec::new(),
3427                degradations: Vec::new(),
3428                operator_sid: None,
3429                current: Default::default(),
3430                next_generation: 0,
3431                result_ref: None,
3432                input_json: Some("{}".to_string()),
3433                created_at: 0,
3434                updated_at: 0,
3435            })
3436            .await
3437            .expect("seed RunRecord");
3438
3439        let mut input = launch_input(blueprint, json!({ "input": "hi" }));
3440        input.run_ctx = Some(RunContext::new(run_id, run_store));
3441
3442        let err = svc.launch(input).await.expect_err("expected FlowEval");
3443        match err {
3444            TaskLaunchError::FlowEval {
3445                message,
3446                failed_step,
3447                verdict_value,
3448                partial_ctx,
3449            } => {
3450                assert!(
3451                    message.contains("blocked"),
3452                    "expected message to mention blocked, got: {message}"
3453                );
3454                assert_eq!(
3455                    failed_step,
3456                    Some("gate".to_string()),
3457                    "failed_step should be the Blueprint step ref, not the opaque StepId"
3458                );
3459                let vv = verdict_value.expect("verdict_value must be Some for Blocked");
3460                assert_eq!(vv["verdict"], "BLOCKED");
3461                assert_eq!(vv["reason"], "not applicable");
3462                // With a RunContext supplied, partial_ctx is always Some
3463                // (may be an empty steps map if no step_entry was appended
3464                // yet, but the reconstruction ran).
3465                assert!(
3466                    partial_ctx.is_some(),
3467                    "partial_ctx must be Some when a RunContext was supplied"
3468                );
3469            }
3470            other => panic!("expected FlowEval, got {other:?}"),
3471        }
3472    }
3473
3474    /// 3-stage chain, stage 2 blocks. The reconstructed `partial_ctx` from
3475    /// the run_store's step-entry log must include the stage 1 (passed)
3476    /// entry AND the stage 2 (blocked) entry — proving that the
3477    /// dispatcher's step-entry writes are visible to the eval-boundary
3478    /// snapshot regardless of subsequent abort.
3479    #[tokio::test]
3480    async fn task_launch_flow_eval_error_partial_ctx_reconstructs_from_run_store() {
3481        use crate::store::run::{InMemoryRunStore, RunContext, RunRecord, RunStatus, RunStore};
3482        use crate::types::{RunId, TaskId};
3483
3484        let factory = RustFnInProcessSpawnerFactory::new()
3485            .register_fn("upper", |inv| async move {
3486                Ok(WorkerResult {
3487                    value: json!(inv.prompt.to_uppercase()),
3488                    ok: true,
3489                    stats: None,
3490                })
3491            })
3492            .register_fn("gate", |_inv| async move {
3493                Ok(WorkerResult {
3494                    value: json!({ "verdict": "BLOCKED" }),
3495                    ok: false,
3496                    stats: None,
3497                })
3498            })
3499            .register_fn("never", |inv| async move {
3500                Ok(WorkerResult {
3501                    value: json!(inv.prompt),
3502                    ok: true,
3503                    stats: None,
3504                })
3505            });
3506        let svc = build_service(factory);
3507        let flow = FlowNode::Seq {
3508            children: vec![
3509                step("upper", path("$.in"), path("$.s1")),
3510                step("gate", path("$.s1"), path("$.s2")),
3511                step("never", path("$.s2"), path("$.s3")),
3512            ],
3513        };
3514        let blueprint = bp(
3515            flow,
3516            vec![
3517                agent("upper", "upper"),
3518                agent("gate", "gate"),
3519                agent("never", "never"),
3520            ],
3521        );
3522
3523        let run_store: Arc<dyn RunStore> = Arc::new(InMemoryRunStore::new());
3524        let run_id = RunId::new();
3525        run_store
3526            .create(RunRecord {
3527                id: run_id.clone(),
3528                task_id: TaskId::new(),
3529                status: RunStatus::Running,
3530                step_entries: Vec::new(),
3531                degradations: Vec::new(),
3532                operator_sid: None,
3533                current: Default::default(),
3534                next_generation: 0,
3535                result_ref: None,
3536                input_json: Some("{}".to_string()),
3537                created_at: 0,
3538                updated_at: 0,
3539            })
3540            .await
3541            .expect("seed RunRecord");
3542
3543        let mut input = launch_input(blueprint, json!({ "in": "hi" }));
3544        input.run_ctx = Some(RunContext::new(run_id.clone(), run_store.clone()));
3545
3546        let err = svc.launch(input).await.expect_err("expected FlowEval");
3547        let partial_ctx = match err {
3548            TaskLaunchError::FlowEval { partial_ctx, .. } => {
3549                partial_ctx.expect("partial_ctx must be Some")
3550            }
3551            other => panic!("expected FlowEval, got {other:?}"),
3552        };
3553        let steps = partial_ctx
3554            .get("steps")
3555            .and_then(|v| v.as_object())
3556            .expect("partial_ctx.steps object");
3557        // stage 1 (upper) passed + stage 2 (gate) blocked: two entries.
3558        // stage 3 (never) is never dispatched because flow-ir stops after
3559        // the Blocked arm's `EvalError::DispatcherError`.
3560        assert_eq!(
3561            steps.len(),
3562            2,
3563            "expected 2 step_entries (upper passed + gate blocked), got: {steps:?}"
3564        );
3565        let mut status_by_ref: HashMap<String, String> = HashMap::new();
3566        for (_step_id, entry) in steps {
3567            let step_ref = entry
3568                .get("step_ref")
3569                .and_then(|v| v.as_str())
3570                .expect("step_ref present")
3571                .to_string();
3572            let status = entry
3573                .get("status")
3574                .and_then(|v| v.as_str())
3575                .expect("status present")
3576                .to_string();
3577            status_by_ref.insert(step_ref, status);
3578        }
3579        assert_eq!(
3580            status_by_ref.get("upper").map(String::as_str),
3581            Some("passed")
3582        );
3583        assert_eq!(
3584            status_by_ref.get("gate").map(String::as_str),
3585            Some("blocked")
3586        );
3587        assert!(
3588            !status_by_ref.contains_key("never"),
3589            "step 'never' must not appear — flow-ir stops dispatching after Blocked abort"
3590        );
3591    }
3592
3593    /// When `TaskLaunchService::launch` is called WITHOUT a `RunContext`
3594    /// (the legacy path), the map_err closure must still return a
3595    /// well-formed `FlowEval` — every new field is `None` because there is
3596    /// no breadcrumb source nor snapshot source. Regression test for the
3597    /// null-object path.
3598    #[tokio::test]
3599    async fn task_launch_flow_eval_error_without_run_ctx_has_none_fields() {
3600        let factory = RustFnInProcessSpawnerFactory::new().register_fn("gate", |_inv| async move {
3601            Ok(WorkerResult {
3602                value: json!({ "verdict": "BLOCKED" }),
3603                ok: false,
3604                stats: None,
3605            })
3606        });
3607        let svc = build_service(factory);
3608        let blueprint = bp(
3609            step("gate", path("$.input"), path("$.out")),
3610            vec![agent("gate", "gate")],
3611        );
3612        let err = svc
3613            .launch(launch_input(blueprint, json!({ "input": "hi" })))
3614            .await
3615            .expect_err("expected FlowEval");
3616        match err {
3617            TaskLaunchError::FlowEval {
3618                failed_step,
3619                verdict_value,
3620                partial_ctx,
3621                ..
3622            } => {
3623                assert_eq!(
3624                    failed_step, None,
3625                    "failed_step must be None without run_ctx"
3626                );
3627                assert_eq!(
3628                    verdict_value, None,
3629                    "verdict_value must be None without run_ctx"
3630                );
3631                assert_eq!(
3632                    partial_ctx, None,
3633                    "partial_ctx must be None without run_ctx"
3634                );
3635            }
3636            other => panic!("expected FlowEval, got {other:?}"),
3637        }
3638    }
3639}