1use serde::Serialize;
9
10use memstead_schema::Schema;
11
12pub const BINDING_INTENT_UNKNOWN_RELATIONSHIP_CODE: &str = "BINDING_INTENT_UNKNOWN_RELATIONSHIP";
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
19pub struct IntentFinding {
20 pub code: &'static str,
22 pub token: String,
24 pub schema: String,
26 pub vocabulary: Vec<String>,
29}
30
31impl std::fmt::Display for IntentFinding {
32 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 write!(
34 f,
35 "{}: the intent names `{}`, which is not a relationship of the destination \
36 schema `{}` (vocabulary: {})",
37 self.code,
38 self.token,
39 self.schema,
40 self.vocabulary.join(", ")
41 )
42 }
43}
44
45pub fn relationship_vocabulary(schema: &Schema) -> Vec<String> {
51 let mut names: Vec<String> = Vec::new();
52 let defs = schema.manifest.relationships.definitions.iter().chain(
53 schema
54 .manifest
55 .cross_mem_relationships
56 .iter()
57 .flat_map(|block| block.definitions.iter()),
58 );
59 for def in defs {
60 if is_relationship_shaped(&def.name) && !names.contains(&def.name) {
61 names.push(def.name.clone());
62 }
63 }
64 names
65}
66
67pub fn known_relationship_names(engine: &crate::Engine) -> Vec<String> {
72 let mut names: Vec<String> = Vec::new();
73 let all = engine
74 .schemas()
75 .values()
76 .chain(engine.workspace_schemas().iter())
77 .chain(engine.builtin_schemas().iter());
78 for schema in all {
79 for name in relationship_vocabulary(schema) {
80 if !names.contains(&name) {
81 names.push(name);
82 }
83 }
84 }
85 names.sort();
86 names
87}
88
89pub fn intent_findings(
96 intent: Option<&str>,
97 schema_pin: &str,
98 schema: &Schema,
99 known: &[String],
100) -> Vec<IntentFinding> {
101 let Some(intent) = intent else {
102 return Vec::new();
103 };
104 let vocabulary = relationship_vocabulary(schema);
105 let mut findings: Vec<IntentFinding> = Vec::new();
106 for token in unknown_tokens(intent, &vocabulary, known) {
107 findings.push(IntentFinding {
108 code: BINDING_INTENT_UNKNOWN_RELATIONSHIP_CODE,
109 token,
110 schema: schema_pin.to_string(),
111 vocabulary: vocabulary.clone(),
112 });
113 }
114 findings
115}
116
117pub fn binding_intent_findings(
122 engine: &crate::Engine,
123 destination_mem: &str,
124 intent: Option<&str>,
125) -> Vec<IntentFinding> {
126 let Some(pin) = engine.schema_pin(destination_mem) else {
127 return Vec::new();
128 };
129 let Some(schema) = engine.schema_for(destination_mem) else {
130 return Vec::new();
131 };
132 let known = known_relationship_names(engine);
133 intent_findings(intent, &pin.as_display(), &schema, &known)
134}
135
136pub fn unknown_tokens(intent: &str, vocabulary: &[String], known: &[String]) -> Vec<String> {
143 let bytes = intent.as_bytes();
144 let mut out: Vec<String> = Vec::new();
145 let mut i = 0;
146 while i < bytes.len() {
147 let c = bytes[i];
148 if !is_token_byte(c) {
149 i += 1;
150 continue;
151 }
152 let start = i;
155 while i < bytes.len() && is_token_byte(bytes[i]) {
156 i += 1;
157 }
158 let word = &intent[start..i];
159 if !is_relationship_shaped(word) {
160 continue;
161 }
162 if !word.contains('_') && !known.iter().any(|k| k == word) {
163 continue;
166 }
167 if vocabulary.iter().any(|v| v == word) {
168 continue;
169 }
170 if !out.iter().any(|t| t == word) {
171 out.push(word.to_string());
172 }
173 }
174 out
175}
176
177fn is_token_byte(c: u8) -> bool {
180 c.is_ascii_alphanumeric() || c == b'_'
181}
182
183fn is_relationship_shaped(word: &str) -> bool {
186 let mut chars = word.chars();
187 let first = chars.next();
188 word.len() >= 3
189 && first.is_some_and(|c| c.is_ascii_uppercase())
190 && word
191 .chars()
192 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
193}
194
195pub fn render_intent_findings(findings: &[IntentFinding], binding_id: &str) -> String {
199 if findings.is_empty() {
200 return String::new();
201 }
202 let mut lines: Vec<String> = Vec::new();
203 for f in findings {
204 lines.push(format!(
205 "> **[binding] `{}`** — the intent names `{}`, which is not a relationship of \
206 the destination schema `{}`. Read it as prose, never as an edge to write. \
207 Vocabulary: {}.",
208 f.code,
209 f.token,
210 f.schema,
211 f.vocabulary
212 .iter()
213 .map(|v| format!("`{v}`"))
214 .collect::<Vec<_>>()
215 .join(", ")
216 ));
217 }
218 lines.push(format!(
219 "> Fix the intent with `memstead projection edit {binding_id} --patch \
220 '{{\"intent\": \"...\"}}'`; the edit refuses an intent that still names an \
221 unknown token."
222 ));
223 format!("{}\n\n", lines.join("\n>\n"))
224}
225
226pub fn intent_refusal_details(binding: &str, findings: &[IntentFinding]) -> serde_json::Value {
229 let tokens: Vec<&str> = findings.iter().map(|f| f.token.as_str()).collect();
230 let first = findings.first();
231 serde_json::json!({
232 "binding": binding,
233 "tokens": tokens,
234 "schema": first.map(|f| f.schema.clone()).unwrap_or_default(),
235 "vocabulary": first.map(|f| f.vocabulary.clone()).unwrap_or_default(),
236 })
237}
238
239pub fn intent_refusal_message(binding: &str, findings: &[IntentFinding]) -> String {
241 let fmt = |items: &[String]| {
242 items
243 .iter()
244 .map(|t| format!("`{t}`"))
245 .collect::<Vec<_>>()
246 .join(", ")
247 };
248 let tokens: Vec<String> = findings.iter().map(|f| f.token.clone()).collect();
249 let first = findings.first();
250 let schema = first.map(|f| f.schema.clone()).unwrap_or_default();
251 let vocabulary = first.map(|f| f.vocabulary.clone()).unwrap_or_default();
252 format!(
253 "intent refused for `{binding}` (nothing was written): it names {} — not a \
254 relationship of the destination schema `{schema}`. An agent reads an all-caps \
255 token in the intent as an edge it may write, so the intent may name only what \
256 the vocabulary carries: {}",
257 fmt(&tokens),
258 fmt(&vocabulary)
259 )
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265
266 fn vocab(names: &[&str]) -> Vec<String> {
267 names.iter().map(|s| s.to_string()).collect()
268 }
269
270 #[test]
275 fn tokenizer_reads_relationship_shaped_tokens_only() {
276 let v = vocab(&["DEPENDS_ON", "USES"]);
277 let known = vocab(&["DEPENDS_ON", "USES", "PROVIDES", "STORES"]);
278 let intent = "Read the README, CLAUDE.md, VISION and GLOSSARY; the MCP tools, the \
279 JSON envelopes, the HTTP API and the SQL schema. The crate USES what \
280 it DEPENDS_ON, PROVIDED_BY nothing, and PROVIDES an API over HTTP. \
281 An ID is short; Cargo.toml is a file; `#[cfg(test)]` is code.";
282 assert_eq!(
283 unknown_tokens(intent, &v, &known),
284 vec!["PROVIDED_BY".to_string(), "PROVIDES".to_string()]
285 );
286 assert_eq!(
288 unknown_tokens(intent, &v, &vocab(&["DEPENDS_ON", "USES"])),
289 vec!["PROVIDED_BY".to_string()]
290 );
291 }
292
293 #[test]
296 fn tokens_deduplicate_in_first_appearance_order() {
297 let v = vocab(&[]);
298 assert_eq!(
299 unknown_tokens("ZED_A then ALPHA_B then ZED_A again", &v, &[]),
300 vec!["ZED_A".to_string(), "ALPHA_B".to_string()]
301 );
302 }
303
304 #[test]
308 fn vocabulary_wins_and_sentence_end_reads_the_token() {
309 let v = vocab(&["API"]);
310 let known = vocab(&["API"]);
311 assert_eq!(
312 unknown_tokens("An API. Then PART_OF. Done", &v, &known),
313 vec!["PART_OF".to_string()]
314 );
315 assert_eq!(
318 unknown_tokens("An API.", &vocab(&["USES"]), &known),
319 vec!["API".to_string()]
320 );
321 }
322
323 #[test]
327 fn findings_against_the_software_schema() {
328 let registry = memstead_schema::SchemaRegistry::builtin();
329 let schema = registry
330 .resolve_by_name("software")
331 .ok()
332 .flatten()
333 .or_else(|| {
334 registry
337 .available_versions("software")
338 .into_iter()
339 .max()
340 .and_then(|v| registry.get("software", &v))
341 })
342 .expect("the builtin software schema loads");
343 let pin = format!("software@{}", schema.version);
344 let known = relationship_vocabulary(&schema);
345 let found = intent_findings(Some("Edges are PROVIDED_BY code."), &pin, &schema, &known);
346 assert_eq!(found.len(), 1);
347 assert_eq!(found[0].code, BINDING_INTENT_UNKNOWN_RELATIONSHIP_CODE);
348 assert_eq!(found[0].token, "PROVIDED_BY");
349 assert_eq!(found[0].schema, pin);
350 assert!(found[0].vocabulary.iter().any(|v| v == "DEPENDS_ON"));
351 assert!(
352 found[0].vocabulary.iter().all(|v| !v.starts_with('_')),
353 "the loader's synthetic `_default` never rides a finding: {:?}",
354 found[0].vocabulary
355 );
356 assert!(
357 found
358 .iter()
359 .all(|f| f.code == "BINDING_INTENT_UNKNOWN_RELATIONSHIP"),
360 "the code literal is the constant"
361 );
362 assert!(
363 intent_findings(Some("A crate DEPENDS_ON another."), &pin, &schema, &known).is_empty()
364 );
365 assert!(intent_findings(None, &pin, &schema, &known).is_empty());
366 assert!(
367 intent_findings(
368 Some(
369 "Model the README, VISION and GLOSSARY, the MCP tools, the JSON \
370 envelopes, the HTTP routes, the SQL schema and CLAUDE.md"
371 ),
372 &pin,
373 &schema,
374 &known
375 )
376 .is_empty(),
377 "acronyms and file stems are prose"
378 );
379 let rendered = render_intent_findings(&found, "engine/graph");
380 assert!(rendered.contains("BINDING_INTENT_UNKNOWN_RELATIONSHIP"));
381 assert!(rendered.contains("`PROVIDED_BY`"));
382 assert!(rendered.contains("projection edit engine/graph"));
383 assert_eq!(render_intent_findings(&[], "engine/graph"), "");
384 }
385}