cflx 0.6.327

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
//! Repository-local tests for the `/api/v2` worktree contract.
//!
//! Fast and boundary-free: opaque identity, redaction, the closed command
//! shapes, and the inherited v2 guards are all decidable without a repository.
//! Everything that genuinely needs real Git — teardown, dirty refusal, conflict
//! preservation, identity retirement across a real recreate — lives in the heavy
//! `tests/e2e_git_worktree_tests.rs` suite instead.

use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use axum::http::StatusCode;

use crate::web::remote_control_api::dto::{CommandSpec, ErrorCode, SUPPORTED_COMMANDS};
use crate::web::remote_control_api::executor::{CommandFailure, ExecutionSummary};
use crate::web::remote_control_api::worktrees::{
    map_worktree_error, repository_correlation_id, repository_relative_display, WorktreeKey,
    WorktreeListing, WorktreeOperations, WorktreeRegistry, WorktreeResource, WORKTREE_OPERATIONS,
};
use crate::worktree_ops::service::{
    DirtyState, WorktreeFacts, WorktreeOpError, RECOVERY_LOCAL_OR_TUI,
};

use super::{get, harness, json_body, post_json, send, status_and_json};

const TOKEN: &str = "worktree-token";
const REPO: &str = "/srv/repo";

// ============================================================================
// Fake port
// ============================================================================

/// Records what the API delegated and answers from a scripted listing.
#[derive(Default)]
pub(crate) struct FakeWorktreePort {
    listing: Mutex<Option<WorktreeListing>>,
    creates: Mutex<Vec<String>>,
    deletes: Mutex<Vec<String>>,
    merges: Mutex<Vec<String>>,
    outcome: Mutex<Option<CommandFailure>>,
}

impl FakeWorktreePort {
    pub(crate) fn set_listing(&self, listing: WorktreeListing) {
        *self.listing.lock().unwrap() = Some(listing);
    }

    pub(crate) fn fail_with(&self, failure: CommandFailure) {
        *self.outcome.lock().unwrap() = Some(failure);
    }

    pub(crate) fn creates(&self) -> Vec<String> {
        self.creates.lock().unwrap().clone()
    }

    pub(crate) fn deletes(&self) -> Vec<String> {
        self.deletes.lock().unwrap().clone()
    }

    pub(crate) fn merges(&self) -> Vec<String> {
        self.merges.lock().unwrap().clone()
    }

    fn answer(&self) -> Result<ExecutionSummary, CommandFailure> {
        match self.outcome.lock().unwrap().clone() {
            Some(failure) => Err(failure),
            None => Ok(ExecutionSummary::changed("done")),
        }
    }
}

#[async_trait]
impl WorktreeOperations for FakeWorktreePort {
    async fn list(&self) -> Result<WorktreeListing, CommandFailure> {
        self.listing.lock().unwrap().clone().ok_or_else(|| {
            CommandFailure::new(ErrorCode::LifecycleConflict, "no listing configured")
        })
    }

    async fn create(&self, change_id: &str) -> Result<ExecutionSummary, CommandFailure> {
        self.creates.lock().unwrap().push(change_id.to_string());
        self.answer()
    }

    async fn delete(&self, worktree_id: &str) -> Result<ExecutionSummary, CommandFailure> {
        self.deletes.lock().unwrap().push(worktree_id.to_string());
        self.answer()
    }

    async fn merge(&self, worktree_id: &str) -> Result<ExecutionSummary, CommandFailure> {
        self.merges.lock().unwrap().push(worktree_id.to_string());
        self.answer()
    }
}

fn facts(path: &str, branch: &str) -> WorktreeFacts {
    let mut facts = WorktreeFacts::new(path, branch);
    facts.identity = format!("gitdir: {path}/.git");
    facts.head = "0123456789abcdef".to_string();
    facts
}

fn listing(entries: &[(&str, WorktreeFacts)]) -> WorktreeListing {
    let repository_id = repository_correlation_id(Path::new(REPO));
    WorktreeListing {
        repository_id: repository_id.clone(),
        worktrees: entries
            .iter()
            .map(|(id, facts)| {
                WorktreeResource::project(
                    (*id).to_string(),
                    repository_id.clone(),
                    Path::new(REPO),
                    facts,
                )
            })
            .collect(),
    }
}

fn command_body(json: &str, revision: u64, key: &str) -> String {
    let trimmed = json
        .strip_suffix('}')
        .expect("command fragments are JSON objects");
    format!(r#"{trimmed},"expected_revision":{revision},"idempotency_key":"{key}"}}"#)
}

// ============================================================================
// Task 1 — opaque process-local identity
// ============================================================================

fn key(path: &str, identity: &str) -> WorktreeKey {
    WorktreeKey {
        path: PathBuf::from(path),
        identity: identity.to_string(),
    }
}

#[test]
fn remote_worktree_ids_are_random_128_bit_hex_and_stable_across_observations() {
    let registry = WorktreeRegistry::new();
    let observed = vec![key("/w/a", "id-a"), key("/w/b", "id-b")];

    let first = registry.sync(&observed);
    assert_eq!(first.len(), 2);
    for id in &first {
        assert_eq!(id.len(), 32, "expected 128 bits of hex, got {id}");
        assert!(id
            .chars()
            .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase()));
    }
    assert_ne!(
        first[0], first[1],
        "distinct resources must not share an ID"
    );

    assert_eq!(
        registry.sync(&observed),
        first,
        "an unchanged observation must not reallocate identity"
    );
}

#[test]
fn remote_worktree_id_is_retired_when_the_resource_disappears() {
    let registry = WorktreeRegistry::new();
    let id = registry.sync(&[key("/w/a", "id-a")])[0].clone();
    assert!(registry.resolve(&id).is_some());

    registry.sync(&[]);

    assert!(
        registry.resolve(&id).is_none(),
        "a retired ID must not resolve"
    );
    assert!(registry.is_retired(&id));
    assert!(registry.is_empty());
}

