forge-orchestrator 1.8.0

Orchestration for Claude Code on shared repos, with Codex CLI and Antigravity CLI (agy) as task runners — single Rust binary, zero deps.
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// The lifecycle phase a task belongs to.
///
/// Tasks progress through phases: Build -> Verify -> Fix (if needed) -> UAT -> Ship.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TaskPhase {
    /// Initial implementation phase (T-xxx tasks).
    Build,
    /// Automated verification phase (V-xxx tasks).
    Verify,
    /// Fix phase for issues found during verification (F-xxx tasks).
    Fix,
    /// User acceptance testing phase (U-xxx tasks, human-only).
    Uat,
    /// Ship phase — changelog, archive, release.
    Ship,
}

impl std::fmt::Display for TaskPhase {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TaskPhase::Build => write!(f, "build"),
            TaskPhase::Verify => write!(f, "verify"),
            TaskPhase::Fix => write!(f, "fix"),
            TaskPhase::Uat => write!(f, "uat"),
            TaskPhase::Ship => write!(f, "ship"),
        }
    }
}

/// Current status of a task in its lifecycle.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TaskStatus {
    /// Not yet claimed by any agent.
    Pending,
    /// Claimed by an agent but execution has not started.
    Assigned,
    /// Actively being worked on by an agent.
    InProgress,
    /// Successfully finished.
    Completed,
    /// Execution failed (may be retried).
    Failed,
    /// Waiting on unmet dependency tasks.
    Blocked,
}

/// Supported AI agent backends.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum AgentType {
    /// Anthropic Claude Code CLI.
    Claude,
    /// OpenAI Codex CLI.
    Codex,
    /// Antigravity CLI (`agy`). The variant and its serialized id stay `gemini` because task files,
    /// config keys and MCP arguments already store that id; renaming it would break existing projects.
    Gemini,
    /// Any available agent (auto-assigned by the scheduler).
    Any,
}

impl std::fmt::Display for AgentType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AgentType::Claude => write!(f, "claude"),
            AgentType::Codex => write!(f, "codex"),
            AgentType::Gemini => write!(f, "gemini"),
            AgentType::Any => write!(f, "any"),
        }
    }
}

impl std::str::FromStr for AgentType {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "claude" => Ok(AgentType::Claude),
            "codex" => Ok(AgentType::Codex),
            "gemini" => Ok(AgentType::Gemini),
            "any" => Ok(AgentType::Any),
            _ => Err(anyhow::anyhow!("Unknown agent type: {s}")),
        }
    }
}

/// A unit of work in the Forge orchestration system.
///
/// Tasks are persisted as both markdown (`.md`) and JSON (`.json`) files
/// under `.forge/tasks/`. The JSON sidecar is the machine-readable source of truth.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
    /// Unique identifier with phase prefix (e.g., `"T-001"`, `"V-002"`, `"U-003"`).
    pub id: String,
    /// Short human-readable title.
    pub title: String,
    /// Detailed description of what the task requires.
    pub description: String,
    /// Current lifecycle status.
    pub status: TaskStatus,
    /// Agent assigned to execute this task, or `None` if unassigned.
    pub assigned_to: Option<AgentType>,
    /// Task type hint for adapter strategy: design, implement, review, test, document.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub task_type: Option<String>,
    /// Task IDs that must complete before this task can start.
    pub depends_on: Vec<String>,
    /// File paths under exclusive lock while this task is in progress.
    pub locked_files: Vec<String>,
    /// Criteria that must be satisfied for the task to be marked complete.
    pub acceptance_criteria: Vec<String>,
    /// When this task was created.
    pub created_at: DateTime<Utc>,
    /// Last modification timestamp.
    pub updated_at: DateTime<Utc>,
    /// When the task finished (regardless of success or failure).
    pub completed_at: Option<DateTime<Utc>>,
    /// Which plan generation pass created this task.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plan_version: Option<u32>,
    /// Parent task ID for subtasks (e.g., V-002's parent is T-002)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_task: Option<String>,
    /// Lifecycle phase: build, verify, fix
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phase: Option<TaskPhase>,
    /// Retry count for verify/fix loops (max 3 before flagging for human)
    #[serde(default)]
    pub retry_count: u32,
    /// Agent that verified this task (populated when a V-xxx subtask completes)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub verified_by: Option<AgentType>,
    /// When this task was verified
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub verified_at: Option<DateTime<Utc>>,
    /// Outcome reported when the task was completed (`forge_complete_task` `result_summary`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_summary: Option<String>,
    /// Agent that completed the task (explicit `agent` argument, else the claiming agent).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub completed_by: Option<AgentType>,
    /// Where `completed_by` came from, so a reader can tell a stated agent from an inferred one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub completed_by_source: Option<CompletedBySource>,
}

/// Provenance of a task's `completed_by`.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CompletedBySource {
    /// The completing call named the agent (`forge_complete_task` `agent`).
    Explicit,
    /// Forge's own engine ran the agent that completed the task (`forge run`, `start`, dashboard).
    Engine,
    /// Inferred from the agent that claimed the task.
    Claimer,
}

impl std::fmt::Display for CompletedBySource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Explicit => "explicit",
            Self::Engine => "engine",
            Self::Claimer => "claimer",
        })
    }
}

