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//! - `POST /v1/operators` / `GET /v1/operators/:sid` / `DELETE /v1/operators/:sid` /
30//!   `GET /v1/operators/:sid/ws` (WS upgrade) — REST-like Operator login flow,
31//!   Bearer-mandatory; the sole WS Operator session route. See `operator_ws::login`
32//!   module doc.
33//!
34//! The Enhance issue axis (`/issues`) lives in the `issues` module; callers merge
35//! `build_issues_router` to integrate it into the same server.
36//!
37//! # The 3 faces of the Operator role (= registered directly on the engine SoT)
38//!
39//! The engine stateless-executor refactor removed the three
40//! `AppState` registries (former `HookRegistry` / `BridgeRegistry` / `OperatorRegistry`);
41//! all registration now goes directly to the engine SoT via
42//! `engine.register_spawn_hook` / `register_senior_bridge` / `register_operator`.
43//! `WSOperatorSession` (in the `operator_ws` module) registers all three traits
44//! simultaneously under a single sid — one WS connection covers all 3 faces of
45//! the Operator role, the canonical pattern.
46//!
47//! # `build_*` family
48//!
49//! - [`build_router`] — minimal entry (= `default_registry()`)
50//! - [`build_router_with`] — caller provides a `SpawnerRegistry` and optional `BlueprintStore`
51//!
52//! The engine should be started with [`default_layer_registry`] (= `Engine::new_with_layers`);
53//! otherwise `Blueprint.spawner_hints` is ignored.
54
55#![warn(missing_docs)]
56
57/// HTTP surface for inspecting/registering Blueprint state (`/v1/blueprints/*`).
58pub mod blueprints;
59/// Server config file support (`~/.mse/config.toml`, CLI > file > default merge).
60pub mod config;
61/// `/v1/data/*` endpoints (v9 Big Response handling, Store-owner direct path).
62pub mod data;
63/// `GET /v1/doctor` — read-only startup config / Store snapshot.
64pub mod doctor;
65/// HTTP surface for the `/v1/enhance/log` axis.
66pub mod enhance_log;
67/// `EnhanceSetting` HTTP CRUD (`/v1/enhance-settings*`).
68pub mod enhance_settings;
69/// HTTP surface for the Enhance issue axis (`/v1/issues*`).
70pub mod issues;
71/// WebSocket Operator Callback IF (`/v1/operators*`).
72pub mod operator_ws;
73/// `GET /v1/tasks/:id/runs/:run/steps*` (the metadata + content debug
74/// plane over a Run's step OUTPUT — `McpQueryAdapter`, a server-side
75/// `mlua_swarm::core::projection::ProjectionAdapter` impl reading through
76/// the Data-plane `OutputStore` with a persisted `RunRecord.result_ref`
77/// fallback). See the module doc for how this relates to
78/// `operator_ws::session`'s in-flight `FileProjectionAdapter` hook and
79/// `worker`'s Worker-axis `context.steps` pointer assembly.
80pub mod projection;
81/// HTTP surface for the Task/Run persistence axis (issue #13 ID hierarchy;
82/// `GET /v1/tasks`, `GET /v1/tasks/:id`, `POST /v1/tasks/:id/runs`,
83/// `GET /v1/runs/:id`). `POST /v1/tasks` itself stays in this module (it is
84/// the entry point `tasks_start` shares with the flow-eval path) — see the
85/// `tasks` module doc for the split rationale.
86pub mod tasks;
87/// `/v1/worker/*` endpoints (SubAgent self-fetch path).
88pub mod worker;
89pub use blueprints::{build_blueprints_router, build_blueprints_router_with_refs};
90pub use enhance_log::build_enhance_log_router;
91pub use enhance_settings::build_enhance_settings_router;
92pub use issues::{build_issues_router, GetIssueResponse, PostIssueRequest, PostIssueResponse};
93pub use operator_ws::{
94    operators_create, operators_delete, operators_info, operators_ws_connect, ClientMsg,
95    OperatorSessionEntry, ServerMsg, WSOperatorSession,
96};
97pub use projection::{McpQueryAdapter, ProjectionSource, StepList, StepPathQuery, StepSummary};
98pub use tasks::{RunKickRequest, RunKickResponse, TaskDetailResponse};
99pub use worker::{
100    worker_artifact, worker_prompt, worker_result, ArtifactQuery, PromptQuery, WorkerResultReq,
101};
102
103use axum::{
104    extract::{DefaultBodyLimit, State},
105    http::{header::AUTHORIZATION, HeaderMap, StatusCode},
106    response::{IntoResponse, Response},
107    routing::{get, post},
108    Json, Router,
109};
110use mlua_swarm::application::{BlueprintRef, TaskApplication};
111use mlua_swarm::blueprint::store::BlueprintStore;
112use mlua_swarm::service::TaskLaunchService;
113use mlua_swarm::store::run::{RunContext, RunRecord, RunStatus, RunStore};
114use mlua_swarm::store::task::{TaskRecord, TaskRecordStatus, TaskStore};
115use mlua_swarm::{
116    CapToken, Compiler, Engine, LayerRegistry, LuaInProcessSpawnerFactory, MainAIMiddleware,
117    OperatorDelegateMiddleware, OperatorSpawnerFactory, Role, RunId, RustFnInProcessSpawnerFactory,
118    SeniorEscalationMiddleware, SessionId, SpawnerRegistry, SubprocessProcessSpawnerFactory,
119    TaskId,
120};
121use serde::{Deserialize, Serialize};
122use serde_json::{json, Value};
123use std::collections::HashMap;
124use std::sync::Arc;
125use std::time::Duration;
126use tokio::sync::Mutex;
127
128/// In-memory session map backing `/v1/sessions` attach/detach.
129///
130/// The `sid` handed to the client on this REST path is the token nonce
131/// itself (a bearer secret), so the server never uses it as a map key —
132/// entries are keyed by its fingerprint
133/// (`mlua_swarm::types::token_fingerprint`; issue #14).
134#[derive(Default)]
135pub struct SessionStore {
136    /// Live session tokens keyed by the sid's fingerprint.
137    pub map: HashMap<String, CapToken>,
138}
139
140/// Shared axum handler state for the whole router. Cloned per-request (all
141/// fields are `Arc`/cheap-clone), constructed once in [`build_router_with_ws_factory`].
142#[derive(Clone)]
143pub struct AppState {
144    /// The engine SoT (attach/detach, dispatch, registries).
145    pub engine: Engine,
146    /// Live `/v1/sessions` attach records (Operator/Worker/etc session tokens).
147    pub sessions: Arc<Mutex<SessionStore>>,
148    /// Application used at the task entry to resolve `BlueprintRef`. Without a Store, runs in Inline-only mode.
149    pub task_app: Arc<TaskApplication>,
150    /// When `Some`, on WS connect a new `WSOperatorSession` is automatically registered
151    /// with this factory under the sid name (= a `kind=operator` + `operator_ref=<sid>` AgentDef
152    /// binds to the `WSOperatorSession` backend).
153    /// When `None`, no auto-registration happens; the session is only registered on
154    /// `engine.OperatorRegistry` (= only the `OperatorDelegateMiddleware` path is effective;
155    /// the `OperatorSpawnerFactory` path is dead).
156    pub ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
157    /// Owner of the Store on the Data path (Big Response handling). Added in v9.
158    /// Independent layer — the Engine core and the Domain path (`/v1/worker/result`)
159    /// are not involved.
160    /// Default = `InMemoryOutputStore` (constructed inside `build_router_with_ws_factory`);
161    /// callers can swap in an sqlite/fs backend later (future carry).
162    pub data_store: Arc<dyn mlua_swarm::store::output::OutputStore>,
163    /// Login-flow session store (`POST /v1/operators` mint records). `sid` →
164    /// `OperatorSessionEntry`. This is the sole session store for the WS
165    /// Operator role. See `operator_ws::login` module doc.
166    pub operator_sessions:
167        Arc<Mutex<HashMap<SessionId, Arc<crate::operator_ws::login::OperatorSessionEntry>>>>,
168    /// S1 login-flow roles-exclusivity map. Role name → owning `sid`. Checked
169    /// (and updated) atomically under a single lock in
170    /// `operator_ws::login::operators_create` — a role already present here
171    /// causes `POST /v1/operators` to return `409 CONFLICT`. Entries are
172    /// released on `DELETE /v1/operators/:sid`.
173    pub roles_to_sid: Arc<Mutex<HashMap<String, SessionId>>>,
174    /// Persistence for `Task` records (issue #13 ID-hierarchy work-item
175    /// identity; see `mlua_swarm::store::task` module doc). Default =
176    /// `InMemoryTaskStore` (constructed inside `build_router_full`); callers
177    /// can swap in a `SqliteTaskStore` via the `task_store` argument.
178    pub task_store: Arc<dyn TaskStore>,
179    /// Persistence for `Run` records (one kick of a Task; see
180    /// `mlua_swarm::store::run` module doc). Default = `InMemoryRunStore`;
181    /// callers can swap in a `SqliteRunStore` via the `run_store` argument.
182    pub run_store: Arc<dyn RunStore>,
183    /// Public HTTP base URL the server is reachable at (e.g.
184    /// `"http://127.0.0.1:7777"`), sourced from the binary at boot time.
185    /// When `Some`, `WSOperatorSession` renders it literally into the
186    /// Spawn `directive`'s `base_url` line so the receiving operator can
187    /// paste the frame into a SubAgent prompt without a `mse_doctor`
188    /// detour (issue #8). `None` preserves the historical fallback
189    /// (a placeholder that points at `mse_doctor`).
190    pub base_url: Option<Arc<str>>,
191    /// Server-wide fallback ceiling (seconds) for the `POST /v1/tasks`
192    /// synchronous launch await (GH #33 Guard 2; see `run_flow_form`'s doc
193    /// comment). Sourced from `config::ResolvedConfig::sync_timeout_secs`.
194    /// A per-request `TaskLaunchRequest.timeout_secs` override, when
195    /// present, takes priority over this value.
196    pub sync_timeout_secs: u64,
197}
198
199/// Minimal entry point: builds a router with [`default_registry`] and no
200/// `BlueprintStore` (Inline-only mode) or `ws_operator_factory`.
201pub fn build_router(engine: Engine) -> Router {
202    build_router_with(engine, default_registry(), None)
203}
204
205/// Default `LayerRegistry` for the server. Hint keys:
206/// - `"main_ai"` → `MainAIMiddleware` (= fires SpawnHook before/after)
207/// - `"senior_escalation"` → `SeniorEscalationMiddleware` (= on `ok=false`, escalates via `SeniorBridge.ask`)
208/// - `"operator_delegate"` → `OperatorDelegateMiddleware` (= when an operator backend is registered, delegates the entire spawn)
209///
210/// Including any of these keys in `Blueprint.spawner_hints.layers` causes them to
211/// be wrapped into a `SpawnerStack` at `service::linker::link` time (= per-launch;
212/// the old `engine.bind` global-state path is retired).
213/// Callers (the engine builder side) receive it via
214/// `Engine::new_with_layers(cfg, mse_server::default_layer_registry())`.
215pub fn default_layer_registry() -> LayerRegistry {
216    LayerRegistry::new()
217        .with_hint("main_ai", |_engine| Arc::new(MainAIMiddleware::new()))
218        .with_hint("senior_escalation", |_engine| {
219            Arc::new(SeniorEscalationMiddleware::new())
220        })
221        .with_hint("operator_delegate", |_engine| {
222            Arc::new(OperatorDelegateMiddleware::new())
223        })
224}
225
226/// Build form where the caller supplies a registry and an optional `BlueprintStore`.
227/// The Operator callback path (= external HTTP / WS callers acting as an Operator)
228/// must be pre-registered via `engine.register_*` (= the engine is the SoT).
229/// See the `operator_ws` module doc and `OperatorInfo` (engine-side `ctx.rs`) for details.
230pub fn build_router_with(
231    engine: Engine,
232    registry: SpawnerRegistry,
233    store: Option<Arc<dyn BlueprintStore>>,
234) -> Router {
235    build_router_with_ws_factory(engine, registry, store, None)
236}
237
238/// 4-argument variant of `build_router_with`. Passing `ws_operator_factory = Some(arc)`
239/// causes each WS connect to auto-register a new `WSOperatorSession` under its sid
240/// name with the factory (= a `kind=operator` AgentDef with `operator_ref: <sid>`
241/// can then bind to the WS client backend). Callers are expected to also install
242/// the same `Arc` into the `SpawnerRegistry` via
243/// `reg.register::<OperatorSpawnerFactory>(arc.clone())`.
244pub fn build_router_with_ws_factory(
245    engine: Engine,
246    registry: SpawnerRegistry,
247    store: Option<Arc<dyn BlueprintStore>>,
248    ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
249) -> Router {
250    build_router_with_ws_factory_and_output(engine, registry, store, ws_operator_factory, None)
251}
252
253/// 5-argument variant of [`build_router_with_ws_factory`]. Passing
254/// `output_store = Some(arc)` swaps the default `InMemoryOutputStore` for a
255/// caller-supplied backend (a `SqliteOutputStore`, for instance). `None`
256/// preserves the historical behaviour (fresh in-memory store per call).
257pub fn build_router_with_ws_factory_and_output(
258    engine: Engine,
259    registry: SpawnerRegistry,
260    store: Option<Arc<dyn BlueprintStore>>,
261    ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
262    output_store: Option<Arc<dyn mlua_swarm::store::output::OutputStore>>,
263) -> Router {
264    build_router_full(
265        engine,
266        registry,
267        store,
268        ws_operator_factory,
269        output_store,
270        None,
271        None,
272        None,
273        crate::config::default_sync_timeout_secs(),
274    )
275}
276
277/// 8-argument variant of [`build_router_with_ws_factory_and_output`].
278/// Passing `base_url = Some(...)` (e.g. `"http://127.0.0.1:7777"`) makes
279/// `WSOperatorSession` render the actual server bind into the Spawn
280/// directive's `base_url` line, so the receiving operator can copy the
281/// frame straight into a SubAgent prompt (issue #8). `None` preserves
282/// the historical fallback (`<check with mse_doctor>` placeholder).
283/// `task_store` / `run_store` swap the default `InMemoryTaskStore` /
284/// `InMemoryRunStore` (issue #13 ID-hierarchy persistence) for a
285/// caller-supplied backend (`SqliteTaskStore` / `SqliteRunStore`, for
286/// instance); `None` preserves the process-volatile default.
287/// `sync_timeout_secs` is the server-wide fallback ceiling for the `POST
288/// /v1/tasks` synchronous launch await (GH #33 Guard 2) — see
289/// `AppState::sync_timeout_secs` / `run_flow_form`'s doc comment.
290// This is the terminal builder in the `build_router*` delegation chain
291// (each variant adds one more caller-overridable store/factory); the
292// argument count grows with the number of pluggable backends, not with
293// unrelated responsibilities, so a plain allow is preferable to bundling
294// them into a config struct only this one function would consume.
295#[allow(clippy::too_many_arguments)]
296pub fn build_router_full(
297    engine: Engine,
298    registry: SpawnerRegistry,
299    store: Option<Arc<dyn BlueprintStore>>,
300    ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
301    output_store: Option<Arc<dyn mlua_swarm::store::output::OutputStore>>,
302    base_url: Option<Arc<str>>,
303    task_store: Option<Arc<dyn TaskStore>>,
304    run_store: Option<Arc<dyn RunStore>>,
305    sync_timeout_secs: u64,
306) -> Router {
307    let compiler = Compiler::new(registry);
308    let launch = Arc::new(TaskLaunchService::new(engine.clone(), compiler));
309    let task_app = Arc::new(match store {
310        Some(s) => TaskApplication::new(launch, s),
311        None => TaskApplication::new_inline_only(launch),
312    });
313    let data_store: Arc<dyn mlua_swarm::store::output::OutputStore> = match output_store {
314        Some(s) => s,
315        None => Arc::new(mlua_swarm::store::output::InMemoryOutputStore::new()),
316    };
317    // subtask-4 / ST2 rework: wire the SAME `data_store` instance into the
318    // engine's submit-time projection sink (`Engine::submit_output` /
319    // `submit_worker_result_trusted`), so an ordinary worker
320    // `/v1/worker/submit` — not just the explicit `POST /v1/data/emit` —
321    // lands in this store too. `projection::McpQueryAdapter` (`GET
322    // /v1/tasks/:id/runs/:run/steps*`) reads through this same `Arc`,
323    // which is what makes an in-flight run's already-submitted step
324    // OUTPUT queryable.
325    engine.set_output_store(data_store.clone());
326    let task_store: Arc<dyn TaskStore> = match task_store {
327        Some(s) => s,
328        None => Arc::new(mlua_swarm::store::task::InMemoryTaskStore::new()),
329    };
330    let run_store: Arc<dyn RunStore> = match run_store {
331        Some(s) => s,
332        None => Arc::new(mlua_swarm::store::run::InMemoryRunStore::new()),
333    };
334    let state = AppState {
335        engine,
336        sessions: Arc::new(Mutex::new(SessionStore::default())),
337        task_app,
338        ws_operator_factory,
339        data_store,
340        operator_sessions: Arc::new(Mutex::new(HashMap::new())),
341        roles_to_sid: Arc::new(Mutex::new(HashMap::new())),
342        task_store,
343        run_store,
344        base_url,
345        sync_timeout_secs,
346    };
347    Router::new()
348        .route("/v1/healthz", get(healthz))
349        .route("/v1/status", get(status_get))
350        // session = collection (POST = attach, DELETE = detach, sid via Authorization)
351        .route(
352            "/v1/sessions",
353            post(sessions_attach).delete(sessions_detach),
354        )
355        // task = flat, single level; authz resolved via Authorization: Bearer <sid>
356        .route("/v1/tasks", post(tasks_start).get(tasks::tasks_list))
357        .route("/v1/tasks/:id", get(tasks::task_get))
358        .route("/v1/tasks/:id/runs", post(tasks::task_rekick))
359        .route("/v1/tasks/:id/runs/:run/steps", get(projection::steps_list))
360        .route(
361            "/v1/tasks/:id/runs/:run/steps/:step",
362            get(projection::step_get),
363        )
364        .route(
365            "/v1/tasks/:id/runs/:run/steps/:step/content",
366            get(projection::step_content),
367        )
368        .route("/v1/runs/:id", get(tasks::run_get))
369        // REST-like Operator login flow (Bearer-mandatory, roles exclusivity).
370        // Sole WS Operator session route; see `operator_ws::login` module doc.
371        .route("/v1/operators", post(operators_create))
372        .route("/v1/operators/:sid/ws", get(operators_ws_connect))
373        .route(
374            "/v1/operators/:sid",
375            get(operators_info).delete(operators_delete),
376        )
377        // SubAgent self-fetch path (the SubAgent self-fetch design). The SubAgent puts the
378        // CapToken handed over via WS Spawn into Bearer and hits the prompt / result
379        // endpoints directly over HTTP. See the `worker` module doc for details.
380        .route("/v1/worker/prompt", get(worker::worker_prompt))
381        .route("/v1/worker/result", post(worker::worker_result))
382        // Simplified endpoint (= worker POSTs with just token + raw body; task_id is auto-looked-up).
383        // `DefaultBodyLimit::max` is applied explicitly here (and on the sibling
384        // `/v1/worker/artifact` below) — same 2MB axum ships as its implicit
385        // global default, made visible rather than relied on silently.
386        .route(
387            "/v1/worker/submit",
388            post(worker::worker_submit).layer(DefaultBodyLimit::max(2 * 1024 * 1024)),
389        )
390        // GH #36 ST1: named multi-part worker output. A worker stages one
391        // named part per POST here, then completes the attempt with the
392        // ordinary `/v1/worker/submit` above — see the `worker` module doc.
393        .route(
394            "/v1/worker/artifact",
395            post(worker::worker_artifact).layer(DefaultBodyLimit::max(2 * 1024 * 1024)),
396        )
397        // GH #31: `Http`-mode fetch target for `system_ref.uri` (raw baked system
398        // bytes, same Bearer flow as `/v1/worker/prompt`) + live per-agent render-size
399        // lookup for `bp_doctor` (no Bearer, same trust tier as blueprints `get_head`).
400        .route(
401            "/v1/worker/prompt/system",
402            get(worker::worker_prompt_system),
403        )
404        .route(
405            "/v1/agents/:name/render-size",
406            get(worker::agent_render_size),
407        )
408        // GH #32: structured worker degradation reporting — independent channel,
409        // never touches OutputStore / the fold path. See the `worker` module doc.
410        .route("/v1/worker/degradation", post(worker::worker_degradation))
411        // Data path (v9 Big Response handling, independent from Domain / verdict flow)
412        .route("/v1/data/emit", post(data::data_emit))
413        .route(
414            "/v1/data/:key",
415            get(data::data_get).post(data::data_emit_named),
416        )
417        .with_state(state)
418}
419
420/// Default registry = Subprocess + RustFn (baseline `identity` worker pre-baked) + empty Operator factory.
421///
422/// `RustFnInProcessSpawnerFactory` gets one baseline entry (`fn_id = "identity"`)
423/// baked in via [`mlua_swarm::worker::baseline::extend_with_baseline`]. This
424/// is the shared bootstrap / smoke worker SoT across each binary (the server / MCP adapter /
425/// one-shot runner) — it structurally replaces the old per-binary inline echo injection.
426///
427/// Usage: default Task path at server startup. If production needs additional
428/// backends, callers bring in a different registry via
429/// `build_router_with(engine, custom_registry)`. The enhance flow
430/// (= patch-spawner / patch-applier / verifier-router / committer axes) uses
431/// [`default_registry_with_enhance_flow`].
432///
433/// The Operator factory is an empty shell with zero registrations (= sids are
434/// dynamically registered per WS connect; see the `operator_ws` module).
435pub fn default_registry() -> SpawnerRegistry {
436    let rustfn_factory =
437        mlua_swarm::worker::baseline::extend_with_baseline(RustFnInProcessSpawnerFactory::new());
438
439    let mut reg = SpawnerRegistry::new();
440    reg.register::<SubprocessProcessSpawnerFactory>(Arc::new(SubprocessProcessSpawnerFactory));
441    reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(rustfn_factory));
442    // Empty `LuaInProcessSpawnerFactory`: no `fn_id` is pre-registered here,
443    // but BP agents can still declare `kind: lua` by carrying an inline
444    // `spec.source` (or a `$file`-expanded Lua chunk). This lets a BP ship
445    // deterministic Lua gates on the vanilla registry, without opting into
446    // the enhance flow. See `LuaInProcessSpawnerFactory` docs for the spec
447    // shape.
448    reg.register::<LuaInProcessSpawnerFactory>(Arc::new(LuaInProcessSpawnerFactory::new()));
449    reg.register::<OperatorSpawnerFactory>(Arc::new(OperatorSpawnerFactory::new()));
450    reg
451}
452
453/// Opt-in registry that merges [`default_registry`] with the enhance flow
454/// (Lua factory + AgentBlock factory).
455///
456/// Selected via the `the server` CLI flag `--enable-enhance-flow`. The enhance
457/// flow is a separate-axis wrapper: the Lua factory (= 3 Lua workers + 3 primitive
458/// bridges) and the AgentBlock factory (= patch-spawner path, expects
459/// `assets/operator_scripts/blueprint_patch_spawner.lua` + `ANTHROPIC_API_KEY`)
460/// are baked in as pipeline defaults. The baseline RustFn (`identity`) is pre-baked
461/// the same way as in `default_registry`.
462pub fn default_registry_with_enhance_flow() -> SpawnerRegistry {
463    let lua_factory =
464        mlua_swarm::enhance::blueprint::extend_factory(LuaInProcessSpawnerFactory::new());
465    // The Factory is stateless (= 1 process → 1 factory shared by all AgentDefs).
466    // Per-agent specialization (script_path / project_root, etc.) goes through AgentDef.spec.
467    // The enhance-flow patch-spawner is declared literally in agents[].spec of `default_blueprint.yaml`.
468    let agent_block_factory =
469        mlua_swarm::worker::agent_block::AgentBlockInProcessSpawnerFactory::new();
470    let rustfn_factory =
471        mlua_swarm::worker::baseline::extend_with_baseline(RustFnInProcessSpawnerFactory::new());
472
473    let mut reg = SpawnerRegistry::new();
474    reg.register::<SubprocessProcessSpawnerFactory>(Arc::new(SubprocessProcessSpawnerFactory));
475    reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(rustfn_factory));
476    reg.register::<LuaInProcessSpawnerFactory>(Arc::new(lua_factory));
477    reg.register::<mlua_swarm::worker::agent_block::AgentBlockInProcessSpawnerFactory>(Arc::new(
478        agent_block_factory,
479    ));
480    reg.register::<OperatorSpawnerFactory>(Arc::new(OperatorSpawnerFactory::new()));
481    reg
482}
483
484// ─── handlers ────────────────────────────────────────────────────────────
485
486async fn healthz() -> &'static str {
487    "ok"
488}
489
490/// Response body for `GET /v1/status` (issue #35 ST4 — lifecycle
491/// occupancy guard). Cheap-to-poll summary of "is it safe to kill this
492/// server right now".
493#[derive(Debug, Clone, Serialize, schemars::JsonSchema)]
494pub struct StatusResponse {
495    /// Count of `Run`s currently `Running` (`RunStore::list_running`).
496    /// Degrades to `0` on a store error rather than 500ing — see
497    /// module doc rationale.
498    pub running_runs: usize,
499    /// Count of attached Operator ids (`engine.list_operator_ids()`,
500    /// same idiom as `run_flow_form`'s Guard 1).
501    pub attached_operators: usize,
502}
503
504/// `GET /v1/status`. Infallible summary for the ST4 occupancy guard —
505/// store/engine query failures degrade the corresponding count to `0`
506/// (logged via `tracing::warn!`) rather than 500ing, since this
507/// endpoint may be polled frequently by a lifecycle-check caller that
508/// should not itself become a hang/error surface.
509async fn status_get(State(state): State<AppState>) -> Json<StatusResponse> {
510    let running_runs = state
511        .run_store
512        .list_running()
513        .await
514        .map(|v| v.len())
515        .unwrap_or_else(|e| {
516            tracing::warn!(error = %e, "status_get: list_running failed");
517            0
518        });
519    let attached_operators = state.engine.list_operator_ids().await.len();
520    Json(StatusResponse {
521        running_runs,
522        attached_operators,
523    })
524}
525
526#[derive(Deserialize)]
527struct AttachReq {
528    agent_id: String,
529    role: String,
530    ttl_secs: u64,
531}
532
533#[derive(Serialize)]
534struct AttachResp {
535    session_id: String,
536    role: String,
537}
538
539async fn sessions_attach(
540    State(state): State<AppState>,
541    Json(req): Json<AttachReq>,
542) -> Result<Json<AttachResp>, ApiError> {
543    let role = parse_role(&req.role)?;
544    let token = state
545        .engine
546        .attach(req.agent_id, role, Duration::from_secs(req.ttl_secs))
547        .await
548        .map_err(ApiError::engine)?;
549    // The wire `session_id` stays the nonce (Bearer credential contract);
550    // the server-side map key is its fingerprint (issue #14).
551    let sid = token.nonce.clone();
552    let key = token.fingerprint();
553    state.sessions.lock().await.map.insert(key, token);
554    Ok(Json(AttachResp {
555        session_id: sid,
556        role: req.role,
557    }))
558}
559
560async fn sessions_detach(
561    State(state): State<AppState>,
562    headers: HeaderMap,
563) -> Result<StatusCode, ApiError> {
564    let sid = extract_bearer(&headers)?;
565    let token = take_session_token(&state, &sid).await?;
566    state
567        .engine
568        .detach(&token)
569        .await
570        .map_err(ApiError::engine)?;
571    Ok(StatusCode::NO_CONTENT)
572}
573
574// ─── Unified /v1/tasks schema (= flow-eval path, Operator inject supported) ───────
575
576/// `/v1/tasks` POST schema. Uses the flow-eval path and supports Operator inject
577/// (kind / spawn_hook / senior_bridge). Expressing a one-shot task as a 1-Step
578/// Blueprint is the only correct model.
579///
580/// `pub` (issue #19 ST5) so its `schemars`-derived JSON Schema can be
581/// generated cross-crate by `mlua-swarm-cli`'s `mse://api/http-endpoints`
582/// MCP resource; fields stay module-private (no public field-level API
583/// surface is intended).
584#[derive(Deserialize, schemars::JsonSchema)]
585pub struct TaskLaunchRequest {
586    /// `BlueprintRef` selects Inline (a full Blueprint value) or Id (a
587    /// store lookup). Left opaque here — its own schema nests the full
588    /// `Blueprint` schema (owned by `mse://api/blueprint-schema`), and
589    /// mixing the two into this HTTP-endpoint resource would violate
590    /// their separation of concerns (see the resource's module doc).
591    #[schemars(with = "Value")]
592    blueprint: BlueprintRef,
593    /// flow.ir's initial `ctx` — every `Step.in` `$.<path>` reads from
594    /// here. This field's role is limited to the flow-ir eval seed
595    /// (issue #19); the Task-level execution context lives in the
596    /// sibling top-level fields below (`project_root` / `work_dir` /
597    /// `task_metadata`), promoted out of `init_ctx` to remove the
598    /// prior "free bag nested in free JSON" duplication.
599    ///
600    /// Backward compat: the pre-#19 shape — the same three keys nested
601    /// directly inside this object — is still honored as a fallback
602    /// when the sibling field is absent; see `run_flow_form`'s 2-stage
603    /// resolution and `TaskInputMiddleware::from_init_ctx`.
604    #[schemars(with = "Value")]
605    init_ctx: Value,
606    /// Task-level project root (issue #19 canonical Task IF field —
607    /// promoted out of `init_ctx`). Takes priority over a same-named
608    /// key nested inside `init_ctx` (backward-compat fallback).
609    #[serde(default)]
610    project_root: Option<String>,
611    /// Task-level working directory (issue #19), same priority rule as
612    /// `project_root`.
613    #[serde(default)]
614    work_dir: Option<String>,
615    /// Task-level arbitrary metadata bag (issue #19), same priority
616    /// rule as `project_root`.
617    #[serde(default)]
618    #[schemars(with = "Option<Value>")]
619    task_metadata: Option<Value>,
620    /// TTL in seconds. When unspecified (`None`), falls back in this order:
621    /// (1) `metadata.default_run_ttl_secs` from the resolved BP,
622    /// (2) if absent, the server global `default_run_ttl()` (1800s).
623    #[serde(default)]
624    ttl_secs: Option<u64>,
625    #[serde(default)]
626    operator: Option<OperatorReq>,
627    /// Explicit Operator session sid (or role alias) this task's entire Spawn
628    /// stream should be routed to (runtime Operator match stage 1).
629    ///
630    /// When `Some`, it is validated at request time against
631    /// `state.engine.list_operator_ids()` (the live `engine.operators`
632    /// registry key set): an unknown/never-registered id returns `400`
633    /// immediately — this is a deliberate hard-fail, in contrast to
634    /// `OperatorDelegateWrapped::spawn`, which silently falls through to
635    /// `inner.spawn` on a registry miss. A sid that *was* registered but has
636    /// since disconnected (WS `tx` cleared, session entry retained for
637    /// reconnect) passes this check and surfaces as an explicit dispatch-time
638    /// error instead (`WSOperatorSession::send_and_await` returns `Err` when
639    /// `tx` is `None`), which also propagates as a request failure rather
640    /// than a silent fallback.
641    ///
642    /// On success this value **overrides** `operator.operator_backend_id`
643    /// (last-write-wins, `operator_sid` takes priority) before the flow is
644    /// dispatched — see `run_flow_form`. Dispatch still only delegates if the
645    /// Blueprint opts into `spawner_hints.layers = ["operator_delegate"]`
646    /// (unchanged precondition, same as the existing `operator_backend_id`
647    /// field).
648    ///
649    /// When unset, behavior is unchanged: whatever
650    /// `operator.operator_backend_id` / BP-level `operator_ref` alias
651    /// resolution already does still applies.
652    #[serde(default)]
653    operator_sid: Option<String>,
654    /// Per-request override for the sync launch's timeout ceiling (GH #33
655    /// Guard 2, see `run_flow_form`'s doc comment). `None` (the default;
656    /// existing clients are unaffected) falls back to
657    /// `AppState::sync_timeout_secs` (server config), then the built-in
658    /// default (300s). `Some(0)` is rejected with `400` — omit the field
659    /// to defer to the server default rather than sending an explicit
660    /// zero.
661    #[serde(default)]
662    timeout_secs: Option<u64>,
663    /// Human-facing description of the work item (e.g. "resolve issue #10"),
664    /// stashed verbatim into the minted `TaskRecord.goal`. Omitted / `None`
665    /// stores an empty string — the flow-eval path itself never reads it.
666    #[serde(default)]
667    goal: Option<String>,
668    /// GH #37: opt into the detached (asynchronous) launch. `false` (the
669    /// default; existing clients are unaffected) keeps the synchronous
670    /// launch: the handler drives the flow eval inline and returns the
671    /// `final_ctx` on completion. `true` spawns the flow eval as a
672    /// detached background task and returns `202 Accepted` immediately
673    /// with `{task_id, run_id, status: "running"}` (`final_ctx` is
674    /// `null`) — the run's only lifetime bound is `ttl_secs`, and its
675    /// outcome is observed via `GET /v1/runs/:id` (or the `swarm_status`
676    /// MCP tool). Mutually exclusive with `timeout_secs` (the sync-launch
677    /// ceiling has no meaning for a detached run; combining them is a
678    /// `400`).
679    #[serde(default)]
680    detach: bool,
681}
682
683/// Operator inject sub-schema of [`TaskLaunchRequest`] (`kind` / `id` /
684/// `spawn_hook_id` / `senior_bridge_id` / `operator_backend_id` /
685/// `per_agent_kinds`). `pub` for the same cross-crate schema-generation
686/// reason as `TaskLaunchRequest`.
687#[derive(Deserialize, Default, schemars::JsonSchema)]
688pub struct OperatorReq {
689    /// `main_ai` / `automate` / `composite`. This is the "Runtime Global"
690    /// tier of the 4-tier `OperatorKind` cascade (see `mlua_swarm
691    /// ::ctx::collapse_operator_kind`); when unspecified, falls through to
692    /// the BP-level tiers (`OperatorDef.kind` / `Blueprint
693    /// .default_operator_kind`) instead of eagerly defaulting to `automate`.
694    #[serde(default)]
695    kind: Option<String>,
696    /// Operator id at attach time (= sessions tracking key in the EventLog); unspecified defaults to `"http-run"`.
697    #[serde(default)]
698    id: Option<String>,
699    /// Name of a hook pre-registered via `engine.register_spawn_hook`; `None` if unspecified.
700    #[serde(default)]
701    spawn_hook_id: Option<String>,
702    /// Name of a bridge pre-registered via `engine.register_senior_bridge`; `None` if unspecified.
703    #[serde(default)]
704    senior_bridge_id: Option<String>,
705    /// Name of an Operator backend pre-registered via `engine.register_operator`
706    /// (= the path that delegates the entire spawn to an external Operator);
707    /// `None` if unspecified. When `kind == MainAi/Composite` and this id is `Some`,
708    /// `OperatorDelegateMiddleware` bypasses `inner.spawn` and calls `operator.execute` instead.
709    /// This is a different axis from `operator.id` (= session tracking label);
710    /// `operator_backend_id` is the registry lookup key.
711    #[serde(default)]
712    operator_backend_id: Option<String>,
713    /// "Runtime Agent-level" tier (highest priority) of the `OperatorKind`
714    /// cascade — per-agent override, keyed by `AgentDef.name`, value is
715    /// `main_ai` / `automate` / `composite` (same parsing as `kind`).
716    /// `None` / absent means no per-agent override.
717    #[serde(default)]
718    per_agent_kinds: Option<HashMap<String, String>>,
719}
720
721/// Parse a wire-level kind string (`"main_ai"` / `"automate"` / `"composite"`)
722/// into `OperatorKind`. Shared by `OperatorReq.kind` and
723/// `OperatorReq.per_agent_kinds` values.
724fn parse_operator_kind_str(s: &str) -> Result<mlua_swarm::OperatorKind, ApiError> {
725    use mlua_swarm::OperatorKind;
726    match s {
727        "main_ai" => Ok(OperatorKind::MainAi),
728        "composite" => Ok(OperatorKind::Composite),
729        "automate" => Ok(OperatorKind::Automate),
730        other => Err(ApiError::bad_request(format!(
731            "operator kind: unknown value '{other}' (expected main_ai|automate|composite)"
732        ))),
733    }
734}
735
736/// `/v1/tasks` POST response body. `pub` for the same cross-crate
737/// schema-generation reason as [`TaskLaunchRequest`].
738#[derive(Serialize, schemars::JsonSchema)]
739pub struct TaskLaunchResponse {
740    /// The final flow.ir `ctx` after every `Step.out` has been written.
741    #[schemars(with = "Value")]
742    final_ctx: Value,
743    /// Debug-formatted `BlueprintVersion` the run resolved against, when
744    /// the Blueprint came from a store lookup (`None` for `Inline` refs).
745    bound_version: Option<String>,
746    /// Resolved TTL (seconds) actually applied to the run. Exposes the
747    /// 3-layer cascade (request body → BP metadata → server default) so
748    /// clients can verify which value took effect without re-deriving it.
749    effective_ttl_secs: u64,
750    /// Which layer of the TTL cascade won.
751    ttl_source: TtlSource,
752    /// The `TaskRecord` minted for this request (issue #13 ID-hierarchy
753    /// persistence). `GET /v1/tasks/:id` re-fetches it; `POST
754    /// /v1/tasks/:id/runs` re-kicks it under a fresh `RunId`.
755    #[schemars(with = "String")]
756    task_id: TaskId,
757    /// The `RunRecord` minted for this specific kick. `GET /v1/runs/:id`
758    /// re-fetches it (`step_entries` included).
759    #[schemars(with = "String")]
760    run_id: RunId,
761    /// Launch outcome at response time (GH #37). The synchronous path
762    /// (default) reports `done` — the flow eval completed before this
763    /// response was built. A detached launch (`detach: true`) reports
764    /// `running` — the eval continues in the background; poll `GET
765    /// /v1/runs/:id` for the terminal status and result.
766    status: RunStatus,
767}
768
769/// `tasks_start`'s reply — a [`TaskLaunchResponse`] plus the HTTP status
770/// it rides out on (`200 OK` for the synchronous path, `202 Accepted` for
771/// a detached launch, GH #37). A tuple struct with the body first so
772/// handler-level tests keep their established `.0` access to the response
773/// body regardless of which path produced it.
774pub struct TaskLaunchReply(pub TaskLaunchResponse, pub StatusCode);
775
776impl IntoResponse for TaskLaunchReply {
777    fn into_response(self) -> Response {
778        (self.1, Json(self.0)).into_response()
779    }
780}
781
782/// Which layer of the TTL cascade (request body → BP metadata → server
783/// default) resolved [`TaskLaunchResponse::effective_ttl_secs`]. `pub` for
784/// the same cross-crate schema-generation reason as `TaskLaunchRequest`.
785#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq, schemars::JsonSchema)]
786#[serde(rename_all = "snake_case")]
787pub enum TtlSource {
788    /// The request body's `ttl_secs` was set explicitly.
789    RequestBody,
790    /// The request body omitted `ttl_secs`; the resolved Blueprint's
791    /// `metadata.default_run_ttl_secs` was set.
792    BpMetadata,
793    /// Both the request body and the Blueprint metadata omitted a TTL;
794    /// the server-global `default_run_ttl()` (1800s) applied.
795    ServerDefault,
796}
797
798/// Unified `/v1/tasks` POST entry (= Flow form only).
799/// Runs `Blueprint.flow` to completion via flow eval in a single round-trip.
800/// One-shot tasks are also expressed as a 1-Step Blueprint. Operator
801/// (kind / spawn_hook / senior_bridge) can be injected per request body.
802/// `operator_sid` (S2, runtime Operator match stage 1) additionally
803/// lets the caller pin the task to a specific already-registered Operator
804/// session sid, bypassing BP-level alias lookup — see `TaskLaunchRequest` doc.
805async fn tasks_start(
806    State(state): State<AppState>,
807    Json(req): Json<TaskLaunchRequest>,
808) -> Result<TaskLaunchReply, ApiError> {
809    run_flow_form(&state, req).await
810}
811
812/// Flow-form path (= via `TaskApplication::handle_with_run`).
813/// Core handler behind the `/v1/tasks` entry (`tasks_start`).
814///
815/// Engine stateless-executor refactor: the per-request
816/// sub_engine + 3-registry propagate loop is retired; the startup-built
817/// `state.task_app` (= a `TaskLaunchService` wrap around `state.engine`) is
818/// used directly. The Operator callback IF (`spawn_hook_id` /
819/// `senior_bridge_id` / `operator_backend_id`) is registered on
820/// `state.engine.register_*` at WS connect time — the engine is the SoT.
821/// See the `operator_ws` module doc for details.
822///
823/// # GH #33 — sync-hang guards
824///
825/// This handler is always synchronous end-to-end (no sync/async branch);
826/// two fail-loud guards keep a bad launch from hanging the HTTP request
827/// forever:
828///
829/// - **Guard 1 (readiness precheck, `503`)**: when the request/BP
830///   references an operator backend (`operator.operator_backend_id`, set
831///   directly or via `operator_sid`) and `state.engine.list_operator_ids()`
832///   is empty, the request fails immediately rather than dispatching into
833///   a session with nothing attached to serve it. Coarse by design — a
834///   launch that cannot be cheaply determined to route through an operator
835///   is never rejected here (Guard 2 still covers the hang in that case).
836/// - **Guard 2 (sync timeout, `504`)**: the single
837///   `state.task_app.handle_with_run` await is wrapped in
838///   `tokio::time::timeout`. Ceiling cascade, highest priority first:
839///   request `timeout_secs` (rejecting `Some(0)` with `400`), then
840///   `AppState::sync_timeout_secs` (server config), then the built-in
841///   default (300s). On expiry the timed-out future is dropped — this
842///   cancels the in-process flow eval (the flow is abandoned, not
843///   resumed; intended v1 semantics) — and the Task/Run records are
844///   best-effort marked `Failed` so they do not stay `Running` forever.
845///
846/// # GH #37 — detached launch (`detach: true`)
847///
848/// The sync semantics above tie the flow-eval driver's lifetime to this
849/// request's future — a long-running detached worker that outlives the
850/// ceiling gets its (individually successful) `/v1/worker/*` submits
851/// orphaned when the driver is cancelled. `detach: true` decouples them:
852/// the eval (plus `finalize_run`) runs in a `tokio::spawn`ed background
853/// task whose only lifetime bound is the resolved `ttl_secs` (marked
854/// `Failed` on expiry, same best-effort persistence as Guard 2), and the
855/// handler returns `202 Accepted` with `status: "running"` immediately.
856/// Guard 1 still applies (checked before any store write); Guard 2's
857/// ceiling does not (`timeout_secs` + `detach` together is a `400`).
858/// Client disconnect after the `202` cannot cancel the run.
859async fn run_flow_form(
860    state: &AppState,
861    req: TaskLaunchRequest,
862) -> Result<TaskLaunchReply, ApiError> {
863    use mlua_swarm::application::{BlueprintRef as AppBlueprintRef, TaskApplicationInput};
864    use mlua_swarm::OperatorKind;
865
866    // Snapshot everything the TaskRecord needs before `req.blueprint` /
867    // `req.init_ctx` are moved into the dispatch path below.
868    let blueprint_ref_json = serde_json::to_value(&req.blueprint)
869        .map_err(|e| ApiError::bad_request(format!("blueprint snapshot: {e}")))?;
870    let input_ctx_snapshot = req.init_ctx.clone();
871    let goal = req.goal.clone().unwrap_or_default();
872
873    // issue #19 ST2: resolve the Task-level canonical fields
874    // (`project_root` / `work_dir` / `task_metadata`) once, at the wire
875    // boundary. Sibling top-level fields on the request body take
876    // priority; the pre-#19 shape (same key nested inside `init_ctx`) is
877    // only a fallback for legacy callers. The result is threaded straight
878    // through as `TaskApplicationInput.task_input` — `init_ctx` itself is
879    // NOT mutated, so it stays a pure flow-ir eval seed identical to
880    // whatever the caller sent.
881    let task_input_spec = build_task_input_spec_from_request(&req);
882    // Issue #19 ST4: snapshot the resolved spec into the `TaskRecord` (JSON,
883    // same "bare `Value`" rationale as `blueprint_ref_json` /
884    // `input_ctx_snapshot` above) so `POST /v1/tasks/:id/runs` can resolve
885    // it back out on rekick without re-deriving it from a since-stale
886    // request body. Cloned rather than computed from `task_input_spec`
887    // after the fact — the original is still moved into
888    // `TaskApplicationInput.task_input` below.
889    let task_input_spec_snapshot = task_input_spec
890        .clone()
891        .map(|spec| serde_json::to_value(&spec))
892        .transpose()
893        .map_err(|e| ApiError::bad_request(format!("task_input_spec snapshot: {e}")))?;
894    let init_ctx = req.init_ctx.clone();
895
896    let mut op_req = req.operator.unwrap_or_default();
897
898    // S2: explicit `operator_sid` override (runtime Operator match stage 1).
899    // Resolved *before* building `operator_kind` / dispatching so an
900    // unknown sid fails fast with a 400, never silently falling back to the
901    // BP-level alias lookup. See `TaskLaunchRequest::operator_sid` doc for the
902    // disconnected-vs-unknown distinction.
903    if let Some(sid) = &req.operator_sid {
904        let known_ids = state.engine.list_operator_ids().await;
905        if !known_ids.iter().any(|id| id == sid) {
906            return Err(ApiError::bad_request(format!(
907                "operator_sid: no such registered operator session '{sid}'"
908            )));
909        }
910        op_req.operator_backend_id = Some(sid.clone());
911    }
912
913    // GH #33 Guard 2 ceiling resolution: request field > server config >
914    // built-in default (300s, `config::default_sync_timeout_secs`).
915    // Validated up front — before any TaskRecord/RunRecord side effects —
916    // so a caller-supplied `Some(0)` fails fast with `400` rather than
917    // minting records for a launch that was never going to dispatch.
918    // GH #37: `detach: true` makes the sync ceiling meaningless (the
919    // detached run is bounded by `ttl_secs` alone) — combining the two
920    // is rejected here, same fail-fast-before-side-effects ordering.
921    let detach = req.detach;
922    let sync_timeout_secs = match (detach, req.timeout_secs) {
923        (true, Some(_)) => {
924            return Err(ApiError::bad_request(
925                "timeout_secs is the synchronous launch ceiling and does not apply to a \
926                 detached launch (detach: true), whose lifetime bound is ttl_secs — omit \
927                 timeout_secs"
928                    .into(),
929            ));
930        }
931        (false, Some(0)) => {
932            return Err(ApiError::bad_request(
933                "timeout_secs: 0 is invalid; omit the field to use the server default".into(),
934            ));
935        }
936        (false, Some(v)) => v,
937        (_, None) => state.sync_timeout_secs,
938    };
939
940    // GH #33 Guard 1: operator readiness precheck. Coarse signal — this
941    // handler can cheaply see whether the request/BP references an
942    // operator backend (`operator.operator_backend_id`, set directly or
943    // resolved above from `operator_sid`), but not the full
944    // `OperatorDelegateMiddleware` routing decision (that also considers
945    // BP-level `kind` tiers, resolved only at dispatch time). When a
946    // backend is referenced and *zero* operators are attached at all,
947    // fail fast rather than dispatching into a session nothing can serve.
948    // A launch this coarse check cannot positively identify as
949    // operator-delegate is never rejected here — Guard 2 (the timeout
950    // wrap below) still covers the hang in that case.
951    if let Some(backend_id) = op_req.operator_backend_id.as_deref() {
952        let attached = state.engine.list_operator_ids().await;
953        if attached.is_empty() {
954            return Err(ApiError::unavailable(format!(
955                "no operator attached to serve this launch (operator backend '{backend_id}' \
956                 requested): attach an operator via POST /v1/operators + WS, or use the \
957                 poll-style flow (GET /v1/worker/prompt + POST /v1/worker/submit)"
958            )));
959        }
960    }
961
962    // "Runtime Global" tier: `Some(_)` — including `Some(Automate)` — is
963    // always an explicit request that outranks the BP-level tiers; an
964    // absent/unset `kind` in the request body stays `None`, leaving the
965    // BP-level tiers (`OperatorDef.kind` / `Blueprint.default_operator_kind`)
966    // to decide instead of eagerly defaulting to `Automate`.
967    let operator_kind = op_req
968        .kind
969        .as_deref()
970        .map(parse_operator_kind_str)
971        .transpose()?;
972    let operator_id = op_req.id.unwrap_or_else(|| "http-run".to_string());
973    // "Runtime Agent-level" tier: per-agent overrides. Absent/empty = no
974    // override for any agent, letting the BP-level tiers decide per agent.
975    let mut operator_kind_overrides: HashMap<String, OperatorKind> = HashMap::new();
976    for (agent, kind_str) in op_req.per_agent_kinds.take().unwrap_or_default() {
977        operator_kind_overrides.insert(agent, parse_operator_kind_str(&kind_str)?);
978    }
979
980    let blueprint: AppBlueprintRef = match req.blueprint {
981        AppBlueprintRef::Inline { value } => AppBlueprintRef::Inline { value },
982        AppBlueprintRef::Id { id, version } => AppBlueprintRef::Id { id, version },
983    };
984
985    // TTL resolution cascade: (1) request body value, (2) BP metadata `default_run_ttl_secs`,
986    // (3) server global default (`default_run_ttl()`, 1800s).
987    let (ttl_secs, ttl_source) = match req.ttl_secs {
988        Some(v) => (v, TtlSource::RequestBody),
989        None => {
990            let (resolved_bp, _ver) = state
991                .task_app
992                .resolve(&blueprint)
993                .await
994                .map_err(|e| ApiError::bad_request(format!("bp resolve: {e}")))?;
995            match resolved_bp.metadata.default_run_ttl_secs {
996                Some(v) => (v, TtlSource::BpMetadata),
997                None => (default_run_ttl(), TtlSource::ServerDefault),
998            }
999        }
1000    };
1001
1002    // issue #13 ID-hierarchy persistence: mint the work-item identity (Task)
1003    // and this kick's identity (Run) *before* dispatching, so a Task/Run
1004    // pair always exists even if the flow itself fails mid-way (the
1005    // Failed-status paths below still have a row to update).
1006    let task_id = TaskId::new();
1007    let run_id = RunId::new();
1008    let now = tasks::now_secs();
1009    state
1010        .task_store
1011        .create(TaskRecord {
1012            id: task_id.clone(),
1013            goal,
1014            blueprint_ref: blueprint_ref_json,
1015            input_ctx: input_ctx_snapshot,
1016            task_input_spec: task_input_spec_snapshot,
1017            status: TaskRecordStatus::Running,
1018            created_at: now,
1019            updated_at: now,
1020        })
1021        .await
1022        .map_err(ApiError::engine)?;
1023    state
1024        .run_store
1025        .create(RunRecord {
1026            id: run_id.clone(),
1027            task_id: task_id.clone(),
1028            status: RunStatus::Running,
1029            step_entries: Vec::new(),
1030            degradations: Vec::new(),
1031            operator_sid: req.operator_sid.clone(),
1032            result_ref: None,
1033            created_at: now,
1034            updated_at: now,
1035        })
1036        .await
1037        .map_err(ApiError::engine)?;
1038
1039    let run_ctx = RunContext {
1040        run_id: run_id.clone(),
1041        run_store: state.run_store.clone(),
1042    };
1043    let input = TaskApplicationInput {
1044        blueprint,
1045        operator_id: operator_id.clone(),
1046        role: Role::Operator,
1047        ttl: Duration::from_secs(ttl_secs),
1048        init_ctx,
1049        operator_kind,
1050        bridge_id: op_req.senior_bridge_id,
1051        hook_id: op_req.spawn_hook_id,
1052        operator_backend_id: op_req.operator_backend_id,
1053        operator_kind_overrides,
1054        task_input: task_input_spec,
1055    };
1056
1057    // GH #37 detached launch: the eval driver runs in its own spawned
1058    // task — its lifetime is bound to `ttl_secs`, not to this request's
1059    // future (client disconnect / handler completion cannot cancel it).
1060    // The spawned task owns the run to its terminal status: `finalize_run`
1061    // on completion, or the same best-effort `Failed` marking as Guard 2
1062    // if the ttl ceiling expires first.
1063    if detach {
1064        let bg_state = state.clone();
1065        let bg_task_id = task_id.clone();
1066        let bg_run_id = run_id.clone();
1067        tokio::spawn(async move {
1068            let outcome = match tokio::time::timeout(
1069                Duration::from_secs(ttl_secs),
1070                bg_state.task_app.handle_with_run(input, Some(run_ctx)),
1071            )
1072            .await
1073            {
1074                Ok(outcome) => outcome,
1075                Err(_elapsed) => {
1076                    let reason = json!({
1077                        "error": format!("detached run exceeded {ttl_secs}s ttl ceiling"),
1078                    });
1079                    if let Err(e) = bg_state.run_store.set_result(&bg_run_id, reason).await {
1080                        tracing::warn!(%bg_run_id, error = %e, "run_flow_form: detached ttl set_result failed");
1081                    }
1082                    if let Err(e) = bg_state
1083                        .run_store
1084                        .update_status(&bg_run_id, RunStatus::Failed)
1085                        .await
1086                    {
1087                        tracing::warn!(%bg_run_id, error = %e, "run_flow_form: detached ttl run update_status(Failed) failed");
1088                    }
1089                    if let Err(e) = bg_state
1090                        .task_store
1091                        .update_status(&bg_task_id, TaskRecordStatus::Failed)
1092                        .await
1093                    {
1094                        tracing::warn!(%bg_task_id, error = %e, "run_flow_form: detached ttl task update_status(Failed) failed");
1095                    }
1096                    return;
1097                }
1098            };
1099            // `finalize_run` persists both the Ok and Err outcomes itself;
1100            // the passthrough return value has no consumer here.
1101            let _ = tasks::finalize_run(&bg_state, &bg_task_id, &bg_run_id, outcome).await;
1102        });
1103        return Ok(TaskLaunchReply(
1104            TaskLaunchResponse {
1105                final_ctx: Value::Null,
1106                bound_version: None,
1107                effective_ttl_secs: ttl_secs,
1108                ttl_source,
1109                task_id,
1110                run_id,
1111                status: RunStatus::Running,
1112            },
1113            StatusCode::ACCEPTED,
1114        ));
1115    }
1116
1117    // GH #33 Guard 2: the single await point this handler blocks on. On
1118    // expiry the timed-out future is dropped, cancelling the in-process
1119    // flow eval — the flow is abandoned, not resumed (intended v1
1120    // semantics; stage-granularity resume is a coarser guarantee than
1121    // this handler makes, out of scope here).
1122    let outcome = match tokio::time::timeout(
1123        Duration::from_secs(sync_timeout_secs),
1124        state.task_app.handle_with_run(input, Some(run_ctx)),
1125    )
1126    .await
1127    {
1128        Ok(outcome) => outcome,
1129        Err(_elapsed) => {
1130            // Best effort: mark the Task/Run so they do not stay `Running`
1131            // forever. Reuses the existing `Failed` variant (no new
1132            // schema-crate enum additions) and stashes a reason string
1133            // into `RunRecord.result_ref` — the only free-form field the
1134            // Run schema carries; secondary persistence failures here are
1135            // logged and swallowed, mirroring `tasks::finalize_run`'s
1136            // error-path convention.
1137            let reason = json!({
1138                "error": format!("sync launch exceeded {sync_timeout_secs}s timeout ceiling"),
1139            });
1140            if let Err(e) = state.run_store.set_result(&run_id, reason).await {
1141                tracing::warn!(%run_id, error = %e, "run_flow_form: timeout run set_result failed");
1142            }
1143            if let Err(e) = state
1144                .run_store
1145                .update_status(&run_id, RunStatus::Failed)
1146                .await
1147            {
1148                tracing::warn!(%run_id, error = %e, "run_flow_form: timeout run update_status(Failed) failed");
1149            }
1150            if let Err(e) = state
1151                .task_store
1152                .update_status(&task_id, TaskRecordStatus::Failed)
1153                .await
1154            {
1155                tracing::warn!(%task_id, error = %e, "run_flow_form: timeout task update_status(Failed) failed");
1156            }
1157            return Err(ApiError::timeout(format!(
1158                "sync launch exceeded {sync_timeout_secs}s timeout ceiling: the in-process flow \
1159                 eval was abandoned (dropping the future cancels it); attach an operator that \
1160                 acks promptly (POST /v1/operators + WS), or raise timeout_secs / sync_timeout_secs"
1161            )));
1162        }
1163    };
1164
1165    let out = tasks::finalize_run(state, &task_id, &run_id, outcome)
1166        .await
1167        .map_err(|e| ApiError::bad_request(format!("run: {e}")))?;
1168
1169    Ok(TaskLaunchReply(
1170        TaskLaunchResponse {
1171            final_ctx: out.final_ctx,
1172            bound_version: out.bound_version.map(|v| format!("{:?}", v)),
1173            effective_ttl_secs: ttl_secs,
1174            ttl_source,
1175            task_id,
1176            run_id,
1177            status: RunStatus::Done,
1178        },
1179        StatusCode::OK,
1180    ))
1181}
1182
1183/// issue #19 ST2 direct sibling-field resolver — extracts the three
1184/// Task-level canonical fields (`project_root` / `work_dir` /
1185/// `task_metadata`) once at the wire boundary. Sibling top-level body
1186/// fields take priority; the pre-#19 shape (same key nested inside
1187/// `init_ctx`) is only a fallback for legacy callers. Unlike the ST1
1188/// `resolve_task_level_init_ctx` bridge this replaced, `init_ctx` is
1189/// NOT mutated — the resolved values are handed straight to
1190/// [`mlua_swarm::service::TaskLaunchInput::task_input`], keeping
1191/// `init_ctx` a pure flow-ir eval seed.
1192///
1193/// Returns `None` when all three fields resolve to `None` (no
1194/// middleware is layered onto the spawner stack downstream — the
1195/// [`mlua_swarm::middleware::task_input::TaskInputMiddleware::new_from_fields`]
1196/// contract).
1197fn build_task_input_spec_from_request(
1198    req: &TaskLaunchRequest,
1199) -> Option<mlua_swarm::service::TaskInputSpec> {
1200    let project_root = req.project_root.clone().or_else(|| {
1201        req.init_ctx
1202            .get("project_root")
1203            .and_then(Value::as_str)
1204            .map(String::from)
1205    });
1206    let work_dir = req.work_dir.clone().or_else(|| {
1207        req.init_ctx
1208            .get("work_dir")
1209            .and_then(Value::as_str)
1210            .map(String::from)
1211    });
1212    let task_metadata = req.task_metadata.clone().or_else(|| {
1213        req.init_ctx
1214            .get("task_metadata")
1215            .filter(|v| v.is_object())
1216            .cloned()
1217    });
1218
1219    if project_root.is_none() && work_dir.is_none() && task_metadata.is_none() {
1220        None
1221    } else {
1222        Some(mlua_swarm::service::TaskInputSpec {
1223            project_root,
1224            work_dir,
1225            task_metadata,
1226        })
1227    }
1228}
1229
1230// ─── helpers ─────────────────────────────────────────────────────────────
1231
1232async fn take_session_token(state: &AppState, sid: &str) -> Result<CapToken, ApiError> {
1233    // `sid` on this path is the token nonce itself (a bearer secret), so
1234    // both the map key and the not-found diagnostic use its fingerprint
1235    // (issue #14 — never echo the nonce back in an error body).
1236    let key = mlua_swarm::types::token_fingerprint(sid);
1237    state
1238        .sessions
1239        .lock()
1240        .await
1241        .map
1242        .remove(&key)
1243        .ok_or_else(|| ApiError::not_found(format!("session: fp={key}")))
1244}
1245
1246/// Extracts sid from `Authorization: Bearer <sid>`. Strict — does not accept any other scheme prefix.
1247fn extract_bearer(headers: &HeaderMap) -> Result<String, ApiError> {
1248    let v = headers
1249        .get(AUTHORIZATION)
1250        .ok_or_else(|| ApiError::bad_request("missing Authorization header".into()))?
1251        .to_str()
1252        .map_err(|_| ApiError::bad_request("invalid Authorization header encoding".into()))?;
1253    let sid = v
1254        .strip_prefix("Bearer ")
1255        .ok_or_else(|| ApiError::bad_request("Authorization must be 'Bearer <sid>'".into()))?
1256        .trim();
1257    if sid.is_empty() {
1258        return Err(ApiError::bad_request("Bearer sid is empty".into()));
1259    }
1260    Ok(sid.to_string())
1261}
1262
1263fn parse_role(s: &str) -> Result<Role, ApiError> {
1264    match s.to_ascii_lowercase().as_str() {
1265        "operator" => Ok(Role::Operator),
1266        "worker" => Ok(Role::Worker),
1267        "observer" => Ok(Role::Observer),
1268        "senior" => Ok(Role::Senior),
1269        other => Err(ApiError::bad_request(format!("unknown role: {other}"))),
1270    }
1271}
1272
1273// ─── error type ──────────────────────────────────────────────────────────
1274
1275/// Uniform error response type for the handlers in this module. Converts to
1276/// a JSON `{"error": message}` body with the given status via [`IntoResponse`].
1277#[derive(Debug)]
1278pub struct ApiError {
1279    status: StatusCode,
1280    message: String,
1281}
1282
1283impl ApiError {
1284    /// Wraps an engine-side error as `500 Internal Server Error`.
1285    pub fn engine(e: impl std::fmt::Display) -> Self {
1286        Self {
1287            status: StatusCode::INTERNAL_SERVER_ERROR,
1288            message: format!("engine: {e}"),
1289        }
1290    }
1291    /// Builds a `404 Not Found` with the given message.
1292    pub fn not_found(m: String) -> Self {
1293        Self {
1294            status: StatusCode::NOT_FOUND,
1295            message: m,
1296        }
1297    }
1298    /// Builds a `400 Bad Request` with the given message.
1299    pub fn bad_request(m: String) -> Self {
1300        Self {
1301            status: StatusCode::BAD_REQUEST,
1302            message: m,
1303        }
1304    }
1305    /// Builds a `503 Service Unavailable` with the given message (GH #33
1306    /// Guard 1 — operator readiness precheck).
1307    pub fn unavailable(m: String) -> Self {
1308        Self {
1309            status: StatusCode::SERVICE_UNAVAILABLE,
1310            message: m,
1311        }
1312    }
1313    /// Builds a `504 Gateway Timeout` with the given message (GH #33
1314    /// Guard 2 — sync launch timeout ceiling).
1315    pub fn timeout(m: String) -> Self {
1316        Self {
1317            status: StatusCode::GATEWAY_TIMEOUT,
1318            message: m,
1319        }
1320    }
1321    /// Builds a `410 Gone` with the given message (GH #37 — worker
1322    /// submit/artifact addressed at a Run that already reached a terminal
1323    /// status; the silent-`204`-then-orphan alternative is the failure
1324    /// shape this replaces).
1325    pub fn gone(m: String) -> Self {
1326        Self {
1327            status: StatusCode::GONE,
1328            message: m,
1329        }
1330    }
1331    /// Builds a `413 Payload Too Large` with the given message (GH #42 —
1332    /// `@file:` sentinel resolves to a file larger than the shared
1333    /// `DefaultBodyLimit`; same size ceiling as the inline body path).
1334    pub fn payload_too_large(m: String) -> Self {
1335        Self {
1336            status: StatusCode::PAYLOAD_TOO_LARGE,
1337            message: m,
1338        }
1339    }
1340    /// Builds a `422 Unprocessable Entity` with the given message (GH #50
1341    /// — a `worker_submit` / `worker_artifact` value violates the
1342    /// dispatching agent's declared `VerdictContract`: rejected before it
1343    /// reaches `submit_worker_result_trusted` / `stage_worker_artifact_trusted`,
1344    /// i.e. before it can land in the flow ctx).
1345    pub fn unprocessable(m: impl Into<String>) -> Self {
1346        Self {
1347            status: StatusCode::UNPROCESSABLE_ENTITY,
1348            message: m.into(),
1349        }
1350    }
1351}
1352
1353impl IntoResponse for ApiError {
1354    fn into_response(self) -> Response {
1355        (self.status, Json(json!({"error": self.message}))).into_response()
1356    }
1357}
1358
1359fn default_run_ttl() -> u64 {
1360    // 1800s (= 30 min). Prevents op_token expiry across a flow.ir multi-step chain
1361    // (= 5+ SubAgent dispatches at 30–60s each). Origin: the observed fvloop smoke
1362    // where a post-gate mock-commit dispatch blew past 300s and expired — sibling of worker_token TTL.
1363    1800
1364}
1365
1366/// TTL cascade resolve helper (Blueprint metadata → server default fallback).
1367/// Second-stage fallback, called when the POST `/v1/tasks` body does not set `ttl_secs`.
1368/// (1) If BP metadata `default_run_ttl_secs` is `Some`, use it.
1369/// (2) If `None`, fall back to the server global `default_run_ttl()` (1800s).
1370///
1371/// # Full cascade (combined in `run_flow_form`)
1372///
1373/// - request body `ttl_secs=Some(v)` → v (this helper is not called)
1374/// - request body `None` + metadata `Some(v)` → v
1375/// - request body `None` + metadata `None` → `default_run_ttl()` = 1800s
1376#[cfg(test)]
1377fn resolve_ttl_from_metadata(metadata_ttl: Option<u64>) -> u64 {
1378    metadata_ttl.unwrap_or_else(default_run_ttl)
1379}
1380
1381#[cfg(test)]
1382mod tests {
1383    use super::*;
1384
1385    /// TTL cascade case 1: when the request body sets it, that value is used as-is
1386    /// (upper branch that does not go through the helper; semantic verify of the
1387    /// `Some(v) => v` direct-return path in `run_flow_form`).
1388    #[test]
1389    fn ttl_cascade_request_body_wins_over_metadata() {
1390        let req_ttl: Option<u64> = Some(100);
1391        let metadata_ttl: Option<u64> = Some(3600);
1392        let effective = match req_ttl {
1393            Some(v) => v,
1394            None => resolve_ttl_from_metadata(metadata_ttl),
1395        };
1396        assert_eq!(
1397            effective, 100,
1398            "request body ttl_secs=100 must win over metadata=3600 (cascade priority (1) > (2))"
1399        );
1400    }
1401
1402    /// TTL cascade case 2: request body omitted + BP metadata `Some(N)` → `N` is effective.
1403    #[test]
1404    fn ttl_cascade_metadata_used_when_body_missing() {
1405        let req_ttl: Option<u64> = None;
1406        let metadata_ttl: Option<u64> = Some(3600);
1407        let effective = match req_ttl {
1408            Some(v) => v,
1409            None => resolve_ttl_from_metadata(metadata_ttl),
1410        };
1411        assert_eq!(
1412            effective, 3600,
1413            "body None + metadata=3600 must resolve to 3600 (cascade (2))"
1414        );
1415    }
1416
1417    /// TTL cascade case 3: request body omitted + BP metadata `None` → server default (1800s).
1418    #[test]
1419    fn ttl_cascade_server_default_when_both_missing() {
1420        let req_ttl: Option<u64> = None;
1421        let metadata_ttl: Option<u64> = None;
1422        let effective = match req_ttl {
1423            Some(v) => v,
1424            None => resolve_ttl_from_metadata(metadata_ttl),
1425        };
1426        assert_eq!(
1427            effective,
1428            default_run_ttl(),
1429            "body None + metadata None must fall back to default_run_ttl() = 1800s"
1430        );
1431        assert_eq!(effective, 1800, "default_run_ttl() literal = 1800s");
1432    }
1433
1434    /// Helper unit: metadata `None` → 1800 (server default expansion).
1435    #[test]
1436    fn resolve_ttl_from_metadata_none_returns_server_default() {
1437        assert_eq!(resolve_ttl_from_metadata(None), 1800);
1438    }
1439
1440    /// Helper unit: metadata `Some(N)` → `N` (server default ignored).
1441    #[test]
1442    fn resolve_ttl_from_metadata_some_returns_value() {
1443        assert_eq!(resolve_ttl_from_metadata(Some(7200)), 7200);
1444        assert_eq!(resolve_ttl_from_metadata(Some(60)), 60);
1445    }
1446
1447    // ──────────────────────────────────────────────────────────────────
1448    // issue #19 ST2: `build_task_input_spec_from_request` direct resolver
1449    // ──────────────────────────────────────────────────────────────────
1450
1451    fn task_req(
1452        init_ctx: Value,
1453        project_root: Option<&str>,
1454        work_dir: Option<&str>,
1455        task_metadata: Option<Value>,
1456    ) -> TaskLaunchRequest {
1457        TaskLaunchRequest {
1458            blueprint: BlueprintRef::Id {
1459                id: mlua_swarm::blueprint::store::BlueprintId::new("ut"),
1460                version: Default::default(),
1461            },
1462            init_ctx,
1463            project_root: project_root.map(String::from),
1464            work_dir: work_dir.map(String::from),
1465            task_metadata,
1466            ttl_secs: None,
1467            operator: None,
1468            operator_sid: None,
1469            timeout_secs: None,
1470            goal: None,
1471            detach: false,
1472        }
1473    }
1474
1475    /// (a) Sibling fields only — no legacy keys in `init_ctx` — are
1476    /// returned in the `TaskInputSpec` unchanged. `init_ctx` itself is
1477    /// untouched by this resolver (checked separately at the call site).
1478    #[test]
1479    fn build_task_input_spec_from_request_returns_sibling_fields_when_present() {
1480        let req = task_req(
1481            json!({"free": "form"}),
1482            Some("/repo/sibling"),
1483            Some("/repo/sibling/work"),
1484            Some(json!({"issue": 19})),
1485        );
1486        let spec = build_task_input_spec_from_request(&req).expect("spec must be Some");
1487        assert_eq!(spec.project_root.as_deref(), Some("/repo/sibling"));
1488        assert_eq!(spec.work_dir.as_deref(), Some("/repo/sibling/work"));
1489        assert_eq!(spec.task_metadata, Some(json!({"issue": 19})));
1490    }
1491
1492    /// (b) No sibling fields — the pre-#19 shape (same 3 keys nested
1493    /// inside `init_ctx`) is used as the fallback source.
1494    #[test]
1495    fn build_task_input_spec_from_request_falls_back_to_legacy_init_ctx_shape() {
1496        let req = task_req(
1497            json!({
1498                "project_root": "/repo/legacy",
1499                "work_dir": "/repo/legacy/work",
1500                "task_metadata": {"issue": 17},
1501            }),
1502            None,
1503            None,
1504            None,
1505        );
1506        let spec = build_task_input_spec_from_request(&req).expect("spec must be Some");
1507        assert_eq!(spec.project_root.as_deref(), Some("/repo/legacy"));
1508        assert_eq!(spec.work_dir.as_deref(), Some("/repo/legacy/work"));
1509        assert_eq!(spec.task_metadata, Some(json!({"issue": 17})));
1510    }
1511
1512    /// (c) Both present — the sibling field must win over the legacy
1513    /// `init_ctx`-nested value.
1514    #[test]
1515    fn build_task_input_spec_from_request_sibling_wins_over_legacy_shape() {
1516        let req = task_req(
1517            json!({
1518                "project_root": "/repo/legacy",
1519                "work_dir": "/repo/legacy/work",
1520                "task_metadata": {"issue": 17},
1521            }),
1522            Some("/repo/sibling"),
1523            Some("/repo/sibling/work"),
1524            Some(json!({"issue": 19})),
1525        );
1526        let spec = build_task_input_spec_from_request(&req).expect("spec must be Some");
1527        assert_eq!(
1528            spec.project_root.as_deref(),
1529            Some("/repo/sibling"),
1530            "sibling field must win over the legacy init_ctx-nested value"
1531        );
1532        assert_eq!(spec.work_dir.as_deref(), Some("/repo/sibling/work"));
1533        assert_eq!(spec.task_metadata, Some(json!({"issue": 19})));
1534    }
1535
1536    /// (d) All three fields absent from both sibling and legacy shapes —
1537    /// resolver returns `None`, and no middleware is layered downstream.
1538    #[test]
1539    fn build_task_input_spec_from_request_returns_none_when_no_fields_present() {
1540        let req = task_req(json!({"unrelated": "value"}), None, None, None);
1541        assert!(build_task_input_spec_from_request(&req).is_none());
1542    }
1543
1544    /// Minimal `AppState` for the `status_get` handler-fn-direct-call test
1545    /// below — same construction shape as `tasks.rs::test_state()`
1546    /// (mirrors what `build_router_full` does internally, skipping the
1547    /// `Router` wrapper).
1548    fn status_test_state() -> AppState {
1549        let engine = Engine::new(mlua_swarm::EngineCfg::default());
1550        let compiler = mlua_swarm::Compiler::new(default_registry());
1551        let launch = Arc::new(mlua_swarm::TaskLaunchService::new(engine.clone(), compiler));
1552        AppState {
1553            engine,
1554            sessions: Arc::new(Mutex::new(SessionStore::default())),
1555            task_app: Arc::new(mlua_swarm::TaskApplication::new_inline_only(launch)),
1556            ws_operator_factory: None,
1557            data_store: Arc::new(mlua_swarm::store::output::InMemoryOutputStore::new()),
1558            operator_sessions: Arc::new(Mutex::new(HashMap::new())),
1559            roles_to_sid: Arc::new(Mutex::new(HashMap::new())),
1560            task_store: Arc::new(mlua_swarm::store::task::InMemoryTaskStore::new()),
1561            run_store: Arc::new(mlua_swarm::store::run::InMemoryRunStore::new()),
1562            base_url: None,
1563            sync_timeout_secs: 300,
1564        }
1565    }
1566
1567    /// issue #35 ST4 Acceptance Criteria: `GET /v1/status` reports the
1568    /// count of `Running` `Run`s (`RunStore::list_running`) and attached
1569    /// Operator ids (`engine.list_operator_ids()`), called directly as a
1570    /// handler fn (no `Router` wrapper — this crate's established
1571    /// unit-test convention).
1572    #[tokio::test]
1573    async fn status_get_reports_running_runs_and_operators() {
1574        let state = status_test_state();
1575
1576        let now = std::time::SystemTime::now()
1577            .duration_since(std::time::UNIX_EPOCH)
1578            .map(|d| d.as_secs())
1579            .unwrap_or(0);
1580        state
1581            .run_store
1582            .create(RunRecord {
1583                id: RunId::new(),
1584                task_id: TaskId::new(),
1585                status: RunStatus::Running,
1586                step_entries: Vec::new(),
1587                degradations: Vec::new(),
1588                operator_sid: None,
1589                result_ref: None,
1590                created_at: now,
1591                updated_at: now,
1592            })
1593            .await
1594            .expect("seed running RunRecord");
1595
1596        // Throwaway `Operator` impl — only registration/list-count matters
1597        // for this test, `execute` is never dispatched (same idiom as
1598        // `tasks.rs::StallingOperator`).
1599        struct NoopOperator;
1600        #[async_trait::async_trait]
1601        impl mlua_swarm::Operator for NoopOperator {
1602            async fn execute(
1603                &self,
1604                _ctx: &mlua_swarm::Ctx,
1605                _system: Option<String>,
1606                _prompt: Value,
1607                _worker: Option<mlua_swarm::WorkerBinding>,
1608                _worker_token: mlua_swarm::CapToken,
1609            ) -> Result<mlua_swarm::WorkerResult, mlua_swarm::WorkerError> {
1610                unimplemented!("not exercised by this test — only registration/list matters")
1611            }
1612        }
1613        state
1614            .engine
1615            .register_operator("test-op", Arc::new(NoopOperator))
1616            .await;
1617
1618        let Json(resp) = status_get(State(state)).await;
1619        assert_eq!(resp.running_runs, 1);
1620        assert_eq!(resp.attached_operators, 1);
1621    }
1622}