tandem-server 0.7.2

HTTP server for Tandem engine APIs
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
// Copyright (c) 2026 Frumu LTD
// Licensed under the Business Source License 1.1

fn init_git_repo() -> std::path::PathBuf {
    let repo_root = std::env::temp_dir().join(format!("tandem-worktree-test-{}", Uuid::new_v4()));
    std::fs::create_dir_all(&repo_root).expect("create repo dir");
    let status = Command::new("git")
        .args(["init"])
        .current_dir(&repo_root)
        .status()
        .expect("git init");
    assert!(status.success());
    let status = Command::new("git")
        .args(["config", "user.email", "tests@tandem.local"])
        .current_dir(&repo_root)
        .status()
        .expect("git config email");
    assert!(status.success());
    let status = Command::new("git")
        .args(["config", "user.name", "Tandem Tests"])
        .current_dir(&repo_root)
        .status()
        .expect("git config name");
    assert!(status.success());
    std::fs::write(repo_root.join("README.md"), "# test\n").expect("seed readme");
    let status = Command::new("git")
        .args(["add", "README.md"])
        .current_dir(&repo_root)
        .status()
        .expect("git add");
    assert!(status.success());
    let status = Command::new("git")
        .args(["commit", "-m", "init"])
        .current_dir(&repo_root)
        .status()
        .expect("git commit");
    assert!(status.success());
    repo_root
}

async fn insert_test_lease(state: &AppState, lease_id: &str) {
    let now = crate::now_ms();
    state.engine_leases.write().await.insert(
        lease_id.to_string(),
        crate::EngineLease {
            lease_id: lease_id.to_string(),
            client_id: "tests".to_string(),
            client_type: "http-test".to_string(),
            acquired_at_ms: now,
            last_renewed_at_ms: now,
            ttl_ms: 60_000,
            tenant_context: tandem_types::TenantContext::local_implicit(),
        },
    );
}

#[tokio::test]
async fn managed_worktree_endpoints_are_idempotent_and_cleanup_branch() {
    let state = test_state().await;
    let app = app_router(state.clone());
    let repo_root = init_git_repo();
    let repo_root_str = repo_root.to_string_lossy().to_string();
    insert_test_lease(&state, "lease-1").await;

    let create_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root_str,
                "task_id": "task-a",
                "owner_run_id": "run-1",
                "lease_id": "lease-1",
                "managed": true
            })
            .to_string(),
        ))
        .expect("create worktree request");
    let create_resp = app
        .clone()
        .oneshot(create_req)
        .await
        .expect("create worktree response");
    assert_eq!(create_resp.status(), StatusCode::OK);
    let create_payload: Value = serde_json::from_slice(
        &to_bytes(create_resp.into_body(), usize::MAX)
            .await
            .expect("create worktree body"),
    )
    .expect("create worktree json");
    assert_eq!(
        create_payload.get("ok").and_then(Value::as_bool),
        Some(true)
    );
    assert_eq!(
        create_payload.get("managed").and_then(Value::as_bool),
        Some(true)
    );
    assert_eq!(
        create_payload.get("reused").and_then(Value::as_bool),
        Some(false)
    );
    let worktree_path = create_payload
        .get("path")
        .and_then(Value::as_str)
        .expect("worktree path")
        .to_string();
    let branch = create_payload
        .get("branch")
        .and_then(Value::as_str)
        .expect("branch")
        .to_string();
    assert!(worktree_path.contains("/.tandem/worktrees/"));
    assert!(std::path::Path::new(&worktree_path).exists());

    let create_again_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "task_id": "task-a",
                "owner_run_id": "run-1",
                "lease_id": "lease-1",
                "managed": true
            })
            .to_string(),
        ))
        .expect("create worktree again request");
    let create_again_resp = app
        .clone()
        .oneshot(create_again_req)
        .await
        .expect("create worktree again response");
    assert_eq!(create_again_resp.status(), StatusCode::OK);
    let create_again_payload: Value = serde_json::from_slice(
        &to_bytes(create_again_resp.into_body(), usize::MAX)
            .await
            .expect("create worktree again body"),
    )
    .expect("create worktree again json");
    assert_eq!(
        create_again_payload.get("reused").and_then(Value::as_bool),
        Some(true)
    );
    assert_eq!(
        create_again_payload.get("path").and_then(Value::as_str),
        Some(worktree_path.as_str())
    );
    assert_eq!(
        create_again_payload.get("branch").and_then(Value::as_str),
        Some(branch.as_str())
    );

    let list_req = Request::builder()
        .method("GET")
        .extension(direct_loopback_peer())
        .uri(format!(
            "/worktree?repo_root={}&managed_only=true",
            repo_root.to_string_lossy()
        ))
        .body(Body::empty())
        .expect("list worktrees request");
    let list_resp = app
        .clone()
        .oneshot(list_req)
        .await
        .expect("list worktrees response");
    assert_eq!(list_resp.status(), StatusCode::OK);
    let list_payload: Value = serde_json::from_slice(
        &to_bytes(list_resp.into_body(), usize::MAX)
            .await
            .expect("list worktrees body"),
    )
    .expect("list worktrees json");
    assert!(list_payload
        .as_array()
        .is_some_and(|rows| rows.iter().any(|row| {
            row.get("path").and_then(Value::as_str) == Some(worktree_path.as_str())
                && row.get("task_id").and_then(Value::as_str) == Some("task-a")
                && row.get("owner_run_id").and_then(Value::as_str) == Some("run-1")
                && row.get("lease_id").and_then(Value::as_str) == Some("lease-1")
                && row.get("managed").and_then(Value::as_bool) == Some(true)
        })));

    let delete_req = Request::builder()
        .method("DELETE")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "path": worktree_path,
                "lease_id": "lease-1"
            })
            .to_string(),
        ))
        .expect("delete worktree request");
    let delete_resp = app
        .clone()
        .oneshot(delete_req)
        .await
        .expect("delete worktree response");
    assert_eq!(delete_resp.status(), StatusCode::OK);
    let delete_payload: Value = serde_json::from_slice(
        &to_bytes(delete_resp.into_body(), usize::MAX)
            .await
            .expect("delete worktree body"),
    )
    .expect("delete worktree json");
    assert_eq!(
        delete_payload.get("ok").and_then(Value::as_bool),
        Some(true)
    );
    assert_eq!(
        delete_payload
            .get("branch_deleted")
            .and_then(Value::as_bool),
        Some(true)
    );
    assert!(!std::path::Path::new(
        delete_payload
            .get("path")
            .and_then(Value::as_str)
            .expect("deleted path")
    )
    .exists());
    let branch_output = Command::new("git")
        .args(["branch", "--list", &branch])
        .current_dir(&repo_root)
        .output()
        .expect("git branch list");
    assert!(String::from_utf8_lossy(&branch_output.stdout)
        .trim()
        .is_empty());

    let _ = std::fs::remove_dir_all(repo_root);
}

