second-brain-cli 0.13.1

Memory layer for AI coding agents: ingest, recall, and sync across machines
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
use anyhow::{Context, Result};

/// Per-call excerpt cap: conservative against any plausible deployed model's
/// context window (the default `gemma-4-E4B-it-Q4_K_M`, or the configured
/// `context_budget_tokens`, whichever is smaller), so an oversized
/// conversation windows into several calls rather than risking truncation
/// mid-prompt.
const MAX_GROUP_CHARS: usize = 6000;

/// One LLM call's worth of work: a run of same-conversation fragments, kept
/// together so the model sees the conversation instead of an isolated turn.
struct ConsolidationUnit {
    raw_ids: Vec<String>,
    source_id: String,
    project_path: Option<String>,
    fragments: Vec<String>,
}

/// Groups already-ordered (by source_id, created_at) fragments into
/// contiguous same-source_id runs, then splits any run whose combined text
/// would exceed `MAX_GROUP_CHARS` into sequential windows. A batch cut off
/// mid-conversation by `limit` drops its trailing group, since the rest of
/// that conversation arrives complete on the next fetch; the sole exception
/// is a batch containing only that one group, where dropping it would stall
/// the pipeline entirely.
fn group_into_units(memories: &[serde_json::Value], limit: usize) -> Vec<ConsolidationUnit> {
    let mut groups: Vec<Vec<&serde_json::Value>> = Vec::new();
    for m in memories {
        let sid = m["source_id"].as_str().unwrap_or("");
        match groups.last_mut() {
            Some(last) if last.last().unwrap()["source_id"].as_str().unwrap_or("") == sid => {
                last.push(m);
            }
            _ => groups.push(vec![m]),
        }
    }

    if memories.len() == limit && groups.len() > 1 {
        groups.pop();
    }

    let mut units = Vec::new();
    for group in groups {
        let source_id = group[0]["source_id"].as_str().unwrap_or("").to_string();
        let project_path = group_project_path(&group);

        let mut window_ids = Vec::new();
        let mut window_fragments = Vec::new();
        let mut window_len = 0usize;
        for m in &group {
            let content = m["content"].as_str().unwrap_or("").to_string();
            if !window_fragments.is_empty() && window_len + content.len() > MAX_GROUP_CHARS {
                units.push(ConsolidationUnit {
                    raw_ids: std::mem::take(&mut window_ids),
                    source_id: source_id.clone(),
                    project_path: project_path.clone(),
                    fragments: std::mem::take(&mut window_fragments),
                });
                window_len = 0;
            }
            window_len += content.len();
            window_ids.push(m["id"].as_str().unwrap_or("").to_string());
            window_fragments.push(content);
        }
        if !window_fragments.is_empty() {
            units.push(ConsolidationUnit {
                raw_ids: window_ids,
                source_id,
                project_path,
                fragments: window_fragments,
            });
        }
    }
    units
}

/// The group's majority project_path, ties broken by whichever value was
/// seen first. `None` when no fragment in the group carries one.
fn group_project_path(group: &[&serde_json::Value]) -> Option<String> {
    let mut order: Vec<String> = Vec::new();
    let mut counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    for m in group {
        if let Some(p) = m["project_path"].as_str() {
            if !counts.contains_key(p) {
                order.push(p.to_string());
            }
            *counts.entry(p.to_string()).or_insert(0) += 1;
        }
    }
    let mut best: Option<(String, usize)> = None;
    for p in order {
        let c = counts[&p];
        if best.as_ref().is_none_or(|(_, bc)| c > *bc) {
            best = Some((p, c));
        }
    }
    best.map(|(p, _)| p)
}