impl Task {
    /// Create a new task with `Pending` status and the current timestamp.
    pub fn new(
        id: impl Into<String>,
        title: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: id.into(),
            title: title.into(),
            description: description.into(),
            status: TaskStatus::Pending,
            assigned_to: None,
            task_type: None,
            depends_on: Vec::new(),
            locked_files: Vec::new(),
            acceptance_criteria: Vec::new(),
            created_at: now,
            updated_at: now,
            completed_at: None,
            plan_version: None,
            parent_task: None,
            phase: None,
            retry_count: 0,
            verified_by: None,
            verified_at: None,
            result_summary: None,
            completed_by: None,
            completed_by_source: None,
        }
    }

    /// Returns `true` if any dependency task ID is not in the completed set.
    pub fn is_blocked(&self, completed_tasks: &[String]) -> bool {
        self.depends_on
            .iter()
            .any(|dep| !completed_tasks.contains(dep))
    }

    /// Write task as a markdown file to .forge/tasks/
    pub fn write_to_file(&self, forge_dir: &Path) -> anyhow::Result<()> {
        let tasks_dir = forge_dir.join("tasks");
        std::fs::create_dir_all(&tasks_dir)?;

        let content = format!(
            "# {id}: {title}\n\n\
             **Status:** {status:?}\n\
             **Assigned to:** {agent}\n\
             **Type:** {task_type}\n\
             **Phase:** {phase}\n\
             **Parent:** {parent}\n\
             **Created:** {created}\n\
             **Updated:** {updated}\n\n\
             ## Description\n\n{description}\n\n\
             ## Dependencies\n\n{deps}\n\n\
             ## Locked Files\n\n{files}\n\n\
             ## Acceptance Criteria\n\n{criteria}\n{outcome}",
            id = self.id,
            title = self.title,
            status = self.status,
            agent = self
                .assigned_to
                .as_ref()
                .map(|a| a.to_string())
                .unwrap_or_else(|| "unassigned".into()),
            task_type = self.task_type.as_deref().unwrap_or("—"),
            phase = self
                .phase
                .as_ref()
                .map(|p| p.to_string())
                .unwrap_or_else(|| "—".into()),
            parent = self.parent_task.as_deref().unwrap_or("—"),
            created = self.created_at.format("%Y-%m-%d %H:%M UTC"),
            updated = self.updated_at.format("%Y-%m-%d %H:%M UTC"),
            description = self.description,
            deps = if self.depends_on.is_empty() {
                "None".to_string()
            } else {
                self.depends_on
                    .iter()
                    .map(|d| format!("- {d}"))
                    .collect::<Vec<_>>()
                    .join("\n")
            },
            files = if self.locked_files.is_empty() {
                "None".to_string()
            } else {
                self.locked_files
                    .iter()
                    .map(|f| format!("- `{f}`"))
                    .collect::<Vec<_>>()
                    .join("\n")
            },
            outcome = if self.completed_at.is_some() || self.result_summary.is_some() {
                format!(
                    "\n## Outcome\n\n**Completed by:** {by}\n**Completed:** {at}\n\n{summary}\n",
                    by = match (&self.completed_by, self.completed_by_source) {
                        (Some(a), Some(src)) => format!("{a} ({src})"),
                        (Some(a), None) => a.to_string(),
                        (None, _) => "—".into(),
                    },
                    at = self
                        .completed_at
                        .map(|t| t.format("%Y-%m-%d %H:%M UTC").to_string())
                        .unwrap_or_else(|| "—".into()),
                    summary = self
                        .result_summary
                        .as_deref()
                        .unwrap_or("No summary recorded."),
                )
            } else {
                String::new()
            },
            criteria = if self.acceptance_criteria.is_empty() {
                "None specified".to_string()
            } else {
                self.acceptance_criteria
                    .iter()
                    .map(|c| format!("- [ ] {c}"))
                    .collect::<Vec<_>>()
                    .join("\n")
            },
        );

        let path = tasks_dir.join(format!("{}.md", self.id));
        write_atomic(&path, content.as_bytes())
    }

    /// Read task from a JSON sidecar file
    pub fn read_from_json(forge_dir: &Path, task_id: &str) -> anyhow::Result<Self> {
        let path = forge_dir.join("tasks").join(format!("{task_id}.json"));
        let content = std::fs::read_to_string(path)?;
        Ok(serde_json::from_str(&content)?)
    }

    /// Write task JSON sidecar for machine parsing
    pub fn write_json(&self, forge_dir: &Path) -> anyhow::Result<()> {
        let tasks_dir = forge_dir.join("tasks");
        std::fs::create_dir_all(&tasks_dir)?;
        let path = tasks_dir.join(format!("{}.json", self.id));
        let content = serde_json::to_string_pretty(self)?;
        write_atomic(&path, content.as_bytes())
    }
}

/// Write `content` to `path` through a temp file in the same directory and a rename, so a reader
/// never sees a partly written file, and a symlink at `path` is replaced instead of followed.
fn write_atomic(path: &Path, content: &[u8]) -> anyhow::Result<()> {
    use std::io::Write;
    let dir = path.parent().unwrap_or_else(|| Path::new("."));
    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("task");
    let tmp = dir.join(format!(".{name}.{}.tmp", uuid::Uuid::new_v4()));
    let result = (|| {
        let mut file = std::fs::File::create(&tmp)?;
        file.write_all(content)?;
        file.sync_all()?;
        std::fs::rename(&tmp, path)
    })();
    if result.is_err() {
        let _ = std::fs::remove_file(&tmp);
    }
    Ok(result?)
}

/// Manages the collection of tasks stored in `.forge/tasks/`.
///
/// Provides CRUD operations, ID generation, and subtask generation
/// for verify, UAT, and fix phases.
pub struct TaskManager {
    /// Path to the `.forge/` directory.
    forge_dir: PathBuf,
}

impl TaskManager {
    /// Create a new `TaskManager` targeting the given `.forge/` directory.
    pub fn new(forge_dir: impl Into<PathBuf>) -> Self {
        Self {
            forge_dir: forge_dir.into(),
        }
    }

    /// Persist a NEW task to disk as both markdown and JSON files.
    ///
    /// Refuses an id that already exists instead of overwriting it, so two writers that picked
    /// the same next id (the plan generator, the dashboard, an MCP client) cannot destroy each
    /// other's task. Use [`TaskManager::update_task`] to change an existing task.
    pub fn create_task(&self, task: &Task) -> anyhow::Result<()> {
        if !self.reserve_id(&task.id)? {
            anyhow::bail!("task {} already exists", task.id);
        }
        if let Err(e) = task.write_json(&self.forge_dir) {
            let _ = std::fs::remove_file(self.json_path(&task.id));
            return Err(e);
        }
        task.write_to_file(&self.forge_dir)
    }

    fn json_path(&self, id: &str) -> PathBuf {
        self.forge_dir.join("tasks").join(format!("{id}.json"))
    }

