symforge 11.7.2

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
//! MCP `symforge` (the compact facade) for an embedded source. The shared L1
//! planner and L2 economics decide the route; each planned primitive runs on
//! this source's native query lane; the shared executor, ledger and envelope
//! render the answer. This mirrors `SymForgeServer::symforge_stel_handler` on
//! its daemon-less path: there is no daemon to route a foreign project to, so
//! a `project` selector is checked against this source and never forwarded.

use serde_json::Value;

use super::embed_query::{Budget, EmbeddedQuerySnapshot};
use super::embed_session::QuerySession;
use crate::embed::parity::stel::{OutcomeClass, StelRequest, SymforgeAnswer, SymforgeStep};
use crate::embed::parity::{
    QueryObservation, QueryOutput, QueryPolicy, QueryRefusalKind, QueryRequest,
};
use crate::index_lifecycle::guidance::smart_query;
use crate::stel::runtime::{self, FacadeLedgerInput};

/// The native request one planned primitive routes to, decoded from the
/// planner's MCP arguments. A `project` argument was already checked against
/// this source, so it is not forwarded.
pub(super) fn step_request(tool: &str, args: &Value) -> Result<QueryRequest, QueryRefusalKind> {
    use crate::embed::parity::guidance::ExploreRequest;

    let tool = crate::stel::planner::FacadeStepTool::from_name(tool)
        .ok_or(QueryRefusalKind::UnsupportedOption)?;
    let mut args = args.clone();
    if let Value::Object(map) = &mut args {
        map.remove("project");
    }
    fn decode<T: serde::de::DeserializeOwned>(args: Value) -> Result<T, QueryRefusalKind> {
        serde_json::from_value(args).map_err(|_| QueryRefusalKind::InvalidRequest)
    }
    let text = |key: &str| args.get(key).and_then(Value::as_str).map(str::to_owned);
    let number = |key: &str| args.get(key).and_then(Value::as_u64);
    Ok(match tool.as_str() {
        "search_text" => QueryRequest::TextSearch(decode(args)?),
        "search_symbols" => QueryRequest::SymbolSearch(decode(args)?),
        "search_files" => QueryRequest::FileSearch(decode(args)?),
        "search_knowledge" => QueryRequest::SearchKnowledge(decode(args)?),
        "get_file_context" => QueryRequest::FileContext(decode(args)?),
        "get_file_content" => QueryRequest::FileContent(decode(args)?),
        "get_symbol" => QueryRequest::SymbolRead(decode(args)?),
        "get_symbol_context" => QueryRequest::SymbolContext(decode(args)?),
        "find_references" => QueryRequest::ReferenceSearch(decode(args)?),
        "find_dependents" => QueryRequest::DependentSearch(decode(args)?),
        "what_changed" => QueryRequest::WhatChanged(decode(args)?),
        "diff_symbols" => QueryRequest::DiffSymbols(decode(args)?),
        "detect_impact" => QueryRequest::DetectImpact(decode(args)?),
        "analyze_file_impact" => QueryRequest::FileImpact(decode(args)?),
        "get_repo_map" => QueryRequest::RepoMap(decode(args)?),
        "ask" => QueryRequest::Ask(decode(args)?),
        "explore" => {
            let mut request = ExploreRequest::new(text("query").unwrap_or_default());
            if let Some(depth) = number("depth") {
                request.depth =
                    u32::try_from(depth).map_err(|_| QueryRefusalKind::InvalidRequest)?;
            }
            if let Some(limit) = number("limit") {
                request.limit =
                    u32::try_from(limit).map_err(|_| QueryRefusalKind::InvalidRequest)?;
            }
            request.max_tokens = number("max_tokens");
            request.path_prefix = text("path_prefix");
            request.language = text("language");
            QueryRequest::Explore(request)
        }
        "conventions" => QueryRequest::Conventions,
        "context_inventory" => QueryRequest::ContextInventory,
        "investigation_suggest" => QueryRequest::InvestigationSuggest {
            focus: text("focus"),
        },
        "symforge_retrieve" => QueryRequest::Retrieve {
            handle: text("hash").unwrap_or_default(),
            offset: 0,
        },
        _ => return Err(QueryRefusalKind::UnsupportedOption),
    })
}

/// The exact paths MCP's planned read primitives freshen when the facade
/// dispatches them.
pub(super) fn freshen_paths(request: &StelRequest) -> Vec<String> {
    crate::stel::planner::build_plan(request)
        .steps
        .iter()
        .filter_map(|step| step_request(&step.tool, &step.args).ok())
        .filter_map(|request| request.freshen_path().map(str::to_owned))
        .collect()
}

