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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Session memory for the hooks (`<store>.sessions`), `instinct settle`, and the title gate.
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};

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

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

/// Runs the binary with stdin; returns (exit code, stdout). Stderr must stay empty.
fn run(store: Option<&PathBuf>, args: &[&str], stdin: &str) -> (i32, String) {
    let mut c = Command::new(bin());
    c.args(args).env_remove("INSTINCT_STORE");
    if let Some(s) = store {
        c.env("INSTINCT_STORE", s);
    }
    let mut child = c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
    if let Err(e) = child.stdin.take().unwrap().write_all(stdin.as_bytes()) {
        assert_eq!(e.kind(), std::io::ErrorKind::BrokenPipe, "unexpected write error: {e}");
    }
    let out = child.wait_with_output().unwrap();
    (out.status.code().unwrap(), String::from_utf8(out.stdout).unwrap())
}

/// Banks one lesson whose `when` and tags never match the test queries; returns (id, bank output).
fn bank(store: &PathBuf, title: &str, tags: Option<&str>) -> (String, String) {
    let mut args = vec![
        "bank", "--title", title, "--when", "zzzz yyyy", "--found", "f", "--how", "use the vendored dir",
        "--evidence", "seen twice",
    ];
    if let Some(t) = tags {
        args.extend(["--tags", t]);
    }
    let (code, out) = run(Some(store), &args, "");
    assert_eq!(code, 0, "{out}");
    let id = out.split_whitespace().nth(1).unwrap().to_owned();
    (id, out)
}

const TITLE: &str = "Cargo registry mirror outage";
const PROMPT: &str = "the cargo registry mirror is down again";

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

fn guard(sid: &str, command: &str) -> String {
    format!(
        "{{\"session_id\":\"{sid}\",\"hook_event_name\":\"PreToolUse\",\"tool_name\":\"Bash\",\"tool_input\":{{\"command\":\"{command}\"}}}}"
    )
}

fn stop(sid: &str) -> String {
    format!("{{\"session_id\":\"{sid}\",\"hook_event_name\":\"Stop\",\"stop_hook_active\":false}}")
}

#[test]
fn the_same_lesson_is_not_delivered_twice_in_one_session() {
    let s = store("dedupe");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let (_, first) = run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    assert!(first.contains(&id), "{first}");
    let (code, second) = run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    assert_eq!(code, 0);
    assert!(!second.contains(TITLE), "repeat delivery: {second}");
    // The second prompt carries the once-per-session question about the first lesson instead.
    assert!(second.contains(&format!("instinct hit {id}")), "{second}");
    // Another session still gets it.
    let (_, other) = run(Some(&s), &["prompt"], &prompt("b", PROMPT));
    assert!(other.contains(&id), "{other}");
    // The record holds ids and counts only.
    let rec = std::fs::read_to_string(format!("{}.sessions", s.display())).unwrap();
    assert_eq!(rec.lines().count(), 3, "delivered a, reminded a, delivered b: {rec}");
    assert!(rec.lines().all(|l| (4..=5).contains(&l.split('\t').count())), "{rec}");
}

#[test]
fn guard_and_prompt_share_the_session_record() {
    let s = store("shared");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let (_, first) = run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    assert!(first.contains(&id));
    let (code, out) = run(Some(&s), &["guard"], &guard("a", "cargo registry mirror down"));
    assert_eq!(code, 0);
    assert!(out.trim().is_empty(), "guard repeated the lesson: {out}");
    let (_, other) = run(Some(&s), &["guard"], &guard("b", "cargo registry mirror down"));
    assert!(other.contains(&id), "{other}");
}

#[test]
fn without_a_session_id_nothing_is_remembered() {
    let s = store("nosession");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    for _ in 0..2 {
        let (_, out) = run(Some(&s), &["prompt"], &format!("{{\"prompt\":\"{PROMPT}\"}}"));
        assert!(out.contains(&id), "{out}");
    }
    assert!(!PathBuf::from(format!("{}.sessions", s.display())).exists());
}

