use super::*;
const KEEP_SECS: u64 = 35 * 86_400;
pub fn deliveries(store: &Path) -> Vec<(u64, String, String)> {
records(store)
.into_iter()
.filter(|r| r.kind == Kind::Delivered)
.map(|r| (r.ts, r.session, r.lesson))
.collect()
}
fn file(store: &Path) -> PathBuf {
let mut p = store.as_os_str().to_owned();
p.push(".sessions");
PathBuf::from(p)
}
pub fn clean(id: &str) -> Option<String> {
let id: String = id.chars().filter(|c| !c.is_control()).collect();
let id = id.trim();
(!id.is_empty() && id.len() <= 200).then(|| id.to_owned())
}
#[derive(Debug, Default, PartialEq)]
pub struct Seen {
pub delivered: Vec<(String, u64)>,
pub held: Vec<String>,
pub reminded: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
Prompt,
Guard,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Delivered,
Held,
Reminded,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Record {
pub ts: u64,
pub session: String,
pub kind: Kind,
pub lesson: String,
pub source: Source,
}
fn parse_line(line: &str) -> Option<Record> {
let f: Vec<&str> = line.split('\t').collect();
if !(4..=5).contains(&f.len()) {
return None;
}
let kind = match f[2] {
"D" => Kind::Delivered,
"H" => Kind::Held,
"R" => Kind::Reminded,
_ => return None,
};
let source = match f.get(4).copied() {
Some("p") => Source::Prompt,
Some("g") => Source::Guard,
_ => Source::Unknown,
};
Some(Record { ts: f[0].parse().unwrap_or(0), session: f[1].to_owned(), kind, lesson: f[3].to_owned(), source })
}
pub fn records(store: &Path) -> Vec<Record> {
std::fs::read_to_string(file(store)).unwrap_or_default().lines().filter_map(parse_line).collect()
}
pub fn seen(store: &Path, sid: &str) -> Seen {
let mut out = Seen::default();
for r in records(store).into_iter().filter(|r| r.session == sid) {
match r.kind {
Kind::Delivered if !out.delivered.iter().any(|(i, _)| *i == r.lesson) => {
out.delivered.push((r.lesson, r.ts))
}
Kind::Held if !out.held.contains(&r.lesson) => out.held.push(r.lesson),
Kind::Reminded => out.reminded = true,
_ => {}
}
}
out
}
pub fn delivered_ids(store: &Path, sid: &str) -> Vec<String> {
let s = seen(store, sid);
s.delivered.into_iter().map(|(i, _)| i).chain(s.held).collect()
}
fn append(store: &Path, sid: &str, kind: &str, ids: &[String], source: Option<Source>) {
let path = file(store);
let now = now_secs();
prune(&path, now);
let tag = match source {
Some(Source::Prompt) => "\tp",
Some(Source::Guard) => "\tg",
_ => "",
};
let mut body = String::new();
for id in ids {
body.push_str(&format!("{now}\t{sid}\t{kind}\t{id}{tag}\n"));
}
#[cfg(unix)]
let opened = {
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new().create(true).append(true).mode(0o600).open(&path)
};
#[cfg(not(unix))]
let opened = std::fs::OpenOptions::new().create(true).append(true).open(&path);
if let Ok(mut f) = opened {
let _ = f.write_all(body.as_bytes());
}
}
pub fn record_delivered(store: &Path, sid: &str, ids: &[String], source: Source) {
if !ids.is_empty() {
append(store, sid, "D", ids, Some(source));
}
}
pub fn record_held(store: &Path, sid: &str, ids: &[String], source: Source) {
if !ids.is_empty() {
append(store, sid, "H", ids, Some(source));
}
}
pub fn record_reminded(store: &Path, sid: &str) {
append(store, sid, "R", &["-".to_owned()], None);
}
pub fn followup(store: &Path, sid: &str) -> Option<String> {
let state = seen(store, sid);
if state.reminded || state.delivered.is_empty() {
return None;
}
let owed = unsettled(store, &state.delivered);
if owed.is_empty() {
return None;
}
record_reminded(store, sid);
Some(followup_text(&owed))
}
pub fn followup_text(ids: &[String]) -> String {
let shown: Vec<&str> = ids.iter().take(3).map(String::as_str).collect();
let (what, hit, miss) = match shown[..] {
[one] => (format!("lesson {one}"), format!("instinct hit {one} --note '…'"), format!("instinct miss {one} --note '…'")),
_ => (
format!("lessons {}", shown.join(", ")),
"instinct hit ID --note '…'".to_owned(),
"instinct miss ID --note '…'".to_owned(),
),
};
format!(
"Instinct: earlier in this session you were given {what}. If this message shows whether it worked, run `{hit}` or `{miss}` as a command on its own (the instinct CLI is installed; it wrote this line). If it does not, ignore this line and say nothing about it."
)
}
pub fn explore_share() -> f64 {
std::env::var("INSTINCT_EXPLORE")
.ok()
.and_then(|v| v.trim().parse::<f64>().ok())
.filter(|s| s.is_finite() && *s > 0.0)
.map_or(0.0, |s| s.min(1.0))
}
pub fn explore_draw(sid: &str, lesson: &str) -> f64 {
let mut h: u64 = 0xcbf29ce484222325;
let seed = b"instinct-explore-v1";
for b in seed.iter().chain(&[0u8]).chain(sid.as_bytes()).chain(&[0u8]).chain(lesson.as_bytes()) {
h ^= *b as u64;
h = h.wrapping_mul(0x100000001b3);
}
h ^= h >> 30;
h = h.wrapping_mul(0xbf58476d1ce4e5b9);
h ^= h >> 27;
h = h.wrapping_mul(0x94d049bb133111eb);
h ^= h >> 31;
(h >> 11) as f64 / (1u64 << 53) as f64
}
pub fn withheld(sid: &str, lesson: &str, share: f64) -> bool {
share > 0.0 && explore_draw(sid, lesson) < share
}
fn prune(path: &Path, now: u64) {
let Ok(text) = std::fs::read_to_string(path) else { return };
let live = |l: &str| {
l.split('\t')
.next()
.and_then(|t| t.parse::<u64>().ok())
.is_some_and(|t| now.saturating_sub(t) < KEEP_SECS)
};
if text.lines().all(live) {
return;
}
let kept: String = text.lines().filter(|l| live(l)).map(|l| format!("{l}\n")).collect();
let tmp = path.with_extension("sessions.tmp");
if std::fs::write(&tmp, kept).is_ok() {
let _ = std::fs::rename(&tmp, path);
}
}
pub fn unsettled(store: &Path, delivered: &[(String, u64)]) -> Vec<String> {
let journal = journal::read(&store.to_path_buf()).unwrap_or_default();
let marks: Vec<(String, u64)> = journal
.lines()
.filter(|l| l.contains("\"hit\"") || l.contains("\"miss\""))
.filter_map(|l| parse_json(l).ok())
.filter(|v| matches!(v.get("kind").and_then(Json::as_str), Some("hit" | "miss")))
.filter_map(|v| {
Some((
v.get("id")?.as_str()?.to_owned(),
v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64,
))
})
.collect();
delivered
.iter()
.filter(|(id, ts)| !marks.iter().any(|(m, t)| m == id && *t >= *ts))
.map(|(id, _)| id.clone())
.collect()
}
pub enum Format {
Claude,
Codex,
Text,
}
pub fn reminder(ids: &[String]) -> String {
let shown: Vec<&str> = ids.iter().take(3).map(String::as_str).collect();
if let [one] = shown[..] {
format!(
"You used lesson {one} this session. If it helped, run `instinct hit {one} --note '…'`; if it misled you, `instinct miss {one} --note '…'`."
)
} else {
format!(
"You used lessons {} this session. For each one, if it helped, run `instinct hit ID --note '…'`; if it misled you, `instinct miss ID --note '…'`.",
shown.join(", ")
)
}
}
pub fn render(text: &str, format: &Format) -> String {
match format {
Format::Claude => format!(
"{{\"hookSpecificOutput\":{{\"hookEventName\":\"Stop\",\"additionalContext\":\"{}\"}}}}",
escape_json(text)
),
Format::Codex => format!("{{\"decision\":\"block\",\"reason\":\"{}\"}}", escape_json(text)),
Format::Text => text.to_owned(),
}
}
pub fn outcome_observable(t: &super::outcomes::Transcript, since: u64) -> bool {
use super::outcomes::Ev;
let after = |ts: &u64| *ts >= since.saturating_sub(5);
let tools = t.evs.iter().any(|(ts, e)| *ts >= since && matches!(e, Ev::Tool { .. }));
let prompts = t.evs.iter().filter(|(ts, e)| after(ts) && matches!(e, Ev::Prompt(_))).count();
tools || prompts >= 2
}
pub fn settle(a: &Args) {
let mut input = String::new();
if std::io::stdin().take(1 << 20).read_to_string(&mut input).is_err() {
return;
}
let Ok(store) = store_path(a) else { return };
let Ok(event) = parse_json(&input) else { return };
if matches!(event.get("stop_hook_active"), Some(Json::Bool(true))) {
return;
}
let Some(sid) = event.get("session_id").and_then(Json::as_str).and_then(clean) else { return };
let state = seen(&store, &sid);
if state.reminded || state.delivered.is_empty() {
return;
}
let owed = unsettled(&store, &state.delivered);
if owed.is_empty() {
return;
}
if let Some(path) = event.get("transcript_path").and_then(Json::as_str) {
if let Some(t) = super::outcomes::load_transcript(Path::new(path), &sid) {
let since = state
.delivered
.iter()
.filter(|(id, _)| owed.contains(id))
.map(|(_, ts)| *ts)
.min()
.unwrap_or(0);
if !outcome_observable(&t, since) {
return;
}
}
}
let format = match a.opt("format") {
Some("codex") => Format::Codex,
Some("text") => Format::Text,
_ => Format::Claude,
};
record_reminded(&store, &sid);
println!("{}", render(&reminder(&owed), &format));
}
#[cfg(test)]
mod explore_tests {
use super::*;
#[test]
fn the_draw_is_a_pure_function_of_session_and_lesson() {
assert_eq!(explore_draw("s1", "in-a"), explore_draw("s1", "in-a"));
assert_ne!(explore_draw("s1", "in-a"), explore_draw("s2", "in-a"));
assert_ne!(explore_draw("s1", "in-a"), explore_draw("s1", "in-b"));
let d = explore_draw("session-1", "in-abc");
assert!((0.0..1.0).contains(&d));
}
#[test]
fn withholding_is_monotone_in_the_share_and_hits_it_on_average() {
assert!(!withheld("s", "l", 0.0));
assert!(withheld("s", "l", 1.0));
for i in 0..200 {
let sid = format!("sess-{i}");
if withheld(&sid, "in-x", 0.1) {
assert!(withheld(&sid, "in-x", 0.3));
}
}
for share in [0.1, 0.5] {
let n = 4000;
let k = (0..n).filter(|i| withheld(&format!("sess-{i}"), "in-x", share)).count();
let got = k as f64 / n as f64;
assert!((got - share).abs() < 0.03, "share {share}: got {got}");
}
}
#[test]
fn old_four_field_lines_still_read_and_new_ones_carry_the_source() {
let r = parse_line("100\tsid\tD\tin-1").unwrap();
assert_eq!((r.kind, r.source), (Kind::Delivered, Source::Unknown));
let r = parse_line("100\tsid\tH\tin-1\tg").unwrap();
assert_eq!((r.kind, r.source), (Kind::Held, Source::Guard));
assert!(parse_line("100\tsid\tX\tin-1").is_none());
assert!(parse_line("garbage").is_none());
}
#[test]
fn deliveries_and_records_share_one_parser_and_held_lines_are_not_deliveries() {
let dir = std::env::temp_dir().join(format!("instinct-session-unit-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let store = dir.join("bank.hxdb");
let text = "100\ta\tD\tin-1\tp\n110\ta\tH\tin-2\tp\n120\tb\tD\tin-1\n130\tb\tR\t-\nbroken line\n140\tc\tD\tin-3\tg\n";
std::fs::write(file(&store), text).unwrap();
assert_eq!(records(&store).len(), 5, "garbled lines are skipped");
assert_eq!(
deliveries(&store),
vec![(100, "a".into(), "in-1".into()), (120, "b".into(), "in-1".into()), (140, "c".into(), "in-3".into())]
);
let a = seen(&store, "a");
assert_eq!(a.delivered, vec![("in-1".to_string(), 100)]);
assert_eq!(a.held, vec!["in-2".to_string()]);
assert_eq!(delivered_ids(&store, "a"), vec!["in-1".to_string(), "in-2".to_string()]);
assert!(seen(&store, "b").reminded);
}
}