-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathmove-task.js
More file actions
1180 lines (1039 loc) · 34.2 KB
/
move-task.js
File metadata and controls
1180 lines (1039 loc) · 34.2 KB
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
import path from 'path';
import {
findCrossTagDependencies,
getDependentTaskIds,
validateSubtaskMove
} from '../dependency-manager.js';
import {
log,
readJSON,
setTasksForTag,
traverseDependencies,
writeJSON
} from '../utils.js';
/**
* Find all dependencies recursively for a set of source tasks with depth limiting
* @param {Array} sourceTasks - The source tasks to find dependencies for
* @param {Array} allTasks - All available tasks from all tags
* @param {Object} options - Options object
* @param {number} options.maxDepth - Maximum recursion depth (default: 50)
* @param {boolean} options.includeSelf - Whether to include self-references (default: false)
* @returns {Array} Array of all dependency task IDs
*/
function findAllDependenciesRecursively(sourceTasks, allTasks, options = {}) {
return traverseDependencies(sourceTasks, allTasks, {
...options,
direction: 'forward',
logger: { warn: console.warn }
});
}
/**
* Structured error class for move operations
*/
class MoveTaskError extends Error {
constructor(code, message, data = {}) {
super(message);
this.name = 'MoveTaskError';
this.code = code;
this.data = data;
}
}
/**
* Error codes for move operations
*/
const MOVE_ERROR_CODES = {
CROSS_TAG_DEPENDENCY_CONFLICTS: 'CROSS_TAG_DEPENDENCY_CONFLICTS',
CANNOT_MOVE_SUBTASK: 'CANNOT_MOVE_SUBTASK',
SOURCE_TARGET_TAGS_SAME: 'SOURCE_TARGET_TAGS_SAME',
TASK_NOT_FOUND: 'TASK_NOT_FOUND',
SUBTASK_NOT_FOUND: 'SUBTASK_NOT_FOUND',
PARENT_TASK_NOT_FOUND: 'PARENT_TASK_NOT_FOUND',
PARENT_TASK_NO_SUBTASKS: 'PARENT_TASK_NO_SUBTASKS',
DESTINATION_TASK_NOT_FOUND: 'DESTINATION_TASK_NOT_FOUND',
TASK_ALREADY_EXISTS: 'TASK_ALREADY_EXISTS',
INVALID_TASKS_FILE: 'INVALID_TASKS_FILE',
ID_COUNT_MISMATCH: 'ID_COUNT_MISMATCH',
INVALID_SOURCE_TAG: 'INVALID_SOURCE_TAG',
INVALID_TARGET_TAG: 'INVALID_TARGET_TAG'
};
/**
* Normalize a dependency value to its numeric parent task ID.
* - Numbers are returned as-is (if finite)
* - Numeric strings are parsed ("5" -> 5)
* - Dotted strings return the parent portion ("5.2" -> 5)
* - Empty/invalid values return null
* - null/undefined are preserved
* @param {number|string|null|undefined} dep
* @returns {number|null|undefined}
*/
function normalizeDependency(dep) {
if (dep === null || dep === undefined) return dep;
if (typeof dep === 'number') return Number.isFinite(dep) ? dep : null;
if (typeof dep === 'string') {
const trimmed = dep.trim();
if (trimmed === '') return null;
const parentPart = trimmed.includes('.') ? trimmed.split('.')[0] : trimmed;
const parsed = parseInt(parentPart, 10);
return Number.isFinite(parsed) ? parsed : null;
}
return null;
}
/**
* Normalize an array of dependency values to numeric IDs.
* Preserves null/undefined input (returns as-is) and filters out invalid entries.
* @param {Array<any>|null|undefined} deps
* @returns {Array<number>|null|undefined}
*/
function normalizeDependencies(deps) {
if (deps === null || deps === undefined) return deps;
if (!Array.isArray(deps)) return deps;
return deps
.map((d) => normalizeDependency(d))
.filter((n) => Number.isFinite(n));
}
/**
* Move one or more tasks/subtasks to new positions
* @param {string} tasksPath - Path to tasks.json file
* @param {string} sourceId - ID(s) of the task/subtask to move (e.g., '5' or '5.2' or '5,6,7')
* @param {string} destinationId - ID(s) of the destination (e.g., '7' or '7.3' or '7,8,9')
* @param {boolean} generateFiles - Whether to regenerate task files after moving
* @param {Object} options - Additional options
* @param {string} options.projectRoot - Project root directory for tag resolution
* @param {string} options.tag - Explicit tag to use (optional)
* @returns {Object} Result object with moved task details
*/
async function moveTask(
tasksPath,
sourceId,
destinationId,
generateFiles = false,
options = {}
) {
const { projectRoot, tag } = options;
// Check if we have comma-separated IDs (batch move)
const sourceIds = sourceId.split(',').map((id) => id.trim());
const destinationIds = destinationId.split(',').map((id) => id.trim());
if (sourceIds.length !== destinationIds.length) {
throw new MoveTaskError(
MOVE_ERROR_CODES.ID_COUNT_MISMATCH,
`Number of source IDs (${sourceIds.length}) must match number of destination IDs (${destinationIds.length})`
);
}
// For batch moves, process each pair sequentially
if (sourceIds.length > 1) {
const results = [];
for (let i = 0; i < sourceIds.length; i++) {
const result = await moveTask(
tasksPath,
sourceIds[i],
destinationIds[i],
false, // Don't generate files for each individual move
options
);
results.push(result);
}
// Note: Task file generation is no longer supported and has been removed
return {
message: `Successfully moved ${sourceIds.length} tasks/subtasks`,
moves: results
};
}
// Single move logic
// Read the raw data without tag resolution to preserve tagged structure
let rawData = readJSON(tasksPath, projectRoot, tag);
// Handle the case where readJSON returns resolved data with _rawTaggedData
if (rawData && rawData._rawTaggedData) {
// Use the raw tagged data and discard the resolved view
rawData = rawData._rawTaggedData;
}
// Ensure the tag exists in the raw data
if (!rawData || !rawData[tag] || !Array.isArray(rawData[tag].tasks)) {
throw new MoveTaskError(
MOVE_ERROR_CODES.INVALID_TASKS_FILE,
`Invalid tasks file or tag "${tag}" not found at ${tasksPath}`
);
}
// Get the tasks for the current tag
const tasks = rawData[tag].tasks;
log(
'info',
`Moving task/subtask ${sourceId} to ${destinationId} (tag: ${tag})`
);
// Parse source and destination IDs
const isSourceSubtask = sourceId.includes('.');
const isDestSubtask = destinationId.includes('.');
let result;
if (isSourceSubtask && isDestSubtask) {
// Subtask to subtask
result = moveSubtaskToSubtask(tasks, sourceId, destinationId);
} else if (isSourceSubtask && !isDestSubtask) {
// Subtask to task
result = moveSubtaskToTask(tasks, sourceId, destinationId);
} else if (!isSourceSubtask && isDestSubtask) {
// Task to subtask
result = moveTaskToSubtask(tasks, sourceId, destinationId);
} else {
// Task to task
result = moveTaskToTask(tasks, sourceId, destinationId);
}
// Update the data structure with the modified tasks
rawData[tag].tasks = tasks;
// Always write the data object, never the _rawTaggedData directly
// The writeJSON function will filter out _rawTaggedData automatically
writeJSON(tasksPath, rawData, options.projectRoot, tag);
// Note: Task file generation is no longer supported and has been removed
return result;
}
// Helper functions for different move scenarios
function moveSubtaskToSubtask(tasks, sourceId, destinationId) {
// Parse IDs
const [sourceParentId, sourceSubtaskId] = sourceId
.split('.')
.map((id) => parseInt(id, 10));
const [destParentId, destSubtaskId] = destinationId
.split('.')
.map((id) => parseInt(id, 10));
// Find source and destination parent tasks
const sourceParentTask = tasks.find((t) => t.id === sourceParentId);
const destParentTask = tasks.find((t) => t.id === destParentId);
if (!sourceParentTask) {
throw new MoveTaskError(
MOVE_ERROR_CODES.PARENT_TASK_NOT_FOUND,
`Source parent task with ID ${sourceParentId} not found`
);
}
if (!destParentTask) {
throw new MoveTaskError(
MOVE_ERROR_CODES.PARENT_TASK_NOT_FOUND,
`Destination parent task with ID ${destParentId} not found`
);
}
// Initialize subtasks arrays if they don't exist (based on commit fixes)
if (!sourceParentTask.subtasks) {
sourceParentTask.subtasks = [];
}
if (!destParentTask.subtasks) {
destParentTask.subtasks = [];
}
// Find source subtask
const sourceSubtaskIndex = sourceParentTask.subtasks.findIndex(
(st) => st.id === sourceSubtaskId
);
if (sourceSubtaskIndex === -1) {
throw new MoveTaskError(
MOVE_ERROR_CODES.SUBTASK_NOT_FOUND,
`Source subtask ${sourceId} not found`
);
}
const sourceSubtask = sourceParentTask.subtasks[sourceSubtaskIndex];
if (sourceParentId === destParentId) {
// Moving within the same parent
if (destParentTask.subtasks.length > 0) {
const destSubtaskIndex = destParentTask.subtasks.findIndex(
(st) => st.id === destSubtaskId
);
if (destSubtaskIndex !== -1) {
// Remove from old position
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
// Insert at new position (adjust index if moving within same array)
const adjustedIndex =
sourceSubtaskIndex < destSubtaskIndex
? destSubtaskIndex - 1
: destSubtaskIndex;
destParentTask.subtasks.splice(adjustedIndex + 1, 0, sourceSubtask);
} else {
// Destination subtask doesn't exist, insert at end
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
destParentTask.subtasks.push(sourceSubtask);
}
} else {
// No existing subtasks, this will be the first one
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
destParentTask.subtasks.push(sourceSubtask);
}
} else {
// Moving between different parents
moveSubtaskToAnotherParent(
sourceSubtask,
sourceParentTask,
sourceSubtaskIndex,
destParentTask,
destSubtaskId
);
}
return {
message: `Moved subtask ${sourceId} to ${destinationId}`,
movedItem: sourceSubtask
};
}
function moveSubtaskToTask(tasks, sourceId, destinationId) {
// Parse source ID
const [sourceParentId, sourceSubtaskId] = sourceId
.split('.')
.map((id) => parseInt(id, 10));
const destTaskId = parseInt(destinationId, 10);
// Find source parent and destination task
const sourceParentTask = tasks.find((t) => t.id === sourceParentId);
if (!sourceParentTask) {
throw new MoveTaskError(
MOVE_ERROR_CODES.PARENT_TASK_NOT_FOUND,
`Source parent task with ID ${sourceParentId} not found`
);
}
if (!sourceParentTask.subtasks) {
throw new MoveTaskError(
MOVE_ERROR_CODES.PARENT_TASK_NO_SUBTASKS,
`Source parent task ${sourceParentId} has no subtasks`
);
}
// Find source subtask
const sourceSubtaskIndex = sourceParentTask.subtasks.findIndex(
(st) => st.id === sourceSubtaskId
);
if (sourceSubtaskIndex === -1) {
throw new MoveTaskError(
MOVE_ERROR_CODES.SUBTASK_NOT_FOUND,
`Source subtask ${sourceId} not found`
);
}
const sourceSubtask = sourceParentTask.subtasks[sourceSubtaskIndex];
// Check if destination task exists
const existingDestTask = tasks.find((t) => t.id === destTaskId);
if (existingDestTask) {
throw new MoveTaskError(
MOVE_ERROR_CODES.TASK_ALREADY_EXISTS,
`Cannot move to existing task ID ${destTaskId}. Choose a different ID or use subtask destination.`
);
}
// Create new task from subtask
const newTask = {
id: destTaskId,
title: sourceSubtask.title,
description: sourceSubtask.description,
status: sourceSubtask.status || 'pending',
dependencies: sourceSubtask.dependencies || [],
priority: sourceSubtask.priority || 'medium',
details: sourceSubtask.details || '',
testStrategy: sourceSubtask.testStrategy || '',
subtasks: []
};
// Remove subtask from source parent
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
// Insert new task in correct position
const insertIndex = tasks.findIndex((t) => t.id > destTaskId);
if (insertIndex === -1) {
tasks.push(newTask);
} else {
tasks.splice(insertIndex, 0, newTask);
}
return {
message: `Converted subtask ${sourceId} to task ${destinationId}`,
movedItem: newTask
};
}
function moveTaskToSubtask(tasks, sourceId, destinationId) {
// Parse IDs
const sourceTaskId = parseInt(sourceId, 10);
const [destParentId, destSubtaskId] = destinationId
.split('.')
.map((id) => parseInt(id, 10));
// Find source task and destination parent
const sourceTaskIndex = tasks.findIndex((t) => t.id === sourceTaskId);
const destParentTask = tasks.find((t) => t.id === destParentId);
if (sourceTaskIndex === -1) {
throw new MoveTaskError(
MOVE_ERROR_CODES.TASK_NOT_FOUND,
`Source task with ID ${sourceTaskId} not found`
);
}
if (!destParentTask) {
throw new MoveTaskError(
MOVE_ERROR_CODES.PARENT_TASK_NOT_FOUND,
`Destination parent task with ID ${destParentId} not found`
);
}
const sourceTask = tasks[sourceTaskIndex];
// Initialize subtasks array if it doesn't exist (based on commit fixes)
if (!destParentTask.subtasks) {
destParentTask.subtasks = [];
}
// Create new subtask from task
const newSubtask = {
id: destSubtaskId,
title: sourceTask.title,
description: sourceTask.description,
status: sourceTask.status || 'pending',
dependencies: sourceTask.dependencies || [],
details: sourceTask.details || '',
testStrategy: sourceTask.testStrategy || ''
};
// Find insertion position (based on commit fixes)
let destSubtaskIndex = -1;
if (destParentTask.subtasks.length > 0) {
destSubtaskIndex = destParentTask.subtasks.findIndex(
(st) => st.id === destSubtaskId
);
if (destSubtaskIndex === -1) {
// Subtask doesn't exist, we'll insert at the end
destSubtaskIndex = destParentTask.subtasks.length - 1;
}
}
// Insert at specific position (based on commit fixes)
const insertPosition = destSubtaskIndex === -1 ? 0 : destSubtaskIndex + 1;
destParentTask.subtasks.splice(insertPosition, 0, newSubtask);
// Remove the original task from the tasks array
tasks.splice(sourceTaskIndex, 1);
return {
message: `Converted task ${sourceId} to subtask ${destinationId}`,
movedItem: newSubtask
};
}
function moveTaskToTask(tasks, sourceId, destinationId) {
const sourceTaskId = parseInt(sourceId, 10);
const destTaskId = parseInt(destinationId, 10);
// Find source task
const sourceTaskIndex = tasks.findIndex((t) => t.id === sourceTaskId);
if (sourceTaskIndex === -1) {
throw new MoveTaskError(
MOVE_ERROR_CODES.TASK_NOT_FOUND,
`Source task with ID ${sourceTaskId} not found`
);
}
const sourceTask = tasks[sourceTaskIndex];
// Check if destination exists
const destTaskIndex = tasks.findIndex((t) => t.id === destTaskId);
if (destTaskIndex !== -1) {
// Destination exists - this could be overwriting or swapping
const destTask = tasks[destTaskIndex];
// For now, throw an error to avoid accidental overwrites
throw new MoveTaskError(
MOVE_ERROR_CODES.TASK_ALREADY_EXISTS,
`Task with ID ${destTaskId} already exists. Use a different destination ID.`
);
} else {
// Destination doesn't exist - create new task ID
return moveTaskToNewId(tasks, sourceTaskIndex, sourceTask, destTaskId);
}
}
function moveSubtaskToAnotherParent(
sourceSubtask,
sourceParentTask,
sourceSubtaskIndex,
destParentTask,
destSubtaskId
) {
const destSubtaskId_num = parseInt(destSubtaskId, 10);
// Create new subtask with destination ID
const newSubtask = {
...sourceSubtask,
id: destSubtaskId_num
};
// Initialize subtasks array if it doesn't exist (based on commit fixes)
if (!destParentTask.subtasks) {
destParentTask.subtasks = [];
}
// Find insertion position
let destSubtaskIndex = -1;
if (destParentTask.subtasks.length > 0) {
destSubtaskIndex = destParentTask.subtasks.findIndex(
(st) => st.id === destSubtaskId_num
);
if (destSubtaskIndex === -1) {
// Subtask doesn't exist, we'll insert at the end
destSubtaskIndex = destParentTask.subtasks.length - 1;
}
}
// Insert at the destination position (based on commit fixes)
const insertPosition = destSubtaskIndex === -1 ? 0 : destSubtaskIndex + 1;
destParentTask.subtasks.splice(insertPosition, 0, newSubtask);
// Remove the subtask from the original parent
sourceParentTask.subtasks.splice(sourceSubtaskIndex, 1);
return newSubtask;
}
function moveTaskToNewId(tasks, sourceTaskIndex, sourceTask, destTaskId) {
const destTaskIndex = tasks.findIndex((t) => t.id === destTaskId);
// Create moved task with new ID
const movedTask = {
...sourceTask,
id: destTaskId
};
// Update any dependencies that reference the old task ID
tasks.forEach((task) => {
if (task.dependencies && task.dependencies.includes(sourceTask.id)) {
const depIndex = task.dependencies.indexOf(sourceTask.id);
task.dependencies[depIndex] = destTaskId;
}
if (task.subtasks) {
task.subtasks.forEach((subtask) => {
if (
subtask.dependencies &&
subtask.dependencies.includes(sourceTask.id)
) {
const depIndex = subtask.dependencies.indexOf(sourceTask.id);
subtask.dependencies[depIndex] = destTaskId;
}
});
}
});
// Update dependencies within movedTask's subtasks that reference sibling subtasks
if (Array.isArray(movedTask.subtasks)) {
movedTask.subtasks.forEach((subtask) => {
if (Array.isArray(subtask.dependencies)) {
subtask.dependencies = subtask.dependencies.map((dep) => {
// If dependency is a string like "oldParent.subId", update to "newParent.subId"
if (typeof dep === 'string' && dep.includes('.')) {
const [depParent, depSub] = dep.split('.');
if (parseInt(depParent, 10) === sourceTask.id) {
return `${destTaskId}.${depSub}`;
}
}
// If dependency is a number, and matches a subtask ID in the moved task, leave as is (context is implied)
return dep;
});
}
});
}
// Strategy based on commit fixes: remove source first, then replace destination
// This avoids index shifting problems
// Remove the source task first
tasks.splice(sourceTaskIndex, 1);
// Adjust the destination index if the source was before the destination
// Since we removed the source, indices after it shift down by 1
const adjustedDestIndex =
sourceTaskIndex < destTaskIndex ? destTaskIndex - 1 : destTaskIndex;
// Replace the placeholder destination task with the moved task (based on commit fixes)
if (adjustedDestIndex >= 0 && adjustedDestIndex < tasks.length) {
tasks[adjustedDestIndex] = movedTask;
} else {
// Insert at the end if index is out of bounds
tasks.push(movedTask);
}
log('info', `Moved task ${sourceTask.id} to new ID ${destTaskId}`);
return {
message: `Moved task ${sourceTask.id} to new ID ${destTaskId}`,
movedItem: movedTask
};
}
/**
* Get all tasks from all tags with tag information
* @param {Object} rawData - The raw tagged data object
* @returns {Array} A flat array of all task objects with tag property
*/
function getAllTasksWithTags(rawData) {
let allTasks = [];
for (const tagName in rawData) {
if (
Object.prototype.hasOwnProperty.call(rawData, tagName) &&
rawData[tagName] &&
Array.isArray(rawData[tagName].tasks)
) {
const tasksWithTag = rawData[tagName].tasks.map((task) => ({
...task,
tag: tagName
}));
allTasks = allTasks.concat(tasksWithTag);
}
}
return allTasks;
}
/**
* Validate move operation parameters and data
* @param {string} tasksPath - Path to tasks.json file
* @param {Array} taskIds - Array of task IDs to move
* @param {string} sourceTag - Source tag name
* @param {string} targetTag - Target tag name
* @param {Object} context - Context object
* @returns {Object} Validation result with rawData and sourceTasks
*/
async function validateMove(tasksPath, taskIds, sourceTag, targetTag, context) {
const { projectRoot } = context;
// Read the raw data without tag resolution to preserve tagged structure
let rawData = readJSON(tasksPath, projectRoot, sourceTag);
// Handle the case where readJSON returns resolved data with _rawTaggedData
if (rawData && rawData._rawTaggedData) {
rawData = rawData._rawTaggedData;
}
// Validate source tag exists
if (
!rawData ||
!rawData[sourceTag] ||
!Array.isArray(rawData[sourceTag].tasks)
) {
throw new MoveTaskError(
MOVE_ERROR_CODES.INVALID_SOURCE_TAG,
`Source tag "${sourceTag}" not found or invalid`
);
}
// Create target tag if it doesn't exist
if (!rawData[targetTag]) {
rawData[targetTag] = { tasks: [] };
log('info', `Created new tag "${targetTag}"`);
}
// Normalize all IDs to strings once for consistent comparison
const normalizedSearchIds = taskIds.map((id) => String(id));
const sourceTasks = rawData[sourceTag].tasks.filter((t) => {
const normalizedTaskId = String(t.id);
return normalizedSearchIds.includes(normalizedTaskId);
});
// Validate subtask movement
taskIds.forEach((taskId) => {
validateSubtaskMove(taskId, sourceTag, targetTag);
});
return { rawData, sourceTasks };
}
/**
* Load and prepare task data for move operation
* @param {Object} validation - Validation result from validateMove
* @returns {Object} Prepared data with rawData, sourceTasks, and allTasks
*/
async function prepareTaskData(validation) {
const { rawData, sourceTasks } = validation;
// Get all tasks for validation
const allTasks = getAllTasksWithTags(rawData);
return { rawData, sourceTasks, allTasks };
}
/**
* Resolve dependencies and determine tasks to move
* @param {Array} sourceTasks - Source tasks to move
* @param {Array} allTasks - All available tasks from all tags
* @param {Object} options - Move options
* @param {Array} taskIds - Original task IDs
* @param {string} sourceTag - Source tag name
* @param {string} targetTag - Target tag name
* @returns {Object} Tasks to move and dependency resolution info
*/
async function resolveDependencies(
sourceTasks,
allTasks,
options,
taskIds,
sourceTag,
targetTag
) {
const { withDependencies = false, ignoreDependencies = false } = options;
// Scope allTasks to the source tag to avoid cross-tag contamination when
// computing dependency chains for --with-dependencies
const tasksInSourceTag = Array.isArray(allTasks)
? allTasks.filter((t) => t && t.tag === sourceTag)
: [];
// Handle --with-dependencies flag first (regardless of cross-tag dependencies)
if (withDependencies) {
// Move dependent tasks along with main tasks
// Find ALL dependencies recursively, but only using tasks from the source tag
const allDependentTaskIdsRaw = findAllDependenciesRecursively(
sourceTasks,
tasksInSourceTag,
{ maxDepth: 100, includeSelf: false }
);
// Filter dependent IDs to those that actually exist in the source tag
const sourceTagIds = new Set(
tasksInSourceTag.map((t) =>
typeof t.id === 'string' ? parseInt(t.id, 10) : t.id
)
);
const allDependentTaskIds = allDependentTaskIdsRaw.filter((depId) => {
// Only numeric task IDs are eligible to be moved (subtasks cannot be moved cross-tag)
const normalizedId = normalizeDependency(depId);
return Number.isFinite(normalizedId) && sourceTagIds.has(normalizedId);
});
const allTaskIdsToMove = [...new Set([...taskIds, ...allDependentTaskIds])];
log(
'info',
`Moving ${allTaskIdsToMove.length} tasks (including dependencies): ${allTaskIdsToMove.join(', ')}`
);
return {
tasksToMove: allTaskIdsToMove,
dependencyResolution: {
type: 'with-dependencies',
dependentTasks: allDependentTaskIds
}
};
}
// Find cross-tag dependencies (these shouldn't exist since dependencies are only within tags)
const crossTagDependencies = findCrossTagDependencies(
sourceTasks,
sourceTag,
targetTag,
allTasks
);
if (crossTagDependencies.length > 0) {
if (ignoreDependencies) {
// Break cross-tag dependencies (edge case - shouldn't normally happen)
sourceTasks.forEach((task) => {
const sourceTagTasks = tasksInSourceTag;
const targetTagTasks = Array.isArray(allTasks)
? allTasks.filter((t) => t && t.tag === targetTag)
: [];
task.dependencies = task.dependencies.filter((depId) => {
const parentTaskId = normalizeDependency(depId);
// If dependency resolves to a task in the source tag, drop it (would be cross-tag after move)
if (
Number.isFinite(parentTaskId) &&
sourceTagTasks.some((t) => t.id === parentTaskId)
) {
return false;
}
// If dependency resolves to a task in the target tag, keep it
if (
Number.isFinite(parentTaskId) &&
targetTagTasks.some((t) => t.id === parentTaskId)
) {
return true;
}
// Otherwise, keep as-is (unknown/unresolved dependency)
return true;
});
});
log(
'warn',
`Removed ${crossTagDependencies.length} cross-tag dependencies`
);
return {
tasksToMove: taskIds,
dependencyResolution: {
type: 'ignored-dependencies',
conflicts: crossTagDependencies
}
};
} else {
// Block move and show error
throw new MoveTaskError(
MOVE_ERROR_CODES.CROSS_TAG_DEPENDENCY_CONFLICTS,
`Cannot move tasks: ${crossTagDependencies.length} cross-tag dependency conflicts found`,
{
conflicts: crossTagDependencies,
sourceTag,
targetTag,
taskIds
}
);
}
}
return {
tasksToMove: taskIds,
dependencyResolution: { type: 'no-conflicts' }
};
}
/**
* Get the next available task ID in the target tag.
* Finds the maximum existing ID among target tag tasks and any already-assigned
* new IDs from the current move batch, then returns max + 1.
* @param {Object} rawData - Raw data object
* @param {string} targetTag - Target tag name
* @param {Map} idRemapping - Map of old ID -> new ID for tasks already processed in this batch
* @returns {number} Next available task ID
*/
function getNextAvailableId(rawData, targetTag, idRemapping) {
const existingIds = rawData[targetTag].tasks.map((t) => t.id);
const remappedIds = Array.from(idRemapping.values());
const allIds = [...existingIds, ...remappedIds];
if (allIds.length === 0) return 1;
return Math.max(...allIds) + 1;
}
/**
* Execute the actual move operation
* @param {Array} tasksToMove - Array of task IDs to move
* @param {string} sourceTag - Source tag name
* @param {string} targetTag - Target tag name
* @param {Object} rawData - Raw data object
* @param {Object} context - Context object
* @param {string} tasksPath - Path to tasks.json file
* @returns {Object} Move operation result
*/
async function executeMoveOperation(
tasksToMove,
sourceTag,
targetTag,
rawData,
context,
tasksPath
) {
const { projectRoot } = context;
const movedTasks = [];
// Track ID remapping: oldId -> newId (only for tasks that needed renumbering)
const idRemapping = new Map();
// Move each task from source to target tag
for (const taskId of tasksToMove) {
// Normalize taskId to number for comparison
const normalizedTaskId =
typeof taskId === 'string' ? parseInt(taskId, 10) : taskId;
const sourceTaskIndex = rawData[sourceTag].tasks.findIndex(
(t) => t.id === normalizedTaskId
);
if (sourceTaskIndex === -1) {
throw new MoveTaskError(
MOVE_ERROR_CODES.TASK_NOT_FOUND,
`Task ${taskId} not found in source tag "${sourceTag}"`
);
}
const taskToMove = rawData[sourceTag].tasks[sourceTaskIndex];
// Check for ID conflicts in target tag
const existingTaskIndex = rawData[targetTag].tasks.findIndex(
(t) => t.id === normalizedTaskId
);
let assignedId = normalizedTaskId;
if (existingTaskIndex !== -1) {
// ID collision detected — auto-renumber to the next available ID
assignedId = getNextAvailableId(rawData, targetTag, idRemapping);
idRemapping.set(normalizedTaskId, assignedId);
log(
'info',
`Task ${normalizedTaskId} conflicts with existing ID in "${targetTag}", renumbered to ${assignedId}`
);
}
// Apply the new ID to the task
taskToMove.id = assignedId;
// Update internal subtask dependency references that pointed to the old parent ID
if (Array.isArray(taskToMove.subtasks)) {
taskToMove.subtasks.forEach((subtask) => {
if (Array.isArray(subtask.dependencies)) {
subtask.dependencies = subtask.dependencies.map((dep) => {
if (typeof dep === 'string' && dep.includes('.')) {
const [depParent, depSub] = dep.split('.');
if (parseInt(depParent, 10) === normalizedTaskId) {
return `${assignedId}.${depSub}`;
}
}
return dep;
});
}
});
}
// Remove from source tag
rawData[sourceTag].tasks.splice(sourceTaskIndex, 1);
// Preserve task metadata and add to target tag
const taskWithPreservedMetadata = preserveTaskMetadata(
taskToMove,
sourceTag,
targetTag
);
rawData[targetTag].tasks.push(taskWithPreservedMetadata);
const moveEntry = {
id: taskId,
fromTag: sourceTag,
toTag: targetTag
};
if (assignedId !== normalizedTaskId) {
moveEntry.originalId = normalizedTaskId;
moveEntry.newId = assignedId;
}
movedTasks.push(moveEntry);
log(
'info',
`Moved task ${taskId} from "${sourceTag}" to "${targetTag}"${assignedId !== normalizedTaskId ? ` (renumbered to ${assignedId})` : ''}`
);
}
// After all tasks are moved, update cross-references within the moved batch.
// If task A depended on task B and both were moved but B got renumbered,
// update A's dependency to point to B's new ID.
if (idRemapping.size > 0) {
for (const taskId of tasksToMove) {
const normalizedTaskId =
typeof taskId === 'string' ? parseInt(taskId, 10) : taskId;
// Find the task in the target tag (it may have been renumbered)
const finalId = idRemapping.get(normalizedTaskId) || normalizedTaskId;
const movedTask = rawData[targetTag].tasks.find(
(t) => t.id === finalId
);
if (movedTask && Array.isArray(movedTask.dependencies)) {
movedTask.dependencies = movedTask.dependencies.map((dep) => {
const normalizedDep = normalizeDependency(dep);
if (
Number.isFinite(normalizedDep) &&
idRemapping.has(normalizedDep)
) {
return idRemapping.get(normalizedDep);
}
return dep;
});
}
// Also update subtask dependencies that reference remapped IDs
if (movedTask && Array.isArray(movedTask.subtasks)) {
movedTask.subtasks.forEach((subtask) => {
if (Array.isArray(subtask.dependencies)) {
subtask.dependencies = subtask.dependencies.map((dep) => {
const normalizedDep = normalizeDependency(dep);
if (
Number.isFinite(normalizedDep) &&
idRemapping.has(normalizedDep)
) {
return idRemapping.get(normalizedDep);
}
return dep;
});
}
});
}
}
}
return { rawData, movedTasks };
}
/**
* Finalize the move operation by saving data and returning result
* @param {Object} moveResult - Result from executeMoveOperation
* @param {string} tasksPath - Path to tasks.json file
* @param {Object} context - Context object
* @param {string} sourceTag - Source tag name
* @param {string} targetTag - Target tag name
* @returns {Object} Final result object
*/
async function finalizeMove(
moveResult,