#[test]
fn old_session_lines_are_pruned_on_write() {
    let s = store("prune");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let file = format!("{}.sessions", s.display());
    std::fs::write(&file, "1000\told\tD\tin-old\n").unwrap();
    let (_, out) = run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    assert!(out.contains(&id));
    let rec = std::fs::read_to_string(&file).unwrap();
    assert!(!rec.contains("in-old"), "{rec}");
    assert_eq!(rec.lines().count(), 1, "{rec}");
}

#[test]
fn settle_reminds_once_with_the_documented_stop_form() {
    let s = store("settle");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    let (code, out) = run(Some(&s), &["settle"], &stop("a"));
    assert_eq!(code, 0);
    let want = format!(
        "{{\"hookSpecificOutput\":{{\"hookEventName\":\"Stop\",\"additionalContext\":\"You used lesson {id} this session. If it helped, run `instinct hit {id} --note '…'`; if it misled you, `instinct miss {id} --note '…'`.\"}}}}"
    );
    assert_eq!(out.trim(), want);
    let (code, again) = run(Some(&s), &["settle"], &stop("a"));
    assert_eq!(code, 0);
    assert!(again.trim().is_empty(), "second reminder: {again}");
}

#[test]
fn settle_codex_form_and_text_form() {
    let s = store("settle-forms");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    let (_, out) = run(Some(&s), &["settle", "--format", "codex"], &stop("a"));
    assert!(out.starts_with("{\"decision\":\"block\",\"reason\":\"You used lesson "), "{out}");
    assert!(out.contains(&id));
    run(Some(&s), &["prompt"], &prompt("t", PROMPT));
    let (_, text) = run(Some(&s), &["settle", "--format", "text"], &stop("t"));
    assert!(text.starts_with("You used lesson "), "{text}");
}

#[test]
fn settle_is_silent_when_nothing_is_owed_and_never_fails() {
    let s = store("silent");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    // Nothing delivered in this session.
    let (code, out) = run(Some(&s), &["settle"], &stop("a"));
    assert_eq!((code, out.trim()), (0, ""));
    // Delivered, then a hit recorded: settled.
    run(Some(&s), &["prompt"], &prompt("a", PROMPT));
    let (code, _) = run(Some(&s), &["hit", &id, "--note", "worked"], "");
    assert_eq!(code, 0);
    let (code, out) = run(Some(&s), &["settle"], &stop("a"));
    assert_eq!((code, out.trim()), (0, ""));
    // A miss settles too.
    run(Some(&s), &["prompt"], &prompt("m", PROMPT));
    run(Some(&s), &["miss", &id, "--note", "misled", "--outcome-id", "o2"], "");
    let (code, out) = run(Some(&s), &["settle"], &stop("m"));
    assert_eq!((code, out.trim()), (0, ""));
    // A Stop hook that is itself the continuation of a Stop hook stays silent.
    run(Some(&s), &["prompt"], &prompt("c", PROMPT));
    let (code, out) = run(
        Some(&s),
        &["settle"],
        "{\"session_id\":\"c\",\"stop_hook_active\":true}",
    );
    assert_eq!((code, out.trim()), (0, ""));
    // Bad input, empty input, a payload without session_id, and a missing store all exit 0 and print nothing.
    for input in ["", "not json", "{}", "{\"session_id\":\"\"}", "[1,2]"] {
        let (code, out) = run(Some(&s), &["settle"], input);
        assert_eq!((code, out.trim()), (0, ""), "input {input:?}");
    }
    let (code, out) = run(None, &["settle"], &stop("a"));
    assert_eq!((code, out.trim()), (0, ""));
}

#[test]
fn settle_exit_code_is_zero_with_an_unreadable_session_file() {
    let s = store("garbled");
    bank(&s, TITLE, Some("qqqq wwww"));
    std::fs::write(format!("{}.sessions", s.display()), b"\xff\xfe\nnot\ttabs\n").unwrap();
    let (code, out) = run(Some(&s), &["settle"], &stop("a"));
    assert_eq!((code, out.trim()), (0, ""));
}

