instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
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
//! `instinct outcomes` on the fixture week in tests/fixtures/outcomes-week, and the explore arm of the hooks.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_instinct")
}

fn fixtures() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/outcomes-week")
}

fn run(store: &Path, args: &[&str], stdin: &str, env: &[(&str, &str)]) -> (i32, String) {
    let mut c = Command::new(bin());
    c.args(args).env("INSTINCT_STORE", store).env_remove("INSTINCT_EXPLORE");
    for (k, v) in env {
        c.env(k, v);
    }
    let mut child = c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
    let _ = child.stdin.take().unwrap().write_all(stdin.as_bytes());
    let out = child.wait_with_output().unwrap();
    let mut text = String::from_utf8(out.stdout).unwrap();
    if !out.status.success() {
        text.push_str(&String::from_utf8_lossy(&out.stderr));
    }
    (out.status.code().unwrap(), text)
}

fn temp(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("instinct-outcomes-{}-{}-{name}", std::process::id(), uniq()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir.join("bank.hxdb")
}

fn bank(store: &Path, title: &str, when: &str, found: &str, how: &str) -> String {
    let (code, out) = run(
        store,
        &["bank", "--title", title, "--when", when, "--found", found, "--how", how, "--evidence", "seen twice"],
        "",
        &[],
    );
    assert_eq!(code, 0, "{out}");
    out.split_whitespace().nth(1).unwrap().to_owned()
}

/// A store holding the three fixture lessons, and `<store>.sessions` filled from the fixture template.
fn week(name: &str) -> (PathBuf, [String; 3]) {
    let store = temp(name);
    let l1 = bank(
        &store,
        "Cargo registry mirror outage",
        "the cargo registry mirror is down",
        "fetch fails while the mirror is out",
        "use the vendored dir with cargo fetch --offline --vendored-sources",
    );
    let l2 = bank(
        &store,
        "pkill -f kills its own shell",
        "pkill -f worker stop process",
        "pkill -f matches its own shell and exits 144",
        "kill by pid with kill -TERM",
    );
    let l3 = bank(
        &store,
        "Migration lock timeout",
        "the database migration is stuck on a lock",
        "a blocking backend holds the lock",
        "terminate the blocking backend with pg_terminate_backend and set a short lock timeout",
    );
    let tpl = std::fs::read_to_string(fixtures().join("week.sessions")).unwrap();
    let text = tpl.replace("@L1@", &l1).replace("@L2@", &l2).replace("@L3@", &l3);
    let mut sessions = store.as_os_str().to_owned();
    sessions.push(".sessions");
    std::fs::write(sessions, text).unwrap();
    (store, [l1, l2, l3])
}

fn outcomes(store: &Path, extra: &[&str]) -> String {
    let f = fixtures();
    let (claude, codex) = (f.join("claude"), f.join("codex"));
    let mut args = vec!["outcomes", claude.to_str().unwrap(), codex.to_str().unwrap(), "--since", "36500d"];
    args.extend_from_slice(extra);
    let (code, out) = run(store, &args, "", &[]);
    assert_eq!(code, 0, "{out}");
    out
}

fn line_for<'a>(out: &'a str, label: &str, lesson: &str, hook: &str) -> Vec<&'a str> {
    out.lines()
        .filter(|l| {
            let f: Vec<&str> = l.split_whitespace().collect();
            f.first() == Some(&label) && f.get(1) == Some(&lesson) && f.get(2) == Some(&hook)
        })
        .collect()
}

