instinct-cli 0.3.0

Local memory for AI coding agents: an MCP server and CLI that gives Claude Code, Codex, Cursor and any MCP client the one lesson that fits. Lessons that keep failing go quiet.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Per-session memory for the hooks: `<store>.sessions`, append-only, one tab-separated line per event:
//! `unix_ts  session_id  D|H|R  lesson_id  [p|g]`. `D` = a lesson was delivered in that session, `H` = it was
//! withheld by the explore arm (`INSTINCT_EXPLORE`), `R` = the settle reminder was shown. The optional last
//! field says which hook acted: `p` prompt, `g` guard. Counts and ids only, never text. Lines older than
//! 35 days are pruned on write.
//! Every function is best effort: a missing, unwritable or garbled file reads as "nothing recorded".
use super::*;

/// 35 days, so `instinct eval --since 30d` and `instinct outcomes` can see which lessons were delivered.
const KEEP_SECS: u64 = 35 * 86_400;

/// Every delivery on record: (unix_ts, session_id, lesson_id), oldest first. Read only. Withheld (`H`)
/// lines are not deliveries. Built on [`records`], the one parser of this file.
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)
}

/// Tabs and newlines would break the line format; an empty id means "no session memory".
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 {
    /// Delivered lesson ids with the first delivery time, in delivery order, without repeats.
    pub delivered: Vec<(String, u64)>,
    /// Lesson ids the explore arm withheld in this session, without repeats.
    pub held: Vec<String>,
    pub reminded: bool,
}

/// Which hook acted on a lesson.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
    Prompt,
    Guard,
    /// Written before the source field existed.
    Unknown,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    Delivered,
    Held,
    Reminded,
}

/// One line of `<store>.sessions`.
#[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 })
}

/// Every parsable line of `<store>.sessions`, in file order. Garbled lines are skipped.
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
}

/// Lessons the hooks must not offer again in this session: already delivered, or already withheld.
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));
    }
}

/// The explore arm kept this lesson out of the session; recorded as `arm=hold` so `instinct outcomes` can compare.
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);
}

/// For the prompt hook: if a lesson delivered earlier in this session still has no hit or miss and no
/// reminder has been shown, record the reminder and return the line to add to this prompt's context.
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."
    )
}

// ---------------------------------------------------------------- explore arm

/// The share of deliveries to withhold, from `INSTINCT_EXPLORE` (for example `0.1`). Unset, empty, not a
/// number, or not above zero means off; anything above 1 means 1.
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))
}

/// Position of (session, lesson) on [0, 1): FNV-1a over a fixed seed, session id and lesson id, then a
/// splitmix finalizer so the top bits are uniform. Same inputs, same number, on every machine and run.
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
}

/// True when the explore arm withholds `lesson` in session `sid`. Stable: it depends on nothing else.
pub fn withheld(sid: &str, lesson: &str, share: f64) -> bool {
    share > 0.0 && explore_draw(sid, lesson) < share
}

/// Rewrites the file without lines older than the keep window, only when there is something to drop.
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);
    }
}

/// Ids among `delivered` that have no hit or miss line in the journal at or after their delivery time.
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 Code: `hookSpecificOutput.additionalContext` on Stop.
    Claude,
    /// Codex: `{"decision":"block","reason":...}` (Stop continues once with the reason as a prompt).
    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(),
    }
}

/// True when something happened after a delivery at `since` (unix seconds) that shows whether the lesson
/// worked: a tool call, or a user prompt after the one that brought the lesson. The delivering prompt can be
/// stamped a few seconds either side of the hook, so prompts from five seconds before count, and two are needed.
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
}

/// `instinct settle`: the Stop hook. Never returns an error, never exits non-zero, silent unless a lesson
/// delivered in this session still has no hit or miss. Reminds at most once per session.
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;
    }
    // Ask only when the agent can know the answer. A Stop hook that prints anything makes the agent take
    // another turn, so asking after a plain question and answer replaces the answer with talk about lessons.
    // With a readable transcript, ask only if a tool ran or the user wrote again after the first owed
    // delivery. Without one, ask as before. Staying silent records nothing, so a later Stop can still ask.
    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}");
            // withheld at a small share implies withheld at a larger one
            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);
    }
}