#[test]
fn the_title_counts_toward_the_two_word_trigger() {
    let s = store("title");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let (_, out) = run(Some(&s), &["prompt"], &prompt("t1", PROMPT));
    assert!(out.contains(&id), "title-only match was not recalled: {out}");
    // One shared word is not a trigger.
    let (_, one) = run(Some(&s), &["prompt"], &prompt("t2", "my cargo build is slow today"));
    assert!(one.trim().is_empty(), "{one}");
}

#[test]
fn banking_without_tags_derives_one_phrase_from_the_title() {
    let s = store("derive");
    bank(&s, "Cargo registry mirror outage during the build", None);
    let (_, out) = run(Some(&s), &["recall", "--q", "cargo registry mirror outage"], "");
    assert!(out.contains("TAGS: cargo registry mirror outage"), "{out}");
    // Explicit tags are never replaced.
    bank(&s, "Another distinct lesson title here", Some("mine"));
    let (_, kept) = run(Some(&s), &["recall", "--q", "another distinct lesson title"], "");
    assert!(kept.contains("TAGS: mine"), "{kept}");
    // A title with fewer than two distinctive words gets no tag.
    bank(&s, "The fix", None);
    let (_, none) = run(Some(&s), &["recall", "--q", "fix"], "");
    assert!(!none.contains("TAGS:"), "{none}");
}

/// A Claude Code transcript for session `sid`, stamped in 2099 so every event is after the delivery.
fn transcript(s: &PathBuf, sid: &str, with_tool: bool) -> PathBuf {
    let u = |t: &str, content: &str| {
        format!("{{\"type\":\"user\",\"sessionId\":\"{sid}\",\"timestamp\":\"2099-01-01T00:00:{t}Z\",\"message\":{{\"role\":\"user\",\"content\":{content}}}}}\n")
    };
    let a = |t: &str, content: &str| {
        format!("{{\"type\":\"assistant\",\"sessionId\":\"{sid}\",\"timestamp\":\"2099-01-01T00:00:{t}Z\",\"message\":{{\"role\":\"assistant\",\"content\":[{content}]}}}}\n")
    };
    let mut text = u("00", &format!("\"{PROMPT}\""));
    if with_tool {
        text += &a("05", "{\"type\":\"tool_use\",\"id\":\"t1\",\"name\":\"Bash\",\"input\":{\"command\":\"cargo fetch --offline\"}}");
        text += &u("06", "[{\"type\":\"tool_result\",\"tool_use_id\":\"t1\",\"content\":\"ok\",\"is_error\":false}]");
    }
    text += &a("07", "{\"type\":\"text\",\"text\":\"Use the vendored sources while the mirror is down.\"}");
    let path = s.with_file_name(format!("{sid}.jsonl"));
    std::fs::write(&path, text).unwrap();
    path
}

fn stop_with(sid: &str, transcript: &PathBuf) -> String {
    format!(
        "{{\"session_id\":\"{sid}\",\"hook_event_name\":\"Stop\",\"stop_hook_active\":false,\"transcript_path\":\"{}\"}}",
        // A Windows path is full of backslashes, which JSON must escape.
        transcript.display().to_string().replace(String::from(92 as char).as_str(), "\\\\")
    )
}

#[test]
fn settle_stays_silent_after_a_plain_answer_so_the_answer_is_the_last_word() {
    let s = store("settle-qa");
    bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("qa", PROMPT));
    let t = transcript(&s, "qa", false);
    let (code, out) = run(Some(&s), &["settle"], &stop_with("qa", &t));
    assert_eq!(code, 0);
    assert!(out.trim().is_empty(), "nothing to judge yet, so no reminder: {out}");
    // Silence records nothing, so once the session does something the reminder can still come.
    let t = transcript(&s, "qa", true);
    let (_, later) = run(Some(&s), &["settle"], &stop_with("qa", &t));
    assert!(later.contains("instinct hit"), "after a tool call the reminder comes: {later}");
}

#[test]
fn settle_reminds_when_a_tool_ran_after_the_lesson() {
    let s = store("settle-tool");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("tool", PROMPT));
    let t = transcript(&s, "tool", true);
    let (code, out) = run(Some(&s), &["settle"], &stop_with("tool", &t));
    assert_eq!(code, 0);
    assert!(out.contains(&format!("instinct hit {id}")), "{out}");
}

