use serde::Serialize;
use memstead_schema::Schema;
pub const BINDING_INTENT_UNKNOWN_RELATIONSHIP_CODE: &str = "BINDING_INTENT_UNKNOWN_RELATIONSHIP";
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct IntentFinding {
pub code: &'static str,
pub token: String,
pub schema: String,
pub vocabulary: Vec<String>,
}
impl std::fmt::Display for IntentFinding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}: the intent names `{}`, which is not a relationship of the destination \
schema `{}` (vocabulary: {})",
self.code,
self.token,
self.schema,
self.vocabulary.join(", ")
)
}
}
pub fn relationship_vocabulary(schema: &Schema) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
let defs = schema.manifest.relationships.definitions.iter().chain(
schema
.manifest
.cross_mem_relationships
.iter()
.flat_map(|block| block.definitions.iter()),
);
for def in defs {
if is_relationship_shaped(&def.name) && !names.contains(&def.name) {
names.push(def.name.clone());
}
}
names
}
pub fn known_relationship_names(engine: &crate::Engine) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
let all = engine
.schemas()
.values()
.chain(engine.workspace_schemas().iter())
.chain(engine.builtin_schemas().iter());
for schema in all {
for name in relationship_vocabulary(schema) {
if !names.contains(&name) {
names.push(name);
}
}
}
names.sort();
names
}
pub fn intent_findings(
intent: Option<&str>,
schema_pin: &str,
schema: &Schema,
known: &[String],
) -> Vec<IntentFinding> {
let Some(intent) = intent else {
return Vec::new();
};
let vocabulary = relationship_vocabulary(schema);
let mut findings: Vec<IntentFinding> = Vec::new();
for token in unknown_tokens(intent, &vocabulary, known) {
findings.push(IntentFinding {
code: BINDING_INTENT_UNKNOWN_RELATIONSHIP_CODE,
token,
schema: schema_pin.to_string(),
vocabulary: vocabulary.clone(),
});
}
findings
}
pub fn binding_intent_findings(
engine: &crate::Engine,
destination_mem: &str,
intent: Option<&str>,
) -> Vec<IntentFinding> {
let Some(pin) = engine.schema_pin(destination_mem) else {
return Vec::new();
};
let Some(schema) = engine.schema_for(destination_mem) else {
return Vec::new();
};
let known = known_relationship_names(engine);
intent_findings(intent, &pin.as_display(), &schema, &known)
}
pub fn unknown_tokens(intent: &str, vocabulary: &[String], known: &[String]) -> Vec<String> {
let bytes = intent.as_bytes();
let mut out: Vec<String> = Vec::new();
let mut i = 0;
while i < bytes.len() {
let c = bytes[i];
if !is_token_byte(c) {
i += 1;
continue;
}
let start = i;
while i < bytes.len() && is_token_byte(bytes[i]) {
i += 1;
}
let word = &intent[start..i];
if !is_relationship_shaped(word) {
continue;
}
if !word.contains('_') && !known.iter().any(|k| k == word) {
continue;
}
if vocabulary.iter().any(|v| v == word) {
continue;
}
if !out.iter().any(|t| t == word) {
out.push(word.to_string());
}
}
out
}
fn is_token_byte(c: u8) -> bool {
c.is_ascii_alphanumeric() || c == b'_'
}
fn is_relationship_shaped(word: &str) -> bool {
let mut chars = word.chars();
let first = chars.next();
word.len() >= 3
&& first.is_some_and(|c| c.is_ascii_uppercase())
&& word
.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
}
pub fn render_intent_findings(findings: &[IntentFinding], binding_id: &str) -> String {
if findings.is_empty() {
return String::new();
}
let mut lines: Vec<String> = Vec::new();
for f in findings {
lines.push(format!(
"> **[binding] `{}`** — the intent names `{}`, which is not a relationship of \
the destination schema `{}`. Read it as prose, never as an edge to write. \
Vocabulary: {}.",
f.code,
f.token,
f.schema,
f.vocabulary
.iter()
.map(|v| format!("`{v}`"))
.collect::<Vec<_>>()
.join(", ")
));
}
lines.push(format!(
"> Fix the intent with `memstead projection edit {binding_id} --patch \
'{{\"intent\": \"...\"}}'`; the edit refuses an intent that still names an \
unknown token."
));
format!("{}\n\n", lines.join("\n>\n"))
}
#[cfg(test)]
mod tests {
use super::*;
fn vocab(names: &[&str]) -> Vec<String> {
names.iter().map(|s| s.to_string()).collect()
}
#[test]
fn tokenizer_reads_relationship_shaped_tokens_only() {
let v = vocab(&["DEPENDS_ON", "USES"]);
let known = vocab(&["DEPENDS_ON", "USES", "PROVIDES", "STORES"]);
let intent = "Read the README, CLAUDE.md, VISION and GLOSSARY; the MCP tools, the \
JSON envelopes, the HTTP API and the SQL schema. The crate USES what \
it DEPENDS_ON, PROVIDED_BY nothing, and PROVIDES an API over HTTP. \
An ID is short; Cargo.toml is a file; `#[cfg(test)]` is code.";
assert_eq!(
unknown_tokens(intent, &v, &known),
vec!["PROVIDED_BY".to_string(), "PROVIDES".to_string()]
);
assert_eq!(
unknown_tokens(intent, &v, &vocab(&["DEPENDS_ON", "USES"])),
vec!["PROVIDED_BY".to_string()]
);
}
#[test]
fn tokens_deduplicate_in_first_appearance_order() {
let v = vocab(&[]);
assert_eq!(
unknown_tokens("ZED_A then ALPHA_B then ZED_A again", &v, &[]),
vec!["ZED_A".to_string(), "ALPHA_B".to_string()]
);
}
#[test]
fn vocabulary_wins_and_sentence_end_reads_the_token() {
let v = vocab(&["API"]);
let known = vocab(&["API"]);
assert_eq!(
unknown_tokens("An API. Then PART_OF. Done", &v, &known),
vec!["PART_OF".to_string()]
);
assert_eq!(
unknown_tokens("An API.", &vocab(&["USES"]), &known),
vec!["API".to_string()]
);
}
#[test]
fn findings_against_the_software_schema() {
let registry = memstead_schema::SchemaRegistry::builtin();
let schema = registry
.resolve_by_name("software")
.ok()
.flatten()
.or_else(|| {
registry
.available_versions("software")
.into_iter()
.max()
.and_then(|v| registry.get("software", &v))
})
.expect("the builtin software schema loads");
let pin = format!("software@{}", schema.version);
let known = relationship_vocabulary(&schema);
let found = intent_findings(Some("Edges are PROVIDED_BY code."), &pin, &schema, &known);
assert_eq!(found.len(), 1);
assert_eq!(found[0].code, BINDING_INTENT_UNKNOWN_RELATIONSHIP_CODE);
assert_eq!(found[0].token, "PROVIDED_BY");
assert_eq!(found[0].schema, pin);
assert!(found[0].vocabulary.iter().any(|v| v == "DEPENDS_ON"));
assert!(
found[0].vocabulary.iter().all(|v| !v.starts_with('_')),
"the loader's synthetic `_default` never rides a finding: {:?}",
found[0].vocabulary
);
assert!(
found
.iter()
.all(|f| f.code == "BINDING_INTENT_UNKNOWN_RELATIONSHIP"),
"the code literal is the constant"
);
assert!(
intent_findings(Some("A crate DEPENDS_ON another."), &pin, &schema, &known).is_empty()
);
assert!(intent_findings(None, &pin, &schema, &known).is_empty());
assert!(
intent_findings(
Some(
"Model the README, VISION and GLOSSARY, the MCP tools, the JSON \
envelopes, the HTTP routes, the SQL schema and CLAUDE.md"
),
&pin,
&schema,
&known
)
.is_empty(),
"acronyms and file stems are prose"
);
let rendered = render_intent_findings(&found, "engine/graph");
assert!(rendered.contains("BINDING_INTENT_UNKNOWN_RELATIONSHIP"));
assert!(rendered.contains("`PROVIDED_BY`"));
assert!(rendered.contains("projection edit engine/graph"));
assert_eq!(render_intent_findings(&[], "engine/graph"), "");
}
}