feat(app): call detection and the four response policies

- calls.rs: wake words anywhere in the utterance with near matches by
  edit distance on NFKD-normalised letters (Hangul splits into its
  letters), call modes (wakeWord, addressed, everything), designated
  people with both switches, and a voice stop (wake word + stop word).
- policy.rs: first, inOrder, latest and important as an event-driven
  state machine with the time passed in: ordering by end time, waiting
  for an earlier-ended utterance still being transcribed, queue limit,
  interruption, importance ranking only on a tie with a timeout, stop
  dropping the queue, and a reason for every missed request.
- settings: new call and response sections, validated with the key.
- conversation.spec.md documents the contract; registry and roadmap
  updated. Wiring into the Discord core and the brain comes next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 22:05:50 +09:00
parent b88b28140f
commit 6fc3983a40
10 changed files with 1082 additions and 8 deletions

552
app/src/policy.rs Normal file
View File

@@ -0,0 +1,552 @@
//! Response policy: which call Jarvis answers, in what order, and when an answer stops
//! (`app/src/conversation.spec.md`).
//!
//! A state machine driven by events with the time passed in. It never plays or asks anything itself:
//! every call returns the actions for the caller to carry out.
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PolicyKind {
/// 처음 대화만: new requests are dropped while an answer runs (default).
First,
/// 들어온 순서대로: answered one after another in end-time order.
InOrder,
/// 마지막 대화만: the newest request replaces everything else, even a running answer.
Latest,
/// 제일 중요한 대화만: candidates are collected and the best one is answered.
Important,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PolicySettings {
pub kind: PolicyKind,
pub queue_max: usize,
pub collect: Duration,
pub settle: Duration,
pub priorities: HashMap<u64, i64>,
/// How long the brain's importance ranking is waited for.
pub rank_timeout: Duration,
}
impl Default for PolicySettings {
fn default() -> Self {
Self {
kind: PolicyKind::First,
queue_max: 5,
collect: Duration::from_millis(700),
settle: Duration::from_millis(800),
priorities: HashMap::new(),
rank_timeout: Duration::from_millis(1500),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request {
pub id: u64,
pub speaker: u64,
pub text: String,
/// Called by a wake word.
pub direct: bool,
/// When the utterance ended.
pub ended_at: Instant,
/// When its final arrived.
pub arrived_at: Instant,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissReason {
/// `first`: an answer was running or another caller finished first.
Busy,
/// `inOrder`: the queue was full.
QueueFull,
/// `latest`: a newer request took its place.
Replaced,
/// The answer was stopped for a newer or more important request.
Interrupted,
/// `important`: another candidate was chosen.
LowerScore,
/// A stop command.
Stopped,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
/// Start answering this request.
Answer(Request),
/// Stop the running answer with this id (its speech and its reply).
StopAnswer(u64),
/// Not answered, or stopped: for the "놓친 요청" list.
Missed(Request, MissReason),
/// Ask the brain to rank these tied candidates by importance; answer with `ranked`.
Rank(Vec<Request>),
}
#[derive(Debug, Default)]
struct Open {
/// When the speaker stopped sending audio, if they have.
stopped_at: Option<Instant>,
}
pub struct Policy {
s: PolicySettings,
current: Option<Request>,
waiting: Vec<Request>,
open: HashMap<u64, Open>,
/// `important`: no choice before this.
collect_until: Option<Instant>,
/// `important`: the tied candidates being ranked and when to give up waiting.
ranking: Option<(HashSet<u64>, Instant)>,
}
impl Policy {
pub fn new(s: PolicySettings) -> Self {
Self { s, current: None, waiting: vec![], open: HashMap::new(), collect_until: None, ranking: None }
}
pub fn settings(&self) -> &PolicySettings {
&self.s
}
/// The id of the running answer.
pub fn current(&self) -> Option<u64> {
self.current.as_ref().map(|r| r.id)
}
pub fn waiting(&self) -> usize {
self.waiting.len()
}
/// An utterance started (`speech_start`).
pub fn utterance_open(&mut self, speaker: u64) {
self.open.insert(speaker, Open::default());
}
/// The speaker stopped sending audio; their final is still to come.
pub fn speaking_stopped(&mut self, speaker: u64, at: Instant) {
if let Some(o) = self.open.get_mut(&speaker) {
o.stopped_at.get_or_insert(at);
}
}
/// The speaker's final arrived and was not a call (or the speaker left).
pub fn utterance_closed(&mut self, speaker: u64, now: Instant) -> Vec<Action> {
self.open.remove(&speaker);
self.choose(now, None)
}
fn score(&self, r: &Request) -> (i64, bool) {
(self.s.priorities.get(&r.speaker).copied().unwrap_or(0), r.direct)
}
/// The speaker's final was a call.
pub fn request(&mut self, req: Request, now: Instant) -> Vec<Action> {
self.open.remove(&req.speaker);
let mut out = vec![];
if let Some(cur) = self.current.clone() {
match self.s.kind {
PolicyKind::First => out.push(Action::Missed(req, MissReason::Busy)),
PolicyKind::InOrder => self.enqueue(req, &mut out),
PolicyKind::Latest => {
if req.ended_at > cur.ended_at {
self.interrupt(&mut out);
for r in self.waiting.drain(..) {
out.push(Action::Missed(r, MissReason::Replaced));
}
self.waiting.push(req);
} else {
out.push(Action::Missed(req, MissReason::Replaced));
}
}
PolicyKind::Important => {
let beats = self.score(&req) > self.score(&cur);
self.waiting.push(req);
if beats {
self.interrupt(&mut out);
self.collect_until = None;
}
}
}
} else {
if self.s.kind == PolicyKind::Important && self.waiting.is_empty() && self.ranking.is_none() {
self.collect_until = Some(now + self.s.collect);
}
self.enqueue(req, &mut out);
}
out.extend(self.choose(now, None));
out
}
fn enqueue(&mut self, req: Request, out: &mut Vec<Action>) {
let at = self.waiting.partition_point(|r| r.ended_at <= req.ended_at);
self.waiting.insert(at, req);
if self.s.kind == PolicyKind::InOrder {
while self.waiting.len() > self.s.queue_max.max(1) {
out.push(Action::Missed(self.waiting.remove(0), MissReason::QueueFull));
}
}
}
fn interrupt(&mut self, out: &mut Vec<Action>) {
if let Some(cur) = self.current.take() {
out.push(Action::StopAnswer(cur.id));
out.push(Action::Missed(cur, MissReason::Interrupted));
}
}
/// A stop command: stop the answer and drop everything waiting.
pub fn stop(&mut self) -> Vec<Action> {
let mut out = vec![];
if let Some(cur) = self.current.take() {
out.push(Action::StopAnswer(cur.id));
out.push(Action::Missed(cur, MissReason::Stopped));
}
for r in self.waiting.drain(..) {
out.push(Action::Missed(r, MissReason::Stopped));
}
self.collect_until = None;
self.ranking = None;
out
}
/// The answer's speech ended, failed or was stopped.
pub fn answer_done(&mut self, id: u64, now: Instant) -> Vec<Action> {
if self.current.as_ref().map(|r| r.id) != Some(id) {
return vec![];
}
self.current = None;
self.choose(now, None)
}
/// The brain's ranking of the tied candidates, best first.
pub fn ranked(&mut self, order: &[u64], now: Instant) -> Vec<Action> {
let Some((tied, _)) = self.ranking.take() else { return vec![] };
let winner = order.iter().copied().find(|id| tied.contains(id));
self.choose(now, Some(winner))
}
/// Timers: settling, collecting and the ranking timeout.
pub fn tick(&mut self, now: Instant) -> Vec<Action> {
if let Some((_, deadline)) = &self.ranking {
if now >= *deadline {
self.ranking = None;
return self.choose(now, Some(None));
}
}
self.choose(now, None)
}
/// When `tick` should run next.
pub fn next_deadline(&self) -> Option<Instant> {
if let Some((_, t)) = &self.ranking {
return Some(*t);
}
let mut d: Vec<Instant> = vec![];
if self.current.is_none() && !self.waiting.is_empty() {
if let Some(t) = self.collect_until {
d.push(t);
}
if let Some(first) = self.waiting.iter().map(|r| r.arrived_at).min() {
d.push(first + self.s.settle);
}
}
d.into_iter().min()
}
/// Wait for an ending utterance that may still be a call that should come first.
fn blocked(&self, now: Instant) -> bool {
let ending: Vec<Instant> = self.open.values().filter_map(|o| o.stopped_at).collect();
if ending.is_empty() {
return false;
}
let Some(first_arrival) = self.waiting.iter().map(|r| r.arrived_at).min() else { return false };
if now >= first_arrival + self.s.settle {
return false;
}
match self.s.kind {
PolicyKind::Latest => false,
PolicyKind::First | PolicyKind::InOrder => {
let head = self.waiting[0].ended_at;
ending.iter().any(|t| *t < head)
}
PolicyKind::Important => true,
}
}
/// Start the next answer if the policy allows one now. `rank`: `Some(winner)` once a ranking
/// finished or gave up.
fn choose(&mut self, now: Instant, rank: Option<Option<u64>>) -> Vec<Action> {
let mut out = vec![];
if self.current.is_some() || self.waiting.is_empty() || (self.ranking.is_some() && rank.is_none()) {
return out;
}
if rank.is_none() {
if let Some(t) = self.collect_until {
if now < t {
return out;
}
}
if self.blocked(now) {
return out;
}
}
let winner = match self.s.kind {
PolicyKind::First | PolicyKind::InOrder => 0,
PolicyKind::Latest => self.waiting.len() - 1,
PolicyKind::Important => {
let best = self.waiting.iter().map(|r| self.score(r)).max().expect("not empty");
let tied: Vec<usize> = (0..self.waiting.len()).filter(|&i| self.score(&self.waiting[i]) == best).collect();
match rank {
Some(Some(id)) if tied.iter().any(|&i| self.waiting[i].id == id) => {
tied.into_iter().find(|&i| self.waiting[i].id == id).expect("present")
}
// A ranking that failed, timed out, or named nobody still tied: the earliest-ended.
Some(_) => tied[0],
None if tied.len() >= 2 => {
let cands: Vec<Request> = tied.iter().map(|&i| self.waiting[i].clone()).collect();
self.ranking = Some((cands.iter().map(|r| r.id).collect(), now + self.s.rank_timeout));
out.push(Action::Rank(cands));
return out;
}
None => tied[0],
}
}
};
let chosen = self.waiting.remove(winner);
let others = match self.s.kind {
PolicyKind::InOrder => vec![],
PolicyKind::First => std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::Busy)).collect(),
PolicyKind::Latest => std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::Replaced)).collect(),
PolicyKind::Important => {
std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::LowerScore)).collect()
}
};
for (r, why) in others {
out.push(Action::Missed(r, why));
}
self.collect_until = None;
self.current = Some(chosen.clone());
out.push(Action::Answer(chosen));
out
}
}
#[cfg(test)]
mod tests {
use super::*;
const A: u64 = 1;
const B: u64 = 2;
const C: u64 = 3;
struct T {
p: Policy,
t0: Instant,
next_id: u64,
}
impl T {
fn new(kind: PolicyKind) -> Self {
Self::with(PolicySettings { kind, ..PolicySettings::default() })
}
fn with(s: PolicySettings) -> Self {
Self { p: Policy::new(s), t0: Instant::now(), next_id: 0 }
}
fn at(&self, ms: u64) -> Instant {
self.t0 + Duration::from_millis(ms)
}
/// A call from `speaker` that ended at `ended` ms and arrived at `arrived` ms.
fn call(&mut self, speaker: u64, direct: bool, ended: u64, arrived: u64) -> (u64, Vec<Action>) {
self.next_id += 1;
let r = Request { id: self.next_id, speaker, text: String::new(), direct, ended_at: self.at(ended),
arrived_at: self.at(arrived) };
let now = self.at(arrived);
(self.next_id, self.p.request(r, now))
}
}
fn answered(a: &[Action]) -> Vec<u64> {
a.iter().filter_map(|x| if let Action::Answer(r) = x { Some(r.id) } else { None }).collect()
}
fn missed(a: &[Action]) -> Vec<(u64, MissReason)> {
a.iter().filter_map(|x| if let Action::Missed(r, w) = x { Some((r.id, *w)) } else { None }).collect()
}
fn stopped(a: &[Action]) -> Vec<u64> {
a.iter().filter_map(|x| if let Action::StopAnswer(id) = x { Some(*id) } else { None }).collect()
}
#[test]
fn first_answers_at_once_and_drops_what_comes_while_busy() {
let mut t = T::new(PolicyKind::First);
let (a, out) = t.call(A, true, 0, 200);
assert_eq!(answered(&out), vec![a]);
let (b, out) = t.call(B, true, 300, 500);
assert_eq!(missed(&out), vec![(b, MissReason::Busy)]);
assert!(t.p.answer_done(a, t.at(2000)).is_empty());
let (c, out) = t.call(C, true, 2100, 2300);
assert_eq!(answered(&out), vec![c]);
}
#[test]
fn first_waits_for_an_earlier_ended_utterance_and_answers_it_if_it_is_a_call() {
let mut t = T::new(PolicyKind::First);
// B stopped talking at 100 ms but is still being transcribed; A ended at 150 ms.
t.p.utterance_open(B);
t.p.speaking_stopped(B, t.at(100));
let (a, out) = t.call(A, true, 150, 300);
assert!(answered(&out).is_empty(), "waits for B");
let (b, out) = t.call(B, true, 100, 500);
assert_eq!(answered(&out), vec![b], "B finished speaking first");
assert_eq!(missed(&out), vec![(a, MissReason::Busy)]);
}
#[test]
fn settling_ends_when_the_earlier_utterance_is_not_a_call_or_takes_too_long() {
let mut t = T::new(PolicyKind::First);
t.p.utterance_open(B);
t.p.speaking_stopped(B, t.at(100));
let (a, _) = t.call(A, true, 150, 300);
assert_eq!(answered(&t.p.utterance_closed(B, t.at(400))), vec![a]);
let mut t = T::new(PolicyKind::First);
t.p.utterance_open(B);
t.p.speaking_stopped(B, t.at(100));
let (a, _) = t.call(A, true, 150, 300);
assert_eq!(t.p.next_deadline(), Some(t.at(300 + 800)));
assert!(answered(&t.p.tick(t.at(1000))).is_empty());
assert_eq!(answered(&t.p.tick(t.at(1100))), vec![a]);
}
#[test]
fn an_utterance_still_being_spoken_or_ended_later_does_not_hold_up_the_answer() {
let mut t = T::new(PolicyKind::First);
t.p.utterance_open(B); // still talking
t.p.utterance_open(C);
t.p.speaking_stopped(C, t.at(400)); // ended after A
let (a, out) = t.call(A, true, 150, 300);
assert_eq!(answered(&out), vec![a]);
}
#[test]
fn in_order_follows_end_times_not_arrival_and_drops_the_oldest_when_full() {
let mut t = T::with(PolicySettings { kind: PolicyKind::InOrder, queue_max: 2, ..PolicySettings::default() });
let (a, out) = t.call(A, true, 0, 100);
assert_eq!(answered(&out), vec![a]);
let (c, _) = t.call(C, true, 900, 1000); // ended later, arrived first
let (b, _) = t.call(B, true, 600, 1500); // long utterance: ended earlier, arrived later
assert_eq!(answered(&t.p.answer_done(a, t.at(2000))), vec![b]);
assert_eq!(answered(&t.p.answer_done(b, t.at(3000))), vec![c]);
let (_, out) = t.call(A, true, 3100, 3200);
assert!(answered(&out).is_empty());
let (e, _) = t.call(B, true, 3300, 3400);
let (_f, out) = t.call(C, true, 3500, 3600);
assert_eq!(t.p.waiting(), 2);
assert_eq!(missed(&out).len(), 1, "third waiting request pushes the oldest out");
assert_eq!(answered(&t.p.answer_done(c, t.at(4000))), vec![e]);
}
#[test]
fn latest_interrupts_for_a_newer_request_and_drops_older_ones() {
let mut t = T::new(PolicyKind::Latest);
let (a, _) = t.call(A, true, 0, 100);
let (b, out) = t.call(B, true, 500, 700);
assert_eq!(stopped(&out), vec![a]);
assert_eq!(missed(&out), vec![(a, MissReason::Interrupted)]);
assert_eq!(answered(&out), vec![b]);
// A late final from before B's end is not newer.
let (c, out) = t.call(C, true, 400, 900);
assert_eq!(missed(&out), vec![(c, MissReason::Replaced)]);
assert!(stopped(&out).is_empty());
// The stopped answer's late "done" changes nothing.
assert!(t.p.answer_done(a, t.at(1000)).is_empty());
assert_eq!(t.p.current(), Some(b));
}
#[test]
fn latest_answers_the_newest_of_several_waiting() {
let mut t = T::new(PolicyKind::Latest);
t.p.utterance_open(C);
let (a, out) = t.call(A, true, 0, 100);
assert_eq!(answered(&out), vec![a], "latest never settles");
let (b, _) = t.call(B, true, 200, 300);
assert_eq!(t.p.current(), Some(b));
}
#[test]
fn important_collects_then_answers_the_best_by_priority_then_wake_word() {
let mut s = PolicySettings { kind: PolicyKind::Important, ..PolicySettings::default() };
s.priorities.insert(C, 5);
let mut t = T::with(s);
let (a, out) = t.call(A, true, 0, 100);
assert!(answered(&out).is_empty(), "collecting for 700 ms");
let (b, _) = t.call(B, false, 100, 200);
let (c, _) = t.call(C, false, 200, 300);
assert_eq!(t.p.next_deadline(), Some(t.at(800)));
let out = t.p.tick(t.at(800));
assert_eq!(answered(&out), vec![c], "priority wins over the wake word");
let mut m = missed(&out);
m.sort_by_key(|(id, _)| *id);
assert_eq!(m, vec![(a, MissReason::LowerScore), (b, MissReason::LowerScore)]);
}
#[test]
fn important_asks_for_a_ranking_only_on_a_tie_and_falls_back_on_timeout() {
let mut t = T::new(PolicyKind::Important);
let (a, _) = t.call(A, true, 0, 100);
let (b, _) = t.call(B, true, 50, 200);
let out = t.p.tick(t.at(800));
let ranks: Vec<Vec<u64>> = out.iter().filter_map(|x| if let Action::Rank(c) = x {
Some(c.iter().map(|r| r.id).collect()) } else { None }).collect();
assert_eq!(ranks, vec![vec![a, b]]);
assert!(answered(&out).is_empty());
assert_eq!(answered(&t.p.ranked(&[b, a], t.at(900))), vec![b]);
let mut t = T::new(PolicyKind::Important);
let (a, _) = t.call(A, true, 0, 100);
let (_b, _) = t.call(B, true, 50, 200);
t.p.tick(t.at(800));
assert_eq!(t.p.next_deadline(), Some(t.at(800 + 1500)));
assert_eq!(answered(&t.p.tick(t.at(2300))), vec![a], "timeout: earliest-ended wins");
assert!(t.p.ranked(&[2], t.at(2400)).is_empty(), "a late ranking is ignored");
// One candidate: no ranking, no extra delay beyond collecting.
let mut t = T::new(PolicyKind::Important);
let (a, _) = t.call(A, true, 0, 100);
assert_eq!(answered(&t.p.tick(t.at(800))), vec![a]);
}
#[test]
fn important_interrupts_only_for_a_higher_score_and_otherwise_answers_after() {
let mut s = PolicySettings { kind: PolicyKind::Important, collect: Duration::ZERO, ..PolicySettings::default() };
s.priorities.insert(C, 1);
let mut t = T::with(s);
let (a, out) = t.call(A, false, 0, 100);
assert_eq!(answered(&out), vec![a]);
let (b, out) = t.call(B, false, 200, 300);
assert!(stopped(&out).is_empty(), "same score: keep going");
assert_eq!(answered(&t.p.answer_done(a, t.at(1000))), vec![b]);
let (c, out) = t.call(C, false, 1100, 1200);
assert_eq!(stopped(&out), vec![b]);
assert_eq!(missed(&out), vec![(b, MissReason::Interrupted)]);
assert_eq!(answered(&out), vec![c]);
}
#[test]
fn stop_ends_the_answer_and_drops_the_queue_in_every_policy() {
for kind in [PolicyKind::First, PolicyKind::InOrder, PolicyKind::Latest, PolicyKind::Important] {
let mut t = T::with(PolicySettings { kind, collect: Duration::ZERO, ..PolicySettings::default() });
let _ = t.call(A, true, 0, 100);
let _ = t.call(B, true, 50, 200);
let running = t.p.current().expect("an answer runs");
let out = t.p.stop();
assert_eq!(stopped(&out), vec![running], "{kind:?}");
assert!(missed(&out).iter().any(|(id, _)| *id == running), "{kind:?}");
assert!(missed(&out).iter().all(|(_, w)| *w == MissReason::Stopped), "{kind:?}");
assert_eq!(t.p.current(), None);
assert_eq!(t.p.waiting(), 0);
}
}
}