    /// Claim `tasks/<id>.json` with an exclusive create. `Ok(false)` means the id is taken.
    fn reserve_id(&self, id: &str) -> anyhow::Result<bool> {
        std::fs::create_dir_all(self.forge_dir.join("tasks"))?;
        match std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(self.json_path(id))
        {
            Ok(_) => Ok(true),
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(false),
            Err(e) => Err(e.into()),
        }
    }

    /// List all tasks from JSON files on disk, sorted by ID.
    pub fn list_tasks(&self) -> anyhow::Result<Vec<Task>> {
        let tasks_dir = self.forge_dir.join("tasks");
        if !tasks_dir.exists() {
            return Ok(Vec::new());
        }

        let mut tasks = Vec::new();
        for entry in std::fs::read_dir(&tasks_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().is_some_and(|ext| ext == "json") {
                let content = std::fs::read_to_string(&path)?;
                if let Ok(task) = serde_json::from_str::<Task>(&content) {
                    tasks.push(task);
                }
            }
        }

        tasks.sort_by(|a, b| a.id.cmp(&b.id));
        Ok(tasks)
    }

    /// Load a single task by ID from its JSON sidecar file.
    pub fn get_task(&self, task_id: &str) -> anyhow::Result<Task> {
        Task::read_from_json(&self.forge_dir, task_id)
    }

    /// Update a task by overwriting its files on disk.
    pub fn update_task(&self, task: &Task) -> anyhow::Result<()> {
        task.write_json(&self.forge_dir)?;
        task.write_to_file(&self.forge_dir)
    }

    /// Return the IDs of all tasks with `Completed` status.
    pub fn get_completed_task_ids(&self) -> anyhow::Result<Vec<String>> {
        Ok(self
            .list_tasks()?
            .into_iter()
            .filter(|t| t.status == TaskStatus::Completed)
            .map(|t| t.id)
            .collect())
    }

    /// Create one new build task with the next free `T-NNN` id and return it.
    ///
    /// The id is reserved by creating `tasks/T-NNN.json` with `create_new` (as every
    /// [`TaskManager::create_task`] does), so concurrent writers can never take the same id or
    /// overwrite each other's task: a caller that loses the race moves on to the next number.
    pub fn create_next_task(&self, title: &str, description: &str) -> anyhow::Result<Task> {
        let mut n = self.next_task_number()?;
        for _ in 0..1000 {
            let id = format!("T-{n:03}");
            if self.reserve_id(&id)? {
                let task = Task::new(id, title, description);
                if let Err(e) = task.write_json(&self.forge_dir) {
                    let _ = std::fs::remove_file(self.json_path(&task.id));
                    return Err(e);
                }
                task.write_to_file(&self.forge_dir)?;
                return Ok(task);
            }
            n += 1;
        }
        anyhow::bail!("no free task id after 1000 attempts starting at T-{n:03}")
    }

    /// Find the highest existing task ID number and return the next one.
    /// If no tasks exist, returns 1.
    pub fn next_task_number(&self) -> anyhow::Result<u32> {
        let tasks_dir = self.forge_dir.join("tasks");
        if !tasks_dir.exists() {
            return Ok(1);
        }

        let mut max_id: u32 = 0;
        for entry in std::fs::read_dir(&tasks_dir)? {
            let entry = entry?;
            let name = entry.file_name().to_string_lossy().to_string();
            if let Some(num_str) = name
                .strip_prefix("T-")
                .and_then(|s| s.strip_suffix(".json"))
                && let Ok(num) = num_str.parse::<u32>()
            {
                max_id = max_id.max(num);
            }
        }

        Ok(max_id + 1)
    }

    /// Find the highest existing verify task ID number (V-NNN) and return the next one.
    pub fn next_verify_number(&self) -> anyhow::Result<u32> {
        let tasks_dir = self.forge_dir.join("tasks");
        if !tasks_dir.exists() {
            return Ok(1);
        }
        let mut max_id: u32 = 0;
        for entry in std::fs::read_dir(&tasks_dir)? {
            let entry = entry?;
            let name = entry.file_name().to_string_lossy().to_string();
            if let Some(num_str) = name
                .strip_prefix("V-")
                .and_then(|s| s.strip_suffix(".json"))
                && let Ok(num) = num_str.parse::<u32>()
            {
                max_id = max_id.max(num);
            }
        }
        Ok(max_id + 1)
    }

    /// Find the highest existing UAT task ID number (U-NNN) and return the next one.
    pub fn next_uat_number(&self) -> anyhow::Result<u32> {
        let tasks_dir = self.forge_dir.join("tasks");
        if !tasks_dir.exists() {
            return Ok(1);
        }
        let mut max_id: u32 = 0;
        for entry in std::fs::read_dir(&tasks_dir)? {
            let entry = entry?;
            let name = entry.file_name().to_string_lossy().to_string();
            if let Some(num_str) = name
                .strip_prefix("U-")
                .and_then(|s| s.strip_suffix(".json"))
                && let Ok(num) = num_str.parse::<u32>()
            {
                max_id = max_id.max(num);
            }
        }
        Ok(max_id + 1)
    }

