loopflow 0.9.11

Run steps and flows with coding agents
Documentation
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
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
use async_trait::async_trait;
use reqwest::{Method, StatusCode, Url};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use tokio::time::sleep;
use tracing::warn;

use crate::engine::config::AsanaConfig;
use crate::lfd::pm::asana_html::{asana_html_to_markdown, markdown_to_asana_html};
use crate::lfd::pm::{
    PmError, PmItem, PmItemCreate, PmItemUpdate, PmProject, PmProvider, PmResult, PriorityBucket,
    RATE_LIMIT_RETRIES,
};

const ASANA_BASE_URL: &str = "https://app.asana.com/api/1.0";
const TASK_FIELDS: &str = "name,notes,html_notes,completed,assignee.gid,custom_fields.gid,custom_fields.name,custom_fields.resource_subtype,custom_fields.text_value,custom_fields.enum_value.gid,custom_fields.enum_value.name,custom_fields.enum_options.gid,custom_fields.enum_options.name";
const PROJECT_PRIORITY_FIELD_FIELDS: &str =
    "custom_field.gid,custom_field.name,custom_field.resource_subtype,custom_field.enum_options.gid,custom_field.enum_options.name";
const PROJECT_TEXT_FIELD_FIELDS: &str =
    "custom_field.gid,custom_field.name,custom_field.resource_subtype";
const WORKSPACE_TEXT_FIELD_FIELDS: &str = "gid,name,resource_subtype";
const CLAIM_TASK_FIELDS: &str = "assignee.gid,custom_fields.gid,custom_fields.name,custom_fields.resource_subtype,custom_fields.text_value";
const DEFAULT_LOOPFLOW_TEAM_NAME: &str = "Waves";
const PRIORITY_FIELD_NAME: &str = "Priority";
const WORKING_BRANCH_FIELD_NAME: &str = "Working branch";

#[derive(Debug, Clone)]
pub struct AsanaClient {
    client: reqwest::Client,
    token: String,
    config: AsanaConfig,
    base_url: String,
}

impl AsanaClient {
    pub fn new(token: String, config: AsanaConfig) -> Self {
        Self {
            client: reqwest::Client::new(),
            token,
            config,
            base_url: ASANA_BASE_URL.to_string(),
        }
    }

    #[cfg(test)]
    fn with_base_url(token: String, config: AsanaConfig, base_url: String) -> Self {
        Self {
            client: reqwest::Client::new(),
            token,
            config,
            base_url,
        }
    }

    fn request(
        &self,
        method: Method,
        path: &str,
        query: &[(&str, &str)],
    ) -> reqwest::RequestBuilder {
        let mut url = Url::parse(&format!("{}{}", self.base_url, path))
            .expect("asana base URL should be valid");
        if !query.is_empty() {
            let mut pairs = url.query_pairs_mut();
            for (key, value) in query {
                pairs.append_pair(key, value);
            }
        }
        self.client.request(method, url).bearer_auth(&self.token)
    }

    async fn send_json<T, F>(&self, make_request: F) -> PmResult<T>
    where
        T: DeserializeOwned,
        F: Fn() -> reqwest::RequestBuilder,
    {
        for attempt in 0..=RATE_LIMIT_RETRIES {
            let response = make_request()
                .send()
                .await
                .map_err(|err| PmError::Message(format!("asana request failed: {err}")))?;

            if response.status() == StatusCode::TOO_MANY_REQUESTS && attempt < RATE_LIMIT_RETRIES {
                let delay = super::retry_after_delay(response.headers());
                warn!(
                    attempt = attempt + 1,
                    delay_seconds = delay.as_secs(),
                    "asana rate limited; retrying"
                );
                sleep(delay).await;
                continue;
            }

            return parse_response(response).await;
        }

        Err(PmError::Message(
            "asana request failed after retries".to_string(),
        ))
    }

    /// List all workspaces visible to the authenticated user.
    pub async fn list_workspaces(&self) -> PmResult<Vec<AsanaWorkspace>> {
        let response: AsanaResponse<Vec<AsanaWorkspace>> = self
            .send_json(|| self.request(Method::GET, "/workspaces", &[]))
            .await?;
        Ok(response.data)
    }

    /// Resolve the workspace GID: use config if set, otherwise auto-detect.
    /// Fails if the user has zero or multiple workspaces and none is configured.
    pub async fn resolve_workspace(&self) -> PmResult<String> {
        if let Some(workspace) = &self.config.workspace {
            return Ok(workspace.clone());
        }

        let workspaces = self.list_workspaces().await?;
        match workspaces.len() {
            0 => Err(PmError::Message(
                "no asana workspaces found for this token".to_string(),
            )),
            1 => Ok(workspaces.into_iter().next().expect("len is 1").gid),
            n => {
                let list: Vec<String> = workspaces
                    .iter()
                    .map(|ws| format!("  {} ({})", ws.name, ws.gid))
                    .collect();
                Err(PmError::Message(format!(
                    "found {n} asana workspaces — set asana.workspace in .lf/config.yaml:\n{}",
                    list.join("\n")
                )))
            }
        }
    }

    async fn list_teams(&self, workspace_id: &str) -> PmResult<Vec<AsanaTeam>> {
        let path = format!("/workspaces/{workspace_id}/teams");
        let response: AsanaResponse<Vec<AsanaTeam>> = self
            .send_json(|| self.request(Method::GET, &path, &[]))
            .await?;
        Ok(response.data)
    }

    async fn create_team_in_workspace(&self, workspace_id: &str, name: &str) -> PmResult<String> {
        let body = AsanaRequest {
            data: CreateTeamRequest {
                name,
                organization: workspace_id,
            },
        };
        let response: AsanaResponse<AsanaGid> = self
            .send_json(|| self.request(Method::POST, "/teams", &[]).json(&body))
            .await?;
        Ok(response.data.gid)
    }

