leviath_cli/lint/mod.rs
1//! Blueprint lint: the checks [`Blueprint::validate`] deliberately does not make.
2//!
3//! `Blueprint::validate` answers "is this manifest structurally coherent" - the
4//! layout fits, the graph resolves, fan-out wiring points at real stages. It
5//! says nothing about the fields whose *absence* quietly changes what a run
6//! does, and those are what actually bite:
7//!
8//! - a stage with no `[stages.<name>.model]` table parses fine, because the
9//! parser substitutes a default, and then runs on whatever the user's default
10//! provider happens to be
11//! - an agent-level `[model]` block is never read at all, so the author's model
12//! choice is discarded silently
13//! - a typo in `available_tools` matches nothing, and the stage just advertises
14//! one tool fewer - the model is told the tool does not exist
15//! - an autonomous stage granting `ask_user_text` parks in `WaitingInput` the
16//! first time it asks, with nobody there to answer
17//!
18//! Each of those is invisible on inspection and shows up hours later as a stuck
19//! run. This module names them at author time instead.
20//!
21//! Questions about what the author *declared* ("is there a `mode` key?") are
22//! answered from the manifest text, not from the parsed [`Blueprint`]: by then
23//! the parser has already filled in its defaults, and asking the struct cannot
24//! tell "wrote `autonomous`" apart from "wrote nothing".
25//!
26//! [`Blueprint::validate`]: leviath_core::Blueprint::validate
27
28use std::collections::{HashMap, HashSet};
29use std::path::{Path, PathBuf};
30
31use leviath_core::Blueprint;
32use leviath_core::blueprint::StageMode;
33use leviath_runtime::dynamic_interaction::BLOCKING_INTERACTION_TOOLS;
34use leviath_tools::canonical_tool_name;
35use serde::{Deserialize, Serialize};
36
37/// How much a finding matters. Only [`LintSeverity::Error`] fails
38/// `lev validate`; warnings are printed and the command still exits zero
39/// (unless `--deny-warnings` is passed); notes never fail anything.
40///
41/// Declared worst-first so sorting by it groups the report.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
43#[serde(rename_all = "lowercase")]
44pub enum LintSeverity {
45 /// The manifest says something that cannot be what the author meant - a
46 /// tool name matching nothing, a permission for a tool the stage never
47 /// granted.
48 Error,
49 /// The manifest leaves a decision to a default the author may not know
50 /// about.
51 Warning,
52 /// Nothing is wrong; the blueprint is doing something worth knowing before
53 /// you run it, like reaching outside its workdir or running a shell command
54 /// at spawn. A note must never fail a build, so `--deny-warnings` skips it.
55 Note,
56}
57
58impl LintSeverity {
59 /// Fixed-width label for the report, so the messages line up.
60 pub fn label(self) -> &'static str {
61 match self {
62 Self::Error => "ERR ",
63 Self::Warning => "WARN",
64 Self::Note => "NOTE",
65 }
66 }
67}
68
69/// One thing worth telling the author about.
70///
71/// Serialize only: `code` is a `&'static str` pointing at a literal in this
72/// file, which no deserializer can produce.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
74pub struct LintFinding {
75 /// How much this matters, and therefore whether it fails the check.
76 pub severity: LintSeverity,
77 /// Stable slug (`"unknown-tool"`), so a finding can be referenced in an
78 /// issue or grepped for in daemon logs without quoting prose.
79 pub code: &'static str,
80 /// The stage it belongs to, when it belongs to one.
81 pub stage: Option<String>,
82 /// What is wrong.
83 pub message: String,
84 /// What to do about it. Rendered on its own indented line.
85 pub fix: Option<String>,
86}
87
88impl LintFinding {
89 fn new(severity: LintSeverity, code: &'static str, message: String) -> Self {
90 Self {
91 severity,
92 code,
93 stage: None,
94 message,
95 fix: None,
96 }
97 }
98
99 fn in_stage(mut self, stage: &str) -> Self {
100 self.stage = Some(stage.to_string());
101 self
102 }
103
104 fn with_fix(mut self, fix: impl Into<String>) -> Self {
105 self.fix = Some(fix.into());
106 self
107 }
108
109 /// Whether this finding should fail the command.
110 pub fn is_error(&self) -> bool {
111 self.severity == LintSeverity::Error
112 }
113
114 /// One-line rendering for a log record: `stage 'x': message`.
115 pub fn one_line(&self) -> String {
116 match &self.stage {
117 Some(stage) => format!("stage '{stage}': {}", self.message),
118 None => self.message.clone(),
119 }
120 }
121}
122
123/// Facts about the machine the blueprint will run on, which the manifest alone
124/// cannot supply.
125///
126/// Every field is "unknown" when empty/`None`, and an unknown field skips its
127/// check entirely rather than guessing. A linter that cannot see the installed
128/// MCP servers must not claim their tools do not exist.
129#[derive(Debug, Default, Clone)]
130pub struct LintEnv {
131 /// Every tool name a manifest may legally write: canonical built-ins, their
132 /// aliases, the sub-agent tools, this agent's own `tools/*.rhai`, and any
133 /// MCP tools already resolved. Empty skips the unknown-tool check.
134 pub known_tools: HashSet<String>,
135
136 /// `(provider, model)` rows for providers whose catalog is closed enough to
137 /// check against. A provider with no row here is not checked at all, which
138 /// is what keeps open catalogs (Ollama, OpenRouter, script providers) from
139 /// producing noise.
140 pub known_models: Vec<(String, String)>,
141
142 /// The providers the blueprint names that this install can actually reach,
143 /// as answered by `ProviderRegistry::has`. `None` means nobody asked, so
144 /// the check is skipped. Resolution lives with the caller because script
145 /// providers are loaded on demand and cannot be enumerated up front.
146 pub available_providers: Option<HashSet<String>>,
147
148 /// Which of the blueprint's `[read_paths]` this install's config grants.
149 /// `None` means nobody asked (the daemon's offline lint), in which case the
150 /// check only says that a declaration needs granting. `Some(Err(..))` is a
151 /// grant list of the user's own that will not compile.
152 pub read_paths: Option<Result<crate::read_path_report::GrantReport, String>>,
153
154 /// Whether this install's config honours the blueprint's own
155 /// `[safe_commands]`. `None` means nobody asked (the daemon's offline
156 /// lint), in which case the check only says the declaration needs granting.
157 ///
158 /// A bool rather than a report: unlike read paths, where *which* entries are
159 /// granted is the interesting part, a safe-commands block is honoured whole
160 /// or not at all.
161 pub safe_commands_granted: Option<bool>,
162}
163
164impl LintEnv {
165 /// Everything that can be known without touching the user's config: the
166 /// built-in tools (aliases included), the sub-agent tools, the script tools
167 /// in `agent_dir/tools` and the global tools directory, and the model
168 /// catalogs this build ships.
169 ///
170 /// This is what the daemon lints against at spawn. It deliberately leaves
171 /// `available_providers` unset: the daemon already fails a spawn outright
172 /// when no listed provider is registered, so re-deriving that here would
173 /// cost a registry build per agent to say something the spawn will say
174 /// louder a moment later.
175 pub fn offline(agent_dir: &Path) -> Self {
176 let mut known_tools: HashSet<String> = leviath_tools::BuiltinTools::new(
177 leviath_tools::ToolContext::new(agent_dir.to_path_buf()),
178 )
179 .names()
180 .into_iter()
181 .collect();
182 known_tools.extend(leviath_tools::BuiltinTools::subagent_tool_names());
183
184 // The agent's own `tools/`, plus the global one every agent gets.
185 let dirs: Vec<PathBuf> = [Some(agent_dir.join("tools")), leviath_core::tools_dir()]
186 .into_iter()
187 .flatten()
188 .filter(|d| d.is_dir())
189 .collect();
190 let (set, _skipped) = leviath_scripting::ScriptToolSet::discover(&dirs);
191 known_tools.extend(set.names());
192
193 Self {
194 known_tools,
195 known_models: crate::commands::models::closed_catalog_models(),
196 available_providers: None,
197 read_paths: None,
198 safe_commands_granted: None,
199 }
200 }
201
202 /// Add the answer to "can this install reach the providers the blueprint
203 /// names", asked of the same registry the runtime resolves stages against
204 /// so a script provider counts exactly when it would really load.
205 pub fn with_providers(mut self, blueprint: &Blueprint, config: &crate::config::Config) -> Self {
206 let registry = crate::commands::run::build_provider_registry_from_config(config);
207 self.available_providers = Some(
208 blueprint
209 .stages
210 .iter()
211 .flat_map(|s| s.model.models.iter())
212 .map(|e| e.provider.clone())
213 .filter(|p| registry.as_ref().is_ok_and(|r| r.has(p)))
214 .collect(),
215 );
216 self
217 }
218
219 /// Add the answer to "does this install's config grant what the blueprint
220 /// declares under `[read_paths]`", per entry.
221 ///
222 /// Separate from [`Self::with_providers`] because it needs a workdir:
223 /// relative entries resolve against the one a run would use, which for a
224 /// command run outside a run is the directory it was invoked from.
225 pub fn with_read_paths(
226 mut self,
227 blueprint: &Blueprint,
228 config: &crate::config::Config,
229 workdir: &Path,
230 ) -> Self {
231 self.read_paths = crate::read_path_report::build(blueprint, config, workdir);
232 // Asked here rather than in its own builder: both answers come from the
233 // same config, and a caller that has one always has the other.
234 self.safe_commands_granted = Some(
235 config.security.allow_blueprint_safe_commands
236 || config
237 .agent_safe_commands
238 .get(&blueprint.name)
239 .is_some_and(|a| a.allow_blueprint),
240 );
241 self
242 }
243}
244
245/// Lint `blueprint`, which was parsed from `content`.
246///
247/// The two arguments describe the same manifest: `blueprint` for what the
248/// engine will do with it, `content` for what the author actually wrote.
249pub fn lint_manifest(content: &str, blueprint: &Blueprint, env: &LintEnv) -> Vec<LintFinding> {
250 let declared = Declared::from_text(content);
251 let mut findings = Vec::new();
252
253 if declared.agent_model_block {
254 findings.push(
255 LintFinding::new(
256 LintSeverity::Warning,
257 "agent-model-block-ignored",
258 "the top-level [model] block is not read by anything: model \
259 selection is per stage"
260 .to_string(),
261 )
262 .with_fix("move it into each [stages.<name>.model] that needs it"),
263 );
264 }
265
266 findings.extend(lint_dropped_seeds(&declared, blueprint));
267 findings.extend(lint_command_seeds(blueprint));
268 findings.extend(lint_read_paths(blueprint, env));
269 findings.extend(lint_safe_commands(blueprint, env));
270 findings.extend(lint_held_checkpoints(blueprint));
271 findings.extend(lint_graph(blueprint));
272 findings.extend(lint_output_reachable(blueprint));
273 findings.extend(lint_dead_end_possible(blueprint));
274 findings.extend(lint_compacted_deliverables(blueprint));
275
276 let agent_permissions = blueprint.agent_tool_permissions();
277
278 for stage in &blueprint.stages {
279 let keys = declared.stage(&stage.name);
280 findings.extend(lint_declarations(stage, keys));
281 findings.extend(lint_tools(stage, env));
282 findings.extend(lint_blocking_tools(stage));
283 findings.extend(lint_tool_policies(stage, &agent_permissions));
284 findings.extend(lint_models(stage, env));
285 findings.extend(lint_output_stage(stage));
286 }
287
288 // Worst first, stable within a severity so the order a check ran in is the
289 // order its findings read in.
290 findings.sort_by_key(|f| f.severity);
291 findings
292}
293
294/// A region wrote a `seed` the parser could not read, so it has none.
295///
296/// `parse_region_seed` returns `None` for a seed table with no recognized key
297/// and for a seed that is neither a string nor a table, and the region then
298/// simply starts empty. That is deliberate - an unknown key is not worth
299/// rejecting a whole manifest over - but it is invisible, and a one-character
300/// typo (`caller_input` for `caller`) reads exactly like a working blueprint
301/// until an agent answers a question it was never given. This is the check that
302/// says so.
303fn lint_dropped_seeds(declared: &Declared, blueprint: &Blueprint) -> Vec<LintFinding> {
304 declared
305 .seeded_regions
306 .iter()
307 .filter(|name| {
308 blueprint
309 .context_layout
310 .get_region(name)
311 .is_some_and(|r| r.seed.is_none())
312 })
313 .map(|name| {
314 LintFinding::new(
315 LintSeverity::Warning,
316 "region-seed-not-understood",
317 format!(
318 "region '{name}' declares a seed that isn't one of the \
319 recognized forms, so it is ignored and the region starts empty"
320 ),
321 )
322 .with_fix(
323 "use a string (the caller input key), or one of \
324 { caller = }, { literal = }, { files = }, { glob = }, \
325 { rhai = }, { command = }",
326 )
327 })
328 .collect()
329}
330
331// ─── Declared keys ────────────────────────────────────────────────────────────
332
333/// Which optional keys the manifest text actually writes, per stage, plus the
334/// one agent-level block that is silently discarded.
335#[derive(Debug, Default)]
336struct Declared {
337 /// A top-level `[model]` table exists. Nothing reads it.
338 agent_model_block: bool,
339 /// Regions whose text writes a `seed` key, whatever its shape. Compared
340 /// against the parsed seed to catch the ones the parser threw away.
341 seeded_regions: Vec<String>,
342 /// Per stage name, the keys that stage wrote.
343 stages: HashMap<String, StageKeys>,
344 /// The manifest text could not be re-read. Every key is then reported as
345 /// declared, so an unreadable manifest produces no declaration warnings
346 /// rather than a full set of false ones.
347 opaque: bool,
348}
349
350#[derive(Debug, Default, Clone, Copy)]
351struct StageKeys {
352 mode: bool,
353 model: bool,
354}
355
356impl Declared {
357 fn from_text(content: &str) -> Self {
358 // `toml::from_str` and not `str::parse`: the latter deserializes a bare
359 // TOML *value*, not a document, and rejects every real manifest.
360 let Ok(root) = toml::from_str::<toml::Table>(content) else {
361 return Self {
362 opaque: true,
363 ..Self::default()
364 };
365 };
366 let agent_model_block = root.get("model").is_some_and(toml::Value::is_table);
367 // Both region spellings - inline `name = { seed = ... }` under
368 // `[context.regions]` and a `[context.regions.name]` section - land here
369 // as the same nested table, so one path covers both.
370 let seeded_regions = root
371 .get("context")
372 .and_then(toml::Value::as_table)
373 .and_then(|c| c.get("regions"))
374 .and_then(toml::Value::as_table)
375 .map(|regions| {
376 regions
377 .iter()
378 .filter(|(_, body)| body.get("seed").is_some())
379 .map(|(name, _)| name.clone())
380 .collect()
381 })
382 .unwrap_or_default();
383 let stages = root
384 .get("stages")
385 .and_then(toml::Value::as_table)
386 .map(|t| {
387 t.iter()
388 .map(|(name, body)| {
389 (
390 name.clone(),
391 StageKeys {
392 mode: body.get("mode").is_some(),
393 model: body.get("model").is_some(),
394 },
395 )
396 })
397 .collect()
398 })
399 .unwrap_or_default();
400 Self {
401 agent_model_block,
402 seeded_regions,
403 stages,
404 opaque: false,
405 }
406 }
407
408 /// What `stage` declared. An unreadable manifest, or a stage the text has
409 /// no entry for, reports everything as declared so nothing is warned about.
410 fn stage(&self, stage: &str) -> StageKeys {
411 if self.opaque {
412 return StageKeys {
413 mode: true,
414 model: true,
415 };
416 }
417 self.stages.get(stage).copied().unwrap_or(StageKeys {
418 mode: true,
419 model: true,
420 })
421 }
422}
423
424// ─── Checks ───────────────────────────────────────────────────────────────────
425
426// The checks themselves, one module per question they answer. Imported rather
427// than re-exported: `lint_manifest` is the only caller and the only entry point
428// anyone outside this module needs, so the individual checks stay internal.
429mod checks;
430use checks::*;
431mod security;
432use security::*;
433
434#[cfg(test)]
435mod tests;