#[test]
fn remote_worktree_recreated_path_receives_a_new_identity() {
    let registry = WorktreeRegistry::new();
    let original = registry.sync(&[key("/w/a", "id-a")])[0].clone();

    // Disappear, then come back at the very same path.
    registry.sync(&[]);
    let recreated = registry.sync(&[key("/w/a", "id-a")])[0].clone();

    assert_ne!(original, recreated, "a retired ID must never be reused");
    assert!(registry.is_retired(&original));
    assert_eq!(
        registry.resolve(&recreated).map(|k| k.path),
        Some(PathBuf::from("/w/a"))
    );
}

#[test]
fn remote_worktree_same_path_with_new_git_identity_is_a_new_resource() {
    let registry = WorktreeRegistry::new();
    let original = registry.sync(&[key("/w/a", "id-a")])[0].clone();

    // Torn down and rebuilt between two observations: the path is unchanged but
    // the Git identity is not, so it must not inherit the previous ID.
    let rebuilt = registry.sync(&[key("/w/a", "id-a-rebuilt")])[0].clone();

    assert_ne!(original, rebuilt);
    assert!(registry.is_retired(&original));
}

#[test]
fn remote_worktree_explicit_retirement_survives_a_later_observation() {
    let registry = WorktreeRegistry::new();
    let id = registry.sync(&[key("/w/a", "id-a")])[0].clone();

    registry.retire(&id);
    assert!(registry.resolve(&id).is_none());

    let reobserved = registry.sync(&[key("/w/a", "id-a")])[0].clone();
    assert_ne!(id, reobserved);
}

// ============================================================================
// Task 2 — redacted, non-confidential observations
// ============================================================================

#[test]
fn remote_worktree_repository_id_is_16_hex_and_stable_per_repository() {
    let a = repository_correlation_id(Path::new("/srv/one"));
    let b = repository_correlation_id(Path::new("/srv/one"));
    let c = repository_correlation_id(Path::new("/srv/two"));

    assert_eq!(a, b);
    assert_ne!(a, c);
    assert_eq!(a.len(), 16);
    assert!(a
        .chars()
        .all(|ch| ch.is_ascii_hexdigit() && !ch.is_uppercase()));
    // A correlation value, not a secret: it must not be the identity itself.
    assert!(!a.contains("srv"));
}

#[test]
fn remote_worktree_display_paths_are_repository_relative() {
    assert_eq!(
        repository_relative_display(Path::new("/srv/repo"), Path::new("/srv/repo")),
        "."
    );
    assert_eq!(
        repository_relative_display(Path::new("/srv/repo"), Path::new("/srv/repo/sub/wt")),
        "sub/wt"
    );
    // Managed worktrees usually live outside the repository; escaping is normal.
    assert_eq!(
        repository_relative_display(Path::new("/srv/repo"), Path::new("/srv/workspaces/wt")),
        "../workspaces/wt"
    );
}

#[tokio::test]
async fn remote_worktree_list_never_serializes_the_canonical_root() {
    let harness = harness(Some(TOKEN), &[]);
    let mut main = facts("/srv/repo", "main");
    main.is_main = true;
    harness.worktrees.set_listing(listing(&[
        ("id-main", main),
        ("id-a", facts("/srv/workspaces/change-a", "change-a")),
    ]));

    let (status, body) =
        status_and_json(send(&harness.router, get("/api/v2/worktrees", Some(TOKEN))).await).await;

    assert_eq!(status, StatusCode::OK);
    let raw = serde_json::to_string(&body).unwrap();
    assert!(
        !raw.contains("/srv/repo"),
        "the canonical repository root leaked into the response: {raw}"
    );
    assert_eq!(body["worktrees"][0]["path"], ".");
    assert_eq!(body["worktrees"][1]["path"], "../workspaces/change-a");
    assert_eq!(
        body["repository_id"],
        repository_correlation_id(Path::new(REPO))
    );
}

#[test]
fn remote_worktree_unknown_dirty_serializes_as_null_and_blocks_deletion() {
    let mut unknown = facts("/srv/workspaces/change-a", "change-a");
    unknown.dirty = DirtyState::Unknown;
    let resource = &listing(&[("id-a", unknown)]).worktrees[0];

    let json = serde_json::to_value(resource).unwrap();
    assert_eq!(json["dirty"], serde_json::Value::Null);
    assert_eq!(json["operations"]["deletable"], false);
    assert!(json["operations"]["delete_blocked_reason"]
        .as_str()
        .unwrap()
        .contains("could not be determined"));
}

#[test]
fn remote_worktree_conflict_evidence_names_local_recovery() {
    let mut conflicted = facts("/srv/workspaces/change-a", "change-a");
    conflicted.conflict_files = vec!["src/main.rs".to_string()];
    let resource = &listing(&[("id-a", conflicted)]).worktrees[0];

    let json = serde_json::to_value(resource).unwrap();
    assert_eq!(json["conflict"]["files"][0], "src/main.rs");
    assert_eq!(json["conflict"]["recovery"], RECOVERY_LOCAL_OR_TUI);
}

#[test]
fn remote_worktree_resource_carries_no_absolute_path_or_target_field() {
    let resource =
        &listing(&[("id-a", facts("/srv/workspaces/change-a", "change-a"))]).worktrees[0];
    let json = serde_json::to_value(resource).unwrap();
    let object = json.as_object().unwrap();

    for forbidden in [
        "absolute_path",
        "canonical_path",
        "repository_root",
        "worktree_path",
        "base_commit",
        "worktree_command",
    ] {
        assert!(
            !object.contains_key(forbidden),
            "v2 must not expose '{forbidden}'"
        );
    }
}

