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