aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / allen-reflex / src / span.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Argument copy. The text of remember, prefer, task and prompt is copied byte for byte |
| 17 | //! from the operator's request (case and inner punctuation kept). Only its two boundaries |
| 18 | //! are decided: where the command words end and where trailing words ("from now on") begin. |
| 19 | //! |
| 20 | //! Boundaries are learned from training spans (the words before and after the expected |
| 21 | //! text, per action). For an unseen phrasing: |
| 22 | //! 1. the longest learned leading cue at the start, or the last 2+ words of a learned cue |
| 23 | //! one or two words in ("Create a task to" matches the tail of "add a task to"); |
| 24 | //! 2. a colon or free dash within the first 8 words, at or after that cue, when the words |
| 25 | //! before it are cue words or unknown ("Remember this note: ..."); |
| 26 | //! 3. with no cue so far, a store/to-do/preference frame is skipped; then, in every case, |
| 27 | //! words seen more often as cue than as content for that action ("to" after "add a task"). |
| 28 | //! |
| 29 | //! Defined outcomes when no valid text exists (the caller answers `clarify`): |
| 30 | //! [`SpanError::Empty`] (nothing but pointer words: "Save this."), [`SpanError::TooLong`] |
| 31 | //! (more than 48 bytes; never truncated silently), [`SpanError::Unrepresentable`] |
| 32 | //! (a double quote, a backslash or a byte outside printable ASCII, which the card-script |
| 33 | //! format cannot carry). Curly apostrophes are the one substitution: they become `'`. |
| 34 | |
| 35 | use crate::action::Action; |
| 36 | use crate::lexicon::{is_in, longest, skip_polite, TEXT_FRAMES, VACUOUS, WRITE_VERBS}; |
| 37 | use crate::segment::Clause; |
| 38 | use crate::text::{fnv, gap, Token}; |
| 39 | use alloc::collections::BTreeMap; |
| 40 | use alloc::string::String; |
| 41 | use alloc::vec::Vec; |
| 42 | |
| 43 | /// Bound on learned cues (prefix + suffix). |
| 44 | pub const MAX_CUES: usize = 512; |
| 45 | /// Bound on words in one cue. |
| 46 | pub const MAX_CUE_WORDS: usize = 8; |
| 47 | /// Bound on per-word statistics entries. |
| 48 | pub const MAX_STATS: usize = 4096; |
| 49 | /// Longest text the agent accepts (agent_cmd.c). |
| 50 | pub const MAX_TEXT: usize = 48; |
| 51 | |
| 52 | /// Why no text could be produced. |
| 53 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 54 | pub enum SpanError { |
| 55 | /// only pointer or command words |
| 56 | Empty, |
| 57 | /// longer than 48 bytes |
| 58 | TooLong, |
| 59 | /// a byte the card-script format cannot carry |
| 60 | Unrepresentable, |
| 61 | } |
| 62 | |
| 63 | /// Learned cue phrases and per-word cue/content counts. |
| 64 | #[derive(Clone, Default)] |
| 65 | pub struct CueMemory { |
| 66 | prefix: Vec<(u8, Vec<u64>)>, |
| 67 | suffix: Vec<(u8, Vec<u64>)>, |
| 68 | stats: BTreeMap<(u8, u64), (u16, u16)>, |
| 69 | } |
| 70 | |
| 71 | const TRAIL_POLITE: &[&str] = &["please", "thanks"]; |
| 72 | |
| 73 | fn h(t: &Token) -> u64 { |
| 74 | fnv(t.word.as_bytes()) |
| 75 | } |
| 76 | |
| 77 | impl CueMemory { |
| 78 | /// Bytes held (approximate). |
| 79 | pub fn bytes(&self) -> usize { |
| 80 | (self.prefix.iter().chain(self.suffix.iter())) |
| 81 | .map(|c| 32 + c.1.capacity() * 8) |
| 82 | .sum::<usize>() |
| 83 | + self.stats.len() * 48 |
| 84 | } |
| 85 | |
| 86 | /// Number of learned cues. |
| 87 | pub fn cues(&self) -> usize { |
| 88 | self.prefix.len() + self.suffix.len() |
| 89 | } |
| 90 | |
| 91 | fn add_cue(list: &mut Vec<(u8, Vec<u64>)>, a: u8, c: Vec<u64>, total: usize) { |
| 92 | if c.len() > MAX_CUE_WORDS || total >= MAX_CUES { |
| 93 | return; |
| 94 | } |
| 95 | if !list.iter().any(|x| x.0 == a && x.1 == c) { |
| 96 | list.push((a, c)); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | fn bump(&mut self, a: u8, t: &Token, cue: bool) { |
| 101 | let k = (a, h(t)); |
| 102 | if !self.stats.contains_key(&k) && self.stats.len() >= MAX_STATS { |
| 103 | return; |
| 104 | } |
| 105 | let e = self.stats.entry(k).or_insert((0, 0)); |
| 106 | if cue { |
| 107 | e.0 = e.0.saturating_add(1); |
| 108 | } else { |
| 109 | e.1 = e.1.saturating_add(1); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// Learn from one example whose text occupies bytes `[bs, be)` of the message. |
| 114 | /// Returns false when the span does not fall on token boundaries inside the clause. |
| 115 | pub fn learn(&mut self, toks: &[Token], c: Clause, a: Action, bs: usize, be: usize) -> bool { |
| 116 | let lead = skip_polite(toks, c.start, c.end); |
| 117 | let s0 = (c.start..c.end).find(|&i| toks[i].start >= bs); |
| 118 | let e0 = (c.start..c.end).rev().find(|&i| toks[i].end <= be); |
| 119 | let (s0, e0) = match (s0, e0) { |
| 120 | (Some(s), Some(e)) if s <= e && s >= lead => (s, e + 1), |
| 121 | _ => return false, |
| 122 | }; |
| 123 | let ai = a.idx() as u8; |
| 124 | let total = self.cues(); |
| 125 | let pre: Vec<u64> = toks[lead..s0].iter().map(h).collect(); |
| 126 | Self::add_cue(&mut self.prefix, ai, pre, total); |
| 127 | if e0 < c.end { |
| 128 | let total = self.cues(); |
| 129 | let suf: Vec<u64> = toks[e0..c.end].iter().map(h).collect(); |
| 130 | Self::add_cue(&mut self.suffix, ai, suf, total); |
| 131 | } |
| 132 | for i in lead..s0 { |
| 133 | self.bump(ai, &toks[i], true); |
| 134 | } |
| 135 | for i in s0..e0 { |
| 136 | self.bump(ai, &toks[i], false); |
| 137 | } |
| 138 | true |
| 139 | } |
| 140 | |
| 141 | fn cue_like(&self, a: u8, t: &Token) -> Option<bool> { |
| 142 | self.stats.get(&(a, h(t))).map(|(c, p)| c > p) |
| 143 | } |
| 144 | |
| 145 | /// Token range `[s, e)` of the text for action `a` in clause `c`. |
| 146 | pub fn bounds(&self, toks: &[Token], c: Clause, a: Action) -> (usize, usize) { |
| 147 | let ai = a.idx() as u8; |
| 148 | let lead = skip_polite(toks, c.start, c.end); |
| 149 | let end = c.end; |
| 150 | let mut s = None; |
| 151 | // 1. longest learned non-empty leading cue at the head, or the tail (2+ words) of a |
| 152 | // learned cue starting one or two words later ("Create a task to" via "add a task to") |
| 153 | let mut best = 0; |
| 154 | for p in lead..core::cmp::min(lead + 3, end) { |
| 155 | for (la, cue) in &self.prefix { |
| 156 | if *la != ai || cue.is_empty() { |
| 157 | continue; |
| 158 | } |
| 159 | for j in 0..cue.len() { |
| 160 | let m = cue.len() - j; |
| 161 | let full = p == lead && j == 0; |
| 162 | if (!full && (m < 2 || p == lead)) || m <= best || p + m >= end { |
| 163 | continue; |
| 164 | } |
| 165 | if cue[j..] |
| 166 | .iter() |
| 167 | .enumerate() |
| 168 | .all(|(k, w)| h(&toks[p + k]) == *w) |
| 169 | { |
| 170 | best = m; |
| 171 | s = Some(p + m); |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | // 2. colon or free dash within the first 8 words, at or after the cue |
| 177 | { |
| 178 | let from = s.unwrap_or(lead + 1); |
| 179 | let hi = core::cmp::min(end, lead + 8); |
| 180 | if let Some(j) = (from..hi).find(|&j| toks[j].gap & (gap::COLON | gap::DASH) != 0) { |
| 181 | let ok = toks[s.unwrap_or(lead)..j] |
| 182 | .iter() |
| 183 | .all(|t| self.cue_like(ai, t).unwrap_or(true)); |
| 184 | if ok { |
| 185 | s = Some(j); |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | // 3. without a cue: skip a store/to-do/preference frame; then, in every case, skip |
| 190 | // words seen more often as cue than as content for this action ("to" after |
| 191 | // "add a task") |
| 192 | let mut v = match s { |
| 193 | Some(v) => v, |
| 194 | None => { |
| 195 | let mut v = lead; |
| 196 | if a != Action::Prompt { |
| 197 | let f = longest(toks, v, TEXT_FRAMES); |
| 198 | if v + f < end { |
| 199 | v += f; |
| 200 | } |
| 201 | } |
| 202 | v |
| 203 | } |
| 204 | }; |
| 205 | while v + 1 < end && v < lead + 6 && self.cue_like(ai, &toks[v]) == Some(true) { |
| 206 | v += 1; |
| 207 | } |
| 208 | let mut s = v; |
| 209 | if s >= end { |
| 210 | s = end; |
| 211 | } |
| 212 | // trailing cue (longest learned suffix), then trailing courtesy words |
| 213 | let mut e = end; |
| 214 | let mut bests = 0; |
| 215 | for (la, cue) in &self.suffix { |
| 216 | if *la != ai || cue.len() <= bests || s + cue.len() >= e { |
| 217 | continue; |
| 218 | } |
| 219 | let at = e - cue.len(); |
| 220 | if cue.iter().enumerate().all(|(k, w)| h(&toks[at + k]) == *w) { |
| 221 | bests = cue.len(); |
| 222 | } |
| 223 | } |
| 224 | e -= bests; |
| 225 | while e > s + 1 && is_in(TRAIL_POLITE, &toks[e - 1].word) { |
| 226 | e -= 1; |
| 227 | } |
| 228 | if e > s + 2 && toks[e - 2].word == "thank" && toks[e - 1].word == "you" { |
| 229 | e -= 2; |
| 230 | } |
| 231 | (s, e) |
| 232 | } |
| 233 | |
| 234 | /// Copy the text for action `a` out of `msg`. |
| 235 | pub fn extract( |
| 236 | &self, |
| 237 | msg: &str, |
| 238 | toks: &[Token], |
| 239 | c: Clause, |
| 240 | a: Action, |
| 241 | ) -> Result<(String, usize, usize), SpanError> { |
| 242 | let (s, e) = self.bounds(toks, c, a); |
| 243 | if s >= e { |
| 244 | return Err(SpanError::Empty); |
| 245 | } |
| 246 | let content = toks[s..e].iter().any(|t| { |
| 247 | t.alnum |
| 248 | && !is_in(VACUOUS, &t.word) |
| 249 | && !(a == Action::Prompt && is_in(WRITE_VERBS, &t.word)) |
| 250 | }); |
| 251 | if !content { |
| 252 | return Err(SpanError::Empty); |
| 253 | } |
| 254 | let bs = toks[s].start; |
| 255 | let mut be = toks[e - 1].end; |
| 256 | let b = msg.as_bytes(); |
| 257 | let opens = b[bs..be].iter().filter(|&&x| x == b'(').count(); |
| 258 | let closes = b[bs..be].iter().filter(|&&x| x == b')').count(); |
| 259 | if opens > closes && be < b.len() && b[be] == b')' { |
| 260 | be += 1; |
| 261 | } |
| 262 | let mut out = String::with_capacity(be - bs); |
| 263 | for ch in msg[bs..be].chars() { |
| 264 | match ch { |
| 265 | '\u{2019}' | '\u{2018}' => out.push('\''), |
| 266 | c => out.push(c), |
| 267 | } |
| 268 | } |
| 269 | if out.len() > MAX_TEXT { |
| 270 | return Err(SpanError::TooLong); |
| 271 | } |
| 272 | if out |
| 273 | .bytes() |
| 274 | .any(|x| !(0x20..=0x7e).contains(&x) || x == b'"' || x == b'\\') |
| 275 | { |
| 276 | return Err(SpanError::Unrepresentable); |
| 277 | } |
| 278 | Ok((out, bs, be)) |
| 279 | } |
| 280 | } |