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