trusty-code 0.8.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//! Tests for `workstream.*` RPC handlers (DOC-48 §5.1/§6, issues #3294/#3295).

use super::*;
use serde_json::json;
use tempfile::TempDir;
use tokio::sync::mpsc;
use trusty_mcp::Request;

use crate::workstreams::store::WorkstreamStore;

fn test_ctx() -> ConnectionContext {
    let (tx, _rx) = mpsc::unbounded_channel();
    ConnectionContext::new(tx)
}

/// A fresh `SharedWorkstreamStore` backed by a tempfile path, plus the
/// `TempDir` guard (dropped -> file removed) — mirrors `activation_tests`'
/// own helper.
async fn shared_store() -> (SharedWorkstreamStore, TempDir) {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("workstreams-test.json");
    let store = WorkstreamStore::load(path).await.expect("load fresh store");
    (std::sync::Arc::new(tokio::sync::Mutex::new(store)), dir)
}

/// Seed a workstream directly via the store (bypassing the
/// `workstream.create` RPC handler, which some tests below exercise
/// directly under its own name — named distinctly so the two never collide).
async fn seed_workstream(store: &SharedWorkstreamStore, name: &str) -> WorkstreamId {
    store.lock().await.create(name).await.expect("create")
}

fn req(method: &str, params: serde_json::Value) -> Request {
    Request {
        jsonrpc: Some("2.0".to_string()),
        id: Some(json!(1)),
        method: method.to_string(),
        params: Some(params),
    }
}

/// `workstream.activate`/`workstream.deactivate` must be reachable through a
/// `Router` built by `register` (proves the wiring, not just the free
/// functions).
#[tokio::test]
async fn register_wires_activate_and_deactivate() {
    let (store, _dir) = shared_store().await;
    let id = seed_workstream(&store, "t").await;
    let mut router = Router::new();
    register(&mut router, store);

    let resp = router
        .dispatch(
            req("workstream.activate", json!({"id": id.to_string()})),
            &test_ctx(),
        )
        .await;
    assert!(
        resp.error.is_none(),
        "activate should succeed: {:?}",
        resp.error
    );

    let resp = router
        .dispatch(
            req("workstream.deactivate", json!({"id": id.to_string()})),
            &test_ctx(),
        )
        .await;
    assert!(
        resp.error.is_none(),
        "deactivate should succeed: {:?}",
        resp.error
    );
}

/// `workstream.create`/`get`/`list`/`close` must be reachable through a
/// `Router` built by `register` (proves the wiring, not just the free
/// functions) — the #3295 counterpart to
/// `register_wires_activate_and_deactivate` above.
#[tokio::test]
async fn register_wires_create_get_list_close() {
    let (store, _dir) = shared_store().await;
    let mut router = Router::new();
    register(&mut router, store);

    let resp = router
        .dispatch(req("workstream.create", json!({"name": "A"})), &test_ctx())
        .await;
    assert!(resp.error.is_none(), "create failed: {:?}", resp.error);
    let id = resp.result.unwrap()["id"].clone();

    for (method, params) in [
        ("workstream.get", json!({"id": id.clone()})),
        ("workstream.list", json!({})),
        ("workstream.rename", json!({"id": id.clone(), "name": "B"})),
        ("workstream.close", json!({"id": id})),
    ] {
        let resp = router.dispatch(req(method, params), &test_ctx()).await;
        assert!(resp.error.is_none(), "{method} failed: {:?}", resp.error);
    }
}

/// Activating with no prior active workstream must return `active_id` and a
/// null `prior_id`.
#[tokio::test]
async fn activate_succeeds_with_no_prior_active() {
    let (store, _dir) = shared_store().await;
    let id = seed_workstream(&store, "t").await;

    let result = activate(&store, json!({"id": id.to_string()}), test_ctx())
        .await
        .expect("activate must succeed");
    assert_eq!(result["active_id"], json!(id));
    assert_eq!(result["prior_id"], Value::Null);
}

/// Re-activating the already-active workstream (force omitted, defaults to
/// false) must be idempotent, not an error.
#[tokio::test]
async fn activate_already_active_is_idempotent() {
    let (store, _dir) = shared_store().await;
    let id = seed_workstream(&store, "t").await;
    activate(&store, json!({"id": id.to_string()}), test_ctx())
        .await
        .expect("first activate");

    let result = activate(&store, json!({"id": id.to_string()}), test_ctx())
        .await
        .expect("re-activate must succeed");
    assert_eq!(result["active_id"], json!(id));
    assert_eq!(result["prior_id"], Value::Null);
}