#[tokio::test]
async fn managed_worktree_create_rejects_unknown_lease() {
    let state = test_state().await;
    let app = app_router(state);
    let repo_root = init_git_repo();

    let create_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "task_id": "task-b",
                "owner_run_id": "run-2",
                "lease_id": "missing-lease",
                "managed": true
            })
            .to_string(),
        ))
        .expect("create worktree request");
    let create_resp = app
        .oneshot(create_req)
        .await
        .expect("create worktree response");
    assert_eq!(create_resp.status(), StatusCode::CONFLICT);

    let _ = std::fs::remove_dir_all(repo_root);
}

#[tokio::test]
async fn stale_worktree_cleanup_preserves_unknown_restart_worktrees() {
    let state = test_state().await;
    let app = app_router(state.clone());
    let repo_root = init_git_repo();
    let repo_root_str = repo_root.to_string_lossy().to_string();
    insert_test_lease(&state, "lease-cleanup").await;

    let create_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root_str,
                "task_id": "task-cleanup",
                "owner_run_id": "run-cleanup",
                "lease_id": "lease-cleanup",
                "managed": true
            })
            .to_string(),
        ))
        .expect("create worktree request");
    let create_resp = app
        .clone()
        .oneshot(create_req)
        .await
        .expect("create worktree response");
    assert_eq!(create_resp.status(), StatusCode::OK);
    let create_payload: Value = serde_json::from_slice(
        &to_bytes(create_resp.into_body(), usize::MAX)
            .await
            .expect("create worktree body"),
    )
    .expect("create worktree json");
    let worktree_path = create_payload
        .get("path")
        .and_then(Value::as_str)
        .expect("worktree path")
        .to_string();
    let branch = create_payload
        .get("branch")
        .and_then(Value::as_str)
        .expect("branch")
        .to_string();
    assert!(std::path::Path::new(&worktree_path).exists());

    // Simulate a restarted process that lost the in-memory managed_worktrees map.
    state.managed_worktrees.write().await.clear();

    let cleanup_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree/cleanup")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
            })
            .to_string(),
        ))
        .expect("cleanup worktree request");
    let cleanup_resp = app
        .clone()
        .oneshot(cleanup_req)
        .await
        .expect("cleanup worktree response");
    assert_eq!(cleanup_resp.status(), StatusCode::OK);
    assert!(std::path::Path::new(&worktree_path).exists());

    let branch_output = Command::new("git")
        .args(["branch", "--list", &branch])
        .current_dir(&repo_root)
        .output()
        .expect("git branch list");
    assert!(!String::from_utf8_lossy(&branch_output.stdout)
        .trim()
        .is_empty());

    let remove = Command::new("git")
        .args([
            "-C",
            &repo_root_str,
            "worktree",
            "remove",
            "--force",
            &worktree_path,
        ])
        .output()
        .expect("remove preserved test worktree");
    assert!(remove.status.success());
    let delete_branch = Command::new("git")
        .args(["-C", &repo_root_str, "branch", "-D", &branch])
        .output()
        .expect("delete preserved test worktree branch");
    assert!(delete_branch.status.success());
    let _ = std::fs::remove_dir_all(repo_root);
}