    /// Generate UAT subtasks for completed user-facing T-xxx tasks.
    /// U-xxx tasks are human-only validation checkpoints — never dispatched to AI.
    pub fn generate_uat_subtasks(&self) -> anyhow::Result<Vec<Task>> {
        use crate::brain::rule_based::{generate_uat_criteria, is_user_facing};

        let tasks = self.list_tasks()?;
        let mut next_u = self.next_uat_number()?;
        let mut generated = Vec::new();

        for task in &tasks {
            // Only completed T-xxx build tasks (skip V-xxx, U-xxx, Fix)
            if task.status != TaskStatus::Completed {
                continue;
            }
            if task.phase == Some(TaskPhase::Verify)
                || task.phase == Some(TaskPhase::Uat)
                || task.phase == Some(TaskPhase::Fix)
            {
                continue;
            }
            // Must start with T- (skip V-, U- by ID prefix too)
            if !task.id.starts_with("T-") {
                continue;
            }

            // Skip non-user-facing tasks
            if !is_user_facing(&task.title, &task.description) {
                continue;
            }

            // Skip if already has a U-xxx child (idempotent)
            let has_uat = tasks.iter().any(|t| {
                t.parent_task.as_deref() == Some(&task.id) && t.phase == Some(TaskPhase::Uat)
            });
            if has_uat {
                continue;
            }

            // Find corresponding V-xxx if exists
            let verify_id = tasks
                .iter()
                .find(|t| {
                    t.parent_task.as_deref() == Some(&task.id) && t.phase == Some(TaskPhase::Verify)
                })
                .map(|t| t.id.clone());

            // Generate human-testable acceptance criteria
            let criteria = generate_uat_criteria(&task.title, &task.acceptance_criteria);

            let uat_id = format!("U-{next_u:03}");
            let mut uat_task = Task::new(
                &uat_id,
                format!("UAT: {}", task.title),
                format!(
                    "Human validation for task {}.\nVerify user-facing behavior meets expectations.",
                    task.id,
                ),
            );
            uat_task.parent_task = Some(task.id.clone());
            uat_task.phase = Some(TaskPhase::Uat);
            uat_task.task_type = Some("uat".to_string());
            uat_task.depends_on = vec![verify_id.unwrap_or_else(|| task.id.clone())];
            uat_task.assigned_to = None; // Human-only
            uat_task.acceptance_criteria = criteria;

            self.create_task(&uat_task)?;
            generated.push(uat_task);
            next_u += 1;
        }
        Ok(generated)
    }

    /// Generate verify subtasks for each completed implement/test task that lacks one.
    pub fn generate_verify_subtasks(&self) -> anyhow::Result<Vec<Task>> {
        let tasks = self.list_tasks()?;
        let mut next_v = self.next_verify_number()?;
        let mut generated = Vec::new();

        for task in &tasks {
            if task.status != TaskStatus::Completed {
                continue;
            }
            let task_type = task.task_type.as_deref().unwrap_or("");
            if !matches!(task_type, "implement" | "test" | "") {
                continue;
            }

            // Skip if already has a verify subtask
            let has_verify = tasks.iter().any(|t| {
                t.parent_task.as_deref() == Some(&task.id) && t.phase == Some(TaskPhase::Verify)
            });
            if has_verify {
                continue;
            }

            let verify_id = format!("V-{next_v:03}");
            let mut verify_task = Task::new(
                &verify_id,
                format!("Verify: {}", task.title),
                format!(
                    "VERIFY task {} by RUNNING tests, type checker, and linter.\n\
                     Do NOT just read the code — actively execute verification commands.\n\n\
                     Original task: {}\n\n\
                     Original criteria:\n{}\n\n\
                     Your job: Confirm these criteria are met by running the actual test suite, \
                     type checker, and linter. Report specific pass/fail results.",
                    task.id,
                    task.description,
                    task.acceptance_criteria
                        .iter()
                        .map(|c| format!("- {c}"))
                        .collect::<Vec<_>>()
                        .join("\n")
                ),
            );
            verify_task.parent_task = Some(task.id.clone());
            verify_task.phase = Some(TaskPhase::Verify);
            verify_task.task_type = Some("verify".to_string());
            verify_task.depends_on = vec![task.id.clone()];
            verify_task.locked_files = task.locked_files.clone();

            // Enrich acceptance criteria with verification-specific checks
            let mut enriched: Vec<String> = task
                .acceptance_criteria
                .iter()
                .map(|c| format!("Verify: {}", c))
                .collect();
            enriched.push(
                "All project tests pass (run the test suite, don't just read code)".to_string(),
            );
            enriched.push(
                "Type checker passes with zero errors (e.g. tsc --noEmit, mypy, clippy)"
                    .to_string(),
            );
            enriched.push("No new lint warnings introduced".to_string());
            enriched.push(
                "All new files have corresponding test files with meaningful assertions"
                    .to_string(),
            );

            // If the task touches auth/routing/middleware, add cross-cutting checks
            let combined_text = format!(
                "{} {}",
                task.title.to_lowercase(),
                task.description.to_lowercase()
            );
            let cross_cutting_keywords = [
                "auth",
                "jwt",
                "login",
                "route",
                "guard",
                "middleware",
                "interceptor",
                "session",
                "token",
                "cors",
                "permission",
            ];
            if cross_cutting_keywords
                .iter()
                .any(|kw| combined_text.contains(kw))
            {
                enriched.push(
                    "E2E tests still pass (auth/routing changes are cross-cutting)".to_string(),
                );
                enriched.push(
                    "Test mocks and fixtures updated to match new auth/routing state".to_string(),
                );
            }

            // If the task touches UI/frontend, add Playwright-aware checks
            let ui_keywords = [
                "component",
                "page",
                "dashboard",
                "ui",
                "frontend",
                "render",
                "view",
                "layout",
                "button",
                "form",
                "modal",
                "dialog",
                "navigation",
                "sidebar",
            ];
            if ui_keywords.iter().any(|kw| combined_text.contains(kw)) {
                enriched.push(
                    "Playwright E2E tests pass with zero console errors (use page.on('console') and page.on('pageerror') to capture browser errors)".to_string(),
                );
                enriched.push(
                    "No uncaught exceptions or unhandled promise rejections in browser console"
                        .to_string(),
                );
            }

            verify_task.acceptance_criteria = enriched;

            // CRITICAL: Cross-agent verification — the verifier MUST be a
            // different agent than the builder. This is the Circular Validation
            // Trap defense: if the same agent builds and verifies, it will
            // repeat its own mistakes instead of catching them.
            let builder = task.assigned_to.clone().unwrap_or(AgentType::Claude);
            verify_task.assigned_to = Some(pick_different_agent(&builder));

            self.create_task(&verify_task)?;
            generated.push(verify_task);
            next_v += 1;
        }
        Ok(generated)
    }

    /// The first pending task whose dependencies are all completed (UAT-phase tasks excluded).
    pub fn get_next_available(&self) -> anyhow::Result<Option<Task>> {
        let completed = self.get_completed_task_ids()?;
        Ok(self.list_tasks()?.into_iter().find(|t| {
            t.status == TaskStatus::Pending
                && !t.is_blocked(&completed)
                && t.phase != Some(TaskPhase::Uat)
        }))
    }