/// Activating a different workstream without `force` while one is active
/// must map to `-32008 active_conflict`, carrying the currently-active id.
#[tokio::test]
async fn activate_without_force_maps_to_active_conflict() {
    let (store, _dir) = shared_store().await;
    let a = seed_workstream(&store, "a").await;
    let b = seed_workstream(&store, "b").await;
    activate(&store, json!({"id": a.to_string()}), test_ctx())
        .await
        .expect("activate a");

    let err = activate(&store, json!({"id": b.to_string()}), test_ctx())
        .await
        .expect_err("must conflict");
    assert_eq!(err.code, -32008);
    assert_eq!(err.data.expect("data")["active_id"], json!(a.to_string()));
}

/// `force: true` must switch the active workstream and report the prior id.
#[tokio::test]
async fn activate_with_force_switches() {
    let (store, _dir) = shared_store().await;
    let a = seed_workstream(&store, "a").await;
    let b = seed_workstream(&store, "b").await;
    activate(&store, json!({"id": a.to_string()}), test_ctx())
        .await
        .expect("activate a");

    let result = activate(
        &store,
        json!({"id": b.to_string(), "force": true}),
        test_ctx(),
    )
    .await
    .expect("force switch must succeed");
    assert_eq!(result["active_id"], json!(b));
    assert_eq!(result["prior_id"], json!(a));
}

/// Activating an id that names no existing workstream must map to `-32002
/// not_found`.
#[tokio::test]
async fn activate_unknown_id_maps_to_not_found() {
    let (store, _dir) = shared_store().await;
    let unknown = WorkstreamId::new();

    let err = activate(&store, json!({"id": unknown.to_string()}), test_ctx())
        .await
        .expect_err("must not find id");
    assert_eq!(err.code, -32002);
}

/// A malformed UUID string in `id` must map to `-32602 Invalid params`, not
/// panic.
#[tokio::test]
async fn activate_malformed_id_maps_to_invalid_params() {
    let (store, _dir) = shared_store().await;

    let err = activate(&store, json!({"id": "not-a-uuid"}), test_ctx())
        .await
        .expect_err("must reject malformed id");
    assert_eq!(err.code, trusty_mcp::error_codes::INVALID_PARAMS);
}

/// Deactivating the currently active workstream must clear the pointer and
/// return `{}`.
#[tokio::test]
async fn deactivate_active_clears_pointer() {
    let (store, _dir) = shared_store().await;
    let id = seed_workstream(&store, "t").await;
    activate(&store, json!({"id": id.to_string()}), test_ctx())
        .await
        .expect("activate");

    let result = deactivate(&store, json!({"id": id.to_string()}), test_ctx())
        .await
        .expect("deactivate must succeed");
    assert_eq!(result, json!({}));
    assert_eq!(
        store.lock().await.active_workstream_id().await.unwrap(),
        None
    );
}

/// Deactivating an idle (non-active) workstream must be an idempotent
/// success, not an error.
#[tokio::test]
async fn deactivate_idle_is_idempotent_noop() {
    let (store, _dir) = shared_store().await;
    let a = seed_workstream(&store, "a").await;
    let b = seed_workstream(&store, "b").await;
    activate(&store, json!({"id": a.to_string()}), test_ctx())
        .await
        .expect("activate a");

    let result = deactivate(&store, json!({"id": b.to_string()}), test_ctx())
        .await
        .expect("deactivate idle must succeed");
    assert_eq!(result, json!({}));
    assert_eq!(
        store.lock().await.active_workstream_id().await.unwrap(),
        Some(a)
    );
}

/// The active pointer must survive a fresh `WorkstreamStore::load` of the
/// same file after going through the RPC layer (AC-1.4), not just the
/// `activation` module's own direct-store test.
#[tokio::test]
async fn activation_persists_across_store_reload_through_rpc() {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("workstreams-test.json");
    let store = WorkstreamStore::load(&path)
        .await
        .expect("load fresh store");
    let shared: SharedWorkstreamStore = std::sync::Arc::new(tokio::sync::Mutex::new(store));
    let id = seed_workstream(&shared, "t").await;
    activate(&shared, json!({"id": id.to_string()}), test_ctx())
        .await
        .expect("activate");

    let mut reloaded = WorkstreamStore::load(&path).await.expect("reload");
    assert_eq!(
        reloaded.active_workstream_id().await.unwrap(),
        Some(id),
        "active pointer must persist across a fresh load"
    );
}

#[tokio::test]
async fn create_returns_new_id() {
    let (store, _dir) = shared_store().await;
    let result = create(&store, json!({"name": "Token rotation"}), test_ctx())
        .await
        .expect("create");
    assert!(result["id"].is_string());
}

