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}
219
220impl WorkerResultCaptor {
221 /// SDK-quirks normalisation: extract `(value, ok)` from a
222 /// `bus.emit` payload. `pub(crate)` so both callers and unit tests
223 /// can reach it.
224 fn extract(payload: &Value) -> (Value, bool) {
225 let ok = payload.get("ok").and_then(|v| v.as_bool()).unwrap_or(true);
226 let value = payload
227 .get("content")
228 .cloned()
229 .or_else(|| payload.get("response").cloned())
230 .unwrap_or_else(|| payload.clone());
231 (value, ok)
232 }
233
234 /// Stats-sidecar extraction (per-step run stats): the DefaultAgent
235 /// invoker's `agent_result` payload carries the full `agent.run`
236 /// return, whose `usage` (`{input_tokens, output_tokens,
237 /// total_tokens}`, all turns summed) and `num_turns` used to be
238 /// DROPPED here — the exact gap this recovers. `None` when the
239 /// payload carries neither (caller-script `worker_result` shapes).
240 /// The raw `usage` object also rides as `adapter_data` so
241 /// provider-specific detail (cache tokens etc.) survives.
242 fn extract_stats(payload: &Value) -> Option<crate::store::trace::WorkerStats> {
243 let usage_raw = payload.get("usage");
244 let usage = usage_raw.and_then(|u| {
245 let input = u.get("input_tokens").and_then(|v| v.as_u64());
246 let output = u.get("output_tokens").and_then(|v| v.as_u64());
247 match (input, output) {
248 (Some(i), Some(o)) => Some(crate::store::trace::TokenUsage {
249 input_tokens: i,
250 output_tokens: o,
251 total_tokens: u
252 .get("total_tokens")
253 .and_then(|v| v.as_u64())
254 .unwrap_or(i + o),
255 }),
256 _ => None,
257 }
258 });
259 let num_turns = payload
260 .get("num_turns")
261 .and_then(|v| v.as_u64())
262 .map(|n| n as u32);
263 if usage.is_none() && num_turns.is_none() {
264 return None;
265 }
266 Some(crate::store::trace::WorkerStats {
267 worker_kind: Some("agent_block".to_string()),
268 model: None,
269 usage,
270 num_turns,
271 adapter_data: usage_raw.cloned(),
272 })
273 }
274
275 /// GH #86: stage one named part from an [`ARTIFACT_EVENT_KIND`] emit.
276 ///
277 /// `payload.name` (string) is required — an emit without it cannot
278 /// address a part, so it is reported to the script as an error rather
279 /// than dropped. `payload.content` is the body; absent means the part
280 /// is staged empty (`Value::Null`), which is still a distinct,
281 /// addressable staging event.
282 async fn stage_artifact(&self, payload: &Value) -> Result<(), BlockError> {
283 let name = payload
284 .get("name")
285 .and_then(|v| v.as_str())
286 .ok_or_else(|| {
287 BlockError::Runtime(format!(
288 "bus.emit(\"{ARTIFACT_EVENT_KIND}\", ...) requires a string `name` field \
289 naming the part (got: {payload})"
290 ))
291 })?
292 .to_string();
293 let Some(sink) = self.sink.as_ref() else {
294 tracing::warn!(
295 artifact = %name,
296 "agent-block staged an artifact but no OutputSink is wired for this \
297 invocation; the part is dropped"
298 );
299 return Ok(());
300 };
301 let content = payload.get("content").cloned().unwrap_or(Value::Null);
302 sink.emit(crate::worker::output::OutputEvent::Artifact {
303 name: name.clone(),
304 content: crate::worker::output::ContentRef::Inline { value: content },
305 })
306 .await
307 .map_err(|e| BlockError::Runtime(format!("staging artifact '{name}': {e}")))?;
308 Ok(())
309 }
310}
311
312#[async_trait]
313impl Handler for WorkerResultCaptor {
314 async fn call(
315 &self,
316 kind: String,
317 _id: String,
318 payload: Value,
319 _meta: Value,
320 ) -> Result<Value, BlockError> {
321 // GH #86: the one reserved kind routes to the named-part intake and
322 // leaves the invocation running; everything else is the terminal
323 // result (first emit wins).
324 if kind == ARTIFACT_EVENT_KIND {
325 self.stage_artifact(&payload).await?;
326 return Ok(Value::Null);
327 }
328 let (value, ok) = Self::extract(&payload);
329 let stats = Self::extract_stats(&payload);
330 // Even when the SDK payload carries no usage (script-side
331 // `worker_result` shapes), the boundary still knows its own
332 // kind — surface it so `StepEntry.worker_kind` is never empty.
333 let wr = WorkerResult { value, ok, stats }.ensure_worker_kind("agent_block");
334 if let Ok(mut guard) = self.tx.lock() {
335 if let Some(tx) = guard.take() {
336 let _ = tx.send(wr);
337 }
338 }
339 Ok(Value::Null)
340 }
341}
342
343/// The Lua global carrying the launch's `init_ctx.task_metadata` bag into
344/// a script, set through the SDK's `extra_globals` (agent-block-core
345/// v0.30+).
346///
347/// Underscore-prefixed to sit alongside the SDK's own globals.
348/// `_PROMPT` / `_CONTEXT` / `_SCRIPT_NAME` are reserved by the SDK and
349/// must not be used here; this name is ours.
350pub const TASK_METADATA_GLOBAL: &str = "_TASK_METADATA";
351
352/// The Lua global carrying the Blueprint-declared agent context — the
353/// `AgentContextView.extra` bag, which `AgentContextMiddleware` fills from
354/// `Blueprint.default_agent_ctx` / `AgentMeta.ctx` (GH #21) after applying
355/// `ContextPolicy`.
356///
357/// The WS Operator lane has always received these as `{key}: {value}`
358/// lines of the Spawn directive header
359/// (`AgentContextView::to_directive_header`); this is the in-process
360/// equivalent. Delivered as ONE table rather than one global per key,
361/// because the keys are Blueprint-author-chosen and must not be able to
362/// shadow `_PROMPT` / `_CONTEXT` / `_SCRIPT_NAME` or each other's
363/// namespace.
364pub const AGENT_CTX_GLOBAL: &str = "_AGENT_CTX";
365
366/// The Lua globals this backend derives from the materialized context
367/// view — the single place the mapping "view field → Lua global" is
368/// decided, so [`crate::blueprint::compiler`]'s Lua worker can render the
369/// same surface and keep a gate portable between the two in-process
370/// backends.
371///
372/// Absent / empty inputs contribute no entry at all (rather than an empty
373/// table), so a script sees `nil` and can branch on presence — the same
374/// "insert nothing when absent" contract the rest of this axis follows.
375pub fn context_globals(view: Option<&AgentContextView>) -> HashMap<String, Value> {
376 let mut globals = HashMap::new();
377 let Some(view) = view else {
378 return globals;
379 };
380 if let Some(meta) = view.task_metadata.clone() {
381 globals.insert(TASK_METADATA_GLOBAL.to_string(), meta);
382 }
383 if !view.extra.is_empty() {
384 globals.insert(
385 AGENT_CTX_GLOBAL.to_string(),
386 Value::Object(view.extra.clone()),
387 );
388 }
389 globals
390}
391
392/// The one `bus.emit` kind this backend reserves: an emit under it stages
393/// a named part instead of completing the invocation (GH #86).
394///
395/// Payload shape: `{ name = "<part>", content = <any> }`. `name` is
396/// required. Reaching `VerdictChannel::Part` from a script means staging
397/// `{ name = "verdict", content = "PASS" }` before the terminal emit.
398pub const ARTIFACT_EVENT_KIND: &str = "artifact";
399
400/// Settings baked per `AgentDef` — the static portion of one
401/// invocation. Everything task-dependent (`project_root` /
402/// `task_metadata`) is resolved per invocation off
403/// [`WorkerInvocation::context`] instead, so this struct is built once at
404/// compile time and shared by every dispatch of the agent.
405///
406/// v0.28.0 adopted `BlockConfig.host_handler` (a kind-agnostic
407/// single sink backed by `EventBus::on_any`); the older
408/// `result_event_kind: String` field (which required the caller /
409/// script to coordinate a kind string) is gone. One captor per
410/// invocation is enough, so a single sink is enough.
411#[derive(Clone)]
412struct AgentBlockSettings {
413 /// The chunk to run — see [`ScriptPlan`].
414 script: ScriptSource,
415 /// Compile-time fallback cwd: `spec.project_root`, else
416 /// `env::current_dir()`. Outranked per invocation by the context
417 /// view's `work_dir` / `project_root`.
418 spec_project_root: PathBuf,
419 mcp_rpc_timeout: Duration,
420 /// Agent persona — the `system_prompt` composed from the agent.md
421 /// body and frontmatter. `None` maps to `BlockConfig.context = None`
422 /// for backwards compatibility with the old path.
423 profile_context: Option<String>,
424}
425
426/// One invocation's worth of an `agent-block-core` SDK call — the
427/// `WorkerFn` body.
428///
429/// Registers the result captor through the v0.28.0 `host_handler`
430/// (single, kind-agnostic fallback). The plural `host_handlers`
431/// (string-keyed routing) is not needed — one captor per invocation is
432/// enough, and there is no script-side event-kind string to coordinate.
433async fn run_agent_block_worker(
434 settings: Arc<AgentBlockSettings>,
435 inv: WorkerInvocation,
436) -> Result<WorkerResult, WorkerError> {
437 let (tx, rx) = oneshot::channel();
438 let captor: Arc<dyn Handler> = Arc::new(WorkerResultCaptor {
439 tx: Mutex::new(Some(tx)),
440 sink: inv.sink.clone(),
441 });
442
443 // GH #86: the task-context tier, read off the ONE in-process seam
444 // (`WorkerInvocation.context`, filled by `InProcSpawner::spawn` from
445 // the materialized `AgentContextView`) instead of a hand-rolled `Ctx`
446 // peek in a spawner wrapper.
447 let project_root = resolve_project_root(inv.context.as_ref(), &settings.spec_project_root);
448
449 // Bridge the shutdown token: forward `WorkerInvocation.cancel_token`
450 // into the SDK's `shutdown_token` if one is set; otherwise use a
451 // fresh token (no external cancel).
452 let shutdown_token = inv.cancel_token.clone().unwrap_or_default();
453
454 let mut builder = BlockConfig::builder(settings.script.clone(), project_root)
455 .mcp_rpc_timeout(settings.mcp_rpc_timeout)
456 .prompt(PromptSource::Inline(inv.prompt))
457 .host_handler(captor)
458 .auto_serve_bus(true)
459 .shutdown_token(shutdown_token.clone());
460 if let Some(system) = settings.profile_context.clone() {
461 builder = builder.context(PromptSource::Inline(system));
462 }
463 // The task-context globals. `extra_globals` (SDK v0.30) sets each entry
464 // on both Isles before the chunk runs, converting the JSON natively —
465 // so nothing is spliced into the script text: no line-number shift, no
466 // `script_dir` / `package.path` disturbance, and no string-escaping
467 // trust boundary around caller-supplied values.
468 let globals = context_globals(inv.context.as_ref());
469 if !globals.is_empty() {
470 builder = builder.extra_globals(globals);
471 }
472 let config = builder.build();
473
474 let run_handle = tokio::spawn(run(config));
475 let run_result = run_handle
476 .await
477 .map_err(|e| WorkerError::Failed(format!("agent-block task join: {e}")))?;
478 run_result.map_err(|e| WorkerError::Failed(format!("agent-block run failed: {e}")))?;
479
480 rx.await.map_err(|_| {
481 WorkerError::Failed("agent-block script finished without emitting result via bus".into())
482 })
483}
484
485// ─── tools / mcp_servers resolution ───────────────────────────────────────
486
487/// Cross-reference the agent's declared tool set (see
488/// [`resolve_effective_tools`] for which tier that comes from) with
489/// `spec.mcp_servers` (the `"server name" → command + args` mapping
490/// provided by the `AgentDef` literal cascade) and resolve the
491/// `mcp_servers` config actually exposed to the LLM for this invocation.
492///
493/// Algorithm:
494///
495/// 1. Extract `mcp__<server>__<tool>` patterns from `declared_tools`;
496/// collect the `<server>` names.
497/// 2. Filter `spec.mcp_servers` to just the entries whose name is in
498/// that set.
499///
500/// This is the response to observation #3 — do not hand the LLM
501/// `mcp_servers` it does not need (only the servers the declaration
502/// explicitly asks for), and equally do not expose servers the
503/// declaration does not know about even if the spec carries them
504/// (caller intent wins).
505///
506/// CC built-in tools (non-`mcp__`-prefixed names like `Read` / `Write`
507/// / `WebSearch`) are out of scope here; handling those lives in a
508/// different layer — a carry that would come through a future
509/// `opts.extra_tools` Rust implementation.
510pub fn resolve_needed_mcp_servers(
511 declared_tools: &[String],
512 spec_mcp_servers: &[Value],
513) -> Vec<Value> {
514 use std::collections::HashSet;
515 // Step 1: server names from `mcp__<server>__<tool>` patterns in the
516 // declared tool set.
517 let needed: HashSet<&str> = declared_tools
518 .iter()
519 .filter_map(|t| {
520 let rest = t.strip_prefix("mcp__")?;
521 // Split `<server>__<tool>` at the first `__`.
522 let idx = rest.find("__")?;
523 Some(&rest[..idx])
524 })
525 .collect();
526
527 // Step 2: filter `spec.mcp_servers` down to entries whose name is
528 // in `needed`.
529 spec_mcp_servers
530 .iter()
531 .filter(|cfg| {
532 cfg.get("name")
533 .and_then(|n| n.as_str())
534 .map(|name| needed.contains(name))
535 .unwrap_or(false)
536 })
537 .cloned()
538 .collect()
539}
540
541/// GH #86 — the subset of an effective tool set that names an MCP server,
542/// i.e. the only entries this backend's grant model can act on.
543///
544/// Everything else (`Read` / `Write` / `WebSearch` …) selects no server and
545/// is inert here, so it is neither embedded nor treated as a grant that
546/// must be honored — see [`resolve_needed_mcp_servers`]'s `opts.extra_tools`
547/// carry. Used by the ScriptBasedAgent guard in
548/// [`AgentBlockInProcessSpawnerFactory::build`], which must not fail an
549/// agent whose declared tools are all inert.
550fn mcp_tools_of(tools: &[String]) -> Vec<&str> {
551 tools
552 .iter()
553 .filter(|t| t.starts_with("mcp__"))
554 .map(String::as_str)
555 .collect()
556}
557
558/// Build the inline Lua script used on the PromptBasedAgent path (when
559/// `spec.script_path` is absent). Instead of the SDK's embedded
560/// `DEFAULT_AGENT_INVOKER` (which passes no tools), this embeds
561/// `mcp_servers` as a Lua literal table and hands it to `agent.run`.
562///
563/// This is the core of the observation #3 fix. The old DefaultAgent
564/// path had no way to deliver a frontmatter `tools:` line to the SDK.
565/// This inline path bakes the `profile.tools` → `mcp_servers` config
566/// into the Lua source, so the LLM can actually make tool calls.
567///
568/// The JSON-stringify + `std.json.decode` route was ruled out because
569/// the SDK environment cannot `require` the `std` module (no
570/// `package.preload['std']` field), so we take the JSON → Lua-literal
571/// conversion on the Rust side and embed the result directly. The
572/// event name is `agent_result` — the same convention the SDK's
573/// internal `DEFAULT_AGENT_INVOKER` uses.
574pub fn build_inline_agent_invoker(mcp_servers: &[Value]) -> ScriptSource {
575 let mcp_lua = json_array_to_lua_literal(mcp_servers);
576 let source = format!(
577 r##"local agent = require("agent")
578local mcp_servers = {mcp_lua}
579local r = agent.run({{
580 prompt = _PROMPT,
581 system = _CONTEXT,
582 mcp_servers = mcp_servers,
583}})
584bus.emit("agent_result", r)
585"##
586 );
587 ScriptSource::Inline {
588 source,
589 name: "mlua_swarm_engine_default_agent_invoker.lua".into(),
590 }
591}
592
593/// Convert a JSON `Value` into a Lua literal expression, for embedding
594/// into the inline script. Lua string escaping is delegated to Rust's
595/// `{:?}` `Debug` output — Lua syntax is compatible with the escapes
596/// it produces (`"`, `\\`, `\n`, `\r`, `\t`, and so on). Edge cases
597/// like `\0` or unusual Unicode escapes are outside the scope of this
598/// use.
599fn json_to_lua_literal(v: &Value) -> String {
600 match v {
601 Value::Null => "nil".to_string(),
602 Value::Bool(b) => b.to_string(),
603 Value::Number(n) => n.to_string(),
604 Value::String(s) => format!("{s:?}"),
605 Value::Array(arr) => {
606 let items: Vec<String> = arr.iter().map(json_to_lua_literal).collect();
607 format!("{{{}}}", items.join(", "))
608 }
609 Value::Object(map) => {
610 let items: Vec<String> = map
611 .iter()
612 .map(|(k, v)| format!("[{k:?}]={}", json_to_lua_literal(v)))
613 .collect();
614 format!("{{{}}}", items.join(", "))
615 }
616 }
617}
618
619/// Convert a `Vec<Value>` into a Lua literal sequence. An empty array
620/// becomes `{}` — a Lua empty table.
621fn json_array_to_lua_literal(arr: &[Value]) -> String {
622 if arr.is_empty() {
623 return "{}".to_string();
624 }
625 let items: Vec<String> = arr.iter().map(json_to_lua_literal).collect();
626 format!("{{{}}}", items.join(", "))
627}
628
629// ─── SpawnerFactory ───────────────────────────────────────────────────────
630
631/// The compile-time (`spec` / `env::current_dir()`) fallback tier of the
632/// `project_root` priority chain (issue #17) — the tail two links of
633/// **`ctx.meta.runtime` `work_dir` > `ctx.meta.runtime` `project_root` >
634/// `spec.project_root` > `env::current_dir()`**. Extracted as a standalone
635/// pure fn so it is independently testable without needing a full `Ctx` /
636/// `SpawnerAdapter` round-trip.
637fn resolve_spec_project_root(spec: &Value) -> PathBuf {
638 match spec.get("project_root").and_then(|v| v.as_str()) {
639 Some(s) => PathBuf::from(s),
640 None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
641 }
642}
643
644/// Apply the task-context tier on top of the compile-time fallback:
645/// **`view.work_dir` > `view.project_root` > `spec_fallback`**.
646///
647/// `work_dir` outranks `project_root` because it names the exact directory
648/// this specific worker should run from. A `None` view (no `Ctx` on the
649/// caller path) leaves the compile-time fallback in place.
650fn resolve_project_root(view: Option<&AgentContextView>, spec_fallback: &Path) -> PathBuf {
651 view.and_then(|v| v.work_dir.as_deref().or(v.project_root.as_deref()))
652 .map(PathBuf::from)
653 .unwrap_or_else(|| spec_fallback.to_path_buf())
654}
655
656/// The `SpawnerFactory` for AgentBlock. `KIND = AgentKind::AgentBlock`.
657///
658/// **State-less.** One factory per process; every `AgentDef` uses it
659/// as a shared builder. Per-agent specialisation stays **entirely
660/// inside `AgentDef.spec` + `AgentDef.profile`** — the old
661/// `default_script_path` / `default_project_root` fields are gone.
662///
663/// Naming convention: `<WorkerIMPL><AdapterType>SpawnerFactory` — an
664/// AgentBlock worker on the InProcess adapter.
665pub struct AgentBlockInProcessSpawnerFactory;
666
667impl Default for AgentBlockInProcessSpawnerFactory {
668 fn default() -> Self {
669 Self
670 }
671}
672
673impl AgentBlockInProcessSpawnerFactory {
674 /// Stateless constructor — equivalent to `Default::default()`.
675 pub fn new() -> Self {
676 Self
677 }
678}
679
680impl crate::blueprint::compiler::SpawnerFactoryKind for AgentBlockInProcessSpawnerFactory {
681 const KIND: crate::blueprint::AgentKind = crate::blueprint::AgentKind::AgentBlock;
682 type Worker = AgentBlockWorker;
683}
684
685impl crate::blueprint::compiler::SpawnerFactory for AgentBlockInProcessSpawnerFactory {
686 fn build(
687 &self,
688 agent_def: &crate::blueprint::AgentDef,
689 _hint: Option<&Value>,
690 ) -> Result<
691 Arc<dyn crate::worker::adapter::SpawnerAdapter>,
692 crate::blueprint::compiler::CompileError,
693 > {
694 let agent_name = agent_def.name.clone();
695 let spec = &agent_def.spec;
696
697 // Resolve the actual mcp_servers config to pass to the real LLM by
698 // combining the effective tool set with spec.mcp_servers (the first
699 // axis of AgentDef literal cascade — a "server name → command +
700 // args" mapping). The result is JSON-embedded into the Lua source by
701 // build_inline_agent_invoker and flows into
702 // `agent.run({mcp_servers=...})`.
703 //
704 // `profile.tools` IS the effective set: when the agent declares a
705 // `Runner::AgentBlockInProcess`, the compiler has already overwritten
706 // `profile.tools` with that Runner's `tools` off the pinned
707 // `BoundAgent` snapshot (`project_bound_agent_for_legacy_factories`),
708 // including with an empty list. No Runner declared → the agent.md
709 // `tools:` line stands as-is. See the module doc's "Tool grant".
710 let effective_tools: Vec<String> = agent_def
711 .profile
712 .as_ref()
713 .map(|p| p.tools.clone())
714 .unwrap_or_default();
715 let spec_mcp_servers: Vec<Value> = spec
716 .get("mcp_servers")
717 .and_then(|v| v.as_array())
718 .cloned()
719 .unwrap_or_default();
720 let needed_mcp_servers = resolve_needed_mcp_servers(&effective_tools, &spec_mcp_servers);
721
722 // script: `spec.script_path` absent → PromptBasedAgent (the new Inline
723 // path, embedding tools and calling agent.run); present →
724 // ScriptBasedAgent (a caller-provided script path where tools
725 // are the caller's responsibility). Event-kind string
726 // dependency was retired — the `host_handler` single sink
727 // captures every kind.
728 let script = match spec.get("script_path").and_then(|v| v.as_str()) {
729 Some(s) => {
730 // GH #86: a caller script drives its own `mcp.connect`, so the
731 // host has no choke point to enforce an MCP grant through —
732 // the Inline invoker's "embed exactly the declared servers"
733 // lever does not exist on this path. Declaring MCP tools here
734 // would be a promise the runtime cannot keep, so it is
735 // rejected at compile time instead of silently ignored.
736 //
737 // Only `mcp__`-prefixed entries trigger this: everything else
738 // selects no server and is inert in both modes, so an agent.md
739 // `tools: Read, WebSearch` line must not fail a script-mode
740 // agent that compiled before this guard existed.
741 let mcp_tools = mcp_tools_of(&effective_tools);
742 if !mcp_tools.is_empty() {
743 return Err(crate::blueprint::compiler::CompileError::InvalidSpec {
744 name: agent_name,
745 msg: format!(
746 "agent_block ScriptBasedAgent mode (spec.script_path = {s:?}) cannot \
747 enforce an MCP tool grant: the script opens its own connections via \
748 `mcp.connect`, so the declared tools ({}) would be unenforceable. \
749 Either drop spec.script_path to use PromptBasedAgent mode (where the \
750 declared servers ARE the only ones embedded into the invoker), or \
751 drop the mcp__ entries and let the script own its connections.",
752 mcp_tools.join(", ")
753 ),
754 });
755 }
756 ScriptSource::Path(PathBuf::from(s))
757 }
758 None => build_inline_agent_invoker(&needed_mcp_servers),
759 };
760
761 // issue #17: this is the compile-time fallback tier only —
762 // `spec.project_root`, then `env::current_dir()`. No `Ctx` exists
763 // yet at `build()` time, so the higher-priority task-context tier
764 // cannot be consulted here; `run_agent_block_worker` applies it per
765 // invocation off `WorkerInvocation.context` (see the module-level
766 // "`project_root` resolution" doc).
767 let spec_project_root = resolve_spec_project_root(spec);
768 let mcp_rpc_timeout = match spec.get("mcp_rpc_timeout_ms").and_then(|v| v.as_u64()) {
769 Some(ms) => Duration::from_millis(ms),
770 None => Duration::from_secs(30),
771 };
772 let profile_context = agent_def.profile.as_ref().map(|p| p.system_prompt.clone());
773
774 let settings = Arc::new(AgentBlockSettings {
775 script,
776 spec_project_root,
777 mcp_rpc_timeout,
778 profile_context,
779 });
780
781 // A plain `InProcSpawner` with this agent's single route. GH #86
782 // removed the `AgentBlockCtxAwareSpawner` wrapper that used to sit
783 // here purely to re-resolve `ctx.meta.runtime` at spawn time: the
784 // task-context tier now arrives on `WorkerInvocation.context`, the
785 // same seam every other in-process worker reads, so the worker fn
786 // resolves it itself and no bespoke adapter is needed.
787 let worker_fn: crate::worker::adapter::WorkerFn = Arc::new(move |inv| {
788 let settings = settings.clone();
789 Box::pin(run_agent_block_worker(settings, inv))
790 });
791 let mut sp: InProcSpawner<AgentBlockWorker> = InProcSpawner::<AgentBlockWorker>::typed();
792 sp.registry.insert(agent_name, worker_fn);
793 Ok(Arc::new(sp))
794 }
795}
796
797/// Concrete Worker type for the AgentBlock kind — the handle for an
798/// LLM call routed through the `agent-block-core` SDK. Embeds a
799/// `WorkerJoinHandler` to carry the async signal. The intent is to
800/// eventually keep the SDK-specific quirks — the `agent_result` event
801/// name, payload shape, shutdown-token bridging, agent_result.content
802/// normalisation — contained inside this struct. Today it lands as a
803/// thin shape holding only the async signal; Phase B adds the
804/// normalisation layer here and structurally eliminates the
805/// token-boilerplate waste observed in observation #2.
806pub struct AgentBlockWorker {
807 /// The completion-signal handle for this agent-block SDK call's
808 /// spawned task.
809 pub handler: crate::worker::WorkerJoinHandler,
810}
811
812impl From<crate::worker::WorkerJoinHandler> for AgentBlockWorker {
813 fn from(handler: crate::worker::WorkerJoinHandler) -> Self {
814 Self { handler }
815 }
816}
817
818#[async_trait]
819impl crate::worker::Worker for AgentBlockWorker {
820 fn id(&self) -> &crate::types::WorkerId {
821 &self.handler.worker_id
822 }
823 fn cancel_token(&self) -> tokio_util::sync::CancellationToken {
824 self.handler.cancel.clone()
825 }
826 async fn join(self: Box<Self>) -> Result<(), WorkerError> {
827 self.handler.await_completion().await
828 }
829}
830
831#[cfg(test)]
832mod tests {
833 use super::*;
834 use crate::core::agent_context::{TASK_METADATA_KEY, TASK_PROJECT_ROOT_KEY, TASK_WORK_DIR_KEY};
835
836 #[test]
837 fn resolve_needed_mcp_servers_filters_by_tool_prefix() {
838 let tools = vec![
839 "mcp__semantic-scholar__search_papers".to_string(),
840 "mcp__semantic-scholar__get_paper".to_string(),
841 "Read".to_string(),
842 "mcp__outline__list_docs".to_string(),
843 "WebSearch".to_string(),
844 ];
845 let spec_servers = vec![
846 serde_json::json!({"name": "semantic-scholar", "command": "ss-mcp", "args": []}),
847 serde_json::json!({"name": "outline", "command": "outline-mcp", "args": []}),
848 serde_json::json!({"name": "unused", "command": "nope", "args": []}),
849 ];
850 let needed = resolve_needed_mcp_servers(&tools, &spec_servers);
851 assert_eq!(needed.len(), 2, "got: {needed:?}");
852 let names: Vec<&str> = needed
853 .iter()
854 .filter_map(|c| c.get("name").and_then(|n| n.as_str()))
855 .collect();
856 assert!(names.contains(&"semantic-scholar"));
857 assert!(names.contains(&"outline"));
858 assert!(!names.contains(&"unused"), "unused server is filtered out");
859 }
860
861 #[test]
862 fn resolve_needed_mcp_servers_returns_empty_when_no_mcp_tools() {
863 let tools = vec!["Read".to_string(), "WebSearch".to_string()];
864 let spec_servers =
865 vec![serde_json::json!({"name": "outline", "command": "outline-mcp", "args": []})];
866 let needed = resolve_needed_mcp_servers(&tools, &spec_servers);
867 assert!(
868 needed.is_empty(),
869 "no mcp__-prefixed tools → empty result, got: {needed:?}"
870 );
871 }
872
873 #[test]
874 fn build_inline_agent_invoker_embeds_mcp_servers_as_lua_literal() {
875 let servers =
876 vec![serde_json::json!({"name": "outline", "command": "outline-mcp", "args": []})];
877 let script = build_inline_agent_invoker(&servers);
878 match script {
879 ScriptSource::Inline { source, name } => {
880 assert!(name.ends_with(".lua"));
881 assert!(source.contains("require(\"agent\")"));
882 assert!(source.contains("mcp_servers = mcp_servers"));
883 assert!(source.contains("bus.emit(\"agent_result\""));
884 // Lua literal embed (= keys [\"name\"]=\"outline\" form)
885 assert!(source.contains("[\"name\"]=\"outline\""));
886 assert!(source.contains("[\"command\"]=\"outline-mcp\""));
887 assert!(source.contains("[\"args\"]={}"), "args empty array literal");
888 }
889 other => panic!("expected Inline, got: {other:?}"),
890 }
891 }
892
893 #[test]
894 fn build_inline_agent_invoker_with_empty_servers_still_valid() {
895 let script = build_inline_agent_invoker(&[]);
896 match script {
897 ScriptSource::Inline { source, .. } => {
898 assert!(source.contains("local mcp_servers = {}"));
899 }
900 other => panic!("expected Inline, got: {other:?}"),
901 }
902 }
903
904 #[test]
905 fn json_to_lua_literal_handles_primitives_and_nested() {
906 assert_eq!(json_to_lua_literal(&serde_json::json!(null)), "nil");
907 assert_eq!(json_to_lua_literal(&serde_json::json!(true)), "true");
908 assert_eq!(json_to_lua_literal(&serde_json::json!(42)), "42");
909 assert_eq!(json_to_lua_literal(&serde_json::json!("hi")), "\"hi\"");
910 assert_eq!(
911 json_to_lua_literal(&serde_json::json!(["a", "b"])),
912 "{\"a\", \"b\"}"
913 );
914 assert_eq!(
915 json_to_lua_literal(&serde_json::json!({"k": 1})),
916 "{[\"k\"]=1}"
917 );
918 }
919
920 #[test]
921 fn extract_prefers_content_then_response_then_whole() {
922 // (1) `content` takes priority (DefaultAgent invoker / agent.run return-value path).
923 let p = serde_json::json!({
924 "content": "Water boils at 100°C",
925 "messages": [{"role": "assistant"}],
926 "usage": {"input_tokens": 67, "output_tokens": 29},
927 "ok": true,
928 });
929 let (value, ok) = WorkerResultCaptor::extract(&p);
930 assert_eq!(value, serde_json::json!("Water boils at 100°C"));
931 assert!(ok);
932
933 // (2) No `content` → `response` (caller-script convention worker_result).
934 let p = serde_json::json!({ "ok": false, "response": {"patch": "..."} });
935 let (value, ok) = WorkerResultCaptor::extract(&p);
936 assert_eq!(value, serde_json::json!({"patch": "..."}));
937 assert!(!ok);
938
939 // (3) Neither present → the whole payload (custom shape).
940 let p = serde_json::json!({ "custom_field": 42 });
941 let (value, ok) = WorkerResultCaptor::extract(&p);
942 assert_eq!(value, serde_json::json!({"custom_field": 42}));
943 assert!(ok); // `ok` absent → defaults to true
944 }
945
946 #[tokio::test]
947 async fn captor_emits_worker_result_from_payload() {
948 let (tx, rx) = oneshot::channel();
949 let captor = WorkerResultCaptor {
950 tx: Mutex::new(Some(tx)),
951 sink: None,
952 };
953 let payload = serde_json::json!({ "ok": true, "response": "hello" });
954 let ack = captor
955 .call("worker_result".into(), "evt-1".into(), payload, Value::Null)
956 .await
957 .expect("handler ack");
958 assert_eq!(ack, Value::Null);
959 let wr = rx.await.expect("recv");
960 assert!(wr.ok);
961 assert_eq!(wr.value, serde_json::json!("hello"));
962 }
963
964 #[tokio::test]
965 async fn factory_builds_prompt_based_agent_when_script_path_absent() {
966 use crate::blueprint::compiler::SpawnerFactory;
967 use crate::blueprint::{AgentDef, AgentKind, AgentProfile};
968
969 let factory = AgentBlockInProcessSpawnerFactory::new();
970 let ad = AgentDef {
971 name: "writer".into(),
972 kind: AgentKind::AgentBlock,
973 spec: serde_json::json!({}),
974 profile: Some(AgentProfile {
975 system_prompt: "You are writer.".into(),
976 ..Default::default()
977 }),
978 meta: None,
979 runner: None,
980 runner_ref: None,
981 verdict: None,
982 };
983 let _spawner = factory.build(&ad, None).expect("factory build");
984 // = ScriptSource::Inline path (self-hosted invoker, mcp_servers embed);
985 // the host_handler single sink captures every event kind.
986 }
987
988 // ─── GH #86: effective tool grant ─────────────────────────────────────
989
990 fn agent_block_def(name: &str, spec: Value, tools: &[&str]) -> crate::blueprint::AgentDef {
991 use crate::blueprint::{AgentDef, AgentKind, AgentProfile};
992 AgentDef {
993 name: name.into(),
994 kind: AgentKind::AgentBlock,
995 spec,
996 profile: Some(AgentProfile {
997 system_prompt: "You are an auditor.".into(),
998 tools: tools.iter().map(|t| t.to_string()).collect(),
999 ..Default::default()
1000 }),
1001 meta: None,
1002 runner: None,
1003 runner_ref: None,
1004 verdict: None,
1005 }
1006 }
1007
1008 #[test]
1009 fn mcp_tools_of_keeps_only_server_selecting_names() {
1010 let tools = vec![
1011 "Read".to_string(),
1012 "mcp__outline__list_docs".to_string(),
1013 "WebSearch".to_string(),
1014 ];
1015 assert_eq!(mcp_tools_of(&tools), vec!["mcp__outline__list_docs"]);
1016 assert!(mcp_tools_of(&["Read".to_string()]).is_empty());
1017 }
1018
1019 /// PromptBasedAgent mode is where the grant is enforced: only the
1020 /// `spec.mcp_servers` entries named by the effective set (=
1021 /// `profile.tools`, which the compiler has already overwritten from a
1022 /// declared Runner) reach the invoker.
1023 ///
1024 /// Enforcement is per **server**, not per tool — granting
1025 /// `mcp__outline__list_docs` embeds the whole `outline` server, and the
1026 /// SDK exposes every tool of a connected server to the model.
1027 #[tokio::test]
1028 async fn effective_grant_narrows_the_embedded_mcp_servers() {
1029 use crate::blueprint::compiler::SpawnerFactory;
1030
1031 let ad = agent_block_def(
1032 "auditor",
1033 serde_json::json!({
1034 "mcp_servers": [
1035 {"name": "outline", "command": "outline-mcp", "args": []},
1036 {"name": "semantic-scholar", "command": "ss-mcp", "args": []},
1037 ]
1038 }),
1039 &["mcp__outline__list_docs"],
1040 );
1041
1042 // The pure resolution the factory performs, asserted directly (the
1043 // built `Arc<dyn SpawnerAdapter>` is opaque).
1044 let effective = ad.profile.as_ref().unwrap().tools.clone();
1045 let servers = resolve_needed_mcp_servers(
1046 &effective,
1047 ad.spec["mcp_servers"].as_array().expect("array"),
1048 );
1049 let names: Vec<&str> = servers
1050 .iter()
1051 .filter_map(|c| c.get("name").and_then(|n| n.as_str()))
1052 .collect();
1053 assert_eq!(
1054 names,
1055 vec!["outline"],
1056 "semantic-scholar is declared in spec but not selected by the grant"
1057 );
1058
1059 // And the build itself succeeds on this (PromptBased) path.
1060 AgentBlockInProcessSpawnerFactory::new()
1061 .build(&ad, None)
1062 .expect("PromptBasedAgent mode accepts an MCP grant");
1063 }
1064
1065 /// ScriptBasedAgent mode cannot enforce an MCP grant (the script drives
1066 /// its own `mcp.connect`), so declared `mcp__` entries are rejected
1067 /// rather than silently ignored.
1068 #[tokio::test]
1069 async fn script_mode_rejects_a_declared_mcp_grant() {
1070 use crate::blueprint::compiler::{CompileError, SpawnerFactory};
1071
1072 let ad = agent_block_def(
1073 "gate-danger",
1074 serde_json::json!({ "script_path": "gate.lua" }),
1075 &["mcp__outline__list_docs"],
1076 );
1077 let err = AgentBlockInProcessSpawnerFactory::new()
1078 .build(&ad, None)
1079 .err()
1080 .expect("must reject");
1081 match err {
1082 CompileError::InvalidSpec { name, msg } => {
1083 assert_eq!(name, "gate-danger");
1084 assert!(msg.contains("mcp.connect"), "explains why: {msg}");
1085 assert!(
1086 msg.contains("PromptBasedAgent"),
1087 "names the actionable alternative: {msg}"
1088 );
1089 }
1090 other => panic!("expected InvalidSpec, got: {other:?}"),
1091 }
1092 }
1093
1094 /// The guard is scoped to `mcp__` entries: an empty grant (the issue's
1095 /// own repro BP) and an inert-only grant (an agent.md `tools: Read,
1096 /// WebSearch` line, which compiled before the guard existed) both still
1097 /// build in script mode.
1098 #[tokio::test]
1099 async fn script_mode_accepts_empty_and_inert_grants() {
1100 use crate::blueprint::compiler::SpawnerFactory;
1101
1102 let spec = serde_json::json!({ "script_path": "gate.lua" });
1103 for tools in [&[][..], &["Read", "WebSearch"][..]] {
1104 let ad = agent_block_def("gate-danger", spec.clone(), tools);
1105 AgentBlockInProcessSpawnerFactory::new()
1106 .build(&ad, None)
1107 .unwrap_or_else(|e| panic!("script mode must accept tools {tools:?}: {e}"));
1108 }
1109 }
1110
1111 #[tokio::test]
1112 async fn factory_builds_script_based_agent_when_script_path_present() {
1113 use crate::blueprint::compiler::SpawnerFactory;
1114 use crate::blueprint::{AgentDef, AgentKind, AgentProfile};
1115
1116 let factory = AgentBlockInProcessSpawnerFactory::new();
1117 let ad = AgentDef {
1118 name: "patch-spawner".into(),
1119 kind: AgentKind::AgentBlock,
1120 spec: serde_json::json!({
1121 "script_path": "assets/operator_scripts/blueprint_patch_spawner.lua",
1122 "project_root": ".",
1123 }),
1124 profile: Some(AgentProfile {
1125 system_prompt: "Patch generator.".into(),
1126 ..Default::default()
1127 }),
1128 meta: None,
1129 runner: None,
1130 runner_ref: None,
1131 verdict: None,
1132 };
1133 let _spawner = factory.build(&ad, None).expect("factory build");
1134 // = ScriptSource::Path path; caller-provided script; host_handler single sink.
1135 }
1136
1137 // ─── Issue #17: `project_root` priority chain ─────────────────────────
1138
1139 #[test]
1140 fn resolve_spec_project_root_uses_spec_value_when_present() {
1141 let resolved =
1142 resolve_spec_project_root(&serde_json::json!({ "project_root": "/spec-root" }));
1143 assert_eq!(resolved, PathBuf::from("/spec-root"));
1144 }
1145
1146 #[test]
1147 fn resolve_spec_project_root_falls_back_to_env_current_dir_when_spec_absent() {
1148 let resolved = resolve_spec_project_root(&serde_json::json!({}));
1149 assert_eq!(
1150 resolved,
1151 std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
1152 );
1153 }
1154
1155 /// A view carrying exactly the task-context fields under test. Built
1156 /// through the real `AgentContextView::from_ctx` so the field names
1157 /// stay bound to the canonical `ctx.meta.runtime` keys rather than to
1158 /// a hand-written literal that could drift from them.
1159 fn view_with(pairs: &[(&str, Value)]) -> AgentContextView {
1160 let mut ctx = crate::core::ctx::Ctx::new(
1161 crate::types::StepId::parse("ST-project-root").unwrap(),
1162 1,
1163 "writer",
1164 );
1165 for (k, v) in pairs {
1166 ctx.meta.runtime.insert((*k).to_string(), v.clone());
1167 }
1168 AgentContextView::from_ctx(&ctx)
1169 }
1170
1171 // ─── project_root priority chain (issue #17, now off the seam) ────────
1172
1173 #[test]
1174 fn project_root_falls_back_to_spec_when_the_view_carries_neither() {
1175 let view = view_with(&[]);
1176 let resolved = resolve_project_root(Some(&view), Path::new("/spec-root"));
1177 assert_eq!(resolved, PathBuf::from("/spec-root"));
1178 }
1179
1180 /// No `Ctx` on the caller path at all (`inv.context == None`) is the
1181 /// same outcome as an empty view — the compile-time fallback stands.
1182 #[test]
1183 fn project_root_falls_back_to_spec_without_a_view() {
1184 assert_eq!(
1185 resolve_project_root(None, Path::new("/spec-root")),
1186 PathBuf::from("/spec-root")
1187 );
1188 }
1189
1190 #[test]
1191 fn project_root_prefers_the_view_over_spec() {
1192 let view = view_with(&[(TASK_PROJECT_ROOT_KEY, serde_json::json!("/ctx-root"))]);
1193 let resolved = resolve_project_root(Some(&view), Path::new("/spec-root"));
1194 assert_eq!(resolved, PathBuf::from("/ctx-root"));
1195 }
1196
1197 #[test]
1198 fn project_root_prefers_work_dir_over_project_root() {
1199 let view = view_with(&[
1200 (TASK_PROJECT_ROOT_KEY, serde_json::json!("/ctx-root")),
1201 (TASK_WORK_DIR_KEY, serde_json::json!("/ctx-work")),
1202 ]);
1203 let resolved = resolve_project_root(Some(&view), Path::new("/spec-root"));
1204 assert_eq!(resolved, PathBuf::from("/ctx-work"));
1205 }
1206
1207 // ─── GH #86: task_metadata delivery via SDK extra_globals ─────────────
1208
1209 /// An `artifact` emit must reach the sink as an
1210 /// `OutputEvent::Artifact` AND leave the invocation running, so the
1211 /// script can stage parts and still finish with its terminal emit.
1212 #[tokio::test]
1213 async fn artifact_kind_stages_a_named_part_without_completing() {
1214 use crate::worker::output::{ContentRef, OutputEvent, OutputSink};
1215
1216 #[derive(Default)]
1217 struct RecordingSink(Mutex<Vec<OutputEvent>>);
1218 #[async_trait]
1219 impl OutputSink for RecordingSink {
1220 async fn emit(&self, event: OutputEvent) -> Result<(), crate::EngineError> {
1221 self.0.lock().unwrap().push(event);
1222 Ok(())
1223 }
1224 }
1225
1226 let sink = Arc::new(RecordingSink::default());
1227 let (tx, mut rx) = oneshot::channel();
1228 let captor = WorkerResultCaptor {
1229 tx: Mutex::new(Some(tx)),
1230 sink: Some(sink.clone()),
1231 };
1232
1233 captor
1234 .call(
1235 ARTIFACT_EVENT_KIND.into(),
1236 "evt-1".into(),
1237 serde_json::json!({ "name": "verdict", "content": "PASS" }),
1238 Value::Null,
1239 )
1240 .await
1241 .expect("staging must succeed");
1242
1243 let staged = sink.0.lock().unwrap().clone();
1244 assert_eq!(staged.len(), 1, "exactly one artifact staged");
1245 match &staged[0] {
1246 OutputEvent::Artifact { name, content } => {
1247 assert_eq!(name, "verdict");
1248 // `ContentRef` is not `PartialEq`; match the variant.
1249 match content {
1250 ContentRef::Inline { value } => {
1251 assert_eq!(value, &serde_json::json!("PASS"))
1252 }
1253 other => panic!("expected Inline content, got: {other:?}"),
1254 }
1255 }
1256 other => panic!("expected Artifact, got: {other:?}"),
1257 }
1258 assert!(
1259 rx.try_recv().is_err(),
1260 "an artifact emit must NOT complete the invocation"
1261 );
1262
1263 // The terminal emit still lands afterwards.
1264 captor
1265 .call(
1266 "worker_result".into(),
1267 "evt-2".into(),
1268 serde_json::json!({ "ok": true, "response": "done" }),
1269 Value::Null,
1270 )
1271 .await
1272 .expect("terminal emit");
1273 assert_eq!(
1274 rx.await.expect("recv").value,
1275 serde_json::json!("done"),
1276 "the non-reserved kind still completes the invocation"
1277 );
1278 }
1279
1280 /// An `artifact` emit with no `name` cannot address a part, so it is
1281 /// an error back to the script rather than a silent drop.
1282 #[tokio::test]
1283 async fn artifact_without_a_name_is_reported_to_the_script() {
1284 let (tx, _rx) = oneshot::channel();
1285 let captor = WorkerResultCaptor {
1286 tx: Mutex::new(Some(tx)),
1287 sink: None,
1288 };
1289 let err = captor
1290 .call(
1291 ARTIFACT_EVENT_KIND.into(),
1292 "evt-1".into(),
1293 serde_json::json!({ "content": "PASS" }),
1294 Value::Null,
1295 )
1296 .await
1297 .expect_err("a nameless artifact must fail loud");
1298 assert!(
1299 format!("{err}").contains("name"),
1300 "names the missing field: {err}"
1301 );
1302 }
1303
1304 // ─── GH #86: the shared view → Lua-global mapping ─────────────────────
1305
1306 #[test]
1307 fn context_globals_renders_task_metadata_and_agent_ctx() {
1308 let mut view = view_with(&[(TASK_METADATA_KEY, serde_json::json!({"issue": 86}))]);
1309 view.extra.insert(
1310 "org_conventions".to_string(),
1311 serde_json::json!("two-space indent"),
1312 );
1313 let globals = context_globals(Some(&view));
1314 assert_eq!(
1315 globals.get(TASK_METADATA_GLOBAL),
1316 Some(&serde_json::json!({"issue": 86}))
1317 );
1318 assert_eq!(
1319 globals.get(AGENT_CTX_GLOBAL),
1320 Some(&serde_json::json!({"org_conventions": "two-space indent"})),
1321 "Blueprint-declared agent ctx must reach the in-process lane too"
1322 );
1323 }
1324
1325 /// Absent fields contribute no entry, so a script sees `nil` and can
1326 /// branch on presence — an empty table would be indistinguishable from
1327 /// "the author declared an empty ctx".
1328 #[test]
1329 fn context_globals_omits_absent_fields() {
1330 assert!(context_globals(None).is_empty(), "no view → no globals");
1331 assert!(
1332 context_globals(Some(&view_with(&[]))).is_empty(),
1333 "empty view → no globals"
1334 );
1335
1336 let view = view_with(&[(TASK_METADATA_KEY, serde_json::json!({"issue": 86}))]);
1337 let globals = context_globals(Some(&view));
1338 assert!(globals.contains_key(TASK_METADATA_GLOBAL));
1339 assert!(
1340 !globals.contains_key(AGENT_CTX_GLOBAL),
1341 "an empty `extra` must not render an empty _AGENT_CTX table"
1342 );
1343 }
1344
1345 /// Neither global may collide with an SDK-reserved name, and the two
1346 /// must not collide with each other.
1347 #[test]
1348 fn context_globals_use_names_the_sdk_does_not_reserve() {
1349 for name in [TASK_METADATA_GLOBAL, AGENT_CTX_GLOBAL] {
1350 for reserved in ["_PROMPT", "_CONTEXT", "_SCRIPT_NAME"] {
1351 assert_ne!(name, reserved);
1352 }
1353 }
1354 assert_ne!(TASK_METADATA_GLOBAL, AGENT_CTX_GLOBAL);
1355 }
1356
1357 /// The global name must not collide with the three the SDK reserves
1358 /// for itself — a collision would be silently overwritten one way or
1359 /// the other depending on injection order.
1360 #[test]
1361 fn task_metadata_global_does_not_shadow_an_sdk_reserved_name() {
1362 for reserved in ["_PROMPT", "_CONTEXT", "_SCRIPT_NAME"] {
1363 assert_ne!(TASK_METADATA_GLOBAL, reserved);
1364 }
1365 }
1366
1367 /// Script mode keeps `ScriptSource::Path`: delivering `task_metadata`
1368 /// through `extra_globals` means the chunk itself is never rewritten,
1369 /// so a caller script's own directory stays on `package.path` (sibling
1370 /// `require` keeps working) and its Lua stack-trace line numbers are
1371 /// unshifted. The `sibling_require_resolves_*` e2e is the behavioural
1372 /// half of this claim.
1373 #[tokio::test]
1374 async fn script_mode_never_rewrites_the_caller_chunk() {
1375 use crate::blueprint::compiler::SpawnerFactory;
1376
1377 let ad = agent_block_def(
1378 "gate-danger",
1379 serde_json::json!({ "script_path": "/nonexistent/gate.lua" }),
1380 &[],
1381 );
1382 // A build must succeed without touching the file: the path is
1383 // handed to the SDK verbatim, exactly as before GH #86.
1384 AgentBlockInProcessSpawnerFactory::new()
1385 .build(&ad, None)
1386 .expect("script mode must not read the script at build time");
1387 }
1388}