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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Blueprint schema — Swarm IF SoT (= the core type set that defines "how a Blueprint object is written").
//!
//! This crate provides **schema types + serde derives only** as a pure IF crate. Execution
//! layers (SpawnerFactory / EngineDispatcher / Compiler) are not included here; consumers
//! (the `mlua-swarm` crate) own them. External consumers, sibling worktrees, and
//! future bundles can read/write Blueprints by depending on this single crate.
//!
//! # Versioning contract
//!
//! `Blueprint.schema_version` is tied to this crate's semver. It is fixed at 0.1.0 for now;
//! during 0.x breaking changes are free, and 1.0 will freeze the schema.
//!
//! # IN-immutability (extension discipline)
//!
//! This crate is the IN side of the swarm layering and stays **plain serde
//! data**: no compile pass, no field the engine macro-expands, no DSL
//! dialect. Flow conds are written literally against the Flow.ir Expr set
//! (`Eq($.<step>.verdict, Lit("blocked"))` — domain verdicts are plain
//! strings in step output). Authoring sugar (builders) lives OUT on the
//! consumer side; runtime behavior extension lives in the engine's
//! `SpawnerLayer` middleware.
//!
//! # AgentKind handling (= internal SoT)
//!
//! [`AgentKind`] is the SoT for the SpawnerAdapter offering axis. It is a closed enum managed
//! inside Swarm, extended by variant addition through **explicit maintenance**. String lookup
//! or a `Custom` escape hatch is deliberately avoided (= structurally eliminates the "silly
//! runtime typos" class of failures).
//!
//! # Examples
//!
//! Build a minimal [`Blueprint`] with a single [`AgentDef`] via struct literal:
//!
//! ```
//! use mlua_swarm_schema::{
//! AgentDef, AgentKind, Blueprint, current_schema_version,
//! };
//! use mlua_flow_ir::{Expr, Node};
//! use serde_json::json;
//!
//! let bp = Blueprint {
//! schema_version: current_schema_version(),
//! id: "hello".into(),
//! flow: Node::Step {
//! ref_: "greeter".into(),
//! in_: Expr::Lit { value: json!({"name": "world"}) },
//! out: Expr::Path { at: "$.greeting".into() },
//! },
//! agents: vec![AgentDef {
//! name: "greeter".into(),
//! kind: AgentKind::RustFn,
//! spec: json!({"fn_id": "hello_world"}),
//! profile: None,
//! meta: None,
//! }],
//! operators: vec![],
//! hints: Default::default(),
//! strategy: Default::default(),
//! metadata: Default::default(),
//! spawner_hints: Default::default(),
//! default_agent_kind: AgentKind::Operator,
//! default_operator_kind: None,
//! };
//!
//! assert_eq!(bp.id, "hello");
//! assert_eq!(bp.agents.len(), 1);
//! assert_eq!(bp.strategy.strict_refs, true);
//! ```
//!
//! Round-trip a [`Blueprint`] through JSON (= confirms `serde` derives and the
//! `deny_unknown_fields` contract):
//!
//! ```
//! use mlua_swarm_schema::{AgentKind, Blueprint, BlueprintMetadata};
//! use mlua_flow_ir::{Expr, Node};
//! use serde_json::json;
//!
//! let bp = Blueprint {
//! schema_version: mlua_swarm_schema::current_schema_version(),
//! id: "roundtrip".into(),
//! flow: Node::Seq { children: vec![] },
//! agents: vec![],
//! operators: vec![],
//! hints: Default::default(),
//! strategy: Default::default(),
//! metadata: BlueprintMetadata {
//! description: Some("roundtrip smoke".into()),
//! default_run_ttl_secs: Some(1800),
//! ..Default::default()
//! },
//! spawner_hints: Default::default(),
//! default_agent_kind: AgentKind::Operator,
//! default_operator_kind: None,
//! };
//!
//! let json = serde_json::to_string(&bp).unwrap();
//! let back: Blueprint = serde_json::from_str(&json).unwrap();
//! assert_eq!(bp, back);
//! assert_eq!(back.metadata.default_run_ttl_secs, Some(1800));
//! ```
use Node as FlowNode;
use JsonSchema;
use ;
use Value;
use HashMap;
// ──────────────────────────────────────────────────────────────────────────
// Versioning
// ──────────────────────────────────────────────────────────────────────────
/// Current Blueprint schema version. Tied to this crate's semver.
pub const CURRENT_SCHEMA_VERSION: &str = "0.1.0";
/// Blueprint construction helper: returns the semver of the current schema version.
/// Callers can write `schema_version: current_schema_version(),`.
// ──────────────────────────────────────────────────────────────────────────
// Blueprint (top-level package)
// ──────────────────────────────────────────────────────────────────────────
/// Unified package of flow.ir + Swarm extension layers. The entry-point type of Swarm.
/// Global default `AgentKind` at the Schema impl Default layer. Bottom of the 4-layer cascade.
/// Set of **capability hint keys** for the SpawnerLayer required by a Blueprint.
///
/// # Design rationale (= for the person who will reconstruct this later)
///
/// A Blueprint is a pure layer of flow.ir + agent name binding and holds no middleware
/// **implementation**. Nevertheless there are cases where the caller must be told the BP
/// needs certain **capabilities** — e.g. "MainAI hook required", "Operator delegate path
/// required", operator role mode switching, presence/absence of senior escalation, and
/// so on.
///
/// `spawner_hints.layers` is the place where those capabilities are declared as **string
/// keys**. The engine-side `LayerRegistry` (= consumer crate) resolves key → factory and
/// wraps the compiled routes with a `SpawnerStack`. The Blueprint does not import the
/// concrete `MainAIMiddleware` type; it exposes intent through strings such as `"main_ai"`
/// (= separates the pure Flow layer from implementation details).
///
/// # Canonical hint keys
///
/// - `"main_ai"` → `MainAIMiddleware` (= fires SpawnHook before/after when kind is MainAi/Composite)
/// - `"senior_escalation"` → `SeniorEscalationMiddleware` (= fires SeniorBridge.ask on worker ok=false)
/// - `"operator_delegate"` → `OperatorDelegateMiddleware` (= delegates the entire spawn to an external Operator.execute)
///
/// # Behavior of unregistered keys
///
/// If the engine-side LayerRegistry has no matching factory, the key is **silently skipped**
/// (= lenient default). This preserves Blueprint portability (= an unsupported capability in
/// another deployment falls back gracefully).
// ──────────────────────────────────────────────────────────────────────────
// AgentDef / AgentKind / AgentProfile / AgentMeta
// ──────────────────────────────────────────────────────────────────────────
/// Maps an agent name to a Worker IMPL kind and its configuration. Referenced from flow.ir
/// `Step.ref` by name.
///
/// # Design
///
/// `AgentDef.kind` directly expresses the **Worker IMPL axis** (= not the old Spawner axis).
/// Dispatching to a host Spawner adapter (`InProcSpawner` / `ProcessSpawner` /
/// `OperatorSpawner`) is done by an internal Resolver on the compiler side. The design goal
/// is "do not make the caller aware of which Spawner hosts the Worker IMPL"; the caller
/// (Blueprint author) sees only the WorkerIMPL viewpoint.
///
/// A Spawner-axis hint (= "which adapter would you prefer running this Worker on", as a
/// priority list) will be added via a future `spawner_hint: Vec<Spawner>` field as a carry.
/// The current internal Resolver is a fixed 1:1 mapping, so the field is unnecessary today.
/// Agent persona information. Orthogonal to the backend kind (Shell / InProc / Operator).
///
/// Populated by `agent_md_loader::load_dir` from the frontmatter and Markdown body of
/// `agents/*.md` in agent-profiles. The backend (e.g. AgentBlockOperator) receives this
/// struct at construction / dispatch time and consumes `system_prompt` as the LLM API
/// system message and `model` / `tools` as configuration.
///
/// C-C-specific fields (`permissionMode` / `memory` / `abtest`, etc.) are dumped into
/// `extras: Value`, and consumers that need them read them out. This is the escape hatch
/// that keeps the schema future-proof rather than making it strict.
/// SoT of the **Worker IMPL axis**. A closed enum managed inside Swarm and extended by
/// variant addition through **explicit maintenance**. String lookup / escape hatches are
/// deliberately not adopted.
///
/// This enum **expresses Worker IMPL directly**; dispatching to a host Spawner adapter is
/// resolved by an internal Resolver on the compiler side (= callers see only the Worker
/// IMPL viewpoint).
///
/// # Internal Resolver mapping (= currently a fixed 1:1, carry: priority list form)
///
/// | AgentKind | Host Spawner adapter |
/// |---|---|
/// | `Lua` | `InProcSpawner` (mlua VM eval) |
/// | `RustFn` | `InProcSpawner` (Rust closure) |
/// | `AgentBlock` | `InProcSpawner` (agent-block-core SDK in-process) |
/// | `Subprocess` | `ProcessSpawner` (child process launch) |
/// | `Operator` | `OperatorSpawner` (interactive role / Human-MainAI delegation) |
// ──────────────────────────────────────────────────────────────────────────
// OperatorDef / OperatorKind
// ──────────────────────────────────────────────────────────────────────────
/// Kind axis of an Operator role (= "in which mode does this Operator run").
/// Corresponds 1:1 with the engine's runtime `OperatorKind`. Kept as a schema
/// duplicate so that BPs can be authored while depending only on this crate.
/// Design-time definition of an Operator role (first-class).
///
/// `AgentDef.spec.operator_ref` references this struct's `name` as a logical role name.
/// Binding to a runtime backend (WS session / SDK / pool, etc.) is established via the
/// attach path; the BP side only declares "under this logical name we expect an Operator
/// of this Kind".
///
/// `spec` is an escape hatch for kind-specific config (WS endpoint / SDK profile / pool
/// binding, etc.). Even when empty, declaring `name` + `kind` alone is enough for
/// compile-time validation to succeed (= it guarantees that agent `operator_ref` values
/// reference an existing definition).
/// Agent / Operator level metadata (description / version / tags).
// ──────────────────────────────────────────────────────────────────────────
// Compiler hints / strategy
// ──────────────────────────────────────────────────────────────────────────
/// Per-agent overrides / hints. Interpreted by the Compiler / SpawnerFactory; not required.
/// Compiler behavior rules. Controls strict / lenient handling and default fallback.
// ──────────────────────────────────────────────────────────────────────────
// Blueprint metadata / origin
// ──────────────────────────────────────────────────────────────────────────
/// Blueprint-level metadata (description / origin / tags / ttl / version label / alias).
/// Provenance record of a Blueprint.