instinct-cli 0.3.7

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
//! Synonym groups from general software vocabulary. Each group is one idea written several ways, and its
//! first word is the canonical token. The table is not tuned to any bench; a group that causes a false
//! positive is removed, never reworded around one query.
//!
//! On by default together with the rare-word gate (the pair scored highest on the holdout bench); only
//! `INSTINCT_CONCEPTS=0` turns both uses off:
//!  - the trigger gate (`anchors`) maps each word to its canonical token on both sides, so "RAM" and
//!    "memory" count as one shared anchor, and short words (ram, pod, oom) count through their canonical form;
//!  - BM25 expands the query with the members of the groups its words belong to, and nothing else.
//!
//! Sibling access goes through `super::` because the playground compiles main.rs as a submodule.
use std::collections::HashMap;
use std::sync::OnceLock;

const GROUPS: &[&[&str]] = &[
    &["deploy", "release", "ship", "rollout", "cutover"],
    &["rollback", "revert", "undo", "backout"],
    &["memory", "ram", "oom", "heap"],
    &["container", "pod", "docker"],
    &["test", "spec", "suite"],
    &["fail", "failure", "red", "broken", "flaky"],
    &["offline", "airgapped", "gapped", "disconnected"],
    &["host", "machine", "server", "box", "vm"],
    &["rename", "move", "relocate"],
    &["edit", "change", "modify", "alter", "tweak", "amend"],
    &["crash", "panic", "segfault", "abort", "coredump"],
    &["slow", "latency", "lag", "sluggish"],
    &["hang", "stall", "freeze", "stuck", "unresponsive", "deadlock"],
    &["dependency", "package", "crate", "library"],
    &["build", "compile"],
    &["credential", "secret", "token", "password", "apikey"],
    &["delete", "remove", "erase", "purge"],
    &["start", "boot", "startup"],
    &["stop", "halt", "terminate", "kill", "shutdown"],
    &["restart", "reload", "relaunch"],
    &["config", "configuration", "setting", "option"],
    &["environment", "env"],
    &["bug", "defect", "glitch"],
    &["fix", "patch", "repair", "hotfix"],
    &["fast", "quick", "quickly", "rapid", "speedy"],
    &["performance", "perf", "speed", "throughput"],
    &["database", "db", "datastore"],
    &["certificate", "cert", "tls", "ssl"],
    &["permission", "privilege", "acl", "authz"],
    &["auth", "authentication", "login", "signin"],
    &["alert", "notify", "notification", "alarm"],
    &["monitor", "telemetry", "metric", "observability"],
    &["disk", "storage", "drive", "volume"],
    &["cpu", "processor"],
    &["network", "internet", "connectivity"],
    &["timeout", "deadline", "ttl"],
    &["expire", "expiry", "expiration", "lapse"],
    &["document", "doc", "readme", "manual"],
    &["upgrade", "update", "bump"],
    &["old", "stale", "outdated", "obsolete", "legacy"],
    &["duplicate", "dup", "redundant"],
    &["ci", "pipeline", "workflow", "automation"],
    &["job", "task"],
    &["parallel", "concurrent", "simultaneous"],
    &["random", "nondeterministic"],
    &["replay", "reproduce", "repro", "rerun"],
    &["leak", "expose", "disclose"],
    &["large", "big", "huge", "massive"],
    &["small", "tiny", "mini"],
    &["unused", "orphan", "unreferenced", "dead"],
    &["version", "semver"],
    &["backup", "snapshot"],
    &["user", "customer"],
    &["site", "website", "webpage"],
    &["minify", "mangle", "obfuscate", "uglify"],
    &["laptop", "notebook", "workstation"],
    &["install", "setup", "provision"],
    &["wrong", "incorrect", "erroneous"],
    &["missing", "absent", "undefined", "unset"],
    &["connection", "socket"],
    &["repo", "repository", "codebase"],
    &["merge", "integrate"],
    &["flag", "toggle", "featureflag"],
    &["limit", "quota", "cap", "ceiling"],
    &["retry", "reattempt", "backoff"],
    &["wait", "sleep", "pause", "delay"],
    &["validate", "verify", "assert"],
    &["cost", "bill", "spend", "expense", "price"],
    &["reproducible", "deterministic", "hermetic"],
    &["outage", "incident", "downtime"],
    &["traffic", "load"],
    &["artifact", "bundle", "binary", "executable"],
];

