mirror of
https://github.com/eyaltoledano/claude-task-master.git
synced 2025-07-04 23:50:50 +00:00

* feat(tasks): Fix critical tag corruption bug in task management - Fixed missing context parameters in writeJSON calls across add-task, remove-task, and add-subtask functions - Added projectRoot and tag parameters to prevent data corruption in multi-tag environments - Re-enabled generateTaskFiles calls to ensure markdown files are updated after operations - Enhanced add_subtask MCP tool with tag parameter support - Refactored addSubtaskDirect function to properly pass context to core logic - Streamlined codebase by removing deprecated functionality This resolves the critical bug where task operations in one tag context would corrupt or delete tasks from other tags in tasks.json. * feat(task-manager): Enhance addSubtask with current tag support - Added `getCurrentTag` utility to retrieve the current tag context for task operations. - Updated `addSubtask` to use the current tag when reading and writing tasks, ensuring proper context handling. - Refactored tests to accommodate changes in the `addSubtask` function, ensuring accurate mock implementations and expectations. - Cleaned up test cases for better readability and maintainability. This improves task management by preventing tag-related data corruption and enhances the overall functionality of the task manager. * feat(remove-task): Add tag support for task removal and enhance error handling - Introduced `tag` parameter in `removeTaskDirect` to specify context for task operations, improving multi-tag support. - Updated logging to include tag context in messages for better traceability. - Refactored task removal logic to streamline the process and improve error reporting. - Added comprehensive unit tests to validate tag handling and ensure robust error management. This enhancement prevents task data corruption across different tags and improves the overall reliability of the task management system. * feat(add-task): Add projectRoot and tag parameters to addTask tests - Updated `addTask` unit tests to include `projectRoot` and `tag` parameters for better context handling. - Enhanced test cases to ensure accurate expectations and improve overall test coverage. This change aligns with recent enhancements in task management, ensuring consistency across task operations. * feat(set-task-status): Add tag parameter support and enhance task status handling - Introduced `tag` parameter in `setTaskStatusDirect` and related functions to improve context management in multi-tag environments. - Updated `writeJSON` calls to ensure task data integrity across different tags. - Enhanced unit tests to validate tag preservation during task status updates, ensuring robust functionality. This change aligns with recent improvements in task management, preventing data corruption and enhancing overall reliability. * feat(tag-management): Enhance writeJSON calls to preserve tag context - Updated `writeJSON` calls in `createTag`, `deleteTag`, `renameTag`, `copyTag`, and `enhanceTagsWithMetadata` to include `projectRoot` for better context management and to prevent tag corruption. - Added comprehensive unit tests for tag management functions to ensure data integrity and proper tag handling during operations. This change improves the reliability of tag management by ensuring that operations do not corrupt existing tags and maintains the overall structure of the task data. * feat(expand-task): Update writeJSON to include projectRoot and tag context - Modified `writeJSON` call in `expandTaskDirect` to pass `projectRoot` and `tag` parameters, ensuring proper context management when saving tasks.json. - This change aligns with recent enhancements in task management, preventing potential data corruption and improving overall reliability. * feat(fix-dependencies): Add projectRoot and tag parameters for enhanced context management - Updated `fixDependenciesDirect` and `registerFixDependenciesTool` to include `projectRoot` and `tag` parameters, improving context handling during dependency fixes. - Introduced a new unit test for `fixDependenciesCommand` to ensure proper preservation of projectRoot and tag data in JSON outputs. This change enhances the reliability of dependency management by ensuring that context is maintained across operations, preventing potential data issues. * fix(context): propagate projectRoot and tag through dependency, expansion, status-update and tag-management commands to prevent cross-tag data corruption * test(fix-dependencies): Enhance unit tests for fixDependenciesCommand - Refactored tests to use unstable mocks for utils, ui, and task-manager modules, improving isolation and reliability. - Added checks for process.exit to ensure proper handling of invalid data scenarios. - Updated test cases to verify writeJSON calls with projectRoot and tag parameters, ensuring accurate context preservation during dependency fixes. This change strengthens the test suite for dependency management, ensuring robust functionality and preventing potential data issues. * chore(plan): remove outdated fix plan for `writeJSON` context parameters
235 lines
7.4 KiB
JavaScript
235 lines
7.4 KiB
JavaScript
import path from 'path';
|
|
import * as fs from 'fs';
|
|
import { readJSON, writeJSON, log, findTaskById } from '../utils.js';
|
|
import generateTaskFiles from './generate-task-files.js';
|
|
import taskExists from './task-exists.js';
|
|
|
|
/**
|
|
* Removes one or more tasks or subtasks from the tasks file
|
|
* @param {string} tasksPath - Path to the tasks file
|
|
* @param {string} taskIds - Comma-separated string of task/subtask IDs to remove (e.g., '5,6.1,7')
|
|
* @param {Object} context - Context object containing projectRoot and tag information
|
|
* @returns {Object} Result object with success status, messages, and removed task info
|
|
*/
|
|
async function removeTask(tasksPath, taskIds, context = {}) {
|
|
const { projectRoot, tag } = context;
|
|
const results = {
|
|
success: true,
|
|
messages: [],
|
|
errors: [],
|
|
removedTasks: []
|
|
};
|
|
const taskIdsToRemove = taskIds
|
|
.split(',')
|
|
.map((id) => id.trim())
|
|
.filter(Boolean); // Remove empty strings if any
|
|
|
|
if (taskIdsToRemove.length === 0) {
|
|
results.success = false;
|
|
results.errors.push('No valid task IDs provided.');
|
|
return results;
|
|
}
|
|
|
|
try {
|
|
// Read the tasks file ONCE before the loop, preserving the full tagged structure
|
|
const rawData = readJSON(tasksPath, projectRoot); // Read raw data
|
|
if (!rawData) {
|
|
throw new Error(`Could not read tasks file at ${tasksPath}`);
|
|
}
|
|
|
|
// Use the full tagged data if available, otherwise use the data as is
|
|
const fullTaggedData = rawData._rawTaggedData || rawData;
|
|
|
|
const currentTag = tag || rawData.tag || 'master';
|
|
if (!fullTaggedData[currentTag] || !fullTaggedData[currentTag].tasks) {
|
|
throw new Error(`Tag '${currentTag}' not found or has no tasks.`);
|
|
}
|
|
|
|
const tasks = fullTaggedData[currentTag].tasks; // Work with tasks from the correct tag
|
|
|
|
const tasksToDeleteFiles = []; // Collect IDs of main tasks whose files should be deleted
|
|
|
|
for (const taskId of taskIdsToRemove) {
|
|
// Check if the task ID exists *before* attempting removal
|
|
if (!taskExists(tasks, taskId)) {
|
|
const errorMsg = `Task with ID ${taskId} in tag '${currentTag}' not found or already removed.`;
|
|
results.errors.push(errorMsg);
|
|
results.success = false; // Mark overall success as false if any error occurs
|
|
continue; // Skip to the next ID
|
|
}
|
|
|
|
try {
|
|
// Handle subtask removal (e.g., '5.2')
|
|
if (typeof taskId === 'string' && taskId.includes('.')) {
|
|
const [parentTaskId, subtaskId] = taskId
|
|
.split('.')
|
|
.map((id) => parseInt(id, 10));
|
|
|
|
// Find the parent task
|
|
const parentTask = tasks.find((t) => t.id === parentTaskId);
|
|
if (!parentTask || !parentTask.subtasks) {
|
|
throw new Error(
|
|
`Parent task ${parentTaskId} or its subtasks not found for subtask ${taskId}`
|
|
);
|
|
}
|
|
|
|
// Find the subtask to remove
|
|
const subtaskIndex = parentTask.subtasks.findIndex(
|
|
(st) => st.id === subtaskId
|
|
);
|
|
if (subtaskIndex === -1) {
|
|
throw new Error(
|
|
`Subtask ${subtaskId} not found in parent task ${parentTaskId}`
|
|
);
|
|
}
|
|
|
|
// Store the subtask info before removal
|
|
const removedSubtask = {
|
|
...parentTask.subtasks[subtaskIndex],
|
|
parentTaskId: parentTaskId
|
|
};
|
|
results.removedTasks.push(removedSubtask);
|
|
|
|
// Remove the subtask from the parent
|
|
parentTask.subtasks.splice(subtaskIndex, 1);
|
|
|
|
results.messages.push(
|
|
`Successfully removed subtask ${taskId} from tag '${currentTag}'`
|
|
);
|
|
}
|
|
// Handle main task removal
|
|
else {
|
|
const taskIdNum = parseInt(taskId, 10);
|
|
const taskIndex = tasks.findIndex((t) => t.id === taskIdNum);
|
|
if (taskIndex === -1) {
|
|
throw new Error(
|
|
`Task with ID ${taskId} not found in tag '${currentTag}'`
|
|
);
|
|
}
|
|
|
|
// Store the task info before removal
|
|
const removedTask = tasks[taskIndex];
|
|
results.removedTasks.push(removedTask);
|
|
tasksToDeleteFiles.push(taskIdNum); // Add to list for file deletion
|
|
|
|
// Remove the task from the main array
|
|
tasks.splice(taskIndex, 1);
|
|
|
|
results.messages.push(
|
|
`Successfully removed task ${taskId} from tag '${currentTag}'`
|
|
);
|
|
}
|
|
} catch (innerError) {
|
|
// Catch errors specific to processing *this* ID
|
|
const errorMsg = `Error processing ID ${taskId}: ${innerError.message}`;
|
|
results.errors.push(errorMsg);
|
|
results.success = false;
|
|
log('warn', errorMsg); // Log as warning and continue with next ID
|
|
}
|
|
} // End of loop through taskIdsToRemove
|
|
|
|
// --- Post-Loop Operations ---
|
|
|
|
// Only proceed with cleanup and saving if at least one task was potentially removed
|
|
if (results.removedTasks.length > 0) {
|
|
const allRemovedIds = new Set(
|
|
taskIdsToRemove.map((id) =>
|
|
typeof id === 'string' && id.includes('.') ? id : parseInt(id, 10)
|
|
)
|
|
);
|
|
|
|
// Update the tasks in the current tag of the full data structure
|
|
fullTaggedData[currentTag].tasks = tasks;
|
|
|
|
// Remove dependencies from all tags
|
|
for (const tagName in fullTaggedData) {
|
|
if (
|
|
Object.prototype.hasOwnProperty.call(fullTaggedData, tagName) &&
|
|
fullTaggedData[tagName] &&
|
|
fullTaggedData[tagName].tasks
|
|
) {
|
|
const currentTagTasks = fullTaggedData[tagName].tasks;
|
|
currentTagTasks.forEach((task) => {
|
|
if (task.dependencies) {
|
|
task.dependencies = task.dependencies.filter(
|
|
(depId) => !allRemovedIds.has(depId)
|
|
);
|
|
}
|
|
if (task.subtasks) {
|
|
task.subtasks.forEach((subtask) => {
|
|
if (subtask.dependencies) {
|
|
subtask.dependencies = subtask.dependencies.filter(
|
|
(depId) =>
|
|
!allRemovedIds.has(`${task.id}.${depId}`) &&
|
|
!allRemovedIds.has(depId)
|
|
);
|
|
}
|
|
});
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
// Save the updated raw data structure
|
|
writeJSON(tasksPath, fullTaggedData, projectRoot, currentTag);
|
|
|
|
// Delete task files AFTER saving tasks.json
|
|
for (const taskIdNum of tasksToDeleteFiles) {
|
|
const taskFileName = path.join(
|
|
path.dirname(tasksPath),
|
|
`task_${taskIdNum.toString().padStart(3, '0')}.txt`
|
|
);
|
|
if (fs.existsSync(taskFileName)) {
|
|
try {
|
|
fs.unlinkSync(taskFileName);
|
|
results.messages.push(`Deleted task file: ${taskFileName}`);
|
|
} catch (unlinkError) {
|
|
const unlinkMsg = `Failed to delete task file ${taskFileName}: ${unlinkError.message}`;
|
|
results.errors.push(unlinkMsg);
|
|
results.success = false;
|
|
log('warn', unlinkMsg);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Generate updated task files ONCE, with context
|
|
try {
|
|
await generateTaskFiles(tasksPath, path.dirname(tasksPath), {
|
|
projectRoot,
|
|
tag: currentTag
|
|
});
|
|
results.messages.push('Task files regenerated successfully.');
|
|
} catch (genError) {
|
|
const genErrMsg = `Failed to regenerate task files: ${genError.message}`;
|
|
results.errors.push(genErrMsg);
|
|
results.success = false;
|
|
log('warn', genErrMsg);
|
|
}
|
|
} else if (results.errors.length === 0) {
|
|
results.messages.push('No tasks found matching the provided IDs.');
|
|
}
|
|
|
|
// Consolidate messages for final output
|
|
const finalMessage = results.messages.join('\n');
|
|
const finalError = results.errors.join('\n');
|
|
|
|
return {
|
|
success: results.success,
|
|
message: finalMessage || 'No tasks were removed.',
|
|
error: finalError || null,
|
|
removedTasks: results.removedTasks
|
|
};
|
|
} catch (error) {
|
|
// Catch errors from reading file or other initial setup
|
|
log('error', `Error removing tasks: ${error.message}`);
|
|
return {
|
|
success: false,
|
|
message: '',
|
|
error: `Operation failed: ${error.message}`,
|
|
removedTasks: []
|
|
};
|
|
}
|
|
}
|
|
|
|
export default removeTask;
|