Skip to main content

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 `total_tokens` from it. **Every one of the three is
1201    /// optional**: a CLI that prints only a total still lands a usage
1202    /// record (the splits read as `0`), and a CLI that prints only the
1203    /// splits has its total derived as `input + output`. Only a usage
1204    /// object carrying none of the three records no usage.
1205    #[serde(default, skip_serializing_if = "Option::is_none")]
1206    pub usage_ptr: Option<String>,
1207    /// JSON Pointer selecting the model name STRING that actually
1208    /// served the run (overrides the template's declared `{model}`
1209    /// value in the recorded stats when present).
1210    #[serde(default, skip_serializing_if = "Option::is_none")]
1211    pub model_ptr: Option<String>,
1212    /// JSON Pointer selecting the number of LLM turns (a JSON number).
1213    #[serde(default, skip_serializing_if = "Option::is_none")]
1214    pub num_turns_ptr: Option<String>,
1215}
1216
1217/// One [`Blueprint::runners`] registry entry — a named [`Runner`]
1218/// declaration referenced by `AgentDef.runner_ref` /
1219/// [`Blueprint::default_runner`]. Same registry shape as [`MetaDef`] (GH
1220/// #21 Phase 2).
1221#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1222#[serde(deny_unknown_fields)]
1223pub struct RunnerDef {
1224    /// Registry key, referenced by `AgentDef.runner_ref` /
1225    /// `Blueprint.default_runner`.
1226    pub name: String,
1227    /// The declared Runner.
1228    pub runner: Runner,
1229}
1230
1231/// Canonical GH #46 Worker unit: a resolved [`Runner`] paired with the
1232/// [`AgentDef`] it backs. The Milestone 4 adapter is the consumer that
1233/// turns this into a runtime spawn; this crate only declares the shape
1234/// (no execution logic lives here — see the crate doc's IN-immutability
1235/// discipline).
1236#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1237#[serde(deny_unknown_fields)]
1238pub struct WorkerModel {
1239    /// The resolved Runner.
1240    pub runner: Runner,
1241    /// The agent this Runner backs.
1242    pub agent: AgentDef,
1243}
1244
1245/// Everything [`resolve_runner`] can fail with: an `AgentDef.runner_ref`
1246/// / `Blueprint.default_runner` reference that names no entry in
1247/// `Blueprint.runners`.
1248#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1249pub enum RunnerResolveError {
1250    /// `AgentDef.runner_ref` names a [`RunnerDef::name`] absent from
1251    /// `Blueprint.runners`.
1252    #[error(
1253        "agent '{agent}' runner_ref '{ref_name}' does not match any RunnerDef.name in \
1254         Blueprint.runners (defined: {available:?})"
1255    )]
1256    UnknownRunnerRef {
1257        /// The agent whose `runner_ref` didn't resolve.
1258        agent: String,
1259        /// The `runner_ref` value that was looked up.
1260        ref_name: String,
1261        /// The `RunnerDef.name`s that *are* declared, for the error message.
1262        available: Vec<String>,
1263    },
1264    /// `Blueprint.default_runner` names a [`RunnerDef::name`] absent from
1265    /// `Blueprint.runners`.
1266    #[error(
1267        "default_runner '{ref_name}' does not match any RunnerDef.name in Blueprint.runners \
1268         (defined: {available:?})"
1269    )]
1270    UnknownDefaultRunner {
1271        /// The `default_runner` value that was looked up.
1272        ref_name: String,
1273        /// The `RunnerDef.name`s that *are* declared, for the error message.
1274        available: Vec<String>,
1275    },
1276}
1277
1278/// Resolve `agent`'s effective [`Runner`] against `bp`, in cascade order
1279/// (highest priority first):
1280///
1281/// 1. `agent.runner` (inline declaration) — wins unconditionally.
1282/// 2. `agent.runner_ref`, resolved against `bp.runners` (an unresolved
1283///    name is [`RunnerResolveError::UnknownRunnerRef`]).
1284/// 3. Legacy fallback (agent-level): `agent.profile.worker_binding =
1285///    Some(variant)` becomes `Runner::WsClaudeCode { variant,
1286///    tools: profile.tools.clone() }` — the same synthesis
1287///    `crate::service::task_launch::derive_worker_bindings` (in the
1288///    `mlua-swarm` core crate) performs at launch time today.
1289/// 4. `bp.default_runner`, resolved against `bp.runners` (an unresolved
1290///    name is [`RunnerResolveError::UnknownDefaultRunner`]).
1291/// 5. `Ok(None)` — no Runner declared through any tier.
1292///
1293/// **Legacy (agent-level) beats `default_runner` (BP-global)**: tier 3
1294/// outranks tier 4, the same "agent-level wins over BP-global" rule the
1295/// ctx cascade (`AgentInline > MetaRef > BpGlobal`, see
1296/// `mlua-swarm`'s `core::explain::CtxTier`) already follows.
1297///
1298/// Pure and read-only: this Milestone does not wire the result into the
1299/// launch / compile path (Milestone 3 scope) — it only declares the
1300/// resolver.
1301pub fn resolve_runner(
1302    bp: &Blueprint,
1303    agent: &AgentDef,
1304) -> Result<Option<Runner>, RunnerResolveError> {
1305    // 1. inline — wins unconditionally.
1306    if let Some(runner) = &agent.runner {
1307        return Ok(Some(runner.clone()));
1308    }
1309
1310    // 2. runner_ref → bp.runners lookup.
1311    if let Some(ref_name) = &agent.runner_ref {
1312        return match bp.runners.iter().find(|def| &def.name == ref_name) {
1313            Some(def) => Ok(Some(def.runner.clone())),
1314            None => Err(RunnerResolveError::UnknownRunnerRef {
1315                agent: agent.name.clone(),
1316                ref_name: ref_name.clone(),
1317                available: bp.runners.iter().map(|d| d.name.clone()).collect(),
1318            }),
1319        };
1320    }
1321
1322    // 3. legacy fallback (agent-level `profile.worker_binding`) — outranks
1323    // `bp.default_runner` (tier 4).
1324    if let Some(variant) = agent
1325        .profile
1326        .as_ref()
1327        .and_then(|p| p.worker_binding.as_ref())
1328    {
1329        let tools = agent
1330            .profile
1331            .as_ref()
1332            .map(|p| p.tools.clone())
1333            .unwrap_or_default();
1334        return Ok(Some(Runner::WsClaudeCode {
1335            variant: variant.clone(),
1336            tools,
1337        }));
1338    }
1339
1340    // 4. bp.default_runner → bp.runners lookup.
1341    if let Some(ref_name) = &bp.default_runner {
1342        return match bp.runners.iter().find(|def| &def.name == ref_name) {
1343            Some(def) => Ok(Some(def.runner.clone())),
1344            None => Err(RunnerResolveError::UnknownDefaultRunner {
1345                ref_name: ref_name.clone(),
1346                available: bp.runners.iter().map(|d| d.name.clone()).collect(),
1347            }),
1348        };
1349    }
1350
1351    // 5. nothing declared through any tier.
1352    Ok(None)
1353}
1354
1355/// Which declaration tier supplied a [`BoundAgent`]'s resolved Runner.
1356/// Kept in the immutable snapshot so explain surfaces can distinguish a
1357/// first-class binding from the Claude Code compatibility fallback.
1358#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1359#[serde(rename_all = "snake_case")]
1360pub enum RunnerResolutionSource {
1361    /// `AgentDef.runner`.
1362    AgentInline,
1363    /// `AgentDef.runner_ref` resolved through `Blueprint.runners`.
1364    AgentRef,
1365    /// Deprecated `AgentProfile.worker_binding` compatibility path.
1366    LegacyWorkerBinding,
1367    /// `Blueprint.default_runner` resolved through `Blueprint.runners`.
1368    BlueprintDefault,
1369    /// No Runner applies to this in-process or otherwise unbound agent.
1370    None,
1371}
1372
1373/// Strongly typed identity of one immutable [`BoundAgent`] snapshot.
1374/// Transparent serde keeps the public JSON wire form a plain string.
1375#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, JsonSchema)]
1376#[serde(transparent)]
1377pub struct BindingDigest(String);
1378
1379impl BindingDigest {
1380    /// Compute the canonical `sha256:<lowercase-hex>` digest of `bytes`.
1381    pub fn sha256(bytes: impl AsRef<[u8]>) -> Self {
1382        use sha2::Digest as _;
1383        Self(format!(
1384            "sha256:{}",
1385            hex::encode(sha2::Sha256::digest(bytes.as_ref()))
1386        ))
1387    }
1388
1389    /// Borrow the stable wire representation.
1390    pub fn as_str(&self) -> &str {
1391        &self.0
1392    }
1393}
1394
1395impl std::fmt::Display for BindingDigest {
1396    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1397        f.write_str(&self.0)
1398    }
1399}
1400
1401impl std::str::FromStr for BindingDigest {
1402    type Err = BindingDigestParseError;
1403
1404    fn from_str(value: &str) -> Result<Self, Self::Err> {
1405        let Some(hex_part) = value.strip_prefix("sha256:") else {
1406            return Err(BindingDigestParseError::InvalidFormat(value.to_string()));
1407        };
1408        let canonical = hex_part.len() == 64
1409            && hex_part
1410                .bytes()
1411                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
1412        if !canonical {
1413            return Err(BindingDigestParseError::InvalidFormat(value.to_string()));
1414        }
1415        Ok(Self(value.to_string()))
1416    }
1417}
1418
1419impl<'de> Deserialize<'de> for BindingDigest {
1420    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1421    where
1422        D: serde::Deserializer<'de>,
1423    {
1424        use std::str::FromStr as _;
1425        let value = String::deserialize(deserializer)?;
1426        Self::from_str(&value).map_err(serde::de::Error::custom)
1427    }
1428}
1429
1430/// Rejection returned when an external binding digest is not in canonical
1431/// `sha256:<64 lowercase hex>` form.
1432#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1433pub enum BindingDigestParseError {
1434    /// Unsupported algorithm prefix, wrong length, uppercase, or non-hex.
1435    #[error("invalid binding digest '{0}'; expected sha256:<64 lowercase hex>")]
1436    InvalidFormat(String),
1437}
1438
1439/// Platform-neutral request sent to an [`AgentBindingProvider`](https://docs.rs/mlua-swarm)
1440/// before a Run is dispatched.
1441///
1442/// The request contains only Swarm declarations. A provider may resolve
1443/// platform aliases or inspect its own execution environment, but Swarm
1444/// validates the returned [`BindReceipt`] before accepting it.
1445#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1446#[serde(deny_unknown_fields)]
1447pub struct BindRequest {
1448    /// Logical agent name; the receipt correlation key.
1449    pub agent: String,
1450    /// Digest of the declaration-only [`BoundAgent`] snapshot.
1451    pub request_digest: BindingDigest,
1452    /// Runner backend family Core resolved for this agent.
1453    pub backend: BindingBackend,
1454    /// Provider-specific routing key. For Operator-backed runners this is
1455    /// the logical `operator_ref`, never a runtime session id.
1456    #[serde(default, skip_serializing_if = "Option::is_none")]
1457    pub binding_target: Option<String>,
1458    /// Requested model name or tier from [`AgentProfile::model`].
1459    #[serde(default, skip_serializing_if = "Option::is_none")]
1460    pub requested_model: Option<String>,
1461    /// Minimum tool grant declared by the resolved [`Runner`].
1462    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1463    pub requested_tools: Vec<String>,
1464    /// Platform launch variant requested by the resolved [`Runner`].
1465    #[serde(default, skip_serializing_if = "Option::is_none")]
1466    pub launch_variant: Option<String>,
1467}
1468
1469/// Backend family a binding provider must resolve.
1470#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1471#[serde(rename_all = "snake_case")]
1472pub enum BindingBackend {
1473    /// Platform-neutral Operator/MainAI WebSocket execution.
1474    WsOperator,
1475    /// Claude Code wrapper dispatched through an Operator WebSocket.
1476    WsClaudeCode,
1477    /// AgentBlock registry enforced in the Server process.
1478    AgentBlockInProcess,
1479}
1480
1481/// Provider report describing the effective runtime binding for one agent.
1482/// This value is untrusted until Swarm validates it against [`BindRequest`].
1483#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1484#[serde(deny_unknown_fields)]
1485pub struct BindReceipt {
1486    /// Logical agent name copied from the request.
1487    pub agent: String,
1488    /// Declaration digest copied from the request. Core rejects stale or
1489    /// cross-request receipts even when the logical agent name matches.
1490    pub request_digest: BindingDigest,
1491    /// Stable provider implementation identifier.
1492    pub provider_id: String,
1493    /// Provider or adapter revision used to resolve the binding.
1494    #[serde(default, skip_serializing_if = "Option::is_none")]
1495    pub provider_revision: Option<String>,
1496    /// Effective model after platform alias/tier resolution.
1497    #[serde(default, skip_serializing_if = "Option::is_none")]
1498    pub resolved_model: Option<String>,
1499    /// Effective tool grant enforced by the execution environment.
1500    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1501    pub effective_tools: Vec<String>,
1502    /// Effective platform launch variant.
1503    #[serde(default, skip_serializing_if = "Option::is_none")]
1504    pub launch_variant: Option<String>,
1505    /// Optional digest of the provider-observed capability snapshot. This is
1506    /// a drift/lint correlation key, not independent security evidence.
1507    #[serde(
1508        default,
1509        alias = "evidence_digest",
1510        skip_serializing_if = "Option::is_none"
1511    )]
1512    pub capability_snapshot_digest: Option<BindingDigest>,
1513}
1514
1515/// One provider outcome for a single [`BindRequest`].
1516///
1517/// A provider reports exactly one outcome per requested agent. `Bound`
1518/// carries an (untrusted) [`BindReceipt`] Core still validates; `Unbound`
1519/// records that the execution environment currently offers no capability for
1520/// the request (e.g. the role has not joined, or the manifest declares no
1521/// matching launch variant). Whether an `Unbound` outcome fails the launch
1522/// or is merely observed is decided by
1523/// [`CompilerStrategy::strict_binding`] — not by the provider.
1524#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1525#[serde(tag = "outcome", rename_all = "snake_case", deny_unknown_fields)]
1526pub enum BindOutcome {
1527    /// The provider resolved a receipt for the agent. Still untrusted until
1528    /// Core validates it against the originating [`BindRequest`].
1529    Bound {
1530        /// Provider-reported binding, validated by Core before acceptance.
1531        receipt: BindReceipt,
1532    },
1533    /// The provider offers no capability for the request right now. The
1534    /// `reason` is human-facing diagnostic text only; it never enters the
1535    /// [`BoundAgent`] snapshot or its digest lineage.
1536    Unbound {
1537        /// Logical agent name copied from the request.
1538        agent: String,
1539        /// Why the provider could not bind the agent.
1540        reason: String,
1541    },
1542}
1543
1544/// Core-validated capability statement pinned into a [`BoundAgent`].
1545///
1546/// It deliberately omits the logical agent name because the containing
1547/// snapshot already supplies that identity.
1548#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1549#[serde(deny_unknown_fields)]
1550pub struct BindingAttestation {
1551    /// Declaration-only digest the provider attested.
1552    pub request_digest: BindingDigest,
1553    /// Stable provider implementation identifier.
1554    pub provider_id: String,
1555    /// Provider or adapter revision used to resolve the binding.
1556    #[serde(default, skip_serializing_if = "Option::is_none")]
1557    pub provider_revision: Option<String>,
1558    /// Effective model after platform alias/tier resolution.
1559    #[serde(default, skip_serializing_if = "Option::is_none")]
1560    pub resolved_model: Option<String>,
1561    /// Effective tool grant, canonicalized by Swarm.
1562    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1563    pub effective_tools: Vec<String>,
1564    /// Effective platform launch variant.
1565    #[serde(default, skip_serializing_if = "Option::is_none")]
1566    pub launch_variant: Option<String>,
1567    /// Optional digest of the provider-observed capability snapshot.
1568    #[serde(
1569        default,
1570        alias = "evidence_digest",
1571        skip_serializing_if = "Option::is_none"
1572    )]
1573    pub capability_snapshot_digest: Option<BindingDigest>,
1574}
1575
1576/// One effective capability advertised by an execution-environment
1577/// provider. Operator manifests normally publish one entry per wrapper
1578/// variant.
1579#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1580#[serde(deny_unknown_fields)]
1581pub struct AgentProviderCapability {
1582    /// Platform launch variant this capability serves. `None` is reserved
1583    /// for backends without a variant axis.
1584    #[serde(default, skip_serializing_if = "Option::is_none")]
1585    pub launch_variant: Option<String>,
1586    /// Effective model selected by the provider.
1587    #[serde(default, skip_serializing_if = "Option::is_none")]
1588    pub resolved_model: Option<String>,
1589    /// Effective tool grant enforced by the provider.
1590    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1591    pub effective_tools: Vec<String>,
1592    /// Optional digest of the provider-observed capability snapshot.
1593    #[serde(
1594        default,
1595        alias = "evidence_digest",
1596        skip_serializing_if = "Option::is_none"
1597    )]
1598    pub capability_snapshot_digest: Option<BindingDigest>,
1599}
1600
1601/// Capability manifest supplied by an Operator/MainAI or an official
1602/// execution-platform plugin when joining the Server.
1603#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1604#[serde(deny_unknown_fields)]
1605pub struct AgentProviderManifest {
1606    /// Stable provider implementation identifier.
1607    pub provider_id: String,
1608    /// Provider or adapter revision used to inspect capabilities.
1609    #[serde(default, skip_serializing_if = "Option::is_none")]
1610    pub provider_revision: Option<String>,
1611    /// Effective capabilities available through this provider instance.
1612    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1613    pub capabilities: Vec<AgentProviderCapability>,
1614}
1615
1616/// Immutable, Run-scoped result of binding the Runner / Agent / Context
1617/// layers for one logical agent.
1618///
1619/// This is derived state, not a fourth authoring source of truth. The full
1620/// [`AgentDef`] is retained deliberately: resume/replay must not re-read a
1621/// changed role prompt or result contract from a mutable Blueprint registry.
1622/// Capability attestation is adapter-owned and is therefore not guessed here;
1623/// the resolved [`Runner`] remains a declaration until an adapter records its
1624/// requested/effective comparison.
1625#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1626#[serde(deny_unknown_fields)]
1627pub struct BoundAgent {
1628    /// Logical agent definition pinned for the Run.
1629    pub agent: AgentDef,
1630    /// Runner selected by [`resolve_runner`], if this agent needs one.
1631    #[serde(default, skip_serializing_if = "Option::is_none")]
1632    pub runner: Option<Runner>,
1633    /// Effective static Context policy (`AgentMeta.context_policy` wins over
1634    /// `Blueprint.default_context_policy`). Runtime context values are not
1635    /// embedded here.
1636    #[serde(default, skip_serializing_if = "Option::is_none")]
1637    pub context_policy: Option<ContextPolicy>,
1638    /// Declaration tier that supplied `runner`.
1639    pub runner_source: RunnerResolutionSource,
1640    /// Effective capability statement accepted from the injected binding
1641    /// provider. `None` preserves the declaration-only compatibility path.
1642    #[serde(default, skip_serializing_if = "Option::is_none")]
1643    pub attestation: Option<BindingAttestation>,
1644    /// SHA-256 over the other fields of this snapshot, prefixed with
1645    /// `sha256:`. This is replay identity and an observability correlation
1646    /// key, not a signature.
1647    pub binding_digest: BindingDigest,
1648}
1649
1650/// Failure while constructing immutable [`BoundAgent`] snapshots.
1651#[derive(Debug, thiserror::Error)]
1652pub enum BoundAgentResolveError {
1653    /// A Runner reference did not resolve.
1654    #[error(transparent)]
1655    Runner(#[from] RunnerResolveError),
1656    /// The snapshot input could not be serialized for deterministic hashing.
1657    #[error("bound agent '{agent}' could not be serialized for digest: {source}")]
1658    Digest {
1659        /// Logical agent name.
1660        agent: String,
1661        /// Serialization failure.
1662        source: serde_json::Error,
1663    },
1664    /// Strict binding rejected the deprecated Claude Code compatibility
1665    /// declaration instead of silently accepting it.
1666    #[error(
1667        "agent '{agent}' uses deprecated profile.worker_binding; strict binding requires runner or runner_ref"
1668    )]
1669    LegacyWorkerBindingDisabled {
1670        /// Logical agent that must be migrated.
1671        agent: String,
1672    },
1673}
1674
1675#[derive(Serialize)]
1676struct BoundAgentDigestInput<'a> {
1677    agent: &'a AgentDef,
1678    runner: &'a Option<Runner>,
1679    context_policy: &'a Option<ContextPolicy>,
1680    runner_source: RunnerResolutionSource,
1681    attestation: &'a Option<BindingAttestation>,
1682}
1683
1684impl BoundAgent {
1685    /// Replace the effective capability attestation and recompute replay
1686    /// identity over the complete immutable snapshot.
1687    pub fn set_attestation(
1688        &mut self,
1689        attestation: BindingAttestation,
1690    ) -> Result<(), BoundAgentResolveError> {
1691        self.attestation = Some(attestation);
1692        self.recompute_binding_digest()
1693    }
1694
1695    /// Recompute `binding_digest` after a trusted snapshot mutation.
1696    pub fn recompute_binding_digest(&mut self) -> Result<(), BoundAgentResolveError> {
1697        let digest_input = BoundAgentDigestInput {
1698            agent: &self.agent,
1699            runner: &self.runner,
1700            context_policy: &self.context_policy,
1701            runner_source: self.runner_source,
1702            attestation: &self.attestation,
1703        };
1704        let bytes =
1705            serde_json::to_vec(&digest_input).map_err(|source| BoundAgentResolveError::Digest {
1706                agent: self.agent.name.clone(),
1707                source,
1708            })?;
1709        self.binding_digest = BindingDigest::sha256(bytes);
1710        Ok(())
1711    }
1712}
1713
1714/// Resolve every `Blueprint.agents` entry into an immutable Run snapshot.
1715/// Output order follows `Blueprint.agents`, making persistence and explain
1716/// responses stable without a second sort.
1717pub fn resolve_bound_agents(bp: &Blueprint) -> Result<Vec<BoundAgent>, BoundAgentResolveError> {
1718    resolve_bound_agents_with_legacy(bp, true)
1719}
1720
1721/// Strict counterpart to [`resolve_bound_agents`]: rejects the deprecated
1722/// `profile.worker_binding` fallback. This is the migration gate for callers
1723/// that require every binding to use the platform-neutral Runner contract.
1724pub fn resolve_bound_agents_strict(
1725    bp: &Blueprint,
1726) -> Result<Vec<BoundAgent>, BoundAgentResolveError> {
1727    resolve_bound_agents_with_legacy(bp, false)
1728}
1729
1730fn resolve_bound_agents_with_legacy(
1731    bp: &Blueprint,
1732    allow_legacy: bool,
1733) -> Result<Vec<BoundAgent>, BoundAgentResolveError> {
1734    bp.agents
1735        .iter()
1736        .map(|agent| {
1737            let runner = resolve_runner(bp, agent)?;
1738            let runner_source = if agent.runner.is_some() {
1739                RunnerResolutionSource::AgentInline
1740            } else if agent.runner_ref.is_some() {
1741                RunnerResolutionSource::AgentRef
1742            } else if agent
1743                .profile
1744                .as_ref()
1745                .and_then(|p| p.worker_binding.as_ref())
1746                .is_some()
1747            {
1748                RunnerResolutionSource::LegacyWorkerBinding
1749            } else if bp.default_runner.is_some() {
1750                RunnerResolutionSource::BlueprintDefault
1751            } else {
1752                RunnerResolutionSource::None
1753            };
1754            if !allow_legacy && runner_source == RunnerResolutionSource::LegacyWorkerBinding {
1755                return Err(BoundAgentResolveError::LegacyWorkerBindingDisabled {
1756                    agent: agent.name.clone(),
1757                });
1758            }
1759            let context_policy = agent
1760                .meta
1761                .as_ref()
1762                .and_then(|m| m.context_policy.clone())
1763                .or_else(|| bp.default_context_policy.clone());
1764            let digest_input = BoundAgentDigestInput {
1765                agent,
1766                runner: &runner,
1767                context_policy: &context_policy,
1768                runner_source,
1769                attestation: &None,
1770            };
1771            let bytes = serde_json::to_vec(&digest_input).map_err(|source| {
1772                BoundAgentResolveError::Digest {
1773                    agent: agent.name.clone(),
1774                    source,
1775                }
1776            })?;
1777            let binding_digest = BindingDigest::sha256(bytes);
1778            Ok(BoundAgent {
1779                agent: agent.clone(),
1780                runner,
1781                context_policy,
1782                runner_source,
1783                attestation: None,
1784                binding_digest,
1785            })
1786        })
1787        .collect()
1788}
1789
1790// ──────────────────────────────────────────────────────────────────────────
1791// OperatorDef / OperatorKind
1792// ──────────────────────────────────────────────────────────────────────────
1793
1794/// Kind axis of an Operator role (= "in which mode does this Operator run").
1795/// Corresponds 1:1 with the engine's runtime `OperatorKind`. Kept as a schema
1796/// duplicate so that BPs can be authored while depending only on this crate.
1797#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, JsonSchema)]
1798#[serde(rename_all = "snake_case")]
1799pub enum OperatorKind {
1800    /// MainAI (= interactive AI Operator via WS client or SDK).
1801    MainAi,
1802    /// Automate (= normal spawn path, without human interception).
1803    #[default]
1804    Automate,
1805    /// Composite (= MainAi + Automate running side by side).
1806    Composite,
1807}
1808
1809/// Design-time definition of an Operator role (first-class).
1810///
1811/// `AgentDef.spec.operator_ref` references this struct's `name` as a logical role name.
1812/// Binding to a runtime backend (WS session / SDK / pool, etc.) is established via the
1813/// attach path; the BP side only declares "under this logical name we expect an Operator
1814/// of this Kind".
1815///
1816/// `spec` is an escape hatch for kind-specific config (WS endpoint / SDK profile / pool
1817/// binding, etc.). Even when empty, declaring `name` + `kind` alone is enough for
1818/// compile-time validation to succeed (= it guarantees that agent `operator_ref` values
1819/// reference an existing definition).
1820#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
1821#[serde(deny_unknown_fields)]
1822pub struct OperatorDef {
1823    /// Logical role name (= design-time symbol referenced from `AgentDef.spec.operator_ref`).
1824    pub name: String,
1825    /// Display name for UI / docs (optional).
1826    #[serde(default)]
1827    pub display_name: Option<String>,
1828    /// Kind axis of the Operator (MainAi / Automate / Composite) — the "BP
1829    /// Agent-level" tier of the 4-tier `OperatorKind` cascade (see
1830    /// `Blueprint.default_operator_kind` for the full tier list). `None`
1831    /// when this `OperatorDef` does not declare a kind; the resolver then
1832    /// falls through to BP Global / Default Fallback for agents referencing
1833    /// this role via `AgentDef.spec.operator_ref`.
1834    #[serde(default)]
1835    pub kind: Option<OperatorKind>,
1836    /// Kind-specific config (WS endpoint / SDK profile / pool binding, etc.). Interpreted
1837    /// by the factory.
1838    #[serde(default)]
1839    pub spec: Value,
1840    /// Operator persona information (e.g. system_prompt template). Same shape as
1841    /// `AgentDef.profile`. Used as a template when the Operator itself plays a "role".
1842    /// If `None`, the agent-side profile is used instead.
1843    #[serde(default)]
1844    pub profile: Option<AgentProfile>,
1845    /// Operator-level metadata (description / version / tags).
1846    #[serde(default)]
1847    pub meta: Option<AgentMeta>,
1848}
1849
1850/// Named, multi-step-shared declarative context payload (GH #21 Phase 2).
1851///
1852/// Lives in the [`Blueprint::metas`] pool and is referenced by name from
1853/// two independent consumers: a `$step_meta.ref` envelope embedded in a
1854/// Step's evaluated `in` value (the Step tier, resolved by
1855/// `EngineDispatcher::dispatch` in the `mlua-swarm` core crate at
1856/// dispatch time — see `EngineDispatcher::with_step_metas`), and
1857/// [`AgentMeta::meta_ref`] (the Agent tier, resolved at launch time and
1858/// merged UNDER the agent's inline `AgentMeta::ctx`). The pool lets
1859/// multiple Steps and/or Agents share one declarative context object by
1860/// name instead of repeating it inline.
1861#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
1862#[serde(deny_unknown_fields)]
1863pub struct MetaDef {
1864    /// Logical name (= referenced by `$step_meta.ref` and
1865    /// `AgentMeta.meta_ref`; unique within [`Blueprint::metas`]).
1866    pub name: String,
1867    /// Declarative context payload. Consumers expect a JSON `Object` so
1868    /// it can be shallow-merged with an `inline` override / an agent's
1869    /// own `ctx` (a non-`Object` value is rejected — loudly at dispatch
1870    /// time for the Step tier, defensively (warn + skip) at launch time
1871    /// for the Agent tier); the shape is otherwise free-form.
1872    pub ctx: Value,
1873}
1874
1875/// GH #27 (follow-up to #23) — Blueprint-declared override of the
1876/// `mlua-swarm` core crate's placement resolver
1877/// (`mlua_swarm::core::projection_placement::ProjectionPlacement`), which
1878/// decides where a Step's materialized OUTPUT file (submit-time sink,
1879/// server read-back, and spawn-time `ctx_projection` pointer — the "3
1880/// path" convergence point) is written on disk. Both fields are
1881/// independently optional and validated (`dir_template`) at
1882/// `Compiler::compile` time — see that resolver's `from_spec` doc for the
1883/// full rejection rules.
1884#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
1885#[serde(deny_unknown_fields)]
1886pub struct ProjectionPlacementSpec {
1887    /// Which of the spawn-time `work_dir` / `project_root` to prefer as
1888    /// the materialize root, falling back to the other when the
1889    /// preferred one is absent. `"work_dir"` (default, current
1890    /// byte-compat behavior) | `"project_root"`. `None` = the default
1891    /// (`"work_dir"`).
1892    #[serde(default, skip_serializing_if = "Option::is_none")]
1893    pub root: Option<String>,
1894    /// Target directory template, relative to the resolved root, with a
1895    /// `{task_id}` placeholder substituted at materialize time. `None` =
1896    /// the default (`"workspace/tasks/{task_id}/ctx"`, current byte-compat
1897    /// behavior). Must be non-empty, contain the `{task_id}` placeholder,
1898    /// stay relative, and not contain any `..` path segment — rejected at
1899    /// `Compiler::compile` time otherwise.
1900    #[serde(default, skip_serializing_if = "Option::is_none")]
1901    pub dir_template: Option<String>,
1902}
1903
1904/// Agent / Operator level metadata (description / version / tags).
1905#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
1906#[serde(deny_unknown_fields)]
1907pub struct AgentMeta {
1908    /// Short human-readable description.
1909    #[serde(default)]
1910    pub description: Option<String>,
1911    /// Free-form version label.
1912    #[serde(default)]
1913    pub version: Option<String>,
1914    /// Tag list for classification / routing.
1915    #[serde(default)]
1916    pub tags: Vec<String>,
1917    /// GH #21 Phase 1 — "BP Agent-level" tier of the agent-context supply
1918    /// axis: a declarative object merged into `ctx.meta.runtime` for this
1919    /// agent's spawns, on top of (and winning over)
1920    /// [`Blueprint::default_agent_ctx`]. See that field's doc for the
1921    /// contrast with `default_init_ctx`. `None` = this agent declares no
1922    /// per-agent context (the BP-global tier alone applies, if any).
1923    #[serde(default, skip_serializing_if = "Option::is_none")]
1924    #[schemars(with = "Option<Value>")]
1925    pub ctx: Option<Value>,
1926    /// GH #21 Phase 1 — "BP Agent-level" tier of the [`ContextPolicy`]
1927    /// cascade: outranks [`Blueprint::default_context_policy`] for this
1928    /// agent. `None` = fall through to the BP-global policy (or pass-all
1929    /// if that is also `None`).
1930    #[serde(default, skip_serializing_if = "Option::is_none")]
1931    pub context_policy: Option<ContextPolicy>,
1932    /// GH #21 Phase 2 — "BP Agent-level" tier of the [`MetaDef`] pool:
1933    /// resolves against [`Blueprint::metas`] by name. The resolved
1934    /// `ctx` sits UNDER this agent's inline [`Self::ctx`] (inline wins
1935    /// on key collision). `None` = this agent declares no shared
1936    /// `MetaDef` reference.
1937    #[serde(default, skip_serializing_if = "Option::is_none")]
1938    pub meta_ref: Option<String>,
1939    /// GH #23 — the step-projection canonical name this agent's dispatched
1940    /// Steps should be addressed by (data-plane submit / `ContextPolicy`
1941    /// filter / `StepPointer`/`StepSummary` `name` / REST `:step` path /
1942    /// materialized file stem — see `mlua-swarm` core's
1943    /// `core::step_naming::StepNaming` for the table this field feeds).
1944    /// `None` = this agent declares no projection name; the canonical
1945    /// name falls back to the Step's `ref` (the flow.ir data-plane
1946    /// producer name), matching pre-GH-#23 behavior byte-for-byte.
1947    #[serde(default, skip_serializing_if = "Option::is_none")]
1948    pub projection_name: Option<String>,
1949}
1950
1951// ──────────────────────────────────────────────────────────────────────────
1952// Compiler hints / strategy
1953// ──────────────────────────────────────────────────────────────────────────
1954
1955/// Per-agent overrides / hints. Interpreted by the Compiler / SpawnerFactory; not required.
1956#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
1957#[serde(deny_unknown_fields)]
1958pub struct CompilerHints {
1959    /// Agent name → per-agent hint (= passed to `SpawnerFactory.build`).
1960    #[serde(default)]
1961    pub per_agent: HashMap<String, Value>,
1962    /// Global hints (= e.g. parallel limit, default timeout, ...).
1963    #[serde(default)]
1964    pub global: Value,
1965}
1966
1967/// Compiler behavior rules. Controls strict / lenient handling and default fallback.
1968#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
1969#[serde(deny_unknown_fields)]
1970pub struct CompilerStrategy {
1971    /// If `true` (default), an unresolved `Step.ref` is an error; if `false`, it falls
1972    /// through to the default Spawner.
1973    #[serde(default = "default_true")]
1974    pub strict_refs: bool,
1975    /// If `true` (default), an `AgentKind` missing from the registry is an error; if
1976    /// `false`, it is skipped.
1977    #[serde(default = "default_true")]
1978    pub strict_kind: bool,
1979    /// If `true`, every Runner-backed agent must obtain a Core-validated
1980    /// attestation at launch (a binding provider is required, and any agent
1981    /// the provider leaves `Unbound` fails the launch). If `false` (default),
1982    /// an unattested agent runs `DeclarationOnly` and the gap is only
1983    /// observed (tracing warn + a `RunRecord.degradations` entry).
1984    ///
1985    /// This default is deliberately the opposite of `strict_refs` /
1986    /// `strict_kind` (both default `true`): those two guard *structural
1987    /// integrity* of the Blueprint itself (an unresolved ref or unknown kind
1988    /// is always a Blueprint bug), whereas binding attestation is an
1989    /// *execution-assurance opt-in* — it depends on an execution environment
1990    /// being present to attest against, which is not available for embed-only
1991    /// or manifest-less launches. Requiring it by default would break every
1992    /// launch that has no provider, so it is opt-in per Blueprint.
1993    #[serde(default)]
1994    pub strict_binding: bool,
1995}
1996
1997fn default_true() -> bool {
1998    true
1999}
2000
2001impl Default for CompilerStrategy {
2002    fn default() -> Self {
2003        Self {
2004            strict_refs: true,
2005            strict_kind: true,
2006            strict_binding: false,
2007        }
2008    }
2009}
2010
2011// ──────────────────────────────────────────────────────────────────────────
2012// Blueprint metadata / origin
2013// ──────────────────────────────────────────────────────────────────────────
2014
2015/// Blueprint-level metadata (description / origin / tags / ttl / version label / alias).
2016#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
2017#[serde(deny_unknown_fields)]
2018pub struct BlueprintMetadata {
2019    /// Short human-readable description of the Blueprint.
2020    #[serde(default)]
2021    pub description: Option<String>,
2022    /// Provenance record (inline / file / algocline).
2023    #[serde(default)]
2024    pub origin: BlueprintOrigin,
2025    /// Tag list for classification / routing.
2026    #[serde(default)]
2027    pub tags: Vec<String>,
2028    /// Optional SemVer label (= match target for `TaskPipeline VersionSelector::SemVerReq`).
2029    /// Example: `"1.2.3"`. Rewritten by `EnhanceAdapter` on PATCH/MINOR/MAJOR bumps.
2030    #[serde(default, skip_serializing_if = "Option::is_none")]
2031    pub version_label: Option<String>,
2032    /// Optional LDS session alias label. The Swarm engine itself does not apply this
2033    /// (= it is free-form content); the value is expanded into the Spawn directive and
2034    /// reaches the MainAI. The MainAI is expected to establish a task session via
2035    /// `mcp__lds__session_create(root=..., alias=<this>)`, and to inject
2036    /// `LDS Session Alias: <this>` verbatim into the SubAgent dispatch prompt body.
2037    /// The SubAgent body then calls `mcp__lds__session_start(alias=<this>)` with the
2038    /// received alias. Worktree ownership is thereby unified under a single session, and
2039    /// cross-SubAgent / cross-worktree ownership blocks (= `not owned by this session`)
2040    /// cannot fire structurally.
2041    #[serde(default, skip_serializing_if = "Option::is_none")]
2042    pub project_name_alias: Option<String>,
2043    /// Optional default TTL (seconds) for tasks dispatched via this BP. Estimated by the
2044    /// Blueprint author from the flow shape (agent count × expected duration per agent).
2045    /// If `POST /v1/tasks` supplies `ttl_secs` explicitly, the body value wins; otherwise
2046    /// this metadata field is used as the default; if both are absent, the server global
2047    /// default (`default_run_ttl()` = 1800s) applies. Not needed for short chains (~5 min);
2048    /// recommended for long chains (14 agents × several minutes = 30-60 min).
2049    #[serde(default, skip_serializing_if = "Option::is_none")]
2050    pub default_run_ttl_secs: Option<u64>,
2051    /// GH #50 follow-up (issue `33bc825b`): promote `VerdictValueUnhandled`
2052    /// compile-time lint to a hard error. When `false` (or absent), a
2053    /// declared `AgentDef.verdict.values` entry that no downstream cond
2054    /// references is only surfaced via `tracing::warn!` (informational);
2055    /// when `true`, `Compiler::compile` rejects the Blueprint with
2056    /// `CompileError::VerdictValueUnhandled`. Opt-in so existing Blueprints
2057    /// that intentionally leave some verdict values as silent-pass
2058    /// informational tokens keep compiling unchanged.
2059    ///
2060    /// **Legacy spelling.** This is now sugar for
2061    /// [`lints`](Self::lints)` = {"verdict-value-unhandled": "deny"}`,
2062    /// which is the preferred form (it addresses the same lint kind as
2063    /// every other layer and reads next to the rest of the Blueprint's
2064    /// lint policy). Both spellings are honored and union toward `deny`:
2065    /// either one saying deny rejects the compile, and `true` here wins
2066    /// over a `lints` `allow` on *either* layer — this one or
2067    /// [`AgentDef::lints`]. The field is kept indefinitely — existing
2068    /// Blueprints are not asked to migrate. Blueprint-wide by nature: to
2069    /// exempt one agent, drop the flag and declare the kind per agent.
2070    #[serde(default, skip_serializing_if = "Option::is_none")]
2071    pub strict_verdict_handling: Option<bool>,
2072    /// Blueprint-wide lint level overrides — the outermost layer of the
2073    /// [`LintSetting`] cascade (call-site > [`AgentDef::lints`] > this >
2074    /// the kind's registry default), consumed by `bp_doctor`. Keys are
2075    /// kind literals (`"agent-md-size"`), `"category:<cat>"` groups, or
2076    /// `"all"`; see [`LintSetting`] for the full grammar and the
2077    /// precedence rules. `None` (the default) = no Blueprint-wide
2078    /// overrides.
2079    ///
2080    /// One entry also reaches the compile stage: a `deny` matching
2081    /// `"verdict-value-unhandled"` rejects the Blueprint exactly like
2082    /// [`strict_verdict_handling`](Self::strict_verdict_handling), and an
2083    /// `allow` silences its `tracing::warn!`. This is the outer of the two
2084    /// layers the compile stage reads — an agent that declares the kind in
2085    /// its own [`AgentDef::lints`] decides for itself, and only agents
2086    /// that declare nothing fall through to here. No other kind's compile
2087    /// behavior can be changed — compile-stage errors are hard errors, not
2088    /// lints.
2089    #[serde(default, skip_serializing_if = "Option::is_none")]
2090    pub lints: Option<BTreeMap<String, LintSetting>>,
2091}
2092
2093/// Provenance record of a Blueprint.
2094#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, JsonSchema)]
2095#[serde(tag = "kind", rename_all = "snake_case")]
2096pub enum BlueprintOrigin {
2097    /// Inline construction, e.g. via a Rust struct literal or test code.
2098    #[default]
2099    Inline,
2100    /// Loaded from a file.
2101    File {
2102        /// Source file path.
2103        path: String,
2104    },
2105    /// Emitted by an algocline strategy (traced by `session_id`).
2106    Algo {
2107        /// Algocline session identifier.
2108        session_id: String,
2109    },
2110}
2111
2112#[cfg(test)]
2113mod tests {
2114    use super::*;
2115
2116    #[test]
2117    fn schema_version_default_parses() {
2118        let v = default_schema_version();
2119        assert_eq!(v.to_string(), "0.1.0");
2120    }
2121
2122    #[test]
2123    fn current_schema_version_const_matches() {
2124        assert_eq!(CURRENT_SCHEMA_VERSION, "0.1.0");
2125    }
2126
2127    #[test]
2128    fn blueprint_json_schema_exports_key_properties() {
2129        let schema = schemars::schema_for!(Blueprint);
2130        let v = serde_json::to_value(&schema).expect("schema serializes");
2131        let props = v["properties"].as_object().expect("object schema");
2132        for key in [
2133            "schema_version",
2134            "id",
2135            "flow",
2136            "agents",
2137            "operators",
2138            "metas",
2139            "hints",
2140            "strategy",
2141            "metadata",
2142            "spawner_hints",
2143            "default_agent_kind",
2144            "default_operator_kind",
2145            "default_init_ctx",
2146            "default_agent_ctx",
2147            "default_context_policy",
2148            "projection_placement",
2149            "audits",
2150            "runners",
2151            "default_runner",
2152            "check_policy",
2153        ] {
2154            assert!(props.contains_key(key), "missing property: {key}");
2155        }
2156        // semver override lands as a plain string
2157        assert_eq!(v["properties"]["schema_version"]["type"], "string");
2158        // enum variants (snake_case) survive into the schema (LLM author axis)
2159        let dump = v.to_string();
2160        assert!(dump.contains("agent_block"), "AgentKind variants in schema");
2161        assert!(dump.contains("main_ai"), "OperatorKind variants in schema");
2162        // nested defs are referenced (AgentDef reachable from agents[])
2163        assert!(dump.contains("AgentDef"), "AgentDef definition in schema");
2164    }
2165
2166    #[test]
2167    fn agent_profile_worker_binding_roundtrips_when_some() {
2168        let profile = AgentProfile {
2169            worker_binding: Some("code-worker".to_string()),
2170            ..Default::default()
2171        };
2172        let json = serde_json::to_value(&profile).expect("serializes");
2173        assert_eq!(json["worker_binding"], "code-worker");
2174        let back: AgentProfile = serde_json::from_value(json).expect("deserializes");
2175        assert_eq!(back.worker_binding.as_deref(), Some("code-worker"));
2176    }
2177
2178    #[test]
2179    fn agent_profile_worker_binding_omitted_when_none() {
2180        let profile = AgentProfile::default();
2181        let json = serde_json::to_value(&profile).expect("serializes");
2182        // `skip_serializing_if = "Option::is_none"` — the key must not appear at all.
2183        assert!(
2184            json.as_object().unwrap().get("worker_binding").is_none(),
2185            "worker_binding key must be absent when None: {json}"
2186        );
2187        let back: AgentProfile = serde_json::from_value(json).expect("deserializes");
2188        assert_eq!(back.worker_binding, None);
2189    }
2190
2191    // ──────────────────────────────────────────────────────────────
2192    // issue #19 ST3: `Blueprint.default_init_ctx`
2193    // ──────────────────────────────────────────────────────────────
2194
2195    fn minimal_bp(default_init_ctx: Option<Value>) -> Blueprint {
2196        Blueprint {
2197            schema_version: current_schema_version(),
2198            id: "bp-init-ctx-ut".into(),
2199            flow: FlowNode::Seq { children: vec![] },
2200            agents: vec![],
2201            operators: vec![],
2202            metas: vec![],
2203            hints: Default::default(),
2204            strategy: Default::default(),
2205            metadata: Default::default(),
2206            spawner_hints: Default::default(),
2207            default_agent_kind: AgentKind::Operator,
2208            default_operator_kind: None,
2209            default_init_ctx,
2210            default_agent_ctx: None,
2211            default_context_policy: None,
2212            projection_placement: None,
2213            audits: vec![],
2214            degradation_policy: None,
2215            runners: vec![],
2216            default_runner: None,
2217            subprocesses: vec![],
2218            check_policy: None,
2219            blueprint_ref_includes: Vec::new(),
2220        }
2221    }
2222
2223    #[test]
2224    fn blueprint_default_init_ctx_roundtrips_when_some() {
2225        let bp = minimal_bp(Some(serde_json::json!({ "seeded": true })));
2226        let json = serde_json::to_string(&bp).expect("serializes");
2227        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2228        assert_eq!(
2229            back.default_init_ctx,
2230            Some(serde_json::json!({ "seeded": true }))
2231        );
2232        assert_eq!(bp, back);
2233    }
2234
2235    #[test]
2236    fn blueprint_default_init_ctx_omitted_when_none() {
2237        let bp = minimal_bp(None);
2238        let json = serde_json::to_value(&bp).expect("serializes");
2239        // `skip_serializing_if = "Option::is_none"` — the key must not appear at all
2240        // (pre-#19 Blueprints round-trip byte-identical through this path).
2241        assert!(
2242            json.as_object().unwrap().get("default_init_ctx").is_none(),
2243            "default_init_ctx key must be absent when None: {json}"
2244        );
2245        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2246        assert_eq!(back.default_init_ctx, None);
2247        assert_eq!(bp, back);
2248    }
2249
2250    #[test]
2251    fn blueprint_json_schema_exports_default_init_ctx_as_nullable_value() {
2252        let schema = schemars::schema_for!(Blueprint);
2253        let v = serde_json::to_value(&schema).expect("schema serializes");
2254        assert!(
2255            v["properties"]["default_init_ctx"].is_object(),
2256            "default_init_ctx must appear in the exported schema: {v}"
2257        );
2258    }
2259
2260    // ──────────────────────────────────────────────────────────────
2261    // issue #21 Phase 1: `Blueprint.default_agent_ctx` /
2262    // `default_context_policy`, `AgentMeta.ctx` / `context_policy`,
2263    // `ContextPolicy`
2264    // ──────────────────────────────────────────────────────────────
2265
2266    #[test]
2267    fn blueprint_default_agent_ctx_and_context_policy_roundtrip_when_some() {
2268        let mut bp = minimal_bp(None);
2269        bp.default_agent_ctx = Some(serde_json::json!({ "org_conventions": "x" }));
2270        bp.default_context_policy = Some(ContextPolicy {
2271            include: Some(vec!["project_root".to_string()]),
2272            exclude: vec!["work_dir".to_string()],
2273            ..Default::default()
2274        });
2275        let json = serde_json::to_string(&bp).expect("serializes");
2276        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2277        assert_eq!(bp, back);
2278        assert_eq!(
2279            back.default_agent_ctx,
2280            Some(serde_json::json!({ "org_conventions": "x" }))
2281        );
2282        assert_eq!(
2283            back.default_context_policy,
2284            Some(ContextPolicy {
2285                include: Some(vec!["project_root".to_string()]),
2286                exclude: vec!["work_dir".to_string()],
2287                ..Default::default()
2288            })
2289        );
2290    }
2291
2292    #[test]
2293    fn blueprint_default_agent_ctx_and_context_policy_omitted_when_none() {
2294        let bp = minimal_bp(None);
2295        let json = serde_json::to_value(&bp).expect("serializes");
2296        let obj = json.as_object().unwrap();
2297        assert!(
2298            obj.get("default_agent_ctx").is_none(),
2299            "default_agent_ctx key must be absent when None: {json}"
2300        );
2301        assert!(
2302            obj.get("default_context_policy").is_none(),
2303            "default_context_policy key must be absent when None: {json}"
2304        );
2305        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2306        assert_eq!(back.default_agent_ctx, None);
2307        assert_eq!(back.default_context_policy, None);
2308        assert_eq!(bp, back);
2309    }
2310
2311    #[test]
2312    fn blueprint_json_schema_exports_agent_ctx_and_context_policy() {
2313        let schema = schemars::schema_for!(Blueprint);
2314        let v = serde_json::to_value(&schema).expect("schema serializes");
2315        assert!(
2316            v["properties"]["default_agent_ctx"].is_object(),
2317            "default_agent_ctx must appear in the exported schema: {v}"
2318        );
2319        assert!(
2320            v["properties"]["default_context_policy"].is_object(),
2321            "default_context_policy must appear in the exported schema: {v}"
2322        );
2323    }
2324
2325    // ──────────────────────────────────────────────────────────────
2326    // GH #27 (follow-up to #23): `Blueprint.projection_placement` /
2327    // `ProjectionPlacementSpec`
2328    // ──────────────────────────────────────────────────────────────
2329
2330    #[test]
2331    fn blueprint_projection_placement_roundtrips_when_some() {
2332        let mut bp = minimal_bp(None);
2333        bp.projection_placement = Some(ProjectionPlacementSpec {
2334            root: Some("project_root".to_string()),
2335            dir_template: Some("custom/{task_id}/out".to_string()),
2336        });
2337        let json = serde_json::to_string(&bp).expect("serializes");
2338        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2339        assert_eq!(bp, back);
2340        assert_eq!(
2341            back.projection_placement,
2342            Some(ProjectionPlacementSpec {
2343                root: Some("project_root".to_string()),
2344                dir_template: Some("custom/{task_id}/out".to_string()),
2345            })
2346        );
2347    }
2348
2349    #[test]
2350    fn blueprint_projection_placement_omitted_when_none() {
2351        let bp = minimal_bp(None);
2352        let json = serde_json::to_value(&bp).expect("serializes");
2353        assert!(
2354            json.as_object()
2355                .unwrap()
2356                .get("projection_placement")
2357                .is_none(),
2358            "projection_placement key must be absent when None: {json}"
2359        );
2360        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2361        assert_eq!(back.projection_placement, None);
2362        assert_eq!(bp, back);
2363    }
2364
2365    #[test]
2366    fn blueprint_json_schema_exports_projection_placement() {
2367        let schema = schemars::schema_for!(Blueprint);
2368        let v = serde_json::to_value(&schema).expect("schema serializes");
2369        assert!(
2370            v["properties"]["projection_placement"].is_object(),
2371            "projection_placement must appear in the exported schema: {v}"
2372        );
2373    }
2374
2375    #[test]
2376    fn agent_meta_ctx_and_context_policy_roundtrip_when_some() {
2377        let meta = AgentMeta {
2378            ctx: Some(serde_json::json!({ "k": "v" })),
2379            context_policy: Some(ContextPolicy {
2380                include: None,
2381                exclude: vec!["run_id".to_string()],
2382                ..Default::default()
2383            }),
2384            ..Default::default()
2385        };
2386        let json = serde_json::to_value(&meta).expect("serializes");
2387        let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
2388        assert_eq!(back, meta);
2389    }
2390
2391    #[test]
2392    fn agent_meta_ctx_and_context_policy_omitted_when_none() {
2393        let meta = AgentMeta::default();
2394        let json = serde_json::to_value(&meta).expect("serializes");
2395        let obj = json.as_object().unwrap();
2396        assert!(
2397            obj.get("ctx").is_none(),
2398            "ctx key must be absent when None: {json}"
2399        );
2400        assert!(
2401            obj.get("context_policy").is_none(),
2402            "context_policy key must be absent when None: {json}"
2403        );
2404    }
2405
2406    #[test]
2407    fn agent_meta_json_schema_exports_ctx_context_policy_and_meta_ref() {
2408        let schema = schemars::schema_for!(AgentMeta);
2409        let v = serde_json::to_value(&schema).expect("schema serializes");
2410        let props = v["properties"].as_object().expect("object schema");
2411        for key in [
2412            "description",
2413            "version",
2414            "tags",
2415            "ctx",
2416            "context_policy",
2417            "meta_ref",
2418            "projection_name",
2419        ] {
2420            assert!(props.contains_key(key), "missing property: {key}");
2421        }
2422    }
2423
2424    // ──────────────────────────────────────────────────────────────
2425    // issue #21 Phase 2: `MetaDef`, `Blueprint.metas`, `AgentMeta.meta_ref`
2426    // ──────────────────────────────────────────────────────────────
2427
2428    #[test]
2429    fn meta_def_roundtrips_through_json() {
2430        let def = MetaDef {
2431            name: "heavy-scan".to_string(),
2432            ctx: serde_json::json!({ "work_dir": "/x" }),
2433        };
2434        let json = serde_json::to_value(&def).expect("serializes");
2435        let back: MetaDef = serde_json::from_value(json).expect("deserializes");
2436        assert_eq!(back, def);
2437    }
2438
2439    #[test]
2440    fn blueprint_metas_omitted_when_empty() {
2441        let bp = minimal_bp(None);
2442        let json = serde_json::to_value(&bp).expect("serializes");
2443        assert!(
2444            json.as_object().unwrap().get("metas").is_none(),
2445            "metas key must be absent when empty: {json}"
2446        );
2447        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2448        assert!(back.metas.is_empty());
2449        assert_eq!(bp, back);
2450    }
2451
2452    #[test]
2453    fn blueprint_metas_roundtrips_when_non_empty() {
2454        let mut bp = minimal_bp(None);
2455        bp.metas = vec![MetaDef {
2456            name: "heavy-scan".to_string(),
2457            ctx: serde_json::json!({ "work_dir": "/x" }),
2458        }];
2459        let json = serde_json::to_string(&bp).expect("serializes");
2460        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2461        assert_eq!(bp, back);
2462        assert_eq!(back.metas.len(), 1);
2463        assert_eq!(back.metas[0].name, "heavy-scan");
2464    }
2465
2466    #[test]
2467    fn blueprint_json_schema_exports_metas() {
2468        let schema = schemars::schema_for!(Blueprint);
2469        let v = serde_json::to_value(&schema).expect("schema serializes");
2470        assert!(
2471            v["properties"]["metas"].is_object(),
2472            "metas must appear in the exported schema: {v}"
2473        );
2474        let dump = v.to_string();
2475        assert!(dump.contains("MetaDef"), "MetaDef definition in schema");
2476    }
2477
2478    #[test]
2479    fn agent_meta_meta_ref_roundtrips_when_some() {
2480        let meta = AgentMeta {
2481            meta_ref: Some("heavy-scan".to_string()),
2482            ..Default::default()
2483        };
2484        let json = serde_json::to_value(&meta).expect("serializes");
2485        assert_eq!(json["meta_ref"], "heavy-scan");
2486        let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
2487        assert_eq!(back, meta);
2488    }
2489
2490    #[test]
2491    fn agent_meta_meta_ref_omitted_when_none() {
2492        let meta = AgentMeta::default();
2493        let json = serde_json::to_value(&meta).expect("serializes");
2494        assert!(
2495            json.as_object().unwrap().get("meta_ref").is_none(),
2496            "meta_ref key must be absent when None: {json}"
2497        );
2498        let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
2499        assert_eq!(back.meta_ref, None);
2500    }
2501
2502    // ──────────────────────────────────────────────────────────────
2503    // GH #23: `AgentMeta.projection_name`
2504    // ──────────────────────────────────────────────────────────────
2505
2506    #[test]
2507    fn agent_meta_projection_name_roundtrips_when_some() {
2508        let meta = AgentMeta {
2509            projection_name: Some("plan".to_string()),
2510            ..Default::default()
2511        };
2512        let json = serde_json::to_value(&meta).expect("serializes");
2513        assert_eq!(json["projection_name"], "plan");
2514        let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
2515        assert_eq!(back, meta);
2516    }
2517
2518    #[test]
2519    fn agent_meta_projection_name_omitted_when_none() {
2520        let meta = AgentMeta::default();
2521        let json = serde_json::to_value(&meta).expect("serializes");
2522        assert!(
2523            json.as_object().unwrap().get("projection_name").is_none(),
2524            "projection_name key must be absent when None: {json}"
2525        );
2526        let back: AgentMeta = serde_json::from_value(json).expect("deserializes");
2527        assert_eq!(back.projection_name, None);
2528        assert_eq!(back, meta);
2529    }
2530
2531    #[test]
2532    fn agent_meta_rejects_unknown_field_with_projection_name_present() {
2533        // `deny_unknown_fields` must still reject an unrelated stray key
2534        // even when `projection_name` is present alongside it (regression
2535        // guard: adding the field must not accidentally loosen the
2536        // contract for the rest of the struct).
2537        let json = serde_json::json!({
2538            "projection_name": "plan",
2539            "not_a_real_field": true
2540        });
2541        let err = serde_json::from_value::<AgentMeta>(json).unwrap_err();
2542        assert!(
2543            err.to_string().contains("not_a_real_field")
2544                || err.to_string().contains("unknown field"),
2545            "expected an unknown-field rejection, got: {err}"
2546        );
2547    }
2548
2549    #[test]
2550    fn context_policy_default_allows_everything() {
2551        let policy = ContextPolicy::default();
2552        assert!(policy.allows("project_root"));
2553        assert!(policy.allows("anything"));
2554    }
2555
2556    #[test]
2557    fn context_policy_include_only_allows_listed_names() {
2558        let policy = ContextPolicy {
2559            include: Some(vec!["project_root".to_string()]),
2560            exclude: vec![],
2561            ..Default::default()
2562        };
2563        assert!(policy.allows("project_root"));
2564        assert!(!policy.allows("work_dir"));
2565    }
2566
2567    #[test]
2568    fn context_policy_exclude_wins_over_include() {
2569        let policy = ContextPolicy {
2570            include: Some(vec!["project_root".to_string()]),
2571            exclude: vec!["project_root".to_string()],
2572            ..Default::default()
2573        };
2574        assert!(!policy.allows("project_root"));
2575    }
2576
2577    #[test]
2578    fn context_policy_roundtrips_through_json() {
2579        let policy = ContextPolicy {
2580            include: Some(vec!["a".to_string(), "b".to_string()]),
2581            exclude: vec!["c".to_string()],
2582            ..Default::default()
2583        };
2584        let json = serde_json::to_value(&policy).expect("serializes");
2585        let back: ContextPolicy = serde_json::from_value(json).expect("deserializes");
2586        assert_eq!(back, policy);
2587    }
2588
2589    #[test]
2590    fn context_policy_default_roundtrips_as_empty_object() {
2591        let policy = ContextPolicy::default();
2592        let json = serde_json::to_value(&policy).expect("serializes");
2593        assert_eq!(
2594            json,
2595            serde_json::json!({
2596                "include": null,
2597                "exclude": [],
2598                "steps": null,
2599                "steps_exclude": [],
2600            })
2601        );
2602        let back: ContextPolicy = serde_json::from_value(json).expect("deserializes");
2603        assert_eq!(back, policy);
2604    }
2605
2606    // ──────────────────────────────────────────────────────────────
2607    // ST5 (`projection-adapter`): `ContextPolicy.steps` / `steps_exclude`
2608    // ──────────────────────────────────────────────────────────────
2609
2610    #[test]
2611    fn context_policy_steps_default_allows_every_step() {
2612        let policy = ContextPolicy::default();
2613        assert!(policy.allows_step("planner"));
2614        assert!(policy.allows_step("anything"));
2615    }
2616
2617    #[test]
2618    fn context_policy_steps_include_only_allows_listed_names() {
2619        let policy = ContextPolicy {
2620            steps: Some(vec!["planner".to_string()]),
2621            ..Default::default()
2622        };
2623        assert!(policy.allows_step("planner"));
2624        assert!(!policy.allows_step("coder"));
2625    }
2626
2627    #[test]
2628    fn context_policy_steps_empty_list_allows_none() {
2629        let policy = ContextPolicy {
2630            steps: Some(vec![]),
2631            ..Default::default()
2632        };
2633        assert!(!policy.allows_step("planner"));
2634    }
2635
2636    #[test]
2637    fn context_policy_steps_exclude_wins_over_steps() {
2638        let policy = ContextPolicy {
2639            steps: Some(vec!["planner".to_string()]),
2640            steps_exclude: vec!["planner".to_string()],
2641            ..Default::default()
2642        };
2643        assert!(!policy.allows_step("planner"));
2644    }
2645
2646    #[test]
2647    fn context_policy_steps_roundtrips_through_json() {
2648        let policy = ContextPolicy {
2649            steps: Some(vec!["planner".to_string(), "coder".to_string()]),
2650            steps_exclude: vec!["reviewer".to_string()],
2651            ..Default::default()
2652        };
2653        let json = serde_json::to_value(&policy).expect("serializes");
2654        let back: ContextPolicy = serde_json::from_value(json).expect("deserializes");
2655        assert_eq!(back, policy);
2656    }
2657
2658    // ──────────────────────────────────────────────────────────────
2659    // GH #34: `AuditDef`, `AuditMode`, `Blueprint.audits`
2660    // ──────────────────────────────────────────────────────────────
2661
2662    #[test]
2663    fn blueprint_audits_omitted_when_empty() {
2664        let bp = minimal_bp(None);
2665        let json = serde_json::to_value(&bp).expect("serializes");
2666        assert!(
2667            json.as_object().unwrap().get("audits").is_none(),
2668            "audits key must be absent when empty: {json}"
2669        );
2670        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2671        assert!(back.audits.is_empty());
2672        assert_eq!(bp, back);
2673    }
2674
2675    #[test]
2676    fn blueprint_audits_roundtrips_when_non_empty() {
2677        let mut bp = minimal_bp(None);
2678        bp.audits = vec![AuditDef {
2679            agent: "auditor".to_string(),
2680            steps: Some(vec!["worker".to_string()]),
2681            mode: AuditMode::Sync,
2682        }];
2683        let json = serde_json::to_string(&bp).expect("serializes");
2684        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2685        assert_eq!(bp, back);
2686        assert_eq!(back.audits.len(), 1);
2687        assert_eq!(back.audits[0].agent, "auditor");
2688        assert_eq!(back.audits[0].mode, AuditMode::Sync);
2689    }
2690
2691    #[test]
2692    fn audit_def_steps_none_and_mode_default_when_omitted() {
2693        let json = serde_json::json!({ "agent": "auditor" });
2694        let def: AuditDef = serde_json::from_value(json).expect("deserializes");
2695        assert_eq!(def.steps, None);
2696        assert_eq!(def.mode, AuditMode::Async);
2697    }
2698
2699    #[test]
2700    fn audit_def_rejects_unknown_field() {
2701        let json = serde_json::json!({ "agent": "auditor", "not_a_real_field": true });
2702        let err = serde_json::from_value::<AuditDef>(json).unwrap_err();
2703        assert!(
2704            err.to_string().contains("not_a_real_field")
2705                || err.to_string().contains("unknown field"),
2706            "expected an unknown-field rejection, got: {err}"
2707        );
2708    }
2709
2710    #[test]
2711    fn audit_mode_serializes_snake_case() {
2712        assert_eq!(
2713            serde_json::to_value(AuditMode::Async).unwrap(),
2714            serde_json::json!("async")
2715        );
2716        assert_eq!(
2717            serde_json::to_value(AuditMode::Sync).unwrap(),
2718            serde_json::json!("sync")
2719        );
2720    }
2721
2722    #[test]
2723    fn blueprint_json_schema_exports_audits_and_audit_def() {
2724        let schema = schemars::schema_for!(Blueprint);
2725        let v = serde_json::to_value(&schema).expect("schema serializes");
2726        assert!(
2727            v["properties"]["audits"].is_object(),
2728            "audits must appear in the exported schema: {v}"
2729        );
2730        let dump = v.to_string();
2731        assert!(dump.contains("AuditDef"), "AuditDef definition in schema");
2732    }
2733
2734    // ──────────────────────────────────────────────────────────────
2735    // GH #32: `Blueprint.degradation_policy`, `DegradationPolicy`
2736    // ──────────────────────────────────────────────────────────────
2737
2738    #[test]
2739    fn blueprint_without_degradation_policy_deserializes_to_none() {
2740        let json = serde_json::json!({
2741            "schema_version": current_schema_version(),
2742            "id": "no-degradation-policy-ut",
2743            "flow": { "kind": "seq", "children": [] },
2744        });
2745        let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
2746        assert_eq!(bp.degradation_policy, None);
2747    }
2748
2749    #[test]
2750    fn blueprint_degradation_policy_omitted_when_none() {
2751        let bp = minimal_bp(None);
2752        let json = serde_json::to_value(&bp).expect("serializes");
2753        assert!(
2754            json.as_object()
2755                .unwrap()
2756                .get("degradation_policy")
2757                .is_none(),
2758            "degradation_policy key must be absent when None: {json}"
2759        );
2760    }
2761
2762    #[test]
2763    fn blueprint_degradation_policy_warn_and_fail_roundtrip() {
2764        for (label, expected) in [
2765            ("warn", DegradationPolicy::Warn),
2766            ("fail", DegradationPolicy::Fail),
2767        ] {
2768            let mut bp = minimal_bp(None);
2769            bp.degradation_policy = Some(expected);
2770            let json = serde_json::to_string(&bp).expect("serializes");
2771            assert!(json.contains(&format!("\"degradation_policy\":\"{label}\"")));
2772            let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2773            assert_eq!(back.degradation_policy, Some(expected));
2774        }
2775    }
2776
2777    #[test]
2778    fn degradation_policy_rejects_unknown_variant() {
2779        let json = serde_json::json!({
2780            "schema_version": current_schema_version(),
2781            "id": "degradation-policy-unknown-variant-ut",
2782            "flow": { "kind": "seq", "children": [] },
2783            "degradation_policy": "ignore",
2784        });
2785        let err = serde_json::from_value::<Blueprint>(json).unwrap_err();
2786        assert!(
2787            err.to_string().contains("unknown variant"),
2788            "expected an unknown-variant rejection, got: {err}"
2789        );
2790    }
2791
2792    // ──────────────────────────────────────────────────────────────
2793    // GH #46 Milestone 2: `Runner`, `RunnerDef`, `WorkerModel`,
2794    // `Blueprint.runners` / `default_runner`, `AgentDef.runner` /
2795    // `runner_ref`, `resolve_runner`
2796    // ──────────────────────────────────────────────────────────────
2797
2798    fn agent_with_runner(
2799        name: &str,
2800        profile: Option<AgentProfile>,
2801        runner: Option<Runner>,
2802        runner_ref: Option<String>,
2803    ) -> AgentDef {
2804        AgentDef {
2805            name: name.to_string(),
2806            kind: AgentKind::RustFn,
2807            spec: serde_json::json!({ "fn_id": name }),
2808            profile,
2809            meta: None,
2810            runner,
2811            runner_ref,
2812            verdict: None,
2813            lints: None,
2814        }
2815    }
2816
2817    fn ws_runner(variant: &str, tools: Vec<&str>) -> Runner {
2818        Runner::WsClaudeCode {
2819            variant: variant.to_string(),
2820            tools: tools.into_iter().map(str::to_string).collect(),
2821        }
2822    }
2823
2824    fn agent_block_runner(tools: Vec<&str>) -> Runner {
2825        Runner::AgentBlockInProcess {
2826            tools: tools.into_iter().map(str::to_string).collect(),
2827        }
2828    }
2829
2830    // ─── round-trip byte-compat ─────────────────────────────────────
2831
2832    #[test]
2833    fn blueprint_without_runners_or_default_runner_deserializes_to_defaults() {
2834        let json = serde_json::json!({
2835            "schema_version": current_schema_version(),
2836            "id": "no-runners-ut",
2837            "flow": { "kind": "seq", "children": [] },
2838        });
2839        let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
2840        assert!(bp.runners.is_empty());
2841        assert_eq!(bp.default_runner, None);
2842    }
2843
2844    #[test]
2845    fn blueprint_runners_omitted_when_empty() {
2846        let bp = minimal_bp(None);
2847        let json = serde_json::to_value(&bp).expect("serializes");
2848        assert!(
2849            json.as_object().unwrap().get("runners").is_none(),
2850            "runners key must be absent when empty: {json}"
2851        );
2852        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2853        assert!(back.runners.is_empty());
2854        assert_eq!(bp, back);
2855    }
2856
2857    #[test]
2858    fn blueprint_runners_roundtrips_when_non_empty() {
2859        let mut bp = minimal_bp(None);
2860        bp.runners = vec![RunnerDef {
2861            name: "claude-worker".to_string(),
2862            runner: ws_runner("code-worker", vec!["Read", "Grep"]),
2863        }];
2864        let json = serde_json::to_string(&bp).expect("serializes");
2865        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
2866        assert_eq!(bp, back);
2867        assert_eq!(back.runners.len(), 1);
2868        assert_eq!(back.runners[0].name, "claude-worker");
2869    }
2870
2871    #[test]
2872    fn blueprint_default_runner_roundtrips_when_some() {
2873        let mut bp = minimal_bp(None);
2874        bp.default_runner = Some("claude-worker".to_string());
2875        let json = serde_json::to_value(&bp).expect("serializes");
2876        assert_eq!(json["default_runner"], "claude-worker");
2877        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2878        assert_eq!(back, bp);
2879    }
2880
2881    #[test]
2882    fn blueprint_default_runner_omitted_when_none() {
2883        let bp = minimal_bp(None);
2884        let json = serde_json::to_value(&bp).expect("serializes");
2885        assert!(
2886            json.as_object().unwrap().get("default_runner").is_none(),
2887            "default_runner key must be absent when None: {json}"
2888        );
2889        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
2890        assert_eq!(back, bp);
2891    }
2892
2893    #[test]
2894    fn blueprint_json_schema_exports_runners_and_default_runner() {
2895        let schema = schemars::schema_for!(Blueprint);
2896        let v = serde_json::to_value(&schema).expect("schema serializes");
2897        assert!(
2898            v["properties"]["runners"].is_object(),
2899            "runners must appear in the exported schema: {v}"
2900        );
2901        assert!(
2902            v["properties"]["default_runner"].is_object(),
2903            "default_runner must appear in the exported schema: {v}"
2904        );
2905        let dump = v.to_string();
2906        assert!(dump.contains("RunnerDef"), "RunnerDef definition in schema");
2907        assert!(dump.contains("Runner"), "Runner definition in schema");
2908    }
2909
2910    #[test]
2911    fn agent_def_runner_and_runner_ref_omitted_when_none() {
2912        let agent = agent_with_runner("scout", None, None, None);
2913        let json = serde_json::to_value(&agent).expect("serializes");
2914        let obj = json.as_object().unwrap();
2915        assert!(
2916            obj.get("runner").is_none(),
2917            "runner key must be absent when None: {json}"
2918        );
2919        assert!(
2920            obj.get("runner_ref").is_none(),
2921            "runner_ref key must be absent when None: {json}"
2922        );
2923        let back: AgentDef = serde_json::from_value(json).expect("deserializes");
2924        assert_eq!(back, agent);
2925    }
2926
2927    #[test]
2928    fn agent_def_runner_inline_roundtrips_when_some() {
2929        let agent = agent_with_runner("coder", None, Some(agent_block_runner(vec!["Bash"])), None);
2930        let json = serde_json::to_string(&agent).expect("serializes");
2931        let back: AgentDef = serde_json::from_str(&json).expect("deserializes");
2932        assert_eq!(back, agent);
2933    }
2934
2935    #[test]
2936    fn agent_def_runner_ref_roundtrips_when_some() {
2937        let agent = agent_with_runner("coder", None, None, Some("claude-worker".to_string()));
2938        let json = serde_json::to_value(&agent).expect("serializes");
2939        assert_eq!(json["runner_ref"], "claude-worker");
2940        let back: AgentDef = serde_json::from_value(json).expect("deserializes");
2941        assert_eq!(back, agent);
2942    }
2943
2944    #[test]
2945    fn agent_def_json_schema_exports_runner_and_runner_ref() {
2946        let schema = schemars::schema_for!(AgentDef);
2947        let v = serde_json::to_value(&schema).expect("schema serializes");
2948        let props = v["properties"].as_object().expect("object schema");
2949        for key in ["runner", "runner_ref"] {
2950            assert!(props.contains_key(key), "missing property: {key}");
2951        }
2952    }
2953
2954    #[test]
2955    fn runner_ws_claude_code_roundtrips_through_json_and_tags_backend() {
2956        let runner = ws_runner("code-worker", vec!["Read", "Grep"]);
2957        let json = serde_json::to_value(&runner).expect("serializes");
2958        assert_eq!(json["backend"], "ws_claude_code");
2959        assert_eq!(json["variant"], "code-worker");
2960        assert_eq!(json["tools"], serde_json::json!(["Read", "Grep"]));
2961        let back: Runner = serde_json::from_value(json).expect("deserializes");
2962        assert_eq!(back, runner);
2963    }
2964
2965    #[test]
2966    fn runner_ws_operator_roundtrips_through_json_and_tags_backend() {
2967        let runner = Runner::WsOperator {
2968            variant: "mse-worker-reviewer".to_string(),
2969            tools: vec!["Read".to_string(), "Grep".to_string()],
2970        };
2971        let json = serde_json::to_value(&runner).expect("serializes");
2972        assert_eq!(json["backend"], "ws_operator");
2973        assert_eq!(json["variant"], "mse-worker-reviewer");
2974        assert_eq!(json["tools"], serde_json::json!(["Read", "Grep"]));
2975        let back: Runner = serde_json::from_value(json).expect("deserializes");
2976        assert_eq!(back, runner);
2977    }
2978
2979    #[test]
2980    fn runner_agent_block_in_process_roundtrips_through_json_and_tags_backend() {
2981        let runner = agent_block_runner(vec!["Bash"]);
2982        let json = serde_json::to_value(&runner).expect("serializes");
2983        assert_eq!(json["backend"], "agent_block_in_process");
2984        assert_eq!(json["tools"], serde_json::json!(["Bash"]));
2985        let back: Runner = serde_json::from_value(json).expect("deserializes");
2986        assert_eq!(back, runner);
2987    }
2988
2989    #[test]
2990    fn runner_tools_omitted_when_empty() {
2991        let runner = ws_runner("code-worker", vec![]);
2992        let json = serde_json::to_value(&runner).expect("serializes");
2993        assert!(
2994            json.as_object().unwrap().get("tools").is_none(),
2995            "tools key must be absent when empty: {json}"
2996        );
2997        let back: Runner = serde_json::from_value(json).expect("deserializes");
2998        assert_eq!(back, runner);
2999    }
3000
3001    #[test]
3002    fn runner_rejects_unknown_field() {
3003        let json = serde_json::json!({
3004            "backend": "ws_claude_code",
3005            "variant": "x",
3006            "not_a_real_field": true,
3007        });
3008        let err = serde_json::from_value::<Runner>(json).unwrap_err();
3009        assert!(
3010            err.to_string().contains("not_a_real_field")
3011                || err.to_string().contains("unknown field"),
3012            "expected an unknown-field rejection, got: {err}"
3013        );
3014    }
3015
3016    #[test]
3017    fn runner_def_roundtrips_through_json() {
3018        let def = RunnerDef {
3019            name: "claude-worker".to_string(),
3020            runner: ws_runner("code-worker", vec!["Read"]),
3021        };
3022        let json = serde_json::to_value(&def).expect("serializes");
3023        let back: RunnerDef = serde_json::from_value(json).expect("deserializes");
3024        assert_eq!(back, def);
3025    }
3026
3027    // ─── GH #83: SubprocessDef / Runner::Subprocess ────────────────
3028
3029    fn sample_subprocess_def(name: &str) -> SubprocessDef {
3030        SubprocessDef {
3031            name: name.to_string(),
3032            argv: vec![
3033                "sh".to_string(),
3034                "-c".to_string(),
3035                "echo '{\"result\": \"ok\"}'".to_string(),
3036            ],
3037            stdin: Some("{prompt}".to_string()),
3038            env: std::collections::BTreeMap::from([("EXTRA".to_string(), "{task_id}".to_string())]),
3039            cwd: Some("{work_dir}".to_string()),
3040            output: Some(SubprocessOutput {
3041                format: Some("json".to_string()),
3042                result_ptr: Some("/result".to_string()),
3043                ok_from: Some("exit_code".to_string()),
3044                stats: None,
3045            }),
3046            stream_mode: None,
3047        }
3048    }
3049
3050    #[test]
3051    fn subprocess_def_roundtrips_through_json() {
3052        let def = sample_subprocess_def("echo-json");
3053        let json = serde_json::to_value(&def).expect("serializes");
3054        let back: SubprocessDef = serde_json::from_value(json).expect("deserializes");
3055        assert_eq!(back, def);
3056    }
3057
3058    #[test]
3059    fn subprocess_def_optional_fields_omitted_when_default() {
3060        let def = SubprocessDef {
3061            name: "min".to_string(),
3062            argv: vec!["cat".to_string()],
3063            stdin: None,
3064            env: Default::default(),
3065            cwd: None,
3066            output: None,
3067            stream_mode: None,
3068        };
3069        let json = serde_json::to_value(&def).expect("serializes");
3070        let obj = json.as_object().unwrap();
3071        for absent in ["stdin", "env", "cwd", "output", "stream_mode"] {
3072            assert!(
3073                !obj.contains_key(absent),
3074                "{absent} key must be absent when default: {json}"
3075            );
3076        }
3077        let back: SubprocessDef = serde_json::from_value(json).expect("deserializes");
3078        assert_eq!(back, def);
3079    }
3080
3081    #[test]
3082    fn subprocess_def_rejects_unknown_field() {
3083        let json = serde_json::json!({
3084            "name": "x",
3085            "argv": ["cat"],
3086            "not_a_real_field": true,
3087        });
3088        let err = serde_json::from_value::<SubprocessDef>(json).unwrap_err();
3089        assert!(
3090            err.to_string().contains("unknown field"),
3091            "expected an unknown-field rejection, got: {err}"
3092        );
3093    }
3094
3095    #[test]
3096    fn blueprint_subprocesses_defaults_to_empty_and_stays_off_the_wire() {
3097        // Pre-#83 BP JSON (no `subprocesses` key) deserializes to an empty registry.
3098        let bp = minimal_bp(None);
3099        let json = serde_json::to_value(&bp).expect("serializes");
3100        assert!(
3101            json.as_object().unwrap().get("subprocesses").is_none(),
3102            "subprocesses key must be absent when empty: {json}"
3103        );
3104        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
3105        assert!(back.subprocesses.is_empty());
3106    }
3107
3108    #[test]
3109    fn blueprint_subprocesses_roundtrips_when_declared() {
3110        let mut bp = minimal_bp(None);
3111        bp.subprocesses = vec![sample_subprocess_def("echo-json")];
3112        let json = serde_json::to_value(&bp).expect("serializes");
3113        assert_eq!(json["subprocesses"][0]["name"], "echo-json");
3114        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
3115        assert_eq!(back.subprocesses, bp.subprocesses);
3116    }
3117
3118    #[test]
3119    fn runner_subprocess_roundtrips_through_json_and_tags_backend() {
3120        // 1:1 name symmetry with AgentKind::Subprocess — tag must be "subprocess".
3121        let runner = Runner::Subprocess {
3122            template: "echo-json".to_string(),
3123            overrides: SubprocessOverrides {
3124                model: Some("small".to_string()),
3125                tools: vec!["Read".to_string()],
3126                cwd: Some("/tmp/wd".to_string()),
3127            },
3128        };
3129        let json = serde_json::to_value(&runner).expect("serializes");
3130        assert_eq!(json["backend"], "subprocess");
3131        assert_eq!(json["template"], "echo-json");
3132        assert_eq!(json["overrides"]["model"], "small");
3133        let back: Runner = serde_json::from_value(json).expect("deserializes");
3134        assert_eq!(back, runner);
3135    }
3136
3137    #[test]
3138    fn runner_subprocess_overrides_omitted_when_empty() {
3139        let runner = Runner::Subprocess {
3140            template: "echo-json".to_string(),
3141            overrides: SubprocessOverrides::default(),
3142        };
3143        let json = serde_json::to_value(&runner).expect("serializes");
3144        assert!(
3145            json.as_object().unwrap().get("overrides").is_none(),
3146            "overrides key must be absent when all-default: {json}"
3147        );
3148        let back: Runner = serde_json::from_value(json).expect("deserializes");
3149        assert_eq!(back, runner);
3150    }
3151
3152    #[test]
3153    fn resolve_runner_inline_subprocess_variant_resolves() {
3154        let inline = Runner::Subprocess {
3155            template: "echo-json".to_string(),
3156            overrides: SubprocessOverrides::default(),
3157        };
3158        let agent = agent_with_runner("headless", None, Some(inline.clone()), None);
3159        let mut bp = minimal_bp(None);
3160        bp.agents = vec![agent.clone()];
3161
3162        let resolved = resolve_runner(&bp, &agent).expect("resolves");
3163        assert_eq!(resolved, Some(inline));
3164    }
3165
3166    #[test]
3167    fn resolve_runner_registry_and_default_tiers_resolve_subprocess_variant() {
3168        let registry_runner = Runner::Subprocess {
3169            template: "echo-json".to_string(),
3170            overrides: SubprocessOverrides::default(),
3171        };
3172        // Tier 2: runner_ref → registry.
3173        let agent = agent_with_runner("headless", None, None, Some("proc-entry".to_string()));
3174        let mut bp = minimal_bp(None);
3175        bp.runners = vec![RunnerDef {
3176            name: "proc-entry".to_string(),
3177            runner: registry_runner.clone(),
3178        }];
3179        bp.agents = vec![agent.clone()];
3180        let resolved = resolve_runner(&bp, &agent).expect("resolves");
3181        assert_eq!(resolved, Some(registry_runner.clone()));
3182
3183        // Tier 4: default_runner alone.
3184        let bare = agent_with_runner("headless", None, None, None);
3185        bp.agents = vec![bare.clone()];
3186        bp.default_runner = Some("proc-entry".to_string());
3187        let resolved = resolve_runner(&bp, &bare).expect("resolves");
3188        assert_eq!(resolved, Some(registry_runner));
3189    }
3190
3191    #[test]
3192    fn bind_outcome_bound_roundtrips_through_json_and_tags_outcome() {
3193        let outcome = BindOutcome::Bound {
3194            receipt: BindReceipt {
3195                agent: "coder".to_string(),
3196                request_digest: BindingDigest::sha256("req"),
3197                provider_id: "mse-provider".to_string(),
3198                provider_revision: Some("1".to_string()),
3199                resolved_model: Some("claude-sonnet-4".to_string()),
3200                effective_tools: vec!["Read".to_string(), "Write".to_string()],
3201                launch_variant: Some("mse-coder".to_string()),
3202                capability_snapshot_digest: None,
3203            },
3204        };
3205        let json = serde_json::to_value(&outcome).expect("serializes");
3206        assert_eq!(json["outcome"], "bound");
3207        assert_eq!(json["receipt"]["agent"], "coder");
3208        let back: BindOutcome = serde_json::from_value(json).expect("deserializes");
3209        assert_eq!(back, outcome);
3210    }
3211
3212    #[test]
3213    fn bind_outcome_unbound_roundtrips_through_json_and_tags_outcome() {
3214        let outcome = BindOutcome::Unbound {
3215            agent: "coder".to_string(),
3216            reason: "no capability for launch variant".to_string(),
3217        };
3218        let json = serde_json::to_value(&outcome).expect("serializes");
3219        assert_eq!(json["outcome"], "unbound");
3220        assert_eq!(json["agent"], "coder");
3221        assert_eq!(json["reason"], "no capability for launch variant");
3222        let back: BindOutcome = serde_json::from_value(json).expect("deserializes");
3223        assert_eq!(back, outcome);
3224    }
3225
3226    #[test]
3227    fn bind_outcome_rejects_unknown_field() {
3228        let json = serde_json::json!({
3229            "outcome": "unbound",
3230            "agent": "coder",
3231            "reason": "gone",
3232            "not_a_real_field": true,
3233        });
3234        let err = serde_json::from_value::<BindOutcome>(json).unwrap_err();
3235        assert!(
3236            err.to_string().contains("not_a_real_field")
3237                || err.to_string().contains("unknown field"),
3238            "expected an unknown-field rejection, got: {err}"
3239        );
3240    }
3241
3242    #[test]
3243    fn compiler_strategy_strict_binding_defaults_false_and_omitted() {
3244        let strategy = CompilerStrategy::default();
3245        assert!(!strategy.strict_binding);
3246        // Absent in JSON deserializes back to false.
3247        let back: CompilerStrategy = serde_json::from_value(serde_json::json!({
3248            "strict_refs": true,
3249            "strict_kind": true,
3250        }))
3251        .expect("deserializes without strict_binding");
3252        assert!(!back.strict_binding);
3253    }
3254
3255    #[test]
3256    fn worker_model_roundtrips_through_json() {
3257        let model = WorkerModel {
3258            runner: agent_block_runner(vec!["Bash"]),
3259            agent: agent_with_runner("coder", None, None, None),
3260        };
3261        let json = serde_json::to_value(&model).expect("serializes");
3262        let back: WorkerModel = serde_json::from_value(json).expect("deserializes");
3263        assert_eq!(back, model);
3264    }
3265
3266    // ─── resolve_runner cascade precedence ─────────────────────────
3267
3268    #[test]
3269    fn resolve_runner_inline_wins_over_everything() {
3270        let inline = agent_block_runner(vec!["Bash"]);
3271        let profile = AgentProfile {
3272            worker_binding: Some("legacy-variant".to_string()),
3273            tools: vec!["Read".to_string()],
3274            ..Default::default()
3275        };
3276        let agent = agent_with_runner(
3277            "coder",
3278            Some(profile),
3279            Some(inline.clone()),
3280            Some("registry-entry".to_string()),
3281        );
3282        let mut bp = minimal_bp(None);
3283        bp.default_runner = Some("registry-entry".to_string());
3284        bp.runners = vec![RunnerDef {
3285            name: "registry-entry".to_string(),
3286            runner: ws_runner("other-variant", vec![]),
3287        }];
3288        bp.agents = vec![agent.clone()];
3289
3290        let resolved = resolve_runner(&bp, &agent).expect("resolves");
3291        assert_eq!(resolved, Some(inline));
3292    }
3293
3294    #[test]
3295    fn resolve_runner_runner_ref_wins_over_legacy_fallback() {
3296        let profile = AgentProfile {
3297            worker_binding: Some("legacy-variant".to_string()),
3298            tools: vec!["Read".to_string()],
3299            ..Default::default()
3300        };
3301        let registry_runner = ws_runner("registry-variant", vec!["Grep"]);
3302        let agent = agent_with_runner(
3303            "coder",
3304            Some(profile),
3305            None,
3306            Some("registry-entry".to_string()),
3307        );
3308        let mut bp = minimal_bp(None);
3309        bp.runners = vec![RunnerDef {
3310            name: "registry-entry".to_string(),
3311            runner: registry_runner.clone(),
3312        }];
3313        bp.agents = vec![agent.clone()];
3314
3315        let resolved = resolve_runner(&bp, &agent).expect("resolves");
3316        assert_eq!(resolved, Some(registry_runner));
3317    }
3318
3319    #[test]
3320    fn resolve_runner_legacy_fallback_wins_over_default_runner() {
3321        let profile = AgentProfile {
3322            worker_binding: Some("legacy-variant".to_string()),
3323            tools: vec!["Read".to_string(), "Grep".to_string()],
3324            ..Default::default()
3325        };
3326        let agent = agent_with_runner("coder", Some(profile), None, None);
3327        let mut bp = minimal_bp(None);
3328        bp.default_runner = Some("registry-entry".to_string());
3329        bp.runners = vec![RunnerDef {
3330            name: "registry-entry".to_string(),
3331            runner: agent_block_runner(vec!["Bash"]),
3332        }];
3333        bp.agents = vec![agent.clone()];
3334
3335        let resolved = resolve_runner(&bp, &agent).expect("resolves");
3336        assert_eq!(
3337            resolved,
3338            Some(ws_runner("legacy-variant", vec!["Read", "Grep"]))
3339        );
3340    }
3341
3342    #[test]
3343    fn resolve_runner_default_runner_alone_when_no_agent_level_declaration() {
3344        let agent = agent_with_runner("coder", None, None, None);
3345        let mut bp = minimal_bp(None);
3346        bp.default_runner = Some("registry-entry".to_string());
3347        bp.runners = vec![RunnerDef {
3348            name: "registry-entry".to_string(),
3349            runner: agent_block_runner(vec!["Bash"]),
3350        }];
3351        bp.agents = vec![agent.clone()];
3352
3353        let resolved = resolve_runner(&bp, &agent).expect("resolves");
3354        assert_eq!(resolved, Some(agent_block_runner(vec!["Bash"])));
3355    }
3356
3357    #[test]
3358    fn resolve_runner_none_when_nothing_declared_through_any_tier() {
3359        let agent = agent_with_runner("coder", None, None, None);
3360        let bp = minimal_bp(None);
3361
3362        let resolved = resolve_runner(&bp, &agent).expect("resolves");
3363        assert_eq!(resolved, None);
3364    }
3365
3366    #[test]
3367    fn resolve_runner_unknown_runner_ref_errs() {
3368        let agent = agent_with_runner("coder", None, None, Some("no-such-entry".to_string()));
3369        let mut bp = minimal_bp(None);
3370        bp.runners = vec![RunnerDef {
3371            name: "registry-entry".to_string(),
3372            runner: agent_block_runner(vec![]),
3373        }];
3374        bp.agents = vec![agent.clone()];
3375
3376        let err = resolve_runner(&bp, &agent).expect_err("unresolved runner_ref");
3377        assert_eq!(
3378            err,
3379            RunnerResolveError::UnknownRunnerRef {
3380                agent: "coder".to_string(),
3381                ref_name: "no-such-entry".to_string(),
3382                available: vec!["registry-entry".to_string()],
3383            }
3384        );
3385    }
3386
3387    #[test]
3388    fn resolve_runner_unknown_default_runner_errs() {
3389        let agent = agent_with_runner("coder", None, None, None);
3390        let mut bp = minimal_bp(None);
3391        bp.default_runner = Some("no-such-entry".to_string());
3392        bp.runners = vec![RunnerDef {
3393            name: "registry-entry".to_string(),
3394            runner: agent_block_runner(vec![]),
3395        }];
3396        bp.agents = vec![agent.clone()];
3397
3398        let err = resolve_runner(&bp, &agent).expect_err("unresolved default_runner");
3399        assert_eq!(
3400            err,
3401            RunnerResolveError::UnknownDefaultRunner {
3402                ref_name: "no-such-entry".to_string(),
3403                available: vec!["registry-entry".to_string()],
3404            }
3405        );
3406    }
3407
3408    #[test]
3409    fn bound_agent_digest_is_stable_and_tracks_runner_changes() {
3410        let agent = agent_with_runner(
3411            "coder",
3412            None,
3413            Some(ws_runner("worker-a", vec!["Read"])),
3414            None,
3415        );
3416        let mut bp = minimal_bp(None);
3417        bp.agents = vec![agent];
3418
3419        let first = resolve_bound_agents(&bp).expect("binds");
3420        let second = resolve_bound_agents(&bp).expect("binds again");
3421        assert_eq!(first[0].binding_digest, second[0].binding_digest);
3422        assert!(first[0].binding_digest.as_str().starts_with("sha256:"));
3423        assert_eq!(first[0].binding_digest.as_str().len(), 71);
3424        assert_eq!(first[0].runner_source, RunnerResolutionSource::AgentInline);
3425
3426        bp.agents[0].runner = Some(ws_runner("worker-b", vec!["Read"]));
3427        let changed = resolve_bound_agents(&bp).expect("binds changed runner");
3428        assert_ne!(first[0].binding_digest, changed[0].binding_digest);
3429    }
3430
3431    #[test]
3432    fn bound_agent_pins_effective_context_policy_and_full_agent() {
3433        let mut agent = agent_with_runner("scout", None, None, None);
3434        agent.profile = Some(AgentProfile {
3435            system_prompt: "inspect carefully".to_string(),
3436            ..Default::default()
3437        });
3438        let mut bp = minimal_bp(None);
3439        bp.default_context_policy = Some(ContextPolicy {
3440            include: Some(vec!["task".to_string()]),
3441            ..Default::default()
3442        });
3443        bp.agents = vec![agent];
3444
3445        let bound = resolve_bound_agents(&bp).expect("binds").remove(0);
3446        assert_eq!(
3447            bound.agent.profile.unwrap().system_prompt,
3448            "inspect carefully"
3449        );
3450        assert_eq!(
3451            bound.context_policy.unwrap().include,
3452            Some(vec!["task".to_string()])
3453        );
3454        assert_eq!(bound.runner_source, RunnerResolutionSource::None);
3455    }
3456
3457    #[test]
3458    fn strict_bound_agent_resolution_rejects_legacy_worker_binding() {
3459        let profile = AgentProfile {
3460            worker_binding: Some("legacy-worker".to_string()),
3461            ..Default::default()
3462        };
3463        let mut bp = minimal_bp(None);
3464        bp.agents = vec![agent_with_runner("coder", Some(profile), None, None)];
3465
3466        let err = resolve_bound_agents_strict(&bp).expect_err("legacy must fail closed");
3467        assert!(matches!(
3468            err,
3469            BoundAgentResolveError::LegacyWorkerBindingDisabled { agent } if agent == "coder"
3470        ));
3471    }
3472
3473    #[test]
3474    fn binding_digest_is_a_validated_transparent_string() {
3475        use std::str::FromStr as _;
3476
3477        let digest = BindingDigest::sha256(b"same snapshot");
3478        let json = serde_json::to_value(&digest).expect("serializes");
3479        assert_eq!(json, serde_json::Value::String(digest.to_string()));
3480        assert_eq!(
3481            serde_json::from_value::<BindingDigest>(json).expect("deserializes"),
3482            digest
3483        );
3484        for invalid in [
3485            "deadbeef",
3486            "sha256:abc",
3487            "sha256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
3488            "blake3:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
3489        ] {
3490            assert!(
3491                BindingDigest::from_str(invalid).is_err(),
3492                "accepted {invalid}"
3493            );
3494        }
3495    }
3496
3497    #[test]
3498    fn capability_snapshot_digest_accepts_the_legacy_wire_name() {
3499        let digest = BindingDigest::sha256("capabilities");
3500        let capability: AgentProviderCapability = serde_json::from_value(serde_json::json!({
3501            "launch_variant": "coder",
3502            "effective_tools": ["Read"],
3503            "evidence_digest": digest,
3504        }))
3505        .expect("legacy manifest remains readable");
3506        assert_eq!(capability.capability_snapshot_digest, Some(digest.clone()));
3507
3508        let serialized = serde_json::to_value(capability).expect("serialize new wire shape");
3509        assert_eq!(serialized["capability_snapshot_digest"], digest.to_string());
3510        assert!(serialized.get("evidence_digest").is_none());
3511    }
3512
3513    // ──────────────────────────────────────────────────────────────
3514    // GH #50: `AgentDef.verdict` / `VerdictContract` / `VerdictChannel`
3515    // ──────────────────────────────────────────────────────────────
3516
3517    #[test]
3518    fn verdict_contract_roundtrips_body_channel() {
3519        let json = serde_json::json!({"channel": "body", "values": ["PASS", "BLOCKED"]});
3520        let contract: VerdictContract = serde_json::from_value(json.clone()).expect("deserializes");
3521        assert_eq!(contract.channel, VerdictChannel::Body);
3522        assert_eq!(
3523            contract.values,
3524            vec!["PASS".to_string(), "BLOCKED".to_string()]
3525        );
3526        assert_eq!(serde_json::to_value(&contract).expect("serializes"), json);
3527    }
3528
3529    #[test]
3530    fn verdict_contract_roundtrips_part_channel() {
3531        let json = serde_json::json!({"channel": "part", "values": ["ALLOW"]});
3532        let contract: VerdictContract = serde_json::from_value(json.clone()).expect("deserializes");
3533        assert_eq!(contract.channel, VerdictChannel::Part);
3534        assert_eq!(serde_json::to_value(&contract).expect("serializes"), json);
3535    }
3536
3537    #[test]
3538    fn agent_def_verdict_omitted_when_none() {
3539        let agent = agent_with_runner("gate", None, None, None);
3540        let json = serde_json::to_value(&agent).expect("serializes");
3541        assert!(
3542            json.as_object().unwrap().get("verdict").is_none(),
3543            "verdict key must be absent when None: {json}"
3544        );
3545        let back: AgentDef = serde_json::from_value(json).expect("deserializes");
3546        assert_eq!(back.verdict, None);
3547    }
3548
3549    #[test]
3550    fn agent_def_verdict_roundtrips_when_some() {
3551        let mut agent = agent_with_runner("gate", None, None, None);
3552        agent.verdict = Some(VerdictContract {
3553            channel: VerdictChannel::Body,
3554            values: vec!["PASS".to_string(), "BLOCKED".to_string()],
3555        });
3556        let json = serde_json::to_value(&agent).expect("serializes");
3557        let back: AgentDef = serde_json::from_value(json).expect("deserializes");
3558        assert_eq!(back.verdict, agent.verdict);
3559    }
3560
3561    /// Acceptance criterion #2: the `02-verdict-loop.json` sample (no
3562    /// `verdict` field on any of its agents) must still deserialize
3563    /// unchanged under the new `#[serde(deny_unknown_fields)]`-constrained
3564    /// `AgentDef` — `verdict` is `#[serde(default)]`, so its absence is not
3565    /// an error.
3566    #[test]
3567    fn existing_verdict_loop_sample_deserializes_with_verdict_omitted() {
3568        const SAMPLE: &str =
3569            include_str!("../../mlua-swarm-cli/src/mcp/resources/samples/02-verdict-loop.json");
3570        let bp: Blueprint = serde_json::from_str(SAMPLE).expect("sample deserializes");
3571        assert_eq!(bp.agents.len(), 6);
3572        assert!(
3573            bp.agents.iter().all(|a| a.verdict.is_none()),
3574            "no agent in the sample declares a verdict contract"
3575        );
3576    }
3577
3578    // ──────────────────────────────────────────────────────────────
3579    // CheckPolicy enum relocation + Blueprint.check_policy
3580    // (T1: schema round-trip / omit→None / invalid→error)
3581    // ──────────────────────────────────────────────────────────────
3582
3583    /// The wire form is snake_case and byte-identical to the pre-relocation
3584    /// enum (`"silent"` / `"warn"` / `"strict"`), round-tripping in both
3585    /// directions — the relocation must not change the serde surface.
3586    #[test]
3587    fn check_policy_wire_form_round_trips() {
3588        for (variant, wire) in [
3589            (CheckPolicy::Silent, "silent"),
3590            (CheckPolicy::Warn, "warn"),
3591            (CheckPolicy::Strict, "strict"),
3592        ] {
3593            let json = serde_json::to_value(variant).expect("serializes");
3594            assert_eq!(json, serde_json::json!(wire), "wire form for {variant:?}");
3595            let back: CheckPolicy = serde_json::from_value(json).expect("deserializes");
3596            assert_eq!(back, variant, "round-trip for {variant:?}");
3597        }
3598    }
3599
3600    /// The default is `Warn` (preserves the pre-CheckPolicy fail-open
3601    /// behaviour of every submit-time projection sink).
3602    #[test]
3603    fn check_policy_default_is_warn() {
3604        assert_eq!(CheckPolicy::default(), CheckPolicy::Warn);
3605    }
3606
3607    /// A Blueprint that declares `check_policy: "strict"` parses to
3608    /// `Some(Strict)` and re-serializes with the same snake_case literal.
3609    #[test]
3610    fn blueprint_check_policy_strict_round_trips() {
3611        let json = serde_json::json!({
3612            "schema_version": current_schema_version(),
3613            "id": "check-policy-strict-ut",
3614            "flow": { "kind": "seq", "children": [] },
3615            "check_policy": "strict",
3616        });
3617        let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
3618        assert_eq!(bp.check_policy, Some(CheckPolicy::Strict));
3619        let re = serde_json::to_string(&bp).expect("serializes");
3620        assert!(
3621            re.contains("\"check_policy\":\"strict\""),
3622            "re-serialized BP must preserve the snake_case wire literal: {re}"
3623        );
3624    }
3625
3626    /// An omitted `check_policy` parses to `None` and is skipped on
3627    /// serialize (backward-compat with every pre-cascade Blueprint).
3628    #[test]
3629    fn blueprint_check_policy_omitted_is_none() {
3630        let json = serde_json::json!({
3631            "schema_version": current_schema_version(),
3632            "id": "check-policy-omitted-ut",
3633            "flow": { "kind": "seq", "children": [] },
3634        });
3635        let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
3636        assert_eq!(bp.check_policy, None);
3637
3638        let out = serde_json::to_value(&bp).expect("serializes");
3639        assert!(
3640            out.as_object().unwrap().get("check_policy").is_none(),
3641            "check_policy key must be absent when None: {out}"
3642        );
3643    }
3644
3645    /// An invalid `check_policy` value is a hard parse error (not silently
3646    /// dropped) — the enum is closed to the three snake_case variants. This
3647    /// also confirms `deny_unknown_fields` is not the gate here: the field
3648    /// IS known, only its value is invalid.
3649    #[test]
3650    fn blueprint_check_policy_invalid_value_errors() {
3651        let json = serde_json::json!({
3652            "schema_version": current_schema_version(),
3653            "id": "check-policy-invalid-ut",
3654            "flow": { "kind": "seq", "children": [] },
3655            "check_policy": "loud",
3656        });
3657        let err = serde_json::from_value::<Blueprint>(json)
3658            .expect_err("an unknown check_policy value must be rejected");
3659        let msg = err.to_string();
3660        assert!(
3661            msg.contains("check_policy") || msg.contains("loud") || msg.contains("variant"),
3662            "error should point at the bad check_policy value: {msg}"
3663        );
3664    }
3665
3666    #[test]
3667    fn agent_provider_manifest_round_trips_and_rejects_unknown_fields() {
3668        let json = serde_json::json!({
3669            "provider_id": "main-ai-self-report",
3670            "provider_revision": "1",
3671            "capabilities": [{
3672                "launch_variant": "mse-coder",
3673                "resolved_model": "claude-sonnet-4",
3674                "effective_tools": ["Read", "Edit"]
3675            }]
3676        });
3677        let manifest: AgentProviderManifest =
3678            serde_json::from_value(json.clone()).expect("manifest deserializes");
3679        assert_eq!(serde_json::to_value(manifest).unwrap(), json);
3680
3681        let invalid = serde_json::json!({
3682            "provider_id": "main-ai-self-report",
3683            "capabilities": [],
3684            "platform_secret": true
3685        });
3686        assert!(serde_json::from_value::<AgentProviderManifest>(invalid).is_err());
3687    }
3688
3689    // ──────────────────────────────────────────────────────────────
3690    // Lint suppression: `LintSetting`, `AgentDef.lints`,
3691    // `BlueprintMetadata.lints`
3692    // ──────────────────────────────────────────────────────────────
3693
3694    /// The wire form is the lowercase rustc attribute spelling — the diag
3695    /// crate's twin enum parses the same three literals.
3696    #[test]
3697    fn lint_setting_wire_form_round_trips_lowercase() {
3698        for (variant, wire) in [
3699            (LintSetting::Allow, "allow"),
3700            (LintSetting::Warn, "warn"),
3701            (LintSetting::Deny, "deny"),
3702        ] {
3703            let json = serde_json::to_value(variant).expect("serializes");
3704            assert_eq!(json, serde_json::json!(wire), "wire form for {variant:?}");
3705            let back: LintSetting = serde_json::from_value(json).expect("deserializes");
3706            assert_eq!(back, variant, "round-trip for {variant:?}");
3707        }
3708    }
3709
3710    /// Values are typed: an unrecognized *value* is a hard parse error
3711    /// (unrecognized *keys* are lenient by design — they surface as the
3712    /// `unknown-lint-kind` meta-lint at consumption time).
3713    #[test]
3714    fn lint_setting_invalid_value_errors() {
3715        let err = serde_json::from_value::<LintSetting>(serde_json::json!("forbid"))
3716            .expect_err("an unknown LintSetting value must be rejected");
3717        assert!(
3718            err.to_string().contains("forbid") || err.to_string().contains("variant"),
3719            "error should point at the bad value: {err}"
3720        );
3721    }
3722
3723    #[test]
3724    fn agent_def_lints_omitted_when_none() {
3725        let agent = agent_with_runner("gate", None, None, None);
3726        let json = serde_json::to_value(&agent).expect("serializes");
3727        assert!(
3728            json.as_object().unwrap().get("lints").is_none(),
3729            "lints key must be absent when None: {json}"
3730        );
3731        let back: AgentDef = serde_json::from_value(json).expect("deserializes");
3732        assert_eq!(back.lints, None);
3733    }
3734
3735    /// All three key forms (kind literal / `category:` group / `all`)
3736    /// survive the round-trip — key validation happens at consumption
3737    /// time, so serde accepts every string here.
3738    #[test]
3739    fn agent_def_lints_round_trips_every_key_form() {
3740        let mut agent = agent_with_runner("planner", None, None, None);
3741        agent.lints = Some(BTreeMap::from([
3742            ("agent-md-size".to_string(), LintSetting::Allow),
3743            ("category:style".to_string(), LintSetting::Warn),
3744            ("all".to_string(), LintSetting::Deny),
3745        ]));
3746        let json = serde_json::to_value(&agent).expect("serializes");
3747        assert_eq!(json["lints"]["agent-md-size"], "allow");
3748        assert_eq!(json["lints"]["category:style"], "warn");
3749        assert_eq!(json["lints"]["all"], "deny");
3750        let back: AgentDef = serde_json::from_value(json).expect("deserializes");
3751        assert_eq!(back.lints, agent.lints);
3752    }
3753
3754    /// The per-agent layer is top-level, never folded into
3755    /// `profile.extras` (which stays the engine-untouched free-form
3756    /// contract).
3757    #[test]
3758    fn agent_def_lints_stay_out_of_profile_extras() {
3759        let mut agent = agent_with_runner("planner", None, None, None);
3760        agent.profile = Some(AgentProfile::default());
3761        agent.lints = Some(BTreeMap::from([(
3762            "agent-md-size".to_string(),
3763            LintSetting::Allow,
3764        )]));
3765        let json = serde_json::to_value(&agent).expect("serializes");
3766        assert!(
3767            json["lints"].is_object(),
3768            "lints is a top-level key: {json}"
3769        );
3770        assert!(
3771            json["profile"]["extras"].get("lints").is_none(),
3772            "extras must stay untouched: {json}"
3773        );
3774    }
3775
3776    #[test]
3777    fn blueprint_metadata_lints_omitted_when_none() {
3778        let bp = minimal_bp(None);
3779        let json = serde_json::to_value(&bp).expect("serializes");
3780        assert!(
3781            json["metadata"].as_object().unwrap().get("lints").is_none(),
3782            "metadata.lints key must be absent when None: {json}"
3783        );
3784        let back: Blueprint = serde_json::from_value(json).expect("deserializes");
3785        assert_eq!(back.metadata.lints, None);
3786        assert_eq!(bp, back);
3787    }
3788
3789    #[test]
3790    fn blueprint_metadata_lints_round_trips_when_some() {
3791        let mut bp = minimal_bp(None);
3792        bp.metadata.lints = Some(BTreeMap::from([
3793            ("verdict-value-unhandled".to_string(), LintSetting::Deny),
3794            ("category:migration".to_string(), LintSetting::Allow),
3795        ]));
3796        let json = serde_json::to_string(&bp).expect("serializes");
3797        let back: Blueprint = serde_json::from_str(&json).expect("deserializes");
3798        assert_eq!(back.metadata.lints, bp.metadata.lints);
3799        assert_eq!(bp, back);
3800    }
3801
3802    /// A Blueprint written before this field parses unchanged — both
3803    /// `lints` maps are `#[serde(default)]`.
3804    #[test]
3805    fn lints_absent_on_both_layers_deserializes_to_none() {
3806        let json = serde_json::json!({
3807            "schema_version": current_schema_version(),
3808            "id": "lints-absent-ut",
3809            "flow": { "kind": "seq", "children": [] },
3810            "agents": [{ "name": "greeter", "kind": "rust_fn" }],
3811            "metadata": { "description": "no lints declared" },
3812        });
3813        let bp: Blueprint = serde_json::from_value(json).expect("deserializes");
3814        assert_eq!(bp.metadata.lints, None);
3815        assert_eq!(bp.agents[0].lints, None);
3816    }
3817
3818    #[test]
3819    fn blueprint_json_schema_exports_lints_on_both_layers() {
3820        let schema = schemars::schema_for!(Blueprint);
3821        let v = serde_json::to_value(&schema).expect("schema serializes");
3822        let dump = v.to_string();
3823        assert!(
3824            dump.contains("LintSetting"),
3825            "LintSetting definition must reach the exported schema: {dump}"
3826        );
3827        for def in ["AgentDef", "BlueprintMetadata"] {
3828            assert!(
3829                v["definitions"][def]["properties"]["lints"].is_object()
3830                    || v["$defs"][def]["properties"]["lints"].is_object(),
3831                "{def}.lints must appear in the exported schema: {dump}"
3832            );
3833        }
3834    }
3835}