tsk-ai 0.10.4

tsk-tsk: keeping your agents out of trouble with sandboxed coding agent automation
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
use crate::assets::frontmatter::strip_frontmatter;
use crate::assets::{find_template, list_all_templates};
use crate::context::AppContext;
use crate::context::tsk_config;
use crate::context::tsk_env::TskEnv;
use crate::git::RepoManager;
use crate::git_operations;
use crate::task::Task;
use crate::utils::sanitize_for_branch_name;
use chrono::Local;
use std::collections::HashSet;
use std::error::Error;
use std::path::{Path, PathBuf};

/// Alphabet for generating task IDs. Excludes `-` to prevent IDs from being
/// mistaken for CLI flags.
const TASK_ID_ALPHABET: [char; 63] = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
    'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
    'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4',
    '5', '6', '7', '8', '9', '_',
];

/// Builder for creating tasks with a fluent API
pub struct TaskBuilder {
    repo_root: Option<PathBuf>,
    name: Option<String>,
    task_type: Option<String>,
    prompt: Option<String>,
    /// Path to a file containing the task prompt (contents injected into template)
    prompt_file_path: Option<PathBuf>,
    /// Path to an existing instructions file to use as-is (for retry)
    existing_instructions_file: Option<PathBuf>,
    edit: bool,
    agent: Option<String>,
    stack: Option<String>,
    project: Option<String>,
    copied_repo_path: Option<PathBuf>,
    is_interactive: bool,
    /// Parent task ID that this task is chained to
    parent_id: Option<String>,
    network_isolation: bool,
    dind: Option<bool>,
    repo_copy_source: Option<PathBuf>,
}

impl TaskBuilder {
    /// Creates a new TaskBuilder instance
    pub fn new() -> Self {
        Self {
            repo_root: None,
            name: None,
            task_type: None,
            prompt: None,
            prompt_file_path: None,
            existing_instructions_file: None,
            edit: false,
            agent: None,
            stack: None,
            project: None,
            copied_repo_path: None,
            is_interactive: false,
            parent_id: None,
            network_isolation: true,
            dind: None,
            repo_copy_source: None,
        }
    }

    /// Creates a TaskBuilder from an existing task. This is used for retrying tasks.
    pub fn from_existing(task: &Task) -> Self {
        let mut builder = Self::new();
        builder.repo_root = Some(task.repo_root.clone());
        builder.name = Some(task.name.clone());
        builder.task_type = Some(task.task_type.clone());
        builder.agent = Some(task.agent.clone());
        builder.stack = Some(task.stack.clone());
        builder.project = Some(task.project.clone());
        builder.copied_repo_path = task.copied_repo_path.clone();
        builder.is_interactive = task.is_interactive;
        builder.network_isolation = task.network_isolation;
        builder.dind = Some(task.dind);
        // Note: We intentionally don't copy parent_id when retrying a task.
        // The retry creates a fresh task from the current repository state.

        // Use existing instructions as-is for retry (bypasses template rendering)
        builder.existing_instructions_file = Some(PathBuf::from(&task.instructions_file));

        builder
    }

    /// Sets the repository root path
    pub fn repo_root(mut self, repo_root: PathBuf) -> Self {
        self.repo_root = Some(repo_root);
        self
    }

    /// Sets the task name
    pub fn name(mut self, name: String) -> Self {
        self.name = Some(name);
        self
    }

    /// Sets the task type
    pub fn task_type(mut self, task_type: String) -> Self {
        self.task_type = Some(task_type);
        self
    }

    /// Sets the task prompt text that replaces the `{{PROMPT}}` placeholder in templates
    pub fn prompt(mut self, prompt: Option<String>) -> Self {
        self.prompt = prompt;
        self
    }

    /// Sets the path to a file containing the task prompt (contents injected into template)
    pub fn prompt_file(mut self, path: Option<PathBuf>) -> Self {
        self.prompt_file_path = path;
        self
    }

    /// Sets an existing instructions file to copy as-is (bypasses template rendering)
    pub fn existing_instructions_file(mut self, path: Option<PathBuf>) -> Self {
        self.existing_instructions_file = path;
        self
    }

    /// Sets whether to open an editor for instructions
    pub fn edit(mut self, edit: bool) -> Self {
        self.edit = edit;
        self
    }

    /// Sets the AI agent to use
    pub fn agent(mut self, agent: Option<String>) -> Self {
        self.agent = agent;
        self
    }

    /// Sets the stack for Docker image selection
    pub fn stack(mut self, stack: Option<String>) -> Self {
        self.stack = stack;
        self
    }

    /// Sets the project name for Docker image selection
    pub fn project(mut self, project: Option<String>) -> Self {
        self.project = project;
        self
    }

    /// Sets whether the task should run in interactive mode
    pub fn with_interactive(mut self, is_interactive: bool) -> Self {
        self.is_interactive = is_interactive;
        self
    }

    /// Sets the parent task ID that this task is chained to.
    /// When set, the task will wait for the parent to complete before executing,
    /// and will use the parent's completed repository as its starting point.
    pub fn parent_id(mut self, task_id: Option<String>) -> Self {
        self.parent_id = task_id;
        self
    }

    /// Sets whether per-container network isolation is enabled.
    /// When disabled, the container runs on the default Docker network with direct internet access.
    pub fn network_isolation(mut self, enabled: bool) -> Self {
        self.network_isolation = enabled;
        self
    }

