mcp-product-manager
Version:
MCP Orchestrator for task and project management with web interface
271 lines (254 loc) • 9.21 kB
JavaScript
// modeAwareness.js - Middleware to enforce project mode compliance
import { get } from '../utils/database.js';
// Check if a task aligns with the current project mode
async function isTaskAlignedWithMode(task, mode, modeScore = null) {
// If we have a pre-calculated mode score, use it
if (modeScore !== null) {
return modeScore >= 0.5; // Aligned if score is 0.5 or higher
}
// Otherwise, check based on mode rules
const rules = {
prod_push: {
aligned: ['bug', 'test', 'critical'],
keywords: ['fix', 'crash', 'error', 'failing', 'broken', 'security', 'performance'],
priority: ['critical', 'high']
},
feature_expansion: {
aligned: ['feature', 'enhancement'],
keywords: ['add', 'implement', 'create', 'new', 'enhance', 'extend'],
priority: ['high', 'medium']
},
exploratory: {
aligned: ['research', 'prototype', 'experiment'],
keywords: ['explore', 'investigate', 'research', 'prototype', 'poc', 'test'],
priority: ['medium', 'low']
},
maintenance: {
aligned: ['refactor', 'docs', 'cleanup'],
keywords: ['refactor', 'clean', 'document', 'organize', 'optimize', 'technical debt'],
priority: ['medium', 'low']
}
};
const modeRules = rules[mode];
if (!modeRules)
return true; // No rules = aligned by default
// Check category alignment
if (task.category && modeRules.aligned.includes(task.category)) {
return true;
}
// Check keyword alignment
const descLower = (task.description || '').toLowerCase();
if (modeRules.keywords.some(keyword => descLower.includes(keyword))) {
return true;
}
// Check priority alignment
if (task.priority && modeRules.priority.includes(task.priority)) {
return true;
}
return false;
}
// Middleware to add mode context to all project-related requests
export async function projectModeMiddleware(req, res, next) {
const projectName = req.params.project || req.body?.project || req.query?.project;
if (!projectName) {
return next();
}
try {
// Get current project mode
const projectMode = await get('SELECT mode, mode_config FROM project_modes WHERE project = ?', [projectName]);
if (projectMode) {
req.projectMode = {
mode: projectMode.mode,
config: projectMode.mode_config ? JSON.parse(projectMode.mode_config) : {}
};
}
else {
req.projectMode = {
mode: 'none',
config: {}
};
}
next();
}
catch (err) {
console.error('Error in project mode middleware:', err);
next(); // Continue even if mode check fails
}
}
// Middleware to enforce mode compliance on task operations
export async function taskModeComplianceMiddleware(req, res, next) {
// Only enforce on specific endpoints
const enforcedPaths = [
'/api/tasks/claim',
'/api/tasks/create',
'/api/tasks/:id/status'
];
const isEnforcedPath = enforcedPaths.some(path => req.path.match(new RegExp(path.replace(':id', '[^/]+'))));
if (!isEnforcedPath || !req.projectMode || req.projectMode.mode === 'none') {
return next();
}
// Add mode compliance info to request
req.modeCompliance = {
mode: req.projectMode.mode,
enforced: true,
warnings: []
};
next();
}
// Function to add mode warnings to task details
export async function addModeWarningsToTask(task, projectMode) {
if (!projectMode || projectMode.mode === 'none') {
return task;
}
const aligned = await isTaskAlignedWithMode(task, projectMode.mode, task.mode_score);
if (!aligned) {
task.mode_warning = {
message: `This task may not align with current ${projectMode.mode} mode`,
mode: projectMode.mode,
score: task.mode_score || 'not calculated',
recommendation: getModeRecommendation(task, projectMode.mode)
};
}
return task;
}
// Get recommendation based on mode and task
function getModeRecommendation(task, mode) {
const recommendations = {
prod_push: {
default: 'Consider deferring unless it fixes a bug or improves stability',
high_priority: 'Review if this is truly critical for production',
feature: 'Defer feature work until after production push'
},
feature_expansion: {
default: 'Focus on user-facing features and enhancements',
bug: 'Only fix bugs that block feature development',
refactor: 'Defer refactoring unless it enables new features'
},
exploratory: {
default: 'Ensure this explores new possibilities or validates concepts',
bug: 'Only fix bugs that block exploration',
critical: 'Re-evaluate if this is truly critical in exploratory mode'
},
maintenance: {
default: 'Focus on code quality and technical debt reduction',
feature: 'Defer new features during maintenance mode',
critical: 'Address critical issues but maintain focus on cleanup'
}
};
const modeRecs = recommendations[mode];
if (!modeRecs)
return 'Review task alignment with current mode';
// Return specific recommendation based on task properties
if (task.priority === 'critical' && modeRecs.critical) {
return modeRecs.critical;
}
if (task.category === 'feature' && modeRecs.feature) {
return modeRecs.feature;
}
if (task.category === 'bug' && modeRecs.bug) {
return modeRecs.bug;
}
if (task.category === 'refactor' && modeRecs.refactor) {
return modeRecs.refactor;
}
return modeRecs.default;
}
// Function to filter tasks by mode alignment
export async function filterTasksByMode(tasks, mode, includeWarnings = false) {
const filtered = [];
for (const task of tasks) {
const aligned = await isTaskAlignedWithMode(task, mode, task.mode_score);
if (aligned || includeWarnings) {
if (!aligned && includeWarnings) {
task.mode_warning = {
message: `May not align with ${mode} mode`,
mode: mode,
score: task.mode_score || 'not calculated'
};
}
filtered.push(task);
}
}
return filtered;
}
// Agent instruction generator for mode compliance
export function generateModeInstructions(mode) {
const instructions = {
prod_push: `
## CRITICAL: Production Push Mode Active
You are working in PRODUCTION PUSH mode. Your PRIMARY directive is to ensure system stability and reliability.
**MANDATORY ACTIONS:**
1. ONLY work on tasks that directly support production readiness:
- Bug fixes (especially critical/high priority)
- Test failures and test coverage
- Performance issues
- Security vulnerabilities
- Stability improvements
2. DEFER or SKIP tasks that are:
- New features
- Refactoring (unless fixing bugs)
- Documentation (unless critical)
- Exploratory work
3. When you encounter a non-aligned task:
- Add a comment: "DEFERRED: Not aligned with prod_push mode"
- Move to the next task
- Do NOT spend time on it
**Your success is measured by bugs fixed and tests passing, not features added.**
`,
feature_expansion: `
## Feature Expansion Mode Active
You are working in FEATURE EXPANSION mode. Focus on adding value through new capabilities.
**PRIORITIES:**
1. New feature implementation
2. Feature enhancements
3. User-facing improvements
4. Integration of new capabilities
**DEFER:**
- Non-blocking bugs
- Refactoring without feature benefit
- Pure technical debt
- Documentation (unless for new features)
**When encountering maintenance tasks, evaluate if they enable feature work.**
`,
exploratory: `
## Exploratory Mode Active
You are in EXPLORATORY mode. Focus on research, prototypes, and validation.
**PRIORITIES:**
1. Proof of concepts
2. Technology evaluation
3. Architectural exploration
4. Research tasks
**APPROACH:**
- Prioritize learning over perfection
- Document findings thoroughly
- Create minimal viable prototypes
- Don't over-engineer solutions
**Skip detailed implementation unless validating a concept.**
`,
maintenance: `
## Maintenance Mode Active
You are in MAINTENANCE mode. Focus on code quality and sustainability.
**PRIORITIES:**
1. Code refactoring
2. Technical debt reduction
3. Documentation updates
4. Test improvements
5. Performance optimization
**DEFER:**
- New features (unless trivial)
- Major architectural changes
- Exploratory work
**Focus on leaving the codebase better than you found it.**
`
};
return instructions[mode] || '';
}
export default {
projectModeMiddleware,
taskModeComplianceMiddleware,
addModeWarningsToTask,
filterTasksByMode,
generateModeInstructions,
isTaskAlignedWithMode
};
//# sourceMappingURL=modeAwareness.js.map