fn answer(outcome: OutcomeClass, rendered: String, steps: Vec<SymforgeStep>) -> QueryOutput {
    QueryOutput::Symforge(SymforgeAnswer {
        outcome,
        rendered,
        steps,
    })
}

fn refusal(text: impl Into<String>) -> Result<QueryOutput, QueryRefusalKind> {
    Ok(answer(
        OutcomeClass::InvalidRequest,
        text.into(),
        Vec::new(),
    ))
}

pub(super) fn project(
    snapshot: &EmbeddedQuerySnapshot,
    request: &StelRequest,
    budget: &mut Budget,
    observations: &mut Vec<QueryObservation>,
    session: Option<&QuerySession>,
    policy: QueryPolicy,
) -> Result<QueryOutput, QueryRefusalKind> {
    use crate::stel::controller::{build_estimate, evaluate_plan_tuned};
    use crate::stel::executor::{
        ServedStepResult, apply_compact_serve_caps, apply_degrade_to_plan, chain_failure_decision,
        format_bypass_body, format_cache_hit_body, format_multi_step_serve_body,
        format_partial_multi_step_serve_body, format_single_step_serve_body, is_degrade,
        route_tool_label, serve_chain_outcome_class, should_skip_legacy_dispatch, tools_executed,
    };
    use crate::stel::handler::{self, metrics_for_decision_tuned};
    use crate::stel::planner::{build_plan, plan_summary_line};

    if request.query.trim().is_empty() {
        return refusal("query is required: pass a natural-language phrase");
    }
    if smart_query::strip_leading_articles(request.query.trim()).is_empty() {
        return refusal("query requires a non-empty question.");
    }
    if let Some(message) = crate::stel::planner::symbol_contract_violation(request) {
        return refusal(message);
    }
    if request.projects.is_some() {
        return refusal(
            "cross-project targeting is not routed through the `symforge` facade; call \
             search_symbols / search_text / find_references directly with project/projects.",
        );
    }
    let facade_project = request
        .project
        .as_deref()
        .filter(|project| !project.trim().is_empty());
    super::embed_changes::check_project(snapshot, facade_project)?;
    if let Some(path) = request.path.as_deref().filter(|p| !p.trim().is_empty()) {
        if !runtime::facade_path_is_repo_relative(path) {
            return refusal(
                "`path:` requires a repo-relative path: it is a within-project filter, not an \
                 absolute filesystem path or project selector.",
            );
        }
        if !runtime::path_is_within_bound_project(path, &snapshot.root) {
            return refusal(format!(
                "Path is outside the repository root: {path}. The selected project root is \
                 {}; `path:` is a within-project filter, not a project selector (use \
                 `index_folder {{ path }}` to retarget the workspace).",
                crate::paths::normalized_path_string(&snapshot.root)
            ));
        }
    }

    let live = &snapshot.generation.live;
    let bound_root = format!(
        "project_root: {}",
        crate::paths::normalized_path_string(&snapshot.root)
    );
    let mut plan = build_plan(request);
    runtime::ground_plan_economics(live, &mut plan);
    let tuned = runtime::active_tuning_for_economics(budget.stel_store.as_deref());
    let decision = match session {
        Some(session) => session.with_context(|context| {
            evaluate_plan_tuned(request, &plan, Some(context), tuned.as_ref())
        }),
        None => evaluate_plan_tuned(request, &plan, None, tuned.as_ref()),
    };
    let first_tool = plan
        .steps
        .first()
        .map(|step| step.tool.clone())
        .ok_or(QueryRefusalKind::InvalidRequest)?;
    let plan_summary = plan_summary_line(&plan);
    let session_tokens_served = session.map_or(0, QuerySession::served_tokens) as i64;

    if request.preview == Some(true) {
        let estimate = build_estimate(request, &plan, &decision);
        let body = handler::format_preview_estimate(&estimate);
        let metrics = metrics_for_decision_tuned(
            plan_summary,
            &decision,
            &plan,
            0,
            session_tokens_served,
            tuned.as_ref(),
        );
        let envelope = handler::envelope_for_decision(&metrics);
        let output = handler::prepend_envelope(&envelope, &body);
        budget.required(output.len())?;
        return Ok(answer(OutcomeClass::Found, output, Vec::new()));
    }

    if should_skip_legacy_dispatch(&decision) {
        let mut body = if decision.decision == crate::stel::AdmissionDecision::CacheHit {
            format_cache_hit_body(&decision)
        } else {
            format_bypass_body(&decision)
        };
        for note in crate::stel::planner::served_param_disclosures(request, &plan) {
            body.push_str("\n\n");
            body.push_str(&note);
        }
        let (output, event) = runtime::render_facade_answer(FacadeLedgerInput {
            surface: "symforge",
            plan: &plan,
            decision: &decision,
            plan_summary,
            session_tokens_served,
            body: &body,
            legacy_executed: false,
            selected_tool: &first_tool,
            tools_called: None,
            tuned: tuned.as_ref(),
        });
        budget.stel_event = Some(event);
        let output = format!("{output}\n{bound_root}");
        budget.required(output.len())?;
        return Ok(answer(OutcomeClass::Found, output, Vec::new()));
    }

    let exec_plan = if is_degrade(&decision) {
        apply_degrade_to_plan(&plan, &decision)
    } else if decision.decision == crate::stel::AdmissionDecision::Serve {
        apply_compact_serve_caps(&plan, &decision)
    } else {
        plan.clone()
    };
    let is_fusion_union = crate::stel::is_find_fusion_plan(&exec_plan);
    if let Some(project) = facade_project
        && let Some(step) = exec_plan
            .steps
            .iter()
            .find(|step| !runtime::facade_step_accepts_project(&step.tool))
    {
        return refusal(format!(
            "project '{project}' cannot be routed through this plan: planned step `{}` has no \
             project selector. Call the primitive tools directly with `project`.",
            step.tool
        ));
    }

    let mut step_results = Vec::new();
    let mut steps = Vec::new();
    let mut outcome_class = OutcomeClass::Found;
    let mut chain_failed = false;
    for step in &exec_plan.steps {
        let args = runtime::inject_find_fusion_cochange_anchor(live, &step.tool, &step.args, true);
        let nested = step_request(&step.tool, &args)?;
        let projected = super::embed_query::validate_request(&nested).and_then(|()| {
            super::embed_query::project(snapshot, &nested, budget, observations, session, policy)
        });
        // Each step answers once; the outer facade answer is what the
        // session caches, so a child's cache or handle never stands for it.
        budget.cache_output = None;
        budget.reused_handle = None;
        let (mut body, output, step_outcome) = match projected {
            Ok(output) => {
                let body = match render_search(snapshot, session, policy, &nested, &output) {
                    Some(rendered) => rendered?,
                    None => render_output(session, &nested, &output)?,
                };
                // The step's typed outcome, decided from the native result as
                // MCP's tool decides its own; the body never decides.
                let step_outcome = super::embed_query::facade_step_class(
                    &nested,
                    Ok(&output),
                    Some(&snapshot.generation.live),
                );
                (body, Some(Box::new(output)), step_outcome)
            }
            Err(QueryRefusalKind::Cancelled) => return Err(QueryRefusalKind::Cancelled),
            Err(QueryRefusalKind::DeadlineExceeded) => {
                return Err(QueryRefusalKind::DeadlineExceeded);
            }
            Err(QueryRefusalKind::BudgetTooSmall) => {
                return Err(QueryRefusalKind::BudgetTooSmall);
            }
            // MCP's `explore` answers a stopword-only query with this text
            // as a served body; the shared engine's refusal is the same one.
            Err(QueryRefusalKind::InvalidRequest) if step.tool == "explore" => (
                "Explore requires a non-empty query.".to_string(),
                None,
                super::embed_query::facade_step_class(
                    &nested,
                    Err(QueryRefusalKind::InvalidRequest),
                    None,
                ),
            ),
            Err(kind) => (
                format!("Error: {} refused: {kind:?}", step.tool),
                None,
                super::embed_query::facade_step_class(&nested, Err(kind), None),
            ),
        };
        if step.tool == "search_knowledge" {
            body =
                crate::index_lifecycle::guidance::compression::rewrite_footer_for_symforge_facade(
                    body,
                );
        }
        step_results.push(ServedStepResult {
            tool: step.tool.clone(),
            body,
            outcome: Some(step_outcome),
        });
        steps.push(SymforgeStep {
            tool: step.tool.clone(),
            request: nested,
            output,
            outcome: step_outcome,
        });
        if step.tool == "search_knowledge" && step_outcome == OutcomeClass::EmptyResult {
            outcome_class = OutcomeClass::EmptyResult;
            continue;
        }
        if step_outcome != OutcomeClass::Found {
            let fatal = !is_fusion_union
                || matches!(
                    step_outcome,
                    OutcomeClass::InternalFailure | OutcomeClass::InvalidRequest
                );
            if fatal {
                outcome_class = serve_chain_outcome_class(step_outcome);
                chain_failed = true;
                break;
            }
        }
    }

    if is_fusion_union && !chain_failed && !steps.is_empty() {
        let all_empty = steps.iter().all(|step| {
            matches!(
                step.outcome,
                OutcomeClass::EmptyResult | OutcomeClass::NotFound
            )
        });
        if all_empty {
            outcome_class = OutcomeClass::EmptyResult;
        }
    }

    let mut effective_decision = decision.clone();
    if chain_failed {
        let failed_index = steps.len().saturating_sub(1);
        effective_decision = chain_failure_decision(
            &plan,
            &decision,
            failed_index,
            &steps[failed_index].tool,
            steps[failed_index].outcome,
        );
    }
    let chain_failure_note = chain_failed.then(|| effective_decision.decision_reason.clone());
    let mut body = if exec_plan.steps.len() == 1 {
        format_single_step_serve_body(
            &plan,
            &effective_decision,
            &exec_plan.steps[0],
            &step_results[0].body,
        )
    } else if chain_failed {
        format_partial_multi_step_serve_body(
            &plan,
            &effective_decision,
            &step_results,
            chain_failure_note.as_deref(),
        )
    } else {
        format_multi_step_serve_body(&plan, &effective_decision, &step_results)
    };
    if plan.intent == crate::stel::IntentBucket::Impact
        && !chain_failed
        && exec_plan.steps.len() == 1
    {
        let temporal = super::embed_temporal::temporal(snapshot, policy, budget)?;
        runtime::append_impact_intent_cochanges(&temporal, &mut body, &exec_plan.steps[0].args);
    }
    for note in crate::stel::planner::served_param_disclosures(request, &plan) {
        body.push_str("\n\n");
        body.push_str(&note);
    }
    let tools = tools_executed(&step_results);
    let route_label = route_tool_label(&tools);
    let tools_called = (tools.len() > 1).then_some(tools);
    let (output, event) = runtime::render_facade_answer(FacadeLedgerInput {
        surface: "symforge",
        plan: &plan,
        decision: &effective_decision,
        plan_summary,
        session_tokens_served,
        body: &body,
        legacy_executed: !step_results.is_empty(),
        selected_tool: &route_label,
        tools_called,
        tuned: tuned.as_ref(),
    });
    budget.stel_event = Some(event);
    let output = format!("{output}\n{bound_root}");
    budget.required(output.len())?;
    Ok(answer(outcome_class, output, steps))
}

