mirror of
https://github.com/eyaltoledano/claude-task-master.git
synced 2025-11-09 22:37:54 +00:00
* refactor(context): Standardize tag and projectRoot handling across all task tools This commit unifies context management by adopting a boundary-first resolution strategy. All task-scoped tools now resolve `tag` and `projectRoot` at their entry point and forward these values to the underlying direct functions. This approach centralizes context logic, ensuring consistent behavior and enhanced flexibility in multi-tag environments. * fix(tag): Clean up tag handling in task functions and sync process This commit refines the handling of the `tag` parameter across multiple functions, ensuring consistent context management. The `tag` is now passed more efficiently in `listTasksDirect`, `setTaskStatusDirect`, and `syncTasksToReadme`, improving clarity and reducing redundancy. Additionally, a TODO comment has been added in `sync-readme.js` to address future tag support enhancements. * feat(tag): Implement Boundary-First Tag Resolution for consistent tag handling This commit introduces Boundary-First Tag Resolution in the task manager, ensuring consistent and deterministic tag handling across CLI and MCP. This change resolves potential race conditions and improves the reliability of tag-specific operations. Additionally, the `expandTask` function has been updated to use the resolved tag when writing JSON, enhancing data integrity during task updates. * chore(biome): formatting * fix(expand-task): Update writeJSON call to use tag instead of resolvedTag * fix(commands): Enhance complexity report path resolution and task initialization `resolveComplexityReportPath` function to streamline output path generation based on tag context and user-defined output. - Improved clarity and maintainability of command handling by centralizing path resolution logic. * Fix: unknown currentTag * fix(task-manager): Update generateTaskFiles calls to include tag and projectRoot parameters This commit modifies the `moveTask` and `updateSubtaskById` functions to pass the `tag` and `projectRoot` parameters to the `generateTaskFiles` function. This ensures that task files are generated with the correct context when requested, enhancing consistency in task management operations. * fix(commands): Refactor tag handling and complexity report path resolution This commit updates the `registerCommands` function to utilize `taskMaster.getCurrentTag()` for consistent tag retrieval across command actions. It also enhances the initialization of `TaskMaster` by passing the tag directly, improving clarity and maintainability. The complexity report path resolution is streamlined to ensure correct file naming based on the current tag context. * fix(task-master): Update complexity report path expectations in tests This commit modifies the `initTaskMaster` test to expect a valid string for the complexity report path, ensuring it matches the expected file naming convention. This change enhances test reliability by verifying the correct output format when the path is generated. * fix(set-task-status): Enhance logging and tag resolution in task status updates This commit improves the logging output in the `registerSetTaskStatusTool` function to include the tag context when setting task statuses. It also updates the tag handling by resolving the tag using the `resolveTag` utility, ensuring that the correct tag is used when updating task statuses. Additionally, the `setTaskStatus` function is modified to remove the tag parameter from the `readJSON` and `writeJSON` calls, streamlining the data handling process. * fix(commands, expand-task, task-manager): Add complexity report option and enhance path handling This commit introduces a new `--complexity-report` option in the `registerCommands` function, allowing users to specify a custom path for the complexity report. The `expandTask` function is updated to accept the `complexityReportPath` from the context, ensuring it is utilized correctly during task expansion. Additionally, the `setTaskStatus` function now includes the `tag` parameter in the `readJSON` and `writeJSON` calls, improving task status updates with proper context. The `initTaskMaster` function is also modified to create parent directories for output paths, enhancing file handling robustness. * fix(expand-task): Add complexityReportPath to context for task expansion tests This commit updates the test for the `expandTask` function by adding the `complexityReportPath` to the context object. This change ensures that the complexity report path is correctly utilized in the test, aligning with recent enhancements to complexity report handling in the task manager. * chore: implement suggested changes * fix(parse-prd): Clarify tag parameter description for task organization Updated the documentation for the `tag` parameter in the `parse-prd.js` file to provide a clearer context on its purpose for organizing tasks into separate task lists. * Fix Inconsistent tag resolution pattern. * fix: Enhance complexity report path handling with tag support This commit updates various functions to incorporate the `tag` parameter when resolving complexity report paths. The `expandTaskDirect`, `resolveComplexityReportPath`, and related tools now utilize the current tag context, improving consistency in task management. Additionally, the complexity report path is now correctly passed through the context in the `expand-task` and `set-task-status` tools, ensuring accurate report retrieval based on the active tag. * Updated the JSDoc for the `tag` parameter in the `show-task.js` file. * Remove redundant comment on tag parameter in readJSON call * Remove unused import for getTagAwareFilePath * Add missed complexityReportPath to args for task expansion * fix(tests): Enhance research tests with tag-aware functionality This commit updates the `research.test.js` file to improve the testing of the `performResearch` function by incorporating tag-aware functionality. Key changes include mocking the `findProjectRoot` to return a valid path, enhancing the `ContextGatherer` and `FuzzyTaskSearch` mocks, and adding comprehensive tests for tag parameter handling in various scenarios. The tests now cover passing different tag values, ensuring correct behavior when tags are provided, undefined, or null, and validating the integration of tags in task discovery and context gathering processes. * Remove unused import for * fix: Refactor complexity report path handling and improve argument destructuring This commit enhances the `expandTaskDirect` function by improving the destructuring of arguments for better readability. It also updates the `analyze.js` and `analyze-task-complexity.js` files to utilize the new `resolveComplexityReportOutputPath` function, ensuring tag-aware resolution of output paths. Additionally, logging has been added to provide clarity on the report path being used. * test: Add complexity report tag isolation tests and improve path handling This commit introduces a new test file for complexity report tag isolation, ensuring that different tags maintain separate complexity reports. It enhances the existing tests in `analyze-task-complexity.test.js` by updating expectations to use `expect.stringContaining` for file paths, improving robustness against path changes. The new tests cover various scenarios, including path resolution and report generation for both master and feature tags, ensuring no cross-tag contamination occurs. * Update scripts/modules/task-manager/list-tasks.js Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update scripts/modules/task-manager/list-tasks.js Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * test(complexity-report): Fix tag slugification in filename expectations - Update mocks to use slugifyTagForFilePath for cross-platform compatibility - Replace raw tag values with slugified versions in expected filenames - Fix test expecting 'feature/user-auth-v2' to expect 'feature-user-auth-v2' - Align test with actual filename generation logic that sanitizes special chars --------- Co-authored-by: Ralph Khreish <35776126+Crunchyman-ralph@users.noreply.github.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
234 lines
7.4 KiB
JavaScript
234 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
|
|
* @param {string} [context.projectRoot] - Project root path
|
|
* @param {string} [context.tag] - Tag for the task
|
|
* @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, tag); // 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;
|
|
|
|
if (!fullTaggedData[tag] || !fullTaggedData[tag].tasks) {
|
|
throw new Error(`Tag '${tag}' not found or has no tasks.`);
|
|
}
|
|
|
|
const tasks = fullTaggedData[tag].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 '${tag}' 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 '${tag}'`
|
|
);
|
|
}
|
|
// 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 '${tag}'`);
|
|
}
|
|
|
|
// 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 '${tag}'`
|
|
);
|
|
}
|
|
} 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[tag].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, tag);
|
|
|
|
// 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
|
|
});
|
|
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;
|