| 1 | //! Work-graph unit tests: one test per invariant V1–V10, plus the reducer |
| 2 | //! contract (determinism, idempotency dedup, fail-closed rejection, bounded |
| 3 | //! history) and serde round-trip. |
| 4 | |
| 5 | use super::compat; |
| 6 | use super::*; |
| 7 | use codewhale_models::reasoning_effort_tier::ReasoningEffortTier; |
| 8 | |
| 9 | const SESSION: &str = "sess-test"; |
| 10 | |
| 11 | fn nid(disc: &str) -> WorkNodeId { |
| 12 | WorkNodeId::derive(SESSION, disc) |
| 13 | } |
| 14 | |
| 15 | fn eid(disc: &str) -> WorkEdgeId { |
| 16 | WorkEdgeId::derive(SESSION, disc) |
| 17 | } |
| 18 | |
| 19 | fn ctx(now: Ts) -> ChangeCtx { |
| 20 | ChangeCtx { |
| 21 | session_id: SESSION.to_string(), |
| 22 | now, |
| 23 | idempotency_key: None, |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | fn ctx_keyed(now: Ts, seq: u64) -> ChangeCtx { |
| 28 | ChangeCtx { |
| 29 | session_id: SESSION.to_string(), |
| 30 | now, |
| 31 | idempotency_key: Some(IdempotencyKey { |
| 32 | binding: BindingId::derive(SESSION, "binding:op"), |
| 33 | seq, |
| 34 | }), |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | fn mk_node(disc: &str, kind: NodeKind, state: NodeState, now: Ts) -> WorkNode { |
| 39 | WorkNode { |
| 40 | id: nid(disc), |
| 41 | kind, |
| 42 | title: disc.to_string(), |
| 43 | state, |
| 44 | acceptance: Vec::new(), |
| 45 | binding: None, |
| 46 | evidence: None, |
| 47 | provenance: Provenance::Import { |
| 48 | source_digest: "digest".to_string(), |
| 49 | ordinal: None, |
| 50 | }, |
| 51 | created_at: now, |
| 52 | updated_at: now, |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | fn mk_edge(disc: &str, kind: EdgeKind, from: &str, to: &str) -> WorkEdge { |
| 57 | WorkEdge { |
| 58 | id: eid(disc), |
| 59 | kind, |
| 60 | from: nid(from), |
| 61 | to: nid(to), |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | fn effort_activity( |
| 66 | provider: impl Into<String>, |
| 67 | ts: Ts, |
| 68 | operation: Option<WorkNodeId>, |
| 69 | ) -> WorkActivityEvent { |
| 70 | let provider = provider.into(); |
| 71 | WorkActivityEvent::ReasoningEffortChanged { |
| 72 | requested: ReasoningEffortTier::Low, |
| 73 | effective: ReasoningEffortTier::High, |
| 74 | provider_kind: Some( |
| 75 | codewhale_config::ProviderKind::parse(&provider) |
| 76 | .unwrap_or(codewhale_config::ProviderKind::Custom), |
| 77 | ), |
| 78 | provider, |
| 79 | endpoint_identity: Some("https://example.invalid/v1".to_string()), |
| 80 | model: Some("test-model".to_string()), |
| 81 | ts, |
| 82 | operation, |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | fn must(graph: &mut WorkGraph, change: WorkGraphChange, now: Ts) -> ChangeReceipt { |
| 87 | graph.apply(change, ctx(now)).expect("change should apply") |
| 88 | } |
| 89 | |
| 90 | /// Objective ─Contains→ PlanStep ─Contains→ Operation (all Ready). |
| 91 | fn seeded() -> WorkGraph { |
| 92 | let mut graph = WorkGraph::new(); |
| 93 | must( |
| 94 | &mut graph, |
| 95 | WorkGraphChange::AddNode { |
| 96 | node: mk_node("root", NodeKind::Objective, NodeState::Ready, 1), |
| 97 | }, |
| 98 | 1, |
| 99 | ); |
| 100 | must( |
| 101 | &mut graph, |
| 102 | WorkGraphChange::AddNode { |
| 103 | node: mk_node("step", NodeKind::PlanStep, NodeState::Ready, 2), |
| 104 | }, |
| 105 | 2, |
| 106 | ); |
| 107 | must( |
| 108 | &mut graph, |
| 109 | WorkGraphChange::AddEdge { |
| 110 | edge: mk_edge("c:root:step", EdgeKind::Contains, "root", "step"), |
| 111 | }, |
| 112 | 3, |
| 113 | ); |
| 114 | must( |
| 115 | &mut graph, |
| 116 | WorkGraphChange::AddNode { |
| 117 | node: mk_node("op", NodeKind::Operation, NodeState::Ready, 4), |
| 118 | }, |
| 119 | 4, |
| 120 | ); |
| 121 | must( |
| 122 | &mut graph, |
| 123 | WorkGraphChange::AddEdge { |
| 124 | edge: mk_edge("c:step:op", EdgeKind::Contains, "step", "op"), |
| 125 | }, |
| 126 | 5, |
| 127 | ); |
| 128 | graph |
| 129 | } |
| 130 | |
| 131 | fn set_state(graph: &mut WorkGraph, disc: &str, state: NodeState, now: Ts) { |
| 132 | must( |
| 133 | graph, |
| 134 | WorkGraphChange::UpdateNode { |
| 135 | id: nid(disc), |
| 136 | patch: WorkNodePatch { |
| 137 | state: Some(state), |
| 138 | ..WorkNodePatch::default() |
| 139 | }, |
| 140 | }, |
| 141 | now, |
| 142 | ); |
| 143 | } |
| 144 | |
| 145 | fn expect_code( |
| 146 | result: Result<ChangeReceipt, ValidationReport>, |
| 147 | code: ValidationCode, |
| 148 | ) -> ValidationReport { |
| 149 | let report = result.expect_err("change should be rejected"); |
| 150 | assert!(report.contains_code(code), "expected {code:?} in {report}",); |
| 151 | report |
| 152 | } |
| 153 | |
| 154 | #[test] |
| 155 | fn v1_depends_on_cycles_rejected() { |
| 156 | let mut graph = seeded(); |
| 157 | must( |
| 158 | &mut graph, |
| 159 | WorkGraphChange::AddNode { |
| 160 | node: mk_node("step2", NodeKind::PlanStep, NodeState::Ready, 6), |
| 161 | }, |
| 162 | 6, |
| 163 | ); |
| 164 | must( |
| 165 | &mut graph, |
| 166 | WorkGraphChange::AddEdge { |
| 167 | edge: mk_edge("d:step:step2", EdgeKind::DependsOn, "step", "step2"), |
| 168 | }, |
| 169 | 7, |
| 170 | ); |
| 171 | let result = graph.apply( |
| 172 | WorkGraphChange::AddEdge { |
| 173 | edge: mk_edge("d:step2:step", EdgeKind::DependsOn, "step2", "step"), |
| 174 | }, |
| 175 | ctx(8), |
| 176 | ); |
| 177 | expect_code(result, ValidationCode::V1); |
| 178 | } |
| 179 | |
| 180 | #[test] |
| 181 | fn v2_live_operation_requires_plan_ancestry() { |
| 182 | let mut graph = seeded(); |
| 183 | // Attached operation may go live. |
| 184 | set_state(&mut graph, "op", NodeState::Active, 6); |
| 185 | |
| 186 | // An orphaned live operation is rejected outright. |
| 187 | let result = graph.apply( |
| 188 | WorkGraphChange::AddNode { |
| 189 | node: mk_node("orphan-op", NodeKind::Operation, NodeState::Active, 7), |
| 190 | }, |
| 191 | ctx(7), |
| 192 | ); |
| 193 | expect_code(result, ValidationCode::V2); |
| 194 | } |
| 195 | |
| 196 | #[test] |
| 197 | fn v3_binding_only_on_operation_nodes() { |
| 198 | let mut graph = seeded(); |
| 199 | let result = graph.apply( |
| 200 | WorkGraphChange::BindOperation { |
| 201 | node: nid("step"), |
| 202 | binding: OperationBinding { |
| 203 | external: "task:task_0123456789abcdef".to_string(), |
| 204 | durable: true, |
| 205 | last_observation: None, |
| 206 | }, |
| 207 | }, |
| 208 | ctx(6), |
| 209 | ); |
| 210 | expect_code(result, ValidationCode::V3); |
| 211 | } |
| 212 | |
| 213 | #[test] |
| 214 | fn v4_verified_requires_satisfying_evidence() { |
| 215 | let mut graph = seeded(); |
| 216 | |
| 217 | // Verified with empty acceptance: rejected. |
| 218 | let result = graph.apply( |
| 219 | WorkGraphChange::UpdateNode { |
| 220 | id: nid("op"), |
| 221 | patch: WorkNodePatch { |
| 222 | state: Some(NodeState::Verified), |
| 223 | ..WorkNodePatch::default() |
| 224 | }, |
| 225 | }, |
| 226 | ctx(6), |
| 227 | ); |
| 228 | expect_code(result, ValidationCode::V4); |
| 229 | |
| 230 | // Give the node an acceptance requirement; Verified without evidence is |
| 231 | // still rejected — cannot-verify never fails open into done. |
| 232 | must( |
| 233 | &mut graph, |
| 234 | WorkGraphChange::UpdateNode { |
| 235 | id: nid("op"), |
| 236 | patch: WorkNodePatch { |
| 237 | acceptance: Some(vec![AcceptanceRequirement::EvidenceOfKind { |
| 238 | kind: EvidenceKindTag::TestSummary, |
| 239 | }]), |
| 240 | ..WorkNodePatch::default() |
| 241 | }, |
| 242 | }, |
| 243 | 7, |
| 244 | ); |
| 245 | let result = graph.apply( |
| 246 | WorkGraphChange::UpdateNode { |
| 247 | id: nid("op"), |
| 248 | patch: WorkNodePatch { |
| 249 | state: Some(NodeState::Verified), |
| 250 | ..WorkNodePatch::default() |
| 251 | }, |
| 252 | }, |
| 253 | ctx(8), |
| 254 | ); |
| 255 | expect_code(result, ValidationCode::V4); |
| 256 | // The failed attempt changed nothing; the caller's recourse is Blocked, |
| 257 | // never silently-verified. |
| 258 | assert_eq!( |
| 259 | graph.snapshot().node(&nid("op")).unwrap().state, |
| 260 | NodeState::Ready |
| 261 | ); |
| 262 | |
| 263 | // Wrong-kind evidence does not satisfy the requirement. |
| 264 | must( |
| 265 | &mut graph, |
| 266 | WorkGraphChange::AttachEvidence { |
| 267 | node: nid("op"), |
| 268 | evidence: EvidenceRef::new(EvidenceKind::ToolRun, "tool-call:1", None, false).unwrap(), |
| 269 | }, |
| 270 | 9, |
| 271 | ); |
| 272 | let result = graph.apply( |
| 273 | WorkGraphChange::UpdateNode { |
| 274 | id: nid("op"), |
| 275 | patch: WorkNodePatch { |
| 276 | state: Some(NodeState::Verified), |
| 277 | ..WorkNodePatch::default() |
| 278 | }, |
| 279 | }, |
| 280 | ctx(10), |
| 281 | ); |
| 282 | expect_code(result, ValidationCode::V4); |
| 283 | |
| 284 | // Satisfying evidence unlocks Verified. |
| 285 | must( |
| 286 | &mut graph, |
| 287 | WorkGraphChange::AttachEvidence { |
| 288 | node: nid("op"), |
| 289 | evidence: EvidenceRef::new(EvidenceKind::TestSummary, "test-run:42", Some(2048), true) |
| 290 | .unwrap(), |
| 291 | }, |
| 292 | 11, |
| 293 | ); |
| 294 | set_state(&mut graph, "op", NodeState::Verified, 12); |
| 295 | assert_eq!( |
| 296 | graph.snapshot().node(&nid("op")).unwrap().state, |
| 297 | NodeState::Verified |
| 298 | ); |
| 299 | } |
| 300 | |
| 301 | #[test] |
| 302 | fn v5_blocked_requires_visible_cause() { |
| 303 | let mut graph = seeded(); |
| 304 | let result = graph.apply( |
| 305 | WorkGraphChange::UpdateNode { |
| 306 | id: nid("op"), |
| 307 | patch: WorkNodePatch { |
| 308 | state: Some(NodeState::Blocked), |
| 309 | ..WorkNodePatch::default() |
| 310 | }, |
| 311 | }, |
| 312 | ctx(6), |
| 313 | ); |
| 314 | expect_code(result, ValidationCode::V5); |
| 315 | |
| 316 | must( |
| 317 | &mut graph, |
| 318 | WorkGraphChange::AddNode { |
| 319 | node: mk_node("blocker", NodeKind::Blocker, NodeState::Ready, 7), |
| 320 | }, |
| 321 | 7, |
| 322 | ); |
| 323 | must( |
| 324 | &mut graph, |
| 325 | WorkGraphChange::AddEdge { |
| 326 | edge: mk_edge("b:blocker:op", EdgeKind::Blocks, "blocker", "op"), |
| 327 | }, |
| 328 | 8, |
| 329 | ); |
| 330 | set_state(&mut graph, "op", NodeState::Blocked, 9); |
| 331 | assert_eq!( |
| 332 | graph.snapshot().node(&nid("op")).unwrap().state, |
| 333 | NodeState::Blocked |
| 334 | ); |
| 335 | } |
| 336 | |
| 337 | #[test] |
| 338 | fn v6_binding_external_identity() { |
| 339 | let mut graph = seeded(); |
| 340 | |
| 341 | // Unknown scheme: rejected. |
| 342 | let result = graph.apply( |
| 343 | WorkGraphChange::BindOperation { |
| 344 | node: nid("op"), |
| 345 | binding: OperationBinding { |
| 346 | external: "mystery:xyz".to_string(), |
| 347 | durable: true, |
| 348 | last_observation: None, |
| 349 | }, |
| 350 | }, |
| 351 | ctx(6), |
| 352 | ); |
| 353 | expect_code(result, ValidationCode::V6); |
| 354 | |
| 355 | // Well-formed externals bind; fleet's two-part form parses too. |
| 356 | assert!(external_identity_is_well_formed("fleet:run_1/task_2")); |
| 357 | assert!(!external_identity_is_well_formed("fleet:run-only")); |
| 358 | must( |
| 359 | &mut graph, |
| 360 | WorkGraphChange::BindOperation { |
| 361 | node: nid("op"), |
| 362 | binding: OperationBinding { |
| 363 | external: "shell:shell_ab12cd34".to_string(), |
| 364 | durable: false, |
| 365 | last_observation: None, |
| 366 | }, |
| 367 | }, |
| 368 | 7, |
| 369 | ); |
| 370 | |
| 371 | // A second operation cannot claim the same external identity. |
| 372 | must( |
| 373 | &mut graph, |
| 374 | WorkGraphChange::AddNode { |
| 375 | node: mk_node("op2", NodeKind::Operation, NodeState::Ready, 8), |
| 376 | }, |
| 377 | 8, |
| 378 | ); |
| 379 | let result = graph.apply( |
| 380 | WorkGraphChange::BindOperation { |
| 381 | node: nid("op2"), |
| 382 | binding: OperationBinding { |
| 383 | external: "shell:shell_ab12cd34".to_string(), |
| 384 | durable: false, |
| 385 | last_observation: None, |
| 386 | }, |
| 387 | }, |
| 388 | ctx(9), |
| 389 | ); |
| 390 | expect_code(result, ValidationCode::V6); |
| 391 | } |
| 392 | |
| 393 | #[test] |
| 394 | fn v7_reference_nodes_stay_inert() { |
| 395 | let mut graph = seeded(); |
| 396 | let result = graph.apply( |
| 397 | WorkGraphChange::AddNode { |
| 398 | node: mk_node("rt", NodeKind::RuntimeRef, NodeState::Active, 6), |
| 399 | }, |
| 400 | ctx(6), |
| 401 | ); |
| 402 | expect_code(result, ValidationCode::V7); |
| 403 | |
| 404 | // Inert reference nodes are fine. |
| 405 | must( |
| 406 | &mut graph, |
| 407 | WorkGraphChange::AddNode { |
| 408 | node: mk_node("lane", NodeKind::LaneRef, NodeState::Ready, 7), |
| 409 | }, |
| 410 | 7, |
| 411 | ); |
| 412 | } |
| 413 | |
| 414 | #[test] |
| 415 | fn v8_revision_and_history_monotonic() { |
| 416 | // Applied changes increment the revision exactly once each and receipts |
| 417 | // land in order. |
| 418 | let graph = seeded(); |
| 419 | assert_eq!(graph.snapshot().revision, 5); |
| 420 | let revisions: Vec<u64> = graph |
| 421 | .snapshot() |
| 422 | .history |
| 423 | .iter() |
| 424 | .map(|r| r.revision) |
| 425 | .collect(); |
| 426 | assert_eq!(revisions, vec![1, 2, 3, 4, 5]); |
| 427 | |
| 428 | // A snapshot whose history revisions are out of order fails validation. |
| 429 | let mut bad = graph.snapshot().clone(); |
| 430 | let mut receipt = bad.history.last().unwrap().clone(); |
| 431 | receipt.revision = 2; // duplicate/regressing revision |
| 432 | bad.history.push_bounded(receipt); |
| 433 | let report = validate(&bad).expect_err("out-of-order history must fail"); |
| 434 | assert!(report.contains_code(ValidationCode::V8)); |
| 435 | } |
| 436 | |
| 437 | #[test] |
| 438 | fn v9_terminal_states_only_move_via_supersede() { |
| 439 | let mut graph = seeded(); |
| 440 | set_state(&mut graph, "op", NodeState::Cancelled, 6); |
| 441 | |
| 442 | // Patching a terminal node's state is rejected. |
| 443 | let result = graph.apply( |
| 444 | WorkGraphChange::UpdateNode { |
| 445 | id: nid("op"), |
| 446 | patch: WorkNodePatch { |
| 447 | state: Some(NodeState::Active), |
| 448 | ..WorkNodePatch::default() |
| 449 | }, |
| 450 | }, |
| 451 | ctx(7), |
| 452 | ); |
| 453 | expect_code(result, ValidationCode::V9); |
| 454 | |
| 455 | // ...but re-asserting the state it already holds is a no-op, not an error. |
| 456 | // `work_update` replaces the whole list on every call, so a cancelled item |
| 457 | // is re-sent as cancelled every time; rejecting that made the tool unusable |
| 458 | // once anything was cancelled. |
| 459 | let terminal_state = graph.snapshot().node(&nid("op")).expect("op node").state; |
| 460 | let replay = graph.apply( |
| 461 | WorkGraphChange::UpdateNode { |
| 462 | id: nid("op"), |
| 463 | patch: WorkNodePatch { |
| 464 | state: Some(terminal_state), |
| 465 | ..WorkNodePatch::default() |
| 466 | }, |
| 467 | }, |
| 468 | ctx(8), |
| 469 | ); |
| 470 | assert!( |
| 471 | replay.is_ok(), |
| 472 | "re-sending a terminal node's own state must be accepted: {replay:?}" |
| 473 | ); |
| 474 | |
| 475 | // Explicit Supersede is the sanctioned path. |
| 476 | must( |
| 477 | &mut graph, |
| 478 | WorkGraphChange::AddNode { |
| 479 | node: mk_node("op-new", NodeKind::Operation, NodeState::Ready, 8), |
| 480 | }, |
| 481 | 8, |
| 482 | ); |
| 483 | must( |
| 484 | &mut graph, |
| 485 | WorkGraphChange::Supersede { |
| 486 | old: nid("op"), |
| 487 | replacement: nid("op-new"), |
| 488 | }, |
| 489 | 9, |
| 490 | ); |
| 491 | let snapshot = graph.snapshot(); |
| 492 | assert_eq!( |
| 493 | snapshot.node(&nid("op")).unwrap().state, |
| 494 | NodeState::Superseded |
| 495 | ); |
| 496 | assert!(snapshot.edges.iter().any(|e| { |
| 497 | matches!(e.kind, EdgeKind::Supersedes) && e.from == nid("op-new") && e.to == nid("op") |
| 498 | })); |
| 499 | } |
| 500 | |
| 501 | #[test] |
| 502 | fn v10_projections_are_pure_functions_of_snapshot() { |
| 503 | // Type-level enforcement: projections coerce to plain fns over an |
| 504 | // immutable snapshot reference — no mutable access, no ambient state. |
| 505 | let _plan: fn(&WorkGraphSnapshot) -> compat::PlanProjection = compat::project_plan; |
| 506 | let _todos: fn(&WorkGraphSnapshot) -> compat::TodoProjection = compat::project_todos; |
| 507 | } |
| 508 | |
| 509 | #[test] |
| 510 | fn compat_todo_binding_rejects_non_plan_step_node() { |
| 511 | let mut bad = seeded().snapshot().clone(); |
| 512 | bad.compat.todos.push(CompatTodoBinding { |
| 513 | legacy_id: 1, |
| 514 | node: nid("root"), |
| 515 | plan_index: None, |
| 516 | }); |
| 517 | |
| 518 | let report = validate(&bad).expect_err("compat To-do rows must bind to PlanStep nodes"); |
| 519 | assert!(report.contains_code(ValidationCode::Structural)); |
| 520 | } |
| 521 | |
| 522 | /// A representative change sequence exercising nodes, edges, bindings, |
| 523 | /// reconciliation, evidence, proposals, and supersede. |
| 524 | fn scripted_run() -> WorkGraph { |
| 525 | let mut graph = seeded(); |
| 526 | must( |
| 527 | &mut graph, |
| 528 | WorkGraphChange::BindOperation { |
| 529 | node: nid("op"), |
| 530 | binding: OperationBinding { |
| 531 | external: "task:task_0123456789abcdef".to_string(), |
| 532 | durable: true, |
| 533 | last_observation: None, |
| 534 | }, |
| 535 | }, |
| 536 | 6, |
| 537 | ); |
| 538 | graph |
| 539 | .apply( |
| 540 | WorkGraphChange::ReconcileOperation { |
| 541 | node: nid("op"), |
| 542 | obs: OperationObservation::OwnerReported { |
| 543 | state: OwnerState::Running, |
| 544 | seq: 1, |
| 545 | at: 7, |
| 546 | output: None, |
| 547 | }, |
| 548 | }, |
| 549 | ctx_keyed(7, 1), |
| 550 | ) |
| 551 | .expect("reconcile applies"); |
| 552 | must( |
| 553 | &mut graph, |
| 554 | WorkGraphChange::UpdateNode { |
| 555 | id: nid("op"), |
| 556 | patch: WorkNodePatch { |
| 557 | acceptance: Some(vec![AcceptanceRequirement::EvidenceOfKind { |
| 558 | kind: EvidenceKindTag::ToolRun, |
| 559 | }]), |
| 560 | ..WorkNodePatch::default() |
| 561 | }, |
| 562 | }, |
| 563 | 8, |
| 564 | ); |
| 565 | graph |
| 566 | .apply( |
| 567 | WorkGraphChange::ReconcileOperation { |
| 568 | node: nid("op"), |
| 569 | obs: OperationObservation::OwnerReported { |
| 570 | state: OwnerState::Completed, |
| 571 | seq: 2, |
| 572 | at: 9, |
| 573 | output: None, |
| 574 | }, |
| 575 | }, |
| 576 | ctx_keyed(9, 2), |
| 577 | ) |
| 578 | .expect("reconcile applies"); |
| 579 | must( |
| 580 | &mut graph, |
| 581 | WorkGraphChange::AttachEvidence { |
| 582 | node: nid("op"), |
| 583 | evidence: EvidenceRef::new(EvidenceKind::ToolRun, "tool-call:99", Some(512), false) |
| 584 | .unwrap(), |
| 585 | }, |
| 586 | 10, |
| 587 | ); |
| 588 | set_state(&mut graph, "op", NodeState::Verified, 11); |
| 589 | |
| 590 | let proposal = WorkGraphProposal { |
| 591 | id: ProposalId::derive(SESSION, "proposal:1"), |
| 592 | added_nodes: vec![mk_node("step2", NodeKind::PlanStep, NodeState::Ready, 12)], |
| 593 | added_edges: vec![mk_edge("c:root:step2", EdgeKind::Contains, "root", "step2")], |
| 594 | updated_nodes: vec![ProposedNodeUpdate { |
| 595 | id: nid("step"), |
| 596 | patch: WorkNodePatch { |
| 597 | title: Some("step (revised)".to_string()), |
| 598 | ..WorkNodePatch::default() |
| 599 | }, |
| 600 | }], |
| 601 | removed_nodes: Vec::new(), |
| 602 | removed_edges: Vec::new(), |
| 603 | replacement_compat: None, |
| 604 | }; |
| 605 | must( |
| 606 | &mut graph, |
| 607 | WorkGraphChange::ProposePlanDiff { proposal }, |
| 608 | 12, |
| 609 | ); |
| 610 | must( |
| 611 | &mut graph, |
| 612 | WorkGraphChange::AcceptPlanDiff { |
| 613 | proposal_id: ProposalId::derive(SESSION, "proposal:1"), |
| 614 | approval: ApprovalRef { |
| 615 | reference: "user-review:1".to_string(), |
| 616 | }, |
| 617 | }, |
| 618 | 13, |
| 619 | ); |
| 620 | graph |
| 621 | } |
| 622 | |
| 623 | #[test] |
| 624 | fn reducer_is_deterministic_including_ids() { |
| 625 | let first = scripted_run(); |
| 626 | let second = scripted_run(); |
| 627 | assert_eq!(first.snapshot(), second.snapshot()); |
| 628 | // Byte-identical serialization: same IDs, same ordering, same receipts. |
| 629 | let a = serde_json::to_string(first.snapshot()).unwrap(); |
| 630 | let b = serde_json::to_string(second.snapshot()).unwrap(); |
| 631 | assert_eq!(a, b); |
| 632 | } |
| 633 | |
| 634 | #[test] |
| 635 | fn idempotency_key_dedup_is_a_no_op() { |
| 636 | let mut graph = scripted_run(); |
| 637 | let before = graph.snapshot().clone(); |
| 638 | |
| 639 | // Same (binding, seq) as an already-applied observation: acknowledged, |
| 640 | // nothing changes — not revision, not history, not node state. |
| 641 | let receipt = graph |
| 642 | .apply( |
| 643 | WorkGraphChange::ReconcileOperation { |
| 644 | node: nid("op"), |
| 645 | obs: OperationObservation::OwnerReported { |
| 646 | state: OwnerState::Failed, |
| 647 | seq: 2, |
| 648 | at: 99, |
| 649 | output: None, |
| 650 | }, |
| 651 | }, |
| 652 | ctx_keyed(99, 2), |
| 653 | ) |
| 654 | .expect("duplicate is acknowledged, not errored"); |
| 655 | assert!(receipt.no_op); |
| 656 | assert_eq!(receipt.revision, before.revision); |
| 657 | assert_eq!(graph.snapshot(), &before); |
| 658 | } |
| 659 | |
| 660 | #[test] |
| 661 | fn rejected_change_leaves_snapshot_untouched() { |
| 662 | let mut graph = seeded(); |
| 663 | let before = graph.snapshot().clone(); |
| 664 | let result = graph.apply( |
| 665 | WorkGraphChange::UpdateNode { |
| 666 | id: nid("op"), |
| 667 | patch: WorkNodePatch { |
| 668 | state: Some(NodeState::Verified), // V4: no acceptance, no evidence |
| 669 | ..WorkNodePatch::default() |
| 670 | }, |
| 671 | }, |
| 672 | ctx(6), |
| 673 | ); |
| 674 | expect_code(result, ValidationCode::V4); |
| 675 | assert_eq!(graph.snapshot(), &before); |
| 676 | |
| 677 | // Same fail-closed contract on the pure entry point. |
| 678 | let report = apply( |
| 679 | &before, |
| 680 | WorkGraphChange::RemoveEdge { |
| 681 | id: eid("does-not-exist"), |
| 682 | }, |
| 683 | ctx(7), |
| 684 | ) |
| 685 | .expect_err("missing edge is rejected"); |
| 686 | assert!(report.contains_code(ValidationCode::Structural)); |
| 687 | } |
| 688 | |
| 689 | #[test] |
| 690 | fn history_stays_bounded_at_cap() { |
| 691 | let mut graph = seeded(); |
| 692 | let seeded_revision = graph.snapshot().revision; |
| 693 | let extra = HISTORY_CAP as u64 + 44; |
| 694 | for i in 0..extra { |
| 695 | must( |
| 696 | &mut graph, |
| 697 | WorkGraphChange::UpdateNode { |
| 698 | id: nid("step"), |
| 699 | patch: WorkNodePatch { |
| 700 | title: Some(format!("step v{i}")), |
| 701 | ..WorkNodePatch::default() |
| 702 | }, |
| 703 | }, |
| 704 | 100 + i as Ts, |
| 705 | ); |
| 706 | } |
| 707 | let snapshot = graph.snapshot(); |
| 708 | assert_eq!(snapshot.revision, seeded_revision + extra); |
| 709 | assert_eq!(snapshot.history.len(), HISTORY_CAP); |
| 710 | // Oldest receipts were evicted FIFO; the window ends at the current |
| 711 | // revision and starts exactly HISTORY_CAP entries back. |
| 712 | let first = snapshot.history.iter().next().unwrap().revision; |
| 713 | let last = snapshot.history.last().unwrap().revision; |
| 714 | assert_eq!(last, snapshot.revision); |
| 715 | assert_eq!(first, snapshot.revision - (HISTORY_CAP as u64 - 1)); |
| 716 | } |
| 717 | |
| 718 | #[test] |
| 719 | fn activity_receipts_reject_bad_provider_identity_and_oversized_snapshots() { |
| 720 | let mut graph = seeded(); |
| 721 | for provider in [ |
| 722 | String::new(), |
| 723 | "bad route".to_string(), |
| 724 | "bad\nroute".to_string(), |
| 725 | "x".repeat(129), |
| 726 | ] { |
| 727 | let before = graph.snapshot().clone(); |
| 728 | let result = graph.apply( |
| 729 | WorkGraphChange::RecordActivity { |
| 730 | event: effort_activity(provider, 10, None), |
| 731 | }, |
| 732 | ctx(10), |
| 733 | ); |
| 734 | expect_code(result, ValidationCode::Structural); |
| 735 | assert_eq!(graph.snapshot(), &before, "rejection must be atomic"); |
| 736 | } |
| 737 | |
| 738 | for offset in 0..(ACTIVITY_CAP + 8) { |
| 739 | let ts = 100 + offset as Ts; |
| 740 | must( |
| 741 | &mut graph, |
| 742 | WorkGraphChange::RecordActivity { |
| 743 | event: effort_activity("xiaomi-mimo", ts, None), |
| 744 | }, |
| 745 | ts, |
| 746 | ); |
| 747 | } |
| 748 | assert_eq!(graph.snapshot().activities.len(), ACTIVITY_CAP); |
| 749 | assert_eq!( |
| 750 | graph.snapshot().activities.iter().next(), |
| 751 | Some(&effort_activity("xiaomi-mimo", 108, None)), |
| 752 | "bounded writes evict the oldest receipt" |
| 753 | ); |
| 754 | |
| 755 | let mut wire = serde_json::to_value(graph.snapshot()).expect("serialize graph"); |
| 756 | let activities = wire["activities"].as_array_mut().expect("activity array"); |
| 757 | activities.push(activities.last().expect("bounded receipt").clone()); |
| 758 | let oversized: WorkGraphSnapshot = |
| 759 | serde_json::from_value(wire).expect("deserialize untrusted oversized snapshot"); |
| 760 | let report = validate(&oversized).expect_err("oversized activity must fail closed"); |
| 761 | assert!(report.contains_code(ValidationCode::Structural)); |
| 762 | } |
| 763 | |
| 764 | #[test] |
| 765 | fn effective_only_reasoning_states_cannot_be_requested() { |
| 766 | for requested in [ |
| 767 | ReasoningEffortTier::ThinkingEnabledGranularityUnavailable, |
| 768 | ReasoningEffortTier::Unavailable, |
| 769 | ] { |
| 770 | let mut graph = seeded(); |
| 771 | let before = graph.snapshot().clone(); |
| 772 | let result = graph.apply( |
| 773 | WorkGraphChange::RecordActivity { |
| 774 | event: WorkActivityEvent::ReasoningEffortChanged { |
| 775 | requested, |
| 776 | effective: requested, |
| 777 | provider_kind: Some(codewhale_config::ProviderKind::Zai), |
| 778 | provider: "zai".to_string(), |
| 779 | endpoint_identity: Some( |
| 780 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL.to_string(), |
| 781 | ), |
| 782 | model: Some( |
| 783 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL |
| 784 | .to_string(), |
| 785 | ), |
| 786 | ts: 10, |
| 787 | operation: None, |
| 788 | }, |
| 789 | }, |
| 790 | ctx(10), |
| 791 | ); |
| 792 | expect_code(result, ValidationCode::Structural); |
| 793 | assert_eq!(graph.snapshot(), &before, "rejection must be atomic"); |
| 794 | } |
| 795 | } |
| 796 | |
| 797 | #[test] |
| 798 | fn activity_operation_links_require_live_operations_at_write_time() { |
| 799 | let mut graph = seeded(); |
| 800 | for operation in [nid("missing"), nid("root")] { |
| 801 | let before = graph.snapshot().clone(); |
| 802 | let result = graph.apply( |
| 803 | WorkGraphChange::RecordActivity { |
| 804 | event: effort_activity("xiaomi-mimo", 10, Some(operation)), |
| 805 | }, |
| 806 | ctx(10), |
| 807 | ); |
| 808 | expect_code(result, ValidationCode::Structural); |
| 809 | assert_eq!(graph.snapshot(), &before, "rejection must be atomic"); |
| 810 | } |
| 811 | |
| 812 | set_state(&mut graph, "op", NodeState::Active, 10); |
| 813 | set_state(&mut graph, "op", NodeState::Completed, 11); |
| 814 | let result = graph.apply( |
| 815 | WorkGraphChange::RecordActivity { |
| 816 | event: effort_activity("xiaomi-mimo", 12, Some(nid("op"))), |
| 817 | }, |
| 818 | ctx(12), |
| 819 | ); |
| 820 | expect_code(result, ValidationCode::Structural); |
| 821 | |
| 822 | for operation in [nid("missing"), nid("root")] { |
| 823 | let mut malformed = graph.snapshot().clone(); |
| 824 | malformed |
| 825 | .activities |
| 826 | .push_bounded(effort_activity("xiaomi-mimo", 13, Some(operation))); |
| 827 | let report = validate(&malformed).expect_err("invalid historical link must fail closed"); |
| 828 | assert!(report.contains_code(ValidationCode::Structural)); |
| 829 | } |
| 830 | |
| 831 | let mut historical = seeded(); |
| 832 | set_state(&mut historical, "op", NodeState::Active, 20); |
| 833 | must( |
| 834 | &mut historical, |
| 835 | WorkGraphChange::RecordActivity { |
| 836 | event: effort_activity("xiaomi-mimo", 21, Some(nid("op"))), |
| 837 | }, |
| 838 | 21, |
| 839 | ); |
| 840 | set_state(&mut historical, "op", NodeState::Completed, 22); |
| 841 | validate(historical.snapshot()).expect("a formerly-live historical link remains valid"); |
| 842 | } |
| 843 | |
| 844 | #[test] |
| 845 | fn snapshot_serde_round_trips() { |
| 846 | let graph = scripted_run(); |
| 847 | let json = serde_json::to_string(graph.snapshot()).unwrap(); |
| 848 | let restored: WorkGraphSnapshot = serde_json::from_str(&json).unwrap(); |
| 849 | assert_eq!(&restored, graph.snapshot()); |
| 850 | validate(&restored).expect("restored snapshot still satisfies invariants"); |
| 851 | } |
| 852 | |
| 853 | #[test] |
| 854 | fn legacy_reasoning_activity_loads_with_effective_truth_unavailable() { |
| 855 | let mut wire = serde_json::to_value(effort_activity("moonshot", 10, None)).unwrap(); |
| 856 | let object = wire.as_object_mut().expect("activity object"); |
| 857 | object.remove("endpoint_identity"); |
| 858 | object.remove("model"); |
| 859 | |
| 860 | let restored: WorkActivityEvent = serde_json::from_value(wire).expect("legacy activity loads"); |
| 861 | let WorkActivityEvent::ReasoningEffortChanged { |
| 862 | effective, |
| 863 | endpoint_identity, |
| 864 | model, |
| 865 | .. |
| 866 | } = restored; |
| 867 | assert_eq!(effective, ReasoningEffortTier::Unavailable); |
| 868 | assert!(endpoint_identity.is_none()); |
| 869 | assert!(model.is_none()); |
| 870 | } |
| 871 | |
| 872 | #[test] |
| 873 | fn legacy_reasoning_activity_missing_provider_kind_downgrades_effective_truth() { |
| 874 | let activity = WorkActivityEvent::ReasoningEffortChanged { |
| 875 | requested: ReasoningEffortTier::Max, |
| 876 | effective: ReasoningEffortTier::Max, |
| 877 | provider_kind: Some(codewhale_config::ProviderKind::Openai), |
| 878 | provider: "openai".to_string(), |
| 879 | endpoint_identity: Some( |
| 880 | codewhale_config::descriptors::defaults::DEFAULT_OPENAI_BASE_URL.to_string(), |
| 881 | ), |
| 882 | model: Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_MODEL.to_string()), |
| 883 | ts: 10, |
| 884 | operation: None, |
| 885 | }; |
| 886 | let mut wire = serde_json::to_value(activity).expect("serialize current activity"); |
| 887 | wire.as_object_mut() |
| 888 | .expect("activity object") |
| 889 | .remove("provider_kind"); |
| 890 | |
| 891 | let restored: WorkActivityEvent = |
| 892 | serde_json::from_value(wire).expect("legacy activity remains loadable"); |
| 893 | let WorkActivityEvent::ReasoningEffortChanged { |
| 894 | effective, |
| 895 | provider_kind, |
| 896 | endpoint_identity, |
| 897 | model, |
| 898 | .. |
| 899 | } = restored; |
| 900 | assert_eq!(provider_kind, None); |
| 901 | assert_eq!(effective, ReasoningEffortTier::Unavailable); |
| 902 | assert!( |
| 903 | endpoint_identity.is_some(), |
| 904 | "route provenance remains visible" |
| 905 | ); |
| 906 | assert!(model.is_some(), "model provenance remains visible"); |
| 907 | } |
| 908 | |
| 909 | #[test] |
| 910 | fn restored_custom_builtin_slug_collisions_cannot_forge_concrete_tiers() { |
| 911 | for provider in ["openai", "zai"] { |
| 912 | let mut forged = seeded().into_snapshot(); |
| 913 | forged |
| 914 | .activities |
| 915 | .push_bounded(WorkActivityEvent::ReasoningEffortChanged { |
| 916 | requested: ReasoningEffortTier::Max, |
| 917 | effective: ReasoningEffortTier::Max, |
| 918 | provider_kind: Some(codewhale_config::ProviderKind::Custom), |
| 919 | provider: provider.to_string(), |
| 920 | endpoint_identity: Some("https://gateway.example/v1".to_string()), |
| 921 | model: Some("vendor-model-x".to_string()), |
| 922 | ts: 10, |
| 923 | operation: None, |
| 924 | }); |
| 925 | let wire = serde_json::to_string(&forged).expect("serialize forged custom route"); |
| 926 | let restored: WorkGraphSnapshot = |
| 927 | serde_json::from_str(&wire).expect("restore forged custom route"); |
| 928 | let report = validate(&restored) |
| 929 | .expect_err("custom identity collision cannot inherit built-in reasoning tiers"); |
| 930 | assert!( |
| 931 | report.contains_code(ValidationCode::Structural), |
| 932 | "{provider}" |
| 933 | ); |
| 934 | |
| 935 | let mut truthful_snapshot = seeded().into_snapshot(); |
| 936 | truthful_snapshot |
| 937 | .activities |
| 938 | .push_bounded(WorkActivityEvent::ReasoningEffortChanged { |
| 939 | requested: ReasoningEffortTier::Max, |
| 940 | effective: ReasoningEffortTier::Unavailable, |
| 941 | provider_kind: Some(codewhale_config::ProviderKind::Custom), |
| 942 | provider: provider.to_string(), |
| 943 | endpoint_identity: Some("https://gateway.example/v1".to_string()), |
| 944 | model: Some("vendor-model-x".to_string()), |
| 945 | ts: 10, |
| 946 | operation: None, |
| 947 | }); |
| 948 | let truthful_wire = |
| 949 | serde_json::to_string(&truthful_snapshot).expect("serialize truthful custom route"); |
| 950 | let truthful: WorkGraphSnapshot = |
| 951 | serde_json::from_str(&truthful_wire).expect("restore truthful custom route"); |
| 952 | validate(&truthful).expect("custom slug collision remains valid only as unavailable"); |
| 953 | } |
| 954 | } |
| 955 | |
| 956 | #[test] |
| 957 | fn restored_genuine_openai_preserves_known_tier_with_exact_provenance() { |
| 958 | let mut snapshot = seeded().into_snapshot(); |
| 959 | snapshot |
| 960 | .activities |
| 961 | .push_bounded(WorkActivityEvent::ReasoningEffortChanged { |
| 962 | requested: ReasoningEffortTier::Max, |
| 963 | effective: ReasoningEffortTier::Max, |
| 964 | provider_kind: Some(codewhale_config::ProviderKind::Openai), |
| 965 | provider: "openai".to_string(), |
| 966 | endpoint_identity: Some( |
| 967 | codewhale_config::descriptors::defaults::DEFAULT_OPENAI_BASE_URL.to_string(), |
| 968 | ), |
| 969 | model: Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_MODEL.to_string()), |
| 970 | ts: 10, |
| 971 | operation: None, |
| 972 | }); |
| 973 | let wire = serde_json::to_string(&snapshot).expect("serialize built-in OpenAI route"); |
| 974 | let restored: WorkGraphSnapshot = |
| 975 | serde_json::from_str(&wire).expect("restore built-in OpenAI route"); |
| 976 | |
| 977 | validate(&restored).expect("kind plus exact identity and route provenance prove OpenAI"); |
| 978 | } |
| 979 | |
| 980 | #[test] |
| 981 | fn restored_builtin_kind_rejects_mismatched_exact_identity() { |
| 982 | let mut snapshot = seeded().into_snapshot(); |
| 983 | snapshot |
| 984 | .activities |
| 985 | .push_bounded(WorkActivityEvent::ReasoningEffortChanged { |
| 986 | requested: ReasoningEffortTier::Max, |
| 987 | effective: ReasoningEffortTier::Max, |
| 988 | provider_kind: Some(codewhale_config::ProviderKind::Openai), |
| 989 | provider: "zai".to_string(), |
| 990 | endpoint_identity: Some( |
| 991 | codewhale_config::descriptors::defaults::DEFAULT_OPENAI_BASE_URL.to_string(), |
| 992 | ), |
| 993 | model: Some(codewhale_config::descriptors::defaults::DEFAULT_OPENAI_MODEL.to_string()), |
| 994 | ts: 10, |
| 995 | operation: None, |
| 996 | }); |
| 997 | |
| 998 | let report = validate(&snapshot).expect_err("kind and exact identity cannot disagree"); |
| 999 | assert!(report.contains_code(ValidationCode::Structural)); |
| 1000 | assert!(report.violations.iter().any(|violation| { |
| 1001 | violation |
| 1002 | .message |
| 1003 | .contains("provider identity does not match its recorded kind") |
| 1004 | })); |
| 1005 | } |
| 1006 | |
| 1007 | #[test] |
| 1008 | fn restored_zai_gateway_cannot_forge_effective_max() { |
| 1009 | let mut snapshot = seeded().into_snapshot(); |
| 1010 | snapshot |
| 1011 | .activities |
| 1012 | .push_bounded(WorkActivityEvent::ReasoningEffortChanged { |
| 1013 | requested: ReasoningEffortTier::Max, |
| 1014 | effective: ReasoningEffortTier::Max, |
| 1015 | provider_kind: Some(codewhale_config::ProviderKind::Zai), |
| 1016 | provider: "zai".to_string(), |
| 1017 | endpoint_identity: Some("https://gateway.example/v1".to_string()), |
| 1018 | model: Some( |
| 1019 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string(), |
| 1020 | ), |
| 1021 | ts: 10, |
| 1022 | operation: None, |
| 1023 | }); |
| 1024 | let wire = serde_json::to_string(&snapshot).expect("serialize forged snapshot"); |
| 1025 | let restored: WorkGraphSnapshot = serde_json::from_str(&wire).expect("restore forged snapshot"); |
| 1026 | |
| 1027 | let report = validate(&restored).expect_err("gateway cannot prove effective max"); |
| 1028 | assert!(report.contains_code(ValidationCode::Structural)); |
| 1029 | assert!(report.violations.iter().any(|violation| { |
| 1030 | violation |
| 1031 | .message |
| 1032 | .contains("impossible for its recorded route") |
| 1033 | })); |
| 1034 | } |
| 1035 | |
| 1036 | #[test] |
| 1037 | fn restored_zai_toggle_only_and_unknown_models_enforce_effective_truth() { |
| 1038 | for (model, truthful_effective) in [ |
| 1039 | ( |
| 1040 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_1_MODEL, |
| 1041 | ReasoningEffortTier::ThinkingEnabledGranularityUnavailable, |
| 1042 | ), |
| 1043 | ( |
| 1044 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL, |
| 1045 | ReasoningEffortTier::ThinkingEnabledGranularityUnavailable, |
| 1046 | ), |
| 1047 | ("glm-future-unknown", ReasoningEffortTier::Unavailable), |
| 1048 | ] { |
| 1049 | let mut forged = seeded().into_snapshot(); |
| 1050 | forged |
| 1051 | .activities |
| 1052 | .push_bounded(WorkActivityEvent::ReasoningEffortChanged { |
| 1053 | requested: ReasoningEffortTier::Max, |
| 1054 | effective: ReasoningEffortTier::Max, |
| 1055 | provider_kind: Some(codewhale_config::ProviderKind::Zai), |
| 1056 | provider: "zai".to_string(), |
| 1057 | endpoint_identity: Some( |
| 1058 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL.to_string(), |
| 1059 | ), |
| 1060 | model: Some(model.to_string()), |
| 1061 | ts: 10, |
| 1062 | operation: None, |
| 1063 | }); |
| 1064 | validate(&forged).expect_err("toggle-only/unknown Z.ai route cannot prove max"); |
| 1065 | |
| 1066 | let mut truthful = seeded().into_snapshot(); |
| 1067 | truthful |
| 1068 | .activities |
| 1069 | .push_bounded(WorkActivityEvent::ReasoningEffortChanged { |
| 1070 | requested: ReasoningEffortTier::Max, |
| 1071 | effective: truthful_effective, |
| 1072 | provider_kind: Some(codewhale_config::ProviderKind::Zai), |
| 1073 | provider: "zai".to_string(), |
| 1074 | endpoint_identity: Some( |
| 1075 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL.to_string(), |
| 1076 | ), |
| 1077 | model: Some(model.to_string()), |
| 1078 | ts: 10, |
| 1079 | operation: None, |
| 1080 | }); |
| 1081 | validate(&truthful).expect("truthful Z.ai effective state restores"); |
| 1082 | } |
| 1083 | } |
| 1084 | |
| 1085 | #[test] |
| 1086 | fn restored_zai_forced_thinking_models_cannot_claim_effective_off() { |
| 1087 | // GLM-5.3 / GLM-5.3-Flash reject `thinking.type: "disabled"`; the wire |
| 1088 | // sends `off` as `reasoning_effort: "low"`, so only `Low` is a truthful |
| 1089 | // effective receipt for a requested `Off`. GLM-5.2 keeps the toggle. |
| 1090 | // Both hosts of the first-party open platform enforce the same receipt. |
| 1091 | let zai_activity = |
| 1092 | |endpoint: &str, model: &str, effective: ReasoningEffortTier| -> WorkActivityEvent { |
| 1093 | WorkActivityEvent::ReasoningEffortChanged { |
| 1094 | requested: ReasoningEffortTier::Off, |
| 1095 | effective, |
| 1096 | provider_kind: Some(codewhale_config::ProviderKind::Zai), |
| 1097 | provider: "zai".to_string(), |
| 1098 | endpoint_identity: Some(endpoint.to_string()), |
| 1099 | model: Some(model.to_string()), |
| 1100 | ts: 10, |
| 1101 | operation: None, |
| 1102 | } |
| 1103 | }; |
| 1104 | for endpoint in [ |
| 1105 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL, |
| 1106 | "https://open.bigmodel.cn/api/paas/v4", |
| 1107 | ] { |
| 1108 | for model in [ |
| 1109 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_MODEL, |
| 1110 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_FLASH_MODEL, |
| 1111 | ] { |
| 1112 | let mut forged = seeded().into_snapshot(); |
| 1113 | forged |
| 1114 | .activities |
| 1115 | .push_bounded(zai_activity(endpoint, model, ReasoningEffortTier::Off)); |
| 1116 | validate(&forged).expect_err("forced-thinking Z.ai route cannot prove effective off"); |
| 1117 | |
| 1118 | let mut truthful = seeded().into_snapshot(); |
| 1119 | truthful.activities.push_bounded(zai_activity( |
| 1120 | endpoint, |
| 1121 | model, |
| 1122 | ReasoningEffortTier::Low, |
| 1123 | )); |
| 1124 | validate(&truthful).expect("off on a forced-thinking route restores as low"); |
| 1125 | } |
| 1126 | |
| 1127 | let mut glm_5_2 = seeded().into_snapshot(); |
| 1128 | glm_5_2.activities.push_bounded(zai_activity( |
| 1129 | endpoint, |
| 1130 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL, |
| 1131 | ReasoningEffortTier::Off, |
| 1132 | )); |
| 1133 | validate(&glm_5_2).expect("GLM-5.2 still honours the disabled toggle"); |
| 1134 | } |
| 1135 | } |
| 1136 | |
| 1137 | #[test] |
| 1138 | fn restored_named_gateway_cannot_forge_effective_max() { |
| 1139 | let mut snapshot = seeded().into_snapshot(); |
| 1140 | snapshot |
| 1141 | .activities |
| 1142 | .push_bounded(WorkActivityEvent::ReasoningEffortChanged { |
| 1143 | requested: ReasoningEffortTier::Max, |
| 1144 | effective: ReasoningEffortTier::Max, |
| 1145 | provider_kind: Some(codewhale_config::ProviderKind::Custom), |
| 1146 | provider: "my-gateway".to_string(), |
| 1147 | endpoint_identity: Some("https://gateway.example/v1".to_string()), |
| 1148 | model: Some("vendor-model-x".to_string()), |
| 1149 | ts: 10, |
| 1150 | operation: None, |
| 1151 | }); |
| 1152 | let wire = serde_json::to_string(&snapshot).expect("serialize forged snapshot"); |
| 1153 | let restored: WorkGraphSnapshot = serde_json::from_str(&wire).expect("restore forged snapshot"); |
| 1154 | |
| 1155 | let report = validate(&restored).expect_err("unknown gateway cannot prove effective max"); |
| 1156 | assert!(report.contains_code(ValidationCode::Structural)); |
| 1157 | assert!(report.violations.iter().any(|violation| { |
| 1158 | violation |
| 1159 | .message |
| 1160 | .contains("impossible for its recorded route") |
| 1161 | })); |
| 1162 | } |
| 1163 | |
| 1164 | #[test] |
| 1165 | fn restored_named_gateway_accepts_truthful_effective_unavailable() { |
| 1166 | let mut snapshot = seeded().into_snapshot(); |
| 1167 | snapshot |
| 1168 | .activities |
| 1169 | .push_bounded(WorkActivityEvent::ReasoningEffortChanged { |
| 1170 | requested: ReasoningEffortTier::Max, |
| 1171 | effective: ReasoningEffortTier::Unavailable, |
| 1172 | provider_kind: Some(codewhale_config::ProviderKind::Custom), |
| 1173 | provider: "my-gateway".to_string(), |
| 1174 | endpoint_identity: Some("https://gateway.example/v1".to_string()), |
| 1175 | model: Some("vendor-model-x".to_string()), |
| 1176 | ts: 10, |
| 1177 | operation: None, |
| 1178 | }); |
| 1179 | let wire = serde_json::to_string(&snapshot).expect("serialize truthful unknown snapshot"); |
| 1180 | let restored: WorkGraphSnapshot = |
| 1181 | serde_json::from_str(&wire).expect("restore truthful unknown snapshot"); |
| 1182 | |
| 1183 | validate(&restored).expect("unknown route remains valid when effective truth is unavailable"); |
| 1184 | } |
| 1185 | |
| 1186 | #[test] |
| 1187 | fn pre_wg3_proposal_shape_deserializes_with_empty_delta_extensions() { |
| 1188 | let proposal = WorkGraphProposal { |
| 1189 | id: ProposalId::derive(SESSION, "legacy-proposal"), |
| 1190 | added_nodes: Vec::new(), |
| 1191 | added_edges: Vec::new(), |
| 1192 | updated_nodes: Vec::new(), |
| 1193 | removed_nodes: vec![nid("old-step")], |
| 1194 | removed_edges: Vec::new(), |
| 1195 | replacement_compat: Some(CompatProjectionState::default()), |
| 1196 | }; |
| 1197 | let mut value = serde_json::to_value(proposal).expect("serialize current proposal"); |
| 1198 | let object = value.as_object_mut().expect("proposal object"); |
| 1199 | object.remove("removed_nodes"); |
| 1200 | object.remove("replacement_compat"); |
| 1201 | |
| 1202 | let restored: WorkGraphProposal = |
| 1203 | serde_json::from_value(value).expect("deserialize pre-WG3 proposal"); |
| 1204 | assert!(restored.removed_nodes.is_empty()); |
| 1205 | assert!(restored.replacement_compat.is_none()); |
| 1206 | } |
| 1207 | |
| 1208 | #[test] |
| 1209 | fn evidence_ref_rejects_paths_and_key_material() { |
| 1210 | let err = |reference: &str| { |
| 1211 | EvidenceRef::new(EvidenceKind::ToolRun, reference, None, false) |
| 1212 | .expect_err("reference should be rejected") |
| 1213 | }; |
| 1214 | assert_eq!(err(""), EvidenceRefError::EmptyReference); |
| 1215 | assert_eq!(err("/var/log/system.log"), EvidenceRefError::AbsolutePath); |
| 1216 | assert_eq!(err("\\\\server\\share"), EvidenceRefError::AbsolutePath); |
| 1217 | assert_eq!(err("C:\\temp\\out.txt"), EvidenceRefError::AbsolutePath); |
| 1218 | assert_eq!(err("~/notes.txt"), EvidenceRefError::HomeRelativePath); |
| 1219 | assert_eq!( |
| 1220 | err("two words"), |
| 1221 | EvidenceRefError::ContainsWhitespaceOrControl |
| 1222 | ); |
| 1223 | assert_eq!( |
| 1224 | err("line\nbreak"), |
| 1225 | EvidenceRefError::ContainsWhitespaceOrControl |
| 1226 | ); |
| 1227 | // Built at runtime so secret scanners never see a contiguous PEM marker |
| 1228 | // in source; the validator still receives the real prefix. |
| 1229 | let pem_marker = format!("-----{}-RSA-KEY", "BEGIN"); |
| 1230 | assert_eq!(err(&pem_marker), EvidenceRefError::LooksLikeKeyMaterial); |
| 1231 | |
| 1232 | // Deserialization re-runs constructor validation — serde is not a bypass. |
| 1233 | let smuggled = |
| 1234 | r#"{"kind":"tool_run","reference":"/etc/hosts","raw_bytes":null,"truncated":false}"#; |
| 1235 | assert!(serde_json::from_str::<EvidenceRef>(smuggled).is_err()); |
| 1236 | |
| 1237 | let ok = EvidenceRef::new( |
| 1238 | EvidenceKind::Artifact { |
| 1239 | digest: "sha256:abc123".to_string(), |
| 1240 | }, |
| 1241 | "artifact:build-77", |
| 1242 | Some(4096), |
| 1243 | true, |
| 1244 | ) |
| 1245 | .unwrap(); |
| 1246 | assert_eq!(ok.reference(), "artifact:build-77"); |
| 1247 | assert_eq!(ok.raw_bytes(), Some(4096)); |
| 1248 | assert!(ok.truncated()); |
| 1249 | } |
| 1250 | |
| 1251 | #[test] |
| 1252 | fn web_citation_evidence_is_typed_inspectable_and_fail_closed() { |
| 1253 | let kind = EvidenceKind::WebCitation { |
| 1254 | ref_id: "web_0123456789abcdef".to_string(), |
| 1255 | url: "https://example.com/source".to_string(), |
| 1256 | retrieved_at: "2026-07-19T18:00:00Z".to_string(), |
| 1257 | }; |
| 1258 | let evidence = EvidenceRef::new(kind, "web_0123456789abcdef", None, false) |
| 1259 | .expect("valid web citation evidence"); |
| 1260 | assert_eq!(evidence.kind().tag(), EvidenceKindTag::WebCitation); |
| 1261 | |
| 1262 | let serialized = serde_json::to_value(&evidence).expect("serialize citation evidence"); |
| 1263 | let restored: EvidenceRef = |
| 1264 | serde_json::from_value(serialized).expect("deserialize citation evidence"); |
| 1265 | assert_eq!(restored, evidence); |
| 1266 | |
| 1267 | let mismatched = EvidenceRef::new( |
| 1268 | EvidenceKind::WebCitation { |
| 1269 | ref_id: "web_other".to_string(), |
| 1270 | url: "https://example.com/source".to_string(), |
| 1271 | retrieved_at: "2026-07-19T18:00:00Z".to_string(), |
| 1272 | }, |
| 1273 | "web_0123456789abcdef", |
| 1274 | None, |
| 1275 | false, |
| 1276 | ) |
| 1277 | .expect_err("mismatched ref must fail"); |
| 1278 | assert_eq!(mismatched, EvidenceRefError::WebCitationReferenceMismatch); |
| 1279 | |
| 1280 | let credentialed = EvidenceRef::new( |
| 1281 | EvidenceKind::WebCitation { |
| 1282 | ref_id: "web_0123456789abcdef".to_string(), |
| 1283 | url: "https://user:password@example.com/source".to_string(), |
| 1284 | retrieved_at: "2026-07-19T18:00:00Z".to_string(), |
| 1285 | }, |
| 1286 | "web_0123456789abcdef", |
| 1287 | None, |
| 1288 | false, |
| 1289 | ) |
| 1290 | .expect_err("credentialed URL must fail"); |
| 1291 | assert_eq!(credentialed, EvidenceRefError::InvalidWebCitationUrl); |
| 1292 | |
| 1293 | let query_credential = EvidenceRef::new( |
| 1294 | EvidenceKind::WebCitation { |
| 1295 | ref_id: "web_0123456789abcdef".to_string(), |
| 1296 | url: "https://example.com/source?access_token=sensitive".to_string(), |
| 1297 | retrieved_at: "2026-07-19T18:00:00Z".to_string(), |
| 1298 | }, |
| 1299 | "web_0123456789abcdef", |
| 1300 | None, |
| 1301 | false, |
| 1302 | ) |
| 1303 | .expect_err("credential-bearing query must fail"); |
| 1304 | assert_eq!(query_credential, EvidenceRefError::InvalidWebCitationUrl); |
| 1305 | } |
| 1306 |