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")
}
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())
}
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}");
assert!(second.contains(&format!("instinct hit {id}")), "{second}");
let (_, other) = run(Some(&s), &["prompt"], &prompt("b", PROMPT));
assert!(other.contains(&id), "{other}");
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"));
let (code, out) = run(Some(&s), &["settle"], &stop("a"));
assert_eq!((code, out.trim()), (0, ""));
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, ""));
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, ""));
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, ""));
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}");
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}");
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}");
bank(&s, "The fix", None);
let (_, none) = run(Some(&s), &["recall", "--q", "fix"], "");
assert!(!none.contains("TAGS:"), "{none}");
}
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\":\"{}\"}}",
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}");
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}");
}
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;
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();
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();
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();
}
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();
}