instinct-cli 0.3.7

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
# Distinguish an instruction from a passage the user asks an agent to operate on.
AAC # use std::{borrow::Cow, ops::Range}

AAA # fn escaped(text: &str, at: usize) -> bool
TAC # text.as_bytes()[..at].iter().rev().take_while(|&&byte| byte==b'\\').count() % 2 == 1
TTT # end

AAA # pub(crate) fn quoted_spans(text: &str) -> Vec<Range<usize>>
AAC # let mut spans = Vec::new()
AAC # let mut open = None
AGA # for (at,ch) in text.char_indices()
CAA # if let Some((from,end)) = open
CAA # if ch==end && !escaped(text,at)
AAC # let after = at + ch.len_utf8()
CAA # if matches!(ch,'\''|'’') && text[after..].starts_with(char::is_alphanumeric)
GAG # continue
TTT # end
AAC # spans.push(from..after)
AAC # open = None
TTT # end
TAC # } else {
TAC # let end = match ch { '"' | '\'' | '`' => ch, '“' => '”', '‘' => '’', _ => continue };
CAA # if !text[..at].ends_with(char::is_alphanumeric) && !escaped(text,at)
AAC # open = Some((at,end))
TTT # end
TTT # end
TTT # end
TAC # spans
TTT # end

AAA # fn words(text: &str) -> impl Iterator<Item=&str>
TAC # text.split(|c: char| !c.is_alphanumeric() && c!='\'').filter(|w| !w.is_empty())
TTT # end


# Read the operation outside an operand. A term can be an object to define,
# an item to count, or text to translate, even if it happens to name a task.
TAG # #[derive(Copy, Clone, PartialEq, Eq, Debug)]
TAC # enum Role { Transform, Language, Meaning, Count, Check, Find, Create, Change }
TAC # impl Role {
AAA # fn acts_on_words_or_quantity(self) -> bool
TAC # matches!(self, Self::Transform | Self::Language | Self::Meaning | Self::Count)
TTT # end
TAC # }
AAA # fn operator(w: &str) -> Option<Role>
TAC # match w {
TAC # "translate"|"alphabetize"|"alphabetise"|"reorder"|"transcribe"|"uppercase"|"lowercase"|"capitalize"|"capitalise"|"paraphrase"|"proofread"|"rephrase"|"rewrite" => Some(Role::Transform),
TAC # "define" => Some(Role::Meaning), "count"|"calculate"|"enumerate" => Some(Role::Count),
TAC # "verify"|"confirm"|"check"|"validate"|"crosscheck"|"compare"|"inspect"|"diagnose"|"audit"|"debug" => Some(Role::Check),
TAC # "locate"|"search"|"find"|"grep"|"scan"|"filter"|"look"|"retrieve" => Some(Role::Find),
TAC # "write"|"prepare"|"draft"|"produce"|"compose"|"generate"|"make"|"create"|"build"|"print"|"publish"|"deliver"|"send" => Some(Role::Create),
TAC # "change"|"add"|"repair"|"fix"|"remove"|"arrange"|"organize"|"sort"|"update" => Some(Role::Change),
TAC # _ => None,
TAC # }
TTT # end

AAA # fn unit(w: &str) -> bool
TAC # matches!(w,"word"|"words"|"letter"|"letters"|"character"|"characters"|"lines"|"syllables")
TTT # end
AAA # fn syntax_word(w: &str) -> bool
TAC # matches!(w,"verb"|"noun"|"adjective"|"adverb"|"pronoun"|"subject"|"tense"|"syllable"|"grammar"|"punctuation")
TTT # end
AAA # fn filler(w: &str) -> bool
TAC # matches!(w,"please"|"can"|"could"|"would"|"you"|"kindly"|"just"|"then"|"also"|"separately"|"still"|"when"|"to"|"i"|"we"|"need"|"want"|"should")
TTT # end
AAA # fn clause_role(terms: &[&str]) -> Option<Role>
AAC # let start=terms.iter().position(|w| !filler(w)).unwrap_or(terms.len())
AAC # let terms=&terms[start..]
AAC # let first=*terms.first()?
AAC # let asks=matches!(first,"is"|"are"|"does"|"do"|"how"|"what"|"which"|"in"|"within"|"from"|"identify"|"tell"|"find"|"spot"|"give"|"explain")
AAC # let has = |w:&str| terms.contains(&w)
CAA # if terms.windows(2).any(|p| p==["how","many"]) || (first=="count" && terms.iter().skip(1).take(4).any(|w| unit(w)))
CAG # return Some(Role::Count)
TTT # end
CAA # if first=="define" || has("definition") && !matches!(operator(first),Some(Role::Check|Role::Find|Role::Change)) || (asks && has("difference") && has("between")) || (matches!(first,"what"|"explain") && has("mean") && terms.iter().any(|w| matches!(*w,"term"|"word"|"phrase"|"expression"|"acronym"|"abbreviation")))
CAG # return Some(Role::Meaning)
TTT # end
AAC # let refers_to_words=terms.iter().any(|w| matches!(*w,"wording"|"phrase"|"sentence"|"phrasing"|"spelling"|"typo"))
AAC # let tone=terms.iter().any(|w| matches!(*w,"formal"|"informal"|"natural"|"polite"|"rude"|"harsh"|"abrupt"|"clear"|"awkward"|"friendly"|"grammatical"))
CAA # if (refers_to_words && (matches!(first,"soften"|"reword"|"correct"|"spot"|"proofread"|"rephrase") || asks && (tone || has("typo") || has("wording")))) || (asks && terms.iter().any(|w| syntax_word(w)) && (has("which") || has("what") || has("or"))) || (asks && (has("sound") || has("read")) && tone)
CAG # return Some(Role::Language)
TTT # end
TAC # operator(first)
TTT # end

