MCP ENV fallback to read API keys in .env if not found in mcp.json
Problem: - Task Master model configuration wasn't properly checking for API keys in the project's .env file when running through MCP - The isApiKeySet function was only checking session.env and process.env but not inspecting the .env file directly -This caused incorrect API key status reporting in MCP tools even when keys were properly set in .env - All AI commands (core functions, direct functions, mcp tools) have been fixed to ensure they pass `projectRoot` from the mcp tool up to the direct function and through to the core function such that it can use that root to access the user's .env file in the correct location (instead of trying to find it in the server's process.env which is useless). Should have a big impact across the board for all users who were having API related issues
This commit is contained in:
@@ -7,8 +7,8 @@
|
||||
"temperature": 0.2
|
||||
},
|
||||
"research": {
|
||||
"provider": "xai",
|
||||
"modelId": "grok-3",
|
||||
"provider": "perplexity",
|
||||
"modelId": "sonar-pro",
|
||||
"maxTokens": 8700,
|
||||
"temperature": 0.1
|
||||
},
|
||||
|
||||
@@ -23,13 +23,21 @@ import { createLogWrapper } from '../../tools/utils.js';
|
||||
* @param {string} [args.priority='medium'] - Task priority (high, medium, low)
|
||||
* @param {string} [args.tasksJsonPath] - Path to the tasks.json file (resolved by tool)
|
||||
* @param {boolean} [args.research=false] - Whether to use research capabilities for task creation
|
||||
* @param {string} [args.projectRoot] - Project root path
|
||||
* @param {Object} log - Logger object
|
||||
* @param {Object} context - Additional context (session)
|
||||
* @returns {Promise<Object>} - Result object { success: boolean, data?: any, error?: { code: string, message: string } }
|
||||
*/
|
||||
export async function addTaskDirect(args, log, context = {}) {
|
||||
// Destructure expected args (including research)
|
||||
const { tasksJsonPath, prompt, dependencies, priority, research } = args;
|
||||
// Destructure expected args (including research and projectRoot)
|
||||
const {
|
||||
tasksJsonPath,
|
||||
prompt,
|
||||
dependencies,
|
||||
priority,
|
||||
research,
|
||||
projectRoot
|
||||
} = args;
|
||||
const { session } = context; // Destructure session from context
|
||||
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
@@ -108,11 +116,13 @@ export async function addTaskDirect(args, log, context = {}) {
|
||||
taskPriority,
|
||||
{
|
||||
session,
|
||||
mcpLog
|
||||
mcpLog,
|
||||
projectRoot
|
||||
},
|
||||
'json', // outputFormat
|
||||
manualTaskData, // Pass the manual task data
|
||||
false // research flag is false for manual creation
|
||||
false, // research flag is false for manual creation
|
||||
projectRoot // Pass projectRoot
|
||||
);
|
||||
} else {
|
||||
// AI-driven task creation
|
||||
@@ -128,7 +138,8 @@ export async function addTaskDirect(args, log, context = {}) {
|
||||
taskPriority,
|
||||
{
|
||||
session,
|
||||
mcpLog
|
||||
mcpLog,
|
||||
projectRoot
|
||||
},
|
||||
'json', // outputFormat
|
||||
null, // manualTaskData is null for AI creation
|
||||
|
||||
@@ -18,15 +18,17 @@ import { createLogWrapper } from '../../tools/utils.js'; // Import the new utili
|
||||
* @param {string} args.outputPath - Explicit absolute path to save the report.
|
||||
* @param {string|number} [args.threshold] - Minimum complexity score to recommend expansion (1-10)
|
||||
* @param {boolean} [args.research] - Use Perplexity AI for research-backed complexity analysis
|
||||
* @param {string} [args.projectRoot] - Project root path.
|
||||
* @param {Object} log - Logger object
|
||||
* @param {Object} [context={}] - Context object containing session data
|
||||
* @param {Object} [context.session] - MCP session object
|
||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||
*/
|
||||
export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
const { session } = context; // Extract session
|
||||
// Destructure expected args
|
||||
const { tasksJsonPath, outputPath, model, threshold, research } = args; // Model is ignored by core function now
|
||||
const { session } = context;
|
||||
const { tasksJsonPath, outputPath, threshold, research, projectRoot } = args;
|
||||
|
||||
const logWrapper = createLogWrapper(log);
|
||||
|
||||
// --- Initial Checks (remain the same) ---
|
||||
try {
|
||||
@@ -60,35 +62,34 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
log.info('Using research role for complexity analysis');
|
||||
}
|
||||
|
||||
// Prepare options for the core function
|
||||
const options = {
|
||||
file: tasksPath,
|
||||
output: resolvedOutputPath,
|
||||
// model: model, // No longer needed
|
||||
// Prepare options for the core function - REMOVED mcpLog and session here
|
||||
const coreOptions = {
|
||||
file: tasksJsonPath,
|
||||
output: outputPath,
|
||||
threshold: threshold,
|
||||
research: research === true // Ensure boolean
|
||||
research: research === true, // Ensure boolean
|
||||
projectRoot: projectRoot // Pass projectRoot here
|
||||
};
|
||||
// --- End Initial Checks ---
|
||||
|
||||
// --- Silent Mode and Logger Wrapper (remain the same) ---
|
||||
// --- Silent Mode and Logger Wrapper ---
|
||||
const wasSilent = isSilentMode();
|
||||
if (!wasSilent) {
|
||||
enableSilentMode();
|
||||
enableSilentMode(); // Still enable silent mode as a backup
|
||||
}
|
||||
|
||||
// Create logger wrapper using the utility
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
let report; // To store the result from the core function
|
||||
let report;
|
||||
|
||||
try {
|
||||
// --- Call Core Function (Updated Context Passing) ---
|
||||
// Call the core function, passing options and the context object { session, mcpLog }
|
||||
report = await analyzeTaskComplexity(options, {
|
||||
session, // Pass the session object
|
||||
mcpLog // Pass the logger wrapper
|
||||
});
|
||||
// --- End Core Function Call ---
|
||||
// --- Call Core Function (Pass context separately) ---
|
||||
// Pass coreOptions as the first argument
|
||||
// Pass context object { session, mcpLog } as the second argument
|
||||
report = await analyzeTaskComplexity(
|
||||
coreOptions, // Pass options object
|
||||
{ session, mcpLog: logWrapper } // Pass context object
|
||||
// Removed the explicit 'json' format argument, assuming context handling is sufficient
|
||||
// If issues persist, we might need to add an explicit format param to analyzeTaskComplexity
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`Error in analyzeTaskComplexity core function: ${error.message}`
|
||||
@@ -100,7 +101,7 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'ANALYZE_CORE_ERROR', // More specific error code
|
||||
code: 'ANALYZE_CORE_ERROR',
|
||||
message: `Error running core complexity analysis: ${error.message}`
|
||||
}
|
||||
};
|
||||
@@ -124,10 +125,10 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
// The core function now returns the report object directly
|
||||
if (!report || !report.complexityAnalysis) {
|
||||
// Added a check to ensure report is defined before accessing its properties
|
||||
if (!report || typeof report !== 'object') {
|
||||
log.error(
|
||||
'Core analyzeTaskComplexity function did not return a valid report object.'
|
||||
'Core analysis function returned an invalid or undefined response.'
|
||||
);
|
||||
return {
|
||||
success: false,
|
||||
@@ -139,7 +140,10 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
}
|
||||
|
||||
try {
|
||||
const analysisArray = report.complexityAnalysis; // Already an array
|
||||
// Ensure complexityAnalysis exists and is an array
|
||||
const analysisArray = Array.isArray(report.complexityAnalysis)
|
||||
? report.complexityAnalysis
|
||||
: [];
|
||||
|
||||
// Count tasks by complexity (remains the same)
|
||||
const highComplexityTasks = analysisArray.filter(
|
||||
@@ -155,16 +159,15 @@ export async function analyzeTaskComplexityDirect(args, log, context = {}) {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message: `Task complexity analysis complete. Report saved to ${resolvedOutputPath}`,
|
||||
reportPath: resolvedOutputPath,
|
||||
message: `Task complexity analysis complete. Report saved to ${outputPath}`, // Use outputPath from args
|
||||
reportPath: outputPath, // Use outputPath from args
|
||||
reportSummary: {
|
||||
taskCount: analysisArray.length,
|
||||
highComplexityTasks,
|
||||
mediumComplexityTasks,
|
||||
lowComplexityTasks
|
||||
}
|
||||
// Include the full report data if needed by the client
|
||||
// fullReport: report
|
||||
},
|
||||
fullReport: report // Now includes the full report
|
||||
}
|
||||
};
|
||||
} catch (parseError) {
|
||||
|
||||
@@ -17,14 +17,15 @@ import { createLogWrapper } from '../../tools/utils.js';
|
||||
* @param {boolean} [args.research] - Enable research-backed subtask generation
|
||||
* @param {string} [args.prompt] - Additional context to guide subtask generation
|
||||
* @param {boolean} [args.force] - Force regeneration of subtasks for tasks that already have them
|
||||
* @param {string} [args.projectRoot] - Project root path.
|
||||
* @param {Object} log - Logger object from FastMCP
|
||||
* @param {Object} context - Context object containing session
|
||||
* @returns {Promise<{success: boolean, data?: Object, error?: {code: string, message: string}}>}
|
||||
*/
|
||||
export async function expandAllTasksDirect(args, log, context = {}) {
|
||||
const { session } = context; // Extract session
|
||||
// Destructure expected args
|
||||
const { tasksJsonPath, num, research, prompt, force } = args;
|
||||
// Destructure expected args, including projectRoot
|
||||
const { tasksJsonPath, num, research, prompt, force, projectRoot } = args;
|
||||
|
||||
// Create logger wrapper using the utility
|
||||
const mcpLog = createLogWrapper(log);
|
||||
@@ -43,7 +44,7 @@ export async function expandAllTasksDirect(args, log, context = {}) {
|
||||
enableSilentMode(); // Enable silent mode for the core function call
|
||||
try {
|
||||
log.info(
|
||||
`Calling core expandAllTasks with args: ${JSON.stringify({ num, research, prompt, force })}`
|
||||
`Calling core expandAllTasks with args: ${JSON.stringify({ num, research, prompt, force, projectRoot })}`
|
||||
);
|
||||
|
||||
// Parse parameters (ensure correct types)
|
||||
@@ -52,14 +53,14 @@ export async function expandAllTasksDirect(args, log, context = {}) {
|
||||
const additionalContext = prompt || '';
|
||||
const forceFlag = force === true;
|
||||
|
||||
// Call the core function, passing options and the context object { session, mcpLog }
|
||||
// Call the core function, passing options and the context object { session, mcpLog, projectRoot }
|
||||
const result = await expandAllTasks(
|
||||
tasksJsonPath,
|
||||
numSubtasks,
|
||||
useResearch,
|
||||
additionalContext,
|
||||
forceFlag,
|
||||
{ session, mcpLog }
|
||||
{ session, mcpLog, projectRoot }
|
||||
);
|
||||
|
||||
// Core function now returns a summary object
|
||||
|
||||
@@ -25,6 +25,7 @@ import { createLogWrapper } from '../../tools/utils.js';
|
||||
* @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 {Object} log - Logger object
|
||||
* @param {Object} context - Context object containing session
|
||||
* @param {Object} [context.session] - MCP Session object
|
||||
@@ -32,8 +33,8 @@ import { createLogWrapper } from '../../tools/utils.js';
|
||||
*/
|
||||
export async function expandTaskDirect(args, log, context = {}) {
|
||||
const { session } = context; // Extract session
|
||||
// Destructure expected args
|
||||
const { tasksJsonPath, id, num, research, prompt, force } = args;
|
||||
// Destructure expected args, including projectRoot
|
||||
const { tasksJsonPath, id, num, research, prompt, force, projectRoot } = args;
|
||||
|
||||
// Log session root data for debugging
|
||||
log.info(
|
||||
@@ -184,20 +185,22 @@ export async function expandTaskDirect(args, log, context = {}) {
|
||||
// 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
|
||||
const wasSilent = isSilentMode();
|
||||
wasSilent = isSilentMode(); // Assign inside the try block
|
||||
if (!wasSilent) enableSilentMode();
|
||||
|
||||
// Call the core expandTask function with the wrapped logger
|
||||
const result = await expandTask(
|
||||
// Call the core expandTask function with the wrapped logger and projectRoot
|
||||
const updatedTaskResult = await expandTask(
|
||||
tasksPath,
|
||||
taskId,
|
||||
numSubtasks,
|
||||
useResearch,
|
||||
additionalContext,
|
||||
{ mcpLog, session }
|
||||
{ mcpLog, session, projectRoot },
|
||||
forceFlag
|
||||
);
|
||||
|
||||
// Restore normal logging
|
||||
|
||||
@@ -8,9 +8,11 @@ import fs from 'fs';
|
||||
import { parsePRD } from '../../../../scripts/modules/task-manager.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
disableSilentMode,
|
||||
isSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { createLogWrapper } from '../../tools/utils.js';
|
||||
import { getDefaultNumTasks } from '../../../../scripts/modules/config-manager.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for parsing PRD documents and generating tasks.
|
||||
@@ -21,177 +23,160 @@ import { createLogWrapper } from '../../tools/utils.js';
|
||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||
*/
|
||||
export async function parsePRDDirect(args, log, context = {}) {
|
||||
const { session } = context; // Only extract session
|
||||
const { session } = context;
|
||||
// Extract projectRoot from args
|
||||
const {
|
||||
input: inputArg,
|
||||
output: outputArg,
|
||||
numTasks: numTasksArg,
|
||||
force,
|
||||
append,
|
||||
projectRoot
|
||||
} = args;
|
||||
|
||||
try {
|
||||
log.info(`Parsing PRD document with args: ${JSON.stringify(args)}`);
|
||||
const logWrapper = createLogWrapper(log);
|
||||
|
||||
// Validate required parameters
|
||||
if (!args.projectRoot) {
|
||||
const errorMessage = 'Project root is required for parsePRDDirect';
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_PROJECT_ROOT', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
if (!args.input) {
|
||||
const errorMessage = 'Input file path is required for parsePRDDirect';
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_INPUT_PATH', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
if (!args.output) {
|
||||
const errorMessage = 'Output file path is required for parsePRDDirect';
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_OUTPUT_PATH', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
// Resolve input path (expecting absolute path or path relative to project root)
|
||||
const projectRoot = args.projectRoot;
|
||||
const inputPath = path.isAbsolute(args.input)
|
||||
? args.input
|
||||
: path.resolve(projectRoot, args.input);
|
||||
|
||||
// Verify input file exists
|
||||
if (!fs.existsSync(inputPath)) {
|
||||
const errorMessage = `Input file not found: ${inputPath}`;
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'INPUT_FILE_NOT_FOUND',
|
||||
message: errorMessage,
|
||||
details: `Checked path: ${inputPath}\nProject root: ${projectRoot}\nInput argument: ${args.input}`
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
// Resolve output path (expecting absolute path or path relative to project root)
|
||||
const outputPath = path.isAbsolute(args.output)
|
||||
? args.output
|
||||
: path.resolve(projectRoot, args.output);
|
||||
|
||||
// Ensure output directory exists
|
||||
const outputDir = path.dirname(outputPath);
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
log.info(`Creating output directory: ${outputDir}`);
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Parse number of tasks - handle both string and number values
|
||||
let numTasks = 10; // Default
|
||||
if (args.numTasks) {
|
||||
numTasks =
|
||||
typeof args.numTasks === 'string'
|
||||
? parseInt(args.numTasks, 10)
|
||||
: args.numTasks;
|
||||
if (isNaN(numTasks)) {
|
||||
numTasks = 10; // Fallback to default if parsing fails
|
||||
log.warn(`Invalid numTasks value: ${args.numTasks}. Using default: 10`);
|
||||
}
|
||||
}
|
||||
|
||||
// Extract the append flag from args
|
||||
const append = Boolean(args.append) === true;
|
||||
|
||||
// Log key parameters including append flag
|
||||
log.info(
|
||||
`Preparing to parse PRD from ${inputPath} and output to ${outputPath} with ${numTasks} tasks, append mode: ${append}`
|
||||
// --- Input Validation and Path Resolution ---
|
||||
if (!projectRoot || !path.isAbsolute(projectRoot)) {
|
||||
logWrapper.error(
|
||||
'parsePRDDirect requires an absolute projectRoot argument.'
|
||||
);
|
||||
|
||||
// --- Logger Wrapper ---
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
// Prepare options for the core function
|
||||
const options = {
|
||||
mcpLog,
|
||||
session
|
||||
};
|
||||
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
enableSilentMode();
|
||||
try {
|
||||
// Make sure the output directory exists
|
||||
const outputDir = path.dirname(outputPath);
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
log.info(`Creating output directory: ${outputDir}`);
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Execute core parsePRD function with AI client
|
||||
const tasksDataResult = await parsePRD(
|
||||
inputPath,
|
||||
outputPath,
|
||||
numTasks,
|
||||
{
|
||||
mcpLog: logWrapper,
|
||||
session,
|
||||
append
|
||||
},
|
||||
aiClient,
|
||||
modelConfig
|
||||
);
|
||||
|
||||
// Since parsePRD doesn't return a value but writes to a file, we'll read the result
|
||||
// to return it to the caller
|
||||
if (fs.existsSync(outputPath)) {
|
||||
const tasksData = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
||||
const actionVerb = append ? 'appended' : 'generated';
|
||||
const message = `Successfully ${actionVerb} ${tasksData.tasks?.length || 0} tasks from PRD`;
|
||||
|
||||
if (!tasksDataResult || !tasksDataResult.tasks || !tasksData) {
|
||||
throw new Error(
|
||||
'Core parsePRD function did not return valid task data.'
|
||||
);
|
||||
}
|
||||
|
||||
log.info(message);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message,
|
||||
taskCount: tasksDataResult.tasks?.length || 0,
|
||||
outputPath,
|
||||
appended: append
|
||||
},
|
||||
fromCache: false // This operation always modifies state and should never be cached
|
||||
};
|
||||
} else {
|
||||
const errorMessage = `Tasks file was not created at ${outputPath}`;
|
||||
log.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'OUTPUT_FILE_NOT_CREATED', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
} finally {
|
||||
// Always restore normal logging
|
||||
disableSilentMode();
|
||||
}
|
||||
} catch (error) {
|
||||
// Make sure to restore normal logging even if there's an error
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Error parsing PRD: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: error.code || 'PARSE_PRD_ERROR', // Use error code if available
|
||||
message: error.message || 'Unknown error parsing PRD'
|
||||
},
|
||||
fromCache: false
|
||||
code: 'MISSING_ARGUMENT',
|
||||
message: 'projectRoot is required and must be absolute.'
|
||||
}
|
||||
};
|
||||
}
|
||||
if (!inputArg) {
|
||||
logWrapper.error('parsePRDDirect called without input path');
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_ARGUMENT', message: 'Input path is required' }
|
||||
};
|
||||
}
|
||||
|
||||
// Resolve input and output paths relative to projectRoot if they aren't absolute
|
||||
const inputPath = path.resolve(projectRoot, inputArg);
|
||||
const outputPath = outputArg
|
||||
? path.resolve(projectRoot, outputArg)
|
||||
: path.resolve(projectRoot, 'tasks', 'tasks.json'); // Default output path
|
||||
|
||||
// Check if input file exists
|
||||
if (!fs.existsSync(inputPath)) {
|
||||
const errorMsg = `Input PRD file not found at resolved path: ${inputPath}`;
|
||||
logWrapper.error(errorMsg);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'FILE_NOT_FOUND', message: errorMsg }
|
||||
};
|
||||
}
|
||||
|
||||
const outputDir = path.dirname(outputPath);
|
||||
try {
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
logWrapper.info(`Creating output directory: ${outputDir}`);
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
} catch (dirError) {
|
||||
logWrapper.error(
|
||||
`Failed to create output directory ${outputDir}: ${dirError.message}`
|
||||
);
|
||||
// Return an error response immediately if dir creation fails
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'DIRECTORY_CREATION_ERROR',
|
||||
message: `Failed to create output directory: ${dirError.message}`
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let numTasks = getDefaultNumTasks(projectRoot);
|
||||
if (numTasksArg) {
|
||||
numTasks =
|
||||
typeof numTasksArg === 'string' ? parseInt(numTasksArg, 10) : numTasksArg;
|
||||
if (isNaN(numTasks) || numTasks <= 0) {
|
||||
// Ensure positive number
|
||||
numTasks = getDefaultNumTasks(projectRoot); // Fallback to default if parsing fails or invalid
|
||||
logWrapper.warn(
|
||||
`Invalid numTasks value: ${numTasksArg}. Using default: 10`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const useForce = force === true;
|
||||
const useAppend = append === true;
|
||||
if (useAppend) {
|
||||
logWrapper.info('Append mode enabled.');
|
||||
if (useForce) {
|
||||
logWrapper.warn(
|
||||
'Both --force and --append flags were provided. --force takes precedence; append mode will be ignored.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
logWrapper.info(
|
||||
`Parsing PRD via direct function. Input: ${inputPath}, Output: ${outputPath}, NumTasks: ${numTasks}, Force: ${useForce}, Append: ${useAppend}, ProjectRoot: ${projectRoot}`
|
||||
);
|
||||
|
||||
const wasSilent = isSilentMode();
|
||||
if (!wasSilent) {
|
||||
enableSilentMode();
|
||||
}
|
||||
|
||||
try {
|
||||
// Call the core parsePRD function
|
||||
const result = await parsePRD(
|
||||
inputPath,
|
||||
outputPath,
|
||||
numTasks,
|
||||
{ session, mcpLog: logWrapper, projectRoot, useForce, useAppend },
|
||||
'json'
|
||||
);
|
||||
|
||||
// parsePRD returns { success: true, tasks: processedTasks } on success
|
||||
if (result && result.success && Array.isArray(result.tasks)) {
|
||||
logWrapper.success(
|
||||
`Successfully parsed PRD. Generated ${result.tasks.length} tasks.`
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message: `Successfully parsed PRD and generated ${result.tasks.length} tasks.`,
|
||||
outputPath: outputPath,
|
||||
taskCount: result.tasks.length
|
||||
// Optionally include tasks if needed by client: tasks: result.tasks
|
||||
}
|
||||
};
|
||||
} else {
|
||||
// Handle case where core function didn't return expected success structure
|
||||
logWrapper.error(
|
||||
'Core parsePRD function did not return a successful structure.'
|
||||
);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'CORE_FUNCTION_ERROR',
|
||||
message:
|
||||
result?.message ||
|
||||
'Core function failed to parse PRD or returned unexpected result.'
|
||||
}
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
logWrapper.error(`Error executing core parsePRD: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'PARSE_PRD_CORE_ERROR',
|
||||
message: error.message || 'Unknown error parsing PRD'
|
||||
}
|
||||
};
|
||||
} finally {
|
||||
if (!wasSilent && isSilentMode()) {
|
||||
disableSilentMode();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,29 +6,40 @@
|
||||
import { updateSubtaskById } from '../../../../scripts/modules/task-manager.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
disableSilentMode,
|
||||
isSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { createLogWrapper } from '../../tools/utils.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for updateSubtaskById with error handling.
|
||||
*
|
||||
* @param {Object} args - Command arguments containing id, prompt, useResearch and tasksJsonPath.
|
||||
* @param {Object} args - Command arguments containing id, prompt, useResearch, tasksJsonPath, and projectRoot.
|
||||
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file.
|
||||
* @param {string} args.id - Subtask ID in format "parent.sub".
|
||||
* @param {string} args.prompt - Information to append to the subtask.
|
||||
* @param {boolean} [args.research] - Whether to use research role.
|
||||
* @param {string} [args.projectRoot] - Project root path.
|
||||
* @param {Object} log - Logger object.
|
||||
* @param {Object} context - Context object containing session data.
|
||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||
*/
|
||||
export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
||||
const { session } = context; // Only extract session, not reportProgress
|
||||
const { tasksJsonPath, id, prompt, research } = args;
|
||||
const { session } = context;
|
||||
// Destructure expected args, including projectRoot
|
||||
const { tasksJsonPath, id, prompt, research, projectRoot } = args;
|
||||
|
||||
const logWrapper = createLogWrapper(log);
|
||||
|
||||
try {
|
||||
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
||||
logWrapper.info(
|
||||
`Updating subtask by ID via direct function. ID: ${id}, ProjectRoot: ${projectRoot}`
|
||||
);
|
||||
|
||||
// Check if tasksJsonPath was provided
|
||||
if (!tasksJsonPath) {
|
||||
const errorMessage = 'tasksJsonPath is required but was not provided.';
|
||||
log.error(errorMessage);
|
||||
logWrapper.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_ARGUMENT', message: errorMessage },
|
||||
@@ -36,22 +47,22 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
// Check required parameters (id and prompt)
|
||||
if (!id) {
|
||||
// Basic validation for ID format (e.g., '5.2')
|
||||
if (!id || typeof id !== 'string' || !id.includes('.')) {
|
||||
const errorMessage =
|
||||
'No subtask ID specified. Please provide a subtask ID to update.';
|
||||
log.error(errorMessage);
|
||||
'Invalid subtask ID format. Must be in format "parentId.subtaskId" (e.g., "5.2").';
|
||||
logWrapper.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_SUBTASK_ID', message: errorMessage },
|
||||
error: { code: 'INVALID_SUBTASK_ID', message: errorMessage },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
if (!prompt) {
|
||||
const errorMessage =
|
||||
'No prompt specified. Please provide a prompt with information to add to the subtask.';
|
||||
log.error(errorMessage);
|
||||
'No prompt specified. Please provide the information to append.';
|
||||
logWrapper.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_PROMPT', message: errorMessage },
|
||||
@@ -84,51 +95,41 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
||||
|
||||
// Use the provided path
|
||||
const tasksPath = tasksJsonPath;
|
||||
|
||||
// Get research flag
|
||||
const useResearch = research === true;
|
||||
|
||||
log.info(
|
||||
`Updating subtask with ID ${subtaskIdStr} with prompt "${prompt}" and research: ${useResearch}`
|
||||
);
|
||||
|
||||
try {
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
const wasSilent = isSilentMode();
|
||||
if (!wasSilent) {
|
||||
enableSilentMode();
|
||||
}
|
||||
|
||||
// Create the logger wrapper using the utility function
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
try {
|
||||
// Execute core updateSubtaskById function
|
||||
// Pass both session and logWrapper as mcpLog to ensure outputFormat is 'json'
|
||||
const updatedSubtask = await updateSubtaskById(
|
||||
tasksPath,
|
||||
subtaskIdStr,
|
||||
prompt,
|
||||
useResearch,
|
||||
{
|
||||
session,
|
||||
mcpLog
|
||||
}
|
||||
{ mcpLog: logWrapper, session, projectRoot },
|
||||
'json'
|
||||
);
|
||||
|
||||
// Restore normal logging
|
||||
disableSilentMode();
|
||||
|
||||
// Handle the case where the subtask couldn't be updated (e.g., already marked as done)
|
||||
if (!updatedSubtask) {
|
||||
if (updatedSubtask === null) {
|
||||
const message = `Subtask ${id} or its parent task not found.`;
|
||||
logWrapper.error(message); // Log as error since it couldn't be found
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'SUBTASK_UPDATE_FAILED',
|
||||
message:
|
||||
'Failed to update subtask. It may be marked as completed, or another error occurred.'
|
||||
},
|
||||
error: { code: 'SUBTASK_NOT_FOUND', message: message },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
// Return the updated subtask information
|
||||
// Subtask updated successfully
|
||||
const successMessage = `Successfully updated subtask with ID ${subtaskIdStr}`;
|
||||
logWrapper.success(successMessage);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
@@ -139,23 +140,33 @@ export async function updateSubtaskByIdDirect(args, log, context = {}) {
|
||||
tasksPath,
|
||||
useResearch
|
||||
},
|
||||
fromCache: false // This operation always modifies state and should never be cached
|
||||
fromCache: false
|
||||
};
|
||||
} catch (error) {
|
||||
// Make sure to restore normal logging even if there's an error
|
||||
disableSilentMode();
|
||||
throw error; // Rethrow to be caught by outer catch block
|
||||
logWrapper.error(`Error updating subtask by ID: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'UPDATE_SUBTASK_CORE_ERROR',
|
||||
message: error.message || 'Unknown error updating subtask'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
} finally {
|
||||
if (!wasSilent && isSilentMode()) {
|
||||
disableSilentMode();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Ensure silent mode is disabled
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Error updating subtask by ID: ${error.message}`);
|
||||
logWrapper.error(
|
||||
`Setup error in updateSubtaskByIdDirect: ${error.message}`
|
||||
);
|
||||
if (isSilentMode()) disableSilentMode();
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'UPDATE_SUBTASK_ERROR',
|
||||
message: error.message || 'Unknown error updating subtask'
|
||||
code: 'DIRECT_FUNCTION_SETUP_ERROR',
|
||||
message: error.message || 'Unknown setup error'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
|
||||
@@ -6,30 +6,40 @@
|
||||
import { updateTaskById } from '../../../../scripts/modules/task-manager.js';
|
||||
import {
|
||||
enableSilentMode,
|
||||
disableSilentMode
|
||||
disableSilentMode,
|
||||
isSilentMode
|
||||
} from '../../../../scripts/modules/utils.js';
|
||||
import { createLogWrapper } from '../../tools/utils.js';
|
||||
|
||||
/**
|
||||
* Direct function wrapper for updateTaskById with error handling.
|
||||
*
|
||||
* @param {Object} args - Command arguments containing id, prompt, useResearch and tasksJsonPath.
|
||||
* @param {Object} args - Command arguments containing id, prompt, useResearch, tasksJsonPath, and projectRoot.
|
||||
* @param {string} args.tasksJsonPath - Explicit path to the tasks.json file.
|
||||
* @param {string} args.id - Task ID (or subtask ID like "1.2").
|
||||
* @param {string} args.prompt - New information/context prompt.
|
||||
* @param {boolean} [args.research] - Whether to use research role.
|
||||
* @param {string} [args.projectRoot] - Project root path.
|
||||
* @param {Object} log - Logger object.
|
||||
* @param {Object} context - Context object containing session data.
|
||||
* @returns {Promise<Object>} - Result object with success status and data/error information.
|
||||
*/
|
||||
export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||
const { session } = context; // Only extract session, not reportProgress
|
||||
// Destructure expected args, including the resolved tasksJsonPath
|
||||
const { tasksJsonPath, id, prompt, research } = args;
|
||||
const { session } = context;
|
||||
// Destructure expected args, including projectRoot
|
||||
const { tasksJsonPath, id, prompt, research, projectRoot } = args;
|
||||
|
||||
const logWrapper = createLogWrapper(log);
|
||||
|
||||
try {
|
||||
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
||||
logWrapper.info(
|
||||
`Updating task by ID via direct function. ID: ${id}, ProjectRoot: ${projectRoot}`
|
||||
);
|
||||
|
||||
// Check if tasksJsonPath was provided
|
||||
if (!tasksJsonPath) {
|
||||
const errorMessage = 'tasksJsonPath is required but was not provided.';
|
||||
log.error(errorMessage);
|
||||
logWrapper.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_ARGUMENT', message: errorMessage },
|
||||
@@ -41,7 +51,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||
if (!id) {
|
||||
const errorMessage =
|
||||
'No task ID specified. Please provide a task ID to update.';
|
||||
log.error(errorMessage);
|
||||
logWrapper.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_TASK_ID', message: errorMessage },
|
||||
@@ -52,7 +62,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||
if (!prompt) {
|
||||
const errorMessage =
|
||||
'No prompt specified. Please provide a prompt with new information for the task update.';
|
||||
log.error(errorMessage);
|
||||
logWrapper.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'MISSING_PROMPT', message: errorMessage },
|
||||
@@ -71,7 +81,7 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||
taskId = parseInt(id, 10);
|
||||
if (isNaN(taskId)) {
|
||||
const errorMessage = `Invalid task ID: ${id}. Task ID must be a positive integer or subtask ID (e.g., "5.2").`;
|
||||
log.error(errorMessage);
|
||||
logWrapper.error(errorMessage);
|
||||
return {
|
||||
success: false,
|
||||
error: { code: 'INVALID_TASK_ID', message: errorMessage },
|
||||
@@ -89,66 +99,80 @@ export async function updateTaskByIdDirect(args, log, context = {}) {
|
||||
// Get research flag
|
||||
const useResearch = research === true;
|
||||
|
||||
log.info(
|
||||
logWrapper.info(
|
||||
`Updating task with ID ${taskId} with prompt "${prompt}" and research: ${useResearch}`
|
||||
);
|
||||
|
||||
try {
|
||||
// Enable silent mode to prevent console logs from interfering with JSON response
|
||||
const wasSilent = isSilentMode();
|
||||
if (!wasSilent) {
|
||||
enableSilentMode();
|
||||
}
|
||||
|
||||
// Create the logger wrapper using the utility function
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
try {
|
||||
// Execute core updateTaskById function with proper parameters
|
||||
await updateTaskById(
|
||||
const updatedTask = await updateTaskById(
|
||||
tasksPath,
|
||||
taskId,
|
||||
prompt,
|
||||
useResearch,
|
||||
{
|
||||
mcpLog, // Pass the wrapped logger
|
||||
session
|
||||
mcpLog: logWrapper,
|
||||
session,
|
||||
projectRoot
|
||||
},
|
||||
'json'
|
||||
);
|
||||
|
||||
// Since updateTaskById doesn't return a value but modifies the tasks file,
|
||||
// we'll return a success message
|
||||
// Check if the core function indicated the task wasn't updated (e.g., status was 'done')
|
||||
if (updatedTask === null) {
|
||||
// Core function logs the reason, just return success with info
|
||||
const message = `Task ${taskId} was not updated (likely already completed).`;
|
||||
logWrapper.info(message);
|
||||
return {
|
||||
success: true,
|
||||
data: { message: message, taskId: taskId, updated: false },
|
||||
fromCache: false
|
||||
};
|
||||
}
|
||||
|
||||
// Task was updated successfully
|
||||
const successMessage = `Successfully updated task with ID ${taskId} based on the prompt`;
|
||||
logWrapper.success(successMessage);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
message: `Successfully updated task with ID ${taskId} based on the prompt`,
|
||||
taskId,
|
||||
tasksPath: tasksPath, // Return the used path
|
||||
useResearch
|
||||
message: successMessage,
|
||||
taskId: taskId,
|
||||
tasksPath: tasksPath,
|
||||
useResearch: useResearch,
|
||||
updated: true,
|
||||
updatedTask: updatedTask
|
||||
},
|
||||
fromCache: false // This operation always modifies state and should never be cached
|
||||
fromCache: false
|
||||
};
|
||||
} catch (error) {
|
||||
log.error(`Error updating task by ID: ${error.message}`);
|
||||
logWrapper.error(`Error updating task by ID: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'UPDATE_TASK_ERROR',
|
||||
code: 'UPDATE_TASK_CORE_ERROR',
|
||||
message: error.message || 'Unknown error updating task'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
} finally {
|
||||
// Make sure to restore normal logging even if there's an error
|
||||
disableSilentMode();
|
||||
if (!wasSilent && isSilentMode()) {
|
||||
disableSilentMode();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Ensure silent mode is disabled
|
||||
disableSilentMode();
|
||||
|
||||
log.error(`Error updating task by ID: ${error.message}`);
|
||||
logWrapper.error(`Setup error in updateTaskByIdDirect: ${error.message}`);
|
||||
if (isSilentMode()) disableSilentMode();
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: 'UPDATE_TASK_ERROR',
|
||||
message: error.message || 'Unknown error updating task'
|
||||
code: 'DIRECT_FUNCTION_SETUP_ERROR',
|
||||
message: error.message || 'Unknown setup error'
|
||||
},
|
||||
fromCache: false
|
||||
};
|
||||
|
||||
@@ -20,7 +20,7 @@ import { createLogWrapper } from '../../tools/utils.js';
|
||||
*/
|
||||
export async function updateTasksDirect(args, log, context = {}) {
|
||||
const { session } = context; // Extract session
|
||||
const { tasksJsonPath, from, prompt, research } = args;
|
||||
const { tasksJsonPath, from, prompt, research, projectRoot } = args;
|
||||
|
||||
// Create the standard logger wrapper
|
||||
const logWrapper = {
|
||||
@@ -85,21 +85,23 @@ export async function updateTasksDirect(args, log, context = {}) {
|
||||
const useResearch = research === true;
|
||||
// --- End Input Validation ---
|
||||
|
||||
log.info(`Updating tasks from ID ${fromId}. Research: ${useResearch}`);
|
||||
log.info(
|
||||
`Updating tasks from ID ${fromId}. Research: ${useResearch}. Project Root: ${projectRoot}`
|
||||
);
|
||||
|
||||
enableSilentMode(); // Enable silent mode
|
||||
try {
|
||||
// Create logger wrapper using the utility
|
||||
const mcpLog = createLogWrapper(log);
|
||||
|
||||
// Execute core updateTasks function, passing session context
|
||||
// Execute core updateTasks function, passing session context AND projectRoot
|
||||
await updateTasks(
|
||||
tasksJsonPath,
|
||||
fromId,
|
||||
prompt,
|
||||
useResearch,
|
||||
// Pass context with logger wrapper and session
|
||||
{ mcpLog, session },
|
||||
// Pass context with logger wrapper, session, AND projectRoot
|
||||
{ mcpLog, session, projectRoot },
|
||||
'json' // Explicitly request JSON format for MCP
|
||||
);
|
||||
|
||||
|
||||
@@ -105,7 +105,8 @@ export function registerAddTaskTool(server) {
|
||||
testStrategy: args.testStrategy,
|
||||
dependencies: args.dependencies,
|
||||
priority: args.priority,
|
||||
research: args.research
|
||||
research: args.research,
|
||||
projectRoot: rootFolder
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
|
||||
@@ -4,120 +4,142 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import { handleApiResult, createErrorResponse } from './utils.js';
|
||||
import { analyzeTaskComplexityDirect } from '../core/direct-functions/analyze-task-complexity.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
import fs from 'fs'; // Import fs for directory check/creation
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
getProjectRootFromSession // Assuming this is in './utils.js' relative to this file
|
||||
} from './utils.js';
|
||||
import { analyzeTaskComplexityDirect } from '../core/task-master-core.js'; // Assuming core functions are exported via task-master-core.js
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
|
||||
/**
|
||||
* Register the analyze tool with the MCP server
|
||||
* Register the analyze_project_complexity tool
|
||||
* @param {Object} server - FastMCP server instance
|
||||
*/
|
||||
export function registerAnalyzeTool(server) {
|
||||
export function registerAnalyzeProjectComplexityTool(server) {
|
||||
server.addTool({
|
||||
name: 'analyze_project_complexity',
|
||||
description:
|
||||
'Analyze task complexity and generate expansion recommendations',
|
||||
'Analyze task complexity and generate expansion recommendations.',
|
||||
parameters: z.object({
|
||||
threshold: z.coerce // Use coerce for number conversion from string if needed
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(10)
|
||||
.optional()
|
||||
.default(5) // Default threshold
|
||||
.describe('Complexity score threshold (1-10) to recommend expansion.'),
|
||||
research: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe('Use Perplexity AI for research-backed analysis.'),
|
||||
output: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Output file path relative to project root (default: scripts/task-complexity-report.json)'
|
||||
),
|
||||
threshold: z.coerce
|
||||
.number()
|
||||
.min(1)
|
||||
.max(10)
|
||||
.optional()
|
||||
.describe(
|
||||
'Minimum complexity score to recommend expansion (1-10) (default: 5)'
|
||||
'Output file path relative to project root (default: scripts/task-complexity-report.json).'
|
||||
),
|
||||
file: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Absolute path to the tasks file in the /tasks folder inside the project root (default: tasks/tasks.json)'
|
||||
'Path to the tasks file relative to project root (default: tasks/tasks.json).'
|
||||
),
|
||||
research: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe('Use research role for complexity analysis'),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: async (args, { log, session }) => {
|
||||
const toolName = 'analyze_project_complexity'; // Define tool name for logging
|
||||
try {
|
||||
log.info(
|
||||
`Executing analyze_project_complexity tool with args: ${JSON.stringify(args)}`
|
||||
`Executing ${toolName} tool with args: ${JSON.stringify(args)}`
|
||||
);
|
||||
|
||||
// 1. Get Project Root (Mandatory for this tool)
|
||||
const rootFolder = args.projectRoot;
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse('projectRoot is required.');
|
||||
}
|
||||
if (!path.isAbsolute(rootFolder)) {
|
||||
return createErrorResponse('projectRoot must be an absolute path.');
|
||||
if (!rootFolder || !path.isAbsolute(rootFolder)) {
|
||||
log.error(
|
||||
`${toolName}: projectRoot is required and must be absolute.`
|
||||
);
|
||||
return createErrorResponse(
|
||||
'projectRoot is required and must be absolute.'
|
||||
);
|
||||
}
|
||||
log.info(`${toolName}: Project root: ${rootFolder}`);
|
||||
|
||||
// 2. Resolve Paths relative to projectRoot
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
// Note: findTasksJsonPath expects 'file' relative to root, or absolute
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file }, // Pass root and optional relative file path
|
||||
log
|
||||
);
|
||||
log.info(`${toolName}: Resolved tasks path: ${tasksJsonPath}`);
|
||||
} catch (error) {
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
log.error(`${toolName}: Error finding tasks.json: ${error.message}`);
|
||||
return createErrorResponse(
|
||||
`Failed to find tasks.json within project root '${rootFolder}': ${error.message}`
|
||||
);
|
||||
}
|
||||
|
||||
const outputPath = args.output
|
||||
? path.resolve(rootFolder, args.output)
|
||||
: path.resolve(rootFolder, 'scripts', 'task-complexity-report.json');
|
||||
? path.resolve(rootFolder, args.output) // Resolve relative output path
|
||||
: path.resolve(rootFolder, 'scripts', 'task-complexity-report.json'); // Default location resolved relative to root
|
||||
|
||||
log.info(`${toolName}: Report output path: ${outputPath}`);
|
||||
|
||||
// Ensure output directory exists
|
||||
const outputDir = path.dirname(outputPath);
|
||||
try {
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
log.info(`Created output directory: ${outputDir}`);
|
||||
log.info(`${toolName}: Created output directory: ${outputDir}`);
|
||||
}
|
||||
} catch (dirError) {
|
||||
log.error(
|
||||
`Failed to create output directory ${outputDir}: ${dirError.message}`
|
||||
`${toolName}: Failed to create output directory ${outputDir}: ${dirError.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Failed to create output directory: ${dirError.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Call Direct Function - Pass projectRoot in first arg object
|
||||
const result = await analyzeTaskComplexityDirect(
|
||||
{
|
||||
// Pass resolved absolute paths and other args
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
outputPath: outputPath,
|
||||
outputPath: outputPath, // Pass resolved absolute path
|
||||
threshold: args.threshold,
|
||||
research: args.research
|
||||
research: args.research,
|
||||
projectRoot: rootFolder // <<< Pass projectRoot HERE
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
{ session } // Pass context object with session
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
log.info(`Tool analyze_project_complexity finished successfully.`);
|
||||
} else {
|
||||
log.error(
|
||||
`Tool analyze_project_complexity failed: ${result.error?.message || 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
|
||||
return handleApiResult(result, log, 'Error analyzing task complexity');
|
||||
// 4. Handle Result
|
||||
log.info(
|
||||
`${toolName}: Direct function result: success=${result.success}`
|
||||
);
|
||||
return handleApiResult(
|
||||
result,
|
||||
log,
|
||||
'Error analyzing task complexity' // Consistent error prefix
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(`Critical error in analyze tool execute: ${error.message}`);
|
||||
return createErrorResponse(`Internal tool error: ${error.message}`);
|
||||
log.error(
|
||||
`Critical error in ${toolName} tool execute: ${error.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Internal tool error (${toolName}): ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -94,7 +94,8 @@ export function registerExpandAllTool(server) {
|
||||
num: args.num,
|
||||
research: args.research,
|
||||
prompt: args.prompt,
|
||||
force: args.force
|
||||
force: args.force,
|
||||
projectRoot: rootFolder
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
|
||||
@@ -4,13 +4,10 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { handleApiResult, createErrorResponse } from './utils.js';
|
||||
import { expandTaskDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
import path from 'path';
|
||||
|
||||
/**
|
||||
* Register the expand-task tool with the MCP server
|
||||
@@ -51,19 +48,16 @@ export function registerExpandTaskTool(server) {
|
||||
try {
|
||||
log.info(`Starting expand-task with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
const rootFolder = args.projectRoot;
|
||||
if (!rootFolder || !path.isAbsolute(rootFolder)) {
|
||||
log.error(
|
||||
`expand-task: projectRoot is required and must be absolute.`
|
||||
);
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
'projectRoot is required and must be absolute.'
|
||||
);
|
||||
}
|
||||
|
||||
log.info(`Project root resolved to: ${rootFolder}`);
|
||||
|
||||
// Resolve the path to tasks.json using the utility
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
@@ -71,35 +65,39 @@ export function registerExpandTaskTool(server) {
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
log
|
||||
);
|
||||
log.info(`expand-task: Resolved tasks path: ${tasksJsonPath}`);
|
||||
} catch (error) {
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
log.error(`expand-task: Error finding tasks.json: ${error.message}`);
|
||||
return createErrorResponse(
|
||||
`Failed to find tasks.json: ${error.message}`
|
||||
`Failed to find tasks.json within project root '${rootFolder}': ${error.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// Call direct function with only session in the context, not reportProgress
|
||||
// Use the pattern recommended in the MCP guidelines
|
||||
const result = await expandTaskDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
id: args.id,
|
||||
num: args.num,
|
||||
research: args.research,
|
||||
prompt: args.prompt,
|
||||
force: args.force // Need to add force to parameters
|
||||
force: args.force,
|
||||
projectRoot: rootFolder
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
); // Only pass session, NOT reportProgress
|
||||
);
|
||||
|
||||
// Return the result
|
||||
log.info(
|
||||
`expand-task: Direct function result: success=${result.success}`
|
||||
);
|
||||
return handleApiResult(result, log, 'Error expanding task');
|
||||
} catch (error) {
|
||||
log.error(`Error in expand task tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
log.error(
|
||||
`Critical error in ${toolName} tool execute: ${error.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Internal tool error (${toolName}): ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ import { registerExpandTaskTool } from './expand-task.js';
|
||||
import { registerAddTaskTool } from './add-task.js';
|
||||
import { registerAddSubtaskTool } from './add-subtask.js';
|
||||
import { registerRemoveSubtaskTool } from './remove-subtask.js';
|
||||
import { registerAnalyzeTool } from './analyze.js';
|
||||
import { registerAnalyzeProjectComplexityTool } from './analyze.js';
|
||||
import { registerClearSubtasksTool } from './clear-subtasks.js';
|
||||
import { registerExpandAllTool } from './expand-all.js';
|
||||
import { registerRemoveDependencyTool } from './remove-dependency.js';
|
||||
@@ -63,7 +63,7 @@ export function registerTaskMasterTools(server) {
|
||||
registerClearSubtasksTool(server);
|
||||
|
||||
// Group 5: Task Analysis & Expansion
|
||||
registerAnalyzeTool(server);
|
||||
registerAnalyzeProjectComplexityTool(server);
|
||||
registerExpandTaskTool(server);
|
||||
registerExpandAllTool(server);
|
||||
|
||||
|
||||
@@ -4,16 +4,12 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
getProjectRootFromSession,
|
||||
handleApiResult,
|
||||
createErrorResponse
|
||||
} from './utils.js';
|
||||
import path from 'path';
|
||||
import { handleApiResult, createErrorResponse } from './utils.js';
|
||||
import { parsePRDDirect } from '../core/task-master-core.js';
|
||||
import { resolveProjectPaths } from '../core/utils/path-utils.js';
|
||||
|
||||
/**
|
||||
* Register the parsePRD tool with the MCP server
|
||||
* Register the parse_prd tool
|
||||
* @param {Object} server - FastMCP server instance
|
||||
*/
|
||||
export function registerParsePRDTool(server) {
|
||||
@@ -42,71 +38,64 @@ export function registerParsePRDTool(server) {
|
||||
force: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe('Allow overwriting an existing tasks.json file.'),
|
||||
.default(false)
|
||||
.describe('Overwrite existing output file without prompting.'),
|
||||
append: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
'Append new tasks to existing tasks.json instead of overwriting'
|
||||
),
|
||||
.default(false)
|
||||
.describe('Append generated tasks to existing file.'),
|
||||
projectRoot: z
|
||||
.string()
|
||||
.describe('The directory of the project. Must be absolute path.')
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: async (args, { log, session }) => {
|
||||
const toolName = 'parse_prd';
|
||||
try {
|
||||
log.info(`Parsing PRD with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
if (!rootFolder) {
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
);
|
||||
}
|
||||
|
||||
// Resolve input (PRD) and output (tasks.json) paths using the utility
|
||||
const { projectRoot, prdPath, tasksJsonPath } = resolveProjectPaths(
|
||||
rootFolder,
|
||||
args,
|
||||
log
|
||||
log.info(
|
||||
`Executing ${toolName} tool with args: ${JSON.stringify(args)}`
|
||||
);
|
||||
|
||||
// Check if PRD path was found (resolveProjectPaths returns null if not found and not provided)
|
||||
if (!prdPath) {
|
||||
// 1. Get Project Root
|
||||
const rootFolder = args.projectRoot;
|
||||
if (!rootFolder || !path.isAbsolute(rootFolder)) {
|
||||
log.error(
|
||||
`${toolName}: projectRoot is required and must be absolute.`
|
||||
);
|
||||
return createErrorResponse(
|
||||
'No PRD document found or provided. Please ensure a PRD file exists (e.g., PRD.md) or provide a valid input file path.'
|
||||
'projectRoot is required and must be absolute.'
|
||||
);
|
||||
}
|
||||
log.info(`${toolName}: Project root: ${rootFolder}`);
|
||||
|
||||
// Call the direct function with fully resolved paths
|
||||
// 2. Call Direct Function - Pass relevant args including projectRoot
|
||||
// Path resolution (input/output) is handled within the direct function now
|
||||
const result = await parsePRDDirect(
|
||||
{
|
||||
projectRoot: projectRoot,
|
||||
input: prdPath,
|
||||
output: tasksJsonPath,
|
||||
numTasks: args.numTasks,
|
||||
// Pass args directly needed by the direct function
|
||||
input: args.input, // Pass relative or absolute path
|
||||
output: args.output, // Pass relative or absolute path
|
||||
numTasks: args.numTasks, // Pass number (direct func handles default)
|
||||
force: args.force,
|
||||
append: args.append
|
||||
append: args.append,
|
||||
projectRoot: rootFolder
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
{ session } // Pass context object with session
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
log.info(`Successfully parsed PRD: ${result.data.message}`);
|
||||
} else {
|
||||
log.error(
|
||||
`Failed to parse PRD: ${result.error?.message || 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Handle Result
|
||||
log.info(
|
||||
`${toolName}: Direct function result: success=${result.success}`
|
||||
);
|
||||
return handleApiResult(result, log, 'Error parsing PRD');
|
||||
} catch (error) {
|
||||
log.error(`Error in parse-prd tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
log.error(
|
||||
`Critical error in ${toolName} tool execute: ${error.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Internal tool error (${toolName}): ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -4,13 +4,10 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
getProjectRootFromSession
|
||||
} from './utils.js';
|
||||
import { handleApiResult, createErrorResponse } from './utils.js';
|
||||
import { updateSubtaskByIdDirect } from '../core/task-master-core.js';
|
||||
import { findTasksJsonPath } from '../core/utils/path-utils.js';
|
||||
import path from 'path';
|
||||
|
||||
/**
|
||||
* Register the update-subtask tool with the MCP server
|
||||
@@ -38,21 +35,23 @@ export function registerUpdateSubtaskTool(server) {
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: async (args, { log, session }) => {
|
||||
const toolName = 'update_subtask';
|
||||
try {
|
||||
log.info(`Updating subtask with args: ${JSON.stringify(args)}`);
|
||||
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
// 1. Get Project Root
|
||||
const rootFolder = args.projectRoot;
|
||||
if (!rootFolder || !path.isAbsolute(rootFolder)) {
|
||||
log.error(
|
||||
`${toolName}: projectRoot is required and must be absolute.`
|
||||
);
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
'projectRoot is required and must be absolute.'
|
||||
);
|
||||
}
|
||||
log.info(`${toolName}: Project root: ${rootFolder}`);
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
// 2. Resolve Tasks Path
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
@@ -60,20 +59,20 @@ export function registerUpdateSubtaskTool(server) {
|
||||
log
|
||||
);
|
||||
} catch (error) {
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
log.error(`${toolName}: Error finding tasks.json: ${error.message}`);
|
||||
return createErrorResponse(
|
||||
`Failed to find tasks.json: ${error.message}`
|
||||
`Failed to find tasks.json within project root '${rootFolder}': ${error.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Call Direct Function - Include projectRoot
|
||||
const result = await updateSubtaskByIdDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
id: args.id,
|
||||
prompt: args.prompt,
|
||||
research: args.research
|
||||
research: args.research,
|
||||
projectRoot: rootFolder
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
@@ -89,8 +88,12 @@ export function registerUpdateSubtaskTool(server) {
|
||||
|
||||
return handleApiResult(result, log, 'Error updating subtask');
|
||||
} catch (error) {
|
||||
log.error(`Error in update_subtask tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
log.error(
|
||||
`Critical error in ${toolName} tool execute: ${error.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Internal tool error (${toolName}): ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod';
|
||||
import path from 'path'; // Import path
|
||||
import {
|
||||
handleApiResult,
|
||||
createErrorResponse,
|
||||
@@ -23,7 +24,7 @@ export function registerUpdateTaskTool(server) {
|
||||
'Updates a single task by ID with new information or context provided in the prompt.',
|
||||
parameters: z.object({
|
||||
id: z
|
||||
.string()
|
||||
.string() // ID can be number or string like "1.2"
|
||||
.describe(
|
||||
"ID of the task (e.g., '15') to update. Subtasks are supported using the update-subtask tool."
|
||||
),
|
||||
@@ -40,59 +41,65 @@ export function registerUpdateTaskTool(server) {
|
||||
.describe('The directory of the project. Must be an absolute path.')
|
||||
}),
|
||||
execute: async (args, { log, session }) => {
|
||||
const toolName = 'update_task';
|
||||
try {
|
||||
log.info(`Updating task with args: ${JSON.stringify(args)}`);
|
||||
log.info(
|
||||
`Executing ${toolName} tool with args: ${JSON.stringify(args)}`
|
||||
);
|
||||
|
||||
// Get project root from args or session
|
||||
const rootFolder =
|
||||
args.projectRoot || getProjectRootFromSession(session, log);
|
||||
|
||||
// Ensure project root was determined
|
||||
if (!rootFolder) {
|
||||
// 1. Get Project Root
|
||||
const rootFolder = args.projectRoot;
|
||||
if (!rootFolder || !path.isAbsolute(rootFolder)) {
|
||||
log.error(
|
||||
`${toolName}: projectRoot is required and must be absolute.`
|
||||
);
|
||||
return createErrorResponse(
|
||||
'Could not determine project root. Please provide it explicitly or ensure your session contains valid root information.'
|
||||
'projectRoot is required and must be absolute.'
|
||||
);
|
||||
}
|
||||
log.info(`${toolName}: Project root: ${rootFolder}`);
|
||||
|
||||
// Resolve the path to tasks.json
|
||||
// 2. Resolve Tasks Path
|
||||
let tasksJsonPath;
|
||||
try {
|
||||
tasksJsonPath = findTasksJsonPath(
|
||||
{ projectRoot: rootFolder, file: args.file },
|
||||
{ projectRoot: rootFolder, file: args.file }, // Pass root and optional relative file
|
||||
log
|
||||
);
|
||||
log.info(`${toolName}: Resolved tasks path: ${tasksJsonPath}`);
|
||||
} catch (error) {
|
||||
log.error(`Error finding tasks.json: ${error.message}`);
|
||||
log.error(`${toolName}: Error finding tasks.json: ${error.message}`);
|
||||
return createErrorResponse(
|
||||
`Failed to find tasks.json: ${error.message}`
|
||||
`Failed to find tasks.json within project root '${rootFolder}': ${error.message}`
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Call Direct Function - Include projectRoot
|
||||
const result = await updateTaskByIdDirect(
|
||||
{
|
||||
// Pass the explicitly resolved path
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
// Pass other relevant args
|
||||
tasksJsonPath: tasksJsonPath, // Pass resolved path
|
||||
id: args.id,
|
||||
prompt: args.prompt,
|
||||
research: args.research
|
||||
research: args.research,
|
||||
projectRoot: rootFolder // <<< Pass projectRoot HERE
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
{ session } // Pass context with session
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
log.info(`Successfully updated task with ID ${args.id}`);
|
||||
} else {
|
||||
log.error(
|
||||
`Failed to update task: ${result.error?.message || 'Unknown error'}`
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Handle Result
|
||||
log.info(
|
||||
`${toolName}: Direct function result: success=${result.success}`
|
||||
);
|
||||
// Pass the actual data from the result (contains updated task or message)
|
||||
return handleApiResult(result, log, 'Error updating task');
|
||||
} catch (error) {
|
||||
log.error(`Error in update_task tool: ${error.message}`);
|
||||
return createErrorResponse(error.message);
|
||||
log.error(
|
||||
`Critical error in ${toolName} tool execute: ${error.message}`
|
||||
);
|
||||
return createErrorResponse(
|
||||
`Internal tool error (${toolName}): ${error.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -70,7 +70,8 @@ export function registerUpdateTool(server) {
|
||||
tasksJsonPath: tasksJsonPath,
|
||||
from: args.from,
|
||||
prompt: args.prompt,
|
||||
research: args.research
|
||||
research: args.research,
|
||||
projectRoot: rootFolder
|
||||
},
|
||||
log,
|
||||
{ session }
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
getFallbackModelId,
|
||||
getParametersForRole
|
||||
} from './config-manager.js';
|
||||
import { log, resolveEnvVariable } from './utils.js';
|
||||
import { log, resolveEnvVariable, findProjectRoot } from './utils.js';
|
||||
|
||||
import * as anthropic from '../../src/ai-providers/anthropic.js';
|
||||
import * as perplexity from '../../src/ai-providers/perplexity.js';
|
||||
@@ -136,10 +136,11 @@ function _extractErrorMessage(error) {
|
||||
* Internal helper to resolve the API key for a given provider.
|
||||
* @param {string} providerName - The name of the provider (lowercase).
|
||||
* @param {object|null} session - Optional MCP session object.
|
||||
* @param {string|null} projectRoot - Optional project root path for .env fallback.
|
||||
* @returns {string|null} The API key or null if not found/needed.
|
||||
* @throws {Error} If a required API key is missing.
|
||||
*/
|
||||
function _resolveApiKey(providerName, session) {
|
||||
function _resolveApiKey(providerName, session, projectRoot = null) {
|
||||
const keyMap = {
|
||||
openai: 'OPENAI_API_KEY',
|
||||
anthropic: 'ANTHROPIC_API_KEY',
|
||||
@@ -163,10 +164,10 @@ function _resolveApiKey(providerName, session) {
|
||||
);
|
||||
}
|
||||
|
||||
const apiKey = resolveEnvVariable(envVarName, session);
|
||||
const apiKey = resolveEnvVariable(envVarName, session, projectRoot);
|
||||
if (!apiKey) {
|
||||
throw new Error(
|
||||
`Required API key ${envVarName} for provider '${providerName}' is not set in environment or session.`
|
||||
`Required API key ${envVarName} for provider '${providerName}' is not set in environment, session, or .env file.`
|
||||
);
|
||||
}
|
||||
return apiKey;
|
||||
@@ -241,27 +242,35 @@ async function _attemptProviderCallWithRetries(
|
||||
* Base logic for unified service functions.
|
||||
* @param {string} serviceType - Type of service ('generateText', 'streamText', 'generateObject').
|
||||
* @param {object} params - Original parameters passed to the service function.
|
||||
* @param {string} [params.projectRoot] - Optional project root path.
|
||||
* @returns {Promise<any>} Result from the underlying provider call.
|
||||
*/
|
||||
async function _unifiedServiceRunner(serviceType, params) {
|
||||
const {
|
||||
role: initialRole,
|
||||
session,
|
||||
projectRoot,
|
||||
systemPrompt,
|
||||
prompt,
|
||||
schema,
|
||||
objectName,
|
||||
...restApiParams
|
||||
} = params;
|
||||
log('info', `${serviceType}Service called`, { role: initialRole });
|
||||
log('info', `${serviceType}Service called`, {
|
||||
role: initialRole,
|
||||
projectRoot
|
||||
});
|
||||
|
||||
// Determine the effective project root (passed in or detected)
|
||||
const effectiveProjectRoot = projectRoot || findProjectRoot();
|
||||
|
||||
let sequence;
|
||||
if (initialRole === 'main') {
|
||||
sequence = ['main', 'fallback', 'research'];
|
||||
} else if (initialRole === 'fallback') {
|
||||
sequence = ['fallback', 'research'];
|
||||
} else if (initialRole === 'research') {
|
||||
sequence = ['research', 'fallback'];
|
||||
sequence = ['research', 'fallback', 'main'];
|
||||
} else if (initialRole === 'fallback') {
|
||||
sequence = ['fallback', 'main', 'research'];
|
||||
} else {
|
||||
log(
|
||||
'warn',
|
||||
@@ -281,16 +290,16 @@ async function _unifiedServiceRunner(serviceType, params) {
|
||||
log('info', `New AI service call with role: ${currentRole}`);
|
||||
|
||||
// 1. Get Config: Provider, Model, Parameters for the current role
|
||||
// Call individual getters based on the current role
|
||||
// Pass effectiveProjectRoot to config getters
|
||||
if (currentRole === 'main') {
|
||||
providerName = getMainProvider();
|
||||
modelId = getMainModelId();
|
||||
providerName = getMainProvider(effectiveProjectRoot);
|
||||
modelId = getMainModelId(effectiveProjectRoot);
|
||||
} else if (currentRole === 'research') {
|
||||
providerName = getResearchProvider();
|
||||
modelId = getResearchModelId();
|
||||
providerName = getResearchProvider(effectiveProjectRoot);
|
||||
modelId = getResearchModelId(effectiveProjectRoot);
|
||||
} else if (currentRole === 'fallback') {
|
||||
providerName = getFallbackProvider();
|
||||
modelId = getFallbackModelId();
|
||||
providerName = getFallbackProvider(effectiveProjectRoot);
|
||||
modelId = getFallbackModelId(effectiveProjectRoot);
|
||||
} else {
|
||||
log(
|
||||
'error',
|
||||
@@ -314,7 +323,8 @@ async function _unifiedServiceRunner(serviceType, params) {
|
||||
continue;
|
||||
}
|
||||
|
||||
roleParams = getParametersForRole(currentRole);
|
||||
// Pass effectiveProjectRoot to getParametersForRole
|
||||
roleParams = getParametersForRole(currentRole, effectiveProjectRoot);
|
||||
|
||||
// 2. Get Provider Function Set
|
||||
providerFnSet = PROVIDER_FUNCTIONS[providerName?.toLowerCase()];
|
||||
@@ -345,7 +355,12 @@ async function _unifiedServiceRunner(serviceType, params) {
|
||||
}
|
||||
|
||||
// 3. Resolve API Key (will throw if required and missing)
|
||||
apiKey = _resolveApiKey(providerName?.toLowerCase(), session);
|
||||
// Pass effectiveProjectRoot to _resolveApiKey
|
||||
apiKey = _resolveApiKey(
|
||||
providerName?.toLowerCase(),
|
||||
session,
|
||||
effectiveProjectRoot
|
||||
);
|
||||
|
||||
// 4. Construct Messages Array
|
||||
const messages = [];
|
||||
@@ -443,6 +458,7 @@ async function _unifiedServiceRunner(serviceType, params) {
|
||||
* @param {object} params - Parameters for the service call.
|
||||
* @param {string} params.role - The initial client role ('main', 'research', 'fallback').
|
||||
* @param {object} [params.session=null] - Optional MCP session object.
|
||||
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
|
||||
* @param {string} params.prompt - The prompt for the AI.
|
||||
* @param {string} [params.systemPrompt] - Optional system prompt.
|
||||
* // Other specific generateText params can be included here.
|
||||
@@ -459,6 +475,7 @@ async function generateTextService(params) {
|
||||
* @param {object} params - Parameters for the service call.
|
||||
* @param {string} params.role - The initial client role ('main', 'research', 'fallback').
|
||||
* @param {object} [params.session=null] - Optional MCP session object.
|
||||
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
|
||||
* @param {string} params.prompt - The prompt for the AI.
|
||||
* @param {string} [params.systemPrompt] - Optional system prompt.
|
||||
* // Other specific streamText params can be included here.
|
||||
@@ -475,6 +492,7 @@ async function streamTextService(params) {
|
||||
* @param {object} params - Parameters for the service call.
|
||||
* @param {string} params.role - The initial client role ('main', 'research', 'fallback').
|
||||
* @param {object} [params.session=null] - Optional MCP session object.
|
||||
* @param {string} [params.projectRoot=null] - Optional project root path for .env fallback.
|
||||
* @param {import('zod').ZodSchema} params.schema - The Zod schema for the expected object.
|
||||
* @param {string} params.prompt - The prompt for the AI.
|
||||
* @param {string} [params.systemPrompt] - Optional system prompt.
|
||||
|
||||
@@ -345,6 +345,12 @@ function getDefaultSubtasks(explicitRoot = null) {
|
||||
return isNaN(parsedVal) ? DEFAULTS.global.defaultSubtasks : parsedVal;
|
||||
}
|
||||
|
||||
function getDefaultNumTasks(explicitRoot = null) {
|
||||
const val = getGlobalConfig(explicitRoot).defaultNumTasks;
|
||||
const parsedVal = parseInt(val, 10);
|
||||
return isNaN(parsedVal) ? DEFAULTS.global.defaultNumTasks : parsedVal;
|
||||
}
|
||||
|
||||
function getDefaultPriority(explicitRoot = null) {
|
||||
// Directly return value from config
|
||||
return getGlobalConfig(explicitRoot).defaultPriority;
|
||||
@@ -424,12 +430,13 @@ function getParametersForRole(role, explicitRoot = null) {
|
||||
|
||||
/**
|
||||
* Checks if the API key for a given provider is set in the environment.
|
||||
* Checks process.env first, then session.env if session is provided.
|
||||
* Checks process.env first, then session.env if session is provided, then .env file if projectRoot provided.
|
||||
* @param {string} providerName - The name of the provider (e.g., 'openai', 'anthropic').
|
||||
* @param {object|null} [session=null] - The MCP session object (optional).
|
||||
* @param {string|null} [projectRoot=null] - The project root directory (optional, for .env file check).
|
||||
* @returns {boolean} True if the API key is set, false otherwise.
|
||||
*/
|
||||
function isApiKeySet(providerName, session = null) {
|
||||
function isApiKeySet(providerName, session = null, projectRoot = null) {
|
||||
// Define the expected environment variable name for each provider
|
||||
if (providerName?.toLowerCase() === 'ollama') {
|
||||
return true; // Indicate key status is effectively "OK"
|
||||
@@ -454,7 +461,7 @@ function isApiKeySet(providerName, session = null) {
|
||||
}
|
||||
|
||||
const envVarName = keyMap[providerKey];
|
||||
const apiKeyValue = resolveEnvVariable(envVarName, session);
|
||||
const apiKeyValue = resolveEnvVariable(envVarName, session, projectRoot);
|
||||
|
||||
// Check if the key exists, is not empty, and is not a placeholder
|
||||
return (
|
||||
@@ -701,6 +708,7 @@ export {
|
||||
// Global setting getters (No env var overrides)
|
||||
getLogLevel,
|
||||
getDebugFlag,
|
||||
getDefaultNumTasks,
|
||||
getDefaultSubtasks,
|
||||
getDefaultPriority,
|
||||
getProjectName,
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
startLoadingIndicator,
|
||||
stopLoadingIndicator
|
||||
} from '../ui.js';
|
||||
import { log, readJSON, writeJSON, truncate } from '../utils.js';
|
||||
import { readJSON, writeJSON, log as consoleLog, truncate } from '../utils.js';
|
||||
import { generateObjectService } from '../ai-services-unified.js';
|
||||
import { getDefaultPriority } from '../config-manager.js';
|
||||
import generateTaskFiles from './generate-task-files.js';
|
||||
@@ -42,19 +42,41 @@ const AiTaskDataSchema = z.object({
|
||||
* @param {Object} customEnv - Custom environment variables (optional) - Note: AI params override deprecated
|
||||
* @param {Object} manualTaskData - Manual task data (optional, for direct task creation without AI)
|
||||
* @param {boolean} useResearch - Whether to use the research model (passed to unified service)
|
||||
* @param {Object} context - Context object containing session and potentially projectRoot
|
||||
* @param {string} [context.projectRoot] - Project root path (for MCP/env fallback)
|
||||
* @returns {number} The new task ID
|
||||
*/
|
||||
async function addTask(
|
||||
tasksPath,
|
||||
prompt,
|
||||
dependencies = [],
|
||||
priority = getDefaultPriority(), // Keep getter for default priority
|
||||
{ reportProgress, mcpLog, session } = {},
|
||||
outputFormat = 'text',
|
||||
// customEnv = null, // Removed as AI param overrides are deprecated
|
||||
priority = null,
|
||||
context = {},
|
||||
outputFormat = 'text', // Default to text for CLI
|
||||
manualTaskData = null,
|
||||
useResearch = false // <-- Add useResearch parameter
|
||||
useResearch = false
|
||||
) {
|
||||
const { session, mcpLog, projectRoot } = context;
|
||||
const isMCP = !!mcpLog;
|
||||
|
||||
// Create a consistent logFn object regardless of context
|
||||
const logFn = isMCP
|
||||
? mcpLog // Use MCP logger if provided
|
||||
: {
|
||||
// Create a wrapper around consoleLog for CLI
|
||||
info: (...args) => consoleLog('info', ...args),
|
||||
warn: (...args) => consoleLog('warn', ...args),
|
||||
error: (...args) => consoleLog('error', ...args),
|
||||
debug: (...args) => consoleLog('debug', ...args),
|
||||
success: (...args) => consoleLog('success', ...args)
|
||||
};
|
||||
|
||||
const effectivePriority = priority || getDefaultPriority(projectRoot);
|
||||
|
||||
logFn.info(
|
||||
`Adding new task with prompt: "${prompt}", Priority: ${effectivePriority}, Dependencies: ${dependencies.join(', ') || 'None'}, Research: ${useResearch}, ProjectRoot: ${projectRoot}`
|
||||
);
|
||||
|
||||
let loadingIndicator = null;
|
||||
|
||||
// Create custom reporter that checks for MCP log
|
||||
@@ -62,7 +84,7 @@ async function addTask(
|
||||
if (mcpLog) {
|
||||
mcpLog[level](message);
|
||||
} else if (outputFormat === 'text') {
|
||||
log(level, message);
|
||||
consoleLog(level, message);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -220,11 +242,11 @@ async function addTask(
|
||||
const aiGeneratedTaskData = await generateObjectService({
|
||||
role: serviceRole, // <-- Use the determined role
|
||||
session: session, // Pass session for API key resolution
|
||||
projectRoot: projectRoot, // <<< Pass projectRoot here
|
||||
schema: AiTaskDataSchema, // Pass the Zod schema
|
||||
objectName: 'newTaskData', // Name for the object
|
||||
systemPrompt: systemPrompt,
|
||||
prompt: userPrompt,
|
||||
reportProgress // Pass progress reporter if available
|
||||
prompt: userPrompt
|
||||
});
|
||||
report('DEBUG: generateObjectService returned successfully.', 'debug');
|
||||
|
||||
@@ -254,7 +276,7 @@ async function addTask(
|
||||
testStrategy: taskData.testStrategy || '',
|
||||
status: 'pending',
|
||||
dependencies: numericDependencies, // Use validated numeric dependencies
|
||||
priority: priority,
|
||||
priority: effectivePriority,
|
||||
subtasks: [] // Initialize with empty subtasks array
|
||||
};
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ Do not include any explanatory text, markdown formatting, or code block markers
|
||||
* @param {string} options.output - Path to report output file
|
||||
* @param {string|number} [options.threshold] - Complexity threshold
|
||||
* @param {boolean} [options.research] - Use research role
|
||||
* @param {string} [options.projectRoot] - Project root path (for MCP/env fallback).
|
||||
* @param {Object} [options._filteredTasksData] - Pre-filtered task data (internal use)
|
||||
* @param {number} [options._originalTaskCount] - Original task count (internal use)
|
||||
* @param {Object} context - Context object, potentially containing session and mcpLog
|
||||
@@ -59,6 +60,7 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
const outputPath = options.output || 'scripts/task-complexity-report.json';
|
||||
const thresholdScore = parseFloat(options.threshold || '5');
|
||||
const useResearch = options.research || false;
|
||||
const projectRoot = options.projectRoot;
|
||||
|
||||
const outputFormat = mcpLog ? 'json' : 'text';
|
||||
|
||||
@@ -209,15 +211,13 @@ async function analyzeTaskComplexity(options, context = {}) {
|
||||
const role = useResearch ? 'research' : 'main';
|
||||
reportLog(`Using AI service with role: ${role}`, 'info');
|
||||
|
||||
// *** CHANGED: Use generateTextService ***
|
||||
fullResponse = await generateTextService({
|
||||
prompt,
|
||||
systemPrompt,
|
||||
role,
|
||||
session
|
||||
// No schema or objectName needed
|
||||
session,
|
||||
projectRoot
|
||||
});
|
||||
// *** End Service Call Change ***
|
||||
|
||||
reportLog(
|
||||
'Successfully received text response via AI service',
|
||||
|
||||
@@ -503,7 +503,8 @@ async function expandTask(
|
||||
prompt: promptContent,
|
||||
systemPrompt: systemPrompt, // Use the determined system prompt
|
||||
role,
|
||||
session
|
||||
session,
|
||||
projectRoot
|
||||
});
|
||||
logger.info(
|
||||
'Successfully received text response from AI service',
|
||||
|
||||
@@ -77,7 +77,7 @@ function fetchOpenRouterModels() {
|
||||
* @returns {Object} RESTful response with current model configuration
|
||||
*/
|
||||
async function getModelConfiguration(options = {}) {
|
||||
const { mcpLog, projectRoot } = options;
|
||||
const { mcpLog, projectRoot, session } = options;
|
||||
|
||||
const report = (level, ...args) => {
|
||||
if (mcpLog && typeof mcpLog[level] === 'function') {
|
||||
@@ -125,12 +125,16 @@ async function getModelConfiguration(options = {}) {
|
||||
const fallbackModelId = getFallbackModelId(projectRoot);
|
||||
|
||||
// Check API keys
|
||||
const mainCliKeyOk = isApiKeySet(mainProvider);
|
||||
const mainCliKeyOk = isApiKeySet(mainProvider, session, projectRoot);
|
||||
const mainMcpKeyOk = getMcpApiKeyStatus(mainProvider, projectRoot);
|
||||
const researchCliKeyOk = isApiKeySet(researchProvider);
|
||||
const researchCliKeyOk = isApiKeySet(
|
||||
researchProvider,
|
||||
session,
|
||||
projectRoot
|
||||
);
|
||||
const researchMcpKeyOk = getMcpApiKeyStatus(researchProvider, projectRoot);
|
||||
const fallbackCliKeyOk = fallbackProvider
|
||||
? isApiKeySet(fallbackProvider)
|
||||
? isApiKeySet(fallbackProvider, session, projectRoot)
|
||||
: true;
|
||||
const fallbackMcpKeyOk = fallbackProvider
|
||||
? getMcpApiKeyStatus(fallbackProvider, projectRoot)
|
||||
@@ -523,7 +527,7 @@ async function getApiKeyStatusReport(options = {}) {
|
||||
); // Ollama is not a provider, it's a service, doesn't need an api key usually
|
||||
const statusReport = providersToCheck.map((provider) => {
|
||||
// Use provided projectRoot for MCP status check
|
||||
const cliOk = isApiKeySet(provider, session); // Pass session for CLI check too
|
||||
const cliOk = isApiKeySet(provider, session, projectRoot); // Pass session and projectRoot for CLI check
|
||||
const mcpOk = getMcpApiKeyStatus(provider, projectRoot);
|
||||
return {
|
||||
provider,
|
||||
|
||||
@@ -9,28 +9,30 @@ import {
|
||||
writeJSON,
|
||||
enableSilentMode,
|
||||
disableSilentMode,
|
||||
isSilentMode
|
||||
isSilentMode,
|
||||
readJSON,
|
||||
findTaskById
|
||||
} from '../utils.js';
|
||||
|
||||
import { generateObjectService } from '../ai-services-unified.js';
|
||||
import { getDebugFlag } from '../config-manager.js';
|
||||
import generateTaskFiles from './generate-task-files.js';
|
||||
|
||||
// Define Zod schema for task validation
|
||||
const TaskSchema = z.object({
|
||||
id: z.number(),
|
||||
title: z.string(),
|
||||
description: z.string(),
|
||||
status: z.string().default('pending'),
|
||||
dependencies: z.array(z.number()).default([]),
|
||||
priority: z.string().default('medium'),
|
||||
details: z.string().optional(),
|
||||
testStrategy: z.string().optional()
|
||||
// Define the Zod schema for a SINGLE task object
|
||||
const prdSingleTaskSchema = z.object({
|
||||
id: z.number().int().positive(),
|
||||
title: z.string().min(1),
|
||||
description: z.string().min(1),
|
||||
details: z.string().optional().default(''),
|
||||
testStrategy: z.string().optional().default(''),
|
||||
priority: z.enum(['high', 'medium', 'low']).default('medium'),
|
||||
dependencies: z.array(z.number().int().positive()).optional().default([]),
|
||||
status: z.string().optional().default('pending')
|
||||
});
|
||||
|
||||
// Define Zod schema for the complete tasks data
|
||||
const TasksDataSchema = z.object({
|
||||
tasks: z.array(TaskSchema),
|
||||
// Define the Zod schema for the ENTIRE expected AI response object
|
||||
const prdResponseSchema = z.object({
|
||||
tasks: z.array(prdSingleTaskSchema),
|
||||
metadata: z.object({
|
||||
projectName: z.string(),
|
||||
totalTasks: z.number(),
|
||||
@@ -45,35 +47,114 @@ const TasksDataSchema = z.object({
|
||||
* @param {string} tasksPath - Path to the tasks.json file
|
||||
* @param {number} numTasks - Number of tasks to generate
|
||||
* @param {Object} options - Additional options
|
||||
* @param {Object} options.reportProgress - Function to report progress to MCP server (optional)
|
||||
* @param {Object} options.mcpLog - MCP logger object (optional)
|
||||
* @param {Object} options.session - Session object from MCP server (optional)
|
||||
* @param {boolean} [options.useForce=false] - Whether to overwrite existing tasks.json.
|
||||
* @param {boolean} [options.useAppend=false] - Append to existing tasks file.
|
||||
* @param {Object} [options.reportProgress] - Function to report progress (optional, likely unused).
|
||||
* @param {Object} [options.mcpLog] - MCP logger object (optional).
|
||||
* @param {Object} [options.session] - Session object from MCP server (optional).
|
||||
* @param {string} [options.projectRoot] - Project root path (for MCP/env fallback).
|
||||
* @param {string} [outputFormat='text'] - Output format ('text' or 'json').
|
||||
*/
|
||||
async function parsePRD(prdPath, tasksPath, numTasks, options = {}) {
|
||||
const { reportProgress, mcpLog, session } = options;
|
||||
const {
|
||||
reportProgress,
|
||||
mcpLog,
|
||||
session,
|
||||
projectRoot,
|
||||
useForce = false,
|
||||
useAppend = false
|
||||
} = options;
|
||||
const isMCP = !!mcpLog;
|
||||
const outputFormat = isMCP ? 'json' : 'text';
|
||||
|
||||
// Determine output format based on mcpLog presence (simplification)
|
||||
const outputFormat = mcpLog ? 'json' : 'text';
|
||||
const logFn = mcpLog
|
||||
? mcpLog
|
||||
: {
|
||||
// Wrapper for CLI
|
||||
info: (...args) => log('info', ...args),
|
||||
warn: (...args) => log('warn', ...args),
|
||||
error: (...args) => log('error', ...args),
|
||||
debug: (...args) => log('debug', ...args),
|
||||
success: (...args) => log('success', ...args)
|
||||
};
|
||||
|
||||
// Create custom reporter that checks for MCP log and silent mode
|
||||
// Create custom reporter using logFn
|
||||
const report = (message, level = 'info') => {
|
||||
if (mcpLog) {
|
||||
mcpLog[level](message);
|
||||
// Check logFn directly
|
||||
if (logFn && typeof logFn[level] === 'function') {
|
||||
logFn[level](message);
|
||||
} else if (!isSilentMode() && outputFormat === 'text') {
|
||||
// Only log to console if not in silent mode and outputFormat is 'text'
|
||||
// Fallback to original log only if necessary and in CLI text mode
|
||||
log(level, message);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
report(`Parsing PRD file: ${prdPath}`, 'info');
|
||||
report(
|
||||
`Parsing PRD file: ${prdPath}, Force: ${useForce}, Append: ${useAppend}`
|
||||
);
|
||||
|
||||
// Read the PRD content
|
||||
let existingTasks = [];
|
||||
let nextId = 1;
|
||||
|
||||
try {
|
||||
// Handle file existence and overwrite/append logic
|
||||
if (fs.existsSync(tasksPath)) {
|
||||
if (useAppend) {
|
||||
report(
|
||||
`Append mode enabled. Reading existing tasks from ${tasksPath}`,
|
||||
'info'
|
||||
);
|
||||
const existingData = readJSON(tasksPath); // Use readJSON utility
|
||||
if (existingData && Array.isArray(existingData.tasks)) {
|
||||
existingTasks = existingData.tasks;
|
||||
if (existingTasks.length > 0) {
|
||||
nextId = Math.max(...existingTasks.map((t) => t.id || 0)) + 1;
|
||||
report(
|
||||
`Found ${existingTasks.length} existing tasks. Next ID will be ${nextId}.`,
|
||||
'info'
|
||||
);
|
||||
}
|
||||
} else {
|
||||
report(
|
||||
`Could not read existing tasks from ${tasksPath} or format is invalid. Proceeding without appending.`,
|
||||
'warn'
|
||||
);
|
||||
existingTasks = []; // Reset if read fails
|
||||
}
|
||||
} else if (!useForce) {
|
||||
// Not appending and not forcing overwrite
|
||||
const overwriteError = new Error(
|
||||
`Output file ${tasksPath} already exists. Use --force to overwrite or --append.`
|
||||
);
|
||||
report(overwriteError.message, 'error');
|
||||
if (outputFormat === 'text') {
|
||||
console.error(chalk.red(overwriteError.message));
|
||||
process.exit(1);
|
||||
} else {
|
||||
throw overwriteError;
|
||||
}
|
||||
} else {
|
||||
// Force overwrite is true
|
||||
report(
|
||||
`Force flag enabled. Overwriting existing file: ${tasksPath}`,
|
||||
'info'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
report(`Reading PRD content from ${prdPath}`, 'info');
|
||||
const prdContent = fs.readFileSync(prdPath, 'utf8');
|
||||
if (!prdContent) {
|
||||
throw new Error(`Input file ${prdPath} is empty or could not be read.`);
|
||||
}
|
||||
|
||||
// Build system prompt for PRD parsing
|
||||
const systemPrompt = `You are an AI assistant helping to break down a Product Requirements Document (PRD) into a set of sequential development tasks.
|
||||
Your goal is to create ${numTasks} well-structured, actionable development tasks based on the PRD provided.
|
||||
const systemPrompt = `You are an AI assistant specialized in analyzing Product Requirements Documents (PRDs) and generating a structured, logically ordered, dependency-aware and sequenced list of development tasks in JSON format.
|
||||
Analyze the provided PRD content and generate approximately ${numTasks} top-level development tasks. If the complexity or the level of detail of the PRD is high, generate more tasks relative to the complexity of the PRD
|
||||
Each task should represent a logical unit of work needed to implement the requirements and focus on the most direct and effective way to implement the requirements without unnecessary complexity or overengineering. Include pseudo-code, implementation details, and test strategy for each task. Find the most up to date information to implement each task.
|
||||
Assign sequential IDs starting from ${nextId}. Infer title, description, details, and test strategy for each task based *only* on the PRD content.
|
||||
Set status to 'pending', dependencies to an empty array [], and priority to 'medium' initially for all tasks.
|
||||
Respond ONLY with a valid JSON object containing a single key "tasks", where the value is an array of task objects adhering to the provided Zod schema. Do not include any explanation or markdown formatting.
|
||||
|
||||
Each task should follow this JSON structure:
|
||||
{
|
||||
@@ -88,12 +169,12 @@ Each task should follow this JSON structure:
|
||||
}
|
||||
|
||||
Guidelines:
|
||||
1. Create exactly ${numTasks} tasks, numbered from 1 to ${numTasks}
|
||||
2. Each task should be atomic and focused on a single responsibility
|
||||
1. Unless complexity warrants otherwise, create exactly ${numTasks} tasks, numbered sequentially starting from ${nextId}
|
||||
2. Each task should be atomic and focused on a single responsibility following the most up to date best practices and standards
|
||||
3. Order tasks logically - consider dependencies and implementation sequence
|
||||
4. Early tasks should focus on setup, core functionality first, then advanced features
|
||||
5. Include clear validation/testing approach for each task
|
||||
6. Set appropriate dependency IDs (a task can only depend on tasks with lower IDs)
|
||||
6. Set appropriate dependency IDs (a task can only depend on tasks with lower IDs, potentially including existing tasks with IDs less than ${nextId} if applicable)
|
||||
7. Assign priority (high/medium/low) based on criticality and dependency order
|
||||
8. Include detailed implementation guidance in the "details" field
|
||||
9. If the PRD contains specific requirements for libraries, database schemas, frameworks, tech stacks, or any other implementation details, STRICTLY ADHERE to these requirements in your task breakdown and do not discard them under any circumstance
|
||||
@@ -101,41 +182,40 @@ Guidelines:
|
||||
11. Always aim to provide the most direct path to implementation, avoiding over-engineering or roundabout approaches`;
|
||||
|
||||
// Build user prompt with PRD content
|
||||
const userPrompt = `Here's the Product Requirements Document (PRD) to break down into ${numTasks} tasks:
|
||||
const userPrompt = `Here's the Product Requirements Document (PRD) to break down into approximately ${numTasks} tasks, starting IDs from ${nextId}:\n\n${prdContent}\n\n
|
||||
|
||||
${prdContent}
|
||||
|
||||
Return your response in this format:
|
||||
Return your response in this format:
|
||||
{
|
||||
"tasks": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Setup Project Repository",
|
||||
"description": "...",
|
||||
...
|
||||
},
|
||||
...
|
||||
],
|
||||
"metadata": {
|
||||
"projectName": "PRD Implementation",
|
||||
"totalTasks": ${numTasks},
|
||||
"sourceFile": "${prdPath}",
|
||||
"generatedAt": "YYYY-MM-DD"
|
||||
}
|
||||
"tasks": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Setup Project Repository",
|
||||
"description": "...",
|
||||
...
|
||||
},
|
||||
...
|
||||
],
|
||||
"metadata": {
|
||||
"projectName": "PRD Implementation",
|
||||
"totalTasks": ${numTasks},
|
||||
"sourceFile": "${prdPath}",
|
||||
"generatedAt": "YYYY-MM-DD"
|
||||
}
|
||||
}`;
|
||||
|
||||
// Call the unified AI service
|
||||
report('Calling AI service to generate tasks from PRD...', 'info');
|
||||
|
||||
// Call generateObjectService with proper parameters
|
||||
const tasksData = await generateObjectService({
|
||||
role: 'main', // Use 'main' role to get the model from config
|
||||
session: session, // Pass session for API key resolution
|
||||
schema: TasksDataSchema, // Pass the schema for validation
|
||||
objectName: 'tasks_data', // Name the generated object
|
||||
systemPrompt: systemPrompt, // System instructions
|
||||
prompt: userPrompt, // User prompt with PRD content
|
||||
reportProgress // Progress reporting function
|
||||
// Call generateObjectService with the CORRECT schema
|
||||
const generatedData = await generateObjectService({
|
||||
role: 'main',
|
||||
session: session,
|
||||
projectRoot: projectRoot,
|
||||
schema: prdResponseSchema,
|
||||
objectName: 'tasks_data',
|
||||
systemPrompt: systemPrompt,
|
||||
prompt: userPrompt,
|
||||
reportProgress
|
||||
});
|
||||
|
||||
// Create the directory if it doesn't exist
|
||||
@@ -143,11 +223,58 @@ Return your response in this format:
|
||||
if (!fs.existsSync(tasksDir)) {
|
||||
fs.mkdirSync(tasksDir, { recursive: true });
|
||||
}
|
||||
logFn.success('Successfully parsed PRD via AI service.'); // Assumes generateObjectService validated
|
||||
|
||||
// Validate and Process Tasks
|
||||
if (!generatedData || !Array.isArray(generatedData.tasks)) {
|
||||
// This error *shouldn't* happen if generateObjectService enforced prdResponseSchema
|
||||
// But keep it as a safeguard
|
||||
logFn.error(
|
||||
`Internal Error: generateObjectService returned unexpected data structure: ${JSON.stringify(generatedData)}`
|
||||
);
|
||||
throw new Error(
|
||||
'AI service returned unexpected data structure after validation.'
|
||||
);
|
||||
}
|
||||
|
||||
let currentId = nextId;
|
||||
const taskMap = new Map();
|
||||
const processedNewTasks = generatedData.tasks.map((task) => {
|
||||
const newId = currentId++;
|
||||
taskMap.set(task.id, newId);
|
||||
return {
|
||||
...task,
|
||||
id: newId,
|
||||
status: 'pending',
|
||||
priority: task.priority || 'medium',
|
||||
dependencies: Array.isArray(task.dependencies) ? task.dependencies : [],
|
||||
subtasks: []
|
||||
};
|
||||
});
|
||||
|
||||
// Remap dependencies for the NEWLY processed tasks
|
||||
processedNewTasks.forEach((task) => {
|
||||
task.dependencies = task.dependencies
|
||||
.map((depId) => taskMap.get(depId)) // Map old AI ID to new sequential ID
|
||||
.filter(
|
||||
(newDepId) =>
|
||||
newDepId != null && // Must exist
|
||||
newDepId < task.id && // Must be a lower ID (could be existing or newly generated)
|
||||
(findTaskById(existingTasks, newDepId) || // Check if it exists in old tasks OR
|
||||
processedNewTasks.some((t) => t.id === newDepId)) // check if it exists in new tasks
|
||||
);
|
||||
});
|
||||
|
||||
const allTasks = useAppend
|
||||
? [...existingTasks, ...processedNewTasks]
|
||||
: processedNewTasks;
|
||||
|
||||
const finalTaskData = { tasks: allTasks }; // Use the combined list
|
||||
|
||||
// Write the tasks to the file
|
||||
writeJSON(tasksPath, tasksData);
|
||||
writeJSON(tasksPath, finalTaskData);
|
||||
report(
|
||||
`Successfully generated ${tasksData.tasks.length} tasks from PRD`,
|
||||
`Successfully wrote ${allTasks.length} total tasks to ${tasksPath} (${processedNewTasks.length} new).`,
|
||||
'success'
|
||||
);
|
||||
report(`Tasks saved to: ${tasksPath}`, 'info');
|
||||
@@ -156,10 +283,10 @@ Return your response in this format:
|
||||
if (reportProgress && mcpLog) {
|
||||
// Enable silent mode when being called from MCP server
|
||||
enableSilentMode();
|
||||
await generateTaskFiles(tasksPath, tasksDir);
|
||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
||||
disableSilentMode();
|
||||
} else {
|
||||
await generateTaskFiles(tasksPath, tasksDir);
|
||||
await generateTaskFiles(tasksPath, path.dirname(tasksPath));
|
||||
}
|
||||
|
||||
// Only show success boxes for text output (CLI)
|
||||
@@ -167,7 +294,7 @@ Return your response in this format:
|
||||
console.log(
|
||||
boxen(
|
||||
chalk.green(
|
||||
`Successfully generated ${tasksData.tasks.length} tasks from PRD`
|
||||
`Successfully generated ${processedNewTasks.length} new tasks. Total tasks in ${tasksPath}: ${allTasks.length}`
|
||||
),
|
||||
{ padding: 1, borderColor: 'green', borderStyle: 'round' }
|
||||
)
|
||||
@@ -189,7 +316,7 @@ Return your response in this format:
|
||||
);
|
||||
}
|
||||
|
||||
return tasksData;
|
||||
return { success: true, tasks: processedNewTasks };
|
||||
} catch (error) {
|
||||
report(`Error parsing PRD: ${error.message}`, 'error');
|
||||
|
||||
@@ -197,8 +324,8 @@ Return your response in this format:
|
||||
if (outputFormat === 'text') {
|
||||
console.error(chalk.red(`Error: ${error.message}`));
|
||||
|
||||
if (getDebugFlag(session)) {
|
||||
// Use getter
|
||||
if (getDebugFlag(projectRoot)) {
|
||||
// Use projectRoot for debug flag check
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ import generateTaskFiles from './generate-task-files.js';
|
||||
* @param {Object} context - Context object containing session and mcpLog.
|
||||
* @param {Object} [context.session] - Session object from MCP server.
|
||||
* @param {Object} [context.mcpLog] - MCP logger object.
|
||||
* @param {string} [context.projectRoot] - Project root path (needed for AI service key resolution).
|
||||
* @param {string} [outputFormat='text'] - Output format ('text' or 'json'). Automatically 'json' if mcpLog is present.
|
||||
* @returns {Promise<Object|null>} - The updated subtask or null if update failed.
|
||||
*/
|
||||
@@ -40,7 +41,7 @@ async function updateSubtaskById(
|
||||
context = {},
|
||||
outputFormat = context.mcpLog ? 'json' : 'text'
|
||||
) {
|
||||
const { session, mcpLog } = context;
|
||||
const { session, mcpLog, projectRoot } = context;
|
||||
const logFn = mcpLog || consoleLog;
|
||||
const isMCP = !!mcpLog;
|
||||
|
||||
@@ -130,37 +131,6 @@ async function updateSubtaskById(
|
||||
|
||||
const subtask = parentTask.subtasks[subtaskIndex];
|
||||
|
||||
// Check if subtask is already completed
|
||||
if (subtask.status === 'done' || subtask.status === 'completed') {
|
||||
report(
|
||||
'warn',
|
||||
`Subtask ${subtaskId} is already marked as done and cannot be updated`
|
||||
);
|
||||
|
||||
// Only show UI elements for text output (CLI)
|
||||
if (outputFormat === 'text') {
|
||||
console.log(
|
||||
boxen(
|
||||
chalk.yellow(
|
||||
`Subtask ${subtaskId} is already marked as ${subtask.status} and cannot be updated.`
|
||||
) +
|
||||
'\n\n' +
|
||||
chalk.white(
|
||||
'Completed subtasks are locked to maintain consistency. To modify a completed subtask, you must first:'
|
||||
) +
|
||||
'\n' +
|
||||
chalk.white(
|
||||
'1. Change its status to "pending" or "in-progress"'
|
||||
) +
|
||||
'\n' +
|
||||
chalk.white('2. Then run the update-subtask command'),
|
||||
{ padding: 1, borderColor: 'yellow', borderStyle: 'round' }
|
||||
)
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only show UI elements for text output (CLI)
|
||||
if (outputFormat === 'text') {
|
||||
// Show the subtask that will be updated
|
||||
@@ -192,32 +162,38 @@ async function updateSubtaskById(
|
||||
|
||||
// Start the loading indicator - only for text output
|
||||
loadingIndicator = startLoadingIndicator(
|
||||
'Generating additional information with AI...'
|
||||
useResearch
|
||||
? 'Updating subtask with research...'
|
||||
: 'Updating subtask...'
|
||||
);
|
||||
}
|
||||
|
||||
let additionalInformation = '';
|
||||
try {
|
||||
// Reverted: Keep the original system prompt
|
||||
const systemPrompt = `You are an AI assistant helping to update software development subtasks with additional information.
|
||||
Given a subtask, you will provide additional details, implementation notes, or technical insights based on user request.
|
||||
Focus only on adding content that enhances the subtask - don't repeat existing information.
|
||||
Be technical, specific, and implementation-focused rather than general.
|
||||
Provide concrete examples, code snippets, or implementation details when relevant.`;
|
||||
// Build Prompts
|
||||
const systemPrompt = `You are an AI assistant helping to update a software development subtask. Your goal is to APPEND new information to the existing details, not replace them. Add a timestamp.
|
||||
|
||||
// Reverted: Use the full JSON stringification for the user message
|
||||
const subtaskData = JSON.stringify(subtask, null, 2);
|
||||
const userMessageContent = `Here is the subtask to enhance:\n${subtaskData}\n\nPlease provide additional information addressing this request:\n${prompt}\n\nReturn ONLY the new information to add - do not repeat existing content.`;
|
||||
Guidelines:
|
||||
1. Identify the existing 'details' field in the subtask JSON.
|
||||
2. Create a new timestamp string in the format: '[YYYY-MM-DD HH:MM:SS]'.
|
||||
3. Append the new timestamp and the information from the user prompt to the *end* of the existing 'details' field.
|
||||
4. Ensure the final 'details' field is a single, coherent string with the new information added.
|
||||
5. Return the *entire* subtask object as a valid JSON, including the updated 'details' field and all other original fields (id, title, status, dependencies, etc.).`;
|
||||
const subtaskDataString = JSON.stringify(subtask, null, 2);
|
||||
const userPrompt = `Here is the subtask to update:\n${subtaskDataString}\n\nPlease APPEND the following information to the 'details' field, preceded by a timestamp:\n${prompt}\n\nReturn only the updated subtask as a single, valid JSON object.`;
|
||||
|
||||
const serviceRole = useResearch ? 'research' : 'main';
|
||||
report('info', `Calling AI text service with role: ${serviceRole}`);
|
||||
// Call Unified AI Service
|
||||
const role = useResearch ? 'research' : 'main';
|
||||
report('info', `Using AI service with role: ${role}`);
|
||||
|
||||
const streamResult = await generateTextService({
|
||||
role: serviceRole,
|
||||
session: session,
|
||||
const responseText = await generateTextService({
|
||||
prompt: userPrompt,
|
||||
systemPrompt: systemPrompt,
|
||||
prompt: userMessageContent
|
||||
role,
|
||||
session,
|
||||
projectRoot
|
||||
});
|
||||
report('success', 'Successfully received text response from AI service');
|
||||
|
||||
if (outputFormat === 'text' && loadingIndicator) {
|
||||
// Stop indicator immediately since generateText is blocking
|
||||
@@ -226,7 +202,7 @@ Provide concrete examples, code snippets, or implementation details when relevan
|
||||
}
|
||||
|
||||
// Assign the result directly (generateTextService returns the text string)
|
||||
additionalInformation = streamResult ? streamResult.trim() : '';
|
||||
additionalInformation = responseText ? responseText.trim() : '';
|
||||
|
||||
if (!additionalInformation) {
|
||||
throw new Error('AI returned empty response.'); // Changed error message slightly
|
||||
@@ -234,7 +210,7 @@ Provide concrete examples, code snippets, or implementation details when relevan
|
||||
report(
|
||||
// Corrected log message to reflect generateText
|
||||
'success',
|
||||
`Successfully generated text using AI role: ${serviceRole}.`
|
||||
`Successfully generated text using AI role: ${role}.`
|
||||
);
|
||||
} catch (aiError) {
|
||||
report('error', `AI service call failed: ${aiError.message}`);
|
||||
|
||||
@@ -70,29 +70,80 @@ function parseUpdatedTaskFromText(text, expectedTaskId, logFn, isMCP) {
|
||||
|
||||
let cleanedResponse = text.trim();
|
||||
const originalResponseForDebug = cleanedResponse;
|
||||
let parseMethodUsed = 'raw'; // Keep track of which method worked
|
||||
|
||||
// Extract from Markdown code block first
|
||||
const codeBlockMatch = cleanedResponse.match(
|
||||
/```(?:json)?\s*([\s\S]*?)\s*```/
|
||||
);
|
||||
if (codeBlockMatch) {
|
||||
cleanedResponse = codeBlockMatch[1].trim();
|
||||
report('info', 'Extracted JSON content from Markdown code block.');
|
||||
} else {
|
||||
// If no code block, find first '{' and last '}' for the object
|
||||
const firstBrace = cleanedResponse.indexOf('{');
|
||||
const lastBrace = cleanedResponse.lastIndexOf('}');
|
||||
if (firstBrace !== -1 && lastBrace > firstBrace) {
|
||||
cleanedResponse = cleanedResponse.substring(firstBrace, lastBrace + 1);
|
||||
report('info', 'Extracted content between first { and last }.');
|
||||
} else {
|
||||
report(
|
||||
'warn',
|
||||
'Response does not appear to contain a JSON object structure. Parsing raw response.'
|
||||
);
|
||||
// --- NEW Step 1: Try extracting between {} first ---
|
||||
const firstBraceIndex = cleanedResponse.indexOf('{');
|
||||
const lastBraceIndex = cleanedResponse.lastIndexOf('}');
|
||||
let potentialJsonFromBraces = null;
|
||||
|
||||
if (firstBraceIndex !== -1 && lastBraceIndex > firstBraceIndex) {
|
||||
potentialJsonFromBraces = cleanedResponse.substring(
|
||||
firstBraceIndex,
|
||||
lastBraceIndex + 1
|
||||
);
|
||||
if (potentialJsonFromBraces.length <= 2) {
|
||||
potentialJsonFromBraces = null; // Ignore empty braces {}
|
||||
}
|
||||
}
|
||||
|
||||
// If {} extraction yielded something, try parsing it immediately
|
||||
if (potentialJsonFromBraces) {
|
||||
try {
|
||||
const testParse = JSON.parse(potentialJsonFromBraces);
|
||||
// It worked! Use this as the primary cleaned response.
|
||||
cleanedResponse = potentialJsonFromBraces;
|
||||
parseMethodUsed = 'braces';
|
||||
report(
|
||||
'info',
|
||||
'Successfully parsed JSON content extracted between first { and last }.'
|
||||
);
|
||||
} catch (e) {
|
||||
report(
|
||||
'info',
|
||||
'Content between {} looked promising but failed initial parse. Proceeding to other methods.'
|
||||
);
|
||||
// Reset cleanedResponse to original if brace parsing failed
|
||||
cleanedResponse = originalResponseForDebug;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Step 2: If brace parsing didn't work or wasn't applicable, try code block extraction ---
|
||||
if (parseMethodUsed === 'raw') {
|
||||
const codeBlockMatch = cleanedResponse.match(
|
||||
/```(?:json|javascript)?\s*([\s\S]*?)\s*```/i
|
||||
);
|
||||
if (codeBlockMatch) {
|
||||
cleanedResponse = codeBlockMatch[1].trim();
|
||||
parseMethodUsed = 'codeblock';
|
||||
report('info', 'Extracted JSON content from Markdown code block.');
|
||||
} else {
|
||||
// --- Step 3: If code block failed, try stripping prefixes ---
|
||||
const commonPrefixes = [
|
||||
'json\n',
|
||||
'javascript\n'
|
||||
// ... other prefixes ...
|
||||
];
|
||||
let prefixFound = false;
|
||||
for (const prefix of commonPrefixes) {
|
||||
if (cleanedResponse.toLowerCase().startsWith(prefix)) {
|
||||
cleanedResponse = cleanedResponse.substring(prefix.length).trim();
|
||||
parseMethodUsed = 'prefix';
|
||||
report('info', `Stripped prefix: "${prefix.trim()}"`);
|
||||
prefixFound = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!prefixFound) {
|
||||
report(
|
||||
'warn',
|
||||
'Response does not appear to contain {}, code block, or known prefix. Attempting raw parse.'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Step 4: Attempt final parse ---
|
||||
let parsedTask;
|
||||
try {
|
||||
parsedTask = JSON.parse(cleanedResponse);
|
||||
@@ -168,7 +219,7 @@ async function updateTaskById(
|
||||
context = {},
|
||||
outputFormat = 'text'
|
||||
) {
|
||||
const { session, mcpLog } = context;
|
||||
const { session, mcpLog, projectRoot } = context;
|
||||
const logFn = mcpLog || consoleLog;
|
||||
const isMCP = !!mcpLog;
|
||||
|
||||
@@ -343,7 +394,8 @@ The changes described in the prompt should be thoughtfully applied to make the t
|
||||
prompt: userPrompt,
|
||||
systemPrompt: systemPrompt,
|
||||
role,
|
||||
session
|
||||
session,
|
||||
projectRoot
|
||||
});
|
||||
report('success', 'Successfully received text response from AI service');
|
||||
// --- End AI Service Call ---
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
import { getDebugFlag } from '../config-manager.js';
|
||||
import generateTaskFiles from './generate-task-files.js';
|
||||
import { generateTextService } from '../ai-services-unified.js';
|
||||
import { getModelConfiguration } from './models.js';
|
||||
|
||||
// Zod schema for validating the structure of tasks AFTER parsing
|
||||
const updatedTaskSchema = z
|
||||
@@ -42,13 +43,12 @@ const updatedTaskArraySchema = z.array(updatedTaskSchema);
|
||||
* Parses an array of task objects from AI's text response.
|
||||
* @param {string} text - Response text from AI.
|
||||
* @param {number} expectedCount - Expected number of tasks.
|
||||
* @param {Function | Object} logFn - The logging function (consoleLog) or MCP log object.
|
||||
* @param {Function | Object} logFn - The logging function or MCP log object.
|
||||
* @param {boolean} isMCP - Flag indicating if logFn is MCP logger.
|
||||
* @returns {Array} Parsed and validated tasks array.
|
||||
* @throws {Error} If parsing or validation fails.
|
||||
*/
|
||||
function parseUpdatedTasksFromText(text, expectedCount, logFn, isMCP) {
|
||||
// Helper for consistent logging inside parser
|
||||
const report = (level, ...args) => {
|
||||
if (isMCP) {
|
||||
if (typeof logFn[level] === 'function') logFn[level](...args);
|
||||
@@ -69,32 +69,70 @@ function parseUpdatedTasksFromText(text, expectedCount, logFn, isMCP) {
|
||||
let cleanedResponse = text.trim();
|
||||
const originalResponseForDebug = cleanedResponse;
|
||||
|
||||
// Extract from Markdown code block first
|
||||
// Step 1: Attempt to extract from Markdown code block first
|
||||
const codeBlockMatch = cleanedResponse.match(
|
||||
/```(?:json)?\s*([\s\S]*?)\s*```/
|
||||
/```(?:json|javascript)?\s*([\s\S]*?)\s*```/i // Made case-insensitive, allow js
|
||||
);
|
||||
if (codeBlockMatch) {
|
||||
cleanedResponse = codeBlockMatch[1].trim();
|
||||
report('info', 'Extracted JSON content from Markdown code block.');
|
||||
report('info', 'Extracted content from Markdown code block.');
|
||||
} else {
|
||||
// If no code block, find first '[' and last ']' for the array
|
||||
// Step 2 (if no code block): Attempt to strip common language identifiers/intro text
|
||||
// List common prefixes AI might add before JSON
|
||||
const commonPrefixes = [
|
||||
'json\n',
|
||||
'javascript\n',
|
||||
'python\n', // Language identifiers
|
||||
'here are the updated tasks:',
|
||||
'here is the updated json:', // Common intro phrases
|
||||
'updated tasks:',
|
||||
'updated json:',
|
||||
'response:',
|
||||
'output:'
|
||||
];
|
||||
let prefixFound = false;
|
||||
for (const prefix of commonPrefixes) {
|
||||
if (cleanedResponse.toLowerCase().startsWith(prefix)) {
|
||||
cleanedResponse = cleanedResponse.substring(prefix.length).trim();
|
||||
report('info', `Stripped prefix: "${prefix.trim()}"`);
|
||||
prefixFound = true;
|
||||
break; // Stop after finding the first matching prefix
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3 (if no code block and no prefix stripped, or after stripping): Find first '[' and last ']'
|
||||
// This helps if there's still leading/trailing text around the array
|
||||
const firstBracket = cleanedResponse.indexOf('[');
|
||||
const lastBracket = cleanedResponse.lastIndexOf(']');
|
||||
if (firstBracket !== -1 && lastBracket > firstBracket) {
|
||||
cleanedResponse = cleanedResponse.substring(
|
||||
const extractedArray = cleanedResponse.substring(
|
||||
firstBracket,
|
||||
lastBracket + 1
|
||||
);
|
||||
report('info', 'Extracted content between first [ and last ].');
|
||||
} else {
|
||||
// Basic check to see if the extraction looks like JSON
|
||||
if (extractedArray.length > 2) {
|
||||
// More than just '[]'
|
||||
cleanedResponse = extractedArray; // Use the extracted array content
|
||||
if (!codeBlockMatch && !prefixFound) {
|
||||
// Only log if we didn't already log extraction/stripping
|
||||
report('info', 'Extracted content between first [ and last ].');
|
||||
}
|
||||
} else if (!codeBlockMatch && !prefixFound) {
|
||||
report(
|
||||
'warn',
|
||||
'Found brackets "[]" but content seems empty or invalid. Proceeding with original cleaned response.'
|
||||
);
|
||||
}
|
||||
} else if (!codeBlockMatch && !prefixFound) {
|
||||
// Only warn if no other extraction method worked
|
||||
report(
|
||||
'warn',
|
||||
'Response does not appear to contain a JSON array structure. Parsing raw response.'
|
||||
'Response does not appear to contain a JSON code block, known prefix, or clear array structure ([...]). Attempting to parse raw response.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Attempt to parse the array
|
||||
// Step 4: Attempt to parse the (hopefully) cleaned JSON array
|
||||
let parsedTasks;
|
||||
try {
|
||||
parsedTasks = JSON.parse(cleanedResponse);
|
||||
@@ -113,7 +151,7 @@ function parseUpdatedTasksFromText(text, expectedCount, logFn, isMCP) {
|
||||
);
|
||||
}
|
||||
|
||||
// Validate Array structure
|
||||
// Step 5: Validate Array structure
|
||||
if (!Array.isArray(parsedTasks)) {
|
||||
report(
|
||||
'error',
|
||||
@@ -134,7 +172,7 @@ function parseUpdatedTasksFromText(text, expectedCount, logFn, isMCP) {
|
||||
);
|
||||
}
|
||||
|
||||
// Validate each task object using Zod
|
||||
// Step 6: Validate each task object using Zod
|
||||
const validationResult = updatedTaskArraySchema.safeParse(parsedTasks);
|
||||
if (!validationResult.success) {
|
||||
report('error', 'Parsed task array failed Zod validation.');
|
||||
@@ -173,7 +211,7 @@ async function updateTasks(
|
||||
context = {},
|
||||
outputFormat = 'text' // Default to text for CLI
|
||||
) {
|
||||
const { session, mcpLog } = context;
|
||||
const { session, mcpLog, projectRoot } = context;
|
||||
// Use mcpLog if available, otherwise use the imported consoleLog function
|
||||
const logFn = mcpLog || consoleLog;
|
||||
// Flag to easily check which logger type we have
|
||||
@@ -312,7 +350,8 @@ The changes described in the prompt should be applied to ALL tasks in the list.`
|
||||
prompt: userPrompt,
|
||||
systemPrompt: systemPrompt,
|
||||
role,
|
||||
session
|
||||
session,
|
||||
projectRoot
|
||||
});
|
||||
if (isMCP) logFn.info('Successfully received text response');
|
||||
else
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import chalk from 'chalk';
|
||||
import dotenv from 'dotenv';
|
||||
// Import specific config getters needed here
|
||||
import { getLogLevel, getDebugFlag } from './config-manager.js';
|
||||
|
||||
@@ -14,16 +15,47 @@ let silentMode = false;
|
||||
|
||||
// --- Environment Variable Resolution Utility ---
|
||||
/**
|
||||
* Resolves an environment variable by checking process.env first, then session.env.
|
||||
* @param {string} varName - The name of the environment variable.
|
||||
* @param {string|null} session - The MCP session object (optional).
|
||||
* Resolves an environment variable's value.
|
||||
* Precedence:
|
||||
* 1. session.env (if session provided)
|
||||
* 2. process.env
|
||||
* 3. .env file at projectRoot (if projectRoot provided)
|
||||
* @param {string} key - The environment variable key.
|
||||
* @param {object|null} [session=null] - The MCP session object.
|
||||
* @param {string|null} [projectRoot=null] - The project root directory (for .env fallback).
|
||||
* @returns {string|undefined} The value of the environment variable or undefined if not found.
|
||||
*/
|
||||
function resolveEnvVariable(varName, session) {
|
||||
// Ensure session and session.env exist before attempting access
|
||||
const sessionValue =
|
||||
session && session.env ? session.env[varName] : undefined;
|
||||
return process.env[varName] ?? sessionValue;
|
||||
function resolveEnvVariable(key, session = null, projectRoot = null) {
|
||||
// 1. Check session.env
|
||||
if (session?.env?.[key]) {
|
||||
return session.env[key];
|
||||
}
|
||||
|
||||
// 2. Read .env file at projectRoot
|
||||
if (projectRoot) {
|
||||
const envPath = path.join(projectRoot, '.env');
|
||||
if (fs.existsSync(envPath)) {
|
||||
try {
|
||||
const envFileContent = fs.readFileSync(envPath, 'utf-8');
|
||||
const parsedEnv = dotenv.parse(envFileContent); // Use dotenv to parse
|
||||
if (parsedEnv && parsedEnv[key]) {
|
||||
// console.log(`DEBUG: Found key ${key} in ${envPath}`); // Optional debug log
|
||||
return parsedEnv[key];
|
||||
}
|
||||
} catch (error) {
|
||||
// Log error but don't crash, just proceed as if key wasn't found in file
|
||||
log('warn', `Could not read or parse ${envPath}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Fallback: Check process.env
|
||||
if (process.env[key]) {
|
||||
return process.env[key];
|
||||
}
|
||||
|
||||
// Not found anywhere
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// --- Project Root Finding Utility ---
|
||||
@@ -478,8 +510,6 @@ function detectCamelCaseFlags(args) {
|
||||
|
||||
// Export all utility functions and configuration
|
||||
export {
|
||||
// CONFIG, <-- Already Removed
|
||||
// getConfig <-- Removing now
|
||||
LOG_LEVELS,
|
||||
log,
|
||||
readJSON,
|
||||
@@ -500,5 +530,4 @@ export {
|
||||
resolveEnvVariable,
|
||||
getTaskManager,
|
||||
findProjectRoot
|
||||
// getConfig <-- Removed
|
||||
};
|
||||
|
||||
@@ -1,259 +1,291 @@
|
||||
{
|
||||
"meta": {
|
||||
"generatedAt": "2025-04-25T02:29:42.258Z",
|
||||
"tasksAnalyzed": 31,
|
||||
"generatedAt": "2025-05-01T18:17:08.817Z",
|
||||
"tasksAnalyzed": 35,
|
||||
"thresholdScore": 5,
|
||||
"projectName": "Task Master",
|
||||
"projectName": "Taskmaster",
|
||||
"usedResearch": false
|
||||
},
|
||||
"complexityAnalysis": [
|
||||
{
|
||||
"taskId": 24,
|
||||
"taskTitle": "Implement AI-Powered Test Generation Command",
|
||||
"complexityScore": 9,
|
||||
"recommendedSubtasks": 10,
|
||||
"expansionPrompt": "Break down the implementation of an AI-powered test generation command into granular steps, covering CLI integration, task retrieval, AI prompt construction, API integration, test file formatting, error handling, documentation, and comprehensive testing (unit, integration, error cases, and manual verification).",
|
||||
"reasoning": "This task involves advanced CLI development, deep integration with external AI APIs, dynamic prompt engineering, file system operations, error handling, and extensive testing. It requires orchestrating multiple subsystems and ensuring robust, user-friendly output. The cognitive and technical demands are high, justifying a high complexity score and a need for further decomposition into at least 10 subtasks to manage risk and ensure quality.[1][3][4][5]"
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 5,
|
||||
"expansionPrompt": "Break down the implementation of the 'generate-test' command into detailed subtasks covering command structure, AI prompt engineering, test file generation, and integration with existing systems.",
|
||||
"reasoning": "This task involves creating a new CLI command that leverages AI to generate test files. It requires integration with Claude API, understanding of Jest testing, file system operations, and complex prompt engineering. The task already has 3 subtasks but would benefit from further breakdown to address error handling, documentation, and test validation components."
|
||||
},
|
||||
{
|
||||
"taskId": 26,
|
||||
"taskTitle": "Implement Context Foundation for AI Operations",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Expand the context foundation implementation into detailed subtasks for CLI flag integration, file reading utilities, error handling, context formatting, command handler updates, documentation, and comprehensive testing for both functionality and error scenarios.",
|
||||
"reasoning": "This task introduces foundational context management across multiple commands, requiring careful CLI design, file I/O, error handling, and integration with AI prompt construction. While less complex than full AI-powered features, it still spans several modules and requires robust validation, suggesting a moderate-to-high complexity and a need for further breakdown.[1][3][4]"
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the implementation of the context foundation for AI operations into detailed subtasks covering file context handling, cursor rules integration, context extraction utilities, and command handler updates.",
|
||||
"reasoning": "This task involves creating a foundation for context integration in Task Master. It requires implementing file reading functionality, cursor rules integration, and context extraction utilities. The task already has 4 subtasks but would benefit from additional subtasks for testing, documentation, and integration with existing AI operations."
|
||||
},
|
||||
{
|
||||
"taskId": 27,
|
||||
"taskTitle": "Implement Context Enhancements for AI Operations",
|
||||
"complexityScore": 8,
|
||||
"recommendedSubtasks": 10,
|
||||
"expansionPrompt": "Decompose the context enhancement task into subtasks for code context extraction, task history integration, PRD summarization, context formatting, token optimization, error handling, and comprehensive testing for each new context type.",
|
||||
"reasoning": "This phase builds on the foundation to add sophisticated context extraction (code, history, PRD), requiring advanced parsing, summarization, and prompt engineering. The need to optimize for token limits and maintain performance across large codebases increases both technical and cognitive complexity, warranting a high score and further subtask expansion.[1][3][4][5]"
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the implementation of context enhancements for AI operations into detailed subtasks covering code context extraction, task history context, PRD context integration, and context formatting improvements.",
|
||||
"reasoning": "This task builds upon the foundation from task #26 and adds more sophisticated context features. It involves implementing code context extraction, task history awareness, and PRD integration. The task already has 4 subtasks but would benefit from additional subtasks for testing, documentation, and integration with the foundation context system."
|
||||
},
|
||||
{
|
||||
"taskId": 28,
|
||||
"taskTitle": "Implement Advanced ContextManager System",
|
||||
"complexityScore": 10,
|
||||
"recommendedSubtasks": 12,
|
||||
"expansionPrompt": "Expand the ContextManager implementation into subtasks for class design, context source integration, optimization algorithms, caching, token management, command interface updates, AI service integration, performance monitoring, logging, and comprehensive testing (unit, integration, performance, and user experience).",
|
||||
"reasoning": "This is a highly complex architectural task involving advanced class design, optimization algorithms, dynamic context prioritization, caching, and integration with multiple AI services. It requires deep system knowledge, careful performance considerations, and robust error handling, making it one of the most complex tasks in the set and justifying a large number of subtasks.[1][3][4][5]"
|
||||
"complexityScore": 8,
|
||||
"recommendedSubtasks": 7,
|
||||
"expansionPrompt": "Break down the implementation of the advanced ContextManager system into detailed subtasks covering class structure, optimization pipeline, command interface, AI service integration, and performance monitoring.",
|
||||
"reasoning": "This task involves creating a comprehensive ContextManager class with advanced features like context optimization, prioritization, and intelligent selection. It builds on the previous context tasks and requires sophisticated algorithms for token management and context relevance scoring. The task already has 5 subtasks but would benefit from additional subtasks for testing, documentation, and integration with existing systems."
|
||||
},
|
||||
{
|
||||
"taskId": 32,
|
||||
"taskTitle": "Implement \"learn\" Command for Automatic Cursor Rule Generation",
|
||||
"complexityScore": 9,
|
||||
"recommendedSubtasks": 15,
|
||||
"expansionPrompt": "Break down the 'learn' command implementation into subtasks for file structure setup, path utilities, chat history analysis, rule management, AI integration, error handling, performance optimization, CLI integration, logging, and comprehensive testing.",
|
||||
"reasoning": "This task requires orchestrating file system operations, parsing complex chat and code histories, managing rule templates, integrating with AI for pattern extraction, and ensuring robust error handling and performance. The breadth and depth of required functionality, along with the need for both automatic and manual triggers, make this a highly complex task needing extensive decomposition.[1][3][4][5]"
|
||||
},
|
||||
{
|
||||
"taskId": 35,
|
||||
"taskTitle": "Integrate Grok3 API for Research Capabilities",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Expand the Grok3 API integration into subtasks for API client development, service layer updates, payload/response adaptation, error handling, configuration management, UI updates, backward compatibility, and documentation/testing.",
|
||||
"reasoning": "This migration task involves replacing a core external API, adapting to new request/response formats, updating configuration and UI, and ensuring backward compatibility. While not as cognitively complex as some AI tasks, the risk and breadth of impact across the system justify a moderate-to-high complexity and further breakdown.[1][3][4]"
|
||||
},
|
||||
{
|
||||
"taskId": 36,
|
||||
"taskTitle": "Add Ollama Support for AI Services as Claude Alternative",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Decompose the Ollama integration into subtasks for service class implementation, configuration, model selection, prompt formatting, error handling, fallback logic, documentation, and comprehensive testing.",
|
||||
"reasoning": "Adding a local AI provider requires interface compatibility, configuration management, error handling, and fallback logic, as well as user documentation. The technical complexity is moderate-to-high, especially in ensuring seamless switching and robust error handling, warranting further subtasking.[1][3][4]"
|
||||
},
|
||||
{
|
||||
"taskId": 37,
|
||||
"taskTitle": "Add Gemini Support for Main AI Services as Claude Alternative",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Expand Gemini integration into subtasks for service class creation, authentication, prompt/response mapping, configuration, error handling, streaming support, documentation, and comprehensive testing.",
|
||||
"reasoning": "Integrating a new cloud AI provider involves authentication, API adaptation, configuration, and ensuring feature parity. The complexity is similar to other provider integrations, requiring careful planning and multiple subtasks for robust implementation and testing.[1][3][4]"
|
||||
"expansionPrompt": "Break down the implementation of the 'learn' command for automatic Cursor rule generation into detailed subtasks covering chat history analysis, rule management, AI integration, and command structure.",
|
||||
"reasoning": "This task involves creating a complex system that analyzes Cursor's chat history and code changes to automatically generate rule files. It requires sophisticated data analysis, pattern recognition, and AI integration. The task already has 15 subtasks, which is appropriate given its complexity, but could benefit from reorganization into logical groupings."
|
||||
},
|
||||
{
|
||||
"taskId": 40,
|
||||
"taskTitle": "Implement 'plan' Command for Task Implementation Planning",
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the 'plan' command implementation into subtasks for CLI integration, task/subtask retrieval, AI prompt construction, plan formatting, error handling, and testing.",
|
||||
"reasoning": "This task involves AI prompt engineering, CLI integration, and content formatting, but is more focused and less technically demanding than full AI service or context management features. It still requires careful error handling and testing, suggesting a moderate complexity and a handful of subtasks.[1][3][4]"
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 5,
|
||||
"expansionPrompt": "Break down the implementation of the 'plan' command for task implementation planning into detailed subtasks covering command structure, AI integration, plan formatting, and error handling.",
|
||||
"reasoning": "This task involves creating a new command that generates implementation plans for tasks. It requires integration with AI services, understanding of task structure, and proper formatting of generated plans. The task has no subtasks yet, so creating 5 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 41,
|
||||
"taskTitle": "Implement Visual Task Dependency Graph in Terminal",
|
||||
"complexityScore": 8,
|
||||
"recommendedSubtasks": 10,
|
||||
"expansionPrompt": "Expand the visual dependency graph implementation into subtasks for CLI command setup, graph layout algorithms, ASCII/Unicode rendering, color coding, circular dependency detection, filtering, accessibility, performance optimization, documentation, and testing.",
|
||||
"reasoning": "Rendering complex dependency graphs in the terminal with color coding, layout optimization, and accessibility features is technically challenging and requires careful algorithm design and robust error handling. The need for performance optimization and user-friendly output increases the complexity, justifying a high score and further subtasking.[1][3][4][5]"
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Break down the implementation of the visual task dependency graph in terminal into detailed subtasks covering graph layout algorithms, ASCII/Unicode rendering, color coding, circular dependency detection, and filtering options.",
|
||||
"reasoning": "This task involves creating a complex visualization system for task dependencies using ASCII/Unicode characters. It requires sophisticated layout algorithms, rendering logic, and user interface considerations. The task already has 10 subtasks, which is appropriate given its complexity."
|
||||
},
|
||||
{
|
||||
"taskId": 42,
|
||||
"taskTitle": "Implement MCP-to-MCP Communication Protocol",
|
||||
"complexityScore": 10,
|
||||
"recommendedSubtasks": 12,
|
||||
"expansionPrompt": "Break down the MCP-to-MCP protocol implementation into subtasks for protocol definition, adapter pattern, client module, reference integration, mode support, core module updates, configuration, documentation, error handling, security, and comprehensive testing.",
|
||||
"reasoning": "Designing and implementing a standardized communication protocol with dynamic mode switching, adapter patterns, and robust error handling is architecturally complex. It requires deep system understanding, security considerations, and extensive testing, making it one of the most complex tasks and requiring significant decomposition.[1][3][4][5]"
|
||||
"complexityScore": 9,
|
||||
"recommendedSubtasks": 10,
|
||||
"expansionPrompt": "Break down the implementation of the MCP-to-MCP communication protocol into detailed subtasks covering protocol definition, adapter pattern, client module, reference implementation, and mode switching.",
|
||||
"reasoning": "This task involves designing and implementing a standardized communication protocol for Taskmaster to interact with external MCP tools. It requires sophisticated protocol design, authentication mechanisms, error handling, and support for different operational modes. The task already has 8 subtasks but would benefit from additional subtasks for security, testing, and documentation."
|
||||
},
|
||||
{
|
||||
"taskId": 43,
|
||||
"taskTitle": "Add Research Flag to Add-Task Command",
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 5,
|
||||
"expansionPrompt": "Expand the research flag implementation into subtasks for CLI parser updates, subtask generation logic, parent linking, help documentation, and testing.",
|
||||
"reasoning": "This is a focused feature addition involving CLI parsing, subtask generation, and documentation. While it requires some integration with AI or templating logic, the scope is well-defined and less complex than architectural or multi-module tasks, suggesting a moderate complexity and a handful of subtasks.[1][3][4]"
|
||||
"complexityScore": 3,
|
||||
"recommendedSubtasks": 4,
|
||||
"expansionPrompt": "Break down the implementation of the research flag for the add-task command into detailed subtasks covering command argument parsing, research subtask generation, integration with existing command, and documentation.",
|
||||
"reasoning": "This task involves modifying the add-task command to support a new flag that generates research-oriented subtasks. It's relatively straightforward as it builds on existing functionality. The task has no subtasks yet, so creating 4 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 44,
|
||||
"taskTitle": "Implement Task Automation with Webhooks and Event Triggers",
|
||||
"complexityScore": 9,
|
||||
"recommendedSubtasks": 10,
|
||||
"expansionPrompt": "Decompose the webhook and event trigger system into subtasks for event system design, webhook registration, trigger definition, incoming/outgoing webhook handling, authentication, rate limiting, CLI management, payload templating, logging, and comprehensive testing.",
|
||||
"reasoning": "Building a robust automation system with webhooks and event triggers involves designing an event system, secure webhook handling, trigger logic, CLI management, and error handling. The breadth and integration requirements make this a highly complex task needing extensive breakdown.[1][3][4][5]"
|
||||
"complexityScore": 8,
|
||||
"recommendedSubtasks": 7,
|
||||
"expansionPrompt": "Break down the implementation of task automation with webhooks and event triggers into detailed subtasks covering webhook registration, event system, trigger definition, authentication, and payload templating.",
|
||||
"reasoning": "This task involves creating a sophisticated automation system with webhooks and event triggers. It requires implementing webhook registration, event capturing, trigger definitions, authentication, and integration with existing systems. The task has no subtasks yet, so creating 7 subtasks would provide a clear implementation path for this complex feature."
|
||||
},
|
||||
{
|
||||
"taskId": 45,
|
||||
"taskTitle": "Implement GitHub Issue Import Feature",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Expand the GitHub issue import feature into subtasks for CLI flag parsing, URL extraction, API integration, data mapping, authentication, error handling, override logic, documentation, and testing.",
|
||||
"reasoning": "This task involves external API integration, data mapping, authentication, error handling, and user override logic. While not as complex as architectural changes, it still requires careful planning and multiple subtasks for robust implementation and testing.[1][3][4]"
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 5,
|
||||
"expansionPrompt": "Break down the implementation of the GitHub issue import feature into detailed subtasks covering URL parsing, GitHub API integration, task generation, authentication, and error handling.",
|
||||
"reasoning": "This task involves adding a feature to import GitHub issues as tasks. It requires integration with the GitHub API, URL parsing, authentication handling, and proper error management. The task has no subtasks yet, so creating 5 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 46,
|
||||
"taskTitle": "Implement ICE Analysis Command for Task Prioritization",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Break down the ICE analysis command into subtasks for scoring algorithm development, LLM prompt engineering, report generation, CLI rendering, integration with complexity reports, sorting/filtering, error handling, and testing.",
|
||||
"reasoning": "Implementing a prioritization command with LLM-based scoring, report generation, and CLI rendering involves moderate technical and cognitive complexity, especially in ensuring accurate and actionable outputs. It requires several subtasks for robust implementation and validation.[1][3][4]"
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the implementation of the ICE analysis command for task prioritization into detailed subtasks covering scoring algorithm, report generation, CLI rendering, and integration with existing analysis tools.",
|
||||
"reasoning": "This task involves creating a new command that analyzes and ranks tasks based on Impact, Confidence, and Ease scoring. It requires implementing scoring algorithms, report generation, CLI rendering, and integration with existing analysis tools. The task has no subtasks yet, so creating 6 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 47,
|
||||
"taskTitle": "Enhance Task Suggestion Actions Card Workflow",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Expand the workflow enhancement into subtasks for UI redesign, phase management logic, interactive elements, progress tracking, context addition, task management integration, accessibility, and comprehensive testing.",
|
||||
"reasoning": "Redesigning a multi-phase workflow with interactive UI elements, progress tracking, and context management involves both UI/UX and logic complexity. The need for seamless transitions and robust state management increases the complexity, warranting further breakdown.[1][3][4]"
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the enhancement of the task suggestion actions card workflow into detailed subtasks covering task expansion phase, context addition phase, task management phase, and UI/UX improvements.",
|
||||
"reasoning": "This task involves redesigning the suggestion actions card to implement a structured workflow. It requires implementing multiple phases (expansion, context addition, management) with appropriate UI/UX considerations. The task has no subtasks yet, so creating 6 subtasks would provide a clear implementation path for this moderately complex feature."
|
||||
},
|
||||
{
|
||||
"taskId": 48,
|
||||
"taskTitle": "Refactor Prompts into Centralized Structure",
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the prompt refactoring into subtasks for directory setup, prompt extraction, import updates, naming conventions, documentation, and regression testing.",
|
||||
"reasoning": "This is a codebase refactoring task focused on maintainability and organization. While it touches many files, the technical complexity is moderate, but careful planning and testing are needed to avoid regressions, suggesting a moderate complexity and several subtasks.[1][3][4]"
|
||||
"complexityScore": 4,
|
||||
"recommendedSubtasks": 4,
|
||||
"expansionPrompt": "Break down the refactoring of prompts into a centralized structure into detailed subtasks covering directory creation, prompt extraction, function modification, and documentation.",
|
||||
"reasoning": "This task involves restructuring how prompts are managed in the codebase. It's a relatively straightforward refactoring task that requires creating a new directory structure, extracting prompts from functions, and updating references. The task has no subtasks yet, so creating 4 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 49,
|
||||
"taskTitle": "Implement Code Quality Analysis Command",
|
||||
"complexityScore": 8,
|
||||
"recommendedSubtasks": 10,
|
||||
"expansionPrompt": "Expand the code quality analysis command into subtasks for pattern recognition, best practice verification, AI integration, recommendation generation, task integration, CLI development, configuration, error handling, documentation, and comprehensive testing.",
|
||||
"reasoning": "This task involves static code analysis, AI integration for best practice checks, recommendation generation, and task creation workflows. The technical and cognitive demands are high, requiring robust validation and integration, justifying a high complexity and multiple subtasks.[1][3][4][5]"
|
||||
"recommendedSubtasks": 7,
|
||||
"expansionPrompt": "Break down the implementation of the code quality analysis command into detailed subtasks covering pattern recognition, best practice verification, improvement recommendations, task integration, and reporting.",
|
||||
"reasoning": "This task involves creating a sophisticated command that analyzes code quality, identifies patterns, verifies against best practices, and generates improvement recommendations. It requires complex algorithms for code analysis and integration with AI services. The task has no subtasks yet, so creating 7 subtasks would provide a clear implementation path for this complex feature."
|
||||
},
|
||||
{
|
||||
"taskId": 50,
|
||||
"taskTitle": "Implement Test Coverage Tracking System by Task",
|
||||
"complexityScore": 9,
|
||||
"recommendedSubtasks": 12,
|
||||
"expansionPrompt": "Break down the test coverage tracking system into subtasks for data structure design, coverage parsing, mapping algorithms, CLI commands, LLM-powered test generation, MCP integration, visualization, workflow integration, error handling, documentation, and comprehensive testing.",
|
||||
"reasoning": "Mapping test coverage to tasks, integrating with coverage tools, generating targeted tests, and visualizing coverage requires advanced data modeling, parsing, AI integration, and workflow design. The breadth and depth of this system make it highly complex and in need of extensive decomposition.[1][3][4][5]"
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Break down the implementation of the test coverage tracking system by task into detailed subtasks covering data structure design, coverage report parsing, tracking and update generation, CLI commands, and AI-powered test generation.",
|
||||
"reasoning": "This task involves creating a comprehensive system for tracking test coverage at the task level. It requires implementing data structures, coverage report parsing, tracking mechanisms, CLI commands, and AI integration. The task already has 5 subtasks but would benefit from additional subtasks for integration testing, documentation, and user experience."
|
||||
},
|
||||
{
|
||||
"taskId": 51,
|
||||
"taskTitle": "Implement Perplexity Research Command",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Expand the Perplexity research command into subtasks for API client development, context extraction, CLI interface, result formatting, caching, error handling, documentation, and comprehensive testing.",
|
||||
"reasoning": "This task involves external API integration, context extraction, CLI development, result formatting, caching, and error handling. The technical complexity is moderate-to-high, especially in ensuring robust and user-friendly output, suggesting multiple subtasks.[1][3][4]"
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the implementation of the Perplexity research command into detailed subtasks covering API client service, task context extraction, CLI interface, results processing, and caching system.",
|
||||
"reasoning": "This task involves creating a command that integrates with Perplexity AI for research purposes. It requires implementing an API client, context extraction, CLI interface, results processing, and caching. The task already has 5 subtasks, which is appropriate for its complexity."
|
||||
},
|
||||
{
|
||||
"taskId": 52,
|
||||
"taskTitle": "Implement Task Suggestion Command for CLI",
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the task suggestion command into subtasks for task snapshot collection, context extraction, AI suggestion generation, interactive CLI interface, error handling, and testing.",
|
||||
"reasoning": "This is a focused feature involving AI suggestion generation and interactive CLI elements. While it requires careful context management and error handling, the scope is well-defined and less complex than architectural or multi-module tasks, suggesting a moderate complexity and several subtasks.[1][3][4]"
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 5,
|
||||
"expansionPrompt": "Break down the implementation of the task suggestion command for CLI into detailed subtasks covering task data collection, AI integration, suggestion presentation, interactive interface, and configuration options.",
|
||||
"reasoning": "This task involves creating a new CLI command that generates contextually relevant task suggestions. It requires collecting existing task data, integrating with AI services, presenting suggestions, and implementing an interactive interface. The task has no subtasks yet, so creating 5 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 53,
|
||||
"taskTitle": "Implement Subtask Suggestion Feature for Parent Tasks",
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Expand the subtask suggestion feature into subtasks for parent task validation, context gathering, AI suggestion logic, interactive CLI interface, subtask linking, and testing.",
|
||||
"reasoning": "Similar to the task suggestion command, this feature is focused but requires robust context management, AI integration, and interactive CLI handling. The complexity is moderate, warranting several subtasks for a robust implementation.[1][3][4]"
|
||||
},
|
||||
{
|
||||
"taskId": 54,
|
||||
"taskTitle": "Add Research Flag to Add-Task Command",
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 5,
|
||||
"expansionPrompt": "Break down the research flag enhancement into subtasks for CLI parser updates, research invocation, user interaction, task creation flow integration, and testing.",
|
||||
"reasoning": "This is a focused enhancement involving CLI parsing, research invocation, and user interaction. The technical complexity is moderate, with a clear scope and integration points, suggesting a handful of subtasks.[1][3][4]"
|
||||
"expansionPrompt": "Break down the implementation of the subtask suggestion feature for parent tasks into detailed subtasks covering parent task validation, context gathering, AI integration, interactive interface, and subtask linking.",
|
||||
"reasoning": "This task involves creating a feature that suggests contextually relevant subtasks for existing parent tasks. It requires implementing parent task validation, context gathering, AI integration, an interactive interface, and subtask linking. The task already has 6 subtasks, which is appropriate for its complexity."
|
||||
},
|
||||
{
|
||||
"taskId": 55,
|
||||
"taskTitle": "Implement Positional Arguments Support for CLI Commands",
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Expand positional argument support into subtasks for parser updates, argument mapping, help documentation, error handling, backward compatibility, and comprehensive testing.",
|
||||
"reasoning": "Upgrading CLI parsing to support positional arguments requires careful mapping, error handling, documentation, and regression testing to maintain backward compatibility. The complexity is moderate, suggesting several subtasks.[1][3][4]"
|
||||
},
|
||||
{
|
||||
"taskId": 56,
|
||||
"taskTitle": "Refactor Task-Master Files into Node Module Structure",
|
||||
"complexityScore": 8,
|
||||
"recommendedSubtasks": 10,
|
||||
"expansionPrompt": "Break down the refactoring into subtasks for directory setup, file migration, import path updates, build script adjustments, compatibility checks, documentation, regression testing, and rollback planning.",
|
||||
"reasoning": "This is a high-risk, broad refactoring affecting many files and build processes. It requires careful planning, incremental changes, and extensive testing to avoid regressions, justifying a high complexity and multiple subtasks.[1][3][4][5]"
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 5,
|
||||
"expansionPrompt": "Break down the implementation of positional arguments support for CLI commands into detailed subtasks covering argument parsing logic, command mapping, help text updates, error handling, and testing.",
|
||||
"reasoning": "This task involves modifying the command parsing logic to support positional arguments alongside the existing flag-based syntax. It requires updating argument parsing, mapping positional arguments to parameters, updating help text, and handling edge cases. The task has no subtasks yet, so creating 5 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 57,
|
||||
"taskTitle": "Enhance Task-Master CLI User Experience and Interface",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Expand the CLI UX enhancement into subtasks for log management, visual design, interactive elements, output formatting, help/documentation, accessibility, performance optimization, and comprehensive testing.",
|
||||
"reasoning": "Improving CLI UX involves log management, visual enhancements, interactive elements, and accessibility, requiring both technical and design skills. The breadth of improvements and need for robust testing increase the complexity, suggesting multiple subtasks.[1][3][4]"
|
||||
},
|
||||
{
|
||||
"taskId": 58,
|
||||
"taskTitle": "Implement Elegant Package Update Mechanism for Task-Master",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 8,
|
||||
"expansionPrompt": "Break down the update mechanism into subtasks for version detection, update command implementation, file management, configuration migration, notification system, rollback logic, documentation, and comprehensive testing.",
|
||||
"reasoning": "Implementing a robust update mechanism involves version management, file operations, configuration migration, rollback planning, and user communication. The technical and operational complexity is moderate-to-high, requiring multiple subtasks.[1][3][4]"
|
||||
},
|
||||
{
|
||||
"taskId": 59,
|
||||
"taskTitle": "Remove Manual Package.json Modifications and Implement Automatic Dependency Management",
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Expand the dependency management refactor into subtasks for code audit, removal of manual modifications, npm dependency updates, initialization command updates, documentation, and regression testing.",
|
||||
"reasoning": "This is a focused refactoring to align with npm best practices. While it touches installation and configuration logic, the technical complexity is moderate, with a clear scope and manageable risk, suggesting several subtasks.[1][3][4]"
|
||||
"expansionPrompt": "Break down the enhancement of the Task-Master CLI user experience and interface into detailed subtasks covering log management, visual enhancements, interactive elements, output formatting, and help documentation.",
|
||||
"reasoning": "This task involves improving the CLI's user experience through various enhancements to logging, visuals, interactivity, and documentation. It requires implementing log levels, visual improvements, interactive elements, and better formatting. The task has no subtasks yet, so creating 6 subtasks would provide a clear implementation path for this moderately complex feature."
|
||||
},
|
||||
{
|
||||
"taskId": 60,
|
||||
"taskTitle": "Implement Mentor System with Round-Table Discussion Feature",
|
||||
"complexityScore": 9,
|
||||
"recommendedSubtasks": 12,
|
||||
"expansionPrompt": "Break down the mentor system implementation into subtasks for mentor management, round-table simulation, CLI integration, AI personality simulation, task integration, output formatting, error handling, documentation, and comprehensive testing.",
|
||||
"reasoning": "This task involves designing a new system for mentor management, simulating multi-personality AI discussions, integrating with tasks, and ensuring robust CLI and output handling. The breadth and novelty of the feature, along with the need for robust simulation and integration, make it highly complex and in need of extensive decomposition.[1][3][4][5]"
|
||||
"complexityScore": 8,
|
||||
"recommendedSubtasks": 7,
|
||||
"expansionPrompt": "Break down the implementation of the mentor system with round-table discussion feature into detailed subtasks covering mentor management, round-table discussion, task system integration, LLM integration, and documentation.",
|
||||
"reasoning": "This task involves creating a sophisticated mentor system with round-table discussions. It requires implementing mentor management, discussion simulation, task integration, and LLM integration. The task has no subtasks yet, so creating 7 subtasks would provide a clear implementation path for this complex feature."
|
||||
},
|
||||
{
|
||||
"taskId": 61,
|
||||
"taskTitle": "Implement Flexible AI Model Management",
|
||||
"complexityScore": 10,
|
||||
"recommendedSubtasks": 15,
|
||||
"expansionPrompt": "Expand the AI model management implementation into subtasks for configuration management, CLI command parsing, provider module development, unified service abstraction, environment variable handling, documentation, integration testing, migration planning, and cleanup of legacy code.",
|
||||
"reasoning": "This is a major architectural overhaul involving configuration management, CLI design, multi-provider integration, abstraction layers, environment variable handling, documentation, and migration. The technical and organizational complexity is extremely high, requiring extensive decomposition and careful coordination.[1][3][4][5]"
|
||||
"recommendedSubtasks": 10,
|
||||
"expansionPrompt": "Break down the implementation of flexible AI model management into detailed subtasks covering configuration management, CLI command parsing, AI SDK integration, service module development, environment variable handling, and documentation.",
|
||||
"reasoning": "This task involves implementing comprehensive support for multiple AI models with a unified interface. It's extremely complex, requiring configuration management, CLI commands, SDK integration, service modules, and environment handling. The task already has 45 subtasks, which is appropriate given its complexity and scope."
|
||||
},
|
||||
{
|
||||
"taskId": 62,
|
||||
"taskTitle": "Add --simple Flag to Update Commands for Direct Text Input",
|
||||
"complexityScore": 4,
|
||||
"recommendedSubtasks": 5,
|
||||
"expansionPrompt": "Break down the implementation of the --simple flag for update commands into detailed subtasks covering command parser updates, AI processing bypass, timestamp formatting, visual indicators, and documentation.",
|
||||
"reasoning": "This task involves modifying update commands to accept a flag that bypasses AI processing. It requires updating command parsers, implementing conditional logic, formatting user input, and updating documentation. The task already has 8 subtasks, which is more than sufficient for its complexity."
|
||||
},
|
||||
{
|
||||
"taskId": 63,
|
||||
"taskTitle": "Add pnpm Support for the Taskmaster Package",
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the implementation of pnpm support for the Taskmaster package into detailed subtasks covering documentation updates, package script compatibility, lockfile generation, installation testing, CI/CD integration, and website consistency verification.",
|
||||
"reasoning": "This task involves ensuring the Taskmaster package works seamlessly with pnpm. It requires updating documentation, ensuring script compatibility, testing installation, and integrating with CI/CD. The task already has 8 subtasks, which is appropriate for its complexity."
|
||||
},
|
||||
{
|
||||
"taskId": 64,
|
||||
"taskTitle": "Add Yarn Support for Taskmaster Installation",
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the implementation of Yarn support for Taskmaster installation into detailed subtasks covering package.json updates, Yarn-specific configuration, compatibility testing, documentation updates, package manager detection, and website consistency verification.",
|
||||
"reasoning": "This task involves ensuring the Taskmaster package works seamlessly with Yarn. It requires updating package.json, adding Yarn-specific configuration, testing compatibility, and updating documentation. The task already has 9 subtasks, which is appropriate for its complexity."
|
||||
},
|
||||
{
|
||||
"taskId": 65,
|
||||
"taskTitle": "Add Bun Support for Taskmaster Installation",
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the implementation of Bun support for Taskmaster installation into detailed subtasks covering package.json updates, Bun-specific configuration, compatibility testing, documentation updates, package manager detection, and troubleshooting guidance.",
|
||||
"reasoning": "This task involves ensuring the Taskmaster package works seamlessly with Bun. It requires updating package.json, adding Bun-specific configuration, testing compatibility, and updating documentation. The task has no subtasks yet, so creating 6 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 66,
|
||||
"taskTitle": "Support Status Filtering in Show Command for Subtasks",
|
||||
"complexityScore": 3,
|
||||
"recommendedSubtasks": 4,
|
||||
"expansionPrompt": "Break down the implementation of status filtering in the show command for subtasks into detailed subtasks covering command parser updates, filtering logic, help documentation, and testing.",
|
||||
"reasoning": "This task involves enhancing the show command to support status-based filtering of subtasks. It's relatively straightforward, requiring updates to the command parser, filtering logic, and documentation. The task has no subtasks yet, so creating 4 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 67,
|
||||
"taskTitle": "Add CLI JSON output and Cursor keybindings integration",
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the implementation of CLI JSON output and Cursor keybindings integration into detailed subtasks covering JSON flag implementation, output formatting, keybindings command structure, OS detection, file handling, and keybinding definition.",
|
||||
"reasoning": "This task involves two main components: adding JSON output to CLI commands and creating a new command for Cursor keybindings. It requires implementing a JSON flag, formatting output, creating a new command, detecting OS, handling files, and defining keybindings. The task already has 5 subtasks, which is appropriate for its complexity."
|
||||
},
|
||||
{
|
||||
"taskId": 68,
|
||||
"taskTitle": "Ability to create tasks without parsing PRD",
|
||||
"complexityScore": 4,
|
||||
"recommendedSubtasks": 4,
|
||||
"expansionPrompt": "Break down the implementation of creating tasks without parsing PRD into detailed subtasks covering tasks.json creation, function reuse from parse-prd, command modification, and documentation.",
|
||||
"reasoning": "This task involves modifying the task creation process to work without a PRD. It's relatively straightforward, requiring tasks.json creation, function reuse, command modification, and documentation. The task has no subtasks yet, so creating 4 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 69,
|
||||
"taskTitle": "Enhance Analyze Complexity for Specific Task IDs",
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 5,
|
||||
"expansionPrompt": "Break down the --simple flag implementation into subtasks for CLI parser updates, update logic modification, timestamp formatting, display logic, documentation, and testing.",
|
||||
"reasoning": "This is a focused feature addition involving CLI parsing, conditional logic, timestamp formatting, and display updates. The technical complexity is moderate, with a clear scope and manageable risk, suggesting a handful of subtasks.[1][3][4]"
|
||||
"expansionPrompt": "Break down the enhancement of analyze-complexity for specific task IDs into detailed subtasks covering core logic modification, CLI command updates, MCP tool updates, report handling, and testing.",
|
||||
"reasoning": "This task involves modifying the analyze-complexity feature to support analyzing specific task IDs. It requires updating core logic, CLI commands, MCP tools, and report handling. The task has no subtasks yet, so creating 5 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 70,
|
||||
"taskTitle": "Implement 'diagram' command for Mermaid diagram generation",
|
||||
"complexityScore": 6,
|
||||
"recommendedSubtasks": 6,
|
||||
"expansionPrompt": "Break down the implementation of the 'diagram' command for Mermaid diagram generation into detailed subtasks covering command structure, task data collection, diagram generation, rendering options, file export, and documentation.",
|
||||
"reasoning": "This task involves creating a new command that generates Mermaid diagrams for task dependencies. It requires implementing command structure, collecting task data, generating diagrams, providing rendering options, and supporting file export. The task has no subtasks yet, so creating 6 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 72,
|
||||
"taskTitle": "Implement PDF Generation for Project Progress and Dependency Overview",
|
||||
"complexityScore": 7,
|
||||
"recommendedSubtasks": 7,
|
||||
"expansionPrompt": "Break down the implementation of PDF generation for project progress and dependency overview into detailed subtasks covering command structure, data collection, progress summary generation, dependency visualization, PDF creation, styling, and documentation.",
|
||||
"reasoning": "This task involves creating a feature to generate PDF reports of project progress and dependencies. It requires implementing command structure, collecting data, generating summaries, visualizing dependencies, creating PDFs, and styling the output. The task has no subtasks yet, so creating 7 subtasks would provide a clear implementation path for this moderately complex feature."
|
||||
},
|
||||
{
|
||||
"taskId": 73,
|
||||
"taskTitle": "Implement Custom Model ID Support for Ollama/OpenRouter",
|
||||
"complexityScore": 5,
|
||||
"recommendedSubtasks": 5,
|
||||
"expansionPrompt": "Break down the implementation of custom model ID support for Ollama/OpenRouter into detailed subtasks covering CLI flag implementation, model validation, interactive setup, configuration updates, and documentation.",
|
||||
"reasoning": "This task involves allowing users to specify custom model IDs for Ollama and OpenRouter. It requires implementing CLI flags, validating models, updating the interactive setup, modifying configuration, and updating documentation. The task has no subtasks yet, so creating 5 subtasks would provide a clear implementation path."
|
||||
},
|
||||
{
|
||||
"taskId": 75,
|
||||
"taskTitle": "Integrate Google Search Grounding for Research Role",
|
||||
"complexityScore": 4,
|
||||
"recommendedSubtasks": 4,
|
||||
"expansionPrompt": "Break down the integration of Google Search Grounding for research role into detailed subtasks covering AI service layer modification, conditional logic implementation, model configuration updates, and testing.",
|
||||
"reasoning": "This task involves updating the AI service layer to enable Google Search Grounding for the research role. It's relatively straightforward, requiring modifications to the AI service, implementing conditional logic, updating model configurations, and testing. The task has no subtasks yet, so creating 4 subtasks would provide a clear implementation path."
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -46,3 +46,20 @@ Generate task files from sample tasks.json data and verify the content matches t
|
||||
### Details:
|
||||
|
||||
|
||||
<info added on 2025-05-01T21:59:10.551Z>
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Implement Change Detection and Update Handling",
|
||||
"description": "Create a system to detect changes in task files and tasks.json, and handle updates bidirectionally. This includes implementing file watching or comparison mechanisms, determining which version is newer, and applying changes in the appropriate direction. Ensure the system handles edge cases like deleted files, new tasks, and conflicting changes.",
|
||||
"status": "done",
|
||||
"dependencies": [
|
||||
1,
|
||||
3,
|
||||
4,
|
||||
2
|
||||
],
|
||||
"acceptanceCriteria": "- Detects changes in both task files and tasks.json\n- Determines which version is newer based on modification timestamps or content\n- Applies changes in the appropriate direction (file to JSON or JSON to file)\n- Handles edge cases like deleted files, new tasks, and renamed tasks\n- Provides options for manual conflict resolution when necessary\n- Maintains data integrity during the synchronization process\n- Includes a command to force synchronization in either direction\n- Logs all synchronization activities for troubleshooting\n\nEach of these subtasks addresses a specific component of the task file generation system, following a logical progression from template design to bidirectional synchronization. The dependencies ensure that prerequisites are completed before dependent work begins, and the acceptance criteria provide clear guidelines for verifying each subtask's completion.",
|
||||
"details": "[2025-05-01 21:59:07] Adding another note via MCP test."
|
||||
}
|
||||
</info added on 2025-05-01T21:59:10.551Z>
|
||||
|
||||
|
||||
11
tasks/task_075.txt
Normal file
11
tasks/task_075.txt
Normal file
@@ -0,0 +1,11 @@
|
||||
# Task ID: 75
|
||||
# Title: Integrate Google Search Grounding for Research Role
|
||||
# Status: pending
|
||||
# Dependencies: None
|
||||
# Priority: medium
|
||||
# Description: Update the AI service layer to enable Google Search Grounding specifically when a Google model is used in the 'research' role.
|
||||
# Details:
|
||||
**Goal:** Conditionally enable Google Search Grounding based on the AI role.\n\n**Implementation Plan:**\n\n1. **Modify `ai-services-unified.js`:** Update `generateTextService`, `streamTextService`, and `generateObjectService`.\n2. **Conditional Logic:** Inside these functions, check if `providerName === 'google'` AND `role === 'research'`.\n3. **Construct `providerOptions`:** If the condition is met, create an options object:\n ```javascript\n let providerSpecificOptions = {};\n if (providerName === 'google' && role === 'research') {\n log('info', 'Enabling Google Search Grounding for research role.');\n providerSpecificOptions = {\n google: {\n useSearchGrounding: true,\n // Optional: Add dynamic retrieval for compatible models\n // dynamicRetrievalConfig: { mode: 'MODE_DYNAMIC' } \n }\n };\n }\n ```\n4. **Pass Options to SDK:** Pass `providerSpecificOptions` to the Vercel AI SDK functions (`generateText`, `streamText`, `generateObject`) via the `providerOptions` parameter:\n ```javascript\n const { text, ... } = await generateText({\n // ... other params\n providerOptions: providerSpecificOptions \n });\n ```\n5. **Update `supported-models.json`:** Ensure Google models intended for research (e.g., `gemini-1.5-pro-latest`, `gemini-1.5-flash-latest`) include `'research'` in their `allowed_roles` array.\n\n**Rationale:** This approach maintains the clear separation between 'main' and 'research' roles, ensuring grounding is only activated when explicitly requested via the `--research` flag or when the research model is invoked.
|
||||
|
||||
# Test Strategy:
|
||||
1. Configure a Google model (e.g., gemini-1.5-flash-latest) as the 'research' model in `.taskmasterconfig`.\n2. Run a command with the `--research` flag (e.g., `task-master add-task --prompt='Latest news on AI SDK 4.2' --research`).\n3. Verify logs show 'Enabling Google Search Grounding'.\n4. Check if the task output incorporates recent information.\n5. Configure the same Google model as the 'main' model.\n6. Run a command *without* the `--research` flag.\n7. Verify logs *do not* show grounding being enabled.\n8. Add unit tests to `ai-services-unified.test.js` to verify the conditional logic for adding `providerOptions`. Ensure mocks correctly simulate different roles and providers.
|
||||
@@ -110,7 +110,8 @@
|
||||
4,
|
||||
2
|
||||
],
|
||||
"acceptanceCriteria": "- Detects changes in both task files and tasks.json\n- Determines which version is newer based on modification timestamps or content\n- Applies changes in the appropriate direction (file to JSON or JSON to file)\n- Handles edge cases like deleted files, new tasks, and renamed tasks\n- Provides options for manual conflict resolution when necessary\n- Maintains data integrity during the synchronization process\n- Includes a command to force synchronization in either direction\n- Logs all synchronization activities for troubleshooting\n\nEach of these subtasks addresses a specific component of the task file generation system, following a logical progression from template design to bidirectional synchronization. The dependencies ensure that prerequisites are completed before dependent work begins, and the acceptance criteria provide clear guidelines for verifying each subtask's completion."
|
||||
"acceptanceCriteria": "- Detects changes in both task files and tasks.json\n- Determines which version is newer based on modification timestamps or content\n- Applies changes in the appropriate direction (file to JSON or JSON to file)\n- Handles edge cases like deleted files, new tasks, and renamed tasks\n- Provides options for manual conflict resolution when necessary\n- Maintains data integrity during the synchronization process\n- Includes a command to force synchronization in either direction\n- Logs all synchronization activities for troubleshooting\n\nEach of these subtasks addresses a specific component of the task file generation system, following a logical progression from template design to bidirectional synchronization. The dependencies ensure that prerequisites are completed before dependent work begins, and the acceptance criteria provide clear guidelines for verifying each subtask's completion.",
|
||||
"details": "\n\n<info added on 2025-05-01T21:59:10.551Z>\n{\n \"id\": 5,\n \"title\": \"Implement Change Detection and Update Handling\",\n \"description\": \"Create a system to detect changes in task files and tasks.json, and handle updates bidirectionally. This includes implementing file watching or comparison mechanisms, determining which version is newer, and applying changes in the appropriate direction. Ensure the system handles edge cases like deleted files, new tasks, and conflicting changes.\",\n \"status\": \"done\",\n \"dependencies\": [\n 1,\n 3,\n 4,\n 2\n ],\n \"acceptanceCriteria\": \"- Detects changes in both task files and tasks.json\\n- Determines which version is newer based on modification timestamps or content\\n- Applies changes in the appropriate direction (file to JSON or JSON to file)\\n- Handles edge cases like deleted files, new tasks, and renamed tasks\\n- Provides options for manual conflict resolution when necessary\\n- Maintains data integrity during the synchronization process\\n- Includes a command to force synchronization in either direction\\n- Logs all synchronization activities for troubleshooting\\n\\nEach of these subtasks addresses a specific component of the task file generation system, following a logical progression from template design to bidirectional synchronization. The dependencies ensure that prerequisites are completed before dependent work begins, and the acceptance criteria provide clear guidelines for verifying each subtask's completion.\",\n \"details\": \"[2025-05-01 21:59:07] Adding another note via MCP test.\"\n}\n</info added on 2025-05-01T21:59:10.551Z>"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -3937,6 +3938,17 @@
|
||||
"parentTaskId": 74
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 75,
|
||||
"title": "Integrate Google Search Grounding for Research Role",
|
||||
"description": "Update the AI service layer to enable Google Search Grounding specifically when a Google model is used in the 'research' role.",
|
||||
"details": "**Goal:** Conditionally enable Google Search Grounding based on the AI role.\\n\\n**Implementation Plan:**\\n\\n1. **Modify `ai-services-unified.js`:** Update `generateTextService`, `streamTextService`, and `generateObjectService`.\\n2. **Conditional Logic:** Inside these functions, check if `providerName === 'google'` AND `role === 'research'`.\\n3. **Construct `providerOptions`:** If the condition is met, create an options object:\\n ```javascript\\n let providerSpecificOptions = {};\\n if (providerName === 'google' && role === 'research') {\\n log('info', 'Enabling Google Search Grounding for research role.');\\n providerSpecificOptions = {\\n google: {\\n useSearchGrounding: true,\\n // Optional: Add dynamic retrieval for compatible models\\n // dynamicRetrievalConfig: { mode: 'MODE_DYNAMIC' } \\n }\\n };\\n }\\n ```\\n4. **Pass Options to SDK:** Pass `providerSpecificOptions` to the Vercel AI SDK functions (`generateText`, `streamText`, `generateObject`) via the `providerOptions` parameter:\\n ```javascript\\n const { text, ... } = await generateText({\\n // ... other params\\n providerOptions: providerSpecificOptions \\n });\\n ```\\n5. **Update `supported-models.json`:** Ensure Google models intended for research (e.g., `gemini-1.5-pro-latest`, `gemini-1.5-flash-latest`) include `'research'` in their `allowed_roles` array.\\n\\n**Rationale:** This approach maintains the clear separation between 'main' and 'research' roles, ensuring grounding is only activated when explicitly requested via the `--research` flag or when the research model is invoked.",
|
||||
"testStrategy": "1. Configure a Google model (e.g., gemini-1.5-flash-latest) as the 'research' model in `.taskmasterconfig`.\\n2. Run a command with the `--research` flag (e.g., `task-master add-task --prompt='Latest news on AI SDK 4.2' --research`).\\n3. Verify logs show 'Enabling Google Search Grounding'.\\n4. Check if the task output incorporates recent information.\\n5. Configure the same Google model as the 'main' model.\\n6. Run a command *without* the `--research` flag.\\n7. Verify logs *do not* show grounding being enabled.\\n8. Add unit tests to `ai-services-unified.test.js` to verify the conditional logic for adding `providerOptions`. Ensure mocks correctly simulate different roles and providers.",
|
||||
"status": "pending",
|
||||
"dependencies": [],
|
||||
"priority": "medium",
|
||||
"subtasks": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -40,12 +40,14 @@ jest.unstable_mockModule('../../src/ai-providers/perplexity.js', () => ({
|
||||
|
||||
// ... Mock other providers (google, openai, etc.) similarly ...
|
||||
|
||||
// Mock utils logger and API key resolver
|
||||
// Mock utils logger, API key resolver, AND findProjectRoot
|
||||
const mockLog = jest.fn();
|
||||
const mockResolveEnvVariable = jest.fn();
|
||||
const mockFindProjectRoot = jest.fn();
|
||||
jest.unstable_mockModule('../../scripts/modules/utils.js', () => ({
|
||||
log: mockLog,
|
||||
resolveEnvVariable: mockResolveEnvVariable
|
||||
resolveEnvVariable: mockResolveEnvVariable,
|
||||
findProjectRoot: mockFindProjectRoot
|
||||
}));
|
||||
|
||||
// Import the module to test (AFTER mocks)
|
||||
@@ -54,6 +56,8 @@ const { generateTextService } = await import(
|
||||
);
|
||||
|
||||
describe('Unified AI Services', () => {
|
||||
const fakeProjectRoot = '/fake/project/root'; // Define for reuse
|
||||
|
||||
beforeEach(() => {
|
||||
// Clear mocks before each test
|
||||
jest.clearAllMocks(); // Clears all mocks
|
||||
@@ -76,6 +80,9 @@ describe('Unified AI Services', () => {
|
||||
if (key === 'PERPLEXITY_API_KEY') return 'mock-perplexity-key';
|
||||
return null;
|
||||
});
|
||||
|
||||
// Set a default behavior for the new mock
|
||||
mockFindProjectRoot.mockReturnValue(fakeProjectRoot);
|
||||
});
|
||||
|
||||
describe('generateTextService', () => {
|
||||
@@ -91,12 +98,16 @@ describe('Unified AI Services', () => {
|
||||
const result = await generateTextService(params);
|
||||
|
||||
expect(result).toBe('Main provider response');
|
||||
expect(mockGetMainProvider).toHaveBeenCalled();
|
||||
expect(mockGetMainModelId).toHaveBeenCalled();
|
||||
expect(mockGetParametersForRole).toHaveBeenCalledWith('main');
|
||||
expect(mockGetMainProvider).toHaveBeenCalledWith(fakeProjectRoot);
|
||||
expect(mockGetMainModelId).toHaveBeenCalledWith(fakeProjectRoot);
|
||||
expect(mockGetParametersForRole).toHaveBeenCalledWith(
|
||||
'main',
|
||||
fakeProjectRoot
|
||||
);
|
||||
expect(mockResolveEnvVariable).toHaveBeenCalledWith(
|
||||
'ANTHROPIC_API_KEY',
|
||||
params.session
|
||||
params.session,
|
||||
fakeProjectRoot
|
||||
);
|
||||
expect(mockGenerateAnthropicText).toHaveBeenCalledTimes(1);
|
||||
expect(mockGenerateAnthropicText).toHaveBeenCalledWith({
|
||||
@@ -109,26 +120,43 @@ describe('Unified AI Services', () => {
|
||||
{ role: 'user', content: 'Test' }
|
||||
]
|
||||
});
|
||||
// Verify other providers NOT called
|
||||
expect(mockGeneratePerplexityText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('should fall back to fallback provider if main fails', async () => {
|
||||
const mainError = new Error('Main provider failed');
|
||||
mockGenerateAnthropicText
|
||||
.mockRejectedValueOnce(mainError) // Main fails first
|
||||
.mockResolvedValueOnce('Fallback provider response'); // Fallback succeeds
|
||||
.mockRejectedValueOnce(mainError)
|
||||
.mockResolvedValueOnce('Fallback provider response');
|
||||
|
||||
const params = { role: 'main', prompt: 'Fallback test' };
|
||||
const explicitRoot = '/explicit/test/root';
|
||||
const params = {
|
||||
role: 'main',
|
||||
prompt: 'Fallback test',
|
||||
projectRoot: explicitRoot
|
||||
};
|
||||
const result = await generateTextService(params);
|
||||
|
||||
expect(result).toBe('Fallback provider response');
|
||||
expect(mockGetMainProvider).toHaveBeenCalled();
|
||||
expect(mockGetFallbackProvider).toHaveBeenCalled(); // Fallback was tried
|
||||
expect(mockGenerateAnthropicText).toHaveBeenCalledTimes(2); // Called for main (fail) and fallback (success)
|
||||
expect(mockGeneratePerplexityText).not.toHaveBeenCalled(); // Research not called
|
||||
expect(mockGetMainProvider).toHaveBeenCalledWith(explicitRoot);
|
||||
expect(mockGetFallbackProvider).toHaveBeenCalledWith(explicitRoot);
|
||||
expect(mockGetParametersForRole).toHaveBeenCalledWith(
|
||||
'main',
|
||||
explicitRoot
|
||||
);
|
||||
expect(mockGetParametersForRole).toHaveBeenCalledWith(
|
||||
'fallback',
|
||||
explicitRoot
|
||||
);
|
||||
|
||||
// Check log messages for fallback attempt
|
||||
expect(mockResolveEnvVariable).toHaveBeenCalledWith(
|
||||
'ANTHROPIC_API_KEY',
|
||||
undefined,
|
||||
explicitRoot
|
||||
);
|
||||
|
||||
expect(mockGenerateAnthropicText).toHaveBeenCalledTimes(2);
|
||||
expect(mockGeneratePerplexityText).not.toHaveBeenCalled();
|
||||
expect(mockLog).toHaveBeenCalledWith(
|
||||
'error',
|
||||
expect.stringContaining('Service call failed for role main')
|
||||
@@ -153,12 +181,40 @@ describe('Unified AI Services', () => {
|
||||
const result = await generateTextService(params);
|
||||
|
||||
expect(result).toBe('Research provider response');
|
||||
expect(mockGetMainProvider).toHaveBeenCalled();
|
||||
expect(mockGetFallbackProvider).toHaveBeenCalled();
|
||||
expect(mockGetResearchProvider).toHaveBeenCalled(); // Research was tried
|
||||
expect(mockGenerateAnthropicText).toHaveBeenCalledTimes(2); // main, fallback
|
||||
expect(mockGeneratePerplexityText).toHaveBeenCalledTimes(1); // research
|
||||
expect(mockGetMainProvider).toHaveBeenCalledWith(fakeProjectRoot);
|
||||
expect(mockGetFallbackProvider).toHaveBeenCalledWith(fakeProjectRoot);
|
||||
expect(mockGetResearchProvider).toHaveBeenCalledWith(fakeProjectRoot);
|
||||
expect(mockGetParametersForRole).toHaveBeenCalledWith(
|
||||
'main',
|
||||
fakeProjectRoot
|
||||
);
|
||||
expect(mockGetParametersForRole).toHaveBeenCalledWith(
|
||||
'fallback',
|
||||
fakeProjectRoot
|
||||
);
|
||||
expect(mockGetParametersForRole).toHaveBeenCalledWith(
|
||||
'research',
|
||||
fakeProjectRoot
|
||||
);
|
||||
|
||||
expect(mockResolveEnvVariable).toHaveBeenCalledWith(
|
||||
'ANTHROPIC_API_KEY',
|
||||
undefined,
|
||||
fakeProjectRoot
|
||||
);
|
||||
expect(mockResolveEnvVariable).toHaveBeenCalledWith(
|
||||
'ANTHROPIC_API_KEY',
|
||||
undefined,
|
||||
fakeProjectRoot
|
||||
);
|
||||
expect(mockResolveEnvVariable).toHaveBeenCalledWith(
|
||||
'PERPLEXITY_API_KEY',
|
||||
undefined,
|
||||
fakeProjectRoot
|
||||
);
|
||||
|
||||
expect(mockGenerateAnthropicText).toHaveBeenCalledTimes(2);
|
||||
expect(mockGeneratePerplexityText).toHaveBeenCalledTimes(1);
|
||||
expect(mockLog).toHaveBeenCalledWith(
|
||||
'error',
|
||||
expect.stringContaining('Service call failed for role fallback')
|
||||
@@ -204,6 +260,23 @@ describe('Unified AI Services', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('should use default project root or handle null if findProjectRoot returns null', async () => {
|
||||
mockFindProjectRoot.mockReturnValue(null); // Simulate not finding root
|
||||
mockGenerateAnthropicText.mockResolvedValue('Response with no root');
|
||||
|
||||
const params = { role: 'main', prompt: 'No root test' }; // No explicit root passed
|
||||
await generateTextService(params);
|
||||
|
||||
expect(mockGetMainProvider).toHaveBeenCalledWith(null);
|
||||
expect(mockGetParametersForRole).toHaveBeenCalledWith('main', null);
|
||||
expect(mockResolveEnvVariable).toHaveBeenCalledWith(
|
||||
'ANTHROPIC_API_KEY',
|
||||
undefined,
|
||||
null
|
||||
);
|
||||
expect(mockGenerateAnthropicText).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Add more tests for edge cases:
|
||||
// - Missing API keys (should throw from _resolveApiKey)
|
||||
// - Unsupported provider configured (should skip and log)
|
||||
|
||||
Reference in New Issue
Block a user