Skip to main content

cuttlefish_core/
spec.rs

1//! Parsing `Cuttlefish.spec` files.
2//!
3//! # Scope, and why this is a scanner rather than a parser library
4//!
5//! The language this project is heading toward is a typed DSL with `let`-bound
6//! pipelines, block signatures, and inference over them. This is not that. It
7//! reads a deliberately flat subset — a `spec NAME = { key = value; ... }` block
8//! with a fixed set of keys — because that is all the first working end-to-end
9//! job needs.
10//!
11//! Reaching for a parser-combinator library before the grammar has expressions
12//! in it would be building the abstraction for a language that does not exist
13//! yet, against guesses about its shape. When the pipeline syntax lands, this
14//! module gets replaced rather than extended.
15//!
16//! The `nodes = { ... }` / `branches = { ... }` graph syntax added since is not
17//! that pipeline syntax: it is still the same flat `key = value` grammar, just
18//! shaped to describe a graph, with no expressions or inference beyond the
19//! `node.out` reference syntax itself.
20//!
21//! # Why it refuses so much
22//!
23//! A spec grants capabilities. Every accepted-but-misunderstood construct is a
24//! job running under permissions nobody wrote down, so anything not fully
25//! understood is an error:
26//!
27//! - An unknown key is rejected rather than skipped. Silently ignoring one is
28//!   how a misspelled `capabilities` becomes a spec with no capabilities that
29//!   still runs — and looks fine.
30//! - An unsupported model kind or capability kind is rejected by name, rather
31//!   than being treated as the nearest supported thing.
32//!
33//! Being liberal in what it accepts would be exactly the wrong instinct here.
34
35use std::path::{Path, PathBuf};
36use thiserror::Error;
37
38/// Where a job's model comes from.
39///
40/// Deliberately *not* an enum of known providers. Inference can come from a
41/// local Ollama, an OpenAI-compatible HTTP endpoint, an embedded llama.cpp, or
42/// something not thought of yet, and this crate has no business knowing which
43/// of those exist — it parses job descriptions.
44///
45/// So a model reference is a provider name and a target, and resolving one into
46/// something that can actually generate is the host's job, via its backend
47/// registry. Adding a provider therefore touches neither this type nor the
48/// parser: an unknown provider is a resolution error naming what *is*
49/// available, not a syntax error.
50///
51/// In a spec this is written `model = Provider "target"`:
52///
53/// ```text
54/// model = Ollama "llama3.2:1b";          // a local Ollama
55/// model = OpenAi "http://host/v1#gpt-4"; // an OpenAI-compatible endpoint
56/// model = Path "./models/qwen.gguf";     // a local file, for embedded runtimes
57/// ```
58#[derive(Debug, Clone, PartialEq, Eq, Hash)]
59pub struct ModelRef {
60    /// Which backend should serve this, lowercased — `ollama`, `path`, `stub`.
61    ///
62    /// Lowercased at parse time so that `Ollama` and `OLLAMA` name the same
63    /// provider; a spec should not fail over capitalisation.
64    pub provider: String,
65    /// What to ask that backend for. Its meaning belongs entirely to the
66    /// provider: a model tag for Ollama, a filesystem path for an embedded
67    /// runtime, a URL for an HTTP endpoint.
68    pub target: String,
69}
70
71impl ModelRef {
72    /// Construct a reference directly, mostly for tests and for callers
73    /// building a spec without parsing one.
74    pub fn new(provider: impl Into<String>, target: impl Into<String>) -> Self {
75        Self {
76            provider: provider.into().to_lowercase(),
77            target: target.into(),
78        }
79    }
80}
81
82impl std::fmt::Display for ModelRef {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        write!(f, "{}:{}", self.provider, self.target)
85    }
86}
87
88/// How a job's data may be handled.
89///
90/// This is discovery metadata, consumed by the agent harness — it is *not*
91/// enforcement. What actually gates file access is the capability list, checked
92/// by the host at runtime. The distinction matters: `data_policy` tells the
93/// calling *agent* to behave differently (pass paths, not contents), while
94/// capabilities tell the *sandbox* what it may touch.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum DataPolicy {
97    /// Content must not leave the machine; the agent should pass paths.
98    LocalOnly,
99    /// No special handling requested.
100    Any,
101}
102
103/// A parsed spec.
104#[derive(Debug, Clone, PartialEq)]
105pub struct Spec {
106    /// Job name, used to submit against it.
107    pub name: String,
108    /// Trigger conditions for a calling agent — when to use this, never how it
109    /// works. A description that summarises the workflow invites an agent to
110    /// act on the summary instead of reading the real contract.
111    pub description: String,
112    /// Which model serves this job's inference.
113    pub model: ModelRef,
114    /// Data-handling policy; see [`DataPolicy`].
115    pub data_policy: DataPolicy,
116    /// Directories this job may read beneath. Empty means none.
117    pub read_roots: Vec<PathBuf>,
118    /// The proc-blocks implementing the job, as a graph of nodes.
119    ///
120    /// Each node's declared input is typechecked against the nodes feeding
121    /// it before anything runs. `block = "...";` is sugar for a one-node
122    /// graph — see [`crate::graph::NodeGraph::single`].
123    pub nodes: crate::graph::NodeGraph,
124    /// Conditional dispatch: which branch target fires for each labeled
125    /// route a branching node produces. Empty when the spec has none.
126    pub branches: crate::graph::Branches,
127}
128
129/// Why a spec was rejected.
130#[derive(Debug, Error, PartialEq, Eq)]
131pub enum SpecError {
132    /// A required key was absent.
133    #[error("missing required field `{0}`")]
134    MissingField(&'static str),
135    /// A key that this version does not understand.
136    #[error("unknown field `{0}`")]
137    UnknownField(String),
138    /// Structurally malformed input.
139    #[error("malformed spec: {0}")]
140    Malformed(String),
141    /// A capability kind that exists in the design but not in this build.
142    #[error("unsupported capability `{0}` (this build supports only `Read`)")]
143    UnsupportedCapability(String),
144}
145
146use crate::lex::{lex, Tok, Token};
147
148/// Whether `root` contains `candidate`, comparing on meaningful path
149/// components only.
150///
151/// Not `Path::starts_with`: a leading `./` is a real `Component::CurDir`, so
152/// `Path::new("./corpus/m.jsonl").starts_with("corpus")` is `false` — and a
153/// spec author writing `capabilities = [ Read "corpus" ]` beside
154/// `over = "./corpus/m.jsonl"` has no reason to expect one spelling of the
155/// same directory to be rejected.
156fn path_covers(root: &Path, candidate: &Path) -> bool {
157    fn significant(p: &Path) -> Vec<std::ffi::OsString> {
158        p.components()
159            .filter(|c| !matches!(c, std::path::Component::CurDir))
160            .map(|c| c.as_os_str().to_os_string())
161            .collect()
162    }
163    candidate_starts_with(&significant(candidate), &significant(root))
164}
165
166fn candidate_starts_with(candidate: &[std::ffi::OsString], root: &[std::ffi::OsString]) -> bool {
167    candidate.len() >= root.len() && candidate[..root.len()] == *root
168}
169
170impl Spec {
171    /// Refuse a spec whose host-read paths sit outside its granted roots.
172    ///
173    /// Fan-out manifests and acceptance schemas are read by the *host*,
174    /// which is not sandboxed — so nothing would otherwise stop either
175    /// reading a path the spec never granted. Requiring them inside a
176    /// declared `Read` root keeps the capability list a truthful description
177    /// of everything the job touches, which is the property the whole
178    /// capability model rests on.
179    ///
180    /// Call this **after** resolving `read_roots`, `over` and schema paths
181    /// against the spec's directory, so both sides are absolute and
182    /// canonical. Comparing them as written cannot work: a spec that grants
183    /// an absolute root and names a relative manifest is entirely ordinary,
184    /// and lexically a relative path never starts with an absolute one.
185    pub fn validate_host_read_paths(&self) -> Result<(), SpecError> {
186        for (name, node) in &self.nodes.nodes {
187            if let Some(manifest) = &node.over {
188                if !self
189                    .read_roots
190                    .iter()
191                    .any(|root| path_covers(root, manifest))
192                {
193                    return Err(SpecError::Malformed(format!(
194                        "node `{name}`'s manifest {} is outside every path granted by \
195                         `capabilities` — add a `Read` covering it. Granted: {}",
196                        manifest.display(),
197                        roots_for_error(&self.read_roots)
198                    )));
199                }
200            }
201            for check in &node.accept {
202                if let crate::graph::AcceptCheck::Schema(schema) = check {
203                    if !self.read_roots.iter().any(|root| path_covers(root, schema)) {
204                        return Err(SpecError::Malformed(format!(
205                            "node `{name}`'s accept schema {} is outside every path granted \
206                             by `capabilities` — add a `Read` covering it. Granted: {}",
207                            schema.display(),
208                            roots_for_error(&self.read_roots)
209                        )));
210                    }
211                }
212            }
213        }
214        Ok(())
215    }
216}
217
218/// Granted roots, for an error message.
219///
220/// Listed because the failure is nearly always a path that looks right: the
221/// grant and the target differ by a symlink, or by one being relative. Naming
222/// what *was* granted turns a guess into a comparison.
223fn roots_for_error(roots: &[PathBuf]) -> String {
224    if roots.is_empty() {
225        return "(nothing)".to_string();
226    }
227    roots
228        .iter()
229        .map(|r| r.display().to_string())
230        .collect::<Vec<_>>()
231        .join(", ")
232}
233
234/// Parse a spec.
235///
236/// Recursive descent over tokens, not splitting on punctuation — see
237/// [`crate::lex`] for why that distinction is load-bearing rather than
238/// stylistic.
239pub fn parse_spec(src: &str) -> Result<Spec, SpecError> {
240    let tokens = lex(src).map_err(|e| SpecError::Malformed(e.to_string()))?;
241    Parser {
242        tokens: &tokens,
243        at: 0,
244    }
245    .spec()
246}
247
248struct Parser<'a> {
249    tokens: &'a [Token],
250    at: usize,
251}
252
253impl<'a> Parser<'a> {
254    fn peek(&self) -> Option<&'a Tok> {
255        self.tokens.get(self.at).map(|t| &t.tok)
256    }
257
258    /// Describe where the parser is, for an error message.
259    fn here(&self) -> String {
260        match self.tokens.get(self.at) {
261            Some(t) => format!("{} at {}", t.tok.describe(), t.span),
262            None => "end of input".into(),
263        }
264    }
265
266    fn advance(&mut self) -> Option<&'a Token> {
267        let t = self.tokens.get(self.at);
268        if t.is_some() {
269            self.at += 1;
270        }
271        t
272    }
273
274    fn expect(&mut self, want: &Tok) -> Result<(), SpecError> {
275        match self.peek() {
276            Some(got) if got == want => {
277                self.at += 1;
278                Ok(())
279            }
280            _ => Err(SpecError::Malformed(format!(
281                "expected {}, found {}",
282                want.describe(),
283                self.here()
284            ))),
285        }
286    }
287
288    fn ident(&mut self) -> Result<String, SpecError> {
289        match self.advance().map(|t| &t.tok) {
290            Some(Tok::Ident(name)) => Ok(name.clone()),
291            _ => {
292                self.at = self.at.saturating_sub(1);
293                Err(SpecError::Malformed(format!(
294                    "expected a name, found {}",
295                    self.here()
296                )))
297            }
298        }
299    }
300
301    fn string(&mut self, field: &str) -> Result<String, SpecError> {
302        match self.advance().map(|t| &t.tok) {
303            Some(Tok::Str(value)) => Ok(value.clone()),
304            _ => {
305                self.at = self.at.saturating_sub(1);
306                Err(SpecError::Malformed(format!(
307                    "field `{field}` must be a quoted string, found {}",
308                    self.here()
309                )))
310            }
311        }
312    }
313
314    /// `spec NAME = { field* }`
315    fn spec(&mut self) -> Result<Spec, SpecError> {
316        match self.ident()?.as_str() {
317            "spec" => {}
318            other => {
319                return Err(SpecError::Malformed(format!(
320                    "a spec file starts with `spec`, found `{other}`"
321                )))
322            }
323        }
324        let name = self.ident()?;
325        self.expect(&Tok::Equals)?;
326        self.expect(&Tok::OpenBrace)?;
327
328        let (mut description, mut model, mut data_policy, mut read_roots, mut nodes, mut branches) =
329            (None, None, None, None, None, None);
330
331        while self.peek().is_some() && self.peek() != Some(&Tok::CloseBrace) {
332            let key = self.ident()?;
333            self.expect(&Tok::Equals)?;
334
335            match key.as_str() {
336                "description" => description = Some(self.string("description")?),
337                "block" => {
338                    nodes = Some(crate::graph::NodeGraph::single(PathBuf::from(
339                        self.string("block")?,
340                    )))
341                }
342                "nodes" => {
343                    let (g, new_at) = crate::graph::GraphParser {
344                        tokens: self.tokens,
345                        at: self.at,
346                    }
347                    .node_graph()?;
348                    self.at = new_at; // advance Parser's own cursor past what GraphParser consumed
349                    nodes = Some(g);
350                }
351                "branches" => {
352                    let (b, new_at) = crate::graph::GraphParser {
353                        tokens: self.tokens,
354                        at: self.at,
355                    }
356                    .branches()?;
357                    self.at = new_at;
358                    branches = Some(b);
359                }
360                "capabilities" => read_roots = Some(self.capabilities()?),
361                "model" => model = Some(self.model()?),
362                "data_policy" => {
363                    data_policy = Some(match self.ident()?.as_str() {
364                        "Local_only" => DataPolicy::LocalOnly,
365                        "Any" => DataPolicy::Any,
366                        other => {
367                            return Err(SpecError::Malformed(format!(
368                                "unknown data_policy `{other}`"
369                            )))
370                        }
371                    })
372                }
373                other => return Err(SpecError::UnknownField(other.to_string())),
374            }
375
376            // A trailing semicolon is conventional but not required — and,
377            // unlike before, one *inside* a string is just a character.
378            if self.peek() == Some(&Tok::Semicolon) {
379                self.at += 1;
380            }
381        }
382        self.expect(&Tok::CloseBrace)?;
383
384        let read_roots = read_roots.ok_or(SpecError::MissingField("capabilities"))?;
385        let nodes = nodes.ok_or(SpecError::MissingField("block"))?;
386
387        // The equivalent check on manifests and acceptance schemas lives in
388        // `validate_host_read_paths`, called once these paths have been
389        // resolved against the spec's directory. It cannot be done here: a
390        // spec may grant an absolute root and name a relative manifest, and
391        // comparing those as written is not merely imprecise but *always*
392        // wrong — a relative path can never begin with an absolute one, so
393        // every such spec was rejected regardless of where the file actually
394        // sat.
395
396        Ok(Spec {
397            name,
398            description: description.ok_or(SpecError::MissingField("description"))?,
399            model: model.ok_or(SpecError::MissingField("model"))?,
400            data_policy: data_policy.ok_or(SpecError::MissingField("data_policy"))?,
401            read_roots,
402            nodes,
403            branches: branches.unwrap_or_default(),
404        })
405    }
406
407    /// `Provider "target"`
408    fn model(&mut self) -> Result<ModelRef, SpecError> {
409        let provider = self.ident()?;
410        if provider.is_empty() || !provider.chars().all(|c| c.is_alphanumeric() || c == '_') {
411            return Err(SpecError::Malformed(format!(
412                "`{provider}` is not a valid model provider name"
413            )));
414        }
415        Ok(ModelRef::new(provider, self.string("model")?))
416    }
417
418    /// `[ Read "a", Read "b" ]`
419    fn capabilities(&mut self) -> Result<Vec<PathBuf>, SpecError> {
420        let mut roots = Vec::new();
421        self.expect(&Tok::OpenBracket)?;
422        while self.peek() != Some(&Tok::CloseBracket) {
423            let kind = self.ident()?;
424            if kind != "Read" {
425                return Err(SpecError::UnsupportedCapability(kind));
426            }
427            roots.push(PathBuf::from(self.string("capabilities")?));
428            if self.peek() == Some(&Tok::Comma) {
429                self.at += 1;
430            } else {
431                break;
432            }
433        }
434        self.expect(&Tok::CloseBracket)?;
435        Ok(roots)
436    }
437}