@hivetechs/hive-ai
Version:
Real-time streaming AI consensus platform with HTTP+SSE MCP integration for Claude Code, VS Code, Cursor, and Windsurf - powered by OpenRouter's unified API
271 lines ⢠12.9 kB
JavaScript
/**
* Template Maintenance CLI Tool
*
* Provides CLI commands for managing Expert Profile Template health
*/
import { z } from "zod";
export const TemplateMaintenanceToolSchema = z.object({
action: z.enum(['check', 'fix', 'status', 'force-update']).describe('Action to perform'),
template_id: z.string().optional().describe('Specific template ID to check/fix (optional)'),
dry_run: z.boolean().optional().default(false).describe('Show what would be done without making changes')
});
export async function runTemplateMaintenanceTool(args) {
const { action, template_id, dry_run } = args;
try {
const { TemplateMaintenanceManager } = await import('./template-maintenance.js');
const manager = new TemplateMaintenanceManager();
switch (action) {
case 'check':
return await handleCheckAction(manager, template_id);
case 'fix':
return await handleFixAction(manager, template_id, dry_run);
case 'status':
return await handleStatusAction(manager);
case 'force-update':
return await handleForceUpdateAction(manager, dry_run);
default:
return {
result: `ā Unknown action: ${action}\n\nSupported actions: check, fix, status, force-update`
};
}
}
catch (error) {
return {
result: `ā Template maintenance failed: ${error instanceof Error ? error.message : 'Unknown error'}`
};
}
}
async function handleCheckAction(manager, templateId) {
let result = 'š **Template Health Check**\n\n';
if (templateId) {
// Check specific template
const { getTemplateById } = await import('./expert-profile-templates.js');
const template = getTemplateById(templateId);
if (!template) {
return {
result: `ā Template not found: ${templateId}\n\nUse 'hive-ai templates list' to see available templates`
};
}
const report = await manager.validateTemplate(template);
result += `**${report.templateName}** (${report.templateId})\n`;
result += `Status: ${report.isHealthy ? 'ā
Healthy' : 'ā ļø Issues Found'}\n\n`;
if (!report.isHealthy) {
result += '**Issues:**\n';
report.issues.forEach((issue) => {
result += `⢠${issue}\n`;
});
result += '\n';
if (report.suggestions.length > 0) {
result += '**Suggested Fixes:**\n';
report.suggestions.forEach((suggestion) => {
result += `⢠**${suggestion.stage}**: ${suggestion.currentModel} ā ${suggestion.suggestedModel}\n`;
result += ` Reason: ${suggestion.reason} (${(suggestion.confidence * 100).toFixed(0)}% confidence)\n`;
});
result += '\n';
}
}
result += `Last checked: ${new Date(report.lastChecked).toLocaleString()}`;
}
else {
// Check all templates
const reports = await manager.validateAllTemplates();
const healthyCount = reports.filter((r) => r.isHealthy).length;
const totalCount = reports.length;
result += `**Overall Status:** ${healthyCount}/${totalCount} templates healthy\n\n`;
// Show summary
reports.forEach((report) => {
const status = report.isHealthy ? 'ā
' : 'ā ļø';
const issueCount = report.issues.length;
const suggestionCount = report.suggestions.length;
result += `${status} **${report.templateName}**`;
if (!report.isHealthy) {
result += ` (${issueCount} issue${issueCount !== 1 ? 's' : ''}, ${suggestionCount} suggestion${suggestionCount !== 1 ? 's' : ''})`;
}
result += '\n';
});
const unhealthyTemplates = reports.filter((r) => !r.isHealthy);
if (unhealthyTemplates.length > 0) {
result += '\n**Next Steps:**\n';
result += '⢠Run `hive-ai templates fix` to apply suggested fixes\n';
result += '⢠Run `hive-ai templates check <template-id>` for detailed analysis\n';
result += '⢠Run `hive-ai models update` to refresh model data first';
}
}
return { result };
}
async function handleFixAction(manager, templateId, dryRun) {
let result = `š§ **Template ${dryRun ? 'Fix Preview' : 'Fix'}**\n\n`;
if (dryRun) {
result += 'ā ļø **DRY RUN MODE** - No changes will be made\n\n';
}
if (templateId) {
// Fix specific template
const { getTemplateById } = await import('./expert-profile-templates.js');
const template = getTemplateById(templateId);
if (!template) {
return {
result: `ā Template not found: ${templateId}`
};
}
const report = await manager.validateTemplate(template);
result += `**${report.templateName}** (${report.templateId})\n\n`;
if (report.isHealthy) {
result += 'ā
Template is already healthy - no fixes needed';
return { result };
}
if (report.suggestions.length === 0) {
result += 'ā ļø Issues found but no automatic fixes available:\n';
report.issues.forEach((issue) => {
result += `⢠${issue}\n`;
});
result += '\nTry running `hive-ai models update` first';
return { result };
}
result += '**Applying fixes:**\n';
report.suggestions.forEach((suggestion) => {
result += `⢠**${suggestion.stage}**: ${suggestion.currentModel} ā ${suggestion.suggestedModel}\n`;
result += ` Reason: ${suggestion.reason}\n`;
});
if (!dryRun) {
try {
await manager.applyTemplateSuggestions(templateId, report.suggestions);
result += '\nā
Fixes applied successfully';
}
catch (error) {
result += `\nā Failed to apply fixes: ${error instanceof Error ? error.message : 'Unknown error'}`;
}
}
}
else {
// Fix all templates
const reports = await manager.validateAllTemplates();
const unhealthyTemplates = reports.filter((r) => !r.isHealthy);
if (unhealthyTemplates.length === 0) {
result += 'ā
All templates are healthy - no fixes needed';
return { result };
}
result += `Found ${unhealthyTemplates.length} template${unhealthyTemplates.length !== 1 ? 's' : ''} needing fixes:\n\n`;
for (const report of unhealthyTemplates) {
result += `**${report.templateName}**:\n`;
if (report.suggestions.length === 0) {
result += '⢠No automatic fixes available\n';
continue;
}
report.suggestions.forEach((suggestion) => {
result += `⢠${suggestion.stage}: ${suggestion.currentModel} ā ${suggestion.suggestedModel}\n`;
});
if (!dryRun) {
try {
await manager.applyTemplateSuggestions(report.templateId, report.suggestions);
result += ' ā
Applied\n';
}
catch (error) {
result += ` ā Failed: ${error instanceof Error ? error.message : 'Unknown error'}\n`;
}
}
result += '\n';
}
if (dryRun) {
result += '**To apply these fixes, run:** `hive-ai templates fix`';
}
}
return { result };
}
async function handleStatusAction(manager) {
let result = 'š **Template Maintenance Status**\n\n';
try {
const { getConfig } = await import('../../storage/unified-database.js');
const lastMaintenanceStr = await getConfig('last_template_maintenance');
if (!lastMaintenanceStr) {
result += 'ā ļø **Never run** - Template maintenance has never been executed\n\n';
result += '**Recommended actions:**\n';
result += '⢠Run `hive-ai templates check` to validate templates\n';
result += '⢠Run `hive-ai models update` to sync latest model data\n';
result += '⢠Setup automatic maintenance with `hive-ai templates force-update`';
return { result };
}
const maintenanceData = JSON.parse(lastMaintenanceStr);
const lastRun = new Date(maintenanceData.timestamp);
const now = new Date();
const hoursSinceLastRun = Math.floor((now.getTime() - lastRun.getTime()) / (1000 * 60 * 60));
result += `**Last maintenance:** ${lastRun.toLocaleString()}\n`;
result += `**Time since last run:** ${hoursSinceLastRun} hours ago\n`;
result += `**Templates checked:** ${maintenanceData.templateCount}\n`;
result += `**Healthy templates:** ${maintenanceData.healthyCount}/${maintenanceData.templateCount}\n\n`;
const isDue = await manager.isMaintenanceDue();
result += `**Status:** ${isDue ? 'ā ļø Maintenance Due' : 'ā
Up to Date'}\n\n`;
if (maintenanceData.reports) {
result += '**Template Summary:**\n';
maintenanceData.reports.forEach((report) => {
const status = report.isHealthy ? 'ā
' : 'ā ļø';
result += `${status} ${report.templateName}`;
if (!report.isHealthy) {
result += ` (${report.issueCount} issue${report.issueCount !== 1 ? 's' : ''})`;
}
result += '\n';
});
}
if (isDue) {
result += '\n**Recommended actions:**\n';
result += '⢠Run `hive-ai templates check` for current status\n';
result += '⢠Run `hive-ai templates force-update` to update now';
}
}
catch (error) {
result += `ā Error reading maintenance status: ${error instanceof Error ? error.message : 'Unknown error'}`;
}
return { result };
}
async function handleForceUpdateAction(manager, dryRun) {
let result = `š **Force Template ${dryRun ? 'Update Preview' : 'Update'}**\n\n`;
if (dryRun) {
result += 'ā ļø **DRY RUN MODE** - No changes will be made\n\n';
}
try {
result += 'š Running comprehensive template maintenance...\n\n';
if (!dryRun) {
await manager.runMaintenanceCheck();
result += 'ā
**Template maintenance completed successfully**\n\n';
}
else {
// Simulate what would happen
const reports = await manager.validateAllTemplates();
const unhealthyCount = reports.filter((r) => !r.isHealthy).length;
result += `**Would check:** ${reports.length} templates\n`;
result += `**Would fix:** ${unhealthyCount} unhealthy templates\n`;
result += `**Would migrate:** User profiles with outdated models\n\n`;
if (unhealthyCount > 0) {
result += '**Templates that would be updated:**\n';
reports.filter((r) => !r.isHealthy).forEach((report) => {
result += `⢠${report.templateName} (${report.suggestions.length} suggestion${report.suggestions.length !== 1 ? 's' : ''})\n`;
});
result += '\n';
}
}
// Show status after update
const { getConfig } = await import('../../storage/unified-database.js');
const statusData = await getConfig('last_template_maintenance');
if (statusData) {
const data = JSON.parse(statusData);
result += `**Results:**\n`;
result += `⢠Templates checked: ${data.templateCount}\n`;
result += `⢠Healthy templates: ${data.healthyCount}/${data.templateCount}\n`;
result += `⢠Maintenance completed: ${new Date(data.timestamp).toLocaleString()}\n\n`;
}
result += '**Next steps:**\n';
result += '⢠Templates will be automatically checked every 24 hours\n';
result += '⢠Run `hive-ai templates status` to check maintenance status\n';
result += '⢠User profiles are automatically migrated when models change';
if (dryRun) {
result += '\n\n**To apply changes, run:** `hive-ai templates force-update`';
}
}
catch (error) {
result += `ā Force update failed: ${error instanceof Error ? error.message : 'Unknown error'}`;
}
return { result };
}
// Tool exports
export const templateMaintenanceToolName = 'template_maintenance';
export const templateMaintenanceToolDescription = 'Maintain Expert Profile Template health and currency';
//# sourceMappingURL=template-maintenance-tool.js.map