From f7841a8185933ca3e41c69339c1851ec74d9ea50 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 17:09:59 -0500 Subject: [PATCH 1/3] Her view's floor is one fold block, not the sum of every pointer she ever held On the M5 (2026-10-29 22:00Z), after #5595 kept a record for every saved result, Aris's view held 97 results with 2 whole: ~95 pointers x ~190 chars (~4.5k tokens) of floor before anything whole fit, growing with every act. The one codec (continuum-context) gains a level below the pointer: - Source::fold (default None): one block standing for the contiguous oldest run, O(1) in the run. A source without it floors at its pointers as before. - view/allot.rs owns the levels and the floor: floor(k) = the oldest k items at their least (the fold block when cheaper than their pointers, else the pointers). Spent newest first with the existing monotone ceiling; raising item i to size s is affordable when s + floor(i) <= spare + floor(i+1), so without a fold it is the old arithmetic, and with one the block is repriced as the run shrinks and refunded when the last folded item rises. - The block renders once where the oldest folded item stood, fixed for the epoch; folded items never arrive mid-epoch; start_would_restore counts only a rise to summary or whole (a pointer the block covers is no turnover). - Claim.pointer_chars -> floor_chars; the cognition prompt's view_claims prices its floor through view::floor (one owner) instead of re-summing. - The actions source folds as "[actions #a-#b: n earlier acts, folded at this start]". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/context_streams/actions.rs | 11 ++ .../src/cognition/context_streams/tests.rs | 15 ++ .../llm_deliberation_faculty/prompt/epoch.rs | 7 +- .../a_busy_room_keeps_its_prefix.rs | 4 +- core/continuum-context/examples/replay.rs | 2 +- core/continuum-context/src/source.rs | 9 + core/continuum-context/src/view.rs | 145 +++++++--------- core/continuum-context/src/view/allot.rs | 151 +++++++++++++++++ core/continuum-context/src/view/tests.rs | 156 +++++++++++++++++- .../MIND-CONTEXT-AND-ENGINE-CONFIG.md | 10 +- 10 files changed, 414 insertions(+), 96 deletions(-) create mode 100644 core/continuum-context/src/view/allot.rs diff --git a/core/continuum-cognition/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs index 913e5d1cc5..64282c3069 100644 --- a/core/continuum-cognition/src/cognition/context_streams/actions.rs +++ b/core/continuum-cognition/src/cognition/context_streams/actions.rs @@ -87,6 +87,17 @@ impl Source for Actions<'_> { Some(ContextMessage::user(format!("{label}{body}"))) } + /// Her oldest acts as one line: the first and last `#n` and how many, so her floor is one + /// block however many acts she has taken (Aris, the M5, 2026-10-29: 95 pointers at ~190 + /// chars before anything whole fit). The banner folds with them; the line says what it is. + /// `None` for a run with no act in it (the banner alone): nothing to name. + fn fold(&self, folded: &[Item]) -> Option { + let mut acts = folded.iter().filter_map(|item| item.key.parse::().ok()); + let first = acts.next()?; + let (last, count) = acts.fold((first, 1_usize), |(_, count), seq| (seq, count + 1)); + Some(ContextMessage::user(format!("[actions #{first}-#{last}: {count} earlier acts, folded at this start]"))) + } + /// Once she has acted, the void said earlier in this epoch is superseded, never edited: /// her view reads as the timeline it is (the statement was true when it was made). fn retired(&self) -> Vec> { diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index 62b64ce156..9294f95596 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -166,3 +166,18 @@ fn a_thought_renders_the_same_whatever_the_served_window() { memory.set_served_window(131_072); assert_eq!(render(&memory), narrow, "the window changed and the thought's rendering did not"); } + +// what this catches: her floor growing with every act she ever took (Aris, the M5, 2026-10-29: +// 95 pointers at ~190 chars before anything whole fit). Her oldest acts fold into ONE line that +// names the first and last #n and how many, never a list of ids; the banner folds with them, and +// a run with no act in it has nothing to name. +#[test] +fn her_folded_acts_name_their_range_and_count_in_one_line() { + let memory = WorkingMemory::new(2); + let actions = Actions { memory: &memory, persona: uuid::Uuid::nil() }; + let item = |key: &str| continuum_context::source::Item::whole(key, super::ContextMessage::user(format!("act {key}"))); + let run: Vec<_> = std::iter::once(item("banner")).chain((3200..=3330).map(|seq: u64| item(&seq.to_string()))).collect(); + let Some(block) = actions.fold(&run) else { panic!("a run with acts folds") }; + assert_eq!(block.text, "[actions #3200-#3330: 131 earlier acts, folded at this start]"); + assert!(actions.fold(&[item("banner")]).is_none(), "the banner alone has no act to name"); +} diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs index f33acc0f6c..71df6e69d2 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/epoch.rs @@ -52,7 +52,7 @@ impl LlmDeliberationFaculty { /// Her view's sources as claims in the window's one allocation, each `view/`, /// priced in the unit the final fit charges ([`Self::message_cost`], template overhead - /// included): floor = the source collapsed, want = the source whole, at the source's + /// included): floor = the source folded or collapsed, want = the source whole, at the source's /// priority. There is no separate history claim for the view, so the allocation that /// weighs her reply also decides, once, how much of her context she reads. pub(in super::super) fn view_claims(&self, streams: &Streams) -> Vec { @@ -63,7 +63,9 @@ impl LlmDeliberationFaculty { .map(|source| { let items = source.items(); let cost = |message: &ContextMessage| Self::message_cost(&message.to_chat()); - let floor: usize = items.iter().map(|item| item.pointer.as_ref().map_or(0, cost)).sum(); // map_or: an item that leaves when collapsed costs nothing + // Its floor from the view's one owner: one fold block when the source folds its + // oldest run, else each item's pointer, so the allocation prices the true floor. + let floor = continuum_context::view::floor(source, &items, cost); // An item's WHOLE level, stored or resident (`whole_chars`): a body evicted from RAM // is priced from its measured size, never as the pointer resident in its place, // or the allocation would never grant room to see it (FOCUS-CONTRACT rule 7). @@ -313,6 +315,7 @@ impl LlmDeliberationFaculty { epoch = start.epoch, start_chars = start.chars, collapsed_items = start.collapsed, + folded_items = start.folded, "her view started a new epoch: the one re-prefill an epoch costs, collapsed \ by the flexbox at its start" ); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs index eeb31beda1..516804949a 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/a_busy_room_keeps_its_prefix.rs @@ -53,8 +53,8 @@ fn window_plan(claims: &[Claim], window: u32) -> FlexAllocation { .map(|claim| RagSourceBudget { source_id: format!("view/{}", claim.source), priority: claim.priority, - floor_tokens: claim.pointer_chars as u32, - min_tokens: claim.pointer_chars as u32, + floor_tokens: claim.floor_chars as u32, + min_tokens: claim.floor_chars as u32, max_tokens: claim.full_chars as u32, required: false, }) diff --git a/core/continuum-context/examples/replay.rs b/core/continuum-context/examples/replay.rs index dc62e25b2a..700f60e996 100644 --- a/core/continuum-context/examples/replay.rs +++ b/core/continuum-context/examples/replay.rs @@ -135,7 +135,7 @@ fn item(key: String, text: String) -> Item { /// goes to sources by priority level, highest first, sources of one level sharing in /// proportion to what each wants. (In the core this is `flex_allocate`.) fn allocate(claims: &[continuum_context::view::Claim], budget: usize) -> Vec { - let mut grants: Vec = claims.iter().map(|claim| claim.pointer_chars).collect(); + let mut grants: Vec = claims.iter().map(|claim| claim.floor_chars).collect(); let mut spare = budget.saturating_sub(grants.iter().sum()); let mut levels: Vec = claims.iter().map(|claim| claim.priority).collect(); levels.sort_unstable_by(|a, b| b.cmp(a)); diff --git a/core/continuum-context/src/source.rs b/core/continuum-context/src/source.rs index fa5c90f157..62360e0273 100644 --- a/core/continuum-context/src/source.rs +++ b/core/continuum-context/src/source.rs @@ -82,6 +82,15 @@ pub trait Source { fn load(&self, _item: &Item) -> Option { None } + + /// One block standing for `folded`, the contiguous oldest run of this source's items at a + /// start: the range it covers and how to reopen one, its length independent of the run's + /// (never a list of ids). The view folds the run only when this block costs less than the + /// run's pointers, so a source's floor stops growing with every item it ever held. Fixed + /// for the epoch it starts. The default cannot fold: its items floor at their pointers. + fn fold(&self, _folded: &[Item]) -> Option { + None + } } /// What an item's whole level costs: its stored size when the whole is not resident, else diff --git a/core/continuum-context/src/view.rs b/core/continuum-context/src/view.rs index 4dc338d6a9..4f953ff94b 100644 --- a/core/continuum-context/src/view.rs +++ b/core/continuum-context/src/view.rs @@ -2,9 +2,10 @@ //! //! Within an epoch every act only appends: the items whose rendering changed. Turnover is //! the only rewrite. At a start the caller's one allocator grants each source a character -//! budget between its floor (every item collapsed to its pointer) and its want (every item -//! in full); the view spends it newest first, each item at the most detail that fits: whole, -//! its summary (a coarser level, like a mipmap), or its pointer. Those choices hold for the +//! budget between its floor (its items folded into one block when the source folds, else +//! each collapsed to its pointer) and its want (every item in full); the view spends it newest +//! first, each item at the most detail that fits: whole, its summary (a coarser level, like a +//! mipmap), its pointer, or folded with the oldest run. Those choices hold for the //! epoch, and an item that arises mid-epoch (her next act's result) arrives in full unless //! the act's admission ([`View::readmit`]) gives it a coarser level. So collapse happens once, at a start, never as a //! cut in the middle of an epoch. WHEN to turn over (the window filling, a revocation, a @@ -17,14 +18,23 @@ use crate::epoch::{Block, Epoch, Mark, Observed, SourceId}; use crate::motion::{fingerprint, Motion}; use crate::source::{Item, Source}; +mod allot; + +use allot::{allot, rank, Level}; +pub use allot::floor; + +/// The item key a source's fold block is observed under: no source keys an item with it. +const FOLD_KEY: &str = "(folded)"; + /// One source as the allocator sees it at an epoch start. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Claim { pub source: String, pub priority: u8, - /// What the source costs with every item collapsed to its pointer: its floor. - pub pointer_chars: usize, - /// What the source costs in full: its want. + /// What the source costs at its least ([`floor`]): one fold block when the source folds + /// its items, else every item collapsed to its pointer. + pub floor_chars: usize, + /// What the source costs in full: its want. A folded item still wants its whole. pub full_chars: usize, /// Its newest item in full: the newest end a start never collapses when it fits. pub newest_chars: usize, @@ -61,6 +71,8 @@ pub struct Start { pub collapsed: usize, /// Items the grants rendered at their summary for this epoch. pub summarized: usize, + /// Items the grants folded into their source's one block for this epoch. + pub folded: usize, } /// Serializable, so a mind's view survives her restart with the rest of her volatile state: @@ -73,6 +85,10 @@ pub struct View { /// Items rendered as their summary for this epoch. Absent in a view saved before levels. #[serde(default)] summarized: HashSet, + /// Items inside their source's fold block for this epoch: they never arrive on their own + /// until a start raises them. Absent in a view saved before folding. + #[serde(default)] + folded: HashSet, /// Characters each act of this epoch appended, in order. appended: Vec, /// How each source moved across this view's starts; carried over every turnover and @@ -89,86 +105,11 @@ fn key(source: &str, item: &str) -> SourceId { SourceId(format!("{source}/{item}")) } -fn pointer_chars(item: &Item) -> usize { - item.pointer.as_ref().map_or(0, Block::chars) // map_or: an item that leaves when collapsed costs nothing -} - -/// How much of an item the view renders: whole, its summary, or its pointer. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Level { - Full, - Summary, - Pointer, -} - -/// How much of an item a level shows, for comparing two levels of one item. -fn rank(level: &Level) -> u8 { - match level { - Level::Pointer => 0, - Level::Summary => 1, - Level::Full => 2, - } -} - -/// The level a `grant` of characters gives each item. Every item starts at its pointer (the -/// floor); what the grant leaves above it is spent newest first, each item taking the most -/// detail that still fits, and never more detail than the item after it: shrinking is oldest -/// first (goal 7), so an older item is never kept more whole than a newer one. -/// -/// One item too large to keep whole takes its summary instead of collapsing every older item -/// to a line with it (a 51,827-char file read that ended the run left Aiko nothing of it, so -/// she read it whole 9 times in 43 acts, the M5, 2026-10-25). It still caps the older ones: -/// filling them past it doubled the size of every start (median 14,238 -> 27,696 chars) and -/// the median act went 83-111 s -> 140 s under the same eleven residents (canary 28bf81fa7 vs -/// 3cd34f87c, the M5, 2026-10-25 17:00-18:06Z). -fn levels(items: &[Item], grant: usize) -> Vec { - let floor: usize = items.iter().map(pointer_chars).sum(); - let mut spare = grant.saturating_sub(floor); - let mut levels = vec![Level::Pointer; items.len()]; - let mut ceiling = Level::Full; - for (item, level) in items.iter().zip(levels.iter_mut()).rev() { - // A level replaces the item's pointer, already paid in the floor: it is affordable when - // its size fits the spare plus that pointer, and what it leaves is spare + pointer - size. - // An item smaller than its own pointer gives the difference back instead of losing it. - let pointer = pointer_chars(item); - let full = crate::source::whole_chars(item); - let summary = item.summary.as_ref().map(Block::chars); - let afford = |size: usize, spare: usize| size <= spare + pointer; - if ceiling == Level::Full && afford(full, spare) { - spare = spare + pointer - full; - *level = Level::Full; - continue; - } - if ceiling == Level::Summary || ceiling == Level::Full { - match summary { - Some(summary) if afford(summary, spare) => { - spare = spare + pointer - summary; - *level = Level::Summary; - ceiling = Level::Summary; - continue; - } - // An item with no smaller level is its own summary: under a summary ceiling a - // short result stays whole when it fits, and the ceiling holds. Without this a - // short result older than one big read fell to its pointer and collapsed every - // older item with it (Cormac on #5426). - None if ceiling == Level::Summary && afford(full, spare) => { - spare = spare + pointer - full; - *level = Level::Full; - continue; - } - _ => {} - } - } - ceiling = Level::Pointer; - } - levels -} - fn claim(source: &dyn Source, items: &[Item]) -> Claim { Claim { source: source.name().to_owned(), priority: source.priority(), - pointer_chars: items.iter().map(pointer_chars).sum(), + floor_chars: floor(source, items, Block::chars), full_chars: items.iter().map(crate::source::whole_chars).sum(), newest_chars: items.last().map_or(0, crate::source::whole_chars), // map_or: a source with no items has no newest end } @@ -217,6 +158,9 @@ impl View { /// her items stayed collapsed while the window had room for them (Aiko, the M5, 2026-10-29: /// her last fifteen results as handles in a 42k-char prompt on a 55k-token window). This is /// the turnover that gives them back. + /// Only a rise to a summary or whole earns it: a folded item that would rise only to its + /// pointer is not a restore, or every act that could afford one more pointer would turn the + /// view over and lose the prefix for a line the fold block already covers (Cormac). /// An allocator that answers for a different number of sources is the same refusal a start /// gives ([`GrantMismatch`]), never a quiet "nothing to restore" (Codex on #5564). pub fn start_would_restore(&self, sources: &[&dyn Source], allocate: impl FnOnce(&[Claim]) -> Vec) -> Result { @@ -228,15 +172,18 @@ impl View { return Err(GrantMismatch { claims: claims.len(), grants: grants.len() }); } Ok(sources.iter().zip(&offered).zip(&grants).any(|((source, items), grant)| { - levels(items, *grant).iter().zip(items).any(|(level, item)| { + allot(&**source, items, *grant).levels.iter().zip(items).any(|(level, item)| { let id = key(source.name(), &item.key); - self.epoch.holds(&id) && rank(level) > rank(&self.held_level(&id)) + let held = self.epoch.holds(&id) || self.folded.contains(&id); + held && rank(level) > rank(&self.held_level(&id)) && rank(level) > rank(&Level::Pointer) }) })) } fn held_level(&self, id: &SourceId) -> Level { - if self.collapsed.contains(id) { + if self.folded.contains(id) { + Level::Folded + } else if self.collapsed.contains(id) { Level::Pointer } else if self.summarized.contains(id) { Level::Summary @@ -265,12 +212,13 @@ impl View { epoch: Epoch::new(id, head), collapsed: HashSet::new(), summarized: HashSet::new(), + folded: HashSet::new(), appended: Vec::new(), motion: Motion::default(), act: None, }; for ((source, items), grant) in sources.iter().zip(offered).zip(grants) { - let levels = levels(&items, grant); + let allot::Allotment { levels, mut fold } = allot(&**source, &items, grant); let mut rendered = Vec::with_capacity(items.len()); for (item, level) in items.into_iter().zip(levels) { let id = key(source.name(), &item.key); @@ -285,6 +233,16 @@ impl View { view.collapsed.insert(id.clone()); item.pointer } + // The run is the contiguous oldest: its block renders once, where its oldest + // item stood, naming the range it held at this start for the whole epoch. + Level::Folded => { + view.folded.insert(id); + if let Some(block) = fold.take() { + rendered.push((fingerprint(FOLD_KEY, &block), block.chars())); + view.epoch.observe(key(source.name(), FOLD_KEY), block); + } + continue; + } }; if let Some(text) = text { rendered.push((fingerprint(&item_key, &text), text.chars())); @@ -294,7 +252,13 @@ impl View { motion.record(source.name(), rendered); } view.motion = motion; - let start = Start { epoch: id, chars: view.epoch.chars(), collapsed: view.collapsed.len(), summarized: view.summarized.len() }; + let start = Start { + epoch: id, + chars: view.epoch.chars(), + collapsed: view.collapsed.len(), + summarized: view.summarized.len(), + folded: view.folded.len(), + }; Ok((view, start)) } @@ -347,6 +311,11 @@ impl View { for source in sources { for item in source.items() { let id = key(source.name(), &item.key); + // A folded item is held by its source's fold block, fixed at the start: it + // arrives on its own only when a later start raises it (the prefix never moves). + if self.folded.contains(&id) { + continue; + } // An item with no pointer would leave her view entirely if collapsed (a peer's // new turn), so it always arrives whole: admission never drops what she has // not seen. @@ -368,7 +337,7 @@ impl View { let text = match level { Level::Full => Some(crate::source::whole(&**source, item)), Level::Summary => item.summary.or(item.pointer), - Level::Pointer => item.pointer, + Level::Pointer | Level::Folded => item.pointer, }; if let Some(text) = text { let chars = text.chars(); diff --git a/core/continuum-context/src/view/allot.rs b/core/continuum-context/src/view/allot.rs new file mode 100644 index 0000000000..800a64f9a1 --- /dev/null +++ b/core/continuum-context/src/view/allot.rs @@ -0,0 +1,151 @@ +//! Which level each item of one source renders at under a start's grant, and what its floor is. +//! +//! The floor of a source is what its items cost at their least: one fold block for the whole +//! run when the source folds them ([`Source::fold`]) and the block costs less than their +//! pointers, else each item's pointer. A floor that is a sum of pointers grows with every act +//! she ever takes (Aris on the M5, 2026-10-29 22:00Z: 97 results in her view, 2 whole, ~95 +//! pointers at ~190 chars each, ~4.5k tokens before anything whole fit); one block does not. + +use crate::epoch::Block; +use crate::source::{whole_chars, Item, Source}; + +/// How much of an item the view renders: whole, its summary, its pointer, or inside its +/// source's one fold block with the rest of the oldest run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Level { + Full, + Summary, + Pointer, + Folded, +} + +/// How much of an item a level shows, for comparing two levels of one item. +pub(super) fn rank(level: &Level) -> u8 { + match level { + Level::Folded => 0, + Level::Pointer => 1, + Level::Summary => 2, + Level::Full => 3, + } +} + +/// What a start gives one source: each item's level, and the fold block that renders the +/// items at [`Level::Folded`] (the contiguous oldest run), `Some` exactly when one is folded. +pub(super) struct Allotment { + pub levels: Vec, + pub fold: Option, +} + +/// The oldest run `run` at its floor, priced by `cost`, given what its pointers cost: the +/// source's fold block when it has one cheaper than those pointers, else the pointers (`None`). +fn run_floor( + source: &(impl Source + ?Sized), + run: &[Item], + pointers: usize, + cost: &impl Fn(&T) -> usize, +) -> (usize, Option) { + if run.is_empty() { + return (0, None); + } + match source.fold(run) { + Some(block) if cost(&block) < pointers => (cost(&block), Some(block)), + _ => (pointers, None), + } +} + +/// What `items` of `source` cost at their floor, in the unit `cost` prices a block in: the one +/// owner of a source's floor, for the view's own claim and any caller pricing it in tokens. +pub fn floor( + source: &(impl Source + ?Sized), + items: &[Item], + cost: impl Fn(&T) -> usize, +) -> usize { + let pointers = items + .iter() + .map(|item| item.pointer.as_ref().map_or(0, &cost)) + .sum(); // map_or: an item that leaves when collapsed costs nothing + run_floor(source, items, pointers, &cost).0 +} + +/// The level a `grant` of characters gives each item. Every item starts at the floor (folded +/// with the rest when its source folds, else its pointer); what the grant leaves above it is +/// spent newest first, each item taking the most detail that still fits, and never more detail +/// than the item after it: shrinking is oldest first (goal 7), so an older item is never kept +/// more whole than a newer one, and the folded items are always the contiguous oldest run. +/// +/// The arithmetic: `floor(k)` is what the oldest `k` items cost at their floor. With item `i` +/// still in the run, what it and every older item may cost is `spare + floor(i + 1)`; raising +/// it to a level of `size` leaves the older run at `floor(i)`, so it is affordable when +/// `size + floor(i) <= spare + floor(i + 1)`, and leaves that difference as the new spare. +/// Without a fold `floor(i + 1) - floor(i)` is the item's own pointer, the arithmetic before +/// folding; with one, the run's block is repriced as it shrinks and refunded whole when the +/// last folded item rises. The first item that cannot afford even its pointer stops the walk: +/// it and everything older stay at their floor. +/// +/// One item too large to keep whole takes its summary instead of collapsing every older item +/// to a line with it (a 51,827-char file read that ended the run left Aiko nothing of it, so +/// she read it whole 9 times in 43 acts, the M5, 2026-10-25). It still caps the older ones: +/// filling them past it doubled the size of every start (median 14,238 -> 27,696 chars) and +/// the median act went 83-111 s -> 140 s under the same eleven residents (canary 28bf81fa7 vs +/// 3cd34f87c, the M5, 2026-10-25 17:00-18:06Z). +pub(super) fn allot( + source: &(impl Source + ?Sized), + items: &[Item], + grant: usize, +) -> Allotment { + let cost = |block: &T| block.chars(); + let mut pointers = Vec::with_capacity(items.len() + 1); + pointers.push(0); + for item in items { + let below = pointers[pointers.len() - 1]; + pointers.push(below + item.pointer.as_ref().map_or(0, Block::chars)); // map_or: an item that leaves when collapsed costs nothing + } + let floor = |count: usize| run_floor(source, &items[..count], pointers[count], &cost); + let mut levels = vec![Level::Pointer; items.len()]; + let (mut paid, _) = floor(items.len()); + let mut spare = grant.saturating_sub(paid); + let mut ceiling = Level::Full; + let mut run = items.len(); + while run > 0 { + let item = &items[run - 1]; + let (below, _) = floor(run - 1); + let budget = spare + paid; + let afford = |size: usize| size + below <= budget; + let full = whole_chars(item); + let summary = item.summary.as_ref().map(Block::chars); + let rise = if ceiling == Level::Full && afford(full) { + Some((Level::Full, full)) + } else if ceiling == Level::Summary || ceiling == Level::Full { + match summary { + Some(summary) if afford(summary) => Some((Level::Summary, summary)), + // An item with no smaller level is its own summary: under a summary ceiling a + // short result stays whole when it fits, and the ceiling holds. Without this a + // short result older than one big read fell to its pointer and collapsed every + // older item with it (Cormac on #5426). + None if ceiling == Level::Summary && afford(full) => Some((Level::Full, full)), + _ => None, + } + } else { + None + }; + let pointer = item.pointer.as_ref().map_or(0, Block::chars); // map_or: an item that leaves when collapsed costs nothing + let Some((level, size)) = + rise.or_else(|| afford(pointer).then_some((Level::Pointer, pointer))) + else { + break; + }; + // An item with no smaller level holds the summary ceiling it rose under. + if level != Level::Full || ceiling != Level::Summary { + ceiling = level; + } + levels[run - 1] = level; + spare = budget - below - size; + paid = below; + run -= 1; + } + let (_, fold) = floor(run); + if fold.is_some() { + levels[..run].fill(Level::Folded); + } + Allotment { levels, fold } +} diff --git a/core/continuum-context/src/view/tests.rs b/core/continuum-context/src/view/tests.rs index a99dff30f4..46bc0ca5c9 100644 --- a/core/continuum-context/src/view/tests.rs +++ b/core/continuum-context/src/view/tests.rs @@ -199,7 +199,7 @@ fn a_restored_view_renders_the_same_bytes_and_keeps_appending() { let mut actions = Fake::new("actions", 1); actions.push("#1", &"x".repeat(9_000)); actions.push("#2", "short"); - let (mut view, _) = View::start(vec!["head".into()], &[&actions], |claims| vec![claims[0].pointer_chars + 10]).unwrap(); + let (mut view, _) = View::start(vec!["head".into()], &[&actions], |claims| vec![claims[0].floor_chars + 10]).unwrap(); view.advance(&[&actions]); let saved = serde_json::to_string(&view).unwrap(); let mut restored: View = serde_json::from_str(&saved).unwrap(); @@ -415,7 +415,159 @@ fn an_evicted_body_is_priced_whole_and_rendered_whole_when_granted() -> Result<( assert_eq!(claims[0].full_chars, body.chars() + "an older result".to_owned().chars()); let (view, _) = View::start(Vec::new(), &[&spilled], all_full)?; assert!(rendered(&view).contains(&body), "granted whole, it renders the loaded body"); - let (tight, _) = View::start(Vec::new(), &[&spilled], |claims: &[Claim]| claims.iter().map(|c| c.pointer_chars).collect())?; + let (tight, _) = View::start(Vec::new(), &[&spilled], |claims: &[Claim]| claims.iter().map(|c| c.floor_chars).collect())?; assert!(!rendered(&tight).contains(&body) && rendered(&tight).contains("reopen by its handle"), "granted only its floor, it is its pointer"); Ok(()) } + +/// A source shaped like her actions after #5595 kept a record for every saved result: numbered +/// items, each with a ~190-char pointer, folding its oldest run into one line. +struct Folding { + items: Vec<(u64, String, Option)>, +} + +impl Folding { + fn new(count: u64, size: usize) -> Self { + Self { items: (1..=count).map(|seq| (seq, "r".repeat(size), None)).collect() } + } + fn push(&mut self, size: usize) { + let seq = self.items.len() as u64 + 1; + self.items.push((seq, "r".repeat(size), None)); + } + fn pointers(&self) -> usize { + self.items().iter().map(|item| item.pointer.as_ref().map_or(0, String::len)).sum() + } +} + +impl Source for Folding { + fn name(&self) -> &str { + "actions" + } + fn priority(&self) -> u8 { + 1 + } + fn items(&self) -> Vec> { + self.items + .iter() + .map(|(seq, full, summary)| Item { + key: seq.to_string(), + full: full.clone(), + summary: summary.clone(), + pointer: Some(format!("[result #{seq}; room r; operation code/read; output handle: tool/output {seq:0>16} — collapsed; {}]", "p".repeat(80))), + stored: None, + }) + .collect() + } + fn fold(&self, folded: &[Item]) -> Option { + let first = folded.first()?; + let last = folded.last()?; + Some(format!("[actions #{}-#{}: {} earlier acts, folded at this start]", first.key, last.key, folded.len())) + } +} + +fn fold_blocks(view: &View) -> usize { + view.render().filter(|text| text.starts_with("[actions #")).count() +} + +// what this catches: a floor that is the sum of every pointer she ever held (Aris, the M5, +// 2026-10-29 22:00Z: 97 results, 2 whole, ~95 pointers x ~190 chars before anything whole fit). +// A grant far below that sum still shows her newest items whole, and the oldest run is ONE block, +// rendered where its oldest item stood; the claim's floor is that block, its want every whole. +#[test] +fn a_hundred_results_under_a_tight_grant_fold_into_one_block_and_the_newest_stay_whole() -> Result<(), GrantMismatch> { + let actions = Folding::new(100, 1_000); + let claim = &claims(&[&actions])[0]; + assert!(claim.floor_chars < 100, "the floor is one block, not {} chars of pointers", actions.pointers()); + assert_eq!(claim.full_chars, 100 * 1_000, "a folded item still wants its whole"); + let grant = claim.floor_chars + 3 * 1_000; + assert!(grant < actions.pointers()); + let (view, start) = View::start(Vec::new(), &[&actions], |_| vec![grant])?; + let shown: Vec = view.render().cloned().collect(); + assert_eq!(fold_blocks(&view), 1); + assert!(shown[0].starts_with("[actions #1-#97: 97 earlier acts"), "{}", shown[0]); + assert_eq!(&shown[1..], ["r".repeat(1_000), "r".repeat(1_000), "r".repeat(1_000)]); + assert_eq!((start.folded, start.collapsed), (97, 0)); + assert!(view.chars() <= grant); + assert!(!view.renders("actions", "1"), "a folded item is not read"); + Ok(()) +} + +// what this catches: an older item kept more detailed than a newer one under any grant (goal 7: +// shrink oldest first), which with folding would leave a fold block AFTER a pointer or a whole. +// Under every grant from the floor to the whole, the folded items are the oldest run and the +// pointers the run after it. (Above the pointer an item with no summary is its own summary, so +// a short whole may sit older than a big read's outline; that rule is tested above.) +#[test] +fn no_folded_item_is_newer_than_a_pointer_summary_or_whole_item() -> Result<(), GrantMismatch> { + let mut actions = Folding::new(0, 0); + for size in [400, 3_000, 250, 9_000, 600, 1_200, 300, 5_000, 700, 450] { + actions.push(size); + } + for (index, item) in actions.items.iter_mut().enumerate() { + if index % 3 == 1 { + item.2 = Some("s".repeat(item.1.len() / 5)); + } + } + let claim = &claims(&[&actions])[0]; + for grant in (claim.floor_chars..=claim.full_chars).step_by(97) { + let (view, _) = View::start(Vec::new(), &[&actions], |_| vec![grant])?; + let ranks: Vec = actions.items().iter().map(|item| rank(&view.held_level(&key("actions", &item.key))).min(rank(&Level::Summary))).collect(); + assert!(ranks.windows(2).all(|pair| pair[0] <= pair[1]), "grant {grant}: levels oldest -> newest {ranks:?}"); + assert!(fold_blocks(&view) <= 1); + } + Ok(()) +} + +// what this catches: folding changing a source that never opted in. Without a fold its floor is +// the sum of its pointers and a floor grant collapses every item to its pointer, as before. +#[test] +fn a_source_without_a_fold_floors_at_the_sum_of_its_pointers() -> Result<(), GrantMismatch> { + let mut actions = Fake::new("actions", 1); + for act in 1..=5 { + actions.push(&format!("#{act}"), &"r".repeat(1_000)); + } + let pointers: usize = actions.items().iter().map(|item| item.pointer.as_ref().map_or(0, String::len)).sum(); + assert_eq!(claims(&[&actions])[0].floor_chars, pointers); + let (view, start) = View::start(Vec::new(), &[&actions], |_| vec![pointers])?; + assert_eq!((start.collapsed, start.folded), (5, 0)); + assert_eq!(view.chars(), pointers); + Ok(()) +} + +// what this catches: a squeezed start keeping her results folded while a later window has room +// for them whole, and the opposite churn (Cormac): a start that would raise folded items only to +// their pointers is not a restore, or every act that affords one more pointer turns the view over +// and loses the prefix for a line the fold block already covers. +#[test] +fn only_a_rise_past_the_pointer_restores_what_a_squeezed_start_folded() -> Result<(), GrantMismatch> { + let actions = Folding::new(20, 100_000); + let floor = claims(&[&actions])[0].floor_chars; + let (view, start) = View::start(Vec::new(), &[&actions], |_| vec![floor])?; + assert_eq!(start.folded, 20, "a floor grant folds the whole run"); + let pointers = actions.pointers(); + let (pointed, _) = View::start(Vec::new(), &[&actions], |_| vec![pointers])?; + assert_eq!(fold_blocks(&pointed), 0, "precondition: the pointer grant raises every item to its pointer"); + assert!(!view.start_would_restore(&[&actions], |_| vec![pointers])?, "pointers only: no turnover"); + assert!(view.start_would_restore(&[&actions], all_full)?, "room for them whole: a start gives them back"); + Ok(()) +} + +// what this catches: the fold block rewriting itself act to act (it is fixed at its start, so +// the prefix holds), a folded item arriving on its own mid-epoch, and a floor that grows with her +// next result (Cormac). One more act appends one result, keeps the floor one block of the same +// size, and under the same grant is no reason to turn over. +#[test] +fn an_act_appends_one_result_and_neither_turns_over_nor_grows_the_floor() -> Result<(), GrantMismatch> { + let mut actions = Folding::new(100, 1_000); + let floor = claims(&[&actions])[0].floor_chars; + let grant = floor + 3 * 1_000; + let (mut view, _) = View::start(Vec::new(), &[&actions], |_| vec![grant])?; + let before = rendered(&view); + actions.push(1_000); + assert_eq!(view.advance(&[&actions]), Advance { items: 1, chars: 1_000 }); + assert!(rendered(&view).starts_with(&before), "the act rewrote the prefix"); + assert_eq!(fold_blocks(&view), 1, "the fold block is not re-rendered mid-epoch"); + assert_eq!(claims(&[&actions])[0].floor_chars, floor, "one more act, the same one-block floor"); + assert!(!view.start_would_restore(&[&actions], |_| vec![grant])?, "the same grant restores nothing"); + Ok(()) +} diff --git a/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md b/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md index 77420fbe77..8a9df4a95f 100644 --- a/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md +++ b/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md @@ -246,6 +246,13 @@ layer is a context `Source`: - **Levels of detail on every item:** `full`, `summary` (an outline, a digest, a thumbnail: a mipmap level) and `pointer`. A `pointer` is an EXPAND HANDLE that a positron command resolves back to `full`. An item whose pointer cannot be expanded is a defect, not a level. +- **A fold below the pointer** (`Source::fold`, optional): the contiguous OLDEST run of a source's + items as ONE block naming its range and count (O(1) in the run, never a list of ids). The + source's floor is that block, not the sum of its pointers, so a floor never grows with every + act she takes (Aris, the M5, 2026-10-29: ~95 pointers at ~190 chars before anything whole fit). + The block is fixed at its start; folded items never arrive mid-epoch; a later start restores + them only for a rise to summary or whole, never for a pointer the block already covers. Like a + pointer, a fold must name how one of its items reopens. - **The same items for humans and minds.** A human renderer and a mind's view consume one layer at the level each can afford. Screen frames, video and 3D state follow later as items too. @@ -303,7 +310,8 @@ surface, observed back through her eyes and ears. set `required` only for input she must read. 2. `items()` returns one `Item` per subject, under a key that names that whole subject. Build its `summary` with `continuum_context::levels::summarize(full, Shape::…)` (`Code` with the producer's - line parser, `Output`, `List`). Its `pointer` names the handle that expands it. + line parser, `Output`, `List`). Its `pointer` names the handle that expands it. A source + whose items accumulate (her acts) implements `fold` so its floor is one block. 3. Add the source to the view's source list. Never push a prompt message, never collapse, never pick an order: the view appends, levels, admits, orders by measured motion and turns over. 4. Prove it with a fixture in the source's test mod, then with the replay validator. From 71c59369cc94bf7b216aa7db997349d301f52861 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 17:14:40 -0500 Subject: [PATCH 2/3] A folded act reopens by its number: tool/output takes act, and the fold says so Folding her oldest acts into "#a-#b" hid each act's handle, and tool/output took only an outputId, so a folded act could not be reopened (goal 7: the full result stays reachable). - tool/output takes exactly one of outputId or act. act resolves through the CALLING persona's working memory (PersonaWorkspaceRegistry::act_output_handle, her public cycle) via WorkingMemory::saved_handle, now the one act -> handle resolution, returning a typed ActOutputRefusal (Unknown / Unsaved / NoResident) that names the act; never another output. Help, schema doc and the generated ToolOutputParams.ts say so. Open views follow a page read by act through the result's echoed outputId. - The actions fold reads "[actions #a-#b: n earlier acts folded; reopen one with tool/output act=]", fixed per epoch, O(1) in the run. - Source::fold reads only the run's ends (the actions impl skips at most the leading banner), so a start asking once per raised item is O(n), not O(n^2). - Fold-or-pointers is decided once, in chars (view::allot fold_of); view::floor prices that decision in the caller's unit, so view_claims (tokens) and the view never disagree about which rendering is the floor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/context_streams/actions.rs | 21 +-- .../src/cognition/context_streams/tests.rs | 6 +- .../prompt/newest_result.rs | 2 +- .../src/cognition/open_views.rs | 7 +- .../src/cognition/persona_workspace.rs | 1 + .../cognition/persona_workspace/act_output.rs | 25 ++++ .../src/cognition/working_memory.rs | 1 + .../cognition/working_memory/action_log.rs | 15 +++ .../cognition/working_memory/perception.rs | 12 +- core/continuum-context/src/source.rs | 3 +- core/continuum-context/src/view/allot.rs | 42 +++--- core/continuum-context/src/view/tests.rs | 2 +- .../src/commands/tool/output.rs | 124 ++++++++++++++++-- .../MIND-CONTEXT-AND-ENGINE-CONFIG.md | 2 +- protocol/typescript/tool/ToolOutputParams.ts | 11 +- 15 files changed, 221 insertions(+), 53 deletions(-) create mode 100644 core/continuum-cognition/src/cognition/persona_workspace/act_output.rs diff --git a/core/continuum-cognition/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs index 64282c3069..152b4b4164 100644 --- a/core/continuum-cognition/src/cognition/context_streams/actions.rs +++ b/core/continuum-cognition/src/cognition/context_streams/actions.rs @@ -87,15 +87,20 @@ impl Source for Actions<'_> { Some(ContextMessage::user(format!("{label}{body}"))) } - /// Her oldest acts as one line: the first and last `#n` and how many, so her floor is one - /// block however many acts she has taken (Aris, the M5, 2026-10-29: 95 pointers at ~190 - /// chars before anything whole fit). The banner folds with them; the line says what it is. - /// `None` for a run with no act in it (the banner alone): nothing to name. + /// Her oldest acts as one line: the first and last `#n`, how many, and how one reopens + /// (`tool/output` with `act`), so her floor is one block however many acts she has taken + /// (Aris, the M5, 2026-10-29: 95 pointers at ~190 chars before anything whole fit). Reads + /// only the run's ends: the banner, when it is in the run, is its first item and folds + /// with it. `None` for a run with no act in it (the banner alone): nothing to name. fn fold(&self, folded: &[Item]) -> Option { - let mut acts = folded.iter().filter_map(|item| item.key.parse::().ok()); - let first = acts.next()?; - let (last, count) = acts.fold((first, 1_usize), |(_, count), seq| (seq, count + 1)); - Some(ContextMessage::user(format!("[actions #{first}-#{last}: {count} earlier acts, folded at this start]"))) + let banner = usize::from(folded.first().is_some_and(|item| item.key.parse::().is_err())); + let acts = &folded[banner..]; + let first: u64 = acts.first()?.key.parse().ok()?; + let last: u64 = acts.last()?.key.parse().ok()?; + let count = acts.len(); + Some(ContextMessage::user(format!( + "[actions #{first}-#{last}: {count} earlier acts folded; reopen one with tool/output act=]" + ))) } /// Once she has acted, the void said earlier in this epoch is superseded, never edited: diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index 9294f95596..7d60dbf9df 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -169,8 +169,8 @@ fn a_thought_renders_the_same_whatever_the_served_window() { // what this catches: her floor growing with every act she ever took (Aris, the M5, 2026-10-29: // 95 pointers at ~190 chars before anything whole fit). Her oldest acts fold into ONE line that -// names the first and last #n and how many, never a list of ids; the banner folds with them, and -// a run with no act in it has nothing to name. +// names the first and last #n, how many, and how one reopens (tool/output act=), never a list +// of ids; the banner folds with them, and a run with no act in it has nothing to name. #[test] fn her_folded_acts_name_their_range_and_count_in_one_line() { let memory = WorkingMemory::new(2); @@ -178,6 +178,6 @@ fn her_folded_acts_name_their_range_and_count_in_one_line() { let item = |key: &str| continuum_context::source::Item::whole(key, super::ContextMessage::user(format!("act {key}"))); let run: Vec<_> = std::iter::once(item("banner")).chain((3200..=3330).map(|seq: u64| item(&seq.to_string()))).collect(); let Some(block) = actions.fold(&run) else { panic!("a run with acts folds") }; - assert_eq!(block.text, "[actions #3200-#3330: 131 earlier acts, folded at this start]"); + assert_eq!(block.text, "[actions #3200-#3330: 131 earlier acts folded; reopen one with tool/output act=]"); assert!(actions.fold(&[item("banner")]).is_none(), "the banner alone has no act to name"); } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/newest_result.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/newest_result.rs index 24bbe1877b..2eaddf46ef 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/newest_result.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/newest_result.rs @@ -80,7 +80,7 @@ impl LlmDeliberationFaculty { } let Some(memory) = self.working_memory.as_ref() else { return false }; let Some((seq, _)) = memory.active_action_full() else { return false }; - let Some(handle) = memory.saved_handle(seq) else { + let Ok(handle) = memory.saved_handle(seq) else { continuum_base::probe!( class = "delib.newest_result.unsaved_over_window", persona = %self.persona_name, diff --git a/core/continuum-cognition/src/cognition/open_views.rs b/core/continuum-cognition/src/cognition/open_views.rs index a04f6db59f..389fda856b 100644 --- a/core/continuum-cognition/src/cognition/open_views.rs +++ b/core/continuum-cognition/src/cognition/open_views.rs @@ -163,7 +163,11 @@ impl OpenViews { /// touches that file's view: its line numbers are the saved result's, which open with a /// header line, not the file's. fn note_output_page(&mut self, act: &Observation, seq: u64) -> bool { - let Some(handle) = act.call.input.get("outputId").and_then(|v| v.as_str()) else { + let header = crate::cognition::tool_executor::spill::result_scalars(&act.output.result.content); + // The output she named, or, for a call by act number, the one the result echoes. + let named = act.call.input.get("outputId").and_then(|v| v.as_str()); + let echoed = header.as_ref().and_then(|h| h.get("outputId")?.as_str()); + let Some(handle) = named.or(echoed) else { return false; }; let Some(index) = self.views.iter().position(|v| { @@ -175,7 +179,6 @@ impl OpenViews { let mut view = self.views.remove(index); view.touched_seq = seq; if act.completed_successfully() && matches!(view.subject, ViewSubject::Output { .. }) { - let header = crate::cognition::tool_executor::spill::result_scalars(&act.output.result.content); let total = header.as_ref().and_then(|h| h.get("totalLines")?.as_u64()).and_then(|n| u32::try_from(n).ok()); let truncated = header.as_ref().and_then(|h| h.get("truncated")?.as_bool()).unwrap_or(true); // unwrap_or: a page that does not say it came back whole is not counted as read let line = |key: &str| act.call.input.get(key)?.as_u64().and_then(|n| u32::try_from(n).ok()); diff --git a/core/continuum-cognition/src/cognition/persona_workspace.rs b/core/continuum-cognition/src/cognition/persona_workspace.rs index ece912881f..ef9c8369a0 100644 --- a/core/continuum-cognition/src/cognition/persona_workspace.rs +++ b/core/continuum-cognition/src/cognition/persona_workspace.rs @@ -43,6 +43,7 @@ use crate::cognition::rag_budget::RagSource; /// owner's schema, native path, and cross-process checkpoint exclusion. pub mod checkpoint_adoption; +mod act_output; mod rehome; pub use rehome::RehomeReason; diff --git a/core/continuum-cognition/src/cognition/persona_workspace/act_output.rs b/core/continuum-cognition/src/cognition/persona_workspace/act_output.rs new file mode 100644 index 0000000000..470c868ae6 --- /dev/null +++ b/core/continuum-cognition/src/cognition/persona_workspace/act_output.rs @@ -0,0 +1,25 @@ +//! A resident's act number resolved to its saved output, for `tool/output` called with `act`. +//! Her folded acts name only their range ("#a-#b"), so the number is the handle she holds. + +use std::sync::Arc; + +use uuid::Uuid; + +use super::PersonaWorkspaceRegistry; +use crate::cognition::working_memory::ActOutputRefusal; + +impl PersonaWorkspaceRegistry { + /// The saved-output handle of `persona`'s act `act`, through her public cycle's working + /// memory, the record her view's actions source numbers. Her mind cycle keeps its own + /// record and is not consulted: its acts are not in the view that folds them. + pub fn act_output_handle(&self, persona: Uuid, act: u64) -> Result { + let memory = self + .cycles + .lock() + .get(&persona) + .map(|resident| Arc::clone(&resident.working_memory)); + memory + .ok_or(ActOutputRefusal::NoResident { act })? + .saved_handle(act) + } +} diff --git a/core/continuum-cognition/src/cognition/working_memory.rs b/core/continuum-cognition/src/cognition/working_memory.rs index 3aefa0de79..1962dff658 100644 --- a/core/continuum-cognition/src/cognition/working_memory.rs +++ b/core/continuum-cognition/src/cognition/working_memory.rs @@ -716,6 +716,7 @@ mod ledger; mod perception; mod residency; +pub use action_log::ActOutputRefusal; pub use faculty::WorkingMemoryFaculty; pub(crate) use faculty::render_dispatched; pub(crate) use ledger::operation_level; diff --git a/core/continuum-cognition/src/cognition/working_memory/action_log.rs b/core/continuum-cognition/src/cognition/working_memory/action_log.rs index e91fdf3793..e37245f979 100644 --- a/core/continuum-cognition/src/cognition/working_memory/action_log.rs +++ b/core/continuum-cognition/src/cognition/working_memory/action_log.rs @@ -16,6 +16,21 @@ use uuid::Uuid; /// handle keeps it live and stays in the log (`receipt_keys`, `prune`). const POINTER_INDEX: usize = 12; +/// Why an act number does not reopen a saved output (`tool/output` with `act`): a typed +/// refusal naming the act, never a fallback to some other output. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ActOutputRefusal { + /// No record of hers carries this number. + #[error("act #{act} is not on your record; use a #n your view names")] + Unknown { act: u64 }, + /// The act is on record but its save failed: what her view showed of it is all there is. + #[error("act #{act} has no saved output: its save failed, so what your view showed of it is all there is")] + Unsaved { act: u64 }, + /// The caller has no resident mind whose record could resolve the number. + #[error("act #{act} cannot be resolved: no resident mind runs for this caller")] + NoResident { act: u64 }, +} + #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub(crate) struct ActionRecord { pub seq: u64, diff --git a/core/continuum-cognition/src/cognition/working_memory/perception.rs b/core/continuum-cognition/src/cognition/working_memory/perception.rs index 8ea1ce91ce..73cf063c74 100644 --- a/core/continuum-cognition/src/cognition/working_memory/perception.rs +++ b/core/continuum-cognition/src/cognition/working_memory/perception.rs @@ -127,10 +127,14 @@ impl WorkingMemory { format!("Full result of your most recent action ({attribution}):\n{full}") } - /// The handle the saved whole of act `seq` is reopened by (`tool/output`), `None` when its - /// save failed: such a result has no other copy, so it is never shown as less than whole. - pub(crate) fn saved_handle(&self, seq: u64) -> Option { - self.actions.lock().get(seq).and_then(|record| record.handle.clone()) + /// The handle the saved whole of act `seq` is reopened by (`tool/output`, by handle or by + /// `act`): the one resolution of an act number to its saved output. A refusal when no + /// record carries `seq`, or when its save failed: such a result has no other copy, so it + /// is never shown as less than whole. + pub fn saved_handle(&self, seq: u64) -> Result { + let actions = self.actions.lock(); + let record = actions.get(seq).ok_or(ActOutputRefusal::Unknown { act: seq })?; + record.handle.clone().ok_or(ActOutputRefusal::Unsaved { act: seq }) } /// The provenance of the act whose native results the turn carries: `[result #n; room …; diff --git a/core/continuum-context/src/source.rs b/core/continuum-context/src/source.rs index 62360e0273..b22be1952a 100644 --- a/core/continuum-context/src/source.rs +++ b/core/continuum-context/src/source.rs @@ -85,7 +85,8 @@ pub trait Source { /// One block standing for `folded`, the contiguous oldest run of this source's items at a /// start: the range it covers and how to reopen one, its length independent of the run's - /// (never a list of ids). The view folds the run only when this block costs less than the + /// (never a list of ids). It reads only the run's ends, O(1) in the run: a start asks once + /// per item it raises. The view folds the run only when this block is smaller than the /// run's pointers, so a source's floor stops growing with every item it ever held. Fixed /// for the epoch it starts. The default cannot fold: its items floor at their pointers. fn fold(&self, _folded: &[Item]) -> Option { diff --git a/core/continuum-context/src/view/allot.rs b/core/continuum-context/src/view/allot.rs index 800a64f9a1..dcd13b9465 100644 --- a/core/continuum-context/src/view/allot.rs +++ b/core/continuum-context/src/view/allot.rs @@ -36,35 +36,43 @@ pub(super) struct Allotment { pub fold: Option, } -/// The oldest run `run` at its floor, priced by `cost`, given what its pointers cost: the -/// source's fold block when it has one cheaper than those pointers, else the pointers (`None`). -fn run_floor( +/// The fold block standing for the oldest run `run` when its source folds it and the block +/// is smaller than the run's pointers (`pointer_chars`), else `None`: the run floors at its +/// pointers. Decided once, in chars (the view's unit), so the view and every caller pricing +/// the floor in another unit ([`floor`]) price the same rendering. `Source::fold` reads only +/// the run's ends, so asking it once per item a start raises is O(1) each. +fn fold_of( source: &(impl Source + ?Sized), run: &[Item], - pointers: usize, - cost: &impl Fn(&T) -> usize, -) -> (usize, Option) { + pointer_chars: usize, +) -> Option { if run.is_empty() { - return (0, None); - } - match source.fold(run) { - Some(block) if cost(&block) < pointers => (cost(&block), Some(block)), - _ => (pointers, None), + return None; } + source + .fold(run) + .filter(|block| block.chars() < pointer_chars) } /// What `items` of `source` cost at their floor, in the unit `cost` prices a block in: the one /// owner of a source's floor, for the view's own claim and any caller pricing it in tokens. +/// Whether the floor is the fold block or the pointers is [`fold_of`]'s decision, the view's. pub fn floor( source: &(impl Source + ?Sized), items: &[Item], cost: impl Fn(&T) -> usize, ) -> usize { - let pointers = items + let pointer_chars = items .iter() - .map(|item| item.pointer.as_ref().map_or(0, &cost)) + .map(|item| item.pointer.as_ref().map_or(0, Block::chars)) .sum(); // map_or: an item that leaves when collapsed costs nothing - run_floor(source, items, pointers, &cost).0 + match fold_of(source, items, pointer_chars) { + Some(block) => cost(&block), + None => items + .iter() + .map(|item| item.pointer.as_ref().map_or(0, &cost)) + .sum(), // map_or: as above + } } /// The level a `grant` of characters gives each item. Every item starts at the floor (folded @@ -93,14 +101,16 @@ pub(super) fn allot( items: &[Item], grant: usize, ) -> Allotment { - let cost = |block: &T| block.chars(); let mut pointers = Vec::with_capacity(items.len() + 1); pointers.push(0); for item in items { let below = pointers[pointers.len() - 1]; pointers.push(below + item.pointer.as_ref().map_or(0, Block::chars)); // map_or: an item that leaves when collapsed costs nothing } - let floor = |count: usize| run_floor(source, &items[..count], pointers[count], &cost); + let floor = |count: usize| match fold_of(source, &items[..count], pointers[count]) { + Some(block) => (block.chars(), Some(block)), + None => (pointers[count], None), + }; let mut levels = vec![Level::Pointer; items.len()]; let (mut paid, _) = floor(items.len()); let mut spare = grant.saturating_sub(paid); diff --git a/core/continuum-context/src/view/tests.rs b/core/continuum-context/src/view/tests.rs index 46bc0ca5c9..4e7c1241e6 100644 --- a/core/continuum-context/src/view/tests.rs +++ b/core/continuum-context/src/view/tests.rs @@ -461,7 +461,7 @@ impl Source for Folding { fn fold(&self, folded: &[Item]) -> Option { let first = folded.first()?; let last = folded.last()?; - Some(format!("[actions #{}-#{}: {} earlier acts, folded at this start]", first.key, last.key, folded.len())) + Some(format!("[actions #{}-#{}: {} earlier acts folded; reopen one by #n]", first.key, last.key, folded.len())) } } diff --git a/core/continuum-core/src/commands/tool/output.rs b/core/continuum-core/src/commands/tool/output.rs index c14f20370d..22eb072993 100644 --- a/core/continuum-core/src/commands/tool/output.rs +++ b/core/continuum-core/src/commands/tool/output.rs @@ -71,8 +71,8 @@ impl OutputFilter { } } -/// Inputs to `tool/output`. `outputId` is required (from the preview); everything -/// else selects WHAT to pull back. +/// Inputs to `tool/output`. Exactly one of `outputId` (from the preview) or `act` (one of +/// her act numbers); everything else selects WHAT to pull back. #[derive(Debug, Clone, Default, Serialize, Deserialize, TS, JsonSchema)] #[serde(rename_all = "camelCase")] #[ts( @@ -87,7 +87,13 @@ pub struct ToolOutputParams { // name and refuses a string for it (`expected struct HandleRef`) — so the call the // spill-recovery hint told every citizen to make could not be made (card ea28d2f6). #[serde(rename = "outputId")] - pub handle: String, + #[ts(optional)] + pub handle: Option, + /// One of your act numbers (the `#n` your actions name, folded ones included), in + /// place of `outputId`: reopens that act's saved output. Give exactly one of the two. + #[ts(optional)] + #[ts(type = "number")] + pub act: Option, /// A PREBUILT filter — the easy path, no regex needed: `errors` (what broke?), /// `warnings`, `failures` (which tests failed?), or `summary` (how did it end?). /// Start here on a flooded build/test log. Overridden by an explicit `pattern`. @@ -189,7 +195,8 @@ impl ActionCommand for ToolOutput { &["read_output", "grep_output", "tail_output", "search_output"]; const DESCRIPTION: &'static str = "Page or grep a large tool result that was saved to disk because it was too big \ - to show in full. Pass the `outputId` from the elision marker. EASIEST: set \ + to show in full. Pass the `outputId` from the elision marker, OR `act` with one of \ + your act numbers (the #n your actions name, folded ones included). EASIEST: set \ `filter` to a prebuilt preset — `errors` (what broke?), `warnings`, `failures` \ (which tests failed?), or `summary` (how did it end?) — no regex needed. For a \ specific hunt use `pattern` (a regex, e.g. \"error\\[E0308\\]\"). Or read an \ @@ -204,7 +211,7 @@ impl ActionCommand for ToolOutput { async fn run( &self, ctx: &Ctx, - params: ToolOutputParams, + mut params: ToolOutputParams, ) -> Result { // WHO is asking — a spilled output belongs to the persona that produced // it, and the directory layout enforces that. No caller = no scope. @@ -218,7 +225,10 @@ impl ActionCommand for ToolOutput { ) })?; - let path = spill::resolve(persona_id, ¶ms.handle) + let act_handle = + |act| crate::cognition::persona_workspace::global().act_output_handle(persona_id, act); + let handle = named_output(params.handle.take(), params.act, act_handle)?; + let path = spill::resolve(persona_id, &handle) .map_err(|e| CommandError::Invalid(e.to_string()))?; let range = match (params.start_line, params.end_line) { (Some(s), Some(e)) => Some((s, e)), @@ -250,7 +260,7 @@ impl ActionCommand for ToolOutput { } // Disk scanning belongs off the async executor. The same spill owner handles // both views; no second content registry or private whole-file retrieval path. - tokio::task::spawn_blocking(move || read_saved(&path, params, range, budget)) + tokio::task::spawn_blocking(move || read_saved(&path, handle, params, range, budget)) .await .map_err(|e| CommandError::Invalid(format!("saved output reader failed: {e}")))? .map_err(CommandError::Invalid) @@ -258,8 +268,29 @@ impl ActionCommand for ToolOutput { } crate::register_stateless_command!(ToolOutput); +/// The saved output a call names: its `outputId`, or her act number resolved by `act_handle` +/// (her working memory's record). Exactly one; an act that does not resolve is its typed +/// refusal, never another output. +fn named_output( + handle: Option, + act: Option, + act_handle: impl FnOnce(u64) -> Result, +) -> Result { + match (handle, act) { + (Some(handle), None) => Ok(handle), + (None, Some(act)) => { + act_handle(act).map_err(|refusal| CommandError::Invalid(refusal.to_string())) + } + _ => Err(CommandError::Invalid( + "give exactly one of outputId (from the preview) or act (one of your act numbers)" + .into(), + )), + } +} + fn read_saved( path: &std::path::Path, + handle: String, params: ToolOutputParams, range: Option<(usize, usize)>, budget: usize, @@ -267,7 +298,7 @@ fn read_saved( if let Some(offset) = params.byte_offset { let extent = spill::read_extent(&path, offset, params.byte_length, budget)?; return Ok(ToolOutputResult { - handle: params.handle, + handle, total_lines: None, total_bytes: usize::try_from(extent.total_bytes) .map_err(|_| "saved output length exceeds this platform")?, @@ -293,7 +324,7 @@ fn read_saved( budget, )?; Ok(ToolOutputResult { - handle: params.handle, + handle, total_lines: Some(inv.total_lines), total_bytes: inv.total_bytes, total_matches: Some(inv.total_matches), @@ -356,7 +387,7 @@ mod tests { .run( &Ctx::default(), ToolOutputParams { - handle: "deadbeefcafe0001".into(), + handle: Some("deadbeefcafe0001".into()), ..Default::default() }, ) @@ -365,6 +396,73 @@ mod tests { assert!(matches!(err, CommandError::Invalid(_))); } + // what this catches: a folded act she cannot reopen. Her folded acts name only "#a-#b", so + // `act` must reach exactly the output its handle does (resolved through her working memory's + // record), and an act with no record or no saved output is a typed refusal naming the act, + // never some other output. + #[test] + fn an_act_number_reopens_what_its_handle_does_and_an_unknown_or_unsaved_act_refuses() { + use crate::ai::types::ResultCustody; + use crate::cognition::working_memory::WorkingMemory; + let memory = WorkingMemory::new(8); + memory.record_receipt_typed( + &[], + "saved result", + None, + ResultCustody::Whole { + handle: "h1".into(), + }, + ); + memory.record_receipt_typed(&[], "unsaved result", None, ResultCustody::Unsaved); + let Ok(dir) = tempfile::tempdir() else { + panic!("a temp dir for the saved output") + }; + let path = dir.path().join("h1"); + assert!(std::fs::write(&path, "line one\nerror here\nline three\n").is_ok()); + let Ok(by_act) = named_output(None, Some(1), |act| memory.saved_handle(act)) else { + panic!("act #1 was saved") + }; + let Ok(by_handle) = named_output(Some("h1".into()), None, |act| memory.saved_handle(act)) + else { + panic!("a handle names itself") + }; + assert_eq!(by_act, by_handle); + let read = + |handle: String| read_saved(&path, handle, ToolOutputParams::default(), None, 4_096); + let (Ok(act_read), Ok(handle_read)) = (read(by_act), read(by_handle)) else { + panic!("the saved output reads back") + }; + assert_eq!( + (act_read.content, act_read.handle), + (handle_read.content, handle_read.handle) + ); + for (act, says) in [ + (2, "act #2 has no saved output"), + (99, "act #99 is not on your record"), + ] { + match named_output(None, Some(act), |act| memory.saved_handle(act)) { + Err(CommandError::Invalid(refusal)) => { + assert!(refusal.starts_with(says), "{refusal}") + } + other => panic!("act #{act} must refuse, got {other:?}"), + } + } + assert!( + matches!( + named_output(Some("h1".into()), Some(1), |act| memory.saved_handle(act)), + Err(CommandError::Invalid(_)) + ), + "both: refused" + ); + assert!( + matches!( + named_output(None, None, |act| memory.saved_handle(act)), + Err(CommandError::Invalid(_)) + ), + "neither: refused" + ); + } + // what this catches: the real command projection preserves exact byte continuation, // split UTF-8 and whole-file regex counts without loading the retained file in memory. #[test] @@ -379,8 +477,8 @@ mod tests { loop { let result = read_saved( &path, + "id".into(), ToolOutputParams { - handle: "id".into(), byte_offset: Some(offset), byte_length: Some(2), ..Default::default() @@ -413,8 +511,8 @@ mod tests { assert_eq!(actual, body.as_bytes()); let result = read_saved( &path, + "id".into(), ToolOutputParams { - handle: "id".into(), pattern: Some("error".into()), context_lines: Some(0), max_matches: Some(1), @@ -436,8 +534,8 @@ mod tests { std::fs::write(&path, "x".repeat(257)).unwrap(); let error = read_saved( &path, + "id".into(), ToolOutputParams { - handle: "id".into(), pattern: Some("never".into()), ..Default::default() }, diff --git a/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md b/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md index 8a9df4a95f..83ede13cfc 100644 --- a/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md +++ b/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md @@ -252,7 +252,7 @@ layer is a context `Source`: act she takes (Aris, the M5, 2026-10-29: ~95 pointers at ~190 chars before anything whole fit). The block is fixed at its start; folded items never arrive mid-epoch; a later start restores them only for a rise to summary or whole, never for a pointer the block already covers. Like a - pointer, a fold must name how one of its items reopens. + pointer, a fold must name how one of its items reopens (her acts: `tool/output` with `act`). - **The same items for humans and minds.** A human renderer and a mind's view consume one layer at the level each can afford. Screen frames, video and 3D state follow later as items too. diff --git a/protocol/typescript/tool/ToolOutputParams.ts b/protocol/typescript/tool/ToolOutputParams.ts index 97f6d757c3..19e655f51e 100644 --- a/protocol/typescript/tool/ToolOutputParams.ts +++ b/protocol/typescript/tool/ToolOutputParams.ts @@ -2,15 +2,20 @@ import type { OutputFilter } from "./OutputFilter"; /** - * Inputs to `tool/output`. `outputId` is required (from the preview); everything - * else selects WHAT to pull back. + * Inputs to `tool/output`. Exactly one of `outputId` (from the preview) or `act` (one of + * her act numbers); everything else selects WHAT to pull back. */ export type ToolOutputParams = { /** * The output id from the elision marker (e.g. `"deadbeefcafe0001"`). This is * the spill the preview told you was saved. */ -outputId: string, +outputId?: string, +/** + * One of your act numbers (the `#n` your actions name, folded ones included), in + * place of `outputId`: reopens that act's saved output. Give exactly one of the two. + */ +act?: number, /** * A PREBUILT filter — the easy path, no regex needed: `errors` (what broke?), * `warnings`, `failures` (which tests failed?), or `summary` (how did it end?). From ac74f0122293c7010bbaf9ab6d6cedb7836b0555 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 17:46:02 -0500 Subject: [PATCH 3/3] The view never folds a standing head: her [actions] banner stays at the front, so a turnover keeps the settled prefix; the fold run is the oldest acts after it Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- .../src/cognition/context_streams/actions.rs | 10 +-- .../src/cognition/context_streams/tests.rs | 7 ++- core/continuum-context/src/view/allot.rs | 61 ++++++++++++++----- 3 files changed, 55 insertions(+), 23 deletions(-) diff --git a/core/continuum-cognition/src/cognition/context_streams/actions.rs b/core/continuum-cognition/src/cognition/context_streams/actions.rs index 152b4b4164..95c7deaffd 100644 --- a/core/continuum-cognition/src/cognition/context_streams/actions.rs +++ b/core/continuum-cognition/src/cognition/context_streams/actions.rs @@ -93,11 +93,11 @@ impl Source for Actions<'_> { /// only the run's ends: the banner, when it is in the run, is its first item and folds /// with it. `None` for a run with no act in it (the banner alone): nothing to name. fn fold(&self, folded: &[Item]) -> Option { - let banner = usize::from(folded.first().is_some_and(|item| item.key.parse::().is_err())); - let acts = &folded[banner..]; - let first: u64 = acts.first()?.key.parse().ok()?; - let last: u64 = acts.last()?.key.parse().ok()?; - let count = acts.len(); + // The banner stands as itself ahead of the run (the view never folds a standing head), + // so the run is her acts alone, keyed by their #n. + let first: u64 = folded.first()?.key.parse().ok()?; + let last: u64 = folded.last()?.key.parse().ok()?; + let count = folded.len(); Some(ContextMessage::user(format!( "[actions #{first}-#{last}: {count} earlier acts folded; reopen one with tool/output act=]" ))) diff --git a/core/continuum-cognition/src/cognition/context_streams/tests.rs b/core/continuum-cognition/src/cognition/context_streams/tests.rs index 7d60dbf9df..140ad873a7 100644 --- a/core/continuum-cognition/src/cognition/context_streams/tests.rs +++ b/core/continuum-cognition/src/cognition/context_streams/tests.rs @@ -170,14 +170,15 @@ fn a_thought_renders_the_same_whatever_the_served_window() { // what this catches: her floor growing with every act she ever took (Aris, the M5, 2026-10-29: // 95 pointers at ~190 chars before anything whole fit). Her oldest acts fold into ONE line that // names the first and last #n, how many, and how one reopens (tool/output act=), never a list -// of ids; the banner folds with them, and a run with no act in it has nothing to name. +// of ids. The banner stands ahead of the run (the view never folds a standing head), so the +// run is acts alone; a run whose keys are not act numbers names nothing rather than a guess. #[test] fn her_folded_acts_name_their_range_and_count_in_one_line() { let memory = WorkingMemory::new(2); let actions = Actions { memory: &memory, persona: uuid::Uuid::nil() }; let item = |key: &str| continuum_context::source::Item::whole(key, super::ContextMessage::user(format!("act {key}"))); - let run: Vec<_> = std::iter::once(item("banner")).chain((3200..=3330).map(|seq: u64| item(&seq.to_string()))).collect(); + let run: Vec<_> = (3200..=3330).map(|seq: u64| item(&seq.to_string())).collect(); let Some(block) = actions.fold(&run) else { panic!("a run with acts folds") }; assert_eq!(block.text, "[actions #3200-#3330: 131 earlier acts folded; reopen one with tool/output act=]"); - assert!(actions.fold(&[item("banner")]).is_none(), "the banner alone has no act to name"); + assert!(actions.fold(&[item("banner")]).is_none(), "a run that is not acts names nothing"); } diff --git a/core/continuum-context/src/view/allot.rs b/core/continuum-context/src/view/allot.rs index dcd13b9465..7349e7eb25 100644 --- a/core/continuum-context/src/view/allot.rs +++ b/core/continuum-context/src/view/allot.rs @@ -54,6 +54,25 @@ fn fold_of( .filter(|block| block.chars() < pointer_chars) } +/// How many of `items`' leading items stand as themselves: an item with no summary, nothing +/// stored and a pointer as long as its whole has nothing to give up, so folding it saves nothing +/// and only moves the front of her view (her `[actions]` banner folded into the block broke the +/// prefix a turnover keeps, `consecutive_acts_share_the_whole_view_and_a_turnover_keeps_the_settled_front`). +/// They render as themselves at the floor; the fold run is the oldest items after them. +fn standing_head(items: &[Item]) -> usize { + items + .iter() + .take_while(|item| { + item.summary.is_none() + && item.stored.is_none() + && item + .pointer + .as_ref() + .is_some_and(|pointer| pointer.chars() == item.full.chars()) + }) + .count() +} + /// What `items` of `source` cost at their floor, in the unit `cost` prices a block in: the one /// owner of a source's floor, for the view's own claim and any caller pricing it in tokens. /// Whether the floor is the fold block or the pointers is [`fold_of`]'s decision, the view's. @@ -62,17 +81,19 @@ pub fn floor( items: &[Item], cost: impl Fn(&T) -> usize, ) -> usize { - let pointer_chars = items - .iter() - .map(|item| item.pointer.as_ref().map_or(0, Block::chars)) - .sum(); // map_or: an item that leaves when collapsed costs nothing - match fold_of(source, items, pointer_chars) { - Some(block) => cost(&block), - None => items - .iter() - .map(|item| item.pointer.as_ref().map_or(0, &cost)) - .sum(), // map_or: as above - } + let head = standing_head(items); + let pointers = |run: &[Item], cost: &dyn Fn(&T) -> usize| -> usize { + run.iter() + .map(|item| item.pointer.as_ref().map_or(0, cost)) + .sum() // map_or: an item that leaves when collapsed costs nothing + }; + let (standing, rest) = items.split_at(head); + let rest_chars = pointers(rest, &|block: &T| block.chars()); + pointers(standing, &cost) + + match fold_of(source, rest, rest_chars) { + Some(block) => cost(&block), + None => pointers(rest, &cost), + } } /// The level a `grant` of characters gives each item. Every item starts at the floor (folded @@ -107,9 +128,19 @@ pub(super) fn allot( let below = pointers[pointers.len() - 1]; pointers.push(below + item.pointer.as_ref().map_or(0, Block::chars)); // map_or: an item that leaves when collapsed costs nothing } - let floor = |count: usize| match fold_of(source, &items[..count], pointers[count]) { - Some(block) => (block.chars(), Some(block)), - None => (pointers[count], None), + let head = standing_head(items); + let floor = |count: usize| { + if count <= head { + return (pointers[count], None); + } + match fold_of( + source, + &items[head..count], + pointers[count] - pointers[head], + ) { + Some(block) => (pointers[head] + block.chars(), Some(block)), + None => (pointers[count], None), + } }; let mut levels = vec![Level::Pointer; items.len()]; let (mut paid, _) = floor(items.len()); @@ -155,7 +186,7 @@ pub(super) fn allot( } let (_, fold) = floor(run); if fold.is_some() { - levels[..run].fill(Level::Folded); + levels[head..run].fill(Level::Folded); } Allotment { levels, fold } }