Skip to main content

memstead_base/
binding_intent.rs

1//! Binding-intent check — the findings a binding's intent text earns
2//! against the destination schema (relationship-shaped tokens the schema
3//! does not declare, and their kin). Kernel, not loop: the binding editor
4//! validates an intent at write time, so the check lives beside the
5//! binding store. Moved here from `ingest::intent` on 2026-09-10; the loop
6//! and every consumer path reach it through `ingest::intent`.
7
8use serde::Serialize;
9
10use memstead_schema::Schema;
11
12/// The finding code — one literal, indexed by the generated error index.
13pub const BINDING_INTENT_UNKNOWN_RELATIONSHIP_CODE: &str = "BINDING_INTENT_UNKNOWN_RELATIONSHIP";
14
15/// One unknown relationship token in a binding's intent, with the
16/// vocabulary it was checked against so the reader can see the mismatch
17/// without opening the schema.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
19pub struct IntentFinding {
20    /// Always [`BINDING_INTENT_UNKNOWN_RELATIONSHIP_CODE`].
21    pub code: &'static str,
22    /// The token as written in the intent.
23    pub token: String,
24    /// The destination schema pin (`software@0.5.0`) whose vocabulary was read.
25    pub schema: String,
26    /// The relationship names that schema declares — main vocabulary and
27    /// cross-mem blocks alike, in declaration order.
28    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
45/// Every relationship name a schema declares: the main vocabulary and each
46/// cross-mem block, in declaration order, deduplicated. Only names an
47/// intent could actually write are listed: the loader injects a synthetic
48/// `_default` definition that no token can ever match, and it would be
49/// noise in every finding.
50pub 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
67/// Every relationship name any schema the engine knows declares: the
68/// mem-pinned, the workspace-authored and the built-in catalogues. The
69/// `known` side of the token rule: a single all-caps word is read as a
70/// relationship claim only when it is one of these names.
71pub 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
89/// Check an intent against a destination schema's vocabulary. A
90/// relationship-shaped token (see [`unknown_tokens`]) the schema does not
91/// declare is a finding, reported once per token in order of first
92/// appearance. `known` is the union of relationship names across every
93/// schema the engine knows ([`known_relationship_names`]); `None` or an
94/// empty intent yields nothing.
95pub 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
117/// The findings for a binding as loaded: its intent against the schema the
118/// destination mem pins in this engine. A destination that is not mounted,
119/// or carries no schema, has no vocabulary to read, so nothing is reported
120/// — the brief's absent-destination note carries that case.
121pub 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
136/// The relationship-shaped tokens of `intent` that are not in
137/// `vocabulary`, deduplicated in order of first appearance. A token is
138/// relationship-shaped when it is all-caps (letters, digits, underscores,
139/// three or more characters, starting with a letter) AND either carries
140/// an underscore or is one of the `known` relationship names. Split out
141/// from [`intent_findings`] so the tokenizer is testable without a schema.
142pub 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        // Consume one maximal run of token bytes: a word boundary on both
153        // sides, so `PROVIDED_BY` is one token and `memstead-pro` none.
154        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            // A single all-caps word that no schema declares is prose
164            // (an acronym, a file stem such as README), never a claim.
165            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
177/// A token byte: what a `\w`-class word is made of. The run is split on
178/// anything else, so hyphens and dots end a token.
179fn is_token_byte(c: u8) -> bool {
180    c.is_ascii_alphanumeric() || c == b'_'
181}
182
183/// `[A-Z][A-Z0-9_]{2,}` — three or more characters, upper-case letters,
184/// digits and underscores only, starting with a letter.
185fn 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
195/// Render the findings as the Markdown callout every brief carries next to
196/// the intent. Empty when there is nothing to report, so a clean binding's
197/// brief is byte-identical to before the rule.
198pub 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    /// A phantom `PROVIDED_BY` (underscore) and a phantom `PROVIDES` (a
235    /// relationship name another schema declares) are findings; a declared
236    /// name, plain acronyms, file stems, a short token and a mixed-case
237    /// word are not.
238    #[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        // With no schema declaring PROVIDES anywhere, the single word is prose.
251        assert_eq!(
252            unknown_tokens(intent, &v, &vocab(&["DEPENDS_ON", "USES"])),
253            vec!["PROVIDED_BY".to_string()]
254        );
255    }
256
257    /// A token is reported once however often it appears, in order of
258    /// first appearance.
259    #[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    /// A schema that declares an acronym-shaped name as a relationship keeps
269    /// it a relationship: the vocabulary wins, and a sentence ending in a
270    /// token still reads the token.
271    #[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        // The same acronym against a schema that lacks it, while another
280        // schema declares it, is a claim about the wrong vocabulary.
281        assert_eq!(
282            unknown_tokens("An API.", &vocab(&["USES"]), &known),
283            vec!["API".to_string()]
284        );
285    }
286
287    /// The finding against a real schema names the token, the pin, and the
288    /// vocabulary; a legal intent yields nothing; an absent intent yields
289    /// nothing.
290    #[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                // Several versions coexist in the builtin registry; take the
299                // newest for this check.
300                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}