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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
//! `instinct eval`: what the bank is actually doing for you, from data Instinct already records and nothing else:
//! the journal (hits, misses, retractions, quarantines), `<store>.meter` (lookups, bytes, time) and
//! `<store>.sessions` (which lessons were delivered in which session). It reads only. The one write is
//! `--apply-quarantine`, which must be asked for and prints every lesson it touched.
use super::*;

const DAY: u64 = 86_400;
/// A lesson banked less than a day ago has not had a chance to fire yet.
const GRACE: u64 = DAY;

struct Row {
    id: String,
    title: String,
    when: String,
    banked: u64,
    quarantined: bool,
    hits_w: u32,
    misses_w: u32,
    hits_all: u32,
    misses_all: u32,
    deliveries: u32,
    anchors: HashSet<String>,
    /// Sorted `cmd:` matchers. Lessons with different matchers guard different commands, never duplicates.
    cmds: Vec<String>,
    /// Applicability: project, persona, harness, version, machine. Lessons scoped differently serve different
    /// situations, so quarantining one as a duplicate of the other would remove the only lesson for its scope.
    scope: [String; 5],
}

impl Row {
    fn outcomes_w(&self) -> u32 {
        self.hits_w + self.misses_w
    }
    fn rate(&self) -> u32 {
        (100.0 * self.hits_w as f64 / self.outcomes_w().max(1) as f64).round() as u32
    }
    fn proven(&self) -> bool {
        eligibility::promoted(self.hits_all, self.misses_all, 2)
    }
    /// Why this lesson should be quarantined, if it should.
    fn quarantine_reason(&self) -> Option<String> {
        trust::quarantine_reason(self.quarantined, self.hits_w, self.misses_w, self.hits_all, self.misses_all)
    }
}

/// Hit/miss events that still stand: one per outcome id, minus retractions, newest retracted first.
fn standing_events(journal: &str) -> HashMap<String, Vec<(u64, bool)>> {
    let mut out: HashMap<String, Vec<(u64, bool)>> = HashMap::new();
    let mut keyed: HashSet<(String, String)> = HashSet::new();
    for line in journal.lines().filter(|l| !l.trim().is_empty()) {
        let Ok(v) = parse_json(line) else { continue };
        let s = |k: &str| v.get(k).and_then(Json::as_str).unwrap_or("").to_string();
        let ts = v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64;
        match s("kind").as_str() {
            k @ ("hit" | "miss") => {
                let key = s("outcome_id");
                if !key.is_empty() && !keyed.insert((s("id"), key)) {
                    continue;
                }
                out.entry(s("id")).or_default().push((ts, k == "hit"));
            }
            "retract" => {
                let hit = s("of") == "hit";
                if let Some(list) = out.get_mut(&s("id")) {
                    if let Some(i) = list.iter().rposition(|e| e.1 == hit) {
                        list.remove(i);
                    }
                }
            }
            _ => {}
        }
    }
    out
}

fn shorten(s: &str, n: usize) -> String {
    let one: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
    if one.chars().count() <= n {
        one
    } else {
        format!("{}…", one.chars().take(n - 1).collect::<String>())
    }
}

/// Double-quote for a POSIX shell, so a pasted command means the same thing.
fn dq(s: &str) -> String {
    let mut o = String::from("\"");
    for c in s.split_whitespace().collect::<Vec<_>>().join(" ").chars() {
        if matches!(c, '"' | '\\' | '$' | '`') {
            o.push('\\');
        }
        o.push(c);
    }
    o.push('"');
    o
}

fn plural(n: usize, one: &str, many: &str) -> String {
    format!("{n} {}", if n == 1 { one } else { many })
}

struct Action {
    score: usize,
    why: String,
    command: String,
}