/// MCP's search-tool text for a search step: the same shared engine rendered
/// over the same publication the native lane answered from, with the result
/// envelope MCP's search tools prepend. `None` for every other step.
pub(super) fn render_search(
    snapshot: &EmbeddedQuerySnapshot,
    session: Option<&QuerySession>,
    policy: QueryPolicy,
    request: &QueryRequest,
    output: &QueryOutput,
) -> Option<Result<String, QueryRefusalKind>> {
    // MCP's `apply_ccr_budget`: through the session's CCR store when there is
    // one, else the same token cut without a retrievable handle.
    let budget = |tool: &str, rendered: String, max_tokens: Option<u64>| match session {
        Some(session) => session.apply_ccr_budget(snapshot, tool, rendered, max_tokens),
        None => super::guidance::source::enforce_token_budget(
            rendered,
            super::guidance::compression::resolve_tool_max_tokens(tool, max_tokens),
        ),
    };
    use super::guidance::reference_read::with_withheld_note;
    use super::guidance::{file_search, search};
    let generation = &snapshot.generation;
    let rendered = match (request, output) {
        (QueryRequest::TextSearch(input), QueryOutput::TextSearch(value)) => {
            let shared = super::embed_search::text_input(input);
            let executed = match search::execute_text_search(generation, &shared) {
                Ok(executed) => executed,
                Err(_) => return Some(Err(QueryRefusalKind::InvalidRequest)),
            };
            let mut rendered = search::render_search_text_output(
                generation,
                executed.result,
                executed.effective_query.as_deref(),
                executed.structural,
                shared.group_by.as_deref(),
                shared.terms.as_deref(),
                &executed.options,
                executed.is_regex,
                executed.auto_detected_regex,
                executed.auto_corrected_regex,
                &value.untracked_paths,
            );
            if executed.auto_corrected_regex {
                rendered.push_str(&format!(
                    "\n(auto-corrected double-escaped regex: `{}` → `{}`)",
                    shared.query.as_deref().unwrap_or_default(),
                    executed.effective_query.as_deref().unwrap_or_default()
                ));
            }
            budget(
                "search_text",
                with_withheld_note(&generation.live, input.path_prefix.as_deref(), rendered),
                input.max_tokens,
            )
        }
        (QueryRequest::SymbolSearch(input), QueryOutput::SymbolSearch(_)) => {
            let shared = super::embed_search::symbol_input(input);
            let executed = match search::execute_symbol_search(&generation.live, &shared) {
                Ok(executed) => executed,
                Err(_) => return Some(Err(QueryRefusalKind::InvalidRequest)),
            };
            let rendered = search::render_symbol_search(
                generation,
                &executed,
                shared.query.as_deref().unwrap_or("").trim(),
            );
            budget(
                "search_symbols",
                with_withheld_note(&generation.live, input.path_prefix.as_deref(), rendered),
                input.max_tokens,
            )
        }
        (QueryRequest::FileSearch(input), QueryOutput::FileSearch(value))
            if input.resolve != Some(true) && input.changed_with.is_none() =>
        {
            let shared = super::embed_file_search::input(input);
            let ranked = file_search::rank_files(
                generation,
                Some(&snapshot.root),
                snapshot.project_state.as_ref(),
                &shared,
                policy.allow_derived_state_preparation && snapshot.project_state.is_some(),
            );
            file_search::render_ranked_files(
                generation,
                ranked,
                &shared,
                shared.include_vendor.unwrap_or(false),
                shared.include_personal_tooling.unwrap_or(false),
                || value.untracked_paths.clone(),
            )
        }
        _ => return None,
    };
    Some(Ok(rendered))
}