    /// Sets whether Docker-in-Docker support is enabled.
    /// When enabled, container security is relaxed to allow nested container builds.
    /// Uses `Option<bool>` so `None` defers to config-file defaults.
    pub fn dind(mut self, enabled: Option<bool>) -> Self {
        self.dind = enabled;
        self
    }

    /// Overrides the source directory used when copying the repository.
    /// When set, this path is used instead of the auto-detected repository root.
    pub fn repo_copy_source(mut self, source: Option<PathBuf>) -> Self {
        self.repo_copy_source = source;
        self
    }

    /// Builds the task, creating all necessary files and directories
    pub async fn build(self, ctx: &AppContext) -> Result<Task, Box<dyn Error>> {
        let repo_root = self
            .repo_root
            .clone()
            .ok_or("Repository root is required")?;
        let name = self.name.clone().ok_or("Task name is required")?;
        let task_type = self
            .task_type
            .clone()
            .unwrap_or_else(|| "generic".to_string());

        // Check if template requires a prompt
        let template_needs_prompt = if task_type != "generic" {
            match find_template(&task_type, Some(&repo_root), &ctx.tsk_env()) {
                Ok(template_content) => {
                    let body = strip_frontmatter(&template_content);
                    body.contains("{{PROMPT}}") || body.contains("{{DESCRIPTION}}")
                }
                Err(_) => true, // If we can't read the template, assume it needs a prompt
            }
        } else {
            true // Generic tasks always need a prompt
        };

        // Validate input
        if template_needs_prompt
            && self.prompt.is_none()
            && self.prompt_file_path.is_none()
            && self.existing_instructions_file.is_none()
            && !self.edit
        {
            return Err("Either prompt or prompt file must be provided, or use edit mode".into());
        }

        // Auto-detect project name first (needed for project config lookup)
        let project = match self.project {
            Some(ref p) => p.clone(),
            None => match crate::repository::detect_project_name(&repo_root).await {
                Ok(detected) => detected,
                Err(e) => {
                    eprintln!("Warning: Failed to detect project name: {e}. Using default.");
                    "default".to_string()
                }
            },
        };

        // Resolve configuration for this project (layers defaults + project file + project config)
        let tsk_config = ctx.tsk_config();
        let project_config = tsk_config::load_project_config(&repo_root);
        let resolved =
            tsk_config.resolve_config(&project, project_config.as_ref(), Some(&repo_root));

        // Get agent: CLI flag > resolved config (project > defaults > built-in)
        let agent = tsk_config::resolve_agent(self.agent.clone(), &resolved);

        // Validate agent
        if !crate::agent::AgentProvider::is_valid_agent(&agent) {
            let available_agents = crate::agent::AgentProvider::list_agents().join(", ");
            return Err(
                format!("Unknown agent '{agent}'. Available agents: {available_agents}").into(),
            );
        }

        // Validate task type
        if task_type != "generic" {
            let available_templates = list_all_templates(Some(&repo_root), &ctx.tsk_env());
            if !available_templates.contains(&task_type.to_string()) {
                return Err(format!(
                    "No template found for task type '{}'. Available templates: {}",
                    task_type,
                    available_templates.join(", ")
                )
                .into());
            }
        }

        // Check if repository has any commits
        // This must happen before we try to capture source_commit
        let has_commits = match git_operations::get_current_commit(&repo_root).await {
            Ok(_) => true,
            Err(e) => {
                // Check if this is an empty repository error
                if e.contains("Failed to get HEAD") || e.contains("reference 'refs/heads") {
                    false
                } else {
                    // Some other git error - propagate it
                    return Err(format!("Failed to check repository status: {e}").into());
                }
            }
        };

        if !has_commits {
            return Err(
                format!(
                    "Cannot create task in an empty git repository.\n\n\
                     The repository at '{}' has no commits. TSK needs at least one commit to create a branch and track changes.\n\n\
                     To fix this, create an initial commit:\n  \
                     git commit --allow-empty -m \"Initial commit\"\n\n\
                     Then try running your TSK command again.",
                    repo_root.display()
                ).into()
            );
        }

        // Create task directory in centralized location
        let now = Local::now();
        let created_at = now;
        let id = nanoid::nanoid!(8, &TASK_ID_ALPHABET);
        let task_dir_name = id.clone();
        let task_dir = ctx.tsk_env().task_dir(&task_dir_name);
        crate::file_system::create_dir(&task_dir).await?;

        // Create output directory for capturing agent output
        let output_dir = task_dir.join("output");
        crate::file_system::create_dir(&output_dir).await?;

        // Create instructions file
        let instructions_path = if self.edit {
            // Create temporary file in repository root for editing
            let temp_filename = format!(".tsk-edit-{task_dir_name}-instructions.md");
            let temp_path = repo_root.join(&temp_filename);
            self.write_instructions_content(&temp_path, &task_type, ctx)
                .await?;

            // Open editor with the temporary file
            let tsk_env = ctx.tsk_env();
            self.open_editor(temp_path.to_str().ok_or("Invalid path")?, &tsk_env)?;

            // Check if file is empty and ensure cleanup happens even on error
            let needs_cleanup = self.check_instructions_not_empty(&temp_path).await.is_err();

            if needs_cleanup {
                // Clean up the temporary file and task directory before returning the error
                let _ = crate::file_system::remove_file(&temp_path).await;
                let _ = crate::file_system::remove_dir(&task_dir).await;
                return Err("Instructions file is empty. Task creation cancelled.".into());
            }

            // Move the file to the task directory
            let final_path = task_dir.join("instructions.md");
            let content = crate::file_system::read_file(&temp_path).await?;
            crate::file_system::write_file(&final_path, &content).await?;
            crate::file_system::remove_file(&temp_path).await?;

            final_path.to_string_lossy().to_string()
        } else {
            // Create instructions file directly in task directory
            let dest_path = task_dir.join("instructions.md");
            self.write_instructions_content(&dest_path, &task_type, ctx)
                .await?
        };

        // Capture the current commit SHA
        let source_commit = match git_operations::get_current_commit(&repo_root).await {
            Ok(commit) => commit,
            Err(e) => {
                return Err(format!("Failed to get current commit for task '{name}': {e}").into());
            }
        };

        // Capture the current branch for git-town parent tracking
        // Returns None if in detached HEAD state
        let source_branch = git_operations::get_current_branch(&repo_root)
            .await
            .ok()
            .flatten();

        // Resolve stack: CLI flag > config (project > defaults) > auto-detect > built-in default
        let stack = tsk_config::resolve_stack(
            self.stack,
            &tsk_config,
            &project,
            project_config.as_ref(),
            &repo_root,
        )
        .await;

        // Resolve dind: CLI flag > resolved config (project > defaults > built-in)
        let dind = self.dind.unwrap_or(resolved.dind);

        // Generate human-readable branch name with format: tsk/{task-type}/{task-name}/{task-id}
        let sanitized_task_type = sanitize_for_branch_name(&task_type);
        let sanitized_name = sanitize_for_branch_name(&name);
        let branch_name = format!("tsk/{sanitized_task_type}/{sanitized_name}/{id}");

        // Validate parent task if specified
        if let Some(ref pid) = self.parent_id {
            let storage = ctx.task_storage();
            let tasks = storage.list_tasks().await.map_err(|e| e.to_string())?;

            // Check if parent task exists
            let parent_task = tasks.iter().find(|t| t.id == *pid);
            if parent_task.is_none() {
                return Err(format!(
                    "Parent task '{}' not found. Please specify a valid task ID.",
                    pid
                )
                .into());
            }

            // Check for circular parent chains
            // Walk the parent chain to detect cycles
            let mut visited = HashSet::new();
            visited.insert(id.clone()); // Current task being created

            let mut current_id = Some(pid.clone());
            while let Some(check_id) = current_id {
                if visited.contains(&check_id) {
                    return Err(format!(
                        "Circular parent chain detected: task '{}' would create a cycle",
                        pid
                    )
                    .into());
                }
                visited.insert(check_id.clone());

                // Find the task and check its parent
                current_id = tasks
                    .iter()
                    .find(|t| t.id == check_id)
                    .and_then(|t| t.parent_ids.first().cloned());
            }
        }

        // Determine if this task has a parent
        let has_parent = self.parent_id.is_some();

        // Copy the repository for the task (unless it has a parent)
        // Tasks with parents skip repo copy - they'll get it from the parent when scheduled
        let copied_repo_path = if has_parent {
            // Skip repo copy for child tasks - the scheduler will copy from parent task
            None
        } else {
            let copy_source = self.repo_copy_source.as_ref().unwrap_or(&repo_root);
            let repo_manager = RepoManager::new(ctx);
            let copy_result = repo_manager
                .copy_repo(
                    &task_dir_name,
                    copy_source,
                    Some(&source_commit),
                    &branch_name,
                )
                .await
                .map_err(|e| format!("Failed to copy repository: {e}"))?;
            for warning in &copy_result.warnings {
                eprintln!("{warning}");
            }
            Some(copy_result.repo_path)
        };

        // For child tasks, source_branch is set to None - it will be set from parent task later
        let effective_source_branch = if has_parent { None } else { source_branch };

        // Serialize the resolved config for snapshotting in the database.
        // This captures the full config at task creation time so execution
        // doesn't need to rediscover project files.
        let resolved_config_json = serde_json::to_string(&resolved)
            .map_err(|e| format!("Failed to serialize resolved config: {e}"))?;

        // Create and return the task
        let task = Task::new(
            id,
            repo_root,
            name,
            task_type,
            instructions_path,
            agent,
            branch_name,
            source_commit,
            effective_source_branch,
            stack,
            project,
            created_at,
            copied_repo_path,
            self.is_interactive,
            self.parent_id.into_iter().collect::<Vec<String>>(),
            self.network_isolation,
            dind,
            Some(resolved_config_json),
        );

        Ok(task)
    }

