Skip to main content

eclipse_core/
prompt_blocks.rs

1//! The standing instructions that ride after the configured system prompt (`#244`).
2//!
3//! `[agent] system_prompt` is one sentence, and the context files are the user's own words. Neither
4//! tells a model *how* to behave with tools, and the failures that cost a turn — prose instead of a
5//! call, a claim of success with no read-back, three identifiers "repaired" into one — are properties
6//! of a model family rather than of the project. So a small library of blocks lives here, each with a
7//! gate over the model name, and `[agent] prompt_blocks` decides which of them are sent: `auto` (the
8//! default) takes every block whose gate matches, a list of names takes exactly those, and `off` sends
9//! none.
10//!
11//! The gate is a substring match on the model name, which is all a request knows about the model
12//! before it asks anything. It is deliberately narrow: a block that does not match costs nothing,
13//! while one that matches a model it was not written for spends the user's context on advice that
14//! cannot apply. These blocks ship in the *cached prefix* of every request, so the whole set is held
15//! under [`MAX_CHARS`] by a test.
16
17use std::fmt;
18
19/// One block of standing instructions.
20pub struct Block {
21    /// What `[agent] prompt_blocks` names it by.
22    pub name: &'static str,
23    /// The text, sent verbatim under its own heading.
24    pub body: &'static str,
25    /// Model-name fragments this block is for. Empty means every model.
26    ///
27    /// Matched case-insensitively as a substring, the way a backend names a model in practice
28    /// (`gpt-oss:120b`, `mmnuc/gemma-4-12b-it-qat`, `deepseek-v4.1-flash`).
29    pub families: &'static [&'static str],
30}
31
32/// `auto`: every block whose gate matches the model in force.
33pub const AUTO: &str = "auto";
34/// `off`: no block at all — the configured prompt and the context files, nothing more.
35pub const OFF: &str = "off";
36
37/// The ceiling on the whole set, in characters. It ships in every session's cached prefix, so it is
38/// paid for once per session — and a prefix that changes between sessions is a prefix no cache helps.
39pub const MAX_CHARS: usize = 4_000;
40
41/// The two blocks every model gets: they cost a few dozen tokens and they are the ones that transfer.
42const UNIVERSAL_TASK: &str = "task-completion";
43const UNIVERSAL_BATCH: &str = "parallel-tool-calls";
44
45/// The library, in the order the blocks appear in the prompt.
46pub const BLOCKS: &[Block] = &[
47    Block {
48        name: UNIVERSAL_TASK,
49        families: &[],
50        body: "Finish the job. A plan, a stub or a described change is not a result: keep working \
51until the artifact exists and has been exercised, then report what the tool actually returned. \
52Never invent tool output, a file's contents or a test result. When a call fails, say what failed and \
53try another way — a different tool, a different command — before giving up; if nothing works, say \
54exactly what is blocked and why.",
55    },
56    Block {
57        name: UNIVERSAL_BATCH,
58        families: &[],
59        body: "Batch independent tool calls into one reply: calls made together are executed \
60together, while every extra turn resends the whole conversation. Read two files at once; run \
61commands one at a time only when a later call needs an earlier result.",
62    },
63    Block {
64        name: "tool-use-enforcement",
65        families: &[
66            "gpt", "codex", "gemini", "gemma", "grok", "glm", "qwen", "deepseek", "muse",
67        ],
68        body: "Facts about this machine, this repository or this conversation come from a tool, not \
69from memory: counts, arithmetic, dates, file contents, whether a port is open, what a command \
70prints. Do not state a number you did not compute with a tool, and do not describe what a file says \
71without reading it. When the user asks for a change, the tool call is the answer.",
72    },
73    Block {
74        name: "execution-guidance",
75        families: &["gpt", "codex", "grok", "glm", "qwen", "deepseek", "muse"],
76        body: "After a write, read the file back with `read_file` (or read the command's own output) \
77before saying it worked. Keep identifiers, paths and numbers exactly as given: never \"repair\" a \
78token, a case or a spelling that looks wrong — report it instead. Before saying \"all N done\", count \
79what you actually changed and make the number in the sentence match. Prefer `patch` over rewriting a \
80file.",
81    },
82    Block {
83        name: "google-operational",
84        families: &["gemini", "gemma"],
85        body: "One tool call per step: read its result before the next, and keep prose short — state \
86the action, call the tool, report what came back. Do not restate a file you just wrote; cite the \
87path and the lines you changed.",
88    },
89];
90
91/// Whether `name` is a block this build ships.
92pub fn is_block(name: &str) -> bool {
93    BLOCKS.iter().any(|block| block.name == name.trim())
94}
95
96/// Every name this build ships, for a refusal a reader can act on.
97pub fn names() -> Vec<&'static str> {
98    BLOCKS.iter().map(|block| block.name).collect()
99}
100
101/// The block `name`, if this build ships it.
102pub fn block(name: &str) -> Option<&'static Block> {
103    BLOCKS.iter().find(|b| b.name == name.trim())
104}
105
106/// Whether `block` was written for `model`.
107///
108/// An empty gate is every model. Otherwise the match is a case-insensitive substring of the model
109/// name — the one thing available before the backend is asked anything. `contains` is safe here
110/// because a model name is not a URL: the trap `#245` hit (`contains("ollama")` matching
111/// `ollama.com`) was a host, and a host is what a vendor name must not be matched against.
112pub fn fits(block: &Block, model: &str) -> bool {
113    if block.families.is_empty() {
114        return true;
115    }
116    let model = model.trim().to_lowercase();
117    block
118        .families
119        .iter()
120        .any(|family| model.contains(&family.to_lowercase()))
121}
122
123/// The text for a set of names, in library order, each under its own heading.
124pub fn text(names: &[&str]) -> String {
125    let mut out = String::new();
126    for block in BLOCKS.iter().filter(|b| names.contains(&b.name)) {
127        if !out.is_empty() {
128            out.push_str("\n\n");
129        }
130        out.push_str(&format!("## {}\n\n{}", block.name, block.body));
131    }
132    out
133}
134
135/// Which blocks ride in the prompt: `[agent] prompt_blocks`.
136///
137/// Three answers and no fourth: a mode that decides per model (`auto`), a list that decides per name,
138/// and nothing at all. It is one key rather than a boolean per block because the interesting
139/// question is "what is my model being told", and a list of booleans answers it badly.
140#[derive(Debug, Clone, PartialEq, Eq, Default)]
141pub enum Choice {
142    /// Every block whose gate matches the model in force.
143    #[default]
144    Auto,
145    /// No block at all.
146    Off,
147    /// Exactly these, whatever the model.
148    List(Vec<String>),
149}
150
151impl Choice {
152    /// The names in force for `model`, in library order.
153    pub fn names_for(&self, model: &str) -> Vec<&'static str> {
154        match self {
155            Choice::Auto => BLOCKS
156                .iter()
157                .filter(|block| fits(block, model))
158                .map(|block| block.name)
159                .collect(),
160            Choice::Off => Vec::new(),
161            Choice::List(names) => BLOCKS
162                .iter()
163                .filter(|block| names.iter().any(|n| n == block.name))
164                .map(|block| block.name)
165                .collect(),
166        }
167    }
168
169    /// The text to put in the system prompt — empty when nothing is in force, which is what `off`
170    /// means and what an `auto` set that matched nothing means too.
171    pub fn guidance(&self, model: &str) -> String {
172        text(&self.names_for(model))
173    }
174
175    /// One line for `config check`: what this model is being told, and why.
176    pub fn summary(&self, model: &str) -> String {
177        let names = self.names_for(model);
178        let why = match self {
179            Choice::Auto => "auto".to_string(),
180            Choice::Off => "off".to_string(),
181            Choice::List(_) => "listed".to_string(),
182        };
183        if names.is_empty() {
184            return format!("{why}: no block (the prompt and the context files only)");
185        }
186        format!("{why} for `{model}`: {}", names.join(" · "))
187    }
188}
189
190impl fmt::Display for Choice {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        match self {
193            Choice::Auto => write!(f, "{AUTO}"),
194            Choice::Off => write!(f, "{OFF}"),
195            Choice::List(names) => write!(f, "{}", names.join(" · ")),
196        }
197    }
198}
199
200/// `prompt_blocks = "auto"`, `"off"`, or `["task-completion", "parallel-tool-calls"]`.
201///
202/// A name this build does not ship is a parse error rather than a silently ignored entry: a typo in
203/// a list would otherwise delete a block while the file looks like it asked for it.
204impl<'de> serde::Deserialize<'de> for Choice {
205    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
206        use serde::de::Error as _;
207        let value = toml::Value::deserialize(d)?;
208        match value {
209            toml::Value::String(word) => match word.trim().to_lowercase().as_str() {
210                AUTO => Ok(Choice::Auto),
211                OFF => Ok(Choice::Off),
212                other => Err(D::Error::custom(format!(
213                    "`prompt_blocks` takes `{AUTO}`, `{OFF}`, or a list of block names, not `{other}`"
214                ))),
215            },
216            toml::Value::Array(items) => {
217                let mut picked = Vec::with_capacity(items.len());
218                for item in items {
219                    let toml::Value::String(name) = item else {
220                        return Err(D::Error::custom(
221                            "a `prompt_blocks` list holds block names as strings",
222                        ));
223                    };
224                    let name = name.trim().to_string();
225                    if name == AUTO || name == OFF {
226                        return Err(D::Error::custom(format!(
227                            "`{name}` is a mode, not a block name; use it alone rather than in a list"
228                        )));
229                    }
230                    if !is_block(&name) {
231                        return Err(D::Error::custom(format!(
232                            "`{name}` is not a prompt block; this build ships {}",
233                            names().join(", ")
234                        )));
235                    }
236                    picked.push(name);
237                }
238                Ok(Choice::List(picked))
239            }
240            _ => Err(D::Error::custom(format!(
241                "`prompt_blocks` takes `{AUTO}`, `{OFF}`, or a list of block names"
242            ))),
243        }
244    }
245}
246
247impl serde::Serialize for Choice {
248    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
249        match self {
250            Choice::Auto => s.serialize_str(AUTO),
251            Choice::Off => s.serialize_str(OFF),
252            Choice::List(names) => names.serialize(s),
253        }
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    fn chosen(toml_text: &str) -> Choice {
262        toml::from_str::<std::collections::BTreeMap<String, Choice>>(toml_text)
263            .expect("parses")
264            .remove("prompt_blocks")
265            .expect("the key")
266    }
267
268    /// The matrix, asserted rather than claimed: a `gpt`-shaped name, a `gemma` one, and one nothing
269    /// in the library claims.
270    #[test]
271    fn the_matrix_is_a_fact_for_three_shapes_of_model() {
272        let auto = Choice::Auto;
273        assert_eq!(
274            auto.names_for("gpt-oss:120b"),
275            vec![
276                "task-completion",
277                "parallel-tool-calls",
278                "tool-use-enforcement",
279                "execution-guidance"
280            ]
281        );
282        assert_eq!(
283            auto.names_for("mmnuc/gemma-4-12b-it-qat"),
284            vec![
285                "task-completion",
286                "parallel-tool-calls",
287                "tool-use-enforcement",
288                "google-operational"
289            ],
290            "Gemma gets the operational block instead of the execution one"
291        );
292        assert_eq!(
293            auto.names_for("inkling-2-mini"),
294            vec!["task-completion", "parallel-tool-calls"],
295            "a family nothing claims gets only what every model gets"
296        );
297        assert_eq!(
298            auto.names_for("DeepSeek-V4.1-Flash"),
299            auto.names_for("deepseek-v4.1-flash"),
300            "the gate is case-insensitive"
301        );
302    }
303
304    /// The gate must be able to fail: an unknown name gets neither family block, in either
305    /// direction.
306    #[test]
307    fn a_family_block_is_not_sent_to_a_model_it_was_not_written_for() {
308        let auto = Choice::Auto;
309        for family in [
310            "tool-use-enforcement",
311            "execution-guidance",
312            "google-operational",
313        ] {
314            assert!(!auto.names_for("llama-3-70b").contains(&family), "{family}");
315        }
316        assert!(!auto.names_for("gemma-4").contains(&"execution-guidance"));
317        assert!(!auto.names_for("gpt-5").contains(&"google-operational"));
318    }
319
320    /// A block is never sent twice, and no name is claimed by two blocks.
321    #[test]
322    fn no_block_is_sent_twice_and_no_name_is_claimed_twice() {
323        let auto = Choice::Auto;
324        for model in ["gpt-4", "gemma-2", "deepseek-x", "nothing-known"] {
325            let names = auto.names_for(model);
326            let mut sorted = names.clone();
327            sorted.sort_unstable();
328            sorted.dedup();
329            assert_eq!(sorted.len(), names.len(), "{model}: {names:?}");
330            let text = auto.guidance(model);
331            for name in names {
332                assert_eq!(
333                    text.matches(&format!("## {name}")).count(),
334                    1,
335                    "{name} once in {model}"
336                );
337            }
338        }
339        let mut all = names();
340        all.sort_unstable();
341        let unique = all.len();
342        all.dedup();
343        assert_eq!(all.len(), unique, "every block name is unique");
344    }
345
346    /// It ships in the cached prefix of every request, so the whole library has a ceiling.
347    #[test]
348    fn the_whole_library_stays_under_its_budget() {
349        let whole = text(&names());
350        assert!(
351            whole.chars().count() <= MAX_CHARS,
352            "{}",
353            whole.chars().count()
354        );
355        // The unversals are the part every session pays for; they must stay cheap.
356        let universal = text(&[UNIVERSAL_TASK, UNIVERSAL_BATCH]);
357        assert!(
358            universal.chars().count() <= 900,
359            "the universal pair is {} chars",
360            universal.chars().count()
361        );
362    }
363
364    /// `off` is nothing at all, a list is exactly what it names, and both survive a round trip
365    /// through the config file.
366    #[test]
367    fn off_and_a_list_are_what_they_say() {
368        assert!(chosen("prompt_blocks = \"off\"")
369            .names_for("gpt-4")
370            .is_empty());
371        assert_eq!(chosen("prompt_blocks = \"off\"").guidance("gpt-4"), "");
372        let listed = chosen("prompt_blocks = [\"task-completion\"]");
373        assert_eq!(listed.names_for("gpt-4"), vec!["task-completion"]);
374        assert_eq!(
375            listed.names_for("gemma-2"),
376            vec!["task-completion"],
377            "a listed block is not gated: the list is the whole answer"
378        );
379        // A list is written back as the same list, so `config set` and the starter file agree.
380        let round = toml::Value::try_from(&listed).unwrap();
381        assert_eq!(
382            round,
383            toml::Value::Array(vec![toml::Value::String("task-completion".into())]),
384            "a list is written back as a list"
385        );
386        assert_eq!(
387            toml::Value::try_from(&Choice::Auto).unwrap(),
388            toml::Value::String("auto".into())
389        );
390    }
391
392    /// A typo in a list deletes a block while the file looks like it asked for it, so it is a parse
393    /// error that names what exists.
394    #[test]
395    fn a_name_this_build_does_not_ship_is_refused() {
396        let why = toml::from_str::<std::collections::BTreeMap<String, Choice>>(
397            "prompt_blocks = [\"task-completions\"]",
398        )
399        .unwrap_err()
400        .to_string();
401        assert!(why.contains("task-completions"), "{why}");
402        assert!(why.contains("task-completion"), "the list of names: {why}");
403
404        let why = toml::from_str::<std::collections::BTreeMap<String, Choice>>(
405            "prompt_blocks = \"sometimes\"",
406        )
407        .unwrap_err()
408        .to_string();
409        assert!(why.contains("sometimes"), "{why}");
410        assert!(why.contains("auto"), "{why}");
411    }
412
413    /// The summary is what `config check` prints, so it names the model and the blocks in one line.
414    #[test]
415    fn the_summary_says_what_this_model_is_being_told() {
416        let auto = Choice::Auto;
417        let line = auto.summary("gpt-oss:120b");
418        assert!(line.contains("auto"), "{line}");
419        assert!(line.contains("execution-guidance"), "{line}");
420        // An unknown model is not "no block": the universal pair is for every model. What the
421        // summary must not claim is a family block it did not get.
422        let unknown = auto.summary("nothing-known");
423        assert!(unknown.contains("task-completion"), "{unknown}");
424        assert!(!unknown.contains("execution-guidance"), "{unknown}");
425        let off = Choice::Off.summary("gpt-4");
426        assert!(off.contains("off"), "{off}");
427        assert!(off.contains("no block"), "{off}");
428    }
429}