Skip to main content

oomtop_core/
query.rs

1//! Query understanding (UX §5.2): one engine for `/` filters, `:` commands and the `Ctrl-K` palette.
2//!
3//! **Filter grammar** (defined once; used by `/`, aliases, saved views and rules):
4//! - terms separated by spaces are AND (`and` / `&&` are accepted as no-ops);
5//! - `or` (also `||`) is OR and binds looser than AND;
6//! - `-term`, `!term` or `not term` negates; `-(…)` negates a group;
7//! - parentheses group;
8//! - `key:a,b` means `key:a or key:b`; values may be quoted (`owner:"Claude Code"`) and may use `*` globs;
9//! - keys: `kind` (short aliases from SPEC §5: agent, app, model, sandbox, daemon, system, other; plurals and a
10//!   few synonyms such as `vm`/`llm` are accepted), `owner`, `name`, `state` (alias `is`), `sandbox`, and the
11//!   metrics `mem`, `gpu`, `cpu`, `idle`;
12//! - comparisons `> >= < <= =` take units: bytes for `mem`/`gpu` (`2G`, `500M`, `1.5GiB`, `2GB`), percent of one
13//!   core for `cpu` (`50`, `50%`), durations for `idle` (`30m`, `5h`, `1h30m`). Spaces around the operator are
14//!   allowed (`mem > 2G`), as is `mem:>2G`.
15//! - time and staleness ([`TimeMetric`], SPEC §7): `age` (duration, `age>1d`), `duty` (CPU time ÷ age, percent
16//!   of one core, `duty<1%`), `rent` (idle rent in GiB-hours, `rent>10`), `stale` (score 0–1, `stale>0.5`);
17//!   the bare word `stale` (or `state:stale`) matches groups flagged stale. `:sort age|duty|rent|stale` sets
18//!   [`Understanding::sort_time`].
19//! - a bare word matches name, alias, owner, state flag or kind; a fully quoted word (`"a:b"`, `"Claude Code"`)
20//!   is always a literal word (never `key:value` or a keyword), and commas inside quotes never split values
21//!   (`owner:"Smith, John",bob` is two values).
22//!
23//! Example: `kind:model,agent or gpu>1G -muted`.
24//!
25//! **Plain words** go through normalize (case, units `13g`, `13 gb`, typos by Damerau-Levenshtein ≤ 1 on the
26//! known vocabulary; never on entity-name tokens or their prefixes, and 4-letter words only by an adjacent
27//! transposition) → intent classification (rules + keyword lexicon) → entity linking (fzf-style fuzzy score
28//! boosted by frecency) → `{intent, filter, sort, targets, confidence}`. Low confidence (< [`LOW_CONFIDENCE`])
29//! means the palette shows the top-3 [`Interpretation`]s instead of guessing.
30//!
31//! Everything here is deterministic, local and allocation-light (< 1 ms for typical inputs and a few hundred
32//! entities).
33
34use crate::headroom::is_reclaim_candidate;
35use crate::model::{Group, GroupKind, Snapshot};
36use crate::units::{parse_bytes, parse_duration_s, GIB, KIB, MIB, TIB};
37use serde::{Deserialize, Serialize};
38use std::collections::{HashMap, HashSet};
39use std::fmt;
40use thiserror::Error;
41
42/// Below this confidence the palette shows the top interpretations instead of acting.
43pub const LOW_CONFIDENCE: f64 = 0.5;
44/// Weight of frecency-derived affinity (0..1) in entity-linking scores.
45pub const FRECENCY_LINK_BOOST: f64 = 0.5;
46/// Minimum normalized fuzzy score for an entity to be linked at all.
47pub const MIN_LINK_SCORE: f64 = 0.3;
48/// Words shorter than this are never typo-corrected (`cpu` vs `gpu` would collide); words of exactly this
49/// length only by an adjacent transposition.
50pub const MIN_TYPO_LEN: usize = 4;
51
52#[derive(Debug, Error, Clone, PartialEq, Eq)]
53pub enum QueryError {
54    #[error("unknown key {0:?} (expected kind, owner, name, mem, gpu, cpu, idle, age, duty, rent, stale, state, sandbox)")]
55    UnknownKey(String),
56    #[error("bad value {value:?} for {key}: {msg}")]
57    BadValue { key: String, value: String, msg: String },
58    #[error("unbalanced parentheses")]
59    Parens,
60    #[error("empty expression")]
61    Empty,
62    #[error("unterminated quote")]
63    Quote,
64    #[error("expression nested too deeply (more than {MAX_DEPTH} levels)")]
65    TooDeep,
66}
67
68/// Nesting limit of an expression (parentheses and negations): the parser is recursive, and a query is
69/// typed by a person, read from a config file or sent by an MCP client.
70pub const MAX_DEPTH: usize = 64;
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
73#[serde(rename_all = "snake_case")]
74pub enum Metric {
75    Mem,
76    Gpu,
77    Cpu,
78    Idle,
79}
80
81impl Metric {
82    pub fn as_str(self) -> &'static str {
83        match self {
84            Metric::Mem => "mem",
85            Metric::Gpu => "gpu",
86            Metric::Cpu => "cpu",
87            Metric::Idle => "idle",
88        }
89    }
90
91    /// Accepts the key and its aliases (`memory`, `footprint`, `ram`, `vram`, `metal`, …).
92    pub fn parse(s: &str) -> Option<Metric> {
93        match s.trim().to_ascii_lowercase().as_str() {
94            "mem" | "memory" | "footprint" | "ram" => Some(Metric::Mem),
95            "gpu" | "vram" | "metal" => Some(Metric::Gpu),
96            "cpu" => Some(Metric::Cpu),
97            "idle" => Some(Metric::Idle),
98            _ => None,
99        }
100    }
101
102    /// Human label for sort descriptions ("memory", "GPU memory", …).
103    pub fn label(self) -> &'static str {
104        match self {
105            Metric::Mem => "memory",
106            Metric::Gpu => "GPU memory",
107            Metric::Cpu => "CPU",
108            Metric::Idle => "idle time",
109        }
110    }
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "snake_case")]
115pub enum CmpOp {
116    Gt,
117    Ge,
118    Lt,
119    Le,
120    Eq,
121}
122
123impl CmpOp {
124    pub fn as_str(self) -> &'static str {
125        match self {
126            CmpOp::Gt => ">",
127            CmpOp::Ge => ">=",
128            CmpOp::Lt => "<",
129            CmpOp::Le => "<=",
130            CmpOp::Eq => "=",
131        }
132    }
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
136#[serde(rename_all = "snake_case")]
137pub enum FieldKey {
138    Kind,
139    Owner,
140    Name,
141    State,
142    Sandbox,
143}
144
145impl FieldKey {
146    pub fn as_str(self) -> &'static str {
147        match self {
148            FieldKey::Kind => "kind",
149            FieldKey::Owner => "owner",
150            FieldKey::Name => "name",
151            FieldKey::State => "state",
152            FieldKey::Sandbox => "sandbox",
153        }
154    }
155
156    /// Accepts the key and its aliases (`type`, `is`).
157    pub fn parse(s: &str) -> Option<FieldKey> {
158        match s.trim().to_ascii_lowercase().as_str() {
159            "kind" | "type" => Some(FieldKey::Kind),
160            "owner" => Some(FieldKey::Owner),
161            "name" => Some(FieldKey::Name),
162            "state" | "is" => Some(FieldKey::State),
163            "sandbox" => Some(FieldKey::Sandbox),
164            _ => None,
165        }
166    }
167}
168
169/// Time and staleness keys (SPEC §7 "Staleness"): comparisons `age>1d`, `duty<1%`, `rent>10`, `stale>0.5`
170/// and the sort keys of the same names. Kept apart from [`Metric`] so that exhaustive matches on `Metric`
171/// in frontends keep compiling.
172#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
173#[serde(rename_all = "snake_case")]
174pub enum TimeMetric {
175    /// Seconds since the group's root (else oldest member) started.
176    Age,
177    /// CPU time ÷ age, percent of one core.
178    Duty,
179    /// Idle rent, GiB-hours.
180    Rent,
181    /// Staleness score, 0..1.
182    Stale,
183}
184
185impl TimeMetric {
186    pub const ALL: [TimeMetric; 4] = [
187        TimeMetric::Age,
188        TimeMetric::Duty,
189        TimeMetric::Rent,
190        TimeMetric::Stale,
191    ];
192
193    pub fn as_str(self) -> &'static str {
194        match self {
195            TimeMetric::Age => "age",
196            TimeMetric::Duty => "duty",
197            TimeMetric::Rent => "rent",
198            TimeMetric::Stale => "stale",
199        }
200    }
201
202    /// Accepts the key and its aliases (`uptime`, `duty_cycle`, `idle_rent`, `staleness`).
203    pub fn parse(s: &str) -> Option<TimeMetric> {
204        match s.trim().to_ascii_lowercase().as_str() {
205            "age" | "uptime" => Some(TimeMetric::Age),
206            "duty" | "duty_cycle" => Some(TimeMetric::Duty),
207            "rent" | "idle_rent" => Some(TimeMetric::Rent),
208            "stale" | "staleness" => Some(TimeMetric::Stale),
209            _ => None,
210        }
211    }
212
213    /// Human label for sort descriptions.
214    pub fn label(self) -> &'static str {
215        match self {
216            TimeMetric::Age => "age",
217            TimeMetric::Duty => "duty cycle",
218            TimeMetric::Rent => "idle rent",
219            TimeMetric::Stale => "staleness",
220        }
221    }
222
223    /// Larger first when sorting (oldest, busiest, most rent, most stale)? `duty` sorts ascending: the
224    /// least-used first.
225    pub fn descending(self) -> bool {
226        !matches!(self, TimeMetric::Duty)
227    }
228
229    /// The group's value: `age_s`, `duty_pct`, `idle_rent_gib_h`, `staleness.score` (only once computed).
230    pub fn of_group(self, g: &Group) -> Option<f64> {
231        match self {
232            TimeMetric::Age => g.age_s.value.map(|a| a as f64),
233            TimeMetric::Duty => g.duty_pct.value,
234            TimeMetric::Rent => g.idle_rent_gib_h.value,
235            TimeMetric::Stale => (!crate::staleness::not_collected(&g.age_s)).then_some(g.staleness.score),
236        }
237    }
238}
239
240/// Sorts groups by a time metric (see [`TimeMetric::descending`]); unknown values last, then by id.
241pub fn sort_groups_by_time(groups: &mut [&Group], m: TimeMetric) {
242    groups.sort_by(|a, b| {
243        let (x, y) = (m.of_group(a), m.of_group(b));
244        let ord = match (x, y) {
245            (Some(x), Some(y)) => {
246                let o = x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal);
247                if m.descending() {
248                    o.reverse()
249                } else {
250                    o
251                }
252            }
253            (Some(_), None) => std::cmp::Ordering::Less,
254            (None, Some(_)) => std::cmp::Ordering::Greater,
255            (None, None) => std::cmp::Ordering::Equal,
256        };
257        ord.then(a.id.cmp(&b.id))
258    });
259}
260
261#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
262#[serde(rename_all = "snake_case")]
263pub enum Term {
264    Field {
265        key: FieldKey,
266        values: Vec<String>,
267    },
268    /// `value` in base units: bytes (mem/gpu), percent of one core (cpu), seconds (idle).
269    Cmp {
270        metric: Metric,
271        op: CmpOp,
272        value: f64,
273    },
274    Word(String),
275    /// `value` in base units: seconds (age), percent of one core (duty), GiB-hours (rent), 0..1 (stale).
276    TimeCmp {
277        metric: TimeMetric,
278        op: CmpOp,
279        value: f64,
280    },
281}
282
283#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
284#[serde(rename_all = "snake_case")]
285pub enum Expr {
286    And(Vec<Expr>),
287    Or(Vec<Expr>),
288    Not(Box<Expr>),
289    Term(Term),
290}
291
292/// A typo or alias fix applied while understanding a query (shown as "showing results for …").
293#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
294#[serde(default)]
295pub struct Correction {
296    pub from: String,
297    pub to: String,
298}
299
300// ---------------------------------------------------------------------------------------------------------
301// Canonical rendering (saved views, palette labels)
302// ---------------------------------------------------------------------------------------------------------
303
304fn fmt_metric_value(metric: Metric, v: f64) -> String {
305    match metric {
306        Metric::Mem | Metric::Gpu => {
307            let b = v.max(0.0).round() as u64;
308            for (unit, suffix) in [(TIB, "T"), (GIB, "G"), (MIB, "M"), (KIB, "K")] {
309                if b >= unit && b.is_multiple_of(unit) {
310                    return format!("{}{suffix}", b / unit);
311                }
312            }
313            for (unit, suffix) in [
314                (1_000_000_000_000u64, "TB"),
315                (1_000_000_000, "GB"),
316                (1_000_000, "MB"),
317                (1_000, "KB"),
318            ] {
319                if b >= unit && b.is_multiple_of(unit) {
320                    return format!("{}{suffix}", b / unit);
321                }
322            }
323            // A short decimal (`1.5G`) only when it names exactly this many bytes; else plain bytes. The
324            // canonical form must parse back to the same value (saved views are stored in it).
325            for (unit, suffix) in [(TIB, "T"), (GIB, "G"), (MIB, "M")] {
326                if b >= unit {
327                    let x = b as f64 / unit as f64;
328                    for decimals in 1..=3 {
329                        let s = format!("{x:.decimals$}");
330                        let back = s.parse::<f64>().map(|y| (y * unit as f64).round() as u64);
331                        if back == Ok(b) {
332                            let s = s.trim_end_matches('0').trim_end_matches('.');
333                            return format!("{s}{suffix}");
334                        }
335                    }
336                }
337            }
338            if b == 0 {
339                "0".into()
340            } else {
341                format!("{b}B")
342            }
343        }
344        // shortest form that parses back to the same number (`12.345`, not `12.35`)
345        Metric::Cpu => format!("{v}"),
346        Metric::Idle => {
347            let s = v.max(0.0).round() as u64;
348            for (unit, suffix) in [(86_400, "d"), (3_600, "h"), (60, "m")] {
349                if s >= unit && s.is_multiple_of(unit) {
350                    return format!("{}{suffix}", s / unit);
351                }
352            }
353            format!("{s}s")
354        }
355    }
356}
357
358/// Quotes a value or word when the tokenizer would otherwise split or reinterpret it. A bare `word` also
359/// needs quoting when it contains `:` or a comparison character (it would parse as `key:value`).
360fn quote_if_needed(v: &str, word: bool) -> String {
361    if v.is_empty()
362        || v.chars()
363            .any(|c| c.is_whitespace() || matches!(c, '(' | ')' | ',' | '"' | QUOTED_COMMA))
364        || v.starts_with(['-', '!'])
365        || (word && v.contains([':', '<', '>', '=']))
366        // a value that starts with an operator character would read as `key:>value`
367        || (!word && v.starts_with(['<', '>', '=']))
368        || ["or", "not", "and", "||", "|", "&&", "&"].contains(&v.to_ascii_lowercase().as_str())
369    {
370        format!("\"{}\"", v.replace('"', ""))
371    } else {
372        v.to_string()
373    }
374}
375
376impl fmt::Display for Term {
377    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378        match self {
379            Term::Field { key, values } => {
380                let vs: Vec<String> = values.iter().map(|v| quote_if_needed(v, false)).collect();
381                write!(f, "{}:{}", key.as_str(), vs.join(","))
382            }
383            Term::Cmp { metric, op, value } => write!(
384                f,
385                "{}{}{}",
386                metric.as_str(),
387                op.as_str(),
388                fmt_metric_value(*metric, *value)
389            ),
390            Term::Word(w) => write!(f, "{}", quote_if_needed(w, true)),
391            Term::TimeCmp { metric, op, value } => {
392                let v = match metric {
393                    TimeMetric::Age => fmt_metric_value(Metric::Idle, *value),
394                    _ => format!("{value}"),
395                };
396                write!(f, "{}{}{v}", metric.as_str(), op.as_str())
397            }
398        }
399    }
400}
401
402impl fmt::Display for Expr {
403    /// Canonical, re-parseable form: `kind:model,agent or gpu>1G -muted` round-trips.
404    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405        match self {
406            Expr::Term(t) => write!(f, "{t}"),
407            Expr::Not(x) => match x.as_ref() {
408                Expr::Term(t) => write!(f, "-{t}"),
409                other => write!(f, "-({other})"),
410            },
411            Expr::And(xs) => {
412                let parts: Vec<String> = xs
413                    .iter()
414                    .map(|x| match x {
415                        Expr::Or(_) => format!("({x})"),
416                        _ => x.to_string(),
417                    })
418                    .collect();
419                write!(f, "{}", parts.join(" "))
420            }
421            Expr::Or(xs) => {
422                let parts: Vec<String> = xs.iter().map(|x| x.to_string()).collect();
423                write!(f, "{}", parts.join(" or "))
424            }
425        }
426    }
427}
428
429impl Expr {
430    /// Metrics referenced by comparisons anywhere in the expression (deduplicated, in order).
431    pub fn metrics(&self) -> Vec<Metric> {
432        fn walk(e: &Expr, out: &mut Vec<Metric>) {
433            match e {
434                Expr::And(xs) | Expr::Or(xs) => xs.iter().for_each(|x| walk(x, out)),
435                Expr::Not(x) => walk(x, out),
436                Expr::Term(Term::Cmp { metric, .. }) => {
437                    if !out.contains(metric) {
438                        out.push(*metric);
439                    }
440                }
441                Expr::Term(_) => {}
442            }
443        }
444        let mut v = Vec::new();
445        walk(self, &mut v);
446        v
447    }
448
449    fn and_all(mut parts: Vec<Expr>) -> Option<Expr> {
450        match parts.len() {
451            0 => None,
452            1 => parts.pop(),
453            _ => Some(Expr::And(parts)),
454        }
455    }
456}
457
458// ---------------------------------------------------------------------------------------------------------
459// Tokenizer + parser
460// ---------------------------------------------------------------------------------------------------------
461
462#[derive(Debug, Clone, PartialEq)]
463enum Tok {
464    LParen,
465    RParen,
466    Or,
467    Not,
468    Neg,
469    Atom(String),
470    /// A fully quoted atom (`"a:b"`, `"Claude Code"`): always a plain word, never `key:value` or a keyword.
471    /// Quoted commas are still protected ([`QUOTED_COMMA`]) until the parser builds the term.
472    Lit(String),
473}
474
475/// Stands in for a comma inside quotes while tokenizing, so `owner:"Smith, John"` stays one value.
476const QUOTED_COMMA: char = '\u{1f}';
477/// Stand-ins for a quoted `<`, `>`, `=` at the start of a value (`name:">x"`), which would otherwise read
478/// as a comparison (`name:>x`).
479const QUOTED_OPS: [(char, char); 3] = [('<', '\u{1c}'), ('>', '\u{1d}'), ('=', '\u{1e}')];
480
481fn protect_op(c: char) -> char {
482    QUOTED_OPS
483        .iter()
484        .find(|(op, _)| *op == c)
485        .map(|(_, p)| *p)
486        .unwrap_or(c)
487}
488
489fn is_protected(c: char) -> bool {
490    c == QUOTED_COMMA || QUOTED_OPS.iter().any(|(_, p)| *p == c)
491}
492
493fn unprotect(s: &str) -> String {
494    if !s.contains(is_protected) {
495        return s.to_string();
496    }
497    s.chars()
498        .map(|c| match QUOTED_OPS.iter().find(|(_, p)| *p == c) {
499            Some((op, _)) => *op,
500            None if c == QUOTED_COMMA => ',',
501            None => c,
502        })
503        .collect()
504}
505
506fn tokenize(input: &str) -> Result<Vec<Tok>, QueryError> {
507    #[derive(Default)]
508    struct Cur {
509        text: String,
510        any_quote: bool,
511        starts_quoted: bool,
512        /// `-"…"` / `!"…"`: a negated literal.
513        neg: bool,
514    }
515    fn flush(cur: &mut Cur, toks: &mut Vec<Tok>) {
516        let Cur {
517            text,
518            any_quote,
519            starts_quoted,
520            neg,
521        } = std::mem::take(cur);
522        if text.is_empty() {
523            return;
524        }
525        if neg {
526            toks.push(Tok::Neg);
527        }
528        if starts_quoted {
529            toks.push(Tok::Lit(text));
530            return;
531        }
532        if !any_quote {
533            match text.to_ascii_lowercase().as_str() {
534                "or" | "||" | "|" => return toks.push(Tok::Or),
535                "not" | "!" => return toks.push(Tok::Not),
536                "and" | "&&" | "&" | "-" => return,
537                _ => {}
538            }
539        }
540        if let Some(rest) = text.strip_prefix(['-', '!']).filter(|r| !r.is_empty()) {
541            toks.push(Tok::Neg);
542            toks.push(Tok::Atom(rest.to_string()));
543            return;
544        }
545        toks.push(Tok::Atom(text));
546    }
547
548    let mut toks = Vec::new();
549    let mut cur = Cur::default();
550    let mut in_quote = false;
551    // inside the quoted value of `key:"…"`, before its first ordinary character
552    let mut value_lead = false;
553    for c in input.chars() {
554        if in_quote {
555            match c {
556                '"' => in_quote = false,
557                ',' => cur.text.push(QUOTED_COMMA),
558                c if is_protected(c) => {}
559                c if value_lead && is_op_char(c) => cur.text.push(protect_op(c)),
560                c => cur.text.push(c),
561            }
562            value_lead &= in_quote && is_op_char(c);
563            continue;
564        }
565        match c {
566            '"' => {
567                if cur.text.is_empty() && !cur.any_quote {
568                    cur.starts_quoted = true;
569                } else if !cur.any_quote && (cur.text == "-" || cur.text == "!") {
570                    cur.text.clear();
571                    cur.neg = true;
572                    cur.starts_quoted = true;
573                }
574                cur.any_quote = true;
575                in_quote = true;
576                value_lead = cur.text.ends_with(':');
577            }
578            '(' => {
579                if !cur.any_quote && (cur.text == "-" || cur.text == "!") {
580                    cur.text.clear();
581                    toks.push(Tok::Neg);
582                } else {
583                    flush(&mut cur, &mut toks);
584                }
585                toks.push(Tok::LParen);
586            }
587            ')' => {
588                flush(&mut cur, &mut toks);
589                toks.push(Tok::RParen);
590            }
591            c if is_protected(c) => {}
592            c if c.is_whitespace() => flush(&mut cur, &mut toks),
593            c => cur.text.push(c),
594        }
595    }
596    if in_quote {
597        return Err(QueryError::Quote);
598    }
599    flush(&mut cur, &mut toks);
600    Ok(merge_spaced_comparisons(toks))
601}
602
603fn is_known_key(s: &str) -> bool {
604    Metric::parse(s).is_some() || FieldKey::parse(s).is_some() || TimeMetric::parse(s).is_some()
605}
606
607fn is_op_char(c: char) -> bool {
608    matches!(c, '<' | '>' | '=')
609}
610
611/// Joins `mem > 2G`, `mem >2G`, `mem> 2G` and `owner: claude` into single atoms.
612fn merge_spaced_comparisons(toks: Vec<Tok>) -> Vec<Tok> {
613    let mut out: Vec<Tok> = Vec::with_capacity(toks.len());
614    for t in toks {
615        if let Some(Tok::Atom(prev)) = out.last_mut() {
616            let prev_open = prev.ends_with(is_op_char) || prev.ends_with(':');
617            match &t {
618                Tok::Atom(next) if prev_open || (is_known_key(prev) && next.starts_with(is_op_char)) => {
619                    prev.push_str(next);
620                    continue;
621                }
622                // `owner: "Claude Code"`: the quoted literal is the value (commas stay protected).
623                Tok::Lit(next) if prev_open => {
624                    // …and a leading `<`/`>`/`=` of a quoted value is text, not an operator
625                    let lead = if prev.ends_with(':') {
626                        next.find(|c| !is_op_char(c)).unwrap_or(next.len())
627                    } else {
628                        0
629                    };
630                    prev.extend(next[..lead].chars().map(protect_op));
631                    prev.push_str(&next[lead..]);
632                    continue;
633                }
634                _ => {}
635            }
636        }
637        out.push(t);
638    }
639    out
640}
641
642struct Parser<'c> {
643    toks: Vec<Tok>,
644    pos: usize,
645    /// Current nesting of parentheses and negations (bounded by [`MAX_DEPTH`]).
646    depth: usize,
647    corrections: &'c mut Vec<Correction>,
648}
649
650impl Parser<'_> {
651    fn peek(&self) -> Option<&Tok> {
652        self.toks.get(self.pos)
653    }
654    fn next(&mut self) -> Option<Tok> {
655        let t = self.toks.get(self.pos).cloned();
656        self.pos += 1;
657        t
658    }
659    fn or_expr(&mut self) -> Result<Expr, QueryError> {
660        let mut parts = vec![self.and_expr()?];
661        while self.peek() == Some(&Tok::Or) {
662            self.next();
663            parts.push(self.and_expr()?);
664        }
665        Ok(if parts.len() == 1 {
666            parts.remove(0)
667        } else {
668            Expr::Or(parts)
669        })
670    }
671    fn and_expr(&mut self) -> Result<Expr, QueryError> {
672        let mut parts = Vec::new();
673        while let Some(t) = self.peek() {
674            if matches!(t, Tok::Or | Tok::RParen) {
675                break;
676            }
677            parts.push(self.unary()?);
678        }
679        match parts.len() {
680            0 => Err(QueryError::Empty),
681            1 => Ok(parts.remove(0)),
682            _ => Ok(Expr::And(parts)),
683        }
684    }
685    fn descend(&mut self) -> Result<(), QueryError> {
686        self.depth += 1;
687        if self.depth > MAX_DEPTH {
688            return Err(QueryError::TooDeep);
689        }
690        Ok(())
691    }
692    fn unary(&mut self) -> Result<Expr, QueryError> {
693        match self.peek() {
694            Some(Tok::Not) | Some(Tok::Neg) => {
695                self.next();
696                self.descend()?;
697                let inner = self.unary()?;
698                self.depth -= 1;
699                Ok(Expr::Not(Box::new(inner)))
700            }
701            _ => self.atom(),
702        }
703    }
704    fn atom(&mut self) -> Result<Expr, QueryError> {
705        match self.next() {
706            Some(Tok::LParen) => {
707                self.descend()?;
708                let e = self.or_expr()?;
709                self.depth -= 1;
710                if self.next() != Some(Tok::RParen) {
711                    return Err(QueryError::Parens);
712                }
713                Ok(e)
714            }
715            Some(Tok::Atom(a)) => Ok(Expr::Term(parse_term_with(&a, self.corrections)?)),
716            Some(Tok::Lit(w)) => Ok(Expr::Term(Term::Word(unprotect(&w)))),
717            Some(Tok::RParen) => Err(QueryError::Parens),
718            _ => Err(QueryError::Empty),
719        }
720    }
721}
722
723/// Splits `key<op>value`. Returns `None` for plain words.
724fn split_key_op(atom: &str) -> Option<(&str, &str, &str)> {
725    let i = atom.find(|c: char| c == ':' || is_op_char(c))?;
726    let key = &atom[..i];
727    if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphabetic() || c == '_') {
728        return None;
729    }
730    let rest = &atom[i..];
731    let op_len = if let Some(after) = rest.strip_prefix(':') {
732        // `mem:>2G` style.
733        if after.starts_with(">=") || after.starts_with("<=") || after.starts_with("==") {
734            3
735        } else if after.starts_with(is_op_char) {
736            2
737        } else {
738            1
739        }
740    } else if rest.starts_with(">=") || rest.starts_with("<=") || rest.starts_with("==") {
741        2
742    } else {
743        1
744    };
745    Some((key, &rest[..op_len], &rest[op_len..]))
746}
747
748fn cmp_op(op: &str) -> Option<CmpOp> {
749    match op.trim_start_matches(':') {
750        ">" => Some(CmpOp::Gt),
751        ">=" => Some(CmpOp::Ge),
752        "<" => Some(CmpOp::Lt),
753        "<=" => Some(CmpOp::Le),
754        "=" | "==" => Some(CmpOp::Eq),
755        _ => None,
756    }
757}
758
759enum Key {
760    Metric(Metric),
761    Field(FieldKey),
762    Time(TimeMetric),
763}
764
765const CANONICAL_KEYS: &[&str] = &[
766    "kind", "owner", "name", "state", "sandbox", "mem", "memory", "gpu", "cpu", "idle", "age", "duty",
767    "rent", "stale",
768];
769
770fn resolve_key(raw: &str, corrections: &mut Vec<Correction>) -> Result<Key, QueryError> {
771    let k = raw.to_ascii_lowercase();
772    if let Some(m) = Metric::parse(&k) {
773        return Ok(Key::Metric(m));
774    }
775    if let Some(f) = FieldKey::parse(&k) {
776        return Ok(Key::Field(f));
777    }
778    if let Some(t) = TimeMetric::parse(&k) {
779        return Ok(Key::Time(t));
780    }
781    if k.chars().count() >= 3 {
782        if let Some(fixed) = closest(&k, CANONICAL_KEYS.iter().copied(), 3) {
783            corrections.push(Correction {
784                from: k.clone(),
785                to: fixed.to_string(),
786            });
787            return resolve_key(fixed, corrections);
788        }
789    }
790    Err(QueryError::UnknownKey(k))
791}
792
793/// Kind value synonyms beyond `GroupKind::parse` (plurals, `vm`, `llm`, …).
794fn kind_synonym(v: &str) -> Option<GroupKind> {
795    let v = v.trim().to_ascii_lowercase();
796    if let Some(k) = GroupKind::parse(&v) {
797        return Some(k);
798    }
799    let k = match v.as_str() {
800        "agents" | "session" | "sessions" | "agent_sessions" => GroupKind::AgentSession,
801        "apps" | "application" | "applications" => GroupKind::App,
802        "models" | "llm" | "llms" | "model_servers" => GroupKind::ModelServer,
803        "sandboxes" | "vm" | "vms" | "container" | "containers" | "microvm" | "microvms" => {
804            GroupKind::Sandbox
805        }
806        "daemons" | "build" | "builds" | "build_daemons" => GroupKind::BuildDaemon,
807        "sys" => GroupKind::System,
808        "others" => GroupKind::Other,
809        _ => return None,
810    };
811    Some(k)
812}
813
814const KIND_WORDS: &[&str] = &[
815    "agent",
816    "agents",
817    "app",
818    "apps",
819    "model",
820    "models",
821    "sandbox",
822    "sandboxes",
823    "daemon",
824    "daemons",
825    "system",
826    "other",
827    "containers",
828    "container",
829    "vms",
830];
831
832fn normalize_kind_value(v: &str, corrections: &mut Vec<Correction>) -> Option<String> {
833    if v == "*" {
834        return Some("*".into());
835    }
836    if let Some(k) = kind_synonym(v) {
837        return Some(k.alias().to_string());
838    }
839    let lower = v.to_ascii_lowercase();
840    if lower.chars().count() >= MIN_TYPO_LEN {
841        let names = GroupKind::ALL
842            .iter()
843            .flat_map(|k| [k.alias(), k.as_str()])
844            .chain(KIND_WORDS.iter().copied());
845        if let Some(fixed) = closest(&lower, names, MIN_TYPO_LEN) {
846            corrections.push(Correction {
847                from: lower.clone(),
848                to: fixed.to_string(),
849            });
850            return kind_synonym(fixed).map(|k| k.alias().to_string());
851        }
852    }
853    None
854}
855
856fn normalize_state_value(v: &str) -> String {
857    let v = v.trim().to_ascii_lowercase();
858    match v.as_str() {
859        "orphaned" | "orphans" => "orphan".into(),
860        "working" | "generating" | "running" => "busy".into(),
861        "lower_bound" | "lowerbound" => "partial".into(),
862        "mine" | "pin" => "pinned".into(),
863        "mute" => "muted".into(),
864        _ => v,
865    }
866}
867
868fn parse_metric_value(metric: Metric, key: &str, v: &str) -> Result<f64, QueryError> {
869    let bad = |msg: String| QueryError::BadValue {
870        key: key.into(),
871        value: v.into(),
872        msg,
873    };
874    let v = v.trim();
875    if v.is_empty() {
876        return Err(bad("missing value".into()));
877    }
878    match metric {
879        Metric::Mem | Metric::Gpu => {
880            let has_unit = v.chars().any(|c| c.is_ascii_alphabetic());
881            let b = parse_bytes(v).map_err(|e| bad(e.to_string()))?;
882            if !has_unit && b != 0 {
883                return Err(bad("add a unit, e.g. 2G or 500M".into()));
884            }
885            Ok(b as f64)
886        }
887        Metric::Cpu => {
888            let x = v
889                .trim_end_matches('%')
890                .parse::<f64>()
891                .map_err(|e| bad(e.to_string()))?;
892            if !x.is_finite() || x < 0.0 {
893                return Err(bad("expected a non-negative percentage".into()));
894            }
895            Ok(x)
896        }
897        Metric::Idle => parse_duration_s(v).map_err(|e| bad(e.to_string())),
898    }
899}
900
901fn parse_time_value(metric: TimeMetric, key: &str, v: &str) -> Result<f64, QueryError> {
902    let bad = |msg: &str| QueryError::BadValue {
903        key: key.into(),
904        value: v.into(),
905        msg: msg.into(),
906    };
907    let v = v.trim();
908    if v.is_empty() {
909        return Err(bad("missing value"));
910    }
911    let x = match metric {
912        TimeMetric::Age => return parse_duration_s(v).map_err(|e| bad(&e.to_string())),
913        TimeMetric::Duty => v.trim_end_matches('%').trim().parse::<f64>().ok(),
914        TimeMetric::Rent => {
915            let lower = v.to_ascii_lowercase();
916            let num = ["gib·h", "gib-h", "gibh", "gb·h", "gbh", "gh"]
917                .iter()
918                .find_map(|s| lower.strip_suffix(s))
919                .unwrap_or(&lower);
920            num.trim().parse::<f64>().ok()
921        }
922        TimeMetric::Stale => match v.strip_suffix('%') {
923            Some(p) => p.trim().parse::<f64>().ok().map(|x| x / 100.0),
924            None => v.parse::<f64>().ok(),
925        },
926    };
927    let x = x.filter(|x| x.is_finite() && *x >= 0.0).ok_or_else(|| {
928        bad(match metric {
929            TimeMetric::Duty => "expected a percentage of one core, e.g. 1%",
930            TimeMetric::Rent => "expected GiB-hours, e.g. 10",
931            _ => "expected a score from 0 to 1, e.g. 0.5",
932        })
933    })?;
934    if metric == TimeMetric::Stale && x > 1.0 {
935        return Err(bad("expected a score from 0 to 1, e.g. 0.5"));
936    }
937    Ok(x)
938}
939
940fn parse_term_with(atom: &str, corrections: &mut Vec<Correction>) -> Result<Term, QueryError> {
941    let Some((raw_key, op, value)) = split_key_op(atom) else {
942        return Ok(Term::Word(unprotect(atom)));
943    };
944    let key = resolve_key(raw_key, corrections)?;
945    let key_name = raw_key.to_ascii_lowercase();
946    let is_colon = op == ":";
947    match key {
948        Key::Time(metric) => {
949            let op = (!is_colon)
950                .then(|| cmp_op(op))
951                .flatten()
952                .ok_or_else(|| QueryError::BadValue {
953                    key: key_name.clone(),
954                    value: value.into(),
955                    msg: format!(
956                        "use a comparison, e.g. {}",
957                        match metric {
958                            TimeMetric::Age => "age>1d",
959                            TimeMetric::Duty => "duty<1%",
960                            TimeMetric::Rent => "rent>10",
961                            TimeMetric::Stale => "stale>0.5 (or the word `stale`)",
962                        }
963                    ),
964                })?;
965            Ok(Term::TimeCmp {
966                metric,
967                op,
968                value: parse_time_value(metric, &key_name, value)?,
969            })
970        }
971        Key::Metric(metric) => {
972            if is_colon {
973                return Err(QueryError::BadValue {
974                    key: key_name,
975                    value: value.into(),
976                    msg: format!("use a comparison, e.g. {}>2G", metric.as_str()),
977                });
978            }
979            let op = cmp_op(op).ok_or_else(|| QueryError::BadValue {
980                key: key_name.clone(),
981                value: value.into(),
982                msg: "unknown operator".into(),
983            })?;
984            Ok(Term::Cmp {
985                metric,
986                op,
987                value: parse_metric_value(metric, &key_name, value)?,
988            })
989        }
990        Key::Field(fk) => {
991            if !(is_colon || op == "=" || op == "==") {
992                return Err(QueryError::BadValue {
993                    key: key_name,
994                    value: value.into(),
995                    msg: "comparisons need mem, gpu, cpu, idle, age, duty, rent or stale".into(),
996                });
997            }
998            let raw_values: Vec<&str> = value
999                .split(',')
1000                .map(str::trim)
1001                .filter(|s| !s.is_empty())
1002                .collect();
1003            if raw_values.is_empty() {
1004                return Err(QueryError::BadValue {
1005                    key: key_name,
1006                    value: value.into(),
1007                    msg: "missing value".into(),
1008                });
1009            }
1010            let mut values = Vec::with_capacity(raw_values.len());
1011            for val in raw_values {
1012                let val = unprotect(val);
1013                let val = val.as_str();
1014                let v = match fk {
1015                    FieldKey::Kind => {
1016                        normalize_kind_value(val, corrections).ok_or_else(|| QueryError::BadValue {
1017                            key: key_name.clone(),
1018                            value: val.into(),
1019                            msg: "unknown kind (agent, app, model, sandbox, daemon, system, other)".into(),
1020                        })?
1021                    }
1022                    FieldKey::State => normalize_state_value(val),
1023                    _ => val.to_string(),
1024                };
1025                if !values.contains(&v) {
1026                    values.push(v);
1027                }
1028            }
1029            Ok(Term::Field { key: fk, values })
1030        }
1031    }
1032}
1033
1034/// Parses one atom into a term (`kind:model,agent`, `mem>2G`, `claude`).
1035pub fn parse_term(atom: &str) -> Result<Term, QueryError> {
1036    parse_term_with(atom, &mut Vec::new())
1037}
1038
1039fn parse_tokens(toks: Vec<Tok>, corrections: &mut Vec<Correction>) -> Result<Expr, QueryError> {
1040    if toks.is_empty() {
1041        return Err(QueryError::Empty);
1042    }
1043    let mut p = Parser {
1044        toks,
1045        pos: 0,
1046        depth: 0,
1047        corrections,
1048    };
1049    let e = p.or_expr()?;
1050    if p.pos < p.toks.len() {
1051        return Err(QueryError::Parens);
1052    }
1053    Ok(e)
1054}
1055
1056/// Parses a filter expression (grammar in the module docs).
1057pub fn parse_filter(input: &str) -> Result<Expr, QueryError> {
1058    parse_tokens(tokenize(input)?, &mut Vec::new())
1059}
1060
1061/// Like [`parse_filter`], also returning the key/kind typo corrections that were applied.
1062pub fn parse_filter_corrected(input: &str) -> Result<(Expr, Vec<Correction>), QueryError> {
1063    let mut c = Vec::new();
1064    let e = parse_tokens(tokenize(input)?, &mut c)?;
1065    Ok((e, c))
1066}
1067
1068// ---------------------------------------------------------------------------------------------------------
1069// Evaluation
1070// ---------------------------------------------------------------------------------------------------------
1071
1072/// Prefix of the state flag that carries a sandbox runtime (`runtime:docker`), matched by `sandbox:`.
1073pub const RUNTIME_FLAG_PREFIX: &str = "runtime:";
1074/// Prefix of the state entries that carry time metric values (`time:age=3600`), see
1075/// [`EntityView::time_value`]. Never matched by `state:` or bare words.
1076pub const TIME_FLAG_PREFIX: &str = "time:";
1077
1078/// Flattened view of an entity for filter evaluation.
1079#[derive(Debug, Clone, PartialEq, Default)]
1080pub struct EntityView {
1081    pub id: String,
1082    pub kind: GroupKind,
1083    pub name: String,
1084    pub aliases: Vec<String>,
1085    pub owner: Option<String>,
1086    pub mem: Option<u64>,
1087    pub gpu: Option<u64>,
1088    pub cpu: Option<f64>,
1089    pub idle_s: Option<u64>,
1090    /// Flags such as "idle", "orphan", "muted", "pinned", "protected", "reclaimable", "busy", "self",
1091    /// "partial" (footprint is a lower bound), and `runtime:<name>` for sandboxes.
1092    pub state: Vec<String>,
1093    pub sandbox: Option<String>,
1094}
1095
1096impl EntityView {
1097    pub fn from_group(g: &Group, s: &Snapshot) -> Self {
1098        let mut state = Vec::new();
1099        let mut flag = |cond: bool, name: &str| {
1100            if cond {
1101                state.push(name.to_string());
1102            }
1103        };
1104        flag(g.idle, "idle");
1105        flag(g.orphan, "orphan");
1106        flag(g.protected, "protected");
1107        flag(g.is_self, "self");
1108        flag(g.lower_bound, "partial");
1109        flag(is_reclaim_candidate(g), "reclaimable");
1110        let busy = s
1111            .model_servers
1112            .iter()
1113            .any(|m| m.group_id.as_deref() == Some(g.id.as_str()) && m.busy.value == Some(true));
1114        flag(busy, "busy");
1115
1116        let sandbox_rec = s.sandboxes.iter().find(|sb| {
1117            g.root.map(|r| sb.host_pids.contains(&r)).unwrap_or(false)
1118                || sb.host_pids.iter().any(|p| g.members.iter().any(|m| m.id == *p))
1119        });
1120        if let Some(rt) = sandbox_rec.map(|sb| sb.runtime.trim()).filter(|r| !r.is_empty()) {
1121            state.push(format!("{RUNTIME_FLAG_PREFIX}{}", rt.to_lowercase()));
1122        }
1123        let owner_id = g
1124            .owner_group
1125            .clone()
1126            .or_else(|| sandbox_rec.and_then(|sb| sb.started_by_group.clone()));
1127        let owner = owner_id
1128            .as_deref()
1129            .and_then(|o| s.group(o))
1130            .map(|o| o.label.clone());
1131        let is_sandbox = g.kind == GroupKind::Sandbox || sandbox_rec.is_some();
1132        let sandbox = is_sandbox.then(|| {
1133            sandbox_rec
1134                .map(|sb| sb.label.clone())
1135                .unwrap_or_else(|| g.label.clone())
1136        });
1137        // Time and staleness (SPEC §7): the `stale` flag and the values `age`/`duty`/`rent`/`stale` compare.
1138        if g.staleness.stale {
1139            state.push("stale".into());
1140        }
1141        for m in TimeMetric::ALL {
1142            if let Some(x) = m.of_group(g) {
1143                state.push(format!("{TIME_FLAG_PREFIX}{}={x}", m.as_str()));
1144            }
1145        }
1146        EntityView {
1147            id: g.id.clone(),
1148            kind: g.kind,
1149            name: g.label.clone(),
1150            aliases: Vec::new(),
1151            owner,
1152            mem: g.totals.footprint.value,
1153            gpu: g.totals.gpu.value,
1154            cpu: g.totals.cpu_pct.value,
1155            idle_s: g.idle_for_s,
1156            state,
1157            sandbox,
1158        }
1159    }
1160
1161    /// Value of a time metric, carried as a `time:<key>=<value>` entry in `state` (like the sandbox
1162    /// runtime; this keeps `EntityView`'s fields unchanged for frontends that build views by hand). `None`
1163    /// when unknown: comparisons then never match.
1164    pub fn time_value(&self, m: TimeMetric) -> Option<f64> {
1165        let key = m.as_str();
1166        self.state.iter().find_map(|s| {
1167            s.strip_prefix(TIME_FLAG_PREFIX)?
1168                .strip_prefix(key)?
1169                .strip_prefix('=')?
1170                .parse::<f64>()
1171                .ok()
1172        })
1173    }
1174
1175    /// Sets (or clears, with `None`) a time metric value (process views built by hand).
1176    pub fn set_time_value(&mut self, m: TimeMetric, v: Option<f64>) {
1177        let prefix = format!("{TIME_FLAG_PREFIX}{}=", m.as_str());
1178        self.state.retain(|s| !s.starts_with(&prefix));
1179        if let Some(v) = v.filter(|v| v.is_finite()) {
1180            self.state.push(format!("{prefix}{v}"));
1181        }
1182    }
1183
1184    /// Sandbox runtime carried as a `runtime:<name>` flag, if any.
1185    pub fn sandbox_runtime(&self) -> Option<&str> {
1186        self.state
1187            .iter()
1188            .find_map(|s| s.strip_prefix(RUNTIME_FLAG_PREFIX))
1189    }
1190
1191    /// Adds a profile flag (`pinned`, `muted`, …) once.
1192    pub fn add_state(&mut self, flag: &str) {
1193        let f = flag.to_ascii_lowercase();
1194        if !self.state.contains(&f) {
1195            self.state.push(f);
1196        }
1197    }
1198
1199    /// Adds a user rename/alias usable in queries.
1200    pub fn add_alias(&mut self, alias: &str) {
1201        if !alias.is_empty() && !self.aliases.iter().any(|a| a == alias) {
1202            self.aliases.push(alias.to_string());
1203        }
1204    }
1205}
1206
1207fn contains_ci(hay: &str, needle: &str) -> bool {
1208    hay.to_lowercase().contains(&needle.to_lowercase())
1209}
1210
1211/// Case-insensitive match: substring when `pat` has no `*`, anchored glob otherwise.
1212fn text_match(text: &str, pat: &str) -> bool {
1213    if !pat.contains('*') {
1214        return contains_ci(text, pat);
1215    }
1216    let t: Vec<char> = text.to_lowercase().chars().collect();
1217    let p: Vec<char> = pat.to_lowercase().chars().collect();
1218    // Iterative glob with backtracking on the last '*'.
1219    let (mut ti, mut pi) = (0usize, 0usize);
1220    let mut star: Option<(usize, usize)> = None;
1221    while ti < t.len() {
1222        if pi < p.len() && p[pi] != '*' && p[pi] == t[ti] {
1223            ti += 1;
1224            pi += 1;
1225        } else if pi < p.len() && p[pi] == '*' {
1226            star = Some((pi, ti));
1227            pi += 1;
1228        } else if let Some((sp, st)) = star {
1229            pi = sp + 1;
1230            ti = st + 1;
1231            star = Some((sp, st + 1));
1232        } else {
1233            return false;
1234        }
1235    }
1236    p[pi..].iter().all(|c| *c == '*')
1237}
1238
1239fn cmp(op: CmpOp, a: f64, b: f64) -> bool {
1240    match op {
1241        CmpOp::Gt => a > b,
1242        CmpOp::Ge => a >= b,
1243        CmpOp::Lt => a < b,
1244        CmpOp::Le => a <= b,
1245        CmpOp::Eq => (a - b).abs() <= f64::EPSILON.max(b.abs() * 1e-9),
1246    }
1247}
1248
1249fn name_match(v: &EntityView, pat: &str) -> bool {
1250    text_match(&v.name, pat) || v.aliases.iter().any(|a| text_match(a, pat))
1251}
1252
1253/// Evaluates a filter against an entity. Unavailable metrics never satisfy a comparison (they are unknown,
1254/// not zero).
1255pub fn eval(e: &Expr, v: &EntityView) -> bool {
1256    match e {
1257        Expr::And(xs) => xs.iter().all(|x| eval(x, v)),
1258        Expr::Or(xs) => xs.iter().any(|x| eval(x, v)),
1259        Expr::Not(x) => !eval(x, v),
1260        Expr::Term(t) => match t {
1261            Term::Field { key, values } => values.iter().any(|val| match key {
1262                FieldKey::Kind => val == "*" || kind_synonym(val) == Some(v.kind),
1263                FieldKey::Owner => match v.owner.as_deref() {
1264                    Some(o) => val == "*" || text_match(o, val),
1265                    None => false,
1266                },
1267                FieldKey::Name => val == "*" || name_match(v, val),
1268                FieldKey::State if val.contains('*') => v
1269                    .state
1270                    .iter()
1271                    .filter(|s| !s.starts_with(TIME_FLAG_PREFIX))
1272                    .any(|s| text_match(s, val)),
1273                FieldKey::State => v
1274                    .state
1275                    .iter()
1276                    .filter(|s| !s.starts_with(TIME_FLAG_PREFIX))
1277                    .any(|s| s.eq_ignore_ascii_case(val)),
1278                FieldKey::Sandbox => match v.sandbox.as_deref() {
1279                    Some(sb) => {
1280                        val == "*"
1281                            || text_match(sb, val)
1282                            || v.sandbox_runtime().map(|r| text_match(r, val)).unwrap_or(false)
1283                    }
1284                    None => false,
1285                },
1286            }),
1287            Term::Cmp { metric, op, value } => {
1288                let x = match metric {
1289                    Metric::Mem => v.mem.map(|b| b as f64),
1290                    Metric::Gpu => v.gpu.map(|b| b as f64),
1291                    Metric::Cpu => v.cpu,
1292                    Metric::Idle => v.idle_s.map(|s| s as f64),
1293                };
1294                x.map(|x| cmp(*op, x, *value)).unwrap_or(false)
1295            }
1296            Term::TimeCmp { metric, op, value } => v
1297                .time_value(*metric)
1298                .map(|x| cmp(*op, x, *value))
1299                .unwrap_or(false),
1300            Term::Word(w) => {
1301                v.state.iter().any(|s| s.eq_ignore_ascii_case(w))
1302                    || name_match(v, w)
1303                    || v.owner.as_deref().map(|o| text_match(o, w)).unwrap_or(false)
1304                    || kind_synonym(w) == Some(v.kind)
1305            }
1306        },
1307    }
1308}
1309
1310// ---------------------------------------------------------------------------------------------------------
1311// Understanding plain words
1312// ---------------------------------------------------------------------------------------------------------
1313
1314#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1315#[serde(rename_all = "snake_case")]
1316pub enum View {
1317    Home,
1318    Processes,
1319    Models,
1320    Sandboxes,
1321    Reclaim,
1322    Timeline,
1323}
1324
1325impl View {
1326    pub fn as_str(self) -> &'static str {
1327        match self {
1328            View::Home => "home",
1329            View::Processes => "processes",
1330            View::Models => "models",
1331            View::Sandboxes => "sandboxes",
1332            View::Reclaim => "reclaim",
1333            View::Timeline => "timeline",
1334        }
1335    }
1336
1337    pub fn parse(s: &str) -> Option<View> {
1338        nav_word(&s.trim().to_ascii_lowercase())
1339    }
1340}
1341
1342#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1343#[serde(rename_all = "snake_case")]
1344pub enum Intent {
1345    Find,
1346    RankBy(Metric),
1347    Explain,
1348    Headroom,
1349    Reclaim,
1350    Navigate(View),
1351}
1352
1353impl Intent {
1354    /// Short human label for palette choices.
1355    pub fn label(&self) -> String {
1356        match self {
1357            Intent::Find => "find".into(),
1358            Intent::RankBy(m) => format!("rank by {}", m.label()),
1359            Intent::Explain => "explain slowdown".into(),
1360            Intent::Headroom => "check headroom".into(),
1361            Intent::Reclaim => "reclaim memory".into(),
1362            Intent::Navigate(v) => format!("open {}", v.as_str()),
1363        }
1364    }
1365}
1366
1367#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1368pub struct Command {
1369    pub name: String,
1370    pub args: Vec<String>,
1371}
1372
1373/// Something the user can name: a group/entity with display name, aliases/renames and frecency.
1374/// Ids starting with [`PROCESS_ID_PREFIX`] are single processes (they rank slightly below groups).
1375#[derive(Debug, Clone, PartialEq, Default)]
1376pub struct VocabEntity {
1377    pub id: String,
1378    pub name: String,
1379    pub aliases: Vec<String>,
1380    /// Raw frecency score (UX §5.1), not normalized. Pinned entities carry [`PINNED_FRECENCY_BONUS`].
1381    pub frecency: f64,
1382    /// Cold-start prior from the machine profile (UX §5.4: agent CLIs and model servers detected on this
1383    /// machine), used only while the entity has no frecency — so with no history "cl" means the detected
1384    /// Claude Code session, not an unrelated `clang`. See [`crate::ranking::ColdStartPriors`].
1385    pub prior: f64,
1386}
1387
1388/// Id prefix of process (not group) entities.
1389pub const PROCESS_ID_PREFIX: &str = "pid:";
1390/// Frecency added to pinned entities by [`Vocabulary::from_snapshot`].
1391pub const PINNED_FRECENCY_BONUS: f64 = 3.0;
1392
1393#[derive(Debug, Clone, PartialEq, Default)]
1394pub struct Vocabulary {
1395    pub entities: Vec<VocabEntity>,
1396}
1397
1398/// Maximum number of process entities added by [`Vocabulary::from_snapshot`].
1399pub const VOCAB_MAX_PROCESSES: usize = 200;
1400/// Maximum member-process names added as aliases of one group.
1401pub const VOCAB_MAX_MEMBER_ALIASES: usize = 8;
1402
1403impl Vocabulary {
1404    /// Builds a vocabulary from a snapshot plus the profile (frecency / renames / pins keyed by fingerprint).
1405    /// Every group is an entity; its user rename and the distinct names of its member processes (e.g. the
1406    /// `claude` binary inside "Claude Code", at most [`VOCAB_MAX_MEMBER_ALIASES`]) are aliases, so typing a
1407    /// process name finds its group. Processes outside any group are added as `pid:<n>` entities (largest
1408    /// first, capped at [`VOCAB_MAX_PROCESSES`]).
1409    pub fn from_snapshot(
1410        s: &Snapshot,
1411        frecency_by_fp: &HashMap<String, f64>,
1412        renames_by_fp: &HashMap<String, String>,
1413        pinned_fps: &HashSet<String>,
1414    ) -> Vocabulary {
1415        let mut grouped: HashSet<crate::model::ProcId> = HashSet::new();
1416        let mut entities: Vec<VocabEntity> = Vec::with_capacity(s.groups.len());
1417        let priors = crate::ranking::ColdStartPriors::detect(s);
1418        for g in &s.groups {
1419            let mut aliases: Vec<String> = renames_by_fp.get(&g.fingerprint).cloned().into_iter().collect();
1420            let label = g.label.to_lowercase();
1421            for m in &g.members {
1422                grouped.insert(m.id);
1423                if aliases.len() >= VOCAB_MAX_MEMBER_ALIASES {
1424                    continue;
1425                }
1426                if let Some(p) = s.process(m.id) {
1427                    let n = p.name.trim();
1428                    if !n.is_empty()
1429                        && n.to_lowercase() != label
1430                        && !aliases.iter().any(|a| a.eq_ignore_ascii_case(n))
1431                    {
1432                        aliases.push(n.to_string());
1433                    }
1434                }
1435            }
1436            entities.push(VocabEntity {
1437                id: g.id.clone(),
1438                name: g.label.clone(),
1439                aliases,
1440                prior: priors.map(|p| p.for_kind(g.kind)).unwrap_or(0.0),
1441                frecency: frecency_by_fp
1442                    .get(&g.fingerprint)
1443                    .copied()
1444                    .unwrap_or(0.0)
1445                    .max(0.0)
1446                    + if pinned_fps.contains(&g.fingerprint) {
1447                        PINNED_FRECENCY_BONUS
1448                    } else {
1449                        0.0
1450                    },
1451            });
1452        }
1453        let mut procs: Vec<&crate::model::Process> = s
1454            .processes
1455            .iter()
1456            .filter(|p| !p.name.is_empty() && !grouped.contains(&p.id))
1457            .collect();
1458        procs.sort_by(|a, b| {
1459            b.mem
1460                .footprint_or_pss
1461                .value
1462                .unwrap_or(0)
1463                .cmp(&a.mem.footprint_or_pss.value.unwrap_or(0))
1464                .then(a.id.pid.cmp(&b.id.pid))
1465        });
1466        let mut seen: HashSet<String> = HashSet::new();
1467        let mut added = 0;
1468        for p in procs {
1469            if added >= VOCAB_MAX_PROCESSES {
1470                break;
1471            }
1472            if !seen.insert(p.name.to_lowercase()) {
1473                continue;
1474            }
1475            added += 1;
1476            entities.push(VocabEntity {
1477                id: format!("{PROCESS_ID_PREFIX}{}", p.id.pid),
1478                name: p.name.clone(),
1479                ..Default::default()
1480            });
1481        }
1482        Vocabulary { entities }
1483    }
1484
1485    /// Lowercased name tokens of every entity (used so typo correction never "fixes" a real name).
1486    fn tokens(&self) -> HashSet<String> {
1487        let mut out = HashSet::new();
1488        for e in &self.entities {
1489            for n in std::iter::once(&e.name).chain(e.aliases.iter()) {
1490                out.extend(name_tokens(n));
1491            }
1492        }
1493        out
1494    }
1495}
1496
1497/// Lowercased tokens of a display name: words split on punctuation/space, plus the camelCase humps of each
1498/// word (`GradleDaemon` → `gradledaemon`, `gradle`, `daemon`), so typos and prefixes can hit a hump.
1499pub fn name_tokens(name: &str) -> Vec<String> {
1500    let mut out: Vec<String> = Vec::new();
1501    let mut push = |t: String| {
1502        if !t.is_empty() && !out.contains(&t) {
1503            out.push(t);
1504        }
1505    };
1506    for word in name
1507        .split(|c: char| !c.is_alphanumeric())
1508        .filter(|w| !w.is_empty())
1509    {
1510        push(word.to_lowercase());
1511        let chars: Vec<char> = word.chars().collect();
1512        let mut start = 0;
1513        for i in 1..chars.len() {
1514            let hump = chars[i - 1].is_lowercase() && chars[i].is_uppercase();
1515            // `HTTPServer` → `http`, `server`.
1516            let acronym_end = chars[i - 1].is_uppercase()
1517                && chars[i].is_uppercase()
1518                && chars.get(i + 1).is_some_and(|c| c.is_lowercase());
1519            if hump || acronym_end {
1520                push(chars[start..i].iter().collect::<String>().to_lowercase());
1521                start = i;
1522            }
1523        }
1524        if start > 0 {
1525            push(chars[start..].iter().collect::<String>().to_lowercase());
1526        }
1527    }
1528    out
1529}
1530
1531/// One way to read an ambiguous input (the palette offers the top 3).
1532#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1533pub struct Interpretation {
1534    pub intent: Intent,
1535    #[serde(default)]
1536    pub filter: Option<Expr>,
1537    #[serde(default)]
1538    pub sort: Option<Metric>,
1539    #[serde(default)]
1540    pub targets: Vec<(String, f64)>,
1541    #[serde(default)]
1542    pub need_bytes: Option<u64>,
1543    /// Human label, e.g. "rank by memory", "go to Claude Code", "filter kind:model".
1544    pub label: String,
1545    /// 0..1.
1546    pub score: f64,
1547}
1548
1549#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1550pub struct Understanding {
1551    pub intent: Intent,
1552    pub filter: Option<Expr>,
1553    pub sort: Option<Metric>,
1554    /// Linked entity ids with scores, best first.
1555    pub targets: Vec<(String, f64)>,
1556    pub need_bytes: Option<u64>,
1557    pub command: Option<Command>,
1558    /// 0..1; below [`LOW_CONFIDENCE`] the palette shows `interpretations` instead of guessing.
1559    pub confidence: f64,
1560    /// Intents of the runner-up interpretations when confidence is low (kept for older consumers).
1561    pub alternatives: Vec<Intent>,
1562    /// Top-3 interpretations, best first (always filled when anything was understood).
1563    #[serde(default)]
1564    pub interpretations: Vec<Interpretation>,
1565    /// Typo/alias fixes applied ("showing results for …").
1566    #[serde(default)]
1567    pub corrections: Vec<Correction>,
1568    /// The normalized input (lowercase, units joined, typos fixed).
1569    #[serde(default)]
1570    pub normalized: String,
1571    /// Filter syntax error, if the input looked structured but did not parse.
1572    #[serde(default)]
1573    pub error: Option<String>,
1574    /// `:sort age|duty|rent|stale`: a time sort key (then `sort` is `None`); see [`sort_groups_by_time`].
1575    #[serde(default)]
1576    pub sort_time: Option<TimeMetric>,
1577}
1578
1579impl Understanding {
1580    fn empty() -> Self {
1581        Understanding {
1582            intent: Intent::Find,
1583            filter: None,
1584            sort: None,
1585            targets: Vec::new(),
1586            need_bytes: None,
1587            command: None,
1588            confidence: 0.0,
1589            alternatives: Vec::new(),
1590            interpretations: Vec::new(),
1591            corrections: Vec::new(),
1592            normalized: String::new(),
1593            error: None,
1594            sort_time: None,
1595        }
1596    }
1597
1598    /// True when the palette should offer choices instead of acting.
1599    pub fn is_ambiguous(&self) -> bool {
1600        self.confidence < LOW_CONFIDENCE
1601    }
1602
1603    /// Best linked entity id, if any.
1604    pub fn top_target(&self) -> Option<&str> {
1605        self.targets.first().map(|(id, _)| id.as_str())
1606    }
1607}
1608
1609const STOPWORDS: &[&str] = &[
1610    "what",
1611    "whats",
1612    "is",
1613    "the",
1614    "my",
1615    "me",
1616    "are",
1617    "i",
1618    "im",
1619    "can",
1620    "could",
1621    "show",
1622    "all",
1623    "a",
1624    "an",
1625    "of",
1626    "up",
1627    "to",
1628    "now",
1629    "stuff",
1630    "things",
1631    "who",
1632    "whos",
1633    "which",
1634    "please",
1635    "it",
1636    "its",
1637    "this",
1638    "that",
1639    "for",
1640    "on",
1641    "in",
1642    "any",
1643    "much",
1644    "how",
1645    "do",
1646    "does",
1647    "anything",
1648    "something",
1649    "list",
1650    "give",
1651    "tell",
1652    "get",
1653    "with",
1654    "there",
1655    "so",
1656    "be",
1657    "being",
1658    "am",
1659    "and",
1660    "or",
1661    "by",
1662    "from",
1663    "at",
1664    "if",
1665    "right",
1666    "currently",
1667    "most",
1668    "some",
1669    "lot",
1670    "lots",
1671    "again",
1672    "really",
1673    "very",
1674    "you",
1675    "your",
1676    "we",
1677    "our",
1678    "go",
1679    "open",
1680];
1681const RANK_WORDS: &[&str] = &[
1682    "hog",
1683    "hogs",
1684    "hogging",
1685    "eating",
1686    "eats",
1687    "eat",
1688    "using",
1689    "uses",
1690    "use",
1691    "biggest",
1692    "largest",
1693    "big",
1694    "heavy",
1695    "heaviest",
1696    "top",
1697    "consumers",
1698    "consuming",
1699    "hungry",
1700    "greedy",
1701    "usage",
1702];
1703const MEM_WORDS: &[&str] = &["memory", "mem", "ram", "footprint"];
1704const GPU_WORDS: &[&str] = &["gpu", "vram", "metal"];
1705const CPU_WORDS: &[&str] = &["cpu", "processor", "cores"];
1706const EXPLAIN_STRONG: &[&str] = &[
1707    "slow",
1708    "slowly",
1709    "slowness",
1710    "lag",
1711    "laggy",
1712    "lagging",
1713    "throttle",
1714    "throttling",
1715    "throttled",
1716    "sluggish",
1717    "slowdown",
1718    "stutter",
1719    "stuttering",
1720    "freeze",
1721    "freezing",
1722    "frozen",
1723];
1724const EXPLAIN_WEAK: &[&str] = &["why", "hot", "heat", "fan", "thermal", "explain"];
1725const HEADROOM_VERBS: &[&str] = &["load", "fit", "fits", "run", "start", "launch"];
1726const HEADROOM_NOUNS: &[&str] = &["headroom", "room", "space", "enough", "available"];
1727const RECLAIM_STRONG: &[&str] = &[
1728    "reclaim",
1729    "reclaimable",
1730    "leftovers",
1731    "leftover",
1732    "orphans",
1733    "orphan",
1734    "orphaned",
1735    "cleanup",
1736    "clean",
1737];
1738const RECLAIM_WEAK: &[&str] = &["idle", "unused", "free", "kill", "stop"];
1739
1740fn nav_word(w: &str) -> Option<View> {
1741    match w {
1742        "models" | "model" => Some(View::Models),
1743        "sandboxes" | "sandbox" | "vms" | "vm" | "containers" | "container" => Some(View::Sandboxes),
1744        "processes" | "procs" | "process" => Some(View::Processes),
1745        "timeline" | "history" => Some(View::Timeline),
1746        "home" | "groups" => Some(View::Home),
1747        _ => None,
1748    }
1749}
1750
1751const NAV_WORDS: &[&str] = &[
1752    "models",
1753    "sandboxes",
1754    "processes",
1755    "procs",
1756    "timeline",
1757    "history",
1758    "home",
1759    "groups",
1760];
1761
1762fn lexicon() -> impl Iterator<Item = &'static str> {
1763    RANK_WORDS
1764        .iter()
1765        .chain(MEM_WORDS)
1766        .chain(GPU_WORDS)
1767        .chain(CPU_WORDS)
1768        .chain(EXPLAIN_STRONG)
1769        .chain(EXPLAIN_WEAK)
1770        .chain(HEADROOM_VERBS)
1771        .chain(HEADROOM_NOUNS)
1772        .chain(RECLAIM_STRONG)
1773        .chain(RECLAIM_WEAK)
1774        .chain(NAV_WORDS)
1775        .chain(KIND_WORDS)
1776        .copied()
1777}
1778
1779fn in_lexicon(w: &str) -> bool {
1780    lexicon().any(|l| l == w)
1781}
1782
1783/// Optimal-string-alignment Damerau-Levenshtein distance (adjacent transpositions count as one edit).
1784pub fn damerau_levenshtein(a: &str, b: &str) -> usize {
1785    let a: Vec<char> = a.chars().collect();
1786    let b: Vec<char> = b.chars().collect();
1787    let (n, m) = (a.len(), b.len());
1788    if n == 0 {
1789        return m;
1790    }
1791    if m == 0 {
1792        return n;
1793    }
1794    // Three rolling rows: i-2, i-1, i.
1795    let mut prev2: Vec<usize> = vec![0; m + 1];
1796    let mut prev: Vec<usize> = (0..=m).collect();
1797    let mut cur: Vec<usize> = vec![0; m + 1];
1798    for i in 1..=n {
1799        cur[0] = i;
1800        for j in 1..=m {
1801            let cost = usize::from(a[i - 1] != b[j - 1]);
1802            let mut d = (prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost);
1803            if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
1804                d = d.min(prev2[j - 2] + 1);
1805            }
1806            cur[j] = d;
1807        }
1808        std::mem::swap(&mut prev2, &mut prev);
1809        std::mem::swap(&mut prev, &mut cur);
1810    }
1811    prev[m]
1812}
1813
1814/// Closest candidate within distance 1 (min length `min_len`); ties broken by length difference, then
1815/// alphabetically, so the result is deterministic.
1816fn closest<'a>(w: &str, candidates: impl Iterator<Item = &'a str>, min_len: usize) -> Option<&'a str> {
1817    let wl = w.chars().count();
1818    candidates
1819        .filter(|c| c.chars().count() >= min_len && *c != w)
1820        .filter(|c| damerau_levenshtein(c, w) <= 1)
1821        .min_by(|a, b| {
1822            let da = (a.chars().count() as i64 - wl as i64).abs();
1823            let db = (b.chars().count() as i64 - wl as i64).abs();
1824            da.cmp(&db).then(a.cmp(b))
1825        })
1826}
1827
1828// fzf v2-style scoring constants.
1829const SCORE_MATCH: f64 = 16.0;
1830const GAP_START: f64 = -3.0;
1831const GAP_EXT: f64 = -1.0;
1832const BONUS_BOUNDARY_WHITE: f64 = 10.0;
1833const BONUS_BOUNDARY: f64 = 8.0;
1834const BONUS_CAMEL: f64 = 7.0;
1835const BONUS_CONSECUTIVE: f64 = 4.0;
1836const FIRST_CHAR_MULT: f64 = 2.0;
1837
1838fn char_bonus(prev: Option<char>, cur: char) -> f64 {
1839    match prev {
1840        None => BONUS_BOUNDARY_WHITE,
1841        Some(p) if p.is_whitespace() => BONUS_BOUNDARY_WHITE,
1842        Some('-' | '_' | '.' | '/' | '·' | ':' | ',' | '(' | '[' | '@' | '\\') => BONUS_BOUNDARY,
1843        Some(p) if p.is_lowercase() && cur.is_uppercase() => BONUS_CAMEL,
1844        Some(p) if p.is_alphabetic() && cur.is_ascii_digit() => BONUS_CAMEL,
1845        _ => 0.0,
1846    }
1847}
1848
1849/// fzf-style fuzzy score (higher is better): the best alignment of `pattern` as a case-insensitive
1850/// subsequence of `text`, rewarding matches at word starts / camelCase humps and consecutive runs and
1851/// penalizing gaps. `None` if `pattern` is not a subsequence of `text`. An empty pattern scores 0.
1852pub fn fuzzy_score(pattern: &str, text: &str) -> Option<f64> {
1853    let p: Vec<char> = pattern
1854        .to_lowercase()
1855        .chars()
1856        .filter(|c| !c.is_whitespace())
1857        .collect();
1858    if p.is_empty() {
1859        return Some(0.0);
1860    }
1861    let orig: Vec<char> = text.chars().collect();
1862    let t: Vec<char> = orig
1863        .iter()
1864        .map(|c| c.to_lowercase().next().unwrap_or(*c))
1865        .collect();
1866    let n = t.len();
1867    if n < p.len() {
1868        return None;
1869    }
1870    let bonus: Vec<f64> = (0..n)
1871        .map(|j| char_bonus(if j == 0 { None } else { Some(orig[j - 1]) }, orig[j]))
1872        .collect();
1873    const NEG: f64 = f64::NEG_INFINITY;
1874    // prev[j]: best score with p[..i] matched and p[i-1] at t[j].
1875    let mut prev: Vec<f64> = vec![NEG; n];
1876    for (j, &c) in t.iter().enumerate() {
1877        if c == p[0] {
1878            prev[j] = SCORE_MATCH + bonus[j] * FIRST_CHAR_MULT;
1879        }
1880    }
1881    for &pc in p.iter().skip(1) {
1882        let mut cur: Vec<f64> = vec![NEG; n];
1883        // gap_best: best of prev[k] + gap penalty for k ≤ j-2, maintained incrementally.
1884        let mut gap_best = NEG;
1885        for j in 0..n {
1886            if j >= 2 {
1887                gap_best = (gap_best + GAP_EXT).max(prev[j - 2] + GAP_START);
1888            }
1889            if t[j] != pc {
1890                continue;
1891            }
1892            let consecutive = if j >= 1 && prev[j - 1] > NEG {
1893                prev[j - 1] + SCORE_MATCH + bonus[j].max(BONUS_CONSECUTIVE)
1894            } else {
1895                NEG
1896            };
1897            let gapped = if gap_best > NEG {
1898                gap_best + SCORE_MATCH + bonus[j]
1899            } else {
1900                NEG
1901            };
1902            cur[j] = consecutive.max(gapped);
1903        }
1904        prev = cur;
1905    }
1906    let best = prev.into_iter().fold(NEG, f64::max);
1907    if best == NEG {
1908        return None;
1909    }
1910    // Shorter texts win ties (fzf's length tiebreak).
1911    Some(best - n as f64 * 0.01)
1912}
1913
1914/// [`fuzzy_score`] normalized to 0..1 against the ideal score for this pattern length (a prefix match of the
1915/// whole pattern scores ≈ 1).
1916pub fn fuzzy_match(pattern: &str, text: &str) -> Option<f64> {
1917    let m = pattern.chars().filter(|c| !c.is_whitespace()).count();
1918    if m == 0 {
1919        return Some(0.0);
1920    }
1921    let raw = fuzzy_score(pattern, text)?;
1922    let ideal = SCORE_MATCH
1923        + BONUS_BOUNDARY_WHITE * FIRST_CHAR_MULT
1924        + (m as f64 - 1.0) * (SCORE_MATCH + BONUS_CONSECUTIVE);
1925    Some((raw / ideal).clamp(0.0, 1.0))
1926}
1927
1928fn kind_prior(e: &VocabEntity) -> f64 {
1929    if e.id.starts_with(PROCESS_ID_PREFIX) {
1930        -0.05
1931    } else {
1932        0.0
1933    }
1934}
1935
1936fn affinity(frecency: f64) -> f64 {
1937    1.0 - (-frecency.max(0.0) / 5.0).exp()
1938}
1939
1940/// Match quality (0..1.5) of the query words against one name.
1941fn name_match_quality(words: &[String], name: &str) -> f64 {
1942    let lname = name.to_lowercase();
1943    let joined = words.join(" ");
1944    if lname == joined {
1945        return 1.5; // exact: always beats frecency
1946    }
1947    let mut best = fuzzy_match(&joined, name).unwrap_or(0.0);
1948    if words.len() > 1 {
1949        let per: Vec<f64> = words
1950            .iter()
1951            .map(|w| fuzzy_match(w, name).unwrap_or(0.0))
1952            .collect();
1953        if per.iter().all(|s| *s > 0.0) {
1954            best = best.max(0.9 * per.iter().sum::<f64>() / per.len() as f64);
1955        }
1956    }
1957    // Typo tolerance on whole name tokens and camelCase humps (fuzzy subsequence can't see transpositions).
1958    let tokens = name_tokens(name);
1959    for w in words {
1960        if w.chars().count() >= MIN_TYPO_LEN {
1961            if tokens.iter().any(|t| t == w) {
1962                best = best.max(1.0);
1963            } else if tokens.iter().any(|t| damerau_levenshtein(t, w) <= 1) {
1964                best = best.max(0.7);
1965            }
1966        }
1967    }
1968    best
1969}
1970
1971/// Links words to entities: fzf-style fuzzy match on names/aliases/renames (exact names score highest), plus
1972/// `FRECENCY_LINK_BOOST × affinity(frecency)` (or, without history, the machine-profile cold-start prior)
1973/// and small priors (pinned, groups over processes). Best first;
1974/// ties by id. Entities whose match is below [`MIN_LINK_SCORE`] are dropped.
1975pub fn link_entities(words: &[String], vocab: &Vocabulary) -> Vec<(String, f64)> {
1976    let words: Vec<String> = words
1977        .iter()
1978        .map(|w| w.trim().to_lowercase())
1979        .filter(|w| !w.is_empty())
1980        .collect();
1981    if words.is_empty() {
1982        return Vec::new();
1983    }
1984    let mut out: Vec<(String, f64)> = Vec::new();
1985    for e in &vocab.entities {
1986        let m = std::iter::once(&e.name)
1987            .chain(e.aliases.iter())
1988            .map(|n| name_match_quality(&words, n))
1989            .fold(0.0, f64::max);
1990        if m < MIN_LINK_SCORE {
1991            continue;
1992        }
1993        // Learned frecency replaces the cold-start prior (UX §5.4), exactly like the ranker.
1994        let cold = if e.frecency > 0.0 { 0.0 } else { e.prior.max(0.0) };
1995        let s = m + FRECENCY_LINK_BOOST * affinity(e.frecency) + kind_prior(e) + cold;
1996        out.push((e.id.clone(), (s * 1e6).round() / 1e6));
1997    }
1998    out.sort_by(|a, b| {
1999        b.1.partial_cmp(&a.1)
2000            .unwrap_or(std::cmp::Ordering::Equal)
2001            .then(a.0.cmp(&b.0))
2002    });
2003    out
2004}
2005
2006// ---------------------------------------------------------------------------------------------------------
2007// Normalization
2008// ---------------------------------------------------------------------------------------------------------
2009
2010const BYTE_UNITS: &[&str] = &[
2011    "b", "k", "kb", "kib", "m", "mb", "mib", "g", "gb", "gib", "t", "tb", "tib",
2012];
2013
2014fn unit_alias(u: &str) -> Option<&'static str> {
2015    Some(match u {
2016        "gig" | "gigs" | "gigabyte" | "gigabytes" => "GB",
2017        "meg" | "megs" | "megabyte" | "megabytes" => "MB",
2018        "terabyte" | "terabytes" => "TB",
2019        "kilobyte" | "kilobytes" => "KB",
2020        "gibibyte" | "gibibytes" => "GiB",
2021        _ => return None,
2022    })
2023}
2024
2025const TIME_UNITS: &[&str] = &[
2026    "s", "sec", "secs", "min", "mins", "h", "hr", "hrs", "d", "day", "days", "hours", "hour", "minutes",
2027    "minute",
2028];
2029
2030fn time_alias(u: &str) -> Option<&'static str> {
2031    Some(match u {
2032        "hours" | "hour" => "h",
2033        "minutes" | "minute" => "min",
2034        "seconds" | "second" => "s",
2035        _ => return None,
2036    })
2037}
2038
2039enum Quantity {
2040    Bytes(u64),
2041    Duration(f64),
2042}
2043
2044fn split_num(w: &str) -> Option<(&str, &str)> {
2045    let idx = w
2046        .find(|c: char| !(c.is_ascii_digit() || c == '.'))
2047        .unwrap_or(w.len());
2048    if idx == 0 {
2049        return None;
2050    }
2051    Some((&w[..idx], &w[idx..]))
2052}
2053
2054/// Interprets a number-with-unit word. `m` is ambiguous (MiB vs minutes): `prefer_time` decides.
2055fn quantity(w: &str, prefer_time: bool) -> Option<Quantity> {
2056    let (num, unit) = split_num(w)?;
2057    let unit_l = unit.to_ascii_lowercase();
2058    if unit_l.is_empty() {
2059        return None;
2060    }
2061    if unit_l == "m" {
2062        return if prefer_time {
2063            parse_duration_s(w).ok().map(Quantity::Duration)
2064        } else {
2065            parse_bytes(w).ok().map(Quantity::Bytes)
2066        };
2067    }
2068    if BYTE_UNITS.contains(&unit_l.as_str()) {
2069        return parse_bytes(w).ok().map(Quantity::Bytes);
2070    }
2071    if let Some(u) = unit_alias(&unit_l) {
2072        return parse_bytes(&format!("{num}{u}")).ok().map(Quantity::Bytes);
2073    }
2074    if TIME_UNITS.contains(&unit_l.as_str()) || time_alias(&unit_l).is_some() {
2075        let u = time_alias(&unit_l).unwrap_or(unit_l.as_str());
2076        return parse_duration_s(&format!("{num}{u}"))
2077            .ok()
2078            .map(Quantity::Duration);
2079    }
2080    // Compound durations like 1h30m.
2081    parse_duration_s(w).ok().map(Quantity::Duration)
2082}
2083
2084/// Lowercases, strips punctuation (keeps `.`, digits, letters, `-`, `_`), and joins `13 gb` → `13gb`.
2085fn normalize_raw_words(input: &str) -> Vec<String> {
2086    let cleaned: String = input
2087        .to_lowercase()
2088        .replace(['\u{2019}', '\''], "")
2089        .chars()
2090        .map(|c| {
2091            if c.is_alphanumeric() || matches!(c, '.' | '-' | '_') {
2092                c
2093            } else {
2094                ' '
2095            }
2096        })
2097        .collect();
2098    let raw: Vec<&str> = cleaned
2099        .split_whitespace()
2100        .map(|w| w.trim_matches(|c| c == '.' || c == '-'))
2101        .filter(|w| !w.is_empty())
2102        .collect();
2103    let mut out: Vec<String> = Vec::with_capacity(raw.len());
2104    let mut i = 0;
2105    while i < raw.len() {
2106        let w = raw[i];
2107        let is_num =
2108            w.chars().all(|c| c.is_ascii_digit() || c == '.') && w.chars().any(|c| c.is_ascii_digit());
2109        if is_num && i + 1 < raw.len() {
2110            let u = raw[i + 1];
2111            if BYTE_UNITS.contains(&u)
2112                || unit_alias(u).is_some()
2113                || TIME_UNITS.contains(&u)
2114                || time_alias(u).is_some()
2115            {
2116                out.push(format!("{w}{u}"));
2117                i += 2;
2118                continue;
2119            }
2120        }
2121        out.push(w.to_string());
2122        i += 1;
2123    }
2124    out
2125}
2126
2127/// True when `a` and `b` differ by exactly one swap of adjacent characters (`idel` ↔ `idle`).
2128fn is_adjacent_transposition(a: &str, b: &str) -> bool {
2129    let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
2130    if a.len() != b.len() {
2131        return false;
2132    }
2133    let diff: Vec<usize> = (0..a.len()).filter(|&i| a[i] != b[i]).collect();
2134    diff.len() == 2 && diff[1] == diff[0] + 1 && a[diff[0]] == b[diff[1]] && a[diff[1]] == b[diff[0]]
2135}
2136
2137/// Fixes a typo against the lexicon (Damerau-Levenshtein ≤ 1). Never touches stopwords, numbers, entity name
2138/// tokens, or a word that is the **prefix** of an entity token (the palette re-understands on every keystroke,
2139/// so `clan` on the way to `clang` must not become `clean`). Words of exactly [`MIN_TYPO_LEN`] characters are
2140/// only fixed by an adjacent transposition (`idel` → `idle`), because a single insert/delete/substitute on a
2141/// 4-letter word too often hits a different real word (`zoom` → `room`, `heap` → `heat`).
2142fn fix_typo(w: &str, entity_tokens: &HashSet<String>, corrections: &mut Vec<Correction>) -> String {
2143    let len = w.chars().count();
2144    if len < MIN_TYPO_LEN
2145        || in_lexicon(w)
2146        || STOPWORDS.contains(&w)
2147        || entity_tokens.contains(w)
2148        || entity_tokens.iter().any(|t| t.starts_with(w))
2149        || w.chars().any(|c| c.is_ascii_digit())
2150    {
2151        return w.to_string();
2152    }
2153    let fixed = if len == MIN_TYPO_LEN {
2154        lexicon().filter(|c| is_adjacent_transposition(c, w)).min()
2155    } else {
2156        closest(w, lexicon(), MIN_TYPO_LEN)
2157    };
2158    match fixed {
2159        Some(fixed) => {
2160            corrections.push(Correction {
2161                from: w.to_string(),
2162                to: fixed.to_string(),
2163            });
2164            fixed.to_string()
2165        }
2166        None => w.to_string(),
2167    }
2168}
2169
2170// ---------------------------------------------------------------------------------------------------------
2171// Intent classification
2172// ---------------------------------------------------------------------------------------------------------
2173
2174struct WordAnalysis {
2175    need: Option<u64>,
2176    idle_for: Option<f64>,
2177    kinds: Vec<GroupKind>,
2178    content: Vec<String>,
2179    scores: Vec<(Intent, f64)>,
2180    /// The user said "idle"/"unused" (→ `state:idle` on reclaim).
2181    said_idle: bool,
2182}
2183
2184fn has(words: &[String], set: &[&str]) -> bool {
2185    words.iter().any(|w| set.contains(&w.as_str()))
2186}
2187
2188fn analyze_words(words: &[String]) -> WordAnalysis {
2189    // `m` is MiB or minutes: minutes when the words talk about time ("idle for 30m"), bytes when they talk
2190    // about room ("room for 500m", "can I load 500m").
2191    let time_words = has(words, &["idle", "since", "ago", "older", "unused"]);
2192    let room_words = has(words, HEADROOM_VERBS) || has(words, HEADROOM_NOUNS);
2193    let prefer_time = time_words || (has(words, &["for"]) && !room_words);
2194    let mut need = None;
2195    let mut idle_for = None;
2196    let mut rest: Vec<String> = Vec::new();
2197    for w in words {
2198        match quantity(w, prefer_time) {
2199            Some(Quantity::Bytes(b)) => need = Some(b),
2200            Some(Quantity::Duration(d)) => idle_for = Some(d),
2201            None => rest.push(w.clone()),
2202        }
2203    }
2204    let metric = if has(&rest, GPU_WORDS) {
2205        Some(Metric::Gpu)
2206    } else if has(&rest, CPU_WORDS) {
2207        Some(Metric::Cpu)
2208    } else if has(&rest, MEM_WORDS) {
2209        Some(Metric::Mem)
2210    } else {
2211        None
2212    };
2213    let mut kinds: Vec<GroupKind> = Vec::new();
2214    for w in &rest {
2215        if KIND_WORDS.contains(&w.as_str()) {
2216            if let Some(k) = kind_synonym(w) {
2217                if !kinds.contains(&k) {
2218                    kinds.push(k);
2219                }
2220            }
2221        }
2222    }
2223    let content: Vec<String> = rest
2224        .iter()
2225        .filter(|w| !STOPWORDS.contains(&w.as_str()) && !in_lexicon(w))
2226        .cloned()
2227        .collect();
2228    // Words that carry meaning (not stopwords); used to decide "metric only" / "view only".
2229    let meaningful: Vec<&String> = rest.iter().filter(|w| !STOPWORDS.contains(&w.as_str())).collect();
2230
2231    let mut scores: Vec<(Intent, f64)> = Vec::new();
2232    // Headroom.
2233    let headroom_verb = has(&rest, HEADROOM_VERBS);
2234    let headroom_noun = has(&rest, HEADROOM_NOUNS);
2235    if need.is_some() {
2236        let s = if headroom_verb || headroom_noun {
2237            0.95
2238        } else if meaningful.is_empty() {
2239            0.85
2240        } else {
2241            0.7
2242        };
2243        scores.push((Intent::Headroom, s));
2244    } else if headroom_noun {
2245        scores.push((Intent::Headroom, 0.75));
2246    }
2247    // Explain.
2248    if has(&rest, EXPLAIN_STRONG) {
2249        scores.push((Intent::Explain, 0.9));
2250    } else if has(&rest, EXPLAIN_WEAK) {
2251        scores.push((Intent::Explain, 0.75));
2252    }
2253    // Rank by metric.
2254    let rank_metric = metric.unwrap_or(Metric::Mem);
2255    if has(&rest, RANK_WORDS) {
2256        scores.push((Intent::RankBy(rank_metric), 0.9));
2257    } else if metric.is_some()
2258        && meaningful.iter().all(|w| {
2259            MEM_WORDS.contains(&w.as_str())
2260                || GPU_WORDS.contains(&w.as_str())
2261                || CPU_WORDS.contains(&w.as_str())
2262        })
2263    {
2264        scores.push((Intent::RankBy(rank_metric), 0.8));
2265    } else if metric.is_some() {
2266        scores.push((Intent::RankBy(rank_metric), 0.55));
2267    }
2268    // Reclaim.
2269    if has(&rest, RECLAIM_STRONG) {
2270        scores.push((Intent::Reclaim, 0.9));
2271    } else if has(&rest, &["idle", "unused"]) {
2272        scores.push((Intent::Reclaim, 0.8));
2273    } else if has(&rest, &["free"]) && has(&rest, &["up"]) || has(&rest, &["kill", "stop"]) {
2274        scores.push((Intent::Reclaim, 0.75));
2275    } else if has(&rest, &["free"]) {
2276        scores.push((Intent::Reclaim, 0.5));
2277        if need.is_none() {
2278            scores.push((Intent::Headroom, 0.55));
2279        }
2280    }
2281    // Navigate.
2282    if let Some(v) = rest.iter().find_map(|w| nav_word(w)) {
2283        let only = meaningful.len() == 1;
2284        scores.push((Intent::Navigate(v), if only { 0.8 } else { 0.45 }));
2285    }
2286    WordAnalysis {
2287        need,
2288        idle_for,
2289        kinds,
2290        content,
2291        scores,
2292        said_idle: has(&rest, &["idle", "unused"]),
2293    }
2294}
2295
2296fn kind_filter(kinds: &[GroupKind]) -> Option<Expr> {
2297    (!kinds.is_empty()).then(|| {
2298        Expr::Term(Term::Field {
2299            key: FieldKey::Kind,
2300            values: kinds.iter().map(|k| k.alias().to_string()).collect(),
2301        })
2302    })
2303}
2304
2305fn state_filter(v: &str) -> Expr {
2306    Expr::Term(Term::Field {
2307        key: FieldKey::State,
2308        values: vec![v.to_string()],
2309    })
2310}
2311
2312fn fmt_need(b: u64) -> String {
2313    if b >= GIB && b.is_multiple_of(GIB) {
2314        format!("{} GiB", b / GIB)
2315    } else if b >= 1_000_000_000 && b.is_multiple_of(1_000_000_000) {
2316        format!("{} GB", b / 1_000_000_000)
2317    } else if b >= MIB && b.is_multiple_of(MIB) {
2318        format!("{} MiB", b / MIB)
2319    } else if b >= 1_000_000 && b.is_multiple_of(1_000_000) {
2320        format!("{} MB", b / 1_000_000)
2321    } else {
2322        crate::headline::format_amount(b, crate::units::UnitSystem::Si)
2323    }
2324}
2325
2326/// An intent word at or above this score ("why", "slow", "stop", "hogs") outranks plain entity linking.
2327const STRONG_INTENT: f64 = 0.75;
2328/// How far below a strong intent the plain "go to <entity>" interpretation is placed.
2329const STRONG_INTENT_LEAD: f64 = 0.2;
2330
2331/// Intents that act on the linked entities (their label names the top target).
2332fn targets_intent(i: &Intent) -> bool {
2333    matches!(i, Intent::Explain | Intent::Reclaim | Intent::RankBy(_))
2334}
2335
2336fn describe(intent: &Intent, filter: Option<&Expr>, need: Option<u64>, target_name: Option<&str>) -> String {
2337    let base = match intent {
2338        Intent::Find => match (target_name, filter) {
2339            (Some(n), _) => format!("go to {n}"),
2340            (None, Some(f)) => format!("filter {f}"),
2341            (None, None) => "find".into(),
2342        },
2343        Intent::Headroom => match need {
2344            Some(b) => format!("can {} fit?", fmt_need(b)),
2345            None => "check headroom".into(),
2346        },
2347        other => match target_name {
2348            Some(n) => format!("{} · {n}", other.label()),
2349            None => other.label(),
2350        },
2351    };
2352    match (intent, filter) {
2353        (Intent::Find, _) | (_, None) => base,
2354        (_, Some(f)) => format!("{base} ({f})"),
2355    }
2356}
2357
2358fn finish(mut u: Understanding, mut interps: Vec<Interpretation>) -> Understanding {
2359    interps.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
2360    // Deduplicate by label, keep best 3.
2361    let mut seen = HashSet::new();
2362    interps.retain(|i| seen.insert(i.label.clone()));
2363    interps.truncate(3);
2364    if let Some(best) = interps.first() {
2365        u.intent = best.intent.clone();
2366        u.filter = best.filter.clone();
2367        u.sort = best.sort;
2368        u.need_bytes = best.need_bytes.or(u.need_bytes);
2369        let second = interps.get(1).map(|i| i.score).unwrap_or(0.0);
2370        u.confidence = if best.score - second < 0.1 {
2371            best.score.min(0.45)
2372        } else {
2373            best.score
2374        };
2375    }
2376    u.alternatives = if u.confidence < LOW_CONFIDENCE {
2377        interps.iter().skip(1).map(|i| i.intent.clone()).collect()
2378    } else {
2379        Vec::new()
2380    };
2381    u.interpretations = interps;
2382    u
2383}
2384
2385fn fallback_interpretations() -> Vec<Interpretation> {
2386    [
2387        (Intent::RankBy(Metric::Mem), 0.2),
2388        (Intent::Explain, 0.19),
2389        (Intent::Reclaim, 0.18),
2390    ]
2391    .into_iter()
2392    .map(|(intent, score)| Interpretation {
2393        label: intent.label(),
2394        sort: match intent {
2395            Intent::RankBy(m) => Some(m),
2396            _ => None,
2397        },
2398        intent,
2399        filter: None,
2400        targets: Vec::new(),
2401        need_bytes: None,
2402        score,
2403    })
2404    .collect()
2405}
2406
2407/// Link-derived confidence for a Find interpretation. Entities sharing a display name (e.g. four
2408/// "Claude Code" sessions) count as one: the margin is measured against the best differently named one.
2409fn find_confidence(targets: &[(String, f64)], vocab: &Vocabulary) -> f64 {
2410    let name = |id: &str| {
2411        vocab
2412            .entities
2413            .iter()
2414            .find(|e| e.id == id)
2415            .map(|e| e.name.to_lowercase())
2416            .unwrap_or_else(|| id.to_string())
2417    };
2418    let Some((top_id, a)) = targets.first() else {
2419        return 0.0;
2420    };
2421    let top_name = name(top_id);
2422    match targets.iter().skip(1).find(|(id, _)| name(id) != top_name) {
2423        // A single candidate: confidence follows match quality (gappy fuzzy matches stay ambiguous).
2424        None if *a >= 0.9 => 0.9,
2425        None if *a >= 0.6 => 0.7,
2426        None => 0.45,
2427        Some((_, b)) => {
2428            let margin = a - b;
2429            if margin >= 0.25 {
2430                0.9
2431            } else if margin >= 0.1 {
2432                0.7
2433            } else {
2434                0.4
2435            }
2436        }
2437    }
2438}
2439
2440/// The filters the words of a query imply for an intent: "idle" / "idle for 30m" on a reclaim, kind words
2441/// ("agents", "daemons") wherever a list is shown. Used for plain queries and for the word part of a mixed
2442/// one (`idle daemons mem>1G`), so adding an explicit filter never drops what the words said.
2443fn lexicon_filters(intent: &Intent, wa: &WordAnalysis) -> Vec<Expr> {
2444    let mut parts = Vec::new();
2445    if *intent == Intent::Reclaim {
2446        if let Some(d) = wa.idle_for {
2447            parts.push(Expr::Term(Term::Cmp {
2448                metric: Metric::Idle,
2449                op: CmpOp::Ge,
2450                value: d,
2451            }));
2452        } else if wa.said_idle {
2453            parts.push(state_filter("idle"));
2454        }
2455    }
2456    if !matches!(intent, Intent::Navigate(_) | Intent::Headroom | Intent::Explain) {
2457        parts.extend(kind_filter(&wa.kinds));
2458    }
2459    parts
2460}
2461
2462fn plain_interpretations(
2463    wa: &WordAnalysis,
2464    extra_filter: Option<Expr>,
2465    vocab: &Vocabulary,
2466) -> (Vec<Interpretation>, Vec<(String, f64)>) {
2467    let targets = link_entities(&wa.content, vocab);
2468    let name_of = |id: &str| vocab.entities.iter().find(|e| e.id == id).map(|e| e.name.clone());
2469    let mut interps = Vec::new();
2470    for (intent, score) in &wa.scores {
2471        let mut parts: Vec<Expr> = extra_filter.iter().cloned().collect();
2472        parts.extend(lexicon_filters(intent, wa));
2473        let filter = Expr::and_all(parts);
2474        let sort = match intent {
2475            Intent::RankBy(m) => Some(*m),
2476            _ => None,
2477        };
2478        let about = if targets_intent(intent) {
2479            targets.first().and_then(|(id, _)| name_of(id))
2480        } else {
2481            None
2482        };
2483        interps.push(Interpretation {
2484            label: describe(intent, filter.as_ref(), wa.need, about.as_deref()),
2485            intent: intent.clone(),
2486            filter,
2487            sort,
2488            targets: if matches!(intent, Intent::Find) {
2489                Vec::new()
2490            } else {
2491                targets.iter().take(3).cloned().collect()
2492            },
2493            need_bytes: if matches!(intent, Intent::Headroom) {
2494                wa.need
2495            } else {
2496                None
2497            },
2498            score: *score,
2499        });
2500    }
2501    // Find: one interpretation per top linked entity. When a strong intent word is present ("why is
2502    // sd-server slow", "stop chrome") that intent already carries the targets, so plain "go to" ranks below it
2503    // instead of tying with it (a tie would make every such query ambiguous).
2504    let strong_intent = wa
2505        .scores
2506        .iter()
2507        .filter(|(i, s)| targets_intent(i) && *s >= STRONG_INTENT)
2508        .map(|(_, s)| *s)
2509        .fold(0.0, f64::max);
2510    let mut fc = find_confidence(&targets, vocab);
2511    if strong_intent > 0.0 {
2512        fc = fc.min(strong_intent - STRONG_INTENT_LEAD);
2513    }
2514    for (rank, (id, _)) in targets.iter().take(3).enumerate() {
2515        let name = name_of(id).unwrap_or_else(|| id.clone());
2516        interps.push(Interpretation {
2517            intent: Intent::Find,
2518            filter: extra_filter.clone(),
2519            sort: None,
2520            targets: targets.iter().skip(rank).take(3).cloned().collect(),
2521            need_bytes: None,
2522            label: describe(&Intent::Find, None, None, Some(&name)),
2523            score: if rank == 0 {
2524                fc
2525            } else {
2526                (fc - 0.1 * rank as f64).clamp(0.05, 0.44)
2527            },
2528        });
2529    }
2530    // Kind words alone ("agents", "daemons") → Find kind:…
2531    if !wa.kinds.is_empty() {
2532        let mut parts: Vec<Expr> = extra_filter.iter().cloned().collect();
2533        parts.extend(kind_filter(&wa.kinds));
2534        let filter = Expr::and_all(parts);
2535        interps.push(Interpretation {
2536            label: describe(&Intent::Find, filter.as_ref(), None, None),
2537            intent: Intent::Find,
2538            filter,
2539            sort: None,
2540            targets: Vec::new(),
2541            need_bytes: None,
2542            score: 0.65,
2543        });
2544    }
2545    (interps, targets)
2546}
2547
2548const COMMANDS: &[&str] = &[
2549    "reclaim",
2550    "headroom",
2551    "fit",
2552    "why",
2553    "pin",
2554    "unpin",
2555    "mute",
2556    "unmute",
2557    "rename",
2558    "mode",
2559    "sort",
2560    "save",
2561    "view",
2562    "filter",
2563    "help",
2564    "quit",
2565    "less",
2566    "watch",
2567    "stop",
2568    "suspend",
2569    "resume",
2570    "models",
2571    "sandboxes",
2572    "processes",
2573    "timeline",
2574    "home",
2575    "settings",
2576    "theme",
2577    "clear",
2578    "compare",
2579    "undo",
2580];
2581
2582fn understand_command(cmd: &str, vocab: &Vocabulary) -> Understanding {
2583    let mut u = Understanding::empty();
2584    let mut parts = cmd.split_whitespace().map(str::to_string);
2585    let raw_name = parts.next().unwrap_or_default().to_lowercase();
2586    let args: Vec<String> = parts.collect();
2587    let (name, known) = if COMMANDS.contains(&raw_name.as_str()) {
2588        (raw_name.clone(), true)
2589    } else if let Some(fixed) = (raw_name.chars().count() >= 3)
2590        .then(|| closest(&raw_name, COMMANDS.iter().copied(), 3))
2591        .flatten()
2592    {
2593        u.corrections.push(Correction {
2594            from: raw_name.clone(),
2595            to: fixed.to_string(),
2596        });
2597        (fixed.to_string(), true)
2598    } else {
2599        (raw_name.clone(), false)
2600    };
2601    u.normalized = std::iter::once(format!(":{name}"))
2602        .chain(args.iter().cloned())
2603        .collect::<Vec<_>>()
2604        .join(" ");
2605    let joined_args = normalize_raw_words(&args.join(" "));
2606    let link_args = |a: &[String]| link_entities(&normalize_raw_words(&a.join(" ")), vocab);
2607    let intent = match name.as_str() {
2608        "reclaim" => Intent::Reclaim,
2609        "headroom" | "fit" => {
2610            u.need_bytes = joined_args.iter().find_map(|w| match quantity(w, false) {
2611                Some(Quantity::Bytes(b)) => Some(b),
2612                _ => None,
2613            });
2614            // A bare number is not guessed at (GB? GiB?): ask for a unit instead of silently ignoring it.
2615            if u.need_bytes.is_none() {
2616                if let Some(n) = joined_args
2617                    .iter()
2618                    .find(|w| w.parse::<f64>().is_ok_and(|x| x.is_finite()))
2619                {
2620                    u.error = Some(format!("add a unit to {n}, e.g. {n}G or {n}GB"));
2621                }
2622            }
2623            Intent::Headroom
2624        }
2625        "why" => Intent::Explain,
2626        "sort" => match args.first().and_then(|a| TimeMetric::parse(a)) {
2627            Some(t) => {
2628                u.sort_time = Some(t);
2629                Intent::Find
2630            }
2631            None => {
2632                let m = args.first().and_then(|a| Metric::parse(a)).unwrap_or(Metric::Mem);
2633                u.sort = Some(m);
2634                Intent::RankBy(m)
2635            }
2636        },
2637        "view" => args
2638            .first()
2639            .and_then(|a| View::parse(a))
2640            .map(Intent::Navigate)
2641            .unwrap_or(Intent::Find),
2642        "models" | "sandboxes" | "processes" | "timeline" | "home" => {
2643            Intent::Navigate(View::parse(&name).unwrap_or(View::Home))
2644        }
2645        "filter" => {
2646            match parse_filter_corrected(&args.join(" ")) {
2647                Ok((f, c)) => {
2648                    u.filter = Some(f);
2649                    u.corrections.extend(c);
2650                }
2651                Err(e) => u.error = Some(e.to_string()),
2652            }
2653            Intent::Find
2654        }
2655        "pin" | "unpin" | "mute" | "unmute" | "watch" | "stop" | "suspend" | "resume" | "less" => {
2656            u.targets = link_args(&args);
2657            Intent::Find
2658        }
2659        "rename" => {
2660            // `:rename <entity…> <alias>`: the last word is the new name.
2661            if args.len() >= 2 {
2662                u.targets = link_args(&args[..args.len() - 1]);
2663            }
2664            Intent::Find
2665        }
2666        _ => Intent::Find,
2667    };
2668    u.intent = intent.clone();
2669    u.command = Some(Command { name, args });
2670    u.confidence = if !known {
2671        0.3
2672    } else if u.corrections.is_empty() {
2673        1.0
2674    } else {
2675        0.9
2676    };
2677    if !known {
2678        let mut sugg: Vec<(&str, f64)> = COMMANDS
2679            .iter()
2680            .filter_map(|c| fuzzy_match(&raw_name, c).map(|s| (*c, s)))
2681            .collect();
2682        sugg.sort_by(|a, b| {
2683            b.1.partial_cmp(&a.1)
2684                .unwrap_or(std::cmp::Ordering::Equal)
2685                .then(a.0.cmp(b.0))
2686        });
2687        u.interpretations = sugg
2688            .into_iter()
2689            .take(3)
2690            .map(|(c, s)| Interpretation {
2691                intent: Intent::Find,
2692                filter: None,
2693                sort: None,
2694                targets: Vec::new(),
2695                need_bytes: None,
2696                label: format!(":{c}"),
2697                score: (s * 0.4).min(0.4),
2698            })
2699            .collect();
2700    } else {
2701        u.interpretations = vec![Interpretation {
2702            intent,
2703            filter: u.filter.clone(),
2704            sort: u.sort,
2705            targets: u.targets.clone(),
2706            need_bytes: u.need_bytes,
2707            label: format!(":{}", u.command.as_ref().map(|c| c.name.as_str()).unwrap_or("")),
2708            score: u.confidence,
2709        }];
2710    }
2711    u
2712}
2713
2714fn looks_structured(toks: &[Tok]) -> bool {
2715    toks.iter().any(|t| match t {
2716        Tok::LParen | Tok::RParen | Tok::Or | Tok::Not | Tok::Neg | Tok::Lit(_) => true,
2717        Tok::Atom(a) => split_key_op(a).is_some(),
2718    })
2719}
2720
2721/// Understands any input: `:command`, structured filter, plain words, or a mix of filter terms and words.
2722pub fn understand(input: &str, vocab: &Vocabulary) -> Understanding {
2723    let input = input.trim();
2724    if let Some(cmd) = input.strip_prefix(':') {
2725        return understand_command(cmd, vocab);
2726    }
2727    let mut u = Understanding::empty();
2728    if input.is_empty() {
2729        u.confidence = 1.0;
2730        return u;
2731    }
2732    let entity_tokens = vocab.tokens();
2733
2734    // Structured (or mixed) input. A filter that looks structured but doesn't parse is reported as an
2735    // error (the palette shows it inline) instead of being guessed at as plain words.
2736    match tokenize(input) {
2737        Ok(toks) if looks_structured(&toks) => {
2738            let mut corrections = Vec::new();
2739            match parse_tokens(toks, &mut corrections) {
2740                Ok(expr) => return understand_structured(expr, corrections, vocab, &entity_tokens),
2741                Err(e) => {
2742                    u.error = Some(e.to_string());
2743                    u.corrections = corrections;
2744                    u.normalized = input.to_lowercase();
2745                    return u;
2746                }
2747            }
2748        }
2749        Ok(_) => {}
2750        Err(e) => {
2751            u.error = Some(e.to_string());
2752            u.normalized = input.to_lowercase();
2753            return u;
2754        }
2755    }
2756
2757    // Plain words.
2758    let raw = normalize_raw_words(input);
2759    let words: Vec<String> = raw
2760        .iter()
2761        .map(|w| fix_typo(w, &entity_tokens, &mut u.corrections))
2762        .collect();
2763    u.normalized = words.join(" ");
2764    let wa = analyze_words(&words);
2765    u.need_bytes = wa.need;
2766    let (interps, targets) = plain_interpretations(&wa, None, vocab);
2767    u.targets = targets;
2768    if interps.is_empty() {
2769        u.confidence = 0.2;
2770        u.interpretations = fallback_interpretations();
2771        u.alternatives = u.interpretations.iter().map(|i| i.intent.clone()).collect();
2772        u
2773    } else {
2774        finish(u, interps)
2775    }
2776}
2777
2778fn understand_structured(
2779    expr: Expr,
2780    corrections: Vec<Correction>,
2781    vocab: &Vocabulary,
2782    entity_tokens: &HashSet<String>,
2783) -> Understanding {
2784    let mut u = Understanding::empty();
2785    u.corrections = corrections;
2786    // Split a top-level conjunction into structured parts and plain words. A phrase (a quoted word with
2787    // spaces or punctuation, e.g. `"Claude Code"`) stays one literal filter term; it still links entities.
2788    let is_phrase = |x: &str| {
2789        !x.chars()
2790            .all(|c| c.is_alphanumeric() || matches!(c, '-' | '_' | '.'))
2791    };
2792    let mut phrases: Vec<String> = Vec::new();
2793    let (structured, words): (Vec<Expr>, Vec<String>) = match expr {
2794        Expr::And(parts) => {
2795            let mut s = Vec::new();
2796            let mut w = Vec::new();
2797            for p in parts {
2798                match p {
2799                    Expr::Term(Term::Word(x)) if !is_phrase(&x) => w.push(x),
2800                    Expr::Term(Term::Word(x)) => {
2801                        phrases.push(x.clone());
2802                        s.push(Expr::Term(Term::Word(x)));
2803                    }
2804                    other => s.push(other),
2805                }
2806            }
2807            (s, w)
2808        }
2809        Expr::Term(Term::Word(x)) if !is_phrase(&x) => (Vec::new(), vec![x]),
2810        Expr::Term(Term::Word(x)) => {
2811            phrases.push(x.clone());
2812            (vec![Expr::Term(Term::Word(x))], Vec::new())
2813        }
2814        other => (vec![other], Vec::new()),
2815    };
2816    let norm_words: Vec<String> = normalize_raw_words(&words.join(" "))
2817        .iter()
2818        .map(|w| fix_typo(w, entity_tokens, &mut u.corrections))
2819        .collect();
2820    let wa = analyze_words(&norm_words);
2821    // Content words stay in the filter as name/state matches (a mixed query like `chrome mem>1G`).
2822    let mut parts = structured;
2823    for w in &wa.content {
2824        parts.push(Expr::Term(Term::Word(w.clone())));
2825    }
2826    let filter = Expr::and_all(parts);
2827    let intent_words: Vec<String> = norm_words
2828        .iter()
2829        .filter(|w| !wa.content.contains(w))
2830        .cloned()
2831        .collect();
2832    let filter_text = filter.as_ref().map(|f| f.to_string()).unwrap_or_default();
2833    u.normalized = format!("{} {filter_text}", intent_words.join(" "))
2834        .trim()
2835        .to_string();
2836    let link_words: Vec<String> = wa.content.iter().chain(phrases.iter()).cloned().collect();
2837    u.targets = link_entities(&link_words, vocab);
2838    u.need_bytes = wa.need;
2839    let metrics = filter.as_ref().map(|f| f.metrics()).unwrap_or_default();
2840    let default_sort = (metrics.len() == 1).then(|| metrics[0]);
2841    // The words keep the filters they imply (kind words, "idle", "idle for 30m"), next to the explicit ones.
2842    let with_lexicon = |intent: &Intent| -> Option<Expr> {
2843        let extra = lexicon_filters(intent, &wa);
2844        if extra.is_empty() {
2845            return filter.clone();
2846        }
2847        Expr::and_all(filter.iter().cloned().chain(extra).collect())
2848    };
2849    let mut interps: Vec<Interpretation> = wa
2850        .scores
2851        .iter()
2852        .map(|(intent, score)| {
2853            let filter = with_lexicon(intent);
2854            Interpretation {
2855                label: describe(intent, filter.as_ref(), wa.need, None),
2856                intent: intent.clone(),
2857                filter,
2858                sort: match intent {
2859                    Intent::RankBy(m) => Some(*m),
2860                    _ => default_sort,
2861                },
2862                targets: u.targets.iter().take(3).cloned().collect(),
2863                need_bytes: wa.need,
2864                score: *score,
2865            }
2866        })
2867        .collect();
2868    let filter = with_lexicon(&Intent::Find);
2869    interps.push(Interpretation {
2870        label: describe(&Intent::Find, filter.as_ref(), None, None),
2871        intent: Intent::Find,
2872        filter: filter.clone(),
2873        sort: default_sort,
2874        targets: u.targets.iter().take(3).cloned().collect(),
2875        need_bytes: None,
2876        // A parsed filter is unambiguous; intent words (if any) win over plain filtering.
2877        score: if wa.scores.is_empty() { 1.0 } else { 0.6 },
2878    });
2879    let mut u = finish(u, interps);
2880    // With intent words present the filter still applies to that intent.
2881    if u.filter.is_none() {
2882        u.filter = filter;
2883    }
2884    if u.sort.is_none() {
2885        u.sort = default_sort;
2886    }
2887    // Structured parts are explicit, so confidence stays high unless words were ambiguous.
2888    if wa.scores.is_empty() {
2889        u.confidence = 1.0;
2890    }
2891    u
2892}
2893
2894// ---------------------------------------------------------------------------------------------------------
2895// Learned completion (UX §5.2)
2896// ---------------------------------------------------------------------------------------------------------
2897
2898#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2899#[serde(rename_all = "snake_case")]
2900pub enum SuggestionKind {
2901    PastQuery,
2902    Entity,
2903    Command,
2904    Key,
2905}
2906
2907#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2908pub struct Suggestion {
2909    pub text: String,
2910    pub kind: SuggestionKind,
2911    pub score: f64,
2912}
2913
2914const FILTER_KEYS: &[&str] = &[
2915    "kind:", "owner:", "name:", "state:", "sandbox:", "mem>", "gpu>", "cpu>", "idle>",
2916];
2917
2918/// Palette completion: past queries (frecency-ranked, `past` = (query, frecency)), entity names (frecency
2919/// boosted), commands after `:`, and filter keys. Best first, at most `limit`.
2920pub fn suggest(input: &str, past: &[(String, f64)], vocab: &Vocabulary, limit: usize) -> Vec<Suggestion> {
2921    let q = input.trim();
2922    let mut out: Vec<Suggestion> = Vec::new();
2923    let push = |out: &mut Vec<Suggestion>, text: String, kind, score: f64| {
2924        if !out.iter().any(|s| s.text == text) && text != q {
2925            out.push(Suggestion { text, kind, score });
2926        }
2927    };
2928    if let Some(c) = q.strip_prefix(':') {
2929        for cmd in COMMANDS {
2930            if let Some(s) = fuzzy_match(c, cmd) {
2931                if c.is_empty() || s > 0.3 {
2932                    push(&mut out, format!(":{cmd}"), SuggestionKind::Command, 1.0 + s);
2933                }
2934            }
2935        }
2936    }
2937    for (text, fr) in past {
2938        let s = if q.is_empty() {
2939            Some(0.5)
2940        } else if text.to_lowercase().starts_with(&q.to_lowercase()) {
2941            Some(1.0)
2942        } else {
2943            fuzzy_match(q, text)
2944        };
2945        if let Some(s) = s.filter(|s| *s >= MIN_LINK_SCORE) {
2946            push(
2947                &mut out,
2948                text.clone(),
2949                SuggestionKind::PastQuery,
2950                s + affinity(*fr),
2951            );
2952        }
2953    }
2954    if !q.is_empty() && !q.starts_with(':') {
2955        let last = q.split_whitespace().last().unwrap_or("");
2956        for (id, s) in link_entities(&[last.to_string()], vocab).into_iter().take(limit) {
2957            if let Some(e) = vocab.entities.iter().find(|e| e.id == id) {
2958                push(&mut out, e.name.clone(), SuggestionKind::Entity, s);
2959            }
2960        }
2961        if last.chars().all(|c| c.is_ascii_alphabetic()) && !last.is_empty() {
2962            for k in FILTER_KEYS {
2963                if k.starts_with(&last.to_ascii_lowercase()) {
2964                    push(&mut out, (*k).to_string(), SuggestionKind::Key, 0.4);
2965                }
2966            }
2967        }
2968    }
2969    out.sort_by(|a, b| {
2970        b.score
2971            .partial_cmp(&a.score)
2972            .unwrap_or(std::cmp::Ordering::Equal)
2973            .then(a.text.cmp(&b.text))
2974    });
2975    out.truncate(limit);
2976    out
2977}
2978
2979#[cfg(test)]
2980mod tests {
2981    use super::*;
2982    use crate::units::GIB;
2983
2984    fn view(kind: GroupKind, name: &str, mem: u64, gpu: u64) -> EntityView {
2985        EntityView {
2986            kind,
2987            name: name.into(),
2988            mem: Some(mem),
2989            gpu: Some(gpu),
2990            ..Default::default()
2991        }
2992    }
2993
2994    #[test]
2995    fn grammar_example() {
2996        let e = parse_filter("kind:model,agent or gpu>1G -muted").unwrap();
2997        let m = view(GroupKind::ModelServer, "sd-server", 10 * GIB, 0);
2998        let c = view(GroupKind::App, "Chrome", GIB, 2 * GIB);
2999        let mut muted = view(GroupKind::App, "Chrome", GIB, 2 * GIB);
3000        muted.state.push("muted".into());
3001        let x = view(GroupKind::App, "Slack", GIB, 0);
3002        assert!(eval(&e, &m));
3003        assert!(eval(&e, &c));
3004        assert!(!eval(&e, &muted));
3005        assert!(!eval(&e, &x));
3006        assert_eq!(e.to_string(), "kind:model,agent or gpu>1G -muted");
3007        assert_eq!(parse_filter(&e.to_string()).unwrap(), e);
3008    }
3009
3010    #[test]
3011    fn structured_filters() {
3012        let e = parse_filter("mem>2G kind:daemon idle>30m").unwrap();
3013        let mut v = view(GroupKind::BuildDaemon, "GradleDaemon", 3 * GIB, 0);
3014        v.idle_s = Some(5 * 3600);
3015        assert!(eval(&e, &v));
3016        v.idle_s = Some(60);
3017        assert!(!eval(&e, &v));
3018        assert!(eval(&parse_filter("not (kind:app or kind:system)").unwrap(), &v));
3019        assert!(eval(&parse_filter("-(kind:app or kind:system)").unwrap(), &v));
3020        assert!(eval(&parse_filter(r#"name:"Gradle""#).unwrap(), &v));
3021        assert!(eval(&parse_filter("name:grad*").unwrap(), &v));
3022        assert!(!eval(&parse_filter("name:kot*").unwrap(), &v));
3023        assert!(matches!(parse_filter("foo:bar"), Err(QueryError::UnknownKey(_))));
3024        assert!(matches!(
3025            parse_filter("kind:nope"),
3026            Err(QueryError::BadValue { .. })
3027        ));
3028        assert!(matches!(parse_filter("(kind:app"), Err(QueryError::Parens)));
3029        assert!(matches!(parse_filter("kind:app)"), Err(QueryError::Parens)));
3030        assert!(matches!(parse_filter("\"open"), Err(QueryError::Quote)));
3031        assert!(matches!(parse_filter("mem>2"), Err(QueryError::BadValue { .. })));
3032        assert!(matches!(parse_filter("mem:2G"), Err(QueryError::BadValue { .. })));
3033        assert!(matches!(
3034            parse_filter("name>2G"),
3035            Err(QueryError::BadValue { .. })
3036        ));
3037        assert!(matches!(parse_filter("a or"), Err(QueryError::Empty)));
3038    }
3039
3040    #[test]
3041    fn spaced_and_alias_forms() {
3042        let a = parse_filter("mem > 2G").unwrap();
3043        let b = parse_filter("mem>2G").unwrap();
3044        let c = parse_filter("mem:>2G").unwrap();
3045        let d = parse_filter("memory >2g").unwrap();
3046        assert_eq!(a, b);
3047        assert_eq!(b, c);
3048        assert_eq!(c, d);
3049        assert_eq!(
3050            parse_filter("kind:models,daemons").unwrap().to_string(),
3051            "kind:model,daemon"
3052        );
3053        assert_eq!(parse_filter("is:orphaned").unwrap().to_string(), "state:orphan");
3054        assert_eq!(parse_filter("cpu>=50%").unwrap().to_string(), "cpu>=50");
3055        assert_eq!(parse_filter("idle>1h30m").unwrap().to_string(), "idle>90m");
3056        let (e, c) = parse_filter_corrected("knid:modle").unwrap();
3057        assert_eq!(e.to_string(), "kind:model");
3058        assert_eq!(c.len(), 2);
3059    }
3060
3061    #[test]
3062    fn unavailable_metric_never_matches() {
3063        let mut v = view(GroupKind::App, "x", 0, 0);
3064        v.gpu = None;
3065        assert!(!eval(&parse_filter("gpu<1G").unwrap(), &v));
3066        assert!(!eval(&parse_filter("gpu>=0").unwrap(), &v));
3067        assert!(eval(&parse_filter("-gpu>1G").unwrap(), &v));
3068    }
3069
3070    #[test]
3071    fn sandbox_and_owner() {
3072        let mut v = view(GroupKind::Sandbox, "Claude VM", GIB, 0);
3073        v.sandbox = Some("Claude VM".into());
3074        v.add_state("runtime:virtualization.framework");
3075        v.owner = Some("Claude Code".into());
3076        assert!(eval(&parse_filter("sandbox:*").unwrap(), &v));
3077        assert!(eval(&parse_filter("sandbox:virtualization*").unwrap(), &v));
3078        assert!(eval(&parse_filter(r#"owner:"Claude Code""#).unwrap(), &v));
3079        assert!(!eval(&parse_filter("owner:codex").unwrap(), &v));
3080        let app = view(GroupKind::App, "Chrome", GIB, 0);
3081        assert!(!eval(&parse_filter("sandbox:*").unwrap(), &app));
3082    }
3083
3084    #[test]
3085    fn plain_words_intents() {
3086        let v = Vocabulary::default();
3087        assert_eq!(understand("gpu hogs", &v).intent, Intent::RankBy(Metric::Gpu));
3088        assert_eq!(
3089            understand("what's eating memory", &v).intent,
3090            Intent::RankBy(Metric::Mem)
3091        );
3092        assert_eq!(understand("why slow", &v).intent, Intent::Explain);
3093        let u = understand("idle stuff", &v);
3094        assert_eq!(u.intent, Intent::Reclaim);
3095        assert_eq!(u.filter.unwrap().to_string(), "state:idle");
3096        assert_eq!(understand("models", &v).intent, Intent::Navigate(View::Models));
3097        let u = understand("can I load 13g", &v);
3098        assert_eq!(u.intent, Intent::Headroom);
3099        assert_eq!(u.need_bytes, Some(13 * GIB));
3100        let u = understand("can I load 13 GB", &v);
3101        assert_eq!(u.need_bytes, Some(13_000_000_000));
3102        let u = understand("throtle", &v);
3103        assert_eq!(u.intent, Intent::Explain, "typo corrected");
3104        assert_eq!(u.corrections[0].to, "throttle");
3105        let u = understand("mem>2G", &v);
3106        assert!(u.filter.is_some());
3107        let u = understand(":headroom 13G", &v);
3108        assert_eq!(u.intent, Intent::Headroom);
3109        assert_eq!(u.need_bytes, Some(13 * GIB));
3110        let u = understand("idle daemons", &v);
3111        assert_eq!(u.intent, Intent::Reclaim);
3112        assert_eq!(u.filter.unwrap().to_string(), "state:idle kind:daemon");
3113        let u = understand("idle for 2h", &v);
3114        assert_eq!(u.filter.unwrap().to_string(), "idle>=2h");
3115    }
3116
3117    #[test]
3118    fn mixed_words_and_filters() {
3119        let v = Vocabulary::default();
3120        let u = understand("gpu hogs kind:model", &v);
3121        assert_eq!(u.intent, Intent::RankBy(Metric::Gpu));
3122        assert_eq!(u.filter.unwrap().to_string(), "kind:model");
3123        let u = understand("chrome mem>1G", &v);
3124        assert_eq!(u.intent, Intent::Find);
3125        assert_eq!(u.filter.unwrap().to_string(), "mem>1G chrome");
3126    }
3127
3128    /// Audit finding 10: the words of a mixed query keep the filters they imply.
3129    #[test]
3130    fn mixed_queries_keep_lexicon_filters() {
3131        let v = Vocabulary::default();
3132        // kind word + explicit filter
3133        let u = understand("daemons mem>1G", &v);
3134        assert_eq!(u.filter.unwrap().to_string(), "mem>1G kind:daemon");
3135        // the same words without the explicit part
3136        let plain = understand("idle daemons", &v);
3137        assert_eq!(plain.intent, Intent::Reclaim);
3138        let plain_filter = plain.filter.unwrap().to_string();
3139        assert!(
3140            plain_filter.contains("state:idle") && plain_filter.contains("kind:daemon"),
3141            "{plain_filter}"
3142        );
3143        // …and with it: nothing the words said is dropped
3144        let u = understand("idle daemons mem>1G", &v);
3145        assert_eq!(u.intent, Intent::Reclaim);
3146        let f = u.filter.unwrap().to_string();
3147        assert!(
3148            f.contains("mem>1G") && f.contains("state:idle") && f.contains("kind:daemon"),
3149            "{f}"
3150        );
3151        let u = understand("reclaim agents idle for 30m gpu>1G", &v);
3152        assert_eq!(u.intent, Intent::Reclaim);
3153        let f = u.filter.unwrap().to_string();
3154        assert!(
3155            f.contains("gpu>1G") && f.contains("idle>=30m") && f.contains("kind:agent"),
3156            "{f}"
3157        );
3158    }
3159
3160    /// Audit finding 13: a quoted value may start with an operator character, the canonical form parses
3161    /// back to the same expression, and nesting is bounded.
3162    #[test]
3163    fn quoted_operator_values_round_trip_and_depth_limit() {
3164        for q in [
3165            r#"name:">x""#,
3166            r#"name: ">x""#,
3167            r#"name:"=a,<b""#,
3168            r#"owner:">=""#,
3169        ] {
3170            let e = parse_filter(q).unwrap_or_else(|e| panic!("{q}: {e}"));
3171            let again = parse_filter(&e.to_string()).unwrap_or_else(|err| panic!("{q} → {e}: {err}"));
3172            assert_eq!(e, again, "{q} → {e}");
3173        }
3174        assert_eq!(
3175            parse_filter(r#"name:">x""#).unwrap(),
3176            Expr::Term(Term::Field {
3177                key: FieldKey::Name,
3178                values: vec![">x".into()]
3179            })
3180        );
3181        // unquoted, it is still a (rejected) comparison on a text key
3182        assert!(parse_filter("name:>x").is_err());
3183        // values that used to print in a form the parser refuses or rounds
3184        for q in [
3185            "mem>1500B",
3186            "mem>1B",
3187            "mem>0",
3188            "mem>=1.337G",
3189            "gpu<1234567K",
3190            "mem>1.5G",
3191            "mem>2G",
3192            "mem>3GB",
3193            "mem>1023B",
3194            "mem>1.0001G",
3195            "cpu>12.345",
3196            "cpu>=0.5",
3197            "cpu<100",
3198            "idle>90s",
3199            "idle>=30m",
3200        ] {
3201            let e = parse_filter(q).unwrap_or_else(|e| panic!("{q}: {e}"));
3202            let shown = e.to_string();
3203            let again = parse_filter(&shown).unwrap_or_else(|err| panic!("{q} → {shown}: {err}"));
3204            assert_eq!(e, again, "{q} → {shown}");
3205        }
3206        assert_eq!(parse_filter("mem>1.5G").unwrap().to_string(), "mem>1536M");
3207        assert_eq!(parse_filter("mem>1500B").unwrap().to_string(), "mem>1500B");
3208        assert_eq!(parse_filter("mem>0").unwrap().to_string(), "mem>0");
3209        // nesting: fine up to the limit, an error (not a stack overflow) beyond it
3210        let nest = |n: usize| format!("{}x{}", "(".repeat(n), ")".repeat(n));
3211        assert!(parse_filter(&nest(MAX_DEPTH)).is_ok());
3212        assert_eq!(parse_filter(&nest(MAX_DEPTH + 1)), Err(QueryError::TooDeep));
3213        assert_eq!(parse_filter(&nest(200_000)), Err(QueryError::TooDeep));
3214        assert_eq!(
3215            parse_filter(&format!("{}x", "not ".repeat(200_000))),
3216            Err(QueryError::TooDeep)
3217        );
3218        assert_eq!(
3219            parse_filter(&format!("{}x", "-(".repeat(100_000))),
3220            Err(QueryError::TooDeep)
3221        );
3222        // siblings do not count as depth
3223        let wide = vec!["(a or b)"; 500].join(" ");
3224        assert!(parse_filter(&wide).is_ok());
3225        let _ = understand(&nest(200_000), &Vocabulary::default());
3226    }
3227
3228    #[test]
3229    fn commands() {
3230        let vocab = Vocabulary {
3231            entities: vec![VocabEntity {
3232                id: "model:sd".into(),
3233                name: "sd-server".into(),
3234                ..Default::default()
3235            }],
3236        };
3237        let u = understand(":pin sd-server", &vocab);
3238        assert_eq!(u.command.as_ref().unwrap().name, "pin");
3239        assert_eq!(u.targets[0].0, "model:sd");
3240        let u = understand(":reclam", &vocab);
3241        assert_eq!(u.intent, Intent::Reclaim);
3242        assert_eq!(u.confidence, 0.9);
3243        let u = understand(":sort gpu", &vocab);
3244        assert_eq!(u.intent, Intent::RankBy(Metric::Gpu));
3245        let u = understand(":zzzz", &vocab);
3246        assert!(u.is_ambiguous());
3247        let u = understand(":mode pressure", &vocab);
3248        assert_eq!(u.command.unwrap().args, vec!["pressure".to_string()]);
3249    }
3250
3251    #[test]
3252    fn cl_prefers_frecent_claude() {
3253        let vocab = Vocabulary {
3254            entities: vec![
3255                VocabEntity {
3256                    id: "pid:42".into(),
3257                    name: "clang".into(),
3258                    ..Default::default()
3259                },
3260                VocabEntity {
3261                    id: "agent:claude".into(),
3262                    name: "Claude Code".into(),
3263                    frecency: 12.0,
3264                    ..Default::default()
3265                },
3266            ],
3267        };
3268        let u = understand("cl", &vocab);
3269        assert_eq!(u.intent, Intent::Find);
3270        assert_eq!(u.targets[0].0, "agent:claude");
3271        // Typing the full name of the other entity wins over frecency.
3272        let u = understand("clang", &vocab);
3273        assert_eq!(u.targets[0].0, "pid:42");
3274    }
3275
3276    #[test]
3277    fn fuzzy_scoring() {
3278        assert!(fuzzy_score("cl", "clang").is_some());
3279        assert!(fuzzy_score("xz", "clang").is_none());
3280        assert_eq!(fuzzy_score("", "x"), Some(0.0));
3281        // Word-start matches beat mid-word matches.
3282        let a = fuzzy_score("cc", "Claude Code").unwrap();
3283        let b = fuzzy_score("cc", "accept").unwrap();
3284        assert!(a > b, "{a} {b}");
3285        assert!(fuzzy_match("sd", "sd-server").unwrap() > 0.95);
3286        assert!(fuzzy_match("gd", "GradleDaemon").unwrap() > fuzzy_match("gd", "bigdata").unwrap());
3287        // Best alignment, not leftmost: "code" should hit the word "Code".
3288        assert!(fuzzy_match("code", "Claude Code").unwrap() > 0.95);
3289    }
3290
3291    #[test]
3292    fn dl_distance() {
3293        assert_eq!(damerau_levenshtein("throttle", "throtle"), 1);
3294        assert_eq!(damerau_levenshtein("ab", "ba"), 1);
3295        assert_eq!(damerau_levenshtein("", "abc"), 3);
3296        assert_eq!(damerau_levenshtein("kitten", "sitting"), 3);
3297        assert_eq!(damerau_levenshtein("daemons", "daemnos"), 1);
3298    }
3299
3300    #[test]
3301    fn typo_never_rewrites_entity_names() {
3302        let vocab = Vocabulary {
3303            entities: vec![VocabEntity {
3304                id: "app:slot".into(),
3305                name: "Slot".into(),
3306                ..Default::default()
3307            }],
3308        };
3309        // "slot" is DL 1 from "slow" but it's a known entity token.
3310        let u = understand("slot", &vocab);
3311        assert_eq!(u.intent, Intent::Find);
3312        assert!(u.corrections.is_empty());
3313        assert_eq!(u.targets[0].0, "app:slot");
3314    }
3315
3316    #[test]
3317    fn suggestions() {
3318        let vocab = Vocabulary {
3319            entities: vec![VocabEntity {
3320                id: "agent:c".into(),
3321                name: "Claude Code".into(),
3322                frecency: 3.0,
3323                ..Default::default()
3324            }],
3325        };
3326        let past = vec![("gpu hogs".to_string(), 4.0), ("kind:model".to_string(), 1.0)];
3327        let s = suggest("gp", &past, &vocab, 5);
3328        assert_eq!(s[0].text, "gpu hogs");
3329        let s = suggest("cla", &past, &vocab, 5);
3330        assert!(s.iter().any(|x| x.text == "Claude Code"));
3331        let s = suggest(":rec", &past, &vocab, 3);
3332        assert_eq!(s[0].text, ":reclaim");
3333        let s = suggest("ki", &past, &vocab, 5);
3334        assert!(s.iter().any(|x| x.text == "kind:"));
3335    }
3336}