pub(super) fn run(path: &PathBuf, a: &Args) -> Result<String, String> {
    let since = a.opt("since").filter(|s| !s.starts_with("--")).unwrap_or("30d");
    let window = meter::parse_since(since)?;
    let now = now_secs();
    let floor = window.map(|w| now.saturating_sub(w)).unwrap_or(0);
    let store_arg = a.opt("store").map(|s| format!(" --store {}", dq(s))).unwrap_or_default();
    let cmd = |rest: String| format!("instinct {rest}{store_arg}");

    let lessons = load(path)?;
    let events = standing_events(&journal::read(path)?);
    let delivered = session::deliveries(path);
    let mut per: HashMap<&str, u32> = HashMap::new();
    for (_, _, id) in delivered.iter().filter(|d| d.0 >= floor) {
        *per.entry(id.as_str()).or_default() += 1;
    }
    let deliveries_total: u32 = per.values().sum();
    let sessions_total = delivered.iter().filter(|d| d.0 >= floor).map(|d| d.1.as_str()).collect::<HashSet<_>>().len();
    let record_start = delivered.iter().map(|d| d.0).min();
    // The explore arm: only when the hooks withheld something (INSTINCT_EXPLORE) is there anything to compare.
    let explore = session::records(path)
        .iter()
        .any(|r| r.kind == session::Kind::Held && r.ts >= floor)
        .then(|| outcomes::evaluate(path, &outcomes::Options { since: floor, now, transcripts: Vec::new() }));

    let rows: Vec<Row> = lessons
        .iter()
        .map(|d| {
            let ev = events.get(&d.id).map(Vec::as_slice).unwrap_or(&[]);
            let w = |hit: bool| ev.iter().filter(|e| e.0 >= floor && e.1 == hit).count() as u32;
            Row {
                id: d.id.clone(),
                title: d.title.clone(),
                when: d.when.clone(),
                banked: d.ts,
                quarantined: d.meta.state == "quarantined",
                hits_w: w(true),
                misses_w: w(false),
                hits_all: d.hits,
                misses_all: d.misses,
                deliveries: per.get(d.id.as_str()).copied().unwrap_or(0),
                anchors: anchors(&d.when),
                cmds: super::starter::cmd_specs(d),
                scope: [
                    d.meta.project.clone(),
                    d.meta.persona.clone(),
                    d.meta.harness.clone(),
                    d.meta.version.clone(),
                    d.meta.machine.clone(),
                ],
            }
        })
        .collect();
    let live: Vec<&Row> = rows.iter().filter(|r| !r.quarantined).collect();

    let mut paid: Vec<&Row> = live.iter().copied().filter(|r| r.hits_w > 0).collect();
    paid.sort_by(|a, b| b.hits_w.cmp(&a.hits_w).then(b.rate().cmp(&a.rate())).then(a.id.cmp(&b.id)));
    let mut misled: Vec<&Row> = live.iter().copied().filter(|r| r.misses_w > 0).collect();
    misled.sort_by(|a, b| b.misses_w.cmp(&a.misses_w).then(a.id.cmp(&b.id)));
    let to_quarantine: Vec<(&Row, String)> =
        misled.iter().filter_map(|r| r.quarantine_reason().map(|why| (*r, why))).collect();
    let mut unjudged: Vec<&Row> = live.iter().copied().filter(|r| r.deliveries > 0 && r.outcomes_w() == 0).collect();
    unjudged.sort_by(|a, b| b.deliveries.cmp(&a.deliveries).then(a.id.cmp(&b.id)));
    // Without any delivery record "never fired" would list the whole bank, so it is only told when deliveries exist.
    let tracked = deliveries_total > 0;
    let mut never: Vec<&Row> = if tracked {
        live.iter()
            .copied()
            .filter(|r| r.deliveries == 0 && r.outcomes_w() == 0 && now.saturating_sub(r.banked) >= GRACE)
            .collect()
    } else {
        Vec::new()
    };
    never.sort_by(|a, b| a.banked.cmp(&b.banked).then(a.id.cmp(&b.id)));
    // Lessons inside the one-day grace are left out of "never fired"; say so instead of claiming nothing is missing.
    let fresh = if tracked {
        live.iter().filter(|r| r.deliveries == 0 && r.outcomes_w() == 0 && now.saturating_sub(r.banked) < GRACE).count()
    } else {
        0
    };
    let mut dups: Vec<(&Row, &Row, usize, &str)> = Vec::new();
    for (i, x) in live.iter().enumerate() {
        for y in &live[i + 1..] {
            // Command lessons (`cmd:` tags) fire on their own commands, so a merge or quarantine of one would
            // silence a warning the other never gave. Only identical matcher sets can be duplicates.
            if x.cmds != y.cmds || x.scope != y.scope {
                continue;
            }
            let shared = x.anchors.intersection(&y.anchors).count();
            if trust::near_duplicate(shared, x.anchors.len().min(y.anchors.len())) {
                let (second, why) = trust::duplicate_keep(x.hits_all, y.hits_all, x.deliveries, y.deliveries);
                let (keep, drop) = if second { (*y, *x) } else { (*x, *y) };
                dups.push((keep, drop, shared, why));
            }
        }
    }

    let totals = meter::read(path, window, now);
    let (hits, misses): (u32, u32) = (lessons.iter().map(|d| d.hits).sum(), lessons.iter().map(|d| d.misses).sum());
    let proven = lessons.iter().filter(|d| eligibility::promoted(d.hits, d.misses, 2)).count();
    let bank = meter::Bank { hits, misses, proven };

    // ---- next actions, highest value first
    let mut actions: Vec<Action> = Vec::new();
    if !to_quarantine.is_empty() {
        actions.push(Action {
            score: 3 * to_quarantine.len() + 100,
            why: format!("{} misleading and still served to your agents", plural(to_quarantine.len(), "lesson is", "lessons are")),
            command: cmd("eval --apply-quarantine".into()),
        });
    }
    if let Some(top) = unjudged.first() {
        actions.push(Action {
            score: 2 * unjudged.iter().map(|r| r.deliveries as usize).sum::<usize>(),
            why: format!(
                "{} delivered with no verdict; judging them is what makes good ones proven and bad ones leave",
                plural(unjudged.len(), "lesson was", "lessons were")
            ),
            command: cmd(format!("hit {} --note '…'   # or miss", top.id)),
        });
    }
    if let Some((keep, drop, _, _)) = dups.first() {
        actions.push(Action {
            score: 2 * dups.len() + 1,
            why: format!("{} say nearly the same thing and split the evidence", plural(dups.len(), "pair of lessons", "pairs of lessons")),
            command: cmd(format!(
                "review {} --state quarantined --reason \"duplicate of {}\" --source-ref \"instinct eval\"",
                drop.id, keep.id
            )),
        });
    }
    if let Some(r) = never.first() {
        actions.push(Action {
            score: never.len().min(9),
            why: format!("{} never delivered; check that a reworded `when` still finds it", plural(never.len(), "lesson was", "lessons were")),
            command: cmd(format!("dream --q {} --changed \"<a reworded version>\"", dq(&r.when))),
        });
    }
    actions.sort_by(|a, b| b.score.cmp(&a.score));
    actions.truncate(3);

    // ---- optional write: quarantine the misleading ones, and say so
    let mut applied: Vec<(String, String)> = Vec::new();
    if a.flag("apply-quarantine") {
        for (r, why) in &to_quarantine {
            op_review(path, &r.id, "quarantined", &format!("instinct eval: {why}"), "instinct eval --apply-quarantine")?;
            applied.push((r.id.clone(), why.clone()));
        }
    }

    if a.flag("json") {
        return Ok(json(
            since, now, lessons.len(), &paid, &misled, &to_quarantine, &unjudged, &never, &dups, &totals, &bank,
            &actions, &applied, tracked, deliveries_total, sessions_total, explore.as_ref(),
        ));
    }

    // ---- plain-language report
    let label = match since {
        "all" => "all recorded time".to_string(),
        d => format!("the last {} days", d.trim_end_matches('d')),
    };
    let mut o = String::new();
    o.push_str(&format!(
        "Instinct eval, {label}: {}, {proven} proven, {} and {} recorded.\n",
        plural(lessons.len(), "lesson", "lessons"),
        plural(hits as usize, "hit", "hits"),
        plural(misses as usize, "miss", "misses"),
    ));
    if tracked {
        o.push_str(&format!(
            "Delivery record: {} in {}.\n",
            plural(deliveries_total as usize, "delivery", "deliveries"),
            plural(sessions_total, "session", "sessions")
        ));
        if let (Some(start), Some(_)) = (record_start, window) {
            if start > floor + DAY {
                o.push_str(&format!("  (the record only goes back {} days)\n", now.saturating_sub(start) / DAY));
            }
        }
    } else {
        o.push_str("Delivery record: nothing in this window. The prompt and guard hooks write it when the agent passes a session id.\n");
    }
    if lessons.is_empty() {
        o.push_str("\nThe bank is empty. Save the first lesson with `instinct bank --title T --when W --found F --how H --evidence E`.\n");
        return Ok(o.trim_end().to_string());
    }

    o.push_str(&format!("\nPaid off ({})\n", paid.len()));
    if paid.is_empty() {
        o.push_str("  No lesson has a recorded hit in this window.\n");
    }
    for r in &paid {
        o.push_str(&format!(
            "  {}  {}\n      {} and {}, {}% hit rate{}\n",
            r.id,
            shorten(&r.title, 60),
            plural(r.hits_w as usize, "hit", "hits"),
            plural(r.misses_w as usize, "miss", "misses"),
            r.rate(),
            if r.proven() { ", proven in use" } else { ", not proven yet (needs 2+ hits and strength 0.6)" }
        ));
    }

    o.push_str(&format!("\nMisled ({})\n", misled.len()));
    if misled.is_empty() {
        o.push_str("  No lesson has a recorded miss in this window.\n");
    }
    for r in &misled {
        let verdict = match r.quarantine_reason() {
            Some(why) => format!("quarantine: {why}"),
            None => "keep watching".to_string(),
        };
        o.push_str(&format!(
            "  {}  {}\n      {} and {}; {verdict}\n",
            r.id,
            shorten(&r.title, 60),
            plural(r.misses_w as usize, "miss", "misses"),
            plural(r.hits_w as usize, "hit", "hits")
        ));
    }
    if !applied.is_empty() {
        o.push_str("  Applied --apply-quarantine:\n");
        for (id, why) in &applied {
            o.push_str(&format!("    quarantined {id} ({why}); the original stays in the journal\n"));
        }
    } else if !to_quarantine.is_empty() {
        o.push_str("  Nothing was changed. `instinct eval --apply-quarantine` quarantines the lessons marked above.\n");
    }

    o.push_str(&format!("\nDelivered but never judged ({})\n", unjudged.len()));
    if unjudged.is_empty() {
        o.push_str("  Every delivered lesson has a verdict.\n");
    }
    if !unjudged.is_empty() {
        o.push_str(&format!(
            "  Judge them from the session transcripts: look first, then record.\n      {}\n      {}\n  Or one by one:\n",
            cmd(format!("outcomes --since {since}")),
            cmd(format!("outcomes --since {since} --apply")),
        ));
    }
    for r in &unjudged {
        o.push_str(&format!(
            "  {}  {}\n      delivered {}, no hit or miss recorded\n      {}\n      {}\n",
            r.id,
            shorten(&r.title, 60),
            plural(r.deliveries as usize, "time", "times"),
            cmd(format!("hit {} --note '…'", r.id)),
            cmd(format!("miss {} --note '…'", r.id)),
        ));
    }

    if let Some(r) = &explore {
        o.push_str("\nWithheld vs delivered (INSTINCT_EXPLORE)\n");
        for line in outcomes::comparison_text(r).lines() {
            o.push_str(&format!("  {line}\n"));
        }
    }

    o.push_str(&format!("\nNever fired ({})\n", never.len()));
    if !tracked {
        o.push_str("  Cannot tell yet, there are no recorded deliveries.\n");
    } else if never.is_empty() && fresh == 0 {
        o.push_str("  Every banked lesson was delivered or judged in this window.\n");
    } else {
        if !never.is_empty() {
            o.push_str("  Banked, never delivered. Reword `when` (the words a future question will use) or add `--tags`.\n");
        }
        if fresh > 0 {
            o.push_str(&format!(
                "  {} banked in the last day; they show here once they are a day old.\n",
                plural(fresh, "lesson was", "lessons were")
            ));
        }
    }
    for r in &never {
        o.push_str(&format!(
            "  {}  {}\n      when: {}\n      check: {}\n",
            r.id,
            shorten(&r.title, 60),
            shorten(&r.when, 100),
            cmd(format!("dream --q {} --changed \"<a reworded version>\"", dq(&r.when)))
        ));
    }

    o.push_str(&format!("\nNear-duplicates ({})\n", dups.len()));
    if dups.is_empty() {
        o.push_str("  No two lessons share most of their `when` words.\n");
    }
    for (keep, drop, shared, why) in &dups {
        o.push_str(&format!(
            "  {} and {} share {} anchor words\n      {}\n      {}\n      merge: keep {} ({why}), then\n      {}\n",
            keep.id,
            drop.id,
            shared,
            shorten(&keep.when, 100),
            shorten(&drop.when, 100),
            keep.id,
            cmd(format!("review {} --state quarantined --reason \"duplicate of {}\" --source-ref \"instinct eval\"", drop.id, keep.id))
        ));
    }

    o.push('\n');
    o.push_str(&meter::block(&totals, &bank, since));
    o.push_str("\n\nNext three actions\n");
    if actions.is_empty() {
        o.push_str("  Nothing to fix. Keep judging lessons as they are used.\n");
    }
    for (i, act) in actions.iter().enumerate() {
        o.push_str(&format!("  {}. {}\n     {}\n", i + 1, act.why, act.command));
    }
    Ok(o.trim_end().to_string())
}