    async fn resolve_team_for_project_bootstrap(&self, workspace_id: &str) -> PmResult<String> {
        if let Some(team) = self.config.default_team.as_deref() {
            return Ok(team.to_string());
        }

        let teams = self.list_teams(workspace_id).await?;
        if let Some(existing) = teams
            .iter()
            .find(|team| team.name.eq_ignore_ascii_case(DEFAULT_LOOPFLOW_TEAM_NAME))
        {
            return Ok(existing.gid.clone());
        }

        self.create_team_in_workspace(workspace_id, DEFAULT_LOOPFLOW_TEAM_NAME)
            .await
    }

    async fn create_project_for_team(
        &self,
        team_id: &str,
        name: &str,
        description: &str,
    ) -> PmResult<String> {
        let body = AsanaRequest {
            data: CreateProjectForTeamRequest {
                name,
                notes: description,
            },
        };
        let path = format!("/teams/{team_id}/projects");
        let response: AsanaResponse<AsanaGid> = self
            .send_json(|| self.request(Method::POST, &path, &[]).json(&body))
            .await?;
        Ok(response.data.gid)
    }

    async fn priority_field_for_project(
        &self,
        project_id: &str,
    ) -> PmResult<Option<AsanaPriorityField>> {
        let path = format!("/projects/{project_id}/custom_field_settings");
        let response: AsanaResponse<Vec<AsanaCustomFieldSetting>> = self
            .send_json(|| {
                self.request(
                    Method::GET,
                    &path,
                    &[("opt_fields", PROJECT_PRIORITY_FIELD_FIELDS)],
                )
            })
            .await?;

        Ok(response
            .data
            .into_iter()
            .find_map(|setting| AsanaPriorityField::from_metadata(setting.custom_field)))
    }

    async fn ensure_priority_field_for_project(
        &self,
        project_id: &str,
    ) -> PmResult<AsanaPriorityField> {
        if let Some(field) = self.priority_field_for_project(project_id).await? {
            return Ok(field);
        }

        let body = json!({
            "data": {
                "custom_field": {
                    "name": PRIORITY_FIELD_NAME,
                    "resource_subtype": "enum",
                    "enum_options": [
                        { "name": PriorityBucket::Urgent.semantic_label() },
                        { "name": PriorityBucket::High.semantic_label() },
                        { "name": PriorityBucket::Medium.semantic_label() },
                        { "name": PriorityBucket::Low.semantic_label() }
                    ]
                }
            }
        });
        let path = format!("/projects/{project_id}/addCustomFieldSetting");
        let _: AsanaResponse<Value> = self
            .send_json(|| self.request(Method::POST, &path, &[]).json(&body))
            .await?;

        self.priority_field_for_project(project_id)
            .await?
            .ok_or_else(|| {
                PmError::Message(format!(
                    "asana project {project_id} is missing a priority custom field after creation"
                ))
            })
    }

    async fn working_branch_field_for_project(&self, project_id: &str) -> PmResult<Option<String>> {
        let path = format!("/projects/{project_id}/custom_field_settings");
        let response: AsanaResponse<Vec<AsanaCustomFieldSetting>> = self
            .send_json(|| {
                self.request(
                    Method::GET,
                    &path,
                    &[("opt_fields", PROJECT_TEXT_FIELD_FIELDS)],
                )
            })
            .await?;

        Ok(response
            .data
            .into_iter()
            .find_map(|setting| working_branch_gid_from_metadata(setting.custom_field)))
    }

    async fn workspace_working_branch_field(&self, workspace_id: &str) -> PmResult<Option<String>> {
        let path = format!("/workspaces/{workspace_id}/custom_fields");
        let response: AsanaResponse<Vec<AsanaCustomFieldMetadata>> = self
            .send_json(|| {
                self.request(
                    Method::GET,
                    &path,
                    &[("opt_fields", WORKSPACE_TEXT_FIELD_FIELDS)],
                )
            })
            .await?;

        Ok(response
            .data
            .into_iter()
            .find_map(working_branch_gid_from_metadata))
    }

    async fn create_workspace_working_branch_field(&self, workspace_id: &str) -> PmResult<String> {
        let body = json!({
            "data": {
                "name": WORKING_BRANCH_FIELD_NAME,
                "resource_subtype": "text",
                "workspace": workspace_id
            }
        });
        let response: AsanaResponse<AsanaGid> = self
            .send_json(|| {
                self.request(Method::POST, "/custom_fields", &[])
                    .json(&body)
            })
            .await?;
        Ok(response.data.gid)
    }

    async fn attach_working_branch_field_to_project(
        &self,
        project_id: &str,
        field_id: &str,
    ) -> PmResult<()> {
        let body = json!({ "data": { "custom_field": field_id } });
        let path = format!("/projects/{project_id}/addCustomFieldSetting");
        let _: AsanaResponse<Value> = self
            .send_json(|| self.request(Method::POST, &path, &[]).json(&body))
            .await?;
        Ok(())
    }

    async fn ensure_working_branch_field_for_project(&self, project_id: &str) -> PmResult<String> {
        if let Some(field_id) = self.working_branch_field_for_project(project_id).await? {
            return Ok(field_id);
        }

        let workspace_id = self.resolve_workspace().await?;
        let field_id = match self.workspace_working_branch_field(&workspace_id).await? {
            Some(field_id) => field_id,
            None => {
                self.create_workspace_working_branch_field(&workspace_id)
                    .await?
            }
        };
        self.attach_working_branch_field_to_project(project_id, &field_id)
            .await?;

        self.working_branch_field_for_project(project_id)
            .await?
            .ok_or_else(|| {
                PmError::Message(format!(
                    "asana project {project_id} is missing a Working branch custom field after setup"
                ))
            })
    }
}

#[async_trait]
impl PmProvider for AsanaClient {
    async fn create_project(&self, name: &str, description: &str) -> PmResult<String> {
        let workspace = self.resolve_workspace().await?;
        let team = self.resolve_team_for_project_bootstrap(&workspace).await?;
        self.create_project_for_team(&team, name, description).await
    }