#[tokio::test]
async fn remote_worktree_detail_resolves_by_opaque_id_only() {
    let harness = harness(Some(TOKEN), &[]);
    harness.worktrees.set_listing(listing(&[(
        "id-a",
        facts("/srv/workspaces/change-a", "change-a"),
    )]));

    let (status, body) =
        status_and_json(send(&harness.router, get("/api/v2/worktrees/id-a", Some(TOKEN))).await)
            .await;
    assert_eq!(status, StatusCode::OK);
    assert_eq!(body["worktree"]["worktree_id"], "id-a");

    // A branch name, a path, and a retired ID are all equally "not a resource".
    for addressed in ["change-a", "..%2Fworkspaces%2Fchange-a", "retired-id"] {
        let (status, body) = status_and_json(
            send(
                &harness.router,
                get(&format!("/api/v2/worktrees/{addressed}"), Some(TOKEN)),
            )
            .await,
        )
        .await;
        assert_eq!(status, StatusCode::NOT_FOUND, "addressed by {addressed}");
        assert_eq!(body["error_code"], "worktree_not_found");
    }
}

#[tokio::test]
async fn remote_worktree_reads_require_authentication() {
    let harness = harness(Some(TOKEN), &[]);
    harness.worktrees.set_listing(listing(&[]));

    for uri in ["/api/v2/worktrees", "/api/v2/worktrees/id-a"] {
        let response = send(&harness.router, get(uri, None)).await;
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{uri}");
    }
}

// ============================================================================
// Task 7 — closed command shapes and negative security coverage
// ============================================================================

#[test]
fn remote_worktree_commands_reject_path_branch_and_base_commit_targets() {
    let smuggled = [
        r#"{"type":"create_worktree","target":{"change_id":"a","base_commit":"deadbeef"},"params":{}}"#,
        r#"{"type":"create_worktree","target":{"change_id":"a","branch":"evil"},"params":{}}"#,
        r#"{"type":"create_worktree","target":{"change_id":"a","path":"/etc"},"params":{}}"#,
        r#"{"type":"create_worktree","target":{"path":"/etc"},"params":{}}"#,
        r#"{"type":"delete_worktree","target":{"path":"/srv/workspaces/a"},"params":{}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a","skip_teardown":true},"params":{}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"skip_teardown":true}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"force":true}}"#,
        r#"{"type":"merge_worktree","target":{"branch":"a"},"params":{}}"#,
        r#"{"type":"merge_worktree","target":{"worktree_id":"a"},"params":{"abort":true}}"#,
        r#"{"type":"merge_worktree","target":{"worktree_id":"a"},"params":{"strategy":"ours"}}"#,
        r#"{"type":"merge_worktree","target":{"repository_id":"abc"},"params":{}}"#,
    ];

    for body in smuggled {
        assert!(
            serde_json::from_str::<CommandSpec>(body).is_err(),
            "must fail typed validation: {body}"
        );
    }
}

