mlua-swarm-cli 0.6.0

Command line interface for mlua-swarm (mse binary with serve / mcp subcommands).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! MCP Resource surface for `mse mcp` — read-only guides + Blueprint
//! samples + the live Blueprint JSON Schema, addressable by URI.
//!
//! Guide and sample bodies are baked via `include_str!` at compile time
//! (no runtime file I/O), and the source `.md` / `.json` files live
//! **inside the crate directory** (`src/mcp/resources/guides/` and
//! `src/mcp/resources/samples/`) so `cargo publish` packages them
//! automatically. The one exception is `mse://api/blueprint-schema`,
//! whose body is generated at `read_resource` time from the same
//! `schemars`-derived [`Blueprint`] schema the `bp_schema` tool returns
//! (see [`blueprint_schema_value`]).
//!
//! ## URI scheme
//!
//! ```text
//! mse://guides/<slug>
//! mse://blueprints/samples/<slug>
//! mse://api/blueprint-schema
//! mse://api/http-endpoints
//! ```
//!
//! ## Current resources
//!
//! | uri                                       | role                                              |
//! |--------------------------------------------|---------------------------------------------------|
//! | `mse://guides/getting-started`              | Entry points, quickstart, MCP client wiring.       |
//! | `mse://guides/blueprint-authoring`           | Flow node kinds, expr ops, agents, versioning.     |
//! | `mse://guides/mcp-tool-reference`            | All `mse mcp` tools grouped by family.             |
//! | `mse://guides/id-lifecycle`                  | Canonical ID inventory + lifecycle (issue #11).     |
//! | `mse://guides/operator-execution-model`      | 3-hop execution model for `AgentKind::Operator` (WS thin-path). |
//! | `mse://blueprints/samples/01-pure-ctx-eval`  | Zero-spawn ctx-only Blueprint sample.               |
//! | `mse://blueprints/samples/02-verdict-loop`   | Verdict retry-loop Blueprint sample.                |
//! | `mse://blueprints/samples/03-fn-override`    | Verdict fn-override Blueprint sample.               |
//! | `mse://api/blueprint-schema`                 | Live Blueprint JSON Schema (generated per read).    |
//! | `mse://api/http-endpoints`                   | Live HTTP wire-body JSON Schemas, keyed by endpoint (issue #19 ST5). |
//!
//! `mse://api/http-endpoints` is deliberately a separate resource from
//! `mse://api/blueprint-schema` — the two schemas serve different
//! readers (HTTP wire body vs. the Blueprint document format) and mixing
//! them into one JSON document would blur that boundary. Fields whose
//! type is the Blueprint document itself (`TaskLaunchRequest.blueprint`)
//! stay opaque here; see [`http_endpoints_schema_value`].

use mlua_swarm::blueprint::Blueprint;