pub(crate) fn cmd_consolidate(
    dry_run: bool,
    limit: usize,
    model: &str,
    llm_url: &str,
    concurrency: usize,
    guard: Guard,
) -> Result<()> {
    let api = crate::api::base_url();
    let client = crate::api::client(std::time::Duration::from_secs(30))?;

    let batch_resp = client
        .get(format!("{api}/v1/consolidate/batch?limit={limit}"))
        .send()?;
    let batch: serde_json::Value = crate::api::daemon_ok(batch_resp)
        .context("batch fetch failed")?
        .json()?;

    let total = batch["total"].as_u64().unwrap_or(0);
    let stats = &batch["consolidation"];
    let memories = batch["memories"].as_array().cloned().unwrap_or_default();

    eprintln!(
        "memories: {total} total, {} distilled, {} raw pending, {} retired, {} awaiting retirement",
        stats["distilled_live"],
        stats["raw_pending"],
        stats["raw_retired"],
        stats["raw_retire_pending"]
    );
    if memories.is_empty() {
        eprintln!("nothing to consolidate");
        return Ok(());
    }

    let units = group_into_units(&memories, limit);
    if units.is_empty() {
        eprintln!("nothing to consolidate (batch was a single truncated conversation)");
        return Ok(());
    }
    eprintln!(
        "processing {} memories as {} conversation excerpts with {model} at {llm_url} (concurrency={concurrency})",
        units.iter().map(|u| u.raw_ids.len()).sum::<usize>(),
        units.len(),
    );

    let rt = tokio::runtime::Runtime::new()?;
    let chat_url = format!("{llm_url}/v1/chat/completions");

    let success = std::sync::atomic::AtomicUsize::new(0);
    let skipped = std::sync::atomic::AtomicUsize::new(0);
    let errors = std::sync::atomic::AtomicUsize::new(0);
    let processed = std::sync::atomic::AtomicUsize::new(0);

    let chunks: Vec<&[ConsolidationUnit]> = units.chunks(concurrency).collect();
    let total_count = units.len();

    for chunk in &chunks {
        let futures: Vec<_> = chunk
            .iter()
            .map(|unit| {
                let chat_url = chat_url.clone();
                let model = model.to_string();
                async move {
                    distill_window(&unit.fragments, guard, |prompt| {
                        let (chat_url, model) = (chat_url.clone(), model.clone());
                        async move { call_llm(&chat_url, &model, &prompt).await }
                    })
                    .await
                }
            })
            .collect();

        let results = rt.block_on(async { futures::future::join_all(futures).await });

        for (unit, result) in chunk.iter().zip(results) {
            let i = processed.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;

            let response = match result {
                Ok(r) => r,
                Err(e) => {
                    eprintln!("  [{i}/{total_count}] error: {e}");
                    errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    continue;
                }
            };

            let distilled = response.trim().to_string();

            let (body, skip) = match outcome(unit, &distilled, model, dry_run) {
                Outcome::Preview => {
                    if !is_distillate(&distilled) {
                        skipped.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        continue;
                    }
                    let raw_len: usize = unit.fragments.iter().map(|f| f.len()).sum();
                    println!(
                        "--- [{i}/{total_count}] {} ({} turns, {raw_len} chars) ---",
                        unit.source_id,
                        unit.fragments.len()
                    );
                    println!("--- distilled ({} chars) ---", distilled.len());
                    println!("  {distilled}");
                    println!();
                    success.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    continue;
                }
                Outcome::Store { body, skip } => (body, skip),
            };

            if skip {
                skipped.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                client
                    .post(format!("{api}/v1/consolidate/store"))
                    .json(&body)
                    .send()
                    .ok();
                continue;
            }

            let store_resp = client
                .post(format!("{api}/v1/consolidate/store"))
                .json(&body)
                .send();

            match store_resp {
                Ok(r) if r.status().is_success() => {
                    success.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                }
                Ok(r) => {
                    eprintln!("  [{i}/{total_count}] store error: {}", r.status());
                    errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                }
                Err(e) => {
                    eprintln!("  [{i}/{total_count}] store error: {e}");
                    errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                }
            }

            if i.is_multiple_of(10) {
                let s = success.load(std::sync::atomic::Ordering::Relaxed);
                let sk = skipped.load(std::sync::atomic::Ordering::Relaxed);
                let e = errors.load(std::sync::atomic::Ordering::Relaxed);
                eprintln!("  [{i}/{total_count}] {s} distilled, {sk} skipped, {e} errors");
            }
        }
    }

    let s = success.load(std::sync::atomic::Ordering::Relaxed);
    let sk = skipped.load(std::sync::atomic::Ordering::Relaxed);
    let e = errors.load(std::sync::atomic::Ordering::Relaxed);
    eprintln!();
    eprintln!("consolidation complete: {s} distilled, {sk} skipped, {e} errors");
    if dry_run {
        eprintln!("(dry run, nothing written)");
        return Ok(());
    }

    if s > 0 || sk > 0 {
        eprintln!("retiring consolidated raw memories to the archive tier...");
        match client.post(format!("{api}/v1/consolidate/cleanup")).send() {
            Ok(resp) if resp.status().is_success() => {
                let body: serde_json::Value = resp.json().unwrap_or_default();
                let archived = body["archived"].as_u64().unwrap_or(0);
                eprintln!("archived {archived} raw memories that were consolidated");
            }
            Ok(resp) => {
                eprintln!("cleanup warning: {}", resp.status());
            }
            Err(e) => {
                eprintln!("cleanup warning: {e}");
            }
        }
    }

    Ok(())
}

