//! Per-session memory for the hooks: `<store>.sessions`, append-only, one tab-separated line per event:
//! `unix_ts session_id D|H|R|C lesson_id [p|g]`. `D` = a lesson was delivered in that session, `H` = it was
//! withheld by the explore arm (`INSTINCT_EXPLORE`), `R` = the settle reminder was shown, `C` = the agent was
//! asked once to save a user correction (lesson id `-`). The optional last
//! field says which hook acted: `p` prompt, `g` guard. Counts and ids only, never text. Lines older than
//! 35 days are pruned on write.
//! If the ledger is unwritable, matching advice remains available and feedback reminders stay silent.
use super::*;
/// 35 days, so `instinct eval --since 30d` and `instinct outcomes` can see which lessons were delivered.
const KEEP_SECS: u64 = 35 * 86_400;
/// Every delivery on record: (unix_ts, session_id, lesson_id), oldest first. Read only. Withheld (`H`)
/// lines are not deliveries. Built on [`records`], the one parser of this file.
pub fn deliveries(store: &Path) -> Vec<(u64, String, String)> {
records(store)
.into_iter()
.filter(|r| r.kind == Kind::Delivered)
.map(|r| (r.ts, r.session, r.lesson))
.collect()
}
fn file(store: &Path) -> PathBuf {
let mut p = store.as_os_str().to_owned();
p.push(".sessions");
PathBuf::from(p)
}
/// Tabs and newlines would break the line format; an empty id means "no session memory".
pub fn clean(id: &str) -> Option<String> {
let id: String = id.chars().filter(|c| !c.is_control()).collect();
let id = id.trim();
(!id.is_empty() && id.len() <= 200).then(|| id.to_owned())
}
#[derive(Debug, Default, PartialEq)]
pub struct Seen {
/// Delivered lesson ids with the first delivery time, in delivery order, without repeats.
pub delivered: Vec<(String, u64)>,
/// Lesson ids the explore arm withheld in this session, without repeats.
pub held: Vec<String>,
pub reminded: bool,
pub corrected: bool,
}
/// Which hook acted on a lesson.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
Prompt,
Guard,
/// Written before the source field existed.
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Delivered,
Held,
Reminded,
/// The lesson index (`INSTINCT_INDEX=1`) was shown in that session; the lesson field is `-`.
Indexed,
/// The prompt hook asked the agent once to save a user correction.
Corrected,
/// Retry tripwire: a failed Bash command; the lesson field is `<form hash>:<exit status>`.
Failed,
/// Retry tripwire: the warning for a form was given; the lesson field is the form hash.
RetryWarned,
/// Verify-before-done gate: the Stop hook sent a final message back; the lesson field is the correction key.
DoneBlocked,
}
/// One line of `<store>.sessions`.
#[derive(Debug, Clone, PartialEq)]
pub struct Record {
pub ts: u64,
pub session: String,
pub kind: Kind,
pub lesson: String,
pub source: Source,
}
fn parse_line(line: &str) -> Option<Record> {
let f: Vec<&str> = line.split('\t').collect();
if !(4..=5).contains(&f.len()) {
return None;
}
let kind = match f[2] {
"D" => Kind::Delivered,
"H" => Kind::Held,
"R" => Kind::Reminded,
"I" => Kind::Indexed,
"C" => Kind::Corrected,
"X" => Kind::Failed,
"W" => Kind::RetryWarned,
"B" => Kind::DoneBlocked,
_ => return None,
};
let source = match f.get(4).copied() {
Some("p") => Source::Prompt,
Some("g") => Source::Guard,
_ => Source::Unknown,
};
Some(Record { ts: f[0].parse().unwrap_or(0), session: f[1].to_owned(), kind, lesson: f[3].to_owned(), source })
}
/// Every parsable line of `<store>.sessions`, in file order. Garbled lines are skipped.
pub fn records(store: &Path) -> Vec<Record> {
std::fs::read_to_string(file(store)).unwrap_or_default().lines().filter_map(parse_line).collect()
}
pub fn seen(store: &Path, sid: &str) -> Seen {
let mut out = Seen::default();
let text = fs::read_to_string(file(store)).unwrap_or_default();
let now = now_secs();
for r in text.lines().filter(|line| line.split('\t').nth(1) == Some(sid)).filter_map(parse_line)
.filter(|r| now.saturating_sub(r.ts) < KEEP_SECS) {
match r.kind {
Kind::Delivered if !out.delivered.iter().any(|(i, _)| *i == r.lesson) => {
out.delivered.push((r.lesson, r.ts))
}
Kind::Held if !out.held.contains(&r.lesson) => out.held.push(r.lesson),
Kind::Reminded => out.reminded = true,
Kind::Corrected => out.corrected = true,
_ => {}
}
}
out
}
impl Seen {
/// Both delivered and withheld lessons are excluded from the next lookup.
pub fn lesson_ids(&self) -> Vec<String> {
self.delivered.iter().map(|(id, _)| id).chain(&self.held).cloned().collect()
}
}
fn live(line: &str, now: u64) -> bool {
line.split_once('\t')
.and_then(|(ts, _)| ts.parse::<u64>().ok())
.is_some_and(|ts| now.saturating_sub(ts) < KEEP_SECS)
}
/// Reserve one hook action. The sidecar lock stays on the same inode when prune replaces the ledger.
/// Ranking, transcript parsing and reading the outcome journal happen outside this critical section.
fn record_once(store: &Path, sid: &str, kind: Kind, id: &str, source: Source) -> std::io::Result<bool> {
let path = file(store);
let _lock = journal::identity_lock(&path).map_err(std::io::Error::other)?;
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e),
};
let now = now_secs();
let mut needs_prune = false;
let mut has_delivery = false;
for line in text.lines() {
if !live(line, now) {
needs_prune = true;
continue;
}
if line.split('\t').nth(1) != Some(sid) {
continue;
}
let Some(r) = parse_line(line) else { continue };
has_delivery |= r.kind == Kind::Delivered;
let taken = match kind {
Kind::Reminded => r.kind == Kind::Reminded,
Kind::Indexed => r.kind == Kind::Indexed,
Kind::Corrected => r.kind == Kind::Corrected,
Kind::Failed => false,
Kind::RetryWarned | Kind::DoneBlocked => r.kind == kind && r.lesson == id,
Kind::Delivered | Kind::Held => matches!(r.kind, Kind::Delivered | Kind::Held) && r.lesson == id,
};
if taken {
return Ok(false);
}
}
if kind == Kind::Reminded && !has_delivery {
return Ok(false);
}
let code = match kind {
Kind::Delivered => "D",
Kind::Held => "H",
Kind::Reminded => "R",
Kind::Indexed => "I",
Kind::Corrected => "C",
Kind::Failed => "X",
Kind::RetryWarned => "W",
Kind::DoneBlocked => "B",
};
let tag = match source {
Source::Prompt => "\tp",
Source::Guard => "\tg",
Source::Unknown => "",
};
let line = format!("{now}\t{sid}\t{code}\t{id}{tag}\n");
persist(&path, &text, line, now, needs_prune)?;
Ok(true)
}
fn persist(path: &Path, text: &str, line: String, now: u64, needs_prune: bool) -> std::io::Result<()> {
if needs_prune {
let mut kept = String::new();
for row in text.lines().filter(|row| live(row, now)) {
kept.push_str(row);
kept.push('\n');
}
kept.push_str(&line);
let tmp = path.with_extension("sessions.tmp");
// This name is reserved by the lock. Discard leftovers from interrupted prunes before creating it.
let _ = fs::remove_file(&tmp);
let written = journal::private_options().write(true).create_new(true).open(&tmp)
.and_then(|mut f| f.write_all(kept.as_bytes()))
.and_then(|_| fs::rename(&tmp, path));
if written.is_ok() {
return Ok(());
}
let _ = fs::remove_file(&tmp);
// A read-only directory can still hold a writable ledger. Append under the same lock and retry
// compaction on a later write; old rows are already ignored when reading a session.
}
let row = if !text.is_empty() && !text.ends_with('\n') { format!("\n{line}") } else { line };
let mut out = journal::private_options().append(true).create(true).open(path)?;
if let Err(e) = out.write_all(row.as_bytes()) {
// A quota can stop a short write after its ID but before its newline. Such a partial row
// must not look like a delivered lesson to the next reader.
let _ = out.set_len(text.len() as u64);
return Err(e);
}
Ok(())
}
/// A hold competes for the same (session, lesson) as a delivery, across both hooks.
pub fn claim_lesson(store: &Path, sid: &str, id: &str, source: Source) -> bool {
let held = withheld(sid, id, explore_share());
let kind = if held { Kind::Held } else { Kind::Delivered };
let reserved = record_once(store, sid, kind, id, source);
// An I/O error cannot revoke a useful warning. Dedup against any readable history, but never
// manufacture a hold, a reminder, or an experiment record when the ledger cannot be written.
!held && reserved.unwrap_or_else(|_| !seen(store, sid).lesson_ids().iter().any(|old| old == id))
}
/// True once per session: the first caller records the index delivery, later callers (and a session id
/// that cannot be recorded) get false, so the index is never repeated and never shown without a record.
pub fn claim_index(store: &Path, sid: &str) -> bool {
record_once(store, sid, Kind::Indexed, "-", Source::Prompt).unwrap_or(false)
}
/// Store only hashes and the exit status. Older rows have no missing-input witness.
pub fn record_failure(store: &Path, sid: &str, form: &str, status: i32, missing: Option<String>) {
let mut entry = format!("{form}:{status}");
if let Some(hash) = missing {
entry.push_str(":missing=");
entry.push_str(&hash);
}
let _ = record_once(store, sid, Kind::Failed, &entry, Source::Unknown);
}
pub fn recent_failures(store: &Path, sid: &str, form: &str, limit: usize) -> Vec<String> {
let prefix = format!("{form}:");
let text = fs::read_to_string(file(store)).unwrap_or_default();
text.lines().rev()
.filter(|l| l.contains(&prefix) && l.split('\t').nth(1) == Some(sid))
.filter_map(parse_line)
.filter(|r| r.kind == Kind::Failed && r.lesson.starts_with(&prefix))
.take(limit)
.map(|r| r.lesson)
.collect()
}
/// True once per (session, form): the caller that records the warning may show it.
pub fn claim_warning(store: &Path, sid: &str, form: &str) -> bool {
record_once(store, sid, Kind::RetryWarned, form, Source::Guard).unwrap_or(false)
}
/// True once per (session, correction): the caller that records the block may send the message back.
pub fn claim_block(store: &Path, sid: &str, key: &str) -> bool {
record_once(store, sid, Kind::DoneBlocked, key, Source::Unknown).unwrap_or(false)
}
fn claim_reminder(store: &Path, sid: &str) -> bool {
record_once(store, sid, Kind::Reminded, "-", Source::Unknown).unwrap_or(false)
}
/// `INSTINCT_CORRECTIONS=0` turns the correction line off.
pub fn corrections_on() -> bool {
std::env::var("INSTINCT_CORRECTIONS").map_or(true, |v| v.trim() != "0")
}
/// Offer to bank a reusable correction or an explicit project preference once per session.
pub fn correction_line(store: &Path, sid: &str, state: &Seen, prompt: &str, project: &str) -> Option<String> {
if state.corrected || !corrections_on() {
return None;
}
let preference = !project.is_empty() && explicit_project_preference(prompt);
if !preference && !corrections::correction(prompt) {
return None;
}
if !record_once(store, sid, Kind::Corrected, "-", Source::Prompt).unwrap_or(false) {
return None;
}
Some(if preference {
let project = shell_quote(project);
format!("Instinct: if the user is setting a continuing preference here, save it with `instinct bank --project {project} --title 'TITLE' --when 'TASK' --how 'THEIR WORDS' --found 'user set a project default' --evidence 'current user request'`. Use the returned ID in `instinct default ID --project {project} --instruction 'THEIR WORDS' --source-ref 'current user request'`. Keep the task and exceptions specific. A quoted example or a one-time request sets no default.")
} else {
correction_text(project)
})
}
/// A narrow positive cue for a project rule given before the first mistake.
fn explicit_project_preference(prompt: &str) -> bool {
if prompt.len() > 600 || prompt.contains(['?', '\n', '`']) {
return false;
}
let text = prompt.trim().to_ascii_lowercase();
let Some(rest) = ["for this project", "in this project"].iter().find_map(|p| text.strip_prefix(p)) else {
return false;
};
let Some(rest) = rest.strip_prefix(", ").or_else(|| rest.strip_prefix(' ')) else { return false };
let Some(rule) = rest.strip_prefix("always ").or_else(|| rest.strip_prefix("from now on, ")) else { return false };
let Some((verb, object)) = rule.split_once(' ') else { return false };
!object.trim().is_empty() && matches!(verb, "use" | "lead" | "start" | "write" | "include" | "show" | "put" | "format" | "keep")
}
/// `'` closed, escaped, reopened: safe inside a single-quoted shell word.
fn shell_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', "'\\''"))
}
/// The line the agent sees. `project` is the scope the hook matches lessons against (the event's `cwd`);
/// empty means the event had none, and the template then carries no `--project`.
pub fn correction_text(project: &str) -> String {
let (flag, keep) = if project.is_empty() {
(String::new(), "")
} else {
(
format!(" --project {}", shell_quote(project)),
" Keep --project when the rule is about this project (\"we use pnpm\", \"tests live in tests/\"); drop it only when the rule holds in every project (\"never hardcode API keys\").",
)
};
let default = if project.is_empty() {
String::new()
} else {
format!(" If the user explicitly sets a continuing default for this project, use the returned ID in `instinct default ID{flag} --instruction 'THEIR WORDS' --source-ref 'user correction in this session'`. A one-time edit or approval gives no continuing instruction.")
};
format!(
"Instinct: this message may correct something you did. If it states a rule that applies beyond this one task, save it by running `instinct bank --title '…' --when 'WHEN' --found 'user correction' --how 'HOW' --evidence 'user correction in this session'{flag}` as a command on its own, where WHEN is the situation it applies to and HOW is the user's rule, in their words (the instinct CLI is installed; it wrote this line).{keep}{default} If it is not a reusable rule, ignore this line and say nothing about it."
)
}
#[cfg(test)]
mod correction_text_tests {
use super::*;
#[test]
fn the_template_carries_the_quoted_project_only_when_there_is_one() {
assert!(correction_text("/home/u/app").contains("'user correction in this session' --project '/home/u/app'`"));
assert!(!correction_text("").contains("--project"));
}
#[test]
fn a_single_quote_in_the_path_is_escaped_for_the_shell() {
assert_eq!(shell_quote("/home/o'neil/app"), "'/home/o'\\''neil/app'");
assert!(correction_text("/home/o'neil/app").contains("--project '/home/o'\\''neil/app'`"));
}
}
/// For the prompt hook: if a lesson delivered earlier in this session still has no hit or miss and no
/// reminder has been shown, record the reminder and return the line to add to this prompt's context.
pub fn followup(store: &Path, sid: &str, state: &Seen) -> Option<String> {
if state.reminded || state.delivered.is_empty() {
return None;
}
let owed = unsettled(store, &state.delivered);
if owed.is_empty() {
return None;
}
claim_reminder(store, sid).then(|| followup_text(&owed))
}
pub fn followup_text(ids: &[String]) -> String {
let shown: Vec<&str> = ids.iter().take(3).map(String::as_str).collect();
let (what, hit, miss) = match shown[..] {
[one] => (format!("lesson {one}"), format!("instinct hit {one} --note '…'"), format!("instinct miss {one} --note '…'")),
_ => (
format!("lessons {}", shown.join(", ")),
"instinct hit ID --note '…'".to_owned(),
"instinct miss ID --note '…'".to_owned(),
),
};
format!(
"Instinct: earlier in this session you were given {what}. If this message shows whether it worked, run `{hit}` or `{miss}` as a command on its own (the instinct CLI is installed; it wrote this line). If it does not, ignore this line and say nothing about it."
)
}
// ---------------------------------------------------------------- explore arm
/// The share of deliveries to withhold, from `INSTINCT_EXPLORE` (for example `0.1`). Unset, empty, not a
/// number, or not above zero means off; anything above 1 means 1.
pub fn explore_share() -> f64 {
std::env::var("INSTINCT_EXPLORE")
.ok()
.and_then(|v| v.trim().parse::<f64>().ok())
.filter(|s| s.is_finite() && *s > 0.0)
.map_or(0.0, |s| s.min(1.0))
}
/// Position of (session, lesson) on [0, 1): FNV-1a over a fixed seed, session id and lesson id, then a
/// splitmix finalizer so the top bits are uniform. Same inputs, same number, on every machine and run.
pub fn explore_draw(sid: &str, lesson: &str) -> f64 {
let mut h: u64 = 0xcbf29ce484222325;
let seed = b"instinct-explore-v1";
for b in seed.iter().chain(&[0u8]).chain(sid.as_bytes()).chain(&[0u8]).chain(lesson.as_bytes()) {
h ^= *b as u64;
h = h.wrapping_mul(0x100000001b3);
}
h ^= h >> 30;
h = h.wrapping_mul(0xbf58476d1ce4e5b9);
h ^= h >> 27;
h = h.wrapping_mul(0x94d049bb133111eb);
h ^= h >> 31;
(h >> 11) as f64 / (1u64 << 53) as f64
}
/// True when the explore arm withholds `lesson` in session `sid`. Stable: it depends on nothing else.
pub fn withheld(sid: &str, lesson: &str, share: f64) -> bool {
share > 0.0 && explore_draw(sid, lesson) < share
}
/// Ids among `delivered` that have no hit or miss line in the journal at or after their delivery time.
pub fn unsettled(store: &Path, delivered: &[(String, u64)]) -> Vec<String> {
let journal = journal::read(&store.to_path_buf()).unwrap_or_default();
let marks: Vec<(String, u64)> = journal
.lines()
.filter(|l| l.contains("\"hit\"") || l.contains("\"miss\""))
.filter_map(|l| parse_json(l).ok())
.filter(|v| matches!(v.get("kind").and_then(Json::as_str), Some("hit" | "miss")))
.filter_map(|v| {
Some((
v.get("id")?.as_str()?.to_owned(),
v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64,
))
})
.collect();
delivered
.iter()
.filter(|(id, ts)| !marks.iter().any(|(m, t)| m == id && *t >= *ts))
.map(|(id, _)| id.clone())
.collect()
}
pub enum Format {
/// Claude Code: `hookSpecificOutput.additionalContext` on Stop.
Claude,
/// Codex: `{"decision":"block","reason":...}` (Stop continues once with the reason as a prompt).
Codex,
Text,
}
pub fn reminder(ids: &[String]) -> String {
let shown: Vec<&str> = ids.iter().take(3).map(String::as_str).collect();
if let [one] = shown[..] {
format!(
"You used lesson {one} this session. If it helped, run `instinct hit {one} --note '…'`; if it misled you, `instinct miss {one} --note '…'`."
)
} else {
format!(
"You used lessons {} this session. For each one, if it helped, run `instinct hit ID --note '…'`; if it misled you, `instinct miss ID --note '…'`.",
shown.join(", ")
)
}
}
pub fn render(text: &str, format: &Format) -> String {
match format {
Format::Claude => format!(
"{{\"hookSpecificOutput\":{{\"hookEventName\":\"Stop\",\"additionalContext\":\"{}\"}}}}",
escape_json(text)
),
Format::Codex => format!("{{\"decision\":\"block\",\"reason\":\"{}\"}}", escape_json(text)),
Format::Text => text.to_owned(),
}
}
/// True when something happened after a delivery at `since` (unix seconds) that shows whether the lesson
/// worked: a tool call, or a user prompt after the one that brought the lesson. The delivering prompt can be
/// stamped a few seconds either side of the hook, so prompts from five seconds before count, and two are needed.
pub fn outcome_observable(t: &super::outcomes::Transcript, since: u64) -> bool {
use super::outcomes::Ev;
let after = |ts: &u64| *ts >= since.saturating_sub(5);
let tools = t.evs.iter().any(|(ts, e)| *ts >= since && matches!(e, Ev::Tool { .. }));
let prompts = t.evs.iter().filter(|(ts, e)| after(ts) && matches!(e, Ev::Prompt(_))).count();
tools || prompts >= 2
}
/// `instinct settle`: the Stop hook. Never returns an error, never exits non-zero, silent unless a lesson
/// delivered in this session still has no hit or miss. Reminds at most once per session.
pub fn settle(a: &Args) {
let mut input = String::new();
if std::io::stdin().take(1 << 20).read_to_string(&mut input).is_err() {
return;
}
let Ok(store) = store_path(a) else { return };
let Ok(event) = parse_json(&input) else { return };
if matches!(event.get("stop_hook_active"), Some(Json::Bool(true))) {
return;
}
let Some(sid) = event.get("session_id").and_then(Json::as_str).and_then(clean) else { return };
let state = seen(&store, &sid);
if state.reminded || state.delivered.is_empty() {
return;
}
let owed = unsettled(&store, &state.delivered);
if owed.is_empty() {
return;
}
// Ask only when the agent can know the answer. A Stop hook that prints anything makes the agent take
// another turn, so asking after a plain question and answer replaces the answer with talk about lessons.
// With a readable transcript, ask only if a tool ran or the user wrote again after the first owed
// delivery. Without one, ask as before. Staying silent records nothing, so a later Stop can still ask.
if let Some(path) = event.get("transcript_path").and_then(Json::as_str) {
if let Some(t) = super::outcomes::load_transcript(Path::new(path), &sid) {
let since = state
.delivered
.iter()
.filter(|(id, _)| owed.contains(id))
.map(|(_, ts)| *ts)
.min()
.unwrap_or(0);
if !outcome_observable(&t, since) {
return;
}
}
}
let format = match a.opt("format") {
Some("codex") => Format::Codex,
Some("text") => Format::Text,
_ => Format::Claude,
};
if claim_reminder(&store, &sid) {
println!("{}", render(&reminder(&owed), &format));
}
}
#[cfg(test)]
mod explore_tests {
use super::*;
#[test]
fn the_draw_is_a_pure_function_of_session_and_lesson() {
assert_eq!(explore_draw("s1", "in-a"), explore_draw("s1", "in-a"));
assert_ne!(explore_draw("s1", "in-a"), explore_draw("s2", "in-a"));
assert_ne!(explore_draw("s1", "in-a"), explore_draw("s1", "in-b"));
let d = explore_draw("session-1", "in-abc");
assert!((0.0..1.0).contains(&d));
}
#[test]
fn withholding_is_monotone_in_the_share_and_hits_it_on_average() {
assert!(!withheld("s", "l", 0.0));
assert!(withheld("s", "l", 1.0));
for i in 0..200 {
let sid = format!("sess-{i}");
// withheld at a small share implies withheld at a larger one
if withheld(&sid, "in-x", 0.1) {
assert!(withheld(&sid, "in-x", 0.3));
}
}
for share in [0.1, 0.5] {
let n = 4000;
let k = (0..n).filter(|i| withheld(&format!("sess-{i}"), "in-x", share)).count();
let got = k as f64 / n as f64;
assert!((got - share).abs() < 0.03, "share {share}: got {got}");
}
}
#[test]
fn old_four_field_lines_still_read_and_new_ones_carry_the_source() {
let r = parse_line("100\tsid\tD\tin-1").unwrap();
assert_eq!((r.kind, r.source), (Kind::Delivered, Source::Unknown));
let r = parse_line("100\tsid\tH\tin-1\tg").unwrap();
assert_eq!((r.kind, r.source), (Kind::Held, Source::Guard));
assert!(parse_line("100\tsid\tZ\tin-1").is_none());
assert!(parse_line("garbage").is_none());
}
#[test]
fn deliveries_and_records_share_one_parser_and_held_lines_are_not_deliveries() {
let dir = std::env::temp_dir().join(format!("instinct-session-unit-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let store = dir.join("bank.hxdb");
let c = now_secs();
let (a, b) = (c - 40, c - 20);
let text = format!("{a}\ta\tD\tin-1\tp\n{a}\ta\tH\tin-2\tp\n{b}\tb\tD\tin-1\n{b}\tb\tR\t-\nbroken line\n{c}\tc\tD\tin-3\tg\n");
std::fs::write(file(&store), text).unwrap();
assert_eq!(records(&store).len(), 5, "garbled lines are skipped");
assert_eq!(
deliveries(&store),
vec![(a, "a".into(), "in-1".into()), (b, "b".into(), "in-1".into()), (c, "c".into(), "in-3".into())]
);
let state = seen(&store, "a");
assert_eq!(state.delivered, vec![("in-1".to_string(), a)]);
assert_eq!(state.held, vec!["in-2".to_string()]);
assert_eq!(state.lesson_ids(), vec!["in-1".to_string(), "in-2".to_string()]);
assert!(seen(&store, "b").reminded);
}
}