workflow-agent-cli 2.13.1 → 2.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -338,6 +338,8 @@ var WORKFLOW_SCRIPTS = {
|
|
|
338
338
|
"workflow:learn:apply": "workflow-agent learn:apply",
|
|
339
339
|
"workflow:learn:publish": "workflow-agent learn:publish",
|
|
340
340
|
"workflow:learn:sync": "workflow-agent learn:sync",
|
|
341
|
+
"workflow:learn:sync:push": "workflow-agent learn:sync --push",
|
|
342
|
+
"workflow:learn:sync:pull": "workflow-agent learn:sync --pull",
|
|
341
343
|
"workflow:learn:config": "workflow-agent learn:config",
|
|
342
344
|
"workflow:learn:deprecate": "workflow-agent learn:deprecate",
|
|
343
345
|
"workflow:learn:stats": "workflow-agent learn:stats",
|
|
@@ -387,6 +389,8 @@ var SCRIPT_CATEGORIES = {
|
|
|
387
389
|
"workflow:learn:apply",
|
|
388
390
|
"workflow:learn:publish",
|
|
389
391
|
"workflow:learn:sync",
|
|
392
|
+
"workflow:learn:sync:push",
|
|
393
|
+
"workflow:learn:sync:pull",
|
|
390
394
|
"workflow:learn:config",
|
|
391
395
|
"workflow:learn:deprecate",
|
|
392
396
|
"workflow:learn:stats"
|
|
@@ -701,4 +705,4 @@ export {
|
|
|
701
705
|
installMandatoryTemplates,
|
|
702
706
|
updateTemplates
|
|
703
707
|
};
|
|
704
|
-
//# sourceMappingURL=chunk-
|
|
708
|
+
//# sourceMappingURL=chunk-Q2B25XH2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/scripts/copilot-instructions-generator.ts","../src/scripts/workflow-scripts.ts","../src/scripts/template-installer.ts","../src/templates/metadata.ts"],"sourcesContent":["/**\n * Copilot Instructions Generator\n *\n * Generates .github/copilot-instructions.md from the project's guidelines directory.\n * This file serves as the Single Source of Truth for AI agents (GitHub Copilot, Claude, etc.)\n * when working on the codebase.\n *\n * Features:\n * - Reads all markdown files from guidelines/\n * - Extracts key rules and summaries from each guideline\n * - Loads project config from workflow.config.json\n * - Preserves custom user content between markers\n * - Provides links to full guideline documents\n */\n\nimport { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync } from \"fs\";\nimport { join, basename } from \"path\";\n\n// Markers for custom user content that should be preserved on regeneration\nconst CUSTOM_START_MARKER = \"<!-- CUSTOM START -->\";\nconst CUSTOM_END_MARKER = \"<!-- CUSTOM END -->\";\nconst GENERATED_MARKER = \"<!-- AUTO-GENERATED BY WORKFLOW-AGENT - DO NOT EDIT ABOVE THIS LINE -->\";\n\ninterface WorkflowConfig {\n projectName?: string;\n scopes?: Array<{ name: string; description: string; emoji?: string }>;\n enforcement?: string;\n language?: string;\n}\n\ninterface GuidelineSummary {\n filename: string;\n title: string;\n description: string;\n keyRules: string[];\n}\n\n/**\n * Extract title from markdown content (first H1)\n */\nfunction extractTitle(content: string): string {\n const match = content.match(/^#\\s+(.+)$/m);\n return match ? match[1].trim() : \"Untitled\";\n}\n\n/**\n * Extract description from markdown content (first paragraph after title)\n */\nfunction extractDescription(content: string): string {\n // Look for content after the first heading, before the next heading or section\n const lines = content.split(\"\\n\");\n let foundTitle = false;\n let description = \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"# \")) {\n foundTitle = true;\n continue;\n }\n if (foundTitle) {\n // Skip empty lines and blockquotes at start\n if (line.trim() === \"\" || line.startsWith(\">\")) {\n if (description) break; // End if we already have content\n continue;\n }\n // Stop at next heading or horizontal rule\n if (line.startsWith(\"#\") || line.startsWith(\"---\") || line.startsWith(\"##\")) {\n break;\n }\n description += line.trim() + \" \";\n // Take only first meaningful paragraph\n if (description.length > 150) break;\n }\n }\n\n return description.trim().slice(0, 200) + (description.length > 200 ? \"...\" : \"\");\n}\n\n/**\n * Extract key rules from markdown content\n * Looks for lists, bold text, and important patterns\n */\nfunction extractKeyRules(content: string, maxRules: number = 5): string[] {\n const rules: string[] = [];\n\n // Pattern 1: Look for \"MUST\", \"NEVER\", \"ALWAYS\", \"REQUIRED\" in bold or emphasized\n const emphasisPatterns = [\n /\\*\\*(?:MUST|NEVER|ALWAYS|REQUIRED)[^*]+\\*\\*/gi,\n /(?:^|\\n)\\s*[-*]\\s+\\*\\*[^*]+\\*\\*/gm,\n ];\n\n for (const pattern of emphasisPatterns) {\n const matches = content.match(pattern);\n if (matches) {\n for (const match of matches.slice(0, 2)) {\n const cleaned = match.replace(/\\*\\*/g, \"\").replace(/^[-*]\\s*/, \"\").trim();\n if (cleaned.length > 10 && cleaned.length < 150 && !rules.includes(cleaned)) {\n rules.push(cleaned);\n }\n }\n }\n }\n\n // Pattern 2: Look for numbered or bulleted rules under headings containing \"Rules\", \"Requirements\", \"Guidelines\"\n const rulesSectionMatch = content.match(/##\\s+(?:.*(?:Rules?|Requirements?|Guidelines?|Standards?)[^\\n]*)\\n([\\s\\S]*?)(?=\\n##|\\n#|$)/i);\n if (rulesSectionMatch) {\n const section = rulesSectionMatch[1];\n const listItems = section.match(/^\\s*[-*\\d.]+\\s+(.+)$/gm);\n if (listItems) {\n for (const item of listItems.slice(0, 3)) {\n const cleaned = item.replace(/^[-*\\d.]+\\s*/, \"\").trim();\n if (cleaned.length > 10 && cleaned.length < 150 && !rules.includes(cleaned)) {\n rules.push(cleaned);\n }\n }\n }\n }\n\n // Pattern 3: Look for key points under \"Important\", \"Critical\", \"Key\"\n const importantMatch = content.match(/(?:Important|Critical|Key|Essential)[:\\s]+([^\\n]+)/gi);\n if (importantMatch) {\n for (const match of importantMatch.slice(0, 2)) {\n const cleaned = match.replace(/^(?:Important|Critical|Key|Essential)[:\\s]+/i, \"\").trim();\n if (cleaned.length > 10 && cleaned.length < 150 && !rules.includes(cleaned)) {\n rules.push(cleaned);\n }\n }\n }\n\n // Fallback: Get first few list items if we don't have enough rules\n if (rules.length < 2) {\n const listItems = content.match(/^\\s*[-*]\\s+(.+)$/gm);\n if (listItems) {\n for (const item of listItems.slice(0, 3)) {\n const cleaned = item.replace(/^[-*]\\s*/, \"\").trim();\n if (cleaned.length > 15 && cleaned.length < 150 && !rules.includes(cleaned)) {\n rules.push(cleaned);\n }\n }\n }\n }\n\n return rules.slice(0, maxRules);\n}\n\n/**\n * Parse a guideline markdown file and extract summary\n */\nfunction parseGuideline(filePath: string): GuidelineSummary | null {\n try {\n const content = readFileSync(filePath, \"utf-8\");\n const filename = basename(filePath);\n\n // Skip template example and non-guideline files\n if (filename.startsWith(\"_\") || filename === \"Guidelines.md\") {\n return null;\n }\n\n return {\n filename,\n title: extractTitle(content),\n description: extractDescription(content),\n keyRules: extractKeyRules(content),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Load workflow config from project root\n */\nfunction loadWorkflowConfig(projectRoot: string): WorkflowConfig | null {\n const configPath = join(projectRoot, \"workflow.config.json\");\n if (!existsSync(configPath)) {\n return null;\n }\n\n try {\n const content = readFileSync(configPath, \"utf-8\");\n return JSON.parse(content) as WorkflowConfig;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract preserved custom content from existing file\n */\nfunction extractCustomContent(existingContent: string): string | null {\n const startIndex = existingContent.indexOf(CUSTOM_START_MARKER);\n const endIndex = existingContent.indexOf(CUSTOM_END_MARKER);\n\n if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {\n return existingContent.slice(\n startIndex + CUSTOM_START_MARKER.length,\n endIndex\n ).trim();\n }\n\n return null;\n}\n\n/**\n * Generate the copilot-instructions.md content\n */\nfunction generateInstructionsContent(\n config: WorkflowConfig | null,\n guidelines: GuidelineSummary[],\n customContent: string | null\n): string {\n const projectName = config?.projectName || \"this project\";\n const scopes = config?.scopes || [];\n\n let content = `# Copilot Instructions for ${projectName}\n\n> **This file is the Single Source of Truth for AI agents working on this codebase.**\n> It is auto-generated from the \\`guidelines/\\` directory by workflow-agent-cli.\n> Last generated: ${new Date().toISOString().split(\"T\")[0]}\n\n${GENERATED_MARKER}\n\n## Project Overview\n\n`;\n\n if (config) {\n content += `- **Project Name**: ${projectName}\\n`;\n content += `- **Enforcement Level**: ${config.enforcement || \"strict\"}\\n`;\n if (scopes.length > 0) {\n content += `- **Available Scopes**: ${scopes.map(s => `\\`${s.name}\\``).join(\", \")}\\n`;\n }\n content += \"\\n\";\n }\n\n // Add scope reference if available\n if (scopes.length > 0) {\n content += `### Valid Scopes for Commits and Branches\n\n| Scope | Description |\n|-------|-------------|\n`;\n for (const scope of scopes.slice(0, 15)) {\n content += `| \\`${scope.name}\\` | ${scope.description} |\\n`;\n }\n if (scopes.length > 15) {\n content += `| ... | See workflow.config.json for all ${scopes.length} scopes |\\n`;\n }\n content += \"\\n\";\n }\n\n // Add guidelines summaries\n if (guidelines.length > 0) {\n content += `## Guidelines Summary\n\nThe following guidelines govern development on this project. **Read the linked documents for full details.**\n\n`;\n\n // Group by importance (mandatory templates first)\n const mandatoryFiles = [\n \"AGENT_EDITING_INSTRUCTIONS.md\",\n \"BRANCHING_STRATEGY.md\",\n \"TESTING_STRATEGY.md\",\n \"SINGLE_SOURCE_OF_TRUTH.md\",\n \"PATTERN_ANALYSIS_WORKFLOW.md\",\n \"SELF_IMPROVEMENT_MANDATE.md\",\n ];\n\n const sortedGuidelines = [...guidelines].sort((a, b) => {\n const aIndex = mandatoryFiles.indexOf(a.filename);\n const bIndex = mandatoryFiles.indexOf(b.filename);\n if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;\n if (aIndex !== -1) return -1;\n if (bIndex !== -1) return 1;\n return a.title.localeCompare(b.title);\n });\n\n for (const guideline of sortedGuidelines) {\n content += `### ${guideline.title}\n\n📄 [See full details](../guidelines/${guideline.filename})\n\n${guideline.description}\n\n`;\n if (guideline.keyRules.length > 0) {\n content += `**Key Rules:**\n`;\n for (const rule of guideline.keyRules) {\n content += `- ${rule}\\n`;\n }\n content += \"\\n\";\n }\n }\n }\n\n // Add quick reference section\n content += `## Quick Reference\n\n### Branch Naming Convention\n\\`\\`\\`\n<type>/<scope>/<short-description>\n\\`\\`\\`\n\n**Types**: \\`feature\\`, \\`fix\\`, \\`chore\\`, \\`docs\\`, \\`refactor\\`, \\`test\\`, \\`perf\\`\n\n### Commit Message Format\n\\`\\`\\`\n<type>(<scope>): <description>\n\n[optional body]\n\n[optional footer]\n\\`\\`\\`\n\n### Before Making Changes\n1. Read the relevant guideline document in \\`guidelines/\\`\n2. Check for existing patterns in \\`workflow:solution:search\\`\n3. Create an implementation plan for multi-file changes\n4. Ensure tests are added for new functionality\n\n### Before Committing\n1. Run \\`pnpm run workflow:verify\\` to validate all changes\n2. Ensure branch name follows convention\n3. Ensure commit message follows conventional commits format\n\n`;\n\n // Add custom content section\n content += `## Project-Specific Instructions\n\n${CUSTOM_START_MARKER}\n${customContent || `\n<!-- \nAdd your project-specific instructions here.\nThis section will be preserved when the file is regenerated.\n\nExamples:\n- Specific coding patterns unique to this project\n- Custom review requirements\n- Domain-specific terminology\n- Team-specific workflows\n-->\n`}\n${CUSTOM_END_MARKER}\n\n---\n\n*This file was generated by [workflow-agent-cli](https://www.npmjs.com/package/workflow-agent-cli). Run \\`pnpm run workflow:generate-instructions\\` to regenerate.*\n`;\n\n return content;\n}\n\n/**\n * Result of generating copilot instructions\n */\nexport interface GenerateResult {\n success: boolean;\n filePath: string | null;\n guidelinesCount: number;\n isNew: boolean;\n preservedCustomContent: boolean;\n error?: string;\n}\n\n/**\n * Generate .github/copilot-instructions.md from guidelines directory\n *\n * @param projectRoot - Root directory of the project\n * @param options - Generation options\n * @returns Result of the generation\n */\nexport function generateCopilotInstructions(\n projectRoot: string,\n options: { force?: boolean; silent?: boolean } = {}\n): GenerateResult {\n const { force = false, silent = false } = options;\n\n const guidelinesDir = join(projectRoot, \"guidelines\");\n const githubDir = join(projectRoot, \".github\");\n const outputPath = join(githubDir, \"copilot-instructions.md\");\n\n // Check if guidelines directory exists\n if (!existsSync(guidelinesDir)) {\n if (!silent) {\n // Guidelines don't exist yet - skip silently during postinstall\n }\n return {\n success: false,\n filePath: null,\n guidelinesCount: 0,\n isNew: false,\n preservedCustomContent: false,\n error: \"No guidelines directory found. Run 'workflow init' first.\",\n };\n }\n\n // Read all markdown files from guidelines\n const files = readdirSync(guidelinesDir).filter(f => f.endsWith(\".md\"));\n if (files.length === 0) {\n return {\n success: false,\n filePath: null,\n guidelinesCount: 0,\n isNew: false,\n preservedCustomContent: false,\n error: \"No markdown files found in guidelines directory.\",\n };\n }\n\n // Parse each guideline\n const guidelines: GuidelineSummary[] = [];\n for (const file of files) {\n const summary = parseGuideline(join(guidelinesDir, file));\n if (summary) {\n guidelines.push(summary);\n }\n }\n\n // Load workflow config\n const config = loadWorkflowConfig(projectRoot);\n\n // Check for existing file and extract custom content\n let customContent: string | null = null;\n let isNew = true;\n\n if (existsSync(outputPath)) {\n isNew = false;\n const existingContent = readFileSync(outputPath, \"utf-8\");\n customContent = extractCustomContent(existingContent);\n }\n\n // Generate the content\n const content = generateInstructionsContent(config, guidelines, customContent);\n\n // Ensure .github directory exists\n if (!existsSync(githubDir)) {\n mkdirSync(githubDir, { recursive: true });\n }\n\n // Write the file\n writeFileSync(outputPath, content, \"utf-8\");\n\n return {\n success: true,\n filePath: outputPath,\n guidelinesCount: guidelines.length,\n isNew,\n preservedCustomContent: customContent !== null,\n };\n}\n\n/**\n * Check if copilot instructions need regeneration\n * (e.g., guidelines have been modified since last generation)\n */\nexport function needsRegeneration(projectRoot: string): boolean {\n const guidelinesDir = join(projectRoot, \"guidelines\");\n const outputPath = join(projectRoot, \".github\", \"copilot-instructions.md\");\n\n if (!existsSync(outputPath)) {\n return existsSync(guidelinesDir);\n }\n\n // For now, always regenerate to ensure latest content\n // Future: could compare file modification times\n return true;\n}\n","/**\n * Shared workflow scripts definition\n * Used by postinstall.ts and setup.ts to ensure consistency\n */\n\nexport const WORKFLOW_SCRIPTS = {\n // Core Commands\n \"workflow:init\": \"workflow-agent init\",\n \"workflow:validate\": \"workflow-agent validate\",\n \"workflow:config\": \"workflow-agent config\",\n \"workflow:suggest\": \"workflow-agent suggest\",\n \"workflow:setup\": \"workflow-agent setup\",\n \"workflow:doctor\": \"workflow-agent doctor\",\n\n // Scope Commands\n \"workflow:scope:create\": \"workflow-agent scope:create\",\n \"workflow:scope:migrate\": \"workflow-agent scope:migrate\",\n\n // Verification & Auto-Setup\n \"workflow:verify\": \"workflow-agent verify\",\n \"workflow:verify:fix\": \"workflow-agent verify --fix\",\n \"workflow:auto-setup\": \"workflow-agent auto-setup\",\n\n // Learning System Commands\n \"workflow:learn\": \"workflow-agent learn:list\",\n \"workflow:learn:record\": \"workflow-agent learn:record\",\n \"workflow:learn:list\": \"workflow-agent learn:list\",\n \"workflow:learn:apply\": \"workflow-agent learn:apply\",\n \"workflow:learn:publish\": \"workflow-agent learn:publish\",\n \"workflow:learn:sync\": \"workflow-agent learn:sync\",\n \"workflow:learn:sync:push\": \"workflow-agent learn:sync --push\",\n \"workflow:learn:sync:pull\": \"workflow-agent learn:sync --pull\",\n \"workflow:learn:config\": \"workflow-agent learn:config\",\n \"workflow:learn:deprecate\": \"workflow-agent learn:deprecate\",\n \"workflow:learn:stats\": \"workflow-agent learn:stats\",\n\n // Solution Pattern Commands\n \"workflow:solution\": \"workflow-agent solution:list\",\n \"workflow:solution:capture\": \"workflow-agent solution:capture\",\n \"workflow:solution:search\": \"workflow-agent solution:search\",\n \"workflow:solution:list\": \"workflow-agent solution:list\",\n \"workflow:solution:apply\": \"workflow-agent solution:apply\",\n \"workflow:solution:deprecate\": \"workflow-agent solution:deprecate\",\n \"workflow:solution:stats\": \"workflow-agent solution:stats\",\n\n // Advisory Board Commands\n \"workflow:advisory\": \"workflow-agent advisory\",\n \"workflow:advisory:quick\": \"workflow-agent advisory --depth quick\",\n \"workflow:advisory:standard\": \"workflow-agent advisory --depth standard\",\n \"workflow:advisory:comprehensive\":\n \"workflow-agent advisory --depth comprehensive\",\n \"workflow:advisory:executive\": \"workflow-agent advisory --depth executive\",\n \"workflow:advisory:ci\": \"workflow-agent advisory --ci\",\n\n // AI Agent Instructions\n \"workflow:generate-instructions\": \"workflow-agent generate-instructions\",\n\n // Template Management\n \"workflow:update-templates\": \"workflow-agent update-templates\",\n \"workflow:update-templates:force\": \"workflow-agent update-templates --force\",\n\n // Document Validation\n \"workflow:docs:validate\": \"workflow-agent docs:validate\",\n \"workflow:docs:validate:fix\": \"workflow-agent docs:validate --fix\",\n} as const;\n\nexport type WorkflowScriptName = keyof typeof WORKFLOW_SCRIPTS;\n\n/**\n * Script categories for organized console output\n */\nexport const SCRIPT_CATEGORIES = {\n \"Core Commands\": [\n \"workflow:init\",\n \"workflow:validate\",\n \"workflow:config\",\n \"workflow:suggest\",\n \"workflow:setup\",\n \"workflow:doctor\",\n ],\n \"Scope Commands\": [\"workflow:scope:create\", \"workflow:scope:migrate\"],\n Verification: [\n \"workflow:verify\",\n \"workflow:verify:fix\",\n \"workflow:auto-setup\",\n ],\n \"Learning System\": [\n \"workflow:learn\",\n \"workflow:learn:record\",\n \"workflow:learn:list\",\n \"workflow:learn:apply\",\n \"workflow:learn:publish\",\n \"workflow:learn:sync\",\n \"workflow:learn:sync:push\",\n \"workflow:learn:sync:pull\",\n \"workflow:learn:config\",\n \"workflow:learn:deprecate\",\n \"workflow:learn:stats\",\n ],\n \"Solution Patterns\": [\n \"workflow:solution\",\n \"workflow:solution:capture\",\n \"workflow:solution:search\",\n \"workflow:solution:list\",\n \"workflow:solution:apply\",\n \"workflow:solution:deprecate\",\n \"workflow:solution:stats\",\n ],\n \"Advisory Board\": [\n \"workflow:advisory\",\n \"workflow:advisory:quick\",\n \"workflow:advisory:standard\",\n \"workflow:advisory:comprehensive\",\n \"workflow:advisory:executive\",\n \"workflow:advisory:ci\",\n ],\n \"AI Agent Instructions\": [\n \"workflow:generate-instructions\",\n ],\n \"Template Management\": [\n \"workflow:update-templates\",\n \"workflow:update-templates:force\",\n ],\n \"Document Validation\": [\n \"workflow:docs:validate\",\n \"workflow:docs:validate:fix\",\n ],\n} as const;\n\nexport const TOTAL_SCRIPTS = Object.keys(WORKFLOW_SCRIPTS).length;\n","/**\n * Silent template installer for postinstall and non-interactive contexts\n *\n * This module provides functions to copy mandatory templates without\n * user interaction, suitable for use in postinstall scripts.\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from \"fs\";\nimport { readdirSync } from \"fs\";\nimport { join, basename } from \"path\";\nimport { getMandatoryTemplateFilenames } from \"../templates/metadata.js\";\n\nexport interface InstallTemplatesOptions {\n /** Force overwrite existing files */\n force?: boolean;\n /** Skip if guidelines directory already exists */\n skipIfExists?: boolean;\n /** Silent mode - no console output */\n silent?: boolean;\n /** Only install mandatory templates (default: true) */\n mandatoryOnly?: boolean;\n}\n\nexport interface InstallTemplatesResult {\n success: boolean;\n installed: string[];\n skipped: string[];\n updated: string[];\n errors: string[];\n guidelinesExisted: boolean;\n}\n\n/**\n * Get project name from package.json or directory name\n */\nfunction getProjectName(projectRoot: string): string {\n try {\n const pkgPath = join(projectRoot, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\"));\n return pkg.name || basename(projectRoot);\n }\n } catch {\n // Ignore errors, fall back to directory name\n }\n return basename(projectRoot);\n}\n\n/**\n * Simple template variable substitution using {{variable}} syntax\n */\nfunction renderTemplate(\n template: string,\n context: Record<string, string>,\n): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key) => {\n return context[key] ?? match;\n });\n}\n\n/**\n * Build default template context from project info\n * Uses generic defaults when no workflow.config.json exists\n */\nfunction buildDefaultContext(projectRoot: string): Record<string, string> {\n const projectName = getProjectName(projectRoot);\n\n return {\n projectName,\n framework: \"unknown\",\n scopes: \"feat, fix, docs, refactor, test, chore\",\n scopeList: `- **feat** - New features\n- **fix** - Bug fixes\n- **docs** - Documentation\n- **refactor** - Code refactoring\n- **test** - Testing\n- **chore** - Maintenance`,\n pathStructure: \"N/A\",\n enforcement: \"strict\",\n year: new Date().getFullYear().toString(),\n };\n}\n\n/**\n * Find the templates directory relative to this module\n * Works in both development and installed contexts\n */\nexport function findTemplatesDirectory(callerDirname: string): string | null {\n // When installed: dist/scripts/template-installer.js -> ../../templates\n // Try multiple possible locations\n const possiblePaths = [\n join(callerDirname, \"../../templates\"),\n join(callerDirname, \"../templates\"),\n join(callerDirname, \"templates\"),\n ];\n\n for (const templatePath of possiblePaths) {\n if (existsSync(templatePath)) {\n return templatePath;\n }\n }\n\n return null;\n}\n\n/**\n * Install mandatory templates to a project's guidelines directory\n * Designed for non-interactive use (postinstall, CI, etc.)\n */\nexport function installMandatoryTemplates(\n projectRoot: string,\n templatesDir: string,\n options: InstallTemplatesOptions = {},\n): InstallTemplatesResult {\n const {\n force = false,\n skipIfExists = true,\n silent = false,\n mandatoryOnly = true,\n } = options;\n\n const result: InstallTemplatesResult = {\n success: true,\n installed: [],\n skipped: [],\n updated: [],\n errors: [],\n guidelinesExisted: false,\n };\n\n const guidelinesDir = join(projectRoot, \"guidelines\");\n result.guidelinesExisted = existsSync(guidelinesDir);\n\n // Skip if guidelines exists and skipIfExists is true\n if (result.guidelinesExisted && skipIfExists && !force) {\n if (!silent) {\n console.log(\" Guidelines directory already exists, skipping templates\");\n }\n return result;\n }\n\n // Get list of templates to install\n const mandatoryFiles = getMandatoryTemplateFilenames();\n\n // Check templates directory exists\n if (!existsSync(templatesDir)) {\n result.success = false;\n result.errors.push(`Templates directory not found: ${templatesDir}`);\n return result;\n }\n\n // Get available template files\n let availableFiles: string[];\n try {\n availableFiles = readdirSync(templatesDir).filter((f) => f.endsWith(\".md\"));\n } catch (error) {\n result.success = false;\n result.errors.push(`Failed to read templates directory: ${error}`);\n return result;\n }\n\n // Determine which files to install\n const filesToInstall = mandatoryOnly\n ? availableFiles.filter((f) => mandatoryFiles.includes(f))\n : availableFiles;\n\n if (filesToInstall.length === 0) {\n result.success = false;\n result.errors.push(\"No template files found to install\");\n return result;\n }\n\n // Build template context\n const context = buildDefaultContext(projectRoot);\n\n // Create guidelines directory\n try {\n mkdirSync(guidelinesDir, { recursive: true });\n } catch (error) {\n result.success = false;\n result.errors.push(`Failed to create guidelines directory: ${error}`);\n return result;\n }\n\n // Copy each template\n for (const filename of filesToInstall) {\n const sourcePath = join(templatesDir, filename);\n const destPath = join(guidelinesDir, filename);\n\n const fileExists = existsSync(destPath);\n\n // Skip if file exists and not forcing\n if (fileExists && !force) {\n result.skipped.push(filename);\n continue;\n }\n\n try {\n const template = readFileSync(sourcePath, \"utf-8\");\n const rendered = renderTemplate(template, context);\n writeFileSync(destPath, rendered, \"utf-8\");\n\n if (fileExists) {\n result.updated.push(filename);\n } else {\n result.installed.push(filename);\n }\n } catch (error) {\n result.errors.push(`Failed to install ${filename}: ${error}`);\n }\n }\n\n // Log results if not silent\n if (!silent) {\n if (result.installed.length > 0) {\n console.log(\n `\\n✓ Installed ${result.installed.length} guideline templates:`,\n );\n for (const file of result.installed) {\n console.log(` - ${file}`);\n }\n }\n if (result.updated.length > 0) {\n console.log(`\\n✓ Updated ${result.updated.length} guideline templates:`);\n for (const file of result.updated) {\n console.log(` - ${file}`);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Update templates - reinstall templates with option to force or skip existing\n */\nexport function updateTemplates(\n projectRoot: string,\n templatesDir: string,\n options: { force?: boolean; silent?: boolean } = {},\n): InstallTemplatesResult {\n return installMandatoryTemplates(projectRoot, templatesDir, {\n ...options,\n skipIfExists: false, // Don't skip - we want to update\n mandatoryOnly: false, // Install all templates during update\n });\n}\n","/**\n * Template metadata defining mandatory vs optional guidelines\n * and their associated validators for enforcement\n *\n * @fileoverview This module defines which guidelines are mandatory for projects\n * using the workflow agent. Mandatory guidelines MUST be present and cannot be\n * skipped during project initialization.\n *\n * TODO: Ensure all new templates have associated unit tests in metadata.test.ts\n */\n\nexport type TemplateCategory = \"workflow\" | \"documentation\" | \"development\";\n\nexport type ValidatorType =\n | \"branch-name\"\n | \"commit-message\"\n | \"pr-title\"\n | \"implementation-plan\"\n | \"test-coverage\"\n | \"file-exists\";\n\nexport interface TemplateMetadata {\n /** Template filename */\n filename: string;\n /** Human-readable name */\n displayName: string;\n /** Whether this template is mandatory (cannot be skipped during init) */\n mandatory: boolean;\n /** Category for grouping */\n category: TemplateCategory;\n /** Associated validators that enforce this template's rules */\n validators: ValidatorType[];\n /** Brief description of what this template covers */\n description: string;\n}\n\n/**\n * Metadata for all available templates\n * Templates marked as mandatory will be auto-generated during init\n * and checked by the doctor command\n */\nexport const templateMetadata: Record<string, TemplateMetadata> = {\n \"AGENT_EDITING_INSTRUCTIONS.md\": {\n filename: \"AGENT_EDITING_INSTRUCTIONS.md\",\n displayName: \"Agent Editing Instructions\",\n mandatory: true,\n category: \"workflow\",\n validators: [\"implementation-plan\"],\n description:\n \"Core rules for AI agents: implementation plans, coding standards, architecture\",\n },\n \"BRANCHING_STRATEGY.md\": {\n filename: \"BRANCHING_STRATEGY.md\",\n displayName: \"Branching Strategy\",\n mandatory: true,\n category: \"workflow\",\n validators: [\"branch-name\", \"pr-title\"],\n description:\n \"Git branch naming conventions, PR requirements, merge policies\",\n },\n \"TESTING_STRATEGY.md\": {\n filename: \"TESTING_STRATEGY.md\",\n displayName: \"Testing Strategy\",\n mandatory: true,\n category: \"development\",\n validators: [\"test-coverage\"],\n description:\n \"Testing pyramid, Vitest/Playwright patterns, when tests are required\",\n },\n \"SELF_IMPROVEMENT_MANDATE.md\": {\n filename: \"SELF_IMPROVEMENT_MANDATE.md\",\n displayName: \"Self-Improvement Mandate\",\n mandatory: true,\n category: \"workflow\",\n validators: [],\n description: \"Continuous improvement tracking, changelog requirements\",\n },\n \"PATTERN_ANALYSIS_WORKFLOW.md\": {\n filename: \"PATTERN_ANALYSIS_WORKFLOW.md\",\n displayName: \"Pattern Analysis Workflow\",\n mandatory: true,\n category: \"workflow\",\n validators: [],\n description:\n \"AI agent workflow for analyzing codebases, extracting patterns, and updating the central pattern store\",\n },\n \"SINGLE_SOURCE_OF_TRUTH.md\": {\n filename: \"SINGLE_SOURCE_OF_TRUTH.md\",\n displayName: \"Single Source of Truth\",\n mandatory: true,\n category: \"workflow\",\n validators: [],\n description:\n \"Canonical code locations, service patterns, avoiding duplication\",\n },\n \"COMPONENT_LIBRARY.md\": {\n filename: \"COMPONENT_LIBRARY.md\",\n displayName: \"Component Library\",\n mandatory: false,\n category: \"development\",\n validators: [],\n description: \"UI component patterns, design tokens, decision tree\",\n },\n \"DEPLOYMENT_STRATEGY.md\": {\n filename: \"DEPLOYMENT_STRATEGY.md\",\n displayName: \"Deployment Strategy\",\n mandatory: false,\n category: \"development\",\n validators: [],\n description: \"Deployment workflow, environments, migrations, rollback\",\n },\n \"LIBRARY_INVENTORY.md\": {\n filename: \"LIBRARY_INVENTORY.md\",\n displayName: \"Library Inventory\",\n mandatory: true,\n category: \"development\",\n validators: [],\n description: \"Dependency catalog, approved libraries, new library process\",\n },\n \"SCOPE_CREATION_WORKFLOW.md\": {\n filename: \"SCOPE_CREATION_WORKFLOW.md\",\n displayName: \"Scope Creation Workflow\",\n mandatory: false,\n category: \"workflow\",\n validators: [],\n description: \"Workflow for AI agents creating custom scopes\",\n },\n \"CUSTOM_SCOPE_TEMPLATE.md\": {\n filename: \"CUSTOM_SCOPE_TEMPLATE.md\",\n displayName: \"Custom Scope Template\",\n mandatory: false,\n category: \"workflow\",\n validators: [],\n description: \"Template for defining custom scope packages\",\n },\n \"PROJECT_TEMPLATE_README.md\": {\n filename: \"PROJECT_TEMPLATE_README.md\",\n displayName: \"Project Template README\",\n mandatory: false,\n category: \"documentation\",\n validators: [],\n description: \"Meta-document describing project structure\",\n },\n \"Guidelines.md\": {\n filename: \"Guidelines.md\",\n displayName: \"Custom Guidelines\",\n mandatory: false,\n category: \"documentation\",\n validators: [],\n description: \"Placeholder for custom user guidelines\",\n },\n};\n\n/**\n * Get all mandatory templates\n */\nexport function getMandatoryTemplates(): TemplateMetadata[] {\n return Object.values(templateMetadata).filter((t) => t.mandatory);\n}\n\n/**\n * Get all optional templates\n */\nexport function getOptionalTemplates(): TemplateMetadata[] {\n return Object.values(templateMetadata).filter((t) => !t.mandatory);\n}\n\n/**\n * Get templates by category\n */\nexport function getTemplatesByCategory(\n category: TemplateCategory,\n): TemplateMetadata[] {\n return Object.values(templateMetadata).filter((t) => t.category === category);\n}\n\n/**\n * Get template metadata by filename\n */\nexport function getTemplateMetadata(\n filename: string,\n): TemplateMetadata | undefined {\n return templateMetadata[filename];\n}\n\n/**\n * Check if a template is mandatory\n */\nexport function isTemplateMandatory(filename: string): boolean {\n return templateMetadata[filename]?.mandatory ?? false;\n}\n\n/**\n * Get mandatory template filenames\n */\nexport function getMandatoryTemplateFilenames(): string[] {\n return getMandatoryTemplates().map((t) => t.filename);\n}\n"],"mappings":";AAeA,SAAS,cAAc,eAAe,YAAY,aAAa,iBAAiB;AAChF,SAAS,MAAM,gBAAgB;AAG/B,IAAM,sBAAsB;AAC5B,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;AAmBzB,SAAS,aAAa,SAAyB;AAC7C,QAAM,QAAQ,QAAQ,MAAM,aAAa;AACzC,SAAO,QAAQ,MAAM,CAAC,EAAE,KAAK,IAAI;AACnC;AAKA,SAAS,mBAAmB,SAAyB;AAEnD,QAAM,QAAQ,QAAQ,MAAM,IAAI;AAChC,MAAI,aAAa;AACjB,MAAI,cAAc;AAElB,aAAW,QAAQ,OAAO;AACxB,QAAI,KAAK,WAAW,IAAI,GAAG;AACzB,mBAAa;AACb;AAAA,IACF;AACA,QAAI,YAAY;AAEd,UAAI,KAAK,KAAK,MAAM,MAAM,KAAK,WAAW,GAAG,GAAG;AAC9C,YAAI,YAAa;AACjB;AAAA,MACF;AAEA,UAAI,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,KAAK,KAAK,KAAK,WAAW,IAAI,GAAG;AAC3E;AAAA,MACF;AACA,qBAAe,KAAK,KAAK,IAAI;AAE7B,UAAI,YAAY,SAAS,IAAK;AAAA,IAChC;AAAA,EACF;AAEA,SAAO,YAAY,KAAK,EAAE,MAAM,GAAG,GAAG,KAAK,YAAY,SAAS,MAAM,QAAQ;AAChF;AAMA,SAAS,gBAAgB,SAAiB,WAAmB,GAAa;AACx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AAQ;AAAA,MAChC;AAAA,IACF,SAAS,OAAO;AACd,aAAO,OAAO,KAAK,qBAAqB,QAAQ,KAAK,KAAK,EAAE;AAAA,IAC9D;AAAA,EACF;AAGA,MAAI,CAAC,QAAQ;AACX,QAAI,OAAO,UAAU,SAAS,GAAG;AAC/B,cAAQ;AAAA,QACN;AAAA,mBAAiB,OAAO,UAAU,MAAM;AAAA,MAC1C;AACA,iBAAW,QAAQ,OAAO,WAAW;AACnC,gBAAQ,IAAI,SAAS,IAAI,EAAE;AAAA,MAC7B;AAAA,IACF;AACA,QAAI,OAAO,QAAQ,SAAS,GAAG;AAC7B,cAAQ,IAAI;AAAA,iBAAe,OAAO,QAAQ,MAAM,uBAAuB;AACvE,iBAAW,QAAQ,OAAO,SAAS;AACjC,gBAAQ,IAAI,SAAS,IAAI,EAAE;AAAA,MAC7B;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAKO,SAAS,gBACd,aACA,cACA,UAAiD,CAAC,GAC1B;AACxB,SAAO,0BAA0B,aAAa,cAAc;AAAA,IAC1D,GAAG;AAAA,IACH,cAAc;AAAA;AAAA,IACd,eAAe;AAAA;AAAA,EACjB,CAAC;AACH;","names":["existsSync","readFileSync","writeFileSync","mkdirSync","readdirSync","join","basename","join","existsSync","readFileSync","basename","readdirSync","mkdirSync","writeFileSync"]}
|
package/dist/cli/index.js
CHANGED
|
@@ -31,7 +31,7 @@ import {
|
|
|
31
31
|
installMandatoryTemplates,
|
|
32
32
|
templateMetadata,
|
|
33
33
|
updateTemplates
|
|
34
|
-
} from "../chunk-
|
|
34
|
+
} from "../chunk-Q2B25XH2.js";
|
|
35
35
|
import {
|
|
36
36
|
autoFixConfigFile,
|
|
37
37
|
validateScopeDefinitions
|
|
@@ -5232,6 +5232,194 @@ import {
|
|
|
5232
5232
|
PatternAnonymizer,
|
|
5233
5233
|
TelemetryCollector as TelemetryCollector2
|
|
5234
5234
|
} from "@hawkinside_out/workflow-improvement-tracker";
|
|
5235
|
+
|
|
5236
|
+
// src/sync/registry-client.ts
|
|
5237
|
+
var DEFAULT_REGISTRY_URL = "https://patterns.workflow-agent.dev";
|
|
5238
|
+
var RegistryClient = class {
|
|
5239
|
+
baseUrl;
|
|
5240
|
+
timeout;
|
|
5241
|
+
retries;
|
|
5242
|
+
constructor(options = {}) {
|
|
5243
|
+
this.baseUrl = options.baseUrl || process.env.WORKFLOW_REGISTRY_URL || DEFAULT_REGISTRY_URL;
|
|
5244
|
+
this.baseUrl = this.baseUrl.replace(/\/$/, "");
|
|
5245
|
+
this.timeout = options.timeout ?? 3e4;
|
|
5246
|
+
this.retries = options.retries ?? 3;
|
|
5247
|
+
}
|
|
5248
|
+
/**
|
|
5249
|
+
* Push patterns to the registry
|
|
5250
|
+
*
|
|
5251
|
+
* @param patterns - Array of anonymized patterns to push
|
|
5252
|
+
* @param contributorId - Anonymous contributor ID
|
|
5253
|
+
* @returns Push result with count of pushed/skipped patterns
|
|
5254
|
+
* @throws Error if rate limited or push fails
|
|
5255
|
+
*/
|
|
5256
|
+
async push(patterns, contributorId) {
|
|
5257
|
+
const payload = {
|
|
5258
|
+
patterns: patterns.map((p13) => ({
|
|
5259
|
+
id: p13.pattern.id,
|
|
5260
|
+
type: p13.type,
|
|
5261
|
+
data: p13.pattern,
|
|
5262
|
+
hash: p13.hash
|
|
5263
|
+
}))
|
|
5264
|
+
};
|
|
5265
|
+
const response = await this.request(
|
|
5266
|
+
"/patterns/push",
|
|
5267
|
+
{
|
|
5268
|
+
method: "POST",
|
|
5269
|
+
headers: {
|
|
5270
|
+
"Content-Type": "application/json",
|
|
5271
|
+
"x-contributor-id": contributorId
|
|
5272
|
+
},
|
|
5273
|
+
body: JSON.stringify(payload)
|
|
5274
|
+
}
|
|
5275
|
+
);
|
|
5276
|
+
return response;
|
|
5277
|
+
}
|
|
5278
|
+
/**
|
|
5279
|
+
* Pull patterns from the registry
|
|
5280
|
+
*
|
|
5281
|
+
* @param options - Pull options
|
|
5282
|
+
* @returns Array of patterns from the registry
|
|
5283
|
+
*/
|
|
5284
|
+
async pull(options = {}) {
|
|
5285
|
+
const params = new URLSearchParams();
|
|
5286
|
+
if (options.type) {
|
|
5287
|
+
params.set("type", options.type);
|
|
5288
|
+
}
|
|
5289
|
+
if (options.limit) {
|
|
5290
|
+
params.set("limit", options.limit.toString());
|
|
5291
|
+
}
|
|
5292
|
+
if (options.offset) {
|
|
5293
|
+
params.set("offset", options.offset.toString());
|
|
5294
|
+
}
|
|
5295
|
+
if (options.since) {
|
|
5296
|
+
params.set("since", options.since);
|
|
5297
|
+
}
|
|
5298
|
+
const queryString = params.toString();
|
|
5299
|
+
const url = `/patterns/pull${queryString ? `?${queryString}` : ""}`;
|
|
5300
|
+
return this.request(url, {
|
|
5301
|
+
method: "GET"
|
|
5302
|
+
});
|
|
5303
|
+
}
|
|
5304
|
+
/**
|
|
5305
|
+
* Get a single pattern by ID
|
|
5306
|
+
*
|
|
5307
|
+
* @param patternId - UUID of the pattern
|
|
5308
|
+
* @returns Pattern data or null if not found
|
|
5309
|
+
*/
|
|
5310
|
+
async getPattern(patternId) {
|
|
5311
|
+
try {
|
|
5312
|
+
return await this.request(`/patterns/${patternId}`, {
|
|
5313
|
+
method: "GET"
|
|
5314
|
+
});
|
|
5315
|
+
} catch (error) {
|
|
5316
|
+
if (error instanceof RegistryError && error.statusCode === 404) {
|
|
5317
|
+
return null;
|
|
5318
|
+
}
|
|
5319
|
+
throw error;
|
|
5320
|
+
}
|
|
5321
|
+
}
|
|
5322
|
+
/**
|
|
5323
|
+
* Check if the registry is available
|
|
5324
|
+
*/
|
|
5325
|
+
async healthCheck() {
|
|
5326
|
+
try {
|
|
5327
|
+
await this.request("/health", {
|
|
5328
|
+
method: "GET"
|
|
5329
|
+
});
|
|
5330
|
+
return true;
|
|
5331
|
+
} catch {
|
|
5332
|
+
return false;
|
|
5333
|
+
}
|
|
5334
|
+
}
|
|
5335
|
+
/**
|
|
5336
|
+
* Make an HTTP request to the registry
|
|
5337
|
+
*/
|
|
5338
|
+
async request(path3, options) {
|
|
5339
|
+
const url = `${this.baseUrl}${path3}`;
|
|
5340
|
+
let lastError = null;
|
|
5341
|
+
for (let attempt = 1; attempt <= this.retries; attempt++) {
|
|
5342
|
+
try {
|
|
5343
|
+
const controller = new AbortController();
|
|
5344
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
5345
|
+
const response = await fetch(url, {
|
|
5346
|
+
...options,
|
|
5347
|
+
signal: controller.signal
|
|
5348
|
+
});
|
|
5349
|
+
clearTimeout(timeoutId);
|
|
5350
|
+
if (response.status === 429) {
|
|
5351
|
+
const body = await response.json();
|
|
5352
|
+
throw new RateLimitedException(
|
|
5353
|
+
body.message || "Rate limit exceeded",
|
|
5354
|
+
body.resetAt,
|
|
5355
|
+
body.remaining ?? 0
|
|
5356
|
+
);
|
|
5357
|
+
}
|
|
5358
|
+
if (!response.ok) {
|
|
5359
|
+
const body = await response.json().catch(() => ({}));
|
|
5360
|
+
throw new RegistryError(
|
|
5361
|
+
body.error || `Request failed with status ${response.status}`,
|
|
5362
|
+
response.status,
|
|
5363
|
+
body
|
|
5364
|
+
);
|
|
5365
|
+
}
|
|
5366
|
+
return await response.json();
|
|
5367
|
+
} catch (error) {
|
|
5368
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
5369
|
+
if (error instanceof RateLimitedException) {
|
|
5370
|
+
throw error;
|
|
5371
|
+
}
|
|
5372
|
+
if (error instanceof RegistryError && error.statusCode >= 400 && error.statusCode < 500) {
|
|
5373
|
+
throw error;
|
|
5374
|
+
}
|
|
5375
|
+
if (attempt < this.retries) {
|
|
5376
|
+
await new Promise(
|
|
5377
|
+
(resolve2) => setTimeout(resolve2, Math.pow(2, attempt) * 1e3)
|
|
5378
|
+
);
|
|
5379
|
+
}
|
|
5380
|
+
}
|
|
5381
|
+
}
|
|
5382
|
+
throw lastError ?? new Error("Request failed after retries");
|
|
5383
|
+
}
|
|
5384
|
+
};
|
|
5385
|
+
var RegistryError = class extends Error {
|
|
5386
|
+
constructor(message, statusCode, body) {
|
|
5387
|
+
super(message);
|
|
5388
|
+
this.statusCode = statusCode;
|
|
5389
|
+
this.body = body;
|
|
5390
|
+
this.name = "RegistryError";
|
|
5391
|
+
}
|
|
5392
|
+
};
|
|
5393
|
+
var RateLimitedException = class extends Error {
|
|
5394
|
+
constructor(message, resetAt, remaining) {
|
|
5395
|
+
super(message);
|
|
5396
|
+
this.resetAt = resetAt;
|
|
5397
|
+
this.remaining = remaining;
|
|
5398
|
+
this.name = "RateLimitedException";
|
|
5399
|
+
}
|
|
5400
|
+
/**
|
|
5401
|
+
* Get human-readable time until rate limit resets
|
|
5402
|
+
*/
|
|
5403
|
+
getTimeUntilReset() {
|
|
5404
|
+
if (!this.resetAt) {
|
|
5405
|
+
return "unknown";
|
|
5406
|
+
}
|
|
5407
|
+
const resetTime = new Date(this.resetAt).getTime();
|
|
5408
|
+
const now = Date.now();
|
|
5409
|
+
const diffMs = resetTime - now;
|
|
5410
|
+
if (diffMs <= 0) {
|
|
5411
|
+
return "now";
|
|
5412
|
+
}
|
|
5413
|
+
const minutes = Math.ceil(diffMs / 6e4);
|
|
5414
|
+
if (minutes < 60) {
|
|
5415
|
+
return `${minutes} minute${minutes === 1 ? "" : "s"}`;
|
|
5416
|
+
}
|
|
5417
|
+
const hours = Math.ceil(minutes / 60);
|
|
5418
|
+
return `${hours} hour${hours === 1 ? "" : "s"}`;
|
|
5419
|
+
}
|
|
5420
|
+
};
|
|
5421
|
+
|
|
5422
|
+
// src/cli/commands/learn.ts
|
|
5235
5423
|
function getWorkspacePath() {
|
|
5236
5424
|
return process.cwd();
|
|
5237
5425
|
}
|
|
@@ -5675,37 +5863,213 @@ async function learnSyncCommand(options) {
|
|
|
5675
5863
|
);
|
|
5676
5864
|
if (options.push) {
|
|
5677
5865
|
console.log(chalk16.cyan("\n\u{1F4E4} Pushing patterns...\n"));
|
|
5678
|
-
|
|
5679
|
-
let anonymizedBlueprints = 0;
|
|
5866
|
+
const anonymizedPatterns = [];
|
|
5680
5867
|
for (const fix of fixes) {
|
|
5681
5868
|
const result = anonymizer.anonymizeFixPattern(fix);
|
|
5682
|
-
if (result.success) {
|
|
5683
|
-
|
|
5684
|
-
|
|
5685
|
-
|
|
5686
|
-
|
|
5869
|
+
if (result.success && result.data) {
|
|
5870
|
+
anonymizedPatterns.push({
|
|
5871
|
+
pattern: result.data,
|
|
5872
|
+
type: "fix",
|
|
5873
|
+
originalId: fix.id
|
|
5874
|
+
});
|
|
5875
|
+
console.log(chalk16.dim(` \u2713 Anonymized: ${fix.name}`));
|
|
5687
5876
|
}
|
|
5688
5877
|
}
|
|
5689
5878
|
for (const bp of blueprints) {
|
|
5690
5879
|
const result = anonymizer.anonymizeBlueprint(bp);
|
|
5691
|
-
if (result.success) {
|
|
5692
|
-
|
|
5693
|
-
|
|
5694
|
-
|
|
5695
|
-
|
|
5880
|
+
if (result.success && result.data) {
|
|
5881
|
+
anonymizedPatterns.push({
|
|
5882
|
+
pattern: result.data,
|
|
5883
|
+
type: "blueprint",
|
|
5884
|
+
originalId: bp.id
|
|
5885
|
+
});
|
|
5886
|
+
console.log(chalk16.dim(` \u2713 Anonymized: ${bp.name}`));
|
|
5696
5887
|
}
|
|
5697
5888
|
}
|
|
5889
|
+
const fixCount = anonymizedPatterns.filter((p13) => p13.type === "fix").length;
|
|
5890
|
+
const bpCount = anonymizedPatterns.filter((p13) => p13.type === "blueprint").length;
|
|
5891
|
+
if (anonymizedPatterns.length === 0) {
|
|
5892
|
+
console.log(chalk16.yellow("\n\u26A0\uFE0F No patterns to push"));
|
|
5893
|
+
return;
|
|
5894
|
+
}
|
|
5698
5895
|
console.log(
|
|
5699
|
-
chalk16.
|
|
5896
|
+
chalk16.dim(
|
|
5700
5897
|
`
|
|
5701
|
-
|
|
5898
|
+
Ready to push ${fixCount} fixes and ${bpCount} blueprints`
|
|
5702
5899
|
)
|
|
5703
5900
|
);
|
|
5704
|
-
|
|
5901
|
+
if (options.dryRun) {
|
|
5902
|
+
console.log(chalk16.yellow("\n\u{1F4CB} DRY-RUN: Patterns would be pushed (no actual changes)"));
|
|
5903
|
+
return;
|
|
5904
|
+
}
|
|
5905
|
+
const contributorResult = await contributorManager.getOrCreateId();
|
|
5906
|
+
if (!contributorResult.success || !contributorResult.data) {
|
|
5907
|
+
console.log(chalk16.red("\n\u274C Failed to get contributor ID"));
|
|
5908
|
+
return;
|
|
5909
|
+
}
|
|
5910
|
+
const registryClient = new RegistryClient();
|
|
5911
|
+
try {
|
|
5912
|
+
console.log(chalk16.dim("\n Connecting to registry..."));
|
|
5913
|
+
const pushResult = await registryClient.push(
|
|
5914
|
+
anonymizedPatterns.map((p13) => ({
|
|
5915
|
+
pattern: p13.pattern,
|
|
5916
|
+
type: p13.type
|
|
5917
|
+
})),
|
|
5918
|
+
contributorResult.data
|
|
5919
|
+
);
|
|
5920
|
+
if (pushResult.pushed > 0) {
|
|
5921
|
+
const pushedFixIds = anonymizedPatterns.filter((p13) => p13.type === "fix").map((p13) => p13.originalId);
|
|
5922
|
+
const pushedBpIds = anonymizedPatterns.filter((p13) => p13.type === "blueprint").map((p13) => p13.originalId);
|
|
5923
|
+
if (pushedFixIds.length > 0) {
|
|
5924
|
+
await store.markAsSynced(pushedFixIds, "fix");
|
|
5925
|
+
}
|
|
5926
|
+
if (pushedBpIds.length > 0) {
|
|
5927
|
+
await store.markAsSynced(pushedBpIds, "blueprint");
|
|
5928
|
+
}
|
|
5929
|
+
}
|
|
5930
|
+
console.log(
|
|
5931
|
+
chalk16.green(`
|
|
5932
|
+
\u2705 Successfully pushed ${pushResult.pushed} patterns to registry`)
|
|
5933
|
+
);
|
|
5934
|
+
if (pushResult.skipped > 0) {
|
|
5935
|
+
console.log(
|
|
5936
|
+
chalk16.dim(` (${pushResult.skipped} patterns already existed)`)
|
|
5937
|
+
);
|
|
5938
|
+
}
|
|
5939
|
+
if (pushResult.errors && pushResult.errors.length > 0) {
|
|
5940
|
+
console.log(chalk16.yellow(`
|
|
5941
|
+
\u26A0\uFE0F Some patterns had errors:`));
|
|
5942
|
+
for (const err of pushResult.errors) {
|
|
5943
|
+
console.log(chalk16.dim(` - ${err}`));
|
|
5944
|
+
}
|
|
5945
|
+
}
|
|
5946
|
+
console.log(
|
|
5947
|
+
chalk16.dim(
|
|
5948
|
+
`
|
|
5949
|
+
Rate limit: ${pushResult.rateLimit.remaining} patterns remaining this hour`
|
|
5950
|
+
)
|
|
5951
|
+
);
|
|
5952
|
+
} catch (error) {
|
|
5953
|
+
if (error instanceof RateLimitedException) {
|
|
5954
|
+
console.log(chalk16.red("\n\u274C Rate limit exceeded"));
|
|
5955
|
+
console.log(
|
|
5956
|
+
chalk16.dim(
|
|
5957
|
+
` Try again in ${error.getTimeUntilReset()}`
|
|
5958
|
+
)
|
|
5959
|
+
);
|
|
5960
|
+
} else if (error instanceof RegistryError) {
|
|
5961
|
+
console.log(chalk16.red(`
|
|
5962
|
+
\u274C Registry error: ${error.message}`));
|
|
5963
|
+
} else {
|
|
5964
|
+
console.log(
|
|
5965
|
+
chalk16.red(
|
|
5966
|
+
`
|
|
5967
|
+
\u274C Failed to push: ${error instanceof Error ? error.message : String(error)}`
|
|
5968
|
+
)
|
|
5969
|
+
);
|
|
5970
|
+
}
|
|
5971
|
+
process.exit(1);
|
|
5972
|
+
}
|
|
5705
5973
|
}
|
|
5706
5974
|
if (options.pull) {
|
|
5707
5975
|
console.log(chalk16.cyan("\n\u{1F4E5} Pulling patterns from registry...\n"));
|
|
5708
|
-
|
|
5976
|
+
if (options.dryRun) {
|
|
5977
|
+
console.log(chalk16.yellow("\u{1F4CB} DRY-RUN: Would pull patterns (no actual changes)\n"));
|
|
5978
|
+
const registryClient2 = new RegistryClient();
|
|
5979
|
+
try {
|
|
5980
|
+
const result = await registryClient2.pull({ limit: 10 });
|
|
5981
|
+
console.log(chalk16.dim(` Registry has ${result.pagination.total} patterns available`));
|
|
5982
|
+
if (result.patterns.length > 0) {
|
|
5983
|
+
console.log(chalk16.dim("\n First 10 patterns:"));
|
|
5984
|
+
for (const p13 of result.patterns) {
|
|
5985
|
+
console.log(chalk16.dim(` - [${p13.type}] ${p13.data.name || p13.id}`));
|
|
5986
|
+
}
|
|
5987
|
+
if (result.pagination.hasMore) {
|
|
5988
|
+
console.log(chalk16.dim(` ... and ${result.pagination.total - 10} more`));
|
|
5989
|
+
}
|
|
5990
|
+
}
|
|
5991
|
+
} catch (error) {
|
|
5992
|
+
console.log(
|
|
5993
|
+
chalk16.red(
|
|
5994
|
+
` Failed to connect: ${error instanceof Error ? error.message : String(error)}`
|
|
5995
|
+
)
|
|
5996
|
+
);
|
|
5997
|
+
}
|
|
5998
|
+
return;
|
|
5999
|
+
}
|
|
6000
|
+
const registryClient = new RegistryClient();
|
|
6001
|
+
try {
|
|
6002
|
+
console.log(chalk16.dim(" Connecting to registry..."));
|
|
6003
|
+
let totalPulled = 0;
|
|
6004
|
+
let totalSkipped = 0;
|
|
6005
|
+
let offset = 0;
|
|
6006
|
+
const limit = 50;
|
|
6007
|
+
while (true) {
|
|
6008
|
+
const result = await registryClient.pull({ limit, offset });
|
|
6009
|
+
if (result.patterns.length === 0) {
|
|
6010
|
+
break;
|
|
6011
|
+
}
|
|
6012
|
+
for (const pattern of result.patterns) {
|
|
6013
|
+
let exists = false;
|
|
6014
|
+
if (pattern.type === "fix") {
|
|
6015
|
+
const existingResult = await store.getFixPattern(pattern.id);
|
|
6016
|
+
exists = existingResult.success && !!existingResult.data;
|
|
6017
|
+
} else if (pattern.type === "blueprint") {
|
|
6018
|
+
const existingResult = await store.getBlueprint(pattern.id);
|
|
6019
|
+
exists = existingResult.success && !!existingResult.data;
|
|
6020
|
+
}
|
|
6021
|
+
if (exists) {
|
|
6022
|
+
totalSkipped++;
|
|
6023
|
+
continue;
|
|
6024
|
+
}
|
|
6025
|
+
if (pattern.type === "fix") {
|
|
6026
|
+
const fixData = pattern.data;
|
|
6027
|
+
await store.saveFixPattern({
|
|
6028
|
+
...fixData,
|
|
6029
|
+
id: pattern.id,
|
|
6030
|
+
source: "community",
|
|
6031
|
+
isPrivate: true
|
|
6032
|
+
// Keep pulled patterns private by default
|
|
6033
|
+
});
|
|
6034
|
+
totalPulled++;
|
|
6035
|
+
} else if (pattern.type === "blueprint") {
|
|
6036
|
+
const bpData = pattern.data;
|
|
6037
|
+
await store.saveBlueprint({
|
|
6038
|
+
...bpData,
|
|
6039
|
+
id: pattern.id,
|
|
6040
|
+
source: "community",
|
|
6041
|
+
isPrivate: true
|
|
6042
|
+
});
|
|
6043
|
+
totalPulled++;
|
|
6044
|
+
}
|
|
6045
|
+
}
|
|
6046
|
+
if (!result.pagination.hasMore) {
|
|
6047
|
+
break;
|
|
6048
|
+
}
|
|
6049
|
+
offset += limit;
|
|
6050
|
+
console.log(chalk16.dim(` ... pulled ${offset} patterns so far`));
|
|
6051
|
+
}
|
|
6052
|
+
console.log(
|
|
6053
|
+
chalk16.green(`
|
|
6054
|
+
\u2705 Pulled ${totalPulled} new patterns from registry`)
|
|
6055
|
+
);
|
|
6056
|
+
if (totalSkipped > 0) {
|
|
6057
|
+
console.log(chalk16.dim(` (${totalSkipped} patterns already existed locally)`));
|
|
6058
|
+
}
|
|
6059
|
+
} catch (error) {
|
|
6060
|
+
if (error instanceof RegistryError) {
|
|
6061
|
+
console.log(chalk16.red(`
|
|
6062
|
+
\u274C Registry error: ${error.message}`));
|
|
6063
|
+
} else {
|
|
6064
|
+
console.log(
|
|
6065
|
+
chalk16.red(
|
|
6066
|
+
`
|
|
6067
|
+
\u274C Failed to pull: ${error instanceof Error ? error.message : String(error)}`
|
|
6068
|
+
)
|
|
6069
|
+
);
|
|
6070
|
+
}
|
|
6071
|
+
process.exit(1);
|
|
6072
|
+
}
|
|
5709
6073
|
}
|
|
5710
6074
|
if (!options.push && !options.pull) {
|
|
5711
6075
|
console.log(
|