/// The MCP text of one primitive's native answer.
fn render_output(
    session: Option<&QuerySession>,
    request: &QueryRequest,
    output: &QueryOutput,
) -> Result<String, QueryRefusalKind> {
    Ok(match output {
        QueryOutput::FileContent(value) => value.rendered.clone(),
        QueryOutput::FileContext(value) => value.rendered.clone(),
        QueryOutput::SymbolRead(value) => value.rendered.clone(),
        QueryOutput::InspectMatch(value) => value.rendered.clone(),
        QueryOutput::DiffSymbols(value) => value.rendered.clone(),
        QueryOutput::FileImpact(value) => value.rendered.clone(),
        QueryOutput::Ask(value) => value.rendered.clone(),
        QueryOutput::InvestigationSuggestion(value) => value.text.clone(),
        QueryOutput::RetrievedOutput(value) => String::from_utf8_lossy(&value.bytes).into_owned(),
        QueryOutput::ContextInventory(_) => match session {
            Some(session) => session.render_inventory(),
            None => return Err(QueryRefusalKind::SessionRequired),
        },
        QueryOutput::Conventions(value) => {
            crate::index_lifecycle::guidance::conventions::format_conventions(
                &crate::index_lifecycle::guidance::conventions::ProjectConventions {
                    language: value.language.clone(),
                    error_handling: value.error_handling.clone(),
                    naming: value.naming.clone(),
                    test_patterns: value.test_patterns.clone(),
                    common_imports: value.common_imports.clone(),
                    file_organization: value.file_organization.clone(),
                    complexity: value.complexity.clone(),
                },
            )
        }
        QueryOutput::DetectImpact(value) => value.rendered.clone(),
        _ => super::embed_ask::render_routed(request, output)?,
    })
}

