返回 CodeWhale
turn.rs
根目录 / crates / engine / src / core / turn.rs
1 //! Turn context and tracking.
2 //!
3 //! A "turn" is one user message and the resulting AI response,
4 //! including any tool calls that occur.
5 //!
6 //! ## Snapshot lifecycle hooks
7 //!
8 //! [`restore_point_snapshot`] (`pre-turn:`, `tool:`, `post-tool:`) and
9 //! [`post_turn_snapshot`] book-end a turn and its tool calls by
10 //! taking a workspace-level snapshot into a side git repo (see
11 //! `codewhale_snapshot`). They are intentionally non-blocking and
12 //! non-fatal: any IO error is logged at WARN and swallowed so a busted
13 //! filesystem or missing `git` binary never derails the agent loop.
14 //! `/restore N` and the `revert_turn` tool both consume these
15 //! snapshots.
16
17 use crate::core::events::TurnRoute;
18 use codewhale_models::Usage;
19 use codewhale_snapshot::{SnapshotRepo, TakenSnapshot};
20 use std::path::Path;
21 use std::time::Instant;
22
23 /// Which configured limit governs a turn's step budget (#5994).
24 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
25 pub enum StepBudgetSource {
26 /// The ordinary interactive ceiling (`max_steps`).
27 Interactive,
28 /// The goal-turn allowance (`[goal] max_steps`).
29 Goal,
30 }
31
32 impl StepBudgetSource {
33 /// The configuration key named in exhaustion notices.
34 #[must_use]
35 pub const fn key_label(self) -> &'static str {
36 match self {
37 Self::Interactive => "max_steps",
38 Self::Goal => "[goal] max_steps",
39 }
40 }
41 }
42
43 /// Where a turn's user message sat in the session right after it was added:
44 /// the session length and messages revision then. Together they identify
45 /// that message; a later append or rewrite changes one of them (#6566).
46 #[derive(Debug, Clone, PartialEq, Eq)]
47 pub struct UnansweredUserMessage {
48 pub index: usize,
49 pub content_sha256: String,
50 }
51
52 /// Context for a single turn (user message + AI response).
53 #[derive(Debug)]
54 pub struct TurnContext {
55 pub max_output_tokens: Option<std::num::NonZeroU32>,
56 /// Turn ID
57 pub id: String,
58
59 /// When the turn started
60 pub started_at: Instant,
61
62 /// Current step in the turn (tool call iteration)
63 pub step: u32,
64
65 /// Configured steps, or `u32::MAX` for no limit. Use `step_limit` for
66 /// budget decisions; the counter saturates without stopping an uncapped turn.
67 pub max_steps: u32,
68
69 /// Which configured limit `max_steps` came from.
70 pub budget_source: StepBudgetSource,
71
72 /// The turn's step budget was exhausted and the bounded final report was
73 /// granted (#5994). Set by the turn loop; the cross-turn goal fence reads
74 /// it so an exhausted goal pauses instead of re-arming.
75 pub budget_exhausted_final_report: bool,
76 /// This turn's user message while no model request has been accepted
77 /// yet. A credential rejection while it is still the last message takes
78 /// it back out of the session, so a retry after fixing the key is not a
79 /// duplicate (#6566). Cleared once a request is accepted: from then on a
80 /// model has seen the message.
81 pub unanswered_user_message: Option<UnansweredUserMessage>,
82
83 pub stop_diagnostics: crate::tool_inspection::TurnStopDiagnostics,
84 pub last_request_snapshot: Option<crate::tool_inspection::ToolInspectionSnapshot>,
85
86 /// Number of tool calls made in this turn.
87
88 /// Usage for this turn
89 pub usage: Usage,
90
91 /// Subset of `usage` served by the parent turn's frozen route. Programmatic
92 /// reviewer/RLM calls remain in the total above but are billed only from
93 /// their own routed receipts.
94 pub parent_route_usage: Usage,
95
96 /// Provider calls whose usage became ambiguous after dispatch (for
97 /// example an RLM timeout). A non-zero value makes cost coverage
98 /// explicitly incomplete instead of inventing a zero-usage receipt.
99 pub routed_usage_dropped_records: u64,
100
101 /// Input tokens reported for the most recent parent-route model request.
102 /// This is deliberately separate from `usage`, which accumulates every
103 /// parent step and programmatic child call for billing.
104 pub latest_parent_input_tokens: Option<u32>,
105
106 /// `session.messages.len()` at the parent request whose billed prompt is
107 /// in `latest_parent_input_tokens`. Tool results appended after that
108 /// request are not in the bill; GrokBuild's pre-sampling gate adds a
109 /// byte-estimate of that suffix so auto-compact can fire mid-turn.
110 pub messages_len_at_last_parent_prompt: Option<usize>,
111 pub input_token_ratio: (usize, usize),
112 pub last_compaction_step: Option<u32>,
113
114 /// One-shot latch: an automatic-compaction refusal has already been
115 /// surfaced this turn. Pressure is re-checked every step, and repeating
116 /// the same refusal on each of a long turn's steps would be noise.
117 pub compaction_refusal_notified: bool,
118
119 /// Route facts resolved for this turn but not timestamped until the first
120 /// provider request is actually dispatched.
121 pub pending_route: Option<TurnRoute>,
122
123 /// The provider's answer when it rejected an emergency context-recovery
124 /// request (capability, auth, unreachable). The turn then fails on that
125 /// cause, not on the context budget the recovery was trying to fix.
126 pub context_recovery_rejection: Option<anyhow::Error>,
127 pub recent_actions: Vec<RecentReviewAction>,
128 }
129
130 #[derive(Debug, Clone, PartialEq, Eq)]
131 pub struct RecentReviewAction {
132 pub tool_name: String,
133 pub summary: String,
134 }
135
136 impl TurnContext {
137 /// Create a new turn context
138 pub fn new(max_steps: u32) -> Self {
139 Self::with_budget_source(max_steps, StepBudgetSource::Interactive)
140 }
141
142 /// Create a turn context with an explicit budget provenance (#5994).
143 pub fn with_budget_source(max_steps: u32, budget_source: StepBudgetSource) -> Self {
144 Self {
145 max_output_tokens: None,
146 id: uuid::Uuid::new_v4().to_string(),
147 started_at: Instant::now(),
148 step: 0,
149 max_steps,
150 budget_source,
151 budget_exhausted_final_report: false,
152 unanswered_user_message: None,
153 stop_diagnostics: crate::tool_inspection::TurnStopDiagnostics {
154 effective_max_steps: (max_steps != u32::MAX).then_some(max_steps),
155 step_budget_source: budget_source.key_label(),
156 ..Default::default()
157 },
158 last_request_snapshot: None,
159 usage: Usage {
160 input_tokens: 0,
161 output_tokens: 0,
162 ..Usage::default()
163 },
164 parent_route_usage: Usage::default(),
165 routed_usage_dropped_records: 0,
166 latest_parent_input_tokens: None,
167 messages_len_at_last_parent_prompt: None,
168 input_token_ratio: (1, 1),
169 last_compaction_step: None,
170 compaction_refusal_notified: false,
171 pending_route: None,
172 context_recovery_rejection: None,
173 recent_actions: Vec::new(),
174 }
175 }
176
177 /// Increment the step counter
178 pub fn next_step(&mut self) -> bool {
179 self.step = self.step.saturating_add(1);
180 self.step_limit().is_none_or(|limit| self.step <= limit)
181 }
182
183 /// A resolved integer default means no ceiling, including at counter
184 /// saturation. Explicit positive configuration is clamped before here.
185 #[must_use]
186 pub fn step_limit(&self) -> Option<u32> {
187 (self.max_steps != u32::MAX).then_some(self.max_steps)
188 }
189
190 /// Check if the turn has reached max steps
191 pub fn at_max_steps(&self) -> bool {
192 self.step_limit().is_some_and(|limit| self.step >= limit)
193 }
194
195 /// Model steps consumed so far (for reporting).
196 #[must_use]
197 pub fn steps_used(&self) -> u32 {
198 self.step
199 }
200
201 /// Complete the existing request projection with observed turn-exit facts.
202 /// A turn that never prepared a request has no request snapshot to publish.
203 pub fn terminal_request_snapshot(
204 &mut self,
205 status: super::events::TurnOutcomeStatus,
206 ) -> Option<crate::tool_inspection::ToolInspectionSnapshot> {
207 use crate::tool_inspection::TurnStopReason;
208 self.stop_diagnostics.status = Some(status);
209 self.stop_diagnostics.model_step_index = self.step;
210 self.stop_diagnostics.final_report_requested |= self.budget_exhausted_final_report;
211 self.stop_diagnostics.last_reported_input_tokens = self.latest_parent_input_tokens;
212 match status {
213 super::events::TurnOutcomeStatus::Interrupted => {
214 self.stop_diagnostics.reason = Some(TurnStopReason::Interrupted);
215 }
216 super::events::TurnOutcomeStatus::Failed if self.stop_diagnostics.reason.is_none() => {
217 self.stop_diagnostics.reason = Some(TurnStopReason::Failed);
218 }
219 _ => {}
220 }
221 let mut snapshot = self.last_request_snapshot.take()?;
222 snapshot.terminal = Some(self.stop_diagnostics.clone());
223 Some(snapshot)
224 }
225
226 /// Add usage from an API response
227 pub fn add_usage(&mut self, usage: &Usage) {
228 add_usage_to(&mut self.usage, usage);
229 }
230
231 /// Record one parent-route response for both billing and live-context
232 /// pressure. Child-model usage must call [`Self::add_usage`] directly so
233 /// it cannot masquerade as the parent request's context size.
234 pub fn add_parent_usage(&mut self, usage: &Usage) {
235 let latest = usage.request_usages.last().unwrap_or(usage);
236 self.latest_parent_input_tokens = (latest.input_tokens > 0).then_some(latest.input_tokens);
237 self.add_usage(usage);
238 add_usage_to(&mut self.parent_route_usage, usage);
239 }
240
241 pub fn add_routed_usage_dropped_records(&mut self, dropped_records: u64) {
242 self.routed_usage_dropped_records = self
243 .routed_usage_dropped_records
244 .saturating_add(dropped_records);
245 }
246
247 /// Add programmatic child-call usage to the authoritative total and
248 /// return the same batch aggregate for telemetry emission.
249 pub fn add_routed_usages<'a>(&mut self, usages: impl IntoIterator<Item = &'a Usage>) -> Usage {
250 let mut aggregate = Usage::default();
251 for usage in usages {
252 self.add_usage(usage);
253 add_usage_to(&mut aggregate, usage);
254 }
255 aggregate
256 }
257 }
258
259 pub fn add_usage_to(total: &mut Usage, delta: &Usage) {
260 if total.request_usages.is_empty() && (total.input_tokens > 0 || total.output_tokens > 0) {
261 total.request_usages.push(total.clone());
262 }
263 if total.request_usages.len() <= 1024 {
264 if delta.request_usages.is_empty() {
265 total.request_usages.push(delta.clone());
266 } else {
267 let remaining = 1025 - total.request_usages.len();
268 total
269 .request_usages
270 .extend(delta.request_usages.iter().take(remaining).cloned());
271 }
272 }
273 total.input_tokens = total.input_tokens.saturating_add(delta.input_tokens);
274 total.output_tokens = total.output_tokens.saturating_add(delta.output_tokens);
275 total.prompt_cache_hit_tokens =
276 add_optional_usage(total.prompt_cache_hit_tokens, delta.prompt_cache_hit_tokens);
277 total.prompt_cache_miss_tokens = add_optional_usage(
278 total.prompt_cache_miss_tokens,
279 delta.prompt_cache_miss_tokens,
280 );
281 total.prompt_cache_write_tokens = add_optional_usage(
282 total.prompt_cache_write_tokens,
283 delta.prompt_cache_write_tokens,
284 );
285 total.reasoning_tokens = add_optional_usage(total.reasoning_tokens, delta.reasoning_tokens);
286 total.input_audio_tokens =
287 add_optional_usage(total.input_audio_tokens, delta.input_audio_tokens);
288 total.output_audio_tokens =
289 add_optional_usage(total.output_audio_tokens, delta.output_audio_tokens);
290 total.reasoning_replay_tokens =
291 add_optional_usage(total.reasoning_replay_tokens, delta.reasoning_replay_tokens);
292 total.safety_tokens = add_optional_usage(total.safety_tokens, delta.safety_tokens);
293 if let Some(delta) = delta.server_tool_use.as_ref() {
294 let server_total = total.server_tool_use.get_or_insert_default();
295 server_total.code_execution_requests = add_optional_usage(
296 server_total.code_execution_requests,
297 delta.code_execution_requests,
298 );
299 server_total.tool_search_requests = add_optional_usage(
300 server_total.tool_search_requests,
301 delta.tool_search_requests,
302 );
303 server_total.web_search_requests =
304 add_optional_usage(server_total.web_search_requests, delta.web_search_requests);
305 server_total.web_fetch_requests =
306 add_optional_usage(server_total.web_fetch_requests, delta.web_fetch_requests);
307 server_total.tool_search = add_optional_usage(server_total.tool_search, delta.tool_search);
308 server_total.tool_fetch = add_optional_usage(server_total.tool_fetch, delta.tool_fetch);
309 server_total.tool_image_search =
310 add_optional_usage(server_total.tool_image_search, delta.tool_image_search);
311 }
312 }
313
314 impl TurnContext {
315 /// Billed prompt the compaction gate should honor: this turn's latest
316 /// parent request, else the session-carried receipt from the previous
317 /// turn. A fresh `TurnContext` starts empty, so without the session
318 /// fallback an 842k DeepSeek bill dies at the turn boundary and the
319 /// next send never auto-compacts (#5577).
320 #[must_use]
321 pub fn billed_input_tokens_for_compaction(&self, session_billed: Option<u32>) -> Option<u64> {
322 self.latest_parent_input_tokens
323 .or(session_billed)
324 .map(u64::from)
325 }
326
327 /// Record how long the transcript was when the latest parent prompt was
328 /// billed. Call immediately after `add_parent_usage`, before this
329 /// response's assistant/tool messages are appended.
330 pub fn note_parent_prompt_len(&mut self, message_count: usize, estimated_input: usize) {
331 self.messages_len_at_last_parent_prompt = Some(message_count);
332 if let Some(reported) = self.latest_parent_input_tokens
333 && estimated_input > 0
334 && u128::from(reported) * self.input_token_ratio.1 as u128
335 > self.input_token_ratio.0 as u128 * estimated_input as u128
336 {
337 self.input_token_ratio = (reported as usize, estimated_input);
338 }
339 }
340
341 pub fn calibrated_input_tokens(&self, estimate: usize) -> usize {
342 crate::compaction::calibrate_token_estimate(estimate, self.input_token_ratio)
343 }
344
345 pub fn compaction_thrash_message(&self) -> Option<String> {
346 let attempts = self
347 .stop_diagnostics
348 .automatic_compaction_attempts
349 .saturating_add(self.stop_diagnostics.emergency_compaction_attempts);
350 (attempts >= 2
351 && self.last_compaction_step.is_some_and(|step| self.step.saturating_sub(step) <= 2))
352 .then(|| "Context filled again within two model steps after repeated compaction. The turn was stopped to preserve the task and avoid another summary loop. The conversation is saved; choose a larger context route or reduce the task's retained input before retrying.".to_string())
353 }
354
355 /// Live context for the auto-compact gate: last billed prompt plus a
356 /// calibrated estimate of messages appended since that prompt (tool results,
357 /// the assistant reply that will be replayed on the next request).
358 ///
359 /// `max(billed, estimate(full list))` hides mid-turn growth when the
360 /// estimator undercounts the whole transcript below the last bill —
361 /// which is why auto-compact never fired even with the UI meter above
362 /// 80%. GrokBuild's `check_auto_compact_needed` uses the same split:
363 /// exact prior count + byte-estimate of items since last response.
364 #[must_use]
365 pub fn live_input_tokens_for_compaction(
366 &self,
367 messages: &[codewhale_models::Message],
368 system_prompt: Option<&codewhale_models::SystemPrompt>,
369 session_billed: Option<u32>,
370 ) -> Option<u64> {
371 let billed = self.billed_input_tokens_for_compaction(session_billed);
372 let suffix_start = self
373 .messages_len_at_last_parent_prompt
374 .unwrap_or(messages.len())
375 .min(messages.len());
376 let suffix = &messages[suffix_start..];
377 let growth = if suffix.is_empty() {
378 0
379 } else {
380 u64::try_from(self.calibrated_input_tokens(
381 crate::compaction::estimate_input_tokens_for_pressure(suffix, None),
382 ))
383 .unwrap_or(u64::MAX)
384 };
385 let estimated = u64::try_from(self.calibrated_input_tokens(
386 crate::compaction::estimate_input_tokens_for_pressure(messages, system_prompt),
387 ))
388 .unwrap_or(u64::MAX);
389 let live = estimated.max(billed.unwrap_or(0).saturating_add(growth));
390 (live > 0).then_some(live)
391 }
392
393 /// Drop the turn-local billed receipt after history is rewritten, retaining
394 /// the learned token ratio for the replacement history and its growth.
395 pub fn clear_parent_input_tokens(&mut self) {
396 self.latest_parent_input_tokens = None;
397 self.messages_len_at_last_parent_prompt = None;
398 }
399 }
400
401 fn add_optional_usage(total: Option<u32>, delta: Option<u32>) -> Option<u32> {
402 match (total, delta) {
403 (Some(total), Some(delta)) => Some(total.saturating_add(delta)),
404 (None, Some(delta)) => Some(delta),
405 (Some(total), None) => Some(total),
406 (None, None) => None,
407 }
408 }
409
410 #[cfg(test)]
411 mod usage_tests {
412 use super::*;
413 use codewhale_models::ServerToolUsage;
414
415 #[test]
416 fn add_usage_preserves_replay_and_saturates_server_tool_counters() {
417 let mut turn = TurnContext::new(2);
418 turn.add_usage(&Usage {
419 reasoning_replay_tokens: Some(u32::MAX - 1),
420 server_tool_use: Some(ServerToolUsage {
421 code_execution_requests: Some(u32::MAX),
422 tool_search_requests: Some(2),
423 ..Default::default()
424 }),
425 ..Usage::default()
426 });
427 turn.add_usage(&Usage {
428 reasoning_replay_tokens: Some(9),
429 server_tool_use: Some(ServerToolUsage {
430 code_execution_requests: Some(1),
431 tool_search_requests: Some(3),
432 ..Default::default()
433 }),
434 ..Usage::default()
435 });
436
437 assert_eq!(turn.usage.reasoning_replay_tokens, Some(u32::MAX));
438 let server = turn.usage.server_tool_use.expect("server tool usage");
439 assert_eq!(server.code_execution_requests, Some(u32::MAX));
440 assert_eq!(server.tool_search_requests, Some(5));
441 }
442
443 fn below_threshold(messages: &[codewhale_models::Message], turn: &TurnContext) -> bool {
444 let config = crate::compaction::CompactionConfig {
445 enabled: true,
446 token_threshold: 100_000,
447 ..Default::default()
448 };
449 !crate::compaction::compaction_pressure_reached_with_billed(
450 messages,
451 None,
452 &config,
453 turn.latest_parent_input_tokens.map(u64::from),
454 )
455 }
456
457 #[test]
458 fn cumulative_low_context_parent_steps_cannot_trigger_compaction() {
459 let mut turn = TurnContext::new(4);
460 turn.add_parent_usage(&Usage {
461 input_tokens: 60_000,
462 ..Usage::default()
463 });
464 turn.add_parent_usage(&Usage {
465 input_tokens: 70_000,
466 ..Usage::default()
467 });
468
469 assert_eq!(turn.usage.input_tokens, 130_000);
470 assert_eq!(turn.latest_parent_input_tokens, Some(70_000));
471 assert!(below_threshold(&[], &turn));
472 }
473
474 #[test]
475 fn child_usage_cannot_replace_parent_context_pressure() {
476 let mut turn = TurnContext::new(4);
477 turn.add_parent_usage(&Usage {
478 input_tokens: 70_000,
479 ..Usage::default()
480 });
481 turn.add_usage(&Usage {
482 input_tokens: 250_000,
483 ..Usage::default()
484 });
485
486 assert_eq!(turn.usage.input_tokens, 320_000);
487 assert_eq!(turn.latest_parent_input_tokens, Some(70_000));
488 assert!(below_threshold(&[], &turn));
489 }
490
491 #[test]
492 fn fresh_turn_inherits_session_billed_prompt_for_compaction() {
493 let turn = TurnContext::new(4);
494 assert_eq!(turn.latest_parent_input_tokens, None);
495 assert_eq!(
496 turn.billed_input_tokens_for_compaction(Some(842_000)),
497 Some(842_000)
498 );
499 assert_eq!(turn.billed_input_tokens_for_compaction(None), None);
500 }
501
502 #[test]
503 fn live_turn_billed_outranks_stale_session_billed() {
504 let mut turn = TurnContext::new(4);
505 turn.add_parent_usage(&Usage {
506 input_tokens: 12_000,
507 ..Usage::default()
508 });
509 assert_eq!(
510 turn.billed_input_tokens_for_compaction(Some(842_000)),
511 Some(12_000)
512 );
513 turn.clear_parent_input_tokens();
514 assert_eq!(turn.latest_parent_input_tokens, None);
515 assert_eq!(turn.messages_len_at_last_parent_prompt, None);
516 assert_eq!(
517 turn.billed_input_tokens_for_compaction(Some(842_000)),
518 Some(842_000)
519 );
520 }
521
522 #[test]
523 fn live_compaction_tokens_include_tool_results_after_the_billed_prompt() {
524 // GrokBuild/Codex: last billed prompt + items since that request.
525 // A 70k bill plus a large tool result must cross an 80k trigger even
526 // when the full-list /4 estimate stays below the bill (the failure
527 // mode that kept auto-compact from firing mid-turn above 80%).
528 let mut turn = TurnContext::new(4);
529 turn.add_parent_usage(&Usage {
530 input_tokens: 70_000,
531 ..Usage::default()
532 });
533 let prompt = vec![codewhale_models::Message {
534 role: codewhale_models::Role::User,
535 content: vec![codewhale_models::ContentBlock::Text {
536 text: "do the work".to_string(),
537 cache_control: None,
538 }],
539 }];
540 turn.note_parent_prompt_len(prompt.len(), 70_000);
541
542 let mut with_tool = prompt;
543 with_tool.push(codewhale_models::Message {
544 role: codewhale_models::Role::User,
545 content: vec![codewhale_models::ContentBlock::ToolResult {
546 execution_id: None,
547 tool_use_id: "call-1".to_string(),
548 content: "x".repeat(80_000),
549 is_error: None,
550 content_blocks: None,
551 }],
552 });
553
554 let config = crate::compaction::CompactionConfig {
555 enabled: true,
556 token_threshold: 80_000,
557 ..Default::default()
558 };
559 assert!(
560 !crate::compaction::compaction_pressure_reached_with_billed(
561 &with_tool,
562 None,
563 &config,
564 turn.billed_input_tokens_for_compaction(None),
565 ),
566 "stale billed prompt alone must not be the live gate"
567 );
568 let live = turn
569 .live_input_tokens_for_compaction(&with_tool, None, None)
570 .expect("live tokens");
571 assert!(
572 live >= 80_000,
573 "tool-result suffix must lift live tokens over the trigger, got {live}"
574 );
575 assert!(crate::compaction::compaction_pressure_reached_with_billed(
576 &with_tool,
577 None,
578 &config,
579 Some(live),
580 ));
581 turn.note_parent_prompt_len(1, 35_000);
582 let calibrated = turn
583 .live_input_tokens_for_compaction(&with_tool, None, None)
584 .expect("calibrated live tokens");
585 assert!(calibrated > live);
586 turn.clear_parent_input_tokens();
587 assert_eq!(turn.calibrated_input_tokens(20_000), 40_000);
588 turn.last_compaction_step = Some(3);
589 turn.step = 4;
590 turn.stop_diagnostics.automatic_compaction_attempts = 2;
591 assert!(turn.compaction_thrash_message().is_some());
592 turn.step = 6;
593 assert!(turn.compaction_thrash_message().is_none());
594 }
595 }
596
597 /// Maximum characters of the user prompt snippet to embed in a snapshot
598 /// label. Longer prompts are truncated with an ellipsis.
599 const USER_PROMPT_LABEL_MAX: usize = 100;
600
601 /// Format a snapshot label that includes the user prompt for readability
602 /// in `/restore` listings.
603 ///
604 /// Takes the first line of the prompt (up to `USER_PROMPT_LABEL_MAX`
605 /// characters) and appends it to the traditional `type:seq` label so
606 /// users can identify which turn each snapshot belongs to.
607 pub fn format_snapshot_label(prefix: &str, turn_seq: u64, user_prompt: Option<&str>) -> String {
608 let base = format!("{prefix}:{turn_seq}");
609 match user_prompt {
610 None | Some("") => base,
611 Some(prompt) => match snapshot_label_prompt_snippet(prompt) {
612 None => base,
613 Some(snippet) => format!("{base}: {snippet}"),
614 },
615 }
616 }
617
618 /// The exact prompt snippet [`format_snapshot_label`] embeds after `type:seq`.
619 ///
620 /// Read surfaces that want to correlate a recorded prompt back to a restore
621 /// point must go through this function rather than re-deriving the truncation,
622 /// so the reader and the writer can never disagree about what a label means.
623 /// Returns `None` when the prompt contributes no snippet at all.
624 pub fn snapshot_label_prompt_snippet(prompt: &str) -> Option<String> {
625 if prompt.is_empty() {
626 return None;
627 }
628 let first_line = prompt.lines().next().unwrap_or("");
629 let truncated: String = first_line.chars().take(USER_PROMPT_LABEL_MAX).collect();
630 if truncated.chars().count() < first_line.chars().count() {
631 Some(format!("{truncated}…"))
632 } else {
633 Some(truncated)
634 }
635 }
636
637 /// A snapshot label parsed back into its parts.
638 #[derive(Debug, Clone, PartialEq, Eq)]
639 pub struct ParsedSnapshotLabel {
640 /// `pre-turn`, `post-turn`, `tool`, or whatever prefix produced it.
641 pub kind: String,
642 /// The turn sequence for `pre-turn`/`post-turn` labels. `tool` labels
643 /// carry a call id rather than a sequence, so this stays `None` for them.
644 pub seq: Option<u64>,
645 /// The embedded prompt snippet, exactly as
646 /// [`snapshot_label_prompt_snippet`] produced it.
647 pub prompt_snippet: Option<String>,
648 }
649
650 /// Parse a label produced by [`format_snapshot_label`].
651 ///
652 /// This is deliberately total: an unrecognized label still yields a record with
653 /// the raw text as `kind`, because a read surface must describe what is really
654 /// stored rather than silently dropping rows it does not recognize.
655 pub fn parse_snapshot_label(label: &str) -> ParsedSnapshotLabel {
656 let (head, snippet) = match label.split_once(": ") {
657 Some((head, rest)) => (head, Some(rest.to_string())),
658 None => (label, None),
659 };
660 match head.split_once(':') {
661 Some((kind, seq)) => ParsedSnapshotLabel {
662 kind: kind.to_string(),
663 seq: seq.parse::<u64>().ok(),
664 prompt_snippet: snippet,
665 },
666 None => ParsedSnapshotLabel {
667 kind: head.to_string(),
668 seq: None,
669 prompt_snippet: snippet,
670 },
671 }
672 }
673
674 /// Take a `pre-turn:<seq>` workspace snapshot.
675 ///
676 /// `cap_bytes` is the workspace-size ceiling that gates first-init
677 /// (passed through to [`SnapshotRepo::open_or_init_with_cap`]); pass
678 /// `0` to disable the cap.
679 /// `user_prompt` is an optional snippet of the user's message for this
680 /// turn, embedded in the snapshot label so `/restore` listings are
681 /// human-readable.
682 ///
683 /// Returns the snapshot (commit and tree) on success, `None` on any error.
684 /// Errors are logged at WARN; the turn loop must not block on this. The
685 /// engine takes its pre-turn snapshots through [`restore_point_snapshot`].
686 #[cfg(any(test, feature = "test-support"))]
687 pub fn pre_turn_snapshot(
688 workspace: &Path,
689 turn_seq: u64,
690 cap_bytes: u64,
691 user_prompt: Option<&str>,
692 session_id: Option<&str>,
693 ) -> Option<TakenSnapshot> {
694 snapshot_with_label(
695 workspace,
696 &format_snapshot_label("pre-turn", turn_seq, user_prompt),
697 cap_bytes,
698 session_id,
699 )
700 }
701
702 /// Take a workspace snapshot under `label` for the running turn, and report
703 /// which paths changed since the turn's previous snapshot `since` (a tree or
704 /// commit id).
705 ///
706 /// The comparison runs before the count prune that follows every snapshot,
707 /// so `since` is still in the store; `None` for the changed paths means there
708 /// was no `since` or it could not be compared. `None` on any error, logged
709 /// at WARN; the turn loop must not block on it.
710 pub fn restore_point_snapshot(
711 workspace: &Path,
712 label: &str,
713 cap_bytes: u64,
714 session_id: Option<&str>,
715 since: Option<&codewhale_snapshot::SnapshotId>,
716 ) -> Option<(TakenSnapshot, Option<Vec<std::path::PathBuf>>)> {
717 snapshot_with_label_since(workspace, label, cap_bytes, session_id, since)
718 }
719
720 /// Take a `post-turn:<seq>` workspace snapshot. Same failure model as
721 /// [`restore_point_snapshot`].
722 pub fn post_turn_snapshot(
723 workspace: &Path,
724 turn_seq: u64,
725 cap_bytes: u64,
726 user_prompt: Option<&str>,
727 session_id: Option<&str>,
728 ) -> Option<TakenSnapshot> {
729 snapshot_with_label(
730 workspace,
731 &format_snapshot_label("post-turn", turn_seq, user_prompt),
732 cap_bytes,
733 session_id,
734 )
735 }
736
737 fn snapshot_with_label(
738 workspace: &Path,
739 label: &str,
740 cap_bytes: u64,
741 session_id: Option<&str>,
742 ) -> Option<TakenSnapshot> {
743 snapshot_with_label_since(workspace, label, cap_bytes, session_id, None).map(|(taken, _)| taken)
744 }
745
746 fn snapshot_with_label_since(
747 workspace: &Path,
748 label: &str,
749 cap_bytes: u64,
750 session_id: Option<&str>,
751 since: Option<&codewhale_snapshot::SnapshotId>,
752 ) -> Option<(TakenSnapshot, Option<Vec<std::path::PathBuf>>)> {
753 match SnapshotRepo::open_or_init_with_cap(workspace, cap_bytes) {
754 Ok(repo) => {
755 // Undo that silently stops working is the failure this guards
756 // (B2): a repaired history and a failing snapshot both reach the
757 // user through the same notice as the gates, never only a log.
758 let taken = repo.repair_broken_head().and_then(|repaired| {
759 repo.take_snapshot(label, session_id)
760 .map(|taken| (taken, repaired))
761 });
762 let (id, repaired) = match taken {
763 Ok((taken, repaired)) => (Some(taken), repaired),
764 Err(e) => {
765 tracing::warn!(target: "snapshot", "snapshot '{label}' failed: {e}");
766 record_snapshot_notice(
767 workspace,
768 session_id,
769 SnapshotsDisabledScope::Failing,
770 snapshot_failure_detail(&e),
771 );
772 return None;
773 }
774 };
775 clear_snapshots_disabled_status(workspace, session_id);
776 if repaired {
777 record_snapshot_notice(
778 workspace,
779 session_id,
780 SnapshotsDisabledScope::HistoryRepaired,
781 String::new(),
782 );
783 }
784 // What changed since the turn's previous snapshot, compared
785 // before the prune below can drop that snapshot.
786 let changed = match (&id, since) {
787 (Some(taken), Some(since)) if since.as_str() == taken.tree.as_str() => {
788 Some(Vec::new())
789 }
790 (Some(taken), Some(since)) => {
791 match repo.changed_paths_between(since, &taken.tree) {
792 Ok(paths) => Some(paths),
793 Err(e) => {
794 tracing::warn!(
795 target: "snapshot",
796 "comparing snapshot '{label}' with the turn's previous one failed: {e}"
797 );
798 None
799 }
800 }
801 }
802 _ => None,
803 };
804 // Prune oldest snapshots to cap disk usage (#1112).
805 if let Err(e) = repo.prune_keep_last_n_batched(max_snapshots_for(workspace)) {
806 tracing::warn!(target: "snapshot", "snapshot prune failed: {e}");
807 }
808 id.map(|taken| (taken, changed))
809 }
810 Err(e) => {
811 // The first gated failure belongs to this session, even when other
812 // sessions use the same workspace in this process (#5930).
813 if maybe_notify_snapshots_disabled_once(workspace, session_id, cap_bytes, &e) {
814 tracing::warn!(target: "snapshot", session_id, "snapshot repo init failed: {e}");
815 } else {
816 tracing::debug!(target: "snapshot", "snapshot repo init still failing: {e}");
817 }
818 None
819 }
820 }
821 }
822
823 /// The count cap [`SnapshotRepo::prune_keep_last_n`] applies after each
824 /// snapshot: [`codewhale_snapshot::DEFAULT_MAX_SNAPSHOTS`], which tests can
825 /// lower per workspace to exercise pruning without taking fifty snapshots.
826 fn max_snapshots_for(workspace: &Path) -> usize {
827 #[cfg(any(test, feature = "test-support"))]
828 if let Some(max) = test_max_snapshots::get(workspace) {
829 return max;
830 }
831 let _ = workspace;
832 codewhale_snapshot::DEFAULT_MAX_SNAPSHOTS
833 }
834
835 #[cfg(any(test, feature = "test-support"))]
836 pub mod test_max_snapshots {
837 use std::collections::HashMap;
838 use std::path::{Path, PathBuf};
839
840 static OVERRIDES: parking_lot::Mutex<Option<HashMap<PathBuf, usize>>> =
841 parking_lot::Mutex::new(None);
842
843 fn key(workspace: &Path) -> PathBuf {
844 workspace
845 .canonicalize()
846 .unwrap_or_else(|_| workspace.to_path_buf())
847 }
848
849 /// Prune `workspace`'s snapshots to `max` (plus as many turn
850 /// boundaries) after each snapshot, for the rest of the test process.
851 pub fn set(workspace: &Path, max: usize) {
852 OVERRIDES
853 .lock()
854 .get_or_insert_with(HashMap::new)
855 .insert(key(workspace), max);
856 }
857
858 pub(super) fn get(workspace: &Path) -> Option<usize> {
859 OVERRIDES
860 .lock()
861 .as_ref()
862 .and_then(|overrides| overrides.get(&key(workspace)).copied())
863 }
864 }
865
866 // Shared snapshot data; host localization and session retention stay here.
867 #[cfg(test)]
868 pub use codewhale_command_contract::config_policy::SNAPSHOTS_CAP_CONFIG_KEY;
869 pub use codewhale_command_contract::config_policy::{
870 StatusSnapshotNotice as SnapshotsDisabledNotice, StatusSnapshotScope as SnapshotsDisabledScope,
871 };
872
873 /// Host localization of the shared semantic notice, including the toast surface.
874 pub trait SnapshotsDisabledNoticeUi {
875 fn localize(&self, locale: codewhale_localization::Locale) -> String;
876 }
877 impl SnapshotsDisabledNoticeUi for SnapshotsDisabledNotice {
878 fn localize(&self, locale: codewhale_localization::Locale) -> String {
879 use codewhale_localization::MessageId;
880 let id = match self.scope {
881 SnapshotsDisabledScope::WorkspaceTooLarge => MessageId::SnapshotsDisabledTooLarge,
882 SnapshotsDisabledScope::TooManyFiles => MessageId::SnapshotsDisabledTooManyFiles,
883 SnapshotsDisabledScope::UnsafeLocation => MessageId::SnapshotsDisabledUnsafeLocation,
884 SnapshotsDisabledScope::HistoryRepaired => MessageId::SnapshotsHistoryRepaired,
885 SnapshotsDisabledScope::Failing => MessageId::SnapshotsFailing,
886 };
887 self.render(&codewhale_localization::tr(locale, id))
888 }
889 }
890
891 /// Human-readable byte cap for the size-gate notice. Keeps small test caps
892 /// from rendering as a misleading `0 GB`.
893 fn format_cap_bytes(bytes: u64) -> String {
894 const KIB: f64 = 1024.0;
895 let value = bytes as f64;
896 if value >= KIB.powi(3) {
897 format!("{:.1} GB", value / KIB.powi(3))
898 } else if value >= KIB.powi(2) {
899 format!("{:.1} MB", value / KIB.powi(2))
900 } else if value >= KIB {
901 format!("{:.1} KB", value / KIB)
902 } else {
903 format!("{bytes} bytes")
904 }
905 }
906
907 type SnapshotNoticeKey = (std::path::PathBuf, Option<String>);
908
909 #[derive(Default)]
910 struct SnapshotNoticeState {
911 announced: Option<SnapshotsDisabledScope>,
912 announced_scopes: Vec<SnapshotsDisabledScope>,
913 pending: bool,
914 resumed: bool,
915 disabled: Option<SnapshotsDisabledNotice>,
916 }
917
918 fn snapshot_notices()
919 -> &'static std::sync::Mutex<std::collections::HashMap<SnapshotNoticeKey, SnapshotNoticeState>> {
920 static NOTICES: std::sync::OnceLock<
921 std::sync::Mutex<std::collections::HashMap<SnapshotNoticeKey, SnapshotNoticeState>>,
922 > = std::sync::OnceLock::new();
923 NOTICES.get_or_init(Default::default)
924 }
925
926 fn snapshot_notice_key(workspace: &Path, session_id: Option<&str>) -> SnapshotNoticeKey {
927 (workspace.to_path_buf(), session_id.map(str::to_owned))
928 }
929
930 /// Take only this session's pending delivery. Other sessions in the same
931 /// workspace keep their own notice; the observed disabled status remains.
932 pub fn take_snapshots_disabled_notices(
933 workspace: &Path,
934 session_id: Option<&str>,
935 ) -> Vec<SnapshotsDisabledNotice> {
936 let mut states = snapshot_notices()
937 .lock()
938 .unwrap_or_else(std::sync::PoisonError::into_inner);
939 let Some(state) = states.get_mut(&snapshot_notice_key(workspace, session_id)) else {
940 return Vec::new();
941 };
942 if !std::mem::take(&mut state.pending) {
943 return Vec::new();
944 }
945 state.disabled.iter().cloned().collect()
946 }
947
948 /// Non-consuming availability projection for the current session's status.
949 pub fn snapshots_disabled_status(
950 workspace: &Path,
951 session_id: Option<&str>,
952 ) -> Option<SnapshotsDisabledNotice> {
953 snapshot_notices()
954 .lock()
955 .unwrap_or_else(std::sync::PoisonError::into_inner)
956 .get(&snapshot_notice_key(workspace, session_id))
957 .and_then(|state| state.disabled.clone())
958 }
959
960 fn clear_snapshots_disabled_status(workspace: &Path, session_id: Option<&str>) {
961 if let Some(state) = snapshot_notices()
962 .lock()
963 .unwrap_or_else(std::sync::PoisonError::into_inner)
964 .get_mut(&snapshot_notice_key(workspace, session_id))
965 {
966 state.disabled = None;
967 if let Some(scope) = state.announced.take() {
968 state.resumed = !state.pending && scope != SnapshotsDisabledScope::HistoryRepaired;
969 if state.pending {
970 state.announced_scopes.retain(|seen| *seen != scope);
971 }
972 }
973 state.pending = false;
974 }
975 }
976
977 pub fn take_snapshots_resumed_notice(workspace: &Path, session_id: Option<&str>) -> bool {
978 snapshot_notices()
979 .lock()
980 .unwrap_or_else(std::sync::PoisonError::into_inner)
981 .get_mut(&snapshot_notice_key(workspace, session_id))
982 .is_some_and(|state| std::mem::take(&mut state.resumed))
983 }
984
985 pub fn snapshots_resumed_line(workspace: &Path, locale: codewhale_localization::Locale) -> String {
986 codewhale_localization::tr(locale, codewhale_localization::MessageId::SnapshotsResumed)
987 .replace("{workspace}", &workspace.to_string_lossy())
988 }
989
990 fn maybe_notify_snapshots_disabled_once(
991 workspace: &Path,
992 session_id: Option<&str>,
993 cap_bytes: u64,
994 error: &std::io::Error,
995 ) -> bool {
996 let message = error.to_string();
997 // The gate markers are declared by the snapshot policy that produces them,
998 // so this stays one classifier rather than a second copy of the rules.
999 let scope = if message.contains(codewhale_snapshot::GATE_TOO_LARGE_MARKER) {
1000 SnapshotsDisabledScope::WorkspaceTooLarge
1001 } else if message.contains(codewhale_snapshot::GATE_TOO_MANY_ENTRIES_MARKER) {
1002 SnapshotsDisabledScope::TooManyFiles
1003 } else if message.contains(codewhale_snapshot::GATE_UNSAFE_LOCATION_MARKER) {
1004 SnapshotsDisabledScope::UnsafeLocation
1005 } else {
1006 // A real snapshot/data-loss error, not a gate: say snapshots are
1007 // failing and why, never a "snapshots are off" gate notice.
1008 return record_snapshot_notice(
1009 workspace,
1010 session_id,
1011 SnapshotsDisabledScope::Failing,
1012 snapshot_failure_detail(error),
1013 );
1014 };
1015 let limit = match scope {
1016 SnapshotsDisabledScope::WorkspaceTooLarge => format_cap_bytes(cap_bytes),
1017 SnapshotsDisabledScope::TooManyFiles => {
1018 codewhale_snapshot::SIZE_WALK_MAX_ENTRIES.to_string()
1019 }
1020 _ => String::new(),
1021 };
1022 record_snapshot_notice(workspace, session_id, scope, limit)
1023 }
1024
1025 /// One line of a snapshot error for the notice: the first line, bounded.
1026 fn snapshot_failure_detail(error: &std::io::Error) -> String {
1027 const MAX_CHARS: usize = 200;
1028 let text = error.to_string();
1029 let line = text.lines().next().unwrap_or_default().trim();
1030 if line.chars().count() > MAX_CHARS {
1031 let cut: String = line.chars().take(MAX_CHARS).collect();
1032 format!("{cut}…")
1033 } else {
1034 line.to_string()
1035 }
1036 }
1037
1038 /// Record the session's snapshot availability and queue one notice per scope
1039 /// per session for the host. Returns whether this call queued it.
1040 fn record_snapshot_notice(
1041 workspace: &Path,
1042 session_id: Option<&str>,
1043 scope: SnapshotsDisabledScope,
1044 limit: String,
1045 ) -> bool {
1046 let notice = SnapshotsDisabledNotice {
1047 workspace: workspace.to_string_lossy().into_owned(),
1048 scope,
1049 limit,
1050 };
1051 let mut states = snapshot_notices()
1052 .lock()
1053 .unwrap_or_else(std::sync::PoisonError::into_inner);
1054 let state = states
1055 .entry(snapshot_notice_key(workspace, session_id))
1056 .or_default();
1057 state.disabled = Some(notice);
1058 state.resumed = false;
1059 if state.announced_scopes.contains(&scope) {
1060 return false;
1061 }
1062 state.announced_scopes.push(scope);
1063 state.announced = Some(scope);
1064 state.pending = true;
1065 true
1066 }
1067
1068 #[cfg(test)]
1069 mod snapshot_notice_tests {
1070 use super::*;
1071 use std::sync::{
1072 Arc,
1073 atomic::{AtomicUsize, Ordering},
1074 };
1075 use tracing_subscriber::prelude::*;
1076
1077 #[derive(Clone, Default)]
1078 struct SnapshotWarnings(Arc<AtomicUsize>);
1079
1080 impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for SnapshotWarnings {
1081 fn on_event(
1082 &self,
1083 event: &tracing::Event<'_>,
1084 _context: tracing_subscriber::layer::Context<'_, S>,
1085 ) {
1086 if event.metadata().target() == "snapshot"
1087 && *event.metadata().level() == tracing::Level::WARN
1088 {
1089 self.0.fetch_add(1, Ordering::SeqCst);
1090 }
1091 }
1092 }
1093
1094 #[test]
1095 fn oversized_workspace_warns_once_per_session_and_retains_status_after_delivery() {
1096 let _env = crate::test_support::lock_test_env();
1097 let root = tempfile::tempdir().unwrap();
1098 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
1099 let _user_home = crate::test_support::EnvVarGuard::set("HOME", root.path());
1100 let _user_profile = crate::test_support::EnvVarGuard::set("USERPROFILE", root.path());
1101 let workspace = root.path().join("workspace");
1102 std::fs::create_dir(&workspace).unwrap();
1103 std::fs::write(workspace.join("large.txt"), vec![b'x'; 4096]).unwrap();
1104 let warnings = SnapshotWarnings::default();
1105 let subscriber = tracing_subscriber::registry().with(warnings.clone());
1106 tracing::subscriber::with_default(subscriber, || {
1107 for session in ["session-a", "session-b"] {
1108 for turn in 1..=3 {
1109 assert!(
1110 pre_turn_snapshot(&workspace, turn, 1024, None, Some(session)).is_none()
1111 );
1112 assert!(
1113 post_turn_snapshot(&workspace, turn, 1024, None, Some(session)).is_none()
1114 );
1115 }
1116 }
1117 });
1118 assert_eq!(
1119 warnings.0.load(Ordering::SeqCst),
1120 2,
1121 "exactly one real WARN for each session"
1122 );
1123 for session in ["session-b", "session-a"] {
1124 let notices = take_snapshots_disabled_notices(&workspace, Some(session));
1125 assert_eq!(notices.len(), 1, "each session receives its own notice");
1126 assert_eq!(notices[0].scope, SnapshotsDisabledScope::WorkspaceTooLarge);
1127 let line = notices[0].localize(codewhale_localization::Locale::En);
1128 assert_eq!(line.lines().count(), 1, "one line, not a stacked notice");
1129 assert_eq!(
1130 line.matches(&workspace.display().to_string()).count(),
1131 1,
1132 "the workspace is named exactly once: {line}"
1133 );
1134 assert_eq!(
1135 line.matches(SNAPSHOTS_CAP_CONFIG_KEY).count(),
1136 1,
1137 "the remedy is stated exactly once: {line}"
1138 );
1139 assert!(line.contains("1.0 KB"), "the tripped cap is named: {line}");
1140 assert!(take_snapshots_disabled_notices(&workspace, Some(session)).is_empty());
1141 assert_eq!(
1142 snapshots_disabled_status(&workspace, Some(session)),
1143 notices.first().cloned(),
1144 "delivery must not erase /status"
1145 );
1146 }
1147 assert!(snapshots_disabled_status(&workspace, Some("session-c")).is_none());
1148 assert!(snapshots_disabled_status(&root.path().join("other"), Some("session-a")).is_none());
1149 }
1150
1151 /// The quiet case: a workspace under the cap snapshots and says nothing.
1152 #[test]
1153 fn small_workspace_snapshots_with_no_notice_at_all() {
1154 let _env = crate::test_support::lock_test_env();
1155 let root = tempfile::tempdir().unwrap();
1156 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
1157 let _user_home = crate::test_support::EnvVarGuard::set("HOME", root.path());
1158 let _user_profile = crate::test_support::EnvVarGuard::set("USERPROFILE", root.path());
1159 let workspace = root.path().join("workspace");
1160 std::fs::create_dir(&workspace).unwrap();
1161 std::fs::write(workspace.join("small.txt"), b"tiny").unwrap();
1162 assert!(pre_turn_snapshot(&workspace, 1, 1024 * 1024, None, Some("session")).is_some());
1163 assert!(snapshots_disabled_status(&workspace, Some("session")).is_none());
1164 assert!(take_snapshots_disabled_notices(&workspace, Some("session")).is_empty());
1165 }
1166
1167 #[test]
1168 fn successful_snapshot_clears_disabled_status_and_pending_notice() {
1169 let _env = crate::test_support::lock_test_env();
1170 let root = tempfile::tempdir().unwrap();
1171 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
1172 let _user_home = crate::test_support::EnvVarGuard::set("HOME", root.path());
1173 let _user_profile = crate::test_support::EnvVarGuard::set("USERPROFILE", root.path());
1174 let workspace = root.path().join("workspace");
1175 std::fs::create_dir(&workspace).unwrap();
1176 std::fs::write(workspace.join("large.txt"), vec![b'x'; 4096]).unwrap();
1177 assert!(pre_turn_snapshot(&workspace, 1, 1024, None, Some("session")).is_none());
1178 assert!(snapshots_disabled_status(&workspace, Some("session")).is_some());
1179 assert!(pre_turn_snapshot(&workspace, 2, 0, None, Some("session")).is_some());
1180 assert!(snapshots_disabled_status(&workspace, Some("session")).is_none());
1181 assert!(take_snapshots_disabled_notices(&workspace, Some("session")).is_empty());
1182 }
1183
1184 #[test]
1185 fn gate_is_announced_once_then_again_only_when_its_state_changes() {
1186 let _env = crate::test_support::lock_test_env();
1187 let root = tempfile::tempdir().unwrap();
1188 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
1189 let _user_home = crate::test_support::EnvVarGuard::set("HOME", root.path());
1190 let _user_profile = crate::test_support::EnvVarGuard::set("USERPROFILE", root.path());
1191 let workspace = root.path().join("workspace");
1192 std::fs::create_dir(&workspace).unwrap();
1193 std::fs::write(workspace.join("large.txt"), vec![b'x'; 4096]).unwrap();
1194 let mut delivered = 0;
1195 for turn in 1..=10 {
1196 assert!(pre_turn_snapshot(&workspace, turn, 1024, None, Some("s")).is_none());
1197 assert!(post_turn_snapshot(&workspace, turn, 1024, None, Some("s")).is_none());
1198 delivered += take_snapshots_disabled_notices(&workspace, Some("s")).len();
1199 assert!(!take_snapshots_resumed_notice(&workspace, Some("s")));
1200 }
1201 assert_eq!(delivered, 1, "ten gated turns announce the gate once");
1202 assert!(snapshots_disabled_status(&workspace, Some("s")).is_some());
1203
1204 for turn in 11..=13 {
1205 assert!(pre_turn_snapshot(&workspace, turn, 0, None, Some("s")).is_some());
1206 }
1207 assert!(take_snapshots_resumed_notice(&workspace, Some("s")));
1208 assert!(!take_snapshots_resumed_notice(&workspace, Some("s")));
1209 assert!(snapshots_disabled_status(&workspace, Some("s")).is_none());
1210 assert!(
1211 snapshots_resumed_line(&workspace, codewhale_localization::Locale::En)
1212 .contains("back on")
1213 );
1214
1215 let gate = std::io::Error::new(
1216 std::io::ErrorKind::InvalidInput,
1217 format!(
1218 "{}: over x bytes in y",
1219 codewhale_snapshot::GATE_TOO_LARGE_MARKER
1220 ),
1221 );
1222 assert!(
1223 !maybe_notify_snapshots_disabled_once(&workspace, Some("s"), 1024, &gate),
1224 "the same scope stays silent if it flaps back in the same session"
1225 );
1226 assert!(take_snapshots_disabled_notices(&workspace, Some("s")).is_empty());
1227 assert!(snapshots_disabled_status(&workspace, Some("s")).is_some());
1228 assert!(pre_turn_snapshot(&workspace, 14, 0, None, Some("s")).is_some());
1229 assert!(!take_snapshots_resumed_notice(&workspace, Some("s")));
1230
1231 let files_gate = std::io::Error::new(
1232 std::io::ErrorKind::InvalidInput,
1233 format!(
1234 "{}: over 2 bytes in y",
1235 codewhale_snapshot::GATE_TOO_MANY_ENTRIES_MARKER
1236 ),
1237 );
1238 assert!(
1239 maybe_notify_snapshots_disabled_once(&workspace, Some("s"), 1024, &files_gate),
1240 "a distinct scope is still announced once in the session"
1241 );
1242 assert_eq!(
1243 take_snapshots_disabled_notices(&workspace, Some("s")).len(),
1244 1
1245 );
1246 assert!(pre_turn_snapshot(&workspace, 15, 0, None, Some("s")).is_some());
1247 assert!(take_snapshots_resumed_notice(&workspace, Some("s")));
1248 }
1249
1250 #[test]
1251 fn transient_snapshot_failure_cleared_before_delivery_never_emits_back_on() {
1252 let workspace = tempfile::tempdir().unwrap();
1253 let error = std::io::Error::other("transient io error");
1254 assert!(maybe_notify_snapshots_disabled_once(
1255 workspace.path(),
1256 Some("s"),
1257 1024,
1258 &error
1259 ));
1260 clear_snapshots_disabled_status(workspace.path(), Some("s"));
1261 assert!(take_snapshots_disabled_notices(workspace.path(), Some("s")).is_empty());
1262 assert!(
1263 !take_snapshots_resumed_notice(workspace.path(), Some("s")),
1264 "back on must not appear without a delivered off notice"
1265 );
1266
1267 assert!(maybe_notify_snapshots_disabled_once(
1268 workspace.path(),
1269 Some("s"),
1270 1024,
1271 &error
1272 ));
1273 assert_eq!(
1274 take_snapshots_disabled_notices(workspace.path(), Some("s")).len(),
1275 1
1276 );
1277 clear_snapshots_disabled_status(workspace.path(), Some("s"));
1278 assert!(take_snapshots_resumed_notice(workspace.path(), Some("s")));
1279 assert!(!take_snapshots_resumed_notice(workspace.path(), Some("s")));
1280 }
1281
1282 /// A real error is not a gate: the user is told snapshots are failing
1283 /// and why, never that they are "off" behind a limit.
1284 #[test]
1285 fn unrelated_snapshot_errors_say_snapshots_are_failing() {
1286 let workspace = tempfile::tempdir().unwrap();
1287 let error = std::io::Error::other("disk full");
1288 assert!(maybe_notify_snapshots_disabled_once(
1289 workspace.path(),
1290 Some("session"),
1291 1024,
1292 &error
1293 ));
1294 let notices = take_snapshots_disabled_notices(workspace.path(), Some("session"));
1295 assert_eq!(notices.len(), 1);
1296 assert_eq!(notices[0].scope, SnapshotsDisabledScope::Failing);
1297 let line = notices[0].localize(codewhale_localization::Locale::En);
1298 assert!(
1299 line.contains("failing") && line.contains("disk full"),
1300 "{line}"
1301 );
1302 assert!(!line.contains(SNAPSHOTS_CAP_CONFIG_KEY), "{line}");
1303 assert!(snapshots_disabled_status(workspace.path(), Some("session")).is_some());
1304 assert!(
1305 !maybe_notify_snapshots_disabled_once(workspace.path(), Some("session"), 1024, &error),
1306 "told once per session"
1307 );
1308 }
1309
1310 /// B2: a side repo whose HEAD names a missing commit is repaired on the
1311 /// next turn snapshot, and the user is told earlier restore points are
1312 /// gone instead of /undo silently dying.
1313 #[test]
1314 fn broken_snapshot_history_is_repaired_and_the_user_is_told() {
1315 let _env = crate::test_support::lock_test_env();
1316 let root = tempfile::tempdir().unwrap();
1317 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
1318 let _user_home = crate::test_support::EnvVarGuard::set("HOME", root.path());
1319 let _user_profile = crate::test_support::EnvVarGuard::set("USERPROFILE", root.path());
1320 let workspace = root.path().join("workspace");
1321 std::fs::create_dir(&workspace).unwrap();
1322 std::fs::write(workspace.join("a.txt"), b"alpha").unwrap();
1323 assert!(pre_turn_snapshot(&workspace, 1, 0, None, Some("session")).is_some());
1324 let repo = SnapshotRepo::open_or_init(&workspace).unwrap();
1325 repo.point_head_at_missing_commit_for_test();
1326 // With a reflog the repair recovers the last good commit silently
1327 // (restore points survive); without one history restarts, which is
1328 // the case the user must be told about.
1329 std::fs::remove_dir_all(repo.git_dir().join("logs")).expect("drop reflogs");
1330
1331 std::fs::write(workspace.join("a.txt"), b"beta").unwrap();
1332 assert!(
1333 post_turn_snapshot(&workspace, 1, 0, None, Some("session")).is_some(),
1334 "the snapshot succeeds after the repair"
1335 );
1336 let notices = take_snapshots_disabled_notices(&workspace, Some("session"));
1337 assert_eq!(notices.len(), 1, "{notices:?}");
1338 assert_eq!(notices[0].scope, SnapshotsDisabledScope::HistoryRepaired);
1339 let line = notices[0].localize(codewhale_localization::Locale::En);
1340 assert!(line.contains("restarted"), "{line}");
1341 assert!(line.contains(&workspace.display().to_string()), "{line}");
1342 assert!(pre_turn_snapshot(&workspace, 2, 0, None, Some("session")).is_some());
1343 assert!(
1344 take_snapshots_disabled_notices(&workspace, Some("session")).is_empty(),
1345 "a healthy history says nothing more"
1346 );
1347 }
1348
1349 /// Every gate must state a recovery that actually lifts *that* gate. The
1350 /// entry ceiling and the home/root refusal are not raised by the GB cap,
1351 /// so naming it there is the unhelpful follow-up this packet removes.
1352 #[test]
1353 fn each_gate_gets_its_own_accurate_recovery() {
1354 let workspace = tempfile::tempdir().unwrap();
1355 for (gate_message, scope, cap_bytes) in [
1356 (
1357 format!(
1358 "{}: over 2 bytes in x",
1359 codewhale_snapshot::GATE_TOO_MANY_ENTRIES_MARKER
1360 ),
1361 SnapshotsDisabledScope::TooManyFiles,
1362 0,
1363 ),
1364 (
1365 format!(
1366 "{} for home directory: x",
1367 codewhale_snapshot::GATE_UNSAFE_LOCATION_MARKER
1368 ),
1369 SnapshotsDisabledScope::UnsafeLocation,
1370 2 * 1024 * 1024 * 1024,
1371 ),
1372 ] {
1373 let session = format!("{scope:?}");
1374 let error = std::io::Error::new(std::io::ErrorKind::InvalidInput, gate_message);
1375 assert!(maybe_notify_snapshots_disabled_once(
1376 workspace.path(),
1377 Some(&session),
1378 cap_bytes,
1379 &error
1380 ));
1381 let notice = snapshots_disabled_status(workspace.path(), Some(&session))
1382 .expect("gated error must be retained for /status");
1383 assert_eq!(notice.scope, scope);
1384 let line = notice.localize(codewhale_localization::Locale::En);
1385 assert_eq!(line.lines().count(), 1, "one line, not a stacked notice");
1386 assert!(
1387 !line.contains(SNAPSHOTS_CAP_CONFIG_KEY),
1388 "{scope:?} must not advertise a config key that cannot lift it: {line}"
1389 );
1390 assert!(line.contains("/undo"), "the consequence is named: {line}");
1391 if scope == SnapshotsDisabledScope::TooManyFiles {
1392 // The `{limit}` this notice carries is the entry ceiling.
1393 // Nothing else asserts it reaches the user, so a dropped
1394 // placeholder would render "more than files" silently.
1395 assert!(
1396 line.contains(&codewhale_snapshot::SIZE_WALK_MAX_ENTRIES.to_string()),
1397 "the entry ceiling must be stated, not left as a blank limit: {line}"
1398 );
1399 }
1400 }
1401 }
1402
1403 #[test]
1404 fn oversize_notice_names_the_cap_and_only_then_the_config_key() {
1405 let workspace = tempfile::tempdir().unwrap();
1406 let error = std::io::Error::new(
1407 std::io::ErrorKind::InvalidInput,
1408 format!(
1409 "{}: over x bytes in y",
1410 codewhale_snapshot::GATE_TOO_LARGE_MARKER
1411 ),
1412 );
1413 assert!(maybe_notify_snapshots_disabled_once(
1414 workspace.path(),
1415 Some("session"),
1416 2 * 1024 * 1024 * 1024,
1417 &error
1418 ));
1419 let notice =
1420 snapshots_disabled_status(workspace.path(), Some("session")).expect("retained");
1421 let line = notice.localize(codewhale_localization::Locale::En);
1422 assert!(line.contains("2.0 GB"), "{line}");
1423 assert!(line.contains(SNAPSHOTS_CAP_CONFIG_KEY), "{line}");
1424 }
1425 }
1426
1427 #[cfg(test)]
1428 mod snapshot_label_tests {
1429 use super::*;
1430
1431 #[test]
1432 fn label_writer_and_parser_agree_on_prompt_snippet() {
1433 let prompt = "rename the widget\nsecond line is dropped";
1434 let label = format_snapshot_label("pre-turn", 7, Some(prompt));
1435 assert_eq!(label, "pre-turn:7: rename the widget");
1436
1437 let parsed = parse_snapshot_label(&label);
1438 assert_eq!(parsed.kind, "pre-turn");
1439 assert_eq!(parsed.seq, Some(7));
1440 assert_eq!(
1441 parsed.prompt_snippet.as_deref(),
1442 snapshot_label_prompt_snippet(prompt).as_deref(),
1443 "a reader must recover exactly the snippet the writer embedded"
1444 );
1445 }
1446
1447 #[test]
1448 fn truncated_prompt_round_trips_with_its_ellipsis() {
1449 let prompt = "x".repeat(USER_PROMPT_LABEL_MAX + 25);
1450 let label = format_snapshot_label("post-turn", 2, Some(&prompt));
1451 let parsed = parse_snapshot_label(&label);
1452 let snippet = parsed.prompt_snippet.expect("snippet");
1453 assert!(snippet.ends_with('…'));
1454 assert_eq!(snippet.chars().count(), USER_PROMPT_LABEL_MAX + 1);
1455 assert_eq!(
1456 Some(snippet),
1457 snapshot_label_prompt_snippet(&prompt),
1458 "truncated snippets must also round-trip"
1459 );
1460 }
1461
1462 #[test]
1463 fn labels_without_a_prompt_parse_without_inventing_one() {
1464 let label = format_snapshot_label("pre-turn", 3, None);
1465 assert_eq!(label, "pre-turn:3");
1466 let parsed = parse_snapshot_label(&label);
1467 assert_eq!(parsed.kind, "pre-turn");
1468 assert_eq!(parsed.seq, Some(3));
1469 assert_eq!(parsed.prompt_snippet, None);
1470 }
1471
1472 #[test]
1473 fn tool_labels_carry_a_call_id_not_a_sequence() {
1474 let label = format!("tool:{}", "call_abc123");
1475 let parsed = parse_snapshot_label(&label);
1476 assert_eq!(parsed.kind, "tool");
1477 assert_eq!(parsed.seq, None, "a call id is not a turn sequence");
1478 assert_eq!(parsed.prompt_snippet, None);
1479 }
1480
1481 #[test]
1482 fn unrecognized_labels_are_reported_rather_than_dropped() {
1483 let parsed = parse_snapshot_label("manual checkpoint");
1484 assert_eq!(parsed.kind, "manual checkpoint");
1485 assert_eq!(parsed.seq, None);
1486 assert_eq!(parsed.prompt_snippet, None);
1487 }
1488
1489 #[test]
1490 fn empty_prompt_contributes_no_snippet() {
1491 assert_eq!(snapshot_label_prompt_snippet(""), None);
1492 assert_eq!(format_snapshot_label("pre-turn", 1, Some("")), "pre-turn:1");
1493 }
1494 }
1495
1495 lines RUST