    async fn list_projects(&self, team_id: &str) -> PmResult<Vec<PmProject>> {
        let path = format!("/teams/{team_id}/projects");
        let response: AsanaResponse<Vec<AsanaProjectNode>> = self
            .send_json(|| self.request(Method::GET, &path, &[("opt_fields", "name")]))
            .await?;
        Ok(response
            .data
            .into_iter()
            .map(|p| PmProject {
                id: p.gid,
                name: p.name,
            })
            .collect())
    }

    async fn init_project(&self, project_id: &str) -> PmResult<()> {
        self.ensure_working_branch_field_for_project(project_id)
            .await
            .map(|_| ())
    }

    async fn list_items(&self, project_id: &str) -> PmResult<Vec<PmItem>> {
        let path = format!("/projects/{project_id}/tasks");
        let mut offset = None;
        let mut items = Vec::new();
        let mut response_index = 0usize;

        loop {
            let page_offset = offset.clone();
            let response: AsanaListResponse<AsanaTask> = self
                .send_json(|| {
                    let mut query = vec![("opt_fields", TASK_FIELDS)];
                    if let Some(offset) = page_offset.as_deref() {
                        query.push(("offset", offset));
                    }
                    self.request(Method::GET, &path, &query)
                })
                .await?;

            for task in response.data {
                items.push((response_index, task.into_pm_item()));
                response_index += 1;
            }

            offset = response.next_page.and_then(|page| page.offset);
            if offset.is_none() {
                items.sort_by(|left, right| {
                    left.1
                        .rank
                        .cmp(&right.1.rank)
                        .then_with(|| left.0.cmp(&right.0))
                });
                return Ok(items.into_iter().map(|(_, item)| item).collect());
            }
        }
    }

    async fn create_item(&self, project_id: &str, item: &PmItemCreate) -> PmResult<String> {
        let priority_field = self.ensure_priority_field_for_project(project_id).await?;
        let priority_field_id = priority_field.gid.clone();
        let priority_option_id = priority_field
            .option_gid(PriorityBucket::from_rank(item.rank))
            .to_string();
        let html_notes = markdown_to_asana_html(&item.description);
        let mut data = Map::new();
        data.insert("name".to_string(), json!(item.name));
        data.insert("html_notes".to_string(), json!(html_notes));
        data.insert("projects".to_string(), json!([project_id]));
        data.insert(
            "custom_fields".to_string(),
            json!({
                priority_field_id: priority_option_id,
            }),
        );
        let body = json!({ "data": data });

        let response: AsanaResponse<AsanaGid> = self
            .send_json(|| self.request(Method::POST, "/tasks", &[]).json(&body))
            .await?;
        Ok(response.data.gid)
    }

    async fn update_item(&self, item_id: &str, update: &PmItemUpdate) -> PmResult<()> {
        let Some(update) = update.text_update() else {
            return Ok(());
        };

        let mut data = Map::new();
        if let Some(name) = update.name {
            data.insert("name".to_string(), json!(name));
        }
        if let Some(description) = update.description {
            data.insert(
                "html_notes".to_string(),
                json!(markdown_to_asana_html(description)),
            );
        }

        let body = json!({ "data": data });
        let path = format!("/tasks/{item_id}");
        let _: AsanaResponse<Value> = self
            .send_json(|| self.request(Method::PUT, &path, &[]).json(&body))
            .await?;
        Ok(())
    }

    async fn complete_item(&self, item_id: &str) -> PmResult<()> {
        let body = AsanaRequest {
            data: UpdateTaskRequest::completed(),
        };
        let path = format!("/tasks/{item_id}");
        let _: AsanaResponse<Value> = self
            .send_json(|| self.request(Method::PUT, &path, &[]).json(&body))
            .await?;
        Ok(())
    }

    async fn comment(&self, item_id: &str, body: &str) -> PmResult<()> {
        let request = AsanaRequest {
            data: CreateStoryRequest { text: body },
        };
        let path = format!("/tasks/{item_id}/stories");
        let _: AsanaResponse<Value> = self
            .send_json(|| self.request(Method::POST, &path, &[]).json(&request))
            .await?;
        Ok(())
    }

    async fn claim_item(&self, item_id: &str, branch: &str) -> PmResult<()> {
        let me: AsanaResponse<AsanaGid> = self
            .send_json(|| self.request(Method::GET, "/users/me", &[("opt_fields", "gid")]))
            .await?;
        let my_gid = me.data.gid;

        let path = format!("/tasks/{item_id}");
        let task: AsanaResponse<Value> = self
            .send_json(|| self.request(Method::GET, &path, &[("opt_fields", CLAIM_TASK_FIELDS)]))
            .await?;
        let field_id = working_branch_field_from_task(&task.data).ok_or_else(|| {
            PmError::Message(
                "asana task is missing a Working branch custom field; run `lf op pm init` for this wave"
                    .to_string(),
            )
        })?;
        let current_branch = working_branch_value(&task.data, &field_id);
        if current_branch.is_some_and(|actual| !actual.is_empty() && actual != branch) {
            return Err(PmError::Message(format!(
                "item claimed by another worker (expected branch {branch}, got {current_branch:?})"
            )));
        }

        let mut custom_fields = Map::new();
        custom_fields.insert(field_id.clone(), json!(branch));
        let body = json!({
            "data": {
                "assignee": "me",
                "custom_fields": custom_fields
            }
        });
        let _: AsanaResponse<Value> = self
            .send_json(|| self.request(Method::PUT, &path, &[]).json(&body))
            .await?;

        let task: AsanaResponse<Value> = self
            .send_json(|| self.request(Method::GET, &path, &[("opt_fields", CLAIM_TASK_FIELDS)]))
            .await?;
        let actual_assignee = task.data.pointer("/assignee/gid").and_then(|v| v.as_str());
        if actual_assignee != Some(&my_gid) {
            return Err(PmError::Message(format!(
                "item claimed by another assignee (expected {my_gid}, got {actual_assignee:?})"
            )));
        }

        let actual_branch = working_branch_value(&task.data, &field_id);
        if actual_branch != Some(branch) {
            return Err(PmError::Message(format!(
                "item claimed by another worker (expected branch {branch}, got {actual_branch:?})"
            )));
        }

        self.comment(item_id, &format!("Working branch: `{branch}`"))
            .await?;
        Ok(())
    }
}