#[test]
fn settle_with_an_unreadable_transcript_asks_as_before() {
    let s = store("settle-notranscript");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("gone", PROMPT));
    let missing = s.with_file_name("missing.jsonl");
    let (code, out) = run(Some(&s), &["settle"], &stop_with("gone", &missing));
    assert_eq!(code, 0);
    assert!(out.contains(&format!("instinct hit {id}")), "{out}");
}

#[test]
fn the_question_about_a_lesson_rides_on_the_next_prompt_once() {
    let s = store("followup");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let (_, first) = run(Some(&s), &["prompt"], &prompt("f", PROMPT));
    assert!(first.contains(&id) && !first.contains("earlier in this session"), "not asked in the turn it arrives: {first}");
    let (code, next) = run(Some(&s), &["prompt"], &prompt("f", "that worked, thanks"));
    assert_eq!(code, 0);
    assert!(next.contains(&format!("instinct hit {id}")) && next.contains("earlier in this session"), "{next}");
    let (_, third) = run(Some(&s), &["prompt"], &prompt("f", "one more thing"));
    assert!(!third.contains("earlier in this session"), "asked once per session: {third}");
}

#[test]
fn no_question_once_the_lesson_has_a_verdict() {
    let s = store("followup-judged");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    run(Some(&s), &["prompt"], &prompt("j", PROMPT));
    run(Some(&s), &["hit", &id, "--note", "used it"], "");
    let (_, next) = run(Some(&s), &["prompt"], &prompt("j", "next question"));
    assert!(!next.contains("earlier in this session"), "{next}");
}

/// Start independent hook processes before giving any of them their input.
fn race(s: &PathBuf, jobs: Vec<(&str, String)>, shares: &[&str]) -> Vec<String> {
    let children: Vec<_> = jobs.into_iter().zip(shares.iter().cycle()).map(|((hook, input), share)| {
        let child = Command::new(bin()).args([hook, "--format", "text"])
            .env("INSTINCT_STORE", s).env("INSTINCT_EXPLORE", share)
            .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
        (child, input)
    }).collect();
    let mut running = Vec::new();
    for (mut child, input) in children {
        child.stdin.take().unwrap().write_all(input.as_bytes()).ok();
        running.push(child);
    }
    running.into_iter().map(|child| {
        let out = child.wait_with_output().unwrap();
        assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
        String::from_utf8(out.stdout).unwrap()
    }).collect()
}

const WRITERS: usize = 12;

/// A real retained history makes it likely that reads overlap, even on a small CI host.
fn history(s: &PathBuf, expired: bool) -> (PathBuf, String) {
    use std::time::{SystemTime, UNIX_EPOCH};
    let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
    let retained: String = (0..3000).map(|i| format!("{now}\tprior-{i}\tD\tin-prior\n")).collect();
    let path = PathBuf::from(format!("{}.sessions", s.display()));
    let old = if expired { "1000\texpired\tD\tin-expired\n" } else { "" };
    std::fs::write(&path, format!("{old}{retained}")).unwrap();
    (path, retained)
}

fn mixed_hooks() -> Vec<(&'static str, String)> {
    (0..WRITERS).map(|i| {
        if i % 2 == 0 { ("prompt", prompt("shared", PROMPT)) }
        else { ("guard", guard("shared", "cargo registry mirror outage")) }
    }).collect()
}

#[test]
fn concurrent_prompt_and_guard_deliver_once() {
    let s = store("race-delivery");
    bank(&s, TITLE, Some("qqqq wwww"));
    let (path, _) = history(&s, false);
    let answers = race(&s, mixed_hooks(), &["0"]);
    let records = std::fs::read_to_string(path).unwrap();
    let emitted = answers.iter().filter(|v| v.contains(TITLE)).count();
    let saved = records.lines().filter(|r| r.contains("\tshared\tD\t")).count();
    assert_eq!((emitted, saved), (1, 1));
}

