diff --git a/docs/maintenance-2026-12-02.md b/docs/maintenance-2026-12-02.md new file mode 100644 index 0000000..f91240c --- /dev/null +++ b/docs/maintenance-2026-12-02.md @@ -0,0 +1,27 @@ +# Upstream maintenance — 2026-12-02 + +## Scope and history + +- Exact fork baseline: `79953e3d92ca610a301123e1621d55949fee98e8`. +- Latest fetched upstream: `52532d8f3d082d21360a192c6d76c8783847de97`. +- Newly inspected upstream range: `dbe641f286a489ecb39e3c041c554371e6add864..52532d8f3d082d21360a192c6d76c8783847de97` (50 commits). +- Semantic adaptation only of `6101a906d3d0c7b222ddb283f058950607e81bd7`: incremental Claude tool arguments and empty-object fallback. Independent Rust and Go histories cannot be merged literally; patch IDs do not establish semantic coverage. This is NOT a complete upstream sync. + +## Combination and retained features + +The fork already forwards tool argument fragments immediately. Retain that implementation and empty opening argument delta, suppress empty fragments, and emit `{}` once at tool-block stop only if no nonempty argument fragment was emitted. Track argument presence by Claude block index independently of OpenAI tool indices. Regression coverage includes sparse block indices, two tool calls, byte-fragmented SSE, empty and split arguments, repeated stops, terminal framing. + +No textual merge conflict. Upstream semantics are adapted into the existing Rust translator rather than replacing it with Go. Preserve bounded SSE parsing, reasoning/usage translation, Home-owned scheduling/authentication, RESP/mTLS, durable accounting, branding, and plugin restrictions. No Home/UI payload or database schema change. Home database remains version 31; no migration added. + +## Verification + +Same toolchain/environment, independent existing Cargo target caches: + +- `cargo test --locked --lib claude_tool_arguments_stream_immediately_and_default_only_when_empty`: identical new fixture on exact baseline FAIL (missing `{}` fallback), integration PASS. Temporary fixture removed from detached baseline after comparison. +- `cargo test --locked --all-targets`: baseline 528 pass / 0 fail / 1 ignored; integration 529 pass / 0 fail / 1 ignored. +- `cargo fmt --all --check`: PASS. +- `bash -n install.sh scripts/test-install.sh && bash scripts/test-install.sh`: PASS (synthetic installer checks, not production deployment). +- `cargo clippy --locked --all-targets -- -D warnings`: baseline and integration both FAIL, exit 101, identical six diagnostics in unchanged codex_catalog, classifier, gateway and test code. Logs differ only in worktree path. This PR must remain DRAFT pending required lint gate resolution. +- Disk checked before builds: 3.7 GiB available; no ENOSPC encountered. + +No deployment, restart, production DB access, force push, or main push. Docker/release/live-provider qualification not run. Broader upstream changes (Copilot Decisions, affinity routing, Claude cloaking, Antigravity replay/TTL) are NOT claimed implemented; they need contract-aware Rust ports, not replacement of Home-owned architecture. diff --git a/docs/maintenance-2026-12-03.md b/docs/maintenance-2026-12-03.md new file mode 100644 index 0000000..035a21a --- /dev/null +++ b/docs/maintenance-2026-12-03.md @@ -0,0 +1,28 @@ +# Daily upstream review — 2026-12-03 WIB + +## Scope + +- Exact origin/main baseline: `79953e3d92ca610a301123e1621d55949fee98e8`. +- Latest inspected upstream: `1c0d1cd5fea1cb2aeda5a06358bf74ae9277a3cd`. +- New upstream range: `52532d8f3d082d21360a192c6d76c8783847de97..1c0d1cd5fea1cb2aeda5a06358bf74ae9277a3cd` (22 commits). +- Existing draft branch already contains current origin/main; normal merge reports already up to date. + +This is a partial semantic review, not a complete upstream merge. The fork is Rust and upstream is Go; patch equivalence alone cannot establish behavior coverage. + +## Preserved stream behavior + +Upstream `b5978ab210b63e7b2a45c9fb848456230efb398b` fixes premature Claude stream completion on mid-stream OpenAI usage-only chunks. The Rust translator already does not close on usage chunks: it requires a finish reason and `[DONE]`. Retain its incremental usage delivery rather than replacing it with the upstream buffering implementation. + +Add a byte-fragmented regression covering mid-stream usage, subsequent tool arguments, clean truncated EOF, finish reason without premature message stop, authoritative trailing token counts including cache reads, and exactly one final message stop. The same fixture passes on exact origin/main, establishing existing semantic coverage for this translator scenario, not route-level or full upstream equivalence. + +The previous draft's empty Claude tool argument fallback remains intact. Home-owned credentials/scheduling, RESP/mTLS, bounded parsing, durable accounting, plugin restrictions, branding, authentication and billing contracts are unchanged. No textual conflict or production implementation replacement was needed. + +## Boundaries + +- Upstream Devin cooling and AI Studio relay updates do not justify enabling those unsupported workers: Devin remains intentionally out of scope; AI Studio remains fail-closed. +- Antigravity hub/session/signature changes need a contract-aware Rust port; do not introduce a local scheduler or credential store. +- The Kimi truncated-EOF update needs provider/route-level investigation; this translator regression does not claim to cover that route. +- Existing strict Clippy errors block readiness. Keep the PR draft; do not weaken lint assertions or silently declare the gate passed. +- No database schema changes. Home fork schema stays 31 (upstream Home schema 21); no migration or version bump. + +No deployment, restart, production database access, main push, force push or auto-merge. diff --git a/src/protocol/stream.rs b/src/protocol/stream.rs index efbc829..3fdeae0 100644 --- a/src/protocol/stream.rs +++ b/src/protocol/stream.rs @@ -12,6 +12,7 @@ pub struct StreamTranslator { started: bool, pub complete: bool, blocks: BTreeMap, + tool_arguments_seen: std::collections::BTreeSet, next_block: u64, text_block: Option, input: Option, @@ -33,6 +34,7 @@ impl StreamTranslator { started: false, complete: false, blocks: BTreeMap::new(), + tool_arguments_seen: std::collections::BTreeSet::new(), next_block: 0, text_block: None, input: None, @@ -163,16 +165,32 @@ impl StreamTranslator { // Thinking signatures only matter for Claude-native replay. "signature_delta" => (), "input_json_delta" => { - let index = self + let block = uint(&v["index"])?; + let index = *self .blocks - .get(&uint(&v["index"])?) + .get(&block) .ok_or_else(|| invalid("unknown tool block"))?; - self.chunk(out,json!({"tool_calls":[{"index":index,"function":{"arguments":string(&delta["partial_json"])?}}]}),Value::Null); + let arguments = string(&delta["partial_json"])?; + if !arguments.is_empty() { + self.tool_arguments_seen.insert(block); + self.chunk(out,json!({"tool_calls":[{"index":index,"function":{"arguments":arguments}}]}),Value::Null); + } } _ => return Err(unsupported("Claude stream delta")), } } - "content_block_stop" => (), + "content_block_stop" => { + if let Some(block) = v["index"].as_u64() + && let Some(index) = self.blocks.get(&block) + && self.tool_arguments_seen.insert(block) + { + self.chunk( + out, + json!({"tool_calls":[{"index":index,"function":{"arguments":"{}"}}]}), + Value::Null, + ); + } + } "message_delta" if self.started => { if let Some(u) = v.get("usage").and_then(Value::as_object) { self.usage.as_object_mut().unwrap().extend(u.clone()); diff --git a/src/protocol/stream_tests.rs b/src/protocol/stream_tests.rs index 4833165..f00e1fd 100644 --- a/src/protocol/stream_tests.rs +++ b/src/protocol/stream_tests.rs @@ -1,4 +1,52 @@ use super::*; +#[test] +fn claude_tool_arguments_stream_immediately_and_default_only_when_empty() { + for fragments in [vec![], vec![""], vec!["{\"x\":", "1}"], vec!["{}"]] { + let mut t = StreamTranslator::new(Format::ClaudeMessages, "alias", 42); + let mut feed = |event: Value| { + let wire = format!("data: {event}\n\n"); + let mut out = Vec::new(); + for byte in wire.bytes() { + out.extend(t.feed(&[byte]).unwrap()); + } + String::from_utf8(out).unwrap() + }; + feed(json!({"type":"message_start","message":{"id":"r","usage":{}}})); + for block in [2, 5] { + let opening = feed( + json!({"type":"content_block_start","index":block,"content_block":{"type":"tool_use","id":format!("c{block}"),"name":"f","input":{}}}), + ); + assert!(opening.contains("\"arguments\":\"\"")); + for fragment in &fragments { + let out = feed( + json!({"type":"content_block_delta","index":block,"delta":{"type":"input_json_delta","partial_json":fragment}}), + ); + if fragment.is_empty() { + assert!(out.is_empty()); + } else { + let chunk: Value = + serde_json::from_str(out.trim().strip_prefix("data: ").unwrap()).unwrap(); + assert_eq!( + chunk["choices"][0]["delta"]["tool_calls"][0]["function"]["arguments"], + *fragment + ); + } + } + let stop = json!({"type":"content_block_stop","index":block}); + let out = feed(stop.clone()); + if fragments.iter().all(|fragment| fragment.is_empty()) { + assert!(out.contains("\"arguments\":\"{}\"")); + } else { + assert!(out.is_empty()); + } + assert!(feed(stop).is_empty()); + } + feed(json!({"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{}})); + assert!(feed(json!({"type":"message_stop"})).ends_with("data: [DONE]\n\n")); + t.finish().unwrap(); + } +} + fn fixture(from: Format, events: &[Value], done: bool) -> (StreamTranslator, String) { let mut wire = events .iter() @@ -33,6 +81,44 @@ fn fragmented_chat_text_tools_usage_to_claude() { assert!(out.contains("\"cache_read_input_tokens\":3")); assert!(out.ends_with("data: {\"type\":\"message_stop\"}\n\n")); } +// Upstream b5978ab2: usage-only chunks are not a generation boundary. +#[test] +fn midstream_usage_does_not_close_claude_before_finish_reason() { + let mut t = StreamTranslator::new(Format::OpenAiChat, "alias", 42); + let mut feed = |event: Value| { + let wire = format!("data: {event}\n\n"); + let mut out = Vec::new(); + for byte in wire.bytes() { + out.extend(t.feed(&[byte]).unwrap()); + } + String::from_utf8(out).unwrap() + }; + feed(json!({"id":"r","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":null}]})); + let interim = + feed(json!({"id":"r","choices":[],"usage":{"prompt_tokens":5,"completion_tokens":1}})); + assert!(interim.contains("\"input_tokens\":5")); + assert!(!interim.contains("message_stop")); + assert!(!interim.contains("stop_reason")); + let tool = feed( + json!({"id":"r","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call","function":{"name":"f","arguments":"{}"}}]},"finish_reason":null}]}), + ); + assert!(tool.contains("input_json_delta")); + assert!(!tool.contains("message_stop")); + // A clean transport EOF is still truncation, even after a valid usage chunk. + assert!(t.finish().is_err()); + let finish = t.feed(b"data: {\"id\":\"r\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n").unwrap(); + assert!(!String::from_utf8(finish).unwrap().contains("message_stop")); + let trailing = t.feed(b"data: {\"id\":\"r\",\"choices\":[],\"usage\":{\"prompt_tokens\":10,\"completion_tokens\":4,\"prompt_tokens_details\":{\"cached_tokens\":3}}}\n\n").unwrap(); + let trailing = String::from_utf8(trailing).unwrap(); + assert!(trailing.contains("\"input_tokens\":7")); + assert!(trailing.contains("\"cache_read_input_tokens\":3")); + assert!(trailing.contains("\"output_tokens\":4")); + assert!(!trailing.contains("message_stop")); + let end = String::from_utf8(t.feed(b"data: [DONE]\n\n").unwrap()).unwrap(); + assert_eq!(end.matches("event: message_stop").count(), 1); + t.finish().unwrap(); +} + #[test] fn fragmented_claude_text_tools_and_partial_usage_to_chat() { let (t, out) = fixture(