#[tokio::test]
async fn managed_worktree_create_rejects_external_path_override() {
    let state = test_state().await;
    let app = app_router(state.clone());
    let repo_root = init_git_repo();
    insert_test_lease(&state, "lease-path-boundary").await;
    let external_path = std::env::temp_dir().join(format!("tandem-external-{}", Uuid::new_v4()));

    let create_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "path": external_path.to_string_lossy(),
                "task_id": "task-path",
                "owner_run_id": "run-path",
                "lease_id": "lease-path-boundary",
                "managed": true
            })
            .to_string(),
        ))
        .expect("create worktree request");
    let create_resp = app
        .oneshot(create_req)
        .await
        .expect("create worktree response");
    assert_eq!(create_resp.status(), StatusCode::BAD_REQUEST);
    assert!(!external_path.exists());

    let _ = std::fs::remove_dir_all(repo_root);
}

#[tokio::test]
async fn managed_worktree_mutations_require_matching_active_lease() {
    let state = test_state().await;
    let app = app_router(state.clone());
    let repo_root = init_git_repo();
    insert_test_lease(&state, "lease-1").await;

    let create_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "task_id": "task-c",
                "owner_run_id": "run-3",
                "lease_id": "lease-1",
                "managed": true
            })
            .to_string(),
        ))
        .expect("create worktree request");
    let create_resp = app
        .clone()
        .oneshot(create_req)
        .await
        .expect("create worktree response");
    let create_payload: Value = serde_json::from_slice(
        &to_bytes(create_resp.into_body(), usize::MAX)
            .await
            .expect("create worktree body"),
    )
    .expect("create worktree json");
    let worktree_path = create_payload
        .get("path")
        .and_then(Value::as_str)
        .expect("worktree path")
        .to_string();

    let reset_without_lease = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree/reset")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "path": worktree_path
            })
            .to_string(),
        ))
        .expect("reset worktree request");
    let reset_resp = app
        .clone()
        .oneshot(reset_without_lease)
        .await
        .expect("reset worktree response");
    assert_eq!(reset_resp.status(), StatusCode::CONFLICT);

    let delete_wrong_lease = Request::builder()
        .method("DELETE")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "path": worktree_path,
                "lease_id": "lease-other"
            })
            .to_string(),
        ))
        .expect("delete wrong lease request");
    let delete_wrong_resp = app
        .clone()
        .oneshot(delete_wrong_lease)
        .await
        .expect("delete wrong lease response");
    assert_eq!(delete_wrong_resp.status(), StatusCode::CONFLICT);

    let delete_req = Request::builder()
        .method("DELETE")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "path": worktree_path,
                "lease_id": "lease-1"
            })
            .to_string(),
        ))
        .expect("delete worktree request");
    let delete_resp = app
        .clone()
        .oneshot(delete_req)
        .await
        .expect("delete worktree response");
    assert_eq!(delete_resp.status(), StatusCode::OK);

    let _ = std::fs::remove_dir_all(repo_root);
}