    /// Generate fix tasks for failed quality gates.
    /// Fix tasks have phase=Build and task_type="fix" so they get dispatched to agents
    /// but do NOT generate V-xxx verify subtasks (generate_verify_subtasks skips "fix").
    pub fn generate_gate_fix_tasks(
        &self,
        failed_gates: &[crate::core::quality_gate::GateResult],
    ) -> anyhow::Result<Vec<Task>> {
        let mut generated = Vec::new();

        for (next_t, gate) in (self.next_task_number()?..).zip(failed_gates.iter()) {
            let task_id = format!("T-{next_t:03}");
            let stderr_tail = truncate_output(&gate.stderr, 1500);
            let stdout_tail = truncate_output(&gate.stdout, 1500);

            let mut fix_task = Task::new(
                &task_id,
                format!("Fix: {} failures", gate.gate_name),
                format!(
                    "The quality gate '{}' failed with exit code {}.\n\
                     Fix ALL errors reported below. Run the gate command to verify your fix.\n\n\
                     STDERR:\n{}\n\n\
                     STDOUT:\n{}",
                    gate.gate_name, gate.exit_code, stderr_tail, stdout_tail,
                ),
            );
            fix_task.phase = Some(TaskPhase::Build);
            fix_task.task_type = Some("fix".to_string());
            fix_task.acceptance_criteria = vec![
                format!("{} passes with exit code 0", gate.gate_name),
                "No regressions introduced by the fix".to_string(),
            ];
            fix_task.assigned_to = Some(AgentType::Claude);

            self.create_task(&fix_task)?;
            generated.push(fix_task);
        }
        Ok(generated)
    }
}

/// Pick a different agent than the builder for cross-agent verification.
/// Ensures v.agent != t.agent — the Circular Validation Trap defense.
fn pick_different_agent(builder: &AgentType) -> AgentType {
    match builder {
        AgentType::Claude | AgentType::Any => AgentType::Codex,
        AgentType::Codex => AgentType::Claude,
        AgentType::Gemini => AgentType::Claude,
    }
}