#[cfg_attr(not(test), allow(dead_code))]
pub(super) fn group_count() -> usize {
    GROUPS.len()
}

pub(super) fn enabled() -> bool {
    std::env::var("INSTINCT_CONCEPTS").map(|v| v != "0").unwrap_or(true)
}

/// folded word -> group index
fn index() -> &'static HashMap<String, usize> {
    static IDX: OnceLock<HashMap<String, usize>> = OnceLock::new();
    IDX.get_or_init(|| {
        let mut m = HashMap::new();
        for (g, words) in GROUPS.iter().enumerate() {
            for w in *words {
                m.insert(super::fold_word(w), g);
            }
        }
        // fold_word is not a stemmer ("moved" folds to "mov", "move" stays), so a member's plain
        // inflections are keyed too. A listed member always wins over an inflection of another.
        for (g, words) in GROUPS.iter().enumerate() {
            let mut all = Vec::new();
            for w in *words {
                forms(w, &mut all);
            }
            for f in all {
                m.entry(super::fold_word(&f)).or_insert(g);
            }
        }
        m
    })
}

/// Canonical token of an already folded word, or None when it is in no group or concepts are off.
pub(super) fn canon(folded: &str) -> Option<String> {
    if !enabled() {
        return None;
    }
    canon_any(folded)
}

fn canon_any(folded: &str) -> Option<String> {
    index().get(folded).map(|&g| super::fold_word(GROUPS[g][0]))
}

fn forms(w: &str, out: &mut Vec<String>) {
    out.push(w.to_string());
    out.push(format!("{w}s"));
    if let Some(stem) = w.strip_suffix('e') {
        out.push(format!("{w}d"));
        out.push(format!("{stem}ing"));
    } else {
        out.push(format!("{w}ed"));
        out.push(format!("{w}ing"));
    }
}

/// The query followed by the members (and their plain inflections) of every group one of its words is in.
/// Unchanged when concepts are off or no word is in a group.
pub(super) fn expand(query: &str) -> String {
    if !enabled() {
        return query.to_string();
    }
    expand_any(query)
}

fn expand_any(query: &str) -> String {
    let mut seen: Vec<usize> = Vec::new();
    for w in super::tokens(query) {
        if let Some(&g) = index().get(&super::fold_word(&w)) {
            if !seen.contains(&g) {
                seen.push(g);
            }
        }
    }
    if seen.is_empty() {
        return query.to_string();
    }
    let mut extra: Vec<String> = Vec::new();
    for g in seen {
        for w in GROUPS[g] {
            forms(w, &mut extra);
        }
    }
    format!("{query} {}", extra.join(" "))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn each_word_is_in_one_group() {
        let mut seen: HashMap<String, usize> = HashMap::new();
        for (g, words) in GROUPS.iter().enumerate() {
            assert!(words.len() >= 2, "group {g} is a single word");
            for w in *words {
                let f = super::super::fold_word(w);
                assert!(seen.insert(f.clone(), g).is_none(), "{w} ({f}) is in two groups");
            }
        }
        assert!((40..=80).contains(&group_count()), "{} groups", group_count());
    }

    #[test]
    fn synonyms_share_a_canonical_token() {
        let c = |w: &str| canon_any(&super::super::fold_word(w));
        for (a, b) in [
            ("ram", "memory"),
            ("pods", "containers"),
            ("revert", "rollback"),
            ("moved", "renamed"),
            ("airgapped", "offline"),
            ("red", "failing"),
            ("shipping", "deploys"),
        ] {
            assert!(c(a).is_some() && c(a) == c(b), "{a} vs {b}");
        }
        assert_eq!(c("dinner"), None);
        assert_eq!(c("landing"), None);
    }

    #[test]
    fn expansion_adds_only_group_members() {
        let q = expand_any("Containers keep getting killed");
        assert!(q.starts_with("Containers keep getting killed"));
        assert!(q.contains(" pod ") && q.contains(" docker"));
        assert!(!q.contains(" memory"));
        assert_eq!(expand_any("Plan a trip to Lisbon"), "Plan a trip to Lisbon");
    }
}