1use std::fmt;
18
19pub struct Block {
21 pub name: &'static str,
23 pub body: &'static str,
25 pub families: &'static [&'static str],
30}
31
32pub const AUTO: &str = "auto";
34pub const OFF: &str = "off";
36
37pub const MAX_CHARS: usize = 4_000;
40
41const UNIVERSAL_TASK: &str = "task-completion";
43const UNIVERSAL_BATCH: &str = "parallel-tool-calls";
44
45pub 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
91pub fn is_block(name: &str) -> bool {
93 BLOCKS.iter().any(|block| block.name == name.trim())
94}
95
96pub fn names() -> Vec<&'static str> {
98 BLOCKS.iter().map(|block| block.name).collect()
99}
100
101pub fn block(name: &str) -> Option<&'static Block> {
103 BLOCKS.iter().find(|b| b.name == name.trim())
104}
105
106pub 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
123pub 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#[derive(Debug, Clone, PartialEq, Eq, Default)]
141pub enum Choice {
142 #[default]
144 Auto,
145 Off,
147 List(Vec<String>),
149}
150
151impl Choice {
152 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 pub fn guidance(&self, model: &str) -> String {
172 text(&self.names_for(model))
173 }
174
175 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
200impl<'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 #[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 #[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 #[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 #[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 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 #[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 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 #[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 #[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 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}