mlua_swarm_schema/lib.rs
1//! Blueprint schema — Swarm IF SoT (= the core type set that defines "how a Blueprint object is written").
2//!
3//! This crate provides **schema types + serde derives only** as a pure IF crate. Execution
4//! layers (SpawnerFactory / EngineDispatcher / Compiler) are not included here; consumers
5//! (the `mlua-swarm` crate) own them. External consumers, sibling worktrees, and
6//! future bundles can read/write Blueprints by depending on this single crate.
7//!
8//! # Versioning contract
9//!
10//! `Blueprint.schema_version` is tied to this crate's semver. It is fixed at 0.1.0 for now;
11//! during 0.x breaking changes are free, and 1.0 will freeze the schema.
12//!
13//! # IN-immutability (extension discipline)
14//!
15//! This crate is the IN side of the swarm layering and stays **plain serde
16//! data**: no compile pass, no field the engine macro-expands, no DSL
17//! dialect. Flow conds are written literally against the Flow.ir Expr set
18//! (`Eq($.<step>.verdict, Lit("blocked"))` — domain verdicts are plain
19//! strings in step output). Authoring sugar (builders) lives OUT on the
20//! consumer side; runtime behavior extension lives in the engine's
21//! `SpawnerLayer` middleware.
22//!
23//! # AgentKind handling (= internal SoT)
24//!
25//! [`AgentKind`] is the SoT for the SpawnerAdapter offering axis. It is a closed enum managed
26//! inside Swarm, extended by variant addition through **explicit maintenance**. String lookup
27//! or a `Custom` escape hatch is deliberately avoided (= structurally eliminates the "silly
28//! runtime typos" class of failures).
29//!
30//! # Examples
31//!
32//! Build a minimal [`Blueprint`] with a single [`AgentDef`] via struct literal:
33//!
34//! ```
35//! use mlua_swarm_schema::{
36//! AgentDef, AgentKind, Blueprint, current_schema_version,
37//! };
38//! use mlua_flow_ir::{Expr, Node};
39//! use serde_json::json;
40//!
41//! let bp = Blueprint {
42//! schema_version: current_schema_version(),
43//! id: "hello".into(),
44//! flow: Node::Step {
45//! ref_: "greeter".into(),
46//! in_: Expr::Lit { value: json!({"name": "world"}) },
47//! out: Expr::Path { at: "$.greeting".parse().unwrap() },
48//! },
49//! agents: vec![AgentDef {
50//! name: "greeter".into(),
51//! kind: AgentKind::RustFn,
52//! spec: json!({"fn_id": "hello_world"}),
53//! profile: None,
54//! meta: None,
55//! runner: None,
56//! runner_ref: None,
57//! verdict: None,
58//! }],
59//! operators: vec![],
60//! metas: vec![],
61//! hints: Default::default(),
62//! strategy: Default::default(),
63//! metadata: Default::default(),
64//! spawner_hints: Default::default(),
65//! default_agent_kind: AgentKind::Operator,
66//! default_operator_kind: None,
67//! default_init_ctx: None,
68//! default_agent_ctx: None,
69//! default_context_policy: None,
70//! projection_placement: None,
71//! audits: vec![],
72//! degradation_policy: None,
73//! runners: vec![],
74//! default_runner: None,
75//! subprocesses: vec![],
76//! check_policy: None,
77//! blueprint_ref_includes: vec![],
78//! };
79//!
80//! assert_eq!(bp.id.as_str(), "hello");
81//! assert_eq!(bp.agents.len(), 1);
82//! assert_eq!(bp.strategy.strict_refs, true);
83//! ```
84//!
85//! Round-trip a [`Blueprint`] through JSON (= confirms `serde` derives and the
86//! `deny_unknown_fields` contract):
87//!
88//! ```
89//! use mlua_swarm_schema::{AgentKind, Blueprint, BlueprintMetadata};
90//! use mlua_flow_ir::{Expr, Node};
91//! use serde_json::json;
92//!
93//! let bp = Blueprint {
94//! schema_version: mlua_swarm_schema::current_schema_version(),
95//! id: "roundtrip".into(),
96//! flow: Node::Seq { children: vec![] },
97//! agents: vec![],
98//! operators: vec![],
99//! metas: vec![],
100//! hints: Default::default(),
101//! strategy: Default::default(),
102//! metadata: BlueprintMetadata {
103//! description: Some("roundtrip smoke".into()),
104//! default_run_ttl_secs: Some(1800),
105//! ..Default::default()
106//! },
107//! spawner_hints: Default::default(),
108//! default_agent_kind: AgentKind::Operator,
109//! default_operator_kind: None,
110//! default_init_ctx: None,
111//! default_agent_ctx: None,
112//! default_context_policy: None,
113//! projection_placement: None,
114//! audits: vec![],
115//! degradation_policy: None,
116//! runners: vec![],
117//! default_runner: None,
118//! subprocesses: vec![],
119//! check_policy: None,
120//! blueprint_ref_includes: vec![],
121//! };
122//!
123//! let json = serde_json::to_string(&bp).unwrap();
124//! let back: Blueprint = serde_json::from_str(&json).unwrap();
125//! assert_eq!(bp, back);
126//! assert_eq!(back.metadata.default_run_ttl_secs, Some(1800));
127//! ```
128
129#![warn(missing_docs)]
130
131use mlua_flow_ir::Node as FlowNode;
132use schemars::JsonSchema;
133use serde::{Deserialize, Serialize};
134use serde_json::Value;
135use std::collections::HashMap;
136
137// ──────────────────────────────────────────────────────────────────────────
138// Versioning
139// ──────────────────────────────────────────────────────────────────────────
140
141/// Current Blueprint schema version. Tied to this crate's semver.
142pub const CURRENT_SCHEMA_VERSION: &str = "0.1.0";
143
144fn default_schema_version() -> semver::Version {
145 current_schema_version()
146}
147
148/// Blueprint construction helper: returns the semver of the current schema version.
149/// Callers can write `schema_version: current_schema_version(),`.
150pub fn current_schema_version() -> semver::Version {
151 semver::Version::parse(CURRENT_SCHEMA_VERSION)
152 .expect("CURRENT_SCHEMA_VERSION must be valid semver")
153}
154
155// ──────────────────────────────────────────────────────────────────────────
156// BlueprintId (human-facing ID newtype)
157// ──────────────────────────────────────────────────────────────────────────
158
159/// Identifier for a Blueprint series — the domain name (`coding`,
160/// `design`, `testing`, etc.). Default: [`BlueprintId::main`].
161///
162/// One representation across the workspace (issue #14): this type is
163/// shared by the schema's [`Blueprint::id`] and the engine's store-layer
164/// keys (`mlua-swarm` re-exports it at the old
165/// `blueprint::store::types::BlueprintId` path). The value is
166/// user-supplied — there is no prefix convention to validate, unlike the
167/// engine's minted `T-` / `R-` / `ST-` ids — so construction is
168/// infallible; the inner string is private so call sites go through
169/// [`BlueprintId::new`] and the accessors. `#[serde(transparent)]` keeps
170/// both the JSON wire shape and the generated JSON Schema a plain string.
171#[derive(
172 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
173)]
174#[serde(transparent)]
175pub struct BlueprintId(String);
176
177impl BlueprintId {
178 /// The default series name used when a caller doesn't pick one.
179 pub const MAIN: &'static str = "main";
180
181 /// Shorthand for `BlueprintId::new(BlueprintId::MAIN)`.
182 pub fn main() -> Self {
183 Self(Self::MAIN.to_string())
184 }
185
186 /// Wrap any string-like value as a `BlueprintId` (user-supplied key;
187 /// nothing to validate).
188 pub fn new(s: impl Into<String>) -> Self {
189 Self(s.into())
190 }
191
192 /// Borrow the inner series name.
193 pub fn as_str(&self) -> &str {
194 &self.0
195 }
196
197 /// Consume the id and return the inner series name.
198 pub fn into_string(self) -> String {
199 self.0
200 }
201}
202
203impl std::fmt::Display for BlueprintId {
204 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205 f.write_str(&self.0)
206 }
207}
208
209impl From<String> for BlueprintId {
210 fn from(s: String) -> Self {
211 Self(s)
212 }
213}
214
215impl From<&str> for BlueprintId {
216 fn from(s: &str) -> Self {
217 Self(s.to_string())
218 }
219}
220
221#[cfg(test)]
222mod blueprint_id_tests {
223 use super::*;
224
225 /// issue #14 convergence guard: `Blueprint.id` becoming a newtype must
226 /// not change the generated JSON Schema — the property stays an inline
227 /// plain string (no `$ref`), byte-compatible with the `String` era.
228 #[test]
229 fn blueprint_id_field_schema_stays_a_plain_inline_string() {
230 let schema = schemars::schema_for!(Blueprint);
231 let v = serde_json::to_value(&schema).expect("schema serializes");
232 let id = &v["properties"]["id"];
233 assert_eq!(id["type"], "string", "id must stay a plain string: {id}");
234 assert!(id.get("$ref").is_none(), "id must not become a $ref: {id}");
235 }
236
237 /// The JSON wire shape of the newtype is the bare string.
238 #[test]
239 fn blueprint_id_serde_is_transparent() {
240 let id = BlueprintId::new("coding");
241 assert_eq!(
242 serde_json::to_value(&id).unwrap(),
243 serde_json::json!("coding")
244 );
245 let back: BlueprintId = serde_json::from_value(serde_json::json!("coding")).unwrap();
246 assert_eq!(back, id);
247 }
248}
249
250// ──────────────────────────────────────────────────────────────────────────
251// Blueprint (top-level package)
252// ──────────────────────────────────────────────────────────────────────────
253
254/// Unified package of flow.ir + Swarm extension layers. The entry-point type of Swarm.
255#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
256#[serde(deny_unknown_fields)]
257pub struct Blueprint {
258 /// Schema version (= tied to this crate's semver). Default = `CURRENT_SCHEMA_VERSION`.
259 /// Serialized as a semver string (e.g. `"0.1.0"`).
260 #[serde(default = "default_schema_version")]
261 #[schemars(with = "String")]
262 pub schema_version: semver::Version,
263 /// Blueprint identifier (= unique key within the caller's namespace).
264 #[schemars(with = "String")]
265 pub id: BlueprintId,
266 /// Embeds the flow.ir Node verbatim (= keeps flow.ir side unpolluted).
267 /// Opaque in the JSON Schema (the Node shape is owned by the `mlua-flow-ir`
268 /// crate, a separate repo; see its docs for the Node / Expr grammar).
269 #[schemars(with = "Value")]
270 pub flow: FlowNode,
271 /// Swarm extension layer: agent → backend mapping.
272 #[serde(default)]
273 pub agents: Vec<AgentDef>,
274 /// Swarm extension layer: **design-time definition** of Operator roles (first-class).
275 ///
276 /// `AgentDef.spec.operator_ref` references an `OperatorDef.name` (logical role name) in
277 /// this vec. Embedding runtime-generated IDs such as sid into the BP is forbidden
278 /// (= collapses the design-time vs runtime boundary). Runtime backend bindings are
279 /// established via the attach / register path; the BP side holds only logical names.
280 ///
281 /// Every `kind = Operator` agent must have its `spec.operator_ref` present in this
282 /// list — the compiler validates it at `compile()` time. May be `[]` only when the
283 /// Blueprint declares no Operator agents.
284 #[serde(default)]
285 pub operators: Vec<OperatorDef>,
286 /// GH #21 Phase 2 — named, BP-scoped pool of [`MetaDef`] entries. Two
287 /// independent consumers resolve names against this pool: a
288 /// `$step_meta.ref` envelope embedded in a Step's evaluated `in`
289 /// value (the Step tier — resolved by `EngineDispatcher` in the
290 /// `mlua-swarm` core crate at dispatch time), and
291 /// [`AgentMeta::meta_ref`] (the Agent tier — resolved at launch
292 /// time). The pool lets multiple Steps and/or Agents share one
293 /// declarative context object by name instead of repeating it
294 /// inline. `[]` = no named `MetaDef`s declared (pre-#21-Phase-2
295 /// Blueprints unaffected).
296 #[serde(default, skip_serializing_if = "Vec::is_empty")]
297 pub metas: Vec<MetaDef>,
298 /// Swarm extension layer: per-agent hints (interpreted by the Compiler).
299 #[serde(default)]
300 pub hints: CompilerHints,
301 /// Swarm extension layer: Compiler behavior strategy (strict / lenient).
302 #[serde(default)]
303 pub strategy: CompilerStrategy,
304 /// Blueprint metadata (description / origin / tags / ttl / version label / alias).
305 #[serde(default)]
306 pub metadata: BlueprintMetadata,
307 /// Swarm extension layer: hint keys of the layers to wrap around the SpawnerStack.
308 /// Resolved by the LayerRegistry at engine bind time (= unregistered keys are silently
309 /// skipped). Flow / Blueprint do not hold middleware implementations (e.g. MainAIMiddleware)
310 /// directly; they only declare required capabilities as string keys (= implementations
311 /// live in the engine-side LayerRegistry).
312 #[serde(default)]
313 pub spawner_hints: SpawnerHints,
314 /// BP-wide default `AgentKind` (= fallback when `AgentDef.kind` is omitted).
315 /// Four-layer cascade: (1) Schema impl Default = Operator, (2) CLI
316 /// `--default-agent-kind`, (3) this field (BP JSON literal), (4) `AgentDef.kind`
317 /// (per-agent literal). (5) `CompilerHints.kind_override` allows runtime override.
318 /// All default resolution flows through this path.
319 #[serde(default = "default_global_agent_kind")]
320 pub default_agent_kind: AgentKind,
321 /// BP-wide default `OperatorKind` (= the "BP Global" tier of the 4-tier
322 /// `OperatorKind` cascade). `None` when the Blueprint author does not
323 /// declare a default; the caller-side resolver then falls through to
324 /// the hardcoded `OperatorKind::default()` (Automate).
325 ///
326 /// # 4-tier cascade (highest to lowest priority)
327 ///
328 /// 1. Runtime Agent-level (per-agent override supplied at task-launch time)
329 /// 2. Runtime Global (the launch-time `operator_kind` request)
330 /// 3. BP Agent-level (`OperatorDef.kind`, resolved via `AgentDef.spec.operator_ref`)
331 /// 4. BP Global (this field)
332 /// 5. Default Fallback (`OperatorKind::default()` = Automate)
333 ///
334 /// The collapse itself is implemented once on the engine side and consumed
335 /// per-agent when resolving operator info.
336 #[serde(default, skip_serializing_if = "Option::is_none")]
337 pub default_operator_kind: Option<OperatorKind>,
338 /// Blueprint-level default initial `ctx` for flow-ir eval.
339 /// `TaskLaunchService::launch` shallow-merges this with the
340 /// Task-level `init_ctx` (Task wins on key collision when both
341 /// are `Object`; if Task's `init_ctx` is not an `Object`, it
342 /// full-replaces the default). `None` — no default is merged;
343 /// backward-compat with pre-#19 Blueprints.
344 #[serde(default, skip_serializing_if = "Option::is_none")]
345 #[schemars(with = "Option<Value>")]
346 pub default_init_ctx: Option<Value>,
347 /// GH #21 Phase 1 — "BP Global" tier of the agent-context supply axis:
348 /// a declarative object merged into `ctx.meta.runtime` (and, for
349 /// unnamed keys, `AgentContextView.extra`) targeting every agent's
350 /// runtime materialization. Contrast with [`Self::default_init_ctx`]:
351 /// that field seeds the flow-ir eval `ctx` once at flow start, while
352 /// this one is consumed per-spawn by
353 /// `AgentContextMiddleware`/`AgentContextView` (Contract C, GH #20) —
354 /// a pure flow-ir eval seed vs. an Agent/LLM-boundary runtime default.
355 /// `None` = no BP-global default (pre-#21 Blueprints unaffected).
356 #[serde(default, skip_serializing_if = "Option::is_none")]
357 #[schemars(with = "Option<Value>")]
358 pub default_agent_ctx: Option<Value>,
359 /// GH #21 Phase 1 — "BP Global" tier of the [`ContextPolicy`] cascade:
360 /// the default filter applied to the materialized `AgentContextView`
361 /// when the targeted agent declares no `AgentMeta.context_policy` of
362 /// its own. `None` = pass-all (the pre-#21 behavior).
363 #[serde(default, skip_serializing_if = "Option::is_none")]
364 pub default_context_policy: Option<ContextPolicy>,
365 /// GH #27 (follow-up to #23) — Blueprint-declared override of the
366 /// `mlua-swarm` core crate's projection placement resolver (root
367 /// preference + target directory template for materialized step
368 /// OUTPUT files). `None` = the resolver's byte-compat default (root =
369 /// `work_dir` falling back to `project_root`; dir_template =
370 /// `"workspace/tasks/{task_id}/ctx"`) — every pre-#27 Blueprint is
371 /// unaffected. See [`ProjectionPlacementSpec`]'s doc for field detail.
372 #[serde(default, skip_serializing_if = "Option::is_none")]
373 pub projection_placement: Option<ProjectionPlacementSpec>,
374 /// GH #34 — Blueprint-declared after-run audit hooks: the engine
375 /// auto-kicks each listed [`AuditDef`]'s agent once a matching Step
376 /// settles, and persists its findings as an `OutputEvent::Artifact`
377 /// named `"audit:<step_ref>"` on the AUDITED step's own output tail
378 /// (see `mlua-swarm` core's `AfterRunAuditMiddleware` for the
379 /// dispatch mechanics). `audits[].agent` is validated at
380 /// `Compiler::compile` time against `Blueprint.agents[].name`
381 /// (mirrors the `operator_ref` validation). `[]` (the default) = no
382 /// audit hooks declared — every pre-#34 Blueprint is unaffected,
383 /// byte-for-byte.
384 ///
385 /// **Binding invariant**: an audit's verdict, findings, or even its
386 /// own failure NEVER change the audited step's outcome or gate the
387 /// flow — audits are purely observational.
388 #[serde(default, skip_serializing_if = "Vec::is_empty")]
389 pub audits: Vec<AuditDef>,
390 /// GH #32 — Blueprint-declared policy for worker-reported degradations
391 /// (see `mlua-swarm` core's `RunRecord.degradations` /
392 /// `DegradationEntry`). `None` (the default) is schema-only for now:
393 /// [`DegradationPolicy::Warn`] and [`DegradationPolicy::Fail`] carry the
394 /// same observational behavior at this point — degradations are always
395 /// persisted, never gate the flow. Engine enforcement of `Fail`
396 /// (terminating a Run on any reported degradation) is a follow-up; this
397 /// field only declares author intent today. Every pre-#32 Blueprint is
398 /// unaffected.
399 #[serde(default, skip_serializing_if = "Option::is_none")]
400 pub degradation_policy: Option<DegradationPolicy>,
401 /// GH #46 M2 — named registry of [`RunnerDef`] entries (Tier 1 of the
402 /// 3-tier Worker model: Runner / Agent / Context). Referenced by
403 /// `AgentDef.runner_ref` and [`Self::default_runner`] by name.
404 /// Same registry shape as [`Self::metas`] (GH #21 Phase 2). `[]` (the
405 /// default) = no Runner registry declared — every pre-#46 Blueprint
406 /// is unaffected, byte-for-byte.
407 #[serde(default, skip_serializing_if = "Vec::is_empty")]
408 pub runners: Vec<RunnerDef>,
409 /// GH #46 M2 — the "BP Global" tier of the [`resolve_runner`] cascade:
410 /// a [`RunnerDef::name`] reference into [`Self::runners`] (inline
411 /// `Runner` values are not accepted here — registry names only,
412 /// mirroring [`Self::default_agent_ctx`]'s design). Ranks BELOW an
413 /// agent's own inline `runner` / `runner_ref` / legacy
414 /// `profile.worker_binding` declaration (see [`resolve_runner`]'s
415 /// cascade doc for the full precedence). `None` = no BP-wide default
416 /// declared — every pre-#46 Blueprint is unaffected.
417 #[serde(default, skip_serializing_if = "Option::is_none")]
418 pub default_runner: Option<String>,
419 /// GH #83 — named registry of [`SubprocessDef`] CLI invocation
420 /// templates, referenced by `Runner::Subprocess { template }` by
421 /// name. Same registry shape as [`Self::metas`] / [`Self::runners`].
422 /// `[]` (the default) = no templates declared — every pre-#83
423 /// Blueprint is unaffected, byte-for-byte.
424 #[serde(default, skip_serializing_if = "Vec::is_empty")]
425 pub subprocesses: Vec<SubprocessDef>,
426 /// "Blueprint" tier (tier 2) of the `check_policy`
427 /// cascade: `launch request > blueprint > server config` (highest to
428 /// lowest priority). The launch entry point resolves
429 /// `launch.check_policy.or(blueprint.check_policy)` exactly once and
430 /// threads the result into every spawned step's `TaskSpec.check_policy`;
431 /// `None` here (the default) is a no declaration — resolution falls
432 /// through to the launch-request tier and, absent that, to the
433 /// server-wide `EngineCfg.check_policy` default. Every pre-cascade
434 /// Blueprint is unaffected, byte-for-byte. See [`CheckPolicy`] for the
435 /// three fail-open reaction modes.
436 #[serde(default, skip_serializing_if = "Option::is_none")]
437 pub check_policy: Option<CheckPolicy>,
438 /// Authoring-time include list consumed by the compile-side linker
439 /// (tier 2 of the include cascade — see `mlua-swarm-compile`'s
440 /// `ResolveConfig`). Each entry is a directory path resolved
441 /// relative to the bp.lua parent that `$agent_md` / `$file` refs
442 /// will search after the parent dir itself. Bare list; the schema
443 /// carries the field only so `deny_unknown_fields` won't reject a
444 /// bp.lua that declares it. `[]` (the default) — no in-bp includes;
445 /// every pre-cascade Blueprint is unaffected.
446 #[serde(default, skip_serializing_if = "Vec::is_empty")]
447 #[schemars(with = "Vec<String>")]
448 pub blueprint_ref_includes: Vec<std::path::PathBuf>,
449}
450
451/// How a submit-time projection sink reacts when a fail-open condition
452/// is encountered.
453///
454/// This is the Swarm IF SoT type for the `check_policy` axis; the
455/// `mlua-swarm` core crate re-exports it as `crate::core::config::CheckPolicy`
456/// so every existing path (`EngineCfg.check_policy`, `TaskSpec.check_policy`,
457/// `apply_check_policy`) keeps its old type path unchanged.
458///
459/// Fail-open conditions include: `work_dir` / `project_root` unresolved,
460/// `OutputStore` write error, `FileProjectionAdapter::materialize_submission`
461/// error, and state lookup error. Each call site inside the engine's
462/// `materialize_final_submission` / `materialize_artifact_submission`
463/// currently logs a `tracing::warn!` and returns without materializing the
464/// file / dual-write; `CheckPolicy` is the first-class knob that lets a
465/// caller opt into a different reaction without changing that behaviour by
466/// default.
467///
468/// The three modes are (a) [`CheckPolicy::Silent`] — no log, no error,
469/// operation continues; (b) [`CheckPolicy::Warn`] — log warn (existing
470/// message literal preserved), no error, operation continues (the
471/// default = pre-existing behaviour); (c) [`CheckPolicy::Strict`] — log
472/// the same warn AND return `EngineError::CheckPolicyStrict` (in the core
473/// crate) so the caller can fail the step / launch fast. When Strict
474/// returns an error, the underlying `OutputStore` may already have
475/// appended (dual-write side-effect is not rolled back) — this "state
476/// dirty on fail" semantics is intentional: the append happens **before**
477/// the fail-open branch runs, so Strict surfaces the mismatch instead of
478/// hiding it.
479///
480/// The wire form is snake_case (`"silent"` / `"warn"` / `"strict"`); the
481/// default is [`CheckPolicy::Warn`].
482#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
483#[serde(rename_all = "snake_case")]
484pub enum CheckPolicy {
485 /// Skip both the log warn and the error path — completely silent.
486 /// The operation continues (fail-open is still in effect).
487 Silent,
488 /// Log a `tracing::warn!` with the call site's existing message and
489 /// continue (fail-open). Default — byte-identical to the
490 /// pre-`CheckPolicy` behaviour of every submit-time projection sink
491 /// code path.
492 #[default]
493 Warn,
494 /// Log the same warn AND return `EngineError::CheckPolicyStrict` (the
495 /// core crate's error variant). A caller that has opted in can fail the
496 /// step / launch fast instead of proceeding with a partially-realized
497 /// submission. This mode also drives a launch-time pre-dispatch
498 /// validation in `TaskLaunchService::launch` (the `mlua-swarm` core
499 /// crate): a launch whose effective policy resolves to `Strict` and
500 /// that supplies neither `project_root` nor `work_dir` is rejected
501 /// with `TaskLaunchError::PreDispatch` before any step is dispatched,
502 /// rather than dispatching a step that would deterministically hit
503 /// this same error at its first submit-time file materialize.
504 Strict,
505}
506
507/// GH #32 — Blueprint-declared policy for worker-reported degradations. See
508/// [`Blueprint::degradation_policy`] for the (currently schema-only)
509/// enforcement contract.
510#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
511#[serde(rename_all = "snake_case")]
512pub enum DegradationPolicy {
513 /// Observational only (today's only enforced behavior, regardless of
514 /// which variant is declared): degradations are persisted to
515 /// `RunRecord.degradations` and surfaced via `mse_doctor` /
516 /// `GET /v1/runs/:id`, but never change the Run's outcome.
517 Warn,
518 /// Declares intent to terminate the Run on any reported degradation.
519 /// Not yet enforced by the engine — schema-only until the follow-up
520 /// lands.
521 Fail,
522}
523
524/// GH #34 — one Blueprint-declared after-run audit hook. See
525/// [`Blueprint::audits`] for the persistence / invariant contract.
526#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
527#[serde(deny_unknown_fields)]
528pub struct AuditDef {
529 /// Name of the audit agent (must match a [`Blueprint::agents`] entry's
530 /// `name`) the engine dispatches after a matched step settles.
531 /// Validated at `Compiler::compile` time (mirrors
532 /// `AgentDef.spec.operator_ref`'s `operator_ref` validation) — an
533 /// unresolved name rejects compilation.
534 pub agent: String,
535 /// Step names this audit applies to, matched against the step's agent
536 /// ref name. `None`, or a list containing the literal `"*"`, means
537 /// "every step". `Some(vec![])` (an explicit empty list) audits no
538 /// step. `None` is the default.
539 #[serde(default, skip_serializing_if = "Option::is_none")]
540 pub steps: Option<Vec<String>>,
541 /// Dispatch timing for this audit's agent (see [`AuditMode`]).
542 /// Defaults to [`AuditMode::Async`].
543 #[serde(default)]
544 pub mode: AuditMode,
545}
546
547/// GH #34 — dispatch timing for an [`AuditDef`]'s audit agent. Neither
548/// variant ever changes the audited step's outcome (see
549/// [`Blueprint::audits`]'s binding invariant).
550#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
551#[serde(rename_all = "snake_case")]
552pub enum AuditMode {
553 /// Fire-and-forget: the audit runs in the background after the
554 /// audited step settles; the audited step's own spawn signal returns
555 /// immediately, without waiting for the audit to finish.
556 #[default]
557 Async,
558 /// Awaited before the audited step's spawn signal is returned to the
559 /// engine — still never alters that signal or the step's recorded
560 /// outcome.
561 Sync,
562}
563
564/// Receptacle for a Blueprint-driven filter over the materialized
565/// `AgentContextView` (GH #20/#21). Declared BP-side via
566/// [`Blueprint::default_context_policy`] (BP-global) or
567/// `AgentMeta::context_policy` (per-agent, outranks the BP-global tier) —
568/// resolved and applied by `AgentContextMiddleware` in the `mlua-swarm`
569/// core crate (this crate stays execution-free; see the crate doc).
570/// Default (`include: None, exclude: vec![]`) is pass-all — [`Self::allows`]
571/// returns `true` for every field name.
572#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
573#[serde(deny_unknown_fields)]
574pub struct ContextPolicy {
575 /// Field names to keep. `None` means "keep everything" (pass-all).
576 /// Matched against the `AgentContextView` named-field strings
577 /// (`"project_root"` / `"work_dir"` / `"task_metadata"` / `"run_id"` /
578 /// `"project_name_alias"`) and `extra` keys by their own key string.
579 /// Identity fields (`task_id` / `agent` / `attempt`) are never
580 /// filtered regardless of `include`.
581 #[serde(default)]
582 pub include: Option<Vec<String>>,
583 /// Field names to drop, applied AFTER `include` (exclude wins when a
584 /// name appears in both). Same name-matching rule as `include`.
585 #[serde(default)]
586 pub exclude: Vec<String>,
587 /// Which preceding steps' OUTPUT pointers a worker's fetch payload may
588 /// see (`WorkerPayload.context.steps`, ST5 of the `projection-adapter`
589 /// design). `None` = pass-all (every submitted step, the pre-ST5
590 /// `ctx_step_dir` behavior); `Some(list)` = only the named steps;
591 /// `Some(vec![])` = none. Evaluated by [`Self::allows_step`], a sibling
592 /// of [`Self::allows`] with the same include/exclude precedence rule
593 /// but a separate namespace (step names vs. `AgentContextView` field /
594 /// `extra` key names never collide).
595 #[serde(default)]
596 pub steps: Option<Vec<String>>,
597 /// Step names to drop, applied AFTER `steps` (exclude wins when a name
598 /// appears in both). Same name-matching rule as `steps`.
599 #[serde(default)]
600 pub steps_exclude: Vec<String>,
601}
602
603impl ContextPolicy {
604 /// Whether `name` survives this policy: `false` if `exclude` lists it;
605 /// otherwise `true` when `include` is `None` (pass-all) or lists
606 /// `name`. Shared by both the schema crate (tests) and the `mlua-swarm`
607 /// core crate's `AgentContextView::apply_policy`, so the include/exclude
608 /// evaluation rule has exactly one implementation.
609 pub fn allows(&self, name: &str) -> bool {
610 if self.exclude.iter().any(|excluded| excluded == name) {
611 return false;
612 }
613 match &self.include {
614 Some(list) => list.iter().any(|included| included == name),
615 None => true,
616 }
617 }
618
619 /// Whether the preceding step named `name` survives this policy for the
620 /// worker fetch payload's `context.steps` pointer list: `false` if
621 /// `steps_exclude` lists it; otherwise `true` when `steps` is `None`
622 /// (pass-all) or lists `name`. Same precedence rule as [`Self::allows`],
623 /// evaluated against the separate `steps` / `steps_exclude` fields.
624 pub fn allows_step(&self, name: &str) -> bool {
625 if self.steps_exclude.iter().any(|excluded| excluded == name) {
626 return false;
627 }
628 match &self.steps {
629 Some(list) => list.iter().any(|included| included == name),
630 None => true,
631 }
632 }
633}
634
635/// Global default `AgentKind` at the Schema impl Default layer. Bottom of the 4-layer cascade.
636pub fn default_global_agent_kind() -> AgentKind {
637 AgentKind::Operator
638}
639
640/// Set of **capability hint keys** for the SpawnerLayer required by a Blueprint.
641///
642/// # Design rationale (= for the person who will reconstruct this later)
643///
644/// A Blueprint is a pure layer of flow.ir + agent name binding and holds no middleware
645/// **implementation**. Nevertheless there are cases where the caller must be told the BP
646/// needs certain **capabilities** — e.g. "MainAI hook required", "Operator delegate path
647/// required", operator role mode switching, presence/absence of senior escalation, and
648/// so on.
649///
650/// `spawner_hints.layers` is the place where those capabilities are declared as **string
651/// keys**. The engine-side `LayerRegistry` (= consumer crate) resolves key → factory and
652/// wraps the compiled routes with a `SpawnerStack`. The Blueprint does not import the
653/// concrete `MainAIMiddleware` type; it exposes intent through strings such as `"main_ai"`
654/// (= separates the pure Flow layer from implementation details).
655///
656/// # Canonical hint keys
657///
658/// - `"main_ai"` → `MainAIMiddleware` (= fires SpawnHook before/after when kind is MainAi/Composite)
659/// - `"senior_escalation"` → `SeniorEscalationMiddleware` (= fires SeniorBridge.ask on worker ok=false)
660/// - `"operator_delegate"` → `OperatorDelegateMiddleware` (= delegates the entire spawn to an external Operator.execute)
661///
662/// # Behavior of unregistered keys
663///
664/// If the engine-side LayerRegistry has no matching factory, the key is **silently skipped**
665/// (= lenient default). This preserves Blueprint portability (= an unsupported capability in
666/// another deployment falls back gracefully).
667#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, JsonSchema)]
668#[serde(deny_unknown_fields)]
669pub struct SpawnerHints {
670 /// Ordered list of layer hint keys to wrap around the SpawnerStack.
671 #[serde(default)]
672 pub layers: Vec<String>,
673}
674
675// ──────────────────────────────────────────────────────────────────────────
676// AgentDef / AgentKind / AgentProfile / AgentMeta
677// ──────────────────────────────────────────────────────────────────────────
678
679/// Maps an agent name to a Worker IMPL kind and its configuration. Referenced from flow.ir
680/// `Step.ref` by name.
681///
682/// # Design
683///
684/// `AgentDef.kind` directly expresses the **Worker IMPL axis** (= not the old Spawner axis).
685/// Dispatching to a host Spawner adapter (`InProcSpawner` / `ProcessSpawner` /
686/// `OperatorSpawner`) is done by an internal Resolver on the compiler side. The design goal
687/// is "do not make the caller aware of which Spawner hosts the Worker IMPL"; the caller
688/// (Blueprint author) sees only the WorkerIMPL viewpoint.
689///
690/// A Spawner-axis hint (= "which adapter would you prefer running this Worker on", as a
691/// priority list) will be added via a future `spawner_hint: Vec<Spawner>` field as a carry.
692/// The current internal Resolver is a fixed 1:1 mapping, so the field is unnecessary today.
693#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
694#[serde(deny_unknown_fields)]
695pub struct AgentDef {
696 /// Agent name (= referenced from flow.ir `Step.ref`).
697 pub name: String,
698 /// Worker IMPL kind (= see [`AgentKind`]).
699 pub kind: AgentKind,
700 /// Free-form schema per kind. Interpreted by the SpawnerFactory.
701 #[serde(default)]
702 pub spec: Value,
703 /// Agent persona information (system_prompt / model / tools, etc.). Orthogonal to the
704 /// backend kind and is a first-class field. Expected to be populated by
705 /// `agent_md_loader` from the frontmatter + body of an `agent.md`. `None` = an agent
706 /// without a profile (= backend built solely from `spec`).
707 #[serde(default)]
708 pub profile: Option<AgentProfile>,
709 /// Agent-level metadata (description / version / tags).
710 #[serde(default)]
711 pub meta: Option<AgentMeta>,
712 /// GH #46 M2 — inline [`Runner`] declaration: the highest-priority
713 /// tier of the [`resolve_runner`] cascade. `None` = this agent
714 /// declares no inline Runner (falls through to [`Self::runner_ref`],
715 /// then the legacy `profile.worker_binding` fallback, then
716 /// `Blueprint.default_runner`).
717 #[serde(default, skip_serializing_if = "Option::is_none")]
718 pub runner: Option<Runner>,
719 /// GH #46 M2 — a [`RunnerDef::name`] reference into
720 /// `Blueprint.runners` (second-priority tier of [`resolve_runner`]).
721 /// `None` = this agent declares no Runner registry reference.
722 #[serde(default, skip_serializing_if = "Option::is_none")]
723 pub runner_ref: Option<String>,
724 /// GH #50 — opt-in declaration of which OUTPUT channel this agent's
725 /// verdict token lives on, and the closed set of tokens it may emit
726 /// through that channel (see [`VerdictContract`]). Consumed by the
727 /// `mlua-swarm` core crate's `Compiler::compile` to lint
728 /// `Branch`/`Loop` `Eq`/`Ne`/`In` conds against this agent's output at
729 /// register time; a follow-up submit-time producer gate is a separate
730 /// enforcement point. `None` (the default) — this agent declares no
731 /// contract; a cond comparing its output to a literal is unchanged (at
732 /// most a `tracing::warn!`, never rejected) — every pre-GH-#50
733 /// Blueprint is unaffected, byte-for-byte.
734 #[serde(default, skip_serializing_if = "Option::is_none")]
735 pub verdict: Option<VerdictContract>,
736}
737
738/// Agent persona information. Orthogonal to the backend kind (Shell / InProc / Operator).
739///
740/// Populated by `agent_md_loader::load_dir` from the frontmatter and Markdown body of
741/// `agents/*.md` in agent-profiles. The backend (e.g. AgentBlockOperator) receives this
742/// struct at construction / dispatch time and consumes `system_prompt` as the LLM API
743/// system message and `model` / `tools` as configuration.
744///
745/// C-C-specific fields (`permissionMode` / `memory` / `abtest`, etc.) are dumped into
746/// `extras: Value`, and consumers that need them read them out. This is the escape hatch
747/// that keeps the schema future-proof rather than making it strict.
748#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
749#[serde(deny_unknown_fields)]
750pub struct AgentProfile {
751 /// Markdown body (= system prompt content).
752 #[serde(default)]
753 pub system_prompt: String,
754 /// LLM model identifier (e.g. `"sonnet"` / `"haiku"` / `"opus"`).
755 #[serde(default)]
756 pub model: Option<String>,
757 /// Reasoning effort (e.g. `"low"` / `"medium"` / `"high"`).
758 #[serde(default)]
759 pub effort: Option<String>,
760 /// List of available tool names (normalized from the CSV form in frontmatter).
761 #[serde(default)]
762 pub tools: Vec<String>,
763 /// Frontmatter `description`. A short one-line description.
764 #[serde(default)]
765 pub description: Option<String>,
766 /// C-C-specific / future-proof fields (permissionMode / memory / abtest / ...).
767 /// Shape is the leftover keys of the agent.md frontmatter dumped as a JSON object.
768 #[serde(default)]
769 pub extras: Value,
770 /// Content hash (blake3 32-byte hex) of the agent body (= `system_prompt`).
771 ///
772 /// # Purpose
773 ///
774 /// When the Enhance loop receives a Patch that replaces
775 /// `/agents/N/profile/system_prompt`, the post-hook in `patch_applier.lua`
776 /// recomputes this field (= new blake3 of the body) and updates it automatically.
777 /// This is the field that structurally prevents a Blueprint carrying a stale hash
778 /// from being committed.
779 ///
780 /// - `None` = hash not computed (= manually built agent, or a Blueprint predating this field)
781 /// - `Some(hex)` = latest hash at agent-profiles seed time or after PatchApplier
782 ///
783 /// Planned to be used as the cache-index key in `AgentStore`.
784 #[serde(default)]
785 pub version_hash: Option<String>,
786 /// Claude Code SubAgent definition name this agent binds to at spawn
787 /// time (e.g. "mse-worker-coder"). Why: the Blueprint is the single
788 /// source of truth for the declaration↔executor binding — an external
789 /// registry would duplicate what `tools` already declares and drift.
790 /// `None` is valid for agents whose operator backend never dispatches
791 /// a SubAgent (direct-LLM operators); WS thin-path operators require
792 /// it at compile time (see `Operator::requires_worker_binding`).
793 #[serde(default, skip_serializing_if = "Option::is_none")]
794 pub worker_binding: Option<String>,
795}
796
797/// SoT of the **Worker IMPL axis**. A closed enum managed inside Swarm and extended by
798/// variant addition through **explicit maintenance**. String lookup / escape hatches are
799/// deliberately not adopted.
800///
801/// This enum **expresses Worker IMPL directly**; dispatching to a host Spawner adapter is
802/// resolved by an internal Resolver on the compiler side (= callers see only the Worker
803/// IMPL viewpoint).
804///
805/// # Internal Resolver mapping (= currently a fixed 1:1, carry: priority list form)
806///
807/// | AgentKind | Host Spawner adapter |
808/// |---|---|
809/// | `Lua` | `InProcSpawner` (mlua VM eval) |
810/// | `RustFn` | `InProcSpawner` (Rust closure) |
811/// | `AgentBlock` | `InProcSpawner` (agent-block-core SDK in-process) |
812/// | `Subprocess` | `ProcessSpawner` (child process launch) |
813/// | `Operator` | `OperatorSpawner` (interactive role / Human-MainAI delegation) |
814#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, JsonSchema)]
815#[serde(rename_all = "snake_case")]
816pub enum AgentKind {
817 /// Lua script eval through the mlua VM (= factory-side registry looked up by `spec.fn_id`).
818 Lua,
819 /// Rust closure (= factory-side registry looked up by `spec.fn_id`).
820 RustFn,
821 /// Headless LLM agent via the agent-block-core SDK (in-process).
822 AgentBlock,
823 /// Child-process launch (= `spec.program` + `args`, via the ProcessSpawner path).
824 Subprocess,
825 /// Interactive Operator role (= MainAI / Human delegation, `spec.operator_ref`).
826 Operator,
827}
828
829// ──────────────────────────────────────────────────────────────────────────
830// VerdictContract / VerdictChannel (GH #50 — opt-in cond↔output-shape lint)
831// ──────────────────────────────────────────────────────────────────────────
832
833/// Opt-in per-agent declaration of the step OUTPUT shape a downstream
834/// `Branch`/`Loop` `cond` is allowed to structurally compare against — see
835/// the `blueprint-authoring.md` guide's "Returning verdicts to drive BP
836/// flow" section for the Pattern A/B shapes this mirrors. Consumed by the
837/// `mlua-swarm` core crate's `Compiler::compile` (a register-time,
838/// read-only lint over `Branch`/`Loop` `Eq`/`Ne`/`In` conds — no `flow`
839/// rewriting, no new `Expr` forms) and, as a follow-up, by the server's
840/// submit-time producer gate. `None` on [`AgentDef::verdict`] (the
841/// default) means neither enforcement point runs for that agent — the
842/// pre-GH-#50 behavior, byte-for-byte.
843#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
844#[serde(deny_unknown_fields)]
845pub struct VerdictContract {
846 /// Which OUTPUT channel carries the verdict token — see
847 /// [`VerdictChannel`].
848 pub channel: VerdictChannel,
849 /// Closed set of the verdict tokens this agent may emit through the
850 /// declared `channel` (e.g. `["PASS", "BLOCKED"]`). A `Branch`/`Loop`
851 /// cond's `Lit` operand(s) compared against this agent's declared
852 /// channel must be members of this set.
853 pub values: Vec<String>,
854}
855
856/// Which step OUTPUT channel a [`VerdictContract`] addresses — the two
857/// canonical submit shapes documented in the `blueprint-authoring.md`
858/// guide's "Returning verdicts to drive BP flow" section.
859#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
860#[serde(rename_all = "lowercase")]
861pub enum VerdictChannel {
862 /// Pattern A — the plain step OUTPUT body IS the verdict scalar; a cond
863 /// addresses it as the bare step output (`$.<step>`).
864 Body,
865 /// Pattern B — the verdict is staged as the named part `"verdict"`
866 /// alongside a separate plain-body report; a cond addresses it as
867 /// `$.<step>.parts.verdict` (equivalently `$.<step>.parts["verdict"]`
868 /// — both forms normalize to the same canonical [`Path`](mlua_flow_ir::Path) `Display`).
869 Part,
870}
871
872// ──────────────────────────────────────────────────────────────────────────
873// Runner / RunnerDef / WorkerModel / resolve_runner (GH #46 Milestone 2)
874// ──────────────────────────────────────────────────────────────────────────
875
876/// The execution shell an agent's Worker IMPL runs inside — holding tool
877/// grant, model selection, and runtime capabilities. Tier 1 of the GH #46
878/// 3-tier Worker model (Runner / Agent / Context).
879///
880/// Runner here is broader than the ADK / OpenAI Agents SDK Runner (a loop
881/// driver): it is the execution shell holding tool grant, model
882/// selection, and runtime capabilities. Loop driving itself is the
883/// backend's job (Claude Code harness / AgentBlock runtime).
884///
885/// Resolved per-agent by [`resolve_runner`]'s 5-step cascade; wiring the
886/// resolved value into the launch path is Milestone 3 — this Milestone
887/// only declares the shape and the pure resolver.
888#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
889#[serde(tag = "backend", rename_all = "snake_case", deny_unknown_fields)]
890pub enum Runner {
891 /// Platform-neutral WebSocket Operator backend. The joined execution
892 /// environment may be Claude Code, Codex, or another MainAI/plugin that
893 /// implements the common binding and spawn contracts.
894 WsOperator {
895 /// Provider-defined launch variant selected by the execution environment.
896 variant: String,
897 /// Minimum tool grant the provider must enforce.
898 #[serde(default, skip_serializing_if = "Vec::is_empty")]
899 tools: Vec<String>,
900 },
901 /// WS backend: Claude Code subagent wrapper. `variant` is the
902 /// wrapper's subagent_type; `tools` mirrors the wrapper frontmatter =
903 /// enforced grant.
904 ///
905 /// Kept as a compatibility backend for existing Blueprints. New
906 /// platform-neutral declarations should use [`Self::WsOperator`].
907 WsClaudeCode {
908 /// The wrapper's `subagent_type` (= `WorkerBinding.variant` in the
909 /// `mlua-swarm` core crate).
910 variant: String,
911 /// Declared (informational) tool list — mirrors the wrapper
912 /// frontmatter; the actual grant is enforced by the wrapper file
913 /// itself, not by this list.
914 #[serde(default, skip_serializing_if = "Vec::is_empty")]
915 tools: Vec<String>,
916 },
917 /// In-process backend: agent-block runtime. `tools` is the effective
918 /// (enforced) tool set for the in-process registry.
919 AgentBlockInProcess {
920 /// Effective (enforced) tool set passed to the agent-block
921 /// runtime's registry — unlike WebSocket Runner tool requests, this
922 /// list is not merely informational.
923 #[serde(default, skip_serializing_if = "Vec::is_empty")]
924 tools: Vec<String>,
925 },
926 /// GH #83 — Subprocess EmbedAgent backend: the step runs headless
927 /// through the `ProcessSpawner` path, with the invocation described by
928 /// a [`SubprocessDef`] template looked up by name in
929 /// [`Blueprint::subprocesses`]. Name symmetry with
930 /// `AgentKind::Subprocess` is deliberate (1:1 — this variant is the
931 /// Runner-axis face of the same Worker IMPL kind).
932 ///
933 /// Per-agent overrides live HERE (not on `SubprocessDef`) so the
934 /// template struct stays flat and shareable across agents.
935 Subprocess {
936 /// [`SubprocessDef::name`] reference into
937 /// [`Blueprint::subprocesses`].
938 template: String,
939 /// Per-agent overrides applied on top of the referenced template
940 /// and the agent profile. Empty (all defaults) is omitted on the
941 /// wire.
942 #[serde(default, skip_serializing_if = "SubprocessOverrides::is_empty")]
943 overrides: SubprocessOverrides,
944 },
945}
946
947/// Per-agent overrides for [`Runner::Subprocess`] — values that take
948/// precedence over the agent's `profile.model` / `profile.tools` and the
949/// spawn-time `{work_dir}` placeholder source when rendering the
950/// [`SubprocessDef`] template. Lives on the Runner variant (not on
951/// `SubprocessDef`) so the template itself stays flat (no per-agent
952/// state, no variant axis).
953#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
954#[serde(deny_unknown_fields)]
955pub struct SubprocessOverrides {
956 /// Overrides the `{model}` placeholder value (wins over
957 /// `profile.model`).
958 #[serde(default, skip_serializing_if = "Option::is_none")]
959 pub model: Option<String>,
960 /// Overrides the `{tools_csv}` placeholder value (wins over
961 /// `profile.tools`).
962 #[serde(default, skip_serializing_if = "Vec::is_empty")]
963 pub tools: Vec<String>,
964 /// Overrides the child process working directory (wins over the
965 /// template's `cwd` and the spawn-time `{work_dir}` source).
966 #[serde(default, skip_serializing_if = "Option::is_none")]
967 pub cwd: Option<String>,
968}
969
970impl SubprocessOverrides {
971 /// `true` when every field is at its default — used by
972 /// `skip_serializing_if` so an empty overrides block stays off the
973 /// wire (pre-#83 byte-compatibility for the `Runner` enum).
974 pub fn is_empty(&self) -> bool {
975 self.model.is_none() && self.tools.is_empty() && self.cwd.is_none()
976 }
977}
978
979/// GH #83 — one declarative CLI invocation template: how a materialized
980/// worker payload (system prompt + task + model/tools/cwd) is rendered
981/// into a child-process invocation, and how its stdout is normalized back
982/// into the worker-result shape.
983///
984/// Deliberately a **flat struct** — no internal variant/kind
985/// discriminator. Adding support for a new CLI backend means adding one
986/// more named entry to [`Blueprint::subprocesses`], never a new enum arm
987/// or spawner branch (the `AgentKind` closed enum already owns the kind
988/// axis; nesting a second "backend" hierarchy under it is the exact
989/// complexity this shape refuses).
990///
991/// `argv` / `stdin` / `env` values / `cwd` may contain `{placeholder}`
992/// tokens drawn from a closed, logic-free set (`{system}` /
993/// `{system_file}` / `{prompt}` / `{model}` / `{tools_csv}` /
994/// `{work_dir}` / `{task_id}` / `{attempt}`). Rendering is pure string
995/// substitution — no conditionals, no loops, no expression language; the
996/// engine-side consumer validates tokens against the closed set at
997/// compile time. This crate stores the templates as plain strings only
998/// (IN-immutability: no execution logic here).
999#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1000#[serde(deny_unknown_fields)]
1001pub struct SubprocessDef {
1002 /// Registry key, referenced by `Runner::Subprocess { template }`.
1003 pub name: String,
1004 /// Program + arguments. `argv[0]` is the binary; every element may
1005 /// carry placeholder tokens.
1006 pub argv: Vec<String>,
1007 /// Rendered and piped to the child's stdin when `Some`; `None` = no
1008 /// stdin write (EOF immediately).
1009 #[serde(default, skip_serializing_if = "Option::is_none")]
1010 pub stdin: Option<String>,
1011 /// Extra environment variables (appended to the engine's `MSE_*`
1012 /// token exports). Values may carry placeholder tokens. `BTreeMap`
1013 /// for a deterministic wire order.
1014 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
1015 pub env: std::collections::BTreeMap<String, String>,
1016 /// Child working directory (may carry placeholder tokens). `None` =
1017 /// the spawn-time `{work_dir}` source decides (or the engine default
1018 /// when no source exists).
1019 #[serde(default, skip_serializing_if = "Option::is_none")]
1020 pub cwd: Option<String>,
1021 /// stdout normalization declaration. `None` = the engine's historical
1022 /// JSON-or-raw behavior, byte-for-byte.
1023 #[serde(default, skip_serializing_if = "Option::is_none")]
1024 pub output: Option<SubprocessOutput>,
1025 /// Streaming wire protocol for stdout (`"ndjson_lines"` /
1026 /// `"sse_events"` / `"length_prefixed"` — same vocabulary as the
1027 /// spec-based Subprocess path). `None` = plain mode.
1028 #[serde(default, skip_serializing_if = "Option::is_none")]
1029 pub stream_mode: Option<String>,
1030}
1031
1032/// GH #83 — declarative stdout → worker-result normalization for a
1033/// [`SubprocessDef`] (plain mode only; streaming modes keep their event
1034/// protocol untouched).
1035#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1036#[serde(deny_unknown_fields)]
1037pub struct SubprocessOutput {
1038 /// Expected stdout format. `Some("json")` = stdout MUST parse as
1039 /// JSON (an unparsable stdout is a failed step). `None` = the
1040 /// historical lenient JSON-or-raw wrap.
1041 #[serde(default, skip_serializing_if = "Option::is_none")]
1042 pub format: Option<String>,
1043 /// JSON Pointer (RFC 6901) selecting the worker-result value out of
1044 /// the parsed stdout (e.g. `"/result"`). `None` = the whole parsed
1045 /// value.
1046 #[serde(default, skip_serializing_if = "Option::is_none")]
1047 pub result_ptr: Option<String>,
1048 /// Where the ok/failure signal comes from: `"exit_code"` (default
1049 /// behavior) or a JSON Pointer into the parsed stdout whose value
1050 /// must be boolean `true` for ok.
1051 #[serde(default, skip_serializing_if = "Option::is_none")]
1052 pub ok_from: Option<String>,
1053}
1054
1055/// One [`Blueprint::runners`] registry entry — a named [`Runner`]
1056/// declaration referenced by `AgentDef.runner_ref` /
1057/// [`Blueprint::default_runner`]. Same registry shape as [`MetaDef`] (GH
1058/// #21 Phase 2).
1059#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1060#[serde(deny_unknown_fields)]
1061pub struct RunnerDef {
1062 /// Registry key, referenced by `AgentDef.runner_ref` /
1063 /// `Blueprint.default_runner`.
1064 pub name: String,
1065 /// The declared Runner.
1066 pub runner: Runner,
1067}
1068
1069/// Canonical GH #46 Worker unit: a resolved [`Runner`] paired with the
1070/// [`AgentDef`] it backs. The Milestone 4 adapter is the consumer that
1071/// turns this into a runtime spawn; this crate only declares the shape
1072/// (no execution logic lives here — see the crate doc's IN-immutability
1073/// discipline).
1074#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1075#[serde(deny_unknown_fields)]
1076pub struct WorkerModel {
1077 /// The resolved Runner.
1078 pub runner: Runner,
1079 /// The agent this Runner backs.
1080 pub agent: AgentDef,
1081}
1082
1083/// Everything [`resolve_runner`] can fail with: an `AgentDef.runner_ref`
1084/// / `Blueprint.default_runner` reference that names no entry in
1085/// `Blueprint.runners`.
1086#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1087pub enum RunnerResolveError {
1088 /// `AgentDef.runner_ref` names a [`RunnerDef::name`] absent from
1089 /// `Blueprint.runners`.
1090 #[error(
1091 "agent '{agent}' runner_ref '{ref_name}' does not match any RunnerDef.name in \
1092 Blueprint.runners (defined: {available:?})"
1093 )]
1094 UnknownRunnerRef {
1095 /// The agent whose `runner_ref` didn't resolve.
1096 agent: String,
1097 /// The `runner_ref` value that was looked up.
1098 ref_name: String,
1099 /// The `RunnerDef.name`s that *are* declared, for the error message.
1100 available: Vec<String>,
1101 },
1102 /// `Blueprint.default_runner` names a [`RunnerDef::name`] absent from
1103 /// `Blueprint.runners`.
1104 #[error(
1105 "default_runner '{ref_name}' does not match any RunnerDef.name in Blueprint.runners \
1106 (defined: {available:?})"
1107 )]
1108 UnknownDefaultRunner {
1109 /// The `default_runner` value that was looked up.
1110 ref_name: String,
1111 /// The `RunnerDef.name`s that *are* declared, for the error message.
1112 available: Vec<String>,
1113 },
1114}
1115
1116/// Resolve `agent`'s effective [`Runner`] against `bp`, in cascade order
1117/// (highest priority first):
1118///
1119/// 1. `agent.runner` (inline declaration) — wins unconditionally.
1120/// 2. `agent.runner_ref`, resolved against `bp.runners` (an unresolved
1121/// name is [`RunnerResolveError::UnknownRunnerRef`]).
1122/// 3. Legacy fallback (agent-level): `agent.profile.worker_binding =
1123/// Some(variant)` becomes `Runner::WsClaudeCode { variant,
1124/// tools: profile.tools.clone() }` — the same synthesis
1125/// `crate::service::task_launch::derive_worker_bindings` (in the
1126/// `mlua-swarm` core crate) performs at launch time today.
1127/// 4. `bp.default_runner`, resolved against `bp.runners` (an unresolved
1128/// name is [`RunnerResolveError::UnknownDefaultRunner`]).
1129/// 5. `Ok(None)` — no Runner declared through any tier.
1130///
1131/// **Legacy (agent-level) beats `default_runner` (BP-global)**: tier 3
1132/// outranks tier 4, the same "agent-level wins over BP-global" rule the
1133/// ctx cascade (`AgentInline > MetaRef > BpGlobal`, see
1134/// `mlua-swarm`'s `core::explain::CtxTier`) already follows.
1135///
1136/// Pure and read-only: this Milestone does not wire the result into the
1137/// launch / compile path (Milestone 3 scope) — it only declares the
1138/// resolver.
1139pub fn resolve_runner(
1140 bp: &Blueprint,
1141 agent: &AgentDef,
1142) -> Result<Option<Runner>, RunnerResolveError> {
1143 // 1. inline — wins unconditionally.
1144 if let Some(runner) = &agent.runner {
1145 return Ok(Some(runner.clone()));
1146 }
1147
1148 // 2. runner_ref → bp.runners lookup.
1149 if let Some(ref_name) = &agent.runner_ref {
1150 return match bp.runners.iter().find(|def| &def.name == ref_name) {
1151 Some(def) => Ok(Some(def.runner.clone())),
1152 None => Err(RunnerResolveError::UnknownRunnerRef {
1153 agent: agent.name.clone(),
1154 ref_name: ref_name.clone(),
1155 available: bp.runners.iter().map(|d| d.name.clone()).collect(),
1156 }),
1157 };
1158 }
1159
1160 // 3. legacy fallback (agent-level `profile.worker_binding`) — outranks
1161 // `bp.default_runner` (tier 4).
1162 if let Some(variant) = agent
1163 .profile
1164 .as_ref()
1165 .and_then(|p| p.worker_binding.as_ref())
1166 {
1167 let tools = agent
1168 .profile
1169 .as_ref()
1170 .map(|p| p.tools.clone())
1171 .unwrap_or_default();
1172 return Ok(Some(Runner::WsClaudeCode {
1173 variant: variant.clone(),
1174 tools,
1175 }));
1176 }
1177
1178 // 4. bp.default_runner → bp.runners lookup.
1179 if let Some(ref_name) = &bp.default_runner {
1180 return match bp.runners.iter().find(|def| &def.name == ref_name) {
1181 Some(def) => Ok(Some(def.runner.clone())),
1182 None => Err(RunnerResolveError::UnknownDefaultRunner {
1183 ref_name: ref_name.clone(),
1184 available: bp.runners.iter().map(|d| d.name.clone()).collect(),
1185 }),
1186 };
1187 }
1188
1189 // 5. nothing declared through any tier.
1190 Ok(None)
1191}
1192
1193/// Which declaration tier supplied a [`BoundAgent`]'s resolved Runner.
1194/// Kept in the immutable snapshot so explain surfaces can distinguish a
1195/// first-class binding from the Claude Code compatibility fallback.
1196#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1197#[serde(rename_all = "snake_case")]
1198pub enum RunnerResolutionSource {
1199 /// `AgentDef.runner`.
1200 AgentInline,
1201 /// `AgentDef.runner_ref` resolved through `Blueprint.runners`.
1202 AgentRef,
1203 /// Deprecated `AgentProfile.worker_binding` compatibility path.
1204 LegacyWorkerBinding,
1205 /// `Blueprint.default_runner` resolved through `Blueprint.runners`.
1206 BlueprintDefault,
1207 /// No Runner applies to this in-process or otherwise unbound agent.
1208 None,
1209}
1210
1211/// Strongly typed identity of one immutable [`BoundAgent`] snapshot.
1212/// Transparent serde keeps the public JSON wire form a plain string.
1213#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, JsonSchema)]
1214#[serde(transparent)]
1215pub struct BindingDigest(String);
1216
1217impl BindingDigest {
1218 /// Compute the canonical `sha256:<lowercase-hex>` digest of `bytes`.
1219 pub fn sha256(bytes: impl AsRef<[u8]>) -> Self {
1220 use sha2::Digest as _;
1221 Self(format!(
1222 "sha256:{}",
1223 hex::encode(sha2::Sha256::digest(bytes.as_ref()))
1224 ))
1225 }
1226
1227 /// Borrow the stable wire representation.
1228 pub fn as_str(&self) -> &str {
1229 &self.0
1230 }
1231}
1232
1233impl std::fmt::Display for BindingDigest {
1234 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1235 f.write_str(&self.0)
1236 }
1237}
1238
1239impl std::str::FromStr for BindingDigest {
1240 type Err = BindingDigestParseError;
1241
1242 fn from_str(value: &str) -> Result<Self, Self::Err> {
1243 let Some(hex_part) = value.strip_prefix("sha256:") else {
1244 return Err(BindingDigestParseError::InvalidFormat(value.to_string()));
1245 };
1246 let canonical = hex_part.len() == 64
1247 && hex_part
1248 .bytes()
1249 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
1250 if !canonical {
1251 return Err(BindingDigestParseError::InvalidFormat(value.to_string()));
1252 }
1253 Ok(Self(value.to_string()))
1254 }
1255}
1256
1257impl<'de> Deserialize<'de> for BindingDigest {
1258 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1259 where
1260 D: serde::Deserializer<'de>,
1261 {
1262 use std::str::FromStr as _;
1263 let value = String::deserialize(deserializer)?;
1264 Self::from_str(&value).map_err(serde::de::Error::custom)
1265 }
1266}
1267
1268/// Rejection returned when an external binding digest is not in canonical
1269/// `sha256:<64 lowercase hex>` form.
1270#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1271pub enum BindingDigestParseError {
1272 /// Unsupported algorithm prefix, wrong length, uppercase, or non-hex.
1273 #[error("invalid binding digest '{0}'; expected sha256:<64 lowercase hex>")]
1274 InvalidFormat(String),
1275}
1276
1277/// Platform-neutral request sent to an [`AgentBindingProvider`](https://docs.rs/mlua-swarm)
1278/// before a Run is dispatched.
1279///
1280/// The request contains only Swarm declarations. A provider may resolve
1281/// platform aliases or inspect its own execution environment, but Swarm
1282/// validates the returned [`BindReceipt`] before accepting it.
1283#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1284#[serde(deny_unknown_fields)]
1285pub struct BindRequest {
1286 /// Logical agent name; the receipt correlation key.
1287 pub agent: String,
1288 /// Digest of the declaration-only [`BoundAgent`] snapshot.
1289 pub request_digest: BindingDigest,
1290 /// Runner backend family Core resolved for this agent.
1291 pub backend: BindingBackend,
1292 /// Provider-specific routing key. For Operator-backed runners this is
1293 /// the logical `operator_ref`, never a runtime session id.
1294 #[serde(default, skip_serializing_if = "Option::is_none")]
1295 pub binding_target: Option<String>,
1296 /// Requested model name or tier from [`AgentProfile::model`].
1297 #[serde(default, skip_serializing_if = "Option::is_none")]
1298 pub requested_model: Option<String>,
1299 /// Minimum tool grant declared by the resolved [`Runner`].
1300 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1301 pub requested_tools: Vec<String>,
1302 /// Platform launch variant requested by the resolved [`Runner`].
1303 #[serde(default, skip_serializing_if = "Option::is_none")]
1304 pub launch_variant: Option<String>,
1305}
1306
1307/// Backend family a binding provider must resolve.
1308#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1309#[serde(rename_all = "snake_case")]
1310pub enum BindingBackend {
1311 /// Platform-neutral Operator/MainAI WebSocket execution.
1312 WsOperator,
1313 /// Claude Code wrapper dispatched through an Operator WebSocket.
1314 WsClaudeCode,
1315 /// AgentBlock registry enforced in the Server process.
1316 AgentBlockInProcess,
1317}
1318
1319/// Provider report describing the effective runtime binding for one agent.
1320/// This value is untrusted until Swarm validates it against [`BindRequest`].
1321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1322#[serde(deny_unknown_fields)]
1323pub struct BindReceipt {
1324 /// Logical agent name copied from the request.
1325 pub agent: String,
1326 /// Declaration digest copied from the request. Core rejects stale or
1327 /// cross-request receipts even when the logical agent name matches.
1328 pub request_digest: BindingDigest,
1329 /// Stable provider implementation identifier.
1330 pub provider_id: String,
1331 /// Provider or adapter revision used to resolve the binding.
1332 #[serde(default, skip_serializing_if = "Option::is_none")]
1333 pub provider_revision: Option<String>,
1334 /// Effective model after platform alias/tier resolution.
1335 #[serde(default, skip_serializing_if = "Option::is_none")]
1336 pub resolved_model: Option<String>,
1337 /// Effective tool grant enforced by the execution environment.
1338 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1339 pub effective_tools: Vec<String>,
1340 /// Effective platform launch variant.
1341 #[serde(default, skip_serializing_if = "Option::is_none")]
1342 pub launch_variant: Option<String>,
1343 /// Optional digest of the provider-observed capability snapshot. This is
1344 /// a drift/lint correlation key, not independent security evidence.
1345 #[serde(
1346 default,
1347 alias = "evidence_digest",
1348 skip_serializing_if = "Option::is_none"
1349 )]
1350 pub capability_snapshot_digest: Option<BindingDigest>,
1351}
1352
1353/// One provider outcome for a single [`BindRequest`].
1354///
1355/// A provider reports exactly one outcome per requested agent. `Bound`
1356/// carries an (untrusted) [`BindReceipt`] Core still validates; `Unbound`
1357/// records that the execution environment currently offers no capability for
1358/// the request (e.g. the role has not joined, or the manifest declares no
1359/// matching launch variant). Whether an `Unbound` outcome fails the launch
1360/// or is merely observed is decided by
1361/// [`CompilerStrategy::strict_binding`] — not by the provider.
1362#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1363#[serde(tag = "outcome", rename_all = "snake_case", deny_unknown_fields)]
1364pub enum BindOutcome {
1365 /// The provider resolved a receipt for the agent. Still untrusted until
1366 /// Core validates it against the originating [`BindRequest`].
1367 Bound {
1368 /// Provider-reported binding, validated by Core before acceptance.
1369 receipt: BindReceipt,
1370 },
1371 /// The provider offers no capability for the request right now. The
1372 /// `reason` is human-facing diagnostic text only; it never enters the
1373 /// [`BoundAgent`] snapshot or its digest lineage.
1374 Unbound {
1375 /// Logical agent name copied from the request.
1376 agent: String,
1377 /// Why the provider could not bind the agent.
1378 reason: String,
1379 },
1380}
1381
1382/// Core-validated capability statement pinned into a [`BoundAgent`].
1383///
1384/// It deliberately omits the logical agent name because the containing
1385/// snapshot already supplies that identity.
1386#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1387#[serde(deny_unknown_fields)]
1388pub struct BindingAttestation {
1389 /// Declaration-only digest the provider attested.
1390 pub request_digest: BindingDigest,
1391 /// Stable provider implementation identifier.
1392 pub provider_id: String,
1393 /// Provider or adapter revision used to resolve the binding.
1394 #[serde(default, skip_serializing_if = "Option::is_none")]
1395 pub provider_revision: Option<String>,
1396 /// Effective model after platform alias/tier resolution.
1397 #[serde(default, skip_serializing_if = "Option::is_none")]
1398 pub resolved_model: Option<String>,
1399 /// Effective tool grant, canonicalized by Swarm.
1400 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1401 pub effective_tools: Vec<String>,
1402 /// Effective platform launch variant.
1403 #[serde(default, skip_serializing_if = "Option::is_none")]
1404 pub launch_variant: Option<String>,
1405 /// Optional digest of the provider-observed capability snapshot.
1406 #[serde(
1407 default,
1408 alias = "evidence_digest",
1409 skip_serializing_if = "Option::is_none"
1410 )]
1411 pub capability_snapshot_digest: Option<BindingDigest>,
1412}
1413
1414/// One effective capability advertised by an execution-environment
1415/// provider. Operator manifests normally publish one entry per wrapper
1416/// variant.
1417#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1418#[serde(deny_unknown_fields)]
1419pub struct AgentProviderCapability {
1420 /// Platform launch variant this capability serves. `None` is reserved
1421 /// for backends without a variant axis.
1422 #[serde(default, skip_serializing_if = "Option::is_none")]
1423 pub launch_variant: Option<String>,
1424 /// Effective model selected by the provider.
1425 #[serde(default, skip_serializing_if = "Option::is_none")]
1426 pub resolved_model: Option<String>,
1427 /// Effective tool grant enforced by the provider.
1428 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1429 pub effective_tools: Vec<String>,
1430 /// Optional digest of the provider-observed capability snapshot.
1431 #[serde(
1432 default,
1433 alias = "evidence_digest",
1434 skip_serializing_if = "Option::is_none"
1435 )]
1436 pub capability_snapshot_digest: Option<BindingDigest>,
1437}
1438
1439/// Capability manifest supplied by an Operator/MainAI or an official
1440/// execution-platform plugin when joining the Server.
1441#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1442#[serde(deny_unknown_fields)]
1443pub struct AgentProviderManifest {
1444 /// Stable provider implementation identifier.
1445 pub provider_id: String,
1446 /// Provider or adapter revision used to inspect capabilities.
1447 #[serde(default, skip_serializing_if = "Option::is_none")]
1448 pub provider_revision: Option<String>,
1449 /// Effective capabilities available through this provider instance.
1450 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1451 pub capabilities: Vec<AgentProviderCapability>,
1452}
1453
1454/// Immutable, Run-scoped result of binding the Runner / Agent / Context
1455/// layers for one logical agent.
1456///
1457/// This is derived state, not a fourth authoring source of truth. The full
1458/// [`AgentDef`] is retained deliberately: resume/replay must not re-read a
1459/// changed role prompt or result contract from a mutable Blueprint registry.
1460/// Capability attestation is adapter-owned and is therefore not guessed here;
1461/// the resolved [`Runner`] remains a declaration until an adapter records its
1462/// requested/effective comparison.
1463#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1464#[serde(deny_unknown_fields)]
1465pub struct BoundAgent {
1466 /// Logical agent definition pinned for the Run.
1467 pub agent: AgentDef,
1468 /// Runner selected by [`resolve_runner`], if this agent needs one.
1469 #[serde(default, skip_serializing_if = "Option::is_none")]
1470 pub runner: Option<Runner>,
1471 /// Effective static Context policy (`AgentMeta.context_policy` wins over
1472 /// `Blueprint.default_context_policy`). Runtime context values are not
1473 /// embedded here.
1474 #[serde(default, skip_serializing_if = "Option::is_none")]
1475 pub context_policy: Option<ContextPolicy>,
1476 /// Declaration tier that supplied `runner`.
1477 pub runner_source: RunnerResolutionSource,
1478 /// Effective capability statement accepted from the injected binding
1479 /// provider. `None` preserves the declaration-only compatibility path.
1480 #[serde(default, skip_serializing_if = "Option::is_none")]
1481 pub attestation: Option<BindingAttestation>,
1482 /// SHA-256 over the other fields of this snapshot, prefixed with
1483 /// `sha256:`. This is replay identity and an observability correlation
1484 /// key, not a signature.
1485 pub binding_digest: BindingDigest,
1486}
1487
1488/// Failure while constructing immutable [`BoundAgent`] snapshots.
1489#[derive(Debug, thiserror::Error)]
1490pub enum BoundAgentResolveError {
1491 /// A Runner reference did not resolve.
1492 #[error(transparent)]
1493 Runner(#[from] RunnerResolveError),
1494 /// The snapshot input could not be serialized for deterministic hashing.
1495 #[error("bound agent '{agent}' could not be serialized for digest: {source}")]
1496 Digest {
1497 /// Logical agent name.
1498 agent: String,
1499 /// Serialization failure.
1500 source: serde_json::Error,
1501 },
1502 /// Strict binding rejected the deprecated Claude Code compatibility
1503 /// declaration instead of silently accepting it.
1504 #[error(
1505 "agent '{agent}' uses deprecated profile.worker_binding; strict binding requires runner or runner_ref"
1506 )]
1507 LegacyWorkerBindingDisabled {
1508 /// Logical agent that must be migrated.
1509 agent: String,
1510 },
1511}
1512
1513#[derive(Serialize)]
1514struct BoundAgentDigestInput<'a> {
1515 agent: &'a AgentDef,
1516 runner: &'a Option<Runner>,
1517 context_policy: &'a Option<ContextPolicy>,
1518 runner_source: RunnerResolutionSource,
1519 attestation: &'a Option<BindingAttestation>,
1520}
1521
1522impl BoundAgent {
1523 /// Replace the effective capability attestation and recompute replay
1524 /// identity over the complete immutable snapshot.
1525 pub fn set_attestation(
1526 &mut self,
1527 attestation: BindingAttestation,
1528 ) -> Result<(), BoundAgentResolveError> {
1529 self.attestation = Some(attestation);
1530 self.recompute_binding_digest()
1531 }
1532
1533 /// Recompute `binding_digest` after a trusted snapshot mutation.
1534 pub fn recompute_binding_digest(&mut self) -> Result<(), BoundAgentResolveError> {
1535 let digest_input = BoundAgentDigestInput {
1536 agent: &self.agent,
1537 runner: &self.runner,
1538 context_policy: &self.context_policy,
1539 runner_source: self.runner_source,
1540 attestation: &self.attestation,
1541 };
1542 let bytes =
1543 serde_json::to_vec(&digest_input).map_err(|source| BoundAgentResolveError::Digest {
1544 agent: self.agent.name.clone(),
1545 source,
1546 })?;
1547 self.binding_digest = BindingDigest::sha256(bytes);
1548 Ok(())
1549 }
1550}
1551
1552/// Resolve every `Blueprint.agents` entry into an immutable Run snapshot.
1553/// Output order follows `Blueprint.agents`, making persistence and explain
1554/// responses stable without a second sort.
1555pub fn resolve_bound_agents(bp: &Blueprint) -> Result<Vec<BoundAgent>, BoundAgentResolveError> {
1556 resolve_bound_agents_with_legacy(bp, true)
1557}
1558
1559/// Strict counterpart to [`resolve_bound_agents`]: rejects the deprecated
1560/// `profile.worker_binding` fallback. This is the migration gate for callers
1561/// that require every binding to use the platform-neutral Runner contract.
1562pub fn resolve_bound_agents_strict(
1563 bp: &Blueprint,
1564) -> Result<Vec<BoundAgent>, BoundAgentResolveError> {
1565 resolve_bound_agents_with_legacy(bp, false)
1566}
1567
1568fn resolve_bound_agents_with_legacy(
1569 bp: &Blueprint,
1570 allow_legacy: bool,
1571) -> Result<Vec<BoundAgent>, BoundAgentResolveError> {
1572 bp.agents
1573 .iter()
1574 .map(|agent| {
1575 let runner = resolve_runner(bp, agent)?;
1576 let runner_source = if agent.runner.is_some() {
1577 RunnerResolutionSource::AgentInline
1578 } else if agent.runner_ref.is_some() {
1579 RunnerResolutionSource::AgentRef
1580 } else if agent
1581 .profile
1582 .as_ref()
1583 .and_then(|p| p.worker_binding.as_ref())
1584 .is_some()
1585 {
1586 RunnerResolutionSource::LegacyWorkerBinding
1587 } else if bp.default_runner.is_some() {
1588 RunnerResolutionSource::BlueprintDefault
1589 } else {
1590 RunnerResolutionSource::None
1591 };
1592 if !allow_legacy && runner_source == RunnerResolutionSource::LegacyWorkerBinding {
1593 return Err(BoundAgentResolveError::LegacyWorkerBindingDisabled {
1594 agent: agent.name.clone(),
1595 });
1596 }
1597 let context_policy = agent
1598 .meta
1599 .as_ref()
1600 .and_then(|m| m.context_policy.clone())
1601 .or_else(|| bp.default_context_policy.clone());
1602 let digest_input = BoundAgentDigestInput {
1603 agent,
1604 runner: &runner,
1605 context_policy: &context_policy,
1606 runner_source,
1607 attestation: &None,
1608 };
1609 let bytes = serde_json::to_vec(&digest_input).map_err(|source| {
1610 BoundAgentResolveError::Digest {
1611 agent: agent.name.clone(),
1612 source,
1613 }
1614 })?;
1615 let binding_digest = BindingDigest::sha256(bytes);
1616 Ok(BoundAgent {
1617 agent: agent.clone(),
1618 runner,
1619 context_policy,
1620 runner_source,
1621 attestation: None,
1622 binding_digest,
1623 })
1624 })
1625 .collect()
1626}
1627
1628// ──────────────────────────────────────────────────────────────────────────
1629// OperatorDef / OperatorKind
1630// ──────────────────────────────────────────────────────────────────────────
1631
1632/// Kind axis of an Operator role (= "in which mode does this Operator run").
1633/// Corresponds 1:1 with the engine's runtime `OperatorKind`. Kept as a schema
1634/// duplicate so that BPs can be authored while depending only on this crate.
1635#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
1636#[serde(rename_all = "snake_case")]
1637pub enum OperatorKind {
1638 /// MainAI (= interactive AI Operator via WS client or SDK).
1639 MainAi,
1640 /// Automate (= normal spawn path, without human interception).
1641 #[default]
1642 Automate,
1643 /// Composite (= MainAi + Automate running side by side).
1644 Composite,
1645}
1646
1647/// Design-time definition of an Operator role (first-class).
1648///
1649/// `AgentDef.spec.operator_ref` references this struct's `name` as a logical role name.
1650/// Binding to a runtime backend (WS session / SDK / pool, etc.) is established via the
1651/// attach path; the BP side only declares "under this logical name we expect an Operator
1652/// of this Kind".
1653///
1654/// `spec` is an escape hatch for kind-specific config (WS endpoint / SDK profile / pool
1655/// binding, etc.). Even when empty, declaring `name` + `kind` alone is enough for
1656/// compile-time validation to succeed (= it guarantees that agent `operator_ref` values
1657/// reference an existing definition).
1658#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
1659#[serde(deny_unknown_fields)]
1660pub struct OperatorDef {
1661 /// Logical role name (= design-time symbol referenced from `AgentDef.spec.operator_ref`).
1662 pub name: String,
1663 /// Display name for UI / docs (optional).
1664 #[serde(default)]
1665 pub display_name: Option<String>,
1666 /// Kind axis of the Operator (MainAi / Automate / Composite) — the "BP
1667 /// Agent-level" tier of the 4-tier `OperatorKind` cascade (see
1668 /// `Blueprint.default_operator_kind` for the full tier list). `None`
1669 /// when this `OperatorDef` does not declare a kind; the resolver then
1670 /// falls through to BP Global / Default Fallback for agents referencing
1671 /// this role via `AgentDef.spec.operator_ref`.
1672 #[serde(default)]
1673 pub kind: Option<OperatorKind>,
1674 /// Kind-specific config (WS endpoint / SDK profile / pool binding, etc.). Interpreted
1675 /// by the factory.
1676 #[serde(default)]
1677 pub spec: Value,
1678 /// Operator persona information (e.g. system_prompt template). Same shape as
1679 /// `AgentDef.profile`. Used as a template when the Operator itself plays a "role".
1680 /// If `None`, the agent-side profile is used instead.
1681 #[serde(default)]
1682 pub profile: Option<AgentProfile>,
1683 /// Operator-level metadata (description / version / tags).
1684 #[serde(default)]
1685 pub meta: Option<AgentMeta>,
1686}
1687
1688/// Named, multi-step-shared declarative context payload (GH #21 Phase 2).
1689///
1690/// Lives in the [`Blueprint::metas`] pool and is referenced by name from
1691/// two independent consumers: a `$step_meta.ref` envelope embedded in a
1692/// Step's evaluated `in` value (the Step tier, resolved by
1693/// `EngineDispatcher::dispatch` in the `mlua-swarm` core crate at
1694/// dispatch time — see `EngineDispatcher::with_step_metas`), and
1695/// [`AgentMeta::meta_ref`] (the Agent tier, resolved at launch time and
1696/// merged UNDER the agent's inline `AgentMeta::ctx`). The pool lets
1697/// multiple Steps and/or Agents share one declarative context object by
1698/// name instead of repeating it inline.
1699#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
1700#[serde(deny_unknown_fields)]
1701pub struct MetaDef {
1702 /// Logical name (= referenced by `$step_meta.ref` and
1703 /// `AgentMeta.meta_ref`; unique within [`Blueprint::metas`]).
1704 pub name: String,
1705 /// Declarative context payload. Consumers expect a JSON `Object` so
1706 /// it can be shallow-merged with an `inline` override / an agent's
1707 /// own `ctx` (a non-`Object` value is rejected — loudly at dispatch
1708 /// time for the Step tier, defensively (warn + skip) at launch time
1709 /// for the Agent tier); the shape is otherwise free-form.
1710 pub ctx: Value,
1711}
1712
1713/// GH #27 (follow-up to #23) — Blueprint-declared override of the
1714/// `mlua-swarm` core crate's placement resolver
1715/// (`mlua_swarm::core::projection_placement::ProjectionPlacement`), which
1716/// decides where a Step's materialized OUTPUT file (submit-time sink,
1717/// server read-back, and spawn-time `ctx_projection` pointer — the "3
1718/// path" convergence point) is written on disk. Both fields are
1719/// independently optional and validated (`dir_template`) at
1720/// `Compiler::compile` time — see that resolver's `from_spec` doc for the
1721/// full rejection rules.
1722#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
1723#[serde(deny_unknown_fields)]
1724pub struct ProjectionPlacementSpec {
1725 /// Which of the spawn-time `work_dir` / `project_root` to prefer as
1726 /// the materialize root, falling back to the other when the
1727 /// preferred one is absent. `"work_dir"` (default, current
1728 /// byte-compat behavior) | `"project_root"`. `None` = the default
1729 /// (`"work_dir"`).
1730 #[serde(default, skip_serializing_if = "Option::is_none")]
1731 pub root: Option<String>,
1732 /// Target directory template, relative to the resolved root, with a
1733 /// `{task_id}` placeholder substituted at materialize time. `None` =
1734 /// the default (`"workspace/tasks/{task_id}/ctx"`, current byte-compat
1735 /// behavior). Must be non-empty, contain the `{task_id}` placeholder,
1736 /// stay relative, and not contain any `..` path segment — rejected at
1737 /// `Compiler::compile` time otherwise.
1738 #[serde(default, skip_serializing_if = "Option::is_none")]
1739 pub dir_template: Option<String>,
1740}
1741
1742/// Agent / Operator level metadata (description / version / tags).
1743#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
1744#[serde(deny_unknown_fields)]
1745pub struct AgentMeta {
1746 /// Short human-readable description.
1747 #[serde(default)]
1748 pub description: Option<String>,
1749 /// Free-form version label.
1750 #[serde(default)]
1751 pub version: Option<String>,
1752 /// Tag list for classification / routing.
1753 #[serde(default)]
1754 pub tags: Vec<String>,
1755 /// GH #21 Phase 1 — "BP Agent-level" tier of the agent-context supply
1756 /// axis: a declarative object merged into `ctx.meta.runtime` for this
1757 /// agent's spawns, on top of (and winning over)
1758 /// [`Blueprint::default_agent_ctx`]. See that field's doc for the
1759 /// contrast with `default_init_ctx`. `None` = this agent declares no
1760 /// per-agent context (the BP-global tier alone applies, if any).
1761 #[serde(default, skip_serializing_if = "Option::is_none")]
1762 #[schemars(with = "Option<Value>")]
1763 pub ctx: Option<Value>,
1764 /// GH #21 Phase 1 — "BP Agent-level" tier of the [`ContextPolicy`]
1765 /// cascade: outranks [`Blueprint::default_context_policy`] for this
1766 /// agent. `None` = fall through to the BP-global policy (or pass-all
1767 /// if that is also `None`).
1768 #[serde(default, skip_serializing_if = "Option::is_none")]
1769 pub context_policy: Option<ContextPolicy>,
1770 /// GH #21 Phase 2 — "BP Agent-level" tier of the [`MetaDef`] pool:
1771 /// resolves against [`Blueprint::metas`] by name. The resolved
1772 /// `ctx` sits UNDER this agent's inline [`Self::ctx`] (inline wins
1773 /// on key collision). `None` = this agent declares no shared
1774 /// `MetaDef` reference.
1775 #[serde(default, skip_serializing_if = "Option::is_none")]
1776 pub meta_ref: Option<String>,
1777 /// GH #23 — the step-projection canonical name this agent's dispatched
1778 /// Steps should be addressed by (data-plane submit / `ContextPolicy`
1779 /// filter / `StepPointer`/`StepSummary` `name` / REST `:step` path /
1780 /// materialized file stem — see `mlua-swarm` core's
1781 /// `core::step_naming::StepNaming` for the table this field feeds).
1782 /// `None` = this agent declares no projection name; the canonical
1783 /// name falls back to the Step's `ref` (the flow.ir data-plane
1784 /// producer name), matching pre-GH-#23 behavior byte-for-byte.
1785 #[serde(default, skip_serializing_if = "Option::is_none")]
1786 pub projection_name: Option<String>,
1787}
1788
1789// ──────────────────────────────────────────────────────────────────────────
1790// Compiler hints / strategy
1791// ──────────────────────────────────────────────────────────────────────────
1792
1793/// Per-agent overrides / hints. Interpreted by the Compiler / SpawnerFactory; not required.
1794#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
1795#[serde(deny_unknown_fields)]
1796pub struct CompilerHints {
1797 /// Agent name → per-agent hint (= passed to `SpawnerFactory.build`).
1798 #[serde(default)]
1799 pub per_agent: HashMap<String, Value>,
1800 /// Global hints (= e.g. parallel limit, default timeout, ...).
1801 #[serde(default)]
1802 pub global: Value,
1803}
1804
1805/// Compiler behavior rules. Controls strict / lenient handling and default fallback.
1806#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
1807#[serde(deny_unknown_fields)]
1808pub struct CompilerStrategy {
1809 /// If `true` (default), an unresolved `Step.ref` is an error; if `false`, it falls
1810 /// through to the default Spawner.
1811 #[serde(default = "default_true")]
1812 pub strict_refs: bool,
1813 /// If `true` (default), an `AgentKind` missing from the registry is an error; if
1814 /// `false`, it is skipped.
1815 #[serde(default = "default_true")]
1816 pub strict_kind: bool,
1817 /// If `true`, every Runner-backed agent must obtain a Core-validated
1818 /// attestation at launch (a binding provider is required, and any agent
1819 /// the provider leaves `Unbound` fails the launch). If `false` (default),
1820 /// an unattested agent runs `DeclarationOnly` and the gap is only
1821 /// observed (tracing warn + a `RunRecord.degradations` entry).
1822 ///
1823 /// This default is deliberately the opposite of `strict_refs` /
1824 /// `strict_kind` (both default `true`): those two guard *structural
1825 /// integrity* of the Blueprint itself (an unresolved ref or unknown kind
1826 /// is always a Blueprint bug), whereas binding attestation is an
1827 /// *execution-assurance opt-in* — it depends on an execution environment
1828 /// being present to attest against, which is not available for embed-only
1829 /// or manifest-less launches. Requiring it by default would break every
1830 /// launch that has no provider, so it is opt-in per Blueprint.
1831 #[serde(default)]
1832 pub strict_binding: bool,
1833}
1834
1835fn default_true() -> bool {
1836 true
1837}
1838
1839impl Default for CompilerStrategy {
1840 fn default() -> Self {
1841 Self {
1842 strict_refs: true,
1843 strict_kind: true,
1844 strict_binding: false,
1845 }
1846 }
1847}
1848
1849// ──────────────────────────────────────────────────────────────────────────
1850// Blueprint metadata / origin
1851// ──────────────────────────────────────────────────────────────────────────
1852
1853/// Blueprint-level metadata (description / origin / tags / ttl / version label / alias).
1854#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
1855#[serde(deny_unknown_fields)]
1856pub struct BlueprintMetadata {
1857 /// Short human-readable description of the Blueprint.
1858 #[serde(default)]
1859 pub description: Option<String>,
1860 /// Provenance record (inline / file / algocline).
1861 #[serde(default)]
1862 pub origin: BlueprintOrigin,
1863 /// Tag list for classification / routing.
1864 #[serde(default)]
1865 pub tags: Vec<String>,
1866 /// Optional SemVer label (= match target for `TaskPipeline VersionSelector::SemVerReq`).
1867 /// Example: `"1.2.3"`. Rewritten by `EnhanceAdapter` on PATCH/MINOR/MAJOR bumps.
1868 #[serde(default, skip_serializing_if = "Option::is_none")]
1869 pub version_label: Option<String>,
1870 /// Optional LDS session alias label. The Swarm engine itself does not apply this
1871 /// (= it is free-form content); the value is expanded into the Spawn directive and
1872 /// reaches the MainAI. The MainAI is expected to establish a task session via
1873 /// `mcp__lds__session_create(root=..., alias=<this>)`, and to inject
1874 /// `LDS Session Alias: <this>` verbatim into the SubAgent dispatch prompt body.
1875 /// The SubAgent body then calls `mcp__lds__session_start(alias=<this>)` with the
1876 /// received alias. Worktree ownership is thereby unified under a single session, and
1877 /// cross-SubAgent / cross-worktree ownership blocks (= `not owned by this session`)
1878 /// cannot fire structurally.
1879 #[serde(default, skip_serializing_if = "Option::is_none")]
1880 pub project_name_alias: Option<String>,
1881 /// Optional default TTL (seconds) for tasks dispatched via this BP. Estimated by the
1882 /// Blueprint author from the flow shape (agent count × expected duration per agent).
1883 /// If `POST /v1/tasks` supplies `ttl_secs` explicitly, the body value wins; otherwise
1884 /// this metadata field is used as the default; if both are absent, the server global
1885 /// default (`default_run_ttl()` = 1800s) applies. Not needed for short chains (~5 min);
1886 /// recommended for long chains (14 agents × several minutes = 30-60 min).
1887 #[serde(default, skip_serializing_if = "Option::is_none")]
1888 pub default_run_ttl_secs: Option<u64>,
1889 /// GH #50 follow-up (issue `33bc825b`): promote `VerdictValueUnhandled`
1890 /// compile-time lint to a hard error. When `false` (or absent), a
1891 /// declared `AgentDef.verdict.values` entry that no downstream cond
1892 /// references is only surfaced via `tracing::warn!` (informational);
1893 /// when `true`, `Compiler::compile` rejects the Blueprint with
1894 /// `CompileError::VerdictValueUnhandled`. Opt-in so existing Blueprints
1895 /// that intentionally leave some verdict values as silent-pass
1896 /// informational tokens keep compiling unchanged.
1897 #[serde(default, skip_serializing_if = "Option::is_none")]
1898 pub strict_verdict_handling: Option<bool>,
1899}
1900
1901/// Provenance record of a Blueprint.
1902#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
1903#[serde(tag = "kind", rename_all = "snake_case")]
1904pub enum BlueprintOrigin {
1905 /// Inline construction, e.g. via a Rust struct literal or test code.
1906 #[default]
1907 Inline,
1908 /// Loaded from a file.
1909 File {
1910 /// Source file path.
1911 path: String,
1912 },
1913 /// Emitted by an algocline strategy (traced by `session_id`).
1914 Algo {
1915 /// Algocline session identifier.
1916 session_id: String,
1917 },
1918}
1919
1920#[cfg(test)]
1921mod tests {
1922 use super::*;
1923
1924 #[test]
1925 fn schema_version_default_parses() {
1926 let v = default_schema_version();
1927 assert_eq!(v.to_string(), "0.1.0");
1928 }
1929
1930 #[test]
1931 fn current_schema_version_const_matches() {
1932 assert_eq!(CURRENT_SCHEMA_VERSION, "0.1.0");
1933 }
1934
1935 #[test]
1936 fn blueprint_json_schema_exports_key_properties() {
1937 let schema = schemars::schema_for!(Blueprint);
1938 let v = serde_json::to_value(&schema).expect("schema serializes");
1939 let props = v["properties"].as_object().expect("object schema");
1940 for key in [
1941 "schema_version",
1942 "id",
1943 "flow",
1944 "agents",
1945 "operators",
1946 "metas",
1947 "hints",
1948 "strategy",
1949 "metadata",
1950 "spawner_hints",
1951 "default_agent_kind",
1952 "default_operator_kind",
1953 "default_init_ctx",
1954 "default_agent_ctx",
1955 "default_context_policy",
1956 "projection_placement",
1957 "audits",
1958 "runners",
1959 "default_runner",
1960 "check_policy",
1961 ] {
1962 assert!(props.contains_key(key), "missing property: {key}");
1963 }
1964 // semver override lands as a plain string
1965 assert_eq!(v["properties"]["schema_version"]["type"], "string");
1966 // enum variants (snake_case) survive into the schema (LLM author axis)
1967 let dump = v.to_string();
1968 assert!(dump.contains("agent_block"), "AgentKind variants in schema");
1969 assert!(dump.contains("main_ai"), "OperatorKind variants in schema");
1970 // nested defs are referenced (AgentDef reachable from agents[])
1971 assert!(dump.contains("AgentDef"), "AgentDef definition in schema");
1972 }
1973
1974 #[test]
1975 fn agent_profile_worker_binding_roundtrips_when_some() {
1976 let profile = AgentProfile {
1977 worker_binding: Some("mse-worker-coder".to_string()),
1978 ..Default::default()
1979 };
1980 let json = serde_json::to_value(&profile).expect("serializes");
1981 assert_eq!(json["worker_binding"], "mse-worker-coder");
1982 let back: AgentProfile = serde_json::from_value(json).expect("deserializes");
1983 assert_eq!(back.worker_binding.as_deref(), Some("mse-worker-coder"));
1984 }
1985
1986 #[test]
1987 fn agent_profile_worker_binding_omitted_when_none() {
1988 let profile = AgentProfile::default();
1989 let json = serde_json::to_value(&profile).expect("serializes");
1990 // `skip_serializing_if = "Option::is_none"` — the key must not appear at all.
1991 assert!(
1992 json.as_object().unwrap().get("worker_binding").is_none(),
1993 "worker_binding key must be absent when None: {json}"
1994 );
1995 let back: AgentProfile = serde_json::from_value(json).expect("deserializes");
1996 assert_eq!(back.worker_binding, None);
1997 }
1998
1999 // ──────────────────────────────────────────────────────────────
2000 // issue #19 ST3: `Blueprint.default_init_ctx`
2001 // ──────────────────────────────────────────────────────────────
2002
2003 fn minimal_bp(default_init_ctx: Option<Value>) -> Blueprint {
2004 Blueprint {
2005 schema_version: current_schema_version(),
2006 id: "bp-init-ctx-ut".into(),
2007 flow: FlowNode::Seq { children: vec![] },
2008 agents: vec![],
2009 operators: vec![],
2010 metas: vec![],
2011 hints: Default::default(),
2012 strategy: Default::default(),
2013 metadata: Default::default(),
2014 spawner_hints: Default::default(),
2015 default_agent_kind: AgentKind::Operator,
2016 default_operator_kind: None,
2017 default_init_ctx,
2018 default_agent_ctx: None,
2019 default_context_policy: None,
2020 projection_placement: None,
2021 audits: vec![],
2022 degradation_policy: None,
2023 runners: vec![],
2024 default_runner: None,
2025 subprocesses: vec![],
2026 check_policy: None,
2027 blueprint_ref_includes: Vec::new(),
2028 }
2029 }
2030
2031 #[test]
2032 fn blueprint_default_init_ctx_roundtrips_when_some() {
2033 let bp = minimal_bp(Some(serde_json::json!({ "seeded": true })));
2034 let json = serde_json::to_string(&bp).expect("serializes");
2035 let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2036 assert_eq!(
2037 back.default_init_ctx,
2038 Some(serde_json::json!({ "seeded": true }))
2039 );
2040 assert_eq!(bp, back);
2041 }
2042
2043 #[test]
2044 fn blueprint_default_init_ctx_omitted_when_none() {
2045 let bp = minimal_bp(None);
2046 let json = serde_json::to_value(&bp).expect("serializes");
2047 // `skip_serializing_if = "Option::is_none"` — the key must not appear at all
2048 // (pre-#19 Blueprints round-trip byte-identical through this path).
2049 assert!(
2050 json.as_object().unwrap().get("default_init_ctx").is_none(),
2051 "default_init_ctx key must be absent when None: {json}"
2052 );
2053 let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2054 assert_eq!(back.default_init_ctx, None);
2055 assert_eq!(bp, back);
2056 }
2057
2058 #[test]
2059 fn blueprint_json_schema_exports_default_init_ctx_as_nullable_value() {
2060 let schema = schemars::schema_for!(Blueprint);
2061 let v = serde_json::to_value(&schema).expect("schema serializes");
2062 assert!(
2063 v["properties"]["default_init_ctx"].is_object(),
2064 "default_init_ctx must appear in the exported schema: {v}"
2065 );
2066 }
2067
2068 // ──────────────────────────────────────────────────────────────
2069 // issue #21 Phase 1: `Blueprint.default_agent_ctx` /
2070 // `default_context_policy`, `AgentMeta.ctx` / `context_policy`,
2071 // `ContextPolicy`
2072 // ──────────────────────────────────────────────────────────────
2073
2074 #[test]
2075 fn blueprint_default_agent_ctx_and_context_policy_roundtrip_when_some() {
2076 let mut bp = minimal_bp(None);
2077 bp.default_agent_ctx = Some(serde_json::json!({ "org_conventions": "x" }));
2078 bp.default_context_policy = Some(ContextPolicy {
2079 include: Some(vec!["project_root".to_string()]),
2080 exclude: vec!["work_dir".to_string()],
2081 ..Default::default()
2082 });
2083 let json = serde_json::to_string(&bp).expect("serializes");
2084 let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2085 assert_eq!(bp, back);
2086 assert_eq!(
2087 back.default_agent_ctx,
2088 Some(serde_json::json!({ "org_conventions": "x" }))
2089 );
2090 assert_eq!(
2091 back.default_context_policy,
2092 Some(ContextPolicy {
2093 include: Some(vec!["project_root".to_string()]),
2094 exclude: vec!["work_dir".to_string()],
2095 ..Default::default()
2096 })
2097 );
2098 }
2099
2100 #[test]
2101 fn blueprint_default_agent_ctx_and_context_policy_omitted_when_none() {
2102 let bp = minimal_bp(None);
2103 let json = serde_json::to_value(&bp).expect("serializes");
2104 let obj = json.as_object().unwrap();
2105 assert!(
2106 obj.get("default_agent_ctx").is_none(),
2107 "default_agent_ctx key must be absent when None: {json}"
2108 );
2109 assert!(
2110 obj.get("default_context_policy").is_none(),
2111 "default_context_policy key must be absent when None: {json}"
2112 );
2113 let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2114 assert_eq!(back.default_agent_ctx, None);
2115 assert_eq!(back.default_context_policy, None);
2116 assert_eq!(bp, back);
2117 }
2118
2119 #[test]
2120 fn blueprint_json_schema_exports_agent_ctx_and_context_policy() {
2121 let schema = schemars::schema_for!(Blueprint);
2122 let v = serde_json::to_value(&schema).expect("schema serializes");
2123 assert!(
2124 v["properties"]["default_agent_ctx"].is_object(),
2125 "default_agent_ctx must appear in the exported schema: {v}"
2126 );
2127 assert!(
2128 v["properties"]["default_context_policy"].is_object(),
2129 "default_context_policy must appear in the exported schema: {v}"
2130 );
2131 }
2132
2133 // ──────────────────────────────────────────────────────────────
2134 // GH #27 (follow-up to #23): `Blueprint.projection_placement` /
2135 // `ProjectionPlacementSpec`
2136 // ──────────────────────────────────────────────────────────────
2137
2138 #[test]
2139 fn blueprint_projection_placement_roundtrips_when_some() {
2140 let mut bp = minimal_bp(None);
2141 bp.projection_placement = Some(ProjectionPlacementSpec {
2142 root: Some("project_root".to_string()),
2143 dir_template: Some("custom/{task_id}/out".to_string()),
2144 });
2145 let json = serde_json::to_string(&bp).expect("serializes");
2146 let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2147 assert_eq!(bp, back);
2148 assert_eq!(
2149 back.projection_placement,
2150 Some(ProjectionPlacementSpec {
2151 root: Some("project_root".to_string()),
2152 dir_template: Some("custom/{task_id}/out".to_string()),
2153 })
2154 );
2155 }
2156
2157 #[test]
2158 fn blueprint_projection_placement_omitted_when_none() {
2159 let bp = minimal_bp(None);
2160 let json = serde_json::to_value(&bp).expect("serializes");
2161 assert!(
2162 json.as_object()
2163 .unwrap()
2164 .get("projection_placement")
2165 .is_none(),
2166 "projection_placement key must be absent when None: {json}"
2167 );
2168 let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2169 assert_eq!(back.projection_placement, None);
2170 assert_eq!(bp, back);
2171 }
2172
2173 #[test]
2174 fn blueprint_json_schema_exports_projection_placement() {
2175 let schema = schemars::schema_for!(Blueprint);
2176 let v = serde_json::to_value(&schema).expect("schema serializes");
2177 assert!(
2178 v["properties"]["projection_placement"].is_object(),
2179 "projection_placement must appear in the exported schema: {v}"
2180 );
2181 }
2182
2183 #[test]
2184 fn agent_meta_ctx_and_context_policy_roundtrip_when_some() {
2185 let meta = AgentMeta {
2186 ctx: Some(serde_json::json!({ "k": "v" })),
2187 context_policy: Some(ContextPolicy {
2188 include: None,
2189 exclude: vec!["run_id".to_string()],
2190 ..Default::default()
2191 }),
2192 ..Default::default()
2193 };
2194 let json = serde_json::to_value(&meta).expect("serializes");
2195 let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
2196 assert_eq!(back, meta);
2197 }
2198
2199 #[test]
2200 fn agent_meta_ctx_and_context_policy_omitted_when_none() {
2201 let meta = AgentMeta::default();
2202 let json = serde_json::to_value(&meta).expect("serializes");
2203 let obj = json.as_object().unwrap();
2204 assert!(
2205 obj.get("ctx").is_none(),
2206 "ctx key must be absent when None: {json}"
2207 );
2208 assert!(
2209 obj.get("context_policy").is_none(),
2210 "context_policy key must be absent when None: {json}"
2211 );
2212 }
2213
2214 #[test]
2215 fn agent_meta_json_schema_exports_ctx_context_policy_and_meta_ref() {
2216 let schema = schemars::schema_for!(AgentMeta);
2217 let v = serde_json::to_value(&schema).expect("schema serializes");
2218 let props = v["properties"].as_object().expect("object schema");
2219 for key in [
2220 "description",
2221 "version",
2222 "tags",
2223 "ctx",
2224 "context_policy",
2225 "meta_ref",
2226 "projection_name",
2227 ] {
2228 assert!(props.contains_key(key), "missing property: {key}");
2229 }
2230 }
2231
2232 // ──────────────────────────────────────────────────────────────
2233 // issue #21 Phase 2: `MetaDef`, `Blueprint.metas`, `AgentMeta.meta_ref`
2234 // ──────────────────────────────────────────────────────────────
2235
2236 #[test]
2237 fn meta_def_roundtrips_through_json() {
2238 let def = MetaDef {
2239 name: "heavy-scan".to_string(),
2240 ctx: serde_json::json!({ "work_dir": "/x" }),
2241 };
2242 let json = serde_json::to_value(&def).expect("serializes");
2243 let back: MetaDef = serde_json::from_value(json).expect("deserializes");
2244 assert_eq!(back, def);
2245 }
2246
2247 #[test]
2248 fn blueprint_metas_omitted_when_empty() {
2249 let bp = minimal_bp(None);
2250 let json = serde_json::to_value(&bp).expect("serializes");
2251 assert!(
2252 json.as_object().unwrap().get("metas").is_none(),
2253 "metas key must be absent when empty: {json}"
2254 );
2255 let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2256 assert!(back.metas.is_empty());
2257 assert_eq!(bp, back);
2258 }
2259
2260 #[test]
2261 fn blueprint_metas_roundtrips_when_non_empty() {
2262 let mut bp = minimal_bp(None);
2263 bp.metas = vec![MetaDef {
2264 name: "heavy-scan".to_string(),
2265 ctx: serde_json::json!({ "work_dir": "/x" }),
2266 }];
2267 let json = serde_json::to_string(&bp).expect("serializes");
2268 let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2269 assert_eq!(bp, back);
2270 assert_eq!(back.metas.len(), 1);
2271 assert_eq!(back.metas[0].name, "heavy-scan");
2272 }
2273
2274 #[test]
2275 fn blueprint_json_schema_exports_metas() {
2276 let schema = schemars::schema_for!(Blueprint);
2277 let v = serde_json::to_value(&schema).expect("schema serializes");
2278 assert!(
2279 v["properties"]["metas"].is_object(),
2280 "metas must appear in the exported schema: {v}"
2281 );
2282 let dump = v.to_string();
2283 assert!(dump.contains("MetaDef"), "MetaDef definition in schema");
2284 }
2285
2286 #[test]
2287 fn agent_meta_meta_ref_roundtrips_when_some() {
2288 let meta = AgentMeta {
2289 meta_ref: Some("heavy-scan".to_string()),
2290 ..Default::default()
2291 };
2292 let json = serde_json::to_value(&meta).expect("serializes");
2293 assert_eq!(json["meta_ref"], "heavy-scan");
2294 let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
2295 assert_eq!(back, meta);
2296 }
2297
2298 #[test]
2299 fn agent_meta_meta_ref_omitted_when_none() {
2300 let meta = AgentMeta::default();
2301 let json = serde_json::to_value(&meta).expect("serializes");
2302 assert!(
2303 json.as_object().unwrap().get("meta_ref").is_none(),
2304 "meta_ref key must be absent when None: {json}"
2305 );
2306 let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
2307 assert_eq!(back.meta_ref, None);
2308 }
2309
2310 // ──────────────────────────────────────────────────────────────
2311 // GH #23: `AgentMeta.projection_name`
2312 // ──────────────────────────────────────────────────────────────
2313
2314 #[test]
2315 fn agent_meta_projection_name_roundtrips_when_some() {
2316 let meta = AgentMeta {
2317 projection_name: Some("plan".to_string()),
2318 ..Default::default()
2319 };
2320 let json = serde_json::to_value(&meta).expect("serializes");
2321 assert_eq!(json["projection_name"], "plan");
2322 let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
2323 assert_eq!(back, meta);
2324 }
2325
2326 #[test]
2327 fn agent_meta_projection_name_omitted_when_none() {
2328 let meta = AgentMeta::default();
2329 let json = serde_json::to_value(&meta).expect("serializes");
2330 assert!(
2331 json.as_object().unwrap().get("projection_name").is_none(),
2332 "projection_name key must be absent when None: {json}"
2333 );
2334 let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
2335 assert_eq!(back.projection_name, None);
2336 assert_eq!(back, meta);
2337 }
2338
2339 #[test]
2340 fn agent_meta_rejects_unknown_field_with_projection_name_present() {
2341 // `deny_unknown_fields` must still reject an unrelated stray key
2342 // even when `projection_name` is present alongside it (regression
2343 // guard: adding the field must not accidentally loosen the
2344 // contract for the rest of the struct).
2345 let json = serde_json::json!({
2346 "projection_name": "plan",
2347 "not_a_real_field": true
2348 });
2349 let err = serde_json::from_value::<AgentMeta>(json).unwrap_err();
2350 assert!(
2351 err.to_string().contains("not_a_real_field")
2352 || err.to_string().contains("unknown field"),
2353 "expected an unknown-field rejection, got: {err}"
2354 );
2355 }
2356
2357 #[test]
2358 fn context_policy_default_allows_everything() {
2359 let policy = ContextPolicy::default();
2360 assert!(policy.allows("project_root"));
2361 assert!(policy.allows("anything"));
2362 }
2363
2364 #[test]
2365 fn context_policy_include_only_allows_listed_names() {
2366 let policy = ContextPolicy {
2367 include: Some(vec!["project_root".to_string()]),
2368 exclude: vec![],
2369 ..Default::default()
2370 };
2371 assert!(policy.allows("project_root"));
2372 assert!(!policy.allows("work_dir"));
2373 }
2374
2375 #[test]
2376 fn context_policy_exclude_wins_over_include() {
2377 let policy = ContextPolicy {
2378 include: Some(vec!["project_root".to_string()]),
2379 exclude: vec!["project_root".to_string()],
2380 ..Default::default()
2381 };
2382 assert!(!policy.allows("project_root"));
2383 }
2384
2385 #[test]
2386 fn context_policy_roundtrips_through_json() {
2387 let policy = ContextPolicy {
2388 include: Some(vec!["a".to_string(), "b".to_string()]),
2389 exclude: vec!["c".to_string()],
2390 ..Default::default()
2391 };
2392 let json = serde_json::to_value(&policy).expect("serializes");
2393 let back: ContextPolicy = serde_json::from_value(json).expect("deserializes");
2394 assert_eq!(back, policy);
2395 }
2396
2397 #[test]
2398 fn context_policy_default_roundtrips_as_empty_object() {
2399 let policy = ContextPolicy::default();
2400 let json = serde_json::to_value(&policy).expect("serializes");
2401 assert_eq!(
2402 json,
2403 serde_json::json!({
2404 "include": null,
2405 "exclude": [],
2406 "steps": null,
2407 "steps_exclude": [],
2408 })
2409 );
2410 let back: ContextPolicy = serde_json::from_value(json).expect("deserializes");
2411 assert_eq!(back, policy);
2412 }
2413
2414 // ──────────────────────────────────────────────────────────────
2415 // ST5 (`projection-adapter`): `ContextPolicy.steps` / `steps_exclude`
2416 // ──────────────────────────────────────────────────────────────
2417
2418 #[test]
2419 fn context_policy_steps_default_allows_every_step() {
2420 let policy = ContextPolicy::default();
2421 assert!(policy.allows_step("planner"));
2422 assert!(policy.allows_step("anything"));
2423 }
2424
2425 #[test]
2426 fn context_policy_steps_include_only_allows_listed_names() {
2427 let policy = ContextPolicy {
2428 steps: Some(vec!["planner".to_string()]),
2429 ..Default::default()
2430 };
2431 assert!(policy.allows_step("planner"));
2432 assert!(!policy.allows_step("coder"));
2433 }
2434
2435 #[test]
2436 fn context_policy_steps_empty_list_allows_none() {
2437 let policy = ContextPolicy {
2438 steps: Some(vec![]),
2439 ..Default::default()
2440 };
2441 assert!(!policy.allows_step("planner"));
2442 }
2443
2444 #[test]
2445 fn context_policy_steps_exclude_wins_over_steps() {
2446 let policy = ContextPolicy {
2447 steps: Some(vec!["planner".to_string()]),
2448 steps_exclude: vec!["planner".to_string()],
2449 ..Default::default()
2450 };
2451 assert!(!policy.allows_step("planner"));
2452 }
2453
2454 #[test]
2455 fn context_policy_steps_roundtrips_through_json() {
2456 let policy = ContextPolicy {
2457 steps: Some(vec!["planner".to_string(), "coder".to_string()]),
2458 steps_exclude: vec!["reviewer".to_string()],
2459 ..Default::default()
2460 };
2461 let json = serde_json::to_value(&policy).expect("serializes");
2462 let back: ContextPolicy = serde_json::from_value(json).expect("deserializes");
2463 assert_eq!(back, policy);
2464 }
2465
2466 // ──────────────────────────────────────────────────────────────
2467 // GH #34: `AuditDef`, `AuditMode`, `Blueprint.audits`
2468 // ──────────────────────────────────────────────────────────────
2469
2470 #[test]
2471 fn blueprint_audits_omitted_when_empty() {
2472 let bp = minimal_bp(None);
2473 let json = serde_json::to_value(&bp).expect("serializes");
2474 assert!(
2475 json.as_object().unwrap().get("audits").is_none(),
2476 "audits key must be absent when empty: {json}"
2477 );
2478 let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2479 assert!(back.audits.is_empty());
2480 assert_eq!(bp, back);
2481 }
2482
2483 #[test]
2484 fn blueprint_audits_roundtrips_when_non_empty() {
2485 let mut bp = minimal_bp(None);
2486 bp.audits = vec![AuditDef {
2487 agent: "auditor".to_string(),
2488 steps: Some(vec!["worker".to_string()]),
2489 mode: AuditMode::Sync,
2490 }];
2491 let json = serde_json::to_string(&bp).expect("serializes");
2492 let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2493 assert_eq!(bp, back);
2494 assert_eq!(back.audits.len(), 1);
2495 assert_eq!(back.audits[0].agent, "auditor");
2496 assert_eq!(back.audits[0].mode, AuditMode::Sync);
2497 }
2498
2499 #[test]
2500 fn audit_def_steps_none_and_mode_default_when_omitted() {
2501 let json = serde_json::json!({ "agent": "auditor" });
2502 let def: AuditDef = serde_json::from_value(json).expect("deserializes");
2503 assert_eq!(def.steps, None);
2504 assert_eq!(def.mode, AuditMode::Async);
2505 }
2506
2507 #[test]
2508 fn audit_def_rejects_unknown_field() {
2509 let json = serde_json::json!({ "agent": "auditor", "not_a_real_field": true });
2510 let err = serde_json::from_value::<AuditDef>(json).unwrap_err();
2511 assert!(
2512 err.to_string().contains("not_a_real_field")
2513 || err.to_string().contains("unknown field"),
2514 "expected an unknown-field rejection, got: {err}"
2515 );
2516 }
2517
2518 #[test]
2519 fn audit_mode_serializes_snake_case() {
2520 assert_eq!(
2521 serde_json::to_value(AuditMode::Async).unwrap(),
2522 serde_json::json!("async")
2523 );
2524 assert_eq!(
2525 serde_json::to_value(AuditMode::Sync).unwrap(),
2526 serde_json::json!("sync")
2527 );
2528 }
2529
2530 #[test]
2531 fn blueprint_json_schema_exports_audits_and_audit_def() {
2532 let schema = schemars::schema_for!(Blueprint);
2533 let v = serde_json::to_value(&schema).expect("schema serializes");
2534 assert!(
2535 v["properties"]["audits"].is_object(),
2536 "audits must appear in the exported schema: {v}"
2537 );
2538 let dump = v.to_string();
2539 assert!(dump.contains("AuditDef"), "AuditDef definition in schema");
2540 }
2541
2542 // ──────────────────────────────────────────────────────────────
2543 // GH #32: `Blueprint.degradation_policy`, `DegradationPolicy`
2544 // ──────────────────────────────────────────────────────────────
2545
2546 #[test]
2547 fn blueprint_without_degradation_policy_deserializes_to_none() {
2548 let json = serde_json::json!({
2549 "schema_version": current_schema_version(),
2550 "id": "no-degradation-policy-ut",
2551 "flow": { "kind": "seq", "children": [] },
2552 });
2553 let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
2554 assert_eq!(bp.degradation_policy, None);
2555 }
2556
2557 #[test]
2558 fn blueprint_degradation_policy_omitted_when_none() {
2559 let bp = minimal_bp(None);
2560 let json = serde_json::to_value(&bp).expect("serializes");
2561 assert!(
2562 json.as_object()
2563 .unwrap()
2564 .get("degradation_policy")
2565 .is_none(),
2566 "degradation_policy key must be absent when None: {json}"
2567 );
2568 }
2569
2570 #[test]
2571 fn blueprint_degradation_policy_warn_and_fail_roundtrip() {
2572 for (label, expected) in [
2573 ("warn", DegradationPolicy::Warn),
2574 ("fail", DegradationPolicy::Fail),
2575 ] {
2576 let mut bp = minimal_bp(None);
2577 bp.degradation_policy = Some(expected);
2578 let json = serde_json::to_string(&bp).expect("serializes");
2579 assert!(json.contains(&format!("\"degradation_policy\":\"{label}\"")));
2580 let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2581 assert_eq!(back.degradation_policy, Some(expected));
2582 }
2583 }
2584
2585 #[test]
2586 fn degradation_policy_rejects_unknown_variant() {
2587 let json = serde_json::json!({
2588 "schema_version": current_schema_version(),
2589 "id": "degradation-policy-unknown-variant-ut",
2590 "flow": { "kind": "seq", "children": [] },
2591 "degradation_policy": "ignore",
2592 });
2593 let err = serde_json::from_value::<Blueprint>(json).unwrap_err();
2594 assert!(
2595 err.to_string().contains("unknown variant"),
2596 "expected an unknown-variant rejection, got: {err}"
2597 );
2598 }
2599
2600 // ──────────────────────────────────────────────────────────────
2601 // GH #46 Milestone 2: `Runner`, `RunnerDef`, `WorkerModel`,
2602 // `Blueprint.runners` / `default_runner`, `AgentDef.runner` /
2603 // `runner_ref`, `resolve_runner`
2604 // ──────────────────────────────────────────────────────────────
2605
2606 fn agent_with_runner(
2607 name: &str,
2608 profile: Option<AgentProfile>,
2609 runner: Option<Runner>,
2610 runner_ref: Option<String>,
2611 ) -> AgentDef {
2612 AgentDef {
2613 name: name.to_string(),
2614 kind: AgentKind::RustFn,
2615 spec: serde_json::json!({ "fn_id": name }),
2616 profile,
2617 meta: None,
2618 runner,
2619 runner_ref,
2620 verdict: None,
2621 }
2622 }
2623
2624 fn ws_runner(variant: &str, tools: Vec<&str>) -> Runner {
2625 Runner::WsClaudeCode {
2626 variant: variant.to_string(),
2627 tools: tools.into_iter().map(str::to_string).collect(),
2628 }
2629 }
2630
2631 fn agent_block_runner(tools: Vec<&str>) -> Runner {
2632 Runner::AgentBlockInProcess {
2633 tools: tools.into_iter().map(str::to_string).collect(),
2634 }
2635 }
2636
2637 // ─── round-trip byte-compat ─────────────────────────────────────
2638
2639 #[test]
2640 fn blueprint_without_runners_or_default_runner_deserializes_to_defaults() {
2641 let json = serde_json::json!({
2642 "schema_version": current_schema_version(),
2643 "id": "no-runners-ut",
2644 "flow": { "kind": "seq", "children": [] },
2645 });
2646 let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
2647 assert!(bp.runners.is_empty());
2648 assert_eq!(bp.default_runner, None);
2649 }
2650
2651 #[test]
2652 fn blueprint_runners_omitted_when_empty() {
2653 let bp = minimal_bp(None);
2654 let json = serde_json::to_value(&bp).expect("serializes");
2655 assert!(
2656 json.as_object().unwrap().get("runners").is_none(),
2657 "runners key must be absent when empty: {json}"
2658 );
2659 let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2660 assert!(back.runners.is_empty());
2661 assert_eq!(bp, back);
2662 }
2663
2664 #[test]
2665 fn blueprint_runners_roundtrips_when_non_empty() {
2666 let mut bp = minimal_bp(None);
2667 bp.runners = vec![RunnerDef {
2668 name: "claude-worker".to_string(),
2669 runner: ws_runner("mse-worker-coder", vec!["Read", "Grep"]),
2670 }];
2671 let json = serde_json::to_string(&bp).expect("serializes");
2672 let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2673 assert_eq!(bp, back);
2674 assert_eq!(back.runners.len(), 1);
2675 assert_eq!(back.runners[0].name, "claude-worker");
2676 }
2677
2678 #[test]
2679 fn blueprint_default_runner_roundtrips_when_some() {
2680 let mut bp = minimal_bp(None);
2681 bp.default_runner = Some("claude-worker".to_string());
2682 let json = serde_json::to_value(&bp).expect("serializes");
2683 assert_eq!(json["default_runner"], "claude-worker");
2684 let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2685 assert_eq!(back, bp);
2686 }
2687
2688 #[test]
2689 fn blueprint_default_runner_omitted_when_none() {
2690 let bp = minimal_bp(None);
2691 let json = serde_json::to_value(&bp).expect("serializes");
2692 assert!(
2693 json.as_object().unwrap().get("default_runner").is_none(),
2694 "default_runner key must be absent when None: {json}"
2695 );
2696 let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2697 assert_eq!(back, bp);
2698 }
2699
2700 #[test]
2701 fn blueprint_json_schema_exports_runners_and_default_runner() {
2702 let schema = schemars::schema_for!(Blueprint);
2703 let v = serde_json::to_value(&schema).expect("schema serializes");
2704 assert!(
2705 v["properties"]["runners"].is_object(),
2706 "runners must appear in the exported schema: {v}"
2707 );
2708 assert!(
2709 v["properties"]["default_runner"].is_object(),
2710 "default_runner must appear in the exported schema: {v}"
2711 );
2712 let dump = v.to_string();
2713 assert!(dump.contains("RunnerDef"), "RunnerDef definition in schema");
2714 assert!(dump.contains("Runner"), "Runner definition in schema");
2715 }
2716
2717 #[test]
2718 fn agent_def_runner_and_runner_ref_omitted_when_none() {
2719 let agent = agent_with_runner("scout", None, None, None);
2720 let json = serde_json::to_value(&agent).expect("serializes");
2721 let obj = json.as_object().unwrap();
2722 assert!(
2723 obj.get("runner").is_none(),
2724 "runner key must be absent when None: {json}"
2725 );
2726 assert!(
2727 obj.get("runner_ref").is_none(),
2728 "runner_ref key must be absent when None: {json}"
2729 );
2730 let back: AgentDef = serde_json::from_value(json).expect("deserializes");
2731 assert_eq!(back, agent);
2732 }
2733
2734 #[test]
2735 fn agent_def_runner_inline_roundtrips_when_some() {
2736 let agent = agent_with_runner("coder", None, Some(agent_block_runner(vec!["Bash"])), None);
2737 let json = serde_json::to_string(&agent).expect("serializes");
2738 let back: AgentDef = serde_json::from_str(&json).expect("deserializes");
2739 assert_eq!(back, agent);
2740 }
2741
2742 #[test]
2743 fn agent_def_runner_ref_roundtrips_when_some() {
2744 let agent = agent_with_runner("coder", None, None, Some("claude-worker".to_string()));
2745 let json = serde_json::to_value(&agent).expect("serializes");
2746 assert_eq!(json["runner_ref"], "claude-worker");
2747 let back: AgentDef = serde_json::from_value(json).expect("deserializes");
2748 assert_eq!(back, agent);
2749 }
2750
2751 #[test]
2752 fn agent_def_json_schema_exports_runner_and_runner_ref() {
2753 let schema = schemars::schema_for!(AgentDef);
2754 let v = serde_json::to_value(&schema).expect("schema serializes");
2755 let props = v["properties"].as_object().expect("object schema");
2756 for key in ["runner", "runner_ref"] {
2757 assert!(props.contains_key(key), "missing property: {key}");
2758 }
2759 }
2760
2761 #[test]
2762 fn runner_ws_claude_code_roundtrips_through_json_and_tags_backend() {
2763 let runner = ws_runner("mse-worker-coder", vec!["Read", "Grep"]);
2764 let json = serde_json::to_value(&runner).expect("serializes");
2765 assert_eq!(json["backend"], "ws_claude_code");
2766 assert_eq!(json["variant"], "mse-worker-coder");
2767 assert_eq!(json["tools"], serde_json::json!(["Read", "Grep"]));
2768 let back: Runner = serde_json::from_value(json).expect("deserializes");
2769 assert_eq!(back, runner);
2770 }
2771
2772 #[test]
2773 fn runner_ws_operator_roundtrips_through_json_and_tags_backend() {
2774 let runner = Runner::WsOperator {
2775 variant: "mse-worker-reviewer".to_string(),
2776 tools: vec!["Read".to_string(), "Grep".to_string()],
2777 };
2778 let json = serde_json::to_value(&runner).expect("serializes");
2779 assert_eq!(json["backend"], "ws_operator");
2780 assert_eq!(json["variant"], "mse-worker-reviewer");
2781 assert_eq!(json["tools"], serde_json::json!(["Read", "Grep"]));
2782 let back: Runner = serde_json::from_value(json).expect("deserializes");
2783 assert_eq!(back, runner);
2784 }
2785
2786 #[test]
2787 fn runner_agent_block_in_process_roundtrips_through_json_and_tags_backend() {
2788 let runner = agent_block_runner(vec!["Bash"]);
2789 let json = serde_json::to_value(&runner).expect("serializes");
2790 assert_eq!(json["backend"], "agent_block_in_process");
2791 assert_eq!(json["tools"], serde_json::json!(["Bash"]));
2792 let back: Runner = serde_json::from_value(json).expect("deserializes");
2793 assert_eq!(back, runner);
2794 }
2795
2796 #[test]
2797 fn runner_tools_omitted_when_empty() {
2798 let runner = ws_runner("mse-worker-coder", vec![]);
2799 let json = serde_json::to_value(&runner).expect("serializes");
2800 assert!(
2801 json.as_object().unwrap().get("tools").is_none(),
2802 "tools key must be absent when empty: {json}"
2803 );
2804 let back: Runner = serde_json::from_value(json).expect("deserializes");
2805 assert_eq!(back, runner);
2806 }
2807
2808 #[test]
2809 fn runner_rejects_unknown_field() {
2810 let json = serde_json::json!({
2811 "backend": "ws_claude_code",
2812 "variant": "x",
2813 "not_a_real_field": true,
2814 });
2815 let err = serde_json::from_value::<Runner>(json).unwrap_err();
2816 assert!(
2817 err.to_string().contains("not_a_real_field")
2818 || err.to_string().contains("unknown field"),
2819 "expected an unknown-field rejection, got: {err}"
2820 );
2821 }
2822
2823 #[test]
2824 fn runner_def_roundtrips_through_json() {
2825 let def = RunnerDef {
2826 name: "claude-worker".to_string(),
2827 runner: ws_runner("mse-worker-coder", vec!["Read"]),
2828 };
2829 let json = serde_json::to_value(&def).expect("serializes");
2830 let back: RunnerDef = serde_json::from_value(json).expect("deserializes");
2831 assert_eq!(back, def);
2832 }
2833
2834 // ─── GH #83: SubprocessDef / Runner::Subprocess ────────────────
2835
2836 fn sample_subprocess_def(name: &str) -> SubprocessDef {
2837 SubprocessDef {
2838 name: name.to_string(),
2839 argv: vec![
2840 "sh".to_string(),
2841 "-c".to_string(),
2842 "echo '{\"result\": \"ok\"}'".to_string(),
2843 ],
2844 stdin: Some("{prompt}".to_string()),
2845 env: std::collections::BTreeMap::from([("EXTRA".to_string(), "{task_id}".to_string())]),
2846 cwd: Some("{work_dir}".to_string()),
2847 output: Some(SubprocessOutput {
2848 format: Some("json".to_string()),
2849 result_ptr: Some("/result".to_string()),
2850 ok_from: Some("exit_code".to_string()),
2851 }),
2852 stream_mode: None,
2853 }
2854 }
2855
2856 #[test]
2857 fn subprocess_def_roundtrips_through_json() {
2858 let def = sample_subprocess_def("echo-json");
2859 let json = serde_json::to_value(&def).expect("serializes");
2860 let back: SubprocessDef = serde_json::from_value(json).expect("deserializes");
2861 assert_eq!(back, def);
2862 }
2863
2864 #[test]
2865 fn subprocess_def_optional_fields_omitted_when_default() {
2866 let def = SubprocessDef {
2867 name: "min".to_string(),
2868 argv: vec!["cat".to_string()],
2869 stdin: None,
2870 env: Default::default(),
2871 cwd: None,
2872 output: None,
2873 stream_mode: None,
2874 };
2875 let json = serde_json::to_value(&def).expect("serializes");
2876 let obj = json.as_object().unwrap();
2877 for absent in ["stdin", "env", "cwd", "output", "stream_mode"] {
2878 assert!(
2879 !obj.contains_key(absent),
2880 "{absent} key must be absent when default: {json}"
2881 );
2882 }
2883 let back: SubprocessDef = serde_json::from_value(json).expect("deserializes");
2884 assert_eq!(back, def);
2885 }
2886
2887 #[test]
2888 fn subprocess_def_rejects_unknown_field() {
2889 let json = serde_json::json!({
2890 "name": "x",
2891 "argv": ["cat"],
2892 "not_a_real_field": true,
2893 });
2894 let err = serde_json::from_value::<SubprocessDef>(json).unwrap_err();
2895 assert!(
2896 err.to_string().contains("unknown field"),
2897 "expected an unknown-field rejection, got: {err}"
2898 );
2899 }
2900
2901 #[test]
2902 fn blueprint_subprocesses_defaults_to_empty_and_stays_off_the_wire() {
2903 // Pre-#83 BP JSON (no `subprocesses` key) deserializes to an empty registry.
2904 let bp = minimal_bp(None);
2905 let json = serde_json::to_value(&bp).expect("serializes");
2906 assert!(
2907 json.as_object().unwrap().get("subprocesses").is_none(),
2908 "subprocesses key must be absent when empty: {json}"
2909 );
2910 let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2911 assert!(back.subprocesses.is_empty());
2912 }
2913
2914 #[test]
2915 fn blueprint_subprocesses_roundtrips_when_declared() {
2916 let mut bp = minimal_bp(None);
2917 bp.subprocesses = vec![sample_subprocess_def("echo-json")];
2918 let json = serde_json::to_value(&bp).expect("serializes");
2919 assert_eq!(json["subprocesses"][0]["name"], "echo-json");
2920 let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2921 assert_eq!(back.subprocesses, bp.subprocesses);
2922 }
2923
2924 #[test]
2925 fn runner_subprocess_roundtrips_through_json_and_tags_backend() {
2926 // 1:1 name symmetry with AgentKind::Subprocess — tag must be "subprocess".
2927 let runner = Runner::Subprocess {
2928 template: "echo-json".to_string(),
2929 overrides: SubprocessOverrides {
2930 model: Some("small".to_string()),
2931 tools: vec!["Read".to_string()],
2932 cwd: Some("/tmp/wd".to_string()),
2933 },
2934 };
2935 let json = serde_json::to_value(&runner).expect("serializes");
2936 assert_eq!(json["backend"], "subprocess");
2937 assert_eq!(json["template"], "echo-json");
2938 assert_eq!(json["overrides"]["model"], "small");
2939 let back: Runner = serde_json::from_value(json).expect("deserializes");
2940 assert_eq!(back, runner);
2941 }
2942
2943 #[test]
2944 fn runner_subprocess_overrides_omitted_when_empty() {
2945 let runner = Runner::Subprocess {
2946 template: "echo-json".to_string(),
2947 overrides: SubprocessOverrides::default(),
2948 };
2949 let json = serde_json::to_value(&runner).expect("serializes");
2950 assert!(
2951 json.as_object().unwrap().get("overrides").is_none(),
2952 "overrides key must be absent when all-default: {json}"
2953 );
2954 let back: Runner = serde_json::from_value(json).expect("deserializes");
2955 assert_eq!(back, runner);
2956 }
2957
2958 #[test]
2959 fn resolve_runner_inline_subprocess_variant_resolves() {
2960 let inline = Runner::Subprocess {
2961 template: "echo-json".to_string(),
2962 overrides: SubprocessOverrides::default(),
2963 };
2964 let agent = agent_with_runner("headless", None, Some(inline.clone()), None);
2965 let mut bp = minimal_bp(None);
2966 bp.agents = vec![agent.clone()];
2967
2968 let resolved = resolve_runner(&bp, &agent).expect("resolves");
2969 assert_eq!(resolved, Some(inline));
2970 }
2971
2972 #[test]
2973 fn resolve_runner_registry_and_default_tiers_resolve_subprocess_variant() {
2974 let registry_runner = Runner::Subprocess {
2975 template: "echo-json".to_string(),
2976 overrides: SubprocessOverrides::default(),
2977 };
2978 // Tier 2: runner_ref → registry.
2979 let agent = agent_with_runner("headless", None, None, Some("proc-entry".to_string()));
2980 let mut bp = minimal_bp(None);
2981 bp.runners = vec![RunnerDef {
2982 name: "proc-entry".to_string(),
2983 runner: registry_runner.clone(),
2984 }];
2985 bp.agents = vec![agent.clone()];
2986 let resolved = resolve_runner(&bp, &agent).expect("resolves");
2987 assert_eq!(resolved, Some(registry_runner.clone()));
2988
2989 // Tier 4: default_runner alone.
2990 let bare = agent_with_runner("headless", None, None, None);
2991 bp.agents = vec![bare.clone()];
2992 bp.default_runner = Some("proc-entry".to_string());
2993 let resolved = resolve_runner(&bp, &bare).expect("resolves");
2994 assert_eq!(resolved, Some(registry_runner));
2995 }
2996
2997 #[test]
2998 fn bind_outcome_bound_roundtrips_through_json_and_tags_outcome() {
2999 let outcome = BindOutcome::Bound {
3000 receipt: BindReceipt {
3001 agent: "coder".to_string(),
3002 request_digest: BindingDigest::sha256("req"),
3003 provider_id: "mse-provider".to_string(),
3004 provider_revision: Some("1".to_string()),
3005 resolved_model: Some("claude-sonnet-4".to_string()),
3006 effective_tools: vec!["Read".to_string(), "Write".to_string()],
3007 launch_variant: Some("mse-coder".to_string()),
3008 capability_snapshot_digest: None,
3009 },
3010 };
3011 let json = serde_json::to_value(&outcome).expect("serializes");
3012 assert_eq!(json["outcome"], "bound");
3013 assert_eq!(json["receipt"]["agent"], "coder");
3014 let back: BindOutcome = serde_json::from_value(json).expect("deserializes");
3015 assert_eq!(back, outcome);
3016 }
3017
3018 #[test]
3019 fn bind_outcome_unbound_roundtrips_through_json_and_tags_outcome() {
3020 let outcome = BindOutcome::Unbound {
3021 agent: "coder".to_string(),
3022 reason: "no capability for launch variant".to_string(),
3023 };
3024 let json = serde_json::to_value(&outcome).expect("serializes");
3025 assert_eq!(json["outcome"], "unbound");
3026 assert_eq!(json["agent"], "coder");
3027 assert_eq!(json["reason"], "no capability for launch variant");
3028 let back: BindOutcome = serde_json::from_value(json).expect("deserializes");
3029 assert_eq!(back, outcome);
3030 }
3031
3032 #[test]
3033 fn bind_outcome_rejects_unknown_field() {
3034 let json = serde_json::json!({
3035 "outcome": "unbound",
3036 "agent": "coder",
3037 "reason": "gone",
3038 "not_a_real_field": true,
3039 });
3040 let err = serde_json::from_value::<BindOutcome>(json).unwrap_err();
3041 assert!(
3042 err.to_string().contains("not_a_real_field")
3043 || err.to_string().contains("unknown field"),
3044 "expected an unknown-field rejection, got: {err}"
3045 );
3046 }
3047
3048 #[test]
3049 fn compiler_strategy_strict_binding_defaults_false_and_omitted() {
3050 let strategy = CompilerStrategy::default();
3051 assert!(!strategy.strict_binding);
3052 // Absent in JSON deserializes back to false.
3053 let back: CompilerStrategy = serde_json::from_value(serde_json::json!({
3054 "strict_refs": true,
3055 "strict_kind": true,
3056 }))
3057 .expect("deserializes without strict_binding");
3058 assert!(!back.strict_binding);
3059 }
3060
3061 #[test]
3062 fn worker_model_roundtrips_through_json() {
3063 let model = WorkerModel {
3064 runner: agent_block_runner(vec!["Bash"]),
3065 agent: agent_with_runner("coder", None, None, None),
3066 };
3067 let json = serde_json::to_value(&model).expect("serializes");
3068 let back: WorkerModel = serde_json::from_value(json).expect("deserializes");
3069 assert_eq!(back, model);
3070 }
3071
3072 // ─── resolve_runner cascade precedence ─────────────────────────
3073
3074 #[test]
3075 fn resolve_runner_inline_wins_over_everything() {
3076 let inline = agent_block_runner(vec!["Bash"]);
3077 let profile = AgentProfile {
3078 worker_binding: Some("legacy-variant".to_string()),
3079 tools: vec!["Read".to_string()],
3080 ..Default::default()
3081 };
3082 let agent = agent_with_runner(
3083 "coder",
3084 Some(profile),
3085 Some(inline.clone()),
3086 Some("registry-entry".to_string()),
3087 );
3088 let mut bp = minimal_bp(None);
3089 bp.default_runner = Some("registry-entry".to_string());
3090 bp.runners = vec![RunnerDef {
3091 name: "registry-entry".to_string(),
3092 runner: ws_runner("other-variant", vec![]),
3093 }];
3094 bp.agents = vec![agent.clone()];
3095
3096 let resolved = resolve_runner(&bp, &agent).expect("resolves");
3097 assert_eq!(resolved, Some(inline));
3098 }
3099
3100 #[test]
3101 fn resolve_runner_runner_ref_wins_over_legacy_fallback() {
3102 let profile = AgentProfile {
3103 worker_binding: Some("legacy-variant".to_string()),
3104 tools: vec!["Read".to_string()],
3105 ..Default::default()
3106 };
3107 let registry_runner = ws_runner("registry-variant", vec!["Grep"]);
3108 let agent = agent_with_runner(
3109 "coder",
3110 Some(profile),
3111 None,
3112 Some("registry-entry".to_string()),
3113 );
3114 let mut bp = minimal_bp(None);
3115 bp.runners = vec![RunnerDef {
3116 name: "registry-entry".to_string(),
3117 runner: registry_runner.clone(),
3118 }];
3119 bp.agents = vec![agent.clone()];
3120
3121 let resolved = resolve_runner(&bp, &agent).expect("resolves");
3122 assert_eq!(resolved, Some(registry_runner));
3123 }
3124
3125 #[test]
3126 fn resolve_runner_legacy_fallback_wins_over_default_runner() {
3127 let profile = AgentProfile {
3128 worker_binding: Some("legacy-variant".to_string()),
3129 tools: vec!["Read".to_string(), "Grep".to_string()],
3130 ..Default::default()
3131 };
3132 let agent = agent_with_runner("coder", Some(profile), None, None);
3133 let mut bp = minimal_bp(None);
3134 bp.default_runner = Some("registry-entry".to_string());
3135 bp.runners = vec![RunnerDef {
3136 name: "registry-entry".to_string(),
3137 runner: agent_block_runner(vec!["Bash"]),
3138 }];
3139 bp.agents = vec![agent.clone()];
3140
3141 let resolved = resolve_runner(&bp, &agent).expect("resolves");
3142 assert_eq!(
3143 resolved,
3144 Some(ws_runner("legacy-variant", vec!["Read", "Grep"]))
3145 );
3146 }
3147
3148 #[test]
3149 fn resolve_runner_default_runner_alone_when_no_agent_level_declaration() {
3150 let agent = agent_with_runner("coder", None, None, None);
3151 let mut bp = minimal_bp(None);
3152 bp.default_runner = Some("registry-entry".to_string());
3153 bp.runners = vec![RunnerDef {
3154 name: "registry-entry".to_string(),
3155 runner: agent_block_runner(vec!["Bash"]),
3156 }];
3157 bp.agents = vec![agent.clone()];
3158
3159 let resolved = resolve_runner(&bp, &agent).expect("resolves");
3160 assert_eq!(resolved, Some(agent_block_runner(vec!["Bash"])));
3161 }
3162
3163 #[test]
3164 fn resolve_runner_none_when_nothing_declared_through_any_tier() {
3165 let agent = agent_with_runner("coder", None, None, None);
3166 let bp = minimal_bp(None);
3167
3168 let resolved = resolve_runner(&bp, &agent).expect("resolves");
3169 assert_eq!(resolved, None);
3170 }
3171
3172 #[test]
3173 fn resolve_runner_unknown_runner_ref_errs() {
3174 let agent = agent_with_runner("coder", None, None, Some("no-such-entry".to_string()));
3175 let mut bp = minimal_bp(None);
3176 bp.runners = vec![RunnerDef {
3177 name: "registry-entry".to_string(),
3178 runner: agent_block_runner(vec![]),
3179 }];
3180 bp.agents = vec![agent.clone()];
3181
3182 let err = resolve_runner(&bp, &agent).expect_err("unresolved runner_ref");
3183 assert_eq!(
3184 err,
3185 RunnerResolveError::UnknownRunnerRef {
3186 agent: "coder".to_string(),
3187 ref_name: "no-such-entry".to_string(),
3188 available: vec!["registry-entry".to_string()],
3189 }
3190 );
3191 }
3192
3193 #[test]
3194 fn resolve_runner_unknown_default_runner_errs() {
3195 let agent = agent_with_runner("coder", None, None, None);
3196 let mut bp = minimal_bp(None);
3197 bp.default_runner = Some("no-such-entry".to_string());
3198 bp.runners = vec![RunnerDef {
3199 name: "registry-entry".to_string(),
3200 runner: agent_block_runner(vec![]),
3201 }];
3202 bp.agents = vec![agent.clone()];
3203
3204 let err = resolve_runner(&bp, &agent).expect_err("unresolved default_runner");
3205 assert_eq!(
3206 err,
3207 RunnerResolveError::UnknownDefaultRunner {
3208 ref_name: "no-such-entry".to_string(),
3209 available: vec!["registry-entry".to_string()],
3210 }
3211 );
3212 }
3213
3214 #[test]
3215 fn bound_agent_digest_is_stable_and_tracks_runner_changes() {
3216 let agent = agent_with_runner(
3217 "coder",
3218 None,
3219 Some(ws_runner("worker-a", vec!["Read"])),
3220 None,
3221 );
3222 let mut bp = minimal_bp(None);
3223 bp.agents = vec![agent];
3224
3225 let first = resolve_bound_agents(&bp).expect("binds");
3226 let second = resolve_bound_agents(&bp).expect("binds again");
3227 assert_eq!(first[0].binding_digest, second[0].binding_digest);
3228 assert!(first[0].binding_digest.as_str().starts_with("sha256:"));
3229 assert_eq!(first[0].binding_digest.as_str().len(), 71);
3230 assert_eq!(first[0].runner_source, RunnerResolutionSource::AgentInline);
3231
3232 bp.agents[0].runner = Some(ws_runner("worker-b", vec!["Read"]));
3233 let changed = resolve_bound_agents(&bp).expect("binds changed runner");
3234 assert_ne!(first[0].binding_digest, changed[0].binding_digest);
3235 }
3236
3237 #[test]
3238 fn bound_agent_pins_effective_context_policy_and_full_agent() {
3239 let mut agent = agent_with_runner("scout", None, None, None);
3240 agent.profile = Some(AgentProfile {
3241 system_prompt: "inspect carefully".to_string(),
3242 ..Default::default()
3243 });
3244 let mut bp = minimal_bp(None);
3245 bp.default_context_policy = Some(ContextPolicy {
3246 include: Some(vec!["task".to_string()]),
3247 ..Default::default()
3248 });
3249 bp.agents = vec![agent];
3250
3251 let bound = resolve_bound_agents(&bp).expect("binds").remove(0);
3252 assert_eq!(
3253 bound.agent.profile.unwrap().system_prompt,
3254 "inspect carefully"
3255 );
3256 assert_eq!(
3257 bound.context_policy.unwrap().include,
3258 Some(vec!["task".to_string()])
3259 );
3260 assert_eq!(bound.runner_source, RunnerResolutionSource::None);
3261 }
3262
3263 #[test]
3264 fn strict_bound_agent_resolution_rejects_legacy_worker_binding() {
3265 let profile = AgentProfile {
3266 worker_binding: Some("legacy-worker".to_string()),
3267 ..Default::default()
3268 };
3269 let mut bp = minimal_bp(None);
3270 bp.agents = vec![agent_with_runner("coder", Some(profile), None, None)];
3271
3272 let err = resolve_bound_agents_strict(&bp).expect_err("legacy must fail closed");
3273 assert!(matches!(
3274 err,
3275 BoundAgentResolveError::LegacyWorkerBindingDisabled { agent } if agent == "coder"
3276 ));
3277 }
3278
3279 #[test]
3280 fn binding_digest_is_a_validated_transparent_string() {
3281 use std::str::FromStr as _;
3282
3283 let digest = BindingDigest::sha256(b"same snapshot");
3284 let json = serde_json::to_value(&digest).expect("serializes");
3285 assert_eq!(json, serde_json::Value::String(digest.to_string()));
3286 assert_eq!(
3287 serde_json::from_value::<BindingDigest>(json).expect("deserializes"),
3288 digest
3289 );
3290 for invalid in [
3291 "deadbeef",
3292 "sha256:abc",
3293 "sha256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
3294 "blake3:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
3295 ] {
3296 assert!(
3297 BindingDigest::from_str(invalid).is_err(),
3298 "accepted {invalid}"
3299 );
3300 }
3301 }
3302
3303 #[test]
3304 fn capability_snapshot_digest_accepts_the_legacy_wire_name() {
3305 let digest = BindingDigest::sha256("capabilities");
3306 let capability: AgentProviderCapability = serde_json::from_value(serde_json::json!({
3307 "launch_variant": "coder",
3308 "effective_tools": ["Read"],
3309 "evidence_digest": digest,
3310 }))
3311 .expect("legacy manifest remains readable");
3312 assert_eq!(capability.capability_snapshot_digest, Some(digest.clone()));
3313
3314 let serialized = serde_json::to_value(capability).expect("serialize new wire shape");
3315 assert_eq!(serialized["capability_snapshot_digest"], digest.to_string());
3316 assert!(serialized.get("evidence_digest").is_none());
3317 }
3318
3319 // ──────────────────────────────────────────────────────────────
3320 // GH #50: `AgentDef.verdict` / `VerdictContract` / `VerdictChannel`
3321 // ──────────────────────────────────────────────────────────────
3322
3323 #[test]
3324 fn verdict_contract_roundtrips_body_channel() {
3325 let json = serde_json::json!({"channel": "body", "values": ["PASS", "BLOCKED"]});
3326 let contract: VerdictContract = serde_json::from_value(json.clone()).expect("deserializes");
3327 assert_eq!(contract.channel, VerdictChannel::Body);
3328 assert_eq!(
3329 contract.values,
3330 vec!["PASS".to_string(), "BLOCKED".to_string()]
3331 );
3332 assert_eq!(serde_json::to_value(&contract).expect("serializes"), json);
3333 }
3334
3335 #[test]
3336 fn verdict_contract_roundtrips_part_channel() {
3337 let json = serde_json::json!({"channel": "part", "values": ["ALLOW"]});
3338 let contract: VerdictContract = serde_json::from_value(json.clone()).expect("deserializes");
3339 assert_eq!(contract.channel, VerdictChannel::Part);
3340 assert_eq!(serde_json::to_value(&contract).expect("serializes"), json);
3341 }
3342
3343 #[test]
3344 fn agent_def_verdict_omitted_when_none() {
3345 let agent = agent_with_runner("gate", None, None, None);
3346 let json = serde_json::to_value(&agent).expect("serializes");
3347 assert!(
3348 json.as_object().unwrap().get("verdict").is_none(),
3349 "verdict key must be absent when None: {json}"
3350 );
3351 let back: AgentDef = serde_json::from_value(json).expect("deserializes");
3352 assert_eq!(back.verdict, None);
3353 }
3354
3355 #[test]
3356 fn agent_def_verdict_roundtrips_when_some() {
3357 let mut agent = agent_with_runner("gate", None, None, None);
3358 agent.verdict = Some(VerdictContract {
3359 channel: VerdictChannel::Body,
3360 values: vec!["PASS".to_string(), "BLOCKED".to_string()],
3361 });
3362 let json = serde_json::to_value(&agent).expect("serializes");
3363 let back: AgentDef = serde_json::from_value(json).expect("deserializes");
3364 assert_eq!(back.verdict, agent.verdict);
3365 }
3366
3367 /// Acceptance criterion #2: the `02-verdict-loop.json` sample (no
3368 /// `verdict` field on any of its agents) must still deserialize
3369 /// unchanged under the new `#[serde(deny_unknown_fields)]`-constrained
3370 /// `AgentDef` — `verdict` is `#[serde(default)]`, so its absence is not
3371 /// an error.
3372 #[test]
3373 fn existing_verdict_loop_sample_deserializes_with_verdict_omitted() {
3374 const SAMPLE: &str =
3375 include_str!("../../mlua-swarm-cli/src/mcp/resources/samples/02-verdict-loop.json");
3376 let bp: Blueprint = serde_json::from_str(SAMPLE).expect("sample deserializes");
3377 assert_eq!(bp.agents.len(), 6);
3378 assert!(
3379 bp.agents.iter().all(|a| a.verdict.is_none()),
3380 "no agent in the sample declares a verdict contract"
3381 );
3382 }
3383
3384 // ──────────────────────────────────────────────────────────────
3385 // CheckPolicy enum relocation + Blueprint.check_policy
3386 // (T1: schema round-trip / omit→None / invalid→error)
3387 // ──────────────────────────────────────────────────────────────
3388
3389 /// The wire form is snake_case and byte-identical to the pre-relocation
3390 /// enum (`"silent"` / `"warn"` / `"strict"`), round-tripping in both
3391 /// directions — the relocation must not change the serde surface.
3392 #[test]
3393 fn check_policy_wire_form_round_trips() {
3394 for (variant, wire) in [
3395 (CheckPolicy::Silent, "silent"),
3396 (CheckPolicy::Warn, "warn"),
3397 (CheckPolicy::Strict, "strict"),
3398 ] {
3399 let json = serde_json::to_value(variant).expect("serializes");
3400 assert_eq!(json, serde_json::json!(wire), "wire form for {variant:?}");
3401 let back: CheckPolicy = serde_json::from_value(json).expect("deserializes");
3402 assert_eq!(back, variant, "round-trip for {variant:?}");
3403 }
3404 }
3405
3406 /// The default is `Warn` (preserves the pre-CheckPolicy fail-open
3407 /// behaviour of every submit-time projection sink).
3408 #[test]
3409 fn check_policy_default_is_warn() {
3410 assert_eq!(CheckPolicy::default(), CheckPolicy::Warn);
3411 }
3412
3413 /// A Blueprint that declares `check_policy: "strict"` parses to
3414 /// `Some(Strict)` and re-serializes with the same snake_case literal.
3415 #[test]
3416 fn blueprint_check_policy_strict_round_trips() {
3417 let json = serde_json::json!({
3418 "schema_version": current_schema_version(),
3419 "id": "check-policy-strict-ut",
3420 "flow": { "kind": "seq", "children": [] },
3421 "check_policy": "strict",
3422 });
3423 let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
3424 assert_eq!(bp.check_policy, Some(CheckPolicy::Strict));
3425 let re = serde_json::to_string(&bp).expect("serializes");
3426 assert!(
3427 re.contains("\"check_policy\":\"strict\""),
3428 "re-serialized BP must preserve the snake_case wire literal: {re}"
3429 );
3430 }
3431
3432 /// An omitted `check_policy` parses to `None` and is skipped on
3433 /// serialize (backward-compat with every pre-cascade Blueprint).
3434 #[test]
3435 fn blueprint_check_policy_omitted_is_none() {
3436 let json = serde_json::json!({
3437 "schema_version": current_schema_version(),
3438 "id": "check-policy-omitted-ut",
3439 "flow": { "kind": "seq", "children": [] },
3440 });
3441 let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
3442 assert_eq!(bp.check_policy, None);
3443
3444 let out = serde_json::to_value(&bp).expect("serializes");
3445 assert!(
3446 out.as_object().unwrap().get("check_policy").is_none(),
3447 "check_policy key must be absent when None: {out}"
3448 );
3449 }
3450
3451 /// An invalid `check_policy` value is a hard parse error (not silently
3452 /// dropped) — the enum is closed to the three snake_case variants. This
3453 /// also confirms `deny_unknown_fields` is not the gate here: the field
3454 /// IS known, only its value is invalid.
3455 #[test]
3456 fn blueprint_check_policy_invalid_value_errors() {
3457 let json = serde_json::json!({
3458 "schema_version": current_schema_version(),
3459 "id": "check-policy-invalid-ut",
3460 "flow": { "kind": "seq", "children": [] },
3461 "check_policy": "loud",
3462 });
3463 let err = serde_json::from_value::<Blueprint>(json)
3464 .expect_err("an unknown check_policy value must be rejected");
3465 let msg = err.to_string();
3466 assert!(
3467 msg.contains("check_policy") || msg.contains("loud") || msg.contains("variant"),
3468 "error should point at the bad check_policy value: {msg}"
3469 );
3470 }
3471
3472 #[test]
3473 fn agent_provider_manifest_round_trips_and_rejects_unknown_fields() {
3474 let json = serde_json::json!({
3475 "provider_id": "main-ai-self-report",
3476 "provider_revision": "1",
3477 "capabilities": [{
3478 "launch_variant": "mse-coder",
3479 "resolved_model": "claude-sonnet-4",
3480 "effective_tools": ["Read", "Edit"]
3481 }]
3482 });
3483 let manifest: AgentProviderManifest =
3484 serde_json::from_value(json.clone()).expect("manifest deserializes");
3485 assert_eq!(serde_json::to_value(manifest).unwrap(), json);
3486
3487 let invalid = serde_json::json!({
3488 "provider_id": "main-ai-self-report",
3489 "capabilities": [],
3490 "platform_secret": true
3491 });
3492 assert!(serde_json::from_value::<AgentProviderManifest>(invalid).is_err());
3493 }
3494}