#[test]
fn remote_worktree_command_surface_has_no_generic_or_editor_operation() {
    for absent in [
        "worktree_command",
        "run_in_worktree",
        "open_editor",
        "open_worktree",
        "create_session",
        "resolve_worktree_conflict",
        "abort_worktree_merge",
        "force_delete_worktree",
    ] {
        assert!(
            !SUPPORTED_COMMANDS.contains(&absent),
            "v2 must not advertise '{absent}'"
        );
        assert!(
            serde_json::from_str::<CommandSpec>(&format!(r#"{{"type":"{absent}"}}"#)).is_err(),
            "v2 must not parse '{absent}'"
        );
    }
}

#[tokio::test]
async fn remote_worktree_unauthenticated_mutation_never_reaches_the_service() {
    let harness = harness(Some(TOKEN), &[]);
    let body = command_body(
        r#"{"type":"delete_worktree","target":{"worktree_id":"id-a"},"params":{}}"#,
        0,
        "k1",
    );

    let response = send(&harness.router, post_json("/api/v2/commands", None, &body)).await;

    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    assert!(harness.worktrees.deletes().is_empty());
}

#[tokio::test]
async fn remote_worktree_unknown_parameter_is_a_422_with_no_delegation() {
    let harness = harness(Some(TOKEN), &[]);
    let body = command_body(
        r#"{"type":"delete_worktree","target":{"worktree_id":"id-a"},"params":{"skip_teardown":true}}"#,
        0,
        "k1",
    );

    let (status, json) = status_and_json(
        send(
            &harness.router,
            post_json("/api/v2/commands", Some(TOKEN), &body),
        )
        .await,
    )
    .await;

    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(json["error_code"], "validation_failed");
    assert!(harness.worktrees.deletes().is_empty());
}

// ============================================================================
// Tasks 4-6 — delegation and inherited v2 guards
// ============================================================================

#[tokio::test]
async fn remote_worktree_create_delegates_only_the_change_id() {
    let harness = harness(Some(TOKEN), &[]);
    let body = command_body(
        r#"{"type":"create_worktree","target":{"change_id":"change-a"},"params":{}}"#,
        0,
        "k1",
    );

    let (status, json) = status_and_json(
        send(
            &harness.router,
            post_json("/api/v2/commands", Some(TOKEN), &body),
        )
        .await,
    )
    .await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(json["type"], "create_worktree");
    assert_eq!(harness.worktrees.creates(), vec!["change-a".to_string()]);
}

#[tokio::test]
async fn remote_worktree_delete_and_merge_delegate_only_the_opaque_id() {
    let harness = harness(Some(TOKEN), &[]);

    for (index, (json, key)) in [
        (
            r#"{"type":"delete_worktree","target":{"worktree_id":"id-a"},"params":{}}"#,
            "k-delete",
        ),
        (
            r#"{"type":"merge_worktree","target":{"worktree_id":"id-a"},"params":{}}"#,
            "k-merge",
        ),
    ]
    .into_iter()
    .enumerate()
    {
        let body = command_body(json, index as u64, key);
        let response = send(
            &harness.router,
            post_json("/api/v2/commands", Some(TOKEN), &body),
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);
        // Each accepted command advances the revision the next one must quote.
        harness.projection.apply_state(
            "worktree_changed",
            None,
            serde_json::json!({}),
            super::snapshot_with(&format!("c{index}"), "queued"),
        );
    }

    assert_eq!(harness.worktrees.deletes(), vec!["id-a".to_string()]);
    assert_eq!(harness.worktrees.merges(), vec!["id-a".to_string()]);
}

#[tokio::test]
async fn remote_worktree_commands_require_revision_and_idempotency_key() {
    let harness = harness(Some(TOKEN), &[]);

    for incomplete in [
        r#"{"type":"create_worktree","target":{"change_id":"a"},"params":{},"idempotency_key":"k"}"#,
        r#"{"type":"create_worktree","target":{"change_id":"a"},"params":{},"expected_revision":0}"#,
    ] {
        let (status, _) = status_and_json(
            send(
                &harness.router,
                post_json("/api/v2/commands", Some(TOKEN), incomplete),
            )
            .await,
        )
        .await;
        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{incomplete}");
    }
    assert!(harness.worktrees.creates().is_empty());
}

#[tokio::test]
async fn remote_worktree_stale_revision_is_refused_before_delegation() {
    let harness = harness(Some(TOKEN), &[]);
    harness.projection.apply_state(
        "moved_on",
        None,
        serde_json::json!({}),
        super::snapshot_with("c1", "queued"),
    );

    let body = command_body(
        r#"{"type":"merge_worktree","target":{"worktree_id":"id-a"},"params":{}}"#,
        0,
        "k1",
    );
    let (status, json) = status_and_json(
        send(
            &harness.router,
            post_json("/api/v2/commands", Some(TOKEN), &body),
        )
        .await,
    )
    .await;

    assert_eq!(status, StatusCode::CONFLICT);
    assert_eq!(json["error_code"], "stale_revision");
    assert!(harness.worktrees.merges().is_empty());
}

#[tokio::test]
async fn remote_worktree_replayed_delete_runs_its_side_effect_once() {
    let harness = harness(Some(TOKEN), &[]);
    let body = command_body(
        r#"{"type":"delete_worktree","target":{"worktree_id":"id-a"},"params":{}}"#,
        0,
        "same-key",
    );

    let first = send(
        &harness.router,
        post_json("/api/v2/commands", Some(TOKEN), &body),
    )
    .await;
    let second = send(
        &harness.router,
        post_json("/api/v2/commands", Some(TOKEN), &body),
    )
    .await;

    assert_eq!(first.status(), StatusCode::OK);
    assert_eq!(second.status(), StatusCode::OK);
    assert_eq!(
        harness.worktrees.deletes(),
        vec!["id-a".to_string()],
        "an exact replay must not delete twice"
    );
}

#[tokio::test]
async fn remote_worktree_service_refusals_surface_as_typed_v2_errors() {
    for (error, expected_code, expected_status) in [
        (
            WorktreeOpError::Exists("exists".to_string()),
            "worktree_exists",
            StatusCode::CONFLICT,
        ),
        (
            WorktreeOpError::NotFound("gone".to_string()),
            "worktree_not_found",
            StatusCode::NOT_FOUND,
        ),
        (
            WorktreeOpError::Dirty {
                message: "dirty".to_string(),
                target: Box::new(crate::worktree_ops::service::DirtyTarget::from_facts(
                    &facts("/srv/workspaces/a", "a"),
                )),
            },
            "worktree_dirty",
            StatusCode::CONFLICT,
        ),
        (
            WorktreeOpError::DirtyUnknown("unknown".to_string()),
            "worktree_dirty_unknown",
            StatusCode::CONFLICT,
        ),
        (
            WorktreeOpError::RootBusy("busy".to_string()),
            "root_busy",
            StatusCode::CONFLICT,
        ),
        (
            WorktreeOpError::MergeConflict {
                files: vec!["src/main.rs".to_string()],
                recovery: RECOVERY_LOCAL_OR_TUI,
            },
            "merge_conflict",
            StatusCode::CONFLICT,
        ),
    ] {
        let harness = harness(Some(TOKEN), &[]);
        harness.worktrees.fail_with(map_worktree_error(&error));

        let body = command_body(
            r#"{"type":"merge_worktree","target":{"worktree_id":"id-a"},"params":{}}"#,
            0,
            "k1",
        );
        let (status, json) = status_and_json(
            send(
                &harness.router,
                post_json("/api/v2/commands", Some(TOKEN), &body),
            )
            .await,
        )
        .await;

        assert_eq!(status, expected_status, "{expected_code}");
        assert_eq!(json["state"], "failed");
        assert_eq!(json["error_code"], expected_code);
    }
}

#[tokio::test]
async fn remote_worktree_merge_conflict_detail_names_files_and_local_recovery() {
    let harness = harness(Some(TOKEN), &[]);
    harness
        .worktrees
        .fail_with(map_worktree_error(&WorktreeOpError::MergeConflict {
            files: vec!["src/main.rs".to_string(), "README.md".to_string()],
            recovery: RECOVERY_LOCAL_OR_TUI,
        }));

    let body = command_body(
        r#"{"type":"merge_worktree","target":{"worktree_id":"id-a"},"params":{}}"#,
        0,
        "k1",
    );
    let (_, json) = status_and_json(
        send(
            &harness.router,
            post_json("/api/v2/commands", Some(TOKEN), &body),
        )
        .await,
    )
    .await;

    let detail = json["detail"]
        .as_str()
        .expect("failed commands carry detail");
    assert!(detail.contains("src/main.rs"));
    assert!(detail.contains("README.md"));
    assert!(detail.contains(RECOVERY_LOCAL_OR_TUI));
    assert!(detail.contains("preserved"));
}

#[tokio::test]
async fn remote_worktree_commands_are_refused_before_a_runtime_is_bound() {
    // The default port is the unbound one; nothing may be reported as accepted.
    let harness = harness(Some(TOKEN), &[]);
    let unbound = crate::web::remote_control_api::worktrees::UnboundWorktreeOperations;
    let failure = unbound.delete("id-a").await.expect_err("must refuse");
    assert_eq!(failure.error_code, ErrorCode::LifecycleConflict);

    let response = send(&harness.router, get("/api/v2/worktrees", Some(TOKEN))).await;
    // The harness port has no listing configured, which stands in for "unbound".
    assert_eq!(response.status(), StatusCode::CONFLICT);
}

// ============================================================================
// Capabilities
// ============================================================================

#[tokio::test]
async fn remote_worktree_capabilities_report_the_operations_and_recovery_boundary() {
    let harness = harness(Some(TOKEN), &[]);
    let body =
        json_body(send(&harness.router, get("/api/v2/capabilities", Some(TOKEN))).await).await;

    let operations: Vec<String> =
        serde_json::from_value(body["worktrees"]["operations"].clone()).unwrap();
    assert_eq!(operations, WORKTREE_OPERATIONS.to_vec());
    assert_eq!(
        body["worktrees"]["merge_conflict_recovery"],
        RECOVERY_LOCAL_OR_TUI
    );
    assert_eq!(body["worktrees"]["merge_conflict_preserves_state"], true);
    assert_eq!(body["worktrees"]["delete_requires_teardown"], true);

    let commands: Vec<String> = serde_json::from_value(body["commands"].clone()).unwrap();
    for expected in ["create_worktree", "delete_worktree", "merge_worktree"] {
        assert!(commands.contains(&expected.to_string()), "{expected}");
    }

    let error_codes: Vec<String> = serde_json::from_value(body["error_codes"].clone()).unwrap();
    for expected in [
        "worktree_exists",
        "worktree_not_found",
        "worktree_dirty",
        "worktree_dirty_unknown",
        "merge_conflict",
    ] {
        assert!(error_codes.contains(&expected.to_string()), "{expected}");
    }
}

// ============================================================================
// Task 3 — adapter parity
// ============================================================================

#[tokio::test]
async fn remote_worktree_adapters_share_one_service_implementation() {
    use crate::worktree_ops::service::{
        ConflictPolicy, DeleteOptions, ExpectedTarget, MergeAttempt, WorktreeBackend,
        WorktreeEventSink, WorktreeOpResult, WorktreeOperationEvent, WorktreeService,
    };

    /// One backend, driven twice: once with the TUI's policy values and once
    /// with the remote ones. Anything a frontend re-implemented instead of
    /// delegating would be missing from this recording.
    #[derive(Default)]
    struct ParityBackend {
        calls: Mutex<Vec<String>>,
        merged: std::sync::atomic::AtomicBool,
    }

    #[async_trait]
    impl WorktreeBackend for ParityBackend {
        async fn observe(
            &self,
            _request: crate::worktree_ops::ObservationRequest,
        ) -> WorktreeOpResult<Vec<WorktreeFacts>> {
            let mut wt = WorktreeFacts::new("/srv/workspaces/change-a", "change-a");
            // Merging is what makes the worktree deletable, so the observation
            // has to move with it or the second half of the run is untestable.
            wt.has_commits_ahead = crate::worktree_ops::service::SafetyFact::from(
                !self.merged.load(std::sync::atomic::Ordering::SeqCst),
            );
            Ok(vec![wt])
        }
        async fn base_head(&self) -> WorktreeOpResult<String> {
            Ok("head".to_string())
        }
        async fn create(&self, _p: &Path, _b: &str, _c: &str) -> WorktreeOpResult<()> {
            Ok(())
        }
        async fn teardown(&self, _path: &Path) -> WorktreeOpResult<()> {
            self.calls.lock().unwrap().push("teardown".to_string());
            Ok(())
        }
        async fn remove_worktree(&self, _path: &Path) -> WorktreeOpResult<()> {
            self.calls.lock().unwrap().push("remove".to_string());
            Ok(())
        }
        async fn branch_ref(&self, _branch: &str) -> WorktreeOpResult<Option<String>> {
            Ok(Some(String::new()))
        }
        async fn delete_branch_if_merged(&self, _branch: &str) -> WorktreeOpResult<()> {
            self.calls.lock().unwrap().push("delete_branch".to_string());
            Ok(())
        }
        async fn delete_branch_at(&self, _branch: &str, _oid: &str) -> WorktreeOpResult<()> {
            self.calls
                .lock()
                .unwrap()
                .push("delete_branch_at".to_string());
            Ok(())
        }
        async fn merge_into_base(
            &self,
            _branch: &str,
            policy: ConflictPolicy,
        ) -> WorktreeOpResult<MergeAttempt> {
            self.calls
                .lock()
                .unwrap()
                .push(format!("merge({policy:?})"));
            self.merged.store(true, std::sync::atomic::Ordering::SeqCst);
            Ok(MergeAttempt::Merged)
        }
        async fn run_on_merged(&self, _c: &str, _p: &Path) -> WorktreeOpResult<()> {
            self.calls.lock().unwrap().push("on_merged".to_string());
            Ok(())
        }
        async fn change_is_eligible(&self, _change_id: &str) -> WorktreeOpResult<()> {
            Ok(())
        }
    }

    #[derive(Default)]
    struct Sink(Mutex<Vec<String>>);

    #[async_trait]
    impl WorktreeEventSink for Sink {
        async fn emit(&self, event: WorktreeOperationEvent) {
            self.0.lock().unwrap().push(format!("{event:?}"));
        }
    }

    async fn run(options: DeleteOptions, policy: ConflictPolicy) -> (Vec<String>, Vec<String>) {
        let backend = Arc::new(ParityBackend::default());
        let sink = Arc::new(Sink::default());
        let service = WorktreeService::new(
            backend.clone(),
            sink.clone(),
            PathBuf::from("/srv/workspaces"),
        );
        let path = Path::new("/srv/workspaces/change-a");
        service.merge_worktree(path, policy).await.expect("merged");
        service
            .delete_worktree(path, &ExpectedTarget::unchecked(), options)
            .await
            .expect("deleted");
        let calls = backend.calls.lock().unwrap().clone();
        let events = sink.0.lock().unwrap().clone();
        (calls, events)
    }

    let (tui_calls, tui_events) =
        run(DeleteOptions::local(false), ConflictPolicy::AbortOnConflict).await;
    let (remote_calls, remote_events) = run(
        DeleteOptions::fail_closed(),
        ConflictPolicy::PreserveConflict,
    )
    .await;

    // Same operation sequence, same event sequence: the only difference between
    // the two frontends is the declared conflict policy.
    assert_eq!(
        tui_calls,
        vec![
            "merge(AbortOnConflict)".to_string(),
            "on_merged".to_string(),
            "teardown".to_string(),
            "remove".to_string(),
            "delete_branch".to_string(),
        ]
    );
    assert_eq!(
        remote_calls,
        vec![
            "merge(PreserveConflict)".to_string(),
            "on_merged".to_string(),
            "teardown".to_string(),
            "remove".to_string(),
            "delete_branch".to_string(),
        ]
    );
    assert_eq!(tui_events, remote_events);
}

// ============================================================================
// Published schema shape
// ============================================================================

#[test]
fn remote_worktree_published_schemas_expose_no_path_branch_or_base_commit_input() {
    use crate::web::remote_control_api::dto::{ChangeTarget, EmptyParams, WorktreeTarget};
    use utoipa::PartialSchema;

    let change_target = serde_json::to_value(ChangeTarget::schema()).unwrap();
    let worktree_target = serde_json::to_value(WorktreeTarget::schema()).unwrap();
    let params = serde_json::to_value(EmptyParams::schema()).unwrap();

    assert_eq!(
        change_target["properties"]
            .as_object()
            .unwrap()
            .keys()
            .collect::<Vec<_>>(),
        vec!["change_id"]
    );
    assert_eq!(
        worktree_target["properties"]
            .as_object()
            .unwrap()
            .keys()
            .collect::<Vec<_>>(),
        vec!["worktree_id"]
    );
    assert!(
        params["properties"]
            .as_object()
            .map(|properties| properties.is_empty())
            .unwrap_or(true),
        "the published parameter object must accept nothing: {params}"
    );

    // The generated contract is what a client codegens against, so the absence
    // has to hold there and not only in the deserializer. Only the property
    // names are inspected: descriptions deliberately *name* the fields that are
    // refused, and matching those would assert the opposite of the intent.
    let published: Vec<String> = [&change_target, &worktree_target, &params]
        .iter()
        .filter_map(|schema| schema["properties"].as_object())
        .flat_map(|properties| properties.keys().cloned())
        .collect();
    for forbidden in [
        "base_commit",
        "path",
        "branch",
        "skip_teardown",
        "force",
        "command",
        "repository_id",
    ] {
        assert!(
            !published.iter().any(|name| name == forbidden),
            "v2 worktree command schemas must not publish '{forbidden}': {published:?}"
        );
    }

    // Closed by construction: an unknown property is a schema violation.
    for schema in [&change_target, &worktree_target, &params] {
        assert_eq!(
            schema["additionalProperties"],
            serde_json::Value::Bool(false)
        );
    }
}

// ============================================================================
// Explicit dirty discard is a local-only permission
// ============================================================================

#[test]
fn remote_worktree_dirty_discard_command_shapes_are_rejected_wholesale() {
    // Every way a client could try to ask for the local escalation: as a target
    // field, as a parameter, and as its own command type. `deny_unknown_fields`
    // on both objects is what turns each of these into a schema failure rather
    // than a silently ignored field.
    let smuggled = [
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"allow_dirty":true}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"dirty_discard":true}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"allow_known_dirty":true}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"force":true}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"skip_teardown":true}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"path":"/srv/workspaces/a"}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"branch":"change-a"}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a","allow_dirty":true},"params":{}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a","dirty_discard":true},"params":{}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a","force":true},"params":{}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a","skip_teardown":true},"params":{}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a","path":"/srv/workspaces/a"},"params":{}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a","branch":"change-a"},"params":{}}"#,
        r#"{"type":"discard_worktree_changes","target":{"worktree_id":"a"},"params":{}}"#,
        r#"{"type":"force_delete_worktree","target":{"worktree_id":"a"},"params":{}}"#,
    ];

    for body in smuggled {
        assert!(
            serde_json::from_str::<CommandSpec>(body).is_err(),
            "a remote dirty-discard request must fail typed validation: {body}"
        );
    }
}