#[derive(Serialize)]
struct AsanaRequest<T> {
    data: T,
}

#[derive(Serialize)]
struct CreateProjectForTeamRequest<'a> {
    name: &'a str,
    notes: &'a str,
}

#[derive(Serialize)]
struct CreateTeamRequest<'a> {
    name: &'a str,
    organization: &'a str,
}

#[derive(Serialize)]
struct UpdateTaskRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    completed: Option<bool>,
}

impl UpdateTaskRequest {
    fn completed() -> Self {
        Self {
            completed: Some(true),
        }
    }
}

#[derive(Serialize)]
struct CreateStoryRequest<'a> {
    text: &'a str,
}

#[derive(Deserialize)]
struct AsanaResponse<T> {
    data: T,
}

#[derive(Deserialize)]
struct AsanaListResponse<T> {
    data: Vec<T>,
    next_page: Option<AsanaPageInfo>,
}

#[derive(Deserialize)]
struct AsanaTask {
    gid: String,
    name: String,
    #[serde(default)]
    notes: String,
    #[serde(default)]
    html_notes: String,
    #[serde(default)]
    completed: bool,
    #[serde(default)]
    assignee: Option<AsanaGid>,
    #[serde(default)]
    custom_fields: Vec<AsanaCustomFieldValue>,
}

#[derive(Deserialize)]
struct AsanaGid {
    gid: String,
}

impl AsanaTask {
    fn into_pm_item(self) -> PmItem {
        let rank = self.priority_bucket().rank();
        let assignee = self.assignee.map(|a| a.gid);
        let description = if self.html_notes.is_empty() {
            self.notes
        } else {
            asana_html_to_markdown(&self.html_notes)
        };

        PmItem {
            id: self.gid,
            name: self.name,
            description,
            rank,
            completed: self.completed,
            assignee,
        }
    }

    fn priority_bucket(&self) -> PriorityBucket {
        self.custom_fields
            .iter()
            .find_map(AsanaPriorityField::priority_from_value)
            .unwrap_or(PriorityBucket::Low)
    }
}

#[derive(Deserialize)]
struct AsanaCustomFieldValue {
    #[serde(default)]
    resource_subtype: String,
    #[serde(default)]
    enum_value: Option<AsanaEnumOption>,
    #[serde(default)]
    enum_options: Vec<AsanaEnumOption>,
}

#[derive(Deserialize)]
struct AsanaCustomFieldSetting {
    custom_field: AsanaCustomFieldMetadata,
}

#[derive(Deserialize)]
struct AsanaCustomFieldMetadata {
    gid: String,
    #[serde(default)]
    name: String,
    #[serde(default)]
    resource_subtype: String,
    #[serde(default)]
    enum_options: Vec<AsanaEnumOption>,
}

#[derive(Deserialize)]
struct AsanaEnumOption {
    gid: String,
    #[serde(default)]
    name: String,
}

#[derive(Debug)]
struct AsanaPriorityField {
    gid: String,
    options: [String; 4],
}

impl AsanaPriorityField {
    fn from_metadata(field: AsanaCustomFieldMetadata) -> Option<Self> {
        if field.resource_subtype != "enum" {
            return None;
        }

        let mut options: [Option<String>; 4] = std::array::from_fn(|_| None);

        for option in field.enum_options {
            if let Some(bucket) = PriorityBucket::from_semantic_label(&option.name) {
                options[usize::from(bucket.order())] = Some(option.gid);
            }
        }

        Some(Self {
            gid: field.gid,
            options: [
                options[0].take()?,
                options[1].take()?,
                options[2].take()?,
                options[3].take()?,
            ],
        })
    }

    fn priority_from_value(field: &AsanaCustomFieldValue) -> Option<PriorityBucket> {
        if field.resource_subtype != "enum" {
            return None;
        }
        let mut buckets = [false; 4];
        for option in &field.enum_options {
            if let Some(bucket) = PriorityBucket::from_semantic_label(&option.name) {
                buckets[usize::from(bucket.order())] = true;
            }
        }
        if buckets.into_iter().any(|present| !present) {
            return None;
        }
        let current = field.enum_value.as_ref()?;
        PriorityBucket::from_semantic_label(&current.name)
    }

    fn option_gid(&self, priority: PriorityBucket) -> &str {
        &self.options[usize::from(priority.order())]
    }
}

fn working_branch_gid_from_metadata(field: AsanaCustomFieldMetadata) -> Option<String> {
    if field.name == WORKING_BRANCH_FIELD_NAME && field.resource_subtype == "text" {
        Some(field.gid)
    } else {
        None
    }
}

fn working_branch_field_from_task(task: &Value) -> Option<String> {
    task.pointer("/custom_fields")?
        .as_array()?
        .iter()
        .find(|field| {
            field.pointer("/name").and_then(|v| v.as_str()) == Some(WORKING_BRANCH_FIELD_NAME)
                && field.pointer("/resource_subtype").and_then(|v| v.as_str()) == Some("text")
        })
        .and_then(|field| field.pointer("/gid"))
        .and_then(|value| value.as_str())
        .map(str::to_string)
}

fn working_branch_value<'a>(task: &'a Value, field_id: &str) -> Option<&'a str> {
    task.pointer("/custom_fields")?
        .as_array()?
        .iter()
        .find(|field| field.pointer("/gid").and_then(|v| v.as_str()) == Some(field_id))
        .and_then(|field| field.pointer("/text_value"))
        .and_then(|value| value.as_str())
}

#[derive(Debug, Clone, Deserialize)]
pub struct AsanaWorkspace {
    pub gid: String,
    pub name: String,
}

#[derive(Debug, Clone, Deserialize)]
struct AsanaTeam {
    gid: String,
    name: String,
}

#[derive(Deserialize)]
struct AsanaProjectNode {
    gid: String,
    name: String,
}

#[derive(Deserialize)]
struct AsanaPageInfo {
    offset: Option<String>,
}

