Skip to main content

codewhale_models/
turn_classify.rs

1use crate::{ContentBlock, Message, Role};
2
3/// Detection marker for a new-format checkpoint: the opening words of
4/// `SUMMARY_HEADER`. A new checkpoint is recognised only when its first
5/// block starts with this marker and its second block is the provenance
6/// block, so a user message that merely quotes the phrase stays a user
7/// message.
8pub const COMPACTION_SUMMARY_MARKER: &str = "Codewhale handoff note";
9
10/// Legacy detection marker only. Checkpoints written before the handoff note
11/// opened with this sentence. Saved sessions that still carry it must be
12/// recognised so the next pass replaces that checkpoint instead of stacking a
13/// second one.
14pub const LEGACY_V2_COMPACTION_SUMMARY_MARKER: &str =
15    "Another language model started to solve this problem";
16
17pub const COMPACTION_CHECKPOINT_PROVENANCE: &str = "<!-- codewhale.compaction-checkpoint.v1 -->";
18
19/// Request-time recognition: exactly the header text block plus the
20/// provenance block. User text merely quoting a marker keeps its original
21/// wire position. Checkpoints saved before the handoff note still pass, so
22/// their position survives restore and the next pass replaces them.
23pub fn is_wire_compaction_checkpoint_message(message: &Message) -> bool {
24    let [
25        ContentBlock::Text {
26            text,
27            cache_control: None,
28        },
29        ContentBlock::Text {
30            text: provenance,
31            cache_control: None,
32        },
33    ] = message.content.as_slice()
34    else {
35        return false;
36    };
37    message.role == Role::User
38        && (text.starts_with(COMPACTION_SUMMARY_MARKER)
39            || text.starts_with(LEGACY_V2_COMPACTION_SUMMARY_MARKER))
40        && provenance == COMPACTION_CHECKPOINT_PROVENANCE
41}
42
43pub const RESTORED_CHECKPOINT_TURN_META: &str = concat!(
44    "<turn_meta>\n",
45    "Input provenance: subagent_handoff (non-authoritative)\n",
46    "Restore projection: subagent_checkpoint_v1\n",
47    "</turn_meta>",
48);
49
50pub const RESTORED_COMPLETION_HEADER: &str = "[Codewhale restored sub-agent checkpoint]";
51
52pub const RESTORED_COMPLETIONS_HEADER: &str = "[Codewhale restored sub-agent checkpoints]";
53
54pub const RESTORED_RUNNING_HEADER: &str = "[Codewhale restored sub-agent runtime checkpoint]";
55
56pub const RESTORED_TOPOLOGY_HEADER: &str = "[Codewhale restored Agent topology checkpoint]";
57
58/// Return the user-safe display body for an already projected checkpoint.
59/// The exact metadata marker keeps arbitrary user-authored text on the normal
60/// conversation path.
61pub fn restored_subagent_checkpoint_display(message: &Message) -> Option<&str> {
62    if message.role != "user" {
63        return None;
64    }
65    let [
66        ContentBlock::Text {
67            text,
68            cache_control: first_cache,
69        },
70        ContentBlock::Text {
71            text: turn_meta,
72            cache_control: meta_cache,
73        },
74    ] = message.content.as_slice()
75    else {
76        return None;
77    };
78    if first_cache.is_some()
79        || meta_cache.is_some()
80        || turn_meta != RESTORED_CHECKPOINT_TURN_META
81        || ![
82            RESTORED_COMPLETION_HEADER,
83            RESTORED_COMPLETIONS_HEADER,
84            RESTORED_RUNNING_HEADER,
85            RESTORED_TOPOLOGY_HEADER,
86        ]
87        .iter()
88        .any(|header| text.starts_with(header))
89    {
90        return None;
91    }
92    Some(text)
93}
94
95/// Classification used when locating a user-authored turn in the session log.
96///
97/// Runtime and tool messages are skipped because their provider-compatible
98/// `role = "user"` is not user authority. Unsupported user content is a real
99/// turn boundary, however, so callers must not skip it and edit an older turn.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum UserTurnPromptKind {
102    /// Assistant messages, tool results, and runtime-owned control messages.
103    NotPrompt,
104    /// A genuine user turn containing editable text.
105    Editable,
106    /// A genuine user turn without editable text, such as an image-only turn.
107    Unsupported,
108}
109
110/// Classify `message` for edit-last-turn and admitted-display handling.
111#[must_use]
112pub fn classify_user_turn_prompt(message: &Message) -> UserTurnPromptKind {
113    if message.role != Role::User {
114        return UserTurnPromptKind::NotPrompt;
115    }
116    if message.content.iter().any(|block| {
117        matches!(
118            block,
119            ContentBlock::ToolResult { .. }
120                | ContentBlock::ToolSearchToolResult { .. }
121                | ContentBlock::CodeExecutionToolResult { .. }
122                | ContentBlock::WebSearchToolResult { .. }
123                | ContentBlock::WebFetchToolResult { .. }
124        )
125    }) {
126        return UserTurnPromptKind::NotPrompt;
127    }
128    if is_runtime_owned_user_message(message) || is_wire_compaction_checkpoint_message(message) {
129        return UserTurnPromptKind::NotPrompt;
130    }
131
132    let turn_metadata_index = turn_metadata_text(message).map(|(index, _)| index);
133    if message.content.iter().enumerate().any(|(index, block)| {
134        Some(index) != turn_metadata_index && matches!(block, ContentBlock::Text { .. })
135    }) {
136        UserTurnPromptKind::Editable
137    } else {
138        UserTurnPromptKind::Unsupported
139    }
140}
141
142/// True when a `role = "user"` message is runtime-owned rather than
143/// user-authored. Runtime authority is accepted only from the engine-owned
144/// structural `<turn_meta>` block, never from arbitrary user text that happens
145/// to resemble a runtime envelope or metadata marker.
146pub fn is_runtime_owned_user_message(message: &Message) -> bool {
147    restored_subagent_checkpoint_display(message).is_some()
148        || has_non_authoritative_turn_provenance(message)
149}
150
151/// Return engine-owned metadata in either the current trailing shape or the
152/// historical leading shape. Requiring a separate prompt block prevents a
153/// user who submits `<turn_meta>…</turn_meta>` as ordinary text from minting
154/// authority.
155pub fn turn_metadata_text(message: &Message) -> Option<(usize, &str)> {
156    if message.content.len() < 2 {
157        return None;
158    }
159    if let Some(ContentBlock::Text {
160        text,
161        cache_control: None,
162    }) = message.content.last()
163    {
164        let trimmed = text.trim();
165        if is_complete_turn_metadata(trimmed) {
166            return Some((message.content.len() - 1, trimmed));
167        }
168    }
169    // Sessions written before the metadata-tail migration used
170    // `[turn_meta, prompt, ...]`. Match the same conservative legacy shape as
171    // the transcript renderer: a metadata envelope first and ordinary text
172    // last. A single user-authored metadata example is never hidden.
173    let ContentBlock::Text {
174        text,
175        cache_control: None,
176    } = message.content.first()?
177    else {
178        return None;
179    };
180    let trimmed = text.trim();
181    let trailing_text_is_ordinary = matches!(
182        message.content.last(),
183        Some(ContentBlock::Text { text, .. }) if !is_complete_turn_metadata(text.trim())
184    );
185    (is_complete_turn_metadata(trimmed) && trailing_text_is_ordinary).then_some((0, trimmed))
186}
187
188fn is_complete_turn_metadata(text: &str) -> bool {
189    text.strip_prefix("<turn_meta>")
190        .and_then(|body| body.split_once("</turn_meta>"))
191        .is_some_and(|(_, tail)| tail.is_empty())
192}
193
194pub fn same_recorded_turn(left: &Message, right: &Message) -> bool {
195    if left == right {
196        return true;
197    }
198    if left.role != Role::User || right.role != Role::User {
199        return false;
200    }
201    let (bare, stamped) = if left.content.len() < right.content.len() {
202        (left, right)
203    } else {
204        (right, left)
205    };
206    if stamped.content.len().checked_sub(1) != Some(bare.content.len()) {
207        return false;
208    }
209    let Some((index, metadata)) = turn_metadata_text(stamped) else {
210        return false;
211    };
212    if !metadata.starts_with("<turn_meta>\nCurrent local date: ")
213        || classify_user_turn_prompt(stamped) == UserTurnPromptKind::NotPrompt
214        || turn_metadata_text(bare).is_some()
215    {
216        return false;
217    }
218    stamped.content[..index] == bare.content[..index]
219        && stamped.content[index + 1..] == bare.content[index..]
220}
221
222/// Recognize both the current condensed provenance line and the legacy
223/// provenance/authority pair. Any explicitly non-authoritative provenance is
224/// runtime-owned; this stays correct as new provenance variants are added.
225fn has_non_authoritative_turn_provenance(message: &Message) -> bool {
226    let Some((_, metadata)) = turn_metadata_text(message) else {
227        return false;
228    };
229    let mut has_provenance = false;
230    let mut condensed_non_authoritative = false;
231    let mut legacy_non_authoritative = false;
232    for line in metadata.lines().map(str::trim) {
233        if let Some(value) = line.strip_prefix("Input provenance: ") {
234            has_provenance = true;
235            condensed_non_authoritative |= value.ends_with(" (non-authoritative)");
236        }
237        legacy_non_authoritative |= line == "Input authority: non_authoritative";
238    }
239    condensed_non_authoritative || (has_provenance && legacy_non_authoritative)
240}