#[tokio::test]
async fn remote_worktree_dirty_discard_request_is_a_422_with_no_delegation() {
    for params in [
        r#"{"allow_dirty":true}"#,
        r#"{"dirty_discard":true}"#,
        r#"{"force":true}"#,
        r#"{"skip_teardown":true}"#,
        r#"{"path":"/srv/workspaces/a"}"#,
        r#"{"branch":"change-a"}"#,
    ] {
        let harness = harness(Some(TOKEN), &[]);
        let body = command_body(
            &format!(
                r#"{{"type":"delete_worktree","target":{{"worktree_id":"id-a"}},"params":{params}}}"#
            ),
            0,
            "k1",
        );

        let (status, _json) = status_and_json(
            send(
                &harness.router,
                post_json("/api/v2/commands", Some(TOKEN), &body),
            )
            .await,
        )
        .await;

        assert_eq!(
            status,
            StatusCode::UNPROCESSABLE_ENTITY,
            "params {params} must be refused as a schema violation"
        );
        assert!(
            harness.worktrees.deletes().is_empty(),
            "params {params} must not reach the worktree service at all"
        );
    }
}

#[tokio::test]
async fn remote_worktree_dirty_discard_is_never_granted_by_the_remote_port() {
    use crate::worktree_ops::service::{
        ConflictPolicy, MergeAttempt, WorktreeBackend, WorktreeEventSink, WorktreeOpResult,
        WorktreeOperationEvent, WorktreeService,
    };

    /// A backend whose only worktree is known dirty and whose removal panics.
    ///
    /// The recorded facts alone would let a caller that granted discard through
    /// to removal, so "no removal delegation" is enforced here by making the
    /// removal itself impossible to survive.
    #[derive(Default)]
    struct DirtyBackend {
        removals: Mutex<Vec<String>>,
    }

    #[async_trait]
    impl WorktreeBackend for DirtyBackend {
        async fn observe(
            &self,
            _request: crate::worktree_ops::ObservationRequest,
        ) -> WorktreeOpResult<Vec<WorktreeFacts>> {
            let mut wt = facts("/srv/workspaces/change-a", "change-a");
            wt.dirty = DirtyState::Dirty;
            Ok(vec![wt])
        }
        async fn base_head(&self) -> WorktreeOpResult<String> {
            Ok("head".to_string())
        }
        async fn create(&self, _p: &Path, _b: &str, _c: &str) -> WorktreeOpResult<()> {
            Ok(())
        }
        async fn teardown(&self, _path: &Path) -> WorktreeOpResult<()> {
            self.removals.lock().unwrap().push("teardown".to_string());
            Ok(())
        }
        async fn remove_worktree(&self, _path: &Path) -> WorktreeOpResult<()> {
            self.removals.lock().unwrap().push("remove".to_string());
            Ok(())
        }
        async fn branch_ref(&self, _branch: &str) -> WorktreeOpResult<Option<String>> {
            Ok(None)
        }
        async fn delete_branch_if_merged(&self, _branch: &str) -> WorktreeOpResult<()> {
            self.removals
                .lock()
                .unwrap()
                .push("delete_branch".to_string());
            Ok(())
        }
        async fn delete_branch_at(&self, _branch: &str, _oid: &str) -> WorktreeOpResult<()> {
            self.removals
                .lock()
                .unwrap()
                .push("delete_branch_at".to_string());
            Ok(())
        }
        async fn merge_into_base(
            &self,
            _branch: &str,
            _policy: ConflictPolicy,
        ) -> WorktreeOpResult<MergeAttempt> {
            Ok(MergeAttempt::Merged)
        }
        async fn run_on_merged(&self, _c: &str, _p: &Path) -> WorktreeOpResult<()> {
            Ok(())
        }
        async fn change_is_eligible(&self, _change_id: &str) -> WorktreeOpResult<()> {
            Ok(())
        }
    }

    struct NullSink;

    #[async_trait]
    impl WorktreeEventSink for NullSink {
        async fn emit(&self, _event: WorktreeOperationEvent) {}
    }

    let backend = Arc::new(DirtyBackend::default());
    let service = Arc::new(WorktreeService::new(
        backend.clone(),
        Arc::new(NullSink),
        PathBuf::from("/srv/workspaces"),
    ));
    let registry = Arc::new(WorktreeRegistry::new());
    let port = crate::web::remote_control_api::worktrees::RemoteWorktreeOperations::new(
        service,
        registry,
        PathBuf::from(REPO),
    );

    let listing = port.list().await.expect("listed");
    let worktree_id = listing.worktrees[0].worktree_id.clone();
    assert_eq!(listing.worktrees[0].dirty, Some(true));
    assert!(!listing.worktrees[0].operations.deletable);

    let failure = port
        .delete(&worktree_id)
        .await
        .expect_err("a dirty worktree must refuse remote deletion");
    assert_eq!(failure.error_code, ErrorCode::WorktreeDirty);

    // No teardown, no removal, no branch deletion: the remote port has no way to
    // express the permission that would have let any of them happen.
    assert!(
        backend.removals.lock().unwrap().is_empty(),
        "a remote delete must not delegate removal for a dirty worktree: {:?}",
        backend.removals.lock().unwrap()
    );
}

