interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / allen-reflex / src / lib.rs

596 lines · 19056 bytes Raw Blame History
1#![no_std]
2// SPDX-License-Identifier: Apache-2.0
3// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16#![deny(unsafe_code)]
17#![allow(clippy::needless_range_loop)]
18
19//! ALLEN REFLEX v0: ALLEN's own decision core for the Pi.
20//!
21//! It reads an operator message (with earlier turns) and answers with exactly one
22//! machine-checkable decision `{"action":"<name>","args":{...}}` from the 15 decisions of
23//! the orchestration exam. No language model and no prompt: a small learned memory plus
24//! explicit rules taken from the agent's own source (`agent_cmd.c`, `lifecycle_fsm.c`).
25//!
26//! Pipeline for one decision:
27//! 1. [`dialog`]: roles and turn order; pending-task state from earlier decisions.
28//! 2. [`text`]: tokens with byte offsets into the original message.
29//! 3. [`segment`]: ordered requests; the decision is about the first real request.
30//! 4. [`policy`]: refuse by intent (rule breaking, verbs the agent lacks, obeying data).
31//! 5. [`features`] then a scorer from [`model`]: hypervector memory (REFLEX), or the
32//! nearest-exemplar and perceptron baselines over the same features.
33//! 6. Abstention: low similarity, low margin or low neighbour agreement -> `clarify`/`none`.
34//! 7. [`span`]: copy the argument text (1..48 printable ASCII bytes) or answer `clarify`.
35//!
36//! The crate is `no_std` + `alloc`; its only dependency is the in-repo `aienos-crypto`
37//! (SHA-256 for [`tower`] cache keys). A kernel that links it must provide a global
38//! allocator and a panic handler. Every input is bounded (see [`Config`]).
39
40extern crate alloc;
41#[cfg(test)]
42extern crate std;
43
44pub mod action;
45pub mod dialog;
46pub mod features;
47pub mod hv;
48pub mod lexicon;
49pub mod model;
50pub mod policy;
51pub mod route;
52pub mod segment;
53pub mod span;
54pub mod text;
55pub mod tower;
56
57pub use action::{Action, N_LABELS};
58pub use dialog::{Pending, Role, Turn};
59pub use model::{Conflict, HvConfig, MemoryFull, SleepReport};
60
61use alloc::string::String;
62use alloc::vec::Vec;
63use features::{Feat, N_CHANNELS};
64use model::{argmax, HvModel, NearestModel, PerceptronModel, Scores};
65use policy::RefuseRule;
66use segment::Clause;
67use span::{CueMemory, SpanError};
68use text::Token;
69
70/// Which label scorer runs behind the shared front end.
71#[derive(Clone, Copy, PartialEq, Eq, Debug)]
72pub enum Mode {
73 /// hypervector exemplars + ternary prototypes
74 Reflex,
75 /// nearest exemplar over sparse feature sets (no hypervectors)
76 Nearest,
77 /// averaged perceptron over sparse features
78 Perceptron,
79}
80
81impl Mode {
82 /// Mode name used in result file names.
83 pub fn name(self) -> &'static str {
84 match self {
85 Mode::Reflex => "reflex",
86 Mode::Nearest => "nearest",
87 Mode::Perceptron => "perceptron",
88 }
89 }
90}
91
92/// All knobs. [`Config::frozen`] holds the values the exam was scored with.
93#[derive(Clone, Copy, Debug)]
94pub struct Config {
95 /// scorer
96 pub mode: Mode,
97 /// weight per feature channel (Word, Bigram, Chars, Concept, Lead, Ctx, CtxConj, Shape)
98 pub weights: [u16; N_CHANNELS],
99 /// hypervector settings (k is also used by the nearest baseline)
100 pub hv: HvConfig,
101 /// below this score margin between the top two labels: abstain (`clarify`)
102 pub t_margin: f32,
103 /// below this similarity to the nearest exemplar: answer `abs_label`
104 pub t_abs: f32,
105 /// what an unfamiliar message gets
106 pub abs_label: Action,
107 /// below this share of top-k neighbours agreeing with the top label: abstain
108 pub t_agree: f32,
109 /// at or above this similarity the nearest exemplar's label is taken as is
110 /// (one-shot corrections win for the same message)
111 pub exact: f32,
112 /// perceptron passes
113 pub perceptron_epochs: u32,
114 /// sleep: same-label exemplars this similar are merged
115 pub sleep_dup: f32,
116 /// sleep: different-label exemplars this similar are reported as conflicts
117 pub sleep_conflict: f32,
118 /// input bound: bytes of the scored message (agent_cmd.c's file limit)
119 pub max_msg_bytes: usize,
120 /// input bound: tokens read
121 pub max_tokens: usize,
122 /// input bound: turns read
123 pub max_turns: usize,
124}
125
126impl Config {
127 /// The frozen configuration (chosen on dev; see docs/native/PI5-8-ALLEN-REFLEX.md).
128 pub fn frozen(mode: Mode) -> Config {
129 let base = Config {
130 mode,
131 weights: [3, 2, 1, 4, 4, 3, 3, 2],
132 hv: HvConfig {
133 words: 128,
134 k: 3,
135 alpha: 0.5,
136 zero_band: 0.42,
137 epochs: 40,
138 eta: 0.5,
139 max_exemplars: 1024,
140 },
141 t_margin: 0.0,
142 t_abs: -1.0,
143 abs_label: Action::None,
144 t_agree: 0.0,
145 exact: 0.97,
146 perceptron_epochs: 20,
147 sleep_dup: 0.95,
148 sleep_conflict: 0.80,
149 max_msg_bytes: 2048,
150 max_tokens: 256,
151 max_turns: 16,
152 };
153 match mode {
154 Mode::Reflex => Config {
155 weights: [3, 0, 1, 6, 4, 3, 3, 2],
156 ..base
157 },
158 Mode::Nearest => Config {
159 weights: [0, 2, 0, 6, 4, 0, 3, 2],
160 hv: HvConfig { k: 5, ..base.hv },
161 ..base
162 },
163 Mode::Perceptron => Config {
164 weights: [0, 2, 1, 4, 4, 3, 3, 2],
165 perceptron_epochs: 10,
166 ..base
167 },
168 }
169 }
170}
171
172/// One decision.
173#[derive(Clone, Debug, PartialEq, Eq)]
174pub struct Decision {
175 /// the action
176 pub action: Action,
177 /// text for remember, prefer, task, prompt (1..48 printable ASCII, no `"` or `\`)
178 pub text: Option<String>,
179}
180
181impl Decision {
182 fn bare(a: Action) -> Decision {
183 Decision {
184 action: a,
185 text: None,
186 }
187 }
188
189 /// The decision as one JSON line, always valid for the exam schema.
190 pub fn json(&self) -> String {
191 let mut s = String::from("{\"action\":\"");
192 s.push_str(self.action.name());
193 s.push_str("\",\"args\":{");
194 if let Some(t) = &self.text {
195 s.push_str("\"text\":\"");
196 s.push_str(t);
197 s.push('"');
198 }
199 s.push_str("}}");
200 s
201 }
202}
203
204/// Why the decision came out as it did.
205#[derive(Clone, Copy, Debug, PartialEq)]
206pub enum Why {
207 /// no user turn
208 NoUserTurn,
209 /// message longer than the bound
210 InputTooLong,
211 /// no words
212 NoWords,
213 /// policy layer refused
214 Policy(RefuseRule),
215 /// nearest exemplar is (almost) the same message
216 ExactRecall,
217 /// top label of the scorer
218 Scored,
219 /// nearest exemplar too far: unfamiliar message
220 LowSimilarity,
221 /// top two labels too close
222 LowMargin,
223 /// neighbours disagree
224 LowAgreement,
225 /// a text action without usable text
226 Span(SpanError),
227}
228
229/// Explanation of a decision. Kept outside the decision JSON.
230#[derive(Clone, Debug)]
231pub struct Explanation {
232 /// reason
233 pub why: Why,
234 /// scorer's top label (before abstention)
235 pub top: Action,
236 /// runner-up
237 pub second: Action,
238 /// score margin between them
239 pub margin: f32,
240 /// nearest exemplar similarity
241 pub best_sim: f32,
242 /// neighbour agreement
243 pub agree: f32,
244 /// nearest exemplar: label and its message
245 pub nearest: Option<(Action, String)>,
246 /// word where a policy rule fired
247 pub rule_word: Option<String>,
248 /// byte range of the copied text in the message
249 pub span: Option<(usize, usize)>,
250}
251
252impl Explanation {
253 fn new(why: Why) -> Explanation {
254 Explanation {
255 why,
256 top: Action::Clarify,
257 second: Action::Clarify,
258 margin: 0.0,
259 best_sim: 0.0,
260 agree: 0.0,
261 nearest: None,
262 rule_word: None,
263 span: None,
264 }
265 }
266}
267
268/// Why learning was not done.
269#[derive(Clone, Copy, Debug, PartialEq, Eq)]
270pub enum LearnError {
271 /// learning is switched off (evaluation)
272 Off,
273 /// exemplar memory is full; run `sleep()`
274 Full,
275 /// the turns have no user message
276 NoUserTurn,
277}
278
279enum Model {
280 Hv(HvModel),
281 Nearest(NearestModel),
282 Perceptron(PerceptronModel),
283}
284
285struct Analysis<'a> {
286 msg: &'a str,
287 toks: Vec<Token>,
288 clauses: Vec<Clause>,
289 primary: Clause,
290 state: dialog::DialogState,
291}
292
293/// The decision core.
294pub struct Reflex {
295 cfg: Config,
296 model: Model,
297 cues: CueMemory,
298 learning: bool,
299}
300
301fn find_ci(hay: &str, needle: &str) -> Option<usize> {
302 let h = hay.as_bytes();
303 let n = needle.as_bytes();
304 if n.is_empty() || n.len() > h.len() {
305 return None;
306 }
307 (0..=h.len() - n.len()).find(|&i| h[i..i + n.len()].eq_ignore_ascii_case(n))
308}
309
310impl Reflex {
311 /// Empty core with configuration `cfg`. Learning is on.
312 pub fn new(cfg: Config) -> Reflex {
313 let model = match cfg.mode {
314 Mode::Reflex => Model::Hv(HvModel::new(cfg.hv)),
315 Mode::Nearest => Model::Nearest(NearestModel::new(cfg.hv.k, cfg.hv.max_exemplars)),
316 Mode::Perceptron => {
317 Model::Perceptron(PerceptronModel::new(cfg.perceptron_epochs, 65536))
318 }
319 };
320 Reflex {
321 cfg,
322 model,
323 cues: CueMemory::default(),
324 learning: true,
325 }
326 }
327
328 /// The configuration.
329 pub fn config(&self) -> &Config {
330 &self.cfg
331 }
332
333 /// Switch learning on or off. With learning off, `learn_*` return [`LearnError::Off`].
334 pub fn set_learning(&mut self, on: bool) {
335 self.learning = on;
336 }
337
338 /// Stored exemplars (0 for the perceptron, which keeps weights).
339 pub fn exemplars(&self) -> usize {
340 match &self.model {
341 Model::Hv(m) => m.len(),
342 Model::Nearest(m) => m.len(),
343 Model::Perceptron(_) => 0,
344 }
345 }
346
347 /// Label and message of exemplar `i`.
348 pub fn exemplar(&self, i: usize) -> Option<(Action, &str)> {
349 match &self.model {
350 Model::Hv(m) if i < m.len() => Some(m.exemplar(i)),
351 Model::Nearest(m) if i < m.len() => Some(m.exemplar(i)),
352 _ => None,
353 }
354 }
355
356 /// Bytes of learned state (exemplars, prototypes, cues), capacity based.
357 pub fn memory_bytes(&self) -> usize {
358 let m = match &self.model {
359 Model::Hv(m) => m.bytes(),
360 Model::Nearest(m) => m.bytes(),
361 Model::Perceptron(m) => m.bytes(),
362 };
363 m + self.cues.bytes()
364 }
365
366 fn analyse<'a>(&self, turns: &[Turn<'a>]) -> Result<Analysis<'a>, Why> {
367 let turns = if turns.len() > self.cfg.max_turns {
368 &turns[turns.len() - self.cfg.max_turns..]
369 } else {
370 turns
371 };
372 let state = dialog::state(turns);
373 let lu = state.last_user.ok_or(Why::NoUserTurn)?;
374 let msg = turns[lu].text;
375 if msg.len() > self.cfg.max_msg_bytes {
376 return Err(Why::InputTooLong);
377 }
378 let toks = text::tokenize(msg, self.cfg.max_tokens);
379 if !toks.iter().any(|t| t.alnum) {
380 return Err(Why::NoWords);
381 }
382 let clauses = segment::clauses(&toks);
383 let primary = segment::primary(&toks, &clauses).ok_or(Why::NoWords)?;
384 Ok(Analysis {
385 msg,
386 toks,
387 clauses,
388 primary,
389 state,
390 })
391 }
392
393 fn feats(&self, a: &Analysis) -> Vec<Feat> {
394 let p = a.primary;
395 let from = a.toks[p.end - 1].end;
396 let to = if p.end < a.toks.len() {
397 a.toks[p.end].start
398 } else {
399 a.msg.len()
400 };
401 let ends_q = a.msg.as_bytes()[from..to].contains(&b'?');
402 features::extract(&a.toks, p, &a.state, &self.cfg.weights, ends_q)
403 }
404
405 fn score(&self, f: &[Feat]) -> Scores {
406 match &self.model {
407 Model::Hv(m) => m.score_hv(&m.encode(f)),
408 Model::Nearest(m) => m.score(f),
409 Model::Perceptron(m) => m.score(f),
410 }
411 }
412
413 /// Decide. Never fails: every outcome is one schema-valid decision.
414 pub fn decide(&self, turns: &[Turn]) -> (Decision, Explanation) {
415 let a = match self.analyse(turns) {
416 Ok(a) => a,
417 Err(w) => return (Decision::bare(Action::Clarify), Explanation::new(w)),
418 };
419 if let Some((r, i)) = policy::check(&a.toks, &a.clauses) {
420 let mut e = Explanation::new(Why::Policy(r));
421 e.rule_word = Some(a.toks[i].word.clone());
422 return (Decision::bare(Action::Refuse), e);
423 }
424 let f = self.feats(&a);
425 let mut sc = self.score(&f);
426 if a.state.pending == Pending::No {
427 for l in [Action::Approve, Action::Deny, Action::Cancel] {
428 sc.s[l.idx()] = -9.0;
429 }
430 }
431 let top = argmax(&sc.s);
432 let mut s2 = sc.s;
433 s2[top] = f32::MIN;
434 let second = argmax(&s2);
435 let mut e = Explanation::new(Why::Scored);
436 e.top = Action::from_idx(top);
437 e.second = Action::from_idx(second);
438 e.margin = sc.s[top] - sc.s[second];
439 e.best_sim = sc.best_sim;
440 e.agree = sc.agree;
441 e.nearest = sc
442 .nearest
443 .and_then(|i| self.exemplar(i))
444 .map(|(l, n)| (l, String::from(n)));
445 let mut act = Action::from_idx(top);
446 let near_label = e.nearest.as_ref().map(|n| n.0);
447 if sc.best_sim >= self.cfg.exact
448 && near_label.is_some_and(|l| !(a.state.pending == Pending::No && l.needs_pending()))
449 {
450 act = near_label.unwrap_or(act);
451 e.why = Why::ExactRecall;
452 } else if sc.best_sim < self.cfg.t_abs {
453 act = self.cfg.abs_label;
454 e.why = Why::LowSimilarity;
455 } else if e.margin < self.cfg.t_margin && act != Action::Clarify {
456 act = Action::Clarify;
457 e.why = Why::LowMargin;
458 } else if sc.agree < self.cfg.t_agree && act != Action::Clarify {
459 act = Action::Clarify;
460 e.why = Why::LowAgreement;
461 }
462 if act.has_text() {
463 match self.cues.extract(a.msg, &a.toks, a.primary, act) {
464 Ok((t, bs, be)) => {
465 e.span = Some((bs, be));
466 return (
467 Decision {
468 action: act,
469 text: Some(t),
470 },
471 e,
472 );
473 }
474 Err(se) => {
475 e.why = Why::Span(se);
476 return (Decision::bare(Action::Clarify), e);
477 }
478 }
479 }
480 (Decision::bare(act), e)
481 }
482
483 fn store(
484 &mut self,
485 turns: &[Turn],
486 label: Action,
487 text: Option<&str>,
488 wrong: Option<Action>,
489 online: bool,
490 ) -> Result<(), LearnError> {
491 let a = self.analyse(turns).map_err(|_| LearnError::NoUserTurn)?;
492 let f = self.feats(&a);
493 let note = String::from(a.msg);
494 match &mut self.model {
495 Model::Hv(m) => {
496 let q = m.encode(&f);
497 let i = m.push(&q, label, &note).map_err(|_| LearnError::Full)?;
498 if online {
499 m.online(i, wrong);
500 }
501 }
502 Model::Nearest(m) => {
503 m.push(&f, label, &note).map_err(|_| LearnError::Full)?;
504 }
505 Model::Perceptron(m) => {
506 if online {
507 m.online(&f, label);
508 } else {
509 m.push(&f, label);
510 }
511 }
512 }
513 if let (true, Some(t)) = (label.has_text(), text) {
514 if let Some(bs) = find_ci(a.msg, t) {
515 self.cues.learn(&a.toks, a.primary, label, bs, bs + t.len());
516 }
517 }
518 Ok(())
519 }
520
521 /// Bulk training: store one labelled example. Call [`Reflex::finish_training`] after the last.
522 pub fn train(
523 &mut self,
524 turns: &[Turn],
525 label: Action,
526 text: Option<&str>,
527 ) -> Result<(), LearnError> {
528 self.store(turns, label, text, None, false)
529 }
530
531 /// Build prototypes (REFLEX: bundling + retraining) or fit weights (perceptron).
532 pub fn finish_training(&mut self) {
533 match &mut self.model {
534 Model::Hv(m) => {
535 m.rebuild();
536 }
537 Model::Nearest(_) => {}
538 Model::Perceptron(m) => m.fit(),
539 }
540 }
541
542 /// The operator confirmed a decision: keep it as an exemplar (one-shot).
543 pub fn learn_confirm(&mut self, turns: &[Turn], d: &Decision) -> Result<(), LearnError> {
544 if !self.learning {
545 return Err(LearnError::Off);
546 }
547 self.store(turns, d.action, d.text.as_deref(), None, true)
548 }
549
550 /// The operator corrected a decision: store the right label and text (one-shot).
551 /// The same message is answered with the corrected label from then on.
552 pub fn learn_correct(
553 &mut self,
554 turns: &[Turn],
555 label: Action,
556 text: Option<&str>,
557 ) -> Result<(), LearnError> {
558 if !self.learning {
559 return Err(LearnError::Off);
560 }
561 let wrong = Some(self.decide(turns).0.action).filter(|w| *w != label);
562 self.store(turns, label, text, wrong, true)
563 }
564
565 /// Consolidation ("sleep"): merge near duplicates, rebuild prototypes, and list
566 /// exemplar pairs with different labels that look alike (questions for the operator).
567 pub fn sleep(&mut self) -> SleepReport {
568 let (dup, con) = (self.cfg.sleep_dup, self.cfg.sleep_conflict);
569 match &mut self.model {
570 Model::Hv(m) => m.sleep(dup, con),
571 Model::Nearest(m) => SleepReport {
572 kept: m.len(),
573 ..SleepReport::default()
574 },
575 Model::Perceptron(m) => {
576 m.fit();
577 SleepReport::default()
578 }
579 }
580 }
581}
582
583/// Build turns from the exam's `turns` field ("user ~~ assistant ~~ user ...").
584pub fn exam_turns(s: &str) -> Vec<Turn<'_>> {
585 s.split(" ~~ ")
586 .enumerate()
587 .map(|(i, t)| Turn {
588 role: if i % 2 == 0 {
589 Role::User
590 } else {
591 Role::Assistant
592 },
593 text: t,
594 })
595 .collect()
596}