| 1 | use super::*; |
| 2 | use crate::http::*; |
| 3 | use crate::stdio::*; |
| 4 | use crate::turns::*; |
| 5 | use axum::extract::Request; |
| 6 | use axum::extract::State; |
| 7 | use axum::http::header; |
| 8 | use axum::response::{IntoResponse, Response}; |
| 9 | use axum::routing::get; |
| 10 | use axum::{Json, Router}; |
| 11 | use tokio::sync::Notify; |
| 12 | |
| 13 | #[derive(Clone)] |
| 14 | struct FakeOwner { |
| 15 | record: Arc<Mutex<Value>>, |
| 16 | calls: Arc<Mutex<Vec<(String, String, Value)>>>, |
| 17 | owner: RuntimeOwnerReceipt, |
| 18 | block_import: bool, |
| 19 | import_seen: Arc<Notify>, |
| 20 | import_release: Arc<Notify>, |
| 21 | operations: Arc<Mutex<HashMap<String, (Value, CanonicalThreadReceipt)>>>, |
| 22 | fork_record: Arc<Mutex<Option<Value>>>, |
| 23 | missing_after_commit: Arc<std::sync::atomic::AtomicBool>, |
| 24 | goal: Arc<Mutex<Option<Value>>>, |
| 25 | turn_seq: Arc<std::sync::atomic::AtomicU64>, |
| 26 | pending_operation: Arc<std::sync::atomic::AtomicBool>, |
| 27 | recovery_prepared: Arc<std::sync::atomic::AtomicBool>, |
| 28 | recovery_refusal: Arc<std::sync::atomic::AtomicBool>, |
| 29 | document_digest: Arc<Mutex<String>>, |
| 30 | } |
| 31 | |
| 32 | async fn owned_http(State(fake): State<FakeOwner>, request: Request) -> Response { |
| 33 | let method = request.method().clone(); |
| 34 | let path = request.uri().path().to_owned(); |
| 35 | let authorization = request |
| 36 | .headers() |
| 37 | .get(axum::http::header::AUTHORIZATION) |
| 38 | .cloned(); |
| 39 | let bytes = axum::body::to_bytes(request.into_body(), MAX_CANONICAL_HISTORY_BYTES) |
| 40 | .await |
| 41 | .unwrap(); |
| 42 | let body = if bytes.is_empty() { |
| 43 | Value::Null |
| 44 | } else { |
| 45 | serde_json::from_slice(&bytes).unwrap() |
| 46 | }; |
| 47 | fake.calls |
| 48 | .lock() |
| 49 | .await |
| 50 | .push((method.to_string(), path.clone(), body.clone())); |
| 51 | if path == "/v1/config/reload" { |
| 52 | assert_eq!(method, Method::POST); |
| 53 | assert_eq!( |
| 54 | authorization.as_ref().map(|value| value.as_bytes()), |
| 55 | Some(b"Bearer private-compatibility-reload-fixture".as_slice()) |
| 56 | ); |
| 57 | return StatusCode::NO_CONTENT.into_response(); |
| 58 | } |
| 59 | if path == "/v1/thread-history/operations/lookup" |
| 60 | || path == "/v1/thread-history/operations/recover" |
| 61 | { |
| 62 | let recovery = if path.ends_with("/recover") { |
| 63 | Some(serde_json::from_value::<CanonicalThreadOperationRecovery>(body.clone()).unwrap()) |
| 64 | } else { |
| 65 | None |
| 66 | }; |
| 67 | let input: CanonicalThreadOperationLookup = match recovery.as_ref() { |
| 68 | Some(recovery) => recovery.operation.clone(), |
| 69 | None => serde_json::from_value(body).unwrap(), |
| 70 | }; |
| 71 | assert_eq!(input.expected_data_dir, fake.owner.data_dir); |
| 72 | assert_eq!(input.expected_execution_scope, fake.owner.execution_scope); |
| 73 | let operations = fake.operations.lock().await; |
| 74 | let Some((prior, receipt)) = operations.get(&input.operation_key) else { |
| 75 | return Json(CanonicalThreadOperationStatus::Absent).into_response(); |
| 76 | }; |
| 77 | let prior: CanonicalThreadMutationRequest = serde_json::from_value(prior.clone()).unwrap(); |
| 78 | assert_eq!(input.workspace, prior.workspace); |
| 79 | let (kind, source) = match prior.mutation { |
| 80 | CanonicalThreadMutation::Create { .. } => (CanonicalThreadOperationKind::Create, None), |
| 81 | CanonicalThreadMutation::Resume { source, .. } => { |
| 82 | (CanonicalThreadOperationKind::Resume, Some(source)) |
| 83 | } |
| 84 | CanonicalThreadMutation::Fork { source, .. } => { |
| 85 | (CanonicalThreadOperationKind::Fork, Some(source)) |
| 86 | } |
| 87 | }; |
| 88 | let source_runtime_thread_id = source.as_ref().and_then(|source| match source { |
| 89 | CanonicalHistorySource::Thread { |
| 90 | runtime_thread_id, .. |
| 91 | } => Some(runtime_thread_id.clone()), |
| 92 | CanonicalHistorySource::SavedSession { .. } => None, |
| 93 | }); |
| 94 | let association = codewhale_protocol::CanonicalThreadOperationAssociation { |
| 95 | kind, |
| 96 | source_runtime_thread_id, |
| 97 | source_session_id: None, |
| 98 | }; |
| 99 | if let Some(recovery) = recovery { |
| 100 | if recovery.association != association { |
| 101 | return ( |
| 102 | StatusCode::CONFLICT, |
| 103 | Json(json!({"error":"retained association changed"})), |
| 104 | ) |
| 105 | .into_response(); |
| 106 | } |
| 107 | if fake |
| 108 | .recovery_refusal |
| 109 | .load(std::sync::atomic::Ordering::SeqCst) |
| 110 | { |
| 111 | return ( |
| 112 | StatusCode::CONFLICT, |
| 113 | Json(json!({"error":"prepared target graph changed"})), |
| 114 | ) |
| 115 | .into_response(); |
| 116 | } |
| 117 | if fake |
| 118 | .recovery_prepared |
| 119 | .load(std::sync::atomic::Ordering::SeqCst) |
| 120 | { |
| 121 | fake.pending_operation |
| 122 | .store(false, std::sync::atomic::Ordering::SeqCst); |
| 123 | } |
| 124 | } |
| 125 | let status = if fake |
| 126 | .pending_operation |
| 127 | .load(std::sync::atomic::Ordering::SeqCst) |
| 128 | { |
| 129 | CanonicalThreadOperationStatus::Pending { |
| 130 | receipt: receipt.clone(), |
| 131 | association, |
| 132 | } |
| 133 | } else { |
| 134 | CanonicalThreadOperationStatus::Committed { |
| 135 | receipt: receipt.clone(), |
| 136 | association, |
| 137 | } |
| 138 | }; |
| 139 | return Json(status).into_response(); |
| 140 | } |
| 141 | if path == "/v1/thread-history/mutate" { |
| 142 | let input: CanonicalThreadMutationRequest = serde_json::from_value(body.clone()).unwrap(); |
| 143 | let mut operations = fake.operations.lock().await; |
| 144 | if let Some((prior, receipt)) = operations.get(&input.operation_key) { |
| 145 | if prior != &body { |
| 146 | return ( |
| 147 | StatusCode::CONFLICT, |
| 148 | Json(json!({"error":"intent changed"})), |
| 149 | ) |
| 150 | .into_response(); |
| 151 | } |
| 152 | return Json(receipt.clone()).into_response(); |
| 153 | } |
| 154 | let mut record = fake.record.lock().await.clone(); |
| 155 | let id = if matches!(input.mutation, CanonicalThreadMutation::Fork { .. }) { |
| 156 | record["id"] = json!("canonical-fork"); |
| 157 | record["workspace"] = json!(input.workspace); |
| 158 | *fake.fork_record.lock().await = Some(record); |
| 159 | "canonical-fork" |
| 160 | } else { |
| 161 | "canonical-1" |
| 162 | }; |
| 163 | let receipt = CanonicalThreadReceipt { |
| 164 | version: 1, |
| 165 | data_dir: fake.owner.data_dir, |
| 166 | execution_scope: fake.owner.execution_scope, |
| 167 | operation_key: input.operation_key.clone(), |
| 168 | request_digest: "1".repeat(64), |
| 169 | history_digest: "2".repeat(64), |
| 170 | runtime_thread_id: id.into(), |
| 171 | session_id: if id == "canonical-fork" { |
| 172 | "session-fork" |
| 173 | } else { |
| 174 | "session-1" |
| 175 | } |
| 176 | .into(), |
| 177 | }; |
| 178 | operations.insert(input.operation_key, (body, receipt.clone())); |
| 179 | return Json(receipt).into_response(); |
| 180 | } |
| 181 | if path == "/v1/thread-history/import" { |
| 182 | let input: CanonicalHistoryImportRequest = serde_json::from_value(body).unwrap(); |
| 183 | if input |
| 184 | .target_runtime_thread_id |
| 185 | .as_deref() |
| 186 | .is_some_and(|id| id != "canonical-1") |
| 187 | { |
| 188 | return ( |
| 189 | StatusCode::NOT_FOUND, |
| 190 | Json(json!({"error":"existing canonical target missing; no replacement"})), |
| 191 | ) |
| 192 | .into_response(); |
| 193 | } |
| 194 | fake.import_seen.notify_one(); |
| 195 | if fake.block_import { |
| 196 | fake.import_release.notified().await; |
| 197 | } |
| 198 | if let Some(mut goal) = input.history.goal { |
| 199 | goal.thread_id = input |
| 200 | .target_runtime_thread_id |
| 201 | .clone() |
| 202 | .unwrap_or_else(|| "canonical-1".into()); |
| 203 | if goal.status == codewhale_protocol::ThreadGoalStatus::Active { |
| 204 | goal.status = codewhale_protocol::ThreadGoalStatus::Paused; |
| 205 | goal.pause_reason = None; |
| 206 | } |
| 207 | let goal = serde_json::to_value(goal).unwrap(); |
| 208 | let mut current = fake.goal.lock().await; |
| 209 | if current.as_ref().is_some_and(|prior| prior != &goal) { |
| 210 | return ( |
| 211 | StatusCode::CONFLICT, |
| 212 | Json(json!({"error":"canonical goal conflict; source retained"})), |
| 213 | ) |
| 214 | .into_response(); |
| 215 | } |
| 216 | *current = Some(goal); |
| 217 | } |
| 218 | return Json(CanonicalThreadReceipt { |
| 219 | version: 1, |
| 220 | data_dir: fake.owner.data_dir, |
| 221 | execution_scope: fake.owner.execution_scope, |
| 222 | operation_key: input.operation_key, |
| 223 | request_digest: "1".repeat(64), |
| 224 | history_digest: "2".repeat(64), |
| 225 | runtime_thread_id: input |
| 226 | .target_runtime_thread_id |
| 227 | .unwrap_or_else(|| "canonical-1".into()), |
| 228 | session_id: "session-1".into(), |
| 229 | }) |
| 230 | .into_response(); |
| 231 | } |
| 232 | if path == "/v1/threads/running" { |
| 233 | return Json(json!([])).into_response(); |
| 234 | } |
| 235 | if path == "/v1/threads/canonical-1/turns" && method == Method::POST { |
| 236 | let seq = fake |
| 237 | .turn_seq |
| 238 | .fetch_add(1, std::sync::atomic::Ordering::SeqCst) |
| 239 | + 1; |
| 240 | return Json(json!({"thread":{"id":"canonical-1","model":"fixture-model"},"turn":{"id":format!("fixture-turn-{seq}"),"thread_id":"canonical-1"}})).into_response(); |
| 241 | } |
| 242 | if path == "/v1/threads/canonical-1/events" { |
| 243 | let seq = fake.turn_seq.load(std::sync::atomic::Ordering::SeqCst); |
| 244 | let frame = json!({"seq":seq,"thread_id":"canonical-1","turn_id":format!("fixture-turn-{seq}"), |
| 245 | "payload":{"turn":{"id":format!("fixture-turn-{seq}"),"thread_id":"canonical-1","status":"completed"}}}); |
| 246 | return ( |
| 247 | [(header::CONTENT_TYPE, "text/event-stream")], |
| 248 | format!("event: turn.completed\ndata: {frame}\n\n"), |
| 249 | ) |
| 250 | .into_response(); |
| 251 | } |
| 252 | if path == "/v1/threads/canonical-1/goal" { |
| 253 | if method == Method::PUT { |
| 254 | let goal = json!({"thread_id":"canonical-1","goal_id":"fixture-goal", |
| 255 | "objective":body["objective"],"token_budget":body["token_budget"],"status":"active", |
| 256 | "tokens_used":0,"time_used_seconds":0,"continuation_count":0, |
| 257 | "created_at":1,"updated_at":1,"repeated_gap_count":0}); |
| 258 | *fake.goal.lock().await = Some(goal.clone()); |
| 259 | return Json(goal).into_response(); |
| 260 | } |
| 261 | let mut goal = fake.goal.lock().await; |
| 262 | if method == Method::DELETE && goal.take().is_some() { |
| 263 | return StatusCode::NO_CONTENT.into_response(); |
| 264 | } |
| 265 | return match goal.clone() { |
| 266 | Some(goal) => Json(goal).into_response(), |
| 267 | None => (StatusCode::NOT_FOUND, Json(json!({"error":"no goal"}))).into_response(), |
| 268 | }; |
| 269 | } |
| 270 | if path == "/v1/threads" { |
| 271 | return Json(json!([fake.record.lock().await.clone()])).into_response(); |
| 272 | } |
| 273 | if path == "/v1/threads/canonical-1/history" { |
| 274 | return Json(json!({"version":1,"data_dir":fake.owner.data_dir,"execution_scope":fake.owner.execution_scope, |
| 275 | "runtime_thread_id":"canonical-1","saved_session_id":"session-1","saved_document_digest":"a".repeat(64),"session_goal_digest":"74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b","document_digest":fake.document_digest.lock().await.clone(), |
| 276 | "session":{"metadata":{"id":"session-1"},"messages":[{"role":"user","content":"active"}], |
| 277 | "journal":{"entries":[{"id":"root"},{"id":"inactive-branch"},{"id":"active"}]},"leaf_id":"active"}})).into_response(); |
| 278 | } |
| 279 | if path == "/v1/threads/canonical-fork" { |
| 280 | return Json(fake.fork_record.lock().await.clone().unwrap()).into_response(); |
| 281 | } |
| 282 | if path != "/v1/threads/canonical-1" { |
| 283 | return (StatusCode::NOT_FOUND, Json(json!({"error":"missing"}))).into_response(); |
| 284 | } |
| 285 | if fake |
| 286 | .missing_after_commit |
| 287 | .load(std::sync::atomic::Ordering::SeqCst) |
| 288 | && !fake.operations.lock().await.is_empty() |
| 289 | { |
| 290 | return ( |
| 291 | StatusCode::NOT_FOUND, |
| 292 | Json(json!({"error":"metadata disappeared"})), |
| 293 | ) |
| 294 | .into_response(); |
| 295 | } |
| 296 | if method == Method::PATCH { |
| 297 | let mut record = fake.record.lock().await; |
| 298 | for (key, value) in body.as_object().unwrap() { |
| 299 | record[key] = if key == "title" && value.as_str().is_some_and(|s| s.trim().is_empty()) { |
| 300 | Value::Null |
| 301 | } else { |
| 302 | value.clone() |
| 303 | }; |
| 304 | } |
| 305 | return Json(record.clone()).into_response(); |
| 306 | } |
| 307 | Json(json!({"thread":fake.record.lock().await.clone(),"items":[],"turns":[]})).into_response() |
| 308 | } |
| 309 | |
| 310 | fn fixture_state(block_import: bool) -> (AppState, tempfile::TempDir, FakeOwner) { |
| 311 | let temp = tempfile::tempdir().unwrap(); |
| 312 | let config_path = temp.path().join("config.toml"); |
| 313 | std::fs::write(&config_path, "").unwrap(); |
| 314 | let mut state = build_state(Some(config_path.clone()), None).unwrap(); |
| 315 | let owner = RuntimeOwnerReceipt { |
| 316 | version: 1, |
| 317 | data_dir: temp.path().to_owned(), |
| 318 | execution_scope: "fixture-owner".into(), |
| 319 | lease_generation: "fixture-generation".into(), |
| 320 | pid: std::process::id(), |
| 321 | process_start: "fixture".into(), |
| 322 | principal: "fixture".into(), |
| 323 | socket_path: temp.path().join("owner.sock"), |
| 324 | config_path: Some(config_path), |
| 325 | }; |
| 326 | state.captured_owner = Some(owner.clone()); |
| 327 | state.frontend_workspace = Some(temp.path().to_owned()); |
| 328 | let fake = FakeOwner { |
| 329 | record: Arc::new(Mutex::new( |
| 330 | json!({"id":"canonical-1","created_at":"2026-10-02T00:00:00Z", |
| 331 | "updated_at":"2026-10-02T00:00:01Z","model":"fixture-model","model_provider":"custom","model_provider_id":"fixture-account", |
| 332 | "workspace":temp.path(),"archived":false,"title":"named"}), |
| 333 | )), |
| 334 | calls: Arc::default(), |
| 335 | owner, |
| 336 | block_import, |
| 337 | import_seen: Arc::new(Notify::new()), |
| 338 | import_release: Arc::new(Notify::new()), |
| 339 | operations: Arc::default(), |
| 340 | fork_record: Arc::default(), |
| 341 | missing_after_commit: Arc::default(), |
| 342 | goal: Arc::default(), |
| 343 | turn_seq: Arc::default(), |
| 344 | pending_operation: Arc::default(), |
| 345 | recovery_prepared: Arc::default(), |
| 346 | recovery_refusal: Arc::default(), |
| 347 | document_digest: Arc::new(Mutex::new("b".repeat(64))), |
| 348 | }; |
| 349 | (state, temp, fake) |
| 350 | } |
| 351 | |
| 352 | async fn fixture( |
| 353 | block_import: bool, |
| 354 | ) -> ( |
| 355 | AppState, |
| 356 | tempfile::TempDir, |
| 357 | FakeOwner, |
| 358 | tokio::task::JoinHandle<()>, |
| 359 | ) { |
| 360 | let (mut state, temp, fake) = fixture_state(block_import); |
| 361 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 362 | let address = listener.local_addr().unwrap(); |
| 363 | let app = Router::new().fallback(owned_http).with_state(fake.clone()); |
| 364 | let server = tokio::spawn(async move { |
| 365 | axum::serve(listener, app).await.unwrap(); |
| 366 | }); |
| 367 | let mut bridge = RuntimeBridge::from_base_url_for_test(format!("http://{address}")); |
| 368 | bridge.auth_token = Some("private-compatibility-reload-fixture".into()); |
| 369 | *state.runtime_bridge.lock().await = Some(Arc::new(Mutex::new(bridge))); |
| 370 | crate::tests::install_mock_native_services(&mut state).await; |
| 371 | (state, temp, fake, server) |
| 372 | } |
| 373 | |
| 374 | pub(super) fn compatibility_router() -> (AppState, tempfile::TempDir, Router) { |
| 375 | let (state, temp, fake) = fixture_state(false); |
| 376 | ( |
| 377 | state, |
| 378 | temp, |
| 379 | Router::new().fallback(owned_http).with_state(fake), |
| 380 | ) |
| 381 | } |
| 382 | |
| 383 | pub(super) async fn compatibility_fixture() |
| 384 | -> (AppState, tempfile::TempDir, tokio::task::JoinHandle<()>) { |
| 385 | let (state, temp, _fake, server) = fixture(false).await; |
| 386 | (state, temp, server) |
| 387 | } |
| 388 | |
| 389 | async fn seed(state: &AppState, id: &str, workspace: &Path) -> StateStore { |
| 390 | seed_archive(state, id, workspace, Vec::new(), None).await |
| 391 | } |
| 392 | |
| 393 | async fn seed_archive( |
| 394 | state: &AppState, |
| 395 | id: &str, |
| 396 | workspace: &Path, |
| 397 | messages: Vec<codewhale_state::MessageRecord>, |
| 398 | goal: Option<codewhale_state::ThreadGoalRecord>, |
| 399 | ) -> StateStore { |
| 400 | let store = state.runtime.read().await.state_store().clone(); |
| 401 | let thread = codewhale_state::ThreadMetadata { |
| 402 | id: id.into(), |
| 403 | rollout_path: None, |
| 404 | preview: "legacy preview".into(), |
| 405 | ephemeral: false, |
| 406 | model_provider: "legacy-provider".into(), |
| 407 | created_at: 1, |
| 408 | updated_at: 1, |
| 409 | status: codewhale_state::ThreadStatus::Idle, |
| 410 | path: None, |
| 411 | cwd: workspace.to_owned(), |
| 412 | cli_version: "old".into(), |
| 413 | source: codewhale_state::SessionSource::Api, |
| 414 | name: Some("old name".into()), |
| 415 | sandbox_policy: None, |
| 416 | approval_mode: None, |
| 417 | archived: false, |
| 418 | archived_at: None, |
| 419 | git_sha: None, |
| 420 | git_branch: None, |
| 421 | git_origin_url: None, |
| 422 | memory_mode: None, |
| 423 | current_leaf_id: messages.last().map(|message| message.id), |
| 424 | }; |
| 425 | store |
| 426 | .restore_legacy_thread_archive(&codewhale_state::LegacyThreadArchive { |
| 427 | thread, |
| 428 | messages, |
| 429 | goal, |
| 430 | checkpoints: Vec::new(), |
| 431 | }) |
| 432 | .unwrap(); |
| 433 | store |
| 434 | } |
| 435 | |
| 436 | fn archive_message( |
| 437 | id: i64, |
| 438 | text: &str, |
| 439 | parent_entry_id: Option<i64>, |
| 440 | ) -> codewhale_state::MessageRecord { |
| 441 | codewhale_state::MessageRecord { |
| 442 | id, |
| 443 | thread_id: "legacy".into(), |
| 444 | role: "user".into(), |
| 445 | content: text.into(), |
| 446 | item: None, |
| 447 | created_at: 1, |
| 448 | parent_entry_id, |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | // Model an external historical writer only in test-owned SQLite. Production |
| 453 | // controls cannot append/replace history or mint bare links through State APIs. |
| 454 | fn seed_bare_link(store: &StateStore, thread: &str, runtime: &str) { |
| 455 | rusqlite::Connection::open(store.db_path()).unwrap().execute( |
| 456 | "INSERT INTO thread_runtime_links(thread_id,runtime_thread_id,created_at) VALUES(?1,?2,1)", |
| 457 | rusqlite::params![thread,runtime], |
| 458 | ).unwrap(); |
| 459 | } |
| 460 | |
| 461 | #[tokio::test] |
| 462 | async fn legacy_resolution_imports_all_branches_and_publishes_the_same_operation_once() { |
| 463 | let (state, temp, fake, server) = fixture(false).await; |
| 464 | let store = seed_archive( |
| 465 | &state, |
| 466 | "legacy", |
| 467 | temp.path(), |
| 468 | vec![ |
| 469 | archive_message(1, "root", None), |
| 470 | archive_message(2, "old branch", Some(1)), |
| 471 | archive_message(3, "new branch", Some(1)), |
| 472 | ], |
| 473 | None, |
| 474 | ) |
| 475 | .await; |
| 476 | let before = store.snapshot_legacy_thread_history("legacy").unwrap(); |
| 477 | let first = resolve(&state, "legacy", true).await.unwrap(); |
| 478 | let second = resolve(&state, "legacy", true).await.unwrap(); |
| 479 | assert_eq!(first, second); |
| 480 | let calls = fake.calls.lock().await; |
| 481 | let imports: Vec<_> = calls |
| 482 | .iter() |
| 483 | .filter(|(_, path, _)| path == "/v1/thread-history/import") |
| 484 | .collect(); |
| 485 | assert_eq!(imports.len(), 1); |
| 486 | assert_eq!( |
| 487 | imports[0].2["history"], |
| 488 | serde_json::to_value(&before).unwrap() |
| 489 | ); |
| 490 | assert_eq!(imports[0].2["target_runtime_thread_id"], Value::Null); |
| 491 | let receipt = store |
| 492 | .get_canonical_runtime_link("legacy", state.captured_owner.as_ref().unwrap()) |
| 493 | .unwrap() |
| 494 | .unwrap(); |
| 495 | assert_eq!(receipt.operation_key, migration_key(&before).unwrap()); |
| 496 | assert_eq!(receipt.runtime_thread_id, "canonical-1"); |
| 497 | server.abort(); |
| 498 | } |
| 499 | |
| 500 | #[tokio::test] |
| 501 | async fn existing_bare_link_adopts_exact_target_without_empty_creation() { |
| 502 | let (state, temp, fake, server) = fixture(false).await; |
| 503 | let store = seed_archive( |
| 504 | &state, |
| 505 | "legacy", |
| 506 | temp.path(), |
| 507 | vec![archive_message(1, "retained source", None)], |
| 508 | None, |
| 509 | ) |
| 510 | .await; |
| 511 | seed_bare_link(&store, "legacy", "canonical-1"); |
| 512 | resolve(&state, "legacy", true).await.unwrap(); |
| 513 | let calls = fake.calls.lock().await; |
| 514 | let import = calls |
| 515 | .iter() |
| 516 | .find(|(_, p, _)| p == "/v1/thread-history/import") |
| 517 | .unwrap(); |
| 518 | assert_eq!(import.2["target_runtime_thread_id"], "canonical-1"); |
| 519 | assert_eq!( |
| 520 | import.2["history"]["messages"][0]["content"], |
| 521 | "retained source" |
| 522 | ); |
| 523 | assert!( |
| 524 | !calls |
| 525 | .iter() |
| 526 | .any(|(m, p, _)| m == "POST" && p == "/v1/threads") |
| 527 | ); |
| 528 | server.abort(); |
| 529 | } |
| 530 | |
| 531 | #[tokio::test] |
| 532 | async fn cancelled_waiter_cannot_drop_committed_alias_publication() { |
| 533 | let (state, temp, fake, server) = fixture(true).await; |
| 534 | let store = seed(&state, "legacy", temp.path()).await; |
| 535 | let worker_state = state.clone(); |
| 536 | let waiter = tokio::spawn(async move { resolve(&worker_state, "legacy", true).await }); |
| 537 | fake.import_seen.notified().await; |
| 538 | waiter.abort(); |
| 539 | fake.import_release.notify_one(); |
| 540 | tokio::time::timeout(Duration::from_secs(5), async { |
| 541 | loop { |
| 542 | if store |
| 543 | .get_canonical_runtime_link("legacy", state.captured_owner.as_ref().unwrap()) |
| 544 | .unwrap() |
| 545 | .is_some() |
| 546 | { |
| 547 | break; |
| 548 | } |
| 549 | tokio::task::yield_now().await; |
| 550 | } |
| 551 | }) |
| 552 | .await |
| 553 | .unwrap(); |
| 554 | assert_eq!( |
| 555 | store.get_runtime_thread_link("legacy").unwrap().as_deref(), |
| 556 | Some("canonical-1") |
| 557 | ); |
| 558 | server.abort(); |
| 559 | } |
| 560 | |
| 561 | #[tokio::test] |
| 562 | async fn source_graph_change_during_import_refuses_publication_and_preserves_both_histories() { |
| 563 | let (state, temp, fake, server) = fixture(true).await; |
| 564 | let store = seed_archive( |
| 565 | &state, |
| 566 | "legacy", |
| 567 | temp.path(), |
| 568 | vec![archive_message(1, "first", None)], |
| 569 | None, |
| 570 | ) |
| 571 | .await; |
| 572 | let worker_state = state.clone(); |
| 573 | let waiter = tokio::spawn(async move { resolve(&worker_state, "legacy", true).await }); |
| 574 | fake.import_seen.notified().await; |
| 575 | let mut foreign = rusqlite::Connection::open(store.db_path()).unwrap(); |
| 576 | let transaction = foreign |
| 577 | .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate) |
| 578 | .unwrap(); |
| 579 | transaction.execute("INSERT INTO messages(id,thread_id,role,content,item_json,created_at,parent_entry_id) VALUES(2,'legacy','user','changed while waiting',NULL,1,1)", []).unwrap(); |
| 580 | transaction |
| 581 | .execute("UPDATE threads SET current_leaf_id=2 WHERE id='legacy'", []) |
| 582 | .unwrap(); |
| 583 | transaction.commit().unwrap(); |
| 584 | fake.import_release.notify_one(); |
| 585 | let error = waiter.await.unwrap().unwrap_err(); |
| 586 | assert!(format!("{error:#}").contains("legacy history changed")); |
| 587 | assert!( |
| 588 | store |
| 589 | .get_canonical_runtime_link("legacy", state.captured_owner.as_ref().unwrap()) |
| 590 | .unwrap() |
| 591 | .is_none() |
| 592 | ); |
| 593 | assert_eq!( |
| 594 | store |
| 595 | .snapshot_legacy_thread_history("legacy") |
| 596 | .unwrap() |
| 597 | .messages |
| 598 | .len(), |
| 599 | 2 |
| 600 | ); |
| 601 | assert_eq!(fake.record.lock().await["id"], "canonical-1"); |
| 602 | server.abort(); |
| 603 | } |
| 604 | |
| 605 | #[tokio::test] |
| 606 | async fn list_is_global_read_only_union_and_bound_alias_dedupes_actual_metadata() { |
| 607 | let (state, temp, fake, server) = fixture(false).await; |
| 608 | let store = seed(&state, "legacy", temp.path()).await; |
| 609 | resolve(&state, "legacy", true).await.unwrap(); |
| 610 | let other = temp.path().join("other-workspace"); |
| 611 | seed(&state, "other-legacy", &other).await; |
| 612 | fake.record.lock().await["title"] = json!("canonical title"); |
| 613 | let before = |
| 614 | serde_json::to_value(store.snapshot_legacy_thread_history("legacy").unwrap()).unwrap(); |
| 615 | let result = handle( |
| 616 | &state, |
| 617 | ThreadRequest::List(codewhale_protocol::ThreadListParams { |
| 618 | include_archived: false, |
| 619 | limit: None, |
| 620 | }), |
| 621 | ) |
| 622 | .await |
| 623 | .unwrap(); |
| 624 | assert_eq!(result.threads.len(), 2); |
| 625 | assert!( |
| 626 | result |
| 627 | .threads |
| 628 | .iter() |
| 629 | .any(|t| t.id == "other-legacy" && t.cwd == other) |
| 630 | ); |
| 631 | let alias = result.threads.iter().find(|t| t.id == "legacy").unwrap(); |
| 632 | assert_eq!(alias.name.as_deref(), Some("canonical title")); |
| 633 | assert!(!result.threads.iter().any(|t| t.id == "canonical-1")); |
| 634 | assert_eq!( |
| 635 | serde_json::to_value(store.snapshot_legacy_thread_history("legacy").unwrap()).unwrap(), |
| 636 | before |
| 637 | ); |
| 638 | assert_eq!( |
| 639 | fake.calls |
| 640 | .lock() |
| 641 | .await |
| 642 | .iter() |
| 643 | .filter(|(_, p, _)| p == "/v1/thread-history/import") |
| 644 | .count(), |
| 645 | 1 |
| 646 | ); |
| 647 | server.abort(); |
| 648 | } |
| 649 | |
| 650 | #[tokio::test] |
| 651 | async fn canonical_title_clear_and_archive_filter_ignore_stale_sqlite_names() { |
| 652 | let (state, temp, fake, server) = fixture(false).await; |
| 653 | let store = seed(&state, "legacy", temp.path()).await; |
| 654 | resolve(&state, "legacy", true).await.unwrap(); |
| 655 | let clear = handle( |
| 656 | &state, |
| 657 | ThreadRequest::SetName(codewhale_protocol::ThreadSetNameParams { |
| 658 | thread_id: "legacy".into(), |
| 659 | name: String::new(), |
| 660 | }), |
| 661 | ) |
| 662 | .await |
| 663 | .unwrap(); |
| 664 | assert!(clear.thread.unwrap().name.is_none()); |
| 665 | assert_eq!(fake.record.lock().await["title"], Value::Null); |
| 666 | assert_eq!( |
| 667 | store.get_thread("legacy").unwrap().unwrap().name.as_deref(), |
| 668 | Some("old name") |
| 669 | ); |
| 670 | handle( |
| 671 | &state, |
| 672 | ThreadRequest::Archive { |
| 673 | thread_id: "legacy".into(), |
| 674 | }, |
| 675 | ) |
| 676 | .await |
| 677 | .unwrap(); |
| 678 | let active = list( |
| 679 | &state, |
| 680 | codewhale_protocol::ThreadListParams { |
| 681 | include_archived: false, |
| 682 | limit: None, |
| 683 | }, |
| 684 | ) |
| 685 | .await |
| 686 | .unwrap(); |
| 687 | assert!(active.threads.is_empty()); |
| 688 | let all = list( |
| 689 | &state, |
| 690 | codewhale_protocol::ThreadListParams { |
| 691 | include_archived: true, |
| 692 | limit: None, |
| 693 | }, |
| 694 | ) |
| 695 | .await |
| 696 | .unwrap(); |
| 697 | assert_eq!(all.threads.len(), 1); |
| 698 | assert_eq!(all.threads[0].status, ThreadStatus::Archived); |
| 699 | server.abort(); |
| 700 | } |
| 701 | |
| 702 | #[tokio::test] |
| 703 | async fn read_returns_full_journal_including_inactive_branch() { |
| 704 | let (state, _temp, _fake, server) = fixture(false).await; |
| 705 | let value = handle( |
| 706 | &state, |
| 707 | ThreadRequest::Read(codewhale_protocol::ThreadReadParams { |
| 708 | thread_id: "canonical-1".into(), |
| 709 | }), |
| 710 | ) |
| 711 | .await |
| 712 | .unwrap(); |
| 713 | assert_eq!( |
| 714 | value.data["history"]["session"]["journal"]["entries"] |
| 715 | .as_array() |
| 716 | .unwrap() |
| 717 | .len(), |
| 718 | 3 |
| 719 | ); |
| 720 | assert_eq!( |
| 721 | value.data["history"]["session"]["journal"]["entries"][1]["id"], |
| 722 | "inactive-branch" |
| 723 | ); |
| 724 | server.abort(); |
| 725 | } |
| 726 | |
| 727 | #[tokio::test] |
| 728 | async fn unknown_canonical_target_never_creates_or_changes_an_alias() { |
| 729 | let (state, _temp, fake, server) = fixture(false).await; |
| 730 | let error = resolve(&state, "missing", true).await.unwrap_err(); |
| 731 | assert!(format!("{error:#}").contains("no replacement thread")); |
| 732 | assert!(state.runtime_thread_map.lock().await.is_empty()); |
| 733 | assert!(!fake.calls.lock().await.iter().any(|(m, _, _)| m == "POST")); |
| 734 | server.abort(); |
| 735 | } |
| 736 | |
| 737 | #[tokio::test] |
| 738 | async fn unreceipted_goal_deltas_and_unqualified_controls_are_refused_before_io() { |
| 739 | let (state, _temp, fake, server) = fixture(false).await; |
| 740 | for request in [ |
| 741 | ThreadRequest::GoalRecordProgress(codewhale_protocol::ThreadGoalProgressParams { |
| 742 | thread_id: "canonical-1".into(), |
| 743 | token_delta: 1, |
| 744 | time_delta_seconds: 1, |
| 745 | record_continuation: true, |
| 746 | }), |
| 747 | ThreadRequest::Create { |
| 748 | metadata: Value::Null, |
| 749 | }, |
| 750 | ] { |
| 751 | assert!(handle(&state, request).await.is_err()); |
| 752 | } |
| 753 | assert!(fake.calls.lock().await.is_empty()); |
| 754 | server.abort(); |
| 755 | } |
| 756 | |
| 757 | #[tokio::test] |
| 758 | async fn keyed_start_carries_exact_captured_config_and_never_opens_a_legacy_writer() { |
| 759 | let (state, temp, fake, server) = fixture(false).await; |
| 760 | let request: ThreadRequest = serde_json::from_value(json!({"kind":"start", |
| 761 | "operation_key":"start-intent","model":"fixture-model", |
| 762 | "model_provider":"fixture-account","cwd":temp.path(),"persist_extended_history":true})) |
| 763 | .unwrap(); |
| 764 | let result = handle(&state, request).await.unwrap(); |
| 765 | assert_eq!(result.status, "started"); |
| 766 | assert_eq!(result.thread_id, "canonical-1"); |
| 767 | assert_eq!(result.data["receipt"]["operation_key"], "start-intent"); |
| 768 | let operations = fake.operations.lock().await; |
| 769 | assert_eq!(operations.len(), 1); |
| 770 | let (body, _) = operations.get("start-intent").unwrap(); |
| 771 | assert_eq!( |
| 772 | body["mutation"]["config"], |
| 773 | json!({"workspace":temp.path(), |
| 774 | "model":"fixture-model","model_provider":"fixture-account"}) |
| 775 | ); |
| 776 | assert_eq!(body["expected_data_dir"], json!(fake.owner.data_dir)); |
| 777 | assert_eq!(body["expected_execution_scope"], fake.owner.execution_scope); |
| 778 | let store = state.runtime.read().await.state_store().clone(); |
| 779 | assert!( |
| 780 | store |
| 781 | .list_threads(codewhale_state::ThreadListFilters { |
| 782 | include_archived: true, |
| 783 | limit: None |
| 784 | }) |
| 785 | .unwrap() |
| 786 | .is_empty() |
| 787 | ); |
| 788 | server.abort(); |
| 789 | } |
| 790 | |
| 791 | #[tokio::test] |
| 792 | async fn create_retry_keeps_exact_client_intent_and_returns_same_owner_receipt() { |
| 793 | let (state, temp, fake, server) = fixture(false).await; |
| 794 | let request = ThreadRequest::Create { |
| 795 | metadata: json!({"operation_key":"create-intent", |
| 796 | "workspace":temp.path(),"model":"fixture-model","allowed_tools":[],"allow_shell":false}), |
| 797 | }; |
| 798 | let first = handle(&state, request.clone()).await.unwrap(); |
| 799 | let second = handle(&state, request).await.unwrap(); |
| 800 | assert_eq!(first.thread_id, second.thread_id); |
| 801 | assert_eq!(first.data["receipt"], second.data["receipt"]); |
| 802 | assert_eq!(fake.operations.lock().await.len(), 1); |
| 803 | let calls = fake.calls.lock().await; |
| 804 | let requests: Vec<_> = calls |
| 805 | .iter() |
| 806 | .filter(|(_, path, _)| path == "/v1/thread-history/mutate") |
| 807 | .map(|(_, _, body)| body) |
| 808 | .collect(); |
| 809 | assert_eq!(requests.len(), 1); |
| 810 | assert_eq!( |
| 811 | calls |
| 812 | .iter() |
| 813 | .filter(|(_, path, _)| path.ends_with("/operations/lookup")) |
| 814 | .count(), |
| 815 | 2 |
| 816 | ); |
| 817 | assert!( |
| 818 | requests[0]["mutation"]["config"] |
| 819 | .get("operation_key") |
| 820 | .is_none() |
| 821 | ); |
| 822 | server.abort(); |
| 823 | } |
| 824 | |
| 825 | #[tokio::test] |
| 826 | async fn creation_without_acknowledged_scope_or_stable_key_refuses_before_io() { |
| 827 | let (mut state, temp, fake, server) = fixture(false).await; |
| 828 | for input in [ |
| 829 | json!({"kind":"start"}), |
| 830 | json!({"kind":"create","metadata":{"operation_key":"wrong-scope","workspace":temp.path().join("other")}}), |
| 831 | ] { |
| 832 | assert!( |
| 833 | handle(&state, serde_json::from_value(input).unwrap()) |
| 834 | .await |
| 835 | .is_err() |
| 836 | ); |
| 837 | } |
| 838 | state.frontend_workspace = None; |
| 839 | let request = |
| 840 | serde_json::from_value(json!({"kind":"start","operation_key":"no-default"})).unwrap(); |
| 841 | assert!( |
| 842 | handle(&state, request) |
| 843 | .await |
| 844 | .unwrap_err() |
| 845 | .wire |
| 846 | .message |
| 847 | .contains("acknowledged workspace") |
| 848 | ); |
| 849 | assert!(fake.calls.lock().await.is_empty()); |
| 850 | server.abort(); |
| 851 | } |
| 852 | |
| 853 | #[tokio::test] |
| 854 | async fn ordinary_resume_binds_full_document_digest_and_preserves_public_alias() { |
| 855 | let (state, temp, fake, server) = fixture(false).await; |
| 856 | let store = seed(&state, "legacy", temp.path()).await; |
| 857 | resolve(&state, "legacy", true).await.unwrap(); |
| 858 | let before = store.snapshot_legacy_thread_history("legacy").unwrap(); |
| 859 | let request = serde_json::from_value(json!({"kind":"resume","thread_id":"legacy", |
| 860 | "operation_key":"resume-intent","persist_extended_history":true})) |
| 861 | .unwrap(); |
| 862 | let result = handle(&state, request).await.unwrap(); |
| 863 | assert_eq!(result.thread_id, "legacy"); |
| 864 | assert_eq!(result.status, "resumed"); |
| 865 | let operations = fake.operations.lock().await; |
| 866 | assert_eq!( |
| 867 | operations["resume-intent"].0["mutation"]["source"], |
| 868 | json!({"kind":"thread", |
| 869 | "runtime_thread_id":"canonical-1","expected_document_digest":"b".repeat(64)}) |
| 870 | ); |
| 871 | assert_eq!( |
| 872 | serde_json::to_value(store.snapshot_legacy_thread_history("legacy").unwrap()).unwrap(), |
| 873 | serde_json::to_value(before).unwrap() |
| 874 | ); |
| 875 | server.abort(); |
| 876 | } |
| 877 | |
| 878 | #[tokio::test] |
| 879 | async fn ordinary_fork_returns_canonical_identity_and_preserves_original_branches() { |
| 880 | let (state, temp, fake, server) = fixture(false).await; |
| 881 | let store = seed(&state, "legacy", temp.path()).await; |
| 882 | resolve(&state, "legacy", true).await.unwrap(); |
| 883 | let before = store.snapshot_legacy_thread_history("legacy").unwrap(); |
| 884 | let request = serde_json::from_value(json!({"kind":"fork","thread_id":"legacy", |
| 885 | "operation_key":"fork-intent"})) |
| 886 | .unwrap(); |
| 887 | let result = handle(&state, request).await.unwrap(); |
| 888 | assert_eq!(result.thread_id, "canonical-fork"); |
| 889 | assert_eq!(result.status, "forked"); |
| 890 | assert_eq!(result.data["receipt"]["session_id"], "session-fork"); |
| 891 | assert_eq!(fake.record.lock().await["id"], "canonical-1"); |
| 892 | assert_eq!( |
| 893 | store.get_runtime_thread_link("legacy").unwrap().as_deref(), |
| 894 | Some("canonical-1") |
| 895 | ); |
| 896 | assert_eq!( |
| 897 | serde_json::to_value(store.snapshot_legacy_thread_history("legacy").unwrap()).unwrap(), |
| 898 | serde_json::to_value(before).unwrap() |
| 899 | ); |
| 900 | server.abort(); |
| 901 | } |
| 902 | |
| 903 | #[tokio::test] |
| 904 | async fn confirmed_mutation_metadata_404_keeps_completed_effect_and_retry_identity() { |
| 905 | let (state, _temp, fake, server) = fixture(false).await; |
| 906 | fake.missing_after_commit |
| 907 | .store(true, std::sync::atomic::Ordering::SeqCst); |
| 908 | let request = |
| 909 | serde_json::from_value(json!({"kind":"start","operation_key":"completed-intent"})).unwrap(); |
| 910 | let error = handle(&state, request).await.unwrap_err(); |
| 911 | assert_eq!(fake.operations.lock().await.len(), 1); |
| 912 | assert!(error.wire.message.contains("completed-intent")); |
| 913 | assert!( |
| 914 | error |
| 915 | .wire |
| 916 | .message |
| 917 | .contains("completed as thread canonical-1 / session session-1") |
| 918 | ); |
| 919 | assert!(error.wire.message.contains("without replay")); |
| 920 | assert_ne!( |
| 921 | error.wire.code, |
| 922 | DispatchError::thread_not_found("canonical-1").wire.code |
| 923 | ); |
| 924 | server.abort(); |
| 925 | } |
| 926 | |
| 927 | #[tokio::test] |
| 928 | async fn encoded_oversize_creation_refuses_before_owner_effect() { |
| 929 | let (state, _temp, fake, server) = fixture(false).await; |
| 930 | let request = ThreadRequest::Create { |
| 931 | metadata: json!({"operation_key":"oversize-intent", |
| 932 | "system_prompt":"x".repeat(MAX_CANONICAL_HISTORY_BYTES)}), |
| 933 | }; |
| 934 | let error = handle(&state, request).await.unwrap_err(); |
| 935 | assert!( |
| 936 | error |
| 937 | .wire |
| 938 | .message |
| 939 | .contains("encoded canonical control exceeds bound") |
| 940 | ); |
| 941 | assert!(fake.operations.lock().await.is_empty()); |
| 942 | assert!( |
| 943 | fake.calls |
| 944 | .lock() |
| 945 | .await |
| 946 | .iter() |
| 947 | .all(|(_, path, _)| path.ends_with("/operations/lookup")) |
| 948 | ); |
| 949 | server.abort(); |
| 950 | } |
| 951 | |
| 952 | #[tokio::test] |
| 953 | async fn declared_oversize_response_refuses_complete_document_without_truncation() { |
| 954 | crate::install_test_crypto_provider(); |
| 955 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 956 | let address = listener.local_addr().unwrap(); |
| 957 | let app = Router::new().route( |
| 958 | "/large", |
| 959 | get(|| async { |
| 960 | ( |
| 961 | [(header::CONTENT_TYPE, "application/json")], |
| 962 | format!("\"{}\"", "x".repeat(MAX_CANONICAL_HISTORY_BYTES)), |
| 963 | ) |
| 964 | }), |
| 965 | ); |
| 966 | let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); |
| 967 | let response = reqwest::get(format!("http://{address}/large")) |
| 968 | .await |
| 969 | .unwrap(); |
| 970 | let error = read_json_response(response).await.unwrap_err(); |
| 971 | assert!(format!("{error:#}").contains("complete-document bound")); |
| 972 | server.abort(); |
| 973 | } |
| 974 | |
| 975 | #[tokio::test] |
| 976 | async fn http_and_stdio_dispatch_share_the_same_full_history_owner() { |
| 977 | let (state, _temp, fake, server) = fixture(false).await; |
| 978 | for (method, params) in [ |
| 979 | ("thread/list", json!({"cwd":"/another-workspace"})), |
| 980 | ("thread/list", json!({"cursor":"unsupported"})), |
| 981 | ("thread/list", json!({"archived":true})), |
| 982 | ( |
| 983 | "thread/read", |
| 984 | json!({"thread_id":"canonical-1","includeTurns":false}), |
| 985 | ), |
| 986 | ( |
| 987 | "thread/request", |
| 988 | json!({"kind":"list","cwd":"/another-workspace"}), |
| 989 | ), |
| 990 | ( |
| 991 | "thread/request", |
| 992 | json!({"kind":"read","thread_id":"canonical-1","includeTurns":false}), |
| 993 | ), |
| 994 | ] { |
| 995 | let error = dispatch_stdio_request(&state, method, params) |
| 996 | .await |
| 997 | .unwrap_err(); |
| 998 | assert_eq!(error.wire.code, -32602); |
| 999 | assert!(error.wire.message.contains("unknown field")); |
| 1000 | assert!(fake.calls.lock().await.is_empty()); |
| 1001 | } |
| 1002 | let request = ThreadRequest::Read(codewhale_protocol::ThreadReadParams { |
| 1003 | thread_id: "canonical-1".into(), |
| 1004 | }); |
| 1005 | let http = thread_handler(State(state.clone()), Json(request.clone())).await; |
| 1006 | assert_eq!(http.status(), StatusCode::OK); |
| 1007 | let bytes = axum::body::to_bytes(http.into_body(), MAX_CANONICAL_HISTORY_BYTES) |
| 1008 | .await |
| 1009 | .unwrap(); |
| 1010 | let http: ThreadResponse = serde_json::from_slice(&bytes).unwrap(); |
| 1011 | let stdio = dispatch_stdio_request( |
| 1012 | &state, |
| 1013 | "thread/request", |
| 1014 | serde_json::to_value(request).unwrap(), |
| 1015 | ) |
| 1016 | .await |
| 1017 | .unwrap(); |
| 1018 | let stdio: ThreadResponse = serde_json::from_value(stdio.result).unwrap(); |
| 1019 | assert_eq!(http.data["history"], stdio.data["history"]); |
| 1020 | assert_eq!( |
| 1021 | fake.calls |
| 1022 | .lock() |
| 1023 | .await |
| 1024 | .iter() |
| 1025 | .filter(|(_, path, _)| path.ends_with("/history")) |
| 1026 | .count(), |
| 1027 | 2 |
| 1028 | ); |
| 1029 | server.abort(); |
| 1030 | } |
| 1031 | |
| 1032 | #[tokio::test] |
| 1033 | async fn completed_resume_retry_reads_original_operation_before_changed_history() { |
| 1034 | let (state, _temp, fake, server) = fixture(false).await; |
| 1035 | let request: ThreadRequest = |
| 1036 | serde_json::from_value(json!({"kind":"resume","thread_id":"canonical-1", |
| 1037 | "operation_key":"resume-recovery"})) |
| 1038 | .unwrap(); |
| 1039 | let first = handle(&state, request.clone()).await.unwrap(); |
| 1040 | *fake.document_digest.lock().await = "c".repeat(64); |
| 1041 | let count = fake.calls.lock().await.len(); |
| 1042 | let second = handle(&state, request).await.unwrap(); |
| 1043 | assert_eq!(first.data["receipt"], second.data["receipt"]); |
| 1044 | let calls = fake.calls.lock().await; |
| 1045 | assert!( |
| 1046 | calls[count..] |
| 1047 | .iter() |
| 1048 | .all(|(_, path, _)| path.ends_with("/operations/lookup") |
| 1049 | || path == "/v1/threads/canonical-1") |
| 1050 | ); |
| 1051 | assert_eq!( |
| 1052 | calls |
| 1053 | .iter() |
| 1054 | .filter(|(_, path, _)| path == "/v1/thread-history/mutate") |
| 1055 | .count(), |
| 1056 | 1 |
| 1057 | ); |
| 1058 | server.abort(); |
| 1059 | } |
| 1060 | |
| 1061 | #[tokio::test] |
| 1062 | async fn pending_retained_operation_never_reconstructs_or_replays_source() { |
| 1063 | let (state, _temp, fake, server) = fixture(false).await; |
| 1064 | let request: ThreadRequest = |
| 1065 | serde_json::from_value(json!({"kind":"resume","thread_id":"canonical-1", |
| 1066 | "operation_key":"pending-recovery"})) |
| 1067 | .unwrap(); |
| 1068 | handle(&state, request.clone()).await.unwrap(); |
| 1069 | fake.pending_operation |
| 1070 | .store(true, std::sync::atomic::Ordering::SeqCst); |
| 1071 | let count = fake.calls.lock().await.len(); |
| 1072 | let error = handle(&state, request).await.unwrap_err(); |
| 1073 | assert!( |
| 1074 | error.wire.message.contains("pending-recovery") |
| 1075 | && error.wire.message.contains("pending") |
| 1076 | && error |
| 1077 | .wire |
| 1078 | .message |
| 1079 | .contains("no resume, replay or replacement") |
| 1080 | ); |
| 1081 | let calls = fake.calls.lock().await; |
| 1082 | assert_eq!(calls.len(), count + 2); |
| 1083 | assert!(calls[count].1.ends_with("/operations/lookup")); |
| 1084 | assert!(calls[count + 1].1.ends_with("/operations/recover")); |
| 1085 | assert_eq!(calls[count + 1].2["operation"], calls[count].2); |
| 1086 | assert!( |
| 1087 | calls[count..] |
| 1088 | .iter() |
| 1089 | .all(|(_, path, _)| !path.ends_with("/history") && !path.ends_with("/mutate")) |
| 1090 | ); |
| 1091 | server.abort(); |
| 1092 | } |
| 1093 | |
| 1094 | #[tokio::test] |
| 1095 | async fn prepared_pending_resume_settles_reserved_receipt_without_reconstructing_source() { |
| 1096 | let (state, _temp, fake, server) = fixture(false).await; |
| 1097 | let request: ThreadRequest = |
| 1098 | serde_json::from_value(json!({"kind":"resume","thread_id":"canonical-1", |
| 1099 | "operation_key":"prepared-recovery"})) |
| 1100 | .unwrap(); |
| 1101 | let first = handle(&state, request.clone()).await.unwrap(); |
| 1102 | fake.pending_operation |
| 1103 | .store(true, std::sync::atomic::Ordering::SeqCst); |
| 1104 | fake.recovery_prepared |
| 1105 | .store(true, std::sync::atomic::Ordering::SeqCst); |
| 1106 | *fake.document_digest.lock().await = "c".repeat(64); |
| 1107 | let count = fake.calls.lock().await.len(); |
| 1108 | let second = handle(&state, request.clone()).await.unwrap(); |
| 1109 | assert_eq!(first.data["receipt"], second.data["receipt"]); |
| 1110 | let calls = fake.calls.lock().await; |
| 1111 | assert_eq!(calls[count].1, "/v1/thread-history/operations/lookup"); |
| 1112 | assert_eq!(calls[count + 1].1, "/v1/thread-history/operations/recover"); |
| 1113 | assert_eq!( |
| 1114 | calls[count + 1].2["association"]["source_runtime_thread_id"], |
| 1115 | "canonical-1" |
| 1116 | ); |
| 1117 | assert!( |
| 1118 | calls[count..] |
| 1119 | .iter() |
| 1120 | .all(|(_, path, _)| !path.ends_with("/history") && !path.ends_with("/mutate")) |
| 1121 | ); |
| 1122 | drop(calls); |
| 1123 | let again = handle(&state, request).await.unwrap(); |
| 1124 | assert_eq!(again.data["receipt"], first.data["receipt"]); |
| 1125 | assert_eq!( |
| 1126 | fake.calls |
| 1127 | .lock() |
| 1128 | .await |
| 1129 | .iter() |
| 1130 | .filter(|(_, path, _)| path.ends_with("/recover")) |
| 1131 | .count(), |
| 1132 | 1 |
| 1133 | ); |
| 1134 | server.abort(); |
| 1135 | } |
| 1136 | |
| 1137 | #[tokio::test] |
| 1138 | async fn pending_wrong_action_refuses_before_any_prepared_recovery() { |
| 1139 | let (state, _temp, fake, server) = fixture(false).await; |
| 1140 | let create = |
| 1141 | serde_json::from_value(json!({"kind":"start","operation_key":"wrong-pending-action"})) |
| 1142 | .unwrap(); |
| 1143 | handle(&state, create).await.unwrap(); |
| 1144 | fake.pending_operation |
| 1145 | .store(true, std::sync::atomic::Ordering::SeqCst); |
| 1146 | fake.recovery_prepared |
| 1147 | .store(true, std::sync::atomic::Ordering::SeqCst); |
| 1148 | let count = fake.calls.lock().await.len(); |
| 1149 | let request = serde_json::from_value( |
| 1150 | json!({"kind":"fork","thread_id":"canonical-1","operation_key":"wrong-pending-action"}), |
| 1151 | ) |
| 1152 | .unwrap(); |
| 1153 | let error = handle(&state, request).await.unwrap_err(); |
| 1154 | assert!( |
| 1155 | error.wire.message.contains("another action or source") |
| 1156 | && error.wire.message.contains("wrong-pending-action") |
| 1157 | ); |
| 1158 | let calls = fake.calls.lock().await; |
| 1159 | assert_eq!(calls.len(), count + 1); |
| 1160 | assert!(calls[count].1.ends_with("/lookup")); |
| 1161 | assert!( |
| 1162 | fake.pending_operation |
| 1163 | .load(std::sync::atomic::Ordering::SeqCst) |
| 1164 | ); |
| 1165 | server.abort(); |
| 1166 | } |
| 1167 | |
| 1168 | #[tokio::test] |
| 1169 | async fn changed_prepared_target_refusal_keeps_reserved_operation_and_no_replay() { |
| 1170 | let (state, _temp, fake, server) = fixture(false).await; |
| 1171 | let request: ThreadRequest = |
| 1172 | serde_json::from_value(json!({"kind":"resume","thread_id":"canonical-1", |
| 1173 | "operation_key":"changed-prepared-target"})) |
| 1174 | .unwrap(); |
| 1175 | handle(&state, request.clone()).await.unwrap(); |
| 1176 | fake.pending_operation |
| 1177 | .store(true, std::sync::atomic::Ordering::SeqCst); |
| 1178 | fake.recovery_refusal |
| 1179 | .store(true, std::sync::atomic::Ordering::SeqCst); |
| 1180 | let count = fake.calls.lock().await.len(); |
| 1181 | let error = handle(&state, request).await.unwrap_err(); |
| 1182 | assert!( |
| 1183 | error.wire.message.contains("changed-prepared-target") |
| 1184 | && error |
| 1185 | .wire |
| 1186 | .message |
| 1187 | .contains("canonical-1 / session session-1") |
| 1188 | && error.wire.message.contains("prepared target graph changed") |
| 1189 | ); |
| 1190 | let calls = fake.calls.lock().await; |
| 1191 | assert_eq!(calls.len(), count + 2); |
| 1192 | assert!( |
| 1193 | calls[count..] |
| 1194 | .iter() |
| 1195 | .all(|(_, path, _)| path.ends_with("/lookup") || path.ends_with("/recover")) |
| 1196 | ); |
| 1197 | assert_eq!(fake.operations.lock().await.len(), 1); |
| 1198 | server.abort(); |
| 1199 | } |
| 1200 | |
| 1201 | #[tokio::test] |
| 1202 | async fn retained_operation_rejects_another_action_or_source_with_completed_facts() { |
| 1203 | let (state, _temp, fake, server) = fixture(false).await; |
| 1204 | let create: ThreadRequest = |
| 1205 | serde_json::from_value(json!({"kind":"start","operation_key":"action-bound"})).unwrap(); |
| 1206 | handle(&state, create).await.unwrap(); |
| 1207 | let request = serde_json::from_value(json!({"kind":"fork","thread_id":"canonical-1", |
| 1208 | "operation_key":"action-bound"})) |
| 1209 | .unwrap(); |
| 1210 | let error = handle(&state, request).await.unwrap_err(); |
| 1211 | assert!( |
| 1212 | error |
| 1213 | .wire |
| 1214 | .message |
| 1215 | .contains("completed as thread canonical-1 / session session-1") |
| 1216 | ); |
| 1217 | assert!(error.wire.message.contains("another action or source")); |
| 1218 | assert_eq!(fake.operations.lock().await.len(), 1); |
| 1219 | server.abort(); |
| 1220 | } |
| 1221 | |
| 1222 | #[tokio::test] |
| 1223 | async fn resume_options_are_forwarded_exactly_to_the_owning_decoder() { |
| 1224 | let (state, temp, fake, server) = fixture(false).await; |
| 1225 | let history = json!([{"role":"user","content":"offered"}]); |
| 1226 | let config = json!({"allow_shell":false,"mode":"ask","system_prompt":"captured override"}); |
| 1227 | let source_path = temp.path().join("sessions/session-1.json"); |
| 1228 | let request = serde_json::from_value(json!({"kind":"resume","thread_id":"canonical-1", |
| 1229 | "operation_key":"options-intent","history":history,"path":source_path, |
| 1230 | "model":"fixture-model","model_provider":"fixture-account","cwd":temp.path(), |
| 1231 | "approval_policy":"on-request","sandbox":"captured-ceiling","config":config, |
| 1232 | "base_instructions":"base","developer_instructions":"developer","personality":"brief", |
| 1233 | "persist_extended_history":false})) |
| 1234 | .unwrap(); |
| 1235 | handle(&state, request).await.unwrap(); |
| 1236 | let operations = fake.operations.lock().await; |
| 1237 | let options = &operations["options-intent"].0["mutation"]["options"]; |
| 1238 | assert_eq!(options["offered_history"], history); |
| 1239 | assert_eq!(options["source_path"], json!(source_path)); |
| 1240 | assert!(options.get("expected_session_goal_digest").is_none()); |
| 1241 | assert_eq!( |
| 1242 | options["overrides"], |
| 1243 | json!({"model":"fixture-model","model_provider":"fixture-account", |
| 1244 | "cwd":temp.path(),"approval_policy":"on-request","sandbox":"captured-ceiling","config":config, |
| 1245 | "base_instructions":"base","developer_instructions":"developer","personality":"brief"}) |
| 1246 | ); |
| 1247 | server.abort(); |
| 1248 | } |
| 1249 | |
| 1250 | #[tokio::test] |
| 1251 | async fn fork_reads_other_workspace_source_but_uses_acknowledged_target_scope() { |
| 1252 | let (state, temp, fake, server) = fixture(false).await; |
| 1253 | let original = temp.path().join("original"); |
| 1254 | fake.record.lock().await["workspace"] = json!(original); |
| 1255 | let request = serde_json::from_value(json!({"kind":"fork","thread_id":"canonical-1", |
| 1256 | "operation_key":"cross-workspace-fork","cwd":temp.path()})) |
| 1257 | .unwrap(); |
| 1258 | let response = handle(&state, request).await.unwrap(); |
| 1259 | assert_eq!(response.cwd.as_deref(), Some(temp.path())); |
| 1260 | assert_eq!( |
| 1261 | fake.operations.lock().await["cross-workspace-fork"].0["workspace"], |
| 1262 | json!(temp.path()) |
| 1263 | ); |
| 1264 | assert_eq!(fake.record.lock().await["workspace"], json!(original)); |
| 1265 | let request = serde_json::from_value(json!({"kind":"resume","thread_id":"canonical-1", |
| 1266 | "operation_key":"cross-workspace-resume","cwd":temp.path()})) |
| 1267 | .unwrap(); |
| 1268 | assert!(handle(&state, request).await.is_err()); |
| 1269 | assert_eq!(fake.operations.lock().await.len(), 1); |
| 1270 | server.abort(); |
| 1271 | } |
| 1272 | |
| 1273 | #[tokio::test] |
| 1274 | async fn bridged_turn_sends_the_observed_owner_workspace_as_final_narrowing() { |
| 1275 | let (state, temp, fake, server) = fixture(false).await; |
| 1276 | run_http_thread_message( |
| 1277 | &state, |
| 1278 | "canonical-1".into(), |
| 1279 | "hello".into(), |
| 1280 | Some(Vec::new()), |
| 1281 | Vec::new(), |
| 1282 | None, |
| 1283 | ) |
| 1284 | .await |
| 1285 | .unwrap(); |
| 1286 | let calls = fake.calls.lock().await; |
| 1287 | let turn = calls |
| 1288 | .iter() |
| 1289 | .find(|(_, path, _)| path.ends_with("/turns")) |
| 1290 | .unwrap(); |
| 1291 | assert_eq!(turn.2["expected_workspace"], json!(temp.path())); |
| 1292 | server.abort(); |
| 1293 | } |
| 1294 | |
| 1295 | fn legacy_goal_record(status: &str, objective: &str) -> codewhale_state::ThreadGoalRecord { |
| 1296 | serde_json::from_value( |
| 1297 | json!({"thread_id":"legacy","goal_id":"old-goal","objective":objective, |
| 1298 | "status":status,"token_budget":1000,"tokens_used":137,"time_used_seconds":23, |
| 1299 | "continuation_count":2,"created_at":1,"updated_at":2,"repeated_gap_count":0}), |
| 1300 | ) |
| 1301 | .unwrap() |
| 1302 | } |
| 1303 | |
| 1304 | #[tokio::test] |
| 1305 | async fn legacy_goal_remains_visible_and_cannot_silently_restart_or_be_replaced() { |
| 1306 | let (state, temp, fake, server) = fixture(false).await; |
| 1307 | let goal = legacy_goal_record("active", "retained work"); |
| 1308 | let store = seed_archive(&state, "legacy", temp.path(), Vec::new(), Some(goal)).await; |
| 1309 | let before = store.snapshot_legacy_thread_history("legacy").unwrap(); |
| 1310 | assert_eq!( |
| 1311 | before.goal.as_ref().unwrap().status, |
| 1312 | codewhale_protocol::ThreadGoalStatus::Active |
| 1313 | ); |
| 1314 | let request = ThreadRequest::GoalGet(codewhale_protocol::ThreadGoalGetParams { |
| 1315 | thread_id: "legacy".into(), |
| 1316 | }); |
| 1317 | let result = handle(&state, request.clone()).await.unwrap(); |
| 1318 | assert_eq!(result.status, "ok"); |
| 1319 | let recovered = result.goal.unwrap(); |
| 1320 | assert_eq!(recovered.thread_id, "legacy"); |
| 1321 | assert_eq!(recovered.goal_id, "old-goal"); |
| 1322 | assert_eq!(recovered.tokens_used, 137); |
| 1323 | assert_eq!(recovered.time_used_seconds, 23); |
| 1324 | assert_eq!(recovered.continuation_count, 2); |
| 1325 | assert_eq!(recovered.created_at, 1); |
| 1326 | assert_eq!(recovered.updated_at, 2); |
| 1327 | assert_eq!(recovered.token_budget, Some(1000)); |
| 1328 | assert_eq!( |
| 1329 | recovered.status, |
| 1330 | codewhale_protocol::ThreadGoalStatus::Paused |
| 1331 | ); |
| 1332 | assert_eq!(recovered.pause_reason, None); |
| 1333 | assert_eq!( |
| 1334 | serde_json::to_value(store.snapshot_legacy_thread_history("legacy").unwrap()).unwrap(), |
| 1335 | serde_json::to_value(before).unwrap() |
| 1336 | ); |
| 1337 | // Later owner progress is authoritative. A repeated alias read neither |
| 1338 | // imports the old goal again nor resets its real current progress. |
| 1339 | fake.goal.lock().await.as_mut().unwrap()["tokens_used"] = json!(151); |
| 1340 | let again = handle(&state, request).await.unwrap(); |
| 1341 | assert_eq!(again.goal.unwrap().tokens_used, 151); |
| 1342 | let calls = fake.calls.lock().await; |
| 1343 | assert_eq!( |
| 1344 | calls |
| 1345 | .iter() |
| 1346 | .filter(|(_, p, _)| p.ends_with("/import")) |
| 1347 | .count(), |
| 1348 | 1 |
| 1349 | ); |
| 1350 | assert!( |
| 1351 | calls |
| 1352 | .iter() |
| 1353 | .all(|(m, p, _)| !(p.ends_with("/turns") || p.ends_with("/goal") && m != "GET")) |
| 1354 | ); |
| 1355 | server.abort(); |
| 1356 | } |
| 1357 | |
| 1358 | #[tokio::test] |
| 1359 | async fn changed_legacy_goal_during_import_refuses_alias_publication() { |
| 1360 | let (state, temp, fake, server) = fixture(true).await; |
| 1361 | let store = seed_archive( |
| 1362 | &state, |
| 1363 | "legacy", |
| 1364 | temp.path(), |
| 1365 | Vec::new(), |
| 1366 | Some(legacy_goal_record("paused", "original")), |
| 1367 | ) |
| 1368 | .await; |
| 1369 | let worker_state = state.clone(); |
| 1370 | let waiter = tokio::spawn(async move { resolve(&worker_state, "legacy", true).await }); |
| 1371 | fake.import_seen.notified().await; |
| 1372 | rusqlite::Connection::open(store.db_path()) |
| 1373 | .unwrap() |
| 1374 | .execute( |
| 1375 | "UPDATE thread_goals SET objective='changed during import' WHERE thread_id='legacy'", |
| 1376 | [], |
| 1377 | ) |
| 1378 | .unwrap(); |
| 1379 | fake.import_release.notify_one(); |
| 1380 | let error = waiter.await.unwrap().unwrap_err(); |
| 1381 | assert!(format!("{error:#}").contains("legacy history changed")); |
| 1382 | assert!( |
| 1383 | store |
| 1384 | .get_canonical_runtime_link("legacy", state.captured_owner.as_ref().unwrap()) |
| 1385 | .unwrap() |
| 1386 | .is_none() |
| 1387 | ); |
| 1388 | assert_eq!( |
| 1389 | store.get_thread_goal("legacy").unwrap().unwrap().objective, |
| 1390 | "changed during import" |
| 1391 | ); |
| 1392 | assert_eq!( |
| 1393 | fake.goal.lock().await.as_ref().unwrap()["objective"], |
| 1394 | "original" |
| 1395 | ); |
| 1396 | server.abort(); |
| 1397 | } |
| 1398 | |
| 1399 | #[tokio::test] |
| 1400 | async fn conflicting_existing_owner_goal_is_visible_refusal_without_empty_alias() { |
| 1401 | let (state, temp, fake, server) = fixture(false).await; |
| 1402 | let store = seed_archive( |
| 1403 | &state, |
| 1404 | "legacy", |
| 1405 | temp.path(), |
| 1406 | Vec::new(), |
| 1407 | Some(legacy_goal_record("paused", "legacy objective")), |
| 1408 | ) |
| 1409 | .await; |
| 1410 | let mut existing = |
| 1411 | serde_json::to_value(legacy_goal_record("paused", "owned objective")).unwrap(); |
| 1412 | existing["thread_id"] = json!("canonical-1"); |
| 1413 | existing["goal_id"] = json!("owned-goal"); |
| 1414 | *fake.goal.lock().await = Some(existing.clone()); |
| 1415 | let request = ThreadRequest::GoalGet(codewhale_protocol::ThreadGoalGetParams { |
| 1416 | thread_id: "legacy".into(), |
| 1417 | }); |
| 1418 | let error = handle(&state, request).await.unwrap_err(); |
| 1419 | assert!(error.wire.message.contains("canonical goal conflict")); |
| 1420 | assert!( |
| 1421 | store |
| 1422 | .get_canonical_runtime_link("legacy", state.captured_owner.as_ref().unwrap()) |
| 1423 | .unwrap() |
| 1424 | .is_none() |
| 1425 | ); |
| 1426 | assert_eq!( |
| 1427 | store.get_thread_goal("legacy").unwrap().unwrap().objective, |
| 1428 | "legacy objective" |
| 1429 | ); |
| 1430 | assert_eq!(fake.goal.lock().await.as_ref().unwrap(), &existing); |
| 1431 | server.abort(); |
| 1432 | } |
| 1433 |