/// How a [`ResourceEntry`] produces its body when read.
pub enum ResourceBody {
    /// Body is baked in at compile time via `include_str!`.
    Static(&'static str),
    /// Body is generated at `read_resource` time (the Blueprint JSON Schema).
    BlueprintSchema,
    /// Body is generated at `read_resource` time (the HTTP wire-body JSON
    /// Schemas, keyed by endpoint; see [`http_endpoints_schema_value`]).
    HttpEndpoints,
}

/// One MCP Resource entry exposed under the `mse://` scheme.
pub struct ResourceEntry {
    /// Full resource URI, e.g. `"mse://guides/getting-started"`.
    pub uri: &'static str,
    /// Human-readable title (used as the `resources/list` `name`).
    pub title: &'static str,
    /// One-line description shown in `resources/list`.
    pub description: &'static str,
    /// MIME type reported in `resources/list` and `resources/read`.
    pub mime_type: &'static str,
    /// Body source (static or dynamically generated).
    pub body: ResourceBody,
}

const GETTING_STARTED_BODY: &str = include_str!("./resources/guides/getting-started.md");
const BLUEPRINT_AUTHORING_BODY: &str = include_str!("./resources/guides/blueprint-authoring.md");
const MCP_TOOL_REFERENCE_BODY: &str = include_str!("./resources/guides/mcp-tool-reference.md");
const ID_LIFECYCLE_BODY: &str = include_str!("./resources/guides/id-lifecycle.md");
const OPERATOR_EXECUTION_MODEL_BODY: &str =
    include_str!("./resources/guides/operator-execution-model.md");

const SAMPLE_01_PURE_CTX_EVAL_BODY: &str =
    include_str!("./resources/samples/01-pure-ctx-eval.json");
const SAMPLE_02_VERDICT_LOOP_BODY: &str = include_str!("./resources/samples/02-verdict-loop.json");
const SAMPLE_03_FN_OVERRIDE_BODY: &str = include_str!("./resources/samples/03-fn-override.json");

/// Static resource catalogue. Order is the order `list_resources` reports.
pub const RESOURCES: &[ResourceEntry] = &[
    ResourceEntry {
        uri: "mse://guides/getting-started",
        title: "mse — Getting started",
        description: "What mse is, the three entry points (serve / mcp / run), and quickstart snippets.",
        mime_type: "text/markdown",
        body: ResourceBody::Static(GETTING_STARTED_BODY),
    },
    ResourceEntry {
        uri: "mse://guides/blueprint-authoring",
        title: "mse — Blueprint authoring guide",
        description: "Blueprint shape, flow node kinds, expr ops, agents, $agent_md refs, and versioning.",
        mime_type: "text/markdown",
        body: ResourceBody::Static(BLUEPRINT_AUTHORING_BODY),
    },
    ResourceEntry {
        uri: "mse://guides/mcp-tool-reference",
        title: "mse — MCP tool reference",
        description: "All mse mcp tools grouped by family, with side-effect notes.",
        mime_type: "text/markdown",
        body: ResourceBody::Static(MCP_TOOL_REFERENCE_BODY),
    },
    ResourceEntry {
        uri: "mse://guides/id-lifecycle",
        title: "mse — ID lifecycle",
        description: "Canonical inventory of every run-pipeline identifier (Blueprint/Task/Run/Step/Attempt, sid, worker_handle, req_id, capability_token) with mint sites and lifecycle scopes.",
        mime_type: "text/markdown",
        body: ResourceBody::Static(ID_LIFECYCLE_BODY),
    },
    ResourceEntry {
        uri: "mse://guides/operator-execution-model",
        title: "mse — Operator execution model",
        description: "The three-hop execution model for AgentKind::Operator (WS thin-path): Task IF → mse-server splice → MainAI → SubAgent. Explains the responsibility boundary at each hop.",
        mime_type: "text/markdown",
        body: ResourceBody::Static(OPERATOR_EXECUTION_MODEL_BODY),
    },
    ResourceEntry {
        uri: "mse://blueprints/samples/01-pure-ctx-eval",
        title: "Sample Blueprint — pure ctx eval",
        description: "Zero-spawn pure ctx evaluation using Assign + And + Gt + Lt + Lit primitives.",
        mime_type: "application/json",
        body: ResourceBody::Static(SAMPLE_01_PURE_CTX_EVAL_BODY),
    },
    ResourceEntry {
        uri: "mse://blueprints/samples/02-verdict-loop",
        title: "Sample Blueprint — verdict loop",
        description: "Verdict retry loop with a self-managed counter (Loop + Branch + Operator agents).",
        mime_type: "application/json",
        body: ResourceBody::Static(SAMPLE_02_VERDICT_LOOP_BODY),
    },
    ResourceEntry {
        uri: "mse://blueprints/samples/03-fn-override",
        title: "Sample Blueprint — fn override",
        description: "A BLOCKED verdict overridden to ALLOW by an approver step, gating a commit branch.",
        mime_type: "application/json",
        body: ResourceBody::Static(SAMPLE_03_FN_OVERRIDE_BODY),
    },
    ResourceEntry {
        uri: "mse://api/blueprint-schema",
        title: "Blueprint JSON Schema",
        description: "Live schemars-generated JSON Schema for the Blueprint type. flow is opaque (owned by mlua-flow-ir).",
        mime_type: "application/json",
        body: ResourceBody::BlueprintSchema,
    },
    ResourceEntry {
        uri: "mse://api/http-endpoints",
        title: "HTTP endpoint wire-body JSON Schemas",
        description: "Live schemars-generated request/response JSON Schemas for /v1/blueprints, /v1/tasks, and /v1/tasks/:id/runs, keyed by endpoint. A separate resource from mse://api/blueprint-schema (issue #19 ST5).",
        mime_type: "application/json",
        body: ResourceBody::HttpEndpoints,
    },
];

/// Look up a resource entry by its full URI. Returns `None` for unknown URIs.
pub fn find_by_uri(uri: &str) -> Option<&'static ResourceEntry> {
    RESOURCES.iter().find(|r| r.uri == uri)
}

/// Generate the Blueprint JSON Schema (schemars-derived) as a
/// `serde_json::Value`. Shared by the `bp_schema` tool and the
/// `mse://api/blueprint-schema` dynamic resource so both surfaces stay
/// byte-for-byte identical.
pub fn blueprint_schema_value() -> Result<serde_json::Value, serde_json::Error> {
    let schema = schemars::schema_for!(Blueprint);
    serde_json::to_value(&schema)
}