#[test]
fn remote_worktree_dirty_discard_capabilities_advertise_no_bypass() {
    use crate::web::remote_control_api::worktrees::WorktreeCapabilities;

    let capabilities = WorktreeCapabilities::default();
    assert!(capabilities.delete_requires_teardown);
    assert_eq!(
        capabilities.operations,
        WORKTREE_OPERATIONS
            .iter()
            .map(|o| o.to_string())
            .collect::<Vec<_>>()
    );

    let json = serde_json::to_string(&capabilities).unwrap();
    for forbidden in [
        "dirty_discard",
        "allow_dirty",
        "allow_known_dirty",
        "allow_commits_ahead",
        "ahead_discard",
        "force",
        "discard",
    ] {
        assert!(
            !json.contains(forbidden),
            "worktree capabilities must not advertise '{forbidden}': {json}"
        );
    }
}

// ============================================================================
// Explicit ahead discard is a local-only permission
// ============================================================================

/// A worktree ahead of base, at an absolute path outside the repository root.
fn ahead_facts(path: &str, branch: &str) -> WorktreeFacts {
    let mut facts = facts(path, branch);
    facts.has_commits_ahead = crate::worktree_ops::service::SafetyFact::Yes;
    facts
}

#[test]
fn remote_worktree_ahead_refusal_maps_onto_the_existing_ineligible_class() {
    // The refusal became typed so the *local* TUI could escalate it. Remotely it
    // must look exactly as it did before: one more ineligible target, not a new
    // error code hinting at an override that does not exist.
    let failure = map_worktree_error(&WorktreeOpError::CommitsAhead {
        message: "the worktree has unmerged commits ahead of base".to_string(),
        target: Box::new(crate::worktree_ops::service::AheadTarget::from_facts(
            &ahead_facts("/srv/workspaces/change-a", "change-a"),
        )),
    });

    assert_eq!(failure.error_code, ErrorCode::TargetIneligible);
    assert!(
        !failure.message.contains("/srv/"),
        "a v2 failure message must not carry an absolute path: {}",
        failure.message
    );
}