fn row_json(r: &Row) -> Vec<(String, Json)> {
    let n = |v: u32| Json::Num(v as f64);
    vec![
        ("id".into(), Json::Str(r.id.clone())),
        ("title".into(), Json::Str(r.title.clone())),
        ("when".into(), Json::Str(r.when.clone())),
        ("hits".into(), n(r.hits_w)),
        ("misses".into(), n(r.misses_w)),
        ("deliveries".into(), n(r.deliveries)),
        ("proven".into(), Json::Bool(r.proven())),
    ]
}

#[allow(clippy::too_many_arguments)]
fn json(
    since: &str,
    now: u64,
    lessons: usize,
    paid: &[&Row],
    misled: &[&Row],
    quarantine: &[(&Row, String)],
    unjudged: &[&Row],
    never: &[&Row],
    dups: &[(&Row, &Row, usize, &str)],
    totals: &meter::Totals,
    bank: &meter::Bank,
    actions: &[Action],
    applied: &[(String, String)],
    tracked: bool,
    deliveries: u32,
    sessions: usize,
    explore: Option<&outcomes::Report>,
) -> String {
    let list = |rows: &[&Row], extra: &dyn Fn(&Row) -> Vec<(String, Json)>| {
        Json::Arr(
            rows.iter()
                .map(|r| {
                    let mut f = row_json(r);
                    f.extend(extra(r));
                    Json::Obj(f)
                })
                .collect(),
        )
    };
    let none = |_: &Row| Vec::new();
    let misled_extra = |r: &Row| {
        let why = r.quarantine_reason();
        vec![("quarantine".into(), Json::Bool(why.is_some())), ("reason".into(), Json::Str(why.unwrap_or_default()))]
    };
    let paid_extra = |r: &Row| vec![("hit_rate_percent".into(), Json::Num(r.rate() as f64))];
    let id_reason = |id: &str, why: &str| {
        Json::Obj(vec![("id".into(), Json::Str(id.into())), ("reason".into(), Json::Str(why.into()))])
    };
    let doc = Json::Obj(vec![
        ("schema".into(), Json::Str("instinct-eval/1".into())),
        ("since".into(), Json::Str(since.into())),
        ("generated".into(), Json::Num(now as f64)),
        ("lessons".into(), Json::Num(lessons as f64)),
        ("proven".into(), Json::Num(bank.proven as f64)),
        (
            "delivery_record".into(),
            Json::Obj(vec![
                ("tracked".into(), Json::Bool(tracked)),
                ("deliveries".into(), Json::Num(deliveries as f64)),
                ("sessions".into(), Json::Num(sessions as f64)),
            ]),
        ),
        ("paid_off".into(), list(paid, &paid_extra)),
        ("misled".into(), list(misled, &misled_extra)),
        ("to_quarantine".into(), Json::Arr(quarantine.iter().map(|(r, why)| id_reason(&r.id, why)).collect())),
        ("delivered_never_judged".into(), list(unjudged, &none)),
        ("never_fired".into(), list(never, &none)),
        (
            "near_duplicates".into(),
            Json::Arr(
                dups.iter()
                    .map(|(keep, drop, shared, _)| {
                        Json::Obj(vec![
                            ("keep".into(), Json::Str(keep.id.clone())),
                            ("merge_away".into(), Json::Str(drop.id.clone())),
                            ("shared_anchor_words".into(), Json::Num(*shared as f64)),
                        ])
                    })
                    .collect(),
            ),
        ),
        ("savings".into(), parse_json(&meter::json(totals, bank, since)).unwrap_or(Json::Null)),
        (
            "next_actions".into(),
            Json::Arr(
                actions
                    .iter()
                    .map(|a| {
                        Json::Obj(vec![
                            ("why".into(), Json::Str(a.why.clone())),
                            ("command".into(), Json::Str(a.command.clone())),
                        ])
                    })
                    .collect(),
            ),
        ),
        ("applied_quarantine".into(), Json::Arr(applied.iter().map(|(id, why)| id_reason(id, why)).collect())),
        (
            "explore".into(),
            explore.map_or(Json::Null, |r| parse_json(&outcomes::comparison_json(r)).unwrap_or(Json::Null)),
        ),
    ]);
    json_out(&doc)
}