/// Generate the HTTP endpoint wire-body JSON Schemas (issue #19 ST5) as a
/// `serde_json::Value`, keyed by endpoint. Shared by the
/// `mse://api/http-endpoints` dynamic resource; regenerated on every call
/// so it never drifts from the wire structs' current shape.
///
/// Form (endpoint-unit map, easy to extend — `must_not_simplify #5`):
/// `{"endpoints": {"<METHOD PATH>": {"request"?, "response"?}}}`. Endpoints
/// whose request body *is* the Blueprint document (`POST
/// /v1/blueprints/:id`) point at `mse://api/blueprint-schema` by URI
/// instead of duplicating that schema here — the two resources stay
/// separate documents (see the module doc / `must_not_simplify #1` /
/// `#6`). Thin endpoints (`doctor` / `healthz`) are out of this
/// subtask's scope; adding one later is one more map entry.
pub fn http_endpoints_schema_value() -> Result<serde_json::Value, serde_json::Error> {
    let task_launch_request_schema = schemars::schema_for!(mlua_swarm_server::TaskLaunchRequest);
    let task_launch_request = serde_json::to_value(&task_launch_request_schema)?;
    let task_launch_response_schema = schemars::schema_for!(mlua_swarm_server::TaskLaunchResponse);
    let task_launch_response = serde_json::to_value(&task_launch_response_schema)?;
    let task_detail_response_schema = schemars::schema_for!(mlua_swarm_server::TaskDetailResponse);
    let task_detail_response = serde_json::to_value(&task_detail_response_schema)?;
    let run_kick_request_schema = schemars::schema_for!(mlua_swarm_server::RunKickRequest);
    let run_kick_request = serde_json::to_value(&run_kick_request_schema)?;
    let run_kick_response_schema = schemars::schema_for!(mlua_swarm_server::RunKickResponse);
    let run_kick_response = serde_json::to_value(&run_kick_response_schema)?;

    Ok(serde_json::json!({
        "endpoints": {
            "POST /v1/blueprints/:id": {
                "request": {
                    "$comment": "Body is a Blueprint document verbatim; see mse://api/blueprint-schema for its schema.",
                    "schema_ref": "mse://api/blueprint-schema",
                },
                "response": {
                    "$comment": "Ad-hoc JSON {id, version, seeded} (201/200); not yet a typed schemars struct.",
                },
            },
            "POST /v1/tasks": {
                "request": task_launch_request,
                "response": task_launch_response,
            },
            "GET /v1/tasks/:id": {
                "response": task_detail_response,
            },
            "POST /v1/tasks/:id/runs": {
                "request": run_kick_request,
                "response": run_kick_response,
            },
        },
    }))
}

