Skip to main content

mlua_swarm_server/
lib.rs

1//! the server lib: axum Router + handler set. Split out as a library so it can
2//! be used from both `main.rs` (CLI) and integration tests.
3//!
4//! # Endpoints
5//!
6//! - `GET /v1/healthz`
7//! - `POST /v1/sessions` / `DELETE /v1/sessions` (= operator attach / detach, Bearer sid)
8//! - `POST /v1/tasks` (= unified Flow-form entry, Operator inject supported;
9//!   `operator_sid` explicitly pins the task to a registered Operator session, S2).
10//!   Also creates a `TaskRecord` + `RunRecord` (issue #13 ID-hierarchy persistence)
11//!   and echoes their ids in the response; see the `tasks` module doc. Always
12//!   synchronous, guarded against hanging (GH #33) by a readiness precheck
13//!   (`503` when the launch resolves to an operator-delegate path with zero
14//!   attached operators) and a `tokio::time::timeout` ceiling around the
15//!   dispatch await (`504` on expiry) — see `run_flow_form`'s doc comment.
16//! - `GET /v1/tasks` — list every persisted `TaskRecord` (newest first).
17//! - `GET /v1/tasks/:id` — a `TaskRecord` plus every `RunRecord` kicked from it.
18//! - `POST /v1/tasks/:id/runs` — re-kick an existing Task (new `RunId`, same
19//!   `blueprint_ref` / `input_ctx`).
20//! - `GET /v1/tasks/:id/runs/:run/steps` / `.../steps/:step` /
21//!   `.../steps/:step/content` — the metadata + content debug plane over a
22//!   Run's step OUTPUT (`:run` accepts `latest` or an explicit `R-<hex>`,
23//!   `projection::McpQueryAdapter`); see the `projection` module doc. This
24//!   is the operator / human-debug counterpart to the Worker axis's
25//!   `context.steps` pointer list on `GET /v1/worker/prompt`
26//!   (`projection-adapter` ST5 — replaces the ST2/ST4 single-value `GET
27//!   /v1/tasks/:id/ctx`).
28//! - `GET /v1/runs/:id` — a single `RunRecord` (its `step_entries` trace included).
29//! - `GET /v1/runs/:id/bindings` — immutable requested/effective AgentProvider
30//!   binding explain for that Run.
31//! - `POST /v1/runs/:id/resume` — resume an `Interrupted` Run under the same `run_id`.
32//! - `POST /v1/runs/:id/rerun-from` — GH #71 Layer A. Rerun a terminal Run from
33//!   a caller-specified step under the same `run_id` (physically truncates the
34//!   replay log at the cut point). See `tasks::run_rerun_from`.
35//! - `POST /v1/operators` / `GET /v1/operators/:sid` / `DELETE /v1/operators/:sid` /
36//!   `GET /v1/operators/:sid/ws` (WS upgrade) — REST-like Operator login flow,
37//!   Bearer-mandatory; the sole WS Operator session route. See `operator_ws::login`
38//!   module doc.
39//!
40//! The Enhance issue axis (`/issues`) lives in the `issues` module; callers merge
41//! `build_issues_router` to integrate it into the same server.
42//!
43//! # The 3 faces of the Operator role (= registered directly on the engine SoT)
44//!
45//! The engine stateless-executor refactor removed the three
46//! `AppState` registries (former `HookRegistry` / `BridgeRegistry` / `OperatorRegistry`);
47//! all registration now goes directly to the engine SoT via
48//! `engine.register_spawn_hook` / `register_senior_bridge` / `register_operator`.
49//! `WSOperatorSession` (in the `operator_ws` module) registers all three traits
50//! simultaneously under a single sid — one WS connection covers all 3 faces of
51//! the Operator role, the canonical pattern.
52//!
53//! # `build_*` family
54//!
55//! - [`build_router`] — minimal entry (= `default_registry()`)
56//! - [`build_router_with`] — caller provides a `SpawnerRegistry` and optional `BlueprintStore`
57//!
58//! The engine should be started with [`default_layer_registry`] (= `Engine::new_with_layers`);
59//! otherwise `Blueprint.spawner_hints` is ignored.
60
61#![warn(missing_docs)]
62
63pub mod binding;
64/// HTTP surface for inspecting/registering Blueprint state (`/v1/blueprints/*`).
65pub mod blueprints;
66/// Server config file support (`~/.mse/config.toml`, CLI > file > default merge).
67pub mod config;
68/// `/v1/data/*` endpoints (v9 Big Response handling, Store-owner direct path).
69pub mod data;
70/// `GET /v1/doctor` — read-only startup config / Store snapshot.
71pub mod doctor;
72/// HTTP surface for the `/v1/enhance/log` axis.
73pub mod enhance_log;
74/// `EnhanceSetting` HTTP CRUD (`/v1/enhance-settings*`).
75pub mod enhance_settings;
76/// HTTP surface for the Enhance issue axis (`/v1/issues*`).
77pub mod issues;
78/// WebSocket Operator Callback IF (`/v1/operators*`).
79pub mod operator_ws;
80/// `GET /v1/tasks/:id/runs/:run/steps*` (the metadata + content debug
81/// plane over a Run's step OUTPUT — `McpQueryAdapter`, a server-side
82/// `mlua_swarm::core::projection::ProjectionAdapter` impl reading through
83/// the Data-plane `OutputStore` with a persisted `RunRecord.result_ref`
84/// fallback). See the module doc for how this relates to
85/// `operator_ws::session`'s in-flight `FileProjectionAdapter` hook and
86/// `worker`'s Worker-axis `context.steps` pointer assembly.
87pub mod projection;
88/// HTTP surface for the Task/Run persistence axis (issue #13 ID hierarchy;
89/// `GET /v1/tasks`, `GET /v1/tasks/:id`, `POST /v1/tasks/:id/runs`,
90/// `GET /v1/runs/:id`). `POST /v1/tasks` itself stays in this module (it is
91/// the entry point `tasks_start` shares with the flow-eval path) — see the
92/// `tasks` module doc for the split rationale.
93pub mod tasks;
94/// `/v1/worker/*` endpoints (SubAgent self-fetch path).
95pub mod worker;
96pub use blueprints::{
97    build_blueprints_router, build_blueprints_router_with_refs, BindingRequirementsResponse,
98};
99pub use enhance_log::build_enhance_log_router;
100pub use enhance_settings::build_enhance_settings_router;
101pub use issues::{build_issues_router, GetIssueResponse, PostIssueRequest, PostIssueResponse};
102pub use operator_ws::{
103    operators_create, operators_delete, operators_delete_by_role, operators_info, operators_list,
104    operators_ws_connect, ClientMsg, OperatorSessionEntry, OperatorsListEntry, OperatorsListResp,
105    ServerMsg, WSOperatorSession,
106};
107pub use projection::{McpQueryAdapter, ProjectionSource, StepList, StepPathQuery, StepSummary};
108pub use tasks::{
109    RunBindingDifference, RunBindingExplainEntry, RunBindingStatus, RunBindingsExplainResponse,
110    RunKickRequest, RunKickResponse, RunResumeResponse, RunStepsResponse, TaskDetailResponse,
111};
112pub use worker::{
113    worker_artifact, worker_prompt, worker_result, ArtifactQuery, DegradationBody, PromptQuery,
114    StatsBody, WorkerResultReq,
115};
116
117use axum::{
118    extract::{DefaultBodyLimit, State},
119    http::{header::AUTHORIZATION, HeaderMap, StatusCode},
120    response::{IntoResponse, Response},
121    routing::{get, post},
122    Json, Router,
123};
124use mlua_swarm::application::{BlueprintRef, TaskApplication, TaskApplicationError};
125use mlua_swarm::blueprint::store::BlueprintStore;
126use mlua_swarm::core::config::CheckPolicy;
127use mlua_swarm::service::{TaskLaunchError, TaskLaunchService};
128use mlua_swarm::store::replay::{InMemoryReplayStore, ReplayStore};
129use mlua_swarm::store::run::{RunContext, RunRecord, RunStatus, RunStore};
130use mlua_swarm::store::task::{TaskRecord, TaskRecordStatus, TaskStore};
131use mlua_swarm::{
132    AgentBlockInProcessSpawnerFactory, CapToken, Compiler, Engine, LayerRegistry,
133    LongHoldMiddleware, LuaInProcessSpawnerFactory, MainAIMiddleware, OperatorDelegateMiddleware,
134    OperatorSpawnerFactory, Role, RunId, RustFnInProcessSpawnerFactory, SeniorEscalationMiddleware,
135    SessionId, SpawnerRegistry, SubprocessProcessSpawnerFactory, TaskId,
136};
137use serde::{Deserialize, Serialize};
138use serde_json::{json, Value};
139use std::collections::HashMap;
140use std::sync::Arc;
141use std::time::Duration;
142use tokio::sync::Mutex;
143
144/// In-memory session map backing `/v1/sessions` attach/detach.
145///
146/// The `sid` handed to the client on this REST path is the token nonce
147/// itself (a bearer secret), so the server never uses it as a map key —
148/// entries are keyed by its fingerprint
149/// (`mlua_swarm::types::token_fingerprint`; issue #14).
150#[derive(Default)]
151pub struct SessionStore {
152    /// Live session tokens keyed by the sid's fingerprint.
153    pub map: HashMap<String, CapToken>,
154}
155
156/// Shared axum handler state for the whole router. Cloned per-request (all
157/// fields are `Arc`/cheap-clone), constructed once in [`build_router_with_ws_factory`].
158#[derive(Clone)]
159pub struct AppState {
160    /// The engine SoT (attach/detach, dispatch, registries).
161    pub engine: Engine,
162    /// Live `/v1/sessions` attach records (Operator/Worker/etc session tokens).
163    pub sessions: Arc<Mutex<SessionStore>>,
164    /// Application used at the task entry to resolve `BlueprintRef`. Without a Store, runs in Inline-only mode.
165    pub task_app: Arc<TaskApplication>,
166    /// When `Some`, on WS connect a new `WSOperatorSession` is automatically registered
167    /// with this factory under the sid name (= a `kind=operator` + `operator_ref=<sid>` AgentDef
168    /// binds to the `WSOperatorSession` backend).
169    /// When `None`, no auto-registration happens; the session is only registered on
170    /// `engine.OperatorRegistry` (= only the `OperatorDelegateMiddleware` path is effective;
171    /// the `OperatorSpawnerFactory` path is dead).
172    pub ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
173    /// Owner of the Store on the Data path (Big Response handling). Added in v9.
174    /// Independent layer — the Engine core and the Domain path (`/v1/worker/result`)
175    /// are not involved.
176    /// Default = `InMemoryOutputStore` (constructed inside `build_router_with_ws_factory`);
177    /// callers can swap in an sqlite/fs backend later (future carry).
178    pub data_store: Arc<dyn mlua_swarm::store::output::OutputStore>,
179    /// Login-flow session store (`POST /v1/operators` mint records). `sid` →
180    /// `OperatorSessionEntry`. This is the sole session store for the WS
181    /// Operator role. See `operator_ws::login` module doc.
182    pub operator_sessions:
183        Arc<Mutex<HashMap<SessionId, Arc<crate::operator_ws::login::OperatorSessionEntry>>>>,
184    /// S1 login-flow roles-exclusivity map. Role name → owning `sid`. Checked
185    /// (and updated) atomically under a single lock in
186    /// `operator_ws::login::operators_create` — a role already present here
187    /// causes `POST /v1/operators` to return `409 CONFLICT`. Entries are
188    /// released on `DELETE /v1/operators/:sid`.
189    pub roles_to_sid: Arc<Mutex<HashMap<String, SessionId>>>,
190    /// Persistence for `Task` records (issue #13 ID-hierarchy work-item
191    /// identity; see `mlua_swarm::store::task` module doc). Default =
192    /// `InMemoryTaskStore` (constructed inside `build_router_full`); callers
193    /// can swap in a `SqliteTaskStore` via the `task_store` argument.
194    pub task_store: Arc<dyn TaskStore>,
195    /// Persistence for `Run` records (one kick of a Task; see
196    /// `mlua_swarm::store::run` module doc). Default = `InMemoryRunStore`;
197    /// callers can swap in a `SqliteRunStore` via the `run_store` argument.
198    pub run_store: Arc<dyn RunStore>,
199    /// Per-run replay log — the Ctx-snapshot + step-output store the engine
200    /// appends to after every completed step (see `mlua_swarm::store::replay`
201    /// module doc). Threaded into `RunContext` at every dispatch site so a
202    /// later restart-equivalent recovery can reconstruct the run. Default =
203    /// `InMemoryReplayStore` (process-volatile); callers can swap in a
204    /// `SqliteReplayStore` via the `replay_store` argument.
205    pub replay_store: Arc<dyn ReplayStore>,
206    /// Per-Run trace stream (the RunTrace rail — see
207    /// `mlua_swarm::store::trace` module doc). A `TraceHandle` bound to
208    /// this store is threaded into `RunContext` at every dispatch site
209    /// (`core.*` events + middleware/worker insertion) and read back via
210    /// `GET /v1/runs/:id/trace`. Default = `InMemoryRunTraceStore`;
211    /// callers can swap in a `SqliteRunTraceStore` (typically sharing
212    /// the `SqliteRunStore` file) via the terminal builder's
213    /// `run_trace_store` argument.
214    pub run_trace_store: Arc<dyn mlua_swarm::store::trace::RunTraceStore>,
215    /// Public HTTP base URL the server is reachable at (e.g.
216    /// `"http://127.0.0.1:7777"`), sourced from the binary at boot time.
217    /// When `Some`, `WSOperatorSession` renders it literally into the
218    /// Spawn `directive`'s `base_url` line so the receiving operator can
219    /// paste the frame into a SubAgent prompt without a `mse_doctor`
220    /// detour (issue #8). `None` preserves the historical fallback
221    /// (a placeholder that points at `mse_doctor`).
222    pub base_url: Option<Arc<str>>,
223    /// Server-wide fallback ceiling (seconds) for the `POST /v1/tasks`
224    /// synchronous launch await (GH #33 Guard 2; see `run_flow_form`'s doc
225    /// comment). Sourced from `config::ResolvedConfig::sync_timeout_secs`.
226    /// A per-request `TaskLaunchRequest.timeout_secs` override, when
227    /// present, takes priority over this value.
228    pub sync_timeout_secs: u64,
229}
230
231/// Minimal entry point: builds a router with [`default_registry`] and no
232/// `BlueprintStore` (Inline-only mode) or `ws_operator_factory`.
233pub fn build_router(engine: Engine) -> Router {
234    build_router_with(engine, default_registry(), None)
235}
236
237/// Default `LayerRegistry` for the server. Hint keys:
238/// - `"main_ai"` → `MainAIMiddleware` (= fires SpawnHook before/after)
239/// - `"senior_escalation"` → `SeniorEscalationMiddleware` (= on `ok=false`, escalates via `SeniorBridge.ask`)
240/// - `"operator_delegate"` → `OperatorDelegateMiddleware` (= when an operator backend is registered, delegates the entire spawn)
241///
242/// Including any of these keys in `Blueprint.spawner_hints.layers` causes them to
243/// be wrapped into a `SpawnerStack` at `service::linker::link` time (= per-launch;
244/// the old `engine.bind` global-state path is retired).
245/// Callers (the engine builder side) receive it via
246/// `Engine::new_with_layers(cfg, mse_server::default_layer_registry())`.
247pub fn default_layer_registry() -> LayerRegistry {
248    default_layer_registry_with(LayerOptions::default())
249}
250
251/// Optional knobs the terminal `default_layer_registry_with` builder
252/// consumes — the only currently-tunable knob is the LongHold threshold.
253#[derive(Debug, Default, Clone, Copy)]
254pub struct LayerOptions {
255    /// When `Some(ms)`, wire [`LongHoldMiddleware`] as a **base layer**
256    /// (applied to every dispatched step) with `default_hold = ms`.
257    /// The layer stays observational: on threshold breach it broadcasts
258    /// `Event::TaskAttemptCompleted { long_hold_warn: true, .. }` and
259    /// (when the dispatcher registered a `TraceHandle` for the step)
260    /// appends a `mw.long_hold_warn` event to the persistent
261    /// `RunTraceStore`. `None` = the layer is not installed — the same
262    /// no-op default the pre-config shape had.
263    pub long_hold_warn_ms: Option<u64>,
264}
265
266/// Variant of [`default_layer_registry`] that also honours per-server
267/// [`LayerOptions`] (currently: the LongHold threshold). Called by
268/// `mse serve` with the resolved config value; every other caller
269/// (tests, in-tree bins that don't tune the LongHold knob) can keep
270/// using the zero-arg [`default_layer_registry`].
271pub fn default_layer_registry_with(options: LayerOptions) -> LayerRegistry {
272    let mut reg = LayerRegistry::new()
273        .with_hint("main_ai", |_engine| Arc::new(MainAIMiddleware::new()))
274        .with_hint("senior_escalation", |_engine| {
275            Arc::new(SeniorEscalationMiddleware::new())
276        })
277        .with_hint("operator_delegate", |_engine| {
278            Arc::new(OperatorDelegateMiddleware::new())
279        });
280    if let Some(ms) = options.long_hold_warn_ms {
281        // Bake the millisecond threshold into the factory closure so it
282        // rides into every per-launch stack build without any per-BP
283        // state. The `Engine::event_tx()` sender is captured at bind
284        // time (fresh per Engine — the factory takes `&Engine`).
285        reg = reg.with_base(move |engine| {
286            Arc::new(LongHoldMiddleware::new(
287                std::time::Duration::from_millis(ms),
288                engine.event_tx(),
289            ))
290        });
291    }
292    reg
293}
294
295/// Build form where the caller supplies a registry and an optional `BlueprintStore`.
296/// The Operator callback path (= external HTTP / WS callers acting as an Operator)
297/// must be pre-registered via `engine.register_*` (= the engine is the SoT).
298/// See the `operator_ws` module doc and `OperatorInfo` (engine-side `ctx.rs`) for details.
299pub fn build_router_with(
300    engine: Engine,
301    registry: SpawnerRegistry,
302    store: Option<Arc<dyn BlueprintStore>>,
303) -> Router {
304    build_router_with_ws_factory(engine, registry, store, None)
305}
306
307/// 4-argument variant of `build_router_with`. Passing `ws_operator_factory = Some(arc)`
308/// causes each WS connect to auto-register a new `WSOperatorSession` under its sid
309/// name with the factory (= a `kind=operator` AgentDef with `operator_ref: <sid>`
310/// can then bind to the WS client backend). Callers are expected to also install
311/// the same `Arc` into the `SpawnerRegistry` via
312/// `reg.register::<OperatorSpawnerFactory>(arc.clone())`.
313pub fn build_router_with_ws_factory(
314    engine: Engine,
315    registry: SpawnerRegistry,
316    store: Option<Arc<dyn BlueprintStore>>,
317    ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
318) -> Router {
319    build_router_with_ws_factory_and_output(engine, registry, store, ws_operator_factory, None)
320}
321
322/// 5-argument variant of [`build_router_with_ws_factory`]. Passing
323/// `output_store = Some(arc)` swaps the default `InMemoryOutputStore` for a
324/// caller-supplied backend (a `SqliteOutputStore`, for instance). `None`
325/// preserves the historical behaviour (fresh in-memory store per call).
326pub fn build_router_with_ws_factory_and_output(
327    engine: Engine,
328    registry: SpawnerRegistry,
329    store: Option<Arc<dyn BlueprintStore>>,
330    ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
331    output_store: Option<Arc<dyn mlua_swarm::store::output::OutputStore>>,
332) -> Router {
333    build_router_full(
334        engine,
335        registry,
336        store,
337        ws_operator_factory,
338        output_store,
339        None,
340        None,
341        None,
342        None,
343        crate::config::default_sync_timeout_secs(),
344    )
345}
346
347// Backend-availability note for the trace rail: `build_router_full`
348// keeps its pre-trace signature (every existing caller gets the
349// in-memory default); a persistent `RunTraceStore` is injected via the
350// terminal `build_router_full_with_legacy_worker_binding_policy`'s
351// `run_trace_store` argument (the CLI `serve` path does this, sharing
352// the `SqliteRunStore` file).
353
354/// 8-argument variant of [`build_router_with_ws_factory_and_output`].
355/// Passing `base_url = Some(...)` (e.g. `"http://127.0.0.1:7777"`) makes
356/// `WSOperatorSession` render the actual server bind into the Spawn
357/// directive's `base_url` line, so the receiving operator can copy the
358/// frame straight into a SubAgent prompt (issue #8). `None` preserves
359/// the historical fallback (`<check with mse_doctor>` placeholder).
360/// `task_store` / `run_store` swap the default `InMemoryTaskStore` /
361/// `InMemoryRunStore` (issue #13 ID-hierarchy persistence) for a
362/// caller-supplied backend (`SqliteTaskStore` / `SqliteRunStore`, for
363/// instance); `None` preserves the process-volatile default.
364/// `sync_timeout_secs` is the server-wide fallback ceiling for the `POST
365/// /v1/tasks` synchronous launch await (GH #33 Guard 2) — see
366/// `AppState::sync_timeout_secs` / `run_flow_form`'s doc comment.
367// This is the terminal builder in the `build_router*` delegation chain
368// (each variant adds one more caller-overridable store/factory); the
369// argument count grows with the number of pluggable backends, not with
370// unrelated responsibilities, so a plain allow is preferable to bundling
371// them into a config struct only this one function would consume.
372#[allow(clippy::too_many_arguments)]
373pub fn build_router_full(
374    engine: Engine,
375    registry: SpawnerRegistry,
376    store: Option<Arc<dyn BlueprintStore>>,
377    ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
378    output_store: Option<Arc<dyn mlua_swarm::store::output::OutputStore>>,
379    base_url: Option<Arc<str>>,
380    task_store: Option<Arc<dyn TaskStore>>,
381    run_store: Option<Arc<dyn RunStore>>,
382    replay_store: Option<Arc<dyn ReplayStore>>,
383    sync_timeout_secs: u64,
384) -> Router {
385    build_router_full_with_legacy_worker_binding_policy(
386        engine,
387        registry,
388        store,
389        ws_operator_factory,
390        output_store,
391        base_url,
392        task_store,
393        run_store,
394        replay_store,
395        None,
396        sync_timeout_secs,
397        mlua_swarm::LegacyWorkerBindingPolicy::Allow,
398    )
399}
400
401/// Full router builder with an explicit migration gate for deprecated
402/// `AgentProfile.worker_binding` Runner fallback. The existing
403/// [`build_router_full`] remains compatibility-defaulted to `Allow`.
404#[allow(clippy::too_many_arguments)]
405pub fn build_router_full_with_legacy_worker_binding_policy(
406    engine: Engine,
407    registry: SpawnerRegistry,
408    store: Option<Arc<dyn BlueprintStore>>,
409    ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
410    output_store: Option<Arc<dyn mlua_swarm::store::output::OutputStore>>,
411    base_url: Option<Arc<str>>,
412    task_store: Option<Arc<dyn TaskStore>>,
413    run_store: Option<Arc<dyn RunStore>>,
414    replay_store: Option<Arc<dyn ReplayStore>>,
415    run_trace_store: Option<Arc<dyn mlua_swarm::store::trace::RunTraceStore>>,
416    sync_timeout_secs: u64,
417    legacy_worker_binding_policy: mlua_swarm::LegacyWorkerBindingPolicy,
418) -> Router {
419    let operator_sessions = Arc::new(Mutex::new(HashMap::new()));
420    let roles_to_sid = Arc::new(Mutex::new(HashMap::new()));
421    let compiler = Compiler::new(registry);
422    let binding_provider = Arc::new(binding::OperatorSessionBindingProvider::new(
423        operator_sessions.clone(),
424        roles_to_sid.clone(),
425    ));
426    let launch = Arc::new(
427        TaskLaunchService::new(engine.clone(), compiler)
428            .with_binding_provider(binding_provider)
429            .with_legacy_worker_binding_policy(legacy_worker_binding_policy),
430    );
431    let task_app = Arc::new(match store {
432        Some(s) => TaskApplication::new(launch, s),
433        None => TaskApplication::new_inline_only(launch),
434    });
435    let data_store: Arc<dyn mlua_swarm::store::output::OutputStore> = match output_store {
436        Some(s) => s,
437        None => Arc::new(mlua_swarm::store::output::InMemoryOutputStore::new()),
438    };
439    // subtask-4 / ST2 rework: wire the SAME `data_store` instance into the
440    // engine's submit-time projection sink (`Engine::submit_output` /
441    // `submit_worker_result_trusted`), so an ordinary worker
442    // `/v1/worker/submit` — not just the explicit `POST /v1/data/emit` —
443    // lands in this store too. `projection::McpQueryAdapter` (`GET
444    // /v1/tasks/:id/runs/:run/steps*`) reads through this same `Arc`,
445    // which is what makes an in-flight run's already-submitted step
446    // OUTPUT queryable.
447    engine.set_output_store(data_store.clone());
448    let task_store: Arc<dyn TaskStore> = match task_store {
449        Some(s) => s,
450        None => Arc::new(mlua_swarm::store::task::InMemoryTaskStore::new()),
451    };
452    let run_store: Arc<dyn RunStore> = match run_store {
453        Some(s) => s,
454        None => Arc::new(mlua_swarm::store::run::InMemoryRunStore::new()),
455    };
456    let replay_store: Arc<dyn ReplayStore> = match replay_store {
457        Some(s) => s,
458        None => Arc::new(InMemoryReplayStore::new()),
459    };
460    let run_trace_store: Arc<dyn mlua_swarm::store::trace::RunTraceStore> = match run_trace_store {
461        Some(s) => s,
462        None => Arc::new(mlua_swarm::store::trace::InMemoryRunTraceStore::new()),
463    };
464    let state = AppState {
465        engine,
466        sessions: Arc::new(Mutex::new(SessionStore::default())),
467        task_app,
468        ws_operator_factory,
469        data_store,
470        operator_sessions,
471        roles_to_sid,
472        task_store,
473        run_store,
474        replay_store,
475        run_trace_store,
476        base_url,
477        sync_timeout_secs,
478    };
479    Router::new()
480        .route("/v1/healthz", get(healthz))
481        .route("/v1/status", get(status_get))
482        // session = collection (POST = attach, DELETE = detach, sid via Authorization)
483        .route(
484            "/v1/sessions",
485            post(sessions_attach).delete(sessions_detach),
486        )
487        // task = flat, single level; authz resolved via Authorization: Bearer <sid>
488        .route("/v1/tasks", post(tasks_start).get(tasks::tasks_list))
489        .route("/v1/tasks/:id", get(tasks::task_get))
490        .route("/v1/tasks/:id/runs", post(tasks::task_rekick))
491        .route("/v1/tasks/:id/runs/:run/steps", get(projection::steps_list))
492        .route(
493            "/v1/tasks/:id/runs/:run/steps/:step",
494            get(projection::step_get),
495        )
496        .route(
497            "/v1/tasks/:id/runs/:run/steps/:step/content",
498            get(projection::step_content),
499        )
500        // Run collection + sub-resources (per-step run stats / trace rail):
501        // `GET /v1/runs` = filtered list, `DELETE /v1/runs/:id` = retention
502        // prune (run row + trace stream together), `:id/steps` = the
503        // terminal per-step stats, `:id/trace` = the TraceEvent stream.
504        .route("/v1/runs", get(tasks::runs_list))
505        .route(
506            "/v1/runs/:id",
507            get(tasks::run_get).delete(tasks::run_delete),
508        )
509        .route("/v1/runs/:id/cancel", post(tasks::run_cancel))
510        .route("/v1/runs/:id/steps", get(tasks::run_steps))
511        .route("/v1/runs/:id/trace", get(tasks::run_trace))
512        .route("/v1/runs/:id/bindings", get(tasks::run_bindings_explain))
513        // Resume an Interrupted Run under the SAME run_id (replay cursor +
514        // stored launch-input snapshot); see `tasks::run_resume`.
515        .route("/v1/runs/:id/resume", post(tasks::run_resume))
516        // Rerun-from-step on a terminal Run under the SAME run_id (physically
517        // truncates the replay log at the cut point); see
518        // `tasks::run_rerun_from` for the full contract (GH #71 Layer A).
519        .route("/v1/runs/:id/rerun-from", post(tasks::run_rerun_from))
520        // REST-like Operator login flow (Bearer-mandatory, roles exclusivity).
521        // Sole WS Operator session route; see `operator_ws::login` module doc.
522        // GH #81 Layer 2: `GET /v1/operators` (list, read-only observability
523        // — no Bearer, same trust tier as `GET /v1/status`) and
524        // `DELETE /v1/operators/by-role/:role` (stale-session recovery
525        // without knowing the sid — same trust tier as
526        // `mlua_swarm_server_shutdown`) close the pre-#81 recovery gap
527        // where a stale session was only clearable via a full server
528        // restart. Order matters: the `by-role` route is declared BEFORE
529        // the `:sid` route so `axum` matches `by-role/:role` as its own
530        // path, not as a `:sid` extract of literal `by-role`.
531        .route("/v1/operators", post(operators_create).get(operators_list))
532        .route("/v1/operators/:sid/ws", get(operators_ws_connect))
533        .route(
534            "/v1/operators/by-role/:role",
535            axum::routing::delete(operators_delete_by_role),
536        )
537        .route(
538            "/v1/operators/:sid",
539            get(operators_info).delete(operators_delete),
540        )
541        // SubAgent self-fetch path (the SubAgent self-fetch design). The SubAgent puts the
542        // CapToken handed over via WS Spawn into Bearer and hits the prompt / result
543        // endpoints directly over HTTP. See the `worker` module doc for details.
544        .route("/v1/worker/prompt", get(worker::worker_prompt))
545        .route("/v1/worker/result", post(worker::worker_result))
546        // Simplified endpoint (= worker POSTs with just token + raw body; task_id is auto-looked-up).
547        // `DefaultBodyLimit::max` is applied explicitly here (and on the sibling
548        // `/v1/worker/artifact` below) — same 2MB axum ships as its implicit
549        // global default, made visible rather than relied on silently.
550        .route(
551            "/v1/worker/submit",
552            post(worker::worker_submit).layer(DefaultBodyLimit::max(2 * 1024 * 1024)),
553        )
554        // GH #36 ST1: named multi-part worker output. A worker stages one
555        // named part per POST here, then completes the attempt with the
556        // ordinary `/v1/worker/submit` above — see the `worker` module doc.
557        .route(
558            "/v1/worker/artifact",
559            post(worker::worker_artifact).layer(DefaultBodyLimit::max(2 * 1024 * 1024)),
560        )
561        // GH #31: `Http`-mode fetch target for `system_ref.uri` (raw baked system
562        // bytes, same Bearer flow as `/v1/worker/prompt`) + live per-agent render-size
563        // lookup for `bp_doctor` (no Bearer, same trust tier as blueprints `get_head`).
564        .route(
565            "/v1/worker/prompt/system",
566            get(worker::worker_prompt_system),
567        )
568        .route(
569            "/v1/agents/:name/render-size",
570            get(worker::agent_render_size),
571        )
572        // GH #32: structured worker degradation reporting — independent channel,
573        // never touches OutputStore / the fold path. See the `worker` module doc.
574        .route("/v1/worker/degradation", post(worker::worker_degradation))
575        .route("/v1/worker/stats", post(worker::worker_stats))
576        // Data path (v9 Big Response handling, independent from Domain / verdict flow)
577        .route("/v1/data/emit", post(data::data_emit))
578        .route(
579            "/v1/data/:key",
580            get(data::data_get).post(data::data_emit_named),
581        )
582        .with_state(state)
583}
584
585/// Default registry = Subprocess + RustFn (baseline `identity` worker pre-baked) + Lua + AgentBlock + empty Operator factory.
586///
587/// `RustFnInProcessSpawnerFactory` gets one baseline entry (`fn_id = "identity"`)
588/// baked in via [`mlua_swarm::worker::baseline::extend_with_baseline`]. This
589/// is the shared bootstrap / smoke worker SoT across each binary (the server / MCP adapter /
590/// one-shot runner) — it structurally replaces the old per-binary inline echo injection.
591///
592/// Usage: default Task path at server startup. If production needs additional
593/// backends, callers bring in a different registry via
594/// `build_router_with(engine, custom_registry)`. The enhance flow
595/// (= patch-spawner / patch-applier / verifier-router / committer axes) uses
596/// [`default_registry_with_enhance_flow`].
597///
598/// The Operator factory is an empty shell with zero registrations (= sids are
599/// dynamically registered per WS connect; see the `operator_ws` module).
600pub fn default_registry() -> SpawnerRegistry {
601    let rustfn_factory =
602        mlua_swarm::worker::baseline::extend_with_baseline(RustFnInProcessSpawnerFactory::new());
603
604    let mut reg = SpawnerRegistry::new();
605    reg.register::<SubprocessProcessSpawnerFactory>(Arc::new(SubprocessProcessSpawnerFactory));
606    reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(rustfn_factory));
607    // Empty `LuaInProcessSpawnerFactory`: no `fn_id` is pre-registered here,
608    // but BP agents can still declare `kind: lua` by carrying an inline
609    // `spec.source` (or a `$file`-expanded Lua chunk). This lets a BP ship
610    // deterministic Lua gates on the vanilla registry, without opting into
611    // the enhance flow. See `LuaInProcessSpawnerFactory` docs for the spec
612    // shape.
613    reg.register::<LuaInProcessSpawnerFactory>(Arc::new(LuaInProcessSpawnerFactory::new()));
614    // GH #86: the stateless AgentBlock factory belongs on the vanilla path
615    // too — every per-agent specialization lives in `AgentDef.spec` /
616    // `.profile` / `.runner`, so registering it here grants no enhance-flow
617    // capability, it only makes the first-class `AgentKind::AgentBlock`
618    // dispatchable. Before this, a BP declaring `kind = "agent_block"`
619    // compiled only under `--enable-enhance-flow`; the enhance branch below
620    // still differs by baking the enhance-flow Lua `fn_id`s.
621    reg.register::<AgentBlockInProcessSpawnerFactory>(Arc::new(
622        AgentBlockInProcessSpawnerFactory::new(),
623    ));
624    reg.register::<OperatorSpawnerFactory>(Arc::new(OperatorSpawnerFactory::new()));
625    reg
626}
627
628/// Opt-in registry that merges [`default_registry`] with the enhance flow
629/// (Lua factory + AgentBlock factory).
630///
631/// Selected via the `the server` CLI flag `--enable-enhance-flow`. The enhance
632/// flow is a separate-axis wrapper: the Lua factory (= 3 Lua workers + 3 primitive
633/// bridges) and the AgentBlock factory (= patch-spawner path, expects
634/// `assets/operator_scripts/blueprint_patch_spawner.lua` + `ANTHROPIC_API_KEY`)
635/// are baked in as pipeline defaults. The baseline RustFn (`identity`) is pre-baked
636/// the same way as in `default_registry`.
637pub fn default_registry_with_enhance_flow() -> SpawnerRegistry {
638    let lua_factory =
639        mlua_swarm::enhance::blueprint::extend_factory(LuaInProcessSpawnerFactory::new());
640    // The Factory is stateless (= 1 process → 1 factory shared by all AgentDefs).
641    // Per-agent specialization (script_path / project_root, etc.) goes through AgentDef.spec.
642    // The enhance-flow patch-spawner is declared literally in agents[].spec of `default_blueprint.yaml`.
643    let agent_block_factory = AgentBlockInProcessSpawnerFactory::new();
644    let rustfn_factory =
645        mlua_swarm::worker::baseline::extend_with_baseline(RustFnInProcessSpawnerFactory::new());
646
647    let mut reg = SpawnerRegistry::new();
648    reg.register::<SubprocessProcessSpawnerFactory>(Arc::new(SubprocessProcessSpawnerFactory));
649    reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(rustfn_factory));
650    reg.register::<LuaInProcessSpawnerFactory>(Arc::new(lua_factory));
651    reg.register::<AgentBlockInProcessSpawnerFactory>(Arc::new(agent_block_factory));
652    reg.register::<OperatorSpawnerFactory>(Arc::new(OperatorSpawnerFactory::new()));
653    reg
654}
655
656// ─── handlers ────────────────────────────────────────────────────────────
657
658async fn healthz() -> &'static str {
659    "ok"
660}
661
662/// Response body for `GET /v1/status` (issue #35 ST4 — lifecycle
663/// occupancy guard). Cheap-to-poll summary of "is it safe to kill this
664/// server right now".
665#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
666pub struct StatusResponse {
667    /// Count of `Run`s currently `Running` (`RunStore::list_running`).
668    /// Degrades to `0` on a store error rather than 500ing — see
669    /// module doc rationale.
670    pub running_runs: usize,
671    /// Count of attached Operator ids (`engine.list_operator_ids()`,
672    /// same idiom as `run_flow_form`'s Guard 1).
673    pub attached_operators: usize,
674}
675
676/// `GET /v1/status`. Infallible summary for the ST4 occupancy guard —
677/// store/engine query failures degrade the corresponding count to `0`
678/// (logged via `tracing::warn!`) rather than 500ing, since this
679/// endpoint may be polled frequently by a lifecycle-check caller that
680/// should not itself become a hang/error surface.
681async fn status_get(State(state): State<AppState>) -> Json<StatusResponse> {
682    let running_runs = state
683        .run_store
684        .list_running()
685        .await
686        .map(|v| v.len())
687        .unwrap_or_else(|e| {
688            tracing::warn!(error = %e, "status_get: list_running failed");
689            0
690        });
691    let attached_operators = state.engine.list_operator_ids().await.len();
692    Json(StatusResponse {
693        running_runs,
694        attached_operators,
695    })
696}
697
698#[derive(Deserialize)]
699struct AttachReq {
700    agent_id: String,
701    role: String,
702    ttl_secs: u64,
703}
704
705#[derive(Serialize)]
706struct AttachResp {
707    session_id: String,
708    role: String,
709}
710
711async fn sessions_attach(
712    State(state): State<AppState>,
713    Json(req): Json<AttachReq>,
714) -> Result<Json<AttachResp>, ApiError> {
715    let role = parse_role(&req.role)?;
716    let token = state
717        .engine
718        .attach(req.agent_id, role, Duration::from_secs(req.ttl_secs))
719        .await
720        .map_err(ApiError::engine)?;
721    // The wire `session_id` stays the nonce (Bearer credential contract);
722    // the server-side map key is its fingerprint (issue #14).
723    let sid = token.nonce.clone();
724    let key = token.fingerprint();
725    state.sessions.lock().await.map.insert(key, token);
726    Ok(Json(AttachResp {
727        session_id: sid,
728        role: req.role,
729    }))
730}
731
732async fn sessions_detach(
733    State(state): State<AppState>,
734    headers: HeaderMap,
735) -> Result<StatusCode, ApiError> {
736    let sid = extract_bearer(&headers)?;
737    let token = take_session_token(&state, &sid).await?;
738    state
739        .engine
740        .detach(&token)
741        .await
742        .map_err(ApiError::engine)?;
743    Ok(StatusCode::NO_CONTENT)
744}
745
746// ─── Unified /v1/tasks schema (= flow-eval path, Operator inject supported) ───────
747
748/// `/v1/tasks` POST schema. Uses the flow-eval path and supports Operator inject
749/// (kind / spawn_hook / senior_bridge). Expressing a one-shot task as a 1-Step
750/// Blueprint is the only correct model.
751///
752/// `pub` (issue #19 ST5) so its `schemars`-derived JSON Schema can be
753/// generated cross-crate by `mlua-swarm-cli`'s `mse://api/http-endpoints`
754/// MCP resource; fields stay module-private (no public field-level API
755/// surface is intended).
756#[derive(Deserialize, schemars::JsonSchema)]
757pub struct TaskLaunchRequest {
758    /// `BlueprintRef` selects Inline (a full Blueprint value) or Id (a
759    /// store lookup). Left opaque here — its own schema nests the full
760    /// `Blueprint` schema (owned by `mse://api/blueprint-schema`), and
761    /// mixing the two into this HTTP-endpoint resource would violate
762    /// their separation of concerns (see the resource's module doc).
763    #[schemars(with = "Value")]
764    blueprint: BlueprintRef,
765    /// flow.ir's initial `ctx` — every `Step.in` `$.<path>` reads from
766    /// here. This field's role is limited to the flow-ir eval seed
767    /// (issue #19); the Task-level execution context lives in the
768    /// sibling top-level fields below (`project_root` / `work_dir` /
769    /// `task_metadata`), promoted out of `init_ctx` to remove the
770    /// prior "free bag nested in free JSON" duplication.
771    ///
772    /// Backward compat: the pre-#19 shape — the same three keys nested
773    /// directly inside this object — is still honored as a fallback
774    /// when the sibling field is absent; see `run_flow_form`'s 2-stage
775    /// resolution and `TaskInputMiddleware::from_init_ctx`.
776    #[schemars(with = "Value")]
777    init_ctx: Value,
778    /// Task-level project root (issue #19 canonical Task IF field —
779    /// promoted out of `init_ctx`). Takes priority over a same-named
780    /// key nested inside `init_ctx` (backward-compat fallback).
781    #[serde(default)]
782    project_root: Option<String>,
783    /// Task-level working directory (issue #19), same priority rule as
784    /// `project_root`.
785    #[serde(default)]
786    work_dir: Option<String>,
787    /// Task-level arbitrary metadata bag (issue #19), same priority
788    /// rule as `project_root`.
789    #[serde(default)]
790    #[schemars(with = "Option<Value>")]
791    task_metadata: Option<Value>,
792    /// TTL in seconds. When unspecified (`None`), falls back in this order:
793    /// (1) `metadata.default_run_ttl_secs` from the resolved BP,
794    /// (2) if absent, the server global `default_run_ttl()` (1800s).
795    #[serde(default)]
796    ttl_secs: Option<u64>,
797    #[serde(default)]
798    operator: Option<OperatorReq>,
799    /// Explicit Operator session sid (or role alias) this task's entire Spawn
800    /// stream should be routed to (runtime Operator match stage 1).
801    ///
802    /// When `Some`, it is validated at request time against
803    /// `state.engine.list_operator_ids()` (the live `engine.operators`
804    /// registry key set): an unknown/never-registered id returns `400`
805    /// immediately — this is a deliberate hard-fail, in contrast to
806    /// `OperatorDelegateWrapped::spawn`, which silently falls through to
807    /// `inner.spawn` on a registry miss. A sid that *was* registered but has
808    /// since disconnected (WS `tx` cleared, session entry retained for
809    /// reconnect) passes this check and surfaces as an explicit dispatch-time
810    /// error instead (`WSOperatorSession::send_and_await` returns `Err` when
811    /// `tx` is `None`), which also propagates as a request failure rather
812    /// than a silent fallback.
813    ///
814    /// On success this value **overrides** `operator.operator_backend_id`
815    /// (last-write-wins, `operator_sid` takes priority) before the flow is
816    /// dispatched — see `run_flow_form`. Dispatch still only delegates if the
817    /// Blueprint opts into `spawner_hints.layers = ["operator_delegate"]`
818    /// (unchanged precondition, same as the existing `operator_backend_id`
819    /// field).
820    ///
821    /// The field also pins the **AgentSpec axis** (the per-agent
822    /// `spec.operator_ref` route every Blueprint with `kind = Operator`
823    /// agents uses, whether or not it declares the delegate layer):
824    /// `TaskApplicationInput.operator_pin` carries the sid down to the
825    /// compiler, which resolves those agents against the pinned session
826    /// instead of the role's current process-global holder, and to the
827    /// binding provider, which attests their manifests through the same
828    /// session. Blueprints keep declaring the logical role; which session
829    /// that role means for this run becomes a launch-time fact, recorded on
830    /// `RunRecord.operator_sid`. A pin naming no live session fails the
831    /// launch — there is no fallback to the role, because that fallback is
832    /// exactly how a run ends up on another driver's session.
833    ///
834    /// When unset, behavior is unchanged: whatever
835    /// `operator.operator_backend_id` / BP-level `operator_ref` alias
836    /// resolution already does still applies.
837    #[serde(default)]
838    operator_sid: Option<String>,
839    /// Per-request override for the sync launch's timeout ceiling (GH #33
840    /// Guard 2, see `run_flow_form`'s doc comment). `None` (the default;
841    /// existing clients are unaffected) falls back to
842    /// `AppState::sync_timeout_secs` (server config), then the built-in
843    /// default (300s). `Some(0)` is rejected with `400` — omit the field
844    /// to defer to the server default rather than sending an explicit
845    /// zero.
846    #[serde(default)]
847    timeout_secs: Option<u64>,
848    /// Human-facing description of the work item (e.g. "resolve issue #10"),
849    /// stashed verbatim into the minted `TaskRecord.goal`. Omitted / `None`
850    /// stores an empty string — the flow-eval path itself never reads it.
851    #[serde(default)]
852    goal: Option<String>,
853    /// The "launch request" tier (tier 1, highest
854    /// priority) of the `check_policy` cascade
855    /// (`launch request > blueprint > server config`). `None` (the default;
856    /// existing clients are unaffected) leaves the tier unspecified so the
857    /// Blueprint-declared `check_policy` and, failing that, the server-wide
858    /// `EngineCfg.check_policy` default decide. Wire form is snake_case
859    /// (`"silent"` / `"warn"` / `"strict"`). Threaded verbatim into
860    /// `TaskApplicationInput.check_policy`.
861    #[serde(default)]
862    check_policy: Option<CheckPolicy>,
863    /// GH #37: opt into the detached (asynchronous) launch. `false` (the
864    /// default; existing clients are unaffected) keeps the synchronous
865    /// launch: the handler drives the flow eval inline and returns the
866    /// `final_ctx` on completion. `true` spawns the flow eval as a
867    /// detached background task and returns `202 Accepted` immediately
868    /// with `{task_id, run_id, status: "running"}` (`final_ctx` is
869    /// `null`) — the run's only lifetime bound is `ttl_secs`, and its
870    /// outcome is observed via `GET /v1/runs/:id` (or the `swarm_status`
871    /// MCP tool). Mutually exclusive with `timeout_secs` (the sync-launch
872    /// ceiling has no meaning for a detached run; combining them is a
873    /// `400`).
874    #[serde(default)]
875    detach: bool,
876}
877
878/// Operator inject sub-schema of [`TaskLaunchRequest`] (`kind` / `id` /
879/// `spawn_hook_id` / `senior_bridge_id` / `operator_backend_id` /
880/// `per_agent_kinds`). `pub` for the same cross-crate schema-generation
881/// reason as `TaskLaunchRequest`.
882#[derive(Deserialize, Default, schemars::JsonSchema)]
883pub struct OperatorReq {
884    /// `main_ai` / `automate` / `composite`. This is the "Runtime Global"
885    /// tier of the 4-tier `OperatorKind` cascade (see `mlua_swarm
886    /// ::ctx::collapse_operator_kind`); when unspecified, falls through to
887    /// the BP-level tiers (`OperatorDef.kind` / `Blueprint
888    /// .default_operator_kind`) instead of eagerly defaulting to `automate`.
889    #[serde(default)]
890    kind: Option<String>,
891    /// Operator id at attach time (= sessions tracking key in the EventLog); unspecified defaults to `"http-run"`.
892    #[serde(default)]
893    id: Option<String>,
894    /// Name of a hook pre-registered via `engine.register_spawn_hook`; `None` if unspecified.
895    #[serde(default)]
896    spawn_hook_id: Option<String>,
897    /// Name of a bridge pre-registered via `engine.register_senior_bridge`; `None` if unspecified.
898    #[serde(default)]
899    senior_bridge_id: Option<String>,
900    /// Name of an Operator backend pre-registered via `engine.register_operator`
901    /// (= the path that delegates the entire spawn to an external Operator);
902    /// `None` if unspecified. When `kind == MainAi/Composite` and this id is `Some`,
903    /// `OperatorDelegateMiddleware` bypasses `inner.spawn` and calls `operator.execute` instead.
904    /// This is a different axis from `operator.id` (= session tracking label);
905    /// `operator_backend_id` is the registry lookup key.
906    #[serde(default)]
907    operator_backend_id: Option<String>,
908    /// "Runtime Agent-level" tier (highest priority) of the `OperatorKind`
909    /// cascade — per-agent override, keyed by `AgentDef.name`, value is
910    /// `main_ai` / `automate` / `composite` (same parsing as `kind`).
911    /// `None` / absent means no per-agent override.
912    #[serde(default)]
913    per_agent_kinds: Option<HashMap<String, String>>,
914}
915
916/// Parse a wire-level kind string (`"main_ai"` / `"automate"` / `"composite"`)
917/// into `OperatorKind`. Shared by `OperatorReq.kind` and
918/// `OperatorReq.per_agent_kinds` values.
919fn parse_operator_kind_str(s: &str) -> Result<mlua_swarm::OperatorKind, ApiError> {
920    use mlua_swarm::OperatorKind;
921    match s {
922        "main_ai" => Ok(OperatorKind::MainAi),
923        "composite" => Ok(OperatorKind::Composite),
924        "automate" => Ok(OperatorKind::Automate),
925        other => Err(ApiError::bad_request(format!(
926            "operator kind: unknown value '{other}' (expected main_ai|automate|composite)"
927        ))),
928    }
929}
930
931/// `/v1/tasks` POST response body. `pub` for the same cross-crate
932/// schema-generation reason as [`TaskLaunchRequest`].
933#[derive(Serialize, schemars::JsonSchema)]
934pub struct TaskLaunchResponse {
935    /// The final flow.ir `ctx` after every `Step.out` has been written.
936    #[schemars(with = "Value")]
937    final_ctx: Value,
938    /// Debug-formatted `BlueprintVersion` the run resolved against, when
939    /// the Blueprint came from a store lookup (`None` for `Inline` refs).
940    bound_version: Option<String>,
941    /// Resolved TTL (seconds) actually applied to the run. Exposes the
942    /// 3-layer cascade (request body → BP metadata → server default) so
943    /// clients can verify which value took effect without re-deriving it.
944    effective_ttl_secs: u64,
945    /// Which layer of the TTL cascade won.
946    ttl_source: TtlSource,
947    /// The `TaskRecord` minted for this request (issue #13 ID-hierarchy
948    /// persistence). `GET /v1/tasks/:id` re-fetches it; `POST
949    /// /v1/tasks/:id/runs` re-kicks it under a fresh `RunId`.
950    #[schemars(with = "String")]
951    task_id: TaskId,
952    /// The `RunRecord` minted for this specific kick. `GET /v1/runs/:id`
953    /// re-fetches it (`step_entries` included).
954    #[schemars(with = "String")]
955    run_id: RunId,
956    /// Launch outcome at response time (GH #37). The synchronous path
957    /// (default) reports `done` — the flow eval completed before this
958    /// response was built. A detached launch (`detach: true`) reports
959    /// `running` — the eval continues in the background; poll `GET
960    /// /v1/runs/:id` for the terminal status and result.
961    status: RunStatus,
962}
963
964/// `tasks_start`'s reply — a [`TaskLaunchResponse`] plus the HTTP status
965/// it rides out on (`200 OK` for the synchronous path, `202 Accepted` for
966/// a detached launch, GH #37). A tuple struct with the body first so
967/// handler-level tests keep their established `.0` access to the response
968/// body regardless of which path produced it.
969pub struct TaskLaunchReply(pub TaskLaunchResponse, pub StatusCode);
970
971impl IntoResponse for TaskLaunchReply {
972    fn into_response(self) -> Response {
973        (self.1, Json(self.0)).into_response()
974    }
975}
976
977/// Which layer of the TTL cascade (request body → BP metadata → server
978/// default) resolved [`TaskLaunchResponse::effective_ttl_secs`]. `pub` for
979/// the same cross-crate schema-generation reason as `TaskLaunchRequest`.
980#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq, schemars::JsonSchema)]
981#[serde(rename_all = "snake_case")]
982pub enum TtlSource {
983    /// The request body's `ttl_secs` was set explicitly.
984    RequestBody,
985    /// The request body omitted `ttl_secs`; the resolved Blueprint's
986    /// `metadata.default_run_ttl_secs` was set.
987    BpMetadata,
988    /// Both the request body and the Blueprint metadata omitted a TTL;
989    /// the server-global `default_run_ttl()` (1800s) applied.
990    ServerDefault,
991}
992
993/// Unified `/v1/tasks` POST entry (= Flow form only).
994/// Runs `Blueprint.flow` to completion via flow eval in a single round-trip.
995/// One-shot tasks are also expressed as a 1-Step Blueprint. Operator
996/// (kind / spawn_hook / senior_bridge) can be injected per request body.
997/// `operator_sid` (S2, runtime Operator match stage 1) additionally
998/// lets the caller pin the task to a specific already-registered Operator
999/// session sid, bypassing BP-level alias lookup — see `TaskLaunchRequest` doc.
1000async fn tasks_start(
1001    State(state): State<AppState>,
1002    Json(req): Json<TaskLaunchRequest>,
1003) -> Result<TaskLaunchReply, ApiError> {
1004    run_flow_form(&state, req).await
1005}
1006
1007/// Flow-form path (= via `TaskApplication::handle_with_run`).
1008/// Core handler behind the `/v1/tasks` entry (`tasks_start`).
1009///
1010/// Engine stateless-executor refactor: the per-request
1011/// sub_engine + 3-registry propagate loop is retired; the startup-built
1012/// `state.task_app` (= a `TaskLaunchService` wrap around `state.engine`) is
1013/// used directly. The Operator callback IF (`spawn_hook_id` /
1014/// `senior_bridge_id` / `operator_backend_id`) is registered on
1015/// `state.engine.register_*` at WS connect time — the engine is the SoT.
1016/// See the `operator_ws` module doc for details.
1017///
1018/// # GH #33 — sync-hang guards
1019///
1020/// This handler is always synchronous end-to-end (no sync/async branch);
1021/// two fail-loud guards keep a bad launch from hanging the HTTP request
1022/// forever:
1023///
1024/// - **Guard 1 (readiness precheck, `503`)**: when the request/BP
1025///   references an operator backend (`operator.operator_backend_id`, set
1026///   directly or via `operator_sid`) and `state.engine.list_operator_ids()`
1027///   is empty, the request fails immediately rather than dispatching into
1028///   a session with nothing attached to serve it. Coarse by design — a
1029///   launch that cannot be cheaply determined to route through an operator
1030///   is never rejected here (Guard 2 still covers the hang in that case).
1031/// - **Guard 2 (sync timeout, `504`)**: the single
1032///   `state.task_app.handle_with_run` await is wrapped in
1033///   `tokio::time::timeout`. Ceiling cascade, highest priority first:
1034///   request `timeout_secs` (rejecting `Some(0)` with `400`), then
1035///   `AppState::sync_timeout_secs` (server config), then the built-in
1036///   default (300s). On expiry the timed-out future is dropped — this
1037///   cancels the in-process flow eval (the flow is abandoned, not
1038///   resumed; intended v1 semantics) — and the Task/Run records are
1039///   best-effort marked `Failed` so they do not stay `Running` forever.
1040///
1041/// # GH #37 — detached launch (`detach: true`)
1042///
1043/// The sync semantics above tie the flow-eval driver's lifetime to this
1044/// request's future — a long-running detached worker that outlives the
1045/// ceiling gets its (individually successful) `/v1/worker/*` submits
1046/// orphaned when the driver is cancelled. `detach: true` decouples them:
1047/// the eval (plus `finalize_run`) runs in a `tokio::spawn`ed background
1048/// task whose only lifetime bound is the resolved `ttl_secs` (marked
1049/// `Failed` on expiry, same best-effort persistence as Guard 2), and the
1050/// handler returns `202 Accepted` with `status: "running"` immediately.
1051/// Guard 1 still applies (checked before any store write); Guard 2's
1052/// ceiling does not (`timeout_secs` + `detach` together is a `400`).
1053/// Client disconnect after the `202` cannot cancel the run.
1054async fn run_flow_form(
1055    state: &AppState,
1056    req: TaskLaunchRequest,
1057) -> Result<TaskLaunchReply, ApiError> {
1058    use mlua_swarm::application::{BlueprintRef as AppBlueprintRef, TaskApplicationInput};
1059    use mlua_swarm::OperatorKind;
1060
1061    // Snapshot everything the TaskRecord needs before `req.blueprint` /
1062    // `req.init_ctx` are moved into the dispatch path below.
1063    let blueprint_ref_json = serde_json::to_value(&req.blueprint)
1064        .map_err(|e| ApiError::bad_request(format!("blueprint snapshot: {e}")))?;
1065    let input_ctx_snapshot = req.init_ctx.clone();
1066    let goal = req.goal.clone().unwrap_or_default();
1067
1068    // issue #19 ST2: resolve the Task-level canonical fields
1069    // (`project_root` / `work_dir` / `task_metadata`) once, at the wire
1070    // boundary. Sibling top-level fields on the request body take
1071    // priority; the pre-#19 shape (same key nested inside `init_ctx`) is
1072    // only a fallback for legacy callers. The result is threaded straight
1073    // through as `TaskApplicationInput.task_input` — `init_ctx` itself is
1074    // NOT mutated, so it stays a pure flow-ir eval seed identical to
1075    // whatever the caller sent.
1076    let task_input_spec = build_task_input_spec_from_request(&req);
1077    // Issue #19 ST4: snapshot the resolved spec into the `TaskRecord` (JSON,
1078    // same "bare `Value`" rationale as `blueprint_ref_json` /
1079    // `input_ctx_snapshot` above) so `POST /v1/tasks/:id/runs` can resolve
1080    // it back out on rekick without re-deriving it from a since-stale
1081    // request body. Cloned rather than computed from `task_input_spec`
1082    // after the fact — the original is still moved into
1083    // `TaskApplicationInput.task_input` below.
1084    let task_input_spec_snapshot = task_input_spec
1085        .clone()
1086        .map(|spec| serde_json::to_value(&spec))
1087        .transpose()
1088        .map_err(|e| ApiError::bad_request(format!("task_input_spec snapshot: {e}")))?;
1089    let init_ctx = req.init_ctx.clone();
1090
1091    let mut op_req = req.operator.unwrap_or_default();
1092
1093    // S2: explicit `operator_sid` override (runtime Operator match stage 1).
1094    // Resolved *before* building `operator_kind` / dispatching so an
1095    // unknown sid fails fast with a 400, never silently falling back to the
1096    // BP-level alias lookup. See `TaskLaunchRequest::operator_sid` doc for the
1097    // disconnected-vs-unknown distinction.
1098    if let Some(sid) = &req.operator_sid {
1099        let known_ids = state.engine.list_operator_ids().await;
1100        if !known_ids.iter().any(|id| id == sid) {
1101            return Err(ApiError::bad_request(format!(
1102                "operator_sid: no such registered operator session '{sid}'"
1103            )));
1104        }
1105        op_req.operator_backend_id = Some(sid.clone());
1106    }
1107
1108    // GH #33 Guard 2 ceiling resolution: request field > server config >
1109    // built-in default (300s, `config::default_sync_timeout_secs`).
1110    // Validated up front — before any TaskRecord/RunRecord side effects —
1111    // so a caller-supplied `Some(0)` fails fast with `400` rather than
1112    // minting records for a launch that was never going to dispatch.
1113    // GH #37: `detach: true` makes the sync ceiling meaningless (the
1114    // detached run is bounded by `ttl_secs` alone) — combining the two
1115    // is rejected here, same fail-fast-before-side-effects ordering.
1116    let detach = req.detach;
1117    let sync_timeout_secs = match (detach, req.timeout_secs) {
1118        (true, Some(_)) => {
1119            return Err(ApiError::bad_request(
1120                "timeout_secs is the synchronous launch ceiling and does not apply to a \
1121                 detached launch (detach: true), whose lifetime bound is ttl_secs — omit \
1122                 timeout_secs"
1123                    .into(),
1124            ));
1125        }
1126        (false, Some(0)) => {
1127            return Err(ApiError::bad_request(
1128                "timeout_secs: 0 is invalid; omit the field to use the server default".into(),
1129            ));
1130        }
1131        (false, Some(v)) => v,
1132        (_, None) => state.sync_timeout_secs,
1133    };
1134
1135    // GH #33 Guard 1: operator readiness precheck. Coarse signal — this
1136    // handler can cheaply see whether the request/BP references an
1137    // operator backend (`operator.operator_backend_id`, set directly or
1138    // resolved above from `operator_sid`), but not the full
1139    // `OperatorDelegateMiddleware` routing decision (that also considers
1140    // BP-level `kind` tiers, resolved only at dispatch time). When a
1141    // backend is referenced and *zero* operators are attached at all,
1142    // fail fast rather than dispatching into a session nothing can serve.
1143    // A launch this coarse check cannot positively identify as
1144    // operator-delegate is never rejected here — Guard 2 (the timeout
1145    // wrap below) still covers the hang in that case.
1146    if let Some(backend_id) = op_req.operator_backend_id.as_deref() {
1147        let attached = state.engine.list_operator_ids().await;
1148        if attached.is_empty() {
1149            return Err(ApiError::unavailable(format!(
1150                "no operator attached to serve this launch (operator backend '{backend_id}' \
1151                 requested): attach an operator via POST /v1/operators + WS, or use the \
1152                 poll-style flow (GET /v1/worker/prompt + POST /v1/worker/submit)"
1153            )));
1154        }
1155    }
1156
1157    // "Runtime Global" tier: `Some(_)` — including `Some(Automate)` — is
1158    // always an explicit request that outranks the BP-level tiers; an
1159    // absent/unset `kind` in the request body stays `None`, leaving the
1160    // BP-level tiers (`OperatorDef.kind` / `Blueprint.default_operator_kind`)
1161    // to decide instead of eagerly defaulting to `Automate`.
1162    let operator_kind = op_req
1163        .kind
1164        .as_deref()
1165        .map(parse_operator_kind_str)
1166        .transpose()?;
1167    let operator_id = op_req.id.unwrap_or_else(|| "http-run".to_string());
1168    // "Runtime Agent-level" tier: per-agent overrides. Absent/empty = no
1169    // override for any agent, letting the BP-level tiers decide per agent.
1170    let mut operator_kind_overrides: HashMap<String, OperatorKind> = HashMap::new();
1171    for (agent, kind_str) in op_req.per_agent_kinds.take().unwrap_or_default() {
1172        operator_kind_overrides.insert(agent, parse_operator_kind_str(&kind_str)?);
1173    }
1174
1175    let blueprint: AppBlueprintRef = match req.blueprint {
1176        AppBlueprintRef::Inline { value } => AppBlueprintRef::Inline { value },
1177        AppBlueprintRef::Id { id, version } => AppBlueprintRef::Id { id, version },
1178    };
1179
1180    // TTL resolution cascade: (1) request body value, (2) BP metadata `default_run_ttl_secs`,
1181    // (3) server global default (`default_run_ttl()`, 1800s).
1182    let (ttl_secs, ttl_source) = match req.ttl_secs {
1183        Some(v) => (v, TtlSource::RequestBody),
1184        None => {
1185            let (resolved_bp, _ver) = state
1186                .task_app
1187                .resolve(&blueprint)
1188                .await
1189                .map_err(|e| ApiError::from_task_resolve(&e, "bp resolve"))?;
1190            match resolved_bp.metadata.default_run_ttl_secs {
1191                Some(v) => (v, TtlSource::BpMetadata),
1192                None => (default_run_ttl(), TtlSource::ServerDefault),
1193            }
1194        }
1195    };
1196
1197    // Build the launch input up front so a snapshot of it can be persisted
1198    // into the RunRecord below — an Interrupted Run is resumed from that
1199    // snapshot (`POST /v1/runs/:id/resume`) under the same run_id.
1200    let input = TaskApplicationInput {
1201        blueprint,
1202        operator_id: operator_id.clone(),
1203        role: Role::Operator,
1204        ttl: Duration::from_secs(ttl_secs),
1205        init_ctx,
1206        operator_kind,
1207        bridge_id: op_req.senior_bridge_id,
1208        hook_id: op_req.spawn_hook_id,
1209        operator_backend_id: op_req.operator_backend_id,
1210        // Axis-independent half of `operator_sid` (see its doc on
1211        // `TaskLaunchRequest`): the same sid binds this launch's AgentSpec
1212        // axis — Operator agents compile against the pinned session and
1213        // their manifests are attested through it — while the field above
1214        // keeps feeding the opt-in delegate layer unchanged.
1215        operator_pin: req.operator_sid.clone(),
1216        operator_kind_overrides,
1217        task_input: task_input_spec,
1218        // The request-body top-level `check_policy` (tier 1)
1219        // flows straight into the cascade resolved once in
1220        // `TaskLaunchService::launch`.
1221        check_policy: req.check_policy,
1222    };
1223    let input_json = Some(tasks::snapshot_launch_input(&input)?);
1224
1225    // issue #13 ID-hierarchy persistence: mint the work-item identity (Task)
1226    // and this kick's identity (Run) *before* dispatching, so a Task/Run
1227    // pair always exists even if the flow itself fails mid-way (the
1228    // Failed-status paths below still have a row to update).
1229    let task_id = TaskId::new();
1230    let run_id = RunId::new();
1231    let now = tasks::now_secs();
1232    state
1233        .task_store
1234        .create(TaskRecord {
1235            id: task_id.clone(),
1236            goal,
1237            blueprint_ref: blueprint_ref_json,
1238            input_ctx: input_ctx_snapshot,
1239            task_input_spec: task_input_spec_snapshot,
1240            status: TaskRecordStatus::Running,
1241            created_at: now,
1242            updated_at: now,
1243        })
1244        .await
1245        .map_err(ApiError::engine)?;
1246    state
1247        .run_store
1248        .create(RunRecord {
1249            id: run_id.clone(),
1250            task_id: task_id.clone(),
1251            status: RunStatus::Running,
1252            step_entries: Vec::new(),
1253            degradations: Vec::new(),
1254            operator_sid: req.operator_sid.clone(),
1255            result_ref: None,
1256            input_json,
1257            created_at: now,
1258            updated_at: now,
1259        })
1260        .await
1261        .map_err(ApiError::engine)?;
1262
1263    let trace =
1264        mlua_swarm::store::trace::TraceHandle::new(run_id.clone(), state.run_trace_store.clone());
1265    trace
1266        .append(
1267            mlua_swarm::store::trace::kind::RUN_STARTED,
1268            None,
1269            None,
1270            json!({"mode": "launch"}),
1271        )
1272        .await;
1273    let run_ctx = RunContext::new(run_id.clone(), state.run_store.clone())
1274        .with_replay_store(state.replay_store.clone())
1275        .with_trace(trace);
1276
1277    // GH #37 detached launch: the eval driver runs in its own spawned
1278    // task — its lifetime is bound to `ttl_secs`, not to this request's
1279    // future (client disconnect / handler completion cannot cancel it).
1280    // The spawned task owns the run to its terminal status: `finalize_run`
1281    // on completion, or the same best-effort `Failed` marking as Guard 2
1282    // if the ttl ceiling expires first.
1283    if detach {
1284        let bg_state = state.clone();
1285        let bg_task_id = task_id.clone();
1286        let bg_run_id = run_id.clone();
1287        // Panic guard (see `tasks::catch_run_panic`): without it a panic in
1288        // the driver unwinds this whole spawned task — timeout combinator
1289        // included — and strands the Run in `Running`.
1290        let guard_state = state.clone();
1291        let guard_task_id = task_id.clone();
1292        let guard_run_id = run_id.clone();
1293        tokio::spawn(async move {
1294            let driver = async move {
1295                let outcome = match tokio::time::timeout(
1296                    Duration::from_secs(ttl_secs),
1297                    bg_state.task_app.handle_with_run(input, Some(run_ctx)),
1298                )
1299                .await
1300                {
1301                    Ok(outcome) => outcome,
1302                    Err(_elapsed) => {
1303                        let reason = json!({
1304                            "error": format!("detached run exceeded {ttl_secs}s ttl ceiling"),
1305                        });
1306                        if let Err(e) = bg_state.run_store.set_result(&bg_run_id, reason).await {
1307                            tracing::warn!(%bg_run_id, error = %e, "run_flow_form: detached ttl set_result failed");
1308                        }
1309                        if let Err(e) = bg_state
1310                            .run_store
1311                            .update_status(&bg_run_id, RunStatus::Failed)
1312                            .await
1313                        {
1314                            tracing::warn!(%bg_run_id, error = %e, "run_flow_form: detached ttl run update_status(Failed) failed");
1315                        }
1316                        if let Err(e) = bg_state
1317                            .task_store
1318                            .update_status(&bg_task_id, TaskRecordStatus::Failed)
1319                            .await
1320                        {
1321                            tracing::warn!(%bg_task_id, error = %e, "run_flow_form: detached ttl task update_status(Failed) failed");
1322                        }
1323                        // This arm never reaches `finalize_run`, so the trace
1324                        // stream gets its terminal marker here.
1325                        mlua_swarm::store::trace::TraceHandle::new(
1326                        bg_run_id.clone(),
1327                        bg_state.run_trace_store.clone(),
1328                    )
1329                    .append(
1330                        mlua_swarm::store::trace::kind::RUN_FINISHED,
1331                        None,
1332                        None,
1333                        json!({ "status": "failed", "reason": format!("ttl {ttl_secs}s exceeded") }),
1334                    )
1335                    .await;
1336                        return;
1337                    }
1338                };
1339                // `finalize_run` persists both the Ok and Err outcomes itself;
1340                // the passthrough return value has no consumer here.
1341                let _ = tasks::finalize_run(&bg_state, &bg_task_id, &bg_run_id, outcome).await;
1342            };
1343            let _ = tasks::catch_run_panic(
1344                &guard_state,
1345                &guard_task_id,
1346                &guard_run_id,
1347                "launch.detach",
1348                driver,
1349            )
1350            .await;
1351        });
1352        return Ok(TaskLaunchReply(
1353            TaskLaunchResponse {
1354                final_ctx: Value::Null,
1355                bound_version: None,
1356                effective_ttl_secs: ttl_secs,
1357                ttl_source,
1358                task_id,
1359                run_id,
1360                status: RunStatus::Running,
1361            },
1362            StatusCode::ACCEPTED,
1363        ));
1364    }
1365
1366    // GH #33 Guard 2: the single await point this handler blocks on. On
1367    // expiry the timed-out future is dropped, cancelling the in-process
1368    // flow eval — the flow is abandoned, not resumed (intended v1
1369    // semantics; stage-granularity resume is a coarser guarantee than
1370    // this handler makes, out of scope here).
1371    //
1372    // Wrapped in the panic guard (`tasks::catch_run_panic`) so a panicking
1373    // driver returns a structured 500 with a resumable `Interrupted` Run
1374    // instead of propagating into the connection task and dropping the
1375    // response mid-request.
1376    let timed = tasks::catch_run_panic(
1377        state,
1378        &task_id,
1379        &run_id,
1380        "launch.sync",
1381        tokio::time::timeout(
1382            Duration::from_secs(sync_timeout_secs),
1383            state.task_app.handle_with_run(input, Some(run_ctx)),
1384        ),
1385    )
1386    .await
1387    .map_err(|msg| {
1388        ApiError::engine(format!(
1389            "run driver panicked: {msg}; the run was marked Interrupted and can be resumed \
1390             via POST /v1/runs/{run_id}/resume"
1391        ))
1392    })?;
1393    let outcome = match timed {
1394        Ok(outcome) => outcome,
1395        Err(_elapsed) => {
1396            // Best effort: mark the Task/Run so they do not stay `Running`
1397            // forever. Reuses the existing `Failed` variant (no new
1398            // schema-crate enum additions) and stashes a reason string
1399            // into `RunRecord.result_ref` — the only free-form field the
1400            // Run schema carries; secondary persistence failures here are
1401            // logged and swallowed, mirroring `tasks::finalize_run`'s
1402            // error-path convention.
1403            let reason = json!({
1404                "error": format!("sync launch exceeded {sync_timeout_secs}s timeout ceiling"),
1405            });
1406            if let Err(e) = state.run_store.set_result(&run_id, reason).await {
1407                tracing::warn!(%run_id, error = %e, "run_flow_form: timeout run set_result failed");
1408            }
1409            if let Err(e) = state
1410                .run_store
1411                .update_status(&run_id, RunStatus::Failed)
1412                .await
1413            {
1414                tracing::warn!(%run_id, error = %e, "run_flow_form: timeout run update_status(Failed) failed");
1415            }
1416            if let Err(e) = state
1417                .task_store
1418                .update_status(&task_id, TaskRecordStatus::Failed)
1419                .await
1420            {
1421                tracing::warn!(%task_id, error = %e, "run_flow_form: timeout task update_status(Failed) failed");
1422            }
1423            return Err(ApiError::timeout(format!(
1424                "sync launch exceeded {sync_timeout_secs}s timeout ceiling: the in-process flow \
1425                 eval was abandoned (dropping the future cancels it); attach an operator that \
1426                 acks promptly (POST /v1/operators + WS), or raise timeout_secs / sync_timeout_secs"
1427            )));
1428        }
1429    };
1430
1431    let out = tasks::finalize_run(state, &task_id, &run_id, outcome)
1432        .await
1433        .map_err(flow_eval_error_to_api_error)?;
1434
1435    Ok(TaskLaunchReply(
1436        TaskLaunchResponse {
1437            final_ctx: out.final_ctx,
1438            bound_version: out.bound_version.map(|v| format!("{:?}", v)),
1439            effective_ttl_secs: ttl_secs,
1440            ttl_source,
1441            task_id,
1442            run_id,
1443            status: RunStatus::Done,
1444        },
1445        StatusCode::OK,
1446    ))
1447}
1448
1449/// issue #19 ST2 direct sibling-field resolver — extracts the three
1450/// Task-level canonical fields (`project_root` / `work_dir` /
1451/// `task_metadata`) once at the wire boundary. Sibling top-level body
1452/// fields take priority; the pre-#19 shape (same key nested inside
1453/// `init_ctx`) is only a fallback for legacy callers. Unlike the ST1
1454/// `resolve_task_level_init_ctx` bridge this replaced, `init_ctx` is
1455/// NOT mutated — the resolved values are handed straight to
1456/// [`mlua_swarm::service::TaskLaunchInput::task_input`], keeping
1457/// `init_ctx` a pure flow-ir eval seed.
1458///
1459/// Returns `None` when all three fields resolve to `None` (no
1460/// middleware is layered onto the spawner stack downstream — the
1461/// [`mlua_swarm::middleware::task_input::TaskInputMiddleware::new_from_fields`]
1462/// contract).
1463fn build_task_input_spec_from_request(
1464    req: &TaskLaunchRequest,
1465) -> Option<mlua_swarm::service::TaskInputSpec> {
1466    let project_root = req.project_root.clone().or_else(|| {
1467        req.init_ctx
1468            .get("project_root")
1469            .and_then(Value::as_str)
1470            .map(String::from)
1471    });
1472    let work_dir = req.work_dir.clone().or_else(|| {
1473        req.init_ctx
1474            .get("work_dir")
1475            .and_then(Value::as_str)
1476            .map(String::from)
1477    });
1478    let task_metadata = req.task_metadata.clone().or_else(|| {
1479        req.init_ctx
1480            .get("task_metadata")
1481            .filter(|v| v.is_object())
1482            .cloned()
1483    });
1484
1485    if project_root.is_none() && work_dir.is_none() && task_metadata.is_none() {
1486        None
1487    } else {
1488        Some(mlua_swarm::service::TaskInputSpec {
1489            project_root,
1490            work_dir,
1491            task_metadata,
1492        })
1493    }
1494}
1495
1496// ─── helpers ─────────────────────────────────────────────────────────────
1497
1498async fn take_session_token(state: &AppState, sid: &str) -> Result<CapToken, ApiError> {
1499    // `sid` on this path is the token nonce itself (a bearer secret), so
1500    // both the map key and the not-found diagnostic use its fingerprint
1501    // (issue #14 — never echo the nonce back in an error body).
1502    let key = mlua_swarm::types::token_fingerprint(sid);
1503    state
1504        .sessions
1505        .lock()
1506        .await
1507        .map
1508        .remove(&key)
1509        .ok_or_else(|| ApiError::not_found(format!("session: fp={key}")))
1510}
1511
1512/// Extracts sid from `Authorization: Bearer <sid>`. Strict — does not accept any other scheme prefix.
1513fn extract_bearer(headers: &HeaderMap) -> Result<String, ApiError> {
1514    let v = headers
1515        .get(AUTHORIZATION)
1516        .ok_or_else(|| ApiError::bad_request("missing Authorization header".into()))?
1517        .to_str()
1518        .map_err(|_| ApiError::bad_request("invalid Authorization header encoding".into()))?;
1519    let sid = v
1520        .strip_prefix("Bearer ")
1521        .ok_or_else(|| ApiError::bad_request("Authorization must be 'Bearer <sid>'".into()))?
1522        .trim();
1523    if sid.is_empty() {
1524        return Err(ApiError::bad_request("Bearer sid is empty".into()));
1525    }
1526    Ok(sid.to_string())
1527}
1528
1529fn parse_role(s: &str) -> Result<Role, ApiError> {
1530    match s.to_ascii_lowercase().as_str() {
1531        "operator" => Ok(Role::Operator),
1532        "worker" => Ok(Role::Worker),
1533        "observer" => Ok(Role::Observer),
1534        "senior" => Ok(Role::Senior),
1535        other => Err(ApiError::bad_request(format!("unknown role: {other}"))),
1536    }
1537}
1538
1539// ─── error type ──────────────────────────────────────────────────────────
1540
1541/// GH #76 error surface: adapter that lifts a [`TaskApplicationError`] into an
1542/// [`ApiError`], surfacing the structured
1543/// [`TaskLaunchError::FlowEval`] fields
1544/// (`failed_step` / `verdict_value` / `partial_ctx`) into the response
1545/// body's `details` object when the abort originated from a Blueprint
1546/// step. Every other error variant collapses to the pre-#76
1547/// `bad_request(format!("run: {e}"))` shape byte-for-byte, so callers
1548/// that only match on the `{"error": message}` message keep working.
1549fn flow_eval_error_to_api_error(e: TaskApplicationError) -> ApiError {
1550    if let TaskApplicationError::Launch(TaskLaunchError::FlowEval {
1551        message,
1552        failed_step,
1553        verdict_value,
1554        partial_ctx,
1555    }) = &e
1556    {
1557        let details = json!({
1558            "failed_step": failed_step,
1559            "verdict_value": verdict_value,
1560            "partial_ctx": partial_ctx,
1561        });
1562        return ApiError::bad_request(format!("run: flow eval: {message}")).with_details(details);
1563    }
1564    ApiError::bad_request(format!("run: {e}"))
1565}
1566
1567/// Uniform error response type for the handlers in this module. Converts to
1568/// a JSON `{"error": message}` body with the given status via [`IntoResponse`].
1569///
1570/// GH #76 error surface: an optional `details` field carries the structured
1571/// [`mlua_swarm::service::TaskLaunchError::FlowEval`] envelope
1572/// (`failed_step` / `verdict_value` / `partial_ctx`) when the abort
1573/// originated from a Blueprint step. When present, the JSON body becomes
1574/// `{"error": message, "details": {...}}` — a pure ADDITIVE schema change
1575/// for consumers that already ignore unknown keys. Absent (the default)
1576/// preserves the pre-#76 `{"error": message}` shape byte-for-byte for
1577/// every other error site.
1578#[derive(Debug)]
1579pub struct ApiError {
1580    status: StatusCode,
1581    message: String,
1582    details: Option<Value>,
1583}
1584
1585impl ApiError {
1586    /// Wraps an engine-side error as `500 Internal Server Error`.
1587    pub fn engine(e: impl std::fmt::Display) -> Self {
1588        Self {
1589            status: StatusCode::INTERNAL_SERVER_ERROR,
1590            message: format!("engine: {e}"),
1591            details: None,
1592        }
1593    }
1594    /// Builds a `404 Not Found` with the given message.
1595    pub fn not_found(m: String) -> Self {
1596        Self {
1597            status: StatusCode::NOT_FOUND,
1598            message: m,
1599            details: None,
1600        }
1601    }
1602    /// Builds a `400 Bad Request` with the given message.
1603    pub fn bad_request(m: String) -> Self {
1604        Self {
1605            status: StatusCode::BAD_REQUEST,
1606            message: m,
1607            details: None,
1608        }
1609    }
1610    /// Builds a `409 Conflict` with the given message (`POST
1611    /// /v1/runs/:id/resume` — the Run is not `Interrupted`, or a concurrent
1612    /// resume already won the `Interrupted -> Running` compare-and-set).
1613    pub fn conflict(m: String) -> Self {
1614        Self {
1615            status: StatusCode::CONFLICT,
1616            message: m,
1617            details: None,
1618        }
1619    }
1620    /// GH #81 Layer 1: map a `TaskApplication::resolve` failure into the
1621    /// same recovery wording the register path already emits when the
1622    /// underlying condition is that the Blueprint is archived. On the
1623    /// archived branch the caller gets a `409 CONFLICT` with the exact
1624    /// hint `blueprint {id} is archived; POST /v1/blueprints/{id}/unarchive
1625    /// first` — byte-identical to `blueprints::seed_blueprint`'s message
1626    /// so downstream tooling can grep either surface. Every other
1627    /// `TaskApplicationError` falls through to the pre-#81 `400 bad
1628    /// request` shape, preserving the launch / rekick error surface for
1629    /// callers that don't distinguish store errors from other resolve
1630    /// failures.
1631    pub fn from_task_resolve(err: &mlua_swarm::TaskApplicationError, prefix: &str) -> Self {
1632        use mlua_swarm::blueprint::store::BlueprintStoreError;
1633        use mlua_swarm::TaskApplicationError as E;
1634        if let E::Store(BlueprintStoreError::Archived(bp_id)) = err {
1635            return Self {
1636                status: StatusCode::CONFLICT,
1637                message: format!(
1638                    "{prefix}: blueprint {bp_id} is archived; \
1639                     POST /v1/blueprints/{bp_id}/unarchive first"
1640                ),
1641                details: None,
1642            };
1643        }
1644        Self::bad_request(format!("{prefix}: {err}"))
1645    }
1646    /// Builds a `503 Service Unavailable` with the given message (GH #33
1647    /// Guard 1 — operator readiness precheck).
1648    pub fn unavailable(m: String) -> Self {
1649        Self {
1650            status: StatusCode::SERVICE_UNAVAILABLE,
1651            message: m,
1652            details: None,
1653        }
1654    }
1655    /// Builds a `504 Gateway Timeout` with the given message (GH #33
1656    /// Guard 2 — sync launch timeout ceiling).
1657    pub fn timeout(m: String) -> Self {
1658        Self {
1659            status: StatusCode::GATEWAY_TIMEOUT,
1660            message: m,
1661            details: None,
1662        }
1663    }
1664    /// Builds a `410 Gone` with the given message (GH #37 — worker
1665    /// submit/artifact addressed at a Run that already reached a terminal
1666    /// status; the silent-`204`-then-orphan alternative is the failure
1667    /// shape this replaces).
1668    pub fn gone(m: String) -> Self {
1669        Self {
1670            status: StatusCode::GONE,
1671            message: m,
1672            details: None,
1673        }
1674    }
1675    /// Builds a `413 Payload Too Large` with the given message (GH #42 —
1676    /// `@file:` sentinel resolves to a file larger than the shared
1677    /// `DefaultBodyLimit`; same size ceiling as the inline body path).
1678    pub fn payload_too_large(m: String) -> Self {
1679        Self {
1680            status: StatusCode::PAYLOAD_TOO_LARGE,
1681            message: m,
1682            details: None,
1683        }
1684    }
1685    /// Builds a `422 Unprocessable Entity` with the given message (GH #50
1686    /// — a `worker_submit` / `worker_artifact` value violates the
1687    /// dispatching agent's declared `VerdictContract`: rejected before it
1688    /// reaches `submit_worker_result_trusted` / `stage_worker_artifact_trusted`,
1689    /// i.e. before it can land in the flow ctx).
1690    pub fn unprocessable(m: impl Into<String>) -> Self {
1691        Self {
1692            status: StatusCode::UNPROCESSABLE_ENTITY,
1693            message: m.into(),
1694            details: None,
1695        }
1696    }
1697    /// GH #76 error surface: attach a structured details payload alongside the
1698    /// string message. Consumed by [`IntoResponse`] to emit
1699    /// `{"error": message, "details": {...}}`. The current sole caller
1700    /// is `run_flow_form`'s `TaskApplicationError::Launch(FlowEval)` arm,
1701    /// which lifts `failed_step` / `verdict_value` / `partial_ctx` out of
1702    /// the structured [`mlua_swarm::service::TaskLaunchError::FlowEval`]
1703    /// variant into this field.
1704    pub fn with_details(mut self, details: Value) -> Self {
1705        self.details = Some(details);
1706        self
1707    }
1708}
1709
1710impl IntoResponse for ApiError {
1711    fn into_response(self) -> Response {
1712        let body = match self.details {
1713            Some(details) => json!({"error": self.message, "details": details}),
1714            None => json!({"error": self.message}),
1715        };
1716        (self.status, Json(body)).into_response()
1717    }
1718}
1719
1720fn default_run_ttl() -> u64 {
1721    // 1800s (= 30 min). Prevents op_token expiry across a flow.ir multi-step chain
1722    // (= 5+ SubAgent dispatches at 30–60s each). Origin: the observed fvloop smoke
1723    // where a post-gate mock-commit dispatch blew past 300s and expired — sibling of worker_token TTL.
1724    1800
1725}
1726
1727/// TTL cascade resolve helper (Blueprint metadata → server default fallback).
1728/// Second-stage fallback, called when the POST `/v1/tasks` body does not set `ttl_secs`.
1729/// (1) If BP metadata `default_run_ttl_secs` is `Some`, use it.
1730/// (2) If `None`, fall back to the server global `default_run_ttl()` (1800s).
1731///
1732/// # Full cascade (combined in `run_flow_form`)
1733///
1734/// - request body `ttl_secs=Some(v)` → v (this helper is not called)
1735/// - request body `None` + metadata `Some(v)` → v
1736/// - request body `None` + metadata `None` → `default_run_ttl()` = 1800s
1737#[cfg(test)]
1738fn resolve_ttl_from_metadata(metadata_ttl: Option<u64>) -> u64 {
1739    metadata_ttl.unwrap_or_else(default_run_ttl)
1740}
1741
1742#[cfg(test)]
1743mod tests {
1744    use super::*;
1745
1746    /// TTL cascade case 1: when the request body sets it, that value is used as-is
1747    /// (upper branch that does not go through the helper; semantic verify of the
1748    /// `Some(v) => v` direct-return path in `run_flow_form`).
1749    #[test]
1750    fn ttl_cascade_request_body_wins_over_metadata() {
1751        let req_ttl: Option<u64> = Some(100);
1752        let metadata_ttl: Option<u64> = Some(3600);
1753        let effective = match req_ttl {
1754            Some(v) => v,
1755            None => resolve_ttl_from_metadata(metadata_ttl),
1756        };
1757        assert_eq!(
1758            effective, 100,
1759            "request body ttl_secs=100 must win over metadata=3600 (cascade priority (1) > (2))"
1760        );
1761    }
1762
1763    /// TTL cascade case 2: request body omitted + BP metadata `Some(N)` → `N` is effective.
1764    #[test]
1765    fn ttl_cascade_metadata_used_when_body_missing() {
1766        let req_ttl: Option<u64> = None;
1767        let metadata_ttl: Option<u64> = Some(3600);
1768        let effective = match req_ttl {
1769            Some(v) => v,
1770            None => resolve_ttl_from_metadata(metadata_ttl),
1771        };
1772        assert_eq!(
1773            effective, 3600,
1774            "body None + metadata=3600 must resolve to 3600 (cascade (2))"
1775        );
1776    }
1777
1778    /// TTL cascade case 3: request body omitted + BP metadata `None` → server default (1800s).
1779    #[test]
1780    fn ttl_cascade_server_default_when_both_missing() {
1781        let req_ttl: Option<u64> = None;
1782        let metadata_ttl: Option<u64> = None;
1783        let effective = match req_ttl {
1784            Some(v) => v,
1785            None => resolve_ttl_from_metadata(metadata_ttl),
1786        };
1787        assert_eq!(
1788            effective,
1789            default_run_ttl(),
1790            "body None + metadata None must fall back to default_run_ttl() = 1800s"
1791        );
1792        assert_eq!(effective, 1800, "default_run_ttl() literal = 1800s");
1793    }
1794
1795    /// Helper unit: metadata `None` → 1800 (server default expansion).
1796    #[test]
1797    fn resolve_ttl_from_metadata_none_returns_server_default() {
1798        assert_eq!(resolve_ttl_from_metadata(None), 1800);
1799    }
1800
1801    /// Helper unit: metadata `Some(N)` → `N` (server default ignored).
1802    #[test]
1803    fn resolve_ttl_from_metadata_some_returns_value() {
1804        assert_eq!(resolve_ttl_from_metadata(Some(7200)), 7200);
1805        assert_eq!(resolve_ttl_from_metadata(Some(60)), 60);
1806    }
1807
1808    // ──────────────────────────────────────────────────────────────────
1809    // `TaskLaunchRequest.check_policy` wire field (T5)
1810    // ──────────────────────────────────────────────────────────────────
1811
1812    /// T5: a `POST /v1/tasks` body carrying a top-level `check_policy`
1813    /// deserializes into `TaskLaunchRequest.check_policy` using the
1814    /// snake_case wire form.
1815    #[test]
1816    fn task_launch_request_parses_check_policy_wire_field() {
1817        let body = json!({
1818            "blueprint": { "kind": "id", "id": "some-bp" },
1819            "init_ctx": {},
1820            "check_policy": "silent",
1821        });
1822        let req: TaskLaunchRequest =
1823            serde_json::from_value(body).expect("request must deserialize");
1824        assert_eq!(req.check_policy, Some(CheckPolicy::Silent));
1825    }
1826
1827    /// A body that omits `check_policy` leaves the field `None` (existing
1828    /// clients are unaffected — `#[serde(default)]`).
1829    #[test]
1830    fn task_launch_request_check_policy_defaults_to_none_when_omitted() {
1831        let body = json!({
1832            "blueprint": { "kind": "id", "id": "some-bp" },
1833            "init_ctx": {},
1834        });
1835        let req: TaskLaunchRequest =
1836            serde_json::from_value(body).expect("request must deserialize");
1837        assert_eq!(req.check_policy, None);
1838    }
1839
1840    // ──────────────────────────────────────────────────────────────────
1841    // issue #19 ST2: `build_task_input_spec_from_request` direct resolver
1842    // ──────────────────────────────────────────────────────────────────
1843
1844    fn task_req(
1845        init_ctx: Value,
1846        project_root: Option<&str>,
1847        work_dir: Option<&str>,
1848        task_metadata: Option<Value>,
1849    ) -> TaskLaunchRequest {
1850        TaskLaunchRequest {
1851            blueprint: BlueprintRef::Id {
1852                id: mlua_swarm::blueprint::store::BlueprintId::new("ut"),
1853                version: Default::default(),
1854            },
1855            init_ctx,
1856            project_root: project_root.map(String::from),
1857            work_dir: work_dir.map(String::from),
1858            task_metadata,
1859            ttl_secs: None,
1860            operator: None,
1861            operator_sid: None,
1862            timeout_secs: None,
1863            goal: None,
1864            detach: false,
1865            check_policy: None,
1866        }
1867    }
1868
1869    /// (a) Sibling fields only — no legacy keys in `init_ctx` — are
1870    /// returned in the `TaskInputSpec` unchanged. `init_ctx` itself is
1871    /// untouched by this resolver (checked separately at the call site).
1872    #[test]
1873    fn build_task_input_spec_from_request_returns_sibling_fields_when_present() {
1874        let req = task_req(
1875            json!({"free": "form"}),
1876            Some("/repo/sibling"),
1877            Some("/repo/sibling/work"),
1878            Some(json!({"issue": 19})),
1879        );
1880        let spec = build_task_input_spec_from_request(&req).expect("spec must be Some");
1881        assert_eq!(spec.project_root.as_deref(), Some("/repo/sibling"));
1882        assert_eq!(spec.work_dir.as_deref(), Some("/repo/sibling/work"));
1883        assert_eq!(spec.task_metadata, Some(json!({"issue": 19})));
1884    }
1885
1886    /// (b) No sibling fields — the pre-#19 shape (same 3 keys nested
1887    /// inside `init_ctx`) is used as the fallback source.
1888    #[test]
1889    fn build_task_input_spec_from_request_falls_back_to_legacy_init_ctx_shape() {
1890        let req = task_req(
1891            json!({
1892                "project_root": "/repo/legacy",
1893                "work_dir": "/repo/legacy/work",
1894                "task_metadata": {"issue": 17},
1895            }),
1896            None,
1897            None,
1898            None,
1899        );
1900        let spec = build_task_input_spec_from_request(&req).expect("spec must be Some");
1901        assert_eq!(spec.project_root.as_deref(), Some("/repo/legacy"));
1902        assert_eq!(spec.work_dir.as_deref(), Some("/repo/legacy/work"));
1903        assert_eq!(spec.task_metadata, Some(json!({"issue": 17})));
1904    }
1905
1906    /// (c) Both present — the sibling field must win over the legacy
1907    /// `init_ctx`-nested value.
1908    #[test]
1909    fn build_task_input_spec_from_request_sibling_wins_over_legacy_shape() {
1910        let req = task_req(
1911            json!({
1912                "project_root": "/repo/legacy",
1913                "work_dir": "/repo/legacy/work",
1914                "task_metadata": {"issue": 17},
1915            }),
1916            Some("/repo/sibling"),
1917            Some("/repo/sibling/work"),
1918            Some(json!({"issue": 19})),
1919        );
1920        let spec = build_task_input_spec_from_request(&req).expect("spec must be Some");
1921        assert_eq!(
1922            spec.project_root.as_deref(),
1923            Some("/repo/sibling"),
1924            "sibling field must win over the legacy init_ctx-nested value"
1925        );
1926        assert_eq!(spec.work_dir.as_deref(), Some("/repo/sibling/work"));
1927        assert_eq!(spec.task_metadata, Some(json!({"issue": 19})));
1928    }
1929
1930    /// (d) All three fields absent from both sibling and legacy shapes —
1931    /// resolver returns `None`, and no middleware is layered downstream.
1932    #[test]
1933    fn build_task_input_spec_from_request_returns_none_when_no_fields_present() {
1934        let req = task_req(json!({"unrelated": "value"}), None, None, None);
1935        assert!(build_task_input_spec_from_request(&req).is_none());
1936    }
1937
1938    /// Minimal `AppState` for the `status_get` handler-fn-direct-call test
1939    /// below — same construction shape as `tasks.rs::test_state()`
1940    /// (mirrors what `build_router_full` does internally, skipping the
1941    /// `Router` wrapper).
1942    fn status_test_state() -> AppState {
1943        let engine = Engine::new(mlua_swarm::EngineCfg::default());
1944        let compiler = mlua_swarm::Compiler::new(default_registry());
1945        let launch = Arc::new(mlua_swarm::TaskLaunchService::new(engine.clone(), compiler));
1946        AppState {
1947            engine,
1948            sessions: Arc::new(Mutex::new(SessionStore::default())),
1949            task_app: Arc::new(mlua_swarm::TaskApplication::new_inline_only(launch)),
1950            ws_operator_factory: None,
1951            data_store: Arc::new(mlua_swarm::store::output::InMemoryOutputStore::new()),
1952            operator_sessions: Arc::new(Mutex::new(HashMap::new())),
1953            roles_to_sid: Arc::new(Mutex::new(HashMap::new())),
1954            task_store: Arc::new(mlua_swarm::store::task::InMemoryTaskStore::new()),
1955            run_store: Arc::new(mlua_swarm::store::run::InMemoryRunStore::new()),
1956            replay_store: Arc::new(mlua_swarm::store::replay::InMemoryReplayStore::new()),
1957            run_trace_store: Arc::new(mlua_swarm::store::trace::InMemoryRunTraceStore::new()),
1958            base_url: None,
1959            sync_timeout_secs: 300,
1960        }
1961    }
1962
1963    /// issue #35 ST4 Acceptance Criteria: `GET /v1/status` reports the
1964    /// count of `Running` `Run`s (`RunStore::list_running`) and attached
1965    /// Operator ids (`engine.list_operator_ids()`), called directly as a
1966    /// handler fn (no `Router` wrapper — this crate's established
1967    /// unit-test convention).
1968    #[tokio::test]
1969    async fn status_get_reports_running_runs_and_operators() {
1970        let state = status_test_state();
1971
1972        let now = std::time::SystemTime::now()
1973            .duration_since(std::time::UNIX_EPOCH)
1974            .map(|d| d.as_secs())
1975            .unwrap_or(0);
1976        state
1977            .run_store
1978            .create(RunRecord {
1979                id: RunId::new(),
1980                task_id: TaskId::new(),
1981                status: RunStatus::Running,
1982                step_entries: Vec::new(),
1983                degradations: Vec::new(),
1984                operator_sid: None,
1985                result_ref: None,
1986                input_json: None,
1987                created_at: now,
1988                updated_at: now,
1989            })
1990            .await
1991            .expect("seed running RunRecord");
1992
1993        // Throwaway `Operator` impl — only registration/list-count matters
1994        // for this test, `execute` is never dispatched (same idiom as
1995        // `tasks.rs::StallingOperator`).
1996        struct NoopOperator;
1997        #[async_trait::async_trait]
1998        impl mlua_swarm::Operator for NoopOperator {
1999            async fn execute(
2000                &self,
2001                _ctx: &mlua_swarm::Ctx,
2002                _system: Option<String>,
2003                _prompt: Value,
2004                _worker: Option<mlua_swarm::WorkerBinding>,
2005                _worker_token: mlua_swarm::CapToken,
2006            ) -> Result<mlua_swarm::WorkerResult, mlua_swarm::WorkerError> {
2007                unimplemented!("not exercised by this test — only registration/list matters")
2008            }
2009        }
2010        state
2011            .engine
2012            .register_operator("test-op", Arc::new(NoopOperator))
2013            .await;
2014
2015        let Json(resp) = status_get(State(state)).await;
2016        assert_eq!(resp.running_runs, 1);
2017        assert_eq!(resp.attached_operators, 1);
2018    }
2019
2020    // ──────────────────────────────────────────────────────────────────
2021    // GH #76 error surface: ApiError.details + flow_eval_error_to_api_error mapper
2022    // ──────────────────────────────────────────────────────────────────
2023
2024    /// `ApiError::with_details` populates the optional `details` field, and
2025    /// [`IntoResponse`] renders it into the JSON body as a sibling of
2026    /// `error`. Pre-#76 shape (no details) stays byte-for-byte
2027    /// `{"error": message}`.
2028    #[tokio::test]
2029    async fn api_error_details_render_into_response_body() {
2030        use axum::body::to_bytes;
2031        use axum::response::IntoResponse;
2032
2033        // Baseline: no details → pre-#76 shape.
2034        let bare = ApiError::bad_request("something".to_string()).into_response();
2035        let (parts, body) = bare.into_parts();
2036        assert_eq!(parts.status, StatusCode::BAD_REQUEST);
2037        let bytes = to_bytes(body, 1024).await.expect("bare body");
2038        let parsed: serde_json::Value = serde_json::from_slice(&bytes).expect("parse bare");
2039        assert_eq!(parsed, json!({"error": "something"}));
2040
2041        // With details → additive `details` key.
2042        let with_details = ApiError::bad_request("run: flow eval: blocked".to_string())
2043            .with_details(json!({
2044                "failed_step": "gate",
2045                "verdict_value": {"verdict": "BLOCKED"},
2046                "partial_ctx": {"steps": {}},
2047            }));
2048        let resp = with_details.into_response();
2049        let (parts, body) = resp.into_parts();
2050        assert_eq!(parts.status, StatusCode::BAD_REQUEST);
2051        let bytes = to_bytes(body, 4096).await.expect("details body");
2052        let parsed: serde_json::Value = serde_json::from_slice(&bytes).expect("parse details");
2053        assert_eq!(parsed["error"], "run: flow eval: blocked");
2054        assert_eq!(parsed["details"]["failed_step"], "gate");
2055        assert_eq!(parsed["details"]["verdict_value"]["verdict"], "BLOCKED");
2056        assert!(parsed["details"]["partial_ctx"].is_object());
2057    }
2058
2059    /// The mapper lifts the structured `TaskLaunchError::FlowEval` fields
2060    /// into `ApiError.details` while preserving the pre-#76 message prefix
2061    /// (`"run: flow eval: <msg>"`). Regression: every other
2062    /// `TaskApplicationError` variant collapses to the pre-#76 shape (no
2063    /// `details`).
2064    #[test]
2065    fn flow_eval_error_to_api_error_lifts_structural_fields_into_details() {
2066        let err = TaskApplicationError::Launch(TaskLaunchError::FlowEval {
2067            message: "blocked: {\"verdict\":\"BLOCKED\"}".to_string(),
2068            failed_step: Some("gate".to_string()),
2069            verdict_value: Some(json!({"verdict": "BLOCKED"})),
2070            partial_ctx: Some(json!({"steps": {}})),
2071        });
2072        let api_err = flow_eval_error_to_api_error(err);
2073        assert_eq!(api_err.status, StatusCode::BAD_REQUEST);
2074        assert!(
2075            api_err.message.starts_with("run: flow eval: "),
2076            "message must preserve pre-#76 `run: flow eval: <msg>` prefix, got: {}",
2077            api_err.message
2078        );
2079        let details = api_err.details.expect("details must be Some for FlowEval");
2080        assert_eq!(details["failed_step"], "gate");
2081        assert_eq!(details["verdict_value"]["verdict"], "BLOCKED");
2082        assert!(details["partial_ctx"].is_object());
2083    }
2084
2085    /// Regression: a non-`FlowEval` error must still map to a `bad_request`
2086    /// without a `details` field — the pre-#76 shape for e.g.
2087    /// `TaskApplicationError::NoStore`.
2088    #[test]
2089    fn flow_eval_error_to_api_error_non_flow_eval_falls_back_to_message_only() {
2090        let api_err = flow_eval_error_to_api_error(TaskApplicationError::NoStore);
2091        assert_eq!(api_err.status, StatusCode::BAD_REQUEST);
2092        assert!(api_err.message.starts_with("run: "));
2093        assert!(
2094            api_err.details.is_none(),
2095            "non-FlowEval errors must not carry a details field (pre-#76 shape)"
2096        );
2097    }
2098
2099    /// A `FlowEval` with every optional field `None` (upstream flow-ir
2100    /// error path — no dispatcher breadcrumb, no run_ctx snapshot) still
2101    /// lifts into `details` — the shape is `null` per key, which serialize
2102    /// as JSON `null`. Consumers must treat missing / `null` as "not
2103    /// available", both are legitimate.
2104    #[test]
2105    fn flow_eval_error_to_api_error_with_all_none_still_populates_details_with_nulls() {
2106        let err = TaskApplicationError::Launch(TaskLaunchError::FlowEval {
2107            message: "unresolved extern".to_string(),
2108            failed_step: None,
2109            verdict_value: None,
2110            partial_ctx: None,
2111        });
2112        let api_err = flow_eval_error_to_api_error(err);
2113        let details = api_err
2114            .details
2115            .expect("details Some even when fields are None");
2116        assert_eq!(details["failed_step"], Value::Null);
2117        assert_eq!(details["verdict_value"], Value::Null);
2118        assert_eq!(details["partial_ctx"], Value::Null);
2119    }
2120
2121    // ─── GH #81 Layer 1: archived-BP guidance on run paths ──────────
2122
2123    #[test]
2124    fn from_task_resolve_archived_maps_to_409_with_unarchive_hint() {
2125        use mlua_swarm::blueprint::store::{BlueprintId, BlueprintStoreError};
2126        use mlua_swarm::TaskApplicationError;
2127        let bp_id = BlueprintId::new("greeter".to_string());
2128        let err = TaskApplicationError::Store(BlueprintStoreError::Archived(bp_id));
2129        let api = ApiError::from_task_resolve(&err, "bp resolve");
2130        assert_eq!(api.status, StatusCode::CONFLICT);
2131        // The wording is byte-identical to the register path
2132        // (`blueprints::seed_blueprint`) so downstream tooling can grep
2133        // either surface.
2134        assert_eq!(
2135            api.message,
2136            "bp resolve: blueprint greeter is archived; \
2137             POST /v1/blueprints/greeter/unarchive first"
2138        );
2139    }
2140
2141    #[test]
2142    fn from_task_resolve_archived_honours_the_caller_supplied_prefix() {
2143        use mlua_swarm::blueprint::store::{BlueprintId, BlueprintStoreError};
2144        use mlua_swarm::TaskApplicationError;
2145        // The rekick site prepends `task {task_id}: ` to distinguish
2146        // rekick failures from launch failures in logs.
2147        let bp_id = BlueprintId::new("scout".to_string());
2148        let err = TaskApplicationError::Store(BlueprintStoreError::Archived(bp_id));
2149        let api = ApiError::from_task_resolve(&err, "task T-abc: bp resolve");
2150        assert_eq!(api.status, StatusCode::CONFLICT);
2151        assert!(api.message.starts_with("task T-abc: bp resolve:"));
2152        assert!(api
2153            .message
2154            .contains("blueprint scout is archived; POST /v1/blueprints/scout/unarchive first"));
2155    }
2156
2157    #[test]
2158    fn from_task_resolve_non_archived_store_error_stays_400() {
2159        // A store IdNotFound → resolve() surfaces
2160        // `TaskApplicationError::Store(BlueprintStoreError::IdNotFound(...))`
2161        // which must remain the pre-#81 400 shape.
2162        use mlua_swarm::blueprint::store::{BlueprintId, BlueprintStoreError};
2163        use mlua_swarm::TaskApplicationError;
2164        let bp_id = BlueprintId::new("no-such".to_string());
2165        let err = TaskApplicationError::Store(BlueprintStoreError::IdNotFound(bp_id));
2166        let api = ApiError::from_task_resolve(&err, "bp resolve");
2167        assert_eq!(api.status, StatusCode::BAD_REQUEST);
2168        assert!(api.message.starts_with("bp resolve:"));
2169    }
2170
2171    #[test]
2172    fn from_task_resolve_no_store_error_stays_400() {
2173        // A non-Store variant (NoStore fires when `BlueprintRef::Id` is
2174        // used against an inline-only TaskApplication) also stays 400.
2175        use mlua_swarm::TaskApplicationError;
2176        let err = TaskApplicationError::NoStore;
2177        let api = ApiError::from_task_resolve(&err, "bp resolve");
2178        assert_eq!(api.status, StatusCode::BAD_REQUEST);
2179    }
2180}