#[test]
fn concurrent_prompt_and_guard_hold_once() {
    let s = store("race-hold");
    bank(&s, TITLE, Some("qqqq wwww"));
    let (path, _) = history(&s, false);
    assert!(race(&s, mixed_hooks(), &["1"]).iter().all(|v| v.trim().is_empty()));
    let records = std::fs::read_to_string(path).unwrap();
    assert_eq!(records.lines().filter(|r| r.contains("\tshared\tH\t")).count(), 1);
    assert!(!records.contains("\tshared\tD\t"));
}

#[test]
fn competing_hold_and_delivery_commit_one_experiment_arm() {
    let s = store("race-mixed");
    bank(&s, TITLE, Some("qqqq wwww"));
    let (path, _) = history(&s, false);
    let answers = race(&s, mixed_hooks(), &["0", "1"]);
    let records = std::fs::read_to_string(path).unwrap();
    let deliveries = records.lines().filter(|r| r.contains("\tshared\tD\t")).count();
    let holds = records.lines().filter(|r| r.contains("\tshared\tH\t")).count();
    assert_eq!(deliveries + holds, 1);
    assert_eq!(answers.iter().filter(|out| out.contains(TITLE)).count(), deliveries);
}

#[test]
fn concurrent_settle_and_prompt_emit_one_reminder() {
    let s = store("race-reminder");
    bank(&s, TITLE, Some("qqqq wwww"));
    let (path, _) = history(&s, false);
    assert!(race(&s, vec![("guard", guard("shared", "cargo registry mirror outage"))], &["0"])[0].contains(TITLE));
    let jobs = (0..WRITERS).map(|i| if i % 2 == 0 {
        ("settle", stop("shared"))
    } else {
        ("prompt", prompt("shared", "thanks for your help"))
    }).collect();
    let answers = race(&s, jobs, &["0"]);
    let records = std::fs::read_to_string(path).unwrap();
    let emitted = answers.iter().filter(|v| v.contains("instinct hit")).count();
    let saved = records.lines().filter(|r| r.contains("\tshared\tR\t")).count();
    assert_eq!((emitted, saved), (1, 1));
}

#[test]
fn concurrent_prune_retains_every_unexpired_delivery() {
    let s = store("race-prune");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let (path, retained) = history(&s, true);
    let jobs = (0..WRITERS).map(|i| ("guard", guard(&format!("writer-{i}"), "cargo registry mirror outage"))).collect();
    assert!(race(&s, jobs, &["0"]).iter().all(|v| v.contains(TITLE)));
    let records = std::fs::read_to_string(&path).unwrap();
    assert!(records.starts_with(&retained), "a retained record was lost or corrupted during prune");
    let mut actual: Vec<_> = records[retained.len()..].lines().map(|line| line.split_once('\t').unwrap().1.to_string()).collect();
    let mut expected: Vec<_> = (0..WRITERS).map(|i| format!("writer-{i}\tD\t{id}\tg")).collect();
    actual.sort();
    expected.sort();
    assert_eq!(actual, expected);
    #[cfg(unix)] {
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(std::fs::metadata(path).unwrap().permissions().mode() & 0o077, 0);
    }
}

#[test]
fn unavailable_lock_preserves_matching_advice_but_never_invents_experiment_or_reminder_records() {
    let s = store("race-unwritable");
    bank(&s, TITLE, Some("qqqq wwww"));
    let lock = PathBuf::from(format!("{}.sessions.lock", s.display()));
    let ledger = PathBuf::from(format!("{}.sessions", s.display()));
    std::fs::create_dir(&lock).unwrap();
    let hooks = || vec![("prompt", prompt("p", PROMPT)), ("guard", guard("g", PROMPT))];
    assert!(race(&s, hooks(), &["0"]).iter().all(|out| out.contains(TITLE)));
    assert!(race(&s, hooks(), &["1"]).iter().all(|out| out.trim().is_empty()));
    assert!(!ledger.exists());
    std::fs::remove_dir(&lock).unwrap();
    assert!(race(&s, hooks(), &["0"]).iter().all(|out| out.contains(TITLE)));
    let recorded = std::fs::read_to_string(&ledger).unwrap();
    std::fs::remove_file(&lock).unwrap();
    std::fs::create_dir(&lock).unwrap();
    // Existing delivery still excludes a repeat. Failed reminder reservations stay silent.
    assert!(race(&s, hooks(), &["0"]).iter().all(|out| out.trim().is_empty()));
    assert!(race(&s, vec![("settle", stop("p"))], &["0"])[0].trim().is_empty());
    assert_eq!(std::fs::read_to_string(&ledger).unwrap(), recorded);
    std::fs::remove_dir(&lock).unwrap();
    assert!(race(&s, vec![("settle", stop("p"))], &["0"])[0].contains("instinct hit"));
}