#[tokio::test]
async fn releasing_lease_cleans_up_managed_worktrees() {
    let state = test_state().await;
    let app = app_router(state.clone());
    let repo_root = init_git_repo();
    insert_test_lease(&state, "lease-cleanup").await;

    let create_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "task_id": "task-d",
                "owner_run_id": "run-4",
                "lease_id": "lease-cleanup",
                "managed": true
            })
            .to_string(),
        ))
        .expect("create worktree request");
    let create_resp = app
        .clone()
        .oneshot(create_req)
        .await
        .expect("create worktree response");
    let create_payload: Value = serde_json::from_slice(
        &to_bytes(create_resp.into_body(), usize::MAX)
            .await
            .expect("create worktree body"),
    )
    .expect("create worktree json");
    let worktree_path = create_payload
        .get("path")
        .and_then(Value::as_str)
        .expect("worktree path")
        .to_string();
    let branch = create_payload
        .get("branch")
        .and_then(Value::as_str)
        .expect("branch")
        .to_string();

    let release_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/global/lease/release")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({ "lease_id": "lease-cleanup" }).to_string(),
        ))
        .expect("release request");
    let release_resp = app
        .clone()
        .oneshot(release_req)
        .await
        .expect("release response");
    assert_eq!(release_resp.status(), StatusCode::OK);
    let release_payload: Value = serde_json::from_slice(
        &to_bytes(release_resp.into_body(), usize::MAX)
            .await
            .expect("release body"),
    )
    .expect("release json");
    assert_eq!(
        release_payload.get("ok").and_then(Value::as_bool),
        Some(true)
    );
    assert!(release_payload
        .get("released_worktrees")
        .and_then(Value::as_array)
        .is_some_and(|rows| rows
            .iter()
            .any(|row| row.as_str() == Some(worktree_path.as_str()))));
    assert!(!std::path::Path::new(&worktree_path).exists());

    let branch_output = Command::new("git")
        .args(["branch", "--list", &branch])
        .current_dir(&repo_root)
        .output()
        .expect("git branch list");
    assert!(String::from_utf8_lossy(&branch_output.stdout)
        .trim()
        .is_empty());

    let _ = std::fs::remove_dir_all(repo_root);
}

#[tokio::test]
async fn releasing_lease_retries_retained_branch_cleanup_after_lease_removal() {
    let state = test_state().await;
    let app = app_router(state.clone());
    let repo_root = init_git_repo();
    let repo_root_str = repo_root.to_string_lossy().to_string();
    insert_test_lease(&state, "lease-cleanup-retry").await;

    let create_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root_str,
                "task_id": "task-cleanup-retry",
                "owner_run_id": "run-cleanup-retry",
                "lease_id": "lease-cleanup-retry",
                "managed": true
            })
            .to_string(),
        ))
        .expect("create worktree request");
    let create_resp = app
        .clone()
        .oneshot(create_req)
        .await
        .expect("create worktree response");
    assert_eq!(create_resp.status(), StatusCode::OK);
    let create_payload: Value = serde_json::from_slice(
        &to_bytes(create_resp.into_body(), usize::MAX)
            .await
            .expect("create worktree body"),
    )
    .expect("create worktree json");
    let worktree_id = create_payload
        .get("worktree_id")
        .and_then(Value::as_str)
        .expect("worktree id")
        .to_string();
    let worktree_path = create_payload
        .get("path")
        .and_then(Value::as_str)
        .expect("worktree path")
        .to_string();
    let branch = create_payload
        .get("branch")
        .and_then(Value::as_str)
        .expect("branch")
        .to_string();
    let duplicate_path =
        std::env::temp_dir().join(format!("tandem-worktree-duplicate-{}", Uuid::new_v4()));
    let duplicate_path_str = duplicate_path.to_string_lossy().to_string();
    let duplicate = Command::new("git")
        .args([
            "-C",
            &repo_root_str,
            "worktree",
            "add",
            "--force",
            &duplicate_path_str,
            &branch,
        ])
        .output()
        .expect("create duplicate branch checkout");
    assert!(
        duplicate.status.success(),
        "duplicate worktree creation failed: {}",
        String::from_utf8_lossy(&duplicate.stderr)
    );

    let release = |app: axum::Router| async move {
        let request = Request::builder()
            .method("POST")
            .extension(direct_loopback_peer())
            .uri("/global/lease/release")
            .header("content-type", "application/json")
            .body(Body::from(
                json!({ "lease_id": "lease-cleanup-retry" }).to_string(),
            ))
            .expect("release request");
        let response = app.oneshot(request).await.expect("release response");
        assert_eq!(response.status(), StatusCode::OK);
        serde_json::from_slice::<Value>(
            &to_bytes(response.into_body(), usize::MAX)
                .await
                .expect("release body"),
        )
        .expect("release json")
    };

    let first_release = release(app.clone()).await;
    assert_eq!(
        first_release.get("ok").and_then(Value::as_bool),
        Some(false)
    );
    assert_eq!(
        first_release
            .get("released_worktree_failure_count")
            .and_then(Value::as_u64),
        Some(1)
    );
    assert!(!state
        .engine_leases
        .read()
        .await
        .contains_key("lease-cleanup-retry"));
    assert!(!std::path::Path::new(&worktree_path).exists());
    assert!(state
        .managed_worktrees
        .read()
        .await
        .contains_key(&worktree_id));

    let remove_duplicate = Command::new("git")
        .args([
            "-C",
            &repo_root_str,
            "worktree",
            "remove",
            "--force",
            &duplicate_path_str,
        ])
        .output()
        .expect("remove duplicate branch checkout");
    assert!(
        remove_duplicate.status.success(),
        "duplicate worktree removal failed: {}",
        String::from_utf8_lossy(&remove_duplicate.stderr)
    );

    let retry_release = release(app).await;
    assert_eq!(
        retry_release.get("ok").and_then(Value::as_bool),
        Some(true)
    );
    assert_eq!(
        retry_release
            .get("released_worktree_failure_count")
            .and_then(Value::as_u64),
        Some(0)
    );
    assert!(!state
        .managed_worktrees
        .read()
        .await
        .contains_key(&worktree_id));
    let branch_output = Command::new("git")
        .args(["branch", "--list", &branch])
        .current_dir(&repo_root)
        .output()
        .expect("git branch list");
    assert!(String::from_utf8_lossy(&branch_output.stdout)
        .trim()
        .is_empty());

    let _ = std::fs::remove_dir_all(duplicate_path);
    let _ = std::fs::remove_dir_all(repo_root);
}