fn build_consolidation_prompt(fragments: &[String]) -> String {
    let excerpt = fragments
        .iter()
        .enumerate()
        .map(|(i, f)| format!("--- turn {} ---\n{f}", i + 1))
        .collect::<Vec<_>>()
        .join("\n\n");
    format!(
        r#"Extract the key knowledge facts from this excerpt of a conversation. The excerpt may span several consecutive turns; read it as one continuous exchange, not independent fragments. Return ONLY the distilled facts as a concise paragraph. No preamble, no explanation, no bullet points unless the content is a list of items.

Rules:
- Keep technical details exact (names, versions, commands, file paths, config values)
- Remove conversational noise ("Let me check...", "Perfect!", "Now let me...")
- Preserve decisions and their reasoning
- Preserve architecture choices and trade-offs
- If the excerpt shows a problem being investigated and then resolved, state the resolution reached, not just the initial symptom
- If the excerpt contains no extractable knowledge, respond with just "SKIP"
- Keep it under 200 words

Excerpt:
{excerpt}"#
    )
}

/// Thinking is turned off because a reasoning model such as qwen3.5 would
/// otherwise spend the token cap reasoning and return empty content, which
/// is stored as a skip; servers whose chat template has no such switch ignore it.
fn chat_request(model: &str, prompt: &str) -> serde_json::Value {
    serde_json::json!({
        "model": model,
        "messages": [
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.1,
        "max_tokens": 4096,
        "chat_template_kwargs": {"enable_thinking": false},
    })
}

async fn call_llm(url: &str, model: &str, prompt: &str) -> Result<String> {
    let client = reqwest::Client::new();
    let body = chat_request(model, prompt);

    let resp = client
        .post(url)
        .json(&body)
        .timeout(std::time::Duration::from_secs(120))
        .send()
        .await
        .context("connecting to LLM")?;

    if !resp.status().is_success() {
        let status = resp.status();
        let text = resp.text().await.unwrap_or_default();
        anyhow::bail!("LLM returned {status}: {text}");
    }

    let json: serde_json::Value = resp.json().await.context("parsing LLM response")?;
    let content = json["choices"][0]["message"]["content"]
        .as_str()
        .unwrap_or("");
    Ok(content.to_string())
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Guard {
    None,
    /// Distil, then ask once for a rewrite naming the identifiers the draft
    /// dropped. Chosen by second-brain's pre-registered evals/distill_guard
    /// test, which hearth's consolidation passed with the same prompts.
    Retry,
}

impl Guard {
    pub(crate) fn parse(value: &str) -> Result<Guard> {
        match value {
            "none" => Ok(Guard::None),
            "retry" => Ok(Guard::Retry),
            other => anyhow::bail!("unknown --guard {other:?}, expected none or retry"),
        }
    }
}

/// What to do with one window's distillate.
#[derive(Debug, PartialEq)]
enum Outcome {
    /// Dry run: print it, write nothing.
    Preview,
    /// A body for `/v1/consolidate/store`; `skip` marks the raws consolidated
    /// with nothing distilled.
    Store { body: serde_json::Value, skip: bool },
}

fn outcome(unit: &ConsolidationUnit, distilled: &str, model: &str, dry_run: bool) -> Outcome {
    if dry_run {
        return Outcome::Preview;
    }
    if !is_distillate(distilled) {
        return Outcome::Store {
            body: serde_json::json!({
                "raw_ids": unit.raw_ids,
                "source_id": unit.source_id,
                "distilled_content": "",
                "model": model,
                "skip": true,
            }),
            skip: true,
        };
    }
    Outcome::Store {
        body: serde_json::json!({
            "raw_ids": unit.raw_ids,
            "source_id": unit.source_id,
            "project_path": unit.project_path,
            "distilled_content": distilled,
            "model": model,
            "skip": false,
        }),
        skip: false,
    }
}

/// A window's identifiers can run to hundreds because every number of two or
/// more digits counts; the cap keeps the list from rivalling the excerpt.
const MAX_PROMPT_IDENTIFIERS: usize = 40;
const REWRITE_WORD_LIMIT: usize = 300;

fn build_rewrite_prompt(fragments: &[String], draft: &str, missing: &[String]) -> String {
    format!(
        "{}\n\nA first summary of this excerpt:\n{draft}\n\n\
         It dropped these exact identifiers from the excerpt: {}. Rewrite the summary \
         so it keeps each of them a future reader would need, stated with what it \
         refers to, and keeps every identifier the first summary already has. Follow \
         the same rules, except keep it under {REWRITE_WORD_LIMIT} words. Return only \
         the rewritten summary.",
        build_consolidation_prompt(fragments),
        missing.join(", ")
    )
}

/// False for the answers stored as skips: empty, under 20 bytes, or the
/// prompt's own "SKIP" convention for nothing extractable.
fn is_distillate(text: &str) -> bool {
    text.len() >= 20 && text != "SKIP"
}

/// Distils one window through `call` (one gateway round trip per prompt).
/// Under `Guard::Retry` a draft that dropped identifiers gets one rewrite,
/// kept only if it is a real distillate that loses nothing the draft kept, so
/// the guard can add identifiers but never trade one away; a failed rewrite
/// call keeps the draft rather than losing the window's only result.
async fn distill_window<F, Fut>(fragments: &[String], guard: Guard, call: F) -> Result<String>
where
    F: Fn(String) -> Fut,
    Fut: std::future::Future<Output = Result<String>>,
{
    let draft = call(build_consolidation_prompt(fragments))
        .await?
        .trim()
        .to_string();
    if guard == Guard::None || !is_distillate(&draft) {
        return Ok(draft);
    }
    let window = fragments.join("\n\n");
    let lost = crate::tokens::missing_tokens(&[&window], &draft);
    if lost.is_empty() {
        return Ok(draft);
    }
    let mut missing = crate::tokens::ordered_identifiers(&window, &lost);
    missing.truncate(MAX_PROMPT_IDENTIFIERS);
    let rewrite = match call(build_rewrite_prompt(fragments, &draft, &missing)).await {
        Ok(text) => text.trim().to_string(),
        Err(e) => {
            eprintln!("  rewrite failed, keeping the draft: {e:#}");
            return Ok(draft);
        }
    };
    let rewrite_lost = crate::tokens::missing_tokens(&[&window], &rewrite);
    if !is_distillate(&rewrite) || rewrite_lost.iter().any(|t| !lost.contains(t)) {
        return Ok(draft);
    }
    Ok(rewrite)
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use super::*;

    const WINDOW: &str = "Set `MemoryMax=2400M` in pi/sb.service for AUS-12, retry after 900s";

    /// Runs distill_window against scripted replies, recording each prompt;
    /// an `Err` reply stands for a failed gateway call.
    fn distill(
        fragments: &[String],
        guard: Guard,
        replies: Vec<Result<&str, &str>>,
    ) -> (Result<String>, Vec<String>) {
        let prompts = RefCell::new(Vec::new());
        let out = futures::executor::block_on(distill_window(fragments, guard, |prompt| {
            let reply = replies[prompts.borrow().len()]
                .map(str::to_string)
                .map_err(|e| anyhow::anyhow!(e.to_string()));
            prompts.borrow_mut().push(prompt);
            async move { reply }
        }));
        (out, prompts.into_inner())
    }

    fn window() -> Vec<String> {
        vec![WINDOW.to_string()]
    }

    fn unit() -> ConsolidationUnit {
        ConsolidationUnit {
            raw_ids: vec!["r1".to_string()],
            source_id: "s".to_string(),
            project_path: Some("/p".to_string()),
            fragments: vec![WINDOW.to_string()],
        }
    }

    #[test]
    fn a_dry_run_writes_nothing_even_for_a_skip() {
        assert_eq!(outcome(&unit(), "SKIP", "m", true), Outcome::Preview);
        assert_eq!(
            outcome(&unit(), "a distilled memory with details", "m", true),
            Outcome::Preview
        );
    }

    #[test]
    fn a_skip_is_stored_as_a_skip_marker() {
        let Outcome::Store { body, skip } = outcome(&unit(), "SKIP", "m", false) else {
            panic!("a real run stores the skip");
        };
        assert!(skip);
        assert_eq!(body["skip"], true);
        assert_eq!(body["distilled_content"], "");
        assert_eq!(body["raw_ids"], serde_json::json!(["r1"]));
    }

    #[test]
    fn a_distillate_is_stored_with_its_project() {
        let text = "a distilled memory with details";
        let Outcome::Store { body, skip } = outcome(&unit(), text, "m", false) else {
            panic!("a real run stores the distillate");
        };
        assert!(!skip);
        assert_eq!(body["distilled_content"], text);
        assert_eq!(body["project_path"], "/p");
        assert_eq!(body["model"], "m");
    }

    #[test]
    fn chat_request_turns_thinking_off() {
        let body = chat_request("qwen3.5-4b", "p");
        assert_eq!(body["chat_template_kwargs"]["enable_thinking"], false);
        assert_eq!(body["messages"][0]["content"], "p");
    }

    #[test]
    fn build_consolidation_prompt_text_is_pinned() {
        assert_eq!(
            build_consolidation_prompt(&["only turn".to_string()]),
            "Extract the key knowledge facts from this excerpt of a conversation. \
             The excerpt may span several consecutive turns; read it as one \
             continuous exchange, not independent fragments. Return ONLY the \
             distilled facts as a concise paragraph. No preamble, no explanation, \
             no bullet points unless the content is a list of items.\n\
             \n\
             Rules:\n\
             - Keep technical details exact (names, versions, commands, file paths, config values)\n\
             - Remove conversational noise (\"Let me check...\", \"Perfect!\", \"Now let me...\")\n\
             - Preserve decisions and their reasoning\n\
             - Preserve architecture choices and trade-offs\n\
             - If the excerpt shows a problem being investigated and then resolved, state the resolution reached, not just the initial symptom\n\
             - If the excerpt contains no extractable knowledge, respond with just \"SKIP\"\n\
             - Keep it under 200 words\n\
             \n\
             Excerpt:\n--- turn 1 ---\nonly turn"
        );
    }

    #[test]
    fn build_rewrite_prompt_text_is_pinned() {
        // Must match hearth's build_rewrite_prompt word for word, since the
        // held-out test that passed it was run with hearth's text.
        let fragments = vec!["only turn".to_string()];
        assert_eq!(
            build_rewrite_prompt(
                &fragments,
                "a draft",
                &["pi/sb.service".to_string(), "900".to_string()]
            ),
            build_consolidation_prompt(&fragments)
                + "\n\nA first summary of this excerpt:\na draft\n\n\
                   It dropped these exact identifiers from the excerpt: pi/sb.service, 900. \
                   Rewrite the summary so it keeps each of them a future reader would need, \
                   stated with what it refers to, and keeps every identifier the first \
                   summary already has. Follow the same rules, except keep it under 300 \
                   words. Return only the rewritten summary."
        );
    }

    #[test]
    fn none_guard_sends_todays_prompt_once() {
        let (out, prompts) = distill(
            &window(),
            Guard::None,
            vec![Ok("a draft that names nothing")],
        );
        assert_eq!(out.unwrap(), "a draft that names nothing");
        assert_eq!(prompts, vec![build_consolidation_prompt(&window())]);
    }

    #[test]
    fn retry_guard_makes_one_call_when_the_draft_keeps_every_identifier() {
        let draft = "MemoryMax=2400M set in pi/sb.service (AUS-12); retry after 900s.";
        let (out, prompts) = distill(&window(), Guard::Retry, vec![Ok(draft)]);
        assert_eq!(out.unwrap(), draft);
        assert_eq!(prompts.len(), 1);
    }

    #[test]
    fn retry_guard_rewrites_a_draft_that_dropped_identifiers() {
        let draft = "Raised MemoryMax=2400M for AUS-12.";
        let rewrite = "Raised MemoryMax=2400M in pi/sb.service for AUS-12; retry after 900s.";
        let (out, prompts) = distill(&window(), Guard::Retry, vec![Ok(draft), Ok(rewrite)]);
        assert_eq!(out.unwrap(), rewrite);
        assert_eq!(
            prompts[1],
            build_rewrite_prompt(
                &window(),
                draft,
                &["pi/sb.service".to_string(), "900".to_string()]
            )
        );
    }

    #[test]
    fn retry_guard_refuses_a_rewrite_that_loses_an_identifier_the_draft_had() {
        let draft = "Raised MemoryMax=2400M for AUS-12.";
        let rewrite = "Raised the memory cap in pi/sb.service; retry after 900s.";
        let (out, _) = distill(&window(), Guard::Retry, vec![Ok(draft), Ok(rewrite)]);
        assert_eq!(out.unwrap(), draft);
    }

    #[test]
    fn retry_guard_keeps_the_draft_when_the_rewrite_is_a_skip() {
        let draft = "Raised MemoryMax=2400M for AUS-12.";
        let (out, _) = distill(&window(), Guard::Retry, vec![Ok(draft), Ok("SKIP")]);
        assert_eq!(out.unwrap(), draft);
    }

    #[test]
    fn retry_guard_does_not_rewrite_a_skip() {
        let (out, prompts) = distill(&window(), Guard::Retry, vec![Ok("SKIP")]);
        assert_eq!(out.unwrap(), "SKIP");
        assert_eq!(prompts.len(), 1);
    }

    #[test]
    fn retry_guard_caps_the_missing_list() {
        let fragments = vec![
            (100..160)
                .map(|n| format!("AUS-{n}"))
                .collect::<Vec<_>>()
                .join(" "),
        ];
        let (_, prompts) = distill(
            &fragments,
            Guard::Retry,
            vec![Ok("a draft that names no ticket"), Ok("still none")],
        );
        let listed = prompts[1]
            .split_once("from the excerpt: ")
            .unwrap()
            .1
            .split_once('.')
            .unwrap()
            .0;
        let expected: Vec<String> = (100..140).map(|n| format!("AUS-{n}")).collect();
        assert_eq!(listed.split(", ").collect::<Vec<_>>(), expected);
    }

    #[test]
    fn retry_guard_keeps_the_draft_when_the_rewrite_call_fails() {
        let (out, prompts) = distill(
            &window(),
            Guard::Retry,
            vec![Ok("Raised MemoryMax=2400M."), Err("budget exhausted")],
        );
        assert_eq!(out.unwrap(), "Raised MemoryMax=2400M.");
        assert_eq!(prompts.len(), 2);
    }

    #[test]
    fn a_failed_draft_call_is_an_error() {
        let (out, _) = distill(&window(), Guard::Retry, vec![Err("connection refused")]);
        assert!(out.is_err());
    }
}