mirror of
https://github.com/eyaltoledano/claude-task-master.git
synced 2025-07-04 07:26:38 +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
202 lines
6.3 KiB
JavaScript
202 lines
6.3 KiB
JavaScript
import path from 'path';
|
|
import fs from 'fs';
|
|
import chalk from 'chalk';
|
|
|
|
import { log, readJSON } from '../utils.js';
|
|
import { formatDependenciesWithStatus } from '../ui.js';
|
|
import { validateAndFixDependencies } from '../dependency-manager.js';
|
|
import { getDebugFlag } from '../config-manager.js';
|
|
|
|
/**
|
|
* Generate individual task files from tasks.json
|
|
* @param {string} tasksPath - Path to the tasks.json file
|
|
* @param {string} outputDir - Output directory for task files
|
|
* @param {Object} options - Additional options (mcpLog for MCP mode, projectRoot, tag)
|
|
* @returns {Object|undefined} Result object in MCP mode, undefined in CLI mode
|
|
*/
|
|
function generateTaskFiles(tasksPath, outputDir, options = {}) {
|
|
try {
|
|
const isMcpMode = !!options?.mcpLog;
|
|
|
|
// 1. Read the raw data structure, ensuring we have all tags.
|
|
// We call readJSON without a specific tag to get the resolved default view,
|
|
// which correctly contains the full structure in `_rawTaggedData`.
|
|
const resolvedData = readJSON(tasksPath, options.projectRoot);
|
|
if (!resolvedData) {
|
|
throw new Error(`Could not read or parse tasks file: ${tasksPath}`);
|
|
}
|
|
// Prioritize the _rawTaggedData if it exists, otherwise use the data as is.
|
|
const rawData = resolvedData._rawTaggedData || resolvedData;
|
|
|
|
// 2. Determine the target tag we need to generate files for.
|
|
const targetTag = options.tag || resolvedData.tag || 'master';
|
|
const tagData = rawData[targetTag];
|
|
|
|
if (!tagData || !tagData.tasks) {
|
|
throw new Error(
|
|
`Tag '${targetTag}' not found or has no tasks in the data.`
|
|
);
|
|
}
|
|
const tasksForGeneration = tagData.tasks;
|
|
|
|
// Create the output directory if it doesn't exist
|
|
if (!fs.existsSync(outputDir)) {
|
|
fs.mkdirSync(outputDir, { recursive: true });
|
|
}
|
|
|
|
log(
|
|
'info',
|
|
`Preparing to regenerate ${tasksForGeneration.length} task files for tag '${targetTag}'`
|
|
);
|
|
|
|
// 3. Validate dependencies using the FULL, raw data structure to prevent data loss.
|
|
validateAndFixDependencies(
|
|
rawData, // Pass the entire object with all tags
|
|
tasksPath,
|
|
options.projectRoot,
|
|
targetTag // Provide the current tag context for the operation
|
|
);
|
|
|
|
const allTasksInTag = tagData.tasks;
|
|
const validTaskIds = allTasksInTag.map((task) => task.id);
|
|
|
|
// Cleanup orphaned task files
|
|
log('info', 'Checking for orphaned task files to clean up...');
|
|
try {
|
|
const files = fs.readdirSync(outputDir);
|
|
// Tag-aware file patterns: master -> task_001.txt, other tags -> task_001_tagname.txt
|
|
const masterFilePattern = /^task_(\d+)\.txt$/;
|
|
const taggedFilePattern = new RegExp(`^task_(\\d+)_${targetTag}\\.txt$`);
|
|
|
|
const orphanedFiles = files.filter((file) => {
|
|
let match = null;
|
|
let fileTaskId = null;
|
|
|
|
// Check if file belongs to current tag
|
|
if (targetTag === 'master') {
|
|
match = file.match(masterFilePattern);
|
|
if (match) {
|
|
fileTaskId = parseInt(match[1], 10);
|
|
// Only clean up master files when processing master tag
|
|
return !validTaskIds.includes(fileTaskId);
|
|
}
|
|
} else {
|
|
match = file.match(taggedFilePattern);
|
|
if (match) {
|
|
fileTaskId = parseInt(match[1], 10);
|
|
// Only clean up files for the current tag
|
|
return !validTaskIds.includes(fileTaskId);
|
|
}
|
|
}
|
|
return false;
|
|
});
|
|
|
|
if (orphanedFiles.length > 0) {
|
|
log(
|
|
'info',
|
|
`Found ${orphanedFiles.length} orphaned task files to remove for tag '${targetTag}'`
|
|
);
|
|
orphanedFiles.forEach((file) => {
|
|
const filePath = path.join(outputDir, file);
|
|
fs.unlinkSync(filePath);
|
|
});
|
|
} else {
|
|
log('info', 'No orphaned task files found.');
|
|
}
|
|
} catch (err) {
|
|
log('warn', `Error cleaning up orphaned task files: ${err.message}`);
|
|
}
|
|
|
|
// Generate task files for the target tag
|
|
log('info', `Generating individual task files for tag '${targetTag}'...`);
|
|
tasksForGeneration.forEach((task) => {
|
|
// Tag-aware file naming: master -> task_001.txt, other tags -> task_001_tagname.txt
|
|
const taskFileName =
|
|
targetTag === 'master'
|
|
? `task_${task.id.toString().padStart(3, '0')}.txt`
|
|
: `task_${task.id.toString().padStart(3, '0')}_${targetTag}.txt`;
|
|
|
|
const taskPath = path.join(outputDir, taskFileName);
|
|
|
|
let content = `# Task ID: ${task.id}\n`;
|
|
content += `# Title: ${task.title}\n`;
|
|
content += `# Status: ${task.status || 'pending'}\n`;
|
|
|
|
if (task.dependencies && task.dependencies.length > 0) {
|
|
content += `# Dependencies: ${formatDependenciesWithStatus(task.dependencies, allTasksInTag, false)}\n`;
|
|
} else {
|
|
content += '# Dependencies: None\n';
|
|
}
|
|
|
|
content += `# Priority: ${task.priority || 'medium'}\n`;
|
|
content += `# Description: ${task.description || ''}\n`;
|
|
content += '# Details:\n';
|
|
content += (task.details || '')
|
|
.split('\n')
|
|
.map((line) => line)
|
|
.join('\n');
|
|
content += '\n\n';
|
|
content += '# Test Strategy:\n';
|
|
content += (task.testStrategy || '')
|
|
.split('\n')
|
|
.map((line) => line)
|
|
.join('\n');
|
|
content += '\n';
|
|
|
|
if (task.subtasks && task.subtasks.length > 0) {
|
|
content += '\n# Subtasks:\n';
|
|
task.subtasks.forEach((subtask) => {
|
|
content += `## ${subtask.id}. ${subtask.title} [${subtask.status || 'pending'}]\n`;
|
|
if (subtask.dependencies && subtask.dependencies.length > 0) {
|
|
const subtaskDeps = subtask.dependencies
|
|
.map((depId) =>
|
|
typeof depId === 'number'
|
|
? `${task.id}.${depId}`
|
|
: depId.toString()
|
|
)
|
|
.join(', ');
|
|
content += `### Dependencies: ${subtaskDeps}\n`;
|
|
} else {
|
|
content += '### Dependencies: None\n';
|
|
}
|
|
content += `### Description: ${subtask.description || ''}\n`;
|
|
content += '### Details:\n';
|
|
content += (subtask.details || '')
|
|
.split('\n')
|
|
.map((line) => line)
|
|
.join('\n');
|
|
content += '\n\n';
|
|
});
|
|
}
|
|
|
|
fs.writeFileSync(taskPath, content);
|
|
});
|
|
|
|
log(
|
|
'success',
|
|
`All ${tasksForGeneration.length} tasks for tag '${targetTag}' have been generated into '${outputDir}'.`
|
|
);
|
|
|
|
if (isMcpMode) {
|
|
return {
|
|
success: true,
|
|
count: tasksForGeneration.length,
|
|
directory: outputDir
|
|
};
|
|
}
|
|
} catch (error) {
|
|
log('error', `Error generating task files: ${error.message}`);
|
|
if (!options?.mcpLog) {
|
|
console.error(chalk.red(`Error generating task files: ${error.message}`));
|
|
if (getDebugFlag()) {
|
|
console.error(error);
|
|
}
|
|
process.exit(1);
|
|
} else {
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
export default generateTaskFiles;
|