[core] Canon, claims, hooks: strict parser, fail-closed claim checker, hook templates
This commit is contained in:
@@ -3,12 +3,17 @@
|
||||
|
||||
//! Hook templates: `brand/hooks.md` lines `- [H<n>] <template>` with slots from a fixed set.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use crate::text::{self, ItemLine, LineError};
|
||||
|
||||
/// The only slot names a template may use.
|
||||
pub const SLOTS: [&str; 7] = ["app", "feature", "pain", "number", "platform", "clicks", "audience"];
|
||||
pub const SLOTS: [&str; 7] = [
|
||||
"app", "feature", "pain", "number", "platform", "clicks", "audience",
|
||||
];
|
||||
|
||||
/// Largest hooks file accepted, in bytes.
|
||||
pub const MAX_FILE_BYTES: usize = 64 * 1024;
|
||||
@@ -44,22 +49,77 @@ pub struct Genome {
|
||||
pub lead_verb: Option<String>,
|
||||
}
|
||||
|
||||
/// Imperative openers recognised as commands.
|
||||
const COMMAND_VERBS: &[&str] = &[
|
||||
"ask", "build", "check", "discover", "ditch", "do", "don't", "dont", "download", "find",
|
||||
"forget", "get", "give", "grab", "imagine", "install", "join", "keep", "learn", "let", "make",
|
||||
"meet", "never", "open", "picture", "plan", "quit", "read", "save", "say", "see", "skip",
|
||||
"start", "stop", "switch", "take", "track", "try", "turn", "use", "watch", "write",
|
||||
];
|
||||
|
||||
impl Genome {
|
||||
/// Derive the genome from a template or a filled hook.
|
||||
///
|
||||
/// Opening, in this order: starts with a digit or `{number}` → number; first sentence ends with `?` →
|
||||
/// question; first word is a known imperative verb → command; otherwise statement.
|
||||
pub fn of(text: &str) -> Genome {
|
||||
let _ = text;
|
||||
todo!()
|
||||
let words: Vec<&str> = text.unicode_words().collect();
|
||||
let has_number = text.chars().any(char::is_numeric) || text.contains("{number}");
|
||||
let lead = text
|
||||
.trim_start()
|
||||
.trim_start_matches(|c: char| !c.is_alphanumeric() && c != '{');
|
||||
let first_word = words.first().map(|w| w.to_lowercase().replace('’', "'"));
|
||||
let opening = if lead.starts_with(|c: char| c.is_numeric()) || lead.starts_with("{number}")
|
||||
{
|
||||
Opening::Number
|
||||
} else if first_sentence_is_question(text) {
|
||||
Opening::Question
|
||||
} else if first_word
|
||||
.as_deref()
|
||||
.is_some_and(|w| COMMAND_VERBS.contains(&w))
|
||||
&& !lead.starts_with('{')
|
||||
{
|
||||
Opening::Command
|
||||
} else {
|
||||
Opening::Statement
|
||||
};
|
||||
let lead_verb = if opening == Opening::Command {
|
||||
first_word
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Genome {
|
||||
opening,
|
||||
words: words.len(),
|
||||
has_number,
|
||||
lead_verb,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn first_sentence_is_question(text: &str) -> bool {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
if matches!(c, '.' | '!' | '?' | '…') && chars.get(i + 1).is_none_or(|n| n.is_whitespace())
|
||||
{
|
||||
return c == '?';
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A hooks file error.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum HookError {
|
||||
#[error("the file is {bytes} bytes; the limit is 65536")]
|
||||
TooLarge { bytes: usize },
|
||||
#[error("line {line}: forbidden character U+{codepoint:04X} (control, hidden or direction-changing)")]
|
||||
#[error(
|
||||
"line {line}: forbidden character U+{codepoint:04X} (control, hidden or direction-changing)"
|
||||
)]
|
||||
ForbiddenCharacter { line: usize, codepoint: u32 },
|
||||
#[error("line {line}: a carriage return that is not part of a CRLF line ending")]
|
||||
LoneCarriageReturn { line: usize },
|
||||
#[error("line {line}: a line starting '- [H' must be '- [H<n>] <template>'")]
|
||||
Malformed { line: usize },
|
||||
#[error("line {line}: hook number must be 1-9999 without leading zeros")]
|
||||
@@ -76,16 +136,100 @@ pub enum HookError {
|
||||
MissingValue { slot: String },
|
||||
}
|
||||
|
||||
/// The slots of a template, unique, in order of first use.
|
||||
fn slots_of(template: &str, line: usize) -> Result<Vec<String>, HookError> {
|
||||
let mut slots: Vec<String> = Vec::new();
|
||||
let mut rest = template;
|
||||
while let Some(i) = rest.find(['{', '}']) {
|
||||
if rest[i..].starts_with('}') {
|
||||
return Err(HookError::UnbalancedBrace { line });
|
||||
}
|
||||
let after = &rest[i + 1..];
|
||||
let Some(j) = after.find(['{', '}']) else {
|
||||
return Err(HookError::UnbalancedBrace { line });
|
||||
};
|
||||
if after[j..].starts_with('{') {
|
||||
return Err(HookError::UnbalancedBrace { line });
|
||||
}
|
||||
let name = &after[..j];
|
||||
if !SLOTS.contains(&name) {
|
||||
return Err(HookError::UnknownSlot {
|
||||
line,
|
||||
slot: name.to_string(),
|
||||
});
|
||||
}
|
||||
if !slots.iter().any(|s| s == name) {
|
||||
slots.push(name.to_string());
|
||||
}
|
||||
rest = &after[j + 1..];
|
||||
}
|
||||
Ok(slots)
|
||||
}
|
||||
|
||||
/// Parse `brand/hooks.md`. Lines that do not start `- [H` are ignored (headings, prose).
|
||||
///
|
||||
/// Strict like the canon: a bullet line starting `[H` must be exactly `- [H<n>] <template>`; a leading BOM and CRLF
|
||||
/// are tolerated; control, hidden and direction-changing characters are errors; 64 KiB at most.
|
||||
pub fn parse(md: &str) -> Result<Vec<HookTemplate>, HookError> {
|
||||
let _ = md;
|
||||
todo!()
|
||||
if md.len() > MAX_FILE_BYTES {
|
||||
return Err(HookError::TooLarge { bytes: md.len() });
|
||||
}
|
||||
let lines = text::clean_lines(md).map_err(|(line, e)| match e {
|
||||
LineError::LoneCr => HookError::LoneCarriageReturn { line },
|
||||
LineError::Forbidden(codepoint) => HookError::ForbiddenCharacter { line, codepoint },
|
||||
})?;
|
||||
let mut out = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for (i, &l) in lines.iter().enumerate() {
|
||||
let line = i + 1;
|
||||
match text::item_line(l, 'H') {
|
||||
ItemLine::No => {}
|
||||
ItemLine::Malformed => return Err(HookError::Malformed { line }),
|
||||
ItemLine::IdOutOfRange => return Err(HookError::IdOutOfRange { line }),
|
||||
ItemLine::Item { id, text } => {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Err(HookError::Empty { line });
|
||||
}
|
||||
let id = format!("H{id}");
|
||||
if !seen.insert(id.clone()) {
|
||||
return Err(HookError::Duplicate { line, id });
|
||||
}
|
||||
let slots = slots_of(text, line)?;
|
||||
out.push(HookTemplate {
|
||||
id,
|
||||
text: text.to_string(),
|
||||
slots,
|
||||
genome: Genome::of(text),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl HookTemplate {
|
||||
/// Fill every slot. A missing value is an error; braces inside values are not expanded again.
|
||||
/// Extra values are ignored.
|
||||
pub fn fill(&self, values: &BTreeMap<String, String>) -> Result<String, HookError> {
|
||||
let _ = values;
|
||||
todo!()
|
||||
let mut out = String::with_capacity(self.text.len() + 32);
|
||||
let mut rest = self.text.as_str();
|
||||
while let Some(i) = rest.find('{') {
|
||||
out.push_str(&rest[..i]);
|
||||
let after = &rest[i + 1..];
|
||||
// Templates are validated at parse time; a hand-built one with a stray brace keeps it literally.
|
||||
let Some(j) = after.find('}') else {
|
||||
out.push_str(&rest[i..]);
|
||||
return Ok(out);
|
||||
};
|
||||
let name = &after[..j];
|
||||
let value = values.get(name).ok_or_else(|| HookError::MissingValue {
|
||||
slot: name.to_string(),
|
||||
})?;
|
||||
out.push_str(value);
|
||||
rest = &after[j + 1..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user