#[tokio::test]
async fn expired_leases_are_pruned_and_cleanup_managed_worktrees() {
    let state = test_state().await;
    let app = app_router(state.clone());
    let repo_root = init_git_repo();
    let now = crate::now_ms();
    state.engine_leases.write().await.insert(
        "lease-expired".to_string(),
        crate::EngineLease {
            lease_id: "lease-expired".to_string(),
            client_id: "tests".to_string(),
            client_type: "http-test".to_string(),
            acquired_at_ms: now.saturating_sub(120_000),
            last_renewed_at_ms: now.saturating_sub(120_000),
            ttl_ms: 5_000,
            tenant_context: tandem_types::TenantContext::local_implicit(),
        },
    );

    let create_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "task_id": "task-e",
                "owner_run_id": "run-5",
                "lease_id": "lease-expired",
                "managed": true
            })
            .to_string(),
        ))
        .expect("create worktree request");
    let create_resp = app
        .clone()
        .oneshot(create_req)
        .await
        .expect("create worktree response");
    assert_eq!(create_resp.status(), StatusCode::CONFLICT);

    insert_test_lease(&state, "lease-fresh").await;
    let create_req = Request::builder()
        .method("POST")
        .extension(direct_loopback_peer())
        .uri("/worktree")
        .header("content-type", "application/json")
        .body(Body::from(
            json!({
                "repo_root": repo_root.to_string_lossy(),
                "task_id": "task-f",
                "owner_run_id": "run-6",
                "lease_id": "lease-fresh",
                "managed": true
            })
            .to_string(),
        ))
        .expect("create worktree request");
    let create_resp = app
        .clone()
        .oneshot(create_req)
        .await
        .expect("create worktree response");
    let create_payload: Value = serde_json::from_slice(
        &to_bytes(create_resp.into_body(), usize::MAX)
            .await
            .expect("create worktree body"),
    )
    .expect("create worktree json");
    let worktree_path = create_payload
        .get("path")
        .and_then(Value::as_str)
        .expect("worktree path")
        .to_string();
    let branch = create_payload
        .get("branch")
        .and_then(Value::as_str)
        .expect("branch")
        .to_string();

    {
        let mut leases = state.engine_leases.write().await;
        let lease = leases.get_mut("lease-fresh").expect("fresh lease present");
        lease.last_renewed_at_ms = now.saturating_sub(120_000);
        lease.ttl_ms = 5_000;
    }

    let health_req = Request::builder()
        .method("GET")
        .uri("/global/health")
        .body(Body::empty())
        .expect("health request");
    let health_resp = app
        .clone()
        .oneshot(health_req)
        .await
        .expect("health response");
    assert_eq!(health_resp.status(), StatusCode::OK);
    assert!(!std::path::Path::new(&worktree_path).exists());
    let branch_output = Command::new("git")
        .args(["branch", "--list", &branch])
        .current_dir(&repo_root)
        .output()
        .expect("git branch list");
    assert!(String::from_utf8_lossy(&branch_output.stdout)
        .trim()
        .is_empty());

    let _ = std::fs::remove_dir_all(repo_root);
}