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