instinct-cli 0.3.7

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
//! 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,
}

/// 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,
        _ => 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::Delivered | Kind::Held => !matches!(r.kind, Kind::Reminded | Kind::Indexed | Kind::Corrected) && 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",
    };
    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)
}

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\tX\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);
    }
}