#[tokio::test]
async fn create_without_name_defaults_to_empty() {
    let (store, _dir) = shared_store().await;
    let result = create(&store, json!({}), test_ctx()).await.expect("create");
    let id = result["id"].clone();
    let ws = get(&store, json!({"id": id}), test_ctx())
        .await
        .expect("get");
    assert_eq!(ws["name"], "");
}

#[tokio::test]
async fn get_returns_workstream_with_state() {
    let (store, _dir) = shared_store().await;
    let created = create(&store, json!({"name": "A"}), test_ctx())
        .await
        .expect("create");
    let id = created["id"].clone();

    let ws = get(&store, json!({"id": id}), test_ctx())
        .await
        .expect("get");
    assert_eq!(ws["name"], "A");
    assert_eq!(ws["state"], "idle");
    assert!(ws["session_ids"].as_array().unwrap().is_empty());
}

#[tokio::test]
async fn get_unknown_id_maps_to_not_found() {
    let (store, _dir) = shared_store().await;
    let err = get(
        &store,
        json!({"id": WorkstreamId::new().to_string()}),
        test_ctx(),
    )
    .await
    .unwrap_err();
    assert_eq!(err.code, -32002);
}

#[tokio::test]
async fn get_invalid_params_maps_to_invalid_params() {
    let (store, _dir) = shared_store().await;
    let err = get(&store, json!({"id": "not-a-uuid"}), test_ctx())
        .await
        .unwrap_err();
    assert_eq!(err.code, trusty_mcp::error_codes::INVALID_PARAMS);
}

#[tokio::test]
async fn list_returns_active_workstream_id_and_records() {
    let (store, _dir) = shared_store().await;
    let a = create(&store, json!({"name": "A"}), test_ctx())
        .await
        .expect("create A")["id"]
        .clone();
    create(&store, json!({"name": "B"}), test_ctx())
        .await
        .expect("create B");

    let a_id: WorkstreamId = serde_json::from_value(a.clone()).unwrap();
    store
        .lock()
        .await
        .set_active(Some(a_id))
        .await
        .expect("activate A");

    let result = list(&store, json!({}), test_ctx()).await.expect("list");
    assert_eq!(result["active_workstream_id"], a);
    let workstreams = result["workstreams"].as_array().unwrap();
    assert_eq!(workstreams.len(), 2);
    let a_view = workstreams.iter().find(|w| w["id"] == a).unwrap();
    assert_eq!(a_view["state"], "active");
}

#[tokio::test]
async fn list_missing_params_defaults_to_include_closed_false() {
    let (store, _dir) = shared_store().await;
    let result = list(&store, Value::Null, test_ctx()).await.expect("list");
    assert!(result["workstreams"].as_array().unwrap().is_empty());
}

#[tokio::test]
async fn list_default_excludes_closed() {
    let (store, _dir) = shared_store().await;
    let id = create(&store, json!({"name": "A"}), test_ctx())
        .await
        .expect("create")["id"]
        .clone();
    close(&store, json!({"id": id}), test_ctx())
        .await
        .expect("close");

    let result = list(&store, json!({}), test_ctx()).await.expect("list");
    assert!(
        result["workstreams"].as_array().unwrap().is_empty(),
        "closed workstream must be excluded by default"
    );
}

#[tokio::test]
async fn list_include_closed_true_includes_closed() {
    let (store, _dir) = shared_store().await;
    let id = create(&store, json!({"name": "A"}), test_ctx())
        .await
        .expect("create")["id"]
        .clone();
    close(&store, json!({"id": id}), test_ctx())
        .await
        .expect("close");

    let result = list(&store, json!({"include_closed": true}), test_ctx())
        .await
        .expect("list");
    let workstreams = result["workstreams"].as_array().unwrap();
    assert_eq!(workstreams.len(), 1);
    assert_eq!(workstreams[0]["state"], "closed");
}

#[tokio::test]
async fn close_succeeds_and_clears_active_pointer() {
    let (store, _dir) = shared_store().await;
    let id = create(&store, json!({"name": "A"}), test_ctx())
        .await
        .expect("create")["id"]
        .clone();
    let ws_id: WorkstreamId = serde_json::from_value(id.clone()).unwrap();
    store
        .lock()
        .await
        .set_active(Some(ws_id))
        .await
        .expect("activate");

    let result = close(&store, json!({"id": id}), test_ctx())
        .await
        .expect("close");
    assert_eq!(result, json!({}));

    let list_result = list(&store, json!({"include_closed": true}), test_ctx())
        .await
        .expect("list");
    assert_eq!(list_result["active_workstream_id"], Value::Null);
}