#[test]
fn every_label_is_produced_with_its_evidence() {
    let (store, [l1, l2, l3]) = week("labels");
    let out = outcomes(&store, &[]);
    assert!(out.contains("13 delivered, 7 withheld, 19 transcript(s) read"), "{out}");
    assert!(out.contains("helped 7 . misled 2 . unused 3 . unclear 1"), "{out}");
    // prompt, helped: lesson words that were not in the prompt show up in the next calls, no correction
    assert_eq!(line_for(&out, "helped", &l1, "prompt").len(), 4, "{out}");
    assert!(out.contains("acted on it (fails, fetch, offline); no correction in 3 user turns"), "{out}");
    // prompt, misled: acted on it, then the user said it was wrong
    assert!(out.contains("then the user corrected: \"no, that's wrong, revert that\""), "{out}");
    // prompt, unused
    assert_eq!(line_for(&out, "unused", &l1, "prompt").len(), 1, "{out}");
    assert!(out.contains("not acted on: no lesson words in the next 1 calls; no correction"), "{out}");
    // tripwire: warned call failed once and never again; failed again; succeeded and nothing failed
    assert_eq!(line_for(&out, "helped", &l2, "guard").len(), 2, "{out}");
    assert!(out.contains("warned call failed once; it was not repeated, and the next 4 calls ran clean"), "{out}");
    assert_eq!(line_for(&out, "misled", &l2, "guard").len(), 1, "{out}");
    assert!(out.contains("the warned action failed again: `pkill -f worker --signal 9`"), "{out}");
    assert_eq!(line_for(&out, "unused", &l2, "guard").len(), 1, "{out}");
    // a delivery whose transcript is not here
    assert_eq!(line_for(&out, "unclear", &l3, "prompt").len(), 1, "{out}");
    assert!(out.contains("no transcript found for this session"), "{out}");
    // the Codex session is read the same way
    assert!(out.contains("dddddddd"), "{out}");
    assert!(out.contains("dry run: nothing written"), "{out}");
}

#[test]
fn dry_run_writes_nothing_and_apply_is_idempotent() {
    let (store, [l1, ..]) = week("apply");
    let before = std::fs::read(&store).unwrap();
    outcomes(&store, &[]);
    assert_eq!(std::fs::read(&store).unwrap(), before, "a dry run must not touch the bank");

    let first = outcomes(&store, &["--apply"]);
    assert!(first.contains("applied: 7 hit(s), 2 miss(es) recorded; 0 already recorded"), "{first}");
    let after_first = std::fs::read(&store).unwrap();
    assert_ne!(after_first, before);
    let second = outcomes(&store, &["--apply"]);
    assert!(second.contains("applied: 0 hit(s), 0 miss(es) recorded; 9 already recorded"), "{second}");
    assert_eq!(std::fs::read(&store).unwrap(), after_first, "a rerun must not write anything");

    let (_, listing) = run(&store, &["instincts"], "", &[]);
    assert!(listing.contains(&format!("{l1} · 4 hits")), "{listing}");
}

#[test]
fn an_explicit_hit_is_never_counted_twice() {
    let (store, [l1, ..]) = week("explicit");
    // The agent marked the lesson itself in the session that ended up `helped`. The record carries no
    // session, so the guard is "after the delivery and before that session's transcript ends": the first
    // fixture session starts at 1795609800 and its last event is 30 minutes later.
    let (code, _) = run(&store, &["hit", &l1, "--note", "explicit"], "", &[]);
    assert_eq!(code, 0);
    // Marks are stamped with the real clock, which is long after the fixture week: nothing is suppressed.
    let out = outcomes(&store, &["--apply"]);
    assert!(out.contains("7 hit(s)"), "{out}");
    assert!(out.contains("0 skipped because the agent marked them itself"), "{out}");
}

fn civil_iso(secs: u64) -> String {
    let days = (secs / 86_400) as i64;
    let rem = secs % 86_400;
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = yoe + era * 400 + i64::from(m <= 2);
    format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60)
}

/// A session that is happening now: the lesson is delivered, used, and three calm turns follow.
fn live_session(store: &Path, dir: &Path, sid: &str, lesson: &str) {
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
    let t = now - 1900;
    let user = |at: u64, text: &str| {
        format!("{{\"type\":\"user\",\"sessionId\":\"{sid}\",\"timestamp\":\"{}\",\"message\":{{\"role\":\"user\",\"content\":\"{text}\"}}}}\n", civil_iso(at))
    };
    let mut lines = user(t, "the cargo registry mirror is down again");
    lines.push_str(&format!(
        "{{\"type\":\"assistant\",\"sessionId\":\"{sid}\",\"timestamp\":\"{}\",\"message\":{{\"role\":\"assistant\",\"content\":[{{\"type\":\"tool_use\",\"id\":\"u1\",\"name\":\"Bash\",\"input\":{{\"command\":\"cargo fetch --offline --vendored-sources\"}}}}]}}}}\n",
        civil_iso(t + 5)
    ));
    lines.push_str(&user(t + 600, "ok now run the tests"));
    lines.push_str(&user(t + 1200, "thanks"));
    lines.push_str(&user(t + 1800, "next task please"));
    std::fs::create_dir_all(dir).unwrap();
    std::fs::write(dir.join(format!("{sid}.jsonl")), lines).unwrap();
    let mut p = store.as_os_str().to_owned();
    p.push(".sessions");
    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(PathBuf::from(p)).unwrap();
    writeln!(f, "{}\t{sid}\tD\t{lesson}\tp", t + 1).unwrap();
}