AAA # fn is_source(prefix: &str,suffix: &str) -> bool
AAC # let before=prefix.rsplit(['.','!','?',';',',','\n']).next().unwrap_or("")
TGT # The immediate grammatical complement suffices; bound repeated right-context lookahead.
AAC # let mut after=String::new()
AGA # for word in suffix.split_whitespace().take(16)
CAA # if let Some(end)=word.find(['.','!','?',';'])
AAC # after.push_str(&word[..end])
GAG # break
TTT # end
AAC # after.push_str(word)
AAC # after.push(' ')
TTT # end
AAC # let lower=before.to_lowercase()
AAC # let terms:Vec<_>=words(&lower).collect()
TGT # A subsequent command can change the role of its own quoted operand.
AAC # let cut=terms.windows(2).rposition(|p| matches!(p[0],"then"|"also"|"and"|"but") && operator(p[1]).is_some()).map_or(0,|i|i+1)
AAC # let after=after.to_lowercase()
AAC # let mut surrounding=terms[cut..].to_vec()
AAC # surrounding.extend(words(&after))
TAC # match clause_role(&surrounding) {
TAC # Some(Role::Count) => surrounding.iter().any(|w| unit(w)),
TAC # Some(role) => role.acts_on_words_or_quantity(),
TAC # None => false,
TAC # }
TTT # end
AAA # pub(crate) fn action_text(text: &str) -> Cow<'_, str>
CAA # if !text.contains(['"','\'','`','“','‘'])
CAG # return Cow::Borrowed(text)
TTT # end
AAC # let mut copied=0
AAC # let mut last_source=false
AAC # let mut out=String::new()
AGA # for range in quoted_spans(text)
AAC # let between=&text[copied..range.start]
AAC # out.push_str(between)
AAC # let continuation=last_source && !between.contains(['.','!','?',';','\n']) && words(between).all(|w| matches!(w,"and"|"or"))
AAC # last_source = continuation || is_source(between,&text[range.end..])
CAA # if last_source
AAC # out.push(' ')
CAC # else
AAC # out.push_str(&text[range.clone()])
TTT # end
AAC # copied=range.end
TTT # end
CAA # if copied==0 || out==text[..copied]
CAG # return Cow::Borrowed(text)
TTT # end
AAC # out.push_str(&text[copied..])
TAC # Cow::Owned(out)
TTT # end

AAA # fn split_roles(text: &str) -> Vec<(Role,String)>
AAC # let mut found=Vec::new()
AGA # for sentence in text.split(['.','!','?',';','\n'])
AAC # let lower=sentence.to_lowercase()
AAC # let terms:Vec<_>=words(&lower).collect()
AAC # let mut starts=vec![0]
AGA # for (i,pair) in terms.windows(2).enumerate()
CAA # if matches!(pair[0],"and"|"then"|"also"|"but"|"separately") && operator(pair[1]).is_some()
AAC # starts.push(i+1)
TTT # end
TTT # end
TGT # A leading purpose phrase may precede the imperative after a comma.
AAC # starts.push(terms.len())
AGA # for range in starts.windows(2)
AAC # let part=&terms[range[0]..range[1]]
AAC # let role=clause_role(part).or_else(|| { if starts.len()==2 {let tail=lower.rsplit_once(',')?.1;clause_role(&words(tail).collect::<Vec<_>>())} else {None} })
CAA # if let Some(role)=role
AAC # found.push((role,part.join(" ")))
TTT # end
TTT # end
TTT # end
TAC # found
TTT # end