/// (issue #3297) `workstream.close` must publish
/// `Event::WorkstreamStateInferred{state: "closed"}`.
#[tokio::test]
async fn close_publishes_state_inferred() {
    let (store, _dir) = shared_store().await;
    let id = create(&store, json!({"name": "A"}), test_ctx())
        .await
        .expect("create")["id"]
        .clone();
    let ws_id: WorkstreamId = serde_json::from_value(id.clone()).unwrap();

    let mut rx = crate::events::subscribe();
    close(&store, json!({"id": id}), test_ctx())
        .await
        .expect("close");

    // `crate::events::bus()` is a process-wide singleton shared by every
    // concurrently-running test (issue #3297 CI: `cargo test` runs tests in
    // parallel by default, so a raw `rx.recv().await` can observe another
    // test's unrelated envelope first) — loop past anything that doesn't
    // name THIS test's own workstream id, mirroring
    // `workstreams::activation_tests::next_state_inferred_for`.
    let target = ws_id.to_string();
    let (state, _reason) = tokio::time::timeout(std::time::Duration::from_secs(2), async {
        loop {
            let envelope = rx.recv().await.expect("event bus channel closed");
            if let crate::events::Event::WorkstreamStateInferred {
                workstream_id,
                state,
                reason,
            } = envelope.event
                && workstream_id == target
            {
                return (state, reason);
            }
        }
    })
    .await
    .expect("timed out waiting for WorkstreamStateInferred naming this workstream");
    assert_eq!(state, "closed");
}

#[tokio::test]
async fn close_unknown_id_maps_to_not_found() {
    let (store, _dir) = shared_store().await;
    let err = close(
        &store,
        json!({"id": WorkstreamId::new().to_string()}),
        test_ctx(),
    )
    .await
    .unwrap_err();
    assert_eq!(err.code, -32002);
}

/// `workstream.rename` (issue #3300, Phase C) must overwrite `name` and
/// return the updated view.
#[tokio::test]
async fn rename_succeeds_and_returns_updated_view() {
    let (store, _dir) = shared_store().await;
    let id = create(&store, json!({"name": "A"}), test_ctx())
        .await
        .expect("create")["id"]
        .clone();

    let renamed = rename(&store, json!({"id": id, "name": "B"}), test_ctx())
        .await
        .expect("rename");
    assert_eq!(renamed["name"], "B");
    assert_eq!(renamed["state"], "idle");
}

#[tokio::test]
async fn rename_unknown_id_maps_to_not_found() {
    let (store, _dir) = shared_store().await;
    let err = rename(
        &store,
        json!({"id": WorkstreamId::new().to_string(), "name": "B"}),
        test_ctx(),
    )
    .await
    .unwrap_err();
    assert_eq!(err.code, -32002);
}

#[tokio::test]
async fn rename_invalid_params_maps_to_invalid_params() {
    let (store, _dir) = shared_store().await;
    let err = rename(&store, json!({"id": "not-a-uuid", "name": "B"}), test_ctx())
        .await
        .unwrap_err();
    assert_eq!(err.code, trusty_mcp::error_codes::INVALID_PARAMS);
}

// -- resolve_validate_bind / check_workstream_immutable (issue #3298;
//    validate-before-mint atomicity per PR #3354 code-critic HIGH 1 & 2) --

/// A mint closure that returns a fixed id and records whether it ran — the
/// critic's required property is precisely "the mint must NOT run on any
/// rejected bind".
fn tracked_mint(
    id: &str,
) -> (
    impl FnOnce() -> String,
    std::sync::Arc<std::sync::atomic::AtomicBool>,
) {
    let minted = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let flag = minted.clone();
    let id = id.to_string();
    (
        move || {
            flag.store(true, std::sync::atomic::Ordering::SeqCst);
            id
        },
        minted,
    )
}

#[tokio::test]
async fn resolve_validate_bind_explicit_wins_over_active() {
    let (store, _dir) = shared_store().await;
    let active = seed_workstream(&store, "active").await;
    let explicit = seed_workstream(&store, "explicit").await;
    activation::activate(&store, active, false)
        .await
        .expect("activate");

    let (session_id, bound) =
        resolve_validate_bind(&store, Some(&explicit.to_string()), "test", || {
            "s-1".to_string()
        })
        .await
        .expect("resolve");
    assert_eq!(session_id, "s-1");
    assert_eq!(bound, Some(explicit));
    let ws = store.lock().await.get(explicit).await.expect("get");
    assert_eq!(ws.session_ids, vec!["s-1".to_string()]);
}