#[derive(Deserialize)]
struct AsanaErrorBody {
    errors: Vec<AsanaErrorMessage>,
}

#[derive(Deserialize)]
struct AsanaErrorMessage {
    message: String,
}

async fn parse_response<T: DeserializeOwned>(response: reqwest::Response) -> PmResult<T> {
    let status = response.status();
    let body = response
        .bytes()
        .await
        .map_err(|err| PmError::Message(format!("failed to read asana response: {err}")))?;

    if !status.is_success() {
        return Err(PmError::Message(parse_error_message(status, &body)));
    }

    serde_json::from_slice(&body)
        .map_err(|err| PmError::Message(format!("failed to decode asana response: {err}")))
}

fn parse_error_message(status: StatusCode, body: &[u8]) -> String {
    if let Ok(error_body) = serde_json::from_slice::<AsanaErrorBody>(body) {
        if let Some(error) = error_body.errors.first() {
            if error.message.contains("Missing required `team` field") {
                return format!(
                    "asana request failed with status {status}: Missing required `team` field. Set `pm.team` in wave/<name>/<name>.yaml or `asana.default_team` in .lf/config.yaml."
                );
            }
            return format!(
                "asana request failed with status {status}: {}",
                error.message
            );
        }
    }

    let body_text = String::from_utf8_lossy(body).trim().to_string();
    if body_text.is_empty() {
        format!("asana request failed with status {status}")
    } else {
        format!("asana request failed with status {status}: {body_text}")
    }
}

#[cfg(test)]
mod tests {
    use axum::http::StatusCode;
    use serde_json::{json, Map, Value};

    use super::*;
    use crate::engine::config::AsanaConfig;
    use crate::lfd::pm::test_server::{self, json_response, response};
    use crate::lfd::pm::PmProvider;

    fn working_branch_metadata() -> Value {
        json!({
            "gid": "field-branch",
            "name": "Working branch",
            "resource_subtype": "text"
        })
    }

    fn working_branch_setting() -> Value {
        json!({ "custom_field": working_branch_metadata() })
    }

    fn working_branch_field(branch: Option<&str>) -> Value {
        let mut field = Map::new();
        field.insert("gid".to_string(), json!("field-branch"));
        field.insert("name".to_string(), json!("Working branch"));
        field.insert("resource_subtype".to_string(), json!("text"));
        if let Some(branch) = branch {
            field.insert("text_value".to_string(), json!(branch));
        }
        Value::Object(field)
    }

    fn task_with_working_branch(assignee: Option<&str>, branch: Option<&str>) -> Value {
        let mut task = Map::new();
        task.insert("gid".to_string(), json!("task-1"));
        if let Some(assignee) = assignee {
            task.insert("assignee".to_string(), json!({ "gid": assignee }));
        }
        task.insert(
            "custom_fields".to_string(),
            json!([working_branch_field(branch)]),
        );
        Value::Object(task)
    }

    #[tokio::test]
    async fn create_project_uses_workspace_and_team() {
        let (base_url, requests) = test_server::spawn(vec![json_response(
            StatusCode::CREATED,
            json!({ "data": { "gid": "project-123" } }),
        )])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig {
                workspace: Some("workspace-1".to_string()),
                default_team: Some("team-9".to_string()),
            },
            base_url,
        );

        let project_id = client
            .create_project("Wave PM", "Ship the Asana client")
            .await
            .expect("create project should succeed");