fn live_outcomes(store: &Path, dir: &Path, extra: &[&str]) -> String {
    let mut args = vec!["outcomes", dir.to_str().unwrap(), "--since", "1d"];
    args.extend_from_slice(extra);
    let (code, out) = run(store, &args, "", &[]);
    assert_eq!(code, 0, "{out}");
    out
}

#[test]
fn an_explicit_mark_in_the_same_session_wins_and_is_never_counted_twice() {
    let store = temp("explicit-live");
    let id = bank(
        &store,
        "Cargo registry mirror outage",
        "the cargo registry mirror is down",
        "fetch fails while the mirror is out",
        "use the vendored dir with cargo fetch --offline --vendored-sources",
    );
    let dir = store.parent().unwrap().join("transcripts");
    live_session(&store, &dir, "live-session-1", &id);

    // Observed alone: helped, one hit.
    let dry = live_outcomes(&store, &dir, &[]);
    assert!(dry.contains(&format!("helped  {id} prompt")), "{dry}");

    // The agent records its own hit during that session (stamped now, inside the session's window).
    let (code, _) = run(&store, &["hit", &id, "--note", "agent said so"], "", &[]);
    assert_eq!(code, 0);
    let out = live_outcomes(&store, &dir, &["--apply"]);
    assert!(out.contains("applied: 0 hit(s), 0 miss(es) recorded; 0 already recorded; 1 skipped because the agent marked them itself"), "{out}");
    let (_, listing) = run(&store, &["recall", "--q", "the cargo registry mirror is down"], "", &[]);
    assert!(listing.contains("1 hit / 0 miss"), "one hit, from the agent only: {listing}");
}

#[test]
fn without_an_explicit_mark_the_same_session_records_exactly_one_hit() {
    let store = temp("observed-live");
    let id = bank(
        &store,
        "Cargo registry mirror outage",
        "the cargo registry mirror is down",
        "fetch fails while the mirror is out",
        "use the vendored dir with cargo fetch --offline --vendored-sources",
    );
    let dir = store.parent().unwrap().join("transcripts");
    live_session(&store, &dir, "live-session-2", &id);
    let out = live_outcomes(&store, &dir, &["--apply"]);
    assert!(out.contains("applied: 1 hit(s), 0 miss(es) recorded; 0 already recorded; 0 skipped"), "{out}");
    let again = live_outcomes(&store, &dir, &["--apply"]);
    assert!(again.contains("applied: 0 hit(s), 0 miss(es) recorded; 1 already recorded"), "{again}");
    let (_, listing) = run(&store, &["recall", "--q", "the cargo registry mirror is down"], "", &[]);
    assert!(listing.contains("1 hit / 0 miss"), "{listing}");
}

#[test]
fn json_output_carries_the_labels_and_the_comparison() {
    let (store, _) = week("json");
    let out = outcomes(&store, &["--json"]);
    assert!(out.starts_with("{\"delivered\":13,\"withheld\":7,"), "{out}");
    assert!(out.contains("\"helped\":7,\"misled\":2,\"unused\":3,\"unclear\":1"), "{out}");
    assert!(out.contains("\"comparison\":{\"lessons\":2,"), "{out}");
    assert!(out.contains("\"outcome_id\":\"outcome:"), "{out}");
}

fn prompt_json(sid: &str, text: &str) -> String {
    format!("{{\"session_id\":\"{sid}\",\"prompt\":\"{text}\"}}")
}

