From 09542e05a1574c6204c927a804afeeb8bfd1ed2e Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Fri, 27 Nov 2026 18:13:18 +0100 Subject: [PATCH] audit: tool_call_id replay, CoT dup guard, notepad/shell/sqlite/detok hardening (BUG-04/05/06/07/11/16, SEC-11) --- src/agent/notepad.rs | 53 +++++++++++++++-- src/agent/shell.rs | 26 ++++++++- src/context.rs | 120 +++++++++++++++++++++++++++++++++------ src/inkling/dialect.rs | 14 ++++- src/inkling/tokenizer.rs | 11 +++- src/store.rs | 49 +++++++++++++++- tests/inkling_dialect.rs | 35 ++++++++++-- 7 files changed, 276 insertions(+), 32 deletions(-) diff --git a/src/agent/notepad.rs b/src/agent/notepad.rs index 9430a43..7063301 100644 --- a/src/agent/notepad.rs +++ b/src/agent/notepad.rs @@ -79,7 +79,8 @@ pub async fn execute(store: &Arc, session_id: &str, args: &Json) -> S .and_then(|v| v.as_str()) .unwrap_or("") .trim() - .to_string(); + .replace("\r\n", "\n") + .replace('\r', "\n"); let store = store.clone(); let sid = session_id.to_string(); let res = tokio::task::spawn_blocking(move || -> Result { @@ -91,8 +92,8 @@ pub async fn execute(store: &Arc, session_id: &str, args: &Json) -> S if key.chars().count() > MAX_KEY_CHARS { return Ok(format!("error: key too long (max {MAX_KEY_CHARS} chars)")); } - if key.contains('\n') { - return Ok("error: key must be a single line".into()); + if key.chars().any(|c| c.is_control()) { + return Ok("error: key must be a single line (no control characters)".into()); } if text.is_empty() { return Ok("error: notepad set requires non-empty 'text'".into()); @@ -104,12 +105,14 @@ pub async fn execute(store: &Arc, session_id: &str, args: &Json) -> S )); } let entries = store.notepad(&sid)?; + // Budget the RENDERED header (`key: text` per line), not just the + // text: excluding keys let many long keys blow past the ceiling. let others: usize = entries .iter() .filter(|e| e.key != key) - .map(|e| e.text.chars().count()) + .map(|e| e.key.chars().count() + 2 + e.text.chars().count()) .sum(); - let total = others + nlen; + let total = others + key.chars().count() + 2 + nlen; if total > MAX_TOTAL_CHARS { return Ok(format!( "error: notepad full ({total} > {MAX_TOTAL_CHARS} chars). Remove or \ @@ -240,4 +243,44 @@ mod tests { assert_eq!(d["function"]["name"], "notepad"); assert_eq!(d["function"]["parameters"]["required"][0], "action"); } + + #[tokio::test] + async fn budget_counts_keys_and_rejects_control_chars() { + let (store, sid) = setup(); + // A carriage return (or any control char) in the key is rejected. + let out = execute( + &store, + &sid, + &json!({"action":"set","key":"a\rb","text":"x"}), + ) + .await; + assert!(out.contains("single line"), "{out}"); + // Keys count toward the budget: long keys + 1-char text hit the ceiling + // after ~125 entries, not the 8000 the text-only budget would allow. + let prefix = "k".repeat(60); + let mut refused = false; + for i in 0..200 { + let key = format!("{prefix}{i}"); + let out = execute(&store, &sid, &json!({"action":"set","key":key,"text":"x"})).await; + if out.contains("full") { + refused = true; + break; + } + } + assert!(refused, "key length must count toward the notepad budget"); + assert!(store.notepad(&sid).unwrap().len() < 200); + } + + #[tokio::test] + async fn text_carriage_returns_normalized() { + let (store, sid) = setup(); + execute( + &store, + &sid, + &json!({"action":"set","key":"k","text":"a\r\nb\rc"}), + ) + .await; + let np = store.notepad(&sid).unwrap(); + assert_eq!(np[0].text, "a\nb\nc"); + } } diff --git a/src/agent/shell.rs b/src/agent/shell.rs index 15bca2c..a5a682b 100644 --- a/src/agent/shell.rs +++ b/src/agent/shell.rs @@ -147,9 +147,16 @@ impl ShellRequest { .filter(|s| !s.trim().is_empty()) .ok_or_else(|| anyhow::anyhow!("shell_exec requires a non-empty 'command'"))? .to_string(); - let cwd = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string); + let cwd = args + .get("cwd") + .and_then(|v| v.as_str()) + .filter(|s| !s.trim().is_empty()) + .map(str::to_string); + // Accept `timeout` as an alias of `timeout_secs`: the TOOL_USE manual + // spells `timeout?`, so a model following it must not be silently ignored. let secs = args .get("timeout_secs") + .or_else(|| args.get("timeout")) .and_then(|v| v.as_u64()) .unwrap_or(DEFAULT_TIMEOUT_SECS) .clamp(1, 3600); @@ -268,4 +275,21 @@ mod tests { assert_eq!(d["function"]["name"], "shell_exec"); assert_eq!(d["function"]["parameters"]["required"][0], "command"); } + + #[test] + fn empty_cwd_falls_back_and_timeout_alias_accepted() { + // cwd:"" (or whitespace) must be None so the caller falls back to the + // session folder instead of Command::current_dir("") failing with ENOENT. + for cwd in ["", " "] { + let r = ShellRequest::from_args(&json!({"command":"ls","cwd":cwd})).unwrap(); + assert_eq!(r.cwd, None, "cwd {cwd:?} should fall back"); + } + // The manual spells `timeout`; accept it as an alias of timeout_secs. + let r = ShellRequest::from_args(&json!({"command":"ls","timeout":300})).unwrap(); + assert_eq!(r.timeout, Duration::from_secs(300)); + // timeout_secs wins when both are present. + let r = ShellRequest::from_args(&json!({"command":"ls","timeout":300,"timeout_secs":5})) + .unwrap(); + assert_eq!(r.timeout, Duration::from_secs(5)); + } } diff --git a/src/context.rs b/src/context.rs index 547e237..012f018 100644 --- a/src/context.rs +++ b/src/context.rs @@ -103,25 +103,43 @@ fn prefix_messages( // Tool/system turns stay untagged. Strip any tag the model echoed into // stored content so we never stack a second one (duplication loop). let clean = strip_speaker_tags(&m.content); - let content = match m.role.as_str() { - "user" => format!( - "{}{}", - speaker_prefix(user_name, m.created_at, tz_offset), - clean - ), - "assistant" => format!( - "{}{}", - speaker_prefix(&sess.title, m.created_at, tz_offset), - clean - ), - _ => clean, - }; - let mut msg = text_message(role_of(&m.role), content); - msg.tool_calls = m + let tool_calls = m .tool_calls_json .as_deref() .and_then(|s| serde_json::from_str(s).ok()); - messages.push(msg); + // A tool-call-only assistant turn carries no text: keep content None to + // match `agent::run_loop` (which pushed the model's message verbatim). + // Stamping a bare [SPEAKER] here would emit a spurious <|content_text|> + // block, priming empty speaker tags and diverging from the cached prefix. + let tool_only = m.role == "assistant" && clean.is_empty() && tool_calls.is_some(); + let content = if tool_only { + None + } else { + let text = match m.role.as_str() { + "user" => format!( + "{}{}", + speaker_prefix(user_name, m.created_at, tz_offset), + clean + ), + "assistant" => format!( + "{}{}", + speaker_prefix(&sess.title, m.created_at, tz_offset), + clean + ), + _ => clean, + }; + Some(serde_json::Value::String(text)) + }; + messages.push(ChatMessage { + role: role_of(&m.role), + content, + // Restore the tool-call id so the template resolves the tool name from + // the preceding assistant turn (and the prefix matches run_loop). + tool_call_id: m.tool_call_id.clone(), + tool_calls, + name: None, + reasoning_content: None, + }); } messages } @@ -326,6 +344,76 @@ mod tests { ); } + #[test] + fn history_restores_tool_call_id_and_skips_speaker_on_tool_only_turns() { + let sess = Session { + id: "s".into(), + title: "Nebula".into(), + model: "m".into(), + settings: crate::store::SessionSettings::default(), + name_locked: true, + folder: None, + created_at: 0, + updated_at: 0, + }; + let calls = serde_json::json!([{ + "id": "call_1", "type": "function", + "function": {"name": "shell_exec", "arguments": "{\"command\":\"ls\"}"} + }]); + let history = vec![ + StoredMessage { + id: 1, + role: "user".into(), + content: "lista i file".into(), + reasoning_content: None, + tool_calls_json: None, + tool_call_id: None, + prompt_tokens: 0, + completion_tokens: 0, + created_at: 1_700_000_000, + }, + StoredMessage { + id: 2, + role: "assistant".into(), + content: "".into(), + reasoning_content: Some("penso".into()), + tool_calls_json: Some(calls.to_string()), + tool_call_id: None, + prompt_tokens: 0, + completion_tokens: 0, + created_at: 1_700_000_001, + }, + StoredMessage { + id: 3, + role: "tool".into(), + content: "file.txt".into(), + reasoning_content: None, + tool_calls_json: None, + tool_call_id: Some("call_1".into()), + prompt_tokens: 0, + completion_tokens: 0, + created_at: 1_700_000_002, + }, + ]; + let prefix = compose_prefix(&sess, &history, "Federico", &[], &[]); + // BUG-05: the tool-only assistant turn has no text (no bare [SPEAKER] block). + let asst = prefix + .iter() + .find(|m| matches!(m.role, Role::Assistant)) + .unwrap(); + assert!( + asst.content.is_none(), + "tool-only turn must not carry a [SPEAKER] text block" + ); + assert!(asst.tool_calls.is_some()); + // BUG-04: the tool result keeps its id so the template resolves the name. + let tool = prefix + .iter() + .find(|m| matches!(m.role, Role::Tool)) + .unwrap(); + assert_eq!(tool.tool_call_id.as_deref(), Some("call_1")); + } + #[test] fn format_stamp_known_dates_and_offset() { assert_eq!(format_stamp(0, 0), "1970-01-01 00:00"); diff --git a/src/inkling/dialect.rs b/src/inkling/dialect.rs index 39bc061..a44ac28 100644 --- a/src/inkling/dialect.rs +++ b/src/inkling/dialect.rs @@ -163,6 +163,8 @@ pub struct InklingDialect { think_acc: String, end_ws: String, emitted_visible: bool, + /// Thinking already streamed live by `emit` (so `finish` must not re-emit it). + emitted_reasoning: bool, /// How many tool frames have been rendered (diagnostics). pub calls: u32, } @@ -228,6 +230,7 @@ impl InklingDialect { State::Think => { self.append_think(chunk); out.push(Out::reasoning(chunk)); + self.emitted_reasoning = true; } State::ThinkEnd => { if chunk.trim().is_empty() { @@ -237,6 +240,7 @@ impl InklingDialect { let combined = format!("{}{}{}", tag::END_MESSAGE, self.end_ws, chunk); self.append_think(&combined); out.push(Out::reasoning(combined)); + self.emitted_reasoning = true; self.end_ws.clear(); self.state = State::Think; } @@ -318,6 +322,10 @@ impl InklingDialect { State::ThinkEnd => { let held = format!("{}{}", tag::END_MESSAGE, self.end_ws); self.append_think(&held); + // Stream the quoted end-message live (mirrors TextEnd below): + // it is thinking text, not a channel end, and must not be lost. + out.push(Out::reasoning(held)); + self.emitted_reasoning = true; self.end_ws.clear(); } State::Text => { @@ -424,11 +432,13 @@ impl InklingDialect { self.emitted_visible = true; } } - // #6682: budget expired inside thinking with no visible answer yet: - // surface the truncated thinking rather than an empty 200 OK. + // #6682: budget expired inside thinking with no visible answer yet. + // Thinking is streamed live by `emit`, so only surface the buffer if + // it was somehow NOT streamed — never duplicate the live CoT (BUG-06). State::Think | State::ThinkEnd if reason == Some("length") && !self.emitted_visible + && !self.emitted_reasoning && !think.trim().is_empty() => { out.push(Out::reasoning(think)); diff --git a/src/inkling/tokenizer.rs b/src/inkling/tokenizer.rs index 545f984..61b76df 100644 --- a/src/inkling/tokenizer.rs +++ b/src/inkling/tokenizer.rs @@ -133,8 +133,15 @@ impl Detok { /// Flush whatever is left (including any held replacement) at end of stream. pub fn finish(&mut self) -> String { let full = self.tok.decode_all(&self.ids).unwrap_or_default(); - if full.len() > self.emitted { - let piece = full[self.emitted..].to_string(); + // `emitted` was a char boundary in an earlier decode; floor it to one in + // case the suffix re-aligned (an incomplete code point resolved at EOF), + // so the slice can never panic. + let mut start = self.emitted.min(full.len()); + while start > 0 && !full.is_char_boundary(start) { + start -= 1; + } + if full.len() > start { + let piece = full[start..].to_string(); self.emitted = full.len(); piece } else { diff --git a/src/store.rs b/src/store.rs index 7bada9e..066aaaa 100644 --- a/src/store.rs +++ b/src/store.rs @@ -346,6 +346,9 @@ impl SqliteStore { conn.pragma_update(None, "journal_mode", "WAL")?; conn.pragma_update(None, "synchronous", "NORMAL")?; conn.pragma_update(None, "foreign_keys", "ON")?; + // Wait briefly for a concurrent writer (e.g. an external reader/tool in + // WAL) instead of failing immediately with SQLITE_BUSY. + conn.pragma_update(None, "busy_timeout", 5000)?; conn.execute_batch(SCHEMA)?; migrate(&conn)?; seed_context_sections(&conn)?; @@ -637,13 +640,16 @@ impl Store for SqliteStore { fn stats(&self) -> Result { let conn = self.lock(); let sessions: i64 = conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?; - // Totals + tool-call count in one pass. tool_calls_json is always a JSON - // array of calls (or NULL); json_array_length counts the calls themselves. + // Totals + tool-call count in one pass. tool_calls_json is a JSON array + // of calls (or NULL); guard with json_valid/json_type so one corrupt or + // non-array row cannot fail the whole stats query. let (messages, prompt, completion, tool_calls): (i64, i64, i64, i64) = conn.query_row( "SELECT COUNT(*), COALESCE(SUM(prompt_tokens),0), COALESCE(SUM(completion_tokens),0), COALESCE(SUM(CASE WHEN tool_calls_json IS NOT NULL + AND json_valid(tool_calls_json) + AND json_type(tool_calls_json) = 'array' THEN json_array_length(tool_calls_json) ELSE 0 END),0) FROM messages", [], @@ -975,6 +981,45 @@ mod tests { assert_eq!(st.daily[0].completion_tokens, 5); } + #[test] + fn stats_survives_a_corrupt_tool_calls_row() { + let s = store(); + let sess = s + .create_session("Chat", "m", &SessionSettings::default()) + .unwrap(); + // A corrupt (non-JSON) tool_calls_json row must not fail the whole query. + s.append_message( + &sess.id, + NewMessage { + role: "assistant", + content: "x", + reasoning_content: None, + tool_calls_json: Some("not-json"), + tool_call_id: None, + prompt_tokens: 1, + completion_tokens: 1, + }, + ) + .unwrap(); + // A valid array still counts. + s.append_message( + &sess.id, + NewMessage { + role: "assistant", + content: "y", + reasoning_content: None, + tool_calls_json: Some(r#"[{"id":"1"}]"#), + tool_call_id: None, + prompt_tokens: 1, + completion_tokens: 1, + }, + ) + .unwrap(); + let st = s.stats().unwrap(); + assert_eq!(st.messages, 2); + assert_eq!(st.tool_calls, 1); // corrupt row skipped, valid array counted + } + #[test] fn settings_instance_and_name_lock() { let s = store(); diff --git a/tests/inkling_dialect.rs b/tests/inkling_dialect.rs index 57aac28..2bbe91b 100644 --- a/tests/inkling_dialect.rs +++ b/tests/inkling_dialect.rs @@ -214,7 +214,9 @@ fn truncated_tool_falls_back_to_header_name() { #[test] fn thinking_only_at_length_surfaces_reasoning() { - // #6682: budget expires mid-thinking with no answer. + // #6682: budget expires mid-thinking with no answer. Thinking is streamed + // live by emit(), so finish() must NOT re-emit it: the whole CoT appears + // exactly once (BUG-06 — duplication was amplified by the 16384 budget). let outs = run( &[ (tag::MESSAGE_MODEL, true), @@ -224,9 +226,34 @@ fn thinking_only_at_length_surfaces_reasoning() { Some("length"), ); assert!(content_of(&outs).is_empty()); - // the live delta plus the finish-time accumulation both carry it (faithful - // to the reference: patched emit + _finish_typed #6682) - assert!(reasoning_of(&outs).contains("pondering")); + assert_eq!( + reasoning_of(&outs), + "pondering", + "thinking must appear exactly once, not duplicated at finish" + ); +} + +#[test] +fn quoted_end_message_in_think_end_streams_live() { + // #6675: two consecutive end-messages in thinking — the first is quoted text + // and must surface in reasoning live (mirrors TextEnd), not be lost. + let outs = run( + &[ + (tag::MESSAGE_MODEL, true), + (tag::CONTENT_THINKING, true), + ("x", false), + (tag::END_MESSAGE, true), + (tag::END_MESSAGE, true), + ], + None, + ); + let r = reasoning_of(&outs); + assert!(r.contains('x'), "{r}"); + assert!( + r.contains(tag::END_MESSAGE), + "quoted tag must stream live: {r}" + ); + assert!(content_of(&outs).is_empty()); } #[test]