#[test]
fn remote_worktree_ahead_projection_stays_undeletable_without_leaking_its_path() {
    let resource = WorktreeResource::project(
        "id-a".to_string(),
        repository_correlation_id(Path::new(REPO)),
        Path::new(REPO),
        &ahead_facts("/srv/workspaces/change-a", "change-a"),
    );

    assert!(resource.has_commits_ahead);
    assert!(
        !resource.operations.deletable,
        "an ahead worktree stays undeletable for remote clients"
    );
    let reason = resource
        .operations
        .delete_blocked_reason
        .expect("an undeletable worktree must say why");
    assert!(
        reason.contains("unmerged commits ahead of base"),
        "the reason must name the actual blocker: {reason}"
    );
    // The typed refusal now carries a freshly observed absolute path. That
    // payload exists for the local confirmation, and it must not ride along into
    // a server-provided reason string.
    for leaked in ["/srv/workspaces", "/srv/repo", "change-a/.git"] {
        assert!(
            !reason.contains(leaked),
            "the blocked reason must not disclose '{leaked}': {reason}"
        );
    }
}

#[test]
fn remote_worktree_ahead_discard_command_shapes_are_rejected_wholesale() {
    // The same closed-schema property the dirty escalation relies on, for every
    // name a client might reach for to ask for the new local permission.
    let smuggled = [
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"allow_commits_ahead":true}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"ahead_discard":true}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"allow_ahead":true}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a"},"params":{"delete_branch":true}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a","allow_commits_ahead":true},"params":{}}"#,
        r#"{"type":"delete_worktree","target":{"worktree_id":"a","head":"0123456789abcdef"},"params":{}}"#,
        r#"{"type":"discard_worktree_commits","target":{"worktree_id":"a"},"params":{}}"#,
        r#"{"type":"delete_worktree_and_branch","target":{"worktree_id":"a"},"params":{}}"#,
    ];

    for body in smuggled {
        assert!(
            serde_json::from_str::<CommandSpec>(body).is_err(),
            "a remote ahead-discard request must fail typed validation: {body}"
        );
    }
}