#[test]
fn explore_arm_withholds_records_hold_and_stays_stable() {
    let store = temp("explore");
    let id = bank(&store, "Cargo registry mirror outage", "the cargo registry mirror is down", "fetch fails", "use the vendored dir");
    let q = prompt_json("sess-explore-1", "the cargo registry mirror is down again");
    let sessions = {
        let mut p = store.as_os_str().to_owned();
        p.push(".sessions");
        PathBuf::from(p)
    };

    // Off by default: delivered, recorded as D with the prompt source.
    let (_, out) = run(&store, &["prompt"], &q, &[]);
    assert!(out.contains(&id), "{out}");
    let text = std::fs::read_to_string(&sessions).unwrap();
    assert!(text.lines().any(|l| l.ends_with(&format!("\tD\t{id}\tp"))), "{text}");

    // Share 1: always withheld, recorded as H, nothing printed, and asking again stays the same.
    let (_, out) = run(&store, &["prompt"], &prompt_json("sess-explore-2", "the cargo registry mirror is down again"), &[("INSTINCT_EXPLORE", "1")]);
    assert!(out.trim().is_empty(), "{out}");
    let (_, again) = run(&store, &["prompt"], &prompt_json("sess-explore-2", "the cargo registry mirror is down again"), &[("INSTINCT_EXPLORE", "1")]);
    assert!(again.trim().is_empty(), "{again}");
    let text = std::fs::read_to_string(&sessions).unwrap();
    let held: Vec<&str> = text.lines().filter(|l| l.contains("\tH\t")).collect();
    assert_eq!(held.len(), 1, "a withheld lesson is recorded once per session: {text}");
    assert!(held[0].contains("sess-explore-2") && held[0].ends_with(&format!("\tH\t{id}\tp")), "{text}");

    // Share 0 and junk values mean off.
    for (n, off) in ["0", "", "abc", "-1"].into_iter().enumerate() {
        let (_, out) = run(&store, &["prompt"], &prompt_json(&format!("sess-explore-off-{n}"), "the cargo registry mirror is down again"), &[("INSTINCT_EXPLORE", off)]);
        assert!(out.contains(&id), "INSTINCT_EXPLORE={off:?}: {out}");
    }
}

#[test]
fn explore_arm_covers_the_tripwire_too() {
    let store = temp("explore-guard");
    let (code, out) = run(
        &store,
        &["bank", "--title", "pkill -f kills its own shell", "--when", "pkill -f worker", "--found", "pkill -f matches itself", "--how", "kill by pid", "--evidence", "seen", "--tags", "tool_bash pkill"],
        "",
        &[],
    );
    assert_eq!(code, 0, "{out}");
    let id = out.split_whitespace().nth(1).unwrap().to_owned();
    let payload = "{\"session_id\":\"sess-g-1\",\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"tool_input\":{\"command\":\"pkill -f worker\"}}";
    let (_, held) = run(&store, &["guard"], payload, &[("INSTINCT_EXPLORE", "1")]);
    assert!(held.trim().is_empty(), "{held}");
    let mut p = store.as_os_str().to_owned();
    p.push(".sessions");
    let text = std::fs::read_to_string(PathBuf::from(p)).unwrap();
    assert!(text.lines().any(|l| l.ends_with(&format!("\tH\t{id}\tg"))), "{text}");
}

#[test]
fn explore_share_is_close_to_the_requested_share() {
    // The hash is stable and uniform (unit-tested in session.rs); here the hook over many sessions.
    let store = temp("explore-share");
    bank(&store, "Cargo registry mirror outage", "the cargo registry mirror is down", "fetch fails", "use the vendored dir");
    let mut held = 0;
    let n = 200;
    for i in 0..n {
        let q = prompt_json(&format!("share-session-{i}"), "the cargo registry mirror is down again");
        let (_, out) = run(&store, &["prompt"], &q, &[("INSTINCT_EXPLORE", "0.25")]);
        if out.trim().is_empty() {
            held += 1;
        }
    }
    let share = held as f64 / n as f64;
    assert!((0.15..0.35).contains(&share), "withheld share {share} for 0.25");
}

