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
170/// Parse a spec.
171///
172/// Recursive descent over tokens, not splitting on punctuation — see
173/// [`crate::lex`] for why that distinction is load-bearing rather than
174/// stylistic.
175pub fn parse_spec(src: &str) -> Result<Spec, SpecError> {
176 let tokens = lex(src).map_err(|e| SpecError::Malformed(e.to_string()))?;
177 Parser {
178 tokens: &tokens,
179 at: 0,
180 }
181 .spec()
182}
183
184struct Parser<'a> {
185 tokens: &'a [Token],
186 at: usize,
187}
188
189impl<'a> Parser<'a> {
190 fn peek(&self) -> Option<&'a Tok> {
191 self.tokens.get(self.at).map(|t| &t.tok)
192 }
193
194 /// Describe where the parser is, for an error message.
195 fn here(&self) -> String {
196 match self.tokens.get(self.at) {
197 Some(t) => format!("{} at {}", t.tok.describe(), t.span),
198 None => "end of input".into(),
199 }
200 }
201
202 fn advance(&mut self) -> Option<&'a Token> {
203 let t = self.tokens.get(self.at);
204 if t.is_some() {
205 self.at += 1;
206 }
207 t
208 }
209
210 fn expect(&mut self, want: &Tok) -> Result<(), SpecError> {
211 match self.peek() {
212 Some(got) if got == want => {
213 self.at += 1;
214 Ok(())
215 }
216 _ => Err(SpecError::Malformed(format!(
217 "expected {}, found {}",
218 want.describe(),
219 self.here()
220 ))),
221 }
222 }
223
224 fn ident(&mut self) -> Result<String, SpecError> {
225 match self.advance().map(|t| &t.tok) {
226 Some(Tok::Ident(name)) => Ok(name.clone()),
227 _ => {
228 self.at = self.at.saturating_sub(1);
229 Err(SpecError::Malformed(format!(
230 "expected a name, found {}",
231 self.here()
232 )))
233 }
234 }
235 }
236
237 fn string(&mut self, field: &str) -> Result<String, SpecError> {
238 match self.advance().map(|t| &t.tok) {
239 Some(Tok::Str(value)) => Ok(value.clone()),
240 _ => {
241 self.at = self.at.saturating_sub(1);
242 Err(SpecError::Malformed(format!(
243 "field `{field}` must be a quoted string, found {}",
244 self.here()
245 )))
246 }
247 }
248 }
249
250 /// `spec NAME = { field* }`
251 fn spec(&mut self) -> Result<Spec, SpecError> {
252 match self.ident()?.as_str() {
253 "spec" => {}
254 other => {
255 return Err(SpecError::Malformed(format!(
256 "a spec file starts with `spec`, found `{other}`"
257 )))
258 }
259 }
260 let name = self.ident()?;
261 self.expect(&Tok::Equals)?;
262 self.expect(&Tok::OpenBrace)?;
263
264 let (mut description, mut model, mut data_policy, mut read_roots, mut nodes, mut branches) =
265 (None, None, None, None, None, None);
266
267 while self.peek().is_some() && self.peek() != Some(&Tok::CloseBrace) {
268 let key = self.ident()?;
269 self.expect(&Tok::Equals)?;
270
271 match key.as_str() {
272 "description" => description = Some(self.string("description")?),
273 "block" => {
274 nodes = Some(crate::graph::NodeGraph::single(PathBuf::from(
275 self.string("block")?,
276 )))
277 }
278 "nodes" => {
279 let (g, new_at) = crate::graph::GraphParser {
280 tokens: self.tokens,
281 at: self.at,
282 }
283 .node_graph()?;
284 self.at = new_at; // advance Parser's own cursor past what GraphParser consumed
285 nodes = Some(g);
286 }
287 "branches" => {
288 let (b, new_at) = crate::graph::GraphParser {
289 tokens: self.tokens,
290 at: self.at,
291 }
292 .branches()?;
293 self.at = new_at;
294 branches = Some(b);
295 }
296 "capabilities" => read_roots = Some(self.capabilities()?),
297 "model" => model = Some(self.model()?),
298 "data_policy" => {
299 data_policy = Some(match self.ident()?.as_str() {
300 "Local_only" => DataPolicy::LocalOnly,
301 "Any" => DataPolicy::Any,
302 other => {
303 return Err(SpecError::Malformed(format!(
304 "unknown data_policy `{other}`"
305 )))
306 }
307 })
308 }
309 other => return Err(SpecError::UnknownField(other.to_string())),
310 }
311
312 // A trailing semicolon is conventional but not required — and,
313 // unlike before, one *inside* a string is just a character.
314 if self.peek() == Some(&Tok::Semicolon) {
315 self.at += 1;
316 }
317 }
318 self.expect(&Tok::CloseBrace)?;
319
320 let read_roots = read_roots.ok_or(SpecError::MissingField("capabilities"))?;
321 let nodes = nodes.ok_or(SpecError::MissingField("block"))?;
322
323 // Fan-out manifests and acceptance schemas are both read by the
324 // *host*, which is not sandboxed — so nothing would stop either
325 // reading a path the spec never granted. Requiring them inside a
326 // declared `Read` root keeps the capability list a truthful
327 // description of everything the job touches, which is the property
328 // the whole capability model rests on.
329 for (name, node) in &nodes.nodes {
330 if let Some(manifest) = &node.over {
331 if !read_roots.iter().any(|root| path_covers(root, manifest)) {
332 return Err(SpecError::Malformed(format!(
333 "node `{name}`'s manifest {} is outside every path granted by \
334 `capabilities` — add a `Read` for it",
335 manifest.display()
336 )));
337 }
338 }
339 for check in &node.accept {
340 if let crate::graph::AcceptCheck::Schema(schema) = check {
341 if !read_roots.iter().any(|root| path_covers(root, schema)) {
342 return Err(SpecError::Malformed(format!(
343 "node `{name}`'s accept schema {} is outside every path granted by \
344 `capabilities` — add a `Read` for it",
345 schema.display()
346 )));
347 }
348 }
349 }
350 }
351
352 Ok(Spec {
353 name,
354 description: description.ok_or(SpecError::MissingField("description"))?,
355 model: model.ok_or(SpecError::MissingField("model"))?,
356 data_policy: data_policy.ok_or(SpecError::MissingField("data_policy"))?,
357 read_roots,
358 nodes,
359 branches: branches.unwrap_or_default(),
360 })
361 }
362
363 /// `Provider "target"`
364 fn model(&mut self) -> Result<ModelRef, SpecError> {
365 let provider = self.ident()?;
366 if provider.is_empty() || !provider.chars().all(|c| c.is_alphanumeric() || c == '_') {
367 return Err(SpecError::Malformed(format!(
368 "`{provider}` is not a valid model provider name"
369 )));
370 }
371 Ok(ModelRef::new(provider, self.string("model")?))
372 }
373
374 /// `[ Read "a", Read "b" ]`
375 fn capabilities(&mut self) -> Result<Vec<PathBuf>, SpecError> {
376 let mut roots = Vec::new();
377 self.expect(&Tok::OpenBracket)?;
378 while self.peek() != Some(&Tok::CloseBracket) {
379 let kind = self.ident()?;
380 if kind != "Read" {
381 return Err(SpecError::UnsupportedCapability(kind));
382 }
383 roots.push(PathBuf::from(self.string("capabilities")?));
384 if self.peek() == Some(&Tok::Comma) {
385 self.at += 1;
386 } else {
387 break;
388 }
389 }
390 self.expect(&Tok::CloseBracket)?;
391 Ok(roots)
392 }
393}