Skip to main content

mlua_swarm/worker/agent_block/
runtime.rs

1//! [`AgentBlockInProcessSpawnerFactory`] — in-process headless LLM
2//! agent execution over the `agent-block-core` SDK.
3//!
4//! ## Design responsibility — a state-less factory
5//!
6//! The factory is a **kind-level general-purpose builder** — the
7//! process-wide infrastructure layer. It does not carry per-agent
8//! specialisation (script / `system_prompt` / tools); all agent
9//! specialisation belongs to `AgentDef.spec` + `AgentDef.profile`. The
10//! old `default_script_path` / `default_project_root` fields were
11//! removed — they were the collision source when a single process
12//! hosts multiple agent.md files.
13//!
14//! ## Two modes (via `ScriptSource`)
15//!
16//! | Mode | Trigger | Chunk |
17//! |---|---|---|
18//! | **PromptBasedAgent** (default) | `spec.script_path` absent | `ScriptSource::Inline` — the invoker [`build_inline_agent_invoker`] generates, which calls the SDK's `agent` StdPkg module with the resolved `mcp_servers` embedded. NOT the SDK's own `DefaultAgent`: that one passes no tools, so a frontmatter `tools:` line could never reach the model. |
19//! | **ScriptBasedAgent** | `spec.script_path = "<path>"` | `ScriptSource::Path(...)` — a caller-provided Lua script, handed to the SDK verbatim. |
20//!
21//! Neither mode requires the script to agree on an event-kind string: the
22//! `host_handler` sink takes any kind as the terminal result (see
23//! "Per-task input and result" below for the one reserved exception).
24//!
25//! `profile.system_prompt` (the agent.md body) is injected into the
26//! `_CONTEXT` Lua global through `BlockConfig.context`, and applies to
27//! both modes.
28//!
29//! ## Spec shape (`AgentDef.spec`)
30//!
31//! This is the settled `spec` contract for `AgentKind::AgentBlock` (GH
32//! #86) — every key is optional, and every key the factory reads is
33//! listed here:
34//!
35//! ```jsonc
36//! {
37//!   "project_root": "<path>",          // optional, default = std::env::current_dir()
38//!   "script_path": "<path>",           // optional; absent => PromptBasedAgent mode
39//!   "mcp_rpc_timeout_ms": 30000,       // optional, default = 30s
40//!   "mcp_servers": [                   // optional; the pool the tool grant selects from
41//!     { "name": "outline", "command": "outline-mcp", "args": [] }
42//!   ]
43//! }
44//! ```
45//!
46//! ## Tool grant (GH #86)
47//!
48//! The factory reads the effective tool set off `profile.tools` — which
49//! is **already** the resolved `Runner::AgentBlockInProcess.tools`
50//! whenever the agent declares that Runner, because
51//! `compiler::project_bound_agent_for_legacy_factories` overwrites
52//! `profile.tools` from the immutable `BoundAgent` snapshot (including
53//! with an empty list, so a Blueprint can revoke an agent.md's inherited
54//! `tools:` line). No Runner declared → the agent.md line stands. There
55//! is deliberately no build hint for this axis: re-deriving the Runner
56//! here would bypass the pinned snapshot and let a `Blueprint.runners`
57//! edit change an in-flight Run's grant on resume.
58//!
59//! Enforcement is per mode:
60//!
61//! | Mode | Enforcement |
62//! |---|---|
63//! | PromptBasedAgent | Enforced at **server** granularity. Only the `spec.mcp_servers` entries named by an `mcp__<server>__<tool>` entry of the effective set are embedded into the invoker ([`resolve_needed_mcp_servers`]), so the LLM cannot reach an unlisted server — but it CAN reach every tool of a listed one (the SDK exposes a connected server's full tool list). Grant per server, not per tool. |
64//! | ScriptBasedAgent | Not enforceable — the script drives its own `mcp.connect`. Declared `mcp__` entries are therefore **rejected at compile time** rather than silently ignored; drop them and let the script own its connections. |
65//!
66//! Non-`mcp__`-prefixed names (`Read` / `Write` / `WebSearch`) do not
67//! select an MCP server and are inert in both modes (see
68//! [`mcp_tools_of`]) — the `opts.extra_tools` carry noted on
69//! [`resolve_needed_mcp_servers`].
70//!
71//! ## Per-task input and result (GH #86)
72//!
73//! Task context reaches this backend through **one seam**:
74//! [`WorkerInvocation::context`], the in-process twin of
75//! `WorkerPayload.context`, filled once by `InProcSpawner::spawn` from the
76//! materialized [`AgentContextView`]. Nothing here peeks at `Ctx`
77//! directly, and no `SpawnerAdapter` wrapper re-resolves it — every
78//! Lua-visible surface below is derived from that one value:
79//!
80//! | Lua surface | Source |
81//! |---|---|
82//! | `_PROMPT` | The step's evaluated `in`, via `inv.prompt` → `BlockConfig.prompt`. A **String** — a structured `in` arrives JSON-stringified, so a script that wants a table calls `std.json.decode(_PROMPT)`. |
83//! | `_CONTEXT` | `profile.system_prompt`, via `BlockConfig.context`. |
84//! | [`TASK_METADATA_GLOBAL`] (`_TASK_METADATA`) | `view.task_metadata` (the launch's `init_ctx.task_metadata` bag), set through the SDK's `extra_globals` — converted natively, so nesting survives and the chunk text is never rewritten. |
85//! | [`AGENT_CTX_GLOBAL`] (`_AGENT_CTX`) | `view.extra` — the Blueprint-declared agent context (`default_agent_ctx` / `AgentMeta.ctx`, GH #21) after `ContextPolicy` filtering. |
86//!
87//! Both come from [`context_globals`], the single place this mapping is
88//! decided; the Lua in-process worker renders the same two globals from
89//! it, so a gate is portable between the two backends. `view.steps`
90//! (prior-step OUTPUT pointers) is deliberately NOT rendered — see the
91//! carrier note in [`crate::core::agent_context`].
92//!
93//! No server-process env is involved in any of them. The per-task working
94//! directory is not a Lua global — it becomes the SDK's `project_root`
95//! (see the next section), which surfaces to a script as
96//! `std.env.project_root()` and as the default cwd of `sh.exec` and of
97//! MCP servers spawned by `mcp.connect`. It does NOT `chdir` the host
98//! process, so a bare `io.open("rel/path")` still resolves against the
99//! server's own cwd.
100//!
101//! A script returns its result by calling `bus.emit(<kind>, payload)` —
102//! **not** by returning a value from the chunk. Two destinations:
103//!
104//! | emit kind | Effect |
105//! |---|---|
106//! | [`ARTIFACT_EVENT_KIND`] (`artifact`) | Stages a named part through [`WorkerInvocation::sink`] (`{name = ..., content = ...}`) and leaves the invocation running. Any number of these. |
107//! | anything else | The terminal result, **first emit wins**. [`WorkerResultCaptor`] normalises the payload into [`WorkerResult`]`.value` (`payload.content` → `payload.response` → the whole payload). |
108//!
109//! Both verdict channels are therefore reachable:
110//! `VerdictChannel::Body` compares the terminal value, and
111//! `VerdictChannel::Part` compares a staged `"verdict"` part — stage it
112//! with `bus.emit("artifact", {name = "verdict", content = "PASS"})`
113//! before the terminal emit, and the plain body stays free for the
114//! report.
115//!
116//! ## `project_root` resolution (issue #17, GH #20)
117//!
118//! `spec.project_root` (above) is only the **compile-time fallback**
119//! tier — resolved once in [`AgentBlockInProcessSpawnerFactory::build`],
120//! before any `Ctx` exists. Per invocation, [`resolve_project_root`]
121//! applies the task-context tier off [`WorkerInvocation::context`] (GH
122//! #20 Contract C — see [`crate::core::agent_context`] for the full
123//! narrative) with this priority (highest first):
124//!
125//! 1. `view.work_dir` — Task-level, set by `TaskInputMiddleware` from
126//!    the launch's `init_ctx.work_dir`.
127//! 2. `view.project_root` — same middleware, `init_ctx.project_root`.
128//! 3. `spec.project_root` / `std::env::current_dir()` (the compile-time
129//!    fallback baked into [`AgentBlockSettings`] above).
130//!
131//! This lets a single Blueprint's `AgentDef.spec.project_root` (fixed at
132//! compile time) be overridden per task launch, so the same Blueprint
133//! can run against different caller-supplied project roots without a
134//! `spec` edit.
135//!
136//! ## SDK paths introduced from v0.22.0 through v0.27.0
137//!
138//! | Version | Feature | Use case |
139//! |---|---|---|
140//! | v0.22.0 | `bus.emit(kind, payload, id?)` Lua bridge | script → host event push |
141//! | v0.23.0 | `BlockConfig.host_handlers` | Pre-install a Rust handler on the EventBus |
142//! | v0.24.0 | `BlockConfig.auto_serve_bus` | SDK embed drives the dispatcher in the background |
143//! | v0.25.0 | `BlockConfig.shutdown_token` + `BlockError::Cancelled` + `Send` on `run()` | `tokio::spawn` and external cancel |
144//! | v0.26.0 | `ScriptSource` / `PromptSource` / `SecretKeySource` enums plus the embedded `DefaultAgent` invoker (breaking) | Script becomes optional at the SDK level |
145//! | v0.27.0 | Embed the `compile_loop` StdPkg into core | `require("compile_loop")` hits directly |
146
147use crate::core::agent_context::AgentContextView;
148use crate::worker::adapter::{InProcSpawner, WorkerError, WorkerInvocation, WorkerResult};
149use agent_block_core::bus::dispatcher::Handler;
150use agent_block_core::host::{PromptSource, ScriptSource};
151use agent_block_core::{run, BlockConfig};
152use agent_block_types::error::BlockError;
153use async_trait::async_trait;
154use serde_json::Value;
155use std::collections::HashMap;
156use std::path::{Path, PathBuf};
157use std::sync::{Arc, Mutex};
158use std::time::Duration;
159use tokio::sync::oneshot;
160
161/// Host-side handler that fires when the Lua script (or the
162/// DefaultAgent invoker) calls `bus.emit(<kind>, payload)`. It folds
163/// the payload into a [`WorkerResult`] and forwards it on the
164/// [`oneshot::Sender`].
165///
166/// This is **an AgentBlock-internal helper**. Different SDK paths use
167/// different event names and payload shapes — the DefaultAgent
168/// invoker's `agent_result` event carries the entire `agent.run`
169/// return value (`{content, messages, num_turns, ok, usage}`), while a
170/// caller script's `worker_result` event carries `{ok, response}`. The
171/// captor keeps those quirks contained and **normalises them**, so
172/// callers (flow.ir, the engine, higher-level Workers) always see the
173/// same single form: "the raw LLM response is `WorkerResult.value`".
174///
175/// Value extraction priority (the normalisation policy that hides the
176/// SDK quirks):
177///
178/// 1. `payload.content` — from the DefaultAgent invoker / `agent.run`
179///    return value; carried as a string.
180/// 2. `payload.response` — the caller script's `worker_result`
181///    convention; free-form.
182/// 3. Fallback: the whole payload — for custom shapes that carry
183///    neither of the above.
184///
185/// `ok` extraction: `payload.ok` if present, otherwise `true` — the
186/// DefaultAgent invoker includes `ok`, so this recovers it.
187///
188/// This is the core of the observation #2 fix. The previous
189/// implementation did not consult (1); it only fell back
190/// `(2) → (3)`. On the DefaultAgent path that pushed the whole
191/// `agent_result` object into `WorkerResult.value`, which then rode
192/// through the chain and hit the next step's prompt via
193/// JSON-stringification — burning 50-60% of the tokens on
194/// boilerplate. Pulling out (1) first normalises the chain to a single
195/// LLM raw-text carry and brings the Worker pattern up to the token
196/// efficiency of the Phase 3 WS Operator path.
197///
198/// # Named parts (GH #86)
199///
200/// One event kind is reserved: [`ARTIFACT_EVENT_KIND`]. An emit under that
201/// kind is staged as an [`OutputEvent::Artifact`] through
202/// [`WorkerInvocation::sink`] and does **not** complete the invocation, so
203/// a script may stage any number of named parts and then finish with its
204/// terminal emit as usual. This is what makes `VerdictChannel::Part`
205/// reachable from this backend — the engine's completion-time contract
206/// check looks for a staged `"verdict"` artifact.
207///
208/// Reserving a kind is a deliberate step back from "kind-agnostic": with
209/// two destinations there is now something to route, so the script side
210/// has one string to coordinate. Every other kind keeps the old
211/// first-emit-wins result behavior.
212struct WorkerResultCaptor {
213    tx: Mutex<Option<oneshot::Sender<WorkerResult>>>,
214    /// Intake for staged named parts; `None` when the caller path did not
215    /// wire one (an `artifact` emit then degrades to a `tracing::warn!`
216    /// rather than silently vanishing).
217    sink: Option<Arc<dyn crate::worker::output::OutputSink>>,
218    /// The agent's Blueprint-declared model
219    /// ([`AgentBlockSettings::declared_model`]) — the fallback for
220    /// `stats.model` when the payload does not report one at runtime.
221    declared_model: Option<String>,
222}
223
224impl WorkerResultCaptor {
225    /// SDK-quirks normalisation: extract `(value, ok)` from a
226    /// `bus.emit` payload. `pub(crate)` so both callers and unit tests
227    /// can reach it.
228    fn extract(payload: &Value) -> (Value, bool) {
229        let ok = payload.get("ok").and_then(|v| v.as_bool()).unwrap_or(true);
230        let value = payload
231            .get("content")
232            .cloned()
233            .or_else(|| payload.get("response").cloned())
234            .unwrap_or_else(|| payload.clone());
235        (value, ok)
236    }
237
238    /// Stats-sidecar extraction (per-step run stats): the DefaultAgent
239    /// invoker's `agent_result` payload carries the full `agent.run`
240    /// return, whose `usage` (`{input_tokens, output_tokens,
241    /// total_tokens}`, all turns summed) and `num_turns` used to be
242    /// DROPPED here — the exact gap this recovers. `None` when the
243    /// payload carries none of them (caller-script `worker_result`
244    /// shapes). The raw `usage` object also rides as `adapter_data` so
245    /// provider-specific detail (cache tokens etc.) survives.
246    ///
247    /// A payload-level `"model"` string is the **runtime-observed** model
248    /// and is adopted verbatim; it outranks the Blueprint-declared
249    /// fallback applied in [`Handler::call`], because what actually
250    /// served the attempt beats what was asked for.
251    fn extract_stats(payload: &Value) -> Option<crate::store::trace::WorkerStats> {
252        let usage_raw = payload.get("usage");
253        let usage = usage_raw.and_then(|u| {
254            let input = u.get("input_tokens").and_then(|v| v.as_u64());
255            let output = u.get("output_tokens").and_then(|v| v.as_u64());
256            match (input, output) {
257                (Some(i), Some(o)) => Some(crate::store::trace::TokenUsage {
258                    input_tokens: i,
259                    output_tokens: o,
260                    total_tokens: u
261                        .get("total_tokens")
262                        .and_then(|v| v.as_u64())
263                        .unwrap_or(i + o),
264                }),
265                _ => None,
266            }
267        });
268        let num_turns = payload
269            .get("num_turns")
270            .and_then(|v| v.as_u64())
271            .map(|n| n as u32);
272        let model = payload
273            .get("model")
274            .and_then(|v| v.as_str())
275            .map(str::to_string);
276        if usage.is_none() && num_turns.is_none() && model.is_none() {
277            return None;
278        }
279        Some(crate::store::trace::WorkerStats {
280            worker_kind: Some("agent_block".to_string()),
281            model,
282            usage,
283            num_turns,
284            adapter_data: usage_raw.cloned(),
285        })
286    }
287
288    /// GH #86: stage one named part from an [`ARTIFACT_EVENT_KIND`] emit.
289    ///
290    /// `payload.name` (string) is required — an emit without it cannot
291    /// address a part, so it is reported to the script as an error rather
292    /// than dropped. `payload.content` is the body; absent means the part
293    /// is staged empty (`Value::Null`), which is still a distinct,
294    /// addressable staging event.
295    async fn stage_artifact(&self, payload: &Value) -> Result<(), BlockError> {
296        let name = payload
297            .get("name")
298            .and_then(|v| v.as_str())
299            .ok_or_else(|| {
300                BlockError::Runtime(format!(
301                    "bus.emit(\"{ARTIFACT_EVENT_KIND}\", ...) requires a string `name` field \
302                     naming the part (got: {payload})"
303                ))
304            })?
305            .to_string();
306        let Some(sink) = self.sink.as_ref() else {
307            tracing::warn!(
308                artifact = %name,
309                "agent-block staged an artifact but no OutputSink is wired for this \
310                 invocation; the part is dropped"
311            );
312            return Ok(());
313        };
314        let content = payload.get("content").cloned().unwrap_or(Value::Null);
315        sink.emit(crate::worker::output::OutputEvent::Artifact {
316            name: name.clone(),
317            content: crate::worker::output::ContentRef::Inline { value: content },
318        })
319        .await
320        .map_err(|e| BlockError::Runtime(format!("staging artifact '{name}': {e}")))?;
321        Ok(())
322    }
323}
324
325#[async_trait]
326impl Handler for WorkerResultCaptor {
327    async fn call(
328        &self,
329        kind: String,
330        _id: String,
331        payload: Value,
332        _meta: Value,
333    ) -> Result<Value, BlockError> {
334        // GH #86: the one reserved kind routes to the named-part intake and
335        // leaves the invocation running; everything else is the terminal
336        // result (first emit wins).
337        if kind == ARTIFACT_EVENT_KIND {
338            self.stage_artifact(&payload).await?;
339            return Ok(Value::Null);
340        }
341        let (value, ok) = Self::extract(&payload);
342        let stats = Self::extract_stats(&payload);
343        // Even when the SDK payload carries no usage (script-side
344        // `worker_result` shapes), the boundary still knows its own
345        // kind — surface it so `StepEntry.worker_kind` is never empty.
346        let mut wr = WorkerResult { value, ok, stats }.ensure_worker_kind("agent_block");
347        // `agent.run` returns no model, so without this the sidecar's
348        // `model` was always empty on this backend. Fall back to the
349        // Blueprint-declared `profile.model`, mirroring the subprocess
350        // backend's baked `{model}`. Precedence: runtime-observed
351        // (`extract_stats`) > declared > none — `get_or_insert_with`
352        // encodes exactly that (it is a no-op once a value is present).
353        if let (Some(declared), Some(stats)) = (self.declared_model.as_deref(), wr.stats.as_mut()) {
354            stats.model.get_or_insert_with(|| declared.to_string());
355        }
356        if let Ok(mut guard) = self.tx.lock() {
357            if let Some(tx) = guard.take() {
358                let _ = tx.send(wr);
359            }
360        }
361        Ok(Value::Null)
362    }
363}
364
365/// The Lua global carrying the launch's `init_ctx.task_metadata` bag into
366/// a script, set through the SDK's `extra_globals` (agent-block-core
367/// v0.30+).
368///
369/// Underscore-prefixed to sit alongside the SDK's own globals.
370/// `_PROMPT` / `_CONTEXT` / `_SCRIPT_NAME` are reserved by the SDK and
371/// must not be used here; this name is ours.
372pub const TASK_METADATA_GLOBAL: &str = "_TASK_METADATA";
373
374/// The Lua global carrying the Blueprint-declared agent context — the
375/// `AgentContextView.extra` bag, which `AgentContextMiddleware` fills from
376/// `Blueprint.default_agent_ctx` / `AgentMeta.ctx` (GH #21) after applying
377/// `ContextPolicy`.
378///
379/// The WS Operator lane has always received these as `{key}: {value}`
380/// lines of the Spawn directive header
381/// (`AgentContextView::to_directive_header`); this is the in-process
382/// equivalent. Delivered as ONE table rather than one global per key,
383/// because the keys are Blueprint-author-chosen and must not be able to
384/// shadow `_PROMPT` / `_CONTEXT` / `_SCRIPT_NAME` or each other's
385/// namespace.
386pub const AGENT_CTX_GLOBAL: &str = "_AGENT_CTX";
387
388/// The Lua globals this backend derives from the materialized context
389/// view — the single place the mapping "view field → Lua global" is
390/// decided, so [`crate::blueprint::compiler`]'s Lua worker can render the
391/// same surface and keep a gate portable between the two in-process
392/// backends.
393///
394/// Absent / empty inputs contribute no entry at all (rather than an empty
395/// table), so a script sees `nil` and can branch on presence — the same
396/// "insert nothing when absent" contract the rest of this axis follows.
397pub fn context_globals(view: Option<&AgentContextView>) -> HashMap<String, Value> {
398    let mut globals = HashMap::new();
399    let Some(view) = view else {
400        return globals;
401    };
402    if let Some(meta) = view.task_metadata.clone() {
403        globals.insert(TASK_METADATA_GLOBAL.to_string(), meta);
404    }
405    if !view.extra.is_empty() {
406        globals.insert(
407            AGENT_CTX_GLOBAL.to_string(),
408            Value::Object(view.extra.clone()),
409        );
410    }
411    globals
412}
413
414/// The one `bus.emit` kind this backend reserves: an emit under it stages
415/// a named part instead of completing the invocation (GH #86).
416///
417/// Payload shape: `{ name = "<part>", content = <any> }`. `name` is
418/// required. Reaching `VerdictChannel::Part` from a script means staging
419/// `{ name = "verdict", content = "PASS" }` before the terminal emit.
420pub const ARTIFACT_EVENT_KIND: &str = "artifact";
421
422/// Settings baked per `AgentDef` — the static portion of one
423/// invocation. Everything task-dependent (`project_root` /
424/// `task_metadata`) is resolved per invocation off
425/// [`WorkerInvocation::context`] instead, so this struct is built once at
426/// compile time and shared by every dispatch of the agent.
427///
428/// v0.28.0 adopted `BlockConfig.host_handler` (a kind-agnostic
429/// single sink backed by `EventBus::on_any`); the older
430/// `result_event_kind: String` field (which required the caller /
431/// script to coordinate a kind string) is gone. One captor per
432/// invocation is enough, so a single sink is enough.
433#[derive(Clone)]
434struct AgentBlockSettings {
435    /// The chunk to run — see [`ScriptPlan`].
436    script: ScriptSource,
437    /// Compile-time fallback cwd: `spec.project_root`, else
438    /// `env::current_dir()`. Outranked per invocation by the context
439    /// view's `work_dir` / `project_root`.
440    spec_project_root: PathBuf,
441    mcp_rpc_timeout: Duration,
442    /// Agent persona — the `system_prompt` composed from the agent.md
443    /// body and frontmatter. `None` maps to `BlockConfig.context = None`
444    /// for backwards compatibility with the old path.
445    profile_context: Option<String>,
446    /// The agent.md frontmatter `model:` line (`profile.model`), baked at
447    /// compile time. Observational only — this backend does not select a
448    /// model with it (the SDK owns that); it is the declared fallback for
449    /// the per-step `stats.model` sidecar, so a step of an agent whose BP
450    /// names a model is attributable even though `agent.run` reports
451    /// none. Sibling of the subprocess backend's baked `{model}`.
452    declared_model: Option<String>,
453}
454
455/// One invocation's worth of an `agent-block-core` SDK call — the
456/// `WorkerFn` body.
457///
458/// Registers the result captor through the v0.28.0 `host_handler`
459/// (single, kind-agnostic fallback). The plural `host_handlers`
460/// (string-keyed routing) is not needed — one captor per invocation is
461/// enough, and there is no script-side event-kind string to coordinate.
462async fn run_agent_block_worker(
463    settings: Arc<AgentBlockSettings>,
464    inv: WorkerInvocation,
465) -> Result<WorkerResult, WorkerError> {
466    let (tx, rx) = oneshot::channel();
467    let captor: Arc<dyn Handler> = Arc::new(WorkerResultCaptor {
468        tx: Mutex::new(Some(tx)),
469        sink: inv.sink.clone(),
470        declared_model: settings.declared_model.clone(),
471    });
472
473    // GH #86: the task-context tier, read off the ONE in-process seam
474    // (`WorkerInvocation.context`, filled by `InProcSpawner::spawn` from
475    // the materialized `AgentContextView`) instead of a hand-rolled `Ctx`
476    // peek in a spawner wrapper.
477    let project_root = resolve_project_root(inv.context.as_ref(), &settings.spec_project_root);
478
479    // Bridge the shutdown token: forward `WorkerInvocation.cancel_token`
480    // into the SDK's `shutdown_token` if one is set; otherwise use a
481    // fresh token (no external cancel).
482    let shutdown_token = inv.cancel_token.clone().unwrap_or_default();
483
484    let mut builder = BlockConfig::builder(settings.script.clone(), project_root)
485        .mcp_rpc_timeout(settings.mcp_rpc_timeout)
486        .prompt(PromptSource::Inline(inv.prompt))
487        .host_handler(captor)
488        .auto_serve_bus(true)
489        .shutdown_token(shutdown_token.clone());
490    if let Some(system) = settings.profile_context.clone() {
491        builder = builder.context(PromptSource::Inline(system));
492    }
493    // The task-context globals. `extra_globals` (SDK v0.30) sets each entry
494    // on both Isles before the chunk runs, converting the JSON natively —
495    // so nothing is spliced into the script text: no line-number shift, no
496    // `script_dir` / `package.path` disturbance, and no string-escaping
497    // trust boundary around caller-supplied values.
498    let globals = context_globals(inv.context.as_ref());
499    if !globals.is_empty() {
500        builder = builder.extra_globals(globals);
501    }
502    let config = builder.build();
503
504    let run_handle = tokio::spawn(run(config));
505    let run_result = run_handle
506        .await
507        .map_err(|e| WorkerError::Failed(format!("agent-block task join: {e}")))?;
508    run_result.map_err(|e| WorkerError::Failed(format!("agent-block run failed: {e}")))?;
509
510    rx.await.map_err(|_| {
511        WorkerError::Failed("agent-block script finished without emitting result via bus".into())
512    })
513}
514
515// ─── tools / mcp_servers resolution ───────────────────────────────────────
516
517/// Cross-reference the agent's declared tool set (see
518/// [`resolve_effective_tools`] for which tier that comes from) with
519/// `spec.mcp_servers` (the `"server name" → command + args` mapping
520/// provided by the `AgentDef` literal cascade) and resolve the
521/// `mcp_servers` config actually exposed to the LLM for this invocation.
522///
523/// Algorithm:
524///
525/// 1. Extract `mcp__<server>__<tool>` patterns from `declared_tools`;
526///    collect the `<server>` names.
527/// 2. Filter `spec.mcp_servers` to just the entries whose name is in
528///    that set.
529///
530/// This is the response to observation #3 — do not hand the LLM
531/// `mcp_servers` it does not need (only the servers the declaration
532/// explicitly asks for), and equally do not expose servers the
533/// declaration does not know about even if the spec carries them
534/// (caller intent wins).
535///
536/// CC built-in tools (non-`mcp__`-prefixed names like `Read` / `Write`
537/// / `WebSearch`) are out of scope here; handling those lives in a
538/// different layer — a carry that would come through a future
539/// `opts.extra_tools` Rust implementation.
540pub fn resolve_needed_mcp_servers(
541    declared_tools: &[String],
542    spec_mcp_servers: &[Value],
543) -> Vec<Value> {
544    use std::collections::HashSet;
545    // Step 1: server names from `mcp__<server>__<tool>` patterns in the
546    // declared tool set.
547    let needed: HashSet<&str> = declared_tools
548        .iter()
549        .filter_map(|t| {
550            let rest = t.strip_prefix("mcp__")?;
551            // Split `<server>__<tool>` at the first `__`.
552            let idx = rest.find("__")?;
553            Some(&rest[..idx])
554        })
555        .collect();
556
557    // Step 2: filter `spec.mcp_servers` down to entries whose name is
558    // in `needed`.
559    spec_mcp_servers
560        .iter()
561        .filter(|cfg| {
562            cfg.get("name")
563                .and_then(|n| n.as_str())
564                .map(|name| needed.contains(name))
565                .unwrap_or(false)
566        })
567        .cloned()
568        .collect()
569}
570
571/// GH #86 — the subset of an effective tool set that names an MCP server,
572/// i.e. the only entries this backend's grant model can act on.
573///
574/// Everything else (`Read` / `Write` / `WebSearch` …) selects no server and
575/// is inert here, so it is neither embedded nor treated as a grant that
576/// must be honored — see [`resolve_needed_mcp_servers`]'s `opts.extra_tools`
577/// carry. Used by the ScriptBasedAgent guard in
578/// [`AgentBlockInProcessSpawnerFactory::build`], which must not fail an
579/// agent whose declared tools are all inert.
580fn mcp_tools_of(tools: &[String]) -> Vec<&str> {
581    tools
582        .iter()
583        .filter(|t| t.starts_with("mcp__"))
584        .map(String::as_str)
585        .collect()
586}
587
588/// Build the inline Lua script used on the PromptBasedAgent path (when
589/// `spec.script_path` is absent). Instead of the SDK's embedded
590/// `DEFAULT_AGENT_INVOKER` (which passes no tools), this embeds
591/// `mcp_servers` as a Lua literal table and hands it to `agent.run`.
592///
593/// This is the core of the observation #3 fix. The old DefaultAgent
594/// path had no way to deliver a frontmatter `tools:` line to the SDK.
595/// This inline path bakes the `profile.tools` → `mcp_servers` config
596/// into the Lua source, so the LLM can actually make tool calls.
597///
598/// The JSON-stringify + `std.json.decode` route was ruled out because
599/// the SDK environment cannot `require` the `std` module (no
600/// `package.preload['std']` field), so we take the JSON → Lua-literal
601/// conversion on the Rust side and embed the result directly. The
602/// event name is `agent_result` — the same convention the SDK's
603/// internal `DEFAULT_AGENT_INVOKER` uses.
604pub fn build_inline_agent_invoker(mcp_servers: &[Value]) -> ScriptSource {
605    let mcp_lua = json_array_to_lua_literal(mcp_servers);
606    let source = format!(
607        r##"local agent = require("agent")
608local mcp_servers = {mcp_lua}
609local r = agent.run({{
610    prompt = _PROMPT,
611    system = _CONTEXT,
612    mcp_servers = mcp_servers,
613}})
614bus.emit("agent_result", r)
615"##
616    );
617    ScriptSource::Inline {
618        source,
619        name: "mlua_swarm_engine_default_agent_invoker.lua".into(),
620    }
621}
622
623/// Convert a JSON `Value` into a Lua literal expression, for embedding
624/// into the inline script. Lua string escaping is delegated to Rust's
625/// `{:?}` `Debug` output — Lua syntax is compatible with the escapes
626/// it produces (`"`, `\\`, `\n`, `\r`, `\t`, and so on). Edge cases
627/// like `\0` or unusual Unicode escapes are outside the scope of this
628/// use.
629fn json_to_lua_literal(v: &Value) -> String {
630    match v {
631        Value::Null => "nil".to_string(),
632        Value::Bool(b) => b.to_string(),
633        Value::Number(n) => n.to_string(),
634        Value::String(s) => format!("{s:?}"),
635        Value::Array(arr) => {
636            let items: Vec<String> = arr.iter().map(json_to_lua_literal).collect();
637            format!("{{{}}}", items.join(", "))
638        }
639        Value::Object(map) => {
640            let items: Vec<String> = map
641                .iter()
642                .map(|(k, v)| format!("[{k:?}]={}", json_to_lua_literal(v)))
643                .collect();
644            format!("{{{}}}", items.join(", "))
645        }
646    }
647}
648
649/// Convert a `Vec<Value>` into a Lua literal sequence. An empty array
650/// becomes `{}` — a Lua empty table.
651fn json_array_to_lua_literal(arr: &[Value]) -> String {
652    if arr.is_empty() {
653        return "{}".to_string();
654    }
655    let items: Vec<String> = arr.iter().map(json_to_lua_literal).collect();
656    format!("{{{}}}", items.join(", "))
657}
658
659// ─── SpawnerFactory ───────────────────────────────────────────────────────
660
661/// The compile-time (`spec` / `env::current_dir()`) fallback tier of the
662/// `project_root` priority chain (issue #17) — the tail two links of
663/// **`ctx.meta.runtime` `work_dir` > `ctx.meta.runtime` `project_root` >
664/// `spec.project_root` > `env::current_dir()`**. Extracted as a standalone
665/// pure fn so it is independently testable without needing a full `Ctx` /
666/// `SpawnerAdapter` round-trip.
667fn resolve_spec_project_root(spec: &Value) -> PathBuf {
668    match spec.get("project_root").and_then(|v| v.as_str()) {
669        Some(s) => PathBuf::from(s),
670        None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
671    }
672}
673
674/// Apply the task-context tier on top of the compile-time fallback:
675/// **`view.work_dir` > `view.project_root` > `spec_fallback`**.
676///
677/// `work_dir` outranks `project_root` because it names the exact directory
678/// this specific worker should run from. A `None` view (no `Ctx` on the
679/// caller path) leaves the compile-time fallback in place.
680fn resolve_project_root(view: Option<&AgentContextView>, spec_fallback: &Path) -> PathBuf {
681    view.and_then(|v| v.work_dir.as_deref().or(v.project_root.as_deref()))
682        .map(PathBuf::from)
683        .unwrap_or_else(|| spec_fallback.to_path_buf())
684}
685
686/// The `SpawnerFactory` for AgentBlock. `KIND = AgentKind::AgentBlock`.
687///
688/// **State-less.** One factory per process; every `AgentDef` uses it
689/// as a shared builder. Per-agent specialisation stays **entirely
690/// inside `AgentDef.spec` + `AgentDef.profile`** — the old
691/// `default_script_path` / `default_project_root` fields are gone.
692///
693/// Naming convention: `<WorkerIMPL><AdapterType>SpawnerFactory` — an
694/// AgentBlock worker on the InProcess adapter.
695pub struct AgentBlockInProcessSpawnerFactory;
696
697impl Default for AgentBlockInProcessSpawnerFactory {
698    fn default() -> Self {
699        Self
700    }
701}
702
703impl AgentBlockInProcessSpawnerFactory {
704    /// Stateless constructor — equivalent to `Default::default()`.
705    pub fn new() -> Self {
706        Self
707    }
708}
709
710impl crate::blueprint::compiler::SpawnerFactoryKind for AgentBlockInProcessSpawnerFactory {
711    const KIND: crate::blueprint::AgentKind = crate::blueprint::AgentKind::AgentBlock;
712    type Worker = AgentBlockWorker;
713}
714
715impl crate::blueprint::compiler::SpawnerFactory for AgentBlockInProcessSpawnerFactory {
716    fn build(
717        &self,
718        agent_def: &crate::blueprint::AgentDef,
719        _hint: Option<&Value>,
720    ) -> Result<
721        Arc<dyn crate::worker::adapter::SpawnerAdapter>,
722        crate::blueprint::compiler::CompileError,
723    > {
724        let agent_name = agent_def.name.clone();
725        let spec = &agent_def.spec;
726
727        // Resolve the actual mcp_servers config to pass to the real LLM by
728        // combining the effective tool set with spec.mcp_servers (the first
729        // axis of AgentDef literal cascade — a "server name → command +
730        // args" mapping). The result is JSON-embedded into the Lua source by
731        // build_inline_agent_invoker and flows into
732        // `agent.run({mcp_servers=...})`.
733        //
734        // `profile.tools` IS the effective set: when the agent declares a
735        // `Runner::AgentBlockInProcess`, the compiler has already overwritten
736        // `profile.tools` with that Runner's `tools` off the pinned
737        // `BoundAgent` snapshot (`project_bound_agent_for_legacy_factories`),
738        // including with an empty list. No Runner declared → the agent.md
739        // `tools:` line stands as-is. See the module doc's "Tool grant".
740        let effective_tools: Vec<String> = agent_def
741            .profile
742            .as_ref()
743            .map(|p| p.tools.clone())
744            .unwrap_or_default();
745        let spec_mcp_servers: Vec<Value> = spec
746            .get("mcp_servers")
747            .and_then(|v| v.as_array())
748            .cloned()
749            .unwrap_or_default();
750        let needed_mcp_servers = resolve_needed_mcp_servers(&effective_tools, &spec_mcp_servers);
751
752        // script: `spec.script_path` absent → PromptBasedAgent (the new Inline
753        //         path, embedding tools and calling agent.run); present →
754        //         ScriptBasedAgent (a caller-provided script path where tools
755        //         are the caller's responsibility). Event-kind string
756        //         dependency was retired — the `host_handler` single sink
757        //         captures every kind.
758        let script = match spec.get("script_path").and_then(|v| v.as_str()) {
759            Some(s) => {
760                // GH #86: a caller script drives its own `mcp.connect`, so the
761                // host has no choke point to enforce an MCP grant through —
762                // the Inline invoker's "embed exactly the declared servers"
763                // lever does not exist on this path. Declaring MCP tools here
764                // would be a promise the runtime cannot keep, so it is
765                // rejected at compile time instead of silently ignored.
766                //
767                // Only `mcp__`-prefixed entries trigger this: everything else
768                // selects no server and is inert in both modes, so an agent.md
769                // `tools: Read, WebSearch` line must not fail a script-mode
770                // agent that compiled before this guard existed.
771                let mcp_tools = mcp_tools_of(&effective_tools);
772                if !mcp_tools.is_empty() {
773                    return Err(crate::blueprint::compiler::CompileError::InvalidSpec {
774                        name: agent_name,
775                        msg: format!(
776                            "agent_block ScriptBasedAgent mode (spec.script_path = {s:?}) cannot \
777                             enforce an MCP tool grant: the script opens its own connections via \
778                             `mcp.connect`, so the declared tools ({}) would be unenforceable. \
779                             Either drop spec.script_path to use PromptBasedAgent mode (where the \
780                             declared servers ARE the only ones embedded into the invoker), or \
781                             drop the mcp__ entries and let the script own its connections.",
782                            mcp_tools.join(", ")
783                        ),
784                    });
785                }
786                ScriptSource::Path(PathBuf::from(s))
787            }
788            None => build_inline_agent_invoker(&needed_mcp_servers),
789        };
790
791        // issue #17: this is the compile-time fallback tier only —
792        // `spec.project_root`, then `env::current_dir()`. No `Ctx` exists
793        // yet at `build()` time, so the higher-priority task-context tier
794        // cannot be consulted here; `run_agent_block_worker` applies it per
795        // invocation off `WorkerInvocation.context` (see the module-level
796        // "`project_root` resolution" doc).
797        let spec_project_root = resolve_spec_project_root(spec);
798        let mcp_rpc_timeout = match spec.get("mcp_rpc_timeout_ms").and_then(|v| v.as_u64()) {
799            Some(ms) => Duration::from_millis(ms),
800            None => Duration::from_secs(30),
801        };
802        let profile_context = agent_def.profile.as_ref().map(|p| p.system_prompt.clone());
803        // Same source the subprocess backend bakes its `{model}`
804        // placeholder from; here it only ever reaches the per-step stats
805        // sidecar (see `AgentBlockSettings::declared_model`).
806        let declared_model = agent_def.profile.as_ref().and_then(|p| p.model.clone());
807
808        let settings = Arc::new(AgentBlockSettings {
809            script,
810            spec_project_root,
811            mcp_rpc_timeout,
812            profile_context,
813            declared_model,
814        });
815
816        // A plain `InProcSpawner` with this agent's single route. GH #86
817        // removed the `AgentBlockCtxAwareSpawner` wrapper that used to sit
818        // here purely to re-resolve `ctx.meta.runtime` at spawn time: the
819        // task-context tier now arrives on `WorkerInvocation.context`, the
820        // same seam every other in-process worker reads, so the worker fn
821        // resolves it itself and no bespoke adapter is needed.
822        let worker_fn: crate::worker::adapter::WorkerFn = Arc::new(move |inv| {
823            let settings = settings.clone();
824            Box::pin(run_agent_block_worker(settings, inv))
825        });
826        let mut sp: InProcSpawner<AgentBlockWorker> = InProcSpawner::<AgentBlockWorker>::typed();
827        sp.registry.insert(agent_name, worker_fn);
828        Ok(Arc::new(sp))
829    }
830}
831
832/// Concrete Worker type for the AgentBlock kind — the handle for an
833/// LLM call routed through the `agent-block-core` SDK. Embeds a
834/// `WorkerJoinHandler` to carry the async signal. The intent is to
835/// eventually keep the SDK-specific quirks — the `agent_result` event
836/// name, payload shape, shutdown-token bridging, agent_result.content
837/// normalisation — contained inside this struct. Today it lands as a
838/// thin shape holding only the async signal; Phase B adds the
839/// normalisation layer here and structurally eliminates the
840/// token-boilerplate waste observed in observation #2.
841pub struct AgentBlockWorker {
842    /// The completion-signal handle for this agent-block SDK call's
843    /// spawned task.
844    pub handler: crate::worker::WorkerJoinHandler,
845}
846
847impl From<crate::worker::WorkerJoinHandler> for AgentBlockWorker {
848    fn from(handler: crate::worker::WorkerJoinHandler) -> Self {
849        Self { handler }
850    }
851}
852
853#[async_trait]
854impl crate::worker::Worker for AgentBlockWorker {
855    fn id(&self) -> &crate::types::WorkerId {
856        &self.handler.worker_id
857    }
858    fn cancel_token(&self) -> tokio_util::sync::CancellationToken {
859        self.handler.cancel.clone()
860    }
861    async fn join(self: Box<Self>) -> Result<(), WorkerError> {
862        self.handler.await_completion().await
863    }
864}
865
866#[cfg(test)]
867mod tests {
868    use super::*;
869    use crate::core::agent_context::{TASK_METADATA_KEY, TASK_PROJECT_ROOT_KEY, TASK_WORK_DIR_KEY};
870
871    #[test]
872    fn resolve_needed_mcp_servers_filters_by_tool_prefix() {
873        let tools = vec![
874            "mcp__semantic-scholar__search_papers".to_string(),
875            "mcp__semantic-scholar__get_paper".to_string(),
876            "Read".to_string(),
877            "mcp__outline__list_docs".to_string(),
878            "WebSearch".to_string(),
879        ];
880        let spec_servers = vec![
881            serde_json::json!({"name": "semantic-scholar", "command": "ss-mcp", "args": []}),
882            serde_json::json!({"name": "outline", "command": "outline-mcp", "args": []}),
883            serde_json::json!({"name": "unused", "command": "nope", "args": []}),
884        ];
885        let needed = resolve_needed_mcp_servers(&tools, &spec_servers);
886        assert_eq!(needed.len(), 2, "got: {needed:?}");
887        let names: Vec<&str> = needed
888            .iter()
889            .filter_map(|c| c.get("name").and_then(|n| n.as_str()))
890            .collect();
891        assert!(names.contains(&"semantic-scholar"));
892        assert!(names.contains(&"outline"));
893        assert!(!names.contains(&"unused"), "unused server is filtered out");
894    }
895
896    #[test]
897    fn resolve_needed_mcp_servers_returns_empty_when_no_mcp_tools() {
898        let tools = vec!["Read".to_string(), "WebSearch".to_string()];
899        let spec_servers =
900            vec![serde_json::json!({"name": "outline", "command": "outline-mcp", "args": []})];
901        let needed = resolve_needed_mcp_servers(&tools, &spec_servers);
902        assert!(
903            needed.is_empty(),
904            "no mcp__-prefixed tools → empty result, got: {needed:?}"
905        );
906    }
907
908    #[test]
909    fn build_inline_agent_invoker_embeds_mcp_servers_as_lua_literal() {
910        let servers =
911            vec![serde_json::json!({"name": "outline", "command": "outline-mcp", "args": []})];
912        let script = build_inline_agent_invoker(&servers);
913        match script {
914            ScriptSource::Inline { source, name } => {
915                assert!(name.ends_with(".lua"));
916                assert!(source.contains("require(\"agent\")"));
917                assert!(source.contains("mcp_servers = mcp_servers"));
918                assert!(source.contains("bus.emit(\"agent_result\""));
919                // Lua literal embed (= keys [\"name\"]=\"outline\" form)
920                assert!(source.contains("[\"name\"]=\"outline\""));
921                assert!(source.contains("[\"command\"]=\"outline-mcp\""));
922                assert!(source.contains("[\"args\"]={}"), "args empty array literal");
923            }
924            other => panic!("expected Inline, got: {other:?}"),
925        }
926    }
927
928    #[test]
929    fn build_inline_agent_invoker_with_empty_servers_still_valid() {
930        let script = build_inline_agent_invoker(&[]);
931        match script {
932            ScriptSource::Inline { source, .. } => {
933                assert!(source.contains("local mcp_servers = {}"));
934            }
935            other => panic!("expected Inline, got: {other:?}"),
936        }
937    }
938
939    #[test]
940    fn json_to_lua_literal_handles_primitives_and_nested() {
941        assert_eq!(json_to_lua_literal(&serde_json::json!(null)), "nil");
942        assert_eq!(json_to_lua_literal(&serde_json::json!(true)), "true");
943        assert_eq!(json_to_lua_literal(&serde_json::json!(42)), "42");
944        assert_eq!(json_to_lua_literal(&serde_json::json!("hi")), "\"hi\"");
945        assert_eq!(
946            json_to_lua_literal(&serde_json::json!(["a", "b"])),
947            "{\"a\", \"b\"}"
948        );
949        assert_eq!(
950            json_to_lua_literal(&serde_json::json!({"k": 1})),
951            "{[\"k\"]=1}"
952        );
953    }
954
955    #[test]
956    fn extract_prefers_content_then_response_then_whole() {
957        // (1) `content` takes priority (DefaultAgent invoker / agent.run return-value path).
958        let p = serde_json::json!({
959            "content": "Water boils at 100°C",
960            "messages": [{"role": "assistant"}],
961            "usage": {"input_tokens": 67, "output_tokens": 29},
962            "ok": true,
963        });
964        let (value, ok) = WorkerResultCaptor::extract(&p);
965        assert_eq!(value, serde_json::json!("Water boils at 100°C"));
966        assert!(ok);
967
968        // (2) No `content` → `response` (caller-script convention worker_result).
969        let p = serde_json::json!({ "ok": false, "response": {"patch": "..."} });
970        let (value, ok) = WorkerResultCaptor::extract(&p);
971        assert_eq!(value, serde_json::json!({"patch": "..."}));
972        assert!(!ok);
973
974        // (3) Neither present → the whole payload (custom shape).
975        let p = serde_json::json!({ "custom_field": 42 });
976        let (value, ok) = WorkerResultCaptor::extract(&p);
977        assert_eq!(value, serde_json::json!({"custom_field": 42}));
978        assert!(ok); // `ok` absent → defaults to true
979    }
980
981    #[tokio::test]
982    async fn captor_emits_worker_result_from_payload() {
983        let (tx, rx) = oneshot::channel();
984        let captor = WorkerResultCaptor {
985            tx: Mutex::new(Some(tx)),
986            sink: None,
987            declared_model: None,
988        };
989        let payload = serde_json::json!({ "ok": true, "response": "hello" });
990        let ack = captor
991            .call("worker_result".into(), "evt-1".into(), payload, Value::Null)
992            .await
993            .expect("handler ack");
994        assert_eq!(ack, Value::Null);
995        let wr = rx.await.expect("recv");
996        assert!(wr.ok);
997        assert_eq!(wr.value, serde_json::json!("hello"));
998    }
999
1000    // ─── declared model → per-step stats sidecar ─────────────────────────
1001
1002    /// Run one payload through a captor carrying `declared_model` and
1003    /// return the resulting `stats.model`.
1004    async fn captured_model(declared: Option<&str>, payload: Value) -> Option<String> {
1005        let (tx, rx) = oneshot::channel();
1006        let captor = WorkerResultCaptor {
1007            tx: Mutex::new(Some(tx)),
1008            sink: None,
1009            declared_model: declared.map(str::to_string),
1010        };
1011        captor
1012            .call("agent_result".into(), "evt-1".into(), payload, Value::Null)
1013            .await
1014            .expect("handler ack");
1015        let wr = rx.await.expect("recv");
1016        wr.stats
1017            .expect("worker_kind alone guarantees a sidecar")
1018            .model
1019    }
1020
1021    /// `agent.run` reports no model, so the declared `profile.model` is
1022    /// what lands in the sidecar — the gap that left `StepEntry.stats
1023    /// .model` permanently `None` on this backend.
1024    #[tokio::test]
1025    async fn declared_model_lands_in_the_stats_sidecar() {
1026        let payload = serde_json::json!({
1027            "content": "done",
1028            "usage": {"input_tokens": 10, "output_tokens": 4},
1029            "num_turns": 2,
1030        });
1031        assert_eq!(
1032            captured_model(Some("opus"), payload).await,
1033            Some("opus".to_string())
1034        );
1035    }
1036
1037    /// The fallback does not depend on the usage rail: a caller-script
1038    /// `worker_result` shape (no `usage`, no `num_turns`) still gets the
1039    /// declared model, because `ensure_worker_kind` has already created
1040    /// the sidecar.
1041    #[tokio::test]
1042    async fn declared_model_lands_even_without_usage_in_the_payload() {
1043        let payload = serde_json::json!({ "ok": true, "response": "hello" });
1044        assert_eq!(
1045            captured_model(Some("sonnet"), payload).await,
1046            Some("sonnet".to_string())
1047        );
1048    }
1049
1050    /// A runtime-reported `model` is what actually served the attempt, so
1051    /// it outranks the declaration.
1052    #[tokio::test]
1053    async fn runtime_reported_model_wins_over_the_declaration() {
1054        let payload = serde_json::json!({
1055            "content": "done",
1056            "model": "claude-runtime-1",
1057            "usage": {"input_tokens": 10, "output_tokens": 4},
1058        });
1059        assert_eq!(
1060            captured_model(Some("opus"), payload).await,
1061            Some("claude-runtime-1".to_string())
1062        );
1063
1064        // …including when the payload carries nothing else the stats
1065        // extractor keys on.
1066        let payload = serde_json::json!({ "content": "done", "model": "claude-runtime-1" });
1067        assert_eq!(
1068            captured_model(Some("opus"), payload).await,
1069            Some("claude-runtime-1".to_string())
1070        );
1071    }
1072
1073    /// No declaration and no runtime report = no attribution invented.
1074    #[tokio::test]
1075    async fn no_declared_model_leaves_the_sidecar_model_empty() {
1076        let payload = serde_json::json!({ "ok": true, "response": "hello" });
1077        assert_eq!(captured_model(None, payload).await, None);
1078    }
1079
1080    #[tokio::test]
1081    async fn factory_builds_prompt_based_agent_when_script_path_absent() {
1082        use crate::blueprint::compiler::SpawnerFactory;
1083        use crate::blueprint::{AgentDef, AgentKind, AgentProfile};
1084
1085        let factory = AgentBlockInProcessSpawnerFactory::new();
1086        let ad = AgentDef {
1087            name: "writer".into(),
1088            kind: AgentKind::AgentBlock,
1089            spec: serde_json::json!({}),
1090            profile: Some(AgentProfile {
1091                system_prompt: "You are writer.".into(),
1092                ..Default::default()
1093            }),
1094            meta: None,
1095            runner: None,
1096            runner_ref: None,
1097            verdict: None,
1098        };
1099        let _spawner = factory.build(&ad, None).expect("factory build");
1100        // = ScriptSource::Inline path (self-hosted invoker, mcp_servers embed);
1101        // the host_handler single sink captures every event kind.
1102    }
1103
1104    // ─── GH #86: effective tool grant ─────────────────────────────────────
1105
1106    fn agent_block_def(name: &str, spec: Value, tools: &[&str]) -> crate::blueprint::AgentDef {
1107        use crate::blueprint::{AgentDef, AgentKind, AgentProfile};
1108        AgentDef {
1109            name: name.into(),
1110            kind: AgentKind::AgentBlock,
1111            spec,
1112            profile: Some(AgentProfile {
1113                system_prompt: "You are an auditor.".into(),
1114                tools: tools.iter().map(|t| t.to_string()).collect(),
1115                ..Default::default()
1116            }),
1117            meta: None,
1118            runner: None,
1119            runner_ref: None,
1120            verdict: None,
1121        }
1122    }
1123
1124    #[test]
1125    fn mcp_tools_of_keeps_only_server_selecting_names() {
1126        let tools = vec![
1127            "Read".to_string(),
1128            "mcp__outline__list_docs".to_string(),
1129            "WebSearch".to_string(),
1130        ];
1131        assert_eq!(mcp_tools_of(&tools), vec!["mcp__outline__list_docs"]);
1132        assert!(mcp_tools_of(&["Read".to_string()]).is_empty());
1133    }
1134
1135    /// PromptBasedAgent mode is where the grant is enforced: only the
1136    /// `spec.mcp_servers` entries named by the effective set (=
1137    /// `profile.tools`, which the compiler has already overwritten from a
1138    /// declared Runner) reach the invoker.
1139    ///
1140    /// Enforcement is per **server**, not per tool — granting
1141    /// `mcp__outline__list_docs` embeds the whole `outline` server, and the
1142    /// SDK exposes every tool of a connected server to the model.
1143    #[tokio::test]
1144    async fn effective_grant_narrows_the_embedded_mcp_servers() {
1145        use crate::blueprint::compiler::SpawnerFactory;
1146
1147        let ad = agent_block_def(
1148            "auditor",
1149            serde_json::json!({
1150                "mcp_servers": [
1151                    {"name": "outline", "command": "outline-mcp", "args": []},
1152                    {"name": "semantic-scholar", "command": "ss-mcp", "args": []},
1153                ]
1154            }),
1155            &["mcp__outline__list_docs"],
1156        );
1157
1158        // The pure resolution the factory performs, asserted directly (the
1159        // built `Arc<dyn SpawnerAdapter>` is opaque).
1160        let effective = ad.profile.as_ref().unwrap().tools.clone();
1161        let servers = resolve_needed_mcp_servers(
1162            &effective,
1163            ad.spec["mcp_servers"].as_array().expect("array"),
1164        );
1165        let names: Vec<&str> = servers
1166            .iter()
1167            .filter_map(|c| c.get("name").and_then(|n| n.as_str()))
1168            .collect();
1169        assert_eq!(
1170            names,
1171            vec!["outline"],
1172            "semantic-scholar is declared in spec but not selected by the grant"
1173        );
1174
1175        // And the build itself succeeds on this (PromptBased) path.
1176        AgentBlockInProcessSpawnerFactory::new()
1177            .build(&ad, None)
1178            .expect("PromptBasedAgent mode accepts an MCP grant");
1179    }
1180
1181    /// ScriptBasedAgent mode cannot enforce an MCP grant (the script drives
1182    /// its own `mcp.connect`), so declared `mcp__` entries are rejected
1183    /// rather than silently ignored.
1184    #[tokio::test]
1185    async fn script_mode_rejects_a_declared_mcp_grant() {
1186        use crate::blueprint::compiler::{CompileError, SpawnerFactory};
1187
1188        let ad = agent_block_def(
1189            "gate-danger",
1190            serde_json::json!({ "script_path": "gate.lua" }),
1191            &["mcp__outline__list_docs"],
1192        );
1193        let err = AgentBlockInProcessSpawnerFactory::new()
1194            .build(&ad, None)
1195            .err()
1196            .expect("must reject");
1197        match err {
1198            CompileError::InvalidSpec { name, msg } => {
1199                assert_eq!(name, "gate-danger");
1200                assert!(msg.contains("mcp.connect"), "explains why: {msg}");
1201                assert!(
1202                    msg.contains("PromptBasedAgent"),
1203                    "names the actionable alternative: {msg}"
1204                );
1205            }
1206            other => panic!("expected InvalidSpec, got: {other:?}"),
1207        }
1208    }
1209
1210    /// The guard is scoped to `mcp__` entries: an empty grant (the issue's
1211    /// own repro BP) and an inert-only grant (an agent.md `tools: Read,
1212    /// WebSearch` line, which compiled before the guard existed) both still
1213    /// build in script mode.
1214    #[tokio::test]
1215    async fn script_mode_accepts_empty_and_inert_grants() {
1216        use crate::blueprint::compiler::SpawnerFactory;
1217
1218        let spec = serde_json::json!({ "script_path": "gate.lua" });
1219        for tools in [&[][..], &["Read", "WebSearch"][..]] {
1220            let ad = agent_block_def("gate-danger", spec.clone(), tools);
1221            AgentBlockInProcessSpawnerFactory::new()
1222                .build(&ad, None)
1223                .unwrap_or_else(|e| panic!("script mode must accept tools {tools:?}: {e}"));
1224        }
1225    }
1226
1227    #[tokio::test]
1228    async fn factory_builds_script_based_agent_when_script_path_present() {
1229        use crate::blueprint::compiler::SpawnerFactory;
1230        use crate::blueprint::{AgentDef, AgentKind, AgentProfile};
1231
1232        let factory = AgentBlockInProcessSpawnerFactory::new();
1233        let ad = AgentDef {
1234            name: "patch-spawner".into(),
1235            kind: AgentKind::AgentBlock,
1236            spec: serde_json::json!({
1237                "script_path": "assets/operator_scripts/blueprint_patch_spawner.lua",
1238                "project_root": ".",
1239            }),
1240            profile: Some(AgentProfile {
1241                system_prompt: "Patch generator.".into(),
1242                ..Default::default()
1243            }),
1244            meta: None,
1245            runner: None,
1246            runner_ref: None,
1247            verdict: None,
1248        };
1249        let _spawner = factory.build(&ad, None).expect("factory build");
1250        // = ScriptSource::Path path; caller-provided script; host_handler single sink.
1251    }
1252
1253    // ─── Issue #17: `project_root` priority chain ─────────────────────────
1254
1255    #[test]
1256    fn resolve_spec_project_root_uses_spec_value_when_present() {
1257        let resolved =
1258            resolve_spec_project_root(&serde_json::json!({ "project_root": "/spec-root" }));
1259        assert_eq!(resolved, PathBuf::from("/spec-root"));
1260    }
1261
1262    #[test]
1263    fn resolve_spec_project_root_falls_back_to_env_current_dir_when_spec_absent() {
1264        let resolved = resolve_spec_project_root(&serde_json::json!({}));
1265        assert_eq!(
1266            resolved,
1267            std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
1268        );
1269    }
1270
1271    /// A view carrying exactly the task-context fields under test. Built
1272    /// through the real `AgentContextView::from_ctx` so the field names
1273    /// stay bound to the canonical `ctx.meta.runtime` keys rather than to
1274    /// a hand-written literal that could drift from them.
1275    fn view_with(pairs: &[(&str, Value)]) -> AgentContextView {
1276        let mut ctx = crate::core::ctx::Ctx::new(
1277            crate::types::StepId::parse("ST-project-root").unwrap(),
1278            1,
1279            "writer",
1280        );
1281        for (k, v) in pairs {
1282            ctx.meta.runtime.insert((*k).to_string(), v.clone());
1283        }
1284        AgentContextView::from_ctx(&ctx)
1285    }
1286
1287    // ─── project_root priority chain (issue #17, now off the seam) ────────
1288
1289    #[test]
1290    fn project_root_falls_back_to_spec_when_the_view_carries_neither() {
1291        let view = view_with(&[]);
1292        let resolved = resolve_project_root(Some(&view), Path::new("/spec-root"));
1293        assert_eq!(resolved, PathBuf::from("/spec-root"));
1294    }
1295
1296    /// No `Ctx` on the caller path at all (`inv.context == None`) is the
1297    /// same outcome as an empty view — the compile-time fallback stands.
1298    #[test]
1299    fn project_root_falls_back_to_spec_without_a_view() {
1300        assert_eq!(
1301            resolve_project_root(None, Path::new("/spec-root")),
1302            PathBuf::from("/spec-root")
1303        );
1304    }
1305
1306    #[test]
1307    fn project_root_prefers_the_view_over_spec() {
1308        let view = view_with(&[(TASK_PROJECT_ROOT_KEY, serde_json::json!("/ctx-root"))]);
1309        let resolved = resolve_project_root(Some(&view), Path::new("/spec-root"));
1310        assert_eq!(resolved, PathBuf::from("/ctx-root"));
1311    }
1312
1313    #[test]
1314    fn project_root_prefers_work_dir_over_project_root() {
1315        let view = view_with(&[
1316            (TASK_PROJECT_ROOT_KEY, serde_json::json!("/ctx-root")),
1317            (TASK_WORK_DIR_KEY, serde_json::json!("/ctx-work")),
1318        ]);
1319        let resolved = resolve_project_root(Some(&view), Path::new("/spec-root"));
1320        assert_eq!(resolved, PathBuf::from("/ctx-work"));
1321    }
1322
1323    // ─── GH #86: task_metadata delivery via SDK extra_globals ─────────────
1324
1325    /// An `artifact` emit must reach the sink as an
1326    /// `OutputEvent::Artifact` AND leave the invocation running, so the
1327    /// script can stage parts and still finish with its terminal emit.
1328    #[tokio::test]
1329    async fn artifact_kind_stages_a_named_part_without_completing() {
1330        use crate::worker::output::{ContentRef, OutputEvent, OutputSink};
1331
1332        #[derive(Default)]
1333        struct RecordingSink(Mutex<Vec<OutputEvent>>);
1334        #[async_trait]
1335        impl OutputSink for RecordingSink {
1336            async fn emit(&self, event: OutputEvent) -> Result<(), crate::EngineError> {
1337                self.0.lock().unwrap().push(event);
1338                Ok(())
1339            }
1340        }
1341
1342        let sink = Arc::new(RecordingSink::default());
1343        let (tx, mut rx) = oneshot::channel();
1344        let captor = WorkerResultCaptor {
1345            tx: Mutex::new(Some(tx)),
1346            sink: Some(sink.clone()),
1347            declared_model: None,
1348        };
1349
1350        captor
1351            .call(
1352                ARTIFACT_EVENT_KIND.into(),
1353                "evt-1".into(),
1354                serde_json::json!({ "name": "verdict", "content": "PASS" }),
1355                Value::Null,
1356            )
1357            .await
1358            .expect("staging must succeed");
1359
1360        let staged = sink.0.lock().unwrap().clone();
1361        assert_eq!(staged.len(), 1, "exactly one artifact staged");
1362        match &staged[0] {
1363            OutputEvent::Artifact { name, content } => {
1364                assert_eq!(name, "verdict");
1365                // `ContentRef` is not `PartialEq`; match the variant.
1366                match content {
1367                    ContentRef::Inline { value } => {
1368                        assert_eq!(value, &serde_json::json!("PASS"))
1369                    }
1370                    other => panic!("expected Inline content, got: {other:?}"),
1371                }
1372            }
1373            other => panic!("expected Artifact, got: {other:?}"),
1374        }
1375        assert!(
1376            rx.try_recv().is_err(),
1377            "an artifact emit must NOT complete the invocation"
1378        );
1379
1380        // The terminal emit still lands afterwards.
1381        captor
1382            .call(
1383                "worker_result".into(),
1384                "evt-2".into(),
1385                serde_json::json!({ "ok": true, "response": "done" }),
1386                Value::Null,
1387            )
1388            .await
1389            .expect("terminal emit");
1390        assert_eq!(
1391            rx.await.expect("recv").value,
1392            serde_json::json!("done"),
1393            "the non-reserved kind still completes the invocation"
1394        );
1395    }
1396
1397    /// An `artifact` emit with no `name` cannot address a part, so it is
1398    /// an error back to the script rather than a silent drop.
1399    #[tokio::test]
1400    async fn artifact_without_a_name_is_reported_to_the_script() {
1401        let (tx, _rx) = oneshot::channel();
1402        let captor = WorkerResultCaptor {
1403            tx: Mutex::new(Some(tx)),
1404            sink: None,
1405            declared_model: None,
1406        };
1407        let err = captor
1408            .call(
1409                ARTIFACT_EVENT_KIND.into(),
1410                "evt-1".into(),
1411                serde_json::json!({ "content": "PASS" }),
1412                Value::Null,
1413            )
1414            .await
1415            .expect_err("a nameless artifact must fail loud");
1416        assert!(
1417            format!("{err}").contains("name"),
1418            "names the missing field: {err}"
1419        );
1420    }
1421
1422    // ─── GH #86: the shared view → Lua-global mapping ─────────────────────
1423
1424    #[test]
1425    fn context_globals_renders_task_metadata_and_agent_ctx() {
1426        let mut view = view_with(&[(TASK_METADATA_KEY, serde_json::json!({"issue": 86}))]);
1427        view.extra.insert(
1428            "org_conventions".to_string(),
1429            serde_json::json!("two-space indent"),
1430        );
1431        let globals = context_globals(Some(&view));
1432        assert_eq!(
1433            globals.get(TASK_METADATA_GLOBAL),
1434            Some(&serde_json::json!({"issue": 86}))
1435        );
1436        assert_eq!(
1437            globals.get(AGENT_CTX_GLOBAL),
1438            Some(&serde_json::json!({"org_conventions": "two-space indent"})),
1439            "Blueprint-declared agent ctx must reach the in-process lane too"
1440        );
1441    }
1442
1443    /// Absent fields contribute no entry, so a script sees `nil` and can
1444    /// branch on presence — an empty table would be indistinguishable from
1445    /// "the author declared an empty ctx".
1446    #[test]
1447    fn context_globals_omits_absent_fields() {
1448        assert!(context_globals(None).is_empty(), "no view → no globals");
1449        assert!(
1450            context_globals(Some(&view_with(&[]))).is_empty(),
1451            "empty view → no globals"
1452        );
1453
1454        let view = view_with(&[(TASK_METADATA_KEY, serde_json::json!({"issue": 86}))]);
1455        let globals = context_globals(Some(&view));
1456        assert!(globals.contains_key(TASK_METADATA_GLOBAL));
1457        assert!(
1458            !globals.contains_key(AGENT_CTX_GLOBAL),
1459            "an empty `extra` must not render an empty _AGENT_CTX table"
1460        );
1461    }
1462
1463    /// Neither global may collide with an SDK-reserved name, and the two
1464    /// must not collide with each other.
1465    #[test]
1466    fn context_globals_use_names_the_sdk_does_not_reserve() {
1467        for name in [TASK_METADATA_GLOBAL, AGENT_CTX_GLOBAL] {
1468            for reserved in ["_PROMPT", "_CONTEXT", "_SCRIPT_NAME"] {
1469                assert_ne!(name, reserved);
1470            }
1471        }
1472        assert_ne!(TASK_METADATA_GLOBAL, AGENT_CTX_GLOBAL);
1473    }
1474
1475    /// The global name must not collide with the three the SDK reserves
1476    /// for itself — a collision would be silently overwritten one way or
1477    /// the other depending on injection order.
1478    #[test]
1479    fn task_metadata_global_does_not_shadow_an_sdk_reserved_name() {
1480        for reserved in ["_PROMPT", "_CONTEXT", "_SCRIPT_NAME"] {
1481            assert_ne!(TASK_METADATA_GLOBAL, reserved);
1482        }
1483    }
1484
1485    /// Script mode keeps `ScriptSource::Path`: delivering `task_metadata`
1486    /// through `extra_globals` means the chunk itself is never rewritten,
1487    /// so a caller script's own directory stays on `package.path` (sibling
1488    /// `require` keeps working) and its Lua stack-trace line numbers are
1489    /// unshifted. The `sibling_require_resolves_*` e2e is the behavioural
1490    /// half of this claim.
1491    #[tokio::test]
1492    async fn script_mode_never_rewrites_the_caller_chunk() {
1493        use crate::blueprint::compiler::SpawnerFactory;
1494
1495        let ad = agent_block_def(
1496            "gate-danger",
1497            serde_json::json!({ "script_path": "/nonexistent/gate.lua" }),
1498            &[],
1499        );
1500        // A build must succeed without touching the file: the path is
1501        // handed to the SDK verbatim, exactly as before GH #86.
1502        AgentBlockInProcessSpawnerFactory::new()
1503            .build(&ad, None)
1504            .expect("script mode must not read the script at build time");
1505    }
1506}