#[test]
fn expired_session_rows_and_an_interrupted_prune_allow_a_new_delivery() {
    let s = store("expired-reused-session");
    let (id, _) = bank(&s, TITLE, Some("qqqq wwww"));
    let ledger = PathBuf::from(format!("{}.sessions", s.display()));
    let tmp = ledger.with_extension("sessions.tmp");
    std::fs::write(&ledger, format!("1000\treused\tD\t{id}\tg\n1000\treused\tR\t-\n1000\tother\tH\t{id}\tp\n")).unwrap();
    std::fs::write(&tmp, "orphaned incomplete prune").unwrap();
    assert!(race(&s, vec![("settle", stop("reused"))], &["0"])[0].trim().is_empty());
    assert!(race(&s, vec![("prompt", prompt("reused", PROMPT))], &["0"])[0].contains(TITLE));
    let live = std::fs::read_to_string(&ledger).unwrap();
    assert_eq!(live.lines().count(), 1);
    assert!(live.trim_end().ends_with(&format!("\treused\tD\t{id}\tp")));
    assert!(!tmp.exists());
    assert!(race(&s, vec![("settle", stop("reused"))], &["0"])[0].contains("instinct hit"));
}

#[cfg(unix)]
#[test]
fn a_read_only_ledger_keeps_the_guard_advisory_available() {
    use std::os::unix::fs::PermissionsExt;
    let s = store("readonly-ledger");
    bank(&s, TITLE, Some("qqqq wwww"));
    let ledger = PathBuf::from(format!("{}.sessions", s.display()));
    assert!(race(&s, vec![("guard", guard("existing", PROMPT))], &["0"])[0].contains(TITLE));
    let before = std::fs::read(&ledger).unwrap();
    std::fs::set_permissions(&ledger, std::fs::Permissions::from_mode(0o400)).unwrap();
    // Privileged test users can still write mode 0400. The blocked-lock test covers that environment.
    if std::fs::OpenOptions::new().append(true).open(&ledger).is_err() {
        assert!(race(&s, vec![("guard", guard("fresh", PROMPT))], &["0"])[0].contains(TITLE));
        assert!(race(&s, vec![("guard", guard("held", PROMPT))], &["1"])[0].trim().is_empty());
        assert!(race(&s, vec![("guard", guard("existing", PROMPT))], &["0"])[0].trim().is_empty());
        assert!(race(&s, vec![("settle", stop("existing"))], &["0"])[0].trim().is_empty());
        assert_eq!(std::fs::read(&ledger).unwrap(), before);
    }
    std::fs::set_permissions(&ledger, std::fs::Permissions::from_mode(0o600)).unwrap();
}

/// 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)
}