/// Resolve a resource entry's body as a `String`. Static entries return
/// instantly; the schema entries generate fresh JSON on every call so
/// they never drift from the underlying Rust types.
pub fn body_for(entry: &ResourceEntry) -> Result<String, String> {
    match entry.body {
        ResourceBody::Static(s) => Ok(s.to_string()),
        ResourceBody::BlueprintSchema => {
            let value = blueprint_schema_value().map_err(|e| format!("schema serialize: {e}"))?;
            serde_json::to_string_pretty(&value).map_err(|e| format!("schema stringify: {e}"))
        }
        ResourceBody::HttpEndpoints => {
            let value =
                http_endpoints_schema_value().map_err(|e| format!("schema serialize: {e}"))?;
            serde_json::to_string_pretty(&value).map_err(|e| format!("schema stringify: {e}"))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resources_have_non_empty_uri_and_body() {
        for r in RESOURCES {
            assert!(!r.uri.is_empty(), "uri empty for {}", r.title);
            let body = body_for(r).expect("body must generate");
            assert!(!body.is_empty(), "body empty for {}", r.title);
        }
    }

    #[test]
    fn find_by_uri_round_trip() {
        for r in RESOURCES {
            let found = find_by_uri(r.uri).expect("resource must be found by its own uri");
            assert_eq!(found.uri, r.uri);
        }
    }

    #[test]
    fn find_by_uri_rejects_unknown_uri() {
        assert!(find_by_uri("mse://guides/nonexistent").is_none());
        assert!(find_by_uri("mse://other/getting-started").is_none());
        assert!(find_by_uri("https://example.com").is_none());
    }

    #[test]
    fn blueprint_schema_resource_generates_valid_json() {
        let entry = find_by_uri("mse://api/blueprint-schema").expect("schema resource must exist");
        let body = body_for(entry).expect("schema resource body generation must succeed");
        let parsed: serde_json::Value =
            serde_json::from_str(&body).expect("body must be valid JSON");
        assert!(
            parsed.get("properties").is_some(),
            "schema must expose properties"
        );
    }

    #[test]
    fn http_endpoints_resource_generates_valid_json_with_expected_endpoints() {
        let entry = find_by_uri("mse://api/http-endpoints").expect("resource must exist");
        let body = body_for(entry).expect("http-endpoints resource body generation must succeed");
        let parsed: serde_json::Value =
            serde_json::from_str(&body).expect("body must be valid JSON");
        let endpoints = parsed
            .get("endpoints")
            .expect("body must expose an endpoints map")
            .as_object()
            .expect("endpoints must be a JSON object");
        for key in [
            "POST /v1/blueprints/:id",
            "POST /v1/tasks",
            "GET /v1/tasks/:id",
            "POST /v1/tasks/:id/runs",
        ] {
            assert!(
                endpoints.contains_key(key),
                "endpoints map must include {key}, got keys: {:?}",
                endpoints.keys().collect::<Vec<_>>()
            );
        }
        // POST /v1/tasks request schema must expose the TaskLaunchRequest
        // properties, and must NOT inline the Blueprint schema (must_not_simplify #1/#6).
        let tasks_request = &endpoints["POST /v1/tasks"]["request"];
        let props = tasks_request
            .get("properties")
            .expect("POST /v1/tasks request must expose properties");
        assert!(
            props.get("init_ctx").is_some(),
            "TaskLaunchRequest schema must expose init_ctx: {tasks_request}"
        );
        assert!(
            props.get("blueprint").is_some(),
            "TaskLaunchRequest schema must expose blueprint (opaque): {tasks_request}"
        );
        // must_not_simplify #6: the blueprint field stays opaque here — no
        // nested Blueprint-schema properties (e.g. `flow`/`agents`) leak in.
        assert!(
            tasks_request.get("flow").is_none(),
            "Blueprint schema must not be inlined into the http-endpoints resource"
        );
        // POST /v1/blueprints/:id cross-refs the existing blueprint-schema
        // resource instead of duplicating it.
        assert_eq!(
            endpoints["POST /v1/blueprints/:id"]["request"]["schema_ref"],
            serde_json::json!("mse://api/blueprint-schema")
        );
    }

    #[test]
    fn sample_bodies_deserialize_into_blueprint() {
        // Guards the shipped samples against Blueprint schema drift: every
        // sample must parse as the typed Blueprint, not merely as JSON.
        for uri in [
            "mse://blueprints/samples/01-pure-ctx-eval",
            "mse://blueprints/samples/02-verdict-loop",
            "mse://blueprints/samples/03-fn-override",
        ] {
            let entry = find_by_uri(uri).unwrap_or_else(|| panic!("sample must exist: {uri}"));
            let body = body_for(entry).expect("sample body must generate");
            let bp: Blueprint = serde_json::from_str(&body)
                .unwrap_or_else(|e| panic!("{uri}: not a valid Blueprint: {e}"));
            assert!(
                !bp.id.as_str().is_empty(),
                "{uri}: sample Blueprint must carry a non-empty id"
            );
        }
    }

    /// Guide ↔ schema drift guard (issue #6, layer 2 AC #4).
    ///
    /// The `blueprint-authoring` guide lists every Expr op / Node kind
    /// with the field names an author writes verbatim. If the upstream
    /// `flow-ir-core` schema renames or removes any of those fields, this
    /// test fails and prompts a guide update — so the guide stays a
    /// trustworthy reference instead of silently drifting.
    ///
    /// Each row is a `(kind_or_op, minimal_json_snippet)` pair. The
    /// snippets use the exact field names documented in the guide.
    #[test]
    fn guide_expr_ops_match_schema_field_names() {
        use mlua_flow_ir::Expr;

        let cases: &[(&str, serde_json::Value)] = &[
            ("path", serde_json::json!({"op":"path","at":"$.x"})),
            ("lit", serde_json::json!({"op":"lit","value":42})),
            (
                "eq",
                serde_json::json!({"op":"eq","lhs":{"op":"lit","value":1},"rhs":{"op":"lit","value":1}}),
            ),
            (
                "ne",
                serde_json::json!({"op":"ne","lhs":{"op":"lit","value":1},"rhs":{"op":"lit","value":2}}),
            ),
            (
                "lt",
                serde_json::json!({"op":"lt","lhs":{"op":"lit","value":1},"rhs":{"op":"lit","value":2}}),
            ),
            (
                "lte",
                serde_json::json!({"op":"lte","lhs":{"op":"lit","value":1},"rhs":{"op":"lit","value":2}}),
            ),
            (
                "gt",
                serde_json::json!({"op":"gt","lhs":{"op":"lit","value":2},"rhs":{"op":"lit","value":1}}),
            ),
            (
                "gte",
                serde_json::json!({"op":"gte","lhs":{"op":"lit","value":2},"rhs":{"op":"lit","value":1}}),
            ),
            (
                "not",
                serde_json::json!({"op":"not","arg":{"op":"lit","value":true}}),
            ),
            (
                "and",
                serde_json::json!({"op":"and","args":[{"op":"lit","value":true}]}),
            ),
            (
                "or",
                serde_json::json!({"op":"or","args":[{"op":"lit","value":true}]}),
            ),
            (
                "exists",
                serde_json::json!({"op":"exists","arg":{"op":"path","at":"$.x"}}),
            ),
            (
                "add",
                serde_json::json!({"op":"add","lhs":{"op":"lit","value":1},"rhs":{"op":"lit","value":2}}),
            ),
            (
                "sub",
                serde_json::json!({"op":"sub","lhs":{"op":"lit","value":3},"rhs":{"op":"lit","value":1}}),
            ),
            (
                "mul",
                serde_json::json!({"op":"mul","lhs":{"op":"lit","value":2},"rhs":{"op":"lit","value":3}}),
            ),
            (
                "div",
                serde_json::json!({"op":"div","lhs":{"op":"lit","value":6},"rhs":{"op":"lit","value":2}}),
            ),
            (
                "mod",
                serde_json::json!({"op":"mod","lhs":{"op":"lit","value":5},"rhs":{"op":"lit","value":2}}),
            ),
            (
                "len",
                serde_json::json!({"op":"len","arg":{"op":"lit","value":"hi"}}),
            ),
            (
                "in",
                serde_json::json!({"op":"in","needle":{"op":"lit","value":1},"haystack":{"op":"lit","value":[1,2,3]}}),
            ),
            (
                "call_extern",
                serde_json::json!({"op":"call_extern","ref":"math.sqrt","args":[{"op":"lit","value":9}]}),
            ),
        ];
        for (op, v) in cases {
            serde_json::from_value::<Expr>(v.clone()).unwrap_or_else(|e| {
                panic!(
                    "guide Expr op `{op}` does not deserialize with the documented field names: {e} \
                     (fix the blueprint-authoring guide or the guide↔schema mapping)"
                )
            });
        }
    }

    #[test]
    fn guide_flow_node_kinds_match_schema_field_names() {
        use mlua_flow_ir::Node;

        let step = serde_json::json!({
            "kind":"step","ref":"a","in":{"op":"path","at":"$.in"},"out":{"op":"path","at":"$.out"}
        });
        let seq = serde_json::json!({"kind":"seq","children":[]});
        let branch = serde_json::json!({
            "kind":"branch",
            "cond":{"op":"lit","value":true},
            "then":{"kind":"seq","children":[]},
            "else":{"kind":"seq","children":[]}
        });
        let loop_n = serde_json::json!({
            "kind":"loop",
            "counter":{"op":"path","at":"$.i"},
            "cond":{"op":"lit","value":true},
            "body":{"kind":"seq","children":[]},
            "max":3
        });
        let fanout = serde_json::json!({
            "kind":"fanout",
            "items":{"op":"lit","value":[1,2]},
            "bind":{"op":"path","at":"$.item"},
            "body":{"kind":"seq","children":[]},
            "join":"all",
            "out":{"op":"path","at":"$.results"}
        });
        let try_n = serde_json::json!({
            "kind":"try",
            "body":{"kind":"seq","children":[]},
            "catch":{"kind":"seq","children":[]},
            "err_at":{"op":"path","at":"$.err"}
        });
        let assign = serde_json::json!({
            "kind":"assign","at":{"op":"path","at":"$.x"},"value":{"op":"lit","value":1}
        });

        for (kind, v) in [
            ("step", step),
            ("seq", seq),
            ("branch", branch),
            ("loop", loop_n),
            ("fanout", fanout),
            ("try", try_n),
            ("assign", assign),
        ] {
            serde_json::from_value::<Node>(v).unwrap_or_else(|e| {
                panic!(
                    "guide Node kind `{kind}` does not deserialize with the documented field names: {e} \
                     (fix the blueprint-authoring guide or the guide↔schema mapping)"
                )
            });
        }
    }
}