#[cfg(test)]
mod step_tool_guard_tests {
    use super::*;
    use crate::embed::ProcessIndexRuntime;
    use crate::embed::parity::QueryLimits;
    use crate::embed::parity::host::{
        HostLimits, HostPhase, HostRequest, HostResponse, HostRights, HostRoom, HostRoomConfig,
        HostRoomGrant,
    };
    use std::time::{Duration, Instant};

    fn guard_args(tool: &str) -> Value {
        match tool {
            "get_file_content" | "get_file_context" | "find_dependents" | "analyze_file_impact" => {
                serde_json::json!({ "path": "src/lib.rs" })
            }
            "get_symbol" => serde_json::json!({ "path": "src/lib.rs", "name": "alpha" }),
            "get_symbol_context" | "find_references" => serde_json::json!({ "name": "alpha" }),
            "search_text" | "search_symbols" | "search_files" | "search_knowledge" | "explore" => {
                serde_json::json!({ "query": "alpha" })
            }
            "ask" => serde_json::json!({ "query": "who calls alpha" }),
            "symforge_retrieve" => serde_json::json!({ "hash": "000000000000" }),
            "what_changed"
            | "diff_symbols"
            | "detect_impact"
            | "get_repo_map"
            | "conventions"
            | "context_inventory"
            | "investigation_suggest"
            | "health_compact" => {
                serde_json::json!({})
            }
            other => panic!(
                "facade step tool `{other}` has no guard arguments: add it here and give it \
                 a typed outcome"
            ),
        }
    }

