//! Memory briefing — the deterministic compiler that turns memory projects //! into the markdown briefing every AI session loads at start. The port of //! `packages/core/src/engine/memoryBriefing.ts`. //! //! Pure and platform-neutral on purpose: the SAME function must answer three //! callers — the server's MCP `brief` tool, its MCP `initialize` //! mini-briefing, and the app's briefing-preview screen. One compiler is the //! trust guarantee: what the owner previews is byte-what agents receive. That //! guarantee is exactly what a second implementation threatens, which is why //! `memory_briefing_tests.rs` compares whole markdown documents against what //! Node compiled from the same JSON. //! //! The style rules it enforces: //! //! - titles only — an entry's body NEVER enters a briefing; //! - factual statements, never system-voice commands (hook-injection defence); //! - every entry rides with its `[slug]` anchor so any AI can cite or edit it; //! - the owner's own order — pinned first, then `position` (schema v14); no //! category decides what leads, and the sections that change least still come //! first so a cacheable prefix stays cacheable; //! - the whole budget is the founder's: memory holds only the owner's own words //! (founder-only memory), so there is no technical tier to trim — technical //! knowledge lives in the repo, next to the code; //! - the Procedures section fits its own share of the budget //! ([`MEMORY_BRIEFING_PROCEDURES_TOKENS`]): a trigger's first sentence, else //! the note's name, else its id alone — never a word cut mid-sentence; //! - over budget degrades deterministically (procedures to their ids → //! procedure lines → the owner's entries, whole, from the end of their //! order) and says where it cut: an entry is never cut //! mid-sentence, and a project that lost entries ends with one line counting //! them and naming the `recall` that reads them. //! //! There is no Now heading and no dated entry. Until schema v34 an entry could //! be flagged as only-true-for-now and briefed under its own heading; the owner //! retired the mechanism, and an entry that is only true for a while now says so //! in its own sentence. One list per project, in his order. use std::collections::BTreeSet; use std::sync::LazyLock; use regex::Regex; use serde::{Deserialize, Serialize}; use unicode_normalization::UnicodeNormalization; use crate::memory_order::{position_order, Positioned}; /// `MEMORY_BRIEFING_BUDGET_TOKENS` — the ceiling the briefing compiler /// degrades against, in the `chars / 4` estimate the app's meter also shows, /// and the limit a new memory entry is refused at. 4,000 since 2026-09-29 (it /// was 2,400). A caller with a harder ceiling asks `brief` for less — the /// session-start hook does, for Claude Code's 10,000-character hook cap — and /// then gets whole entries and a line counting the ones left out. pub const MEMORY_BRIEFING_BUDGET_TOKENS: usize = 4000; /// `MEMORY_BRIEFING_PROCEDURES_TOKENS` — the most of a briefing its /// Procedures section may take: this many tokens, or a quarter of a smaller /// budget. Inside it each procedure says its trigger's first sentence, else /// its name, else only its note id — the id is never what gives way first /// (architect, 12 Oct 2026: 39 procedures had taken a quarter of the brief and /// shed 19 of their ids). pub const MEMORY_BRIEFING_PROCEDURES_TOKENS: usize = 1000; /// `MEMORY_BRIEFING_OWNER_TOKENS` — the most the Owner section, the first in /// every brief, may take: the owner's own entries from their personal /// database, whole, in order, until the next would pass it (owner, 12 Oct /// 2026: what is true of the owner whatever the project). pub const MEMORY_BRIEFING_OWNER_TOKENS: usize = 300; /// What the compiler needs to know about one entry. /// /// Bodies are not here — by construction a briefing cannot leak one. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BriefingEntry { pub slug: String, pub title: String, /// Pinned IN THIS PROJECT — the link's pin. pub pinned: bool, /// The owner's arrangement IN THIS PROJECT — the link's position (schema /// v34). The compiler renders in this order, pinned first, so what they see /// on the project page is what a session reads. /// /// `serde(default)` because the TypeScript admits a caller one release /// behind that sends no `position` at all: every entry then compares equal /// and the list falls through to slug order — a defined order, just not the /// owner's. Rust has no `undefined`, so 0.0 for all of them reproduces /// exactly that outcome. (`f64::NAN` would NOT: JS `undefined !== /// undefined` is false but `NaN !== NaN` is true.) #[serde(default)] pub position: f64, /// Hostname scope; `None` briefs everywhere. pub machine: Option, pub created_at: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct BriefingProjectInput { pub slug: String, pub name: String, pub entries: Vec, } /// One procedure a session can load: a note whose first line is its trigger. /// /// A procedure is a note the owner keeps in Cotton, and the brief advertises it /// rather than inlining it — the whole point is that a session reads only the /// one whose trigger matches the task in front of it. So this carries the /// trigger sentence and the id to fetch, never the body. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BriefingProcedure { /// The project this procedure is linked to — the sort's first key, so a /// session briefing two projects reads them grouped. pub project: String, /// The note's id, which is what `get_record { kind: "note", id }` takes. pub id: String, /// The note's title — the procedure's name in plain words. pub title: String, /// The one sentence a session matches on, already stripped of its /// `Trigger:` label. pub trigger: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BriefingInput { /// The workspace owner's name, when known. pub owner_name: Option, /// ISO instant stamped into the header (date only renders). pub generated_at: String, /// The requesting machine's hostname; filters machine-scoped entries. pub machine: Option, /// The projects that matched the caller's repo, or the one it named. /// /// There is no project-independent layer any more (a memory /// belongs to its projects, and "everywhere" was a list the owner could not /// curate in context). EMPTY when nothing matched, and the briefing then /// says how to find a project rather than briefing nothing silently. pub projects: Vec, /// The owner's own entries from their PERSONAL database, in the order /// they brief — the Owner section, first in every brief whatever project /// matched, or none (owner, 12 Oct 2026). Whole entries until /// [`MEMORY_BRIEFING_OWNER_TOKENS`]; outside the ladder, because the /// section has its own cap. /// /// `serde(default)`: a caller one release behind sends none, and that /// means no Owner section. #[serde(default)] pub owner: Option>, /// The procedures linked to the matched projects, one line each. /// /// Optional: a caller one release behind sends none, and that means "no /// Procedures section", never a crash. #[serde(default)] pub procedures: Option>, #[serde(default)] pub budget_tokens: Option, /// Where the briefing sends a reader for what it left out, in the tools /// the serving surface has. The phone's own when absent. #[serde(default)] pub pointers: Option, } /// The three places a briefing points a reader at, each naming a tool. The /// phone serves `get_project`; the personal object does not, so it names its /// own (apps/business/src/mcp/tools/memory/briefing.ts). Words, not a rule: /// the ladder that decides what is left out is the same on both. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BriefingPointers { /// The second no-project line. pub find_project: String, /// After "N procedure lines show only a name or an id, to fit —". pub every_trigger: String, /// After "Budget trimmed N procedure lines —". pub every_procedure: String, } impl Default for BriefingPointers { fn default() -> Self { BriefingPointers { find_project: NO_PROJECT_LINES[1].to_string(), every_trigger: "`get_project` lists every trigger whole.".to_string(), every_procedure: "`get_project` lists every procedure the project keeps.".to_string(), } } } /// What degradation removed, so the tail can say so honestly. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] pub struct Dropped { /// The owner's entries left out, whole, from the end of their order — the /// last thing a squeeze touches, and only when a caller asks for less than /// the entries alone take (the session-start hook fits Claude Code's /// 10,000-character cap this way). At the owner's own budget the write-time /// limit keeps it 0. /// /// `serde(default)` for the same reason as `procedures`: goldens recorded /// before an entry could be left out carry no count, and absent is 0. #[serde(default)] pub entries: i64, /// Procedure lines left out whole — only after every procedure is down to /// its id, because the owner's own words outrank a pointer to a note, and /// the id is the pointer. /// /// `serde(default)` so the whole-document goldens, recorded before there /// was a Procedures section, still parse: none of them carries a procedure, /// and an absent count is 0. #[serde(default)] pub procedures: i64, /// Procedure lines that show less than their trigger's first sentence — /// the note's name or its id alone — to fit the section's share. #[serde(default)] pub procedures_cut: i64, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BriefingResult { pub markdown: String, /// chars/4 — the same estimate the app's meter shows. pub tokens_estimate: i64, /// True when the owner's entries did not all fit: some were left out /// (`dropped.entries` says how many), or even the header and one entry /// exceed the budget. pub over_budget: bool, pub dropped: Dropped, } /// chars/4 — coarse, stable, and identical on every platform. /// /// `.length` is UTF-16 code units, which is what makes "identical on every /// platform" true and what a `chars().count()` here would quietly break. pub fn estimate_tokens(text: &str) -> i64 { let units = text.encode_utf16().count() as i64; // `Math.ceil(n / 4)` over a non-negative count. Spelled out rather than // `i64::div_ceil`, which this toolchain still gates behind a feature. (units + 3) / 4 } fn positioned(entry: &BriefingEntry) -> Positioned { Positioned { pinned: entry.pinned, position: entry.position, slug: entry.slug.clone(), } } /// Machine filter: an entry scoped to a hostname briefs only that hostname. An /// unscoped entry briefs everywhere — including callers with no hostname. fn for_machine(entries: &[BriefingEntry], machine: Option<&str>) -> Vec { entries .iter() .filter(|entry| entry.machine.is_none() || entry.machine.as_deref() == machine) .cloned() .collect() } fn sorted(entries: Vec) -> Vec { let mut out = entries; out.sort_by(|a, b| position_order(&positioned(a), &positioned(b))); out } /// `- [slug] title`. Memory has no review state (owner, 25 Oct 2026, #77), so /// an entry carries no mark of who has kept it. fn line(entry: &BriefingEntry) -> String { format!("- [{}] {}", entry.slug, entry.title) } /// `String.prototype.slice(0, n)` — UTF-16 code units, so a surrogate pair can /// be split exactly as JavaScript splits it. fn utf16_slice(text: &str, end: usize) -> String { let units: Vec = text.encode_utf16().collect(); let end = end.min(units.len()); String::from_utf16_lossy(&units[..end]) } fn utf16_len(text: &str) -> usize { text.encode_utf16().count() } fn plural<'a>(n: i64, one: &'a str, many: &'a str) -> &'a str { if n == 1 { one } else { many } } struct ProjectSection { slug: String, name: String, entries: Vec, /// Entries the budget left out of this project, whole, from its end. left_out: i64, } /// The briefing's sections after filtering and sorting — what degradation /// edits. struct Sections { projects: Vec, procedures: Vec<(BriefingProcedure, Said)>, } /// How much of itself a procedure line says. The id is in every form: it is /// the handle a session fetches the note by. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Said { /// The trigger's first sentence — what a task is matched against. Sentence, /// The note's name, when the sentence did not fit. Name, /// The note id alone. Id, } /// Project, then title, then id — a total order over distinct rows, so the /// section is byte-identical for the same set however the store returned it. fn procedure_order(a: &BriefingProcedure, b: &BriefingProcedure) -> std::cmp::Ordering { a.project .cmp(&b.project) .then_with(|| a.title.cmp(&b.title)) .then_with(|| a.id.cmp(&b.id)) } fn build_sections(input: &BriefingInput) -> Sections { let mut procedures = input.procedures.clone().unwrap_or_default(); procedures.sort_by(procedure_order); let budget = input.budget_tokens.unwrap_or(MEMORY_BRIEFING_BUDGET_TOKENS); let said = fit_procedures(&procedures, procedures_share(budget)); Sections { procedures: procedures.into_iter().zip(said).collect(), projects: input .projects .iter() .map(|project| { let entries = for_machine(&project.entries, input.machine.as_deref()); ProjectSection { slug: project.slug.clone(), name: project.name.clone(), entries: sorted(entries), left_out: 0, } }) .collect(), } } /// What a session with no project reads instead of memory. /// /// Two lines, not a silent absence: a briefing that says nothing is /// indistinguishable from one that failed, and the fix is a call away. pub const NO_PROJECT_LINES: &[&str] = &[ "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.", ]; /// The label that makes a note a procedure, matched on its first line. const TRIGGER_LABEL: &str = "trigger:"; /// The trigger sentence of a procedure note, or `None` when the note is not /// one. /// /// **This first line IS the marker, on purpose.** The store has no free-form /// marker for a note — `cotton_notes.kind` is constrained to `note` and /// `journal`, `managed_by` belongs to the code-derived managed-note lane, and a /// new column would be a schema migration. More to the point, the trigger /// sentence is the *payload*: the brief exists to print it, so a note carrying /// no trigger has nothing to advertise and is not a procedure however it is /// tagged. One rule, in one place, and no second marker that can disagree with /// the body. /// /// Leading blank lines are skipped, the label is matched case-insensitively, /// and a label with nothing after it does not qualify. pub fn procedure_trigger(body: &str) -> Option { let first = body .lines() .map(|line| line.trim_matches(crate::js::is_js_whitespace)) .find(|line| !line.is_empty())?; let rest = first.get(..TRIGGER_LABEL.len()).and_then(|head| { head.eq_ignore_ascii_case(TRIGGER_LABEL) .then(|| &first[TRIGGER_LABEL.len()..]) })?; let trigger = rest.trim_matches(crate::js::is_js_whitespace); (!trigger.is_empty()).then(|| trigger.to_string()) } /// What a session does with the Procedures section. /// /// A statement of how the section is used, not a system-voice command — the /// same rule the briefing's other prose follows, so an injected line cannot /// pass itself off as an instruction from the owner. pub const PROCEDURES_INSTRUCTION: &str = "Each line is a note kept in Cotton: when it applies, then its id. When a task matches, read that one with `get_record { kind: \"note\", id }` before starting — one procedure, not all of them."; /// The tokens the Procedures section may take under `budget`. pub fn procedures_share(budget: usize) -> usize { MEMORY_BRIEFING_PROCEDURES_TOKENS.min(budget / 4) } /// The first sentence of a trigger: up to the first `.`, `?` or `!` (with any /// closing quote or bracket) that ends the text or is followed by a space and /// a capital or an opening quote; the whole trigger when none does. A cut /// lands only there — never inside a sentence. pub fn first_sentence(trigger: &str) -> &str { let trigger = trigger.trim_matches(crate::js::is_js_whitespace); let chars: Vec<(usize, char)> = trigger.char_indices().collect(); for (at, &(_, c)) in chars.iter().enumerate() { if !matches!(c, '.' | '?' | '!') { continue; } let mut end = at + 1; while chars.get(end).is_some_and(|&(_, c)| matches!(c, '"' | '\'' | '”' | '’' | ')' | ']')) { end += 1; } let cut = chars.get(end).map_or(trigger.len(), |&(i, _)| i); match (chars.get(end), chars.get(end + 1)) { (None, _) => return trigger, (Some(&(_, space)), Some(&(_, next))) if space == ' ' && (next.is_uppercase() || matches!(next, '"' | '“' | '`' | '(')) => { return &trigger[..cut]; } _ => {} } } trigger } /// `- · note `, or the note's name in the /// sentence's place, or `- note `: one line, because the brief advertises /// procedures and never inlines one. fn procedure_line((procedure, said): &(BriefingProcedure, Said)) -> String { match said { Said::Sentence => format!("- {} · note {}", first_sentence(&procedure.trigger), procedure.id), Said::Name => format!("- {} · note {}", procedure.title.trim(), procedure.id), Said::Id => format!("- note {}", procedure.id), } } /// The Procedures section as [`render`] writes it, for pricing. fn procedures_block(procedures: &[(BriefingProcedure, Said)]) -> Vec { if procedures.is_empty() { return Vec::new(); } let mut block = vec![ String::new(), "## Procedures".to_string(), String::new(), PROCEDURES_INSTRUCTION.to_string(), String::new(), ]; block.extend(procedures.iter().map(procedure_line)); block } /// How much each procedure (already in order) says, so the section fits in /// `share` tokens. Every id is priced first; what is left is shared out in /// order, each line taking its sentence or, failing that, its name only when it /// fits that line's fair part of what remains — so one long trigger never eats /// the room of the lines after it — then a second pass in order spends what /// the fair parts left over. When the ids alone exceed the share every line is /// its id and the share is over: an id never gives way here. fn fit_procedures(procedures: &[BriefingProcedure], share: usize) -> Vec { let mut said = vec![Said::Id; procedures.len()]; if procedures.is_empty() { return said; } // One newline joins each line to the one before it, as `render` joins. let units = |lines: &[String]| lines.iter().map(|line| utf16_len(line) + 1).sum::(); let pairs = |said: &[Said]| -> Vec<(BriefingProcedure, Said)> { procedures.iter().cloned().zip(said.iter().copied()).collect() }; let floor = units(&procedures_block(&pairs(&said))); let Some(mut slack) = (share * 4).checked_sub(floor) else { return said; }; let extra = |procedure: &BriefingProcedure, to: Said| { utf16_len(&procedure_line(&(procedure.clone(), to))) .saturating_sub(utf16_len(&procedure_line(&(procedure.clone(), Said::Id)))) }; for (at, procedure) in procedures.iter().enumerate() { let fair = slack / (procedures.len() - at); for to in [Said::Sentence, Said::Name] { let cost = extra(procedure, to); if cost <= fair { said[at] = to; slack -= cost; break; } } } for (at, procedure) in procedures.iter().enumerate() { let now = extra(procedure, said[at]); let better: &[Said] = match said[at] { Said::Sentence => &[], Said::Name => &[Said::Sentence], Said::Id => &[Said::Sentence, Said::Name], }; for &to in better { let cost = extra(procedure, to).saturating_sub(now); if cost <= slack { said[at] = to; slack -= cost; break; } } } said } /// The line that closes a project the budget cut: how many of the owner's /// entries are not shown, and the call that reads them. It stands where the /// cut is, so a session reading the list sees that it stops short rather than /// taking what it read for all there is. fn left_out_line(project: &ProjectSection) -> String { format!( "- {} more {} not shown here — read {} with `recall {{ project: \"{}\" }}`.", project.left_out, plural(project.left_out, "entry is", "entries are"), plural(project.left_out, "it", "them"), project.slug ) } fn attention_lines(dropped: Dropped, pointers: &BriefingPointers) -> Vec { let mut lines: Vec = Vec::new(); // A procedure is not a memory entry — it is a pointer at a note // `get_project` still lists — so what the budget did to it is said here. if dropped.procedures_cut > 0 { lines.push(format!( "- {} procedure {} only a name or an id, to fit — {}", dropped.procedures_cut, plural(dropped.procedures_cut, "line shows", "lines show"), pointers.every_trigger )); } if dropped.procedures > 0 { lines.push(format!( "- Budget trimmed {} procedure {} — {}", dropped.procedures, plural(dropped.procedures, "line", "lines"), pointers.every_procedure )); } lines } /// The Owner section: the owner's personal entries for this machine, whole, /// in their order, while the section stays within /// [`MEMORY_BRIEFING_OWNER_TOKENS`]; the rest are counted on a closing line /// that names the `recall` that reads them. Empty when there are none. fn owner_block(input: &BriefingInput) -> Vec { let entries = for_machine(input.owner.as_deref().unwrap_or_default(), input.machine.as_deref()); if entries.is_empty() { return Vec::new(); } let cap = MEMORY_BRIEFING_OWNER_TOKENS * 4; let head = [String::new(), "## Owner".to_string(), String::new()]; let priced = |lines: &[String]| lines.iter().map(|line| utf16_len(line) + 1).sum::(); let more = |n: usize| { format!( "- {n} more {} not shown here — read {} with `recall` in your personal database.", plural(n as i64, "entry is", "entries are"), plural(n as i64, "it", "them") ) }; let mut shown: Vec = head.to_vec(); for (at, entry) in entries.iter().enumerate() { let left = entries.len() - at - 1; let mut next = shown.clone(); next.push(line(entry)); if left > 0 { next.push(more(left)); } if priced(&next) > cap { shown.push(more(entries.len() - at)); return shown; } shown.push(line(entry)); } shown } /// What the Owner section costs with every one of `entries` in it whole — what /// the write-time cap prices, so an owner entry that would not show is refused /// rather than written and hidden. pub fn owner_section_tokens(entries: &[BriefingEntry]) -> i64 { if entries.is_empty() { return 0; } let mut lines = vec![String::new(), "## Owner".to_string(), String::new()]; lines.extend(entries.iter().map(line)); lines.iter().map(|line| utf16_len(line) as i64 + 1).sum::().div_euclid(4) + 1 } /// Render the whole briefing from already-degraded sections. fn render(input: &BriefingInput, sections: &Sections, dropped: Dropped) -> String { let pointers = input.pointers.clone().unwrap_or_default(); let owner = input .owner_name .as_deref() .map(|name| name.trim_matches(crate::js::is_js_whitespace)) .filter(|name| !name.is_empty()) .unwrap_or("the owner"); let mut parts: Vec = vec![ format!( "# Briefing for sessions working with {owner} — {}", utf16_slice(&input.generated_at, 10) ), String::new(), "Standing knowledge from Cotton memory, addressed by [slug] — cite entries by slug, never restate them.".to_string(), "Read beyond this briefing with `recall`; write a fact with `remember` (it reconciles against what exists); log your session with `log_session`.".to_string(), ]; parts.extend(owner_block(input)); if input.projects.is_empty() { parts.push(String::new()); parts.push(NO_PROJECT_LINES[0].to_string()); parts.push(pointers.find_project.clone()); } for project in §ions.projects { if project.entries.is_empty() && project.left_out == 0 { continue; } parts.push(String::new()); parts.push(format!("## Project: {}", project.name)); parts.push(String::new()); parts.extend(project.entries.iter().map(line)); if project.left_out > 0 { parts.push(left_out_line(project)); } } parts.extend(procedures_block(§ions.procedures)); let attention = attention_lines(dropped, &pointers); if !attention.is_empty() { parts.push(String::new()); parts.push("## Needs attention".to_string()); parts.push(String::new()); parts.extend(attention); } parts.join("\n") } /// Compile one briefing. Deterministic: same input, same bytes. /// /// The Procedures section is fitted to its own share first ([`fit_procedures`]). /// Degradation then removes, in order: what each procedure says beyond its id /// (last of the stable order first), procedure lines whole, and — only when /// the owner's entries alone still exceed the budget — whole entries from the /// end of their order. A procedure's id goes before any entry because every /// entry is the owner's own words. **AN ENTRY IS NEVER CUT MID-SENTENCE**: it is in the /// briefing whole or it is counted on the line that closes its project, which /// names the `recall` that reads it, and the result is flagged `over_budget`. pub fn compile_briefing(input: &BriefingInput) -> BriefingResult { compile(input, true) } /// The briefing with every entry kept, however far over the budget — what the /// write-time limit prices. A briefing that leaves entries out has hidden the /// size a new entry would add to, so the refusal compiles this instead and /// names the whole number. pub fn compile_briefing_whole(input: &BriefingInput) -> BriefingResult { compile(input, false) } fn compile(input: &BriefingInput, leave_entries_out: bool) -> BriefingResult { let budget = input.budget_tokens.unwrap_or(MEMORY_BRIEFING_BUDGET_TOKENS) as i64; let mut sections = build_sections(input); let mut dropped = Dropped::default(); let cut = |sections: &Sections| { sections.procedures.iter().filter(|(_, said)| *said != Said::Sentence).count() as i64 }; dropped.procedures_cut = cut(§ions); let mut markdown = render(input, §ions, dropped); // Procedures down to their ids: the last of the sorted list goes first, so // the ones that keep their words in a squeeze are the same ones every time. while estimate_tokens(&markdown) - budget > 0 { let Some((_, said)) = sections.procedures.iter_mut().rev().find(|(_, said)| *said != Said::Id) else { break; }; *said = Said::Id; dropped.procedures_cut = cut(§ions); markdown = render(input, §ions, dropped); } // Procedure lines whole, last first — ids give way only here, before the // owner's own words. while estimate_tokens(&markdown) - budget > 0 { if sections.procedures.pop().is_none() { break; } dropped.procedures += 1; dropped.procedures_cut = cut(§ions); markdown = render(input, §ions, dropped); } // Entries: whole ones, from the end of the last project's list, so what // survives is the head of the owner's order — pinned first. Each render // prices the closing count line too, so the cut lands under the budget // with the line that says where it is. while leave_entries_out && estimate_tokens(&markdown) - budget > 0 { let Some(project) = sections .projects .iter_mut() .rev() .find(|project| !project.entries.is_empty()) else { break; }; project.entries.pop(); project.left_out += 1; dropped.entries += 1; markdown = render(input, §ions, dropped); } let tokens_estimate = estimate_tokens(&markdown); BriefingResult { markdown, tokens_estimate, over_budget: dropped.entries > 0 || tokens_estimate - budget > 0, dropped, } } /// The `initialize.instructions` form — STATIC. /// /// Connect time has no project, and there is no project-independent layer to /// quote (a "pinned anywhere" kernel would have been the global layer under /// another name), so the kernel says how to GET the briefing rather than being /// one. It sits under the hard cap MCP clients truncate server instructions at. pub fn mini_briefing(owner_name: Option<&str>, cap_chars: usize) -> String { let owner = owner_name .map(|name| name.trim_matches(crate::js::is_js_whitespace)) .filter(|name| !name.is_empty()) .unwrap_or("the owner"); let head = format!( "Cotton is {owner}'s own database of typed records, served to the assistants they connected. How to work with them:" ); let lines = [ head, "- Start with the project this work belongs to: brief { repoUrl, machine } binds a repo to its project, or list_projects then get_project / brief { project }.".to_string(), "- recall before assuming what the owner thinks; remember (with a project) transcribes what they said; log_session at the end of a turn.".to_string(), "- Tools are data: a tool's instructions come with its definition in list_tools; read them before you write its records.".to_string(), ]; let text = lines.join("\n"); if utf16_len(&text) > cap_chars { utf16_slice(&text, cap_chars) } else { text } } /// The default cap `miniBriefing` uses when its caller names none. pub const MINI_BRIEFING_CAP_CHARS: usize = 1800; // ── Slugs ──────────────────────────────────────────────────────────────────── const SLUG_MAX: usize = 64; /// Mint a slug from a title: kebab, ≤64 chars, collision-suffixed (-2, -3, …) /// against the taken set. Deterministic for a given (title, taken). /// /// The `normalize("NFKD")` is load-bearing and comes BEFORE the kebab pass: an /// accented letter decomposes into a plain one plus a combining mark, and the /// mark is what the `[^a-z0-9]+` run then eats — so `café` slugs as `cafe` /// rather than `caf`. pub fn mint_memory_slug(title: &str, taken: &BTreeSet) -> String { static NON_SLUG: LazyLock = LazyLock::new(|| Regex::new(r"[^a-z0-9]+").expect("a valid pattern")); static EDGE_DASHES: LazyLock = LazyLock::new(|| Regex::new(r"^-+|-+$").expect("a valid pattern")); static TRAILING_DASHES: LazyLock = LazyLock::new(|| Regex::new(r"-+$").expect("a valid pattern")); let lowered = title.to_lowercase(); let decomposed: String = lowered.nfkd().collect(); let kebab = NON_SLUG.replace_all(&decomposed, "-"); let trimmed = EDGE_DASHES.replace_all(&kebab, ""); let capped = utf16_slice(&trimmed, SLUG_MAX); let base = TRAILING_DASHES.replace_all(&capped, "").into_owned(); // `|| "entry"` — an empty string is falsy in JavaScript. let base = if base.is_empty() { "entry".to_string() } else { base }; if !taken.contains(&base) { return base; } let mut n = 2u32; loop { let suffix = format!("-{n}"); let candidate = format!("{}{suffix}", utf16_slice(&base, SLUG_MAX - suffix.len())); if !taken.contains(&candidate) { return candidate; } n += 1; } } // ── Secrets never enter memory ─────────────────────────────────────────────── /// The credential shapes a memory entry may never carry, each with the sentence /// a refusal names. static SECRET_PATTERNS: LazyLock> = LazyLock::new(|| { let compile = |pattern: &str| Regex::new(pattern).expect("a valid pattern"); vec![ ( compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), SecretKind::PrivateKey, ), ( compile(r"(?-u:\b)sk-[A-Za-z0-9_-]{16,}"), SecretKind::ApiKey, ), ( compile(r"(?-u:\b)ctn_[A-Za-z0-9_-]{16,}"), SecretKind::CottonToken, ), // An assistant was handed this one in plaintext by // `register_feedback_app`, so it is the credential most likely to be // quoted back into a sentence somebody tries to remember. That tool is // retired and no new `cfi_` exists — this stays for the ones that may // already be written down (see `redact.rs`). ( compile(r"(?-u:\b)cfi_[A-Za-z0-9_-]{16,}"), SecretKind::FeedbackToken, ), ( compile(r"(?-u:\b)gh[pousr]_[A-Za-z0-9]{16,}"), SecretKind::GitHubToken, ), ( compile(r"(?-u:\b)github_pat_[A-Za-z0-9_]{20,}"), SecretKind::GitHubToken, ), ( compile(r"(?-u:\b)xox[baprs]-[A-Za-z0-9-]{10,}"), SecretKind::SlackToken, ), ( compile(r"(?-u:\b)AKIA[0-9A-Z]{16}(?-u:\b)"), SecretKind::AwsKeyId, ), ( compile(r"(?-u:\b)eyJ[A-Za-z0-9_-]{30,}\.[A-Za-z0-9_-]{10,}"), SecretKind::Jwt, ), ] }); /// The kind of credential a sentence appears to hold, as a typed fact; the /// refusal names it in the database's `refusal` lines (`memory.secret`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SecretKind { PrivateKey, ApiKey, CottonToken, FeedbackToken, GitHubToken, SlackToken, AwsKeyId, Jwt, HighEntropy, } impl SecretKind { /// The refusal line that names this kind: a kind's NAME, never a secret's value. #[must_use] pub const fn line_key(self) -> &'static str { match self { SecretKind::PrivateKey => "memory.secret.private_key", SecretKind::ApiKey => "memory.secret.api_key", SecretKind::CottonToken => "memory.secret.cotton_token", SecretKind::FeedbackToken => "memory.secret.feedback_token", SecretKind::GitHubToken => "memory.secret.github_token", SecretKind::SlackToken => "memory.secret.slack_token", SecretKind::AwsKeyId => "memory.secret.aws_key_id", SecretKind::Jwt => "memory.secret.jwt", SecretKind::HighEntropy => "memory.secret.high_entropy", } } } /// A long, whitespace-free, digit-and-letter run that is not a URL or a path /// reads as credential material. /// /// Conservative on purpose: uuids (36 chars) and file paths (which contain `/` /// or `.`) pass. `-` and `=` are BOUNDARIES, not run characters — the /// 2026-08-20 import tripped on a 43-char kebab slug and an `ENV_VAR=1` /// assignment, which are everyday memory content; a hyphenated base64url token /// that slips this catch-all is still caught by the JWT and vendor patterns. static HIGH_ENTROPY: LazyLock = LazyLock::new(|| { Regex::new("(?:^|[\\s\"'`(=:-])([A-Za-z0-9_+]{40,})(?:$|[\\s\"'`)=-])") .expect("a valid pattern") }); /// What the text appears to contain when it looks like a credential, or `None` /// when it reads clean. /// /// Callers refuse the write and NAME the reason — a silent scrub would hide /// that an agent tried to store a secret. (The complement of /// cotton-core's `transforms::redact::redact_secrets`, which cuts rather than refuses, /// because a session log is a record of what was said.) pub fn looks_like_secret(text: &str) -> Option { for (pattern, reason) in SECRET_PATTERNS.iter() { if pattern.is_match(text) { return Some(*reason); } } let run = HIGH_ENTROPY .captures(text) .and_then(|caps| caps.get(1)) .map(|m| m.as_str()); if let Some(run) = run { if run.bytes().any(|b| b.is_ascii_digit()) && run.bytes().any(|b| b.is_ascii_alphabetic()) { return Some(SecretKind::HighEntropy); } } None } // ── Similarity (propose-time dedup) ────────────────────────────────────────── fn bigrams(text: &str) -> BTreeSet { static NON_WORD: LazyLock = LazyLock::new(|| Regex::new(r"[^a-z0-9 ]+").expect("a valid pattern")); static RUNS: LazyLock = LazyLock::new(|| Regex::new(r"\s+").expect("a valid pattern")); let lowered = text.to_lowercase(); let spaced = NON_WORD.replace_all(&lowered, " "); let collapsed = RUNS.replace_all(&spaced, " "); let normalized = collapsed.trim_matches(crate::js::is_js_whitespace); // Everything that survives is ASCII, so bytes, chars and UTF-16 units all // agree from here on. let bytes = normalized.as_bytes(); let mut grams = BTreeSet::new(); for window in bytes.windows(2) { grams.insert(String::from_utf8_lossy(window).into_owned()); } grams } /// Dice coefficient over character bigrams — the propose-time "does a similar /// entry already exist" measure. /// /// Engine-side rather than a database index so the app's preview and the /// server cannot disagree about what counts as similar, and so it is /// exhaustively testable. 0..1; two empty titles are 0. pub fn title_similarity(a: &str, b: &str) -> f64 { let ga = bigrams(a); let gb = bigrams(b); if ga.is_empty() || gb.is_empty() { return 0.0; } let shared = ga.iter().filter(|gram| gb.contains(*gram)).count() as f64; (2.0 * shared) / (ga.len() + gb.len()) as f64 } /// The propose-time threshold: above it, propose answers "update [slug] /// instead" rather than minting a near-duplicate. pub const MEMORY_SIMILARITY_THRESHOLD: f64 = 0.55; // ── Repo URL normalisation ─────────────────────────────────────────────────── /// One spelling for a repo across every way git states it: /// `https://github.com/a/b.git`, `git@github.com:a/b.git`, /// `ssh://git@github.com/a/b` → `github.com/a/b`. /// /// The projects table stores this form; the briefing normalises the caller's /// remote before matching. pub fn normalize_repo_url(raw: &str) -> String { static PROTOCOL: LazyLock = LazyLock::new(|| Regex::new(r"^[a-z+]+://").expect("a valid pattern")); static USER: LazyLock = LazyLock::new(|| Regex::new(r"^[^@/]+@").expect("a valid pattern")); static DOUBLE_SLASH: LazyLock = LazyLock::new(|| Regex::new(r"/{2,}").expect("a valid pattern")); static DOT_GIT: LazyLock = LazyLock::new(|| Regex::new(r"\.git$").expect("a valid pattern")); static TRAILING_SLASH: LazyLock = LazyLock::new(|| Regex::new(r"/+$").expect("a valid pattern")); let lowered = raw .trim_matches(crate::js::is_js_whitespace) .to_lowercase(); let no_protocol = PROTOCOL.replace(&lowered, ""); let no_user = USER.replace(&no_protocol, ""); // `replace(":", "/")` with a STRING argument replaces the FIRST colon only // — a second one survives, which is why this is `replacen`, not a regex. let scp = no_user.replacen(':', "/", 1); let single_slashes = DOUBLE_SLASH.replace_all(&scp, "/"); let no_dot_git = DOT_GIT.replace(&single_slashes, ""); TRAILING_SLASH.replace(&no_dot_git, "").into_owned() } /// A project, as much of it as repo matching reads. pub trait HasRepos { fn repos(&self) -> &[String]; } /// The active projects whose repo list carries the caller's remote. pub fn projects_for_repo<'a, T: HasRepos>(projects: &'a [T], repo_url: &str) -> Vec<&'a T> { let normalized = normalize_repo_url(repo_url); if normalized.is_empty() { return Vec::new(); } projects .iter() .filter(|project| { project .repos() .iter() .any(|repo| normalize_repo_url(repo) == normalized) }) .collect() } #[cfg(test)] #[path = "memory_briefing_tests.rs"] mod tests;