/// Keep the last `max` characters of output for task descriptions.
fn truncate_output(s: &str, max: usize) -> String {
    if s.len() <= max {
        s.to_string()
    } else {
        format!("...truncated...\n{}", &s[s.len() - max..])
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_next_task_number_empty_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());
        assert_eq!(mgr.next_task_number().unwrap(), 1);
    }

    #[test]
    fn test_next_task_number_sequential() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());
        // Create T-001, T-002, T-003
        for i in 1..=3 {
            let task = Task::new(format!("T-{i:03}"), "Test", "desc");
            mgr.create_task(&task).unwrap();
        }
        assert_eq!(mgr.next_task_number().unwrap(), 4);
    }

    #[test]
    fn test_next_task_number_finds_max_not_count() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());
        // Create T-001, T-005, T-017 (gaps)
        for i in [1, 5, 17] {
            let task = Task::new(format!("T-{i:03}"), "Test", "desc");
            mgr.create_task(&task).unwrap();
        }
        // Should return 18, not 4
        assert_eq!(mgr.next_task_number().unwrap(), 18);
    }

    #[test]
    fn test_next_task_number_ignores_non_task_files() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());
        let tasks_dir = tmp.path().join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();

        // Create a real task
        let task = Task::new("T-003", "Test", "desc");
        mgr.create_task(&task).unwrap();

        // Create non-task files that should be ignored
        std::fs::write(tasks_dir.join("archive.json"), "{}").unwrap();
        std::fs::write(tasks_dir.join("T-003.md"), "# markdown").unwrap();
        std::fs::write(tasks_dir.join("notes.txt"), "notes").unwrap();

        assert_eq!(mgr.next_task_number().unwrap(), 4);
    }

    #[test]
    fn test_plan_version_field() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new("T-001", "Test", "desc");
        task.plan_version = Some(1);
        mgr.create_task(&task).unwrap();

        let loaded = mgr.get_task("T-001").unwrap();
        assert_eq!(loaded.plan_version, Some(1));
    }

    #[test]
    fn test_existing_tasks_not_overwritten() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        // Simulate first plan: T-001 completed
        let mut task1 = Task::new("T-001", "Auth module", "Implement auth");
        task1.status = TaskStatus::Completed;
        task1.plan_version = Some(1);
        mgr.create_task(&task1).unwrap();

        // Simulate second plan: new task at T-002
        let mut task2 = Task::new("T-002", "Caching layer", "Add caching");
        task2.plan_version = Some(2);
        mgr.create_task(&task2).unwrap();

        // Verify T-001 is still completed and untouched
        let loaded_t1 = mgr.get_task("T-001").unwrap();
        assert_eq!(loaded_t1.status, TaskStatus::Completed);
        assert_eq!(loaded_t1.plan_version, Some(1));
        assert_eq!(loaded_t1.title, "Auth module");

        // Verify T-002 exists with version 2
        let loaded_t2 = mgr.get_task("T-002").unwrap();
        assert_eq!(loaded_t2.plan_version, Some(2));
    }

    #[test]
    fn test_task_phase_serialization_roundtrip() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new("V-001", "Verify auth", "desc");
        task.phase = Some(TaskPhase::Verify);
        task.parent_task = Some("T-001".to_string());
        task.retry_count = 2;
        mgr.create_task(&task).unwrap();

        let loaded = mgr.get_task("V-001").unwrap();
        assert_eq!(loaded.phase, Some(TaskPhase::Verify));
        assert_eq!(loaded.parent_task, Some("T-001".to_string()));
        assert_eq!(loaded.retry_count, 2);
    }

    #[test]
    fn test_task_phase_display() {
        assert_eq!(TaskPhase::Build.to_string(), "build");
        assert_eq!(TaskPhase::Verify.to_string(), "verify");
        assert_eq!(TaskPhase::Fix.to_string(), "fix");
        assert_eq!(TaskPhase::Uat.to_string(), "uat");
    }

    #[test]
    fn test_task_phase_uat_display() {
        assert_eq!(TaskPhase::Uat.to_string(), "uat");
    }

    #[test]
    fn test_next_uat_number_empty() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());
        assert_eq!(mgr.next_uat_number().unwrap(), 1);
    }

    #[test]
    fn test_next_uat_number_existing() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());
        for i in [1, 3] {
            let mut task = Task::new(format!("U-{i:03}"), "UAT task", "desc");
            task.phase = Some(TaskPhase::Uat);
            mgr.create_task(&task).unwrap();
        }
        assert_eq!(mgr.next_uat_number().unwrap(), 4);
    }

    #[test]
    fn test_generate_uat_for_ui_task() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new(
            "T-001",
            "Add dashboard sidebar",
            "Create navigation sidebar component",
        );
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        task.phase = Some(TaskPhase::Build);
        mgr.create_task(&task).unwrap();

        let generated = mgr.generate_uat_subtasks().unwrap();
        assert_eq!(generated.len(), 1);
        assert_eq!(generated[0].id, "U-001");
        assert_eq!(generated[0].parent_task, Some("T-001".to_string()));
        assert_eq!(generated[0].phase, Some(TaskPhase::Uat));
        assert_eq!(generated[0].task_type, Some("uat".to_string()));
        assert!(generated[0].assigned_to.is_none()); // Human-only
        assert!(!generated[0].acceptance_criteria.is_empty());
    }

    #[test]
    fn test_generate_uat_skips_backend() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new(
            "T-001",
            "Refactor database module",
            "Clean up internal SQL layer",
        );
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        task.phase = Some(TaskPhase::Build);
        mgr.create_task(&task).unwrap();

        let generated = mgr.generate_uat_subtasks().unwrap();
        assert_eq!(generated.len(), 0); // Internal/infra task — no UAT
    }

    #[test]
    fn test_generate_uat_depends_on_verify() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        // Create T-001 (completed build task with UI keyword)
        let mut t1 = Task::new("T-001", "Add dashboard layout", "Create main layout");
        t1.task_type = Some("implement".to_string());
        t1.status = TaskStatus::Completed;
        t1.phase = Some(TaskPhase::Build);
        mgr.create_task(&t1).unwrap();

        // Create V-001 (verify subtask of T-001)
        let mut v1 = Task::new("V-001", "Verify: Add dashboard layout", "desc");
        v1.phase = Some(TaskPhase::Verify);
        v1.parent_task = Some("T-001".to_string());
        v1.status = TaskStatus::Completed;
        mgr.create_task(&v1).unwrap();

        let generated = mgr.generate_uat_subtasks().unwrap();
        assert_eq!(generated.len(), 1);
        assert_eq!(generated[0].depends_on, vec!["V-001".to_string()]);
    }

    #[test]
    fn test_generate_uat_idempotent() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new("T-001", "Add sidebar component", "UI sidebar");
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        task.phase = Some(TaskPhase::Build);
        mgr.create_task(&task).unwrap();

        let gen1 = mgr.generate_uat_subtasks().unwrap();
        assert_eq!(gen1.len(), 1);

        let gen2 = mgr.generate_uat_subtasks().unwrap();
        assert_eq!(gen2.len(), 0); // Idempotent
    }

    #[test]
    fn test_retry_count_defaults_to_zero() {
        let task = Task::new("T-001", "Test", "desc");
        assert_eq!(task.retry_count, 0);
        assert!(task.parent_task.is_none());
        assert!(task.phase.is_none());
    }

    #[test]
    fn test_next_verify_number_empty() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());
        assert_eq!(mgr.next_verify_number().unwrap(), 1);
    }

    #[test]
    fn test_next_verify_number_with_existing() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());
        for i in [1, 3] {
            let mut task = Task::new(format!("V-{i:03}"), "Verify", "desc");
            task.phase = Some(TaskPhase::Verify);
            mgr.create_task(&task).unwrap();
        }
        assert_eq!(mgr.next_verify_number().unwrap(), 4);
    }

    #[test]
    fn test_generate_verify_subtasks_for_completed() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new("T-001", "Auth module", "Implement auth");
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        mgr.create_task(&task).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated.len(), 1);
        assert_eq!(generated[0].id, "V-001");
        assert_eq!(generated[0].parent_task, Some("T-001".to_string()));
        assert_eq!(generated[0].phase, Some(TaskPhase::Verify));
        assert_eq!(generated[0].assigned_to, Some(AgentType::Codex));
    }

    #[test]
    fn test_generate_verify_subtasks_idempotent() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new("T-001", "Auth module", "Implement auth");
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        mgr.create_task(&task).unwrap();

        // First call generates
        let gen1 = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(gen1.len(), 1);

        // Second call is idempotent
        let gen2 = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(gen2.len(), 0);
    }

    #[test]
    fn test_generate_verify_skips_non_implement() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new("T-001", "Write docs", "docs");
        task.task_type = Some("document".to_string());
        task.status = TaskStatus::Completed;
        mgr.create_task(&task).unwrap();

        // "document" tasks should NOT get verify subtasks
        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated.len(), 0);
    }

    #[test]
    fn test_generate_verify_agent_assignment() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        // Unassigned task defaults to Claude → verifier must be Codex (different agent)
        let mut t1 = Task::new("T-001", "Default task", "desc");
        t1.task_type = Some("implement".to_string());
        t1.status = TaskStatus::Completed;
        mgr.create_task(&t1).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated[0].assigned_to, Some(AgentType::Codex));
    }

    #[test]
    fn test_cross_agent_verification_never_same_agent() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        // Codex built it → Claude must verify (v.agent != t.agent)
        let mut t1 = Task::new("T-001", "Codex task", "desc");
        t1.task_type = Some("implement".to_string());
        t1.status = TaskStatus::Completed;
        t1.assigned_to = Some(AgentType::Codex);
        mgr.create_task(&t1).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated.len(), 1);
        assert_eq!(generated[0].assigned_to, Some(AgentType::Claude));
        assert_ne!(
            generated[0].assigned_to, t1.assigned_to,
            "Verifier must differ from builder"
        );
    }

    #[test]
    fn test_cross_agent_verification_gemini_builder() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        // Gemini built it → Claude must verify
        let mut t1 = Task::new("T-001", "Gemini task", "desc");
        t1.task_type = Some("implement".to_string());
        t1.status = TaskStatus::Completed;
        t1.assigned_to = Some(AgentType::Gemini);
        mgr.create_task(&t1).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated[0].assigned_to, Some(AgentType::Claude));
        assert_ne!(generated[0].assigned_to, t1.assigned_to);
    }

    #[test]
    fn test_cross_agent_verification_claude_builder() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        // Claude built it → Codex must verify
        let mut t1 = Task::new("T-001", "Claude task", "desc");
        t1.task_type = Some("implement".to_string());
        t1.status = TaskStatus::Completed;
        t1.assigned_to = Some(AgentType::Claude);
        mgr.create_task(&t1).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated[0].assigned_to, Some(AgentType::Codex));
        assert_ne!(generated[0].assigned_to, t1.assigned_to);
    }

    #[test]
    fn test_generate_verify_enriched_criteria() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new("T-001", "Add caching layer", "Implement Redis cache");
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        task.acceptance_criteria = vec!["Cache invalidation works".to_string()];
        mgr.create_task(&task).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated.len(), 1);
        let criteria = &generated[0].acceptance_criteria;
        assert!(
            criteria
                .iter()
                .any(|c| c.contains("All project tests pass"))
        );
        assert!(criteria.iter().any(|c| c.contains("Type checker passes")));
        assert!(criteria.iter().any(|c| c.contains("No new lint warnings")));
        assert!(
            criteria
                .iter()
                .any(|c| c.contains("corresponding test files"))
        );
    }

    #[test]
    fn test_generate_verify_cross_cutting_auth() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new("T-001", "JWT auth middleware", "Add JWT token validation");
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        task.acceptance_criteria = vec!["Tokens validated correctly".to_string()];
        mgr.create_task(&task).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated.len(), 1);
        let criteria = &generated[0].acceptance_criteria;
        assert!(criteria.iter().any(|c| c.contains("E2E tests still pass")));
        assert!(
            criteria
                .iter()
                .any(|c| c.contains("Test mocks and fixtures updated"))
        );
    }

    #[test]
    fn test_generate_verify_non_cross_cutting() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new(
            "T-001",
            "Optimize query performance",
            "Speed up SQL queries",
        );
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        task.acceptance_criteria = vec!["Query runs under 100ms".to_string()];
        mgr.create_task(&task).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated.len(), 1);
        let criteria = &generated[0].acceptance_criteria;
        // Should NOT have cross-cutting criteria
        assert!(!criteria.iter().any(|c| c.contains("E2E tests still pass")));
        assert!(
            !criteria
                .iter()
                .any(|c| c.contains("Test mocks and fixtures"))
        );
    }

    #[test]
    fn test_generate_verify_prefixed_criteria() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new("T-001", "Build API endpoint", "Create REST endpoint");
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        task.acceptance_criteria = vec![
            "Returns 200 on success".to_string(),
            "Returns 404 for missing resource".to_string(),
        ];
        mgr.create_task(&task).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated.len(), 1);
        let criteria = &generated[0].acceptance_criteria;
        assert!(
            criteria
                .iter()
                .any(|c| c == "Verify: Returns 200 on success")
        );
        assert!(
            criteria
                .iter()
                .any(|c| c == "Verify: Returns 404 for missing resource")
        );
    }

    #[test]
    fn test_generate_gate_fix_tasks() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let failed = vec![crate::core::quality_gate::GateResult {
            gate_name: "TypeCheck".to_string(),
            passed: false,
            exit_code: 2,
            stdout: String::new(),
            stderr: "TS2345: Argument of type 'string' is not assignable".to_string(),
            duration_ms: 500,
        }];

        let generated = mgr.generate_gate_fix_tasks(&failed).unwrap();
        assert_eq!(generated.len(), 1);
        let fix = &generated[0];
        assert_eq!(fix.title, "Fix: TypeCheck failures");
        assert_eq!(fix.phase, Some(TaskPhase::Build));
        assert_eq!(fix.task_type.as_deref(), Some("fix"));
        assert_eq!(fix.assigned_to, Some(AgentType::Claude));
        assert!(fix.description.contains("TS2345"));
        assert!(fix.acceptance_criteria[0].contains("TypeCheck passes"));
    }

    #[test]
    fn test_gate_fix_task_multiple_gates() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let failed = vec![
            crate::core::quality_gate::GateResult {
                gate_name: "TypeCheck".to_string(),
                passed: false,
                exit_code: 2,
                stdout: String::new(),
                stderr: "type error".to_string(),
                duration_ms: 100,
            },
            crate::core::quality_gate::GateResult {
                gate_name: "Lint".to_string(),
                passed: false,
                exit_code: 1,
                stdout: String::new(),
                stderr: "unused import".to_string(),
                duration_ms: 50,
            },
        ];

        let generated = mgr.generate_gate_fix_tasks(&failed).unwrap();
        assert_eq!(generated.len(), 2);
        assert_eq!(generated[0].title, "Fix: TypeCheck failures");
        assert_eq!(generated[1].title, "Fix: Lint failures");
        // Should have sequential task IDs
        assert_eq!(generated[0].id, "T-001");
        assert_eq!(generated[1].id, "T-002");
    }

    #[test]
    fn test_gate_fix_task_not_verified() {
        // Fix tasks with task_type="fix" should NOT generate verify subtasks
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let failed = vec![crate::core::quality_gate::GateResult {
            gate_name: "Test Suite".to_string(),
            passed: false,
            exit_code: 1,
            stdout: "FAIL src/foo.test.ts".to_string(),
            stderr: String::new(),
            duration_ms: 200,
        }];

        let generated = mgr.generate_gate_fix_tasks(&failed).unwrap();
        assert_eq!(generated.len(), 1);

        // Mark fix task as completed
        let mut fix = generated[0].clone();
        fix.status = TaskStatus::Completed;
        mgr.update_task(&fix).unwrap();

        // generate_verify_subtasks should skip "fix" type tasks
        let verify = mgr.generate_verify_subtasks().unwrap();
        assert!(verify.is_empty(), "fix tasks should NOT generate V-xxx");
    }

    #[test]
    fn test_generate_verify_ui_task_has_playwright_checks() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new(
            "T-001",
            "Build dashboard component",
            "Create a React dashboard page with charts",
        );
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        task.acceptance_criteria = vec!["Dashboard renders charts".to_string()];
        mgr.create_task(&task).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated.len(), 1);
        let criteria = &generated[0].acceptance_criteria;
        assert!(
            criteria
                .iter()
                .any(|c| c.contains("Playwright") && c.contains("console errors")),
            "UI tasks should have Playwright console error check, got: {criteria:?}"
        );
        assert!(
            criteria.iter().any(|c| c.contains("uncaught exceptions")),
            "UI tasks should check for uncaught exceptions"
        );
    }

    #[test]
    fn test_generate_verify_non_ui_task_no_playwright() {
        let tmp = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(tmp.path());

        let mut task = Task::new(
            "T-001",
            "Optimize database queries",
            "Speed up the batch processing pipeline",
        );
        task.task_type = Some("implement".to_string());
        task.status = TaskStatus::Completed;
        task.acceptance_criteria = vec!["Queries under 100ms".to_string()];
        mgr.create_task(&task).unwrap();

        let generated = mgr.generate_verify_subtasks().unwrap();
        assert_eq!(generated.len(), 1);
        let criteria = &generated[0].acceptance_criteria;
        assert!(
            !criteria.iter().any(|c| c.contains("Playwright")),
            "Non-UI tasks should NOT have Playwright checks"
        );
    }
    /// DIRECTIVE-NXTG-20261014-10 (Codex finding 1): a second writer that picked the same id gets
    /// an error; the first task is untouched. Updates still overwrite.
    #[test]
    fn test_create_task_refuses_existing_id_and_keeps_original() {
        let dir = tempfile::tempdir().unwrap();
        let mgr = TaskManager::new(dir.path());
        mgr.create_task(&Task::new("T-001", "First", "mcp"))
            .unwrap();
        let err = mgr
            .create_task(&Task::new("T-001", "Second", "plan"))
            .unwrap_err();
        assert!(err.to_string().contains("already exists"), "{err}");
        assert_eq!(mgr.get_task("T-001").unwrap().title, "First");

        let mut t = mgr.get_task("T-001").unwrap();
        t.title = "Renamed".into();
        mgr.update_task(&t).unwrap();
        assert_eq!(mgr.get_task("T-001").unwrap().title, "Renamed");

        // Next-id creation skips the taken id; no temp files are left behind.
        let next = mgr.create_next_task("Next", "d").unwrap();
        assert_eq!(next.id, "T-002");
        let leftovers: Vec<_> = std::fs::read_dir(dir.path().join("tasks"))
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
            .filter(|n| n.ends_with(".tmp"))
            .collect();
        assert!(leftovers.is_empty(), "{leftovers:?}");
    }

    /// Codex finding 2: a dangling `T-NNN.md` symlink aimed at the JSON is replaced by the
    /// markdown file, never followed into the JSON.
    #[cfg(unix)]
    #[test]
    fn test_create_next_task_replaces_md_symlink_instead_of_following_it() {
        let dir = tempfile::tempdir().unwrap();
        let tasks = dir.path().join("tasks");
        std::fs::create_dir_all(&tasks).unwrap();
        std::os::unix::fs::symlink(tasks.join("T-001.json"), tasks.join("T-001.md")).unwrap();
        let mgr = TaskManager::new(dir.path());
        let task = mgr.create_next_task("x", "d").unwrap();
        assert_eq!(task.id, "T-001");
        assert_eq!(mgr.get_task("T-001").unwrap().title, "x");
        let md_meta = std::fs::symlink_metadata(tasks.join("T-001.md")).unwrap();
        assert!(md_meta.file_type().is_file());
    }

    /// Task files written before v1.6.3 have no outcome fields; they must still load.
    #[test]
    fn test_legacy_task_json_without_outcome_fields_loads() {
        let dir = tempfile::tempdir().unwrap();
        let tasks_dir = dir.path().join("tasks");
        std::fs::create_dir_all(&tasks_dir).unwrap();
        std::fs::write(
            tasks_dir.join("T-001.json"),
            r#"{"id":"T-001","title":"Old","description":"d","status":"completed","assigned_to":"claude","depends_on":[],"locked_files":[],"acceptance_criteria":[],"created_at":"2026-08-01T00:00:00Z","updated_at":"2026-08-01T00:00:00Z","completed_at":"2026-08-01T01:00:00Z"}"#,
        )
        .unwrap();
        let task = Task::read_from_json(dir.path(), "T-001").unwrap();
        assert_eq!(task.result_summary, None);
        assert_eq!(task.completed_by, None);
        assert_eq!(task.completed_by_source, None);
        // Round-trip: absent fields stay absent in the JSON.
        let json = serde_json::to_string(&task).unwrap();
        assert!(!json.contains("result_summary") && !json.contains("completed_by"));
    }

    #[test]
    fn test_markdown_view_shows_outcome_only_when_completed() {
        let dir = tempfile::tempdir().unwrap();
        let mut task = Task::new("T-001", "Feature", "desc");
        task.write_to_file(dir.path()).unwrap();
        let md = std::fs::read_to_string(dir.path().join("tasks/T-001.md")).unwrap();
        assert!(!md.contains("## Outcome"));

        task.status = TaskStatus::Completed;
        task.completed_at = Some(Utc::now());
        task.completed_by = Some(AgentType::Claude);
        task.completed_by_source = Some(CompletedBySource::Explicit);
        task.result_summary = Some("Shipped it".into());
        task.write_to_file(dir.path()).unwrap();
        let md = std::fs::read_to_string(dir.path().join("tasks/T-001.md")).unwrap();
        assert!(
            md.contains("## Outcome")
                && md.contains("**Completed by:** claude (explicit)")
                && md.contains("Shipped it")
        );
    }
}