UNPKG

@intellectronica/ruler

Version:

Ruler — apply the same rules to all coding agents

206 lines (205 loc) 8.21 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.FirebenderAgent = void 0; const path = __importStar(require("path")); const fs = __importStar(require("fs")); const FileSystemUtils_1 = require("../core/FileSystemUtils"); /** * Firebender agent adapter. */ class FirebenderAgent { /** * Type guard function to safely check if an object is a FirebenderRule. */ isFirebenderRule(rule) { return (typeof rule === 'object' && rule !== null && 'filePathMatches' in rule && 'rulesPaths' in rule && typeof rule.filePathMatches === 'string' && typeof rule.rulesPaths === 'string'); } getIdentifier() { return 'firebender'; } getName() { return 'Firebender'; } async applyRulerConfig(concatenatedRules, projectRoot, rulerMcpJson, agentConfig, backup = true) { const rulesPath = this.resolveOutputPath(projectRoot, agentConfig); await (0, FileSystemUtils_1.ensureDirExists)(path.dirname(rulesPath)); const firebenderConfig = await this.loadExistingConfig(rulesPath); const newRules = this.createRulesFromConcatenatedRules(concatenatedRules, projectRoot); firebenderConfig.rules.push(...newRules); this.removeDuplicateRules(firebenderConfig); const mcpEnabled = agentConfig?.mcp?.enabled ?? true; if (mcpEnabled && rulerMcpJson) { await this.handleMcpConfiguration(firebenderConfig, rulerMcpJson, agentConfig); } await this.saveConfig(rulesPath, firebenderConfig, backup); } resolveOutputPath(projectRoot, agentConfig) { const outputPaths = this.getDefaultOutputPath(projectRoot); const output = agentConfig?.outputPath ?? agentConfig?.outputPathInstructions ?? outputPaths['instructions']; return path.resolve(projectRoot, output); } async loadExistingConfig(rulesPath) { try { const existingContent = await fs.promises.readFile(rulesPath, 'utf8'); const config = JSON.parse(existingContent); if (!config.rules) { config.rules = []; } return config; } catch (error) { if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') { return { rules: [] }; } console.warn(`Failed to read/parse existing firebender.json: ${error}`); return { rules: [] }; } } createRulesFromConcatenatedRules(concatenatedRules, projectRoot) { const filePaths = this.extractFilePathsFromRules(concatenatedRules, projectRoot); if (filePaths.length > 0) { return this.createRuleObjectsFromFilePaths(filePaths); } else { return this.createRulesFromPlainText(concatenatedRules); } } createRuleObjectsFromFilePaths(filePaths) { return filePaths.map((filePath) => ({ filePathMatches: '**/*', rulesPaths: filePath, })); } createRulesFromPlainText(concatenatedRules) { return concatenatedRules.split('\n').filter((rule) => rule.trim()); } removeDuplicateRules(firebenderConfig) { const seen = new Set(); firebenderConfig.rules = firebenderConfig.rules.filter((rule) => { let key; if (this.isFirebenderRule(rule)) { const filePathMatchesPart = rule.filePathMatches; const rulesPathsPart = rule.rulesPaths; key = `${filePathMatchesPart}::${rulesPathsPart}`; } else { key = String(rule); } if (seen.has(key)) { return false; } seen.add(key); return true; }); } async saveConfig(rulesPath, config, backup) { const updatedContent = JSON.stringify(config, null, 2); if (backup) { await (0, FileSystemUtils_1.backupFile)(rulesPath); } await (0, FileSystemUtils_1.writeGeneratedFile)(rulesPath, updatedContent); } /** * Handle MCP server configuration for Firebender. * Merges or overwrites MCP servers in the firebender.json configuration based on strategy. */ async handleMcpConfiguration(firebenderConfig, rulerMcpJson, agentConfig) { const strategy = agentConfig?.mcp?.strategy ?? 'merge'; const incomingServers = rulerMcpJson.mcpServers || {}; if (!firebenderConfig.mcpServers) { firebenderConfig.mcpServers = {}; } if (strategy === 'overwrite') { firebenderConfig.mcpServers = { ...incomingServers }; } else if (strategy === 'merge') { const existingServers = firebenderConfig.mcpServers || {}; firebenderConfig.mcpServers = { ...existingServers, ...incomingServers }; } } getDefaultOutputPath(projectRoot) { return { instructions: path.join(projectRoot, 'firebender.json'), mcp: path.join(projectRoot, 'firebender.json'), }; } getMcpServerKey() { return 'mcpServers'; } supportsMcpStdio() { return true; } supportsMcpRemote() { return true; } /** * Extracts file paths from concatenated rules by parsing HTML source comments. * @param concatenatedRules The concatenated rules string with HTML comments * @param projectRoot The project root directory * @returns Array of file paths relative to project root */ extractFilePathsFromRules(concatenatedRules, projectRoot) { const sourceCommentRegex = /<!-- Source: (.+?) -->/g; const filePaths = []; let match; while ((match = sourceCommentRegex.exec(concatenatedRules)) !== null) { const relativePath = match[1]; const absolutePath = path.resolve(projectRoot, relativePath); const normalizedProjectRoot = path.resolve(projectRoot); // Ensure the absolutePath is within the project root (cross-platform compatible) // This prevents path traversal attacks while handling Windows/Unix path differences const isWithinProject = absolutePath.startsWith(normalizedProjectRoot) && (absolutePath.length === normalizedProjectRoot.length || absolutePath[normalizedProjectRoot.length] === path.sep); if (isWithinProject) { const projectRelativePath = path.relative(projectRoot, absolutePath); filePaths.push(projectRelativePath); } } return filePaths; } } exports.FirebenderAgent = FirebenderAgent;