返回 CodeWhale
todo_snapshot.rs
根目录 / crates / engine / src / todo_snapshot.rs
1 //! Bounded renderings of a To-do snapshot.
2 //!
3 //! Codewhale has exactly one To-do list. The model learns what is on it the
4 //! same way it learns anything else: from its own `todo_write` /
5 //! `work_update` call, whose input is the whole list, confirmed by a short
6 //! receipt (counts and the item in progress). Both are ordinary persisted
7 //! transcript state. **Nothing in this module is appended to a provider
8 //! request**, and no step of a tool loop re-states the list. If the model
9 //! wants the current list, it reads its own last call or calls the tool again.
10 //!
11 //! What this module owns is the small set of places that render a snapshot
12 //! *once*, at an explicit seam a person asked for:
13 //!
14 //! 1. the `<codewhale:fork_state>` block a newly forked sub-agent is handed,
15 //! 2. `/relay` handoff instructions,
16 //! 3. the in-transcript agent card (display only).
17 //!
18 //! All three share [`todo_snapshot_body`] byte-for-byte, so no two surfaces
19 //! can disagree about what the list says.
20 //!
21 //! Rules the renderer must keep, because this text reaches a model:
22 //!
23 //! - An empty To-do renders nothing at all. Silence beats an empty list that
24 //! reads as "there is no work".
25 //! - `update_plan` strategy state is conversational reasoning, not a second
26 //! list, and never appears here.
27 //! - Items and characters are both hard-bounded, so a large list cannot eat the
28 //! context window. The in-progress item is preserved preferentially — losing
29 //! the active item is the one omission that would actively mislead.
30 //! - Truncation happens on `char` boundaries and marks the omission, so a
31 //! multi-byte item can neither panic nor silently shrink the list.
32 //! - Item text can never close its wrapper: a closing tag in the `codewhale:`
33 //! namespace is escaped before it reaches the model, and control characters
34 //! are flattened so content cannot forge a new line.
35 //!
36 //! **What this module does not do:** it does not sanitize To-do content against
37 //! prompt injection, and no caller should claim that it does. The guarantees
38 //! above are exactly three — wrapper framing cannot be closed early, control
39 //! characters cannot forge the line format, and the item/character bounds hold.
40 //! The *meaning* of arbitrary item text is not inspected, filtered, or
41 //! neutralized; a To-do item containing instructions still reaches the model as
42 //! item text. Treating that text as untrusted data is the model contract's job
43 //! (the constitution), not the renderer's.
44
45 use crate::tools::todo::{SharedTodoList, TodoItem, TodoListSnapshot, TodoStatus};
46 use crate::work_graph::SharedWorkRuntime;
47
48 /// Maximum number of item lines rendered in the body.
49 pub const MAX_ITEM_LINES: usize = 24;
50 /// Hard character ceiling for the body (counted in `char`s).
51 pub const MAX_BODY_CHARS: usize = 2_000;
52 /// Per-item content ceiling before the omission marker is appended.
53 pub const MAX_ITEM_CONTENT_CHARS: usize = 160;
54
55 /// Marks any text elided by a bound.
56 const OMISSION_MARKER: char = '…';
57
58 /// Escaped form of a closing wrapper tag found inside item content.
59 const ESCAPED_CLOSE_PREFIX: &str = "<\\/codewhale:";
60 const CLOSE_PREFIX: &str = "</codewhale:";
61
62 /// Render the To-do snapshot body, or `None` when there is nothing on the list.
63 ///
64 /// The returned string carries no framing; each seam supplies its own, so the
65 /// body itself stays comparable across surfaces.
66 #[must_use]
67 pub fn todo_snapshot_body(snapshot: &TodoListSnapshot) -> Option<String> {
68 if snapshot.items.is_empty() {
69 return None;
70 }
71
72 let header = format!("To-do ({}% settled)", snapshot.completion_pct);
73 let lines: Vec<String> = snapshot.items.iter().map(item_line).collect();
74 let priority = priority_order(snapshot);
75
76 let mut selected: Vec<usize> = Vec::new();
77 let mut used = header.chars().count();
78 for idx in priority {
79 if selected.len() >= MAX_ITEM_LINES {
80 break;
81 }
82 let cost = 1 + lines[idx].chars().count();
83 if used + cost > MAX_BODY_CHARS {
84 break;
85 }
86 used += cost;
87 selected.push(idx);
88 }
89
90 // The omission line itself costs characters, so it has to fit inside the
91 // same ceiling. Drop lowest-priority selections until it does; the active
92 // item sits at index 0 and is never the one dropped.
93 let mut omitted = lines.len() - selected.len();
94 if omitted > 0 {
95 loop {
96 let cost = 1 + omission_line(omitted).chars().count();
97 if used + cost <= MAX_BODY_CHARS || selected.len() <= 1 {
98 break;
99 }
100 if let Some(dropped) = selected.pop() {
101 used -= 1 + lines[dropped].chars().count();
102 omitted += 1;
103 }
104 }
105 }
106
107 selected.sort_unstable();
108 let mut body = header;
109 for idx in selected {
110 body.push('\n');
111 body.push_str(&lines[idx]);
112 }
113 if omitted > 0 {
114 body.push('\n');
115 body.push_str(&omission_line(omitted));
116 }
117
118 debug_assert!(body.chars().count() <= MAX_BODY_CHARS);
119 Some(body)
120 }
121
122 /// The authoritative source of one agent's To-do state.
123 ///
124 /// There are two stores in play and only one of them is current. When a
125 /// [`WorkRuntime`](crate::work_graph::WorkRuntime) owns this list, a
126 /// `work_update` *stages* the new projection in the graph and the legacy
127 /// `SharedTodoList` view is only refreshed later, asynchronously, by the UI's
128 /// publish step. Reading the legacy view alone therefore shows the model its
129 /// state from before its own last write. So: read the graph projection when the
130 /// runtime owns this exact list (`Arc::ptr_eq` via
131 /// [`WorkRuntime::matches_todos`](crate::work_graph::WorkRuntime::matches_todos)),
132 /// and read the list directly otherwise.
133 ///
134 /// The ownership check is what keeps agents isolated. A child's runtime carries
135 /// its *parent's* `WorkRuntime` handle but its **own** list (#4810), so
136 /// `matches_todos` is false for every child and each child resolves against its
137 /// own store — a child can never read the parent's or a sibling's list here.
138 #[derive(Clone)]
139 pub struct TodoSource {
140 work: Option<SharedWorkRuntime>,
141 todos: SharedTodoList,
142 }
143
144 impl std::fmt::Debug for TodoSource {
145 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146 f.debug_struct("TodoSource")
147 .field("graph_backed", &self.is_graph_backed())
148 .finish()
149 }
150 }
151
152 impl TodoSource {
153 /// Bind a source to an agent's own list plus whatever work runtime its
154 /// tool context carries.
155 #[must_use]
156 pub fn new(work: Option<SharedWorkRuntime>, todos: SharedTodoList) -> Self {
157 Self { work, todos }
158 }
159
160 /// Whether the attached runtime actually owns this list.
161 #[must_use]
162 pub fn is_graph_backed(&self) -> bool {
163 self.work
164 .as_ref()
165 .is_some_and(|work| work.matches_todos(&self.todos))
166 }
167
168 /// Current authoritative snapshot.
169 ///
170 /// Never omits and never fails: a graph read error degrades to the legacy
171 /// view with a warning rather than dropping the list from a fork handoff,
172 /// because a silently missing list reads to the model as "no work".
173 pub async fn snapshot(&self) -> TodoListSnapshot {
174 if let Some(work) = self.work.as_ref().filter(|_| self.is_graph_backed()) {
175 match work.current_todos().await {
176 Ok(snapshot) => return snapshot,
177 Err(err) => tracing::warn!(
178 target: "todo_snapshot",
179 error = %err,
180 "work graph projection unavailable; falling back to the legacy To-do view"
181 ),
182 }
183 }
184 self.todos.lock().await.snapshot()
185 }
186
187 /// Body for the current authoritative snapshot.
188 pub async fn body(&self) -> Option<String> {
189 todo_snapshot_body(&self.snapshot().await)
190 }
191 }
192
193 /// Maximum item rows an in-transcript agent card renders (#4810). Narrower
194 /// than the shared bound: a card is a glance, not the whole list.
195 pub const MAX_CARD_ITEM_LINES: usize = 3;
196 /// Per-item content ceiling on a card row.
197 pub const MAX_CARD_ITEM_CONTENT_CHARS: usize = 72;
198
199 /// Bounded, display-only projection of **one agent's own** To-do snapshot for
200 /// its delegate/agent card.
201 ///
202 /// Same list, same priority order, same sanitizer as [`todo_snapshot_body`] —
203 /// only the framing and the bounds differ. Nothing here derives new work: every
204 /// row corresponds to an item that exists in the snapshot it was built from.
205 #[derive(Debug, Clone, PartialEq, Eq)]
206 pub struct TodoCardProjection {
207 /// Bounded progress, e.g. `To-do 1/4 · 25% settled`.
208 pub header: String,
209 /// Item rows in document order, e.g. `[~] #2 Write the renderer`.
210 pub items: Vec<String>,
211 /// Items that exist in the snapshot but did not fit the card bound.
212 pub omitted: usize,
213 }
214
215 /// Project one agent's To-do snapshot onto its card, or `None` when that agent
216 /// has no work to show.
217 ///
218 /// An empty list returns `None` rather than a placeholder row — the same rule
219 /// [`todo_snapshot_body`] follows. A card that has never received a snapshot
220 /// and a card whose agent reported an empty list both render nothing, because
221 /// neither one has a task to name.
222 #[must_use]
223 pub fn card_todo_projection(snapshot: &TodoListSnapshot) -> Option<TodoCardProjection> {
224 if snapshot.items.is_empty() {
225 return None;
226 }
227
228 let total = snapshot.items.len();
229 let settled = snapshot
230 .items
231 .iter()
232 .filter(|item| item.status.is_settled())
233 .count();
234 let header = format!(
235 "To-do {settled}/{total} · {}% settled",
236 snapshot.completion_pct
237 );
238
239 let mut selected: Vec<usize> = priority_order(snapshot)
240 .into_iter()
241 .take(MAX_CARD_ITEM_LINES)
242 .collect();
243 selected.sort_unstable();
244 let items: Vec<String> = selected
245 .iter()
246 .map(|idx| card_item_line(&snapshot.items[*idx]))
247 .collect();
248
249 Some(TodoCardProjection {
250 omitted: total - items.len(),
251 header,
252 items,
253 })
254 }
255
256 fn card_item_line(item: &TodoItem) -> String {
257 format!(
258 "{} #{} {}",
259 status_marker(item.status),
260 item.id,
261 sanitize_to(&item.content, MAX_CARD_ITEM_CONTENT_CHARS)
262 )
263 }
264
265 /// Row appended when the card bound elided items.
266 #[must_use]
267 pub fn card_omission_line(count: usize) -> String {
268 format!("{OMISSION_MARKER} +{count} more")
269 }
270
271 /// Heading the fork-state block uses for its To-do section.
272 pub const FORK_TODO_SECTION_HEADING: &str = "### To-do";
273
274 /// Render the To-do section of a `<codewhale:fork_state>` block.
275 ///
276 /// This is the one place a To-do snapshot is handed to a model that did not
277 /// produce it, and it happens exactly once — when a sub-agent is forked, as
278 /// part of the context block stored in that child's own history. It is not
279 /// refreshed, re-sent, or appended to later requests.
280 #[must_use]
281 pub fn fork_state_todo_section(body: &str) -> String {
282 format!("{FORK_TODO_SECTION_HEADING}\n\n{body}\n")
283 }
284
285 /// Item indexes in render priority: the active (in-progress) item first, then
286 /// document order. Shared by every bounded projection so no two surfaces can
287 /// disagree about which item matters most.
288 fn priority_order(snapshot: &TodoListSnapshot) -> Vec<usize> {
289 let active = active_index(snapshot);
290 let mut priority: Vec<usize> = Vec::with_capacity(snapshot.items.len());
291 if let Some(active) = active {
292 priority.push(active);
293 }
294 priority.extend((0..snapshot.items.len()).filter(|idx| Some(*idx) != active));
295 priority
296 }
297
298 fn active_index(snapshot: &TodoListSnapshot) -> Option<usize> {
299 snapshot
300 .in_progress_id
301 .and_then(|id| snapshot.items.iter().position(|item| item.id == id))
302 .or_else(|| {
303 snapshot
304 .items
305 .iter()
306 .position(|item| item.status == TodoStatus::InProgress)
307 })
308 }
309
310 fn status_marker(status: TodoStatus) -> &'static str {
311 match status {
312 TodoStatus::Pending => "[ ]",
313 TodoStatus::InProgress => "[~]",
314 TodoStatus::Completed => "[x]",
315 TodoStatus::Cancelled => "[-]",
316 }
317 }
318
319 fn item_line(item: &TodoItem) -> String {
320 // IDs stay visible: `work_update` addresses later transitions by stable
321 // item identity, so a body without IDs is not actionable.
322 format!(
323 "- {} #{} {}",
324 status_marker(item.status),
325 item.id,
326 sanitize(&item.content)
327 )
328 }
329
330 fn omission_line(count: usize) -> String {
331 format!("- {OMISSION_MARKER} +{count} more To-do items omitted")
332 }
333
334 fn sanitize(content: &str) -> String {
335 sanitize_to(content, MAX_ITEM_CONTENT_CHARS)
336 }
337
338 fn sanitize_to(content: &str, max_chars: usize) -> String {
339 let flattened: String = content
340 .chars()
341 .map(|ch| if ch.is_control() { ' ' } else { ch })
342 .collect();
343 let escaped = escape_wrapper(&flattened);
344 truncate_chars(escaped.trim(), max_chars)
345 }
346
347 /// Neutralize any closing tag in the `codewhale:` namespace so item content
348 /// cannot terminate a wrapper early and smuggle instructions past it.
349 fn escape_wrapper(content: &str) -> String {
350 if !content.to_ascii_lowercase().contains(CLOSE_PREFIX) {
351 return content.to_string();
352 }
353
354 let lower = content.to_ascii_lowercase();
355 let mut out = String::with_capacity(content.len() + 8);
356 let mut cursor = 0usize;
357 while let Some(found) = lower[cursor..].find(CLOSE_PREFIX) {
358 let at = cursor + found;
359 out.push_str(&content[cursor..at]);
360 out.push_str(ESCAPED_CLOSE_PREFIX);
361 cursor = at + CLOSE_PREFIX.len();
362 }
363 out.push_str(&content[cursor..]);
364 out
365 }
366
367 /// Truncate on `char` boundaries, marking the omission. Never splits a
368 /// multi-byte scalar.
369 fn truncate_chars(text: &str, max_chars: usize) -> String {
370 if text.chars().count() <= max_chars {
371 return text.to_string();
372 }
373 let keep = max_chars.saturating_sub(1);
374 let mut out: String = text.chars().take(keep).collect();
375 out.push(OMISSION_MARKER);
376 out
377 }
378
379 #[cfg(test)]
380 mod tests;
381
381 lines RUST