Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix: cap the prompt list on the session page

Djalma Júnior8c5ed38ca762
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 59954396..9dd2f880 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,13 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
+### Fixed
+- Fixed the session page's uncapped `## Prompts` list. Above 500 prompts the
+ page now lists the first 250 titles and the last 250, numbered by their real
+ position, with one line between them saying how many were left out. The
+ store reads at most 500 titles for it, and the page's prompt count and the
+ digest stats still report the true total. (#PRNUM)
+
## [3.1.0] - 2026-10-16
### Added
diff --git a/crates/ai-memory-hooks/src/session_end_equivalence.rs b/crates/ai-memory-hooks/src/session_end_equivalence.rs
index 52e8c702..d9b27bdc 100644
--- a/crates/ai-memory-hooks/src/session_end_equivalence.rs
+++ b/crates/ai-memory-hooks/src/session_end_equivalence.rs
@@ -871,7 +871,19 @@ impl Fixture {
new_page.frontmatter_json, old_page.frontmatter_json,
"{name}: page frontmatter"
);
- assert_eq!(new_page.body, old_page.body, "{name}: page body");
+ // The oracle predates the prompt-list cap: fold its full prompt list
+ // down to the capped form the new path prints before comparing, so a
+ // session over the cap still compares byte for byte everywhere else.
+ let prompt_titles: Vec<String> = rows
+ .iter()
+ .filter(|r| r.kind == ObservationKind::UserPrompt)
+ .map(|r| r.title.clone())
+ .collect();
+ assert_eq!(
+ new_page.body,
+ prompt_capped_body(&old_page.body, &prompt_titles),
+ "{name}: page body"
+ );
for turn_checkpoint in [false, true] {
let old_handoff = full_load::build_auto_handoff(
@@ -951,6 +963,59 @@ impl Fixture {
}
}
+/// The oracle page predates the prompt-list cap: it lists every prompt.
+/// Replace that section with the capped form the new path prints — the first
+/// and last slice, one omission line between them, each title numbered with
+/// its real position in the session — so the rest of the page still compares
+/// byte for byte. Sessions with at most `PROMPT_TITLES_MAX` prompts come
+/// back untouched, which is what keeps the small-session tests exact.
+fn prompt_capped_body(body: &str, titles: &[String]) -> String {
+ use crate::synth::{PROMPT_TITLES_HEAD, PROMPT_TITLES_MAX, PROMPT_TITLES_TAIL};
+ if titles.len() <= PROMPT_TITLES_MAX {
+ return body.to_string();
+ }
+ let heading = "## Prompts\n\n";
+ let start = body
+ .find(heading)
+ .expect("the oracle page lists its prompts");
+ // Rebuild the old section from `titles` instead of slicing the body, so
+ // a title that looks like a heading cannot move the boundary.
+ let old_section: String = titles
+ .iter()
+ .enumerate()
+ .map(|(i, t)| format!("{}. {t}\n", i + 1))
+ .collect();
+ let end = start + heading.len() + old_section.len();
+ debug_assert!(
+ body[end..].starts_with('\n'),
+ "the section runs to the next heading"
+ );
+ let (head, tail) = (
+ &titles[..PROMPT_TITLES_HEAD],
+ &titles[titles.len() - PROMPT_TITLES_TAIL..],
+ );
+ let mut capped = String::new();
+ for (i, t) in head.iter().enumerate() {
+ capped.push_str(&format!("{}. {t}\n", i + 1));
+ }
+ capped.push_str(&format!(
+ "\n_... {} prompts omitted from the middle (showing first {PROMPT_TITLES_HEAD} and last {PROMPT_TITLES_TAIL})._\n\n",
+ titles.len() - PROMPT_TITLES_MAX
+ ));
+ for (i, t) in tail.iter().enumerate() {
+ capped.push_str(&format!(
+ "{}. {t}\n",
+ titles.len() - PROMPT_TITLES_TAIL + i + 1
+ ));
+ }
+ let mut out = String::with_capacity(body.len());
+ out.push_str(&body[..start]);
+ out.push_str(heading);
+ out.push_str(&capped);
+ out.push_str(&body[end..]);
+ out
+}
+
fn start(at: i64) -> Row {
row(ObservationKind::SessionStart, "session-start", "", at)
}
@@ -1238,8 +1303,9 @@ async fn a_large_mixed_session_renders_identically() {
}
}
-/// The page lists every prompt title, so the digest keeps them all; nothing
-/// else about a session grows its digest.
+/// Nothing about a session's digest grows with the session: the raw lines
+/// and the prompt-title slice are capped, and the rest is counts and
+/// early-exit scans.
#[tokio::test]
async fn a_huge_session_reads_a_bounded_number_of_rows() {
let fx = fixture().await;
@@ -1318,6 +1384,151 @@ async fn subagent_preamble_bodies_stop_at_the_first_usable_one() {
}
}
+/// The `## Prompts` list is capped the way the raw-observation list is: a
+/// session with more prompts than the cap shows its first and last slice,
+/// numbered with the real positions, with one omission line between them,
+/// while the count and the stats keep the true total.
+#[tokio::test]
+async fn the_prompt_list_is_capped_like_the_raw_observations() {
+ use crate::synth::{PROMPT_TITLES_HEAD, PROMPT_TITLES_TAIL};
+
+ let fx = fixture().await;
+ let prompts = 2_000;
+ let mut rows = vec![start(0)];
+ for i in 1..=prompts {
+ rows.push(row(
+ ObservationKind::UserPrompt,
+ &format!("prompt {i}"),
+ "",
+ i as i64,
+ ));
+ }
+ rows.push(end(prompts as i64 + 1));
+ let sid = fx.seed(&rows).await;
+
+ // The store read itself: at most the bounded slice plus the true count.
+ let capped = fx
+ .store
+ .reader
+ .read_session_observations(fx.ws, fx.proj, sid, |s| {
+ s.prompt_titles(PROMPT_TITLES_HEAD, PROMPT_TITLES_TAIL)
+ })
+ .await
+ .unwrap();
+ assert_eq!(capped.total, prompts);
+ assert_eq!(capped.first.len(), PROMPT_TITLES_HEAD);
+ assert_eq!(capped.last.len(), PROMPT_TITLES_TAIL);
+ assert_eq!(capped.first[0], "prompt 1");
+ assert_eq!(
+ capped.first[PROMPT_TITLES_HEAD - 1],
+ format!("prompt {PROMPT_TITLES_HEAD}")
+ );
+ assert_eq!(
+ capped.last[0],
+ format!("prompt {}", prompts - PROMPT_TITLES_TAIL + 1)
+ );
+ assert_eq!(
+ capped.last[PROMPT_TITLES_TAIL - 1],
+ format!("prompt {prompts}")
+ );
+
+ // Through the real SessionEnd path: the stats keep the true total...
+ let (digest, stats) = SessionDigest::load_with_stats(&fx.store.reader, fx.ws, fx.proj, sid)
+ .await
+ .unwrap();
+ assert_eq!(stats.prompt_titles, prompts);
+
+ // ...and the page prints exactly the bounded slice, with the numbers and
+ // the omission line.
+ let page = crate::synthesize_session_page(fx.ws, fx.proj, sid, AgentKind::ClaudeCode, &digest);
+ let section = page
+ .body
+ .split("## Prompts\n\n")
+ .nth(1)
+ .expect("the page lists its prompts")
+ .split("\n## Raw observations")
+ .next()
+ .unwrap();
+ let numbered = section
+ .lines()
+ .filter(|l| l.split('.').next().unwrap_or("").parse::<usize>().is_ok())
+ .count();
+ assert_eq!(numbered, PROMPT_TITLES_HEAD + PROMPT_TITLES_TAIL);
+ assert!(section.contains("1. prompt 1\n"));
+ assert!(section.contains("250. prompt 250\n"));
+ assert!(section.contains("1751. prompt 1751\n"));
+ assert!(section.contains("2000. prompt 2000\n"));
+ assert!(
+ section.contains(
+ "_... 1500 prompts omitted from the middle (showing first 250 and last 250)._"
+ ),
+ "one omission line with the true gap: {section}"
+ );
+ // The count line keeps the true total.
+ let summary = page.frontmatter_json["summary"].as_str().unwrap();
+ assert!(summary.starts_with("2000 prompts"), "count line: {summary}");
+ // And the title, the handoff and the rest of the page are the oracle's.
+ assert_eq!(page.title, "prompt 1");
+ fx.assert_equivalent("2000 prompts (capped list)", sid)
+ .await;
+}
+
+/// Exactly at the cap the page still lists every prompt; one over it shows
+/// the head and tail slices and the omission line.
+#[tokio::test]
+async fn the_prompt_cap_boundary_keeps_five_hundred_and_cuts_five_hundred_one() {
+ for (n, capped) in [(500, false), (501, true)] {
+ let fx = fixture().await;
+ let mut rows = vec![start(0)];
+ for i in 1..=n {
+ rows.push(row(
+ ObservationKind::UserPrompt,
+ &format!("p{i}"),
+ "",
+ i as i64,
+ ));
+ }
+ rows.push(end(n as i64 + 1));
+ let sid = fx.seed(&rows).await;
+ let (digest, stats) = SessionDigest::load_with_stats(&fx.store.reader, fx.ws, fx.proj, sid)
+ .await
+ .unwrap();
+ assert_eq!(
+ stats.prompt_titles, n,
+ "n={n}: the stats keep the true total"
+ );
+ let page =
+ crate::synthesize_session_page(fx.ws, fx.proj, sid, AgentKind::ClaudeCode, &digest);
+ if capped {
+ assert!(page.body.contains("250. p250\n"), "n={n}");
+ assert!(
+ !page.body.contains("251. p251\n"),
+ "n={n}: the gap drops p251"
+ );
+ assert!(page.body.contains("252. p252\n"), "n={n}");
+ assert!(page.body.contains("501. p501\n"), "n={n}");
+ assert!(
+ page.body.contains(
+ "_... 1 prompts omitted from the middle (showing first 250 and last 250)._"
+ ),
+ "n={n}: one omission line"
+ );
+ } else {
+ assert!(page.body.contains("500. p500\n"), "n={n}");
+ assert!(
+ !page.body.contains("prompts omitted"),
+ "n={n}: whole list, no marker"
+ );
+ }
+ let summary = page.frontmatter_json["summary"].as_str().unwrap();
+ assert!(
+ summary.starts_with(&format!("{n} prompts")),
+ "n={n}: count line: {summary}"
+ );
+ fx.assert_equivalent(&format!("prompts={n}"), sid).await;
+ }
+}
+
/// The Rust predicate the original code used and the existence query the
/// router asks now classify every observation kind alike. (The writer's
/// lifecycle-only re-check is pinned to the same query in
diff --git a/crates/ai-memory-hooks/src/synth.rs b/crates/ai-memory-hooks/src/synth.rs
index 75f62750..4a79f6e4 100644
--- a/crates/ai-memory-hooks/src/synth.rs
+++ b/crates/ai-memory-hooks/src/synth.rs
@@ -11,7 +11,9 @@
//! marker, the head and tail the raw-observation list shows, or the first or
//! last row that passes a predicate. [`SessionDigest::load`] reads exactly
//! those with bounded queries, so the memory a SessionEnd spends does not grow
-//! with the session, and the output is the one the full row list produced.
+//! with the session, and the output is the one the full row list produced —
+//! the one exception being the `## Prompts` list, which is capped like the
+//! raw-observation list.
use std::collections::{BTreeMap, BTreeSet};
@@ -32,6 +34,13 @@ use crate::payload::{is_safe_tool_title, tool_family_from_title};
const RAW_OBSERVATION_MAX_LINES: usize = 500;
const RAW_OBSERVATION_HEAD_LINES: usize = 250;
const RAW_OBSERVATION_TAIL_LINES: usize = RAW_OBSERVATION_MAX_LINES - RAW_OBSERVATION_HEAD_LINES;
+/// The `## Prompts` list is capped the way the raw-observation list is: a
+/// session with more prompts than this prints its first and last slice and
+/// an omission line between them. The values are the same bound, so the page
+/// never holds more prompt titles than raw-observation lines.
+pub(crate) const PROMPT_TITLES_MAX: usize = RAW_OBSERVATION_MAX_LINES;
+pub(crate) const PROMPT_TITLES_HEAD: usize = RAW_OBSERVATION_HEAD_LINES;
+pub(crate) const PROMPT_TITLES_TAIL: usize = PROMPT_TITLES_MAX - PROMPT_TITLES_HEAD;
const SUBAGENT_PROMPT_PREAMBLE: &str = "You are a subagent spawned by another session.";
/// Build a [`NewPage`] from the digest of a session's observations.
@@ -140,8 +149,9 @@ pub(crate) struct HandoffFacts {
/// What a session's page and handoff are rendered from.
///
/// Built by [`Self::load`] with bounded reads in one read transaction, so a
-/// session of any size costs the same memory apart from what the output itself
-/// lists: the title of every user prompt, because the page prints each one.
+/// session of any size costs the same memory apart from what the output
+/// itself lists: the first and last prompt-title slice the page prints, at
+/// most [`PROMPT_TITLES_MAX`] titles.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionDigest {
/// Rows the session holds.
@@ -157,8 +167,14 @@ pub struct SessionDigest {
start_at: Option<Timestamp>,
/// The newest `SessionEnd`.
end: Option<SessionEndFact>,
- /// Every user prompt's title, in capture order.
+ /// The prompt titles the page lists: all of them when the session holds
+ /// at most [`PROMPT_TITLES_MAX`], otherwise the first
+ /// [`PROMPT_TITLES_HEAD`] and the last [`PROMPT_TITLES_TAIL`], each in
+ /// capture order.
prompt_titles: Vec<String>,
+ /// User prompts the session holds (the true total; the list above is
+ /// bounded).
+ prompt_count: usize,
/// Completed calls per tool name, keyed for stable ordering.
tool_counts: BTreeMap<String, usize>,
/// The page title.
@@ -173,7 +189,8 @@ pub(crate) struct DigestLoadStats {
/// Rows deserialized: the raw-observation lines plus every row an
/// early-exit scan visited (one resident at a time).
pub rows_read: usize,
- /// User prompts whose title the digest keeps.
+ /// User prompts the session holds (the digest keeps at most the bounded
+ /// slice of their titles).
pub prompt_titles: usize,
/// Prompt bodies read to settle the page title (one resident at a time).
pub prompt_bodies_read: usize,
@@ -326,11 +343,18 @@ fn build_digest(
None => None,
};
+ // The prompt titles the page lists: bounded the way the raw-observation
+ // list is, with the true prompt count beside them.
+ let prompts = snapshot.prompt_titles(PROMPT_TITLES_HEAD, PROMPT_TITLES_TAIL)?;
+ let mut prompt_titles = prompts.first;
+ prompt_titles.extend(prompts.last);
+
// Bodies only for a title that could be the subagent preamble: the title
- // rule is the one reader of a prompt body.
+ // rule is the one reader of a prompt body, and the walk stops once the
+ // title is settled.
let mut title_scan = PromptTitleScan::default();
let mut prompt_bodies_read = 0;
- let prompt_titles = snapshot.prompt_titles(SUBAGENT_PROMPT_PREAMBLE, |title, body| {
+ snapshot.scan_prompts(SUBAGENT_PROMPT_PREAMBLE, |title, body| {
prompt_bodies_read += usize::from(body.is_some());
title_scan.push(title, body.unwrap_or(""))
})?;
@@ -394,7 +418,7 @@ fn build_digest(
let stats = DigestLoadStats {
rows_read: snapshot.rows_read(),
- prompt_titles: prompt_titles.len(),
+ prompt_titles: prompts.total,
prompt_bodies_read,
};
Ok((
@@ -406,6 +430,7 @@ fn build_digest(
start_at,
end,
prompt_titles,
+ prompt_count: prompts.total,
tool_counts,
title,
handoff,
@@ -561,11 +586,11 @@ const SUMMARY_MAX_NAMED_TOOLS: usize = 3;
fn session_summary(digest: &SessionDigest) -> String {
let mut parts: Vec<String> = Vec::new();
- if !digest.prompt_titles.is_empty() {
+ if digest.prompt_count > 0 {
parts.push(format!(
"{} prompt{}",
- digest.prompt_titles.len(),
- plural(digest.prompt_titles.len())
+ digest.prompt_count,
+ plural(digest.prompt_count)
));
}
@@ -693,10 +718,27 @@ fn render_body(session_id: SessionId, digest: &SessionDigest, title: &str) -> St
buf.push_str(&format!("{note}\n\n"));
}
- if !digest.prompt_titles.is_empty() {
+ if digest.prompt_count > 0 {
buf.push_str("## Prompts\n\n");
- for (i, title) in digest.prompt_titles.iter().enumerate() {
- buf.push_str(&format!("{}. {}\n", i + 1, title));
+ if digest.prompt_count <= PROMPT_TITLES_MAX {
+ for (i, title) in digest.prompt_titles.iter().enumerate() {
+ buf.push_str(&format!("{}. {title}\n", i + 1));
+ }
+ } else {
+ let (head, tail) = digest.prompt_titles.split_at(PROMPT_TITLES_HEAD);
+ for (i, title) in head.iter().enumerate() {
+ buf.push_str(&format!("{}. {title}\n", i + 1));
+ }
+ let omitted = digest.prompt_count - PROMPT_TITLES_HEAD - PROMPT_TITLES_TAIL;
+ buf.push_str(&format!(
+ "\n_... {omitted} prompts omitted from the middle (showing first {PROMPT_TITLES_HEAD} and last {PROMPT_TITLES_TAIL})._\n\n",
+ ));
+ for (i, title) in tail.iter().enumerate() {
+ buf.push_str(&format!(
+ "{}. {title}\n",
+ digest.prompt_count - PROMPT_TITLES_TAIL + i + 1
+ ));
+ }
}
buf.push('\n');
}
@@ -847,6 +889,26 @@ impl SessionDigest {
*tool_counts.entry(obs.title.clone()).or_insert(0) += 1;
}
}
+ let prompt_titles_all: Vec<String> = observations
+ .iter()
+ .filter(|o| o.kind == ObservationKind::UserPrompt)
+ .map(|o| o.title.clone())
+ .collect();
+ // The store's bounded read keeps every title when the session fits in
+ // the cap and the first/last slice when it does not; mirror that here
+ // so the row-list digest and the database digest stay equal.
+ let (prompt_count, prompt_titles) = if prompt_titles_all.len() <= PROMPT_TITLES_MAX {
+ (prompt_titles_all.len(), prompt_titles_all)
+ } else {
+ (
+ prompt_titles_all.len(),
+ prompt_titles_all[..PROMPT_TITLES_HEAD]
+ .iter()
+ .chain(prompt_titles_all[prompt_titles_all.len() - PROMPT_TITLES_TAIL..].iter())
+ .cloned()
+ .collect(),
+ )
+ };
Self {
total,
substantive: observations.iter().any(|o| {
@@ -864,11 +926,8 @@ impl SessionDigest {
created_at: o.created_at,
body: o.body.clone(),
}),
- prompt_titles: observations
- .iter()
- .filter(|o| o.kind == ObservationKind::UserPrompt)
- .map(|o| o.title.clone())
- .collect(),
+ prompt_titles,
+ prompt_count,
tool_counts,
title,
handoff: HandoffFacts::from_observations(observations),
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 5b3c1059..06f6e65d 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -95,9 +95,9 @@ pub use reader::{
ReindexTargetStatus, RelatedNode, RelatedPage, RrfContributions, SESSION_LINE_TITLE_CHARS,
SUBSTANTIVE_OBSERVATION_KIND_SQL, ScopeRow, SearchExplain, SessionConsolidationQueue,
SessionConsolidationSummary, SessionDependentRows, SessionEndDisposition, SessionKindSummary,
- SessionLine, SessionObservationSnapshot, SessionSummary, SessionToolTitles, SettledPage,
- StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody, StreamTimings, VectorQuery,
- WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
+ SessionLine, SessionObservationSnapshot, SessionPromptTitles, SessionSummary,
+ SessionToolTitles, SettledPage, StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody,
+ StreamTimings, VectorQuery, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
};
pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};
pub use scope::{
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index a2664dd3..3c1415e4 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -12170,6 +12170,20 @@ pub struct SessionToolTitles {
pub titles: Vec<String>,
}
+/// The prompt titles a session page lists, with the session's true prompt
+/// count.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SessionPromptTitles {
+ /// User prompts the session holds (the uncapped total).
+ pub total: usize,
+ /// The first titles in capture order: every one of them when the session
+ /// holds at most `head + tail` prompts, else the first `head`.
+ pub first: Vec<String>,
+ /// The last `tail` titles in capture order, only when the session holds
+ /// more than `head + tail` prompts.
+ pub last: Vec<String>,
+}
+
/// What a page prints about one observation, without the body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionLine {
@@ -12199,8 +12213,9 @@ pub const SUBSTANTIVE_OBSERVATION_KIND_SQL: &str =
impl SessionObservationSnapshot<'_> {
/// Rows this snapshot has deserialized into an [`Observation`] or a
- /// [`SessionLine`] so far. Aggregates and the prompt-title projection are
- /// not counted: they return counters and strings, not rows.
+ /// [`SessionLine`] so far. Aggregates and the prompt-title queries (the
+ /// bounded list and the one-row-at-a-time title walk) are not counted:
+ /// they return counters and short strings, not rows.
#[must_use]
pub fn rows_read(&self) -> usize {
self.rows_read.get()
@@ -12288,46 +12303,106 @@ impl SessionObservationSnapshot<'_> {
Ok(out)
}
- /// Every user prompt's title in capture order.
+ /// The prompt titles a page lists, with the session's true prompt count.
+ ///
+ /// A page prints at most the first `head` and the last `tail` titles, so
+ /// this reads at most `head + tail` titles plus one `COUNT(*)`, whatever
+ /// the session holds. Titles are short by construction (the router
+ /// truncates them for display).
///
- /// `visit` sees each prompt in that order, with its body only when the
- /// title contains `body_for_titles_like` (a superset the caller filters
- /// exactly), until it returns `false`; later prompts contribute their
- /// title alone. At most one body is resident at a time, so a session full
- /// of subagent preambles costs one body, not all of them.
+ /// # Errors
+ /// Propagates any SQL error.
+ pub fn prompt_titles(&self, head: usize, tail: usize) -> StoreResult<SessionPromptTitles> {
+ let total = self.conn.query_row(
+ "SELECT COUNT(*) FROM observations \
+ WHERE session_id = ?1 AND kind = ?2",
+ params![self.session_id, ObservationKind::UserPrompt.as_str()],
+ |row| row.get::<_, i64>(0),
+ )?;
+ let total = usize::try_from(total).unwrap_or(usize::MAX);
+ if total <= head + tail {
+ return Ok(SessionPromptTitles {
+ total,
+ first: self.prompt_title_window(total, ObservationOrder::Asc)?,
+ last: Vec::new(),
+ });
+ }
+ let mut last = self.prompt_title_window(tail, ObservationOrder::Desc)?;
+ last.reverse();
+ Ok(SessionPromptTitles {
+ total,
+ first: self.prompt_title_window(head, ObservationOrder::Asc)?,
+ last,
+ })
+ }
+
+ /// The first `limit` user-prompt titles of the session in `order`.
///
- /// The titles are the one part of a SessionEnd that grows with the
- /// session: the page it renders lists each of them, so the output cannot
- /// be smaller than this. A title is short by construction (the router
- /// truncates it for display); the bodies, which are not, stay in the
- /// database.
+ /// # Errors
+ /// Propagates any SQL error.
+ fn prompt_title_window(
+ &self,
+ limit: usize,
+ order: ObservationOrder,
+ ) -> StoreResult<Vec<String>> {
+ let direction = match order {
+ ObservationOrder::Asc => "ASC",
+ ObservationOrder::Desc => "DESC",
+ };
+ let sql = format!(
+ "SELECT title FROM observations \
+ WHERE session_id = ?1 AND kind = ?2 \
+ ORDER BY created_at {direction}, rowid {direction} LIMIT ?3"
+ );
+ let mut stmt = self.conn.prepare_cached(&sql)?;
+ let rows = stmt.query_map(
+ params![
+ self.session_id,
+ ObservationKind::UserPrompt.as_str(),
+ i64::try_from(limit).unwrap_or(i64::MAX),
+ ],
+ |row| row.get(0),
+ )?;
+ let mut out = Vec::with_capacity(limit);
+ for title in rows {
+ out.push(title?);
+ }
+ Ok(out)
+ }
+
+ /// Walk the session's user prompts in capture order, one resident at a
+ /// time, feeding `visit` each title and, only when the title contains
+ /// `body_for_titles_like`, the prompt's body. The walk stops at the first
+ /// `false`, so a caller that settles the page title reads bodies no
+ /// further than the prompt that named it: a session full of subagent
+ /// preambles costs the bodies up to the first usable one, not all of
+ /// them, and one row is resident at a time no matter how long it is.
///
/// # Errors
/// Propagates any SQL error.
- pub fn prompt_titles(
+ pub fn scan_prompts(
&self,
body_for_titles_like: &str,
mut visit: impl FnMut(&str, Option<&str>) -> bool,
- ) -> StoreResult<Vec<String>> {
+ ) -> StoreResult<()> {
let mut stmt = self.conn.prepare_cached(
- "SELECT title, CASE WHEN instr(title, ?3) > 0 THEN body END FROM observations WHERE session_id = ?1 AND kind = ?2 ORDER BY created_at ASC, rowid ASC",
+ "SELECT title, CASE WHEN instr(title, ?3) > 0 THEN body END \
+ FROM observations WHERE session_id = ?1 AND kind = ?2 \
+ ORDER BY created_at ASC, rowid ASC",
)?;
let mut rows = stmt.query(params![
self.session_id,
ObservationKind::UserPrompt.as_str(),
body_for_titles_like,
])?;
- let mut titles = Vec::new();
- let mut visiting = true;
while let Some(row) = rows.next()? {
let title: String = row.get(0)?;
- if visiting {
- let body: Option<String> = row.get(1)?;
- visiting = visit(&title, body.as_deref());
+ let body: Option<String> = row.get(1)?;
+ if !visit(&title, body.as_deref()) {
+ break;
}
- titles.push(title);
}
- Ok(titles)
+ Ok(())
}
/// The first `limit` rows of the session, oldest first, as page lines.