    async fn write_instructions_content(
        &self,
        dest_path: &Path,
        task_type: &str,
        ctx: &AppContext,
    ) -> Result<String, Box<dyn Error>> {
        if let Some(ref file_path) = self.existing_instructions_file {
            // Existing instructions file (retry) - copy content as-is
            let content = crate::file_system::read_file(file_path).await?;
            crate::file_system::write_file(dest_path, &content).await?;
        } else {
            // Resolve prompt: prefer explicit prompt, fall back to file contents
            let effective_prompt = if let Some(ref prompt_text) = self.prompt {
                Some(prompt_text.clone())
            } else if let Some(ref file_path) = self.prompt_file_path {
                let content = crate::file_system::read_file(file_path).await?;
                let trimmed = content.trim();
                if trimmed.is_empty() {
                    None
                } else {
                    Some(trimmed.to_string())
                }
            } else {
                None
            };

            if let Some(ref prompt_text) = effective_prompt {
                // Check if a template exists for this task type
                let content = if task_type != "generic" {
                    match find_template(task_type, self.repo_root.as_deref(), &ctx.tsk_env()) {
                        Ok(template_content) => {
                            let body = strip_frontmatter(&template_content);
                            let mut content = body.replace("{{PROMPT}}", prompt_text);
                            if body.contains("{{DESCRIPTION}}") {
                                eprintln!(
                                    "Warning: {{{{DESCRIPTION}}}} placeholder is deprecated. Use {{{{PROMPT}}}} instead."
                                );
                                content = content.replace("{{DESCRIPTION}}", prompt_text);
                            }
                            content
                        }
                        Err(e) => {
                            eprintln!("Warning: Failed to read template: {e}");
                            prompt_text.clone()
                        }
                    }
                } else {
                    prompt_text.clone()
                };

                crate::file_system::write_file(dest_path, &content).await?;
            } else {
                // No prompt provided - use template as-is or create empty file
                let initial_content = if task_type != "generic" {
                    match find_template(task_type, self.repo_root.as_deref(), &ctx.tsk_env()) {
                        Ok(template_content) => {
                            let body = strip_frontmatter(&template_content);
                            if self.edit
                                && (body.contains("{{PROMPT}}") || body.contains("{{DESCRIPTION}}"))
                            {
                                let content = body.replace(
                                    "{{PROMPT}}",
                                    "<!-- TODO: Add your task prompt here -->",
                                );
                                if body.contains("{{DESCRIPTION}}") {
                                    eprintln!(
                                        "Warning: {{{{DESCRIPTION}}}} placeholder is deprecated. Use {{{{PROMPT}}}} instead."
                                    );
                                }
                                content.replace(
                                    "{{DESCRIPTION}}",
                                    "<!-- TODO: Add your task prompt here -->",
                                )
                            } else {
                                // Use template as-is (for templates without prompt placeholder)
                                body.to_string()
                            }
                        }
                        Err(_) => String::new(),
                    }
                } else {
                    String::new()
                };

                crate::file_system::write_file(dest_path, &initial_content).await?;
            }
        }

        Ok(dest_path.to_string_lossy().to_string())
    }