#[tokio::test]
async fn remote_worktree_ahead_discard_request_is_a_422_with_no_delegation() {
    for params in [
        r#"{"allow_commits_ahead":true}"#,
        r#"{"ahead_discard":true}"#,
        r#"{"allow_ahead":true}"#,
        r#"{"delete_branch":true}"#,
    ] {
        let harness = harness(Some(TOKEN), &[]);
        let body = command_body(
            &format!(
                r#"{{"type":"delete_worktree","target":{{"worktree_id":"id-a"}},"params":{params}}}"#
            ),
            0,
            "k1",
        );

        let (status, _json) = status_and_json(
            send(
                &harness.router,
                post_json("/api/v2/commands", Some(TOKEN), &body),
            )
            .await,
        )
        .await;

        assert_eq!(
            status,
            StatusCode::UNPROCESSABLE_ENTITY,
            "params {params} must be refused as a schema violation"
        );
        assert!(
            harness.worktrees.deletes().is_empty(),
            "params {params} must not reach the worktree service at all"
        );
    }
}

#[tokio::test]
async fn remote_worktree_ahead_discard_is_never_granted_by_the_remote_port() {
    use crate::worktree_ops::service::{
        ConflictPolicy, MergeAttempt, WorktreeBackend, WorktreeEventSink, WorktreeOpResult,
        WorktreeOperationEvent, WorktreeService,
    };

    /// A backend whose only worktree is ahead of base and also dirty.
    ///
    /// Both destructive permissions would be needed to get through, and the
    /// remote port can express neither. Every mutating call is recorded so
    /// "no delegation" is proved rather than assumed.
    #[derive(Default)]
    struct AheadBackend {
        mutations: Mutex<Vec<String>>,
    }

    #[async_trait]
    impl WorktreeBackend for AheadBackend {
        async fn observe(
            &self,
            _request: crate::worktree_ops::ObservationRequest,
        ) -> WorktreeOpResult<Vec<WorktreeFacts>> {
            let mut wt = ahead_facts("/srv/workspaces/change-a", "change-a");
            wt.dirty = DirtyState::Dirty;
            Ok(vec![wt])
        }
        async fn base_head(&self) -> WorktreeOpResult<String> {
            Ok("head".to_string())
        }
        async fn create(&self, _p: &Path, _b: &str, _c: &str) -> WorktreeOpResult<()> {
            Ok(())
        }
        async fn teardown(&self, _path: &Path) -> WorktreeOpResult<()> {
            self.mutations.lock().unwrap().push("teardown".to_string());
            Ok(())
        }
        async fn remove_worktree(&self, _path: &Path) -> WorktreeOpResult<()> {
            self.mutations.lock().unwrap().push("remove".to_string());
            Ok(())
        }
        async fn branch_ref(&self, _branch: &str) -> WorktreeOpResult<Option<String>> {
            Ok(Some("0123456789abcdef".to_string()))
        }
        async fn delete_branch_if_merged(&self, _branch: &str) -> WorktreeOpResult<()> {
            self.mutations
                .lock()
                .unwrap()
                .push("delete_branch".to_string());
            Ok(())
        }
        async fn delete_branch_at(&self, _branch: &str, _oid: &str) -> WorktreeOpResult<()> {
            self.mutations
                .lock()
                .unwrap()
                .push("delete_branch_at".to_string());
            Ok(())
        }
        async fn merge_into_base(
            &self,
            _branch: &str,
            _policy: ConflictPolicy,
        ) -> WorktreeOpResult<MergeAttempt> {
            Ok(MergeAttempt::Merged)
        }
        async fn run_on_merged(&self, _c: &str, _p: &Path) -> WorktreeOpResult<()> {
            Ok(())
        }
        async fn change_is_eligible(&self, _change_id: &str) -> WorktreeOpResult<()> {
            Ok(())
        }
    }

    struct NullSink;

    #[async_trait]
    impl WorktreeEventSink for NullSink {
        async fn emit(&self, _event: WorktreeOperationEvent) {}
    }

    let backend = Arc::new(AheadBackend::default());
    let service = Arc::new(WorktreeService::new(
        backend.clone(),
        Arc::new(NullSink),
        PathBuf::from("/srv/workspaces"),
    ));
    let port = crate::web::remote_control_api::worktrees::RemoteWorktreeOperations::new(
        service,
        Arc::new(WorktreeRegistry::new()),
        PathBuf::from(REPO),
    );

    let listing = port.list().await.expect("listed");
    let worktree_id = listing.worktrees[0].worktree_id.clone();
    assert!(listing.worktrees[0].has_commits_ahead);
    assert!(!listing.worktrees[0].operations.deletable);

    let failure = port
        .delete(&worktree_id)
        .await
        .expect_err("an ahead worktree must refuse remote deletion");
    assert_eq!(failure.error_code, ErrorCode::TargetIneligible);

    assert!(
        backend.mutations.lock().unwrap().is_empty(),
        "a remote delete must not delegate teardown, removal, or branch deletion: {:?}",
        backend.mutations.lock().unwrap()
    );
}