#[tokio::test]
async fn resolve_validate_bind_falls_back_to_active() {
    let (store, _dir) = shared_store().await;
    let active = seed_workstream(&store, "active").await;
    activation::activate(&store, active, false)
        .await
        .expect("activate");

    let (_, bound) = resolve_validate_bind(&store, None, "test", || "s-1".to_string())
        .await
        .expect("resolve");
    assert_eq!(bound, Some(active));
}

#[tokio::test]
async fn resolve_validate_bind_none_when_nothing_active() {
    let (store, _dir) = shared_store().await;
    let (session_id, bound) = resolve_validate_bind(&store, None, "test", || "s-1".to_string())
        .await
        .expect("resolve");
    assert_eq!(session_id, "s-1", "the projectless path must still mint");
    assert_eq!(
        bound, None,
        "no explicit param and nothing active must stay projectless"
    );
}

#[tokio::test]
async fn resolve_validate_bind_rejects_closed_target_without_minting() {
    let (store, _dir) = shared_store().await;
    let id = seed_workstream(&store, "closed").await;
    store.lock().await.close(id).await.expect("close");
    let (mint, minted) = tracked_mint("s-1");

    let err = resolve_validate_bind(&store, Some(&id.to_string()), "test", mint)
        .await
        .unwrap_err();
    assert_eq!(err.code, -32003);
    assert!(
        !minted.load(std::sync::atomic::Ordering::SeqCst),
        "a rejected bind must never mint a session (PR #3354 HIGH)"
    );
}

#[tokio::test]
async fn resolve_validate_bind_rejects_unknown_id_without_minting() {
    let (store, _dir) = shared_store().await;
    let (mint, minted) = tracked_mint("s-1");

    let err = resolve_validate_bind(&store, Some(&WorkstreamId::new().to_string()), "test", mint)
        .await
        .unwrap_err();
    assert_eq!(err.code, -32002);
    assert!(
        !minted.load(std::sync::atomic::Ordering::SeqCst),
        "a rejected bind must never mint a session (PR #3354 HIGH)"
    );
}

#[tokio::test]
async fn resolve_validate_bind_rejects_malformed_id_without_minting() {
    let (store, _dir) = shared_store().await;
    let (mint, minted) = tracked_mint("s-1");

    let err = resolve_validate_bind(&store, Some("not-a-uuid"), "test", mint)
        .await
        .unwrap_err();
    assert_eq!(err.code, -32602);
    assert!(
        !minted.load(std::sync::atomic::Ordering::SeqCst),
        "a rejected bind must never mint a session (PR #3354 HIGH)"
    );
}

/// A rejected AMBIENT target (the active workstream was closed out from
/// under the pointer) must likewise reject without minting — the ambient
/// path validates identically to the explicit one.
#[tokio::test]
async fn resolve_validate_bind_rejects_closed_ambient_target_without_minting() {
    let (store, _dir) = shared_store().await;
    let active = seed_workstream(&store, "active").await;
    activation::activate(&store, active, false)
        .await
        .expect("activate");
    // `close` clears the active pointer, so force the dangling-pointer shape
    // directly at the store level: close, then restore the pointer as a
    // simulated concurrent-writer artifact.
    store.lock().await.close(active).await.expect("close");
    store
        .lock()
        .await
        .set_active(Some(active))
        .await
        .expect("restore pointer");
    let (mint, minted) = tracked_mint("s-1");

    let err = resolve_validate_bind(&store, None, "test", mint)
        .await
        .unwrap_err();
    assert_eq!(err.code, -32003);
    assert!(
        !minted.load(std::sync::atomic::Ordering::SeqCst),
        "a rejected ambient bind must never mint a session"
    );
}

#[test]
fn check_workstream_immutable_allows_none() {
    let existing = Some(WorkstreamId::new());
    assert!(check_workstream_immutable(existing, None, "test").is_ok());
}

#[test]
fn check_workstream_immutable_allows_restating_same_id() {
    let id = WorkstreamId::new();
    assert!(check_workstream_immutable(Some(id), Some(&id.to_string()), "test").is_ok());
}

#[test]
fn check_workstream_immutable_rejects_mismatch() {
    let existing = WorkstreamId::new();
    let requested = WorkstreamId::new();
    let err = check_workstream_immutable(Some(existing), Some(&requested.to_string()), "test")
        .unwrap_err();
    assert_eq!(err.code, -32003);
}

#[test]
fn check_workstream_immutable_rejects_binding_an_unbound_session() {
    let requested = WorkstreamId::new();
    let err = check_workstream_immutable(None, Some(&requested.to_string()), "test").unwrap_err();
    assert_eq!(err.code, -32003);
}