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
491 lines
12 KiB
JavaScript
491 lines
12 KiB
JavaScript
/**
|
|
* Tests for the add-task.js module
|
|
*/
|
|
import { jest } from '@jest/globals';
|
|
|
|
// Mock the dependencies before importing the module under test
|
|
jest.unstable_mockModule('../../../../../scripts/modules/utils.js', () => ({
|
|
readJSON: jest.fn(),
|
|
writeJSON: jest.fn(),
|
|
log: jest.fn(),
|
|
CONFIG: {
|
|
model: 'mock-claude-model',
|
|
maxTokens: 4000,
|
|
temperature: 0.7,
|
|
debug: false
|
|
},
|
|
sanitizePrompt: jest.fn((prompt) => prompt),
|
|
truncate: jest.fn((text) => text),
|
|
isSilentMode: jest.fn(() => false),
|
|
findTaskById: jest.fn((tasks, id) => {
|
|
if (!tasks) return null;
|
|
const allTasks = [];
|
|
const queue = [...tasks];
|
|
while (queue.length > 0) {
|
|
const task = queue.shift();
|
|
allTasks.push(task);
|
|
if (task.subtasks) {
|
|
queue.push(...task.subtasks);
|
|
}
|
|
}
|
|
return allTasks.find((task) => String(task.id) === String(id));
|
|
}),
|
|
getCurrentTag: jest.fn(() => 'master'),
|
|
ensureTagMetadata: jest.fn((tagObj) => tagObj),
|
|
flattenTasksWithSubtasks: jest.fn((tasks) => {
|
|
const allTasks = [];
|
|
const queue = [...(tasks || [])];
|
|
while (queue.length > 0) {
|
|
const task = queue.shift();
|
|
allTasks.push(task);
|
|
if (task.subtasks) {
|
|
for (const subtask of task.subtasks) {
|
|
queue.push({ ...subtask, id: `${task.id}.${subtask.id}` });
|
|
}
|
|
}
|
|
}
|
|
return allTasks;
|
|
}),
|
|
markMigrationForNotice: jest.fn(),
|
|
performCompleteTagMigration: jest.fn(),
|
|
setTasksForTag: jest.fn(),
|
|
getTasksForTag: jest.fn((data, tag) => data[tag]?.tasks || [])
|
|
}));
|
|
|
|
jest.unstable_mockModule('../../../../../scripts/modules/ui.js', () => ({
|
|
displayBanner: jest.fn(),
|
|
getStatusWithColor: jest.fn((status) => status),
|
|
startLoadingIndicator: jest.fn(),
|
|
stopLoadingIndicator: jest.fn(),
|
|
succeedLoadingIndicator: jest.fn(),
|
|
failLoadingIndicator: jest.fn(),
|
|
warnLoadingIndicator: jest.fn(),
|
|
infoLoadingIndicator: jest.fn(),
|
|
displayAiUsageSummary: jest.fn(),
|
|
displayContextAnalysis: jest.fn()
|
|
}));
|
|
|
|
jest.unstable_mockModule(
|
|
'../../../../../scripts/modules/ai-services-unified.js',
|
|
() => ({
|
|
generateObjectService: jest.fn().mockResolvedValue({
|
|
mainResult: {
|
|
object: {
|
|
title: 'Task from prompt: Create a new authentication system',
|
|
description:
|
|
'Task generated from: Create a new authentication system',
|
|
details:
|
|
'Implementation details for task generated from prompt: Create a new authentication system',
|
|
testStrategy: 'Write unit tests to verify functionality',
|
|
dependencies: []
|
|
}
|
|
},
|
|
telemetryData: {
|
|
timestamp: new Date().toISOString(),
|
|
userId: '1234567890',
|
|
commandName: 'add-task',
|
|
modelUsed: 'claude-3-5-sonnet',
|
|
providerName: 'anthropic',
|
|
inputTokens: 1000,
|
|
outputTokens: 500,
|
|
totalTokens: 1500,
|
|
totalCost: 0.012414,
|
|
currency: 'USD'
|
|
}
|
|
})
|
|
})
|
|
);
|
|
|
|
jest.unstable_mockModule(
|
|
'../../../../../scripts/modules/config-manager.js',
|
|
() => ({
|
|
getDefaultPriority: jest.fn(() => 'medium')
|
|
})
|
|
);
|
|
|
|
jest.unstable_mockModule(
|
|
'../../../../../scripts/modules/utils/contextGatherer.js',
|
|
() => ({
|
|
default: jest.fn().mockImplementation(() => ({
|
|
gather: jest.fn().mockResolvedValue({
|
|
contextSummary: 'Mock context summary',
|
|
allRelatedTaskIds: [],
|
|
graphVisualization: 'Mock graph'
|
|
})
|
|
}))
|
|
})
|
|
);
|
|
|
|
jest.unstable_mockModule(
|
|
'../../../../../scripts/modules/task-manager/generate-task-files.js',
|
|
() => ({
|
|
default: jest.fn().mockResolvedValue()
|
|
})
|
|
);
|
|
|
|
// Mock external UI libraries
|
|
jest.unstable_mockModule('chalk', () => ({
|
|
default: {
|
|
white: { bold: jest.fn((text) => text) },
|
|
cyan: Object.assign(
|
|
jest.fn((text) => text),
|
|
{
|
|
bold: jest.fn((text) => text)
|
|
}
|
|
),
|
|
green: jest.fn((text) => text),
|
|
yellow: jest.fn((text) => text),
|
|
bold: jest.fn((text) => text)
|
|
}
|
|
}));
|
|
|
|
jest.unstable_mockModule('boxen', () => ({
|
|
default: jest.fn((text) => text)
|
|
}));
|
|
|
|
jest.unstable_mockModule('cli-table3', () => ({
|
|
default: jest.fn().mockImplementation(() => ({
|
|
push: jest.fn(),
|
|
toString: jest.fn(() => 'mocked table')
|
|
}))
|
|
}));
|
|
|
|
// Import the mocked modules
|
|
const { readJSON, writeJSON, log } = await import(
|
|
'../../../../../scripts/modules/utils.js'
|
|
);
|
|
|
|
const { generateObjectService } = await import(
|
|
'../../../../../scripts/modules/ai-services-unified.js'
|
|
);
|
|
|
|
const generateTaskFiles = (
|
|
await import(
|
|
'../../../../../scripts/modules/task-manager/generate-task-files.js'
|
|
)
|
|
).default;
|
|
|
|
// Import the module under test
|
|
const { default: addTask } = await import(
|
|
'../../../../../scripts/modules/task-manager/add-task.js'
|
|
);
|
|
|
|
describe('addTask', () => {
|
|
const sampleTasks = {
|
|
master: {
|
|
tasks: [
|
|
{
|
|
id: 1,
|
|
title: 'Task 1',
|
|
description: 'First task',
|
|
status: 'pending',
|
|
dependencies: []
|
|
},
|
|
{
|
|
id: 2,
|
|
title: 'Task 2',
|
|
description: 'Second task',
|
|
status: 'pending',
|
|
dependencies: []
|
|
},
|
|
{
|
|
id: 3,
|
|
title: 'Task 3',
|
|
description: 'Third task',
|
|
status: 'pending',
|
|
dependencies: [1]
|
|
}
|
|
]
|
|
}
|
|
};
|
|
|
|
// Create a helper function for consistent mcpLog mock
|
|
const createMcpLogMock = () => ({
|
|
info: jest.fn(),
|
|
warn: jest.fn(),
|
|
error: jest.fn(),
|
|
debug: jest.fn(),
|
|
success: jest.fn()
|
|
});
|
|
|
|
beforeEach(() => {
|
|
jest.clearAllMocks();
|
|
readJSON.mockReturnValue(JSON.parse(JSON.stringify(sampleTasks)));
|
|
|
|
// Mock console.log to avoid output during tests
|
|
jest.spyOn(console, 'log').mockImplementation(() => {});
|
|
});
|
|
|
|
afterEach(() => {
|
|
console.log.mockRestore();
|
|
});
|
|
|
|
test('should add a new task using AI', async () => {
|
|
// Arrange
|
|
const prompt = 'Create a new authentication system';
|
|
const context = {
|
|
mcpLog: createMcpLogMock(),
|
|
projectRoot: '/mock/project/root'
|
|
};
|
|
|
|
// Act
|
|
const result = await addTask(
|
|
'tasks/tasks.json',
|
|
prompt,
|
|
[],
|
|
'medium',
|
|
context,
|
|
'json'
|
|
);
|
|
|
|
// Assert
|
|
expect(readJSON).toHaveBeenCalledWith(
|
|
'tasks/tasks.json',
|
|
'/mock/project/root'
|
|
);
|
|
expect(generateObjectService).toHaveBeenCalledWith(expect.any(Object));
|
|
expect(writeJSON).toHaveBeenCalledWith(
|
|
'tasks/tasks.json',
|
|
expect.objectContaining({
|
|
master: expect.objectContaining({
|
|
tasks: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
id: 4, // Next ID after existing tasks
|
|
title: expect.stringContaining(
|
|
'Create a new authentication system'
|
|
),
|
|
status: 'pending'
|
|
})
|
|
])
|
|
})
|
|
}),
|
|
'/mock/project/root', // projectRoot parameter
|
|
'master' // tag parameter
|
|
);
|
|
expect(result).toEqual(
|
|
expect.objectContaining({
|
|
newTaskId: 4,
|
|
telemetryData: expect.any(Object)
|
|
})
|
|
);
|
|
});
|
|
|
|
test('should validate dependencies when adding a task', async () => {
|
|
// Arrange
|
|
const prompt = 'Create a new authentication system';
|
|
const validDependencies = [1, 2]; // These exist in sampleTasks
|
|
const context = {
|
|
mcpLog: createMcpLogMock(),
|
|
projectRoot: '/mock/project/root'
|
|
};
|
|
|
|
// Act
|
|
const result = await addTask(
|
|
'tasks/tasks.json',
|
|
prompt,
|
|
validDependencies,
|
|
'medium',
|
|
context,
|
|
'json'
|
|
);
|
|
|
|
// Assert
|
|
expect(writeJSON).toHaveBeenCalledWith(
|
|
'tasks/tasks.json',
|
|
expect.objectContaining({
|
|
master: expect.objectContaining({
|
|
tasks: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
id: 4,
|
|
dependencies: validDependencies
|
|
})
|
|
])
|
|
})
|
|
}),
|
|
'/mock/project/root', // projectRoot parameter
|
|
'master' // tag parameter
|
|
);
|
|
});
|
|
|
|
test('should filter out invalid dependencies', async () => {
|
|
// Arrange
|
|
const prompt = 'Create a new authentication system';
|
|
const invalidDependencies = [999]; // Non-existent task ID
|
|
const context = {
|
|
mcpLog: createMcpLogMock(),
|
|
projectRoot: '/mock/project/root'
|
|
};
|
|
|
|
// Act
|
|
const result = await addTask(
|
|
'tasks/tasks.json',
|
|
prompt,
|
|
invalidDependencies,
|
|
'medium',
|
|
context,
|
|
'json'
|
|
);
|
|
|
|
// Assert
|
|
expect(writeJSON).toHaveBeenCalledWith(
|
|
'tasks/tasks.json',
|
|
expect.objectContaining({
|
|
master: expect.objectContaining({
|
|
tasks: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
id: 4,
|
|
dependencies: [] // Invalid dependencies should be filtered out
|
|
})
|
|
])
|
|
})
|
|
}),
|
|
'/mock/project/root', // projectRoot parameter
|
|
'master' // tag parameter
|
|
);
|
|
expect(context.mcpLog.warn).toHaveBeenCalledWith(
|
|
expect.stringContaining(
|
|
'The following dependencies do not exist or are invalid: 999'
|
|
)
|
|
);
|
|
});
|
|
|
|
test('should use specified priority', async () => {
|
|
// Arrange
|
|
const prompt = 'Create a new authentication system';
|
|
const priority = 'high';
|
|
const context = {
|
|
mcpLog: createMcpLogMock(),
|
|
projectRoot: '/mock/project/root'
|
|
};
|
|
|
|
// Act
|
|
await addTask('tasks/tasks.json', prompt, [], priority, context, 'json');
|
|
|
|
// Assert
|
|
expect(writeJSON).toHaveBeenCalledWith(
|
|
'tasks/tasks.json',
|
|
expect.objectContaining({
|
|
master: expect.objectContaining({
|
|
tasks: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
priority: priority
|
|
})
|
|
])
|
|
})
|
|
}),
|
|
'/mock/project/root', // projectRoot parameter
|
|
'master' // tag parameter
|
|
);
|
|
});
|
|
|
|
test('should handle empty tasks file', async () => {
|
|
// Arrange
|
|
readJSON.mockReturnValue({ master: { tasks: [] } });
|
|
const prompt = 'Create a new authentication system';
|
|
const context = {
|
|
mcpLog: createMcpLogMock(),
|
|
projectRoot: '/mock/project/root'
|
|
};
|
|
|
|
// Act
|
|
const result = await addTask(
|
|
'tasks/tasks.json',
|
|
prompt,
|
|
[],
|
|
'medium',
|
|
context,
|
|
'json'
|
|
);
|
|
|
|
// Assert
|
|
expect(result.newTaskId).toBe(1); // First task should have ID 1
|
|
expect(writeJSON).toHaveBeenCalledWith(
|
|
'tasks/tasks.json',
|
|
expect.objectContaining({
|
|
master: expect.objectContaining({
|
|
tasks: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
id: 1
|
|
})
|
|
])
|
|
})
|
|
}),
|
|
'/mock/project/root', // projectRoot parameter
|
|
'master' // tag parameter
|
|
);
|
|
});
|
|
|
|
test('should handle missing tasks file', async () => {
|
|
// Arrange
|
|
readJSON.mockReturnValue(null);
|
|
const prompt = 'Create a new authentication system';
|
|
const context = {
|
|
mcpLog: createMcpLogMock(),
|
|
projectRoot: '/mock/project/root'
|
|
};
|
|
|
|
// Act
|
|
const result = await addTask(
|
|
'tasks/tasks.json',
|
|
prompt,
|
|
[],
|
|
'medium',
|
|
context,
|
|
'json'
|
|
);
|
|
|
|
// Assert
|
|
expect(result.newTaskId).toBe(1); // First task should have ID 1
|
|
expect(writeJSON).toHaveBeenCalledTimes(1); // Should create file and add task in one go.
|
|
});
|
|
|
|
test('should handle AI service errors', async () => {
|
|
// Arrange
|
|
generateObjectService.mockRejectedValueOnce(new Error('AI service failed'));
|
|
const prompt = 'Create a new authentication system';
|
|
const context = {
|
|
mcpLog: createMcpLogMock(),
|
|
projectRoot: '/mock/project/root'
|
|
};
|
|
|
|
// Act & Assert
|
|
await expect(
|
|
addTask('tasks/tasks.json', prompt, [], 'medium', context, 'json')
|
|
).rejects.toThrow('AI service failed');
|
|
});
|
|
|
|
test('should handle file read errors', async () => {
|
|
// Arrange
|
|
readJSON.mockImplementation(() => {
|
|
throw new Error('File read failed');
|
|
});
|
|
const prompt = 'Create a new authentication system';
|
|
const context = {
|
|
mcpLog: createMcpLogMock(),
|
|
projectRoot: '/mock/project/root'
|
|
};
|
|
|
|
// Act & Assert
|
|
await expect(
|
|
addTask('tasks/tasks.json', prompt, [], 'medium', context, 'json')
|
|
).rejects.toThrow('File read failed');
|
|
});
|
|
|
|
test('should handle file write errors', async () => {
|
|
// Arrange
|
|
writeJSON.mockImplementation(() => {
|
|
throw new Error('File write failed');
|
|
});
|
|
const prompt = 'Create a new authentication system';
|
|
const context = {
|
|
mcpLog: createMcpLogMock(),
|
|
projectRoot: '/mock/project/root'
|
|
};
|
|
|
|
// Act & Assert
|
|
await expect(
|
|
addTask('tasks/tasks.json', prompt, [], 'medium', context, 'json')
|
|
).rejects.toThrow('File write failed');
|
|
});
|
|
});
|