* 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
255 lines
7.2 KiB
JavaScript
255 lines
7.2 KiB
JavaScript
/**
|
|
* expand-task.js
|
|
* Direct function implementation for expanding a task into subtasks
|
|
*/
|
|
|
|
import expandTask from '../../../../scripts/modules/task-manager/expand-task.js';
|
|
import {
|
|
readJSON,
|
|
writeJSON,
|
|
enableSilentMode,
|
|
disableSilentMode,
|
|
isSilentMode
|
|
} from '../../../../scripts/modules/utils.js';
|
|
import path from 'path';
|
|
import fs from 'fs';
|
|
import { createLogWrapper } from '../../tools/utils.js';
|
|
|
|
/**
|
|
* Direct function wrapper for expanding a task into subtasks with error handling.
|
|
*
|
|
* @param {Object} args - Command arguments
|
|
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file.
|
|
* @param {string} args.id - The ID of the task to expand.
|
|
* @param {number|string} [args.num] - Number of subtasks to generate.
|
|
* @param {boolean} [args.research] - Enable research role for subtask generation.
|
|
* @param {string} [args.prompt] - Additional context to guide subtask generation.
|
|
* @param {boolean} [args.force] - Force expansion even if subtasks exist.
|
|
* @param {string} [args.projectRoot] - Project root directory.
|
|
* @param {string} [args.tag] - Tag for the task
|
|
* @param {Object} log - Logger object
|
|
* @param {Object} context - Context object containing session
|
|
* @param {Object} [context.session] - MCP Session object
|
|
* @returns {Promise<Object>} - Task expansion result { success: boolean, data?: any, error?: { code: string, message: string } }
|
|
*/
|
|
export async function expandTaskDirect(args, log, context = {}) {
|
|
const { session } = context; // Extract session
|
|
// Destructure expected args, including projectRoot
|
|
const { tasksJsonPath, id, num, research, prompt, force, projectRoot, tag } =
|
|
args;
|
|
|
|
// Log session root data for debugging
|
|
log.info(
|
|
`Session data in expandTaskDirect: ${JSON.stringify({
|
|
hasSession: !!session,
|
|
sessionKeys: session ? Object.keys(session) : [],
|
|
roots: session?.roots,
|
|
rootsStr: JSON.stringify(session?.roots)
|
|
})}`
|
|
);
|
|
|
|
// Check if tasksJsonPath was provided
|
|
if (!tasksJsonPath) {
|
|
log.error('expandTaskDirect called without tasksJsonPath');
|
|
return {
|
|
success: false,
|
|
error: {
|
|
code: 'MISSING_ARGUMENT',
|
|
message: 'tasksJsonPath is required'
|
|
}
|
|
};
|
|
}
|
|
|
|
// Use provided path
|
|
const tasksPath = tasksJsonPath;
|
|
|
|
log.info(`[expandTaskDirect] Using tasksPath: ${tasksPath}`);
|
|
|
|
// Validate task ID
|
|
const taskId = id ? parseInt(id, 10) : null;
|
|
if (!taskId) {
|
|
log.error('Task ID is required');
|
|
return {
|
|
success: false,
|
|
error: {
|
|
code: 'INPUT_VALIDATION_ERROR',
|
|
message: 'Task ID is required'
|
|
}
|
|
};
|
|
}
|
|
|
|
// Process other parameters
|
|
const numSubtasks = num ? parseInt(num, 10) : undefined;
|
|
const useResearch = research === true;
|
|
const additionalContext = prompt || '';
|
|
const forceFlag = force === true;
|
|
|
|
try {
|
|
log.info(
|
|
`[expandTaskDirect] Expanding task ${taskId} into ${numSubtasks || 'default'} subtasks. Research: ${useResearch}, Force: ${forceFlag}`
|
|
);
|
|
|
|
// Read tasks data
|
|
log.info(`[expandTaskDirect] Attempting to read JSON from: ${tasksPath}`);
|
|
const data = readJSON(tasksPath, projectRoot);
|
|
log.info(
|
|
`[expandTaskDirect] Result of readJSON: ${data ? 'Data read successfully' : 'readJSON returned null or undefined'}`
|
|
);
|
|
|
|
if (!data || !data.tasks) {
|
|
log.error(
|
|
`[expandTaskDirect] readJSON failed or returned invalid data for path: ${tasksPath}`
|
|
);
|
|
return {
|
|
success: false,
|
|
error: {
|
|
code: 'INVALID_TASKS_FILE',
|
|
message: `No valid tasks found in ${tasksPath}. readJSON returned: ${JSON.stringify(data)}`
|
|
}
|
|
};
|
|
}
|
|
|
|
// Find the specific task
|
|
log.info(`[expandTaskDirect] Searching for task ID ${taskId} in data`);
|
|
const task = data.tasks.find((t) => t.id === taskId);
|
|
log.info(`[expandTaskDirect] Task found: ${task ? 'Yes' : 'No'}`);
|
|
|
|
if (!task) {
|
|
return {
|
|
success: false,
|
|
error: {
|
|
code: 'TASK_NOT_FOUND',
|
|
message: `Task with ID ${taskId} not found`
|
|
}
|
|
};
|
|
}
|
|
|
|
// Check if task is completed
|
|
if (task.status === 'done' || task.status === 'completed') {
|
|
return {
|
|
success: false,
|
|
error: {
|
|
code: 'TASK_COMPLETED',
|
|
message: `Task ${taskId} is already marked as ${task.status} and cannot be expanded`
|
|
}
|
|
};
|
|
}
|
|
|
|
// Check for existing subtasks and force flag
|
|
const hasExistingSubtasks = task.subtasks && task.subtasks.length > 0;
|
|
if (hasExistingSubtasks && !forceFlag) {
|
|
log.info(
|
|
`Task ${taskId} already has ${task.subtasks.length} subtasks. Use --force to overwrite.`
|
|
);
|
|
return {
|
|
success: true,
|
|
data: {
|
|
message: `Task ${taskId} already has subtasks. Expansion skipped.`,
|
|
task,
|
|
subtasksAdded: 0,
|
|
hasExistingSubtasks
|
|
}
|
|
};
|
|
}
|
|
|
|
// If force flag is set, clear existing subtasks
|
|
if (hasExistingSubtasks && forceFlag) {
|
|
log.info(
|
|
`Force flag set. Clearing existing subtasks for task ${taskId}.`
|
|
);
|
|
task.subtasks = [];
|
|
}
|
|
|
|
// Keep a copy of the task before modification
|
|
const originalTask = JSON.parse(JSON.stringify(task));
|
|
|
|
// Tracking subtasks count before expansion
|
|
const subtasksCountBefore = task.subtasks ? task.subtasks.length : 0;
|
|
|
|
// Directly modify the data instead of calling the CLI function
|
|
if (!task.subtasks) {
|
|
task.subtasks = [];
|
|
}
|
|
|
|
// Save tasks.json with potentially empty subtasks array and proper context
|
|
writeJSON(tasksPath, data, projectRoot, tag);
|
|
|
|
// Create logger wrapper using the utility
|
|
const mcpLog = createLogWrapper(log);
|
|
|
|
let wasSilent; // Declare wasSilent outside the try block
|
|
// Process the request
|
|
try {
|
|
// Enable silent mode to prevent console logs from interfering with JSON response
|
|
wasSilent = isSilentMode(); // Assign inside the try block
|
|
if (!wasSilent) enableSilentMode();
|
|
|
|
// Call the core expandTask function with the wrapped logger and projectRoot
|
|
const coreResult = await expandTask(
|
|
tasksPath,
|
|
taskId,
|
|
numSubtasks,
|
|
useResearch,
|
|
additionalContext,
|
|
{
|
|
mcpLog,
|
|
session,
|
|
projectRoot,
|
|
commandName: 'expand-task',
|
|
outputType: 'mcp',
|
|
tag
|
|
},
|
|
forceFlag
|
|
);
|
|
|
|
// Restore normal logging
|
|
if (!wasSilent && isSilentMode()) disableSilentMode();
|
|
|
|
// Read the updated data
|
|
const updatedData = readJSON(tasksPath, projectRoot);
|
|
const updatedTask = updatedData.tasks.find((t) => t.id === taskId);
|
|
|
|
// Calculate how many subtasks were added
|
|
const subtasksAdded = updatedTask.subtasks
|
|
? updatedTask.subtasks.length - subtasksCountBefore
|
|
: 0;
|
|
|
|
// Return the result, including telemetryData
|
|
log.info(
|
|
`Successfully expanded task ${taskId} with ${subtasksAdded} new subtasks`
|
|
);
|
|
return {
|
|
success: true,
|
|
data: {
|
|
task: coreResult.task,
|
|
subtasksAdded,
|
|
hasExistingSubtasks,
|
|
telemetryData: coreResult.telemetryData,
|
|
tagInfo: coreResult.tagInfo
|
|
}
|
|
};
|
|
} catch (error) {
|
|
// Make sure to restore normal logging even if there's an error
|
|
if (!wasSilent && isSilentMode()) disableSilentMode();
|
|
|
|
log.error(`Error expanding task: ${error.message}`);
|
|
return {
|
|
success: false,
|
|
error: {
|
|
code: 'CORE_FUNCTION_ERROR',
|
|
message: error.message || 'Failed to expand task'
|
|
}
|
|
};
|
|
}
|
|
} catch (error) {
|
|
log.error(`Error expanding task: ${error.message}`);
|
|
return {
|
|
success: false,
|
|
error: {
|
|
code: 'CORE_FUNCTION_ERROR',
|
|
message: error.message || 'Failed to expand task'
|
|
}
|
|
};
|
|
}
|
|
}
|