TAC # pub(crate) struct TaskRoles(Vec<(Role,std::collections::HashSet<String>)>);
TAC # impl TaskRoles {
AAA # pub(crate) fn parse(text: &str) -> Self
TGT # Most ordinary tasks need only the existing ranker. Avoid allocating clause/method profiles on that path.
CAA # if !words(text).any(|w| { let folded; let term = if w.bytes().any(|b| b.is_ascii_uppercase()) {folded=w.to_ascii_lowercase(); &folded} else {w}; operator(term).is_some_and(Role::acts_on_words_or_quantity) || matches!(term,"how"|"meaning"|"mean"|"difference"|"definition"|"wording"|"phrasing"|"phrase"|"sentence"|"spot"|"sound"|"read"|"typo"|"soften") || syntax_word(term) })
CAG # return Self(Vec::new())
TTT # end
AAC # let parts=split_roles(text)
CAA # if !parts.iter().any(|(role,_)| role.acts_on_words_or_quantity())
CAG # return Self(Vec::new())
TTT # end
TAC # Self(parts.into_iter().map(|(r,s)|(r,super::anchors(&s))).collect())
TTT # end
AAA # pub(crate) fn allows(&self, cue: &str, method: &str, tags: &str) -> bool
CAA # if self.0.is_empty()
CAG # return true
TTT # end
AAC # let mut method_roles=split_roles(cue)
AAC # method_roles.extend(split_roles(method))
AAC # let cue_words=super::anchors(&format!("{} {} {}",cue,method,tags))
AGA # for (role,args) in &self.0
AAC # let agreement=method_roles.iter().any(|(r,_)| r==role || matches!((r,role),(Role::Transform,Role::Language)|(Role::Language,Role::Transform)))
CAA # if agreement && args.intersection(&cue_words).take(2).count()>=2
CAG # return true
TTT # end
TGT # Implicit or unclassified methods can still apply to the explicit operational task.
CAA # if !role.acts_on_words_or_quantity() && method_roles.is_empty() && args.intersection(&cue_words).take(2).count()>=2
CAG # return true
TTT # end
TTT # end
TAC # false
TTT # end
TAC # }

TAC # #[cfg(test)]
TAC # mod tests {
TAC # use super::*;
TAC # #[test]
AAA # fn quoted_data_and_commands_take_different_roles()
AAC # assert!(!action_text("Please translate ‘deliver the annual report’ into Spanish.").contains("annual report"))
AAC # assert!(!action_text("Count the words in \"send the invoices\".").contains("invoices"))
AAC # assert!(action_text("Debug the message \"missing route file\".").contains("route file"))
AAC # assert!(action_text("Proofread 'this message'. Then diagnose 'expired lease'.").contains("expired lease"))
AAC # assert!(action_text("Translate 'unfinished phrase").contains("unfinished phrase"))
AAC # assert!(!action_text("Does ‘install the generator’ sound abrupt?").contains("generator"))
AAC # assert!(!action_text("In `clean the kettle`, what noun is the object?").contains("kettle"))
AAC # assert!(action_text("Does 'service unavailable' indicate a broken endpoint?").contains("service unavailable"))
AAC # assert!(action_text("Does `route lookup` read from the cache?").contains("route lookup"))
AAC # assert!(action_text("Count records matching 'connection refused'.").contains("connection refused"))
AAC # assert!(action_text("What does 'connection refused' mean when starting the service?").contains("connection refused"))
AAC # assert!(!action_text("Translate 'blue' and 'yellow'.").contains("yellow"))
TTT # end
TAC # #[test]
AAA # fn quoted_subject_and_separate_search_can_need_different_methods()
AAC # let q=action_text("Translate ‘solar power’. Then search all archived logs for the solar power.")
AAC # assert!(q.contains("search all archived logs for the solar power"))
AAC # let roles=TaskRoles::parse(&q)
AAC # assert!(roles.allows("Search archived logs for solar power", "Find its original source", ""))
AAC # assert!(!roles.allows("Create a solar power supply", "Install the equipment", ""))
AAC # let q=action_text("Count the words and letters in ‘check cooling pressure’.")
AAC # assert!(!q.contains("cooling pressure"))
AAC # assert!(TaskRoles::parse(&q).allows("Count words and letters", "Count alphabetic characters separately", ""))
AAC # assert!(!TaskRoles::parse(&q).allows("Check cooling pressure", "Read the gauge", ""))
TTT # end
TAC # #[test]
AAA # fn apostrophes_and_escapes_do_not_split_balanced_spans()
AAC # let s = r#"Don't strip \"unquoted\" or 'this isn't a command', “nor this” and ‘unfinished"#
AAC # assert_eq!(quoted_spans(s).into_iter().map(|r| &s[r]).collect::<Vec<_>>(),["'this isn't a command'","“nor this”"])
TTT # end
TAC # }