1use std::sync::LazyLock;
29
30use regex::Regex;
31use serde_json::{Map, Value};
32
33use crate::core::tokens::count_tokens;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum VolatileKind {
43 Uuid,
44 Timestamp,
45 Jwt,
46 Hash,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct VolatileReport {
56 pub uuid_count: u32,
57 pub timestamp_count: u32,
58 pub jwt_count: u32,
59 pub hash_count: u32,
60 pub total_volatile: u32,
61 pub alignment_score: u8,
62 pub volatile_positions: Vec<(usize, VolatileKind)>,
63}
64
65impl Default for VolatileReport {
66 fn default() -> Self {
67 Self {
68 uuid_count: 0,
69 timestamp_count: 0,
70 jwt_count: 0,
71 hash_count: 0,
72 total_volatile: 0,
73 alignment_score: 100,
74 volatile_positions: Vec::new(),
75 }
76 }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80struct VolatileMatch {
81 start: usize,
82 end: usize,
83 kind: VolatileKind,
84}
85
86pub fn detect_volatile_content(text: &str) -> VolatileReport {
93 let bytes = text.as_bytes();
94 let mut matches = Vec::new();
95 matches.extend(uuid_matches(bytes));
96 matches.extend(timestamp_matches(bytes));
97 matches.extend(jwt_matches(bytes));
98 matches.extend(hash_matches(bytes));
99
100 matches.sort_unstable_by(|left, right| {
103 left.start
104 .cmp(&right.start)
105 .then_with(|| right.end.cmp(&left.end))
106 .then_with(|| volatile_kind_rank(left.kind).cmp(&volatile_kind_rank(right.kind)))
107 });
108
109 let mut report = VolatileReport::default();
110 let mut last_end = 0;
111 for found in matches {
112 if found.start < last_end {
113 continue;
114 }
115 last_end = found.end;
116 match found.kind {
117 VolatileKind::Uuid => report.uuid_count += 1,
118 VolatileKind::Timestamp => report.timestamp_count += 1,
119 VolatileKind::Jwt => report.jwt_count += 1,
120 VolatileKind::Hash => report.hash_count += 1,
121 }
122 report.volatile_positions.push((found.start, found.kind));
123 }
124 report.total_volatile = report
125 .uuid_count
126 .saturating_add(report.timestamp_count)
127 .saturating_add(report.jwt_count)
128 .saturating_add(report.hash_count);
129 report.alignment_score = 100u8
130 .saturating_sub(u8::try_from(report.total_volatile.saturating_mul(10)).unwrap_or(u8::MAX));
131 report
132}
133
134fn volatile_kind_rank(kind: VolatileKind) -> u8 {
135 match kind {
136 VolatileKind::Uuid => 0,
137 VolatileKind::Timestamp => 1,
138 VolatileKind::Jwt => 2,
139 VolatileKind::Hash => 3,
140 }
141}
142
143fn is_hex(byte: u8) -> bool {
144 byte.is_ascii_hexdigit()
145}
146
147fn is_token_char(byte: u8) -> bool {
148 byte.is_ascii_alphanumeric() || byte == b'_'
149}
150
151fn bounded_by_non_tokens(bytes: &[u8], start: usize, end: usize) -> bool {
152 (start == 0 || !is_token_char(bytes[start - 1]))
153 && (end == bytes.len() || !is_token_char(bytes[end]))
154}
155
156fn uuid_matches(bytes: &[u8]) -> Vec<VolatileMatch> {
157 let mut matches = Vec::new();
158 if bytes.len() < 36 {
159 return matches;
160 }
161 for start in 0..=bytes.len().saturating_sub(36) {
162 let end = start + 36;
163 let valid = bytes[start..end].iter().enumerate().all(|(offset, byte)| {
164 matches!(offset, 8 | 13 | 18 | 23) && *byte == b'-'
165 || !matches!(offset, 8 | 13 | 18 | 23) && is_hex(*byte)
166 });
167 if valid && bounded_by_non_tokens(bytes, start, end) {
168 matches.push(VolatileMatch {
169 start,
170 end,
171 kind: VolatileKind::Uuid,
172 });
173 }
174 }
175 matches
176}
177
178fn timestamp_matches(bytes: &[u8]) -> Vec<VolatileMatch> {
179 let mut matches = Vec::new();
180 if bytes.len() < 10 {
181 return matches;
182 }
183 for start in 0..=bytes.len().saturating_sub(10) {
184 let Some(date_end) = date_end(bytes, start) else {
185 continue;
186 };
187 let end = datetime_end(bytes, start).unwrap_or(date_end);
188 if bounded_by_non_tokens(bytes, start, end) {
189 matches.push(VolatileMatch {
190 start,
191 end,
192 kind: VolatileKind::Timestamp,
193 });
194 }
195 }
196 matches
197}
198
199fn date_end(bytes: &[u8], start: usize) -> Option<usize> {
200 let end = start.checked_add(10)?;
201 let slice = bytes.get(start..end)?;
202 if !slice[0..4].iter().all(u8::is_ascii_digit)
203 || slice[4] != b'-'
204 || !slice[5..7].iter().all(u8::is_ascii_digit)
205 || slice[7] != b'-'
206 || !slice[8..10].iter().all(u8::is_ascii_digit)
207 {
208 return None;
209 }
210 let month = two_digits(slice[5], slice[6]);
211 let day = two_digits(slice[8], slice[9]);
212 ((1..=12).contains(&month) && (1..=31).contains(&day)).then_some(end)
213}
214
215fn datetime_end(bytes: &[u8], start: usize) -> Option<usize> {
216 date_end(bytes, start)?;
217 let time_start = start.checked_add(11)?;
218 if !matches!(bytes.get(start + 10), Some(b'T' | b' ')) {
219 return None;
220 }
221 let mut end = time_start.checked_add(5)?;
222 let time = bytes.get(time_start..end)?;
223 if !time[0..2].iter().all(u8::is_ascii_digit)
224 || time[2] != b':'
225 || !time[3..5].iter().all(u8::is_ascii_digit)
226 || two_digits(time[0], time[1]) > 23
227 || two_digits(time[3], time[4]) > 59
228 {
229 return None;
230 }
231 if bytes.get(end) == Some(&b':') {
232 let seconds_end = end.checked_add(3)?;
233 let seconds = bytes.get(end + 1..seconds_end)?;
234 if !seconds.iter().all(u8::is_ascii_digit) || two_digits(seconds[0], seconds[1]) > 59 {
235 return None;
236 }
237 end = seconds_end;
238 }
239 if bytes.get(end) == Some(&b'.') {
240 let fraction_start = end + 1;
241 end = fraction_start;
242 while bytes.get(end).is_some_and(u8::is_ascii_digit) {
243 end += 1;
244 }
245 if end == fraction_start {
246 return None;
247 }
248 }
249 match bytes.get(end) {
250 Some(b'Z') => end += 1,
251 Some(b'+' | b'-') => {
252 let zone_start = end + 1;
253 let zone_end = zone_start.checked_add(5)?;
254 let zone = bytes.get(zone_start..zone_end)?;
255 if !zone[0..2].iter().all(u8::is_ascii_digit)
256 || zone[2] != b':'
257 || !zone[3..5].iter().all(u8::is_ascii_digit)
258 || two_digits(zone[0], zone[1]) > 23
259 || two_digits(zone[3], zone[4]) > 59
260 {
261 return None;
262 }
263 end = zone_end;
264 }
265 _ => {}
266 }
267 Some(end)
268}
269
270fn two_digits(tens: u8, units: u8) -> u8 {
271 (tens - b'0') * 10 + (units - b'0')
272}
273
274fn is_base64url(byte: u8) -> bool {
275 byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')
276}
277
278fn jwt_matches(bytes: &[u8]) -> Vec<VolatileMatch> {
279 let mut matches = Vec::new();
280 for start in 0..bytes.len() {
281 if start > 0 && (is_base64url(bytes[start - 1]) || bytes[start - 1] == b'.') {
282 continue;
283 }
284 let Some(end) = jwt_end(bytes, start) else {
285 continue;
286 };
287 if end == bytes.len() || (!is_base64url(bytes[end]) && bytes[end] != b'.') {
288 matches.push(VolatileMatch {
289 start,
290 end,
291 kind: VolatileKind::Jwt,
292 });
293 }
294 }
295 matches
296}
297
298fn jwt_end(bytes: &[u8], start: usize) -> Option<usize> {
299 let mut cursor = start;
300 for segment in 0..3 {
301 let segment_start = cursor;
302 while bytes.get(cursor).is_some_and(|byte| is_base64url(*byte)) {
303 cursor += 1;
304 }
305 if cursor == segment_start {
306 return None;
307 }
308 if segment < 2 {
309 if bytes.get(cursor) != Some(&b'.') {
310 return None;
311 }
312 cursor += 1;
313 }
314 }
315 Some(cursor)
316}
317
318fn hash_matches(bytes: &[u8]) -> Vec<VolatileMatch> {
319 let mut matches = Vec::new();
320 let mut start = 0;
321 while start < bytes.len() {
322 if !is_hex(bytes[start]) {
323 start += 1;
324 continue;
325 }
326 let end = bytes[start..]
327 .iter()
328 .position(|byte| !is_hex(*byte))
329 .map_or(bytes.len(), |offset| start + offset);
330 if matches!(end - start, 32 | 40 | 64) && bounded_by_non_tokens(bytes, start, end) {
331 matches.push(VolatileMatch {
332 start,
333 end,
334 kind: VolatileKind::Hash,
335 });
336 }
337 start = end;
338 }
339 matches
340}
341
342static VOLATILE_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
348 [
349 r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?",
351 r"\d{4}-\d{2}-\d{2}",
353 r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",
355 r"\b[0-9a-f]{40}\b",
357 ]
358 .iter()
359 .filter_map(|p| Regex::new(p).ok())
360 .collect()
361});
362
363#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
365pub(crate) struct VolatileScan {
366 pub fields: usize,
368 pub volatile_bytes: usize,
370}
371
372fn merged_spans(text: &str) -> Vec<(usize, usize)> {
377 let mut spans: Vec<(usize, usize)> = Vec::new();
378 for re in VOLATILE_PATTERNS.iter() {
379 spans.extend(re.find_iter(text).map(|m| (m.start(), m.end())));
380 }
381 if spans.is_empty() {
382 return spans;
383 }
384 spans.sort_unstable();
385 let mut merged: Vec<(usize, usize)> = Vec::with_capacity(spans.len());
386 for (start, end) in spans {
387 match merged.last_mut() {
388 Some(last) if start <= last.1 => last.1 = last.1.max(end),
389 _ => merged.push((start, end)),
390 }
391 }
392 merged
393}
394
395pub(crate) fn scan_volatile(text: &str) -> VolatileScan {
397 let merged = merged_spans(text);
398 VolatileScan {
399 fields: merged.len(),
400 volatile_bytes: merged.iter().map(|(s, e)| e - s).sum(),
401 }
402}
403
404pub(crate) fn system_text(system: &Value) -> Option<String> {
407 match system {
408 Value::String(s) => Some(s.clone()),
409 Value::Array(blocks) => {
410 let joined = blocks
411 .iter()
412 .filter_map(|b| b.get("text").and_then(Value::as_str))
413 .collect::<Vec<_>>()
414 .join("\n");
415 (!joined.is_empty()).then_some(joined)
416 }
417 _ => None,
418 }
419}
420
421const MIN_STABLE_TOKENS: usize = 1024;
425
426const TAIL_HEADER: &str = "Volatile context (relocated to keep the prompt-cache prefix stable):";
429
430fn placeholder(n: usize) -> String {
435 format!("[ctx#{n}]")
436}
437
438#[derive(Debug, Clone, PartialEq, Eq)]
440pub(crate) struct RelocateResult {
441 pub stable: String,
444 pub tail: String,
447 pub fields: usize,
449}
450
451pub(crate) fn relocate_volatile(text: &str) -> Option<RelocateResult> {
455 let spans = merged_spans(text);
456 if spans.is_empty() {
457 return None;
458 }
459 let mut stable = String::with_capacity(text.len());
460 let mut values: Vec<&str> = Vec::with_capacity(spans.len());
461 let mut cursor = 0usize;
462 for (start, end) in &spans {
463 stable.push_str(&text[cursor..*start]);
464 stable.push_str(&placeholder(values.len() + 1));
465 values.push(&text[*start..*end]);
466 cursor = *end;
467 }
468 stable.push_str(&text[cursor..]);
469
470 let mut tail = String::from(TAIL_HEADER);
471 for (i, value) in values.iter().enumerate() {
472 tail.push('\n');
473 tail.push_str(&placeholder(i + 1));
474 tail.push_str(" = ");
475 tail.push_str(value);
476 }
477 Some(RelocateResult {
478 stable,
479 tail,
480 fields: values.len(),
481 })
482}
483
484fn text_block(text: String) -> Map<String, Value> {
486 let mut block = Map::new();
487 block.insert("type".into(), Value::String("text".into()));
488 block.insert("text".into(), Value::String(text));
489 block
490}
491
492fn stable_block(text: String) -> Value {
494 let mut block = text_block(text);
495 block.insert(
496 "cache_control".into(),
497 serde_json::json!({ "type": "ephemeral" }),
498 );
499 Value::Object(block)
500}
501
502pub(crate) fn apply_anthropic_relocate(doc: &mut Value) -> usize {
510 let Some(system) = doc.get_mut("system") else {
511 return 0;
512 };
513 let text = match system {
514 Value::String(s) => s.clone(),
515 Value::Array(blocks) => {
516 let all_plain_text = !blocks.is_empty()
517 && blocks.iter().all(|b| {
518 b.get("type").and_then(Value::as_str) == Some("text")
519 && b.get("text").is_some_and(Value::is_string)
520 && b.get("cache_control").is_none()
521 });
522 if !all_plain_text {
523 return 0;
524 }
525 blocks
526 .iter()
527 .filter_map(|b| b.get("text").and_then(Value::as_str))
528 .collect::<Vec<_>>()
529 .join("\n")
530 }
531 _ => return 0,
532 };
533 let Some(result) = relocate_volatile(&text) else {
534 return 0;
535 };
536 if count_tokens(&result.stable) < MIN_STABLE_TOKENS {
537 return 0;
538 }
539 *system = Value::Array(vec![
540 stable_block(result.stable),
541 Value::Object(text_block(result.tail)),
542 ]);
543 result.fields
544}
545
546#[cfg(test)]
547mod tests {
548 use super::*;
549
550 #[test]
551 fn counts_each_volatile_kind_once() {
552 let text = "Today is 2026-06-22. Session 550e8400-e29b-41d4-a716-446655440000 \
553 at commit da39a3ee5e6b4b0d3255bfef95601890afd80709.";
554 let scan = scan_volatile(text);
555 assert_eq!(scan.fields, 3, "one date, one UUID, one git SHA");
556 assert!(scan.volatile_bytes > 0);
557 }
558
559 #[test]
560 fn datetime_and_inner_date_merge_to_one_span() {
561 let scan = scan_volatile("Generated at 2026-06-22T15:04:05Z by the agent.");
564 assert_eq!(
565 scan.fields, 1,
566 "overlapping datetime/date spans merge to one"
567 );
568 }
569
570 #[test]
571 fn stable_prompt_has_no_volatile_fields() {
572 let scan = scan_volatile("You are a careful senior engineer. Prefer small diffs.");
573 assert_eq!(scan, VolatileScan::default());
574 }
575
576 #[test]
577 fn scan_is_deterministic() {
578 let text = "v1 2026-06-22 id 550e8400-e29b-41d4-a716-446655440000 and 2025-01-01";
579 assert_eq!(scan_volatile(text), scan_volatile(text));
580 }
581
582 #[test]
583 fn report_detects_uuid_at_its_byte_position() {
584 let text = "run 550e8400-e29b-41d4-a716-446655440000 now";
585 assert_eq!(
586 detect_volatile_content(text),
587 VolatileReport {
588 uuid_count: 1,
589 total_volatile: 1,
590 alignment_score: 90,
591 volatile_positions: vec![(4, VolatileKind::Uuid)],
592 ..VolatileReport::default()
593 }
594 );
595 }
596
597 #[test]
598 fn report_detects_iso_timestamp_once() {
599 let text = "built 2026-06-22T15:04:05Z";
600 assert_eq!(
601 detect_volatile_content(text),
602 VolatileReport {
603 timestamp_count: 1,
604 total_volatile: 1,
605 alignment_score: 90,
606 volatile_positions: vec![(6, VolatileKind::Timestamp)],
607 ..VolatileReport::default()
608 }
609 );
610 }
611
612 #[test]
613 fn report_detects_timestamp_fraction_and_zone() {
614 let text = "built 2026-06-22T15:04:05.123+02:00";
615 let report = detect_volatile_content(text);
616 assert_eq!(report.timestamp_count, 1);
617 assert_eq!(report.alignment_score, 90);
618 }
619
620 #[test]
621 fn report_detects_jwt() {
622 let jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJl";
623 assert_eq!(
624 detect_volatile_content(jwt),
625 VolatileReport {
626 jwt_count: 1,
627 total_volatile: 1,
628 alignment_score: 90,
629 volatile_positions: vec![(0, VolatileKind::Jwt)],
630 ..VolatileReport::default()
631 }
632 );
633 }
634
635 #[test]
636 fn report_scores_mixed_volatile_content() {
637 let text = concat!(
638 "2026-06-22 ",
639 "550e8400-e29b-41d4-a716-446655440000 ",
640 "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJl ",
641 "da39a3ee5e6b4b0d3255bfef95601890afd80709"
642 );
643 let report = detect_volatile_content(text);
644 assert_eq!(report.timestamp_count, 1);
645 assert_eq!(report.uuid_count, 1);
646 assert_eq!(report.jwt_count, 1);
647 assert_eq!(report.hash_count, 1);
648 assert_eq!(report.total_volatile, 4);
649 assert_eq!(report.alignment_score, 60);
650 assert_eq!(report.volatile_positions.len(), 4);
651 }
652
653 #[test]
654 fn system_text_reads_string_and_block_array() {
655 assert_eq!(
656 system_text(&Value::String("hi".into())).as_deref(),
657 Some("hi")
658 );
659 let arr = serde_json::json!([
660 {"type": "text", "text": "alpha"},
661 {"type": "text", "text": "beta"}
662 ]);
663 assert_eq!(system_text(&arr).as_deref(), Some("alpha\nbeta"));
664 assert_eq!(system_text(&serde_json::json!(42)), None);
665 }
666
667 fn big_system_with_date() -> String {
669 format!(
670 "You are a meticulous senior engineer. Today is 2026-06-27. {}",
671 "Prefer small, well-tested diffs. ".repeat(400)
672 )
673 }
674
675 #[test]
676 fn relocate_moves_volatiles_to_tail_and_leaves_placeholders() {
677 let result =
678 relocate_volatile("Date 2026-06-27, id 550e8400-e29b-41d4-a716-446655440000.").unwrap();
679 assert_eq!(result.fields, 2);
680 assert!(!result.stable.contains("2026-06-27"), "value left prefix");
681 assert!(result.stable.contains("[ctx#1]") && result.stable.contains("[ctx#2]"));
682 assert!(result.tail.contains("[ctx#1] = 2026-06-27"));
683 assert!(
684 result
685 .tail
686 .contains("[ctx#2] = 550e8400-e29b-41d4-a716-446655440000")
687 );
688 }
689
690 #[test]
691 fn relocate_is_noop_without_volatile_fields() {
692 assert!(relocate_volatile("You are a careful engineer.").is_none());
693 }
694
695 #[test]
696 fn relocate_is_idempotent() {
697 let once = relocate_volatile("Built at 2026-06-27 ok").unwrap();
698 assert!(
699 relocate_volatile(&once.stable).is_none(),
700 "placeholders carry no volatile pattern, so a second pass is a no-op"
701 );
702 }
703
704 #[test]
705 fn relocate_is_deterministic() {
706 let text = "v 2026-06-27 id 550e8400-e29b-41d4-a716-446655440000 sha \
707 da39a3ee5e6b4b0d3255bfef95601890afd80709";
708 assert_eq!(relocate_volatile(text), relocate_volatile(text));
709 }
710
711 #[test]
712 fn apply_rewrites_string_system_into_stable_plus_tail() {
713 let mut doc = serde_json::json!({ "system": big_system_with_date(), "messages": [] });
714 assert_eq!(apply_anthropic_relocate(&mut doc), 1);
715 let system = &doc["system"];
716 assert!(system.is_array(), "string system becomes a block array");
717 assert_eq!(system[0]["cache_control"]["type"], "ephemeral");
718 assert!(
719 !system[0]["text"].as_str().unwrap().contains("2026-06-27"),
720 "the date left the cacheable prefix"
721 );
722 assert!(
723 system[1].get("cache_control").is_none(),
724 "the tail block stays uncached"
725 );
726 assert!(
727 system[1]["text"].as_str().unwrap().contains("2026-06-27"),
728 "the date was relocated to the tail"
729 );
730 }
731
732 #[test]
733 fn apply_skips_small_system_and_clean_system() {
734 let mut small = serde_json::json!({ "system": "Today is 2026-06-27", "messages": [] });
735 assert_eq!(
736 apply_anthropic_relocate(&mut small),
737 0,
738 "below the cacheable floor → no churn"
739 );
740 let mut clean =
741 serde_json::json!({ "system": "You are precise. ".repeat(400), "messages": [] });
742 assert_eq!(
743 apply_anthropic_relocate(&mut clean),
744 0,
745 "no volatile fields → strict no-op"
746 );
747 }
748
749 #[test]
750 fn apply_skips_array_with_existing_breakpoint() {
751 let mut doc = serde_json::json!({
752 "system": [{
753 "type": "text",
754 "text": big_system_with_date(),
755 "cache_control": { "type": "ephemeral" }
756 }],
757 "messages": []
758 });
759 assert_eq!(
760 apply_anthropic_relocate(&mut doc),
761 0,
762 "a client-anchored array must be left untouched"
763 );
764 }
765
766 #[test]
767 fn apply_is_deterministic() {
768 let mk = || serde_json::json!({ "system": big_system_with_date(), "messages": [] });
769 let (mut a, mut b) = (mk(), mk());
770 assert_eq!(apply_anthropic_relocate(&mut a), 1);
771 assert_eq!(apply_anthropic_relocate(&mut b), 1);
772 assert_eq!(a, b, "identical input → byte-identical output (#498)");
773 }
774}