//! Instinct: situation-triggered recall of discoveries and their methods.
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::{BufRead, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::process;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
mod demo;
mod guide;
mod case_learning;
mod case_experiment;
mod codex_cell;
mod replay_lesson;
mod audit;
mod doctor;
mod codex_trust;
mod learn;
mod connect;
mod connect_mcp;
mod waits;
mod leftovers;
mod brief;
mod brief_action;
mod concepts;
mod unicode_words;
#[allow(dead_code)]
mod consolidation;
mod gates;
mod targets;
mod guard;
mod session;
mod continuation;
mod corrections;
mod outcomes;
mod meter;
mod speed;
mod speed_import;
mod eval;
mod mine;
mod scan;
#[allow(dead_code)]
mod last_turn;
mod starter;
mod rehearsal;
mod trust;
mod check;
mod tripwire;
mod fix;
use rehearsal::StandingInstruction;
#[allow(dead_code)]
mod eligibility;
#[allow(dead_code)]
mod helix_db;
#[allow(dead_code)]
mod journal;
#[allow(dead_code)]
mod recall_index;
// A browser has no filesystem: the verified index snapshot exists only in the native engine.
#[cfg(not(target_arch = "wasm32"))]
#[allow(dead_code)]
mod snapshot;
#[allow(dead_code)]
mod sync;
mod team;
#[cfg(not(target_arch = "wasm32"))]
#[allow(dead_code)]
mod serve_http;
#[cfg(not(target_arch = "wasm32"))]
mod serve;
use journal::append;
const DEFAULT_MODEL: &str = "nomic-embed-text";
const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
const IO_TIMEOUT: Duration = Duration::from_secs(60);
const MAX_RESPONSE: usize = 16 * 1024 * 1024;
const MAX_EMBED_BYTES: usize = 6000;
// ---------------------------------------------------------------- JSON
#[derive(Debug, Clone, PartialEq)]
enum Json {
Null,
Bool(bool),
Num(f64),
Str(String),
Arr(Vec<Json>),
Obj(Vec<(String, Json)>),
}
impl Json {
fn get(&self, key: &str) -> Option<&Json> {
match self {
Json::Obj(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
}
}
fn as_str(&self) -> Option<&str> {
match self {
Json::Str(s) => Some(s),
_ => None,
}
}
fn as_f64(&self) -> Option<f64> {
match self {
Json::Num(n) => Some(*n),
_ => None,
}
}
}
/// Escape `s` as the body of a JSON string (no surrounding quotes).
fn escape_json(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\u{08}' => out.push_str("\\b"),
'\u{0c}' => out.push_str("\\f"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out
}
struct Parser<'a> {
b: &'a [u8],
i: usize,
}
impl<'a> Parser<'a> {
fn ws(&mut self) {
while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\t' | b'\n' | b'\r') {
self.i += 1;
}
}
fn eat(&mut self, c: u8) -> Result<(), String> {
self.ws();
if self.b.get(self.i) == Some(&c) {
self.i += 1;
Ok(())
} else {
Err(format!("expected '{}' at byte {}", c as char, self.i))
}
}
fn lit(&mut self, word: &str, v: Json) -> Result<Json, String> {
if self.b[self.i..].starts_with(word.as_bytes()) {
self.i += word.len();
Ok(v)
} else {
Err(format!("bad literal at byte {}", self.i))
}
}
fn value(&mut self) -> Result<Json, String> {
self.ws();
match self.b.get(self.i) {
None => Err("unexpected end of JSON".into()),
Some(b'{') => {
self.i += 1;
let mut fields = Vec::new();
self.ws();
if self.b.get(self.i) == Some(&b'}') {
self.i += 1;
return Ok(Json::Obj(fields));
}
loop {
self.ws();
let k = self.string()?;
self.eat(b':')?;
fields.push((k, self.value()?));
self.ws();
match self.b.get(self.i) {
Some(b',') => self.i += 1,
Some(b'}') => {
self.i += 1;
return Ok(Json::Obj(fields));
}
_ => return Err(format!("expected ',' or '}}' at byte {}", self.i)),
}
}
}
Some(b'[') => {
self.i += 1;
let mut items = Vec::new();
self.ws();
if self.b.get(self.i) == Some(&b']') {
self.i += 1;
return Ok(Json::Arr(items));
}
loop {
items.push(self.value()?);
self.ws();
match self.b.get(self.i) {
Some(b',') => self.i += 1,
Some(b']') => {
self.i += 1;
return Ok(Json::Arr(items));
}
_ => return Err(format!("expected ',' or ']' at byte {}", self.i)),
}
}
}
Some(b'"') => Ok(Json::Str(self.string()?)),
Some(b't') => self.lit("true", Json::Bool(true)),
Some(b'f') => self.lit("false", Json::Bool(false)),
Some(b'n') => self.lit("null", Json::Null),
Some(_) => self.number(),
}
}
fn number(&mut self) -> Result<Json, String> {
let start = self.i;
while self.i < self.b.len()
&& matches!(
self.b[self.i],
b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E'
)
{
self.i += 1;
}
std::str::from_utf8(&self.b[start..self.i])
.ok()
.and_then(|t| t.parse::<f64>().ok())
.map(Json::Num)
.ok_or_else(|| format!("bad number at byte {start}"))
}
fn hex4(&mut self) -> Result<u32, String> {
let h = self
.b
.get(self.i..self.i + 4)
.ok_or("truncated \\u escape")?;
let v = std::str::from_utf8(h)
.ok()
.and_then(|t| u32::from_str_radix(t, 16).ok())
.ok_or("bad \\u escape")?;
self.i += 4;
Ok(v)
}
fn string(&mut self) -> Result<String, String> {
if self.b.get(self.i) != Some(&b'"') {
return Err(format!("expected string at byte {}", self.i));
}
self.i += 1;
let mut out: Vec<u8> = Vec::new();
loop {
let c = *self.b.get(self.i).ok_or("unterminated string")?;
self.i += 1;
match c {
b'"' => break,
b'\\' => {
let e = *self.b.get(self.i).ok_or("unterminated escape")?;
self.i += 1;
let ch = match e {
b'"' => '"',
b'\\' => '\\',
b'/' => '/',
b'n' => '\n',
b'r' => '\r',
b't' => '\t',
b'b' => '\u{08}',
b'f' => '\u{0c}',
b'u' => {
let mut cp = self.hex4()?;
if (0xD800..0xDC00).contains(&cp)
&& self.b[self.i..].starts_with(b"\\u")
{
self.i += 2;
let lo = self.hex4()?;
if !(0xDC00..0xE000).contains(&lo) {
return Err("bad surrogate pair".into());
}
cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
}
char::from_u32(cp).ok_or("invalid code point")?
}
_ => return Err(format!("bad escape '\\{}'", e as char)),
};
let mut buf = [0u8; 4];
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
}
_ => out.push(c),
}
}
String::from_utf8(out).map_err(|_| "invalid UTF-8 in string".to_string())
}
}
fn parse_json(text: &str) -> Result<Json, String> {
let mut p = Parser {
b: text.as_bytes(),
i: 0,
};
let v = p.value()?;
p.ws();
if p.i != p.b.len() {
return Err(format!("trailing data at byte {}", p.i));
}
Ok(v)
}
fn json_floats(v: &Json) -> Option<Vec<f32>> {
match v {
Json::Arr(items) => items.iter().map(|n| n.as_f64().map(|f| f as f32)).collect(),
_ => None,
}
}
// ---------------------------------------------------------------- embeddings over raw HTTP
/// Decode an HTTP/1.1 chunked body.
fn dechunk(mut body: &[u8]) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
loop {
let nl = body
.windows(2)
.position(|w| w == b"\r\n")
.ok_or("bad chunk framing")?;
let size_txt = std::str::from_utf8(&body[..nl]).map_err(|_| "bad chunk size")?;
let size = usize::from_str_radix(size_txt.split(';').next().unwrap_or("").trim(), 16)
.map_err(|_| "bad chunk size")?;
body = &body[nl + 2..];
if size == 0 {
return Ok(out);
}
if body.len() < size + 2 {
return Err("truncated chunk".into());
}
out.extend_from_slice(&body[..size]);
body = &body[size + 2..];
}
}
/// POST `body` as JSON to `path` on `addr`; returns the response body on HTTP 200.
fn http_post_json(addr: &str, path: &str, body: &str) -> Result<String, String> {
let sock = addr
.to_socket_addrs()
.map_err(|e| format!("cannot resolve {addr}: {e}"))?
.next()
.ok_or_else(|| format!("no address for {addr}"))?;
let mut s = TcpStream::connect_timeout(&sock, CONNECT_TIMEOUT)
.map_err(|e| format!("cannot connect to {addr}: {e}"))?;
let _ = s.set_read_timeout(Some(IO_TIMEOUT));
let _ = s.set_write_timeout(Some(IO_TIMEOUT));
let req = format!(
"POST {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
s.write_all(req.as_bytes())
.map_err(|e| format!("send to {addr} failed: {e}"))?;
let mut raw = Vec::new();
s.take(MAX_RESPONSE as u64)
.read_to_end(&mut raw)
.map_err(|e| format!("read from {addr} failed: {e}"))?;
let split = raw
.windows(4)
.position(|w| w == b"\r\n\r\n")
.ok_or("malformed HTTP response")?;
let head = String::from_utf8_lossy(&raw[..split]).to_string();
let status = head.lines().next().unwrap_or("");
let payload = &raw[split + 4..];
let chunked = head.lines().any(|l| {
let l = l.to_ascii_lowercase();
l.starts_with("transfer-encoding:") && l.contains("chunked")
});
let bytes = if chunked {
dechunk(payload)?
} else {
payload.to_vec()
};
let text = String::from_utf8(bytes).map_err(|_| "response is not UTF-8".to_string())?;
if status.split_whitespace().nth(1) != Some("200") {
return Err(format!(
"{addr}{path} answered '{status}': {}",
text.chars().take(200).collect::<String>()
));
}
Ok(text)
}
/// Pull the single vector out of `{"embeddings":[[f32,...]]}`.
fn parse_embedding(response: &str) -> Result<Vec<f32>, String> {
let v = parse_json(response)?;
if let Some(err) = v.get("error").and_then(Json::as_str) {
return Err(format!("ollama error: {err}"));
}
let emb = match v.get("embeddings") {
Some(Json::Arr(rows)) if rows.len() == 1 => json_floats(&rows[0]),
_ => None,
}
.ok_or("response has no single numeric \"embeddings\" row")?;
if emb.is_empty() || emb.iter().any(|f| !f.is_finite()) {
return Err("embedding is empty or non-finite".into());
}
Ok(emb)
}
/// Cut `s` to at most `max` bytes without splitting a UTF-8 character.
fn truncate_utf8(s: &str, max: usize) -> &str {
if s.len() <= max {
return s;
}
let mut end = max;
while !s.is_char_boundary(end) {
end -= 1;
}
&s[..end]
}
/// Embed `text` under a nomic task prefix (`search_document: ` on add, `search_query: ` on recall).
/// Without the prefixes nomic similarities run ~0.15 low.
fn embed(prefix: &str, text: &str) -> Result<Vec<f32>, String> {
let addr = std::env::var("INSTINCT_OLLAMA").map_err(|_| "optional embeddings disabled")?;
let model = env_or("INSTINCT_EMBED_MODEL", DEFAULT_MODEL);
let input = format!("{prefix}{}", truncate_utf8(text, MAX_EMBED_BYTES));
let body = format!(
"{{\"model\":\"{}\",\"input\":[\"{}\"]}}",
escape_json(&model),
escape_json(&input)
);
let resp = http_post_json(&addr, "/api/embed", &body)?;
parse_embedding(&resp)
}
fn cosine(a: &[f32], b: &[f32]) -> f32 {
if a.len() != b.len() || a.is_empty() {
return 0.0;
}
let (mut dot, mut na, mut nb) = (0.0f32, 0.0f32, 0.0f32);
for (x, y) in a.iter().zip(b) {
dot += x * y;
na += x * x;
nb += y * y;
}
let denom = na.sqrt() * nb.sqrt();
if denom == 0.0 || !denom.is_finite() {
return 0.0;
}
dot / denom
}
// ---------------------------------------------------------------- lexical (BM25) + fusion
const RRF_K: f32 = 60.0;
/// Lowercase alphanumeric/underscore words of >= 2 chars — keeps code identifiers (snake_case) whole.
fn tokens(s: &str) -> Vec<String> {
unicode_words::tokens(s)
}
/// Okapi BM25 (k1=1.2, b=0.75) of `query` against each document.
fn bm25(query: &str, docs: &[String]) -> Vec<f32> {
use std::borrow::Cow;
use std::collections::HashMap;
let mut terms = tokens(query);
terms.sort();
terms.dedup();
if terms.is_empty() || docs.is_empty() {
return vec![0.0; docs.len()];
}
let indices: HashMap<&str, usize> = terms
.iter()
.enumerate()
.map(|(i, term)| (term.as_str(), i))
.collect();
let mut df = vec![0usize; terms.len()];
let mut total_length = 0usize;
let mut corpus = Vec::with_capacity(docs.len());
// Only query terms can contribute to the score. Count them in one pass,
// preserving document lengths and the original sorted-term summation order.
for doc in docs {
let mut length = 0usize;
let mut counts = HashMap::new();
let normalized = unicode_words::normalized(doc);
for word in normalized.split(|c: char| !(c.is_alphanumeric() || c == '_')) {
if word.chars().nth(1).is_none() {
continue;
}
length += 1;
let lower: Cow<'_, str> =
if word.is_ascii() && !word.bytes().any(|b| b.is_ascii_uppercase()) {
Cow::Borrowed(word)
} else {
Cow::Owned(word.to_lowercase())
};
if let Some(&index) = indices.get(lower.as_ref()) {
*counts.entry(index).or_insert(0usize) += 1;
}
}
let mut matched: Vec<_> = counts.into_iter().collect();
matched.sort_unstable_by_key(|&(i, _)| i);
for &(i, _) in &matched {
df[i] += 1;
}
total_length += length;
corpus.push((length, matched));
}
let n = docs.len() as f32;
let avgdl = (total_length as f32 / n).max(1.0);
let idf: Vec<_> = df
.into_iter()
.map(|d| {
let d = d as f32;
((n - d + 0.5) / (d + 0.5) + 1.0).ln()
})
.collect();
corpus
.into_iter()
.map(|(length, matched)| {
matched
.into_iter()
.map(|(i, count)| {
let tf = count as f32;
idf[i] * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * length as f32 / avgdl))
})
.sum()
})
.collect()
}
/// Rank positions (0 = best) of the items with a positive score, best first.
fn ranking(scores: &[f32]) -> Vec<usize> {
let mut idx: Vec<usize> = (0..scores.len()).filter(|&i| scores[i] > 0.0).collect();
idx.sort_by(|&a, &b| {
scores[b]
.partial_cmp(&scores[a])
.unwrap_or(std::cmp::Ordering::Equal)
});
idx
}
// ---------------------------------------------------------------- store
#[derive(Clone)]
struct Discovery {
id: String,
ts: u64,
title: String,
when: String,
found: String,
how: String,
evidence: String,
reconsider: String,
tags: String,
embedding: Vec<f32>,
hits: u32,
misses: u32,
outcomes: HashMap<String, Option<bool>>,
standing: Option<StandingInstruction>,
casebook: Option<case_learning::Casebook>,
meta: eligibility::Meta,
}
fn apply_meta(m: &mut eligibility::Meta, v: &Json) {
for (key, dest) in [
("source", &mut m.source),
("state", &mut m.state),
("evidence_status", &mut m.evidence_status),
("scope_project", &mut m.project),
("scope_persona", &mut m.persona),
("scope_harness", &mut m.harness),
("scope_version", &mut m.version),
("scope_machine", &mut m.machine),
] {
if let Some(s) = v.get(key).and_then(Json::as_str) {
*dest = s.to_string();
}
}
if let Some(n) = v.get("valid_until").and_then(Json::as_f64) {
m.valid_until = n as u64;
}
}
fn meta_from(v: &Json) -> eligibility::Meta {
let mut m = eligibility::Meta::default();
apply_meta(&mut m, v);
m
}
fn quiet_ids(_path: &PathBuf) -> HashSet<String> {
let labels = std::env::var("INSTINCT_LABELS").ok();
let mut counts = std::collections::HashMap::<String, (u32, u32)>::new();
if let Some(text) = labels.and_then(|p| fs::read_to_string(p).ok()) {
for line in text.lines() {
if let Ok(v) = parse_json(line) {
let id = v.get("id").and_then(Json::as_str).unwrap_or("");
if id.is_empty() {
continue;
}
let e = counts.entry(id.to_string()).or_default();
match v.get("verdict").and_then(Json::as_str).unwrap_or("") {
"helped" | "guarded" => e.0 += 1,
"irrelevant" | "misled" => e.1 += 1,
_ => {}
}
}
}
}
counts
.into_iter()
.filter(|(_, (u, i))| eligibility::quiet(*u, *i))
.map(|(id, _)| id)
.collect()
}
impl Discovery {
/// v2 2026-11-04 (lever-1, handover from cc-c9d58ab5): boost `when` 3× in the BM25 corpus.
/// Recall @1 was 34.5 % because BM25 scored prose in `found`/`how` higher than the one field
/// that actually describes the trigger context — `when`. Keep `found`+`how` so semantic phrase
/// matches still land; triple `when` so prompt-text queries hit the right instinct more often.
/// Embeddings computed on `d.text()` are cached per-entry; a `reembed` is needed to realign
/// the semantic side (BM25 benefits immediately on next query).
fn text(&self) -> String {
format!(
"{w} {w} {w} {t} {tg} {f} {h}",
w = self.when,
t = self.title,
tg = self.tags,
f = self.found,
h = self.how
)
}
/// 0.3.0-whenkey (2026-11-04): the BM25 side keys on the one-sentence `when` (ReasoningBank: the
/// description IS the recall key). Field weights are env-tunable for benching — INSTINCT_W_WHEN
/// (default 3) and INSTINCT_W_TITLE (default 1) — and `text()` above stays as the embedding input,
/// so every stored vector remains aligned. With the defaults this equals `text()`.
fn lex_text(&self) -> String {
let (ww, wt, body) = lex_weights();
let mut s = String::with_capacity(
self.when.len() * ww + self.title.len() * wt + self.found.len() + self.how.len() + 16,
);
for _ in 0..ww {
s.push_str(&self.when);
s.push(' ');
}
for _ in 0..wt {
s.push_str(&self.title);
s.push(' ');
}
s.push_str(&self.tags);
s.push(' ');
if body == 1 {
s.push_str(&self.found);
s.push(' ');
s.push_str(&self.how);
}
s
}
fn proven_in_use(&self) -> bool {
self.hits >= 2 && self.strength() >= 0.6
}
/// Laplace-smoothed payoff rate: 0.5 for a fresh entry, -> 1.0 as recalls keep paying off.
fn strength(&self) -> f32 {
eligibility::strength(self.hits, self.misses)
}
fn to_line(&self) -> String {
let emb: Vec<String> = self.embedding.iter().map(|f| f.to_string()).collect();
// Older engines ignore the new record kind rather than using a machine-only
// method on an unknown host. Portable discoveries keep their original kind.
let kind = if self.meta.machine.is_empty() {
"discovery"
} else {
"machine_discovery"
};
let base = format!(
"{{\"kind\":\"{kind}\",\"id\":\"{}\",\"ts\":{},\"title\":\"{}\",\"when\":\"{}\",\"found\":\"{}\",\"how\":\"{}\",\"evidence\":\"{}\",\"tags\":\"{}\",\"reconsider\":\"{}\",\"embedding\":[{}]}}",
escape_json(&self.id), self.ts, escape_json(&self.title), escape_json(&self.when), escape_json(&self.found),
escape_json(&self.how), escape_json(&self.evidence), escape_json(&self.tags), escape_json(&self.reconsider), emb.join(",")
);
format!("{},\"source\":\"{}\",\"state\":\"{}\",\"evidence_status\":\"{}\",\"scope_project\":\"{}\",\"scope_persona\":\"{}\",\"scope_harness\":\"{}\",\"scope_version\":\"{}\",\"scope_machine\":\"{}\",\"valid_until\":{}}}",
base.trim_end_matches('}'), escape_json(&self.meta.source), escape_json(&self.meta.state), escape_json(&self.meta.evidence_status),
escape_json(&self.meta.project),escape_json(&self.meta.persona),escape_json(&self.meta.harness),escape_json(&self.meta.version),escape_json(&self.meta.machine),self.meta.valid_until)
}
}
fn env_or(key: &str, default: &str) -> String {
std::env::var(key)
.ok()
.filter(|v| !v.is_empty())
.unwrap_or_else(|| default.to_string())
}
/// Where the bank lives when nothing says otherwise: `$INSTINCT_STORE`, else `$XDG_DATA_HOME/instinct/bank.hxdb`,
/// else `~/.local/share/instinct/bank.hxdb` (Unix) or `%LOCALAPPDATA%\instinct\bank.hxdb` (Windows).
pub(crate) fn default_store() -> Result<PathBuf, String> {
let set = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
if let Some(p) = set("INSTINCT_STORE") {
return Ok(p);
}
let base = if cfg!(windows) {
set("LOCALAPPDATA")
} else {
set("XDG_DATA_HOME")
.filter(|p| p.is_absolute())
.or_else(|| set("HOME").map(|h| h.join(".local").join("share")))
};
base.map(|b| b.join("instinct").join("bank.hxdb"))
.ok_or_else(|| "no home directory found; set INSTINCT_STORE to a bank file path".into())
}
fn store_path(a: &Args) -> Result<PathBuf, String> {
match a.opt("store") {
Some(p) => Ok(PathBuf::from(p)),
None => default_store(),
}
}
/// Create the default bank's folder (0700 on Unix). Explicit stores are the caller's to manage.
pub(crate) fn ensure_default_dir(path: &std::path::Path) -> Result<(), String> {
let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty() && !d.exists()) else {
return Ok(());
};
let mut b = std::fs::DirBuilder::new();
b.recursive(true);
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700);
b.create(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))
}
/// Set by the commands that run once and exit (`prompt`, `guard`, `recall`).
#[allow(dead_code)]
static ONE_SHOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// The three field weights that shape the lexical text (`when` repeats, title repeats, body on or off).
/// The index snapshot is keyed on them, so a bench that changes one never reads a stale token list.
fn lex_weights() -> (usize, usize, usize) {
let ww = env_or("INSTINCT_W_WHEN", "3").parse::<usize>().unwrap_or(3).clamp(0, 12);
let wt = env_or("INSTINCT_W_TITLE", "1").parse::<usize>().unwrap_or(1).clamp(0, 12);
let body = env_or("INSTINCT_W_BODY", "1").parse::<usize>().unwrap_or(1).clamp(0, 1);
(ww, wt, body)
}
/// A cold load that leaves a verified index snapshot behind for the next `prompt`, `guard` or `recall`.
fn load(path: &PathBuf) -> Result<Vec<Discovery>, String> {
#[cfg(not(target_arch = "wasm32"))]
let key = snapshot::key(path);
let all = load_plain(path)?;
#[cfg(not(target_arch = "wasm32"))]
if let Some(key) = &key {
snapshot::store(path, key, &all);
}
Ok(all)
}
/// Every lesson a read-only command shows: the user's bank, then the project bank's (`.instinct/lessons.jsonl`
/// above the cwd) when one exists. Each is folded on its own; an id in both stays the user's.
fn load_view(path: &PathBuf) -> Result<Vec<Discovery>, String> {
let mut all = load(path)?;
if let Some(shared) = team::find(path) {
let have: HashSet<String> = all.iter().map(|d| d.id.clone()).collect();
match team::load_indexed(&shared) {
Ok(more) => all.extend(more.into_iter().filter(|d| !have.contains(&d.id))),
Err(e) => eprintln!("instinct: project bank {} not used ({e})", shared.display()),
}
}
Ok(all)
}
/// Fold the append-only event log: discovery lines create entries, hit/miss lines count against them.
/// This is the cold load without the snapshot write, for commands that append straight after reading.
fn load_plain(path: &PathBuf) -> Result<Vec<Discovery>, String> {
fold_bank(path, |_, _, _| {})
}
fn fold_bank(path: &PathBuf, mut observe: impl FnMut(&str, u64, bool)) -> Result<Vec<Discovery>, String> {
fold_bank_verified(path, |id, ts, hit, _| observe(id, ts, hit))
}
fn fold_bank_verified(path: &PathBuf, observe: impl FnMut(&str, u64, bool, u8)) -> Result<Vec<Discovery>, String> {
let text = journal::read(path)?;
fold_text(&text, &path.display().to_string(), observe)
}
/// The fold itself, over journal text. `label` names the source in a row error.
fn fold_text(text: &str, label: &str, observe: impl FnMut(&str, u64, bool, u8)) -> Result<Vec<Discovery>, String> {
fold_text_for_bank(text, label, observe, None)
}
fn fold_text_for_bank(text: &str, label: &str, observe: impl FnMut(&str, u64, bool, u8), case_target: Option<&str>) -> Result<Vec<Discovery>, String> {
let mut out: Vec<Discovery> = Vec::new();
let mut superseded = HashMap::new();
let mut retired = HashSet::new();
let mut directly_banked = Vec::new();
let personal = !is_team_bank(Path::new(label));
let mut history: HashMap<usize, Vec<consolidation::Mark>> = HashMap::new();
// id -> position in `out`: every event row resolves its discovery in O(1) instead of a linear scan
// (0.2.2: the scans cost ~6M string compares per load at 5.4k rows; dedupe added another ~2M).
let mut idx: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
for (n, line) in text
.lines()
.enumerate()
.filter(|(_, l)| !l.trim().is_empty())
{
let v = parse_json(line).map_err(|e| format!("{label}:{}: {e}", n + 1))?;
let s = |k: &str| v.get(k).and_then(Json::as_str).unwrap_or("").to_string();
match v.get("kind").and_then(Json::as_str) {
// 0.2.1-dedupe (2026-11-03): a block of 12 discovery rows was written twice. With a plain push the
// `embed` merge below (first match) only reached the first copy, so `reembed` re-embedded the
// empty second copy on every heal tick (273 embed rows per id, heal stuck at 1973/1980).
// First row wins; a later copy of the same id only donates its vector when the first has none.
Some(kind @ ("discovery" | "machine_discovery")) => {
if kind == "machine_discovery" && s("scope_machine").trim().is_empty() {
return Err(format!(
"machine discovery missing its machine at row {}",
n + 1
));
}
let d = Discovery {
id: s("id"),
ts: v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64,
title: s("title"),
when: s("when"),
found: s("found"),
how: s("how"),
evidence: s("evidence"),
reconsider: s("reconsider"),
tags: s("tags"),
embedding: v.get("embedding").and_then(json_floats).unwrap_or_default(),
hits: 0,
misses: 0,
outcomes: HashMap::new(),
standing: None,
casebook: None,
meta: meta_from(&v),
};
if let Some(&i) = idx.get(&d.id) {
if out[i].embedding.is_empty() && !d.embedding.is_empty() {
out[i].embedding = d.embedding;
}
} else {
directly_banked.push(d.meta.source == "banked");
idx.insert(d.id.clone(), out.len());
out.push(d);
}
}
Some("casebook") if personal => {
let id = s("id");
if let Some(&i) = idx.get(&id) {
let d = &mut out[i];
// A peer may have observed this case before our quarantine or retirement.
// Keep the bound history, then gate the folded view on its final eligibility.
if directly_banked[i] && d.meta.source == "banked"
&& v.get("binding").and_then(Json::as_str) == Some(&check::feedback::fingerprint(d))
{
let added = v.get("casebook").ok_or_else(|| "missing casebook".to_owned())
.and_then(case_learning::Casebook::parse)
.and_then(|add| match &d.casebook {
Some(current) => current.merge(&add),
None => Ok(add),
})
.map_err(|e| format!("{label}:{}: {e}", n + 1))?;
d.casebook = Some(added);
}
}
}
Some(k @ ("hit" | "miss")) => {
let id = s("id");
if let Some(&i) = idx.get(&id) {
let hit = k == "hit";
let key = s("outcome_id");
if !key.is_empty() {
match out[i].outcomes.entry(key.clone()) {
std::collections::hash_map::Entry::Vacant(slot) => {
slot.insert(Some(hit));
}
std::collections::hash_map::Entry::Occupied(_) => continue,
}
}
history.entry(i).or_default().push(consolidation::Mark {
ts: v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64,
hit,
key,
withdrawn: false,
verification: check::feedback::provenance(&v, &out[i]),
});
}
}
Some("review") => {
if let Some(&i) = idx.get(&s("id")) {
let d = &mut out[i];
let previous = d.meta.clone();
apply_meta(&mut d.meta, &v);
if d.meta.state == "quarantined"
|| d.meta.evidence_status == "contradicted"
|| d.meta.source != "banked"
|| scope_identity(&d.meta) != scope_identity(&previous)
{
d.standing = None;
}
if d.meta.source != previous.source || d.meta.valid_until != previous.valid_until
|| scope_identity(&d.meta) != scope_identity(&previous)
{
d.casebook = None;
}
}
}
Some("standing_instruction") => {
if let Some(&i) = idx.get(&s("id")) {
let d = &mut out[i];
let text = s("instruction");
let reference = s("source_ref");
if d.meta.source == "banked"
&& !d.meta.project.is_empty()
&& d.meta.project == s("scope_project")
&& d.meta.persona == s("scope_persona")
&& d.meta.state != "quarantined"
&& d.meta.evidence_status != "contradicted"
{
d.standing = match s("action").as_str() {
"clear" => None,
"set" if !text.trim().is_empty() && !reference.trim().is_empty() => {
Some(StandingInstruction { text, reference })
}
_ => {
return Err(format!(
"invalid standing instruction at row {}",
n + 1
))
}
};
}
}
}
// A near-duplicate merged into a canonical lesson (consolidate): its hits/misses move to `by`, it leaves recall.
Some("supersede") => {
if let Some(&i) = idx.get(&s("id")) {
out[i].standing = None;
}
consolidation::supersede(&mut superseded, s("id"), s("by"));
}
Some("unsupersede") => {
let id = s("id");
superseded.remove(&id);
}
// Curated out from its wiki page (lapis-instinct-pages `curation: retire`): history stays, it leaves recall.
Some("retire") => {
if let Some(&i) = idx.get(&s("id")) {
out[i].standing = None;
}
retired.insert(s("id"));
}
Some("unretire") => {
let id = s("id");
retired.remove(&id);
}
// Cancels one earlier hit/miss (wrong-argument marks); history stays append-only.
Some("retract") => {
if let Some(marks) = idx.get(&s("id")).and_then(|i| history.get_mut(i)) {
match s("of").as_str() {
"hit" => consolidation::retract(marks, true),
"miss" => consolidation::retract(marks, false),
_ => {}
}
}
}
// A later embedding for an entry banked while Ollama was down (written by `reembed`).
Some("embed") => {
let id = s("id");
if let (Some(&i), Some(e)) =
(idx.get(&id), v.get("embedding").and_then(json_floats))
{
if !e.is_empty() {
out[i].embedding = e
}
}
}
_ => {}
}
}
if case_target.is_some_and(|id| retired.contains(id) || superseded.contains_key(id) || idx.get(id).is_some_and(|&i| !directly_banked[i])) {
return Err("cases require an active directly banked personal lesson".into());
}
consolidation::finish(&mut out, &idx, &superseded, &retired, history, observe);
for d in &mut out {
if d.casebook.is_some() && !accepts_casebook(&d.meta, now_secs()) {
d.casebook = None;
}
}
Ok(out)
}
// wasm32-unknown-unknown has no clock (SystemTime::now traps): the browser host supplies it.
#[cfg(target_arch = "wasm32")]
fn now_secs() -> u64 {
playground_api::clock()
}
#[cfg(not(target_arch = "wasm32"))]
fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
/// Short stable id: FNV-1a over title+found, base36, prefixed "in-".
fn make_id(title: &str, found: &str) -> String {
let mut h: u64 = 0xcbf29ce484222325;
for b in title.bytes().chain([0u8]).chain(found.bytes()) {
h ^= b as u64;
h = h.wrapping_mul(0x100000001b3);
}
let mut s = String::new();
let mut x = h;
for _ in 0..7 {
s.push(b"0123456789abcdefghijklmnopqrstuvwxyz"[(x % 36) as usize] as char);
x /= 36;
}
format!("in-{s}")
}
// ---------------------------------------------------------------- args
struct Args {
pos: Vec<String>,
kv: Vec<(String, String)>,
}
impl Args {
fn parse(argv: &[String]) -> Args {
let (mut pos, mut kv) = (Vec::new(), Vec::new());
let mut i = 0;
while i < argv.len() {
if let Some(k) = argv[i].strip_prefix("--") {
if let Some((key, value)) = k.split_once('=') {
kv.push((key.to_string(), value.to_string()));
i += 1;
continue;
}
// 0.3.0-whenkey: a `--switch` directly followed by another `--key` (or nothing) is a bare
// switch and consumes no value — before this, `--fold --threshold 0.95` ate `--threshold`
// and `--fold --apply` lost `--apply`. A value of "-" (stdin) is still a value.
let next = argv.get(i + 1);
if next.map_or(true, |n| n.starts_with("--")) {
kv.push((k.to_string(), String::new()));
i += 1;
} else {
kv.push((k.to_string(), next.cloned().unwrap_or_default()));
i += 2;
}
} else {
pos.push(argv[i].clone());
i += 1;
}
}
Args { pos, kv }
}
fn opt(&self, k: &str) -> Option<&str> {
self.kv
.iter()
.rev()
.find(|(key, _)| key == k)
.map(|(_, v)| v.as_str())
}
fn text(&self, k: &str, stdin_used: &mut bool) -> Result<String, String> {
match self.opt(k) {
Some("-") if !*stdin_used => {
*stdin_used = true;
let mut s = String::new();
std::io::stdin()
.read_to_string(&mut s)
.map_err(|e| format!("stdin: {e}"))?;
Ok(s.trim().to_string())
}
Some(v) => Ok(v.to_string()),
None => Ok(String::new()),
}
}
fn num(&self, k: &str, default: usize) -> usize {
self.opt(k).and_then(|v| v.parse().ok()).unwrap_or(default)
}
fn optional_json(&self, key: &str, stdin_used: &mut bool) -> Result<Option<Json>, String> {
let Some(value) = self.opt(key) else { return Ok(None) };
if self.kv.iter().filter(|(k, _)| k == key).count() != 1
|| (value == "-" && (*stdin_used || self.kv.iter().filter(|(_,v)|v=="-").count()!=1)) {
return Err(format!("supply --{key} once, using stdin for at most one field"));
}
let raw = self.text(key, stdin_used)?;
parse_json(&raw).map(Some).map_err(|e| format!("invalid --{key} JSON: {e}"))
}
/// A bare switch (`--apply`): present at all, whatever value the parser paired with it.
fn flag(&self, k: &str) -> bool {
self.kv.iter().any(|(key, _)| key == k)
}
}
// ---------------------------------------------------------------- operations (shared by CLI and MCP)
struct BankIn {
title: String,
when: String,
found: String,
how: String,
evidence: String,
reconsider: String,
tags: String,
project: String,
persona: String,
applicability_harness: String,
applicability_version: String,
applicability_machine: Option<String>,
}
fn scope_identity(meta: &eligibility::Meta) -> [&str; 5] {
[
&meta.project,
&meta.persona,
&meta.harness,
&meta.version,
&meta.machine,
]
}
fn scoped_bank_id(title: &str, found: &str, meta: &eligibility::Meta) -> String {
let scope = scope_identity(meta);
if scope.iter().all(|s| s.is_empty()) {
return make_id(title, found);
}
// JSON supplies unambiguous field boundaries. The original short ID remains
// for unscoped legacy-compatible writes; scoped facts get a separate identity.
let mut fields = vec![title, found, scope[0], scope[1], scope[2], scope[3]];
// Preserve the ID of every portable discovery created before machine scoping.
if !meta.machine.is_empty() {
fields.push(&meta.machine);
}
let body = json_out(&Json::Arr(
fields
.into_iter()
.map(|s| Json::Str(s.to_owned()))
.collect(),
));
let mut hash = 0xcbf29ce484222325u64;
for b in body.bytes() {
hash ^= b as u64;
hash = hash.wrapping_mul(0x100000001b3);
}
format!("in-s{hash:016x}")
}
fn bank_discovery(b: BankIn, context: &eligibility::Scope) -> Result<Discovery, String> {
for (k, v, ex) in [
("title", &b.title, "Count delivered events"),
(
"when",
&b.when,
"Delivery and selection have separate timestamps",
),
(
"found",
&b.found,
"Only two selected items reached the recipient in time",
),
(
"how",
&b.how,
"Join event IDs and compare delivery with decision time",
),
(
"evidence",
&b.evidence,
"Five selected, two received before the decision",
),
] {
if v.trim().is_empty() {
return Err(format!(
"--{k} is required (example: {ex}). A jackpot without its {k} is not reusable."
));
}
}
if b.applicability_machine
.as_ref()
.is_some_and(|alias| alias.trim().is_empty() || alias.trim() != alias)
{
return Err("applicability-machine requires a nonempty alias without leading or trailing whitespace".into());
}
let meta = eligibility::Meta {
source: "banked".into(),
state: "candidate".into(),
evidence_status: "unverified".into(),
project: if b.project.is_empty() {
context.project.clone()
} else {
b.project
},
persona: if b.persona.is_empty() {
context.persona.clone()
} else {
b.persona
},
// Receipt origin and applicability are distinct. Never infer these from
// INSTINCT_HARNESS / INSTINCT_HARNESS_VERSION or the current caller.
harness: b.applicability_harness,
version: b.applicability_version,
machine: b.applicability_machine.unwrap_or_default(),
valid_until: 0,
};
let id = scoped_bank_id(&b.title, &b.found, &meta);
let tags = if b.tags.trim().is_empty() { title_tag(&b.title) } else { b.tags };
Ok(Discovery {
id,
ts: now_secs(),
title: b.title,
when: b.when,
found: b.found,
how: b.how,
evidence: b.evidence,
reconsider: b.reconsider,
tags,
embedding: Vec::new(),
hits: 0,
misses: 0,
outcomes: HashMap::new(),
standing: None,
casebook: None,
meta,
})
}
fn bank_scope_note(meta: &eligibility::Meta) -> String {
let missing: Vec<_> = [
("project", &meta.project),
("persona", &meta.persona),
("applicability harness", &meta.harness),
("applicability version", &meta.version),
("applicability machine", &meta.machine),
]
.iter()
.filter(|(_, v)| v.is_empty())
.map(|(k, _)| *k)
.collect();
format!(
"new lesson, strength 0.50 until hits and misses come in{}",
if missing.is_empty() {
"; scoped to the project, persona, harness, version and machine you gave".into()
} else if missing.len() == 5 {
"; applies in every project (add --project to limit it)".into()
} else {
format!("; not limited by {} (optional)", missing.join(", "))
}
)
}
/// `bank --team`: the project bank above the cwd, which `instinct team init` creates.
fn team_bank_path(user: &PathBuf) -> Result<PathBuf, String> {
if !team::enabled() {
return Err("INSTINCT_TEAM=0 turns the project bank off".into());
}
let bank = team::find(user).ok_or("no project bank above this folder; run `instinct team init` in the repo first")?;
team::ensure_ignore(&bank);
team::WRITING_TEAM.store(true, std::sync::atomic::Ordering::Relaxed);
Ok(bank)
}
fn op_bank(path: &PathBuf, b: BankIn) -> Result<String, String> {
op_bank_as(path, b, "banked")
}
/// Same write with another origin. `instinct mine --apply` banks as "mined", which the engine recalls only after a hit.
fn op_bank_as(path: &PathBuf, b: BankIn, source: &str) -> Result<String, String> {
op_bank_in(path, b, source, &eligibility::env_scope())
}
/// `instinct starter --apply` banks as "community" with an empty scope context, so the pack is portable.
/// A community lesson is not a candidate: it ships reviewed with public evidence, so it can be delivered at once.
fn op_bank_in(path: &PathBuf, b: BankIn, source: &str, context: &eligibility::Scope) -> Result<String, String> {
bank_with_cases(path, b, source, None, context)
}
fn op_bank_cases(path: &PathBuf, b: BankIn, cases: Option<case_learning::Casebook>, context: &eligibility::Scope) -> Result<String, String> {
bank_with_cases(path, b, "banked", cases, context)
}
fn is_team_bank(path: &Path) -> bool {
path.file_name().is_some_and(|file| file == team::FILE)
&& path.parent().and_then(Path::file_name).is_some_and(|dir| dir == team::DIR)
}
fn accepts_casebook(meta: &eligibility::Meta, at: u64) -> bool {
meta.source == "banked" && meta.state != "quarantined" && meta.evidence_status != "contradicted"
&& (meta.valid_until == 0 || at <= meta.valid_until)
}
fn case_event(d: &Discovery, cases: &case_learning::Casebook, ts: u64) -> String {
json_out(&Json::Obj(vec![
("kind".into(), Json::Str("casebook".into())),
("id".into(), Json::Str(d.id.clone())),
("binding".into(), Json::Str(check::feedback::fingerprint(d))),
("ts".into(), Json::Num(ts as f64)),
("casebook".into(), cases.to_json()),
]))
}
fn bank_with_cases(path: &PathBuf, b: BankIn, source: &str, cases: Option<case_learning::Casebook>, context: &eligibility::Scope) -> Result<String, String> {
let mut d0 = bank_discovery(b, context)?;
d0.meta.source = source.into();
if source == "community" {
d0.meta.state = "community".into();
}
let id = d0.id.clone();
let team_write = team::WRITING_TEAM.load(std::sync::atomic::Ordering::Relaxed);
if cases.is_some() && (team_write || is_team_bank(path)) {
return Err("casebooks require a personal bank; --team is unsupported".into());
}
let _lock = journal::identity_lock(path)?;
let on_file = if cases.is_some() {
fold_text_for_bank(&journal::read(path)?, &path.display().to_string(), |_, _, _, _| {}, Some(&id))?
} else if team_write { team::load(path)? } else { load_plain(path)? };
if let Some(existing) = on_file.iter().find(|d| d.id == id) {
if scope_identity(&existing.meta) != scope_identity(&d0.meta) {
return Err(
"bank identity collision across applicability scopes; nothing written".into(),
);
}
if let Some(add) = &cases {
let ts = now_secs();
if !accepts_casebook(&existing.meta, ts) {
return Err("cases require an active directly banked personal lesson".into());
}
d0.meta.valid_until = existing.meta.valid_until;
if check::feedback::fingerprint(existing) != check::feedback::fingerprint(&d0) {
return Err("casebook lesson fields differ from the stored lesson; nothing written".into());
}
if let Some(held) = &existing.casebook {
if held.merge(add)? == *held {
return Ok(format!("already banked: {id}; casebook already recorded"));
}
}
append(path, &case_event(existing, add, ts))?;
return Ok(format!("banked cases for {id}; lesson and feedback preserved"));
}
return Ok(format!(
"already banked: {id}; existing source/status preserved; requested {}",
bank_scope_note(&d0.meta)
));
}
let scope_note = bank_scope_note(&d0.meta);
let embedding = if team_write { Vec::new() } else { embed("search_document: ", &d0.text()).unwrap_or_default() };
// Embeddings are optional and off by default, so only mention them when they were asked for and failed.
let note = if embedding.is_empty() && std::env::var_os("INSTINCT_OLLAMA").is_some() {
" (embedding failed: word recall only for this entry)"
} else {
""
};
d0.embedding = embedding;
let discovery = d0.to_line();
if let Some(add) = &cases {
journal::append_many(path, &[&discovery, &case_event(&d0, add, d0.ts)])?;
} else {
append(path, &discovery)?;
}
Ok(format!("banked {id} ({scope_note}){note}"))
}
fn render(d: &Discovery) -> String {
format!(
"[{}] {} (strength {:.2}, {} hit / {} miss)\n WHEN: {}\n FOUND: {}\n HOW: {}\n EVIDENCE: {}{}",
d.id, d.title, d.strength(), d.hits, d.misses, d.when, d.found, d.how, d.evidence,
[("RECONSIDER", &d.reconsider), ("MACHINE", &d.meta.machine), ("TAGS", &shown_tags(&d.tags))].into_iter().filter(|(_,v)| !v.is_empty()).map(|(k,v)| format!("\n {k}: {v}")).collect::<String>()
)
}
/// Tags as shown to an agent. The `cmd:` matchers that `instinct guard` uses are internal syntax, so they are
/// left out of the rendered lesson. Matching still uses the stored tags unchanged.
fn shown_tags(tags: &str) -> String {
tags.split(';')
.map(str::trim)
.filter(|t| !t.is_empty() && !t.starts_with("cmd:"))
.collect::<Vec<_>>()
.join(";")
}
// ---------------------------------------------------------------- `when` vectors (0.3.0-whenkey)
//
// A second vector per lesson, computed on the one-sentence `when` alone, kept in a SIDECAR
// `<store>.when.bin` (binary ID/vector records), so the main store's format and every 0.2.2
// fixture rule stay byte-identical. Built by `reembed --when` (append-only, only missing ids).
// Recall fuses it as a third RRF list when the sidecar exists; INSTINCT_WHEN_VEC=0 switches it off,
// deleting the sidecar is the full rollback.
/// Sidecar is BINARY (`<store>.when.bin`), append-only records: u16 id_len · id bytes · u16 dim · dim × f32 LE.
/// A text sidecar cost ~1.4 s per recall at 2k rows (measured 2026-11-04) and would breach the deny path's
/// 2 s cap; the binary load is a byte walk (< 10 ms). Rollback = delete the file.
fn when_sidecar(path: &PathBuf) -> PathBuf {
let mut s = path.as_os_str().to_owned();
s.push(".when.bin");
PathBuf::from(s)
}
/// id → `when` vector; later records for the same id win (append-only re-embeds).
fn load_when(path: &PathBuf) -> std::collections::HashMap<String, Vec<f32>> {
let mut out = std::collections::HashMap::new();
let Ok(buf) = fs::read(when_sidecar(path)) else {
return out;
};
let mut p = 0usize;
while p + 4 <= buf.len() {
let il = u16::from_le_bytes([buf[p], buf[p + 1]]) as usize;
p += 2;
if p + il + 2 > buf.len() {
break;
}
let id = String::from_utf8_lossy(&buf[p..p + il]).to_string();
p += il;
let dim = u16::from_le_bytes([buf[p], buf[p + 1]]) as usize;
p += 2;
if p + dim * 4 > buf.len() {
break;
}
let mut v = Vec::with_capacity(dim);
for i in 0..dim {
let o = p + i * 4;
v.push(f32::from_le_bytes([
buf[o],
buf[o + 1],
buf[o + 2],
buf[o + 3],
]));
}
p += dim * 4;
if !v.is_empty() && v.iter().all(|x| x.is_finite()) {
out.insert(id, v);
}
}
out
}
fn append_when(path: &PathBuf, id: &str, v: &[f32]) -> Result<(), String> {
let side = when_sidecar(path);
let mut rec: Vec<u8> = Vec::with_capacity(4 + id.len() + v.len() * 4);
rec.extend_from_slice(&(id.len() as u16).to_le_bytes());
rec.extend_from_slice(id.as_bytes());
rec.extend_from_slice(&(v.len() as u16).to_le_bytes());
for x in v {
rec.extend_from_slice(&x.to_le_bytes());
}
let mut f = journal::private_options()
.create(true)
.append(true)
.open(&side)
.map_err(|e| format!("cannot open {}: {e}", side.display()))?;
f.write_all(&rec)
.map_err(|e| format!("write {} failed: {e}", side.display()))
}
/// Embed `when` for every live entry lacking a when-vector; appends to the sidecar.
fn op_reembed_when(path: &PathBuf) -> Result<String, String> {
let all = load(path)?;
let have = load_when(path);
let todo: Vec<&Discovery> = all
.iter()
.filter(|d| !have.contains_key(&d.id) && !d.when.trim().is_empty())
.collect();
let mut done = 0;
for d in &todo {
let e = embed("search_document: ", &d.when)
.map_err(|e| format!("stopped after {done}/{} ({e})", todo.len()))?;
append_when(path, &d.id, &e)?;
done += 1;
}
Ok(format!(
"when-embedded {done} of {} entries without a when-vector → {}",
todo.len(),
when_sidecar(path).display()
))
}
#[cfg_attr(not(test), allow(dead_code))]
fn op_recall(path: &PathBuf, q: &str, k: usize) -> Result<String, String> {
op_recall_scoped(path, q, k, &eligibility::env_scope())
}
#[cfg_attr(not(test), allow(dead_code))]
fn op_recall_scoped(
path: &PathBuf,
q: &str,
k: usize,
scope: &eligibility::Scope,
) -> Result<String, String> {
op_recall_data(path, q, k, scope).map(|(text, _)| text)
}
// Directly banked discoveries can be tried offline before their first payoff.
fn is_anchor_word(w: &str) -> bool {
w.len() >= 4
&& !matches!(
w,
"with"
| "when"
| "that"
| "this"
| "from"
| "what"
| "which"
| "have"
| "does"
| "need"
| "using"
| "into"
| "were"
| "there"
| "their"
| "they"
| "before"
| "after"
)
}
fn anchors(text: &str) -> HashSet<String> {
tokens(text)
.into_iter()
.filter_map(|w| {
let folded = fold_word(&w);
// A word in a synonym group counts through its canonical token, even a short one (ram, pod).
concepts::canon(&folded).or_else(|| is_anchor_word(&w).then_some(folded))
})
.collect()
}
/// The trigger gate's view of a text: each anchor token with the number of distinct words that map to it.
/// A word outside the synonym groups is its own token with count 1. Words in one group ("test", "suite")
/// share the group's token, and the count keeps them as two words.
fn anchor_counts(text: &str) -> HashMap<String, usize> {
let mut words: HashMap<String, HashSet<String>> = HashMap::new();
for w in tokens(text) {
let folded = fold_word(&w);
let token = match concepts::canon(&folded) {
Some(c) => c,
None if is_anchor_word(&w) => folded.clone(),
None => continue,
};
words.entry(token).or_default().insert(folded);
}
words.into_iter().map(|(k, v)| (k, v.len())).collect()
}
/// Keyword confidence for a delivery that rests on matched words alone (no embedding agreement). Two shared
/// generic words open the trigger gate but score low on BM25, and those were the wrong lessons delivered on
/// paraphrased questions; a lesson that really answers the question scores high. BM25 scores grow with the idf
/// of the matched words, which grows as ln(lessons), so the floors do too (80 lessons: 17 and 14).
/// A lesson is delivered when its score reaches `hi`, or reaches `lo` and is at least 1.5 times the best
/// other lesson's score (a clear winner). Otherwise the recall stays silent. Applies from 20 lessons up,
/// with the rare-word gate. `INSTINCT_MIN_LEX=0` turns it off; any other number replaces `hi` (`lo` is 0.8 of it).
fn lex_floors(lessons: usize) -> (f32, f32) {
if !rare_gate_on(lessons) {
return (0.0, 0.0);
}
match std::env::var("INSTINCT_MIN_LEX").ok().and_then(|v| v.parse::<f32>().ok()) {
Some(v) => (v, v * 0.8),
None => {
let ln = (lessons as f32).ln();
(3.9 * ln, 3.2 * ln)
}
}
}
/// True when a keyword-only delivery of lesson `i` is too weakly supported (see `lex_floors`).
fn weak_keyword_support(score: f32, top_two: (f32, f32), floors: (f32, f32)) -> bool {
// `top_two` is the best and second best score in the bank, so the best other score is one lookup.
let other = if score >= top_two.0 { top_two.1 } else { top_two.0 };
score < floors.0 && !(score >= floors.1 && score >= 1.5 * other)
}
/// The best and second best score in `lex` (the second equals the best when two lessons tie).
fn top_two(lex: &[f32]) -> (f32, f32) {
let (mut a, mut b) = (0.0_f32, 0.0_f32);
for &s in lex {
if s > a {
b = a;
a = s;
} else if s > b {
b = s;
}
}
(a, b)
}
/// The rare-word gate applies from 20 lessons up, unless `INSTINCT_RARE=0`.
fn rare_gate_on(lessons: usize) -> bool {
lessons >= 20 && env_or("INSTINCT_RARE", "1") != "0"
}
/// Anchors too common in the bank to count as the discriminating one: in more than 10% of the lessons'
/// trigger texts (when, title, tags). Empty when the gate is off (`INSTINCT_RARE=0`) or the bank has
/// fewer than 20 lessons, where a document frequency means nothing. The trigger gate then needs at least
/// one shared anchor outside this set, so two generic words ("page", "release") cannot open it alone.
fn common_anchors(all: &[Discovery]) -> HashSet<String> {
if !rare_gate_on(all.len()) {
return HashSet::new();
}
let mut df: HashMap<String, usize> = HashMap::new();
for d in all {
let mut seen = anchors(&d.when);
seen.extend(anchors(&d.title));
for t in d.tags.split(';') {
seen.extend(anchors(t));
}
for a in seen {
*df.entry(a).or_insert(0) += 1;
}
}
df.into_iter().filter(|(_, c)| c * 10 > all.len()).map(|(a, _)| a).collect()
}
/// One tag phrase from a title's distinctive words (first four, in order, no repeats), used when a lesson is
/// banked without tags. Fewer than two distinctive words cannot satisfy the two-word trigger, so no tag.
fn title_tag(title: &str) -> String {
let mut words: Vec<String> = Vec::new();
// Tags are stored user-facing text: retain the legacy spelling and deduplication.
let stored_fold = |w: &str| {
let once = fold_once(w);
if once.len() < w.len() && w.ends_with('s') { fold_once(&once) } else { once }
};
for w in title.split(|c: char| !(c.is_alphanumeric() || c == '_'))
.filter(|w| w.chars().count() >= 2).map(str::to_lowercase) {
if is_anchor_word(&w) && !words.iter().any(|x| stored_fold(x) == stored_fold(&w)) {
words.push(w);
}
}
words.truncate(4);
if words.len() < 2 {
return String::new();
}
words.join(" ")
}
/// Folds common English word forms onto one key, so "tests", "testing" and "tested" all match
/// "test", "running" matches "runs" and "updated" matches "update". Both sides of a trigger match go
/// through this, so the rule only has to be consistent, not linguistically exact. A plural folds a
/// second time so "warnings" and "warning" share a key. Latin accents are normalized first.
fn fold_word(w: &str) -> String {
let normalized = unicode_words::normalized(w);
let w = normalized.as_ref();
let once = fold_once(w);
if once.len() < w.len() && w.ends_with('s') {
fold_once(&once)
} else {
once
}
}
fn fold_once(w: &str) -> String {
if !w.is_ascii() {
return w.to_string();
}
let has_vowel = |s: &str| s.bytes().any(|b| b"aeiouy".contains(&b));
let undouble = |s: &str| -> String {
let b = s.as_bytes();
let n = b.len();
if n >= 3 && b[n - 1] == b[n - 2] && !b"aeiouylsz".contains(&b[n - 1]) {
s[..n - 1].to_string()
} else {
s.to_string()
}
};
let n = w.len();
if n > 4 && w.ends_with("ies") {
return format!("{}y", &w[..n - 3]);
}
if w.ends_with("sses") {
return w[..n - 2].to_string();
}
if n > 5 && w.ends_with("ing") && has_vowel(&w[..n - 3]) {
return undouble(&w[..n - 3]);
}
if n > 4 && w.ends_with("ed") && has_vowel(&w[..n - 2]) {
return undouble(&w[..n - 2]);
}
if n > 4
&& w.ends_with("es")
&& ["x", "ch", "sh", "ss", "z"].iter().any(|t| w[..n - 2].ends_with(t))
{
return w[..n - 2].to_string();
}
if n > 3 && w.ends_with('s') && !w.ends_with("ss") && !w.ends_with("us") && !w.ends_with("is") {
return w[..n - 1].to_string();
}
if n > 4 && w.ends_with('e') && !w.ends_with("ee") {
return w[..n - 1].to_string();
}
w.to_string()
}
fn score_discoveries(query: &str, discoveries: &[Discovery]) -> Vec<f32> {
bm25(query, &discoveries.iter().map(Discovery::lex_text).collect::<Vec<_>>())
}
/// The user's bank answers first; the project bank (`.instinct/lessons.jsonl` above the cwd) is a second layer,
/// ranked on its own index and appended after. A project bank that fails never stops the lookup.
fn recall_methods(
path: &PathBuf,
q: &str,
k: usize,
scope: &eligibility::Scope,
) -> Result<Vec<Discovery>, String> {
let mut picked = recall_layer(path, q, k, scope, false)?;
if let Some(shared) = team::find(path) {
if let Ok(more) = recall_layer(&shared, q, k, scope, true) {
let have: HashSet<String> = picked.iter().map(|d| d.id.clone()).collect();
picked.extend(more.into_iter().filter(|d| !have.contains(&d.id)));
picked.truncate(k);
}
}
Ok(picked)
}
/// One bank, ranked: `shared` says it is a project bank (rows normalized for git merges before the fold).
fn recall_layer(
path: &PathBuf,
q: &str,
k: usize,
scope: &eligibility::Scope,
shared: bool,
) -> Result<Vec<Discovery>, String> {
// A verified snapshot of this exact bank answers without reading, verifying or tokenizing it again.
#[cfg(not(target_arch = "wasm32"))]
if let Some((all, pos, index)) = snapshot::key(path).and_then(|key| snapshot::open(path, &key, scope, now_secs())) {
let picked = rank_methods_with(
path,
q,
k,
scope,
&all,
|action| snapshot::scores(&index, &pos, all.len(), action),
|| if rare_gate_on(all.len()) { snapshot::common_anchors(&index, &pos, all.len()) } else { HashSet::new() },
);
if ONE_SHOT.load(std::sync::atomic::Ordering::Relaxed) {
std::mem::forget((all, index));
}
return picked;
}
let all = if shared { team::scoped(path, scope, now_secs()) } else { load_user_scoped(path, scope, now_secs())? };
rank_methods(path, q, k, scope, &all, |action| score_discoveries(action, &all))
}
fn load_user_scoped(path: &PathBuf, scope: &eligibility::Scope, now: u64) -> Result<Vec<Discovery>, String> {
Ok(load(path)?
.into_iter()
.filter(|d| eligibility::scope_check(&d.meta, scope, now).is_ok())
.collect())
}
/// `load_scoped` for the guard's `cmd:` match: the project bank is read only when its file mentions a `cmd:` tag,
/// so a Bash guard call over thousands of shared lessons does not decode them just to find none.
fn load_scoped_for_cmd(path: &PathBuf, scope: &eligibility::Scope, now: u64) -> Result<Vec<Discovery>, String> {
let mut all = load_user_scoped(path, scope, now)?;
if let Some(shared) = team::find(path).filter(|t| team::mentions(t, "cmd:")) {
let have: HashSet<String> = all.iter().map(|d| d.id.clone()).collect();
all.extend(team::scoped(&shared, scope, now).into_iter().filter(|d| !have.contains(&d.id)));
}
Ok(all)
}
/// Every lesson that fits the scope: the user's bank, then the project bank's.
fn load_scoped(
path: &PathBuf,
scope: &eligibility::Scope,
now: u64,
) -> Result<Vec<Discovery>, String> {
let mut all = load_user_scoped(path, scope, now)?;
if let Some(shared) = team::find(path) {
let have: HashSet<String> = all.iter().map(|d| d.id.clone()).collect();
all.extend(team::scoped(&shared, scope, now).into_iter().filter(|d| !have.contains(&d.id)));
}
Ok(all)
}
fn rank_methods(
path: &PathBuf,
q: &str,
k: usize,
scope: &eligibility::Scope,
all: &[Discovery],
lexical_scores: impl FnOnce(&str) -> Vec<f32>,
) -> Result<Vec<Discovery>, String> {
rank_methods_with(path, q, k, scope, all, lexical_scores, || common_anchors(all))
}
/// `common` supplies the anchors too common to count (see `common_anchors`); a snapshot answers it from stored counts.
fn rank_methods_with(
path: &PathBuf,
q: &str,
k: usize,
scope: &eligibility::Scope,
all: &[Discovery],
lexical_scores: impl FnOnce(&str) -> Vec<f32>,
common: impl FnOnce() -> HashSet<String>,
) -> Result<Vec<Discovery>, String> {
meter::note_eligible(all);
if all.is_empty() || q.trim().is_empty() {
return Ok(Vec::new());
}
// A quoted passage being translated or counted is data. Rank on the request
// around it, including for the resident index and the spelling fallback.
let action_text = brief_action::action_text(q);
let q = action_text.as_ref();
let lex = lexical_scores(&concepts::expand(q));
let mut fused = vec![0f32; all.len()];
let mut similarities: Vec<Option<f32>> = vec![None; all.len()];
let quiet = quiet_ids(path);
let w_lex: f32 = env_or("INSTINCT_W_LEX", "1").parse().unwrap_or(1.0);
for (r, &i) in ranking(&lex).iter().enumerate() {
fused[i] += w_lex / (RRF_K + r as f32 + 1.0);
}
if let Ok(qe) = embed("search_query: ", q) {
let mode = env_or("INSTINCT_VEC_MODE", "both");
let whenv = if env_or("INSTINCT_WHEN_VEC", "1") == "0" || mode == "full" {
std::collections::HashMap::new()
} else {
load_when(path)
};
for (i, d) in all.iter().enumerate() {
if !d.embedding.is_empty() {
similarities[i] = Some(cosine(&qe, &d.embedding));
}
}
if mode != "when" || whenv.is_empty() {
let sem: Vec<f32> = all
.iter()
.map(|d| {
let c = cosine(&qe, &d.embedding);
if c >= 0.5 {
c
} else {
0.0
}
})
.collect();
for (r, &i) in ranking(&sem).iter().enumerate() {
fused[i] += 1.0 / (RRF_K + r as f32 + 1.0);
}
}
// Two guards keep the when-vector from diluting raw-command recall (measured 2026-11-04: as a free third
// list it cost -4 @5 on 46 shell-command situations while gaining +2 @1):
// · INSTINCT_WHENVEC_GATE=1 — the when-vector only re-ranks items an existing signal already found
// (BM25 > 0 or full-vector cosine >= 0.5); it cannot introduce candidates of its own.
// · INSTINCT_WHENVEC_NLONLY=1 — skip it when the query reads as a shell command (>= 30 % of tokens
// carry / - $ | & ; = or start with a digit); situations are prose, deny-path queries are commands.
let shellish = {
let toks: Vec<&str> = q.split_whitespace().collect();
let n = toks.len().max(1) as f32;
let s = toks
.iter()
.filter(|t| {
t.contains('/')
|| t.starts_with('-')
|| t.contains('$')
|| t.contains('|')
|| t.contains('&')
|| t.contains(';')
|| t.contains('=')
|| t.starts_with(|c: char| c.is_ascii_digit())
})
.count() as f32;
s / n >= 0.30
};
let nl_only = env_or("INSTINCT_WHENVEC_NLONLY", "0") == "1";
if !whenv.is_empty() && !(nl_only && shellish) {
let w: f32 = env_or("INSTINCT_W_WHENVEC", "1").parse().unwrap_or(1.0);
let gate = env_or("INSTINCT_WHENVEC_GATE", "0") == "1";
let semw: Vec<f32> = all
.iter()
.enumerate()
.map(|(i, d)| {
if gate && lex[i] <= 0.0 && cosine(&qe, &d.embedding) < 0.5 {
return 0.0;
}
whenv
.get(&d.id)
.map(|v| {
let c = cosine(&qe, v);
if c >= 0.5 {
c
} else {
0.0
}
})
.unwrap_or(0.0)
})
.collect();
for (r, &i) in ranking(&semw).iter().enumerate() {
fused[i] += w / (RRF_K + r as f32 + 1.0);
}
}
}
for (i, d) in all.iter().enumerate() {
if fused[i] > 0.0 {
fused[i] += 0.002 * d.strength();
}
}
// Result fold (INSTINCT_FOLD = cosine threshold, default off): a near-duplicate of a lesson already in
// the answer does not take a slot, so top-k carries k DIFFERENT lessons.
let fold: f32 = env_or("INSTINCT_FOLD", "0").parse().unwrap_or(0.0);
let mut picked: Vec<usize> = Vec::with_capacity(k.min(all.len()));
let cues = anchor_counts(q);
let common = common();
// A BM25 score grows with the number of matched words, so a terse query is held to a proportionally lower
// floor: full strength from 12 words up, a fifth of it at 2 words.
let lex_floors = {
let scale = (tokens(q).len() as f32 / 12.0).clamp(0.2, 1.0);
let (hi, lo) = lex_floors(all.len());
(hi * scale, lo * scale)
};
let lex_top = top_two(&lex);
let brief = brief::Brief::parse(q);
let roles = brief_action::TaskRoles::parse(q);
let excluded = |d: &Discovery| {
!roles.allows(&d.when, &d.how, &d.tags)
|| brief.excludes(&d.when, &d.how)
|| d.standing
.as_ref()
.is_some_and(|s| brief.excludes(&d.when, &s.text))
};
for i in ranking(&fused) {
if picked.len() >= k {
break;
}
let verdict = eligibility::eligible(
&all[i].meta,
scope,
now_secs(),
similarities[i],
all[i].hits,
quiet.contains(&all[i].id),
);
let trigger_matches = |trigger: &str| {
// Count shared words, not shared tokens: "test suite" on both sides is two words even though
// both map to one synonym token. A token contributes as many matches as the side with fewer
// distinct words in it, so one synonym can never stand in for two different words.
let mut shared = 0;
let mut rare = common.is_empty();
for (token, n) in anchor_counts(trigger) {
if let Some(m) = cues.get(&token) {
shared += n.min(*m);
rare |= !common.contains(&token);
}
}
shared >= 2 && rare
};
let strong_trigger =
trigger_matches(&all[i].when)
|| trigger_matches(&all[i].title)
|| all[i].tags.split(';').any(trigger_matches);
let offline_candidate = verdict == Err("candidate_match_unproven")
&& all[i].meta.source == "banked"
&& strong_trigger;
if (verdict.is_err() && !offline_candidate)
|| eligibility::quiet(all[i].hits, all[i].misses)
|| (!strong_trigger && similarities[i].unwrap_or(0.0) < 0.74)
|| (similarities[i].unwrap_or(0.0) < 0.74 && weak_keyword_support(lex[i], lex_top, lex_floors))
|| excluded(&all[i])
{
continue;
}
if fold > 0.0
&& !all[i].embedding.is_empty()
&& picked.iter().any(|&j| {
!all[j].embedding.is_empty() && cosine(&all[i].embedding, &all[j].embedding) >= fold
})
{
continue;
}
picked.push(i);
}
if picked.is_empty() && k > 0 && cues.len() >= 2 {
let query = tokens(q);
let mut matches = Vec::new();
for (i, d) in all.iter().enumerate() {
if d.hits == 0
|| excluded(d)
|| quiet.contains(&d.id)
|| eligibility::quiet(d.hits, d.misses)
|| eligibility::scope_check(&d.meta, scope, now_secs()).is_err()
{
continue;
}
let score = std::iter::once(d.when.as_str())
.chain(d.tags.split(';'))
.map(|cue| helix_db::cue_similarity(&query, cue))
.fold(0.0_f64, f64::max);
if score > 0.0 {
matches.push((i, score));
}
}
matches.sort_by(|a, b| b.1.total_cmp(&a.1));
if let Some(&(i, score)) = matches.first() {
if score >= 0.62 && matches.get(1).is_none_or(|next| score - next.1 >= 0.08) {
picked.push(i);
}
}
}
Ok(picked.into_iter().map(|i| all[i].clone()).collect())
}
// ---------------------------------------------------------------- lesson index (INSTINCT_INDEX=1)
const INDEX_HEADER: &str = "Instinct lessons: if one fits, run `instinct show ID` for the method";
/// The whole index block, header included, never exceeds this many bytes.
const INDEX_BUDGET: usize = 6 * 1024;
/// True for `instinct prompt --index` or `INSTINCT_INDEX=1`. Off by default.
fn index_wanted(a: &Args) -> bool {
a.flag("index") || std::env::var("INSTINCT_INDEX").is_ok_and(|v| v.trim() == "1")
}
/// One line of text: control characters and the column separator become spaces, then cut to `max` bytes
/// at a character boundary with a trailing "...".
fn index_cell(text: &str, max: usize) -> String {
let flat: String = text.chars().map(|c| if c.is_control() || c == '|' { ' ' } else { c }).collect();
let flat = flat.split_whitespace().collect::<Vec<_>>().join(" ");
if flat.len() <= max {
return flat;
}
let mut end = max.saturating_sub(3);
while !flat.is_char_boundary(end) {
end -= 1;
}
format!("{}...", flat[..end].trim_end())
}
/// The index block: a header line, then `ID | title | when` per lesson, strongest first (ties keep bank
/// order). Texts are cut as little as the budget allows: the first column widths that fit every lesson win;
/// if even the narrowest do not, the weakest lessons are left off. Empty when there is nothing to list.
fn render_index(all: &[Discovery], budget: usize) -> String {
if all.is_empty() {
return String::new();
}
let mut order: Vec<&Discovery> = all.iter().collect();
order.sort_by(|a, b| b.strength().total_cmp(&a.strength()));
let widths = [(60usize, 120usize), (48, 90), (40, 70), (36, 56), (32, 44), (28, 36), (24, 28)];
let build = |(tw, ww): (usize, usize)| {
let mut out = String::from(INDEX_HEADER);
let mut all_fit = true;
for d in &order {
let line = format!("\n{} | {} | {}", d.id, index_cell(&d.title, tw), index_cell(&d.when, ww));
if out.len() + line.len() > budget {
all_fit = false;
break;
}
out.push_str(&line);
}
(out, all_fit)
};
for w in widths {
let (out, fit) = build(w);
if fit {
return out;
}
}
build(widths[widths.len() - 1]).0
}
/// The index of the lessons recall may deliver in this scope: the user's bank plus the project (team) bank,
/// in scope, not quiet, and past the same eligibility gate recall applies. A lesson mined or distilled that no
/// hit has confirmed stays out until a match proves it, exactly as in recall; one you banked yourself is
/// listed, as recall lets it through on a strong trigger.
fn index_block(path: &PathBuf, scope: &eligibility::Scope) -> Result<String, String> {
let quiet = quiet_ids(path);
let now = now_secs();
let mut all = load_scoped(path, scope, now)?;
all.retain(|d| {
if eligibility::quiet(d.hits, d.misses) {
return false;
}
match eligibility::eligible(&d.meta, scope, now, None, d.hits, quiet.contains(&d.id)) {
Ok(()) => true,
Err("candidate_match_unproven") => d.meta.source == "banked",
Err(_) => false,
}
});
Ok(render_index(&all, INDEX_BUDGET))
}
/// `instinct show ID [ID...]`: the full lessons, rendered exactly as recall renders them.
fn op_show(path: &PathBuf, ids: &[String]) -> Result<String, String> {
if ids.is_empty() {
return Err("usage: show ID [ID...]".into());
}
// The user's bank and the project (team) bank, so every id the index lists can be shown.
let all = load_view(path)?;
let mut out = Vec::new();
for raw in ids {
let id = raw.trim().trim_matches(|c| c == '[' || c == ']');
let d = all.iter().find(|d| d.id == id).ok_or_else(|| format!("no lesson {id}"))?;
out.push(render_entry(d));
}
Ok(out.join("\n\n"))
}
/// Cline launches the hook in its active workspace. A single reported root also
/// identifies the workspace when the hook is invoked from another directory.
fn cline_workspace(event: &Json) -> Result<Option<&str>, ()> {
match event.get("workspaceRoots") {
None => Ok(None),
Some(Json::Arr(roots)) if roots.is_empty() => Ok(None),
Some(Json::Arr(roots)) => {
let cwd = std::env::current_dir().ok();
roots.iter().filter_map(Json::as_str).find(|root| {
let path = Path::new(root);
path.is_absolute() && (roots.len() == 1 || same_dir(path, cwd.as_deref()))
}).map(Some).ok_or(())
}
_ => Err(()),
}
}
/// getcwd returns the resolved path (macOS reports /private/var for /var), so compare resolved paths.
fn same_dir(root: &Path, cwd: Option<&Path>) -> bool {
let Some(cwd) = cwd else { return false };
root == cwd || matches!((root.canonicalize(), cwd.canonicalize()), (Ok(a), Ok(b)) if a == b)
}
fn cline_reply(text: &str) -> String {
if text.is_empty() {
r#"{"cancel":false}"#.into()
} else {
format!(r#"{{"cancel":false,"contextModification":"{}"}}"#, escape_json(text))
}
}
/// The hook recall (k=1) with session memory: a lesson already delivered in this session is skipped, so the
/// same tokens never arrive twice. Without a session id it behaves exactly like a plain k=1 recall.
fn recall_once_per_session(
path: &PathBuf,
kind: &'static str,
q: &str,
scope: &eligibility::Scope,
sid: Option<&str>,
) -> Result<(String, Vec<String>), String> {
let previous = sid.map(|s| session::seen(path, s)).unwrap_or_default();
let seen = previous.lesson_ids();
let timer = meter::start(path, kind);
let mut methods = recall_methods(path, q, 1 + seen.len().min(10), scope)?;
methods.retain(|d| !seen.contains(&d.id));
methods.truncate(1);
// A correction is actionable on this turn. An unsettled verdict can still be requested later.
let followup = match (kind, sid) {
("prompt", Some(s)) => session::correction_line(path, s, &previous, q, &scope.project)
.or_else(|| session::followup(path, s, &previous)),
_ => None,
};
if let Some(s) = sid {
methods.retain(|d| session::claim_lesson(path, s, &d.id, session::Source::Prompt));
}
let mut text = String::new();
let mut ids = Vec::new();
if let Some(lesson) = methods.first() {
ids.push(lesson.id.clone());
text = match &lesson.standing {
Some(instruction) => render_prompt_default(lesson, instruction),
None => format!("{SELECT_FOR_TASK}\n{}", render_entry(lesson)),
};
}
let text = match followup {
Some(f) if text.trim().is_empty() => f,
Some(f) => format!("{text}\n\n{f}"),
None => text,
};
if let Some(t) = timer {
t.finish(ids.len(), text.len());
}
Ok((text, ids))
}
/// Keep the user's continuing instruction separate from the evidence behind the original method.
fn render_prompt_default(lesson: &Discovery, instruction: &StandingInstruction) -> String {
let mut text = format!(
"Project default [{}] ({}): {}\nWhen: {}",
lesson.id, instruction.reference, instruction.text, lesson.when
);
if !lesson.reconsider.is_empty() {
text.push_str(&format!("\nReconsider: {}", lesson.reconsider));
}
text.push_str("\nOn a match, apply the default without asking again. The current request takes precedence.");
if !lesson.how.is_empty() && lesson.how != instruction.text {
text.push_str(&format!("\nPrior method ({}): {}", validity_text(lesson), lesson.how));
}
text
}
fn op_recall_data(
path: &PathBuf,
q: &str,
k: usize,
scope: &eligibility::Scope,
) -> Result<(String, Vec<String>), String> {
Ok(render_recall(&recall_methods(path, q, k, scope)?))
}
/// Check the receiver's normal ranked selection without counting a delivery or recording feedback.
fn probe_recall(path: &PathBuf, args: &Args, query: &str) -> Result<String, String> {
let mut keys = HashSet::new();
for (key, value) in &args.kv {
if !matches!(key.as_str(), "expect" | "q" | "k" | "store" | "project" | "persona" | "harness" | "harness-version" | "machine")
|| value.trim().is_empty() || !keys.insert(key)
{
return Err("probe requires known, nonempty options supplied once".into());
}
}
let id = args.opt("expect").unwrap_or("");
if !args.pos.is_empty() || id.trim().is_empty() || query.trim().is_empty() {
return Err("probe needs --expect ID and a nonempty --q".into());
}
let k = args.opt("k").unwrap_or("5").parse::<usize>()
.ok().filter(|n| *n > 0).ok_or("probe needs a positive --k")?;
let selected = recall_methods(path, query, k, &eligibility::env_scope())?;
match selected.iter().position(|lesson| lesson.id == id) {
Some(i) => Ok(format!("matched {id} at rank {} of {}", i + 1, selected.len())),
None if selected.is_empty() => Err("expected lesson absent: recall returned no lessons".into()),
None => Err(format!("expected lesson absent: recall selected {} other lesson(s)", selected.len())),
}
}
fn render_recall(methods: &[Discovery]) -> (String, Vec<String>) {
let ids = methods.iter().map(|d| d.id.clone()).collect();
let text = methods
.iter()
.map(render_entry)
.collect::<Vec<_>>()
.join("\n\n");
(text, ids)
}
fn render_recall_with_facts(
methods: &[Discovery],
facts: Option<&Json>,
) -> Result<(String, Vec<String>), String> {
let Some(facts) = facts else {
return Ok(render_recall(methods));
};
case_learning::validate_facts(facts)?;
let mut entries = Vec::with_capacity(methods.len());
for d in methods {
let mut entry = render_plain_entry(d);
if let Some(book) = d.casebook.as_ref().filter(|_| d.standing.is_none()) {
entry.push_str("\n ");
entry.push_str(&book.guidance(facts)?);
}
entries.push(entry);
}
Ok((
entries.join("\n\n"),
methods.iter().map(|d| d.id.clone()).collect(),
))
}
/// A new task may have different vocabulary and the same observed checks. Only
/// an unambiguous, eligible casebook in this exact project can fill an empty recall.
fn case_candidates(
path: &PathBuf,
q: &str,
scope: &eligibility::Scope,
facts: Option<&Json>,
selected: Vec<Discovery>,
) -> Result<Vec<Discovery>, String> {
let Some(facts) = facts else {
return Ok(selected);
};
case_learning::validate_facts(facts)?;
if !selected.is_empty()
|| q.trim().is_empty()
|| scope.project.is_empty()
|| !matches!(facts, Json::Obj(fields) if fields.len() >= 2)
{
return Ok(selected);
}
let quiet = quiet_ids(path);
let mut matched = Vec::new();
for d in load_user_scoped(path, scope, now_secs())? {
if d.meta.project != scope.project
|| d.meta.source != "banked"
|| d.standing.is_some()
|| quiet.contains(&d.id)
|| eligibility::quiet(d.hits, d.misses)
{
continue;
}
let Some(book) = &d.casebook else { continue };
let advice = book.advise(facts)?;
if matches!(advice.get("ignored_keys"), Some(Json::Arr(v)) if v.is_empty())
&& matches!(advice.get("supporting_refs"), Some(Json::Arr(v)) if !v.is_empty())
{
if !matched.is_empty() {
return Ok(Vec::new());
}
matched.push(d);
}
}
Ok(matched)
}
/// Byte length of `render_entry(d)` without building it (the meter needs it for every eligible lesson on every
/// lookup). A test pins it to `render_entry(d).len()`.
fn render_len(d: &Discovery) -> usize {
fn digits(n: u32) -> usize {
n.checked_ilog10().map_or(1, |l| l as usize + 1)
}
let s = d.strength();
if !(0.0..9.995).contains(&s) {
return render_entry(d).len();
}
let mut n = "[".len() + d.id.len() + "] ".len() + d.title.len() + " (strength ".len() + 4
+ ", ".len() + digits(d.hits) + " hit / ".len() + digits(d.misses) + " miss)".len()
+ "\n WHEN: ".len() + d.when.len() + "\n FOUND: ".len() + d.found.len()
+ "\n HOW: ".len() + d.how.len() + "\n EVIDENCE: ".len() + d.evidence.len();
for (key, v) in [("RECONSIDER", &d.reconsider), ("MACHINE", &d.meta.machine), ("TAGS", &shown_tags(&d.tags))] {
if !v.is_empty() {
n += "\n ".len() + key.len() + ": ".len() + v.len();
}
}
n += "\n VALIDITY: ".len();
if d.hits >= 2 && s >= 0.6 {
n += VALID_PROVEN_HEAD.len() + digits(d.hits) + " hits, ".len() + digits(d.misses)
+ VALID_PROVEN_TAIL.len();
} else {
n += if eligibility::unverified(&d.meta) { VALID_UNVERIFIED } else { VALID_VERIFIED }.len();
if d.meta.state == "candidate" || d.meta.source == "mined" {
n += VALID_CANDIDATE.len();
}
}
if let Some(i) = &d.standing {
n += "\n STANDING INSTRUCTION (".len() + i.reference.len() + "): ".len() + i.text.len();
} else if let Some(book) = &d.casebook {
n += "\n ".len() + book.first_guidance().len();
}
n
}
const VALID_UNVERIFIED: &str = "source claim not independently verified";
const VALID_VERIFIED: &str = "verified within recorded scope";
const VALID_CANDIDATE: &str = "; candidate, check original evidence";
const VALID_PROVEN_HEAD: &str = "proven in use (";
const VALID_PROVEN_TAIL: &str = " misses); act on it unless the reconsider condition applies";
fn render_entry(d: &Discovery) -> String {
let mut entry = render_plain_entry(d);
if let Some(book) = d.casebook.as_ref().filter(|_| d.standing.is_none()) {
entry.push_str("\n ");
entry.push_str(&book.first_guidance());
}
entry
}
fn render_plain_entry(d: &Discovery) -> String {
let standing = d
.standing
.as_ref()
.map(|instruction| {
format!(
"\n STANDING INSTRUCTION ({}): {}",
instruction.reference, instruction.text
)
})
.unwrap_or_default();
format!("{}\n VALIDITY: {}{standing}", render(d), validity_text(d))
}
/// A lesson that already paid off twice (the `instinct instincts` bar) is an instinct: tell the agent to
/// act on it instead of re-checking the original evidence every time.
fn validity_text(d: &Discovery) -> String {
if d.proven_in_use() {
format!("{VALID_PROVEN_HEAD}{} hits, {}{VALID_PROVEN_TAIL}", d.hits, d.misses)
} else {
format!(
"{}{}",
if eligibility::unverified(&d.meta) { VALID_UNVERIFIED } else { VALID_VERIFIED },
if d.meta.state == "candidate" || d.meta.source == "mined" { VALID_CANDIDATE } else { "" }
)
}
}
/// A synchronous adapter for any host's pre-decision step. No model call or feedback side effect.
fn decision_context(
path: &PathBuf,
situation: &str,
scope: &eligibility::Scope,
facts: Option<&Json>,
) -> Result<String, String> {
if situation.trim().is_empty() {
return Err("decide requires a situation via --q".into());
}
let timer = meter::start(path, "decide");
let methods = case_candidates(path, situation, scope, facts, recall_methods(path, situation, 2, scope)?)?;
let out = json_out(&decision_packet_with_facts(&methods, facts)?);
if let Some(t) = timer {
t.finish(methods.len(), out.len());
}
Ok(out)
}
/// A short retry can refer to the current job without naming it. Never carry context
/// through a new instruction, quoted text, or an ordinary acknowledgement.
fn short_retry(text: &str) -> bool {
if text.len() > 96 {
return false;
}
let lower = text.trim().trim_end_matches(['.', '!']).to_ascii_lowercase().replace('’', "'");
let words = lower.trim().strip_prefix("no,").unwrap_or(&lower).trim();
matches!(words, "still wrong" | "that's still wrong" | "that is still wrong"
| "still incorrect" | "that's still incorrect" | "that is still incorrect")
}
/// Pick only when one applicability cue covers strictly more of the user's brief
/// than every competing cue. Refuse an incomplete candidate set.
fn retry_check(path: &PathBuf, task: &str, scope: &eligibility::Scope) -> Result<Option<Discovery>, String> {
const LIMIT: usize = 8;
if task.trim().is_empty() || task.len() > 2048 {
return Ok(None);
}
let mut methods = recall_methods(path, task, LIMIT + 1, scope)?;
if methods.len() > LIMIT {
return Ok(None);
}
let query = anchors(brief_action::action_text(task).as_ref());
let support: Vec<_> = methods.iter().map(|d| {
let mut cue = anchors(&d.when);
cue.retain(|a| query.contains(a));
cue
}).collect();
let winner = support.iter().enumerate().position(|(i, cue)| {
cue.len() >= 2 && support.iter().enumerate().all(|(j, other)| {
i == j || (cue.len() > other.len() && cue.is_superset(other))
})
});
Ok(winner.map(|i| methods.swap_remove(i)))
}
/// A short, opt-in preflight after a user correction. Keep the entire applicability boundary or abstain.
fn premortem(path: &PathBuf, situation: &str, previous_task: Option<&str>, scope: &eligibility::Scope) -> Result<String, String> {
if situation.trim().is_empty() {
return Err("premortem requires the user's correction".into());
}
let picked = if let Some(task) = previous_task.filter(|_| short_retry(situation)) {
retry_check(path, task, scope)?
} else if corrections::correction(situation) {
recall_methods(path, situation, 1, scope)?.into_iter().next()
} else {
None
};
let Some(d) = picked else { return Ok(String::new()) };
if !d.proven_in_use() || d.how.trim().is_empty() || d.found.trim().is_empty() {
return Ok(String::new());
}
let mut fields = vec![
("id".into(), Json::Str(d.id.clone())),
("when".into(), Json::Str(d.when.clone())),
("previous_observation".into(), Json::Str(d.found.clone())),
("check".into(), Json::Str(d.how.clone())),
];
if !d.reconsider.is_empty() {
fields.push(("reconsider_if".into(), Json::Str(d.reconsider.clone())));
}
let packet = json_out(&Json::Obj(fields));
Ok(if packet.len() <= 320 { packet } else { String::new() })
}
const SELECT_FOR_TASK: &str = "Select only the methods applicable to the current request. Use none if none apply.";
fn decision_packet(methods: &[Discovery]) -> Json {
decision_packet_with_facts(methods, None).expect("empty facts are valid")
}
fn decision_packet_with_facts(methods: &[Discovery], facts: Option<&Json>) -> Result<Json,String> {
let empty = Json::Obj(vec![]);
let experiences = methods
.iter()
.map(|d| {
let mut fields = vec![
("id".into(), Json::Str(d.id.clone())),
("when".into(), Json::Str(d.when.clone())),
("method".into(), Json::Str(d.how.clone())),
(
"machine".into(),
if d.meta.machine.is_empty() {
Json::Null
} else {
Json::Str(d.meta.machine.clone())
},
),
(
"standing_instruction".into(),
d.standing.as_ref().map_or(Json::Null, |v| {
Json::Obj(vec![
("text".into(), Json::Str(v.text.clone())),
("source_ref".into(), Json::Str(v.reference.clone())),
])
}),
),
("observed".into(), Json::Str(d.found.clone())),
("evidence".into(), Json::Str(d.evidence.clone())),
(
"reconsider_if".into(),
if d.reconsider.is_empty() {
Json::Null
} else {
Json::Str(d.reconsider.clone())
},
),
("hits".into(), Json::Num(d.hits.into())),
("misses".into(), Json::Num(d.misses.into())),
// Same bar as `instinct instincts`: paid off twice, strength 0.6 or more. Hosts can act on it.
("proven".into(), Json::Bool(d.proven_in_use())),
(
"evidence_status".into(),
Json::Str(
if eligibility::unverified(&d.meta) {
"unverified"
} else {
"verified_in_scope"
}
.into(),
),
),
];
if let Some(book) = d.casebook.as_ref().filter(|_| d.standing.is_none()) {
fields.push(("case_advice".into(), book.advise(facts.unwrap_or(&empty))?));
}
Ok(Json::Obj(fields))
})
.collect::<Result<Vec<_>,String>>()?;
Ok(Json::Obj(vec![
("version".into(), Json::Num(1.0)),
("selection_instruction".into(), Json::Str(SELECT_FOR_TASK.into())),
("experiences".into(), Json::Arr(experiences)),
]))
}
/// A checked hit is user-bank only: a team lesson keeps its evidence in the project bank, which has no check attachments.
fn refuse_team_check(path: &PathBuf, id: &str) -> Result<(), String> {
if team::find(path).is_some_and(|t| team::has_lesson(&t, id)) {
return Err("checked feedback does not support team lessons yet; nothing recorded (use plain `hit`)".into());
}
Ok(())
}
fn op_mark(
path: &PathBuf,
kind: &str,
id: &str,
note: &str,
outcome_id: &str,
) -> Result<String, String> {
// A lesson that lives in the project bank takes its evidence there, so the whole team counts it.
let shared = team::find(path).filter(|t| team::has_lesson(t, id));
let path = shared.as_ref().unwrap_or(path);
let _lock = journal::identity_lock(path)?;
let entry = match &shared {
Some(t) => team::load(t),
None => load_plain(path),
}?
.into_iter()
.find(|d| d.id == id)
.ok_or_else(|| format!("no discovery with id {id}"))?;
let generated = if shared.is_some() && outcome_id.trim().is_empty() { team::event_key() } else { String::new() };
let key = if generated.is_empty() { outcome_id.trim() } else { generated.as_str() };
if let Some(&paid_off) = entry.outcomes.get(key) {
if paid_off.is_none() {
return Err("conflicting reports for this outcome; nothing recorded".into());
}
if paid_off != Some(kind == "hit") {
return Err("outcome already recorded with a different verdict".into());
}
return Ok(format!("outcome already recorded for {id}"));
}
append(path, &feedback_event(kind, id, note, key, now_secs()))?;
Ok(format!("{kind} recorded for {id}"))
}
fn feedback_event(kind: &str, id: &str, note: &str, key: &str, ts: u64) -> String {
let mut fields = vec![
("kind".into(), Json::Str(kind.into())),
("id".into(), Json::Str(id.into())),
("ts".into(), Json::Num(ts as f64)),
("note".into(), Json::Str(note.into())),
];
if !key.is_empty() {
fields.push(("outcome_id".into(), Json::Str(key.into())));
}
json_out(&Json::Obj(fields))
}
fn op_mark_case(
path: &PathBuf, kind: &str, id: &str, note: &str, outcome_id: &str,
observation: &Json, scope: &eligibility::Scope,
) -> Result<String, String> {
if !matches!(kind, "hit" | "miss") || outcome_id.is_empty() || outcome_id.trim() != outcome_id {
return Err("observed feedback requires hit or miss and a nonempty stable outcome id".into());
}
if is_team_bank(path) {
return Err("observed feedback requires an active directly banked personal lesson".into());
}
let Json::Obj(fields) = observation else { return Err("observation must contain facts and action".into()) };
if fields.len() != 2 {
return Err("observation must contain exactly facts and action".into());
}
let facts = observation.get("facts").ok_or("observation requires facts")?;
let action = observation.get("action").ok_or("observation requires the action that worked")?;
let _lock = journal::identity_lock(path)?;
let ts = now_secs();
let all = fold_text_for_bank(&journal::read(path)?, &path.display().to_string(), |_, _, _, _| {}, Some(id))?;
let d = all.iter().find(|d| d.id == id).ok_or("no active directly banked personal lesson with this id")?;
eligibility::scope_check(&d.meta, scope, ts).map_err(|why| format!("lesson is outside the active scope: {why}"))?;
let book = d.casebook.as_ref().ok_or("lesson has no active casebook")?;
let vocabulary = book.to_json();
let example = Json::Obj(vec![
("ref".into(), Json::Str(outcome_id.into())), ("facts".into(), facts.clone()), ("action".into(), action.clone()),
]);
let add = case_learning::Casebook::parse(&Json::Obj(vec![
("checks".into(), vocabulary.get("checks").ok_or("casebook is missing checks")?.clone()),
("examples".into(), Json::Arr(vec![example])),
]))?;
let changed = book.merge(&add)? != *book;
let previous = d.outcomes.get(outcome_id);
if previous.is_some_and(|verdict| *verdict != Some(kind == "hit")) {
return Err("conflicting verdict for this outcome; nothing recorded".into());
}
let mut rows = Vec::new();
if changed { rows.push(case_event(d, &add, ts)); }
if previous.is_none() { rows.push(feedback_event(kind, id, note, outcome_id, ts)); }
if rows.is_empty() { return Ok(format!("outcome and observation already recorded for {id}")); }
journal::append_many(path, &rows.iter().map(String::as_str).collect::<Vec<_>>())?;
Ok(format!("{kind} and observation recorded for {id}"))
}
fn op_review(
path: &PathBuf,
id: &str,
state: &str,
reason: &str,
reference: &str,
) -> Result<String, String> {
if !["quarantined", "candidate"].contains(&state)
|| reason.trim().is_empty()
|| reference.trim().is_empty()
{
return Err("review requires state quarantined|candidate, reason and source-ref; does not grant verified status".into());
}
let _lock = journal::identity_lock(path)?;
if !load_plain(path)?.iter().any(|d| d.id == id) {
return Err("unknown active lesson".into());
}
append(path,&format!("{{\"kind\":\"review\",\"id\":\"{}\",\"ts\":{},\"state\":\"{state}\",\"evidence_status\":\"unverified\",\"reason\":\"{}\",\"source_ref\":\"{}\"}}",escape_json(id),now_secs(),escape_json(reason),escape_json(reference)))?;
Ok(format!("reviewed {id}: {state}; original preserved"))
}
/// `sync pull|push|status`: file-level bank sync, the diff and merge live in sync.hlx.
fn op_sync(path: &PathBuf, a: &Args) -> Result<String, String> {
let other = |flag: &str| a.opt(flag).filter(|p| !p.starts_with("--")).map(PathBuf::from).ok_or(format!("usage: instinct sync pull --from PATH | push --to PATH | status --with PATH (missing --{flag})"));
let done = |verb: &str, to: &Path, r: sync::Report| {
let conflicts = if r.conflicts > 0 { format!("; {} outcome(s) kept local: the other side holds a different verdict for the same outcome id", r.conflicts) } else { String::new() };
format!("{verb} {} event(s) into {} ({} already there, {} read){conflicts}", r.added, to.display(), r.had, r.source)
};
match a.pos.first().map(String::as_str) {
Some("pull") => {
let from = other("from")?;
Ok(done("pulled", path, sync::pull(path, &from)?))
}
Some("push") => {
let to = other("to")?;
Ok(done("pushed", &to, sync::pull(&to, path)?))
}
Some("status") => {
let with = other("with")?;
let (lacking_here, lacking_there, conflicts) = sync::status(path, &with)?;
Ok(format!("this bank lacks {lacking_here} event(s) from {w}; {w} lacks {lacking_there} from this bank; {conflicts} conflicting outcome(s)", w = with.display()))
}
_ => Err("usage: instinct sync pull --from PATH | push --to PATH | status --with PATH".into()),
}
}
/// Instincts = discoveries that kept paying off: >= min_hits hits and strength >= 0.6. One reflex line each.
fn op_instincts(path: &PathBuf, min_hits: u32) -> Result<String, String> {
let scope = eligibility::env_scope();
let quiet = quiet_ids(path);
let mut all: Vec<Discovery> = load_view(path)?
.into_iter()
.filter(|d| {
eligibility::promoted(d.hits, d.misses, min_hits)
&& eligibility::eligible(
&d.meta,
&scope,
now_secs(),
None,
d.hits,
quiet.contains(&d.id),
)
.is_ok()
})
.collect();
all.sort_by(|a, b| {
b.strength()
.partial_cmp(&a.strength())
.unwrap_or(std::cmp::Ordering::Equal)
.then(b.hits.cmp(&a.hits))
});
Ok(all.iter().map(|d| format!("- WHEN {} → {} (how: {}) [{} · {} hits; historical source claim, verify applicability]", d.when, d.found, d.how, d.id, d.hits)).collect::<Vec<_>>().join("\n"))
}
/// Embed every entry that has no vector yet (banked while Ollama was down); appends one `embed` event per entry.
fn op_reembed(path: &PathBuf) -> Result<String, String> {
let all = load(path)?;
let todo: Vec<&Discovery> = all.iter().filter(|d| d.embedding.is_empty()).collect();
let mut done = 0;
for d in &todo {
let e = embed("search_document: ", &d.text())
.map_err(|e| format!("stopped after {done}/{} ({e})", todo.len()))?;
let emb: Vec<String> = e.iter().map(|f| f.to_string()).collect();
append(
path,
&format!(
"{{\"kind\":\"embed\",\"id\":\"{}\",\"ts\":{},\"embedding\":[{}]}}",
escape_json(&d.id),
now_secs(),
emb.join(",")
),
)?;
done += 1;
}
Ok(format!(
"re-embedded {done} of {} entries without a vector",
todo.len()
))
}
fn op_stats(path: &PathBuf, a: &Args) -> Result<String, String> {
let all = load_view(path)?;
let inst = all
.iter()
.filter(|d| eligibility::promoted(d.hits, d.misses, 2))
.count();
let emb = all.iter().filter(|d| !d.embedding.is_empty()).count();
let hits: u32 = all.iter().map(|d| d.hits).sum();
let misses: u32 = all.iter().map(|d| d.misses).sum();
let line = format!(
"store {} · {} discoveries ({} embedded) · {} instincts · {} hits / {} misses",
path.display(),
all.len(),
emb,
inst,
hits,
misses
);
let share = a.flag("share");
let since = a
.opt("since")
.filter(|s| !s.starts_with("--"))
.unwrap_or(if share { "7d" } else { "all" });
let window = meter::parse_since(since)?;
let totals = meter::read(path, window, now_secs());
let bank = meter::Bank { hits, misses, proven: inst };
Ok(if a.flag("json") {
meter::json(&totals, &bank, since)
} else if share {
meter::share(&totals, &bank, since)
} else {
format!("{line}\n{}", meter::block(&totals, &bank, since))
})
}
/// Re-serialise a parsed Json value.
fn json_out(v: &Json) -> String {
match v {
Json::Null => "null".into(),
Json::Bool(b) => b.to_string(),
Json::Num(n) => n.to_string(),
Json::Str(s) => format!("\"{}\"", escape_json(s)),
Json::Arr(a) => format!("[{}]", a.iter().map(json_out).collect::<Vec<_>>().join(",")),
Json::Obj(f) => format!(
"{{{}}}",
f.iter()
.map(|(k, v)| format!("\"{}\":{}", escape_json(k), json_out(v)))
.collect::<Vec<_>>()
.join(",")
),
}
}
// ---------------------------------------------------------------- MCP (JSON-RPC 2.0 over newline-delimited stdio)
fn tool_schema() -> &'static str {
r#"[{"name":"instinct_bank","description":"Call after a fix is verified (a command ran, a test passed, the error is gone) to save it as a lesson. Write `when` in the words a future question will use. Saved as an unverified candidate; evidence text does not make it verified. Set project for a project rule. Omit applicability_harness, applicability_version, applicability_machine and persona unless the rule actually depends on that exact dimension. Values like any or all are literal scope names, not wildcards.","inputSchema":{"type":"object","properties":{"title":{"type":"string"},"when":{"type":"string","description":"the situation/trigger where this applies"},"found":{"type":"string","description":"what was discovered (the fact/fix/lever)"},"how":{"type":"string","description":"the method that found it (probe, measurement, question asked)"},"evidence":{"type":"string","description":"the measured numbers or verification"},"reconsider":{"type":"string","description":"observed or explicitly stated change that would make this method unsuitable"},"tags":{"type":"string"},"project":{"type":"string","description":"exact project applicability; falls back only to explicit INSTINCT_PROJECT"},"persona":{"type":"string","description":"exact persona applicability; falls back only to explicit INSTINCT_PERSONA"},"applicability_harness":{"type":"string","description":"harness this lesson applies to, not the caller or receipt origin"},"applicability_version":{"type":"string","description":"exact applicable harness version, if known"},"applicability_machine":{"type":"string","description":"Restrict this lesson to a named machine only when its setup matters. Omit for portable methods."},"cases":{"type":"object","description":"Optional observed examples of one decision. Rebank the same lesson with new evidence references to extend it.","properties":{"checks":{"type":"array","minItems":1,"maxItems":16,"items":{"type":"object","properties":{"key":{"type":"string"},"question":{"type":"string"},"cost":{"type":"integer","minimum":1}},"required":["key","question","cost"],"additionalProperties":false}},"examples":{"type":"array","minItems":1,"maxItems":128,"items":{"type":"object","properties":{"ref":{"type":"string"},"facts":{"type":"object","additionalProperties":{"type":"boolean"}},"action":{"type":"string"}},"required":["ref","facts","action"],"additionalProperties":false}}},"required":["checks","examples"],"additionalProperties":false},"replay":{"type":"object","description":"A completed gnosis-1 check report. Bank its recomputed held-out result with optional scope fields."}},"oneOf":[{"required":["title","when","found","how","evidence"]},{"required":["replay"]}]}},
{"name":"instinct_default","description":"After banking a lesson, record the user's explicit continuing instruction for its project. Supply their exact instruction and its source reference. Use clear=true to withdraw it. One-time approvals are not continuing instructions.","inputSchema":{"type":"object","properties":{"id":{"type":"string"},"project":{"type":"string"},"persona":{"type":"string"},"instruction":{"type":"string"},"source_ref":{"type":"string"},"clear":{"type":"boolean"}},"required":["id","project"]}},
{"name":"instinct_recall","description":"Call before starting a task that failed or was corrected before, with the task, requested format and any exceptions in q. Select the returned methods that apply to this request. Use none if none apply. Apply selected methods marked proven in use. Check the evidence for other selections. Pass project, persona and harness when known; unspecified context does not match explicitly scoped lessons.","inputSchema":{"type":"object","properties":{"q":{"type":"string"},"k":{"type":"integer"},"project":{"type":"string"},"persona":{"type":"string"},"harness":{"type":"string"},"harness_version":{"type":"string"},"machine":{"type":"string","description":"Exact local alias for matching machine-specific lessons."},"session":{"type":"string"},"facts":{"type":"object","additionalProperties":{"type":"boolean"},"description":"Checks already observed on this task, keyed as given by a casebook on the initial recall. Omit unknown checks."}},"required":["q"]}},
{"name":"instinct_guide","description":"List decision workflows or run one on the current task. Use example for an isolated walkthrough. Read-only. Rehearse and transfer take changed, retry takes correction, verify and debrief take expected and optionally observed. Debrief can include method and exception; transfer can include test and prediction. Experiment chooses a feasible teaching case for a lesson with two observed actions or predicts conditionally under a two-check assumption.","inputSchema":{"type":"object","properties":{"mode":{"type":"string","enum":["list","run","prepare","investigate","review","start","options","challenge","explain","rehearse","transfer","verify","retry","handoff","debrief","experiment"]},"example":{"type":"string"},"steps":{"type":"string","description":"Comma-separated workflow names for run, in order."},"q":{"type":"string"},"changed":{"type":"string"},"expected":{"type":"string"},"observed":{"type":"string"},"correction":{"type":"string"},"method":{"type":"string"},"test":{"type":"string"},"prediction":{"type":"string"},"exception":{"type":"string"},"project":{"type":"string"},"persona":{"type":"string"},"harness":{"type":"string"},"harness_version":{"type":"string"},"machine":{"type":"string"},"id":{"type":"string","description":"The banked personal lesson to study in experiment mode."},"facts":{"type":"object","additionalProperties":{"type":"boolean"},"description":"Observed facts of a case to predict. Omit unknown checks."},"pool":{"type":"array","maxItems":512,"items":{"type":"object","additionalProperties":{"type":"boolean"}},"description":"Feasible teaching cases with all check values and no outcomes. An empty list disables suggestions."},"after_ref":{"type":"string","description":"Show how many explanations this observed reference alone rules out when all other evidence and action labels are held fixed."}},"additionalProperties":false},"annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}},
{"name":"instinct_feedback","description":"Call after acting on a recalled lesson to record one outcome: paid_off true (hit) or false (miss), with a short note. Hits promote a lesson to proven in use.","inputSchema":{"type":"object","properties":{"id":{"type":"string"},"paid_off":{"type":"boolean"},"note":{"type":"string"},"outcome_id":{"type":"string","description":"Reuse the same key when retrying feedback for one observed outcome."},"check":{"type":"boolean","description":"Run the attached read-only check before recording a hit; requires a server root grant."},"trusted_staging":{"type":"boolean","description":"Explicitly acknowledge the granted tree is trusted and quiescent for this observation."},"case":{"type":"object","description":"Append a measured example to this lesson’s existing casebook. Supply the actual successful action, all its observed Boolean facts, matching scope and a stable outcome_id. On a miss use the verified correction.","properties":{"facts":{"type":"object","additionalProperties":{"type":"boolean"}},"action":{"type":"string"}},"required":["facts","action"],"additionalProperties":false},"project":{"type":"string","description":"Current task scope when teaching case feedback."},"persona":{"type":"string","description":"Current task scope when teaching case feedback."},"harness":{"type":"string","description":"Current task scope when teaching case feedback."},"harness_version":{"type":"string","description":"Current task scope when teaching case feedback."},"machine":{"type":"string","description":"Current task scope when teaching case feedback."}},"required":["id","paid_off"]}},
{"name":"instinct_list","description":"Call before a broad task, or to review what is proven: lists the lessons that repeatedly paid off, as WHEN -> DO reflex lines.","inputSchema":{"type":"object","properties":{}}}]"#
}
/// Sent in the MCP `initialize` result so an agent that only has the tools still knows the loop.
const MCP_INSTRUCTIONS: &str = "Instinct is a local memory of what worked. The loop: (1) Before a task that failed or was corrected before, call instinct_recall with the task, requested format and any exceptions. Select the methods that apply to the current request. Use none if none apply. Apply selected lessons marked proven in use. Check the evidence for other selections. (2) After you verify a fix (a command ran, a test passed, the error is gone), call instinct_bank. Write `when` in the words a future question will use, not a description of this session. (3) After acting on a recalled lesson, call instinct_feedback once with paid_off true or false and a short note.";
/// MCP prompts, shown as /mcp__instinct__NAME in Claude Code and /NAME in Gemini CLI: (name, description, text).
const PROMPTS: [(&str, &str, &str); 6] = [
(
"learn",
"Bank the fix that just worked in this conversation as an Instinct lesson",
"Bank the fix that just worked in this conversation as one Instinct lesson.\n\n1. Pick the single fix that was verified here (a command ran, a test passed, the error went away). If nothing was verified yet, say so and stop. Do not bank a guess.\n2. Write the lesson: title (short, names the problem); when (the words a future question would use when the problem shows up again: symptoms, error text, tool names); found (the cause, one sentence); how (the exact fix or command); evidence (what you observed that proves it worked); tags (1 to 3 lowercase words).\n3. Bank it with the instinct_bank tool.\n4. Read it back with instinct_recall using the `when` text and show the saved lesson: id, when, how. If the `when` does not find it, rewrite the `when` and bank again.",
),
(
"recall",
"Show what Instinct already knows about a topic or the current task",
"Call the instinct_recall tool with the topic below (k = 3). If no topic is given, use a one-line summary of the current task. Show each lesson with its id, WHEN, HOW and hit/miss counts as returned. If nothing fits, say 'Instinct has nothing for this yet' in one line and do not invent a lesson. Remember the id of the top lesson for /worked and /wrong.",
),
(
"worked",
"Record that the lesson Instinct recalled last paid off",
"Record one hit on the lesson Instinct recalled last in this conversation.\n\n1. Find the id of the most recent lesson Instinct returned here (an in-xxxxxxx id). If there is none, say so and stop. Do not guess an id.\n2. Write a one-sentence note: what the lesson said and how it helped.\n3. Call instinct_feedback with that id, paid_off true and the note.\n4. Show the id, the note and the new hit/miss counts (instinct_recall with the lesson's `when` prints them).",
),
(
"wrong",
"Record that the lesson Instinct recalled last was wrong or did not help",
"Record one miss on the lesson Instinct recalled last in this conversation.\n\n1. Find the id of the most recent lesson Instinct returned here (an in-xxxxxxx id). If there is none, say so and stop. Do not guess an id.\n2. Write a one-sentence note: what the lesson said and what was true instead.\n3. Call instinct_feedback with that id, paid_off false and the note.\n4. Show the id, the note and the new hit/miss counts (instinct_recall with the lesson's `when` prints them).",
),
(
"grade",
"Grade this folder's agent memory files (CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules)",
"Run `instinct audit` in the project folder (with no file it grades whichever of CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules and .github/copilot-instructions.md exist), then `instinct audit --share`. Show the grade and numbers as printed, then the share line on its own so it can be copied. Say in one sentence how many tokens the file adds to every prompt and how many one Instinct lookup adds instead, and give `instinct import FILE --apply` (with the real file name) as the way to turn its rules into lessons. If no file was found, say so and stop.",
),
(
"saved",
"Show Instinct savings and the shareable one-line summary",
"Run `instinct stats`, then `instinct stats --share`. Show both blocks as printed and add no numbers of your own. If the bank is empty, say Instinct has no lessons yet and that /learn banks the first one.",
),
];
fn recall_receipt(picked: &[String], args: Option<&Json>) -> Option<Json> {
let ids: Vec<Json> = picked.iter().map(|id| Json::Str(id.clone())).collect();
if ids.is_empty() {
return None;
}
let arg = |k: &str| {
args.and_then(|v| v.get(k))
.and_then(Json::as_str)
.unwrap_or("")
.to_string()
};
let mut session = arg("session");
if session.is_empty() {
session = env_or("INSTINCT_SESSION", "unknown-session");
}
let mut harness = arg("harness");
if harness.is_empty() {
harness = env_or("INSTINCT_HARNESS", "unknown");
}
let ns = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
Some(Json::Obj(vec![
("schema_version".into(), Json::Num(1.0)),
(
"event_id".into(),
Json::Str(format!("recall-{}-{ns}", std::process::id())),
),
("ts".into(), Json::Num(now_secs() as f64)),
("session".into(), Json::Str(session)),
("harness".into(), Json::Str(harness)),
("ids".into(), Json::Arr(ids)),
("channel".into(), Json::Str("mcp-recall".into())),
(
"delivery_boundary".into(),
Json::Str("MCP stdout flushed; model use unproven".into()),
),
]))
}
fn receipt_stage(mut meta: Json, stage: &str, text: &str) -> Result<(), String> {
// Opt in per installation. Separate stores do not write into another harness's telemetry.
let root = match std::env::var("INSTINCT_TELEMETRY_DIR") {
Ok(s) if !s.is_empty() => PathBuf::from(s),
_ => return Ok(()),
};
// Fixed paths, no PATH lookup: GNU coreutils on Linux, /sbin on recent macOS, shasum on older macOS.
let mut child = [
("/usr/bin/sha256sum", &[][..]),
("/sbin/sha256sum", &[][..]),
("/usr/bin/shasum", &["-a", "256"][..]),
]
.iter()
.find_map(|(exe, args)| {
std::process::Command::new(exe)
.args(*args)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.ok()
})
.ok_or("no sha256 tool at /usr/bin/sha256sum, /sbin/sha256sum or /usr/bin/shasum")?;
child
.stdin
.take()
.ok_or("hash stdin")?
.write_all(text.as_bytes())
.map_err(|e| e.to_string())?;
let out = child.wait_with_output().map_err(|e| e.to_string())?;
let hash = String::from_utf8_lossy(&out.stdout)
.split_whitespace()
.next()
.unwrap_or("")
.to_string();
if !out.status.success() || hash.len() != 64 {
return Err("receipt hashing failed".into());
}
if let Json::Obj(ref mut fields) = meta {
fields.push(("stage".into(), Json::Str(stage.into())));
fields.push(("excerpt_sha256".into(), Json::Str(hash)));
}
append(
&root.join(if stage == "selected" {
"instinct-injections.jsonl"
} else {
"instinct-deliveries.jsonl"
}),
&json_out(&meta),
)
}
fn bank_payload(
path: &PathBuf,
payload: &Json,
scope: &eligibility::Scope,
) -> Result<String, String> {
let mut derived;
let payload = if let Some(report) = payload.get("replay") {
derived = replay_lesson::from_gnosis(report)?;
let Json::Obj(fields) = payload else {
return Err("bank requires an object".into());
};
let Json::Obj(lesson) = &mut derived else {
return Err("expected a replay lesson".into());
};
let mut keys = HashSet::new();
for (key, value) in fields {
if !keys.insert(key) {
return Err(format!("duplicate bank field {key}"));
}
match key.as_str() {
"replay" => {}
"project"
| "persona"
| "applicability_harness"
| "applicability_version"
| "applicability_machine"
if value.as_str().is_some() =>
{
lesson.push((key.clone(), value.clone()));
}
_ => return Err(format!("unexpected field alongside replay: {key}")),
}
}
&derived
} else {
payload
};
let text = |key| {
payload
.get(key)
.and_then(Json::as_str)
.unwrap_or("")
.to_owned()
};
let lesson = BankIn {
title: text("title"),
when: text("when"),
found: text("found"),
how: text("how"),
evidence: text("evidence"),
reconsider: text("reconsider"),
tags: text("tags"),
project: text("project"),
persona: text("persona"),
applicability_harness: text("applicability_harness"),
applicability_version: text("applicability_version"),
applicability_machine: payload
.get("applicability_machine")
.map(|_| text("applicability_machine")),
};
let cases = payload
.get("cases")
.map(case_learning::Casebook::parse)
.transpose()?;
op_bank_cases(path, lesson, cases, scope)
}
/// Scope belongs to the importing caller. A shared file describes the method and its evidence.
fn bank_from(path: &PathBuf, args: &Args, source: &str) -> Result<String, String> {
let mut keys = HashSet::new();
if !args.pos.is_empty()
|| args.kv.iter().any(|(key, _)| {
!matches!(key.as_str(), "from" | "store" | "project" | "persona") || !keys.insert(key)
})
{
return Err("use bank --from SOURCE with optional --project, --persona and --store".into());
}
let raw = match source {
"builtin:zip-handoff" => {
include_str!("../skills/instinct/references/zip-handoff.json").to_owned()
}
"builtin:verify-handoff" => {
include_str!("../skills/instinct/references/verify-handoff.json").to_owned()
}
"-" => {
let mut raw = String::new();
std::io::stdin()
.read_to_string(&mut raw)
.map_err(|e| format!("read lesson from stdin: {e}"))?;
raw
}
file => fs::read_to_string(file).map_err(|e| format!("read lesson file {file}: {e}"))?,
};
let payload = parse_json(&raw)?;
if payload.get("protocol").and_then(Json::as_str) == Some("gnosis-1") {
let lesson = replay_lesson::from_gnosis(&payload)?;
return bank_payload(path, &lesson, &eligibility::env_scope());
}
let Json::Obj(fields) = &payload else {
return Err("lesson file must be a JSON object".into());
};
let mut seen = HashSet::new();
for (key, value) in fields {
if !seen.insert(key)
|| !matches!(
key.as_str(),
"title" | "when" | "found" | "how" | "evidence" | "reconsider" | "tags" | "cases"
)
|| (key != "cases" && value.as_str().is_none())
{
return Err(format!("invalid or repeated lesson field {key}"));
}
}
bank_payload(path, &payload, &eligibility::env_scope())
}
fn mcp_call(
cache: &mut Option<recall_index::Index>,
path: &PathBuf,
name: &str,
args: Option<&Json>,
) -> Result<(String, Vec<String>), String> {
let s = |k: &str| {
args.and_then(|a| a.get(k))
.and_then(Json::as_str)
.unwrap_or("")
.to_string()
};
let request_scope = || {
let mut scope = eligibility::env_scope();
for (key, dest) in [
("project", &mut scope.project),
("persona", &mut scope.persona),
("harness", &mut scope.harness),
("harness_version", &mut scope.version),
("machine", &mut scope.machine),
] {
let v = s(key);
if !v.is_empty() {
*dest = v;
}
}
scope
};
let out = match name {
"instinct_bank" => bank_payload(path, args.ok_or("bank needs lesson fields")?, &request_scope()),
"instinct_default" => {
let mut kv = vec![("project".into(), s("project"))];
for (key, option) in [("instruction", "instruction"), ("source_ref", "source-ref")] {
if let Some(value) = args.and_then(|a| a.get(key)) {
kv.push((option.into(), value.as_str().ok_or("expected text in default instruction and source_ref")?.into()));
}
}
match args.and_then(|a| a.get("clear")) {
Some(Json::Bool(true)) => kv.push(("clear".into(), String::new())),
None | Some(Json::Bool(false)) => {}
_ => return Err("clear requires a boolean".into()),
}
rehearsal::set_default(path, &Args { pos: vec![s("id")], kv }, &request_scope())
}
"instinct_guide" => {
let empty = Json::Obj(vec![]);
guide::run(|| Ok(path.clone()), args.unwrap_or(&empty), &request_scope()).map(|v| json_out(&v))
}
"instinct_recall" => {
let k = args
.and_then(|a| a.get("k"))
.and_then(Json::as_f64)
.unwrap_or(5.0) as usize;
let scope = request_scope();
let timer = meter::start(path, "mcp");
return recall_index::recall(cache, path, &s("q"), k.clamp(1, 20), &scope).and_then(
|methods| {
let facts = args.and_then(|a| a.get("facts"));
let methods = case_candidates(path, &s("q"), &scope, facts, methods)?;
let (r, ids) = render_recall_with_facts(&methods, facts)?;
if let Some(t) = timer {
t.finish(ids.len(), r.len());
}
Ok((
if r.is_empty() {
"(nothing banked matches)".into()
} else {
r
},
ids,
))
},
);
}
"instinct_feedback" => {
// A missing or misspelled flag used to record a silent "miss" (2026-10-20: `paid: true` became a miss, and old
// misses carry notes that read like wins). Now: accept the obvious spellings, refuse anything else.
let flag = ["paid_off", "paid", "helped", "hit"]
.iter()
.find_map(|k| args.and_then(|a| a.get(k)));
let paid = match flag {
Some(Json::Bool(b)) => *b,
_ => return Err("instinct_feedback needs paid_off: true (helped) or false (misled); nothing recorded".into()),
};
if let Some(observation) = args.and_then(|a| a.get("case")) {
if args.is_some_and(|a| ["check","trusted_staging","root"].iter().any(|k| a.get(k).is_some())) {
return Err("case feedback uses the observed example and cannot be combined with checked-feedback options".into());
}
return op_mark_case(path, if paid {"hit"} else {"miss"}, &s("id"), &s("note"),
&s("outcome_id"), observation, &request_scope()).map(|r| (r, vec![]));
}
if let Some(flag) = args.and_then(|a| a.get("check")) {
if !matches!(flag, Json::Bool(_)) { return Err("check must be boolean".into()); }
if flag == &Json::Bool(true) {
if !paid { return Err("checked feedback requires paid_off true".into()); }
if args.is_some_and(|a| a.get("root").is_some()) { return Err("request cannot override server root grant".into()); }
let root = std::env::var("INSTINCT_CHECK_ROOT").unwrap_or_default();
let trusted = args.and_then(|a| a.get("trusted_staging")) == Some(&Json::Bool(true));
refuse_team_check(path, &s("id"))?;
return check::feedback::hit(path, &s("id"), &s("note"), &s("outcome_id"), &root, trusted).map(|r| (r, vec![]));
}
}
op_mark(
path,
if paid { "hit" } else { "miss" },
&s("id"),
&s("note"),
&s("outcome_id"),
)
}
"instinct_list" => op_instincts(path, 2).map(|r| {
if r.is_empty() {
"(no instincts yet — discoveries become instincts after 2+ hits)".into()
} else {
r
}
}),
_ => Err(format!("unknown tool {name}")),
};
out.map(|text| (text, Vec::new()))
}
/// Tools that change the bank. `instinct serve` refuses them (and hides them) unless started with --allow-write.
const WRITE_TOOLS: [&str; 3] = ["instinct_bank", "instinct_feedback", "instinct_default"];
/// One JSON-RPC line in, at most one reply line out. The stdio loop and `instinct serve` both call this, so the
/// tools are identical on both transports. `allow_write` is always true on stdio. The second value is the recall
/// delivery receipt the caller stages after it has sent the reply.
fn mcp_message(
cache: &mut Option<recall_index::Index>,
path: &PathBuf,
line: &str,
allow_write: bool,
) -> Option<(String, Option<(Json, String)>)> {
let msg = parse_json(line).ok()?;
let id = msg.get("id")?; // notifications get no reply
{
let id_txt = match id {
Json::Num(n) => format!("{}", *n as i64),
Json::Str(s) => format!("\"{}\"", escape_json(s)),
_ => "null".into(),
};
let method = msg.get("method").and_then(Json::as_str).unwrap_or("");
let mut delivery: Option<(Json, String)> = None;
let result = match method {
"initialize" => {
let pv = msg
.get("params")
.and_then(|p| p.get("protocolVersion"))
.and_then(Json::as_str)
.unwrap_or("2024-11-05");
format!("{{\"protocolVersion\":\"{}\",\"capabilities\":{{\"tools\":{{}},\"prompts\":{{}}}},\"serverInfo\":{{\"name\":\"instinct\",\"version\":\"{}\"}},\"instructions\":\"{}\"}}", escape_json(pv), env!("CARGO_PKG_VERSION"), escape_json(MCP_INSTRUCTIONS))
}
"prompts/list" => {
let items: Vec<String> = PROMPTS
.iter()
.map(|(name, desc, _)| {
format!(
"{{\"name\":\"{name}\",\"description\":\"{}\",\"arguments\":[{{\"name\":\"text\",\"description\":\"optional detail\",\"required\":false}}]}}",
escape_json(desc)
)
})
.collect();
format!("{{\"prompts\":[{}]}}", items.join(","))
}
"prompts/get" => {
let p = msg.get("params");
let name = p.and_then(|p| p.get("name")).and_then(Json::as_str).unwrap_or("");
let text = p
.and_then(|p| p.get("arguments"))
.and_then(|a| a.get("text"))
.and_then(Json::as_str)
.unwrap_or("")
.trim();
let Some((_, desc, body)) = PROMPTS.iter().find(|(n, _, _)| *n == name) else {
return Some((format!("{{\"jsonrpc\":\"2.0\",\"id\":{id_txt},\"error\":{{\"code\":-32602,\"message\":\"unknown prompt {}\"}}}}", escape_json(name)), None));
};
let extra = if text.is_empty() { String::new() } else { format!("\n\nFrom the user: {text}") };
format!(
"{{\"description\":\"{}\",\"messages\":[{{\"role\":\"user\",\"content\":{{\"type\":\"text\",\"text\":\"{}\"}}}}]}}",
escape_json(desc),
escape_json(&format!("{body}{extra}"))
)
}
"tools/list" => {
let existing = tool_schema().replace('\n', "");
let all = format!("{{\"tools\":{},{}]}}", existing.trim_end_matches(']'), check::mcp::SCHEMA);
if allow_write {
all
} else {
// Read-only: list only the tools that cannot change the bank.
let Ok(Json::Obj(mut fields)) = parse_json(&all) else { return None };
for (_, v) in fields.iter_mut() {
if let Json::Arr(tools) = v {
tools.retain(|t| !t.get("name").and_then(Json::as_str).is_some_and(|n| WRITE_TOOLS.contains(&n)));
}
}
json_out(&Json::Obj(fields))
}
},
"tools/call" => {
let p = msg.get("params");
let name = p
.and_then(|p| p.get("name"))
.and_then(Json::as_str)
.unwrap_or("");
let (text, picked, err) =
match if !allow_write && WRITE_TOOLS.contains(&name) {
Err(format!("{name} changes the bank and this server is read-only; restart `instinct serve` with --allow-write"))
} else if name == "instinct_check" {
check::mcp::call_wire(line)
} else {
mcp_call(cache, path, name, p.and_then(|p| p.get("arguments")))
} {
Ok((t, ids)) => (t, ids, false),
Err(e) => (e, Vec::new(), true),
};
if name == "instinct_recall" && !err {
if let Some(meta) = recall_receipt(&picked, p.and_then(|p| p.get("arguments")))
{
if let Err(e) = receipt_stage(meta.clone(), "selected", &text) {
eprintln!("instinct telemetry: {e}");
}
delivery = Some((meta, text.clone()));
}
}
format!(
"{{\"content\":[{{\"type\":\"text\",\"text\":\"{}\"}}],\"isError\":{err}}}",
escape_json(&text)
)
}
"ping" => "{}".into(),
_ => {
return Some((format!("{{\"jsonrpc\":\"2.0\",\"id\":{id_txt},\"error\":{{\"code\":-32601,\"message\":\"method not found\"}}}}"), None));
}
};
Some((format!("{{\"jsonrpc\":\"2.0\",\"id\":{id_txt},\"result\":{result}}}"), delivery))
}
}
fn mcp(path: &PathBuf) -> Result<(), String> {
let mut cache = None;
let stdin = std::io::stdin();
let mut out = std::io::stdout();
for line in stdin.lock().lines() {
let line = line.map_err(|e| format!("stdin: {e}"))?;
if line.trim().is_empty() {
continue;
}
let Some((reply, delivery)) = mcp_message(&mut cache, path, &line, true) else { continue };
writeln!(out, "{reply}").map_err(|e| format!("stdout: {e}"))?;
out.flush().map_err(|e| format!("stdout flush: {e}"))?;
if let Some((meta, text)) = delivery {
if let Err(e) = receipt_stage(meta, "delivered", &text) {
eprintln!("instinct telemetry: {e}");
}
}
}
Ok(())
}
// ---------------------------------------------------------------- main
const USAGE: &str = "instinct: a local memory of what worked, for any AI agent
usage: instinct COMMAND [options]
deterministic checks
check validate|run|explain --input FILE|-
evaluate a bounded predicate over supplied facts; no bank or action access
pass is not authorization; missing evidence abstains
check observe --root ABS --input FILE|-
read-only staging inventory under an explicit caller trust assumption
check attach --lesson ID --store BANK --input FILE|-
attach a read-only artifact policy; no hit is recorded
hit ID --check --root ABS --trusted-staging --outcome-id KEY
record a hit only after the attached observed check passes
everyday
bank --title T --when W --found F --how H --evidence E [--tags a,b] [--cases JSON|-]
bank --from FILE|-|builtin:verify-handoff|builtin:zip-handoff [--project NAME]
save a lesson; write WHEN in the words a future question will use
recall --q QUESTION [--k 5] [--facts JSON|-]
the lessons that fit (a lesson marked proven has paid off in use)
probe --expect ID --q QUESTION [--k 5]
check the receiving scope; exit 0 only if the expected lesson is selected
show ID [ID...] the full lesson(s), as recall prints them
hit ID [--note N] [--outcome-id KEY] [--case JSON|-]
a recalled lesson paid off; reuse KEY on a retry so one outcome counts once
miss ID [--note N] [--outcome-id KEY] [--case JSON|-]
it did not
instincts [--min-hits 2] the lessons that proved themselves
stats [--since 7d|30d|all] [--json|--share]
eval [--since 7d|30d|all] [--json] [--apply-quarantine] [--store PATH]
what the bank did for you: paid off, misled, never judged, never fired,
near-duplicates, savings, next three actions; reads only
connect codex [--trust] | connect claude [--user]
wire the hooks: Codex hooks.json (--trust: trust only those), or the Claude Code
plugins at project scope (--user: every project)
connect cursor|vscode|gemini|windsurf [--user] [--dry-run]
add the instinct MCP server to that harness's config (merges, backs up, idempotent)
codex-trust [--check] trust the instinct hooks in Codex CLI (Codex skips untrusted hooks silently)
doctor [--json] [--online] [--store PATH] [--fix]
doctor --waits [--min-age MIN] [--fix]
doctor --leftovers [--fix] [--min-age MIN] [--quiet]
stale waits, orphaned agent processes (headless browsers, sleep, tail -f /dev/null,
test binaries) and merged idle worktrees; --fix stops/removes only those
find wait loops (until/while + sleep, tail --pid, pgrep) whose result is in or that
match themselves; --fix stops them (your user only; Linux)
is Instinct wired up here: the bank, when each hook last ran, and each agent's
config (Claude Code, Codex, Gemini CLI, Cursor), with the next command for each;
--fix runs the repairs that only touch Instinct's own bank or hooks (starter
tripwires, connect claude/codex), is a no-op when nothing is needed, and only prints
anything that is another program's file (an older instinct earlier on PATH)
gap; reads only, never writes, exit 0
audit [FILE...] [--share] [--json] [--k N]
grade memory files by tokens per prompt (A <= 400 ... F above 5000);
no FILE: every CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules and
.github/copilot-instructions.md in this folder
mine [PATHS...] [--since 7d] [--project P] [--limit 10] [--apply] [--json]
find lesson candidates in past Claude Code and Codex sessions;
a dry run unless --apply. Mining finds candidates; you decide what to bank
learn [PATHS...] [--days 30] [--project P] [--limit 10] [--apply] [--json]
propose tripwires (and fixes) from commands that failed and were retried
in a corrected form in your own transcripts; replay-scored; a dry run unless --apply
scan [--days 30] [--json] [--share]
what your agent got wrong in the last 30 days and what Instinct would have caught;
reads your Claude Code and Codex transcripts, read-only, no bank needed
starter [--apply] [--json] [--store PATH]
fix --dry-run COMMAND
the community tripwire pack: lessons for classic agent disasters (rm -rf on
an unset variable, force pushes, DROP TABLE ...); a dry run unless --apply
team init share lessons through this repo: creates .instinct/ with a union-merge rule;
`bank --team` writes there, hits and misses on those lessons follow;
INSTINCT_TEAM=0 turns the project bank off
sync pull --from PATH append the events this bank lacks from another bank file (hxdb or jsonl);
a corrupt source stops the pull before any write; pulling twice adds nothing
sync push --to PATH the same, in the other direction
sync status --with PATH how many events each side lacks; read-only
demo [SITUATION] a short tour in a temporary bank
skill [--guide] print the agent skill
hooks and agents
mcp MCP server on stdio
serve [--port N] [--host H] [--allow-write] | serve --init-key
MCP over HTTP on 127.0.0.1 only (prototype); first run `serve --init-key`, see docs/serve.md
prompt [--project P] [--format cline|text]
UserPromptSubmit hook: one fitting lesson per prompt
guard [--project P] [--format text|json]
pre-tool hook: warns when a saved lesson fits the command
timing PostToolUse hook: records how long each kind of Bash command takes (the class only,
never the command); INSTINCT_TIMING=0 turns it off
speed [--json] [--limit N] | speed --import [--days 30]
where the time goes: slowest command classes, p50/p95, a faster route for each
settle [--format claude|codex|text]
Stop hook: asks once per session for a hit or miss on a lesson it used
track PostToolUse and PostToolUseFailure hook: records failed Bash commands (INSTINCT_RETRY=1)
stop Stop hook: sends a done claim back once after a correction when nothing ran
since the last change (INSTINCT_DONE_GATE=1)
outcomes [TRANSCRIPTS...] [--since 7d] [--apply] [--json]
what happened after each delivered lesson, read from the Claude Code or
Codex transcript: helped, misled, unused or unclear, with the evidence;
--apply records hits and misses (idempotent). INSTINCT_EXPLORE=0.1
withholds that share of deliveries so they can be compared
maintenance
import FILE... [--project P] [--apply]
export | migrate --to NEW.hxdb | reembed [--when]
retract hit|miss ID | unsupersede ID | review ID --state quarantined --reason WHY --source-ref REF
default ID --project P (--instruction TEXT --source-ref REF | --clear)
guidebook print the self-contained HTML field guide
guide experiment --id ID [--pool JSON|-] [--facts JSON|-] [--after-ref REF] choose a teaching case or inspect a conditional prediction
guide [MODE] explore ten decision workflows. Try guide list or guide challenge --example website
dream --q USUAL --changed EXCEPTION | decide --q SITUATION [--facts JSON|-]
bank scope options: --project P --persona P --applicability-harness H --applicability-version V
--applicability-machine M --reconsider R
store: $INSTINCT_STORE, else $XDG_DATA_HOME/instinct/bank.hxdb, else ~/.local/share/instinct/bank.hxdb
(%LOCALAPPDATA%\\instinct\\bank.hxdb on Windows); --store PATH overrides for one call";
/// The lines of USAGE that describe `cmd`: every entry (two-space indent) whose first word is `cmd`, with its
/// continuation lines. None when USAGE has no such entry.
fn usage_for(cmd: &str) -> Option<String> {
let mut out = String::new();
let mut inside = false;
for line in USAGE.lines() {
let entry = line.starts_with(" ") && !line.starts_with(" ");
if entry {
inside = line.trim_start().split_whitespace().next() == Some(cmd);
}
if inside {
out.push_str(line);
out.push('\n');
}
}
(!out.is_empty()).then(|| format!("usage: instinct {cmd} ...\n{}", out.trim_end()))
}
fn run(argv: &[String]) -> Result<(), String> {
let cmd = argv.first().map(String::as_str).unwrap_or("");
if matches!(cmd, "" | "--help" | "-h" | "help") {
println!("{USAGE}");
return Ok(());
}
if matches!(cmd, "--version" | "-V") {
println!("instinct {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
// `instinct doctor|codex-trust|connect --help` print that command's own usage (they used to fail or say nothing useful).
if matches!(argv.get(1).map(String::as_str), Some("--help" | "-h")) && matches!(cmd, "doctor" | "codex-trust" | "connect") {
if let Some(u) = usage_for(cmd) {
println!("{u}");
return Ok(());
}
}
if cmd == "continue-tasks" {
return continuation::cli(&argv[1..]);
}
if cmd == "skill" {
let content = match &argv[1..] {
[] => include_str!("../skills/instinct/SKILL.md"),
[arg] if arg == "--guide" => {
include_str!("../skills/instinct/references/architecture.md")
}
_ => return Err("usage: instinct skill [--guide]".into()),
};
print!("{content}");
return Ok(());
}
if cmd == "guidebook" {
if argv.len() != 1 {
return Err("usage: instinct guidebook > instinct-guidebook.html".into());
}
println!("{}", guide::book()?);
return Ok(());
}
if cmd == "demo" {
if argv.len() > 2 {
return Err("usage: instinct demo [quoted situation]".into());
}
return demo::run(argv.get(1).map(String::as_str));
}
if cmd == "learn" {
return learn::run(&argv[1..]);
}
if cmd == "connect" {
return connect::run(&argv[1..]);
}
if cmd == "codex-trust" {
return codex_trust::run(&argv[1..]);
}
if cmd == "doctor" {
return doctor::run(&argv[1..]);
}
if cmd == "audit" {
return audit::run_audit(&argv[1..]);
}
if cmd == "import" {
return audit::run_import(&argv[1..]);
}
if cmd == "team" {
return match argv.get(1).map(String::as_str) {
Some("init") if argv.len() == 2 => {
let here = std::env::current_dir().map_err(|e| format!("no working folder: {e}"))?;
println!("{}", team::init(&here)?);
Ok(())
}
_ => Err("usage: instinct team init".into()),
};
}
if cmd == "fix" {
return fix::run(&argv[1..]);
}
if cmd == "starter" {
return starter::run(&argv[1..]);
}
if cmd == "scan" {
return scan::run(&argv[1..]);
}
if cmd == "gates-trace" {
gates::trace(&argv[1..]);
return Ok(());
}
if cmd == "mine" {
return mine::run(&argv[1..]);
}
const STORE_CMDS: &[&str] = &[
"migrate", "export", "bank", "default", "dream", "decide", "guide", "prompt", "recall", "probe", "show", "review", "hit", "miss",
"instincts", "stats", "eval", "reembed", "unsupersede", "retract", "mcp", "serve", "guard", "settle", "track", "stop", "outcomes", "timing", "speed", "sync",
];
if !STORE_CMDS.contains(&cmd) {
return Err(format!("unknown command {cmd}\n\n{USAGE}"));
}
// These run once and exit: the lessons read for the lookup are not worth freeing one by one.
if matches!(cmd, "prompt" | "guard" | "recall" | "show" | "timing") {
ONE_SHOT.store(true, std::sync::atomic::Ordering::Relaxed);
}
if cmd != "guard" && matches!(argv.get(1).map(String::as_str), Some("--help" | "-h")) {
println!("{USAGE}");
return Ok(());
}
let a = Args::parse(argv.get(1..).unwrap_or(&[]));
if cmd == "guard" {
guard::run(&a);
return Ok(());
}
if cmd == "track" {
gates::track(&a);
return Ok(());
}
if cmd == "stop" {
gates::stop(&a);
return Ok(());
}
if cmd == "timing" {
speed::run_post(&a);
return Ok(());
}
if cmd == "speed" {
speed::run(&a);
return Ok(());
}
if cmd == "settle" {
session::settle(&a);
return Ok(());
}
for (key, env) in [
("project", "INSTINCT_PROJECT"),
("persona", "INSTINCT_PERSONA"),
("harness", "INSTINCT_HARNESS"),
("harness-version", "INSTINCT_HARNESS_VERSION"),
("machine", "INSTINCT_MACHINE"),
] {
if let Some(v) = a.opt(key) {
std::env::set_var(env, v);
}
}
let mut stdin_used = false;
if cmd == "guide" {
if a.pos.len() > 1 {
return Err("supply one guide mode. Use guide list".into());
}
if a.pos.first().is_some_and(|mode| mode == "experiment") {
let mut seen = HashSet::new();
for (key, value) in &a.kv {
let allowed = matches!(key.as_str(), "id" | "facts" | "pool" | "after-ref" | "json"
| "store" | "project" | "persona" | "machine" | "harness" | "harness-version");
if !allowed || !seen.insert(key) || (key == "json") != value.is_empty() {
return Err(format!("invalid or repeated guide experiment option --{key}"));
}
}
}
let mut fields = vec![("mode".into(), Json::Str(a.pos.first().cloned().unwrap_or_default()))];
for key in ["q", "example", "steps", "changed", "expected", "observed", "correction", "method", "test", "prediction", "exception", "id"] {
if a.flag(key) {
if a.opt(key) == Some("-") && stdin_used {
return Err("only one guide input can come from stdin".into());
}
fields.push((key.into(), Json::Str(a.text(key, &mut stdin_used)?)));
}
}
if a.flag("after-ref") {
fields.push(("after_ref".into(), Json::Str(a.text("after-ref", &mut stdin_used)?)));
}
for key in ["facts", "pool"] {
if let Some(value) = a.optional_json(key, &mut stdin_used)? {
fields.push((key.into(), value));
}
}
let result = guide::run(|| store_path(&a), &Json::Obj(fields), &eligibility::env_scope())?;
println!("{}", if a.flag("json") {json_out(&result)} else {guide::display(&result)});
return Ok(());
}
// The store is resolved only now, for commands that read or write it.
let path = store_path(&a)?;
if a.opt("store").is_none() && std::env::var_os("INSTINCT_STORE").map_or(true, |v| v.is_empty()) {
ensure_default_dir(&path)?;
}
let out = match cmd {
"migrate" => {
if !path.is_file() {
return Err("source bank does not exist".into());
}
let dest = PathBuf::from(a.opt("to").ok_or("supply --to NEW.hxdb")?);
let snapshot = journal::read(&path)?;
let count = helix_db::import(&dest, &snapshot)?;
format!("migrated {count} events to {}", dest.display())
}
"export" => {
if !path.is_file() {
return Err("source bank does not exist".into());
}
let snapshot = journal::read(&path)?;
for line in snapshot.lines().filter(|s| !s.trim().is_empty()) {
parse_json(line)?;
}
print!("{snapshot}");
return Ok(());
}
"bank" if a.opt("from").is_some() => bank_from(&path, &a, a.opt("from").unwrap())?,
"bank" => {
if a.flag("cases") && a.flag("team") {
return Err("bank case evidence in a personal bank with the project's scope".into());
}
let cases = a.optional_json("cases", &mut stdin_used)?.as_ref().map(case_learning::Casebook::parse).transpose()?;
let bank = if a.flag("team") { team_bank_path(&path)? } else { path.clone() };
let lesson = BankIn {
title: a.text("title", &mut stdin_used)?,
when: a.text("when", &mut stdin_used)?,
found: a.text("found", &mut stdin_used)?,
how: a.text("how", &mut stdin_used)?,
evidence: a.text("evidence", &mut stdin_used)?,
reconsider: a.text("reconsider", &mut stdin_used)?,
tags: a.text("tags", &mut stdin_used)?,
project: a.text("project", &mut stdin_used)?,
persona: a.text("persona", &mut stdin_used)?,
applicability_harness: a.text("applicability-harness", &mut stdin_used)?,
applicability_version: a.text("applicability-version", &mut stdin_used)?,
applicability_machine: a.opt("applicability-machine").map(str::to_owned),
};
op_bank_cases(&bank, lesson, cases, &eligibility::env_scope())?
}
"default" => rehearsal::set_default(&path, &a, &eligibility::env_scope())?,
"dream" => rehearsal::dream(
&path,
&a.text("q", &mut stdin_used)?,
&a.text("changed", &mut stdin_used)?,
&eligibility::env_scope(),
)?,
"decide" => decision_context(
&path,
&a.text("q", &mut stdin_used)?,
&eligibility::env_scope(),
a.optional_json("facts", &mut stdin_used)?.as_ref(),
)?,
"prompt" => {
let mut input = String::new();
std::io::stdin()
.read_to_string(&mut input)
.map_err(|e| e.to_string())?;
let event = parse_json(&input)?;
let format = a.opt("format");
let cline = format == Some("cline") || event.get("userPromptSubmit").is_some();
let cline_json = cline && format != Some("text");
let (query, cwd, sid) = if cline {
let query = event.get("userPromptSubmit").and_then(|p| p.get("prompt")).and_then(Json::as_str);
let is_submit = event.get("hookName").is_none_or(|name| name.as_str() == Some("UserPromptSubmit"));
let (Some(query), Ok(root), true) = (query.filter(|q| !q.trim().is_empty()), cline_workspace(&event), is_submit) else {
if cline_json {
println!("{}", cline_reply(""));
}
return Ok(());
};
if root.is_none() {
// Without a workspace, the launcher's cwd cannot identify a team bank.
std::env::set_var("INSTINCT_TEAM", "0");
}
let task = event.get("taskId").and_then(Json::as_str).and_then(session::clean);
(query, root, task.and_then(|id| session::clean(&format!("cline:{id}"))))
} else {
let query = event.get("prompt").and_then(Json::as_str).unwrap_or("");
let cwd = event.get("cwd").and_then(Json::as_str);
let sid = event.get("session_id").and_then(Json::as_str).and_then(session::clean);
(query, cwd, sid)
};
team::set_cwd(cwd);
let mut scope = eligibility::prompt_scope(a.opt("project"), cwd);
if cline {
scope.harness = "cline".into();
scope.version = event.get("clineVersion").and_then(Json::as_str).unwrap_or("").into();
}
// First run: a bank that does not exist yet gets the starter tripwires before this call is answered.
let explicit = a.opt("store").is_some() || std::env::var_os("INSTINCT_STORE").is_some_and(|v| !v.is_empty());
let seeded = starter::seed_first_run(&path, explicit);
let mut text = recall_once_per_session(&path, "prompt", query, &scope, sid.as_deref())?.0;
// Opt-in lesson index: the first prompt of a session also carries the compact list.
if index_wanted(&a) {
if let Some(s) = sid.as_deref() {
if session::claim_index(&path, s) {
let block = index_block(&path, &scope)?;
if !block.is_empty() {
text = if text.trim().is_empty() { block } else { format!("{block}\n\n{text}") };
}
}
}
}
if cline_json {
println!("{}", cline_reply(&text));
return Ok(());
}
match seeded {
None => text,
Some(n) => {
// The seeding call only: Claude Code JSON carries the notice for the user as `systemMessage`
// and the lesson as context; `--format text` prints the notice as one plain line first.
let notice = starter::first_run_notice(n);
if a.opt("format") == Some("text") {
if text.trim().is_empty() { notice } else { format!("{notice}\n{text}") }
} else if text.trim().is_empty() {
format!("{{\"systemMessage\":\"{}\"}}", escape_json(¬ice))
} else {
format!(
"{{\"systemMessage\":\"{}\",\"hookSpecificOutput\":{{\"hookEventName\":\"UserPromptSubmit\",\"additionalContext\":\"{}\"}}}}",
escape_json(¬ice),
escape_json(&text)
)
}
}
}
}
"outcomes" => outcomes::run(&path, &a)?,
"sync" => op_sync(&path, &a)?,
"show" => op_show(&path, &a.pos)?,
"probe" => probe_recall(&path, &a, &a.text("q", &mut stdin_used)?)?,
"recall" => meter::recall_text(&path, "recall", &a.text("q", &mut stdin_used)?, a.num("k", 5), &eligibility::env_scope(), a.optional_json("facts", &mut stdin_used)?.as_ref())?,
"review" => op_review(
&path,
a.pos.first().ok_or("review ID required")?,
a.opt("state").unwrap_or(""),
a.opt("reason").unwrap_or(""),
a.opt("source-ref").unwrap_or(""),
)?,
"hit" | "miss" if a.flag("case") => {
if a.pos.len()!=1 || ["check","trusted-staging","root","team"].iter().any(|k| a.flag(k)) {
return Err("case feedback needs one personal lesson ID and a directly observed outcome".into());
}
let observation = a.optional_json("case", &mut stdin_used)?.ok_or("missing --case JSON")?;
op_mark_case(&path,cmd,&a.pos[0],a.opt("note").unwrap_or(""),a.opt("outcome-id").unwrap_or(""),
&observation,&eligibility::env_scope())?
},
"hit" | "miss" if a.flag("check") => {
if cmd != "hit" { return Err("miss --check is not supported; nothing recorded".into()); }
let mut seen = HashSet::new();
for (key, value) in &a.kv {
if !["check", "trusted-staging", "root", "outcome-id", "note", "store", "project", "persona", "harness", "harness-version", "machine"].contains(&key.as_str()) || !seen.insert(key) {
return Err("unknown or repeated checked-feedback option; nothing recorded".into());
}
if matches!(key.as_str(), "check" | "trusted-staging") && !value.is_empty() {
return Err("--check and --trusted-staging are bare flags, not boolean values; nothing recorded".into());
}
}
if a.pos.len() != 1 { return Err("checked feedback requires exactly one lesson ID".into()); }
refuse_team_check(&path, a.pos.first().ok_or("hit ID required")?)?;
check::feedback::hit(&path, a.pos.first().ok_or("hit ID required")?, a.opt("note").unwrap_or(""), a.opt("outcome-id").unwrap_or(""), a.opt("root").unwrap_or(""), a.flag("trusted-staging"))?
},
"hit" | "miss" => op_mark(
&path,
cmd,
a.pos.first().ok_or("usage: hit|miss ID [--note N] [--outcome-id KEY]")?,
a.opt("note").unwrap_or(""),
a.opt("outcome-id").unwrap_or(""),
)?,
"instincts" => op_instincts(&path, a.num("min-hits", 2) as u32)?,
"stats" => op_stats(&path, &a)?,
"eval" => eval::run(&path, &a)?,
"reembed" => {
if a.flag("when") {
op_reembed_when(&path)?
} else {
op_reembed(&path)?
}
}
"unsupersede" => {
let id = a.pos.first().ok_or("usage: unsupersede ID [--note N]")?;
append(
&path,
&format!(
"{{\"kind\":\"unsupersede\",\"id\":\"{}\",\"ts\":{},\"note\":\"{}\"}}",
escape_json(id),
now_secs(),
escape_json(a.opt("note").unwrap_or(""))
),
)?;
format!("unsuperseded {id} (back in recall)")
}
"retract" => {
let of = a.pos.first().map(String::as_str).unwrap_or("");
let id = a
.pos
.get(1)
.ok_or("usage: retract hit|miss ID [--note N]")?;
if of != "hit" && of != "miss" {
return Err("usage: retract hit|miss ID [--note N]".into());
}
append(&path, &format!("{{\"kind\":\"retract\",\"of\":\"{of}\",\"id\":\"{}\",\"ts\":{},\"note\":\"{}\"}}", escape_json(id), now_secs(), escape_json(a.opt("note").unwrap_or(""))))?;
format!("retracted one {of} on {id}")
}
"mcp" => return mcp(&path),
#[cfg(not(target_arch = "wasm32"))]
"serve" => return serve::run(&a, &path),
_ => return Err(USAGE.into()),
};
if !out.is_empty() {
println!("{out}");
}
Ok(())
}
fn main() {
let argv: Vec<String> = std::env::args().skip(1).collect();
// Check operations are opt-in; attach is an explicit bank-sidecar mutation.
if argv.first().map(String::as_str) == Some("check") {
process::exit(check::cli(&argv[1..]));
}
if let Err(e) = run(&argv) {
eprintln!("instinct: {e}");
// `prompt` runs as a UserPromptSubmit hook. Claude Code reads exit 2 as "block and erase the
// prompt", so a missing store, a bad payload or a damaged bank must never cost the user their
// message: drain the payload and exit 0, leaving the note above on stderr.
if argv.first().map(String::as_str) == Some("prompt") {
let _ = std::io::copy(&mut std::io::stdin().take(1 << 20), &mut std::io::sink());
if Args::parse(&argv[1..]).opt("format") == Some("cline") {
println!("{}", cline_reply(""));
}
process::exit(0);
}
process::exit(2);
}
}
/// Browser playground surface: the real banking, BM25 + RRF ranking, eligibility and quiet rules over an
/// in-memory bank. Compiled only for wasm32, so native builds do not contain it. One JSON request in,
/// one JSON reply out; `playground/` wraps `handle` in raw `extern "C"` exports.
#[cfg(target_arch = "wasm32")]
pub mod playground_api {
use super::*;
use std::cell::RefCell;
use std::sync::atomic::{AtomicU64, Ordering};
static CLOCK: AtomicU64 = AtomicU64::new(0);
thread_local! { static BANK: RefCell<Vec<Discovery>> = const { RefCell::new(Vec::new()) }; }
pub fn clock() -> u64 {
CLOCK.load(Ordering::Relaxed)
}
fn view(d: &Discovery) -> Json {
let s = |t: &str| Json::Str(t.to_string());
Json::Obj(vec![
("id".into(), s(&d.id)),
("title".into(), s(&d.title)),
("when".into(), s(&d.when)),
("found".into(), s(&d.found)),
("how".into(), s(&d.how)),
("evidence".into(), s(&d.evidence)),
("reconsider".into(), s(&d.reconsider)),
// Byte length of the full lesson an agent receives from `instinct recall`.
("rendered".into(), Json::Num(render_entry(d).len() as f64)),
("hits".into(), Json::Num(d.hits.into())),
("misses".into(), Json::Num(d.misses.into())),
("strength".into(), Json::Num(d.strength().into())),
(
"quiet".into(),
Json::Bool(eligibility::quiet(d.hits, d.misses)),
),
])
}
fn run(req: &Json) -> Result<Json, String> {
let f = |k: &str| req.get(k).and_then(Json::as_str).unwrap_or("").to_string();
let scope = eligibility::Scope::default();
match f("op").as_str() {
"clock" => {
CLOCK.store(req.get("now").and_then(Json::as_f64).unwrap_or(0.0) as u64, Ordering::Relaxed);
Ok(Json::Null)
}
"reset" => {
BANK.with(|b| b.borrow_mut().clear());
Ok(Json::Null)
}
"bank" => {
let d = bank_discovery(
BankIn {
title: f("title"),
when: f("when"),
found: f("found"),
how: f("how"),
evidence: f("evidence"),
reconsider: f("reconsider"),
tags: f("tags"),
project: String::new(),
persona: String::new(),
applicability_harness: String::new(),
applicability_version: String::new(),
applicability_machine: None,
},
&scope,
)?;
let note = bank_scope_note(&d.meta);
let id = d.id.clone();
let fresh = BANK.with(|b| {
let mut b = b.borrow_mut();
if b.iter().any(|x| x.id == id) {
false
} else {
b.push(d);
true
}
});
Ok(Json::Obj(vec![
("id".into(), Json::Str(id)),
("new".into(), Json::Bool(fresh)),
("note".into(), Json::Str(note)),
]))
}
"recall" => {
let q = f("q");
let k = req.get("k").and_then(Json::as_f64).unwrap_or(1.0) as usize;
let now = now_secs();
let all: Vec<Discovery> = BANK.with(|b| {
b.borrow()
.iter()
.filter(|d| eligibility::scope_check(&d.meta, &scope, now).is_ok())
.cloned()
.collect()
});
let picked = rank_methods(&PathBuf::new(), &q, k, &scope, &all, |action| {
score_discoveries(action, &all)
})?;
Ok(Json::Arr(picked.iter().map(view).collect()))
}
kind @ ("hit" | "miss") => {
let id = f("id");
BANK.with(|b| {
let mut b = b.borrow_mut();
let d = b
.iter_mut()
.find(|d| d.id == id)
.ok_or_else(|| format!("no discovery with id {id}"))?;
if kind == "hit" {
d.hits += 1;
} else {
d.misses += 1;
}
Ok(view(d))
})
}
"list" => Ok(BANK.with(|b| Json::Arr(b.borrow().iter().map(view).collect()))),
other => Err(format!("unknown op {other:?}")),
}
}
/// `request` is one JSON object with an `op`; the reply is `{"ok":...}` or `{"error":"..."}`.
pub fn handle(request: &str) -> String {
let out = parse_json(request).and_then(|req| run(&req));
json_out(&match out {
Ok(v) => Json::Obj(vec![("ok".into(), v)]),
Err(e) => Json::Obj(vec![("error".into(), Json::Str(e))]),
})
}
}
#[cfg(test)]
mod fold_tests {
use super::*;
#[test]
fn word_forms_share_a_key() {
for (a, b) in [
("tests", "test"),
("testing", "test"),
("tested", "test"),
("running", "runs"),
("failing", "fails"),
("failed", "fail"),
("queries", "query"),
("fixes", "fix"),
("passes", "pass"),
("stopped", "stop"),
("warnings", "warning"),
("settings", "setting"),
("updated", "update"),
("updates", "updating"),
("cached", "cache"),
("merging", "merge"),
("writing", "write"),
("issues", "issue"),
] {
assert_eq!(fold_word(a), fold_word(b), "{a} vs {b}");
}
}
#[test]
fn short_words_stay_and_latin_accents_normalize() {
for w in ["status", "class", "bonus", "analysis", "string", "проект", "日本語"] {
assert_eq!(fold_word(w), w, "{w}");
}
assert_eq!(fold_word("zażółć"), "zazolc");
}
#[test]
fn inflected_question_reaches_the_when_line() {
let when = anchors("Running the test suite in this repo");
let cues = anchors("how do I run the tests in this repo?");
assert!(when.intersection(&cues).count() >= 2, "{when:?} vs {cues:?}");
}
}
#[cfg(test)]
mod keyword_support_tests {
use super::*;
#[test]
fn floors_follow_bank_size_and_small_banks_are_exempt() {
assert_eq!(lex_floors(10), (0.0, 0.0));
let (hi80, lo80) = lex_floors(80);
assert!((16.5..17.5).contains(&hi80) && (13.5..14.5).contains(&lo80));
assert!(lex_floors(2000).0 > hi80);
}
#[test]
fn weak_scores_are_silent_unless_a_clear_winner() {
let floors = (17.0, 14.0);
let weak = |lex: &[f32], i: usize, f| weak_keyword_support(lex[i], top_two(lex), f);
assert!(!weak(&[20.0, 19.0], 0, floors)); // strong
assert!(weak(&[10.0, 0.0], 0, floors)); // below both floors
assert!(weak(&[15.0, 14.0], 0, floors)); // middle score, no clear winner
assert!(weak(&[14.0, 15.0], 0, floors)); // not even the best
assert!(!weak(&[15.0, 9.0], 0, floors)); // middle score, 1.5x the next
assert!(!weak(&[3.0], 0, (0.0, 0.0))); // floors off
assert_eq!(top_two(&[5.0, 5.0, 2.0]), (5.0, 5.0));
}
}
#[cfg(test)]
mod reliable_tests {
use super::*;
fn bank_input() -> BankIn {
BankIn {
title: "fixture discovery".into(),
when: "fixture condition".into(),
found: "fixture result".into(),
how: "fixture measurement".into(),
reconsider: String::new(),
evidence: "verified! (caller text, not a verification grant)".into(),
tags: String::new(),
project: String::new(),
persona: String::new(),
applicability_harness: String::new(),
applicability_version: String::new(),
applicability_machine: None,
}
}
fn fixture() -> PathBuf {
let p = std::env::temp_dir().join(format!(
"instinct-bank-test-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&p).unwrap();
p.join("bank.jsonl")
}
fn observed_case(reference: &str, value: bool, action: &str) -> case_learning::Casebook {
let text = format!(r#"{{"checks":[{{"key":"ready","question":"Is it ready?","cost":1}}],"examples":[{{"ref":"{reference}","facts":{{"ready":{value}}},"action":"{action}"}}]}}"#);
case_learning::Casebook::parse(&parse_json(&text).unwrap()).unwrap()
}
#[test]
fn casebook_sync_keeps_counterexamples_and_rejects_conflicts_before_writing() {
let root = fixture();
let scope = eligibility::Scope::default();
let left = root.with_extension("hxdb");
let right = root.with_file_name("other.jsonl");
let conflict = root.with_file_name("conflict.jsonl");
let a = observed_case("positive", true, "use");
let b = observed_case("counter", false, "wait");
let changed = observed_case("positive", true, "wait");
for (path, cases) in [(&left, &a), (&right, &b), (&conflict, &changed)] {
op_bank_cases(path, bank_input(), Some(cases.clone()), &scope).unwrap();
}
sync::pull(&left, &right).unwrap();
sync::pull(&right, &left).unwrap();
let merged = a.merge(&b).unwrap();
for path in [&left, &right] {
let d = load(path).unwrap().pop().unwrap();
assert_eq!(d.casebook.as_ref(), Some(&merged));
assert_eq!((d.hits, d.misses), (0, 0));
assert_eq!(d.meta.source, "banked");
assert_eq!(d.meta.evidence_status, "unverified");
let key = snapshot::key(path).unwrap();
let (cached, _, _) = snapshot::open(path, &key, &scope, now_secs()).unwrap();
assert_eq!(cached[0].casebook.as_ref(), Some(&merged));
let held = fs::read(path).unwrap();
op_bank_cases(path, bank_input(), Some(a.clone()), &scope).unwrap();
assert!(op_bank_cases(path, bank_input(), Some(changed.clone()), &scope).is_err());
assert!(sync::pull(path, &conflict).is_err());
assert_eq!(fs::read(path).unwrap(), held);
}
assert_eq!(sync::status(&left, &right).unwrap(), (0, 0, 0));
fs::remove_dir_all(root.parent().unwrap()).unwrap();
}
#[test]
fn casebook_feedback_validates_both_rows_and_retries_partial_outcomes() {
let path = fixture();
let scope = eligibility::Scope { project: "handoff".into(), ..Default::default() };
let seed = observed_case("starter", true, "use");
op_bank_cases(&path, bank_input(), Some(seed), &scope).unwrap();
let id = load_plain(&path).unwrap().pop().unwrap().id;
let observation = parse_json(r#"{"facts":{"ready":false},"action":"inspect"}"#).unwrap();
let mark = |kind, key, obs: &Json| op_mark_case(&path, kind, &id, "", key, obs, &scope);
assert!(op_mark_case(&path, "miss", &id, "", "wrong-scope", &observation, &Default::default()).is_err());
mark("miss", "actual", &observation).unwrap();
let held = fs::read(&path).unwrap();
mark("miss", "actual", &observation).unwrap();
assert!(mark("hit", "actual", &observation).is_err());
assert!(mark("miss", "actual", &parse_json(r#"{"facts":{"ready":true},"action":"inspect"}"#).unwrap()).is_err());
assert!(mark("hit", "missing-fact", &parse_json(r#"{"facts":{},"action":"inspect"}"#).unwrap()).is_err());
assert_eq!(fs::read(&path).unwrap(), held);
op_mark(&path, "hit", &id, "", "mark-only").unwrap();
mark("hit", "mark-only", &observation).unwrap();
op_bank_cases(&path, bank_input(), Some(observed_case("case-only", false, "inspect")), &scope).unwrap();
mark("hit", "case-only", &observation).unwrap();
let d = load_plain(&path).unwrap().pop().unwrap();
assert_eq!((d.hits, d.misses), (2, 1));
let book = d.casebook.as_ref().unwrap();
for key in ["case-only", "mark-only", "actual"] {
assert_eq!(book.merge(&observed_case(key, false, "inspect")).unwrap(), *book);
}
let peer = path.with_extension("hxdb");
sync::pull(&peer, &path).unwrap();
let held = fs::read(&peer).unwrap();
op_mark_case(&peer, "miss", &id, "", "actual", &observation, &scope).unwrap();
assert_eq!(fs::read(&peer).unwrap(), held);
let imported = load_plain(&peer).unwrap().pop().unwrap();
assert_eq!((imported.hits, imported.misses, imported.casebook), (2, 1, d.casebook));
let opposite = path.with_file_name("opposite.jsonl");
op_bank_in(&opposite, bank_input(), "banked", &scope).unwrap();
op_mark(&opposite, "hit", &id, "", "actual").unwrap();
let held = fs::read(&opposite).unwrap();
assert!(sync::pull(&opposite, &path).is_err());
assert_eq!(fs::read(&opposite).unwrap(), held);
fs::remove_dir_all(path.parent().unwrap()).unwrap();
}
#[test]
fn casebook_concurrent_writers_preserve_scope_fields_and_inactive_history() {
let path = fixture();
let scope = eligibility::Scope::default();
let a = observed_case("one", true, "use");
let b = observed_case("two", false, "wait");
let barrier = std::sync::Barrier::new(2);
std::thread::scope(|s| {
for add in [&a, &b] {
s.spawn(|| {
barrier.wait();
op_bank_cases(&path, bank_input(), Some(add.clone()), &scope).unwrap();
});
}
});
let d = load_plain(&path).unwrap().pop().unwrap();
assert_eq!(d.casebook.as_ref(), Some(&a.merge(&b).unwrap()));
assert_eq!(journal::read(&path).unwrap().lines().count(), 3);
let other_scope = eligibility::Scope { persona: "second".into(), ..scope.clone() };
op_bank_cases(&path, bank_input(), Some(b.clone()), &other_scope).unwrap();
let mut other = load_plain(&path).unwrap();
assert_eq!(other.len(), 2);
assert_eq!(other.pop().unwrap().casebook, Some(b.clone()));
let mut altered = bank_input();
altered.how = "unrelated method".into();
assert!(op_bank_cases(&path, altered, Some(a.clone()), &scope).is_err());
for (kind, undo) in [("retire", "unretire"), ("supersede", "unsupersede")] {
append(&path, &format!(r#"{{"kind":"{kind}","id":"{}"}}"#, d.id)).unwrap();
assert!(op_bank_cases(&path, bank_input(), Some(a.clone()), &scope).is_err());
append(&path, &format!(r#"{{"kind":"{undo}","id":"{}"}}"#, d.id)).unwrap();
}
op_review(&path, &d.id, "quarantined", "under review", "ref").unwrap();
assert!(op_bank_cases(&path, bank_input(), Some(a.clone()), &scope).is_err());
let peer = path.with_file_name("peer.jsonl");
let c = observed_case("from-peer", false, "inspect");
op_bank_cases(&peer, bank_input(), Some(c.clone()), &scope).unwrap();
sync::pull(&path, &peer).unwrap();
assert!(load_plain(&path).unwrap()[0].casebook.is_none());
op_review(&path, &d.id, "candidate", "review ended", "ref").unwrap();
assert_eq!(load_plain(&path).unwrap()[0].casebook, Some(d.casebook.unwrap().merge(&c).unwrap()));
let mined = path.with_file_name("mined.jsonl");
op_bank_in(&mined, bank_input(), "mined", &scope).unwrap();
assert!(op_bank_cases(&mined, bank_input(), Some(a.clone()), &scope).is_err());
let shared = path.parent().unwrap().join(team::DIR).join(team::FILE);
assert!(op_bank_cases(&shared, bank_input(), Some(a), &scope).is_err());
assert!(sync::pull(&shared, &path).is_err());
assert!(!shared.exists());
fs::remove_dir_all(path.parent().unwrap()).unwrap();
}
#[test]
fn consolidated_counts_match_reverse_reachability_on_every_four_lesson_graph() {
// Four possible targets or no edge for each member: 5^4 graphs, including cycles.
const N: usize = 4;
let p = fixture();
let mut rows = Vec::new();
let mut expected = HashMap::new();
for graph in 0..(N + 1).pow(N as u32) {
let id = |i| format!("g{graph}-{i}");
let edges: [usize; N] = std::array::from_fn(|i| graph / (N + 1).pow(i as u32) % (N + 1));
for (i, &target) in edges.iter().enumerate() {
let member = id(i);
rows.push(format!(r#"{{"kind":"discovery","id":"{member}"}}"#));
rows.push(format!(r#"{{"kind":"hit","id":"{member}"}}"#));
let (verdict, key) = match i {
0 | 1 => ("hit", "shared"),
2 => ("miss", "other"),
_ => ("hit", "other"),
};
rows.push(format!(r#"{{"kind":"{verdict}","id":"{member}","outcome_id":"{key}"}}"#));
if target != N {
rows.push(format!(r#"{{"kind":"supersede","id":"{member}","by":"{}"}}"#, id(target)));
}
}
// Independent oracle: expand a set backwards from each visible root.
for root in (0..N).filter(|i| edges[*i] == N) {
let mut family = HashSet::from([root]);
for _ in 0..N {
for (member, to) in edges.iter().enumerate() {
if family.contains(to) {
family.insert(member);
}
}
}
let shared = family.contains(&0) || family.contains(&1);
let yes = family.contains(&3);
let no = family.contains(&2);
let hits = family.len() as u32 + u32::from(shared) + u32::from(yes && !no);
expected.insert(id(root), (hits, u32::from(no && !yes)));
}
}
fs::write(&p, rows.join("\n")).unwrap();
let actual: HashMap<_, _> = load_plain(&p).unwrap().into_iter()
.map(|entry| (entry.id, (entry.hits, entry.misses))).collect();
fs::remove_dir_all(p.parent().unwrap()).unwrap();
assert_eq!(actual, expected);
}
#[test]
fn render_len_matches_the_rendered_bytes() {
let p = fixture();
let mut with_everything = bank_input();
with_everything.title = "čas \"quoted\" ünïcode".into();
with_everything.tags = "a,b".into();
with_everything.reconsider = "if it changes".into();
with_everything.applicability_machine = Some("box-1".into());
with_everything.when = "fixture condition two".into();
op_bank(&p, bank_input()).unwrap();
op_bank(&p, with_everything).unwrap();
let all = load(&p).unwrap();
for d in &all {
op_mark(&p, "hit", &d.id, "", "").unwrap();
}
op_mark(&p, "miss", &all[0].id, "", "").unwrap();
for _ in 0..11 {
op_mark(&p, "hit", &all[1].id, "", "").unwrap();
}
let all = load(&p).unwrap();
assert_eq!(all.len(), 2);
for d in &all {
assert_eq!(render_len(d), render_entry(d).len(), "{}", render_entry(d));
}
assert!(all.iter().any(|d| d.hits >= 10), "two-digit hit counts covered");
assert!(
all.iter().any(|d| render_entry(d).contains("proven in use"))
&& all.iter().any(|d| !render_entry(d).contains("proven in use")),
"both the proven and the unproven validity line are covered"
);
}
#[test]
fn lexical_score_preserves_lengths_case_and_repeated_terms() {
let documents = vec!["Čas CLOCK clock".into(), "čas other".into(), "a".into()];
let scores = bm25("CLOCK čas clock", &documents);
let weight = |df: f32| ((3.0 - df + 0.5) / (df + 0.5) + 1.0).ln();
let term = |df: f32, tf: f32, len: f32| {
weight(df) * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * len / (5.0 / 3.0)))
};
assert_eq!(
scores,
vec![
term(1.0, 2.0, 3.0) + term(2.0, 1.0, 3.0),
term(2.0, 1.0, 2.0),
0.0
]
);
assert_eq!(bm25("", &documents), vec![0.0; 3]);
}
#[test]
fn decision_context_transfers_a_method_with_its_boundary() {
let path = fixture();
let mut entry = bank_input();
entry.when = "command acknowledgement delay".into();
entry.how = "Compare command and acknowledgement timestamps".into();
entry.reconsider = "If clocks differ, measure the offset first".into();
let d = bank_discovery(entry, &eligibility::Scope::default()).unwrap();
append(&path, &d.to_line()).unwrap();
let mut private = bank_input();
private.when = d.when.clone();
private.project = "other-project".into();
let restricted = bank_discovery(private, &eligibility::Scope::default()).unwrap();
append(&path, &restricted.to_line()).unwrap();
let scope = eligibility::Scope::default();
let query = "New controller has an acknowledgement delay";
for hits in 0..=1 {
let data = parse_json(&decision_context(&path, query, &scope, None).unwrap()).unwrap();
let Some(Json::Arr(methods)) = data.get("experiences") else {
panic!("missing experiences")
};
assert_eq!(methods.len(), 1);
assert_eq!(
methods[0].get("method").and_then(Json::as_str),
Some(d.how.as_str())
);
assert_eq!(
methods[0].get("reconsider_if").and_then(Json::as_str),
Some(d.reconsider.as_str())
);
assert_eq!(
methods[0].get("hits").and_then(Json::as_f64),
Some(hits as f64)
);
if hits == 0 {
op_mark(
&path,
"hit",
&d.id,
"Independent timing check succeeded",
"",
)
.unwrap();
}
}
let empty = decision_context(&path, "colour palette", &scope, None).unwrap();
assert!(
matches!(parse_json(&empty).unwrap().get("experiences"),Some(Json::Arr(a)) if a.is_empty())
);
fs::remove_dir_all(path.parent().unwrap()).unwrap();
}
#[test]
fn offline_experience_lifecycle() {
let path = fixture();
let mut entry = bank_input();
entry.when = "signal comparison uses a proxy whose score may disagree with independent task outcomes".into();
entry.found = "Similarity can reward responses that never accomplished the task".into();
entry.how = "Compare each proxy score against an independent completion check".into();
entry.evidence =
"Synthetic sample: two high-similarity failures and one low-similarity success".into();
let d = bank_discovery(entry, &eligibility::Scope::default()).unwrap();
append(&path, &d.to_line()).unwrap();
let query = "Which proxy score tracks completion of a translation task?";
let read = || op_recall_scoped(&path, query, 1, &eligibility::Scope::default()).unwrap();
assert!(read().contains(&d.how));
assert!(op_recall(&path, "prepare dinner", 1).unwrap().is_empty());
assert!(op_instincts(&path, 2).unwrap().is_empty());
for case in [
"translation: independent check passed",
"retrieval: independent check passed",
] {
op_mark(&path, "hit", &d.id, case, "").unwrap();
}
assert!(op_instincts(&path, 2).unwrap().contains(&d.id));
op_review(
&path,
&d.id,
"quarantined",
"Changed applicability",
"fixture:v2",
)
.unwrap();
assert!(read().is_empty());
fs::remove_dir_all(path.parent().unwrap()).unwrap();
}
#[test]
fn scope_and_quarantine_survive_roundtrip_and_append() {
let p = fixture();
let original="{\"kind\":\"discovery\",\"id\":\"in-fixture\",\"title\":\"test\",\"scope_persona\":\"koscak\",\"source\":\"mined\",\"state\":\"candidate\"}\n";
fs::write(&p, original).unwrap();
let d = load(&p).unwrap().remove(0);
let v = parse_json(&d.to_line()).unwrap();
assert_eq!(
v.get("scope_persona").and_then(Json::as_str),
Some("koscak")
);
op_review(
&p,
"in-fixture",
"quarantined",
"contradictory source",
"fixture:1",
)
.unwrap();
assert!(fs::read_to_string(&p).unwrap().starts_with(original));
let d = load(&p).unwrap().remove(0);
assert_eq!(
eligibility::scope_check(&d.meta, &eligibility::Scope::default(), 1),
Err("quarantined")
);
}
#[test]
fn receipt_has_exact_ids_and_unknown_session_is_explicit() {
let r = recall_receipt(&["in-one".into(), "in-two".into()], None).unwrap();
assert!(matches!(r.get("ids"),Some(Json::Arr(v)) if v.len()==2));
assert!(!r.get("event_id").and_then(Json::as_str).unwrap().is_empty());
assert!(recall_receipt(&[], None).is_none());
}
#[test]
fn review_never_grants_verified_status() {
let p = fixture();
assert!(op_review(&p, "x", "validated", "because", "ref").is_err());
assert!(!p.exists());
}
#[test]
fn scope_missing_cannot_match_explicit_requirement() {
let m = meta_from(
&parse_json("{\"scope_project\":\"/project/a\",\"scope_harness\":\"codex\"}").unwrap(),
);
assert_eq!(
eligibility::scope_check(&m, &eligibility::Scope::default(), 1),
Err("project")
);
}
#[test]
fn bank_creation_persists_explicit_scope_without_verification_escalation() {
let mut b = bank_input();
b.project = "/project/a".into();
b.persona = "persona-a".into();
b.applicability_harness = "codex".into();
b.applicability_version = "version-a".into();
let d = bank_discovery(b, &eligibility::Scope::default()).unwrap();
let p = fixture();
append(&p, &d.to_line()).unwrap();
let stored = load(&p).unwrap().remove(0);
assert_eq!(
scope_identity(&stored.meta),
["/project/a", "persona-a", "codex", "version-a", ""]
);
assert_eq!(stored.meta.source, "banked");
assert_eq!(stored.meta.state, "candidate");
assert_eq!(stored.meta.evidence_status, "unverified");
assert!(eligibility::unverified(&stored.meta));
assert_eq!(
eligibility::scope_check(&stored.meta, &eligibility::Scope::default(), 1),
Err("project")
);
}
#[test]
fn bank_creation_does_not_infer_applicability_from_receipt_origin() {
let origin = eligibility::Scope {
project: "/explicit/project".into(),
persona: "explicit-persona".into(),
harness: "claude".into(),
version: "origin-version".into(),
machine: "workstation".into(),
};
let d = bank_discovery(bank_input(), &origin).unwrap();
assert_eq!(
scope_identity(&d.meta),
["/explicit/project", "explicit-persona", "", "", ""]
);
assert!(bank_scope_note(&d.meta).contains("applicability harness, applicability version"));
let d = bank_discovery(bank_input(), &eligibility::Scope::default()).unwrap();
assert_eq!(d.id, make_id(&d.title, &d.found));
// Nothing scoped: the note says the lesson applies everywhere rather than listing five field names.
assert!(bank_scope_note(&d.meta).contains("applies in every project"));
assert_eq!(
eligibility::eligible(&d.meta, &eligibility::Scope::default(), 1, None, 0, false),
Err("candidate_match_unproven")
);
}
#[test]
fn bank_creation_keeps_each_scope_identity_distinct() {
let mut ids = std::collections::HashSet::new();
let p = fixture();
for scope in [
["p1", "a", "codex", "v1"],
["p2", "a", "codex", "v1"],
["p1", "b", "codex", "v1"],
["p1", "a", "claude", "v1"],
["p1", "a", "codex", "v2"],
] {
let mut b = bank_input();
b.project = scope[0].into();
b.persona = scope[1].into();
b.applicability_harness = scope[2].into();
b.applicability_version = scope[3].into();
let d = bank_discovery(b, &eligibility::Scope::default()).unwrap();
assert!(ids.insert(d.id.clone()));
append(&p, &d.to_line()).unwrap();
}
let all = load(&p).unwrap();
assert_eq!(all.len(), 5);
let scope = eligibility::Scope {
project: "p1".into(),
persona: "a".into(),
harness: "codex".into(),
version: "v1".into(),
machine: String::new(),
};
assert_eq!(
all.iter()
.filter(|d| eligibility::eligible(&d.meta, &scope, 1, Some(0.99), 0, false).is_ok())
.count(),
1
);
assert_eq!(
all.iter()
.filter(|d| eligibility::eligible(
&d.meta,
&eligibility::Scope::default(),
1,
Some(0.99),
0,
false
)
.is_ok())
.count(),
0
);
}
}
/// `journal::append` output is pinned to the bytes the 0.3.6 code wrote (captured from origin/main before `append_many`
/// existed), and a batch is byte-identical to the same events appended one at a time. Files written by the batch path
/// therefore read the same under any older binary.
#[cfg(test)]
mod append_bytes_tests {
use super::*;
const EVENTS: [&str; 3] = [
"{\"kind\":\"discovery\",\"id\":\"a1\",\"title\":\"tab\\tq\\\"uote\"}",
"{\"kind\":\"hit\",\"id\":\"a1\",\"note\":\"caf\u{e9} \u{1f600} back\\\\slash\"}",
"{\"kind\":\"miss\",\"id\":\"a1\"}",
];
const JSONL: &str = "{\"kind\":\"discovery\",\"id\":\"a1\",\"title\":\"tab\\tq\\\"uote\"}\n{\"kind\":\"hit\",\"id\":\"a1\",\"note\":\"café 😀 back\\\\slash\"}\n{\"kind\":\"miss\",\"id\":\"a1\"}\n";
const HXDB: &str = "event:0000000000000000\tV\t4a6948f46fe1cd09:{\"kind\":\"discovery\",\"id\":\"a1\",\"title\":\"tab\\\\tq\\\\\"uote\"}\nevent:0000000000000062\tV\t91d327060c95fec2:{\"kind\":\"hit\",\"id\":\"a1\",\"note\":\"café 😀 back\\\\\\\\slash\"}\nevent:00000000000000c7\tV\t3f9c8f27de351bc6:{\"kind\":\"miss\",\"id\":\"a1\"}\n";
#[test]
fn single_appends_are_byte_identical_to_the_previous_release_and_a_batch_matches_them() {
let d = std::env::temp_dir().join(format!("append-bytes-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
for (name, golden) in [("one.jsonl", JSONL), ("one.hxdb", HXDB)] {
let one = d.join(name);
for l in EVENTS {
journal::append(&one, l).unwrap();
}
assert_eq!(std::fs::read_to_string(&one).unwrap(), golden, "{name}: single appends");
let many = d.join(format!("many-{name}"));
journal::append_many(&many, &EVENTS).unwrap();
assert_eq!(std::fs::read_to_string(&many).unwrap(), golden, "{name}: one batch");
let tail = d.join(format!("tail-{name}"));
journal::append(&tail, EVENTS[0]).unwrap();
journal::append_many(&tail, &EVENTS[1..]).unwrap();
assert_eq!(std::fs::read_to_string(&tail).unwrap(), golden, "{name}: single then batch");
let before = std::fs::read_to_string(&many).unwrap();
journal::append_many(&many, &[]).unwrap();
assert_eq!(std::fs::read_to_string(&many).unwrap(), before, "{name}: empty batch");
let none = d.join(format!("none-{name}"));
journal::append_many(&none, &[]).unwrap();
assert!(!none.exists(), "{name}: empty batch creates nothing");
assert_eq!(journal::read(&many).unwrap(), journal::read(&one).unwrap());
}
std::fs::remove_dir_all(&d).ok();
}
}