    /// Guard: every tool the embedded facade dispatches, and every tool the
    /// planner can emit that the room runs, answers with a typed outcome: a
    /// typed refusal, or an output `facade_step_class` types without guessing.
    /// A planned tool the room cannot dispatch is refused as a whole facade
    /// request (typed), and is named here so the gap is explicit.
    #[test]
    fn every_facade_step_tool_has_a_typed_outcome_on_the_room() {
        let (planned, embedded) = crate::stel::planner::facade_step_tool_sets();
        let repository = tempfile::tempdir().unwrap();
        git2::Repository::init(repository.path()).unwrap();
        std::fs::create_dir_all(repository.path().join("src")).unwrap();
        std::fs::write(
            repository.path().join("src/lib.rs"),
            "pub fn alpha() -> u32 {\n    1\n}\n",
        )
        .unwrap();
        let grant = HostRoomGrant::new(
            "step-guard".into(),
            repository.path().to_path_buf(),
            "step-guard-source".into(),
            HostRights::read_only(),
        )
        .unwrap();
        let room = HostRoom::open(
            ProcessIndexRuntime::acquire().unwrap(),
            grant,
            HostRoomConfig {
                room_id: "step-guard".into(),
                limits: HostLimits::default(),
            },
        )
        .unwrap();
        let control = room.control().unwrap();
        let deadline = Instant::now() + Duration::from_secs(20);
        loop {
            let HostResponse::Status(status) =
                room.dispatch(&HostRequest::Status, &control).unwrap()
            else {
                panic!("status response");
            };
            if status.phase == HostPhase::Current {
                break;
            }
            assert!(Instant::now() < deadline, "source did not publish");
            std::thread::sleep(Duration::from_millis(10));
        }
        let mut not_dispatched = Vec::new();
        for tool in planned.union(&embedded) {
            let request = match step_request(tool, &guard_args(tool)) {
                Ok(request) => request,
                Err(_) => {
                    assert!(
                        !embedded.contains(tool),
                        "the room dispatch set names `{tool}` but cannot build its request"
                    );
                    not_dispatched.push(tool.clone());
                    continue;
                }
            };
            match room.dispatch(
                &HostRequest::Query {
                    request: request.clone(),
                    limits: QueryLimits::default(),
                },
                &control,
            ) {
                Ok(HostResponse::Query(reply)) => assert!(
                    crate::embed::lifecycle::embed_query::typed_output_outcome(&reply.output)
                        .is_some(),
                    "facade step tool `{tool}` answers with an untyped output on the room"
                ),
                Ok(_) => panic!("`{tool}`: query response"),
                // A refusal is typed by its kind.
                Err(refusal) => assert!(
                    refusal.query_kind.is_some()
                        || refusal.kind
                            != crate::embed::parity::host::HostRefusalKind::EngineFailure,
                    "`{tool}` refused without a typed kind: {refusal:?}"
                ),
            }
        }
        // Planned steps the room does not dispatch: refused as a whole facade
        // request with a typed refusal. Pinned so a change is deliberate.
        assert_eq!(not_dispatched, vec!["health_compact".to_string()]);

        let refusal = room
            .dispatch(
                &HostRequest::Query {
                    request: crate::embed::parity::QueryRequest::Symforge(
                        crate::stel_core::types::StelRequest {
                            query: "index health".into(),
                            ..Default::default()
                        },
                    ),
                    limits: QueryLimits::default(),
                },
                &control,
            )
            .expect_err("health_compact is refused by the embedded facade");
        assert_eq!(
            refusal.query_kind,
            Some(crate::embed::parity::QueryRefusalKind::UnsupportedOption),
            "health_compact must remain an explicit typed room refusal: {refusal:?}"
        );
    }
}