        assert_eq!(project_id, "project-123");
        let requests = requests.lock().await;
        assert_eq!(requests.len(), 1);
        assert_eq!(requests[0].method, "POST");
        assert_eq!(requests[0].path, "/teams/team-9/projects");
        assert_eq!(
            requests[0].authorization.as_deref(),
            Some("Bearer secret-token")
        );
        let body: Value = serde_json::from_str(&requests[0].body).expect("json body");
        assert_eq!(
            body,
            json!({
                "data": {
                    "name": "Wave PM",
                    "notes": "Ship the Asana client"
                }
            })
        );
    }

    #[tokio::test]
    async fn create_project_reuses_existing_loopflow_team_when_default_missing() {
        let (base_url, requests) = test_server::spawn(vec![
            json_response(
                StatusCode::OK,
                json!({
                    "data": [
                        { "gid": "team-1", "name": "Waves" },
                        { "gid": "team-2", "name": "Other" }
                    ]
                }),
            ),
            json_response(
                StatusCode::CREATED,
                json!({ "data": { "gid": "project-123" } }),
            ),
        ])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig {
                workspace: Some("workspace-1".to_string()),
                default_team: None,
            },
            base_url,
        );

        let project_id = client
            .create_project("Wave PM", "Ship the Asana client")
            .await
            .expect("create project should succeed");

        assert_eq!(project_id, "project-123");
        let requests = requests.lock().await;
        assert_eq!(requests.len(), 2);
        assert_eq!(requests[0].method, "GET");
        assert_eq!(requests[0].path, "/workspaces/workspace-1/teams");
        assert_eq!(requests[1].method, "POST");
        assert_eq!(requests[1].path, "/teams/team-1/projects");
    }

    #[tokio::test]
    async fn create_project_creates_loopflow_team_when_missing() {
        let (base_url, requests) = test_server::spawn(vec![
            json_response(StatusCode::OK, json!({ "data": [] })),
            json_response(
                StatusCode::CREATED,
                json!({ "data": { "gid": "team-loopflow" } }),
            ),
            json_response(
                StatusCode::CREATED,
                json!({ "data": { "gid": "project-123" } }),
            ),
        ])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig {
                workspace: Some("workspace-1".to_string()),
                default_team: None,
            },
            base_url,
        );

        let project_id = client
            .create_project("Wave PM", "Ship the Asana client")
            .await
            .expect("create project should succeed");

        assert_eq!(project_id, "project-123");
        let requests = requests.lock().await;
        assert_eq!(requests.len(), 3);
        assert_eq!(requests[0].method, "GET");
        assert_eq!(requests[0].path, "/workspaces/workspace-1/teams");
        assert_eq!(requests[1].method, "POST");
        assert_eq!(requests[1].path, "/teams");
        assert_eq!(
            serde_json::from_str::<Value>(&requests[1].body).expect("json body"),
            json!({
                "data": {
                    "name": "Waves",
                    "organization": "workspace-1"
                }
            })
        );
        assert_eq!(requests[2].method, "POST");
        assert_eq!(requests[2].path, "/teams/team-loopflow/projects");
    }

    #[tokio::test]
    async fn create_project_fails_with_no_workspaces() {
        let (base_url, _requests) =
            test_server::spawn(vec![json_response(StatusCode::OK, json!({ "data": [] }))]).await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig::default(),
            base_url,
        );

        let error = client
            .create_project("Wave PM", "Ship the Asana client")
            .await
            .expect_err("should fail with no workspaces");

        assert_eq!(
            error,
            PmError::Message("no asana workspaces found for this token".to_string())
        );
    }

    #[test]
    fn parse_error_message_for_missing_team_is_actionable() {
        let body = serde_json::to_vec(&json!({
            "errors": [{ "message": "Missing required `team` field" }]
        }))
        .expect("json body");

        let message = parse_error_message(StatusCode::BAD_REQUEST, &body);

        assert!(message.contains("pm.team"));
        assert!(message.contains("asana.default_team"));
    }

    #[tokio::test]
    async fn list_items_collects_all_pages_and_maps_priority_buckets() {
        let (base_url, requests) = test_server::spawn(vec![
            json_response(
                StatusCode::OK,
                json!({
                    "data": [
                        {
                            "gid": "task-1",
                            "name": "First",
                            "notes": "one",
                            "completed": false,
                            "custom_fields": [{
                                "gid": "field-priority",
                                "name": "Priority",
                                "resource_subtype": "enum",
                                "enum_value": { "gid": "opt-p2", "name": "Medium" },
                                "enum_options": [
                                    { "gid": "opt-p0", "name": "Urgent" },
                                    { "gid": "opt-p1", "name": "High" },
                                    { "gid": "opt-p2", "name": "Medium" },
                                    { "gid": "opt-p3", "name": "Low" }
                                ]
                            }]
                        },
                        {
                            "gid": "task-2",
                            "name": "Second",
                            "notes": "fallback two",
                            "html_notes": "<p><strong>two</strong></p>",
                            "completed": true,
                            "custom_fields": [{
                                "gid": "field-priority",
                                "name": "Priority",
                                "resource_subtype": "enum",
                                "enum_value": { "gid": "opt-p0", "name": "Urgent" },
                                "enum_options": [
                                    { "gid": "opt-p0", "name": "Urgent" },
                                    { "gid": "opt-p1", "name": "High" },
                                    { "gid": "opt-p2", "name": "Medium" },
                                    { "gid": "opt-p3", "name": "Low" }
                                ]
                            }]
                        }
                    ],
                    "next_page": { "offset": "cursor-2" }
                }),
            ),
            json_response(
                StatusCode::OK,
                json!({
                    "data": [
                        {
                            "gid": "task-3",
                            "name": "Third",
                            "notes": "fallback three",
                            "html_notes": "<p>three</p>",
                            "completed": false,
                            "custom_fields": [{
                                "gid": "field-priority",
                                "name": "Priority",
                                "resource_subtype": "enum",
                                "enum_value": { "gid": "opt-p1", "name": "High" },
                                "enum_options": [
                                    { "gid": "opt-p0", "name": "Urgent" },
                                    { "gid": "opt-p1", "name": "High" },
                                    { "gid": "opt-p2", "name": "Medium" },
                                    { "gid": "opt-p3", "name": "Low" }
                                ]
                            }]
                        }
                    ],
                    "next_page": null
                }),
            ),
        ])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig::default(),
            base_url,
        );

        let items = client
            .list_items("project-123")
            .await
            .expect("list items should succeed");

        assert_eq!(
            items,
            vec![
                PmItem {
                    id: "task-2".to_string(),
                    name: "Second".to_string(),
                    description: "**two**".to_string(),
                    rank: 0,
                    completed: true,
                    assignee: None,
                },
                PmItem {
                    id: "task-3".to_string(),
                    name: "Third".to_string(),
                    description: "three".to_string(),
                    rank: 1,
                    completed: false,
                    assignee: None,
                },
                PmItem {
                    id: "task-1".to_string(),
                    name: "First".to_string(),
                    description: "one".to_string(),
                    rank: 2,
                    completed: false,
                    assignee: None,
                },
            ]
        );
        let requests = requests.lock().await;
        assert_eq!(requests.len(), 2);
        assert_eq!(requests[0].path, "/projects/project-123/tasks");
        assert!(requests[0]
            .query
            .as_deref()
            .expect("query")
            .starts_with("opt_fields="));
        assert!(requests[1]
            .query
            .as_deref()
            .expect("query")
            .contains("offset=cursor-2"));
    }

    #[test]
    fn into_pm_item_prefers_html_notes_and_falls_back_to_notes() {
        let html_task = AsanaTask {
            gid: "task-html".to_string(),
            name: "Rich".to_string(),
            notes: "plaintext".to_string(),
            html_notes: "<p><strong>formatted</strong></p>".to_string(),
            completed: false,
            assignee: Some(AsanaGid {
                gid: "user-1".to_string(),
            }),
            custom_fields: Vec::new(),
        };
        let plain_task = AsanaTask {
            gid: "task-plain".to_string(),
            name: "Plain".to_string(),
            notes: "plaintext".to_string(),
            html_notes: String::new(),
            completed: true,
            assignee: None,
            custom_fields: Vec::new(),
        };

        assert_eq!(html_task.into_pm_item().description, "**formatted**");
        let item = plain_task.into_pm_item();
        assert_eq!(item.description, "plaintext");
        assert!(item.completed);
        assert_eq!(item.assignee, None);
    }

    #[tokio::test]
    async fn create_update_complete_and_comment_map_to_asana_endpoints() {
        let (base_url, requests) = test_server::spawn(vec![
            json_response(
                StatusCode::OK,
                json!({
                    "data": [{
                        "custom_field": {
                            "gid": "field-priority",
                            "name": "Priority",
                            "resource_subtype": "enum",
                            "enum_options": [
                                { "gid": "opt-p0", "name": "Urgent" },
                                { "gid": "opt-p1", "name": "High" },
                                { "gid": "opt-p2", "name": "Medium" },
                                { "gid": "opt-p3", "name": "Low" }
                            ]
                        }
                    }]
                }),
            ),
            json_response(
                StatusCode::CREATED,
                json!({ "data": { "gid": "task-123" } }),
            ),
            json_response(StatusCode::OK, json!({ "data": { "gid": "task-123" } })),
            json_response(StatusCode::OK, json!({ "data": { "gid": "task-123" } })),
            json_response(StatusCode::CREATED, json!({ "data": { "gid": "story-1" } })),
        ])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig::default(),
            base_url,
        );

        let item_id = client
            .create_item(
                "project-123",
                &PmItemCreate {
                    name: "Implement client".to_string(),
                    description: "Build the HTTP adapter".to_string(),
                    rank: 0,
                },
            )
            .await
            .expect("create item should succeed");
        client
            .update_item(
                &item_id,
                &PmItemUpdate {
                    name: Some("Implement Asana client".to_string()),
                    description: Some("Build the HTTP adapter and tests".to_string()),
                    rank: Some(1),
                },
            )
            .await
            .expect("update item should succeed");
        client
            .complete_item(&item_id)
            .await
            .expect("complete item should succeed");
        client
            .comment(&item_id, "Shipped in v0.9.9")
            .await
            .expect("comment should succeed");

        assert_eq!(item_id, "task-123");
        let requests = requests.lock().await;
        assert_eq!(requests.len(), 5);

        assert_eq!(requests[0].method, "GET");
        assert_eq!(
            requests[0].path,
            "/projects/project-123/custom_field_settings"
        );
        assert_eq!(requests[1].method, "POST");
        assert_eq!(requests[1].path, "/tasks");
        assert_eq!(
            serde_json::from_str::<Value>(&requests[1].body).expect("json body"),
            json!({
                "data": {
                    "name": "Implement client",
                    "html_notes": "<body>Build the HTTP adapter\n</body>",
                    "projects": ["project-123"],
                    "custom_fields": {
                        "field-priority": "opt-p0"
                    }
                }
            })
        );

        assert_eq!(requests[2].method, "PUT");
        assert_eq!(requests[2].path, "/tasks/task-123");
        assert_eq!(
            serde_json::from_str::<Value>(&requests[2].body).expect("json body"),
            json!({
                "data": {
                    "name": "Implement Asana client",
                    "html_notes": "<body>Build the HTTP adapter and tests\n</body>"
                }
            })
        );

        assert_eq!(requests[3].method, "PUT");
        assert_eq!(requests[3].path, "/tasks/task-123");
        assert_eq!(
            serde_json::from_str::<Value>(&requests[3].body).expect("json body"),
            json!({ "data": { "completed": true } })
        );

        assert_eq!(requests[4].method, "POST");
        assert_eq!(requests[4].path, "/tasks/task-123/stories");
        assert_eq!(
            serde_json::from_str::<Value>(&requests[4].body).expect("json body"),
            json!({ "data": { "text": "Shipped in v0.9.9" } })
        );
    }

    #[tokio::test]
    async fn update_item_skips_rank_only_updates() {
        let (base_url, requests) = test_server::spawn(Vec::new()).await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig::default(),
            base_url,
        );

        client
            .update_item(
                "task-123",
                &PmItemUpdate {
                    name: None,
                    description: None,
                    rank: Some(2),
                },
            )
            .await
            .expect("rank-only update should no-op");

        assert!(requests.lock().await.is_empty());
    }

    #[tokio::test]
    async fn retries_after_rate_limit_response() {
        let (base_url, requests) = test_server::spawn(vec![
            json_response(
                StatusCode::OK,
                json!({
                    "data": [{
                        "custom_field": {
                            "gid": "field-priority",
                            "name": "Priority",
                            "resource_subtype": "enum",
                            "enum_options": [
                                { "gid": "opt-p0", "name": "Urgent" },
                                { "gid": "opt-p1", "name": "High" },
                                { "gid": "opt-p2", "name": "Medium" },
                                { "gid": "opt-p3", "name": "Low" }
                            ]
                        }
                    }]
                }),
            ),
            response(
                StatusCode::TOO_MANY_REQUESTS,
                vec![("retry-after", "0")],
                json!({ "errors": [{ "message": "slow down" }] }).to_string(),
            ),
            json_response(
                StatusCode::CREATED,
                json!({ "data": { "gid": "task-123" } }),
            ),
        ])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig::default(),
            base_url,
        );

        let item_id = client
            .create_item(
                "project-123",
                &PmItemCreate {
                    name: "Implement client".to_string(),
                    description: "Build the HTTP adapter".to_string(),
                    rank: 1,
                },
            )
            .await
            .expect("request should succeed after retry");

        assert_eq!(item_id, "task-123");
        assert_eq!(requests.lock().await.len(), 3);
    }

    #[tokio::test]
    async fn surfaces_asana_error_messages() {
        let (base_url, _requests) = test_server::spawn(vec![json_response(
            StatusCode::BAD_REQUEST,
            json!({ "errors": [{ "message": "workspace is required" }] }),
        )])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig {
                workspace: Some("workspace-1".to_string()),
                default_team: None,
            },
            base_url,
        );

        let error = client
            .create_project("Wave PM", "Ship the Asana client")
            .await
            .expect_err("asana error should surface");

        assert_eq!(
            error,
            PmError::Message(
                "asana request failed with status 400 Bad Request: workspace is required"
                    .to_string()
            )
        );
    }

    #[tokio::test]
    async fn init_project_attaches_workspace_working_branch_field() {
        let (base_url, requests) = test_server::spawn(vec![
            json_response(StatusCode::OK, json!({ "data": [] })),
            json_response(
                StatusCode::OK,
                json!({ "data": [working_branch_metadata()] }),
            ),
            json_response(StatusCode::OK, json!({ "data": { "gid": "setting-1" } })),
            json_response(
                StatusCode::OK,
                json!({ "data": [working_branch_setting()] }),
            ),
        ])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig {
                workspace: Some("workspace-1".to_string()),
                default_team: None,
            },
            base_url,
        );

        client
            .init_project("project-123")
            .await
            .expect("init should attach the shared field");

        let requests = requests.lock().await;
        assert_eq!(requests.len(), 4);
        assert_eq!(
            requests[0].path,
            "/projects/project-123/custom_field_settings"
        );
        assert_eq!(requests[1].path, "/workspaces/workspace-1/custom_fields");
        assert_eq!(
            requests[2].path,
            "/projects/project-123/addCustomFieldSetting"
        );
        assert_eq!(
            serde_json::from_str::<Value>(&requests[2].body).expect("json body"),
            json!({ "data": { "custom_field": "field-branch" } })
        );
    }

    #[tokio::test]
    async fn init_project_creates_workspace_working_branch_field_when_missing() {
        let (base_url, requests) = test_server::spawn(vec![
            json_response(StatusCode::OK, json!({ "data": [] })),
            json_response(StatusCode::OK, json!({ "data": [] })),
            json_response(
                StatusCode::CREATED,
                json!({ "data": { "gid": "field-branch" } }),
            ),
            json_response(StatusCode::OK, json!({ "data": { "gid": "setting-1" } })),
            json_response(
                StatusCode::OK,
                json!({ "data": [working_branch_setting()] }),
            ),
        ])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig {
                workspace: Some("workspace-1".to_string()),
                default_team: None,
            },
            base_url,
        );

        client
            .init_project("project-123")
            .await
            .expect("init should create and attach the shared field");

        let requests = requests.lock().await;
        assert_eq!(requests.len(), 5);
        assert_eq!(requests[2].path, "/custom_fields");
        assert_eq!(
            serde_json::from_str::<Value>(&requests[2].body).expect("json body"),
            json!({
                "data": {
                    "name": "Working branch",
                    "resource_subtype": "text",
                    "workspace": "workspace-1"
                }
            })
        );
    }

    #[tokio::test]
    async fn claim_item_verifies_working_branch_matches() {
        let (base_url, requests) = test_server::spawn(vec![
            json_response(StatusCode::OK, json!({ "data": { "gid": "user-42" } })),
            json_response(
                StatusCode::OK,
                json!({ "data": task_with_working_branch(None, None) }),
            ),
            json_response(StatusCode::OK, json!({ "data": { "gid": "task-1" } })),
            json_response(
                StatusCode::OK,
                json!({ "data": task_with_working_branch(Some("user-42"), Some("feature/test")) }),
            ),
            json_response(StatusCode::CREATED, json!({ "data": { "gid": "story-1" } })),
        ])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig::default(),
            base_url,
        );

        client
            .claim_item("task-1", "feature/test")
            .await
            .expect("claim should succeed when branch matches");

        let requests = requests.lock().await;
        assert_eq!(requests.len(), 5);
        assert_eq!(requests[0].method, "GET");
        assert!(requests[0].path.contains("/users/me"));
        assert_eq!(requests[1].method, "GET");
        assert_eq!(requests[2].method, "PUT");
        assert_eq!(
            serde_json::from_str::<Value>(&requests[2].body).expect("json body"),
            json!({
                "data": {
                    "assignee": "me",
                    "custom_fields": { "field-branch": "feature/test" }
                }
            })
        );
        assert_eq!(requests[3].method, "GET");
        assert_eq!(requests[4].method, "POST");
    }

    #[tokio::test]
    async fn claim_item_fails_when_another_assignee_wins() {
        let (base_url, _requests) = test_server::spawn(vec![
            json_response(StatusCode::OK, json!({ "data": { "gid": "user-42" } })),
            json_response(
                StatusCode::OK,
                json!({ "data": task_with_working_branch(None, None) }),
            ),
            json_response(StatusCode::OK, json!({ "data": { "gid": "task-1" } })),
            json_response(
                StatusCode::OK,
                json!({ "data": task_with_working_branch(Some("user-99"), Some("feature/test")) }),
            ),
        ])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig::default(),
            base_url,
        );

        let error = client
            .claim_item("task-1", "feature/test")
            .await
            .expect_err("claim should fail when another assignee wins");
        assert!(error.to_string().contains("another assignee"));
    }

    #[tokio::test]
    async fn claim_item_fails_same_account_concurrent() {
        let (base_url, _requests) = test_server::spawn(vec![
            json_response(StatusCode::OK, json!({ "data": { "gid": "user-42" } })),
            json_response(
                StatusCode::OK,
                json!({ "data": task_with_working_branch(None, None) }),
            ),
            json_response(StatusCode::OK, json!({ "data": { "gid": "task-1" } })),
            json_response(
                StatusCode::OK,
                json!({ "data": task_with_working_branch(Some("user-42"), Some("worker-a")) }),
            ),
            json_response(StatusCode::CREATED, json!({ "data": { "gid": "story-1" } })),
            json_response(StatusCode::OK, json!({ "data": { "gid": "user-42" } })),
            json_response(
                StatusCode::OK,
                json!({ "data": task_with_working_branch(None, Some("worker-a")) }),
            ),
            json_response(StatusCode::OK, json!({ "data": { "gid": "task-1" } })),
            json_response(
                StatusCode::OK,
                json!({ "data": task_with_working_branch(Some("user-42"), Some("worker-a")) }),
            ),
        ])
        .await;
        let client = AsanaClient::with_base_url(
            "secret-token".to_string(),
            AsanaConfig::default(),
            base_url,
        );

        client
            .claim_item("task-1", "worker-a")
            .await
            .expect("first branch should win");
        let error = client
            .claim_item("task-1", "worker-b")
            .await
            .expect_err("second branch should lose even with the same account");
        assert!(error.to_string().contains("another worker"));
    }
}