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
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 fn vocab(names: &[&str]) -> Vec<String> {
231 names.iter().map(|s| s.to_string()).collect()
232 }
233
234 #[test]
239 fn tokenizer_reads_relationship_shaped_tokens_only() {
240 let v = vocab(&["DEPENDS_ON", "USES"]);
241 let known = vocab(&["DEPENDS_ON", "USES", "PROVIDES", "STORES"]);
242 let intent = "Read the README, CLAUDE.md, VISION and GLOSSARY; the MCP tools, the \
243 JSON envelopes, the HTTP API and the SQL schema. The crate USES what \
244 it DEPENDS_ON, PROVIDED_BY nothing, and PROVIDES an API over HTTP. \
245 An ID is short; Cargo.toml is a file; `#[cfg(test)]` is code.";
246 assert_eq!(
247 unknown_tokens(intent, &v, &known),
248 vec!["PROVIDED_BY".to_string(), "PROVIDES".to_string()]
249 );
250 assert_eq!(
252 unknown_tokens(intent, &v, &vocab(&["DEPENDS_ON", "USES"])),
253 vec!["PROVIDED_BY".to_string()]
254 );
255 }
256
257 #[test]
260 fn tokens_deduplicate_in_first_appearance_order() {
261 let v = vocab(&[]);
262 assert_eq!(
263 unknown_tokens("ZED_A then ALPHA_B then ZED_A again", &v, &[]),
264 vec!["ZED_A".to_string(), "ALPHA_B".to_string()]
265 );
266 }
267
268 #[test]
272 fn vocabulary_wins_and_sentence_end_reads_the_token() {
273 let v = vocab(&["API"]);
274 let known = vocab(&["API"]);
275 assert_eq!(
276 unknown_tokens("An API. Then PART_OF. Done", &v, &known),
277 vec!["PART_OF".to_string()]
278 );
279 assert_eq!(
282 unknown_tokens("An API.", &vocab(&["USES"]), &known),
283 vec!["API".to_string()]
284 );
285 }
286
287 #[test]
291 fn findings_against_the_software_schema() {
292 let registry = memstead_schema::SchemaRegistry::builtin();
293 let schema = registry
294 .resolve_by_name("software")
295 .ok()
296 .flatten()
297 .or_else(|| {
298 registry
301 .available_versions("software")
302 .into_iter()
303 .max()
304 .and_then(|v| registry.get("software", &v))
305 })
306 .expect("the builtin software schema loads");
307 let pin = format!("software@{}", schema.version);
308 let known = relationship_vocabulary(&schema);
309 let found = intent_findings(Some("Edges are PROVIDED_BY code."), &pin, &schema, &known);
310 assert_eq!(found.len(), 1);
311 assert_eq!(found[0].code, BINDING_INTENT_UNKNOWN_RELATIONSHIP_CODE);
312 assert_eq!(found[0].token, "PROVIDED_BY");
313 assert_eq!(found[0].schema, pin);
314 assert!(found[0].vocabulary.iter().any(|v| v == "DEPENDS_ON"));
315 assert!(
316 found[0].vocabulary.iter().all(|v| !v.starts_with('_')),
317 "the loader's synthetic `_default` never rides a finding: {:?}",
318 found[0].vocabulary
319 );
320 assert!(
321 found
322 .iter()
323 .all(|f| f.code == "BINDING_INTENT_UNKNOWN_RELATIONSHIP"),
324 "the code literal is the constant"
325 );
326 assert!(
327 intent_findings(Some("A crate DEPENDS_ON another."), &pin, &schema, &known).is_empty()
328 );
329 assert!(intent_findings(None, &pin, &schema, &known).is_empty());
330 assert!(
331 intent_findings(
332 Some(
333 "Model the README, VISION and GLOSSARY, the MCP tools, the JSON \
334 envelopes, the HTTP routes, the SQL schema and CLAUDE.md"
335 ),
336 &pin,
337 &schema,
338 &known
339 )
340 .is_empty(),
341 "acronyms and file stems are prose"
342 );
343 let rendered = render_intent_findings(&found, "engine/graph");
344 assert!(rendered.contains("BINDING_INTENT_UNKNOWN_RELATIONSHIP"));
345 assert!(rendered.contains("`PROVIDED_BY`"));
346 assert!(rendered.contains("projection edit engine/graph"));
347 assert_eq!(render_intent_findings(&[], "engine/graph"), "");
348 }
349}