    fn open_editor(&self, instructions_path: &str, tsk_env: &TskEnv) -> Result<(), Box<dyn Error>> {
        let editor = tsk_env.editor();

        let status = std::process::Command::new(editor)
            .arg(instructions_path)
            .status()?;

        if !status.success() {
            return Err("Editor exited with non-zero status".into());
        }

        Ok(())
    }

    async fn check_instructions_not_empty(
        &self,
        instructions_path: &Path,
    ) -> Result<(), Box<dyn Error>> {
        // Check if file is empty after editing
        let content = crate::file_system::read_file(instructions_path).await?;
        if content.trim().is_empty() {
            return Err("Instructions file is empty. Task creation cancelled.".into());
        }
        Ok(())
    }
}

impl Default for TaskBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::AppContext;
    /// Helper to create a standard test context with real file system and git operations
    /// Returns (git_repo, AppContext)
    async fn create_test_context() -> (crate::test_utils::TestGitRepository, AppContext) {
        use crate::test_utils::TestGitRepository;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let ctx = AppContext::builder().build();

        (test_repo, ctx)
    }

    /// Helper function to create a basic task for testing
    async fn create_basic_task(name: &str, prompt: &str) -> Task {
        let (test_repo, ctx) = create_test_context().await;
        let current_dir = test_repo.path().to_path_buf();

        TaskBuilder::new()
            .repo_root(current_dir)
            .name(name.to_string())
            .task_type("generic".to_string())
            .prompt(Some(prompt.to_string()))
            .build(&ctx)
            .await
            .unwrap()
    }

    /// Helper to verify task instructions content
    async fn verify_instructions_content(ctx: &AppContext, task: &Task, expected_content: &str) {
        let instructions_path = ctx
            .tsk_env()
            .data_dir()
            .join("tasks")
            .join(&task.id)
            .join(&task.instructions_file);
        let content = crate::file_system::read_file(&instructions_path)
            .await
            .unwrap();
        assert!(content.contains(expected_content));
    }

    #[tokio::test]
    async fn test_task_builder_basic() {
        let task = create_basic_task("test-task", "Test description").await;

        assert_eq!(task.name, "test-task");
        assert_eq!(task.task_type, "generic");
        assert!(!task.instructions_file.is_empty());
        assert_eq!(task.id.len(), 8);
        assert!(
            task.id
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_'),
            "Task ID should only contain [A-Za-z0-9_], got: {}",
            task.id
        );
    }

    #[tokio::test]
    async fn test_task_builder_with_custom_properties() {
        let (test_repo, ctx) = create_test_context().await;
        let current_dir = test_repo.path().to_path_buf();

        let task = TaskBuilder::new()
            .repo_root(current_dir)
            .name("custom-task".to_string())
            .task_type("feat".to_string())
            .prompt(Some("Custom description".to_string()))
            .stack(Some("rust".to_string()))
            .project(Some("web-api".to_string()))
            .build(&ctx)
            .await
            .unwrap();

        assert_eq!(task.name, "custom-task");
        assert_eq!(task.task_type, "feat");
        assert_eq!(task.stack, "rust");
        assert_eq!(task.project, "web-api");
    }

    #[tokio::test]
    async fn test_task_builder_with_template() {
        use crate::test_utils::TestGitRepository;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let current_dir = test_repo.path().to_path_buf();

        // Create template with frontmatter
        let template_content =
            "---\ndescription: A feature template\n---\n# Feature Template\n\n{{PROMPT}}";
        test_repo
            .create_file(".tsk/templates/feat.md", template_content)
            .unwrap();

        let ctx = AppContext::builder().build();

        let task = TaskBuilder::new()
            .repo_root(current_dir)
            .name("test-feature".to_string())
            .task_type("feat".to_string())
            .prompt(Some("My new feature".to_string()))
            .build(&ctx)
            .await
            .unwrap();

        assert_eq!(task.task_type, "feat");
        verify_instructions_content(&ctx, &task, "Feature Template").await;
        verify_instructions_content(&ctx, &task, "My new feature").await;

        // Verify frontmatter is stripped from instructions
        let instructions_path = ctx
            .tsk_env()
            .data_dir()
            .join("tasks")
            .join(&task.id)
            .join(&task.instructions_file);
        let content = crate::file_system::read_file(&instructions_path)
            .await
            .unwrap();
        assert!(
            !content.contains("description: A feature template"),
            "Frontmatter should be stripped from instructions"
        );
    }

    #[tokio::test]
    async fn test_deprecated_description_placeholder_still_works() {
        use crate::test_utils::TestGitRepository;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let current_dir = test_repo.path().to_path_buf();

        // Create template using the deprecated {{DESCRIPTION}} placeholder
        let template_content =
            "---\ndescription: A legacy template\n---\n# Legacy Template\n\n{{DESCRIPTION}}";
        test_repo
            .create_file(".tsk/templates/legacy.md", template_content)
            .unwrap();

        let ctx = AppContext::builder().build();

        let task = TaskBuilder::new()
            .repo_root(current_dir)
            .name("legacy-test".to_string())
            .task_type("legacy".to_string())
            .prompt(Some("My prompt text".to_string()))
            .build(&ctx)
            .await
            .unwrap();

        // Verify the deprecated placeholder was replaced with the prompt text
        verify_instructions_content(&ctx, &task, "My prompt text").await;

        // Verify the placeholder itself is gone
        let instructions_path = ctx
            .tsk_env()
            .data_dir()
            .join("tasks")
            .join(&task.id)
            .join(&task.instructions_file);
        let content = crate::file_system::read_file(&instructions_path)
            .await
            .unwrap();
        assert!(
            !content.contains("{{DESCRIPTION}}"),
            "Deprecated placeholder should be replaced"
        );
    }

    #[tokio::test]
    async fn test_task_builder_validation_errors() {
        let ctx = AppContext::builder().build();
        let non_git_dir = ctx.tsk_env().data_dir().to_path_buf();

        // Test missing repository root
        let result = TaskBuilder::new()
            .name("test".to_string())
            .build(&ctx)
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Repository root"));

        // Test missing task name
        let result = TaskBuilder::new()
            .repo_root(non_git_dir.clone())
            .build(&ctx)
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Task name"));

        // Test missing prompt for generic task
        let result = TaskBuilder::new()
            .repo_root(non_git_dir)
            .name("test".to_string())
            .build(&ctx)
            .await;
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Either prompt or prompt file")
        );
    }

    #[tokio::test]
    async fn test_task_builder_with_prompt_file() {
        let (test_repo, ctx) = create_test_context().await;
        let current_dir = test_repo.path().to_path_buf();

        // Create instructions file
        let instructions_content = "# Instructions for task\n\nDetailed steps here.";
        let instructions_path = current_dir.join("task-instructions.md");
        crate::file_system::write_file(&instructions_path, instructions_content)
            .await
            .unwrap();

        let task = TaskBuilder::new()
            .repo_root(current_dir)
            .name("file-task".to_string())
            .prompt_file(Some(instructions_path))
            .build(&ctx)
            .await
            .unwrap();

        verify_instructions_content(&ctx, &task, "Instructions for task").await;
        verify_instructions_content(&ctx, &task, "Detailed steps here").await;
    }

    #[tokio::test]
    async fn test_task_builder_branch_name_generation() {
        let task = create_basic_task("my-feature-name", "Description").await;

        // Branch name should follow pattern: tsk/{task-type}/{task-name}/{task-id}
        assert!(task.branch_name.starts_with("tsk/generic/my-feature-name/"));
        assert_eq!(task.branch_name.split('/').count(), 4);
    }

    #[tokio::test]
    async fn test_task_builder_captures_source_commit() {
        use crate::test_utils::TestGitRepository;

        let test_repo = TestGitRepository::new().unwrap();
        let initial_commit = test_repo.init_with_commit().unwrap();

        // Add another commit
        test_repo.create_file("new_file.txt", "content").unwrap();
        test_repo.stage_all().unwrap();
        let current_commit = test_repo.commit("Add new file").unwrap();

        let ctx = AppContext::builder().build();

        let task = TaskBuilder::new()
            .repo_root(test_repo.path().to_path_buf())
            .name("test-task".to_string())
            .prompt(Some("Test".to_string()))
            .build(&ctx)
            .await
            .unwrap();

        assert_eq!(task.source_commit, current_commit);
        assert_ne!(task.source_commit, initial_commit);
    }

    #[tokio::test]
    async fn test_task_builder_interactive_mode() {
        let (test_repo, ctx) = create_test_context().await;

        let task = TaskBuilder::new()
            .repo_root(test_repo.path().to_path_buf())
            .name("interactive-task".to_string())
            .prompt(Some("Test".to_string()))
            .with_interactive(true)
            .build(&ctx)
            .await
            .unwrap();

        assert!(task.is_interactive);

        // Default should be non-interactive
        let task2 = TaskBuilder::new()
            .repo_root(test_repo.path().to_path_buf())
            .name("regular-task".to_string())
            .prompt(Some("Test".to_string()))
            .build(&ctx)
            .await
            .unwrap();

        assert!(!task2.is_interactive);
    }

    #[tokio::test]
    async fn test_task_builder_repository_copy() {
        use crate::test_utils::TestGitRepository;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();

        // Add some files to verify they get copied
        test_repo
            .create_file("src/main.rs", "fn main() {}")
            .unwrap();
        test_repo
            .create_file("Cargo.toml", "[package]\nname = \"test\"")
            .unwrap();
        test_repo.stage_all().unwrap();
        test_repo.commit("Add source files").unwrap();

        let ctx = AppContext::builder().build();

        let task = TaskBuilder::new()
            .repo_root(test_repo.path().to_path_buf())
            .name("copy-test".to_string())
            .prompt(Some("Test repository copy".to_string()))
            .build(&ctx)
            .await
            .unwrap();

        // Verify repository was copied to the correct location
        let task_dir = ctx.tsk_env().task_dir(&task.id);
        let copied_repo = task_dir.join("repo");

        assert!(copied_repo.exists());
        assert!(copied_repo.join("src/main.rs").exists());
        assert!(copied_repo.join("Cargo.toml").exists());
        assert!(copied_repo.join(".git").exists());
    }

    #[tokio::test]
    async fn test_task_builder_creates_output_directory() {
        use crate::test_utils::TestGitRepository;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();

        let ctx = AppContext::builder().build();

        let task = TaskBuilder::new()
            .repo_root(test_repo.path().to_path_buf())
            .name("output-test".to_string())
            .prompt(Some("Test output directory creation".to_string()))
            .build(&ctx)
            .await
            .unwrap();

        // Verify output directory was created
        let task_dir = ctx.tsk_env().task_dir(&task.id);
        let output_dir = task_dir.join("output");

        assert!(output_dir.exists());
        assert!(output_dir.is_dir());
    }

    #[tokio::test]
    async fn test_task_builder_rejects_empty_repository() {
        use crate::test_utils::TestGitRepository;

        // Create an empty git repository (no commits)
        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init().unwrap(); // Initialize but don't create initial commit
        let repo_path = test_repo.path().to_path_buf();

        // Create context
        let ctx = AppContext::builder().build();

        // Attempt to create a task in the empty repository
        let result = TaskBuilder::new()
            .repo_root(repo_path.clone())
            .name("test-task".to_string())
            .task_type("generic".to_string())
            .prompt(Some("Test description".to_string()))
            .build(&ctx)
            .await;

        // Verify that task creation failed
        assert!(
            result.is_err(),
            "Task creation should fail on empty repository"
        );

        // Verify error message is helpful and actionable
        let error_message = result.unwrap_err().to_string();
        assert!(
            error_message.contains("empty git repository"),
            "Error should mention empty repository, got: {error_message}"
        );
        assert!(
            error_message.contains("no commits"),
            "Error should mention no commits, got: {error_message}"
        );
        assert!(
            error_message.contains("git commit --allow-empty"),
            "Error should provide the command to fix it, got: {error_message}"
        );
        assert!(
            error_message.contains(&repo_path.display().to_string()),
            "Error should show repository path, got: {error_message}"
        );

        // Verify no task directory was created (cleanup verification)
        // The task ID would be generated, but we can verify that no tasks exist in storage
        // This ensures we're not leaving behind partial state
        let task_storage = ctx.task_storage();
        let all_tasks = task_storage.list_tasks().await.unwrap();
        assert!(
            all_tasks.is_empty(),
            "No tasks should exist after failed creation"
        );
    }

    #[tokio::test]
    async fn test_cli_flags_override_project_config() {
        use crate::context::{SharedConfig, TskConfig};
        use crate::test_utils::TestGitRepository;
        use std::collections::HashMap;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let repo_path = test_repo.path().to_path_buf();

        // Use a fixed project name for the test
        let project_name = "test-project".to_string();

        // Create project config with different agent and stack
        let mut project_configs = HashMap::new();
        project_configs.insert(
            project_name.clone(),
            SharedConfig {
                agent: Some("no-op".to_string()),
                stack: Some("python".to_string()),
                ..Default::default()
            },
        );
        let tsk_config = TskConfig {
            project: project_configs,
            ..Default::default()
        };

        let ctx = AppContext::builder().with_tsk_config(tsk_config).build();

        // CLI flags should override project config
        let task = TaskBuilder::new()
            .repo_root(repo_path)
            .name("cli-override-test".to_string())
            .prompt(Some("Test".to_string()))
            .project(Some(project_name))
            .agent(Some("claude".to_string()))
            .stack(Some("rust".to_string()))
            .build(&ctx)
            .await
            .unwrap();

        assert_eq!(
            task.agent, "claude",
            "CLI agent should override project config"
        );
        assert_eq!(
            task.stack, "rust",
            "CLI stack should override project config"
        );
    }

    #[tokio::test]
    async fn test_project_config_overrides_auto_detect() {
        use crate::context::{SharedConfig, TskConfig};
        use crate::test_utils::TestGitRepository;
        use std::collections::HashMap;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let repo_path = test_repo.path().to_path_buf();

        // Create a Cargo.toml so auto-detect would choose "rust"
        test_repo
            .create_file("Cargo.toml", "[package]\nname = \"test\"")
            .unwrap();

        // Use a fixed project name for the test
        let project_name = "test-project".to_string();

        // Create project config that specifies python
        let mut project_configs = HashMap::new();
        project_configs.insert(
            project_name.clone(),
            SharedConfig {
                agent: Some("no-op".to_string()),
                stack: Some("python".to_string()),
                ..Default::default()
            },
        );
        let tsk_config = TskConfig {
            project: project_configs,
            ..Default::default()
        };

        let ctx = AppContext::builder().with_tsk_config(tsk_config).build();

        let task = TaskBuilder::new()
            .repo_root(repo_path)
            .name("config-override-test".to_string())
            .prompt(Some("Test".to_string()))
            .project(Some(project_name))
            .build(&ctx)
            .await
            .unwrap();

        assert_eq!(task.agent, "no-op", "Project config agent should be used");
        assert_eq!(
            task.stack, "python",
            "Project config stack should override auto-detect"
        );
    }

    #[tokio::test]
    async fn test_partial_project_config_uses_defaults_for_missing() {
        use crate::context::{SharedConfig, TskConfig};
        use crate::test_utils::TestGitRepository;
        use std::collections::HashMap;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let repo_path = test_repo.path().to_path_buf();

        // Create a Cargo.toml so auto-detect would choose "rust"
        test_repo
            .create_file("Cargo.toml", "[package]\nname = \"test\"")
            .unwrap();

        // Use a fixed project name for the test
        let project_name = "test-project".to_string();

        // Create project config with only agent (no stack)
        let mut project_configs = HashMap::new();
        project_configs.insert(
            project_name.clone(),
            SharedConfig {
                agent: Some("no-op".to_string()),
                ..Default::default()
            },
        );
        let tsk_config = TskConfig {
            project: project_configs,
            ..Default::default()
        };

        let ctx = AppContext::builder().with_tsk_config(tsk_config).build();

        let task = TaskBuilder::new()
            .repo_root(repo_path)
            .name("partial-config-test".to_string())
            .prompt(Some("Test".to_string()))
            .project(Some(project_name))
            .build(&ctx)
            .await
            .unwrap();

        assert_eq!(task.agent, "no-op", "Project config agent should be used");
        assert_eq!(
            task.stack, "rust",
            "Stack should be auto-detected when not in config"
        );
    }

    #[tokio::test]
    async fn test_no_project_config_uses_defaults() {
        use crate::test_utils::TestGitRepository;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let repo_path = test_repo.path().to_path_buf();

        // Create a Cargo.toml so stack would auto-detect as "rust"
        test_repo
            .create_file("Cargo.toml", "[package]\nname = \"test\"")
            .unwrap();

        // Use default context (no project config)
        let ctx = AppContext::builder().build();

        let task = TaskBuilder::new()
            .repo_root(repo_path)
            .name("no-config-test".to_string())
            .prompt(Some("Test".to_string()))
            .build(&ctx)
            .await
            .unwrap();

        // Should use defaults: claude for agent, auto-detect for stack
        assert_eq!(task.agent, "claude", "Agent should use default");
        assert_eq!(task.stack, "rust", "Stack should be auto-detected");
    }

    #[tokio::test]
    async fn test_dind_config_resolution_chain() {
        use crate::context::{SharedConfig, TskConfig};
        use crate::test_utils::TestGitRepository;
        use std::collections::HashMap;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let repo_path = test_repo.path().to_path_buf();
        let project_name = "test-project".to_string();

        // Case 1: defaults.dind = true, no project config, no CLI flag -> true
        let tsk_config = TskConfig {
            defaults: SharedConfig {
                dind: Some(true),
                ..Default::default()
            },
            ..Default::default()
        };
        let ctx = AppContext::builder().with_tsk_config(tsk_config).build();
        let task = TaskBuilder::new()
            .repo_root(repo_path.clone())
            .name("dind-docker-default".to_string())
            .prompt(Some("Test".to_string()))
            .build(&ctx)
            .await
            .unwrap();
        assert!(task.dind, "defaults.dind = true should propagate");

        // Case 2: defaults.dind = true, project.dind = Some(false) -> false (project overrides)
        let mut project_configs = HashMap::new();
        project_configs.insert(
            project_name.clone(),
            SharedConfig {
                dind: Some(false),
                ..Default::default()
            },
        );
        let tsk_config = TskConfig {
            defaults: SharedConfig {
                dind: Some(true),
                ..Default::default()
            },
            project: project_configs,
            ..Default::default()
        };
        let ctx = AppContext::builder().with_tsk_config(tsk_config).build();
        let task = TaskBuilder::new()
            .repo_root(repo_path.clone())
            .name("dind-project-override".to_string())
            .prompt(Some("Test".to_string()))
            .project(Some(project_name.clone()))
            .build(&ctx)
            .await
            .unwrap();
        assert!(
            !task.dind,
            "project.dind = false should override defaults.dind = true"
        );

        // Case 3: project.dind = Some(false), CLI --dind -> true (CLI overrides)
        let mut project_configs = HashMap::new();
        project_configs.insert(
            project_name.clone(),
            SharedConfig {
                dind: Some(false),
                ..Default::default()
            },
        );
        let tsk_config = TskConfig {
            project: project_configs,
            ..Default::default()
        };
        let ctx = AppContext::builder().with_tsk_config(tsk_config).build();
        let task = TaskBuilder::new()
            .repo_root(repo_path.clone())
            .name("dind-cli-override".to_string())
            .prompt(Some("Test".to_string()))
            .project(Some(project_name))
            .dind(Some(true))
            .build(&ctx)
            .await
            .unwrap();
        assert!(task.dind, "CLI --dind should override project.dind = false");
    }

    #[tokio::test]
    async fn test_task_builder_with_valid_parent() {
        use crate::test_utils::TestGitRepository;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let repo_path = test_repo.path().to_path_buf();

        let ctx = AppContext::builder().build();

        // First create a parent task
        let parent_task = TaskBuilder::new()
            .repo_root(repo_path.clone())
            .name("parent-task".to_string())
            .prompt(Some("Parent task".to_string()))
            .build(&ctx)
            .await
            .unwrap();

        // Add parent task to storage so validation passes
        let storage = ctx.task_storage();
        storage.add_task(parent_task.clone()).await.unwrap();

        // Create child task
        let child_task = TaskBuilder::new()
            .repo_root(repo_path)
            .name("child-task".to_string())
            .prompt(Some("Child task".to_string()))
            .parent_id(Some(parent_task.id.clone()))
            .build(&ctx)
            .await
            .unwrap();

        assert_eq!(child_task.parent_ids, vec![parent_task.id]);
        assert!(
            child_task.copied_repo_path.is_none(),
            "Child task should have no copied_repo_path"
        );
        assert!(
            child_task.source_branch.is_none(),
            "Child task should have no source_branch initially"
        );
    }

    #[tokio::test]
    async fn test_task_builder_invalid_parent_not_found() {
        use crate::test_utils::TestGitRepository;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let repo_path = test_repo.path().to_path_buf();

        let ctx = AppContext::builder().build();

        // Try to create a task with a non-existent parent
        let result = TaskBuilder::new()
            .repo_root(repo_path)
            .name("orphan-task".to_string())
            .prompt(Some("Orphan task".to_string()))
            .parent_id(Some("nonexistent-task-id".to_string()))
            .build(&ctx)
            .await;

        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("not found"),
            "Expected 'not found' error, got: {err_msg}"
        );
        assert!(
            err_msg.contains("nonexistent-task-id"),
            "Error should mention the invalid task ID, got: {err_msg}"
        );
    }

    #[tokio::test]
    async fn test_task_builder_circular_parent_chain_detection() {
        use crate::test_utils::TestGitRepository;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let repo_path = test_repo.path().to_path_buf();

        let ctx = AppContext::builder().build();
        let storage = ctx.task_storage();

        // Create task A
        let task_a = TaskBuilder::new()
            .repo_root(repo_path.clone())
            .name("task-a".to_string())
            .prompt(Some("Task A".to_string()))
            .build(&ctx)
            .await
            .unwrap();
        storage.add_task(task_a.clone()).await.unwrap();

        // Create task B with parent A
        let task_b = TaskBuilder::new()
            .repo_root(repo_path.clone())
            .name("task-b".to_string())
            .prompt(Some("Task B".to_string()))
            .parent_id(Some(task_a.id.clone()))
            .build(&ctx)
            .await
            .unwrap();
        storage.add_task(task_b.clone()).await.unwrap();

        // Create task C with parent B (this should work - no cycle)
        let task_c = TaskBuilder::new()
            .repo_root(repo_path.clone())
            .name("task-c".to_string())
            .prompt(Some("Task C".to_string()))
            .parent_id(Some(task_b.id.clone()))
            .build(&ctx)
            .await
            .unwrap();
        storage.add_task(task_c.clone()).await.unwrap();

        // Verify the chain is properly traversed
        assert!(task_a.parent_ids.is_empty());
        assert_eq!(task_b.parent_ids, vec![task_a.id.clone()]);
        assert_eq!(task_c.parent_ids, vec![task_b.id.clone()]);

        // The chain A <- B <- C is valid (C has parent B which has parent A)
        // This proves the parent chain traversal works correctly
    }

    #[tokio::test]
    async fn test_task_builder_populates_resolved_config() {
        use crate::context::ResolvedConfig;

        let task = create_basic_task("config-test", "Test config snapshotting").await;

        assert!(
            task.resolved_config.is_some(),
            "Task should have resolved_config set at creation"
        );

        // Verify the JSON is valid and deserializable
        let config: ResolvedConfig =
            serde_json::from_str(task.resolved_config.as_ref().unwrap()).unwrap();
        assert_eq!(config.agent, "claude", "Default agent should be claude");
    }

    #[tokio::test]
    async fn test_task_builder_resolved_config_reflects_project_config() {
        use crate::context::{ResolvedConfig, SharedConfig, TskConfig};
        use crate::test_utils::TestGitRepository;
        use std::collections::HashMap;

        let test_repo = TestGitRepository::new().unwrap();
        test_repo.init_with_commit().unwrap();
        let repo_path = test_repo.path().to_path_buf();
        let project_name = "test-project".to_string();

        let mut project_configs = HashMap::new();
        project_configs.insert(
            project_name.clone(),
            SharedConfig {
                memory_gb: Some(32.0),
                host_ports: vec![5432],
                ..Default::default()
            },
        );
        let tsk_config = TskConfig {
            project: project_configs,
            ..Default::default()
        };

        let ctx = AppContext::builder().with_tsk_config(tsk_config).build();

        let task = TaskBuilder::new()
            .repo_root(repo_path)
            .name("config-merge-test".to_string())
            .prompt(Some("Test".to_string()))
            .project(Some(project_name))
            .build(&ctx)
            .await
            .unwrap();

        let config: ResolvedConfig =
            serde_json::from_str(task.resolved_config.as_ref().unwrap()).unwrap();
        assert_eq!(
            config.memory_gb, 32.0,
            "Project config memory should be in snapshot"
        );
        assert_eq!(
            config.host_ports,
            vec![5432],
            "Project config host_ports should be in snapshot"
        );
    }
}