Cotton code
1658 lines · 58.9 KB · RustRaw
//! Every function here is pure and takes what it needs as an argument — these//! tests are the proof that the compiler is deterministic enough to be the ONE//! answer to "what does every agent read", which is memory's whole promise.//!//! The whole-document goldens in `tests/fixtures/memory_briefing.json` are the//! stronger half: 22 inputs, each with the exact markdown, token estimate,//! over-budget flag and drop counts this compiler produces. A briefing that//! differs by one byte between the preview and the brief is a briefing the owner//! previewed and an agent did not receive.//!//! They were recorded from the TypeScript compiler this module was ported from,//! and they were RE-RECORDED from this one when schema v34 took the dated flag//! off a memory: no Now heading, no dated pool for the budget to shed — and//! again on 2026-09-29, when a budget too small for the owner's entries began//! leaving whole ones out and counting them rather than flagging all of them//! over. The TypeScript is gone, so this is no longer a two-implementation//! comparison — it is a frozen record of what the one compiler answers,//! rewritten only by the explicitly ignored test at the bottom of this file,//! never as a side effect of a failing one.use std::collections::BTreeSet;use serde::{Deserialize, Serialize};use super::*;fn entry(slug: &str) -> BriefingEntry {    BriefingEntry {        slug: slug.to_string(),        title: format!("The {slug} rule."),        pinned: false,        position: 1000.0,        machine: None,        created_at: "2026-08-01T00:00:00Z".to_string(),    }}fn input() -> BriefingInput {    BriefingInput {        owner: None,        owner_name: Some("Ada".to_string()),        generated_at: "2026-08-24T09:30:00Z".to_string(),        machine: None,        projects: Vec::new(),        procedures: None,        budget_tokens: None,        pointers: None,    }}fn project(entries: Vec<BriefingEntry>, slug: &str, name: &str) -> BriefingProjectInput {    BriefingProjectInput {        slug: slug.to_string(),        name: name.to_string(),        entries,    }}fn tinmen(entries: Vec<BriefingEntry>) -> BriefingProjectInput {    project(entries, "tinmen", "Tinmen")}/// The slugs a briefing actually carries, in the order it carries them.fn slugs_in(markdown: &str) -> Vec<String> {    let pattern = Regex::new(r"(?m)^- \[([a-z0-9-]+)\]").expect("a valid pattern");    pattern        .captures_iter(markdown)        .map(|caps| caps[1].to_string())        .collect()}/// The `##` headings, in order.fn headings_in(markdown: &str) -> Vec<String> {    let pattern = Regex::new(r"(?m)^## (.+)$").expect("a valid pattern");    pattern        .captures_iter(markdown)        .map(|caps| caps[1].to_string())        .collect()}// ── compileBriefing — a caller one release behind ────────────────────────────/// The library is shared and a caller can be a release behind, so one that has/// not learned about `position` yet must still get a populated briefing rather/// than an exception. In TypeScript every `position` is `undefined` and/// `positionOrder` falls through to the slug; in Rust `serde(default)` gives/// every entry 0.0, which compares equal and falls through the same way.fn no_position(slug: &str) -> BriefingEntry {    BriefingEntry {        position: 0.0,        ..entry(slug)    }}#[test]fn renders_every_entry_in_slug_order_with_no_section_it_cannot_build() {    let result = compile_briefing(&BriefingInput {        projects: vec![tinmen(vec![            no_position("self-serve"),            no_position("reads-no-prs"),            no_position("on-tinmen"),        ])],        ..input()    });    assert_eq!(headings_in(&result.markdown), vec!["Project: Tinmen"]);    assert_eq!(        slugs_in(&result.markdown),        vec!["on-tinmen", "reads-no-prs", "self-serve"]    );    assert!(!result.markdown.contains("Recent sessions"));    assert!(!result.markdown.contains("Needs attention"));    assert!(!result.over_budget);    assert_eq!(result.dropped, Dropped::default());}#[test]fn serves_the_mini_briefing() {    let text = mini_briefing(Some("Ada"), MINI_BRIEFING_CAP_CHARS);    assert!(!text.contains("Waiting:"));    assert!(text.contains("brief"));    assert!(text.contains("get_project"));    assert!(text.contains("list_tools"));}/// RULE: The briefing is the owner's memory entries and nothing else — no recent sessions, no counts of what waits, no project context and no imported tool instructions ride in it.#[test]fn the_briefing_carries_memory_and_nothing_else() {    let result = compile_briefing(&BriefingInput {        procedures: Some(vec![procedure("tinmen", "Ship a PR", "note-one")]),        ..crowded()    });    for absent in ["## Recent sessions", "## Needs attention", "## Project context", "IMPORTED TOOL DATA", "Waiting:"] {        assert!(!result.markdown.contains(absent), "{absent}: {}", result.markdown);    }    assert_eq!(headings_in(&result.markdown), vec!["Project: Meridian", "Project: Tinmen", "Procedures"]);}// ── determinism ──────────────────────────────────────────────────────────────/// RULE: The same memory and the same projects always produce exactly the same briefing, so every assistant reads one answer.#[test]fn renders_identical_bytes_for_identical_input() {    let shape = BriefingInput {        projects: vec![tinmen(vec![            entry("async-by-default"),            entry("no-prod-release-without-the-ask"),            BriefingEntry {                pinned: true,                ..entry("relaunch-is-owner-triggered")            },        ])],        ..input()    };    assert_eq!(        compile_briefing(&shape).markdown,        compile_briefing(&shape).markdown    );}#[test]fn estimates_tokens_as_ceil_chars_over_four() {    let result = compile_briefing(&BriefingInput {        projects: vec![tinmen(vec![entry("reads-no-prs")])],        ..input()    });    assert_eq!(        result.tokens_estimate,        (result.markdown.encode_utf16().count() as i64 + 3) / 4    );}// ── section order (stable first, volatile last) ──────────────────────────────#[test]fn renders_only_the_sections_that_have_content() {    let result = compile_briefing(&BriefingInput {        projects: vec![tinmen(vec![entry("standing")])],        ..input()    });    assert_eq!(headings_in(&result.markdown), vec!["Project: Tinmen"]);}#[test]fn tells_a_caller_with_no_project_how_to_find_one() {    let result = compile_briefing(&input());    assert!(result.markdown.contains("No project is bound to this repo"));    assert!(result.markdown.contains("`list_projects`"));    assert!(result.markdown.contains("`brief { project }`"));    assert!(headings_in(&result.markdown).is_empty());}#[test]fn opens_with_the_date_only_the_owners_name_and_the_verbs() {    let result = compile_briefing(&input());    assert!(result        .markdown        .starts_with("# Briefing for sessions working with Ada — 2026-08-24"));    assert!(!result.markdown.contains("09:30"));    for verb in ["`recall`", "`remember`", "`log_session`"] {        assert!(result.markdown.contains(verb), "missing {verb}");    }    assert!(!result.markdown.contains("memory_propose"));    assert!(!result.markdown.contains("list_memories"));}#[test]fn falls_back_to_the_owner_when_no_name_is_known() {    let result = compile_briefing(&BriefingInput {        owner_name: None,        projects: vec![tinmen(vec![entry("me")])],        ..input()    });    assert!(result.markdown.contains("working with the owner"));}// ── one section per project ──────────────────────────────────────────────────/// The slice of a briefing that belongs to one `## Project:` heading.fn section_of<'a>(markdown: &'a str, heading: &str) -> &'a str {    let after = markdown        .split_once(heading)        .expect("the heading is present")        .1;    after.split("\n##").next().unwrap_or(after)}#[test]fn keeps_each_projects_entries_under_its_own_heading() {    let result = compile_briefing(&BriefingInput {        projects: vec![            tinmen(vec![entry("tinmen-law")]),            project(vec![entry("meridian-law")], "meridian", "Meridian"),        ],        ..input()    });    assert_eq!(        slugs_in(section_of(&result.markdown, "## Project: Tinmen")),        vec!["tinmen-law"]    );    assert_eq!(        slugs_in(section_of(&result.markdown, "## Project: Meridian")),        vec!["meridian-law"]    );}#[test]fn arranges_the_same_entry_differently_in_two_projects() {    let result = compile_briefing(&BriefingInput {        projects: vec![            tinmen(vec![                BriefingEntry {                    position: 1000.0,                    ..entry("a")                },                BriefingEntry {                    position: 2000.0,                    ..entry("b")                },            ]),            project(                vec![                    BriefingEntry {                        position: 5000.0,                        ..entry("a")                    },                    BriefingEntry {                        position: 1000.0,                        pinned: true,                        ..entry("b")                    },                ],                "meridian",                "Meridian",            ),        ],        ..input()    });    assert_eq!(        slugs_in(section_of(&result.markdown, "## Project: Tinmen")),        vec!["a", "b"]    );    assert_eq!(        slugs_in(section_of(&result.markdown, "## Project: Meridian")),        vec!["b", "a"]    );}/// RULE: A project's memory briefs as one list in the owner's own order, with no sub-heading that splits it.#[test]fn briefs_a_project_as_one_list_with_no_sub_heading() {    let result = compile_briefing(&BriefingInput {        projects: vec![tinmen(vec![            BriefingEntry {                position: 2000.0,                ..entry("in-flight")            },            entry("law"),        ])],        ..input()    });    let proj = section_of(&result.markdown, "## Project: Tinmen");    assert_eq!(slugs_in(proj), vec!["law", "in-flight"]);    // "Now:" was the heading dated entries briefed under until schema v34.    assert!(!proj.contains("Now:"));    assert!(!proj.contains("Pinned technical:"));}#[test]fn names_the_project_section_by_its_name_not_its_slug() {    let result = compile_briefing(&BriefingInput {        projects: vec![project(vec![entry("x")], "pixel-oracle", "Pixel Oracle")],        ..input()    });    assert!(result.markdown.contains("## Project: Pixel Oracle"));    assert!(!result.markdown.contains("## Project: pixel-oracle"));}#[test]fn orders_lines_pinned_first_then_position_then_slug() {    let result = compile_briefing(&BriefingInput {        projects: vec![tinmen(vec![            BriefingEntry {                created_at: "2026-08-10T00:00:00Z".to_string(),                ..entry("newer")            },            BriefingEntry {                created_at: "2026-08-05T00:00:00Z".to_string(),                ..entry("b-same-day")            },            BriefingEntry {                created_at: "2026-08-05T00:00:00Z".to_string(),                ..entry("a-same-day")            },            BriefingEntry {                pinned: true,                created_at: "2026-08-20T00:00:00Z".to_string(),                ..entry("pinned-new")            },        ])],        ..input()    });    assert_eq!(        slugs_in(&result.markdown),        vec!["pinned-new", "a-same-day", "b-same-day", "newer"]    );}// ── no review state ──────────────────────────────────────────────────────────/// RULE (owner, 25 Oct 2026, #77): memory has no review state, so a briefing/// marks no entry as waiting for anyone — every line is the slug and the/// sentence.#[test]fn a_briefing_marks_no_entry_as_unreviewed() {    let result = compile_briefing(&BriefingInput {        projects: vec![tinmen(vec![            BriefingEntry { position: 1000.0, ..entry("kept") },            BriefingEntry { position: 2000.0, ..entry("fresh") },        ])],        ..input()    });    assert!(result.markdown.ends_with("- [kept] The kept rule.\n- [fresh] The fresh rule."), "{}", result.markdown);    assert!(!result.markdown.contains("unreviewed"), "{}", result.markdown);}// ── machine scoping ──────────────────────────────────────────────────────────fn scoped() -> BriefingInput {    BriefingInput {        projects: vec![tinmen(vec![            entry("everywhere"),            BriefingEntry {                machine: Some("studio".to_string()),                ..entry("only-on-studio")            },        ])],        ..input()    }}#[test]fn briefs_a_machine_scoped_entry_on_its_own_machine() {    let result = compile_briefing(&BriefingInput {        machine: Some("studio".to_string()),        ..scoped()    });    assert_eq!(        slugs_in(&result.markdown),        vec!["everywhere", "only-on-studio"]    );}/// RULE: A memory entry scoped to one machine is withheld from every other machine, and from a caller that names none.#[test]fn withholds_it_from_another_machine_and_from_a_nameless_caller() {    let elsewhere = compile_briefing(&BriefingInput {        machine: Some("laptop".to_string()),        ..scoped()    });    assert_eq!(slugs_in(&elsewhere.markdown), vec!["everywhere"]);    let nameless = compile_briefing(&scoped());    assert_eq!(slugs_in(&nameless.markdown), vec!["everywhere"]);}// ── budget degradation ───────────────────────────────────────────────────────/// Every line is ~20 chars; the budget is in tokens (chars / 4), so a handful/// of tokens is one or two lines.////// Two projects, five memory lines between them and no procedures — the whole/// ladder: procedures first, and only then whole memory lines from the end of/// the owner's order.fn crowded() -> BriefingInput {    BriefingInput {        projects: vec![            project(                vec![entry("me"), entry("standing-law"), entry("older-law")],                "meridian",                "Meridian",            ),            tinmen(vec![entry("project-law"), entry("project-rule")]),        ],        ..input()    }}fn crowded_at(budget: i64) -> BriefingResult {    compile_briefing(&BriefingInput {        budget_tokens: Some(budget as usize),        pointers: None,        ..crowded()    })}fn full_size() -> i64 {    compile_briefing(&crowded()).tokens_estimate}#[test]fn fits_inside_a_generous_budget_without_dropping_anything() {    let result = crowded_at(5000);    assert_eq!(result.dropped, Dropped::default());    assert!(!result.over_budget);}/// The `- N more entries are not shown here` lines, as the counts they state.fn left_out_counts(markdown: &str) -> Vec<i64> {    let pattern = Regex::new(r#"(?m)^- (\d+) more entr(?:y is|ies are) not shown here — read (?:it|them) with `recall \{ project: "[a-z0-9-]+" \}`\.$"#)        .expect("a valid pattern");    pattern        .captures_iter(markdown)        .map(|caps| caps[1].parse().expect("a count"))        .collect()}/// Swept over every budget from the full size down, because the trimmed line/// itself costs tokens: each invariant must hold at every step, not just at one/// hand-picked budget.////// RULE: A briefing over its budget leaves out whole entries from the end of the owner's order, never a word of one, and counts what it left out.#[test]fn degrades_by_leaving_out_whole_entries_from_the_end() {    let full = full_size();    // The owner's order: equal positions fall through to slug order.    let every_slug = [        "me",        "older-law",        "standing-law",        "project-law",        "project-rule",    ];    let every_line: Vec<String> = every_slug.iter().map(|slug| line(&entry(slug))).collect();    for budget in (20..=full).rev() {        let result = crowded_at(budget);        let slugs = slugs_in(&result.markdown);        let label = format!("budget {budget}");        // 1. the entries that survive are the HEAD of the owner's order, each        //    one whole — never a line cut short.        assert_eq!(slugs, every_slug[..slugs.len()].to_vec(), "{label}");        for kept in result.markdown.lines().filter(|l| l.starts_with("- [")) {            assert!(                every_line.iter().any(|whole| whole == kept),                "{label}: {kept}"            );        }        // 2. what was left out is counted, and the count is right.        let left_out = (every_slug.len() - slugs.len()) as i64;        assert_eq!(result.dropped.entries, left_out, "{label}");        assert_eq!(            left_out_counts(&result.markdown).iter().sum::<i64>(),            left_out,            "{label}"        );        // 3. inside budget unless there is nothing left to leave out.        if !slugs.is_empty() {            assert!(result.tokens_estimate <= budget, "{label}");        }        assert_eq!(            result.over_budget,            result.dropped.entries > 0 || result.tokens_estimate > budget,            "{label}"        );    }}/// Too tight for even one entry: every project keeps its heading and says how/// many of its entries are not shown, and the flag is up.#[test]fn counts_every_entry_per_project_when_none_fits() {    let result = crowded_at(20);    assert!(slugs_in(&result.markdown).is_empty());    assert!(result.over_budget);    assert_eq!(        result.dropped,        Dropped {            procedures: 0,            procedures_cut: 0,            entries: 5,        }    );    assert!(result.markdown.contains(        "## Project: Meridian\n\n- 3 more entries are not shown here — read them with `recall { project: \"meridian\" }`."    ));    assert!(result.markdown.contains(        "- 2 more entries are not shown here — read them with `recall { project: \"tinmen\" }`."    ));}/// The priced form keeps every entry: it is what the write-time limit reads,/// and a compile that left entries out would hide the size a new one adds to.#[test]fn the_whole_briefing_keeps_every_entry_and_flags_over_budget_instead() {    let whole = compile_briefing_whole(&BriefingInput {        budget_tokens: Some(20),        pointers: None,        ..crowded()    });    assert_eq!(        slugs_in(&whole.markdown),        vec![            "me",            "older-law",            "standing-law",            "project-law",            "project-rule"        ]    );    assert!(whole.over_budget);    assert_eq!(whole.dropped.entries, 0);    assert!(left_out_counts(&whole.markdown).is_empty());}#[test]fn flags_over_budget_only_when_an_entry_is_left_out() {    assert!(!crowded_at(full_size()).over_budget);    // With nothing but the owner's entries to trim, one token short costs at    // least an entry (the line that counts it costs tokens too), and the flag    // says so.    let one_short = crowded_at(full_size() - 1);    assert!(one_short.dropped.entries >= 1);    assert!(one_short.over_budget);}// ── the Procedures section ───────────────────────────────────────────────────fn procedure(project: &str, title: &str, id: &str) -> BriefingProcedure {    BriefingProcedure {        project: project.to_string(),        id: id.to_string(),        title: title.to_string(),        trigger: format!("a task that reads like {title}"),    }}fn with_procedures(procedures: Vec<BriefingProcedure>) -> BriefingInput {    BriefingInput {        projects: vec![tinmen(vec![entry("standing-law")])],        procedures: Some(procedures),        ..input()    }}/// The note ids of the procedure lines a briefing carries, in its order.fn procedure_ids_in(markdown: &str) -> Vec<String> {    let pattern = Regex::new(r"(?m)^- (?:.+ · )?note ([a-z0-9-]+)$").expect("a valid pattern");    pattern        .captures_iter(markdown)        .map(|caps| caps[1].to_string())        .collect()}/// A caller one release behind sends no `procedures` at all, and that has to/// mean "no section", never a crash and never an empty heading.#[test]fn a_caller_that_sends_no_procedures_gets_no_procedures_section() {    let result = compile_briefing(&BriefingInput {        projects: vec![tinmen(vec![entry("standing-law")])],        ..input()    });    assert!(!result.markdown.contains("## Procedures"), "{}", result.markdown);}#[test]fn an_empty_procedures_list_renders_no_heading() {    let result = compile_briefing(&with_procedures(Vec::new()));    assert!(!result.markdown.contains("## Procedures"), "{}", result.markdown);}/// The whole point of the section: the sentence to match the task against and/// the id to fetch the note by — and never the body.#[test]fn a_procedure_line_carries_its_trigger_and_the_note_id() {    let result = compile_briefing(&with_procedures(vec![procedure(        "tinmen",        "Ship a PR",        "note-one",    )]));    for piece in [        "## Procedures",        "get_record { kind: \"note\", id }",        "- a task that reads like Ship a PR · note note-one",    ] {        assert!(result.markdown.contains(piece), "{}", result.markdown);    }}/// After memory — the owner's own words lead, and a cacheable prefix stays/// cacheable.#[test]fn the_procedures_section_comes_after_memory() {    let result = compile_briefing(&BriefingInput {        projects: vec![tinmen(vec![entry("standing-law")])],        procedures: Some(vec![procedure("tinmen", "Ship a PR", "note-one")]),        ..input()    });    assert_eq!(headings_in(&result.markdown), vec!["Project: Tinmen", "Procedures"]);}/// Project, then title, then id — so the same set reads the same way however/// the store happened to return it.#[test]fn sorts_procedures_by_project_then_title_then_id() {    let scrambled = with_procedures(vec![        procedure("tinmen", "Zip it", "note-z"),        procedure("meridian", "Bake a cake", "note-b"),        procedure("tinmen", "Ask a question", "note-a2"),        procedure("tinmen", "Ask a question", "note-a1"),    ]);    let first = compile_briefing(&scrambled);    assert_eq!(        procedure_ids_in(&first.markdown),        vec!["note-b", "note-a1", "note-a2", "note-z"]    );    // Deterministic: the same set in another arrival order compiles to the same    // bytes.    let reversed = with_procedures({        let mut list = scrambled.procedures.clone().unwrap_or_default();        list.reverse();        list    });    assert_eq!(compile_briefing(&reversed).markdown, first.markdown);}/// RULE: A briefing that is too long cuts every procedure to its id, then the procedure lines, before it touches one word of the owner's own memory./// A procedure's id is how a session finds the one note its task needs; it is/// still a pointer at a note `get_project` lists, so it goes before any of the/// owner's own words. Swept over every budget, because each trimmed line costs/// tokens of its own.#[test]fn cuts_procedures_to_their_ids_and_sheds_them_before_it_touches_a_memory_line() {    let crowded_with_procedures = |budget: i64| {        compile_briefing(&BriefingInput {            budget_tokens: Some(budget as usize),            pointers: None,            procedures: Some(vec![                procedure("meridian", "Bake a cake", "note-b"),                procedure("tinmen", "Ship a PR", "note-s"),                procedure("tinmen", "Zip it", "note-z"),            ]),            ..crowded()        })    };    let full = crowded_with_procedures(9_999).tokens_estimate;    for budget in (20..=full).rev() {        let result = crowded_with_procedures(budget);        let label = format!("budget {budget}");        let ids = procedure_ids_in(&result.markdown);        // A procedure line goes only once every procedure is down to its id.        if result.dropped.procedures > 0 {            assert!(!result.markdown.contains("reads like"), "{label}\n{}", result.markdown);        }        // Nothing of memory's is touched while a procedure line is still there.        if result.dropped.entries > 0 {            assert!(ids.is_empty(), "{label}");        }        // The survivors are a PREFIX of the sorted order: the last goes first.        assert_eq!(            ids,            ["note-b", "note-s", "note-z"][..3 - result.dropped.procedures as usize].to_vec(),            "{label}"        );    }}/// RULE: The Procedures section takes at most its share of the budget — 1,000 tokens at the owner's own — and at that budget every procedure keeps its note id, saying its trigger's first sentence, else its name, and never a sentence cut in the middle./// 39 procedures with two-sentence triggers once took a quarter of the brief/// and shed 19 ids (12 Oct 2026).#[test]fn procedures_fit_their_share_and_keep_every_id() {    let procedures: Vec<BriefingProcedure> = (0..39)        .map(|n| BriefingProcedure {            project: "tinmen".to_string(),            id: format!("{n:08}-0000-4000-8000-000000000000"),            title: format!("Procedure {n:02} with a plain name"),            trigger: format!(                "You are doing task number {n:02}, which takes a long sentence to describe — the kind a session matches on. A second sentence adds what the first did not, and costs as much again."            ),        })        .collect();    let result = compile_briefing(&with_procedures(procedures.clone()));    let section = result        .markdown        .split("\n## ")        .find(|part| part.starts_with("Procedures"))        .expect("a Procedures section");    assert!(        estimate_tokens(section) <= MEMORY_BRIEFING_PROCEDURES_TOKENS as i64,        "{} tokens\n{section}",        estimate_tokens(section)    );    let ids = procedure_ids_in(&result.markdown);    assert_eq!(ids.len(), 39, "{section}");    assert_eq!(result.dropped.procedures, 0);    for line in section.lines().filter(|line| line.starts_with("- ")) {        assert!(!line.contains("A second sentence"), "{line}");        assert!(            line.contains("the kind a session matches on. · note")                || line.contains("with a plain name · note")                || line.starts_with("- note "),            "{line}"        );    }    // Some keep their sentence; the rest say so on one line.    assert!(section.contains("matches on."), "{section}");    assert!(result.dropped.procedures_cut > 0);    assert!(        result.markdown.contains(&format!(            "- {} procedure lines show only a name or an id, to fit — `get_project` lists every trigger whole.",            result.dropped.procedures_cut        )),        "{}",        result.markdown    );    // A smaller budget shrinks the share with it: a quarter.    let small = compile_briefing(&BriefingInput {        budget_tokens: Some(2000),        pointers: None,        ..with_procedures(procedures.iter().take(5).cloned().collect())    });    let section = small.markdown.split("\n## ").find(|part| part.starts_with("Procedures")).expect("a section");    assert!(estimate_tokens(section) <= 500, "{section}");}/// RULE: A procedure line is cut only where a sentence ends — at a full stop, question or exclamation mark followed by a capital or the end — never inside one.#[test]fn a_trigger_is_cut_at_its_first_sentence_only() {    for (trigger, first) in [        ("One sentence only", "One sentence only"),        ("First one. Second one.", "First one."),        ("Asked (\"take ownership\"). Then more.", "Asked (\"take ownership\")."),        ("A release cut — the real app. Coordinator only.", "A release cut — the real app."),        ("Talk to `<name>.relay.cottondb.com` e.g. here. Next.", "Talk to `<name>.relay.cottondb.com` e.g. here."),        ("Ends with a question? Yes.", "Ends with a question?"),        ("  Padded.  ", "Padded."),    ] {        assert_eq!(first_sentence(trigger), first, "{trigger:?}");    }}#[test]fn says_out_loud_how_many_procedure_lines_the_budget_trimmed() {    let result = compile_briefing(&BriefingInput {        budget_tokens: Some(20),        pointers: None,        procedures: Some(vec![procedure("tinmen", "Ship a PR", "note-s")]),        ..crowded()    });    assert_eq!(result.dropped.procedures, 1);    assert!(        result            .markdown            .contains("Budget trimmed 1 procedure line — `get_project` lists every procedure"),        "{}",        result.markdown    );}// ── the Owner section ────────────────────────────────────────────────────────/// RULE: The Owner section — the owner's own entries from their personal database — comes first in every brief, before any project, and is there when no project is bound too.#[test]fn the_owner_section_comes_first_with_or_without_a_project() {    let owner = Some(vec![entry("ada-works-from-her-phone")]);    let bound = compile_briefing(&BriefingInput {        owner: owner.clone(),        projects: vec![tinmen(vec![entry("standing-law")])],        procedures: Some(vec![procedure("tinmen", "Ship a PR", "note-one")]),        ..input()    });    assert_eq!(headings_in(&bound.markdown)[..2], ["Owner", "Project: Tinmen"], "{}", bound.markdown);    assert!(bound.markdown.contains("- [ada-works-from-her-phone]"), "{}", bound.markdown);    let unbound = compile_briefing(&BriefingInput { owner, ..input() });    assert_eq!(headings_in(&unbound.markdown).first().map(String::as_str), Some("Owner"));    assert!(unbound.markdown.contains(NO_PROJECT_LINES[0]), "{}", unbound.markdown);    let none = compile_briefing(&BriefingInput { owner: Some(Vec::new()), ..input() });    assert!(!none.markdown.contains("## Owner"), "{}", none.markdown);}/// RULE: The Owner section stays within its 300 tokens whatever the budget, showing whole entries in the owner's order and counting the rest on one line that names `recall` — never a sentence cut.#[test]fn the_owner_section_keeps_to_its_cap_with_whole_entries() {    let entries: Vec<BriefingEntry> = (0..20)        .map(|n| BriefingEntry {            title: format!("Owner sentence {n:02}, written out at the length the owner speaks in, which is long."),            ..entry(&format!("owner-{n:02}"))        })        .collect();    let result = compile_briefing(&BriefingInput {        owner: Some(entries.clone()),        projects: vec![tinmen(vec![entry("standing-law")])],        ..input()    });    let section = result.markdown.split("\n## ").find(|part| part.starts_with("Owner")).expect("an Owner section");    assert!(estimate_tokens(section) <= MEMORY_BRIEFING_OWNER_TOKENS as i64, "{section}");    let shown = section.lines().filter(|line| line.starts_with("- [owner-")).count();    assert!(shown > 0 && shown < 20, "{section}");    for (n, line) in section.lines().filter(|line| line.starts_with("- [owner-")).enumerate() {        assert!(line.starts_with(&format!("- [owner-{n:02}] Owner sentence {n:02},")) && line.contains("which is long."), "{line}");    }    assert!(section.contains(&format!("- {} more entries are not shown here", 20 - shown)), "{section}");    assert!(section.contains("`recall`"), "{section}");    // The write-time price is the whole list's.    assert!(owner_section_tokens(&entries) > MEMORY_BRIEFING_OWNER_TOKENS as i64);    assert!(owner_section_tokens(&entries[..1]) < MEMORY_BRIEFING_OWNER_TOKENS as i64);}// ── procedure_trigger — what makes a note a procedure ────────────────────────#[test]fn reads_the_trigger_off_the_first_line_and_strips_the_label() {    assert_eq!(        procedure_trigger("Trigger: a PR is open and needs merging\n\nThe body."),        Some("a PR is open and needs merging".to_string())    );}#[test]fn accepts_any_casing_of_the_label_and_skips_leading_blank_lines() {    for body in [        "trigger: do the thing",        "TRIGGER: do the thing",        "\n\n  Trigger:   do the thing  ",    ] {        assert_eq!(            procedure_trigger(body),            Some("do the thing".to_string()),            "{body:?}"        );    }}/// A note with no trigger has nothing for the brief to advertise, so it is not/// a procedure however it is filed — including a bare label with no sentence/// after it, and a trigger that only appears further down the body.#[test]fn a_note_without_a_trigger_first_line_is_not_a_procedure() {    for body in [        "",        "   \n\n  ",        "Trigger:",        "Trigger:    ",        "A plain note.\n\nTrigger: too late to count",        "— an em dash first, which is multi-byte",    ] {        assert_eq!(procedure_trigger(body), None, "{body:?}");    }}// ── miniBriefing ─────────────────────────────────────────────────────────────fn kernel() -> String {    mini_briefing(Some("Ada"), MINI_BRIEFING_CAP_CHARS)}/// RULE: The short briefing tells an assistant how to fetch the full one and never quotes a memory entry itself.#[test]fn the_kernel_is_static_how_to_get_the_briefing_never_a_memory() {    let text = kernel();    assert!(slugs_in(&text).is_empty());    for needle in [        "Ada",        "list_tools",        "brief { repoUrl, machine }",        "list_projects",        "get_project",        "recall",        "remember",        "log_session",    ] {        assert!(text.contains(needle), "missing {needle}");    }    assert!(!text.contains("get_briefing"));}#[test]fn the_kernel_stays_inside_the_cap() {    assert!(kernel().encode_utf16().count() <= 1800);    assert!(mini_briefing(Some("Ada"), 100).encode_utf16().count() <= 100);}#[test]fn the_kernel_falls_back_to_the_owner_with_no_name() {    assert!(mini_briefing(None, MINI_BRIEFING_CAP_CHARS).contains("the owner"));}// ── estimateTokens ───────────────────────────────────────────────────────────#[test]fn estimate_tokens_is_ceil_chars_over_four() {    assert_eq!(estimate_tokens(""), 0);    assert_eq!(estimate_tokens("abc"), 1);    assert_eq!(estimate_tokens("abcd"), 1);    assert_eq!(estimate_tokens("abcde"), 2);}/// Node vectors. The two emoji cases are the reason the count is UTF-16 code/// units and not `chars()`: one 🎉 is two units, so it costs a token the same/// way two ASCII characters do.#[test]fn estimate_tokens_matches_the_typescript() {    let vectors: &[(&str, i64)] = &[        ("", 0),        ("a", 1),        ("abc", 1),        ("abcd", 1),        ("abcde", 2),        ("héllo", 2),        ("🎉", 1),        ("🎉🎉🎉", 2),    ];    for (text, expected) in vectors {        assert_eq!(estimate_tokens(text), *expected, "for {text:?}");    }    assert_eq!(estimate_tokens(&"x".repeat(1000)), 250);}// ── mintMemorySlug ───────────────────────────────────────────────────────────fn taken(slugs: &[&str]) -> BTreeSet<String> {    slugs.iter().map(|s| (*s).to_string()).collect()}#[test]fn kebab_cases_a_sentence_dropping_punctuation() {    assert_eq!(        mint_memory_slug("Never cut a prod release!", &taken(&[])),        "never-cut-a-prod-release"    );}#[test]fn collapses_runs_of_punctuation_and_trims_the_edges() {    assert_eq!(        mint_memory_slug("  ...Report — before you mutate!! ", &taken(&[])),        "report-before-you-mutate"    );}#[test]fn caps_a_slug_at_sixty_four_characters() {    let slug = mint_memory_slug(&"a ".repeat(80), &taken(&[]));    assert!(slug.len() <= 64);    assert!(!slug.ends_with('-'));}#[test]fn suffixes_collisions_two_then_three() {    assert_eq!(        mint_memory_slug(            "Report before you mutate",            &taken(&["report-before-you-mutate"])        ),        "report-before-you-mutate-2"    );    assert_eq!(        mint_memory_slug(            "Report before you mutate",            &taken(&["report-before-you-mutate", "report-before-you-mutate-2"])        ),        "report-before-you-mutate-3"    );}#[test]fn keeps_a_collision_suffix_inside_the_cap() {    let long = "x".repeat(70);    let base = mint_memory_slug(&long, &taken(&[]));    let next = mint_memory_slug(&long, &taken(&[base.as_str()]));    assert!(next.len() <= 64);    assert!(next.ends_with("-2"));}#[test]fn falls_back_to_entry_when_a_title_has_nothing_sluggable() {    assert_eq!(mint_memory_slug("!!! ???", &taken(&[])), "entry");    assert_eq!(mint_memory_slug("", &taken(&[])), "entry");}#[test]fn mint_memory_slug_is_deterministic() {    let set = taken(&["a-law"]);    assert_eq!(        mint_memory_slug("A law", &set),        mint_memory_slug("A law", &set)    );}/// Node vectors. The decomposition cases are the load-bearing half: `NFKD`/// runs AFTER `toLowerCase`, so `ÅNGSTRÖM` reaches the kebab pass as `a` +/// combining ring + `ngstro` + combining diaeresis + `m` — and the marks/// become dashes.#[test]fn mint_memory_slug_matches_the_typescript() {    let vectors: &[(&str, &[&str], &str)] = &[        ("Never cut a prod release!", &[], "never-cut-a-prod-release"),        (            "  ...Report — before you mutate!! ",            &[],            "report-before-you-mutate",        ),        (            "Report before you mutate",            &["report-before-you-mutate"],            "report-before-you-mutate-2",        ),        ("!!! ???", &[], "entry"),        ("", &[], "entry"),        ("Café — naïve façade", &[], "cafe-nai-ve-fac-ade"),        ("ÅNGSTRÖM units", &[], "a-ngstro-m-units"),        ("final ligature", &[], "final-ligature"),        ("Ⅻ roman numeral", &[], "xii-roman-numeral"),        ("日本語 only", &[], "only"),        ("MiXeD CaSe 123", &[], "mixed-case-123"),        ("trailing dashes ---", &[], "trailing-dashes"),        ("--leading and trailing--", &[], "leading-and-trailing"),        ("Ⅻ", &[], "xii"),    ];    for (title, already, expected) in vectors {        assert_eq!(            mint_memory_slug(title, &taken(already)),            *expected,            "for {title:?}"        );    }    // The long ones, spelled out rather than pasted.    assert_eq!(        mint_memory_slug(&"a ".repeat(80), &taken(&[])),        "a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a-a"    );    assert_eq!(        mint_memory_slug(&"x".repeat(70), &taken(&[])),        "x".repeat(64)    );    assert_eq!(        mint_memory_slug(&"x".repeat(70), &taken(&["x".repeat(64).as_str()])),        format!("{}-2", "x".repeat(62))    );    assert_eq!(        mint_memory_slug(&format!("{} b", "a".repeat(63)), &taken(&[])),        "a".repeat(63)    );    assert_eq!(        mint_memory_slug(&format!("{}!", "a".repeat(64)), &taken(&[])),        "a".repeat(64)    );}// ── looksLikeSecret ──────────────────────────────────────────────────────────#[test]fn looks_like_secret_flags_credential_shapes() {    let vectors: &[(&str, Option<SecretKind>)] = &[        (            "-----BEGIN RSA PRIVATE KEY-----\nMIIE",            Some(SecretKind::PrivateKey),        ),        ("-----BEGIN PRIVATE KEY-----", Some(SecretKind::PrivateKey)),        (            "key is sk-abcdefghijklmnop0123 here",            Some(SecretKind::ApiKey),        ),        ("token ctn_abcdefghijklmnop0123", Some(SecretKind::CottonToken)),        (            "token cfi_abcdefghijklmnop0123",            Some(SecretKind::FeedbackToken),        ),        (            "token cfi_ab-cd_efghijklmnop0123",            Some(SecretKind::FeedbackToken),        ),        (            "ghp_abcdefghijklmnopqrstuvwxyz0123456789",            Some(SecretKind::GitHubToken),        ),        (            "github_pat_abcdefghijklmnopqrstuvwxyz",            Some(SecretKind::GitHubToken),        ),        ("xoxb-1234567890-abcdefghijkl", Some(SecretKind::SlackToken)),        ("AKIAIOSFODNN7EXAMPLE", Some(SecretKind::AwsKeyId)),        (            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0",            Some(SecretKind::Jwt),        ),        (            "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0",            Some(SecretKind::HighEntropy),        ),        (            "KEY=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0",            Some(SecretKind::HighEntropy),        ),        // Node vectors beyond the TypeScript's own cases: the boundaries.        ("sk-short", None),        ("ghr_abcdefghijklmnopqrstuvwx", Some(SecretKind::GitHubToken)),        ("xoxp-9999999999-zzzz", Some(SecretKind::SlackToken)),        ("AKIAIOSFODNN7EXAMPL", None),        ("a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t", None),        (            "'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0'",            Some(SecretKind::HighEntropy),        ),        (            "prefix\ta1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0\tsuffix",            Some(SecretKind::HighEntropy),        ),    ];    for (text, expected) in vectors {        assert_eq!(looks_like_secret(text), *expected, "for {text:?}");    }}#[test]fn looks_like_secret_lets_real_memory_entries_through() {    let clean: &[&str] = &[        "Never cut a prod release without an explicit per-instance ask.",        "The workspace is 550e8400-e29b-41d4-a716-446655440000.",        "The repo is https://github.com/example/atelier and the branch is main.",        "Read /Users/owner/code/cottondb/apps/cotton/src/tools/me/index.tsx first.",        "Run pnpm cells:doctor --cell owner --env prod before a release.",        // The 2026-08-20 import's false positives — hyphens and `=` are        // boundaries, not run characters, so kebab slugs and env-var        // assignments read clean.        "See the memory expo-router-sdk56-vendored-react-navigation for the trap.",        "Set `EXPO_ROUTER_DISABLE_RN_NAVIGATION_CHECK=1` to bypass the guard.",        "The record is f6281e74-38b2-49c2-9076-82489c9cbf59 on the owner cell.",    ];    for text in clean {        assert_eq!(looks_like_secret(text), None, "for {text:?}");    }    assert_eq!(        looks_like_secret(&format!(            "A very long word with no digits at all: {}",            "a".repeat(50)        )),        None    );}// ── titleSimilarity ──────────────────────────────────────────────────────────#[test]fn title_similarity_scores_an_identical_sentence_one() {    let title = "Never cut a prod release without an explicit ask.";    assert_eq!(title_similarity(title, title), 1.0);}#[test]fn title_similarity_ignores_case_and_punctuation() {    assert_eq!(        title_similarity("Report before you mutate.", "report — before you mutate!"),        1.0    );}#[test]fn title_similarity_scores_unrelated_sentences_low() {    assert!(        title_similarity(            "Never cut a prod release without an explicit ask.",            "This Mac is the only build runner.",        ) < MEMORY_SIMILARITY_THRESHOLD    );}#[test]fn title_similarity_catches_a_reworded_near_duplicate() {    assert!(        title_similarity(            "Never cut a prod release without an explicit ask",            "Never cut a prod release without an explicit per-instance ask",        ) > MEMORY_SIMILARITY_THRESHOLD    );}#[test]fn title_similarity_is_symmetric() {    let a = "Report before you mutate";    let b = "Always report before mutating";    assert_eq!(title_similarity(a, b), title_similarity(b, a));}#[test]fn title_similarity_scores_an_unsluggable_title_zero() {    assert_eq!(title_similarity("", "anything"), 0.0);    assert_eq!(title_similarity("!!!", "anything"), 0.0);    assert_eq!(title_similarity("", ""), 0.0);}#[test]fn the_similarity_threshold_stays_inside_zero_to_one() {    // A const block, because clippy is right that a constant assertion belongs    // at compile time — and the point of the assertion is exactly that: the    // threshold is compared against a Dice coefficient, which lives in 0..1.    const { assert!(MEMORY_SIMILARITY_THRESHOLD > 0.0) };    const { assert!(MEMORY_SIMILARITY_THRESHOLD < 1.0) };}/// Node vectors, to the last bit of the f64. A one-character title scores 0/// against itself because a single character yields no bigram at all.#[test]fn title_similarity_matches_the_typescript() {    let vectors: &[(&str, &str, f64)] = &[        (            "Never cut a prod release without an explicit ask.",            "Never cut a prod release without an explicit ask.",            1.0,        ),        (            "Report before you mutate.",            "report — before you mutate!",            1.0,        ),        (            "Never cut a prod release without an explicit ask.",            "This Mac is the only build runner.",            0.173_913_043_478_260_86,        ),        (            "Never cut a prod release without an explicit ask",            "Never cut a prod release without an explicit per-instance ask",            0.909_090_909_090_909_1,        ),        (            "Report before you mutate",            "Always report before mutating",            0.680_851_063_829_787_2,        ),        (            "Always report before mutating",            "Report before you mutate",            0.680_851_063_829_787_2,        ),        ("", "anything", 0.0),        ("!!!", "anything", 0.0),        ("", "", 0.0),        ("ab", "ab", 1.0),        ("a", "a", 0.0),        ("Café", "cafe", 0.8),        ("one two three", "three two one", 0.956_521_739_130_434_8),    ];    for (a, b, expected) in vectors {        assert_eq!(title_similarity(a, b), *expected, "for {a:?} / {b:?}");    }}// ── normalizeRepoUrl ─────────────────────────────────────────────────────────#[test]fn normalize_repo_url_is_idempotent_and_empty_for_empty() {    let once = normalize_repo_url("git@github.com:example/atelier.git");    assert_eq!(normalize_repo_url(&once), once);    assert_eq!(normalize_repo_url("   "), "");}/// Node vectors. Two of them are the reason the scp-colon step is `replacen`/// and not a global replace: `a:b:c` becomes `a/b:c`, and the `.git` suffix/// only comes off at the very end (`…/b.git/` keeps it).#[test]fn normalize_repo_url_matches_the_typescript() {    let vectors: &[(&str, &str)] = &[        ("https://github.com/A/B.git", "github.com/a/b"),        ("git@github.com:a/b.git", "github.com/a/b"),        ("ssh://git@github.com/a/b/", "github.com/a/b"),        (            "  https://github.com/example/atelier  ",            "github.com/example/atelier",        ),        ("   ", ""),        ("", ""),        (            "git.example.org/decemberfm/cottondb",            "git.example.org/decemberfm/cottondb",        ),        (            "https://git.example.org/decemberfm/cottondb.git",            "git.example.org/decemberfm/cottondb",        ),        ("git+ssh://git@host:2222/a/b.git", "host/2222/a/b"),        ("HTTPS://GITHUB.COM/A/B/", "github.com/a/b"),        ("host.com//a///b", "host.com/a/b"),        ("a:b:c", "a/b:c"),        ("user@host:path/to/repo.git", "host/path/to/repo"),        ("https://github.com/a/b.git/", "github.com/a/b.git"),        ("file:///Users/me/code/repo", "/users/me/code/repo"),    ];    for (raw, expected) in vectors {        assert_eq!(normalize_repo_url(raw), *expected, "for {raw:?}");    }}// ── projectsForRepo ──────────────────────────────────────────────────────────#[derive(Debug, PartialEq)]struct Proj {    slug: &'static str,    repos: Vec<String>,}impl HasRepos for Proj {    fn repos(&self) -> &[String] {        &self.repos    }}fn projects() -> Vec<Proj> {    let of = |slug, repos: &[&str]| Proj {        slug,        repos: repos.iter().map(|r| (*r).to_string()).collect(),    };    vec![        of("atelier", &["https://github.com/example/atelier.git"]),        of("cotton", &["git@github.com:example/atelier.git"]),        of("pixeloracle", &["github.com/example/pixeloracle"]),        of("no-repo", &[]),    ]}fn matched_slugs(repo: &str) -> Vec<&'static str> {    let all = projects();    projects_for_repo(&all, repo)        .into_iter()        .map(|p| p.slug)        .collect()}#[test]fn matches_every_project_listing_the_repo_whatever_spelling_each_used() {    assert_eq!(        matched_slugs("https://github.com/example/atelier"),        vec!["atelier", "cotton"]    );}#[test]fn matches_when_the_caller_uses_the_ssh_spelling() {    assert_eq!(        matched_slugs("git@github.com:example/pixeloracle.git"),        vec!["pixeloracle"]    );}#[test]fn returns_nothing_for_an_unknown_repo_or_an_empty_url() {    assert!(matched_slugs("github.com/someone/else").is_empty());    // Empty, rather than matching everything — including `no-repo`, which lists    // none and would otherwise never be the thing that saves us.    assert!(matched_slugs("").is_empty());}// ── Flat memory (schema v14): one list per project, in the owner's order ─────fn flat(slug: &str) -> BriefingEntry {    BriefingEntry {        title: format!("entry {slug}"),        created_at: "2026-08-01T00:00:00.000Z".to_string(),        ..entry(slug)    }}fn one(entries: Vec<BriefingEntry>, budget: Option<usize>) -> BriefingResult {    compile_briefing(&BriefingInput {        generated_at: "2026-08-30T09:00:00.000Z".to_string(),        projects: vec![project(entries, "cotton", "Cotton")],        budget_tokens: budget,        pointers: None,        ..input()    })}#[test]fn renders_a_projects_entries_as_one_list_in_the_owners_order() {    let result = one(        vec![            BriefingEntry {                position: 3000.0,                ..flat("third")            },            BriefingEntry {                position: 1000.0,                ..flat("first")            },            BriefingEntry {                position: 2000.0,                ..flat("second")            },        ],        None,    );    assert!(result.markdown.contains("## Project: Cotton"));    assert!(!result.markdown.contains("## Standing"));    assert_eq!(slugs_in(&result.markdown), vec!["first", "second", "third"]);}#[test]fn puts_pinned_entries_at_the_head_of_the_list() {    let result = one(        vec![            BriefingEntry {                position: 1000.0,                ..flat("ordinary")            },            BriefingEntry {                position: 9000.0,                pinned: true,                ..flat("pinned")            },        ],        None,    );    assert_eq!(slugs_in(&result.markdown), vec!["pinned", "ordinary"]);}/// RULE: A project's memory briefs as one flat list — there is no Now heading and no dated entry since schema v34.#[test]fn briefs_one_flat_list_with_no_now_heading() {    let result = one(        vec![            flat("durable"),            BriefingEntry {                position: 2000.0,                ..flat("also-durable")            },        ],        None,    );    assert!(!result.markdown.contains("Now:"));    assert_eq!(slugs_in(&result.markdown), vec!["durable", "also-durable"]);}/// The failure this replaces: a 2,400-token briefing that the session-start/// hook then cut at a byte count, mid-sentence ("…leave behind a committed/// script or sk"). The compiler now makes the cut itself, where a line ends.////// RULE: A briefing whose entries alone exceed its budget ends on a whole entry, followed by one line that says how many were left out and how to read them.#[test]fn ends_on_a_whole_entry_and_counts_the_ones_left_out() {    let many: Vec<BriefingEntry> = (0..60)        .map(|i| BriefingEntry {            position: ((i + 1) * 1000) as f64,            created_at: format!("2026-0{}-01T00:00:00.000Z", 1 + (i % 8)),            title: format!("a statement number {i} that is long enough to cost tokens"),            ..flat(&format!("d{i:02}"))        })        .collect();    let slugs: Vec<String> = many.iter().map(|e| e.slug.clone()).collect();    let mut entries = vec![BriefingEntry {        pinned: true,        ..flat("durable")    }];    entries.extend(many);    let result = one(entries, Some(400));    // Far over budget: the head of the owner's order is there, pinned first,    // every line of it whole, and the rest is counted where the list stops.    assert!(result.over_budget);    assert!(result.tokens_estimate <= 400, "{}", result.tokens_estimate);    let shown = slugs_in(&result.markdown);    assert_eq!(shown[0], "durable");    assert_eq!(shown[1..].to_vec(), slugs[..shown.len() - 1].to_vec());    let left_out = 61 - shown.len() as i64;    assert!(left_out > 0);    assert_eq!(result.dropped.entries, left_out);    let last_entry = format!(        "- [{0}] a statement number {1} that is long enough to cost tokens",        shown[shown.len() - 1],        shown.len() - 2    );    let tail = format!(        "{last_entry}\n- {left_out} more entries are not shown here — read them with `recall {{ project: \"cotton\" }}`."    );    assert!(result.markdown.contains(&tail), "{}", result.markdown);    assert_eq!(left_out_counts(&result.markdown), vec![left_out]);}#[test]fn counts_a_single_entry_left_out_in_the_singular() {    // Long enough that leaving one out pays for the line that counts it.    let long = |slug: &str| BriefingEntry {        title: format!(            "{slug}: {}",            "a sentence the owner said at some length. ".repeat(6)        ),        ..flat(slug)    };    let both = one(vec![long("first"), long("second")], None);    let result = one(        vec![long("first"), long("second")],        Some(both.tokens_estimate as usize - 1),    );    assert_eq!(slugs_in(&result.markdown), vec!["first"]);    assert_eq!(result.dropped.entries, 1);    assert!(result.markdown.contains(        "- 1 more entry is not shown here — read it with `recall { project: \"cotton\" }`."    ));}// ── The whole-document goldens ───────────────────────────────────────────────#[derive(Debug, Deserialize, Serialize)]struct Golden {    name: String,    input: BriefingInput,    result: GoldenResult,}#[derive(Debug, Deserialize, Serialize)]#[serde(rename_all = "camelCase")]struct GoldenResult {    markdown: String,    tokens_estimate: i64,    over_budget: bool,    dropped: Dropped,}/// The fixture's path, from the RUNTIME manifest directory — a cached test/// binary from an earlier checkout carries a path that has been deleted, and the/// failure would read like this guard catching real drift.fn goldens_path() -> std::path::PathBuf {    let dir = std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo runs tests with CARGO_MANIFEST_DIR set");    std::path::PathBuf::from(dir).join("vectors").join("memory_briefing.json")}/// Eighteen whole briefings, input and output, byte for byte.////// This is the guarantee the module's doc comment claims: what the owner/// previews is what an agent receives, because there is ONE compiler and its/// whole output is written down. Rewritten only by/// [`rewrite_the_goldens`], never as a side effect of a failing test — a/// fixture that repaired itself would be a guard that agreed with whatever it/// was shown.////// RULE: The briefing compiler is deterministic: the same input compiles to the same markdown, token estimate, over-budget flag and drop counts, byte for byte.#[test]fn compiles_exactly_the_committed_briefings() {    let raw = include_str!("../vectors/memory_briefing.json");    let goldens: Vec<Golden> = serde_json::from_str(raw).expect("the fixture parses");    assert!(goldens.len() >= 18, "the fixture lost cases");    for golden in goldens {        let got = compile_briefing(&golden.input);        assert_eq!(got.markdown, golden.result.markdown, "case {}", golden.name);        assert_eq!(            got.tokens_estimate, golden.result.tokens_estimate,            "case {}",            golden.name        );        assert_eq!(            got.over_budget, golden.result.over_budget,            "case {}",            golden.name        );        assert_eq!(got.dropped, golden.result.dropped, "case {}", golden.name);    }}/// The two lines a session with no project reads, byte for byte.#[test]fn the_no_project_lines_are_the_typescripts() {    assert_eq!(        NO_PROJECT_LINES,        [            "No project is bound to this repo, so there is no memory to brief.",            "Call `list_projects`, then `brief { project }` or `get_project` for the one this work belongs to.",        ]    );}/// Rewrite the committed goldens. Ignored on purpose: it runs when a deliberate/// change to the briefing's shape has made them stale, and never otherwise.////// ```text/// cargo test -p cotton-core --lib -- --ignored rewrite_the_goldens/// ```////// Every INPUT is kept exactly as committed — a rewrite that re-invented the/// cases would be testing whatever the compiler happens to do today against/// inputs chosen to suit it. Only the recorded output moves.#[test]#[ignore = "rewrites the committed briefing goldens; run it only after a deliberate change to the briefing"]fn rewrite_the_goldens() {    let path = goldens_path();    let raw = std::fs::read_to_string(&path).expect("the fixture is there");    let goldens: Vec<Golden> = serde_json::from_str(&raw).expect("the fixture parses");    let rewritten: Vec<Golden> = goldens        .into_iter()        .map(|golden| {            let got = compile_briefing(&golden.input);            Golden {                name: golden.name,                input: golden.input,                result: GoldenResult {                    markdown: got.markdown,                    tokens_estimate: got.tokens_estimate,                    over_budget: got.over_budget,                    dropped: got.dropped,                },            }        })        .collect();    let text = format!(        "{}\n",        serde_json::to_string_pretty(&rewritten).expect("serialises")    );    std::fs::write(&path, text).expect("writes");}