fn copy_dir(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).unwrap();
    for e in std::fs::read_dir(from).unwrap().flatten() {
        std::fs::copy(e.path(), to.join(e.file_name())).unwrap();
    }
}

/// Homes for the two harnesses, filled from the fixture week, so `eval` finds the transcripts by itself.
fn harness_homes(store: &Path) -> (String, String) {
    let root = store.parent().unwrap().join("homes");
    copy_dir(&fixtures().join("claude"), &root.join("claude/projects/p"));
    copy_dir(&fixtures().join("codex"), &root.join("codex/sessions/2026/11/28"));
    (root.join("claude").to_string_lossy().into_owned(), root.join("codex").to_string_lossy().into_owned())
}

#[test]
fn eval_counts_only_real_deliveries_and_points_at_outcomes() {
    let (store, [l1, ..]) = week("eval-suggest");
    let (code, out) = run(&store, &["eval", "--since", "all"], "", &[("HOME", "/nonexistent")]);
    assert_eq!(code, 0, "{out}");
    // 13 delivered lines in the record; the 7 withheld (H) lines are not deliveries
    assert!(out.contains("Delivery record: 13 deliveries in 13 sessions."), "{out}");
    assert!(out.contains(&format!("{l1}  Cargo registry mirror outage\n      delivered 6 times")), "{out}");
    // the automatic way to judge them, dry run first
    assert!(out.contains("Judge them from the session transcripts: look first, then record."), "{out}");
    let dry = out.find("instinct outcomes --since all\n").expect("dry run suggestion");
    let apply = out.find("instinct outcomes --since all --apply\n").expect("apply suggestion");
    assert!(dry < apply, "{out}");
    // and the by-hand commands stay
    assert!(out.contains(&format!("instinct hit {l1} --note")), "{out}");
}

#[test]
fn eval_reports_the_explore_comparison_when_held_lines_exist() {
    let (store, _) = week("eval-explore");
    let (claude, codex) = harness_homes(&store);
    let env = [("CLAUDE_CONFIG_DIR", claude.as_str()), ("CODEX_HOME", codex.as_str()), ("HOME", "/nonexistent")];
    let (code, out) = run(&store, &["eval", "--since", "all"], "", &env);
    assert_eq!(code, 0, "{out}");
    assert!(out.contains("Withheld vs delivered (INSTINCT_EXPLORE)"), "{out}");
    assert!(out.contains("prompt, corrections in the next 3 turns: delivered 16.7% (1/6) vs withheld 25.0% (1/4)"), "{out}");
    assert!(out.contains("tripwire, failed share of the next 8 calls: delivered 7.7% (1/13) vs withheld 22.2% (2/9)"), "{out}");
    assert!(out.contains("caveat: only 6 delivered and 4 withheld observations"), "{out}");
    let (code, json) = run(&store, &["eval", "--since", "all", "--json"], "", &env);
    assert_eq!(code, 0, "{json}");
    assert!(json.contains("\"explore\":{\"delivered\":13,\"withheld\":7,\"lessons\":2,"), "{json}");
}

#[test]
fn eval_has_no_explore_section_without_held_lines() {
    let store = temp("eval-no-explore");
    let id = bank(&store, "Cargo registry mirror outage", "the cargo registry mirror is down", "fetch fails", "use the vendored dir");
    let (_, _) = run(&store, &["prompt"], &prompt_json("sess-plain", "the cargo registry mirror is down again"), &[]);
    let (code, out) = run(&store, &["eval", "--since", "all"], "", &[("HOME", "/nonexistent")]);
    assert_eq!(code, 0, "{out}");
    assert!(!out.contains("INSTINCT_EXPLORE"), "{out}");
    assert!(out.contains(&format!("{id}  Cargo registry mirror outage")), "{out}");
    let (_, json) = run(&store, &["eval", "--since", "all", "--json"], "", &[("HOME", "/nonexistent")]);
    assert!(json.contains("\"explore\":null"), "{json}");
}

/// A number no other call in this test process has seen, so parallel tests never share a folder.
fn uniq() -> usize {
    static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}