#[test]
fn guide_examples_are_read_only_and_cli_matches_mcp() {
    let store = store("guide-examples");
    let modes = ["start", "options", "challenge", "explain", "rehearse", "transfer", "verify", "retry", "handoff", "debrief"];
    let examples = ["shared-document", "client-update", "spreadsheet", "event-booking", "website",
                    "presentation", "coding", "research", "design", "podcast"];
    let mut requests = String::new();
    let mut packets = Vec::new();
    for example in examples {
        for mode in modes {
            let (code, packet) = run(Some(&store), &["guide", mode, "--example", example, "--json"], "");
            assert_eq!(code, 0, "{mode}/{example}");
            assert!(packet.contains(r#""source":"example""#));
            let id = packets.len();
            requests.push_str(&format!(r#"{{"jsonrpc":"2.0","id":{id},"method":"tools/call","params":{{"name":"instinct_guide","arguments":{{"mode":"{mode}","example":"{example}"}}}}}}"#));
            requests.push('\n');
            packets.push(packet.trim_end().replace('\\', "\\\\").replace('"', "\\\""));
        }
    }
    let (code, output) = run(Some(&store), &["mcp"], &requests);
    assert_eq!(code, 0);
    assert_eq!(output.lines().count(), packets.len());
    for (response, packet) in output.lines().zip(packets) {
        assert!(response.contains(&packet) && response.contains(r#""isError":false"#), "{response}");
    }
    assert!(!store.exists(), "using examples created a real bank");
    std::fs::write(&store, b"not a valid bank").unwrap();
    let (code, review) = run(Some(&store), &["guide","review","--example","spreadsheet","--json"], "");
    assert_eq!(code,0);
    assert!(review.contains(r#""current_comparison":{"status":"mismatch","expected":"00501","observed":"501"}"#));
    assert_eq!(std::fs::read(&store).unwrap(), b"not a valid bank");
    for recipe in ["prepare","investigate","review"] {
        let (code, report) = run(Some(&store), &["guide",recipe,"--example","podcast","--json"], "");
        assert_eq!(code,0);
        assert_eq!(report.matches(r#""source":"example""#).count(),3);
    }
    std::fs::remove_dir_all(store.parent().unwrap()).unwrap();
}

#[test]
fn guide_live_decisions_change_with_the_brief_and_keep_feedback_explicit() {
    let store = store("guide-live");
    let do_run = |args: &[&str]| run(Some(&store), args, "");
    let task = "draft weekly client update";
    let (code, saved) = do_run(&["bank","--project","studio","--title","Weekly client update","--when",task,
        "--found","The client approved the short draft.","--how","Lead with the next decision.",
        "--evidence","Approved draft 7","--reconsider","A full audit needs an incident timeline."]);
    assert_eq!(code, 0);
    let id = saved.split_whitespace().nth(1).unwrap();
    for event in ["approved-8","approved-9"] {
        assert_eq!(do_run(&["hit",id,"--outcome-id",event]).0, 0);
    }
    let before = do_run(&["export"]);
    let guide = |mode: &str, extra: &[&str]| {
        let mut args = vec!["guide", mode,"--q",task,"--project","studio","--json"];
        args.extend_from_slice(extra);
        let (code, out) = do_run(&args);
        assert_eq!(code,0,"{args:?}");
        out
    };
    assert!(guide("start",&[]).contains(r#""proven":true"#));
    assert!(guide("challenge",&[]).contains("incident timeline"));
    assert!(guide("handoff",&[]).contains(r#""project":"studio""#));
    assert!(guide("explain",&[]).contains("Approved draft 7"));
    assert!(guide("rehearse",&["--changed","prepare a pottery glaze"]).contains(r#""retained":[],"dropped":[{"id":"#));
    assert!(guide("transfer",&["--changed","prepare a pottery glaze","--prediction","Glaze covers the tile."]).contains(r#""status":"hypothesis""#));
    assert!(guide("verify",&["--expected","00501"]).contains("awaiting_observation"));
    assert!(guide("debrief",&["--method","Reopen the CSV","--expected","00501","--observed","501"]).contains(r#""lesson_draft":{"when":"#));
    assert!(guide("retry",&["--correction","That's still wrong."]).contains(id));
    let recipe = guide("run",&["--steps","challenge,start,handoff"]);
    assert!(recipe.find(r#""mode":"challenge""#).unwrap() < recipe.find(r#""mode":"start""#).unwrap());
    assert_eq!(recipe.matches(r#""source":"live""#).count(),3);
    assert!(do_run(&["guide","start","--q",task,"--project","other","--json"]).1.contains("no_lesson"));
    for args in [
        vec!["guide","bogus","--q",task],
        vec!["guide","rehearse","--q",task,"--changed",task],
        vec!["guide","run","--steps","start,start","--q",task],
        vec!["guide","start","--steps","verify","--q",task],
        vec!["guide","start","--example","website","--q",task],
        vec!["guide","verify","--expected","-","--observed","-","--q",task],
    ] { assert_eq!(do_run(&args).0,2,"{args:?}"); }
    assert_eq!(do_run(&["export"]),before);
    std::fs::remove_dir_all(store.parent().unwrap()).unwrap();
}